diff --git "a/2660.jsonl" "b/2660.jsonl" new file mode 100644--- /dev/null +++ "b/2660.jsonl" @@ -0,0 +1,683 @@ +{"seq_id":"594888671","text":"import subprocess\nfrom datetime import datetime\n\nrevision = subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"]).strip()\ntry:\n subprocess.check_call([\"git\", \"diff\", \"--quiet\", \"HEAD\"])\nexcept subprocess.CalledProcessError:\n revision += \"-dev\"\n\nprint(\"-DMSIGN_GIT_REV=\\\\\\\"-{}\\\\\\\"\".format(revision[:7]))\n","sub_path":"stm/get_ver.py","file_name":"get_ver.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"213197669","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 16 22:41:36 2019\n\n@author: Administrator\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nfrom NewGAN import NewGAN\nimport matplotlib.pyplot as plt\n\ntf.reset_default_graph()\n\n\nEPOCHS = 10000\nBATCH_SIZE = 10\n\ntrain_dir = os.path.split(os.path.realpath(__file__))[0] + '\\\\train_dir'\n\n\n#读取数据集,保存为npy格式\nBASE_PATH = 'C:/Users/Leo/Desktop'#96*96*3\nfilenames = os.listdir(BASE_PATH)\nCKPT_PATH = os.path.split(os.path.realpath(__file__))[0] + '\\\\train_dir'\n\nimgs = []\n'''\nfor f in filenames:\n ii = plt.imread(BASE_PATH + '/' + filenames[0])\n imgs.append(ii)\n \nimgs = np.array(imgs)\n'''\n\nimgs = np.load('faces_data.npy') #[0:20000,:,:,:]\n\ndef iter_batch(x, batch_size, shuffle=True):\n indices = np.arange(x.shape[0]) #例如,2000\n if shuffle:\n np.random.shuffle(indices)\n for i in range(0, x.shape[0], batch_size):\n yield x[indices[i:i+batch_size],:]\n \n\n#定义计算图\ngan = NewGAN()\ninput_size = 4*4*512\ninputs_real, inputs_noise = gan.get_inputs(input_size, 96, 96, 3)\n\n#插值参数alpha\nalpha = tf.random_uniform(\n shape=[BATCH_SIZE,1], \n minval=0.,\n maxval=1.)\n\ng_loss, d_loss = gan.get_loss_wgangp(inputs_real, inputs_noise, 3, alpha)\ng_opt, d_opt = gan.optimizer(g_loss, d_loss)\n\ntest_noise = tf.placeholder(tf.float32, [None, input_size], name = 'test_noise')\nfake_img = gan.netG(test_noise, 3, is_train=False)\n\n\ninit = tf.global_variables_initializer()\nstep = 0\nsaver = tf.train.Saver(max_to_keep=1) #checkpoint saver\n\nwith tf.Session() as sess:\n sess.run(init)\n \n #先在train_dir目录中读取已训练的模型\n ckpt = tf.train.latest_checkpoint(CKPT_PATH)\n if ckpt:\n saver.restore(sess, ckpt)\n step = int(ckpt.split('\\\\')[-1].split('-')[-1])\n print('load checkpoint: %s' % ckpt)\n else:\n pass\n \n for epoch in range(EPOCHS):\n avg_loss = 0\n count = 0\n for x_batch in iter_batch(imgs, batch_size=BATCH_SIZE):\n if x_batch.shape[0] != BATCH_SIZE:\n break\n imgs_noise = np.random.normal(size=(x_batch.shape[0], input_size)).astype(np.float32) #noise_img \n \n D_loss, _ = sess.run([d_loss, d_opt], feed_dict={inputs_real: x_batch, inputs_noise: imgs_noise})\n G_loss, _ = sess.run([g_loss, g_opt], feed_dict={inputs_real: np.zeros(x_batch.shape), inputs_noise: imgs_noise})\n \n print(str(count) + '-' + str(D_loss))\n \n avg_loss += D_loss\n count += 1\n \n \n \n step = step + 1\n if step % 600 == 0:\n saver.save(sess, CKPT_PATH + '\\\\faces-gan.ckpt', global_step=step,write_meta_graph=False)\n print('Model at step %d saved.' % step)\n \n if step % 200 == 0:\n genImg = sess.run(fake_img, feed_dict={test_noise: np.random.normal(size=(1, input_size)).astype(np.float32)})\n plt.imshow(genImg[0]/255.)\n plt.show()\n","sub_path":"代码/ganTest.py","file_name":"ganTest.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"318570467","text":"from django.shortcuts import render, redirect\nfrom django.db.models import Q, CharField, Value\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseForbidden\nfrom django.contrib import messages\n\nfrom bookreviews.forms import TicketForm, ReviewForm\nfrom bookreviews.models import UserFollows, Ticket, Review\nfrom registration.models import User\n\nfrom itertools import chain\n\n\n@login_required()\ndef feed(request):\n i_follow = UserFollows.objects.filter(\n user=request.user).values_list('followed_user')\n\n ticket_list = Ticket.objects.filter(\n Q(user__in=[usr for usr in i_follow]) |\n Q(user=request.user)\n ).annotate(content_type=Value('TICKET', CharField()))\n\n review_list = Review.objects.filter(\n Q(user__in=[usr for usr in i_follow]) |\n Q(user=request.user)\n ).annotate(content_type=Value('REVIEW', CharField()))\n\n posts = sorted(\n chain(review_list, ticket_list),\n key=lambda post: post.time_created,\n reverse=True\n )\n\n paginator = Paginator(posts, 5)\n page = request.GET.get('page')\n paginated_posts = paginator.get_page(page)\n\n return render(\n request,\n 'bookreviews/feed.html',\n context={'posts': paginated_posts, 'user': request.user}\n )\n\n\n@login_required()\ndef follow(request):\n if request.method == 'POST':\n try:\n user_to_follow = User.objects.get(email=request.POST.get('email'))\n UserFollows.objects.create(\n user=request.user,\n followed_user=user_to_follow\n )\n messages.success(request, 'Vous suivez un nouvel utilisateur.')\n except User.DoesNotExist:\n messages.error(request, \"Cet utilisateur n'existe pas.\")\n finally:\n return redirect('follow_view')\n\n if request.method == 'GET':\n i_follow = UserFollows.objects.filter(user=request.user)\n my_followers = UserFollows.objects.filter(followed_user=request.user)\n\n autocomplete = User.objects.exclude(\n Q(email__in=[usr.followed_user for usr in i_follow]) |\n Q(email=request.user.email))\n\n return render(\n request,\n 'bookreviews/follow.html',\n {'i_follow': i_follow,\n 'my_followers': my_followers,\n 'all_users': autocomplete}\n )\n\n\n@login_required()\ndef unfollow(request, user_id):\n user_to_unfollow = User.objects.get(id=user_id)\n UserFollows.objects.get(followed_user=user_to_unfollow, user=request.user).delete()\n messages.success(request, 'Désabonnement réalisé avec succès.')\n return redirect('follow_view')\n\n\n@login_required()\ndef create_ticket(request):\n if request.method == 'POST':\n form = TicketForm(request.POST, request.FILES)\n if form.is_valid():\n form_data = form.save(commit=False)\n form_data.user = request.user\n form_data.save()\n messages.success(request, 'Ticket créé avec succès.')\n return redirect('feed_view')\n\n if request.method == 'GET':\n form = TicketForm()\n return render(\n request,\n 'bookreviews/create-ticket.html',\n {'form': form}\n )\n\n\n@login_required()\ndef create_review(request):\n if request.method == 'POST':\n ticket_form = TicketForm(request.POST, request.FILES)\n review_form = ReviewForm(request.POST)\n if ticket_form.is_valid() and review_form.is_valid():\n # Création du ticket\n ticket_form_data = ticket_form.save(commit=False)\n ticket_form_data.user = request.user\n ticket_form_data.save()\n messages.success(request, 'Ticket créé avec succès.')\n # Création de la review associée\n review_form_data = review_form.save(commit=False)\n review_form_data.user = request.user\n review_form_data.ticket = Ticket.objects.get(\n id=ticket_form_data.id)\n review_form_data.save()\n messages.success(request, 'Review créée avec succès.')\n return redirect('feed_view')\n\n if request.method == 'GET':\n ticket_form = TicketForm()\n review_form = ReviewForm()\n return render(\n request,\n 'bookreviews/create-review.html',\n {'review_form': review_form, 'ticket_form': ticket_form})\n\n\n@login_required()\ndef create_review_from_ticket(request, ticket_id):\n ticket = Ticket.objects.get(id=ticket_id)\n\n if request.method == 'POST':\n review_form = ReviewForm(request.POST)\n if review_form.is_valid():\n # Création de la review associée\n review_form_data = review_form.save(commit=False)\n review_form_data.user = request.user\n review_form_data.ticket = ticket\n review_form_data.save()\n messages.success(request, 'Review créée avec succès.')\n return redirect('feed_view')\n\n if request.method == 'GET':\n review_form = ReviewForm()\n return render(\n request,\n 'bookreviews/create-review-from-ticket.html',\n {'review_form': review_form, 'ticket': ticket, 'user': request.user})\n\n\n@ login_required()\ndef edit_own_ticket(request, ticket_id):\n ticket = Ticket.objects.get(id=ticket_id)\n\n if ticket.user != request.user:\n return HttpResponseForbidden()\n\n if request.method == 'POST':\n form = TicketForm(request.POST, request.FILES, instance=ticket)\n if form.is_valid():\n form.save()\n messages.success(request, 'Ticket modifié avec succès.')\n return redirect('my_posts_view')\n\n if request.method == 'GET':\n form = TicketForm(instance=ticket)\n return render(\n request,\n 'bookreviews/edit-ticket.html',\n {'form': form, 'ticket_id': ticket_id})\n\n\n@ login_required()\ndef delete_ticket(request, ticket_id):\n ticket = Ticket.objects.get(id=ticket_id)\n\n if ticket.user != request.user:\n return HttpResponseForbidden()\n\n ticket.delete()\n\n messages.success(request, 'Ticket supprimé avec succès.')\n return redirect('my_posts_view')\n\n\n@ login_required()\ndef edit_own_review(request, review_id):\n review = Review.objects.get(id=review_id)\n\n if review.user != request.user:\n return HttpResponseForbidden()\n\n if request.method == 'POST':\n form = ReviewForm(request.POST, instance=review)\n if form.is_valid():\n form.save()\n messages.success(request, 'Review modifiée avec succès.')\n return redirect('my_posts_view')\n if request.method == 'GET':\n form = ReviewForm(instance=review)\n return render(\n request,\n 'bookreviews/edit-review.html',\n {'form': form, 'review_id': review_id, 'ticket': review.ticket})\n\n\n@ login_required()\ndef delete_review(request, review_id):\n review = Review.objects.get(id=review_id)\n\n if review.user != request.user:\n return HttpResponseForbidden()\n\n review.delete()\n\n messages.success(request, 'Review supprimée avec succès.')\n return redirect('my_posts_view')\n\n\n@ login_required()\ndef my_posts(request):\n ticket_list = Ticket.objects.filter(\n user=request.user\n ).annotate(content_type=Value('TICKET', CharField()))\n\n review_list = Review.objects.filter(\n user=request.user\n ).annotate(content_type=Value('REVIEW', CharField()))\n\n posts = sorted(\n chain(review_list, ticket_list),\n key=lambda post: post.time_created,\n reverse=True\n )\n return render(\n request,\n 'bookreviews/my-posts.html',\n context={'posts': posts})\n","sub_path":"bookreviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"584125946","text":"import sys\n#sys.path.append(\"c:\\lyhproject\\python\")\n\n\nsys.path.append((\"../../\"))\nimport function_file.data_load as dl\nimport function_file.lyhTrade.lyhTradingSys as lyh\nfrom WindPy import w\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pylab\nimport time\nimport xlrd\nimport datetime\nimport tushare as ts\n\nts.set_token('a63e497e8212c66642311eb645ee785bb7aae3edc15fce7bf026470f')\npro = ts.pro_api()\n\nimport MySQLdb\n\nentiretyList = []\nmedianList = []\noneEnList = []\noneMidList = []\n\ntrade_date_list = []\nreport_date_list = []\n\nrecord_date = lyh.getTradeNReportDate(returnKind = 'quarter', beginYear = 2008)\n\nfor i in range(len(record_date[0])):\n if i%2 ==1:\n trade_date_list.append(record_date[0][i])\n report_date_list.append(record_date[1][i])\n\nreport_date_list_init = report_date_list\nreport_date_list = []\nfor i_date in report_date_list_init:\n if i_date[-4:] == '0930':\n report_date_list.append(i_date[:4]+'1231')\n else:\n report_date_list.append(i_date)\n\n \n\n\n\n#连接天风wind数据库\nconnWind = MySQLdb.connect(\"192.168.41.56\", \"infoasadep01\",\"tfyfInfo@1522\", \"wind\", charset = 'utf8')\n\nconnWindtf = MySQLdb.connect(\"192.168.41.56\", \"ref_reader\", \"ref_reader\", \"tfrefdb\", charset='utf8', port = 3307)\n\nrdf_field_ashareeodderivativeindicator = \"S_DQ_CLOSE_TODAY, TOT_SHR_TODAY, S_VAL_PE_TTM, s_val_pb_new, S_VAL_MV\"\nrdf_field_asharefinancialindicator = \"s_fa_roe, S_FA_YOY_OR, S_FA_YOYNETPROFIT_DEDUCTED, S_FA_ROIC\"\nrdf_field_asharettmhis = \"oper_rev_ttm, S_FA_ASSET_MRQ, S_FA_DEBT_MRQ, NET_PROFIT_PARENT_COMP_TTM\"\nrdf_field_asharebalancesheet = \"INVENTORIES, CONSUMPTIVE_BIO_ASSETS\"\n#rdf_field_asharefinancialderivative = \"ROIC, INVTURN\"\n\n\n\n\nd_lag_1 = None\nSW_LEVEL = 2 #申万几级行业\n\nd_result_dict = {}\n\n#i = 0\n\nresult_list = []\n\nfor i_date in range(len(report_date_list)):\n\n print(report_date_list[i_date])\n\n df1 = dl.get_ashareeodderivativeindicator(connWind, rdf_field_ashareeodderivativeindicator, report_date_list[i_date])\n df2 = dl.get_asharefinancialindicator(connWind, rdf_field_asharefinancialindicator, report_date_list[i_date])\n df3 = dl.get_asharettmhis(connWind, rdf_field_asharettmhis, report_date_list[i_date])\n df4 = dl.get_asharebalancesheet(connWind, rdf_field_asharebalancesheet, report_date_list[i_date])\n\n #合并财务数据\n d = pd.merge(df1, df2, how='outer', on=['s_info_windcode', 's_info_windcode'])\n d = pd.merge(d, df3, how='outer', on=['s_info_windcode', 's_info_windcode'])\n d = pd.merge(d, df4, how='outer', on=['s_info_windcode', 's_info_windcode'])\n\n #合并申万行业数据\n d_industry = dl.get_sw_industry_name(connWind,report_date_list[i_date], SW_LEVEL)\n\n\n d = pd.merge(d, d_industry, on = ['s_info_windcode', 's_info_windcode'], how = 'outer')\n\n d = d.dropna(subset=['Industriesname'])\n\n\n\n if d_lag_1 is None:\n d_lag_1 = d\n continue\n else:\n\n d_merge = pd.merge(d, d_lag_1, on = 's_info_windcode', how = 'inner')\n\n d_industry_sum = d_merge.groupby('Industriesname_x').sum()\n d_industry_mean = d_merge.groupby('Industriesname_x').mean()\n #d_industry_sum_dvd = d_industry_sum[['NET_PROFIT_PARENT_COMP_TTM_x', 'INVENTORIES_x', 'CONSUMPTIVE_BIO_ASSETS_x']]/d_industry_sum[['NET_PROFIT_PARENT_COMP_TTM_y', 'INVENTORIES_y', 'CONSUMPTIVE_BIO_ASSETS_y']]\n\n #d_industry_sum_dvd = d_industry_sum['INVENTORIES_x'] / d_industry_sum['INVENTORIES_x'] - 1\n\n #d_industry_mean_dvd = d_merge.groupby('Industriesname_x').mean()\n\n\n if len(d_result_dict) == 0:\n d_profit_dvd = d_industry_sum['NET_PROFIT_PARENT_COMP_TTM_x'] / d_industry_sum['NET_PROFIT_PARENT_COMP_TTM_y'] - 1\n d_profit_dvd_df = pd.DataFrame(d_profit_dvd.values, index = d_profit_dvd.index, columns= [report_date_list[i_date]])\n d_result_dict['净利润增速'] = d_profit_dvd_df\n\n\n d_roic_mean = d_merge.groupby('Industriesname_x').mean()['S_FA_ROIC_x']\n d_roic_mean_df = pd.DataFrame(d_roic_mean.values, index=d_roic_mean.index, columns=[report_date_list[i_date]])\n d_result_dict['平均ROIC'] = d_roic_mean_df\n\n\n d_inventories_dvd = d_industry_sum['INVENTORIES_x'] / d_industry_sum[\n 'INVENTORIES_y'] - 1\n d_inventories_dvd_df = pd.DataFrame(d_inventories_dvd.values, index=d_inventories_dvd.index, columns=[report_date_list[i_date]])\n d_result_dict['存货增速'] = d_inventories_dvd_df\n\n\n # d_consumptive_dvd = d_industry_sum['CONSUMPTIVE_BIO_ASSETS_x'] / d_industry_sum[\n # 'CONSUMPTIVE_BIO_ASSETS_y'] - 1\n # d_consumptive_dvd_df = pd.DataFrame(d_consumptive_dvd.values, index=d_consumptive_dvd.index,\n # columns=[report_date_list[i_date]])\n # d_result_dict['消耗性生物资产增速'] = d_consumptive_dvd_df\n\n else:\n d_profit_dvd = d_industry_sum['NET_PROFIT_PARENT_COMP_TTM_x'] / d_industry_sum[\n 'NET_PROFIT_PARENT_COMP_TTM_y'] - 1\n d_profit_dvd_df = pd.DataFrame(d_profit_dvd.values, index=d_profit_dvd.index, columns=[report_date_list[i_date]])\n d_result_dict['净利润增速'] = pd.merge(d_result_dict['净利润增速'], d_profit_dvd_df, left_index= True, right_index = True, how = 'outer')\n\n d_roic_mean = d_merge.groupby('Industriesname_x').mean()['S_FA_ROIC_x']\n d_roic_mean_df = pd.DataFrame(d_roic_mean.values, index=d_roic_mean.index, columns=[report_date_list[i_date]])\n d_result_dict['平均ROIC'] = pd.merge(d_result_dict['平均ROIC'], d_roic_mean_df, left_index= True, right_index = True, how = 'outer')\n\n d_inventories_dvd = d_industry_sum['INVENTORIES_x'] / d_industry_sum[\n 'INVENTORIES_y'] - 1\n d_inventories_dvd_df = pd.DataFrame(d_inventories_dvd.values, index=d_inventories_dvd.index,\n columns=[report_date_list[i_date]])\n d_result_dict['存货增速'] = pd.merge(d_result_dict['存货增速'], d_inventories_dvd_df, left_index= True, right_index = True, how = 'outer')\n\n d_lag_1 = d\n\nfor i_key in d_result_dict.keys():\n d_result_dict[i_key]['指标'] = i_key\n\n\nd_result = pd.concat(d_result_dict.values())\nd_result['行业'] = d_result.index\nd_result = d_result.set_index([\"行业\", \"指标\"])\nd_result.sort_index().to_excel('d_result.xlsx')\n\nd_temp = d_result.T\n\nfor i_industry in d_temp.columns.levels[0]:\n\n profit_mean = d_temp[(i_industry,'净利润增速')].mean()\n roic_mean = d_temp[(i_industry,'平均ROIC')].mean()\n inventories_mean = d_temp[(i_industry,'存货增速')].mean()\n\n d_temp[(i_industry,'产能周期')] = '未知'\n d_temp[(i_industry,'产能周期')] = np.where((d_temp[(i_industry,'存货增速')]>inventories_mean) & (d_temp[(i_industry,'平均ROIC')]>roic_mean) & (d_temp[(i_industry,'净利润增速')]>profit_mean) , '主动提库存', d_temp[(i_industry,'产能周期')])\n d_temp[(i_industry,'产能周期')] = np.where((d_temp[(i_industry,'存货增速')]>inventories_mean) & (d_temp[(i_industry,'平均ROIC')]roic_mean) & (d_temp[(i_industry,'净利润增速')]>profit_mean) , '被动降库存', d_temp[(i_industry,'产能周期')])\n d_temp[(i_industry,'产能周期')] = np.where((d_temp[(i_industry,'存货增速')] 4:\n r1 = grangercausalitytests(data1, maxlag=1, verbose=True)\n profit_to_inventories = r1[1][0]['ssr_chi2test'][0] < 0.05\n else:\n profit_to_inventories = False\n\n #需求方主导\n data2 = dtest.loc[['存货增速','净利润增速']].T\n data2 = data2.replace([np.inf, -np.inf], np.nan)\n data2 = data2.dropna()\n if len(data2) > 4:\n r2 = grangercausalitytests(data2, maxlag=1, verbose=True)\n inventories_to_profit = r2[1][0]['ssr_chi2test'][0] < 0.05\n else:\n inventories_to_profit = False\n\n dtest = dtest.T\n\n if profit_to_inventories and inventories_to_profit:\n d_temp2[(i_industry,'因果检验结果')] = '供需双向传导'\n gxsx_str = gxsx_str + '、' + i_industry\n elif profit_to_inventories and not inventories_to_profit:\n d_temp2[(i_industry,'因果检验结果')] = '供给方主导'\n gjfzd_str = gjfzd_str + '、' + i_industry\n elif not profit_to_inventories and inventories_to_profit:\n d_temp2[(i_industry,'因果检验结果')] = '需求方主导'\n xqfzd_str = xqfzd_str + '、' + i_industry\n else:\n d_temp2[(i_industry,'因果检验结果')] = '无传导关系'\n\nd_result_final2 = d_temp2.T.sort_index()\nindex_init = d_result_final2.index\nd_result_final2 = d_result_final2.reindex([(d1, d2) for d1 in index_init.get_level_values(\"行业\").unique() for d2 in ['因果检验结果','产能周期', '净利润增速', '存货增速', '平均ROIC']])\nd_result_final2.to_excel('d_result_final.xlsx')\n\n","sub_path":"inventory_vs_profit/inventory_vs_profit.py","file_name":"inventory_vs_profit.py","file_ext":"py","file_size_in_byte":10039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"532262944","text":"import pygame\nimport random\nfrom time import sleep\n\nWINDOW_SIZE = [600, 660]\nFRAME_COLOR = (0, 255, 204)\nWHITE = (255, 255, 255)\nBLUE = (200, 255, 255)\nSIZE_BLOCK = 20\nMARGIN = 1\nSNAKE_COLOR = (0, 255, 0)\nx = 140\ny = 320\nstep = 20\ngo = \"\"\napple = [int(random.randint(2, 27)*20), int(random.randint(2, 27)*20)]\napple_end = [int(random.randint(2, 27)*20), int(random.randint(2, 27)*20)]\n\n\ndef draw_background():\n screen.fill(FRAME_COLOR)\n for row in range(int(WINDOW_SIZE[0] / SIZE_BLOCK) - 3):\n for column in range(int(WINDOW_SIZE[1] / SIZE_BLOCK) - 6):\n if (row + column) % 2 == 0:\n color = BLUE\n else:\n color = WHITE\n if row == 0 or column == 0 or row == 26 or column == 26:\n pass\n # color = (0, 0, 255)\n pygame.draw.rect(screen, color, [20 + column * SIZE_BLOCK + MARGIN * (column + 1),\n 20 + row * SIZE_BLOCK + MARGIN * (row + 1), SIZE_BLOCK, SIZE_BLOCK])\n\n\nscreen = pygame.display.set_mode(WINDOW_SIZE)\npygame.display.set_caption(\"Օձի կծած\")\nsnake_body = [[x, y], [x + 20, y], [x + 40, y]]\npygame.font.init()\nfont = pygame.font.SysFont(\"arial\", 60, bold=True)\n\nwhile True:\n pygame.time.delay(100)\n\n if len(snake_body)-2 == 0:\n print(\"Game over\")\n game_over = font.render(f\"Game Over\", True, (255, 0, 0))\n screen.blit(game_over, (40, 600))\n pygame.display.flip()\n sleep(3)\n pygame.quit()\n if len(snake_body)-2 == 10:\n print(\"Game over\")\n game_over = font.render(f\"You Win\", True, (25, 112, 221))\n screen.blit(game_over, (40, 600))\n pygame.display.flip()\n sleep(3)\n pygame.quit()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n print(\"exit\")\n pygame.quit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT and go != \"LEFT\":\n go = \"RIGHT\"\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT and go != \"RIGHT\":\n go = \"LEFT\"\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP and go != \"DOWN\":\n go = \"UP\"\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN and go != \"UP\":\n go = \"DOWN\"\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n go = \"\"\n print(snake_body)\n\n if go == \"RIGHT\":\n if x == 540:\n x = 0\n x += step\n snake_head = [x, y]\n snake_body.insert(0, snake_head)\n snake_body.pop()\n # print(snake_head)\n if go == \"LEFT\":\n if x == 20:\n x = 560\n x -= step\n snake_head = [x, y]\n snake_body.pop()\n snake_body.insert(0, snake_head)\n # print(snake_head)\n if go == \"UP\":\n if y == 20:\n y = 560\n y -= step\n snake_head = [x, y]\n snake_body.pop()\n snake_body.insert(0, snake_head)\n # print(snake_head)\n if go == \"DOWN\":\n if y == 540:\n y = 0\n y += step\n snake_head = [x, y]\n snake_body.pop()\n snake_body.insert(0, snake_head)\n # print(snake_head)\n\n draw_background()\n point = font.render(f\"{int(len(snake_body) - 2)}\", True, (255, 255, 255))\n screen.blit(point, (520, 600))\n for snake_block in snake_body:\n if snake_body.index(snake_block) == 0:\n # print(\"________\", snake_block)\n SNAKE_COLOR = (0, 200, 0)\n else:\n SNAKE_COLOR = (0, 255, 0)\n pygame.draw.rect(screen, SNAKE_COLOR,\n [snake_block[0] + int(snake_block[0] / 20), snake_block[1] + int(snake_block[1] / 20),\n SIZE_BLOCK, SIZE_BLOCK])\n pygame.draw.rect(screen, (255, 0, 0), [apple[0] + int(apple[0] / 20), apple[1] + int(apple[1] / 20), SIZE_BLOCK, SIZE_BLOCK])\n if snake_body[0] == apple:\n snake_body.append(apple)\n print(apple)\n apple = [int(random.randint(2, 27)*20), int(random.randint(2, 27)*20)]\n apple_end = [int(random.randint(2, 27) * 20), int(random.randint(2, 27) * 20)]\n print(apple)\n pygame.draw.rect(screen, (0, 0, 255), [apple_end[0] + int(apple_end[0] / 20), apple_end[1] + int(apple_end[1] / 20), SIZE_BLOCK, SIZE_BLOCK])\n if snake_body[0] == apple_end:\n snake_body.pop()\n print(apple_end)\n apple_end = [int(random.randint(2, 27)*20), int(random.randint(2, 27)*20)]\n apple = [int(random.randint(2, 27) * 20), int(random.randint(2, 27) * 20)]\n print(apple_end)\n\n pygame.display.update()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"635663024","text":"# -*- coding: utf-8 -*-\n# /#############################################################################\n#\n# NTF Group\n# Copyright (C) 2019-TODAY NTF Group().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n# /#############################################################################\nimport xlwt\nimport xlsxwriter\nfrom odoo.tools import config\nimport base64\nfrom odoo import api, fields, models, tools, SUPERUSER_ID, _, modules\nfrom datetime import datetime, timedelta, date\nimport calendar\nimport datetime\nimport dateutil.relativedelta\nimport dateutil.parser\n\n\nclass SaleTerminalExcelReport(models.TransientModel):\n _name = 'sale.terminal.excel.report'\n _description = 'Terminal and CC Excel Report'\n\n start_date = fields.Datetime('Start Date')\n end_date = fields.Datetime('End Date')\n start_date_m = fields.Date('Start Date')\n end_date_m = fields.Date('End Date')\n period_string = fields.Selection(\n (('this_week', 'This Week'), ('this_month', 'This Month'), ('last_three_months', 'Last 3 Months'),\n ('last_six_months', 'Last 6 Months'), ('last_one_year', 'Last 1 Year')))\n is_custom_range = fields.Boolean(\"Custom Range\")\n\n @api.onchange('start_date', 'end_date')\n def _onchange_date(self):\n for file in self:\n if file.start_date:\n file.start_date_m = file.start_date\n if file.end_date:\n file.end_date_m = file.end_date\n\n @api.onchange('period_string')\n def onchange_period(self):\n if self.period_string == 'this_month':\n today = datetime.datetime.now()\n _, num_days = calendar.monthrange(today.year, today.month)\n start = datetime.datetime(today.year, today.month, 1)\n end = today\n self.start_date = start\n self.end_date = end\n if self.period_string == 'last_three_months':\n today = datetime.datetime.now()\n start = today - dateutil.relativedelta.relativedelta(months=3)\n print (\"start\", start)\n end = datetime.datetime.now()\n self.start_date = start\n self.end_date = end\n if self.period_string == 'last_six_months':\n today = datetime.datetime.now()\n start = today - dateutil.relativedelta.relativedelta(months=6)\n print (\"start\", start)\n end = datetime.datetime.now()\n self.start_date = start\n self.end_date = end\n if self.period_string == 'last_one_year':\n today = datetime.datetime.now()\n start = today - dateutil.relativedelta.relativedelta(months=12)\n print (\"start\", start)\n end = datetime.datetime.now()\n self.start_date = start\n self.end_date = end\n if self.period_string == 'this_week':\n day = datetime.datetime.now()\n start = day - timedelta(days=day.weekday() + 1)\n end = start + timedelta(days=6)\n self.start_date = start\n self.end_date = end\n\n\n def genarate_excel_report(self):\n custom_value = {}\n custom_obj = self.env['import.logic']\n sale_obj = self.env['sale.order']\n terminal_sea = sale_obj.search(\n [('sales_imp_id.date', '>=', self.start_date_m), ('sales_imp_id.date', '<=', self.end_date_m)])\n custom_sea = custom_obj.search([('date', '>=', self.start_date_m), ('date', '<=', self.end_date_m)])\n workbook = xlwt.Workbook()\n\n # Style for Excel\n style0 = xlwt.easyxf(\n 'font: name Times New Roman bold on;align: horiz center;borders:top_color black, bottom_color black, right_color black, left_color black, top thin,right thin,bottom thin,left thin;')\n style1 = xlwt.easyxf(\n 'font: name Times New Roman bold on; pattern: pattern solid, fore_colour green;align: horiz center;borders:top_color black, bottom_color black, right_color black, left_color black, top thin,right thin,bottom thin,left thin;')\n\n # Excel Heading Manipulation\n sheet = workbook.add_sheet(\"Report By BL\")\n sheet.col(0).width = 2000\n sheet.col(1).width = 17553\n sheet.col(2).width = 13553\n sheet.col(3).width = 9000\n sheet.col(4).width = 6000\n sheet.col(5).width = 6000\n sheet.col(6).width = 9000\n sheet.col(7).width = 9000\n sheet.col(8).width = 6000\n sheet.col(9).width = 9000\n sheet.col(10).width = 9000\n sheet.col(11).width = 9000\n sheet.col(12).width = 9000\n sheet.col(13).width = 9000\n sheet.col(14).width = 9000\n sheet.col(15).width = 10000\n sheet.write(0, 0, 'Job No', style1)\n sheet.write(0, 1, 'Customer', style1)\n sheet.write(0, 2, 'By Customer', style1)\n sheet.write(0, 3, 'Port', style1)\n sheet.write(0, 4, 'B/L Number', style1)\n sheet.write(0, 5, 'No. Of Containers', style1)\n sheet.write(0, 6, 'Docs Received Date', style1)\n sheet.write(0, 7, 'ETA', style1)\n sheet.write(0, 8, 'Demurrage Date', style1)\n sheet.write(0, 9, 'Cleared Date', style1)\n sheet.write(0, 10, 'Delivery Plan Date', style1)\n sheet.write(0, 11, 'Actual Delivery Date', style1)\n sheet.write(0, 12, 'Detention Date', style1)\n sheet.write(0, 13, 'EIR Date(Actual Empty Return)', style1)\n sheet.write(0, 14, 'Invoice Date', style1)\n sheet.write(0, 15, 'Shipment Status', style1)\n\n row = 1\n for rec in custom_sea:\n sheet.write(row, 0, rec.job_no or \"\", style0)\n sheet.write(row, 1, rec.customer.name or \"\", style0)\n sheet.write(row, 2, rec.by_customer.name or \"\", style0)\n sheet.write(row, 3, rec.port.name or \"\", style0)\n sheet.write(row, 4, rec.bill_no or \"\", style0)\n sheet.write(row, 5, rec.count_crt or \"\", style0)\n sheet.write(row, 6, rec.org_date or \"\", style0)\n sheet.write(row, 7, rec.vsl_exp_arvl_date or \"\", style0)\n sheet.write(row, 8, rec.demurrage or \"\", style0)\n sheet.write(row, 9, rec.saddad or \"\", style0)\n sheet.write(row, 10, rec.delivery or \"\", style0)\n sheet.write(row, 11, rec.delivery_date or \"\", style0)\n sheet.write(row, 12, rec.detention_date or \"\", style0)\n sheet.write(row, 13, rec.eir_date or \"\", style0)\n sheet.write(row, 14, rec.acc_link.date_invoice or \"\", style0)\n sheet.write(row, 15, rec.status.name or \"\", style0)\n row += 1\n\n sheet2 = workbook.add_sheet(\"Container Details\")\n sheet2.col(0).width = 6000\n sheet2.col(1).width = 17553\n sheet2.col(2).width = 6000\n sheet2.col(3).width = 9000\n sheet2.col(4).width = 6000\n sheet2.col(5).width = 6000\n sheet2.col(6).width = 9000\n sheet2.col(7).width = 9000\n sheet2.col(8).width = 6000\n sheet2.col(9).width = 9000\n sheet2.col(10).width = 9000\n sheet2.col(11).width = 9000\n sheet2.col(12).width = 9000\n sheet2.col(13).width = 9000\n sheet2.col(14).width = 9000\n sheet2.col(15).width = 10000\n sheet2.write(0, 0, 'Order/Job No', style1)\n sheet2.write(0, 1, 'Customer', style1)\n sheet2.write(0, 2, 'Port', style1)\n sheet2.write(0, 3, 'B/L Number', style1)\n sheet2.write(0, 4, 'Container Number', style1)\n sheet2.write(0, 5, 'ETA', style1)\n sheet2.write(0, 6, 'Docs Received Date', style1)\n sheet2.write(0, 7, 'Demurrage Date', style1)\n sheet2.write(0, 8, 'Cleared Date', style1)\n sheet2.write(0, 9, 'PullOut Date', style1)\n sheet2.write(0, 10, 'Actual Delivery Date', style1)\n sheet2.write(0, 11, 'Depart From Customer', style1)\n sheet2.write(0, 12, 'Arrival To Terminal', style1)\n sheet2.write(0, 13, 'Detention Date', style1)\n sheet2.write(0, 14, 'EIR Date', style1)\n sheet2.write(0, 15, 'Shipment Status', style1)\n\n row = 1\n for rec in terminal_sea:\n if rec.sales_imp_id:\n sheet2.write(row, 0, rec.sales_imp_id.job_no or \"\", style0)\n sheet2.write(row, 1, rec.partner_id.name or \"\", style0)\n sheet2.write(row, 2, rec.sales_imp_id.port.name or \"\", style0)\n sheet2.write(row, 3, rec.sales_imp_id.bill_no or \"\", style0)\n sheet2.write(row, 4, rec.container_num or \"\", style0)\n sheet2.write(row, 5, rec.sales_imp_id.vsl_exp_arvl_date or \"\", style0)\n sheet2.write(row, 6, rec.sales_imp_id.org_date or \"\", style0)\n sheet2.write(row, 7, rec.sales_imp_id.demurrage or \"\", style0)\n sheet2.write(row, 8, rec.sales_imp_id.saddad or \"\", style0)\n sheet2.write(row, 9, rec.pullout_date or \"\", style0)\n sheet2.write(row, 10, rec.delivery_date or \"\", style0)\n sheet2.write(row, 11, rec.upload_date or \"\", style0)\n sheet2.write(row, 12, rec.return_date or \"\", style0)\n sheet2.write(row, 13, rec.sales_imp_id.detention_date or \"\", style0)\n sheet2.write(row, 14, rec.eir_date or \"\", style0)\n sheet2.write(row, 15, rec.sales_imp_id.status.name or \"\", style0)\n row += 1\n\n workbook.save('/tmp/import_shipment_status.xls')\n result_file = open('/tmp/import_shipment_status.xls', 'rb').read()\n attach_id = self.env['wizard.excel.report'].create({\n 'name': 'Import Shipment Status.xls',\n 'report': base64.encodestring(result_file)\n })\n return {\n 'name': _('Notification'),\n 'context': self.env.context,\n 'view_mode': 'form',\n 'res_model': 'wizard.excel.report',\n 'res_id': attach_id.id,\n 'data': None,\n 'type': 'ir.actions.act_window',\n 'target': 'new'\n }\n\n\nclass WizardExcelReport(models.TransientModel):\n _name = \"wizard.excel.report\"\n\n report = fields.Binary('Prepared file', filters='.xls', readonly=True)\n name = fields.Char('File Name', size=32)\n","sub_path":"ntf_custom/wizard/sale_terminal_wiz.py","file_name":"sale_terminal_wiz.py","file_ext":"py","file_size_in_byte":10823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"242627388","text":"# -*- coding: utf-8 -*-\n\nimport flask.ext.wtf as wtf\nfrom eventframe.forms import DateTimeField, DictField, timezone_list\nfrom eventframe.nodes.content import ContentForm\n\n__all__ = ['EventForm']\n\n\nclass EventForm(ContentForm):\n start_datetime = DateTimeField(u\"Start date/time\", validators=[wtf.Required()])\n end_datetime = DateTimeField(u\"End date/time\", validators=[wtf.Required()])\n timezone = wtf.SelectField(u\"Timezone\", choices=timezone_list, validators=[wtf.Required()])\n location_name = wtf.TextField(u\"Location name\", validators=[wtf.Required()])\n location_address = wtf.TextField(u\"Address\", validators=[wtf.Required()])\n map = wtf.QuerySelectField(u\"Map\", get_label='title', allow_blank=True)\n mapmarker = wtf.TextField(u\"Map marker\")\n capacity = wtf.IntegerField(u\"Capacity\", validators=[wtf.Required()])\n allow_waitlisting = wtf.BooleanField(u\"Allow wait-listing if over capacity\", default=False)\n allow_maybe = wtf.BooleanField(u\"Allow “Maybe” responses\", default=True)\n participant_list = wtf.QuerySelectField(u\"Participant list\", get_label='title', allow_blank=True)\n properties = DictField(u\"Properties\")\n","sub_path":"eventframe/nodes/event/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"561226427","text":"# -*- coding:utf-8 -*-\n\nimport requests\n\nfrom error.HttpError import NotFoundError, ForbiddenError, BadRequestError\nfrom util import Config\nfrom util import Logger\nfrom util import MailUtil\n\ndouban_heads = {\n # \"Accept\": \"text/html, application/xhtml+xml, image/jxr, */*\",\n # \"Accept-Encoding\": \"gzip, deflate\",\n # \"Accept-Language\": \"zh-Hans-CN, zh-Hans; q=0.5\",\n # \"Connection\": \"Keep-Alive\",\n \"Cookie\": Config.get_config(\"http_header\", \"Cookie\"),\n # \"Host\": \"movie.douban.com/\",\n # \"Referer\": \"movie.douban.com\",\n # \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": Config.get_config(\"http_header\", \"User-Agent\")}\n\n\ndef read_html_content(url, timeout=10, encoding='utf-8'):\n re = requests.get(url, timeout=timeout, headers=douban_heads)\n re.encoding = encoding\n Logger.Log.logger.debug(\n 'url : ' + url + \"]down_html_by_url status_code : \" + str(re.status_code))\n if re.status_code is requests.codes.ok:\n return re.text\n elif re.status_code == 404:\n Logger.Log.logger.error(\n 'url : ' + url + \"]down_html_by_url ErrorCode : 404\")\n raise NotFoundError()\n elif re.status_code == 403:\n MailUtil.send_mail(\"Download Douban HttpError\", \"[url : \" + url + \"][douban_heads:\" + str(\n douban_heads) + \"]down_html_by_url ForbiddenError ForbiddenError : 403\")\n Logger.Log.logger.error(\n 'url : ' + url + \"]down_html_by_url ErrorCode : 403\")\n raise ForbiddenError()\n elif re.status_code == 400:\n MailUtil.send_mail(\"Download Douban HttpError\", \"[url : \" + url + \"][douban_heads:\" + str(\n douban_heads) + \"]down_html_by_url ForbiddenError BadRequestError : 403\")\n Logger.Log.logger.error(\n 'url : ' + url + \"]down_html_by_url ErrorCode : 400\")\n raise BadRequestError()\n else:\n Logger.Log.logger.error(\n 'url : ' + url + \"]down_html_by_url ErrorCode :\" + str(re.status_code))\n raise IOError()\n","sub_path":"util/HttpUtil.py","file_name":"HttpUtil.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"281608971","text":"import sys\n\nsys.stdin = open('input_1890.txt', 'r')\n\nboard = []\nN = int(input())\n\nfor _ in range(N):\n board.append(list(map(int, input().split())))\n\nzero_list = [[0 for _ in range(N)] for _ in range(N)]\ncnt_list = [[0 for _ in range(N)] for _ in range(N)]\n\ncnt_list[0][0] = 1\n\nzero_list[0][0] = board[0][0]\nfor i in range(len(zero_list)):\n for j in range(len(zero_list)):\n if zero_list[i][j] != 0:\n a = board[i][j]\n if 0 <= i + a < N:\n zero_list[i + a][j] = board[i + a][j]\n cnt_list[i + a][j] += cnt_list[i][j]\n if 0 <= j + a < N:\n zero_list[i][j + a] = board[i][j + a]\n cnt_list[i][j + a] += cnt_list[i][j]\n\nprint(cnt_list[-1][-1])","sub_path":"SWEA/1890_점프.py","file_name":"1890_점프.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"39912236","text":"#363 矩形区域不超过 K 的最大数值和\n\nclass Solution:\n def maxSumSubmatrix(self, matrix, k):\n row = len(matrix)\n col = len(matrix[0])\n res = float('-inf')\n for r in range(col):\n rowSum = [0] * row\n for c in range(r,col):\n for r in range(row):\n rowSum[r] = rowSum[r] + matrix[r][c]\n\n temp = [0]\n subSum = 0\n for e in rowSum:\n subSum = subSum + e\n left = bisect.bisect_left(temp, subSum - k)\n if left < len(temp):\n res = max(subSum - temp[left],res)\n bisect.insort(temp, subSum)\n if res == k:\n return res\n return res","sub_path":"Week_05/max_sum.py","file_name":"max_sum.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"550678568","text":"import math\r\nimport random\r\nclass Player:\r\n def __init__(self,letter):\r\n self.letter=letter\r\n def get_move(self,game):\r\n pass\r\nclass Computer(Player):\r\n def __init__(self,letter):\r\n super().__init__(letter)\r\n def get_move(self,game):\r\n square=random.choice(game.available_moves())\r\n return square\r\nclass HumanPlayer(Player):\r\n def __init__(self,letter):\r\n super().__init__(letter)\r\n def get_move(self,game):\r\n valid_square=False\r\n val=None\r\n while not valid_square:\r\n square=input(self.letter+'\\'s turn. Input move(0-8) :')\r\n try:\r\n val=int(square)\r\n if val not in game.available_moves():\r\n raise ValueError\r\n valid_square=True\r\n except ValueError:\r\n print(\"Invalid Enter again\")\r\n return val\r\nclass SuperComputer(Player):\r\n def __init__(self,letter):\r\n super().__init__(letter)\r\n def get_move(self,game):\r\n if len(game.available_moves())==9:\r\n square= random.choice(game.available_moves())\r\n else:\r\n square=self.minimax(game,self.letter)['pos']\r\n return square\r\n def minimax(self,state,player):\r\n max_player=self.letter\r\n other_player='O' if self.letter=='X' else 'X'\r\n if state.current_winner==other_player:\r\n return {'pos' : None,\r\n 'score': 1*(state.num_empty_squares()+1) if other_player==max_player else -1*(state.num_empty_squares()+1)}\r\n elif state.num_empty_squares()==0:\r\n return {'pos':None,'score':0}\r\n if player==max_player:\r\n best={'pos':None ,'score':-math.inf}\r\n else:\r\n best={'pos':None,'score':math.inf}\r\n for pos_mov in state.available_moves():\r\n state.make_move(pos_mov,player)\r\n sim_score=self.minimax(state,other_player)\r\n state.board[pos_mov]=' '\r\n state.current_winner=None\r\n sim_score['pos']=pos_mov\r\n if player==max_player:\r\n if best['score']sim_score['score']:\r\n best=sim_score\r\n return best","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"398294542","text":"import requests\nimport json\n\nurl = 'http://127.0.0.1:80/api/'\n\n#data = [[14.34, 1.68, 2.7, 25.0, 98.0, 2.8, 1.31, 0.53, 2.7, 13.0, 0.57, 1.96, 660.0]]\ndata2 = [51, 'Female', 'No', 'No', 'No', 'No', 'No', 'No', 'Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'No', 'No']\n\ndata = [{\"Age\":30,\"Gender\":\"Female\",\"Polyuria\":\"No\",\"Polydipsia\":\"No\",\"sudden weight loss\":\"Yes\",\"weakness\":\"Yes\",\"Polyphagia\":\"No\",\"Genital thrush\":\"No\",\"visual blurring\":\"Yes\",\"Itching\":\"No\",\"Irritability\":\"No\",\"delayed healing\":\"No\",\"partial paresis\":\"No\",\"muscle stiffness\":\"No\",\"Alopecia\":\"No\",\"Obesity\":\"No\"}]\n\nj_data = json.dumps(data)\nprint(j_data)\nheaders = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}\nr = requests.post(url, data=j_data, headers=headers)\nprint(r, r.text)\n\n","sub_path":"api/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"115117734","text":"#!/usr/bin/python3\nimport sys\n\nprevious = None\nsum = 0\n\ninput = open(\"bigrams.txt\", 'w')\nfor line in sys.stdin:\n key,value = line.split( '\\t' )\n\n if key != previous:\n if previous is not None:\n input.write ( str( sum ) + '\\t' + previous + '\\n' )\n previous = key\n sum = 0\n \n sum = sum + int(value)\n\ninput.write( str(sum) + '\\t' + previous + '\\n')\ninput.close()\n","sub_path":"breducer.py","file_name":"breducer.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"550629521","text":"# WARNING: SET 0 ON UGS GUI FIRST\n# TODO: Replace the time sleeps with something more reliable.. try to poll GRBL for real time position.\n\nimport serial\nimport time\nimport socket\nfrom helper import *\n\n#first row=[3, 5.7, 8.9, 11.5, 15, 17.6, 21.08, 27.48, 30.78, 33.48, 36.78, 39.4, 42.8, 45.6, 48.82]\n\n# after an offset of 6mm from the switch. the first plant is actually at 2.6in from 0.\n\n\n\n#second row = [3, 5.5, 9, 11.55, 15.05, 17.55, 28.15, 30.71, 34.21, 36.67, 40.21, 46.22, ]\n\n\n# static system timing and demo\nstatics = serial.Serial('/dev/ttyACM0', 115200)\ntime.sleep(2)\n\nstatics.write(b'3') # turn on the first outlet\ntime.sleep(3)\n\n# Open grbl serial port for the robotic base\nrb = serial.Serial('/dev/ttyACM1',115200)\n\n# Open the robotic arm serial port\nra = serial.Serial('/dev/ttyACM2', 115200)\n\ngrbl_init(rb)\n\n\nrb.write('G92 X0 Y0 Z0\\n') # set the origin\n\nrb.write('G00 X23\\n')\ntime.sleep(30)\n\n\n### Imaging Demo ###\n\nrb.write('G00 Y4.5\\n')\ntime.sleep(15)\n\nprint('Front row harvest position')\nfront_image(ra)\ntime.sleep(2)\n\nrb.write('G00 Y0\\n')\ntime.sleep(15)\n\nrb.write('G00 X3\\n')\ntime.sleep(20)\n\n\nfront_plants = [3, 5.7, 8.9, 11.5, 15, 17.6, 21.08]\n\n\nfor i in range(len(front_plants)):\n s = socket.socket() # Create a socket object\n host = '10.42.0.219' # Get local machine name\n port = 12345 # Reserve a port for your service.\n\n print('Moving to plant...')\n rb.write('G00 X{}\\n'.format(front_plants[i]))\n time.sleep(5)\n\n s.connect((host, port))\n\n f = open('{}-{}.jpg'.format(time.time(), i), 'wb')\n\n print('Receiving...')\n l = s.recv(1024)\n while (l):\n f.write(l) # write data\n l = s.recv(1024)\n\n f.close()\n print('Done receiving')\n\n s.shutdown(socket.SHUT_WR)\n s.close() # Close the socket when done\n\n time.sleep(10)\n\n\nback_image(ra)\ntime.sleep(2)\n\nrb.write('G00 X3\\n')\ntime.sleep(25)\n\nback_plants = [3, 5.5, 9, 11.55, 15.05, 17.55]\n\nfor i in range(len(back_plants)):\n s = socket.socket() # Create a socket object\n host = '10.42.0.219' # Get local machine name\n port = 12345 # Reserve a port for your service.\n\n\n print('Moving to plant...')\n rb.write('G00 X{}\\n'.format(back_plants[i]))\n time.sleep(5)\n\n s.connect((host, port))\n\n f = open('{}-{}.jpg'.format(time.time(), i), 'wb')\n\n print('Receiving...')\n l = s.recv(1024)\n while (l):\n f.write(l) # write data\n l = s.recv(1024)\n\n f.close()\n print('Done receiving')\n\n s.shutdown(socket.SHUT_WR)\n s.close() # Close the socket when done\n\n time.sleep(10)\n\nretract(ra)\ntime.sleep(2)\n\nprint(\"Ending image demo\")\nrb.write('G00 X0\\n')\ntime.sleep(40)\n\n#### End Imaging demo ######\n\n\n\nprint(\"Steppin out\")\nrb.write('G00 X6\\n')\ntime.sleep(15)\n\n\nprint('Rotating BOA')\nrb.write('G00 Z-0.15748\\n') # CHANGE VALUE\ntime.sleep(2)\n\nprint('Moving to nursery')\nrb.write('G00 X11 Y-20.7\\n')\ntime.sleep(30)\n\nharvest_front(ra) # move to the harvest position for the front row\ntime.sleep(2)\n\nprint('Rotating BOA')\nrb.write('G00 Z0\\n') # CHANGE VALUE\ntime.sleep(2)\n\nprint('Lowering base')\nrb.write('G00 Y-16.75\\n')\ntime.sleep(20)\n\nclose_grip(ra) # close the EE gippers\ntime.sleep(2)\n\nprint('Raising base')\nrb.write('G00 Y-20.7\\n')\ntime.sleep(20)\n\nprint('Rotating BOA')\nrb.write('G00 Z-0.15748\\n') # CHANGE VALUE\ntime.sleep(3)\n\nprint('Lowering base')\nrb.write('G00 X10.658 Y0\\n')\ntime.sleep(35)\n\nprint('Rotating BOA')\nrb.write('G00 Z0\\n') # CHANGE VALUE\ntime.sleep(5)\n\nprint('Placing plant..')\nrb.write('G00 Y6.75\\n')\ntime.sleep(15)\n\nharvest_front(ra)\ntime.sleep(2)\n\nprint('Raising base')\nrb.write('G00 Y0\\n')\ntime.sleep(5)\n\n\nrb.write('G00 X0\\n')\n\n\ntime.sleep(30)\n\n\n##### Nursery complete ############\n\n\nprint('Moving to first plant')\nrb.write('G00 X5\\n')\ntime.sleep(15)\n\nharvest_front(ra) # move to the harvest position for the front row\ntime.sleep(2)\n\nprint('Lowering base')\nrb.write('G00 Y6.75\\n')\ntime.sleep(11)\n\nclose_grip(ra) # close the EE gippers\ntime.sleep(2)\n\nprint('Raising base')\nrb.write('G00 Y0\\n')\n\nprint('Rotating BOA')\nrb.write('G00 Z-0.15748\\n') # CHANGE VALUE\ntime.sleep(5)\n\nprint('Traveling to next shelf')\nrb.write('G00 X4.9 Y20\\n')\ntime.sleep(40)\n\nprint('Rotating BOA')\nrb.write('G00 Z0\\n') # CHANGE VALUE\ntime.sleep(5)\n\nprint('Second shelf harvest position')\nharvest_second_front(ra)\ntime.sleep(5)\n\nprint('Lowering into position')\nrb.write('G00 Y26.421\\n')\ntime.sleep(11)\n\nprint('Opening gripper')\nsecond_open(ra)\ntime.sleep(5)\n\nprint('Raising base')\nrb.write('G00 Y20\\n')\ntime.sleep(11)\n\nprint('Rotating BOA')\nrb.write('G00 Z-0.15748\\n') # CHANGE VALUE\ntime.sleep(2)\n\n\nprint('Going home...')\nrb.write('G00 X5.3 Y0\\n')\ntime.sleep(25)\n\n\nprint('Rotating BOA')\nrb.write('G00 Z0\\n') # CHANGE VALUE\ntime.sleep(2)\n\n\nrb.write('G00 X0\\n')\n\nprint('First transfer complete..')\n\ntime.sleep(10)\n\n\n# Close file and serial port\nrb.close()\nra.close()\nstatics.close()\n","sub_path":"robotics/alpha-demo.py","file_name":"alpha-demo.py","file_ext":"py","file_size_in_byte":4935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"80758520","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# This module copyright (C) 2015 Savoir-faire Linux\n# ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp import models, fields, api, _\n\n\nsales_order_states = [\n 'progress', 'manual', 'shipping_exept', 'invoice_except', 'done']\n\nquotations_states = ['draft', 'sent', 'waiting_date']\nprojects_states = ['template','draft','open','cancelled', 'pending', 'close']\n\n\nclass CrmLead(models.Model):\n _inherit = 'crm.lead'\n\n def count_sales_order(self):\n if not self.partner_id:\n return False\n self.sales_order_count = self.env['sale.order'].search_count([\n ('partner_id', '=', self.partner_id.id),\n ('state', 'in', sales_order_states),\n ])\n self.quotations_count = self.env['sale.order'].search_count([\n ('partner_id', '=', self.partner_id.id),\n ('state', 'in', quotations_states),\n ])\n self.projects_count = self.env['project.project'].search_count([\n ('partner_id', '=', self.partner_id.id),\n ('state', 'in', projects_states),\n ])\n\n sales_order_count = fields.Integer(compute='count_sales_order')\n quotations_count = fields.Integer(compute='count_sales_order')\n projects_count = fields.Integer(compute='count_sales_order')\n\n @api.multi\n def get_sale_order_view(self, order_states, view_title):\n partner_ids = [lead.partner_id.id for lead in self]\n\n orders = self.env['sale.order'].search([\n ('partner_id', 'in', partner_ids),\n ('state', 'in', order_states),\n ])\n\n res = {\n 'name': view_title,\n 'type': 'ir.actions.act_window',\n 'res_model': 'sale.order',\n 'view_type': 'form',\n }\n\n if len(orders) == 1:\n res['res_id'] = orders[0].id\n res['view_mode'] = 'form'\n else:\n res['domain'] = [\n ('state', 'in', order_states),\n ('partner_id', 'in', partner_ids),\n ]\n res['view_mode'] = 'tree,form'\n\n return res\n \n @api.multi\n def get_projects_view(self, project_states, view_title):\n partner_ids = [lead.partner_id.id for lead in self]\n\n projects = self.env['project.project'].search([\n ('partner_id', 'in', partner_ids),\n ('state', 'in', project_states),\n ])\n\n res = {\n 'name': view_title,\n 'type': 'ir.actions.act_window',\n 'res_model': 'project.project',\n 'view_type': 'form',\n }\n\n if len(projects) == 1:\n res['res_id'] = project[0].id\n res['view_mode'] = 'form'\n else:\n res['domain'] = [\n ('state', 'in', project_states),\n ('partner_id', 'in', partner_ids),\n ]\n res['view_mode'] = 'tree,form'\n\n return res\n\n @api.multi\n def button_sales_orders(self):\n return self.get_sale_order_view(sales_order_states, _('Sales Order'))\n\n @api.multi\n def button_quotations(self):\n return self.get_sale_order_view(quotations_states, _('Quotations'))\n \n @api.multi\n def button_projects(self):\n return self.get_projects_view(projects_states, _('Projects'))\n","sub_path":"crm_lead_sale_link/models/crm_lead.py","file_name":"crm_lead.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"76461512","text":"# # -*- coding: utf-8 -*\ntry:\n import tkinter as tkinter # for python 3.x\n import tkinter.messagebox as mb\nexcept:\n import Tkinter as tkinter # for python 2.x\n import tkMessageBox as mb\n\nimport random, time\n\n'''\n欢迎关注 微信公众号菜鸟学Python\n更多好玩有趣的实战项目\n'''\n\n\nclass Ball():\n ball_num = 0\n gap = 1\n ball_hit_bottom_num = 0\n ball_speed = 5\n\n def __init__(self, canvas, paddle, score, color, init_x=100, init_y=100):\n self.canvas = canvas\n self.paddle = paddle\n self.score = score\n self.color = color\n\n self.id = canvas.create_oval(10, 10, 30, 30, fill=self.color)\n self.canvas.move(self.id, init_x, init_y)\n\n Ball.ball_num += 1\n starts = [-3, -2, -1, 1, 1, 2, 3]\n random.shuffle(starts)\n self.x = starts[0]\n self.y = -3\n\n self.canvas_height = self.canvas.winfo_height()\n self.canvas_width = self.canvas.winfo_width()\n self.hit_bottom = False\n\n def adjust_paddle(self, paddle_pos):\n paddle_grow_length = 30\n paddle_width = paddle_pos[2] - paddle_pos[0]\n if self.color == 'red': # shorten the paddle length\n if paddle_width > 60:\n if paddle_pos[2] >= self.canvas_width:\n paddle_pos[2] = paddle_pos[2] - paddle_grow_length\n else:\n paddle_pos[0] = paddle_pos[0] + paddle_grow_length\n\n elif self.color == 'green': # stretch the paddle length\n if paddle_width < 300:\n if paddle_pos[2] >= self.canvas_width:\n paddle_pos[0] = paddle_pos[0] - paddle_grow_length\n else:\n paddle_pos[2] = paddle_pos[2] + paddle_grow_length\n self.canvas.coords(self.paddle.id, paddle_pos[0], paddle_pos[1], paddle_pos[2], paddle_pos[3])\n\n def hit_paddle(self, pos):\n paddle_pos = self.canvas.coords(self.paddle.id)\n print('paddle_pos:', paddle_pos[0], paddle_pos[1], paddle_pos[2], paddle_pos[3])\n if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:\n if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3] + Ball.gap:\n self.x += self.paddle.x\n colors = ['red', 'green']\n random.shuffle(colors)\n self.color = colors[0]\n self.canvas.itemconfigure(self.id, fill=colors[0])\n self.score.hit(ball_color=self.color)\n self.canvas.itemconfig(self.paddle.id, fill=self.color)\n self.adjust_paddle(paddle_pos)\n return True\n\n return False\n\n def draw(self):\n self.canvas.move(self.id, self.x, self.y)\n pos = self.canvas.coords(self.id)\n # print pos\n if pos[1] <= 0: # move down\n self.y = 3\n if pos[3] >= self.canvas_height: # hit the bottom\n self.hit_bottom = True\n if self.hit_paddle(pos) == True:\n self.y = -4\n\n if pos[0] <= 0: # move right\n self.x = Ball.ball_speed\n if pos[2] >= self.canvas_width: # move left\n self.x = -Ball.ball_speed\n\n\nclass Paddle:\n def __init__(self, canvas, color):\n self.canvas = canvas\n self.canvas_width = self.canvas.winfo_width()\n self.canvas_height = self.canvas.winfo_height()\n self.id = canvas.create_rectangle(0, 0, 180, 15, fill=color)\n self.canvas.move(self.id, 200, self.canvas_height * 0.75)\n self.x = 0\n self.started = False\n self.continue_game = False\n self.canvas.bind_all('', self.turn_left)\n self.canvas.bind_all('', self.turn_right)\n self.canvas.bind_all('', self.continue_game)\n self.canvas.bind_all('', self.start_game)\n self.canvas.bind_all('', self.pause_game)\n\n def draw(self):\n self.canvas.move(self.id, self.x, 0)\n pos = self.canvas.coords(self.id)\n\n if pos[0] <= 0: # left edge\n self.x = 0\n elif pos[2] >= self.canvas_width: # right edge\n self.x = 0\n\n def turn_left(self, evt):\n pos = self.canvas.coords(self.id)\n if pos[0] <= 0:\n self.x = 0\n else:\n self.x = -2\n\n def turn_right(self, evt):\n pos = self.canvas.coords(self.id)\n if pos[2] >= self.canvas_width:\n self.x = 0\n else:\n self.x = 2\n\n def start_game(self, evt):\n self.started = True\n\n def pause_game(self, evt):\n if self.started:\n self.started = False\n else:\n self.started = True\n\n\nclass Score():\n def __init__(self, canvas, color):\n self.score = 0\n self.canvas = canvas\n self.canvas_width = self.canvas.winfo_width()\n self.canvas_height = self.canvas.winfo_height()\n self.id = canvas.create_text(self.canvas_width - 150, 10, text='score:0', fill=color, font=(None, 18, \"bold\"))\n self.note = canvas.create_text(self.canvas_width - 70, 10, text='--', fill='grey', font=(None, 18, \"bold\"))\n\n def hit(self, ball_color='grey'):\n self.score += 1\n self.canvas.itemconfig(self.id, text='score:{}'.format(self.score))\n if ball_color == 'red':\n self.canvas.itemconfig(self.note, text='{}-'.format('W'), fill='red')\n elif ball_color == 'green':\n self.canvas.itemconfig(self.note, text='{}+'.format('W'), fill='green')\n else:\n self.canvas.itemconfig(self.note, text='--', fill='grey')\n\n\ndef main():\n tk = tkinter.Tk()\n\n # call back for Quit\n def callback():\n if mb.askokcancel(\"Quit\", \"Do you really wish to quit?\"):\n Ball.flag = False\n tk.destroy()\n\n tk.protocol(\"WM_DELETE_WINDOW\", callback)\n\n # Init parms in Canvas\n canvas_width = 600\n canvas_hight = 500\n tk.title(\"Ball Game V1.2\")\n tk.resizable(0, 0)\n tk.wm_attributes(\"-topmost\", 1)\n canvas = tkinter.Canvas(tk, width=canvas_width, height=canvas_hight, bd=0, highlightthickness=0, bg='#00ffff')\n canvas.pack()\n tk.update()\n\n score = Score(canvas, 'red')\n paddle = Paddle(canvas, \"magenta\")\n ball = Ball(canvas, paddle, score, \"grey\")\n\n game_over_text = canvas.create_text(canvas_width / 2, canvas_hight / 2, text='Game over', state='hidden',\n fill='red', font=(None, 18, \"bold\"))\n introduce = 'Welcome to Ball GameV1.2:\\nClick Any Key--Start\\nStop--Enter\\nContinue-Enter\\n'\n game_start_text = canvas.create_text(canvas_width / 2, canvas_hight / 2, text=introduce, state='normal',\n fill='magenta', font=(None, 18, \"bold\"))\n while True:\n if (ball.hit_bottom == False) and ball.paddle.started:\n canvas.itemconfigure(game_start_text, state='hidden')\n ball.draw()\n paddle.draw()\n if ball.hit_bottom == True:\n time.sleep(0.1)\n canvas.itemconfigure(game_over_text, state='normal')\n tk.update_idletasks()\n tk.update()\n time.sleep(0.01)\n\n\nif __name__ == '__main__':\n main()","sub_path":"Test/game/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":7164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"603690686","text":"import csv\r\nfrom googletrans import Translator\r\n\r\npl = \"PL\"\r\neng = \"EN\"\r\n\r\ntranslator = Translator()\r\n\r\nwith open('in.tsv') as in_file:\r\n with open('out.tsv', 'w') as out_file:\r\n writer = csv.writer(out_file)\r\n for row in csv.reader(in_file):\r\n if row:\r\n translation = translator.translate(row[0], dest=eng, source=pl)\r\n writer.writerow([translation.text])","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"222673164","text":"import sqlite3\nimport requests\nimport os\n\nBASIC_LANDS = (\n 'plains',\n 'island',\n 'swamp',\n 'mountain',\n 'forest')\n\nDB_FILENAME = \"data/mtg.sqlite\"\n\nCARDS_DB_COLS = (\n 'layout',\n 'colors',\n 'power',\n 'name',\n 'subtypes',\n 'types',\n 'cmc',\n 'manaCost',\n 'imageName',\n 'text',\n 'type',\n 'toughness',\n 'supertypes',\n 'names',\n 'starter',\n 'hand',\n 'life',\n 'loyalty')\n\nSETS_DB_COLS = (\n 'code',\n 'magicCardsInfoCode',\n 'border',\n 'releaseDate',\n 'type',\n 'magicRaritiesCodes',\n 'name',\n 'cards',\n 'booster',\n 'languagesPrinted',\n 'block',\n 'gathererCode',\n 'onlineOnly',\n 'oldCode')\n\ndef card_search(card):\n db = sqlite3.connect(DB_FILENAME)\n cur = db.cursor()\n search = \"%\"+card+\"%\" \n cur.execute('''\n SELECT name FROM mtg_cards WHERE name LIKE ?\n ''', (search,))\n data = cur.fetchall()\n \n if len(data) == 1:\n cur.execute('''\n SELECT * FROM mtg_cards WHERE name = ? \n ''', (data[0][0],))\n data = cur.fetchall()\n db.close()\n return data\n\ndef get_card(card_name):\n card = dict()\n if str(card_name).lower() in BASIC_LANDS:\n for col in CARDS_DB_COLS:\n card[col] = 'NaN'\n card['layout'] = 'normal'\n card['name'] = str(card_name).title()\n card['types'] = ['Land']\n card['type'] = 'Land'\n return card\n else:\n search = card_search(card_name)\n if len(search) == 1:\n for col in CARDS_DB_COLS:\n card[col] = search[0][len(card)]\n return card\n else:\n return None \n \ndef get_sets_json():\n try:\n sets = requests.get('http://mtgjson.com/json/AllSets.json').json()\n return sets\n except:\n return {}\n\ndef get_cards_json():\n try:\n cards = requests.get('http://mtgjson.com/json/AllCards.json').json()\n return cards\n except:\n return {}\n\ndef create_mtg_table():\n while True:\n if not os.path.isfile(DB_FILENAME):\n db = sqlite3.connect(DB_FILENAME) \n cur = db.cursor()\n cur.execute('''\n CREATE TABLE mtg_sets(\n code TEXT,\n magicCardsInfoCode TEXT,\n border TEXT,\n releaseDate DATE,\n type TEXT,\n magicRaritiesCodes TEXT,\n name TEXT,\n cards TEXT,\n booster TEXT,\n languagesPrinted TEXT,\n block TEXT,\n gathererCode TEXT,\n onlineOnly TEXT,\n oldCode TEXT)\n ''')\n cur.execute('''\n CREATE TABLE mtg_cards(\n layout TEXT,\n colors TEXT,\n power TEXT,\n name TEXT,\n subtypes TEXT,\n types TEXT,\n cmc TEXT,\n manaCost TEXT,\n imageName TEXT,\n text TEXT,\n type TEXT,\n toughness TEXT,\n supertypes TEXT,\n names TEXT,\n starter TEXT,\n hand TEXT,\n life TEXT,\n loyalty TEXT)\n ''')\n db.commit()\n db.close()\n break\n else:\n usr = input(\"mtg.sqlite already exists, delete it? [Y/N]\")\n if usr.lower() == 'n':\n break\n elif usr.lower() == 'y':\n os.remove(DB_FILENAME)\n\ndef populate_cards_table():\n if not os.path.isfile(DB_FILENAME):\n create_mtg_table()\n db = sqlite3.connect(DB_FILENAME)\n cur = db.cursor()\n all_cards = get_cards_json()\n for key in all_cards:\n table_list = list()\n for header in CARDS_DB_COLS:\n table_list.append(str(all_cards[key][header]) if header in all_cards[key] else 'NaN')\n cur.execute('''\n INSERT INTO mtg_cards(\n layout,\n colors,\n power,\n name,\n subtypes,\n types,\n cmc,\n manaCost,\n imageName,\n text,\n type,\n toughness,\n supertypes,\n names,\n starter,\n hand,\n life,\n loyalty) \n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) \n ''',table_list)\n db.commit()\n db.close()\n\ndef populate_sets_table():\n if not os.path.isfile(DB_FILENAME):\n create_mtg_table()\n \n db = sqlite3.connect(DB_FILENAME)\n cur = db.cursor()\n all_sets = get_sets_json()\n for key in all_sets:\n table_list = list()\n for header in SETS_DB_COLS:\n table_list.append(str(all_sets[key][header]) if header in all_sets[key] else 'NaN')\n cur.execute('''\n INSERT INTO mtg_sets(\n code,\n magicCardsInfoCode,\n border,\n releaseDate,\n type,\n magicRaritiesCodes,\n name,\n cards,\n booster,\n languagesPrinted,\n block,\n gathererCode,\n onlineOnly,\n oldCode) \n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?) \n ''',table_list)\n db.commit()\n db.close()\n","sub_path":"mtg_db.py","file_name":"mtg_db.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"264326532","text":"# tab1\nimport os\nimport pandas as pd\ntest = {}\nfor i in os.listdir():\n if i=='merge.py':\n continue\n test.setdefault(i.split('.')[1],[]).append(i)\nfor k,v in test.items():\n seps = {'xls':'\\t','csv':','}\n dfs = [pd.read_csv(i,sep=seps[i.split('.')[-1]],engine='python') for i in v]\n df = pd.concat(dfs)\n cols=[]\n for col in ['#Sample','Species','Genus','Re_Abu','SDSMRN','SDSMRNG']:\n if col in df.columns.tolist():\n cols.append(col)\n df=df[cols]\n df.to_csv(r'/hwfssz1/ST_HEALTH/Population_Genomics/User/dengqiuyang/华山医院/0103.merge/{}.merge.xls'.format(k),sep='\\t',index=False)\n","sub_path":"09.已完成/01.不同采样部位病原菌水平分析/02.Huashan_AiJingwen/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"459727789","text":"import re\nfrom collections import Counter\nimport argparse\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--top', '-t', default=None, help='number of words which will be showed')\n parser.add_argument(dest='file', help='input file')\n args = parser.parse_args()\n args.top = int(args.top)\n count = Counter([])\n with open(args.file) as file:\n for line in file:\n count.update(re.findall(r'[\\w]+\\b', line.lower()))\n top_counter = 0\n for word in sorted(count, key=count.get, reverse=True):\n if args.top is not None and args.top <= top_counter:\n break\n print('{}\\t{}'.format(word, count[word]))\n top_counter += 1\n","sub_path":"2018-komp-ling/practicals/practical2-response.eng/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"319232521","text":"from copy import copy\nfrom quex.frs_py.string_handling import blue_print\ndb={}\n\ndef get_label(StateMachineName, StateIdx, SuccessfulOriginalStateMachineID=None):\n \"\"\"\n (1) StateIdx != None\n jump label for state machine state entry \n (2) StateIdx == None: terminal state\n (1a) SuccessfulOriginalStateMachineID == None: not acceptance terminal state\n (1b) else: acceptance terminal state\n \"\"\"\n def nice(SM_ID): return repr(SM_ID).replace(\"L\", \"\")\n\n if StateIdx != None: \n return \"QUEX_LABEL_%s_ENTRY_%s\" % (StateMachineName, nice(StateIdx))\n elif SuccessfulOriginalStateMachineID == None:\n return \"QUEX_LABEL_%s_TERMINAL\" % StateMachineName\n else: \n return \"QUEX_LABEL_%s_TERMINAL_%s\" % (StateMachineName, nice(SuccessfulOriginalStateMachineID))\n\n#________________________________________________________________________________\n# C++\n#\ndef __cpp_goto_state(UserDefinedStateMachineName, StateIdx, SuccessfulOriginalStateMachineID=None):\n return \"goto %s;\" % get_label(UserDefinedStateMachineName, StateIdx, SuccessfulOriginalStateMachineID)\n \ndef __cpp_acceptance_info(SuccessfulOriginalStateMachineID, LanguageDB):\n if SuccessfulOriginalStateMachineID != None:\n txt = \"last_acceptance = %s;\\n\" % SuccessfulOriginalStateMachineID\n txt += LanguageDB[\"$input/tell_position\"](\"last_acceptance_input_position\") + \"\\n\"\n else:\n txt = \"\" \n return txt\n\n__cpp_function_header = \\\n\"\"\"#include\n#define QUEX_CHAR_BUFFER_BASED\n\n#if defined QUEX_ANALYSER_STREAM_BASED\n# define QUEX_ANALYSER_FUNC_ARGS std::istream& stream\n# define QUEX_ANALYSER_RETURN_TYPE int\n# define QUEX_CHARACTER_TYPE int\n# define QUEX_CHARACTER_POSITION std::istream::pos_type\n# define QUEX_STREAM_GET(character) (character = stream.get())\n# define QUEX_STREAM_TELL(position) (position = stream.tellg())\n# define QUEX_STREAM_SEEK(position) (stream.seekg((position)))\n#endif\n\n#if defined QUEX_CHAR_BUFFER_BASED\n/* Pass a pointer to a pointer to the analyser, because the last lexing\n** position is to be stored. This way the next call to the analyser can\n** start where it has stopped before.\n*/\n# define QUEX_ANALYSER_FUNC_ARGS unsigned char** char_pp\n# define QUEX_ANALYSER_RETURN_TYPE int\n# define QUEX_CHARACTER_TYPE unsigned char\n# define QUEX_CHARACTER_POSITION unsigned char*\n# define QUEX_STREAM_GET(character) character = (**char_pp); ++(*char_pp); \n# define QUEX_STREAM_TELL(position) position = *char_pp;\n# define QUEX_STREAM_SEEK(position) *char_pp = position;\n#endif\n\n#if defined QUEX_ANALYSER_UNICODE_VECTOR_BASED\n// Each element in the vector contains a unicode character\n# define QUEX_ANALYSER_FUNC_ARGS std::vector::iterator& it\n# define QUEX_ANALYSER_RETURN_TYPE int\n# define QUEX_CHARACTER_TYPE int\n# define QUEX_CHARACTER_POSITION std::vector::iterator\n# define QUEX_STREAM_GET(character) character = (*it); ++it; \n# define QUEX_STREAM_TELL(position) position = it;\n# define QUEX_STREAM_SEEK(position) it = position;\n#endif\n\nQUEX_ANALYSER_RETURN_TYPE\n$$QUEX_ANALYZER_FUNCTION_NAME$$(QUEX_ANALYSER_FUNC_ARGS) {\n int last_acceptance = -1;\n QUEX_CHARACTER_POSITION last_acceptance_input_position = (QUEX_CHARACTER_POSITION)(0x00);\n QUEX_CHARACTER_TYPE input = (QUEX_CHARACTER_TYPE)(0x00);\\n\n\"\"\"\ndef __cpp_analyser_function(FunctionName, function_body): \n txt = __cpp_function_header.replace(\"$$QUEX_ANALYZER_FUNCTION_NAME$$\", \n FunctionName)\n txt += function_body\n txt += \"}\\n\"\n return txt\n\n__cpp_terminal_state_str = \"\"\"\n // (*) terminal states\n //\n // NOTE: 'input' contains the next character already, so there is no\n // need to read it from the stream again. Thus,\n //\n // goto QUEX_LABEL_$$STATE_MACHINE_NAME$$_ENTRY_INITIAL_STATE;\n //\n // at the end of each acceptance terminal state. However:\n //\n // goto $$INITIAL_STATE_INDEX_LABEL$$;\n // \n // However, in cases that the related action contains a 'return' it has\n // to be sure that the lexical analysis starts at the previous position.\n // Thus one needs to 'seek-back' first. We write the 'input-get' code directly\n // after the pattern action, so that the compiler might be able to recognize\n // a redundancy during optimization.\n\n // specific terminal states, i.e. related to a 'winner pattern'. this means,\n // that the last input before the pattern matched a complete pattern.\n $$SPECIFIC_TERMINAL_STATES$$\n\n TERMINAL_GENERAL:\n int tmp = last_acceptance;\n last_acceptance = 0x00; // reset the last acceptance position for next run\n // jump to last acceptance state\n // if last acceptance:\n // -- execute pattern action \n // -- goto initial state\n // else:\n // -- execute defaul action\n // -- goto initial state \n switch( tmp ) {\n $$JUMPS_TO_ACCEPTANCE_STATE$$\n default:\n // no acceptance state \n $$DEFAULT_ACTION$$\n QUEX_STREAM_GET(input);\n goto QUEX_LABEL_$$STATE_MACHINE_NAME$$_ENTRY_INITIAL_STATE; \n }\n\"\"\"\n\ndef __cpp_terminal_states(StateMachineName, sm, action_db, DefaultAction):\n \n # -- specific terminal states of patterns (entered from acceptance states)\n txt = \"\"\n for state_machine_id in action_db.keys():\n txt += \" %s:\\n\" % get_label(\"\", None, state_machine_id)\n action_code = \" \" + action_db[state_machine_id].replace(\"\\n\", \"\\n \") \n txt += \" QUEX_STREAM_SEEK(last_acceptance_input_position);\"\n txt += action_code + \"\\n\" \n txt += \" // if action code returns from the function, then the following is meaningless\\n\"\n if sm.states[sm.init_state_index].transitions().is_empty() == False:\n txt += \" QUEX_STREAM_GET(input);\"\n txt += \" goto QUEX_LABEL_%s_ENTRY_INITIAL_STATE;\\n\" % StateMachineName\n\n specific_terminal_states_str = txt\n\n # -- general terminal state (entered from non-acceptance state) \n txt = \"\" \n for state_machine_id in action_db.keys():\n txt += \" case %s: goto %s;\\n\" % \\\n (repr(state_machine_id), get_label(\"\", None, state_machine_id))\n jumps_to_acceptance_states_str = txt\n\n\n # -- execute default pattern action \n # -- reset character stream to last success \n # -- goto initial state \n txt = blue_print(__cpp_terminal_state_str, \n [[\"$$JUMPS_TO_ACCEPTANCE_STATE$$\", jumps_to_acceptance_states_str], \n [\"$$SPECIFIC_TERMINAL_STATES$$\", specific_terminal_states_str],\n [\"$$DEFAULT_ACTION$$\", DefaultAction.replace(\"\\n\", \" \\n\")],\n [\"$$STATE_MACHINE_NAME$$\", StateMachineName],\n [\"$$INITIAL_STATE_INDEX_LABEL$$\", get_label(StateMachineName, sm.init_state_index)]])\n return txt\n \n#________________________________________________________________________________\n# Visual Basic 6\n# \ndb[\"VisualBasic6\"] = {\n \"$if\": \"If\",\n \"$then\": \"Then\",\n \"$endif\": \"End If\",\n \"$>=\": \">=\",\n \"$==\": \"==\",\n \"$input\": \"input\",\n \"$return_true\": \"$the_function = True: Exit Function\",\n \"$return_false\": \"$the_function = True: Exit Function\",\n }\n\n\ndef replace_keywords(program_txt, LanguageDB, NoIndentF):\n \"\"\"Replaces pseudo-code keywords with keywords of the given language.\"\"\"\n\n txt = blue_print(program_txt, LanguageDB.items())\n\n if NoIndentF == False:\n # delete the last newline, to prevent additional indentation\n if txt[-1] == \"\\n\": txt = txt[:-1]\n # indent by four spaces\n # (if this happens in recursively called functions nested indented blocks\n # are correctly indented, see NumberSet::get_condition_code() for example) \n txt = txt.replace(\"\\n\", \"\\n \") + \"\\n\"\n \n return txt \n","sub_path":"dependencies/quex-0.34.1/quex/core_engine/generator/languages/visual_basic.py","file_name":"visual_basic.py","file_ext":"py","file_size_in_byte":8249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"368768329","text":"\nimport numpy as np\nimport pandas as pd\nimport codecs\n\n\ndef save_txt(txt_path, *args):\n '''\n Log a text file\n '''\n with codecs.open(txt_path, \"a\", \"utf-8\") as log_file: # \"a\" : append\n for line in args:\n log_file.write(line + \"\\n\")\n\n\ndef save_excel(excel_path, args):\n \"\"\"\n logger function to write input data to an excel file.\n excel_path: path to save excel file\n args: List containing excel sheet name and data. Data structure is a dictionary. [(\"sheet name\", dictionary)]\n Dictionary key is used as column name, and dictionary value is used as data. \n \"\"\"\n excel_writer = pd.ExcelWriter(excel_path)\n\n for (sheet_name, data) in args:\n result_excel = pd.DataFrame.from_dict(data=data)\n result_excel.to_excel(excel_writer, sheet_name, index=False)\n excel_writer.save()\n\n\ndef save_csv(csv_path, data):\n '''\n Save data in a csv file.\n data is a Numpy array\n ''' \n with open(csv_path, 'a') as f:\n # x_numpy.tofile(f, sep=',', format='%10.5f')\n np.savetxt(f, data, delimiter=\",\", fmt='%.5f') # it saves only 5 digts after decimal point to reduce csv file size\n # np.savetxt(f, data, delimiter=\",\")\n\n\n","sub_path":"tools/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"185097473","text":"from io import BytesIO\nfrom random import randint\nfrom typing import List\n\nfrom PIL import Image, ImageOps, UnidentifiedImageError, ImageFilter\n\n\ndef bytes2image(image: bytes) -> Image.Image:\n if image.__sizeof__() > 10 * (2 ** 20):\n raise ValueError(\"Exceeds 10MB\")\n try:\n io = BytesIO(image)\n io.seek(0)\n return Image.open(io)\n except UnidentifiedImageError:\n raise ValueError(\"Unable to use Image\")\n\n\ndef image2bytes(img: Image.Image) -> BytesIO:\n image_bytes = BytesIO()\n img.save(image_bytes, format=\"png\") # type: ignore\n image_bytes.seek(0)\n return image_bytes\n\n\ndef invert(img_bytes: bytes) -> BytesIO:\n img: Image.Image = bytes2image(img_bytes).resize((400, 400), 1)\n img = img.convert(\"RGB\")\n return image2bytes(ImageOps.invert(img))\n\n\ndef red(img_bytes: bytes) -> BytesIO:\n img = bytes2image(img_bytes)\n im = img.resize((400, 400), 1)\n w, h = im.size\n red = Image.new(\"RGBA\", (w, h), color=(255, 0, 0, 120))\n im.paste(red, mask=red)\n return image2bytes(im)\n\n\ndef polaroid(img_bytes: bytes, fixed: bool = True) -> BytesIO:\n if fixed is True:\n w, h = (401, 401)\n img = bytes2image(img_bytes).resize((w, h), 1)\n else:\n img = bytes2image(img_bytes)\n w, h = img.size\n W, H = (w + 29, h + 29)\n blank = Image.new(\"RGBA\", (W, H + 80), color=(255, 255, 255, 255))\n blank.paste(img, (round(round(W - w) / 2), round(round(H - h) / 2)))\n final = blank\n return image2bytes(final)\n\n\ndef sad(img_bytes: bytes) -> BytesIO:\n img = bytes2image(img_bytes)\n im = img.resize((400, 400), 1)\n w, h = im.size\n raindrop = Image.open(\"assets/raindrops.png\")\n raindrop = raindrop.convert(\"RGBA\")\n darken = Image.new(\"RGBA\", (w, h), color=(0, 0, 0, 100))\n im.paste(darken, mask=darken)\n im.paste(raindrop, mask=raindrop)\n return image2bytes(im)\n\n\ndef blurplify(img_bytes: bytes) -> BytesIO:\n img: Image.Image = bytes2image(img_bytes)\n img = img.resize((400, 400), 1)\n w, h = img.size\n blurple = Image.new(\"RGBA\", (w, h), color=(88, 101, 242, 160))\n img.paste(blurple, mask=blurple)\n return image2bytes(img)\n\n\ndef triggered(img_bytes: bytes) -> BytesIO:\n img = bytes2image(img_bytes)\n img = img.resize((500, 500), 1)\n frames: List[Image.Image] = []\n for _frame in range(30):\n canvas = Image.new(\"RGBA\", (400, 400))\n x = -1 * (randint(50, 100))\n y = -1 * (randint(50, 100))\n canvas.paste(img, (x, y))\n red = Image.new(\"RGBA\", (400, 400), color=(255, 0, 0, 80))\n canvas.paste(red, mask=red)\n # Add triggered thingy\n trig: Image.Image = Image.open(\"assets/triggered.png\")\n trig = trig.convert(\"RGBA\")\n canvas.paste(trig, mask=trig)\n frames.append(canvas)\n byteArray = BytesIO()\n frames[0].save(\n byteArray,\n format=\"GIF\",\n save_all=True,\n duration=60,\n loop=0,\n append_images=frames,\n )\n byteArray.seek(0)\n return byteArray\n\n\ndef blur(img_bytes: bytes, fixed: bool = True) -> BytesIO:\n img = bytes2image(img_bytes)\n if fixed:\n img = img.resize((500, 500), 1)\n blur = ImageFilter.GaussianBlur(radius=20)\n img = img.filter(blur)\n return image2bytes(img)\n\n\nif __name__ == \"__main__\":\n with open(\"origin.png\", \"rb\") as in_:\n imgBytes = in_.read()\n changed = blur(imgBytes)\n\n with open(\"changed.png\", \"wb\") as out_:\n out_.write(changed.read())\n","sub_path":"imagemanip.py","file_name":"imagemanip.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"244982532","text":"# coding:utf-8\n\nimport os, sys, random, math\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\nimport optparse\nfrom tqdm import tqdm\nfrom datas.charsets.charset_random import eng_nums, symbols, riyu, cn_words\n\n\nstr_list = [eng_nums, symbols, cn_words]\n\ndef random_text():\n lens = [len(eng_nums), len(symbols), len(cn_words)]\n ratios = [0.1, 0.01, 0.89]\n if random.random() < 0.5:\n n = random.randint(1, 10)\n else:\n n = random.randint(10, 20)\n result = ''\n for i in range(n):\n r_value = random.random()\n sum_value = 0\n tar_id = 0\n for i,r in enumerate(ratios):\n if r_value < r + sum_value:\n tar_id = i\n break\n sum_value += r\n target_s = str_list[tar_id]\n result += target_s[random.randint(0, lens[tar_id] - 1)]\n return result\n\n\ndef run(options):\n with open(options.output_path, 'w', encoding='utf-8') as f:\n for i in tqdm(range(options.gen_number)):\n text = random_text()\n f.write(text + '\\n')\n\ndef get_options(args=None):\n opt_parser = optparse.OptionParser()\n opt_parser.add_option('-n', '--gen_number', type=int, default=100000, help='')\n opt_parser.add_option('-o', '--output_path', type=str, default='/data/caihua/scripts/ocr-recognition-datamaker/datas/corpus_output/rand_chinese.txt', help='')\n\n (options, args) = opt_parser.parse_args(args=args)\n return options\n\nif __name__ == '__main__':\n options = get_options()\n if not options:\n sys.exit(1)\n run(options)","sub_path":"ocr-recognition-datamaker/src/corpus_generate_script/generate_random_sequence.py","file_name":"generate_random_sequence.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"131073114","text":"\"\"\"Extract data, chart by stage of season.\"\"\"\nimport settings\nimport pandas as pd\nimport peewee\nfrom peewee import *\nimport chart_studio.plotly as py\nimport plotly.graph_objects as go\n\ndb = MySQLDatabase(settings.dbname,\n user=settings.dbuser,\n passwd=settings.dbpasswd)\n\n\nclass BaseModel(peewee.Model):\n class Meta:\n database = db\n\n\nclass games(BaseModel):\n matchdate = peewee.DateTimeField()\n hometeam = peewee.CharField()\n awayteam = peewee.CharField()\n homescore = peewee.IntegerField()\n awayscore = peewee.IntegerField()\n league = peewee.CharField()\n stage = peewee.CharField()\n view = peewee.CharField()\n\n\nclass leagues(BaseModel):\n leagues = peewee.CharField()\n sports = peewee.CharField()\n\n\nrq = db.execute_sql(\"\"\"SELECT COUNT(a.hometeam), stage FROM games a\n GROUP BY stage\"\"\")\n\ntoPandas = []\n\nfor row in rq.fetchall():\n toPush = (row[0], row[1])\n toPandas.append(toPush)\n\ntoPandas = tuple(toPandas)\n\n\ndf = pd.DataFrame([[ij for ij in i] for i in toPandas])\ndf.rename(columns={0: 'Games', 1: 'Stage'}, inplace=True)\n\nsports = []\nfor item in df['Stage']:\n sports.append(item)\ngameslist = []\nfor item in df['Games']:\n gameslist.append(item)\n\nfig = {\n 'data': [{'labels': sports,\n 'values': gameslist,\n 'type': 'pie',\n 'name': 'Games by Stage'}],\n 'layout': {'title': \"Games By Stage\"}\n}\n\npy.plot(fig, validate=False, filename='GamesByStage')\n","sub_path":"gamesbystage.py","file_name":"gamesbystage.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"621279359","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport numpy as np\r\nfrom bokeh.resources import INLINE\r\nfrom bokeh.plotting import figure, show, save, ColumnDataSource\r\nfrom bokeh.models import HoverTool, CrosshairTool, WheelZoomTool, ResetTool, RedoTool, BoxZoomTool\r\nfrom bokeh import __base_version__ as bokeh_version\r\nfrom utils.variable import COLORNAMES\r\n\r\nCURDIR = os.getcwd()\r\nDATE_FORMATS = dict(\r\n hours=[\"%a %d %b %y\"],\r\n days=[\"%a %d %b %y\"],\r\n months=[\"%b %y\"],\r\n years=[\"%y\"],\r\n)\r\n\r\n# DatetimeTickFormatter: formats property has been removed in 0.12.6\r\nif bokeh_version >= '0.12.6':\r\n _date_formatter_kwargs = DATE_FORMATS\r\nelse:\r\n _date_formatter_kwargs = dict(\r\n formats=DATE_FORMATS\r\n )\r\n\r\n\r\ndef colorize(labels, random_state=None):\r\n labels_list = np.unique(labels)\r\n n_labels = len(labels_list)\r\n color_list = COLORNAMES[:n_labels]\r\n np.random.seed(random_state)\r\n np.random.shuffle(color_list)\r\n colormap = {label: color for label, color in zip(labels_list, color_list)}\r\n return [colormap[label] for label in labels]\r\n\r\n\r\ndef save_html(obj, title, output_path=None):\r\n if output_path is None:\r\n output_path = os.path.join(CURDIR, title + \".html\")\r\n save(obj, filename=output_path, resources=INLINE, title='Bokeh Plot')\r\n print(\"Visualization saved in %s\" % output_path)\r\n\r\n\r\ndef cluster2d(x, y, height=700, width=700, size=10, alpha=0.7,\r\n colors=None, title=\"t-sne plot\", html_output=False, output_path=None):\r\n\r\n tools = [\r\n # HoverTool(),\r\n # CrosshairTool(),\r\n WheelZoomTool(),\r\n ResetTool(),\r\n RedoTool(),\r\n BoxZoomTool(),\r\n ]\r\n\r\n # source\r\n data = dict(x=x, y=y)\r\n if colors is not None:\r\n data['color'] = colors\r\n source = ColumnDataSource(data=data)\r\n\r\n # figure\r\n n = np.size(x)\r\n p = figure(title=\"%s - %d samples\" % (title, n), tools=tools)\r\n p.plot_height = height\r\n p.plot_width = width\r\n p.ygrid.grid_line_color = None\r\n p.xgrid.grid_line_color = None\r\n\r\n # sample plot\r\n circle_kwargs = dict(size=size, source=source, fill_alpha=alpha)\r\n if colors is not None:\r\n circle_kwargs['color'] = 'color'\r\n p.circle('x', 'y', **circle_kwargs)\r\n\r\n if html_output:\r\n save_html(p, title, output_path=output_path)\r\n show(p)\r\n\r\n","sub_path":"utils/visu.py","file_name":"visu.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"51443946","text":"__all__ = [ \n \"beaconSSID\",\n \"beaconSSID2\",\n \"beaconSsidLen\",\n \"beaconSsidLen2\",\n \"beaconSsidLen2_fixed\",\n \"beaconRatesLen\",\n \"beaconAllIEs\",\n \"beaconCFSet\",\n \"probeSSID\",\n \"probeSsidLen\",\n \"probeRatesLen\",\n \"probeSsidEcho\",\n \"probeWpsLen\",\n \"probeBroadcomCrash\",\n \"probeBroadcomRand\",\n \"probeBroadcomRandLong\",\n \"assocRatesLen_1493\",\n \"assocRatesLen\",\n \"assocRatesLen_pass\",\n \"assocAllIEs\",\n \"wpa_default\",\n \"wpa_key1_flooding\",\n \"wpaKeyDataLen\",\n \"wps_default\",\n \"wps_manual\",\n \"beaconHuSimu\",\n \"dtimCheck\",\n \"wpa_manual\",\n \"probeNoRSN\"\n ]\n\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"470457214","text":"import csv\n\n\ndef get_condition_val_str(metadata_row_list):\n l = list(metadata_row_list.copy())\n del l[0]\n condition_str = \" \".join(l)\n condition_str = condition_str.replace('\"', '')\n condition_str = condition_str.replace(',', ' ')\n return condition_str\n\n\ndef get_condition_val_dict(metadata_file_path):\n condition_val_dict = {}\n with open(metadata_file_path, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in reader:\n condition_val_str = get_condition_val_str(row)\n# if '?' not in condition_val_str and 'none' not in condition_val_str:\n condition_val_dict[row[0].lower()] = condition_val_str # Some labels don't make sense if lowercase, like O2.\n # condition_val_dict[row[0].lower()] = condition_val_str.lower()\n return condition_val_dict\n\n\ndef get_condition_field_val_set(exp_metadata_dict):\n condition_set = set()\n for key_val in exp_metadata_dict.items():\n condition_str = \" \".join(key_val)\n condition_str = condition_str.replace('\"', '')\n condition_str = condition_str.replace(',', ' ')\n condition_set.add(condition_str)\n return condition_set\n\n\nimport os\n\ndef get_all_exp_cond_d(metadata_path):\n all_exp_cond_d = dict()\n \n all_exp_cond_d = {}\n for root, dirs, files in os.walk(metadata_path):\n for name in files:\n relative_file_path_str = str(root)+'/'+name\n d = get_condition_val_dict(relative_file_path_str)\n all_exp_cond_d[d[\"project\"]] = d.copy()\n \n # Removing poor annotation\n no_volume_str = \"(0)\"\n for m_d in all_exp_cond_d.values():\n for key, value in m_d.items():\n if no_volume_str in value:\n # Works because I'm changing reference.\n m_d[key] = value.replace(no_volume_str, \"\")\n \n # Adjusting internals of all_exp_cond_d\n # TODO: would probably be nicer code if I instead said which of these to keep.\n metadata_field_remove_l = [\n \"Flask-number\",\n \"ALE-number\",\n \"Isolate-number\",\n \"technical-replicate-number\",\n \"biological-replicates\",\n \"creator-email\",\n \"data-type\",\n \"technical-replicates\",\n \"serial-number\",\n \"read-files\",\n \"link-to-reference-sequence\",\n \"archive-link\",\n # Global removals that could rather be conditional.\n \"cultivation-details\",\n \"pre-culture-details\",\n \"environment\",\n \"antibody\",\n \"antibiotic\",\n \"isolate-type\",\n \"experiment-details\",\n \"sample-time\",\n \"run-date\",\n \"project\",\n \"creator\",\n \"machine\",\n \"read-length\",\n \"read-type\",\n \"library-prep-kit\",\n \"library-prep-kit-cycles\",\n \"library-prep-kit-manufacturer\",\n 'Link-to-reference-sequence',\n \"genome-reference-file\",\n \"electron-acceptor\"\n ]\n for exp_metadata_d in all_exp_cond_d.values():\n for metadata_field_remove_str in metadata_field_remove_l:\n exp_metadata_d.pop(metadata_field_remove_str.lower(), None)\n exp_metadata_d.pop(metadata_field_remove_str, None)\n\n # improving annotations temperature metadata annotations\n for exp_metadata_d in all_exp_cond_d.values():\n exp_metadata_d[\"temperature\"] += \" celsius\"\n # exp_metadata_d[\"strain\"] = str(exp_metadata_d[\"taxonomy-id\"]+' '+exp_metadata_d[\"strain-description\"])\n # del exp_metadata_d[\"taxonomy-id\"]\n # del exp_metadata_d[\"strain-description\"]\n\n return all_exp_cond_d\n","sub_path":"mutil/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"219781043","text":"import cv2\nimport numpy as np\n\nwindow_name = 'frame'\n\ncv2.namedWindow(window_name)\n \ndef nothing(x):\n pass\n \ncv2.createTrackbar('hue', window_name, 0, 179, nothing)\ncv2.createTrackbar('saturation', window_name, 0, 255, nothing)\ncv2.createTrackbar('value', window_name, 0, 255, nothing)\n\nwhile True:\n\t# get the trackbar values\n\thue = cv2.getTrackbarPos('hue', window_name)\n\tsaturation = cv2.getTrackbarPos('saturation', window_name)\n\tvalue = cv2.getTrackbarPos('value', window_name)\n\n\t# create the hsv_frame\n\thsv_frame = np.zeros((500, 500, 3), np.uint8)\n\thsv_frame[:, :] = (hue, saturation, value)\n\n\t# convert to bgr_frame\n\tbgr_frame = cv2.cvtColor(hsv_frame, cv2.COLOR_HSV2BGR)\n\n\t# show the color\n\tcv2.imshow(window_name, bgr_frame)\n\n\t# quit on escape\n\tk = cv2.waitKey(30) & 0xFF\n\tif k == 27:\n\t\tbreak\n \ncv2.destroyAllWindows()","sub_path":"tools/hsv_color_picker.py","file_name":"hsv_color_picker.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"317867883","text":"from data_preprocess.pic_preprocess import getdata,showpic\r\nfrom SDM.Hog_feature import get_hog_feature,landmark_to_label,label_to_landmark\r\nimport numpy as np\r\nimport pickle\r\nimport matplotlib.pyplot as plt\r\nimport copy\r\nimport pandas as pd\r\nimport datetime\r\nimport logging\r\n\r\nfrom sklearn import decomposition\r\n\r\n\r\nclass DimensionValueError(ValueError):\r\n \"\"\"定义异常类\"\"\"\r\n pass\r\n\r\n\r\nclass PCA(object):\r\n \"\"\"定义PCA类\"\"\"\r\n\r\n def __init__(self, x, n_components=None):\r\n self.x = x\r\n self.dimension = x.shape[1]\r\n\r\n if n_components and n_components >= self.dimension:\r\n raise DimensionValueError(\"n_components error\")\r\n\r\n self.n_components = n_components\r\n\r\n def cov(self):\r\n \"\"\"求x的协方差矩阵\"\"\"\r\n x_T = np.transpose(self.x) #矩阵转置\r\n x_cov = np.cov(x_T) #协方差矩阵\r\n return x_cov\r\n\r\n def get_feature(self):\r\n \"\"\"求协方差矩阵C的特征值和特征向量\"\"\"\r\n x_cov = self.cov()\r\n a, b = np.linalg.eig(x_cov)\r\n m = a.shape[0]\r\n c = np.hstack((a.reshape((m,1)), b))\r\n c_df = pd.DataFrame(c)\r\n c_df_sort = c_df.sort_values(by=0, ascending=False)\r\n return c_df_sort\r\n\r\n def explained_varience_(self):\r\n c_df_sort = self.get_feature()\r\n return c_df_sort.values[:, 0]\r\n\r\n def paint_varience_(self):\r\n explained_variance_ = self.explained_varience_()\r\n plt.figure()\r\n plt.plot(explained_variance_, 'k')\r\n plt.xlabel('n_components', fontsize=16)\r\n plt.ylabel('explained_variance_', fontsize=16)\r\n plt.show()\r\n\r\n def reduce_dimension(self):\r\n \"\"\"指定维度降维和根据方差贡献率自动降维\"\"\"\r\n c_df_sort = self.get_feature()\r\n varience = self.explained_varience_()\r\n\r\n if self.n_components: # 指定降维维度\r\n p = c_df_sort.values[0:self.n_components, 1:]\r\n y = np.dot(p, np.transpose(self.x))\r\n return np.transpose(y),p\r\n\r\n varience_sum = sum(varience)\r\n varience_radio = varience / varience_sum\r\n\r\n varience_contribution = 0\r\n for R in range(self.dimension):\r\n varience_contribution += varience_radio[R]\r\n if varience_contribution >= 0.99:\r\n break\r\n\r\n p = c_df_sort.values[0:R + 1, 1:] # 取前R个特征向量\r\n y = np.dot(p, np.transpose(self.x))\r\n return np.transpose(y),p\r\n\r\nclass GSDM_model():\r\n def __init__(self,leaning_rate,feature_block,blocksize=8):\r\n self.learning_rate = leaning_rate\r\n self.feature_block = feature_block\r\n self.block_size = blocksize\r\n self.f_value={}\r\n self.derection=[]\r\n self.loss = 100\r\n self.avg_phi_star = []\r\n self.pca_base= []\r\n self.name = 'GSDM2_{}_{}'.format(self.learning_rate, self.feature_block)\r\n logging.basicConfig(level=logging.DEBUG,\r\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\r\n datefmt='%a, %d %b %Y %H:%M:%S',\r\n filename='../log/' + self.name + '.log',\r\n filemode='w')\r\n self.logger = logging.getLogger()\r\n # 定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#\r\n console = logging.StreamHandler()\r\n console.setLevel(logging.INFO)\r\n formatter = logging.Formatter('%(message)s') # ('%(name)-12s: %(levelname)-8s )\r\n console.setFormatter(formatter)\r\n # logging.getLogger('').addHandler(console)\r\n self.logger.addHandler(console)\r\n\r\n def get_feature(self,img,state):\r\n '''\r\n 利用图片和当前关键点计算特征,多次使用并且 直接用了类的参数所以 创建一个类方便修改\r\n :param img:\r\n :param state:\r\n :return:\r\n '''\r\n\r\n return get_hog_feature(img, label_to_landmark(state), self.feature_block,self.block_size)# (4-1)*(4-1)*9*4*12 =3888\r\n\r\n\r\n def get_phis(self,imgs,label):\r\n phi_star = [self.get_feature(imgs[idx], label[idx]) for idx in\r\n range(len(imgs))] # (4-1)*(4-1)*9*4*12 =3888\r\n phi_star = np.array(phi_star)\r\n return phi_star\r\n\r\n\r\n def comput_detaX_phi(self,imgs, state, label,phi_star):\r\n deta_X = label - state\r\n phi = self.get_phis(imgs,state)\r\n deta_phi = phi_star-phi\r\n return deta_X,deta_phi\r\n\r\n def devide_subset(self,deta_X,deta_phi):\r\n '''\r\n 利用pca算法求出 deta_X,deta_phi 主要方向 利用主要方向将数据集分成8个子集\r\n :param deta_X:\r\n :param deta_phi:\r\n :return:\r\n '''\r\n pca = PCA(deta_X,2)\r\n pca_deta_X ,pac_base_X = pca.reduce_dimension()\r\n pca = PCA(deta_phi)\r\n pca_deta_phi,pac_base_phi = pca.reduce_dimension()\r\n subset = [[]for i in range(8)]\r\n for idx in range(len(deta_X)):\r\n pca_x = pca_deta_X[idx]\r\n pca_phi = pca_deta_phi[idx]\r\n if pca_x[0]>=0:\r\n if pca_x[1]>=0:\r\n if pca_phi[0]>=0:\r\n subset[0].append(idx)\r\n else:\r\n subset[1].append(idx)\r\n else:\r\n if pca_phi[0]>=0:\r\n subset[2].append(idx)\r\n else:\r\n subset[3].append(idx)\r\n else:\r\n if pca_x[1]>=0:\r\n if pca_phi[0]>=0:\r\n subset[4].append(idx)\r\n else:\r\n subset[5].append(idx)\r\n else:\r\n if pca_phi[0]>=0:\r\n subset[6].append(idx)\r\n else:\r\n subset[7].append(idx)\r\n return subset,(pac_base_X,pac_base_phi)\r\n\r\n\r\n def Descent(self,imgs, state, label,phi_star):\r\n '''\r\n 用最小二乘法求出y=ax+b 中的ab\r\n :param imgs:\r\n :param state:\r\n :param label:\r\n :return:\r\n '''\r\n delta_X = label - state\r\n phi =self.get_phis(imgs,state)\r\n A = phi-phi_star\r\n A = np.mat(A)\r\n X = np.dot(np.dot(np.linalg.pinv(np.dot(A.T, A)), A.T), delta_X)\r\n return X, np.dot(A, X)\r\n def fit(self,imgs,labels,test_imgs = None,test_labels=None):\r\n self.logger.info(\"GSDM learning rate : {} number of picture : {}\".format(self.learning_rate, len(imgs)))\r\n imgs = np.array(imgs)\r\n state = []\r\n for i in range(len(labels)):\r\n state.append(np.array(labels).mean(axis=0))\r\n state = np.array(state)\r\n self.f_value[0] = state\r\n phi_star = self.get_phis(imgs, labels)\r\n\r\n train_loss_list = []\r\n test_loss_list = []\r\n train_loss = self.compute_loss(state, labels)\r\n train_loss_list.append(train_loss)\r\n self.logger.info(\"train_loss : {}\".format(train_loss) )\r\n if test_imgs != None:\r\n test_loss = 0\r\n for idx, img in enumerate(test_imgs):\r\n state = self.predict(img,test_labels[idx])\r\n test_loss += self.compute_loss(state, test_labels[idx])\r\n test_loss = test_loss / len(test_imgs)\r\n test_loss_list.append(test_loss)\r\n self.logger.info(\"test_loss : {}\".format(test_loss) )\r\n\r\n\r\n self.loss = train_loss\r\n iter = 0\r\n\r\n while self.loss>1:\r\n self.logger.info(\"epoch : {}\".format(iter))\r\n starttime = datetime.datetime.now()\r\n deta_X,deta_phi = self.comput_detaX_phi(imgs,self.f_value[iter],labels,phi_star)\r\n subsets,pca_base = self.devide_subset(deta_X,deta_phi)\r\n\r\n self.pca_base.append(pca_base)\r\n self.f_value[iter + 1] = copy.deepcopy(self.f_value[iter])\r\n self.derection.append({})\r\n self.avg_phi_star.append({})\r\n for idx,setindex in enumerate(subsets):\r\n subimgs = imgs[setindex]\r\n substate = self.f_value[iter][setindex]\r\n sublabel = labels[setindex]\r\n subphi = phi_star[setindex]\r\n self.derection[iter][idx],strid = self.Descent(subimgs,substate,sublabel,subphi)\r\n self.avg_phi_star[iter][idx] = subphi.mean(axis=0)\r\n self.f_value[iter + 1][setindex]+=self.learning_rate* strid\r\n # for i,index in enumerate(setindex):\r\n # print(self.f_value[iter+1][index].shape)\r\n # print(strid[i].reshape(24).shape)\r\n # self.f_value[iter+1][index] += self.learning_rate* strid[i].reshape(-1)\r\n train_loss = self.compute_loss(self.f_value[iter+1],labels)\r\n train_loss_list.append(train_loss)\r\n self.loss = train_loss\r\n endtime = datetime.datetime.now()\r\n self.logger.info(\"train_loss : {} costtime : {}\".format(self.loss,(endtime-starttime).seconds))\r\n #print(\"train_loss : \", self.loss)\r\n if test_imgs != None:\r\n starttime = datetime.datetime.now()\r\n test_loss = 0\r\n for idx ,img in enumerate(test_imgs):\r\n state = self.predict(img,test_labels[idx])\r\n test_loss+= self.compute_loss(state,test_labels[idx])\r\n test_loss = test_loss/len(test_imgs)\r\n if test_loss>test_loss_list[-1]:\r\n self.logger.info(\"收敛完成\")\r\n break\r\n test_loss_list.append(test_loss)\r\n endtime = datetime.datetime.now()\r\n self.logger.info(\"test_loss : {} costtime : {}\".format(test_loss, (endtime - starttime).seconds))\r\n # print(\"test_loss : \", test_loss)\r\n\r\n\r\n # states = self.predict_batch(test_imgs)\r\n # test_loss = self.compute_loss(states,test_labels)\r\n # test_loss_list.append(test_loss)\r\n # print(\"batch_test_loss : \", test_loss)\r\n iter+=1\r\n x_axis = range(len(train_loss_list))\r\n plt.plot(x_axis, train_loss_list, label='train_loss') # Plot some data on the (implicit) axes.\r\n if test_imgs != None: plt.plot(x_axis, test_loss_list, label='test_loss') # etc.\r\n plt.xlabel('iter')\r\n plt.ylabel('loss')\r\n figpath = '../resultpic/'+self.name+'_{}_loss.jpg'.format(len(imgs))\r\n if test_imgs != None:figpath = '../resultpic/'+self.name+'_{}_loss_withtest.jpg'.format(len(imgs))\r\n plt.title(figpath.split('/')[-1])\r\n plt.legend()\r\n\r\n plt.savefig(figpath)\r\n plt.close('all')\r\n model_path = '../model/'+self.name+'_{}_.txt'.format(len(imgs))\r\n\r\n self.model_save(model_path)\r\n def predict(self,img, pre_label):\r\n state = [copy.deepcopy(self.f_value[0][0])]\r\n # pre_label=pre_label.reshape(24,1)\r\n phi_star = self.get_feature(img, pre_label)\r\n for i in range(len(self.derection)):\r\n\r\n deta_X = pre_label-state\r\n deta_phi = phi_star - self.get_feature(img, state)\r\n pca_deta_X = np.dot(self.pca_base[i][0], np.transpose(deta_X))\r\n pca_deta_phi = np.dot(self.pca_base[i][1], np.transpose(deta_phi))\r\n if pca_deta_X[0]>=0:\r\n if pca_deta_X[1]>=0:\r\n if pca_deta_phi[0]>=0:\r\n subindex = 0\r\n else:\r\n subindex = 1\r\n else:\r\n if pca_deta_phi[0]>=0:\r\n subindex = 2\r\n else:\r\n subindex = 3\r\n else:\r\n if pca_deta_X[1]>=0:\r\n if pca_deta_phi[0]>=0:\r\n subindex = 4\r\n else:\r\n subindex = 5\r\n else:\r\n if pca_deta_phi[0]>=0:\r\n subindex = 6\r\n else:\r\n subindex = 7\r\n state += self.learning_rate * self.compute_strid(img, state, self.derection[i][subindex],self.avg_phi_star[i][subindex])\r\n return state\r\n def compute_strid(self,img, state, decent_map,phi_star):\r\n '''\r\n 输入单张图片 和 标注 利用计算出来的每一步方向求出每一步的步伐\r\n :param imgs:\r\n :param state:\r\n :param decent_map:\r\n :return:\r\n '''\r\n R = decent_map\r\n phi = self.get_feature(img, state) # (4-1)*(4-1)*9*4*12 =3888\r\n phi = np.array(phi)\r\n A = phi - phi_star\r\n\r\n return np.dot(A, R)\r\n\r\n\r\n def compute_loss(self,state, label):\r\n '''\r\n 计算当前位置和目标位置的误差\r\n :param state:\r\n :param label:\r\n :return:\r\n '''\r\n loss = state - label\r\n return np.square(loss).mean()\r\n\r\n def model_save(self, path):\r\n\r\n with open(path, 'wb') as f:\r\n pickle.dump(self, f)\r\n\r\n @classmethod\r\n def model_load(cls, path):\r\n with open(path, 'rb')as f:\r\n SDM = pickle.load(f)\r\n return SDM\r\n\r\n\r\nif __name__ ==\"__main__\":\r\n SDM_train_path = \"D:\\\\wangqiang\\\\source\\\\SMD_dataset\\\\alltrainset\"\r\n SDM_test_path = \"D:\\\\wangqiang\\\\source\\\\SMD_dataset\\\\alltestset\"\r\n\r\n LEARNING_RATE = 0.1\r\n\r\n train_imgs, train_landmarks = getdata(SDM_train_path, 5400)\r\n train_labels = landmark_to_label(train_landmarks)\r\n train_labels = np.array(train_labels)\r\n test_imgs, test_landmarks = getdata(SDM_test_path, 1000)\r\n test_labels = landmark_to_label(test_landmarks)\r\n test_labels = np.array(test_labels)\r\n test_GSDM = GSDM_model(LEARNING_RATE,5)\r\n test_GSDM.fit(train_imgs, train_labels, test_imgs, test_labels)\r\n # pca = decomposition.PCA()\r\n # pca.fit(test_labels)\r\n #\r\n #\r\n # plt.figure()\r\n # plt.plot(pca.explained_variance_, 'k', linewidth=2)\r\n # plt.xlabel('n_components', fontsize=16)\r\n # plt.ylabel('explained_variance_', fontsize=16)\r\n # plt.show()\r\n #\r\n # pca = PCA(test_labels)\r\n # pca.paint_varience_()\r\n # y = pca.reduce_dimension()\r\n","sub_path":"SDM/GSDM_2.py","file_name":"GSDM_2.py","file_ext":"py","file_size_in_byte":14489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"13267203","text":"#!/usr/bin/env python\nimport re, sys\n\ntry:\n f = open(sys.argv[1], 'r')\n text = f.read()\n #string.split() seperates on empty list if no value is passed in for sep\n #string.join() will join on whatever string is given\n text = ''.join(text.split())\n text = text.strip()\n f.close()\nexcept IOError:\n print(\"Could not open file %s\"%sys.argv[1])\n text = None\n\nlength = 2\nif len(sys.argv) > 2:\n length = int(sys.argv[2])\n\nif text and not re.search(r'[A-Z\\s\\W]', text):\n patterns = []\n str_length = len(text)\n\n for i in range(0, str_length):\n\n pattern = text[i:i+length]\n\n if text.find(pattern, i+length) != -1 and pattern not in patterns:\n patterns.append(pattern)\n\n print(patterns)\n\nelse:\n print(\"invalid input: %s\"%text)\n","sub_path":"pattern_matcher.py","file_name":"pattern_matcher.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399798482","text":"import random\nimport gridgraphdemo as gd\nimport prim_algorithm as pa\nimport math\nimport numpy as np\nimport random as r\nfrom particle_swarm_optimization import Particle, get_fitness, particle_swarm_test, call_methods\n\ndef particle_swarm_optimization(objgbest, p, objpbest):\n #Method for particle Swarm Optimization test\n gbest = math.ceil(1/objgbest)\n pbest = math.ceil(1/objpbest)\n\n s = 150 # Number of Steiner Sets / Particles\n R = r.random() # Relative Quality\n D = 500 * 500 # Dimension of the search space\n\n w = 1 / (3 - np.exp(-s/200) + (R * D / 8)**2)\n\n Vx = w*p.V + 2 * random.randint(0,1) * (pbest - p.Xp) + 2 * random.randint(0, 1) * (gbest - p.Xp)\n\n Vy = w*p.V + 2 * random.randint(0,1) * (pbest - p.Yp) + 2 * random.randint(0, 1) * (gbest - p.Yp)\n\n Vnew = (Vx + Vy)//2\n \n Sxnew = p.Sx + Vx\n Synew = p.Sy + Vy\n len_S = p.Sx.size\n Xpnew = np.sum(Sxnew) // len_S\n Ypnew = np.sum(Synew) // len_S\n\n negatives = 0\n ratio1 = 0.9\n for i in range(len(Sxnew)):\n if Sxnew[i] < 0 or Synew[i] < 0:\n negatives = negatives + 1\n ratio2 = negatives / len(Sxnew)\n # if Xpnew < 0 or Xpnew > 500 or Ypnew < 0 or Ypnew > 500:\n if ratio2 > ratio1:\n p.Sx = p.Sx\n p.Sy = p.Sy\n p.V = p.V\n p.Xp = p.Xp\n p.Yp = p.Yp\n else:\n p.Sx = Sxnew\n p.Sy = Synew\n p.V = Vnew\n p.Xp = Xpnew\n p.Yp = Ypnew\n","sub_path":"weighted_particle_swarm_optimisation.py","file_name":"weighted_particle_swarm_optimisation.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"465859656","text":"import numpy as np\ndef blackBoxNormalization(arrayOfCds):\n retArray = []\n \n #choose the minimum value between the arrays lengths\n normalizedArrayLength = np.min([len(array) for array in arrayOfCds])\n \n \n for array in arrayOfCds:\n if len(array)!=normalizedArrayLength:\n arrayLen = len(array) #get the current array length\n step = arrayLen/normalizedArrayLength #find the step\n\n normalizedArray = []\n normalizedArray.append(array[0])\n idx,aux = 0,0.0\n \n for x in range(normalizedArrayLength-1):\n aux +=step\n a = int(aux)\n idx+=a\n aux -= a\n if idx > arrayLen-1:\n break\n else:\n normalizedArray.append(array[idx])\n \n retArray.append(normalizedArray)\n else:\n retArray.append(array)\n return retArray\n \n \n \n \n \narrayOfCds = [[1, 0, 3, 2, 1, 3, 2, 1, 0, 1], [0,3,2,1,2,3,1,0,3,2,1,3,2,0,1,0]]\nprint(blackBoxNormalization(arrayOfCds))","sub_path":"data_mining_2D/exercises_list/Q1I4.py","file_name":"Q1I4.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"492067242","text":"import os\nfrom glob import glob\n\n\ndef gen_kitti_2015():\n data_dir = 'data/KITTI/kitti_2015/data_scene_flow'\n\n train_file = 'KITTI_2015_train.txt'\n val_file = 'KITTI_2015_val.txt'\n\n # Split the training set with 4:1 raito (160 for training, 40 for validation)\n with open(train_file, 'w') as train_f, open(val_file, 'w') as val_f:\n dir_name = 'image_2'\n left_dir = os.path.join(data_dir, 'training', dir_name)\n left_imgs = sorted(glob(left_dir + '/*_10.png'))\n\n print('Number of images: %d' % len(left_imgs))\n\n for left_img in left_imgs:\n right_img = left_img.replace(dir_name, 'image_3')\n disp_path = left_img.replace(dir_name, 'disp_occ_0')\n\n img_id = int(os.path.basename(left_img).split('_')[0])\n\n if img_id % 5 == 0:\n val_f.write(left_img.replace(data_dir + '/', '') + ' ')\n val_f.write(right_img.replace(data_dir + '/', '') + ' ')\n val_f.write(disp_path.replace(data_dir + '/', '') + '\\n')\n else:\n train_f.write(left_img.replace(data_dir + '/', '') + ' ')\n train_f.write(right_img.replace(data_dir + '/', '') + ' ')\n train_f.write(disp_path.replace(data_dir + '/', '') + '\\n')\n\n\ndef gen_cats_ir():\n\n data_dir = '/home/rtml/Siddhant/CATS_INFERNO/CATS_INFERNO'\n #data_dir = '/home/rtml/Siddhant/CATS_NEW_OUTDOOR'\n \n #data_dir = '/home/rtml/Siddhant/CATS_NEW_GT'\n\n #data_dir = '/home/rtml/Siddhant/CATS_CLIP_GT'\n \n #data_dir = '/home/rtml/Siddhant/CATS_3C_FULL'\n\n #train_file = 'CATS_New_train.txt'\n #val_file = 'CATS_New_val.txt'\n\n #train_file = 'CATS_outdoor_train.txt'\n #val_file = 'CATS_outdoor_val.txt'\n\n #train_file = 'CATS_Clip_train.txt'\n #val_file = 'CATS_Clip_val.txt'\n\n #train_file = 'CATS_All_train.txt'\n #val_file = 'CATS_All_val.txt'\n\n train_file = 'CATS_Inferno_train.txt'\n val_file = 'CATS_Inferno_val.txt'\n\n \n\n # Split data into train and validation\n with open(train_file, 'w') as train_f, open(val_file,'w') as val_f:\n dir_name = 'left'\n #left_dir = os.path.join(data_dir, 'All', dir_name)\n left_dir = os.path.join(data_dir,dir_name)\n left_imgs = (glob(left_dir + '/*.png'))\n\n print('Number of images: %d' % len(left_imgs))\n\n for left_img in left_imgs:\n right_img = left_img.replace(dir_name, 'right')\n disp_path = left_img.replace(dir_name, 'disp')\n\n img_id = int(os.path.basename(left_img).split('.')[0])\n\n #if img_id % 10 == 0:\n if img_id % 8 == 0:\n val_f.write(left_img.replace(data_dir + '/', '') + ' ')\n val_f.write(right_img.replace(data_dir + '/', '') + ' ')\n val_f.write(disp_path.replace(data_dir + '/', '') + '\\n')\n else:\n train_f.write(left_img.replace(data_dir + '/', '') + ' ')\n train_f.write(right_img.replace(data_dir + '/', '') + ' ')\n train_f.write(disp_path.replace(data_dir + '/', '') + '\\n')\n\n\n\nif __name__ == '__main__':\n #gen_kitti_2015()\n gen_cats_ir()\n","sub_path":"aanet/filenames/generate_filenames.py","file_name":"generate_filenames.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"484522246","text":"import zipfile\n\ndef get_next(content):\n number = [int(s) for s in content.split() if s.isdigit()]\n return number[0]\n\n\ndef crawl(zf):\n extension = '.txt'\n next_number = 90052\n comment = \"\"\n while True:\n try:\n name = str(next_number) + extension\n content = zf.read(name)\n comment += zf.getinfo(name).comment.decode('utf-8')\n next_number = get_next(content)\n except IndexError:\n print(\"The next step is:\" + str(content))\n break\n print(\"Comments collected: \"+ comment)\n\n\nif __name__ == \"__main__\":\n zf = zipfile.ZipFile('7.zip', 'r')\n crawl(zf)\n\n# solution is hockey, then oxygen\n","sub_path":"7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"236629316","text":"name = input(\"Enter a Name: \")\nadjective = input(\"Enter a Adjective: \")\nadjective2 = input(\"Enter a Adjective:\")\nadverb = input(\"Enter a adverb: \")\nfood = input(\"Enter a Food: \")\nfood2 = input(\"Enter Another Food: \")\nnoun = input(\"Enter a noun: \")\nplace = input(\"Enter a Place: \")\nverb = input(\"Enter a Verb: \")\nprint(\"Let's play Silly Sentances!\")\nprint( name + \"was planning a dream vacation to \" + place)\nprint( name + \"was especially looking forward to trying the local cuisine, including \" + adjective + food + \" and \" + food2)\nprint( name + \"will have to practice the language \" + adverb + \"to make it easier to \" +verb + \" with people\")\nprint( name + \"has a long list of sights to see, including the \" + noun + \"museum and the \" + adjective2 + \"park.\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"403118189","text":"import numpy as np\nimport h5py, argparse\nfrom pysnptools.snpreader import Bed\n\nparser = argparse.ArgumentParser()\nparser.add_argument('gts', type=str, help='Path to bed file with sibling genotypes')\nparser.add_argument('ped', type=str, help='Path to pedigree file')\nparser.add_argument('ncausal',type=int,help='Number of causal variants')\nparser.add_argument('h2sib',type=float,help='heritability of trait')\nparser.add_argument('nrep',type=int,help='Number of phenotypes to simulate')\nparser.add_argument('outprefix', type=str, help='Location to output csv file with association statistics')\nparser.add_argument('--dncor',type=float,help='Correlation between direct and parental effects',default=0.8)\nargs=parser.parse_args()\n\nprint('reading genotypes')\ngts_f = Bed(args.gts)\n#gts_f = Bed('genotypes/causal_sim/causal_sim.bed')\ngts_ids = gts_f.iid\nid_dict = {}\nfor i in range(0,gts_ids.shape[0]):\n id_dict[gts_ids[i,1]] =i\n\n# Sample causal variants\nsid = gts_f.sid\ncausal_indices = np.sort(np.random.choice(np.array([x for x in range(0,sid.shape[0])]),size=args.ncausal,replace=False))\ncausal_sid = sid[causal_indices]\n\n# Read causal genotypes\ngts = gts_f[:,causal_indices].read().val\ngts = np.array(gts)\ngts_nans = np.isnan(gts)\n\n# Mean impute NAs\nfor j in range(0,gts.shape[1]):\n gts[gts_nans[:,j],j] = np.mean(gts[np.logical_not(gts_nans[:,j]),j])\n\n# Find parents\nped = np.loadtxt(args.ped, dtype='S20', skiprows=1)\n# ped = np.loadtxt('relatedness/families.ped', dtype='S20', skiprows=1)\n\ngenotyped = np.array([x in id_dict for x in ped[:,1]])\nped = ped[genotyped,:]\n\nsibcount = np.zeros((ped.shape[0]),dtype=int)\nsibs_list = []\nfor i in xrange(0,ped.shape[0]):\n sibs_i = np.logical_and(ped[:,0]==ped[i,0],np.logical_and(ped[:,2]==ped[i,2],ped[:,3]==ped[i,3]))\n sibs_i[i] = False\n sibcount[i] = np.sum(sibs_i)\n if sibcount[i]>0:\n sibs_list.append(ped[sibs_i,1])\n\nhas_sibs = sibcount>0\nprint('Removing '+str(np.sum(sibcount==0))+' individuals without genotyped siblings')\nped = ped[has_sibs,:]\n\nG = np.zeros((ped.shape[0],2,gts.shape[1]),dtype=np.float32)\nG[:] = np.nan\nG[:,0,:] = gts[np.array([id_dict[x] for x in ped[:,1]]),:]\ngtcount = 0\nfor i in range(0,G.shape[0]):\n G[i, 1, :] = np.mean(gts[np.array([id_dict[x] for x in sibs_list[i]]), :], axis=0)\n\nprint('simulating trait')\n# Simulate genetic effects\nb = np.random.multivariate_normal(np.zeros((2)),np.array([[1,args.dncor],[args.dncor,1]]),(gts.shape[1],args.nrep))\n# additive genetic component\na = G[:,0,:].dot(b[:,:,0])\na_par = G[:,1,:].dot(b[:,:,1])\n\n# Simulate residual variance\ne = np.random.randn(ped.shape[0],args.nrep)\n\n### Form phenotype\n## standardise\n# genetic effects\nA = a+a_par\na_factor = np.sqrt(args.h2sib)*np.power(np.std(A,axis=0),-1)\n\n# make phenotype\ny = A*a_factor+np.sqrt(1-args.h2sib)*e\n\n# Write phenotype\nyout = np.hstack((ped[:,0:2],np.array(y,dtype=str)))\nnp.savetxt(args.outprefix+'.ped',yout,fmt='%s')\n\n# Write effects\nb_out = np.hstack((causal_sid.reshape((causal_sid.shape[0],1)),np.array(b[:,:,0]*a_factor,dtype=str),np.array(b[:,:,1]*a_factor,dtype=str)))\nnp.savetxt(args.outprefix+'.effects.txt',b_out,fmt='%s')","sub_path":"example/simulate_trait_sib.py","file_name":"simulate_trait_sib.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"35610054","text":"import inspect\nimport sys\n\nimport jax\nimport jax.lax as jla\nimport jax.numpy as jnp\nimport numpy\n\nfrom . import ops_numpy as T\nfrom .base import jax_wrap\nfrom ..nn.ops_nn import relu\n\nmodule = sys.modules[__name__]\n\nindex = jax.ops.index\n\n\ndef hat_1D(x, t_left, t_center, t_right):\n \"\"\"hat basis function in 1-D\n\n Hat function, continuous piecewise linear\n\n Parameters\n ----------\n\n x: array-like\n the sampled input space\n\n t_left: scalar\n the position of the left knot\n\n t_center: scalar\n the position of the center knot\n\n t_right: scalar\n the position of the right knot\n\n Returns\n -------\n\n output : array\n same shape as x with applied hat function\n \"\"\"\n eps = 1e-6\n slope_left = 1 / (t_center - t_left)\n slope_right = 1 / (t_right - t_center)\n output = (\n (relu(x - t_left)) * slope_left\n - relu(x - t_center) * (slope_left + slope_right)\n + relu(x - t_right) * slope_right\n )\n return output\n\n\ndef _extract_signal_patches(signal, window_length, hop=1, data_format=\"NCW\"):\n if hasattr(window_length, \"shape\"):\n assert window_length.shape == ()\n else:\n assert not hasattr(window_length, \"__len__\")\n\n if data_format == \"NCW\":\n if signal.ndim == 2:\n signal_3d = signal[:, None, :]\n elif signal.ndim == 1:\n signal_3d = signal[None, None, :]\n else:\n signal_3d = signal\n\n N = (signal_3d.shape[2] - window_length) // hop + 1\n indices = jnp.arange(window_length) + jnp.expand_dims(jnp.arange(N) * hop, 1)\n indices = jnp.reshape(indices, [1, 1, N * window_length])\n patches = jnp.take_along_axis(signal_3d, indices, 2)\n output = jnp.reshape(patches, signal_3d.shape[:2] + (N, window_length))\n if signal.ndim == 1:\n return output[0, 0]\n elif signal.ndim == 2:\n return output[:, 0, :]\n else:\n return output\n else:\n error\n\n\nextract_signal_patches = jax_wrap(_extract_signal_patches, module)\n\n\ndef _extract_image_patches(\n image, window_shape, hop=1, data_format=\"NCHW\", mode=\"valid\"\n):\n if mode == \"same\":\n p1 = window_shape[0] - 1\n p2 = window_shape[1] - 1\n image = jnp.pad(\n image, [(0, 0), (0, 0), (p1 // 2, p1 - p1 // 2), (p2 // 2, p2 - p2 // 2)],\n )\n if not hasattr(hop, \"__len__\"):\n hop = (hop, hop)\n if data_format == \"NCHW\":\n\n # compute the number of windows in both dimensions\n N = (\n (image.shape[2] - window_shape[0]) // hop[0] + 1,\n (image.shape[3] - window_shape[1]) // hop[1] + 1,\n )\n\n # compute the base indices of a 2d patch\n patch = jnp.arange(numpy.prod(window_shape)).reshape(window_shape)\n offset = jnp.expand_dims(jnp.arange(window_shape[0]), 1)\n patch_indices = patch + offset * (image.shape[3] - window_shape[1])\n\n # create all the shifted versions of it\n ver_shifts = jnp.reshape(\n jnp.arange(N[0]) * hop[0] * image.shape[3], (-1, 1, 1, 1)\n )\n hor_shifts = jnp.reshape(jnp.arange(N[1]) * hop[1], (-1, 1, 1))\n all_cols = patch_indices + jnp.reshape(jnp.arange(N[1]) * hop[1], (-1, 1, 1))\n indices = patch_indices + ver_shifts + hor_shifts\n\n # now extract shape (1, 1, H'W'a'b')\n flat_indices = jnp.reshape(indices, [1, 1, -1])\n # shape is now (N, C, W*H)\n flat_image = jnp.reshape(image, (image.shape[0], image.shape[1], -1))\n # shape is now (N, C)\n patches = jnp.take_along_axis(flat_image, flat_indices, 2)\n return jnp.reshape(patches, image.shape[:2] + N + tuple(window_shape))\n else:\n error\n\n\nextract_image_patches = jax_wrap(_extract_image_patches)\n\n\ndef _add_n(args):\n start = args[0]\n for arg in args:\n start = jnp.add(start, arg)\n return start\n\n\nadd_n = jax_wrap(_add_n)\n\n\ndef one_hot(i, N, dtype=\"float32\"):\n \"\"\"Create a one-hot encoding of x of size k.\"\"\"\n if hasattr(i, \"shape\"):\n return (x[:, None] == arange(k)).astype(dtype)\n else:\n z = T.zeros(N, dtype)\n return index_add(z, i, 1)\n\n\nfor name in [\"index_update\", \"index_min\", \"index_add\", \"index_max\"]:\n module.__dict__.update({name: jax_wrap(jax.ops.__dict__[name])})\n\nstop_gradient = jax_wrap(jla.stop_gradient)\ndynamic_slice_in_dim = jax_wrap(jla.dynamic_slice_in_dim)\ndynamic_slice = jax_wrap(jla.dynamic_slice)\nindex = jax.ops.index\n\n\nmodule = sys.modules[__name__]\n\n_NAMES = [c[0] for c in inspect.getmembers(jax.scipy.special, inspect.isfunction)]\n\n\nfor name in _NAMES:\n if name[0] == \"_\":\n continue\n module.__dict__.update({name: jax_wrap(jax.scipy.special.__dict__[name])})\n","sub_path":"symjax/tensor/ops_special.py","file_name":"ops_special.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"298087537","text":"import pandas as pd\nimport numpy as np\nimport datetime\nfrom watchtower.handlers_ import UserDatabase\n\ndb = UserDatabase(auth='GITHUB_API')\n\n# Times for inclusion\nend = pd.datetime.now()\ninclude_last_n_days = 3\ndelta = datetime.timedelta(days=include_last_n_days + 1)\nstart = end - delta\nprint('Calculating user activity from {} to {}'.format(start, end))\n\nstart, end = (pd.to_datetime(ii) for ii in [start, end])\nexceptions = []\nactivity = []\nfor user in db.users:\n try:\n user_db = db.load_user(user)\n messages, dates = zip(*[(jj['message'], idate)\n for idate, ii in user_db.PushEvent.iterrows()\n for jj in ii['payload']['commits']])\n dates = np.array(dates)\n messages = np.array(messages)\n mask = (dates > start) * (dates <= end)\n messages = messages[mask]\n dates = dates[mask]\n for message, date in zip(messages, dates):\n search_queries = ['DOC', 'docs', 'docstring',\n 'documentation', 'docathon']\n is_doc = 0\n for query in search_queries:\n if message.find(query) != -1:\n is_doc += 1\n is_doc = is_doc > 0\n activity.append((user, date, is_doc))\n\n except Exception as e:\n exceptions.append(e)\n activity.append((user, np.nan, np.nan))\n continue\nactivity = pd.DataFrame(activity, columns=['user', 'date', 'is_doc'])\nactivity = activity.set_index('date')\nactivity.to_csv('.user_totals.csv')","sub_path":"src/watchtower/calculate_user_commits.py","file_name":"calculate_user_commits.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"288697539","text":"import zipfile, urllib.request, shutil, os\n\ncourse_id = input('Course ID: ').upper()\nurl = 'https://www.webucator.com/ClassFiles/getClassFiles.cfm?Type=SP&CourseID=' + course_id\nfile_name = 'classfiles.zip'\n\nwith urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n\nwith zipfile.ZipFile(file_name) as zf:\n zf.extractall()\n","sub_path":"pyt211.py","file_name":"pyt211.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"327616768","text":"import serial\nimport json\nimport time\nimport pandas as pd\n\ndf = pd.DataFrame(columns=[\"time\", \"weight\"])\n\n# get data from arduino port\ntry:\n arduino = serial.Serial('COM3', 9600, timeout=5)\n print(\"Connected to arduino\")\nexcept:\n print(\"Check the port\")\n\nprev_measure = -99999\nprev_data = -99999\ncurr_data = -99999\n\n\ndef write_data():\n global df, prev_measure, prev_data, curr_data, arduino\n while True:\n curr_time = round(time.time(), 0);\n curr_measure = float(str(arduino.readline())[2:-5])\n\n # save all raw data to a csv file\n df = df.append({\"time\": curr_time, \"weight\": curr_measure},\n ignore_index=True)\n df.to_csv(\"raw.csv\")\n\n print(\"-------------------------------------------\")\n print(\"Previous measure: \" + str(prev_measure))\n print(\"Current measure: \" + str(curr_measure))\n print(\"Previous data: \" + str(prev_data))\n print(\"Current data: \" + str(curr_data))\n\n # init prev, curr, last\n if (prev_measure == -99999):\n prev_measure = curr_measure\n else:\n # look for the steady state\n if ((abs(prev_measure - curr_measure) <= 1)):\n\n # update current steady data\n if (curr_measure > 5):\n curr_data = curr_measure\n\n # check if the weight of water cup has decreased\n if (prev_data - curr_data > 5):\n print()\n print(\"Data found: \")\n\n # open a json file\n with open(\"data.json\") as f:\n data = json.load(f)\n\n # append data\n data[\"data\"].append(\n {\"time\": curr_time, \"weight\": curr_data, \"prev_weight\": prev_data, \"volume\": round(prev_data - curr_data, 0)})\n a = {\"time\": curr_time, \"weight\": curr_data,\n \"prev_weight\": prev_data, \"volume\": round(prev_data - curr_data, 0)}\n print(a)\n\n # write data to the json file\n with open('data.json', 'w') as f:\n json.dump(data, f)\n\n # iterate\n prev_data = curr_data\n\n # iterate\n prev_measure = curr_measure\n print()\n print(\"After: \")\n print(\"Previous measure: \" + str(prev_measure))\n print(\"Current measure: \" + str(curr_measure))\n print(\"Previous data: \" + str(prev_data))\n print(\"Current data: \" + str(curr_data))\n\n\nwrite_data()\n","sub_path":"listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"563036534","text":"class Solution:\n def compress(self, s):\n \"\"\"\n :type chars: List[str]\n :rtype: int\n \"\"\"\n if not s: return 0\n i = p = 0\n count, n = 1, len(s)\n for j in range(1, n+1):\n if j < n and s[i] == s[j]:\n count += 1\n else:\n s[p] = s[i]\n if count == 1:\n p += 1\n else:\n cs = str(count)\n for k in range(len(cs)):\n s[p+1+k] = cs[k]\n count = 1\n p += 1 + len(cs)\n i = j\n return p\nif __name__ == '__main__':\n from minitest import *\n\n with test(Solution):\n s = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\n Solution().compress(s).must_equal(6)\n s.must_equal(['a', '2', 'b', '2', 'c', '3', 'c'])\n\n s = [\"a\"]\n Solution().compress(s).must_equal(1)\n s.must_equal(['a'])\n\n s = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\n Solution().compress(s).must_equal(4)\n s.must_equal([\"a\",\"b\",\"1\",\"2\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"])\n","sub_path":"python/leetcode/array/443_String_Compression.py","file_name":"443_String_Compression.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"327082024","text":"import re\nfrom datetime import datetime as dt\nfrom django.db.models import Q\nfrom rest_framework import serializers\nfrom runner.operator.operator import Operator\nfrom django.conf import settings\nimport runner.operator.tempo_mpgen_operator.bin.tempo_sample as tempo_sample\n\n\nclass Patient:\n def __init__(self, patient_id, file_list, pairing={}):\n self.tumor_samples = dict()\n self.normal_samples = dict()\n self.conflict_samples = dict()\n self.sample_pairing = list()\n self.unpaired_samples = list()\n self.pre_pairing = pairing\n self.all_samples = self._get_samples(file_list)\n self._characterize_samples()\n self._pair_samples()\n\n def _get_samples(self, file_list):\n data = dict()\n for f in file_list:\n metadata = f.metadata\n sample_name = metadata[settings.CMO_SAMPLE_TAG_METADATA_KEY]\n if sample_name not in data:\n data[sample_name] = list()\n data[sample_name].append(f)\n\n samples = dict()\n for sample_name in data:\n sample = data[sample_name]\n samples[sample_name] = tempo_sample.TempoSample(sample_name, sample)\n return samples\n\n def _characterize_samples(self):\n for sample_name in self.all_samples:\n sample = self.all_samples[sample_name]\n sample_class = sample.sample_class\n if not sample_class:\n self.conflict_samples[sample_name] = sample\n elif isinstance(sample_class, list):\n self.conflict_samples[sample_name] = sample\n elif not sample_name: # sample name empty\n self.conflict_samples[sample_name] = sample\n elif \"sampleNameMalformed\" in sample.metadata[settings.CMO_SAMPLE_TAG_METADATA_KEY]: # ci tag is no good\n self.conflict_samples[sample_name] = sample\n else:\n if \"normal\" in sample_class.lower():\n self.normal_samples[sample_name] = sample\n else:\n self.tumor_samples[sample_name] = sample\n\n def _pair_samples(self):\n for tumor_sample_name in self.tumor_samples:\n tumor_sample = self.tumor_samples[tumor_sample_name]\n tumor_cmo_sample_name = tumor_sample.metadata[settings.CMO_SAMPLE_TAG_METADATA_KEY][\n 0\n ] # they should all be the same\n tumor_baits = tumor_sample.bait_set\n tumor_run_mode = tumor_sample.run_mode\n expected_normal_cmo_sample_name = \"\"\n if tumor_cmo_sample_name in self.pre_pairing:\n expected_normal_cmo_sample_name = self.pre_pairing[tumor_cmo_sample_name]\n normal = self._get_normal(tumor_baits, tumor_run_mode, expected_normal_cmo_sample_name)\n if normal:\n self.sample_pairing.append([tumor_sample, normal])\n else:\n self.unpaired_samples.append(tumor_sample)\n\n def _get_normal(self, bait_set, run_mode, expected_normal_cmo_sample_name=\"\"):\n normal = None\n for normal_sample_name in self.normal_samples:\n normal_sample = self.normal_samples[normal_sample_name]\n normal_baits = normal_sample.bait_set\n normal_run_mode = normal_sample.run_mode\n if expected_normal_cmo_sample_name: # if this is True, we're using historical pairing info\n normal_cmo_sample_name = normal_sample.metadata[settings.CMO_SAMPLE_TAG_METADATA_KEY][\n 0\n ] # they should all be the same for this sample\n if normal_cmo_sample_name == expected_normal_cmo_sample_name:\n normal = normal_sample\n return normal\n # make sure hiseq pairs with hiseq, novaseq with novaseq\n elif normal_baits.lower() == bait_set.lower() and normal_run_mode.lower() == run_mode.lower():\n if not normal:\n normal = normal_sample\n else:\n normal = self._return_more_recent_normal(normal_sample, normal)\n return normal\n\n def _return_more_recent_normal(self, n1, n2):\n n1_run_date = self._most_recent_date(n1.metadata[\"runDate\"])\n n2_run_date = self._most_recent_date(n2.metadata[\"runDate\"])\n recent_normal = n1\n if n2_run_date > n1_run_date:\n recent_normal = n2\n return recent_normal\n\n def _most_recent_date(self, dates):\n date = None\n for d in dates:\n current_date = None\n try:\n current_date = dt.strptime(d, \"%y-%m-%d\")\n except ValueError:\n current_date = dt.strptime(d, \"%Y-%m-%d\")\n if current_date:\n if not date:\n date = current_date\n else:\n if current_date > date:\n date = current_date\n return date\n\n def get_sample(self, sample_name):\n try:\n return self.all_samples[sample_name]\n except:\n return None\n\n def create_mapping_string(self):\n s = \"\"\n seen = set()\n for pair in self.sample_pairing:\n tumor_sample = pair[0]\n normal_sample = pair[1]\n s += self.get_mapping_string(tumor_sample)\n if normal_sample not in seen:\n s += self.get_mapping_string(normal_sample)\n seen.add(normal_sample)\n return s\n\n def get_mapping_string(self, sample):\n s = \"\"\n target = sample.bait_set\n fastqs = sample.fastqs\n cmo_sample_name = sample.cmo_sample_name\n if fastqs.paired:\n num_fq_pairs = len(fastqs.r1)\n for i in range(0, num_fq_pairs):\n r1 = fastqs.r1[i].path\n r2 = fastqs.r2[i].path\n s += \"%s\\t%s\\t%s\\t%s\\t%i\\n\" % (cmo_sample_name, target, r1, r2, num_fq_pairs)\n return s\n\n def create_pairing_string(self):\n pairing = \"\"\n if self.sample_pairing:\n for pair in self.sample_pairing:\n tumor = pair[0].cmo_sample_name\n normal = pair[1].cmo_sample_name\n pairing += \"%s\\t%s\\n\" % (normal, tumor)\n return pairing\n\n def create_unpaired_string(self, fields):\n s = \"\"\n for sample in self.unpaired_samples:\n data = [\n \";\".join(list(set(sample.metadata[field]))).strip() for field in fields\n ] # hack; probably need better way to map fields to unpaired txt file\n possible_reason = self._get_possible_reason(sample)\n s += \"\\n\" + \"\\t\".join(data) + \"\\t\" + possible_reason\n return s\n\n def _get_possible_reason(self, sample):\n num_normals = len(self.normal_samples)\n if num_normals == 0:\n return \"No normals for patient\"\n matching_baits = False\n matching_run_modes = False\n for sample_name in self.normal_samples:\n normal = self.normal_samples[sample_name]\n if normal.bait_set.lower() == sample.bait_set.lower():\n matching_baits = True\n if normal.run_mode.lower() == sample.run_mode.lower():\n matching_run_modes = True\n if not matching_baits:\n return \"No normal sample has same bait set as tumor in patient\"\n if not matching_run_modes:\n return \"No normal sample has same bait set and run mode (HiSeq/NovaSeq) as tumor in patient\"\n first_half_of_2017 = False\n run_dates = sample.metadata[\"runDate\"]\n if run_dates and isinstance(run_dates, str):\n run_dates = run_dates.split(\";\")\n for run_date in run_dates:\n if run_date:\n try:\n current_date = dt.strptime(d, \"%y-%m-%d\")\n except ValueError:\n current_date = dt.strptime(d, \"%Y-%m-%d\")\n if current_date < dt(2017, 6, 1):\n first_half_of_2017 = True\n if first_half_of_2017:\n return \"Sample run date first half of 2017; normal may have been sequenced in 2016?\"\n return \"\"\n\n def create_conflict_string(self, fields):\n s = \"\"\n for sample_name in self.conflict_samples:\n sample = self.conflict_samples[sample_name]\n data = [\n \";\".join(list(set(sample.metadata[field]))).strip() for field in fields\n ] # hack; probably need better way to map fields to unpaired txt file\n conflicts = []\n if \"sampleNameMalformed\" in sample.metadata[settings.CMO_SAMPLE_TAG_METADATA_KEY]:\n conflicts.append(\"incorrect CMO Sample Name\")\n if not \"\".join(sample.metadata[settings.SAMPLE_CLASS_METADATA_KEY]):\n conflicts.append(\"no sample class\")\n multiple_values = [\n \"\" + field + \"[\" + \";\".join(list(set(sample.metadata[field]))).strip() + \"]\"\n for field in sample.conflict_fields\n ]\n conflicts = conflicts + multiple_values\n s += \"\\n\" + \"\\t\".join(data) + \"\\t\" + \";\".join(conflicts)\n return s\n","sub_path":"runner/operator/tempo_mpgen_operator/bin/tempo_patient.py","file_name":"tempo_patient.py","file_ext":"py","file_size_in_byte":9234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"399538463","text":"import os\nos.chdir('/jukebox/witten/Alex/PYTHON/rewardworld/ephys/analysis')\nfrom brainbox.singlecell import calculate_peths\nfrom sklearn.linear_model import Lasso as LR\nfrom scipy.stats import pearsonr\nfrom scipy.stats import zscore\n#import multiprocess as mp\nimport sys\nfrom ephys_alf_summary import alf\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nfrom decoding_debugging import *\n\n##########################\n####### Parameters #######\n##########################\nSESSIONS = ['/jukebox/witten/Alex/Data/Subjects/dop_48/2022-06-20/001', \n'/jukebox/witten/Alex/Data/Subjects/dop_48/2022-06-19/002', \n'/jukebox/witten/Alex/Data/Subjects/dop_48/2022-06-28/001', \n'/jukebox/witten/Alex/Data/Subjects/dop_48/2022-06-27/002', \n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-14/001', \n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-15/001', \n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-16/001', \n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-17/001',\n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-18/002', \n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-19/001', \n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-27/003', \n'/jukebox/witten/Alex/Data/Subjects/dop_49/2022-06-20/001', \n'/jukebox/witten/Alex/Data/Subjects/dop_47/2022-06-11/001',\n'/jukebox/witten/Alex/Data/Subjects/dop_47/2022-06-10/002', \n'/jukebox/witten/Alex/Data/Subjects/dop_47/2022-06-09/003',\n'/jukebox/witten/Alex/Data/Subjects/dop_47/2022-06-05/001']\nfor ses in SESSIONS:\n print(ses)\n n_neurons_minimum = 10\n alignment_time = 'response_times'\n pre_time = 0.5\n post_time = 4\n smoothing=0\n bin_size=0.1\n output_folder = '/jukebox/witten/Alex/decoder_output'\n temp_folder = '/jukebox/witten/Alex/decoder_wd'\n\n ##########################\n ####### Load Data ########\n ##########################\n\n alfio = alf(ses, ephys=True)\n alfio.mouse = Path(ses).parent.parent.name\n alfio.date = Path(ses).parent.name\n alfio.ses = Path(ses).name\n alfio.path = ses\n\n # Load variable to be decoded and aligment times\n regressed_variable = np.copy(alfio.QRreward) #For now qchosen\n regressed_variable[np.where(alfio.choice==-1)] = alfio.QLreward[np.where(alfio.choice==-1)] #For now qchosen\n alignment_times_all = getattr(alfio, alignment_time)\n #weights = get_session_sample_weights(alfio.to_df(), categories = ['choice','probabilityLeft', 'outcome'])\n weights=None\n # Get areas in recording\n areas = []\n for p in np.arange(4): # Max 4 probes\n try:\n areas.append(alfio.probe[p].cluster_group_locations.unique()[~pd.isna(alfio.probe[p].cluster_group_locations.unique())])\n except:\n continue\n areas = np.unique(np.concatenate(areas))\n # Load and run null distributions\n null_sesssions = []\n null_weights = []\n for i in np.arange(200):\n n_temp = pd.read_csv('/jukebox/witten/Alex/null_sessions/laser_only/'+str(i)+'.csv')\n n_temp = n_temp.iloc[:, np.where(n_temp.columns=='choice')[0][0]:]\n qchosen = n_temp['QRreward'].to_numpy()\n qchosen[np.where(n_temp.choice==-1)] = n_temp.QLreward.to_numpy()[np.where(n_temp.choice==-1)]\n null_sesssions.append(qchosen)\n null_weights.append(get_session_sample_weights(n_temp, categories = ['choice','probabilityLeft', 'outcome']))\n\n ##########################\n ## Run decoder (linear) ##\n ##########################\n\n for area in areas:\n run_decoder_for_session(area, alfio, regressed_variable, weights, alignment_times_all, etype = 'real')","sub_path":"ephys/analysis/decoding_value_laser_task_local.py","file_name":"decoding_value_laser_task_local.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"644524463","text":"from flask import Flask, render_template,request,g,flash,redirect,url_for,jsonify,json,session\nfrom datetime import datetime,timedelta\nimport sqlite3\n\n\n#initialising app\napp = Flask(__name__)\napp.secret_key = 'some_secret'\n\n\n@app.route('/')\ndef index():\n\tli = g.db.execute(\"SELECT city,e_name,b_date from Bookings,Rooms where Bookings.r_id = Rooms.r_id and b_date>=date('now') order by b_date asc;\").fetchall();\n\treturn render_template('index.html',data=li)\n\n#connecting to DB before every request\n@app.before_request\ndef before_request():\n g.db = sqlite3.connect('usersDB.db')\n\n#closing connection after every request\n@app.teardown_request\ndef teardown_request(exception):\n if hasattr(g, 'db'):\n g.db.close()\n\n\n@app.route('/signup', methods=['GET', 'POST'])\ndef test():\n\tif(request.method=='POST'):\n\t\tuid = request.form['sp_uid']\n\t\tpassw = request.form['sp_pass']\n\t\tname = request.form['uname']\n\t\temail = request.form['email']\n\t\tphone = request.form['cell']\n\t\tcity = request.form['city']\n\n\t\tif(len(uid)==0 or len(passw)==0 or len(name)==0 or len(email)==0 or len(phone)==0 or city=='City'):\n\t\t\treturn jsonify(result = 'Please fill up all the fields')\n\t\telse:\n\t\t\tli = g.db.execute(\"SELECT * from Users WHERE uid = ?;\",[uid]).fetchall();\n\n\t\t\tif(len(li)>0):\n\t\t\t\treturn jsonify(result='User-id already exists! Please choose a different User-id.')\n\t\t\telse:\n\t\t\t\tg.db.execute(\"INSERT INTO Users VALUES (?,?,?,?,?,?);\", (uid,passw,name,email,phone,city))\n\t\t\t\tg.db.commit()\n\t\t\t\treturn jsonify(result='Signup successful! Now login with your new User-id.')\n\t\t\t\t\n\t\t\t\n#clicking on Login\n@app.route('/login',methods=['GET', 'POST'])\ndef login():\n\tif(request.method=='POST'):\n\t\tuid = request.form['uid']\n\t\tpassw = request.form['pass']\n\n\t\tli = g.db.execute(\"SELECT pass from Users WHERE uid = ?;\",[uid]).fetchall();\n\t\tnm = g.db.execute(\"SELECT uname from Users WHERE uid = ?;\",[uid]).fetchall();\n\n\t\tif(len(li)==0):\n\t\t\tflash(\"Invalid User-id\")\n\t\t\treturn redirect(url_for('index'))\n\t\t\t\n\t\telse:\n\t\t\tif(str(passw)==str(li[0][0])):\n\t\t\t\tsession['uname'] = str(nm[0][0])\n\t\t\t\treturn render_template('choice.html',data = str(nm[0][0]))\n\t\t\telse:\n\t\t\t\tflash(\"Incorrect password\")\n\t\t\t\treturn redirect(url_for('index'))\n\t\t\t\n@app.route('/choice')\ndef manageHall():\n\tif(session.get('uname',None)):\n\t\treturn render_template('choice.html',data = session.get('uname',None))\n\telse:\n\t\treturn render_template('choice.html')\n\n\n@app.route('/calendar',methods=[\"POST\"])\ndef calendar():\n\tif(request.method==\"POST\"):\n\t\tuid = session.get('uid',None)\n\t\trid = request.form['click_rid']\n\t\tr_name = request.form['rname']\n\t\tsession['rname'] = r_name\n\t\tsession['rid'] = rid\n\t\tli = g.db.execute('SELECT e_name,b_date,days from Bookings where r_id = ?',[rid])\n\t\tdays=[]\n\t\tfor day in li:\n\t\t\tdt = datetime.strptime(day[1],'%Y-%m-%d')\n\t\t\tndays = day[2]\n\t\t\tdt_next = dt + timedelta(days = ndays)\n\t\t\tdays.append([day[0],dt,dt_next])\n\n\t\tsession['days'] = days\n\t\t# days = ['TEST','2017-09-25','2017-09-27']\n\t\treturn render_template('calendar.html',data=days,hallname=r_name)\n\n\n@app.route('/searchHalls',methods=['POST'])\ndef searchHalls():\n\tif(request.method=='POST'):\n\t\tcity = request.form['hallcity']\n\t\tno_of_seats = request.form['seats']\n\t\tsession['uid'] = request.form['uid']\n\t\tac = request.form['ac']\n\t\tsb = request.form['sb']\n\t\tpr = request.form['pr']\n\t\ta=1\n\t\ts=1\n\t\tp=1\n\t\tli=[]\n\n\t\tif(no_of_seats==''):\n\t\t\tno_of_seats=0\n\t\telse:\n\t\t\ttry:\n\t\t\t\tno_of_seats=int(no_of_seats)\n\t\t\texcept exception as e:\n\t\t\t\tflash(\"Invalid no. of seats\")\n\t\tif(ac==\"\"):\n\t\t\ta=0\n\t\tif(sb==\"\"):\n\t\t\ts=0\n\t\tif(pr==\"\"):\n\t\t\tp=0\n\t\t\n\t\tif(city=='City'):\n\t\t\tli = g.db.execute(\"SELECT r_id,r_name,loc,seats,city from Rooms WHERE seats >= ? and ac = ? and sb = ? and prj = ?;\",(no_of_seats,a,s,p)).fetchall()\n\t\telse:\n\t\t\tli = g.db.execute(\"SELECT r_id,r_name,loc,seats,city from Rooms WHERE city = ? and seats >= ? and ac = ? and sb = ? and prj = ?;\",(city,no_of_seats,a,s,p)).fetchall()\n\t\t\n\t\treturn jsonify(list=li)\n\n\n@app.route('/bookHall',methods=['POST'])\ndef bookHall():\n\tif(request.method=='POST'):\n\t\td = datetime.today()\n\n\t\tnofdays = (int)(request.form['nofdays'])\n\t\te_name = request.form['eventName']\n\t\tdate = request.form['book-date']\t#2017-09-24\n\t\tbk_day = (int)(date[8:])\n\t\tbk_mon = (int)(date[5:7])\n\t\tbk_year = (int)(date[:4])\n\n\t\treq_date = datetime.strptime(date, '%Y-%m-%d')\n\n\t\tuid = session.get('uid',None)\n\t\trid = session.get('rid',None)\n\t\tr_name =session.get('rname',None)\n\t\tdays = session.get('days',None)\n\n\t\tif((d.year,d.month,d.day)<=(bk_year,bk_mon,bk_day)):\n\t\t\tif(nofdays<=0):\n\t\t\t\tflash('Number of days cannot be negative or 0')\n\t\t\t\treturn render_template('calendar.html',data=days,hallname=r_name)\n\t\t\telif(nofdays>15):\n\t\t\t\tflash('Number of days limit exceeded! Maximum allowed is 15 days')\n\t\t\t\treturn render_template('calendar.html',data=days,hallname=r_name)\n\t\t\telse:\n\t\t\t\tli = g.db.execute('SELECT b_date,days from Bookings where r_id = ?;',[rid]).fetchall()\n\t\t\t\tif(len(li)==0):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tg.db.execute('INSERT into Bookings VALUES (?,?,?,?,?)',(rid,uid,e_name,date,nofdays))\n\t\t\t\t\t\tg.db.commit()\n\t\t\t\t\t\tflash('Booking successful!')\n\t\t\t\t\t\tdt = datetime.strptime(date,'%Y-%m-%d')\n\t\t\t\t\t\tndays = nofdays\n\t\t\t\t\t\tdt_next = dt + timedelta(days = ndays)\n\t\t\t\t\t\tdays.append([e_name,dt,dt_next])\n\t\t\t\t\t\tsession['days'] = days\n\n\t\t\t\t\texcept sqlite3.Error as e:\n\t\t\t\t\t\tflash('Something went wrong..{0}'.format(e))\n\t\t\t\t\t\treturn render_template('calendar.html',data=days,hallname=r_name)\n\t\t\t\telse:\n\t\t\t\t\tflag=0\n\t\t\t\t\tfor x in li:\n\t\t\t\t\t\tdt = x[0]\n\t\t\t\t\t\tdt = datetime.strptime(dt,'%Y-%m-%d')\n\t\t\t\t\t\tndays = x[1]\n\t\t\t\t\t\tdt_next = dt + timedelta(days = ndays-1)\n\t\t\t\t\t\td1 = (dt.year,dt.month,dt.day)\n\t\t\t\t\t\t\n\t\t\t\t\t\td3 = (dt_next.year,dt_next.month,dt_next.day)\n\t\t\t\t\t\tprint(x)\n\t\t\t\t\t\tfor k in range(nofdays):\n\t\t\t\t\t\t\treq_date_nxt = req_date + timedelta(days = k)\n\t\t\t\t\t\t\tprint(req_date_nxt)\n\t\t\t\t\t\t\td2 = (req_date_nxt.year,req_date_nxt.month,req_date_nxt.day)\n\t\t\t\t\t\t\tif(d1<=d2<=d3):\n\t\t\t\t\t\t\t\tflash('Sorry, requested dates are not available.')\n\t\t\t\t\t\t\t\tflag=1\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif(flag==1):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tg.db.execute('INSERT into Bookings VALUES (?,?,?,?,?)',(rid,uid,e_name,date,nofdays))\n\t\t\t\t\t\tg.db.commit()\n\t\t\t\t\t\tflash('Booking successful!')\n\n\t\t\t\t\t\tdt = datetime.strptime(date,'%Y-%m-%d')\n\t\t\t\t\t\tndays = nofdays\n\t\t\t\t\t\tdt_next = dt + timedelta(days = ndays)\n\t\t\t\t\t\tdays.append([e_name,dt,dt_next])\n\t\t\t\t\t\tsession['days'] = days\n\n\t\t\t\treturn render_template('calendar.html',data=days,hallname=r_name)\n\t\telse:\n\t\t\tflash('Invalid booking date: Cannot book a past date.')\n\t\t\treturn render_template('calendar.html',data=days,hallname=r_name)\n\n\nif __name__ == '__main__':\n app.run(host= '0.0.0.0', port=5000, debug=True)\n#host= '0.0.0.0', port=5000,\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"71578739","text":"# object to JSON\n\n\ndef parse_list(data):\n if type(data) == list or type(data) == tuple:\n result = '['\n for i in data:\n result += to_json(i) + \", \"\n result += ']'\n return result\n\n\ndef parse_dict(data):\n if type(data) == dict:\n result = \"{\"\n for key, file in data.items():\n if type(key) not in (str, int):\n raise ValueError\n result += ' \"{}\": {}, '.format(key, to_json(file))\n result += \"}\"\n return result\n\n\ndef to_json(object):\n try:\n selector = {\n type(object) == str:'\"{}\"'.format(object) ,\n type(object) == int or float: \"{}\".format(object),\n type(object) == bool: \"{}\".format(object),\n type(object) == dict: parse_dict(object),\n type(object) == list: parse_list(object),\n type(object) == tuple: parse_list(object),\n object is None: \"null\",\n }[True]\n\n return selector\n\n except KeyError:\n raise ValueError(\"not JSONable type\")\n\nif __name__ == '__main__':\n default_data = {\"somebody\": 1, \"told\": [\"me\", \"the world\"], \"is gonna\": None, \"roll \": {\"me\": 2}}\n\n with open(\"data.txt\", \"w\") as file:\n file.write(to_json(default_data))\n","sub_path":"lab_2/module_26_lab_2_5.py","file_name":"module_26_lab_2_5.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"363607843","text":"# -*- coding: utf-8 -*-\n#/usr/bin/python3\n'''\nFeb. 2019 by kyubyong park.\nkbpark.linguist@gmail.com.\nhttps://www.github.com/kyubyong/transformer.\n\nBuilding blocks for Transformer\n'''\n\nimport numpy as np\nimport tensorflow as tf\n\ndef layer_normalization(inputs, epsilon = 1e-8, scope=\"layer_normalization\"):\n '''Applies layer normalization. See https://arxiv.org/abs/1607.06450.\n inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`.\n epsilon: A floating number. A very small number for preventing ZeroDivision Error.\n scope: Optional scope for `variable_scope`.\n \n Returns:\n A tensor with the same shape and data dtype as `inputs`.\n '''\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n # inputs: [N, T_q, d_model].\n inputs_shape = inputs.get_shape() # (N, T_q, d_model)\n params_shape = inputs_shape[-1:] # 取出最后的维度,(d_model,)\n\n # inputs: [N, T_q, d_model].\n # mean: [N, T_q, 1],只在最后一个维度上进行求平均\n # variance: [N, T_q, 1],只在最后一个维度上进行求方差\n mean, variance = tf.nn.moments(inputs, axes=[-1], keep_dims=True) # 计算输入tensor的均值与方差\n # beta与gamma是需要学习的参数\n # beta:[d_model,]\n beta= tf.get_variable(\"beta\", params_shape, initializer=tf.zeros_initializer())\n # gamma:[d_model,]\n gamma = tf.get_variable(\"gamma\", params_shape, initializer=tf.ones_initializer())\n # inputs: [N, T_q, d_model].\n # mean: [N, T_q, 1]\n # normalized: [N, T_q, d_model].\n normalized = (inputs - mean) / ( (variance + epsilon) ** (.5) ) # (x-mu)/sigma\n \"\"\"\n 注意:此处的gamma在各个维度上的值并不相同,即各维度上不共享\n \"\"\"\n # gamma:[d_model,]\n # normalized: [N, T_q, d_model].\n # beta:[d_model,]\n outputs = gamma * normalized + beta\n \n return outputs\n\ndef get_token_embeddings(vocab_size, num_units, zero_pad=True):\n '''Constructs token embedding matrix.\n Note that the column of index 0's are set to zeros.\n vocab_size: scalar. V.\n num_units: embedding dimensionalty. E.\n zero_pad: Boolean. If True, all the values of the first row (id = 0) should be constant zero\n To apply query/key masks easily, zero pad is turned on.\n\n Returns\n weight variable: (V, E)\n '''\n with tf.variable_scope(\"shared_weight_matrix\"):\n # embeddings:[vocab_size, num_units]\n embeddings = tf.get_variable('weight_mat',\n dtype=tf.float32,\n shape=(vocab_size, num_units),\n initializer=tf.contrib.layers.xavier_initializer())\n if zero_pad:\n # embeddings:[vocab_size, num_units]\n embeddings = tf.concat((tf.zeros(shape=[1, num_units]), # 将第0个vocab_size置成全0, 在padding时,index=0对应的正是字符\n embeddings[1:, :]),\n axis=0)\n return embeddings\n\ndef scaled_dot_product_attention(Q, K, V,\n causality=False,\n dropout_rate=0.,\n training=True,\n scope=\"scaled_dot_product_attention\"):\n '''See 3.2.1.\n Q: Packed queries. 3d tensor. [N, T_q, d_k].\n K: Packed keys. 3d tensor. [N, T_k, d_k].\n V: Packed values. 3d tensor. [N, T_k, d_v].\n causality: If True, applies masking for future blinding\n dropout_rate: A floating point number of [0, 1].\n training: boolean for controlling droput\n scope: Optional scope for `variable_scope`.\n\n :return query_key_interaction:[N, T_q, d_v]\n '''\n \"\"\"\n 注意:key与value的seq长度必须相等\n \n 计算每个q对所有k_i的score\n 如:q=[i,love,nlp]\n \n score_i = q*k(i)/sqrt(d_k)\n score_i = softmax(score_i)\n value = sum_{i}{score_i* value_i}\n \"\"\"\n\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n #Q:[N, T_q, d_k].\n d_k = Q.get_shape().as_list()[-1]\n\n # dot product\n # Q: [N, T_q, d_k]\n # K: [N, T_k, d_k] => [N, d_k, T_k]\n # query_key_interaction:[N, T_q, T_k]\n # tf.matmul矩阵乘法\n query_key_interaction = tf.matmul(Q, tf.transpose(K, [0, 2, 1])) # (N, T_q, T_k)\n\n # scale\n # query_key_interaction:[N, T_q, T_k]\n query_key_interaction /= d_k ** 0.5 # / sqrt(key_dim)\n\n # key masking\n # Q:[N, T_q, d_k]\n # K:[N, T_k, d_k]\n # query_key_interaction:[N, T_q, T_k]\n # 对于key mask的话, 将key padding成outputs的维度\n query_key_interaction = mask(query_key_interaction, Q, K, type=\"key\") # 将key中元素全为0的mask掉,元素全为0的正是对应padding所生成的embedding\n\n # causality or future blinding masking\n \"\"\"\n 生成query_key_interaction关于时间的掩码下三角矩阵\n query_key_interaction:[N, T_q, T_k]\n 例: \n [[-1.4095545 0. 0. ]\n [ 0.526246 -0.11131065 0. ]\n [ 0.80647576 -0.886015 -0.04653838]\n [ 1.073006 -0.6044851 -0.7388869 ]]\n \n 即时间T_q=2时,只能与时间为T_k=1或T_k=2的交互\n 时间T_q=3时,只能与时间为T_k=1或T_k=2, T_k=3的交互\n \n 由于在代码中,padding的是一个非常大的负数,因此经过softmax之后,会变成0\n \"\"\"\n if causality: # 因果关系,即为decoder模式, 不能使用未来的timestep\n query_key_interaction = mask(query_key_interaction, type=\"future\")\n\n # softmax\n # query_key_interaction_norm:[N, T_q, T_k], 每个query对所有的key进行attention\n query_key_interaction_norm = tf.nn.softmax(query_key_interaction, axis=-1)\n # attention:[N, T_k, T_q]\n attention = tf.transpose(query_key_interaction_norm, [0, 2, 1])\n tf.summary.image(\"attention\", tf.expand_dims(attention[:1], -1)) # 取第一个元素,进行展示\n\n # query masking\n # Q:[N, T_q, d_k]\n # K:[N, T_k, d_k]\n # query_key_interaction_norm:[N, T_q, T_k]\n # 对于query mask的话, 将query padding成outputs的维度\n query_key_interaction_norm = mask(query_key_interaction_norm, Q, K, type=\"query\") # 将query中元素全为0的mask掉,元素全为0的正是对应padding所生成的embed\n\n # dropout\n # query_key_interaction_norm:[N, T_q, T_k]\n query_key_interaction_norm = tf.layers.dropout(query_key_interaction_norm, rate=dropout_rate, training=training)\n\n # weighted sum (context vectors)\n # query_key_interaction_norm:[N, T_q, T_k]\n # V:[N, T_k, d_v].\n # attentioned_value:[N, T_q, d_v]\n attentioned_value = tf.matmul(query_key_interaction_norm, V) # (N, T_q, d_v)\n\n return attentioned_value\n\ndef mask(inputs, queries=None, keys=None, type=None):\n \"\"\"Masks paddings on keys or queries to inputs\n inputs: 3d tensor. (N, T_q, T_k), 每个query对每个key的交互:(T_q, T_k)\n queries: 3d tensor. (N, T_q, d)\n keys: 3d tensor. (N, T_k, d)\n\n e.g.,\n >> queries = tf.constant([[[1.],\n [2.],\n [0.]]], tf.float32) # (1, 3, 1)\n >> keys = tf.constant([[[4.],\n [0.]]], tf.float32) # (1, 2, 1)\n >> inputs = tf.constant([[[4., 0.],\n [8., 0.],\n [0., 0.]]], tf.float32) #(1,3,2)\n >> mask(inputs, queries, keys, \"key\") # (1, 3, 2)\n array([[[ 4.0000000e+00, -4.2949673e+09],\n [ 8.0000000e+00, -4.2949673e+09],\n [ 0.0000000e+00, -4.2949673e+09]]], dtype=float32)\n\n >> inputs = tf.constant([[[1., 0.],\n [1., 0.],\n [1., 0.]]], tf.float32) # (1,3,2)\n >> mask(inputs, queries, keys, \"query\") # (1,3,2)\n array([[[1., 0.],\n [1., 0.],\n [0., 0.]]], dtype=float32)\n \"\"\"\n padding_num = -2 ** 32 + 1 # -4294967297\n if type in (\"k\", \"key\", \"keys\"):\n # 对于key的话, padding成input的维度\n # Generate masks\n # keys: [N, T_k, d]\n masks = tf.sign(tf.reduce_sum(tf.abs(keys), axis=-1)) # (N, T_k), 为啥需要将key abs后reduce_sum, 现在里面只有[0,1], 且只有元素都为0时才会为0\n masks = tf.expand_dims(masks, 1) # (N, 1, T_k)\n # masks:[N, 1, T_k]\n # => [N, T_q, T_k]\n # queries: [N, T_q, d]\n masks = tf.tile(masks, [1, tf.shape(queries)[1], 1]) # (N, T_q, T_k)\n\n # Apply masks to inputs\n # inputs: [N, T_q, T_k]\n paddings = tf.ones_like(inputs) * padding_num # 注意, padding的不是0,而是一个比较大的负数\n outputs = tf.where(tf.equal(masks, 0), paddings, inputs) # (N, T_q, T_k), 搞不懂,keys中的这里哪些T_k为0呢?\n\n elif type in (\"q\", \"query\", \"queries\"):\n # 对于query的话, padding成input的维度\n # Generate masks\n # queries: (N, T_q, T_k)\n masks = tf.sign(tf.reduce_sum(tf.abs(queries), axis=-1)) # (N, T_q)\n masks = tf.expand_dims(masks, -1) # (N, T_q, 1)\n masks = tf.tile(masks, [1, 1, tf.shape(keys)[1]]) # (N, T_q, T_k)\n\n # Apply masks to inputs\n outputs = inputs * masks # mask为0的地方直接被置成0了\n elif type in (\"f\", \"future\", \"right\"):\n \"\"\"\n 生成inputs的关于时间的掩码下三角矩阵\n \n 此处是因果推断,即预测T时刻时不能提前看到T时刻的标签\n input: [[-1.4095545 -0.5366828 -0.5652379 ]\n [ 0.526246 -0.11131065 0.26350743]]\n tril: [[-1.4095545 0. 0. ]\n [ 0.526246 -0.11131065 0. ]] \n \"\"\"\n # inputs: [N, T_q, T_k]\n diag_vals = tf.ones_like(inputs[0, :, :]) # (T_q, T_k)\n # 生成diag_vals的下三角矩阵\n # tril:[T_q, T_k]\n tril = tf.linalg.LinearOperatorLowerTriangular(tril=diag_vals).to_dense() # (T_q, T_k)\n # masks:[N, T_q, T_k]\n masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(inputs)[0], 1, 1]) # (N, T_q, T_k)\n\n paddings = tf.ones_like(masks) * padding_num\n # outputs: [N, T_q, T_k]\n outputs = tf.where(tf.equal(masks, 0), paddings, inputs) # 每个T_q只能与前面时间点的T_k进行交互\n else:\n print(\"Check if you entered type correctly!\")\n\n\n return outputs\n\ndef multihead_attention_and_residual_and_norm(queries, keys, values,\n num_heads=8,\n dropout_rate=0,\n training=True,\n causality=False,\n scope=\"multihead_attention\"):\n '''Applies multihead attention. See 3.2.2\n queries: A 3d tensor with shape of [N, T_q, d_model].\n keys: A 3d tensor with shape of [N, T_k, d_model].\n values: A 3d tensor with shape of [N, T_k, d_model].\n num_heads: An int. Number of heads.\n dropout_rate: A floating point number.\n training: Boolean. Controller of mechanism for dropout.\n causality: Boolean. If true, units that reference the future are masked.\n scope: Optional scope for `variable_scope`.\n \n Returns\n A 3d tensor with shape of (N, T_q, C)\n\n =====================\n 注意:T_q与T_k的值不一定会相同,所以会有padding, 但是keys与values的序列长度肯定一样,因为一个key对应一个value,即(key,value)\n procedures:\n 1. self-attention\n 2. add residual\n 3. layer normalization\n =====================\n '''\n # queries: [N, T_q, d_model].\n d_model = queries.get_shape().as_list()[-1]\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n \"\"\"\n Query vector, Key vector, Value vector三者向量维度为64(paper中的参数),小于原始embedding_size(512).\n 注意:感觉此处与原始paper中的略有不同,原始paper中,输入向量的维度(512)>映射后的向量维度(64),而此处是相等的\n \n q=X*Wq \n k=X*Wk\n v=X*Wv\n \"\"\"\n # Linear projections, 将query, key, value映射成指定维度的向量, 其意义是将原始向量空间转换到attention的空间\n # queries:[N, T_q, d_model], units=d_model\n # W: [d_model, d_model]\n # Q: [N, T_q, d_model]\n Q = tf.layers.dense(inputs=queries, units=d_model, use_bias=False) # (N, T_q, d_model), 里面参数是矩阵W_Q: [d_model, d_model], 注意没有bias\n K = tf.layers.dense(inputs=keys, units=d_model, use_bias=False) # (N, T_k, d_model), 里面参数是矩阵W_K: [d_model, d_model], 注意没有bias\n V = tf.layers.dense(inputs=values, units=d_model, use_bias=False) # (N, T_k, d_model), 里面参数是矩阵W_V: [d_model, d_model], 注意没有bias\n \n # Split and concat\n # 将原始的Q在第2维分割成num_heads=h份,然后在第0维拼接, 意义是将attention空间切分成多个等份\n Q_ = tf.concat(tf.split(value=Q, num_or_size_splits=num_heads, axis=2), axis=0) # (h*N, T_q, d_model/h), h即为head\n K_ = tf.concat(tf.split(value=K, num_or_size_splits=num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n V_ = tf.concat(tf.split(value=V, num_or_size_splits=num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n\n \"\"\"\n score_i = q*k(i)/sqrt(d_k)\n score_i = softmax(score_i)\n value = sum_{i}{score_i* value_i}\n \n 此处的mulit-head attention设计的确巧妙!\n \"\"\"\n # Attention\n # Q_:(head*N, T_q, d_model/head)\n # K_:(head*N, T_q, d_model/head)\n # V_:(head*N, T_q, d_model/head)\n # attentioned_value:[N=h*N, T_q, T_v=d_model/h]\n attentioned_value = scaled_dot_product_attention(Q_, K_, V_, causality, dropout_rate, training)\n\n \"\"\"\n 注意:此处与原paper有所不同,原paper中,在concat向量之后,还会将concat_vector乘以Wo,但此处没有乘以Wo\n \"\"\"\n # 直接将multi_head的输出concat拼接起来\n # Restore shape\n # attentioned_value:[h*N, T_q, d_model/h] -> (N, T_q, d_model)\n attentioned_value = tf.concat(tf.split(attentioned_value, num_heads, axis=0), axis=2) # (N, T_q, d_model)\n \n # Residual connection,残差连接\n # queries: [N, T_q, d_model].\n # attentioned_value: [N, T_q, d_model].\n attentioned_value += queries\n \n # layer normalize\n # attentioned_value: [N, T_q, d_model].\n attentioned_value = layer_normalization(attentioned_value)\n \n return attentioned_value\n\ndef positionwise_feedforward_and_residual_and_norm(inputs, num_units:list, scope=\"positionwise_feedforward\"):\n '''position-wise feed forward net. See 3.3\n \n inputs: A 3d tensor with shape of [N, T, C].\n num_units: A list of two integers.\n scope: Optional scope for `variable_scope`.\n\n Returns:\n A 3d tensor with the same shape and dtype as inputs\n\n Observe that during this step, vector representations of tokens don’t “interact” with each other.\n It is equivalent to run the calculations row-wise and stack the resulting rows in a matrix.\n 注意:这个是每个位置上的词,做自己的feed-forward,即各token间并没有发生交互,即在T这个维度上各自前向传播,并未发生交互.\n procedure:\n 1. feed-forward (两层全连接,中间加relu激活函数)\n 2. residual (add)\n 3. layer normalization (norm)\n '''\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n # Inner layer\n # inputs: [N, T, C]. N=batch_size, T=time_step, C=channel\n # W :[C, num_units[0]], b:[num_units[0]], 注意,各个time_step的词共享一个w,而并非单独w\n # outputs: [N, T, num_units[0]].\n outputs = tf.layers.dense(inputs, units=num_units[0], activation=tf.nn.relu) # 参数w: [C, num_units[0]]\n\n # Outer layer\n # w:[num_units[0], num_units[1]], b:[num_units[1]]\n # outputs: [N, T, num_units[1]].\n outputs = tf.layers.dense(outputs, units=num_units[1])\n\n # Residual connection\n # outputs: [N, T, num_units[1]].\n outputs += inputs\n \n # Normalize\n # outputs: [N, T, num_units[1]].\n outputs = layer_normalization(outputs)\n \n return outputs\n\ndef label_smoothing(inputs, epsilon=0.1):\n \"\"\"\n 有点像laplace平滑,将给为0的标签一个比较小的值\n :param inputs:\n :param epsilon:\n :return:\n \"\"\"\n '''Applies label smoothing. See 5.4 and https://arxiv.org/abs/1512.00567.\n inputs: 3d tensor. [N, T, V], where V is the number of vocabulary.\n epsilon: Smoothing rate.\n \n For example,\n \n ```\n import tensorflow as tf\n inputs = tf.convert_to_tensor([[[0, 0, 1], \n [0, 1, 0],\n [1, 0, 0]],\n\n [[1, 0, 0],\n [1, 0, 0],\n [0, 1, 0]]], tf.float32)\n \n outputs = label_smoothing(inputs)\n \n with tf.Session() as sess:\n print(sess.run([outputs]))\n \n >>\n [array([[[ 0.03333334, 0.03333334, 0.93333334],\n [ 0.03333334, 0.93333334, 0.03333334],\n [ 0.93333334, 0.03333334, 0.03333334]],\n\n [[ 0.93333334, 0.03333334, 0.03333334],\n [ 0.93333334, 0.03333334, 0.03333334],\n [ 0.03333334, 0.93333334, 0.03333334]]], dtype=float32)] \n ``` \n '''\n V = inputs.get_shape().as_list()[-1] # number of channels\n return ((1-epsilon) * inputs) + (epsilon / V)\n \ndef positional_encoding(inputs,\n maxlen,\n masking=True,\n scope=\"positional_encoding\"):\n '''Sinusoidal Positional_Encoding. See 3.5\n inputs: 3d tensor. (N, T, E=d_model)\n maxlen: scalar. Must be >= T\n masking: Boolean. If True, padding positions are set to zeros.\n scope: Optional scope for `variable_scope`.\n\n returns\n 3d tensor that has the same shape as inputs.\n\n 说明:\n 偶数位置:\n PE(pos,2i) =sin(pos/power(10000,2i/d_model)), 即偶数时为x-0\n 奇数位置:\n PE(pos,2i+1)=cos(pos/power(10000,2i/d_model)), 即奇数时为x-1\n 上面亦等价于:\n PE(pos,x) = sin(pos/power(10000, x/d_model)) , x为偶数\n PE(pos,x) = cos(pos/power(10000, (x-1)/d_model)), x为奇数\n 即为x-x%2\n '''\n # inputs: [N, T, E=d_model]\n E = inputs.get_shape().as_list()[-1] # static, tuple, 静态shape用x.get_shape()\n N, T = tf.shape(inputs)[0], tf.shape(inputs)[1] # dynamic, 动态shape用tf.shape, 为啥tf不弄成一样的?\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n # position indices\n position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), multiples=[N, 1]) # (N, T), 每行是0~(T-1)的序列\n\n # First part of the Position Embedding function: sin and cos argument\n # 偶数就不减,奇数减1\n # [maxlen, E], 每个pos在相同的embedding维度上的值不一样\n # y=a*sin(wx+b), T = 2*pai/w, sin(x)的T = 2*pai,\n # ind = pos/10000**(x/d_model), d_model一般为512, 10000**(x/d_model)范围在(1, 10000)之间\n # 若2i=0, T = 2*pai\n # 若2i=d_model,T=2*pai*10000~=6w\n # T(pos) = 2*pai*10000,约为6w个词才会重复\n # sin(pos/10000**[(x-x%2)/d_model]), 可简化为: sin(pos/10000**(x/d_model))\n # 序列中不同position以及不同embed_position的值不一样\n position_enc = np.array([\n [pos / np.power(10000, (i-i%2)/E) for i in range(E)] for pos in range(maxlen) # maxlen >= T\n ])\n\n # Second part, apply the cosine to even columns and sin to odds.\n # 序列中不同position以及不同embed_position的值不一样\n position_enc[:, 0::2] = np.sin(position_enc[:, 0::2]) # dim 2i , 偶数位置, 值范围: (~1, +1)\n position_enc[:, 1::2] = np.cos(position_enc[:, 1::2]) # dim 2i+1, 奇数位置, 值范围: (~1, +1)\n # position encoding的值范围是[~1, +1]\n position_enc = tf.convert_to_tensor(position_enc, tf.float32) # (maxlen, E), 将numpy array转为tensor\n\n # lookup\n # position_enc:[maxlen, E], 即[vocab_size=maxlen, embedding_dim=E]\n # position_ind:[N, T]\n # outputs:[N, T, E]\n # 注意: position_encoding 与普通的embedding的唯一区别是它不需要参数,只参与前向传播,而普通的embedding需要训练\n outputs = tf.nn.embedding_lookup(position_enc, position_ind)\n\n # masks\n if masking:\n # inputs:[N,T,E]\n # outputs:[N,T,E]\n # inputs中mask=0的地方,output还是0, 否则就是output\n outputs = tf.where(tf.equal(inputs, 0), x=inputs, y=outputs)\n\n return tf.to_float(outputs)\n\ndef noam_scheme(init_lr, global_step, warmup_steps=4000.):\n '''Noam scheme learning rate decay\n init_lr: initial learning rate. scalar.\n global_step: scalar.\n warmup_steps: scalar. During warmup_steps, learning rate increases\n until it reaches init_lr.\n\n 带有warmup的learning_rate\n '''\n step = tf.cast(global_step + 1, dtype=tf.float32)\n \"\"\"\n 通过代码模拟,可以看出其lr先急速增加至init_lr, 后缓慢减小\n init_lr * warmup^0.5 * min(step*warmup^(-1.5), step^(-0.5))\n \"\"\"\n return init_lr * warmup_steps ** 0.5 * tf.minimum(step * warmup_steps ** -1.5, step ** -0.5)","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":21655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"442116164","text":"from collections import Counter\nimport PyPDF2\n\nvocabFull = open('webster-vocab.pdf', 'rb')\npdfReader = PyPDF2.PdfFileReader(vocabFull)\npdfWriter = PyPDF2.PdfFileWriter()\npageCounter = Counter()\n\nfor pageNum in range(pdfReader.numPages):\n pageObj = pdfReader.getPage(pageNum)\n pdfWriter.addPage(pageObj)\n\n\n\n\npdfOutput = open('test2.pdf', 'wb')\npdfWriter.write(pdfOutput)\npdfOutput.close()","sub_path":"page-copy.py","file_name":"page-copy.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"80586254","text":"import time\nimport logging\nimport responder\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d:%H:%M:%S', level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\napi = responder.API()\n\n@api.route(\"/{greeting}\")\nasync def greet_world(req, resp, *, greeting):\n resp.text = f\"{greeting}, world!\"\n\nif __name__ == '__main__':\n api.run(address=\"0.0.0.0\", port=8080)\n","sub_path":"web/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"409018170","text":"import sys\r\ninput=sys.stdin.readline\r\n\r\nclass Compare:\r\n def read(self):\r\n self.info=[]\r\n self.ind_f=[] \r\n self.n=int(input())\r\n for _ in range(self.n):\r\n [b,h]=list(map(int,input().split()))\r\n self.info.append([b,h])\r\n self.ind_f.append(str(b)+str(h)) #각 사람별 특수한 id \r\n self.info.sort(key=lambda x:x[1],reverse=True)\r\n\r\n\r\n\r\n def solve(self):\r\n ans=[float(\"inf\")]*self.n\r\n for i in range(self.n):\r\n com=self.info[i][0]\r\n cur=self.info[i][1]\r\n ind=self.ind_f.index(str(com)+str(cur))\r\n self.ind_f[ind]=0 #solved \r\n count=0\r\n if i==0:\r\n ans[ind]=count+1\r\n else:\r\n for j in range(i):\r\n if self.info[j][1]>cur and self.info[j][0]>com:\r\n count+=1\r\n \r\n ans[ind]=count+1\r\n \r\n \r\n \r\n for score in ans:\r\n print(score,end=' ')\r\n \r\n \r\nc=Compare()\r\nc.read()\r\nc.solve()","sub_path":"jiyoon🐫/brute force/백준_7568.py","file_name":"백준_7568.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"179053366","text":"import os\nimport random\n\nfrom mixture_of_softmax.mos_model import MosWordPredictor\nfrom mixture_of_softmax.utils import Words2OneHot\nfrom mixture_of_softmax.utils import train\nfrom mixture_of_softmax.utils import get_words\nfrom mixture_of_softmax.utils import get_data_from_text\n\n_bucket_size = 20\n_bptt = 35\n_mixture_components = 15\n_path = os.path.dirname(__file__)\n_saving_dir = os.path.join(_path, '../data/save')\n_all_tokens_filename = os.path.join(_path, '../data/penn/all.txt')\n_training_filename = os.path.join(_path, '../data/penn/train.txt')\n\nif __name__ == '__main__':\n text = open(_training_filename, encoding=\"ISO-8859-1\").read()\n words_list = get_words(text)\n\n tokens_text = open(_all_tokens_filename, encoding=\"ISO-8859-1\").read()\n tokens_list = get_words(tokens_text)\n word_to_one_hot = Words2OneHot(tokens_list)\n\n data = get_data_from_text(words_list, _bptt)\n data = sorted(data, key=lambda x: random.random())\n\n nn_model = MosWordPredictor(word_to_one_hot.get_length(), mixture_components=_mixture_components)\n train(data, nn_model, word_to_one_hot, _saving_dir, num_samples=500000, prefix='mos-', epochs=41, bucket_size=_bucket_size, trace_every=1)\n","sub_path":"mixture_of_softmax/train_mos.py","file_name":"train_mos.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"518277572","text":"# %load q04_count/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution Here\ndef deliveries_count(data=data):\n \n # Your code here\n count=0\n data1=data['innings'][0]['1st innings']['deliveries']\n for i in data1:\n temp1=str(i.keys())\n temp=temp1[11:14]\n if (float(temp)>=10.0):\n temp=temp1[11:15]\n if 'RT Ponting' in i[float(temp)]['batsman']:\n count=count+1\n return count\n\n\n","sub_path":"q04_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"34535242","text":"import mock\nimport unittest\n\nfrom armada.handlers.tiller import Tiller\n\n\nclass TillerTestCase(unittest.TestCase):\n\n @mock.patch.object(Tiller, '_get_tiller_ip')\n @mock.patch('armada.handlers.tiller.K8s')\n @mock.patch('armada.handlers.tiller.grpc')\n @mock.patch('armada.handlers.tiller.Config')\n @mock.patch('armada.handlers.tiller.InstallReleaseRequest')\n @mock.patch('armada.handlers.tiller.ReleaseServiceStub')\n def test_install_release(self, mock_stub, mock_install_request,\n mock_config, mock_grpc, mock_k8s, mock_ip):\n # instantiate Tiller object\n mock_grpc.insecure_channel.return_value = None\n mock_ip.return_value = '0.0.0.0'\n tiller = Tiller()\n assert tiller._get_tiller_ip() == '0.0.0.0'\n\n # set params\n chart = mock.Mock()\n dry_run = False\n name = None\n namespace = None\n initial_values = None\n updated_values = mock_config(raw=initial_values)\n wait = False\n timeout = 3600\n\n tiller.install_release(chart, name, namespace,\n dry_run=dry_run, values=initial_values,\n wait=wait, timeout=timeout)\n\n mock_stub.assert_called_with(tiller.channel)\n release_request = mock_install_request(\n chart=chart,\n dry_run=dry_run,\n values=updated_values,\n release=name,\n namespace=namespace,\n wait=wait,\n timeout=timeout\n )\n (mock_stub(tiller.channel).InstallRelease\n .assert_called_with(release_request,\n timeout + 60,\n metadata=tiller.metadata))\n","sub_path":"armada/tests/unit/handlers/test_tiller.py","file_name":"test_tiller.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"498650381","text":"\"\"\"\n@file\n@brief Various helper about shortcuts and links\n\"\"\"\n\nimport os, sys, platform\n\ndef add_shortcut_to_desktop(file, name, description = \"\", arguments = \"\"):\n \"\"\"\n Add a shortcut to the desktop.\n\n @param file file name (without .lnk extension)\n @param name name of the shortcut\n @param description description\n @param arguments arguments\n @return path to the shortcut\n \"\"\"\n if not sys.platform.startswith(\"win\"):\n raise NotImplementedError(\"not implemented on this platform: \" + sys.platform)\n\n try:\n import winshell\n except ImportError as e :\n if \"DLL load failed\" in str(e):\n os.environ[\"PATH\"] = os.environ[\"PATH\"] + \";\" + os.path.split(sys.executable)[0] + r\"\\lib\\site-packages\\pywin32_system32\"\n try:\n import winshell\n except ImportError as ee :\n raise ImportError(r\"you should run the following in your current folder:\\ncopy C:\\%s\\lib\\site-packages\\pywin32_system32\\py*.dll %s\" % (os.path.split(sys.executable), os.getcwd())) from e\n else :\n raise e\n\n link_filepath = os.path.join(winshell.desktop(), name + \".lnk\")\n with winshell.shortcut(link_filepath) as link:\n link.path = file\n link.description = description\n link.arguments = arguments\n return link_filepath\n\ndef suffix():\n \"\"\"\n add a suffix to a shortcut name = python version + architecture\n\n @return string\n \"\"\"\n ver = \".\".join( str(_) for _ in sys.version_info[:2] )\n arc = platform.architecture()[0]\n return \"{0}.{1}\".format(arc, ver)","sub_path":"src/pymyinstall/installhelper/link_shortcuts.py","file_name":"link_shortcuts.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"89362120","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 11 11:35:13 2019\n\n@author: Fabiana\n\"\"\"\n\nimport sqlite3 \nimport json\nimport random\n\nconn = sqlite3.connect('phonebook.db') \n\nc = conn.cursor()\n\ndef create_table_people():\n c.execute('CREATE TABLE IF NOT EXISTS people(personId REAL, name TEXT, surname TEXT, addressLine1 VARCHAR(255), city TEXT, country TEXT, postcode VARCHAR(10), phoneNumber REAL)')\n \ncreate_table_people() \n\ndef populate_table_people():\n with open('data_people.json') as p:\n dataPeople = json.load(p)\n for row in dataPeople:\n personId = random.randint(0,100000)\n name = row[\"first_name\"]\n surname = row[\"last_name\"]\n addressLine1 = row[\"address_line_1\"]\n city = row[\"address_line_2\"]\n country = row[\"address_line_3\"]\n postcode = row[\"postcode\"]\n phoneNumber = row[\"telephone_number\"]\n c.execute(\"INSERT INTO people(personId, name, surname, addressLine1, city, country, postcode, phoneNumber) VALUES(?,?,?,?,?,?,?,?)\", (personId, name, surname, addressLine1, city, country, postcode, phoneNumber))\n conn.commit() \n\npopulate_table_people() \n \n\nc.close()\nconn.close()\n\n","sub_path":"UpdatedPhoneBookModule3/UpdatedPhoneBook_practice/phonebook_people.py","file_name":"phonebook_people.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"97233702","text":"class Artist:\n\tdef __init__(self, json, id):\n\t\tself.name = json['name']\n\t\tself.mbid = json['mbid']\n\t\tself.heading = \"heading\"+str(id)\n\t\tself.body = \"body\"+str(id)\n\n\tdef toString():\n\t\treturn \"Name: \" + str(name) + \" ||| mbid: \" + str(mbid)\n\nclass Setlist:\n\tdef __init__(self, setlist):\n\t\tself.name = setlist['artist']['name']\n\t\tself.venue_name = setlist['venue']['name']\n\t\tself.venue_city = setlist['venue']['city']['name']\n\t\tself.venue_state = setlist['venue']['city']['state']\n\t\tself.date = setlist['eventDate']\n\n\t\ttry:\n\t\t\tself.tour_name = setlist['tour']['name']\n\t\texcept KeyError:\n\t\t\tself.tour_name = \"\"\n\n\t\ttry:\n\t\t\tself.set_list = setlist['sets']['set'][0]['song'] #list of songs\n\t\texcept IndexError:\n\t\t\tself.set_list = []\n\n\t\ttry:\n\t\t\tself.encore_list = setlist['sets']['set'][1]['song'] #list of encore songs\n\t\texcept IndexError:\n\t\t\tself.encore_list = []\t\n","sub_path":"play_app/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"21251833","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on %(date)s\n\n@author: %(username)s\n\"\"\"\n\nimport plotly.plotly as py\nimport pandas as pd\nfrom math import *\n\ndef lnalpha(series):\n results = []\n for i in range(0,len(series)):\n if (isnan(series.d18OCalcite.iloc[i]) == False) & (isnan(series.d18OWater.iloc[i]) == False):\n result = 1000*(log((series.d18OCalcite.iloc[i] + 1000)/(series.d18OWater.iloc[i] + 1000)))\n results.append(result)\n else:\n results.append(float('Nan'))\n series['1000lnalpha'] = results\n return series\n \nExternalMSResults = pd.read_csv('externalms.csv')\nExternalMSResults.rename(columns={'1000lnalpha': '1000lnalpha_pub'}, inplace=True)\nExternalMSResults = lnalpha(ExternalMSResults).sort('Cave')\ndf = ExternalMSResults[ExternalMSResults.Type == 'Cave Calcite']\nlist_ExternalCaves = list(set(df.Cave))\nlist_ExternalCaves.sort()\n\nJinapsanCaveResults = pd.read_pickle('JinapsanCaveResults')\n\n#df2007 = df[df.year==2007]\n#df1952 = df[df.year==1952]\n#df.head(2)\n\nfig = {\n 'data': [\n# {\n# \t\t\t'x': 1000/((JinpasanCaveResults.Temp)+273), \n# \t'y': JinapsanCaveResults['1000lnalpha'], \n# 'text': JinapsanCaveResults.Temp, \n# 'mode': 'markers', \n# 'name': '2007'},\n \n {\n 'x': 1000/(273.0+df[df['Cave']==cave]['WaterTemp']),\n 'y': df[df['Cave']==cave]['1000lnalpha'],\n 'name': cave, 'mode': 'markers',}\n for cave in list_ExternalCaves\n ],\n 'layout': {\n 'xaxis': {'title': '1000/T (K)'},\n 'yaxis': {'title': \"1000lnalpha\"}\n }\n}\n\nurl = py.plot(fig, filename='pandas/grouped-scatter')","sub_path":"plotly_alpha_fig.py","file_name":"plotly_alpha_fig.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"90421088","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\nimport rospy\nimport serial\nfrom std_msgs.msg import String\nimport math\nimport sys\nimport json\nimport time\nfrom geometry_msgs.msg import Twist\nimport logging\nlogging.basicConfig()\n\nfrom time import sleep\n\n\nport='/dev/dji_board'\nrospy.loginfo(\"Opening %s...\", port)\n#控制电机速度\n\n\ndef send_gimbal(pitch,yaw):\n data = { \"gimbal\":[pitch,yaw]}\n data_string = json.dumps(data)\n ser.write('*'+ data_string +'?')\n\ndef send_chassis(vx,vy,vz):\n data = { \"chassis\":[vx,vy,vz] }\n data_string = json.dumps(data)\n ser.write('*'+ data_string +';')\n\ndef send_translation(translation):\n data ={\"translation\":[translation]}\n data_string = json.dumps(data)\n ser.write('*'+ data_string +'!')\n \ndef send_fric(fric):\n data ={\"fric\":[fric]}\n data_string = json.dumps(data)\n ser.write('*'+ data_string +'>')\n\ndef send_trigger(trigger):\n data ={\"trigger\":[trigger]}\n data_string = json.dumps(data)\n ser.write('*'+ data_string +'>')\ndef send_gimbal_hand_angle(hand_pitch,hand_yaw):\n data = {\"hand_angle\":[hand_pitch,hand_yaw]}\n data_string = json.dumps(data)\n ser.write('*' + data_string + '<')\n\n\n\n\ntry:\n ser = serial.Serial(port=port, baudrate=115200, timeout=5)\nexcept serial.serialutil.SerialException:\n rospy.logerr(\"Dji not found at port \"+port + \". Did you specify the correct port in the launch file?\")\n sys.exit(0)\n\n\n\n\nrospy.init_node('serial', anonymous=True)\n\n\nwhile 1 : \n speed_x = 3\n speed_y = 0\n speed_z = 0\n send_chassis(int(speed_x),int(speed_y),int(speed_z))\n rospy.loginfo(\"linear_x: %f\",speed_x)\n\n\n \n\n\n\n \n\n\nwhile not rospy.is_shutdown():\n line = ser.readline()\n \n #rospy.loginfo(\"I have got chassis velicities: \" + line)\n #解析字符串为python 对象\n #rospy.loginfo(\"hello\")\n #pub = rospy.Publisher('currant_vel', Twist, queue_size=10)\n #sub1= rospy.Subscriber(\"teleop_cmd_vel\", Twist, callback)\n try:\n de_json = json.loads(line)\n #linear_x = de_json[1][0]\n #linear_y = de_json[1][1]\n # angular_z = de_json[1][2]\n # rospy.loginfo(\"get_feedback:[\" + str(linear_x) + \",\" + str(linear_y)+ \",\" + str(angular_z) + \"]\\n\")\n\n except:\n None\n #rospy.loginfo(de_json)\n #控制电机速度\n # speed_x = 0\n # speed_y = 30\n # speed_z = 0\n # send_command(speed_x,speed_y,speed_z)\n#关闭节点时停止电机\n#time.sleep(1)\nsend_command(0,0,0)\nser.close\n\n#关闭节点时先按control-s再按control-c\n","sub_path":"src/sentry/scripts/old/serial123.py","file_name":"serial123.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"344132608","text":"from copy import deepcopy\n\"\"\"\nA matrix will be an N sized list of 4 element lists.\nEach individual list will represent an [x, y, z, 1] point.\nFor multiplication purposes, consider the lists like so:\nx0 x1 xn\ny0 y1 yn\nz0 z1 ... zn\n1 1 1\n\"\"\"\nimport math\n\n#print the matrix such that it looks like\n#the template in the top comment\ndef print_matrix( matrix ):\n s1 = \"\"\n s2 = \"\"\n s3 = \"\"\n s4 = \"\"\n for i in range(len(matrix)):\n s1 += str(matrix[i][0]) + \" \"\n s2 += str(matrix[i][1]) + \" \"\n s3 += str(matrix[i][2]) + \" \"\n s4 += str(matrix[i][3]) + \" \"\n s1 = s1[:-1] + \"\\n\"\n s2 = s2[:-1] + \"\\n\"\n s3 = s3[:-1] + \"\\n\"\n s4 = s4[:-1]\n return s1 + s2 + s3 + s4\n\ndef print_transform(matrix):\n string = \"\"\n for i in matrix:\n for x in i:\n string += str(x) + \" \"\n string.strip()\n string += \"\\n\"\n return string[:-1]\n\n#turn the paramter matrix into an identity matrix\n#you may assume matrix is square\ndef ident(matrix):\n while len(matrix) > 4:\n del matrix[-1]\n while len(matrix) < 4: matrix.append([])\n for i in range(len(matrix)): matrix[i] = [0] * 4\n length = len(matrix)\n for i in range(length):\n for x in range(length):\n if i != x: matrix[i][x] = 0\n else: matrix[i][x] = 1\n\n#relative coordinate system\ndef newStack():\n stack = []\n i = []\n ident(i)\n stack.append(i)\n return stack\n\ndef push(stack):\n stack.append(deepcopy(stack[-1]))\n\ndef pop(stack):\n stack.pop(-1)\n\n#multiply m1 by m2, modifying m2 to be the product\n#m1 * m2 -> m2\n\n#I was unsure of the format for the multiplication\n#because the edge matrices are formatted where the\n#number of rows in the array is actumatrix[0][0] = xally the number\n#of columns in the matrix it is representing.\n\n#because m1 is usually going to be the transformation\n#matrix, I figured that it would be formatted like a\n#normal array, without the need to account for this by\n#flipping the array.\ndef matrix_mult( m1, m2 ):\n for i in range(len(m2)):\n temp = [0, 0, 0, 0]\n temp[0] = (m1[0][0] * m2[i][0]) + (m1[0][1] * m2[i][1]) + (m1[0][2] * m2[i][2]) + (m1[0][3] * m2[i][3])\n temp[1] = (m1[1][0] * m2[i][0]) + (m1[1][1] * m2[i][1]) + (m1[1][2] * m2[i][2]) + (m1[1][3] * m2[i][3])\n temp[2] = (m1[2][0] * m2[i][0]) + (m1[2][1] * m2[i][1]) + (m1[2][2] * m2[i][2]) + (m1[2][3] * m2[i][3])\n temp[3] = (m1[3][0] * m2[i][0]) + (m1[3][1] * m2[i][1]) + (m1[3][2] * m2[i][2]) + (m1[3][3] * m2[i][3])\n m2[i] = temp\n\ndef transform_mult(t1, t2):\n for i in range(4):\n temp = [0, 0, 0, 0]\n temp[0] = (t1[0][0] * t2[0][i]) + (t1[0][1] * t2[1][i]) + (t1[0][2] * t2[2][i]) + (t1[0][3] * t2[3][i])\n temp[1] = (t1[1][0] * t2[0][i]) + (t1[1][1] * t2[1][i]) + (t1[1][2] * t2[2][i]) + (t1[1][3] * t2[3][i])\n temp[2] = (t1[2][0] * t2[0][i]) + (t1[2][1] * t2[1][i]) + (t1[2][2] * t2[2][i]) + (t1[2][3] * t2[3][i])\n temp[3] = (t1[3][0] * t2[0][i]) + (t1[3][1] * t2[1][i]) + (t1[3][2] * t2[2][i]) + (t1[3][3] * t2[3][i])\n for x in range(4):\n t2[x][i] = temp[x]\n\ndef new_matrix(rows = 4, cols = 4):\n m = []\n for c in range( cols ):\n m.append( [] )\n for r in range( rows ):\n m[c].append( 0 )\n return m\n","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"163330053","text":"# The code below seems to have some problems.\n# Fix it before implementing the rest of your lab\n\ndef width(image):\n return image[\"width\"]\n\ndef height(image):\n return image[\"height\"]\n\ndef pixel(image, x, y):\n index = x + width(image)*y\n return image[\"pixels\"][index]\n\ndef set_pixel(image, x, y, color):\n index = x + width(image)*y\n image[\"pixels\"][index] = color\n\ndef make_image(width, height):\n return {\"width\": width, \"height\": height, \"pixels\": ([0]*width*height)}\n\n# return a new image by applying function f to each pixel of the input image\ndef apply_per_pixel(image, f):\n result = make_image(width(image), height(image))\n for x in range(width(result)):\n for y in range(height(result)):\n color = pixel(image, x, y)\n set_pixel(result, x, y, f(color))\n return result\n \ndef invert(c):\n return abs(255-c)\n \ndef filter_invert(image):\n return apply_per_pixel(image, invert)\n##\n## any function of the form \"filter_X( image ):\", where X denotes the name of\n## the filter, can be applied via test.py and the web UI!\n## Feel free to go wild and implement your favorite filters once you are done.\n## Here are some to inspire you: [GIMP filters](https://docs.gimp.org/en/filters.html\n\nkernal = {\"width\":3,\n \"height\":3,\n \"values\":[1.0/16, 2.0/16, 1.0/16,\n 2.0/16, 4.0/16, 2.0/16,\n 1.0/16, 2.0/16, 1.0/16]}\n\nKx = {\"width\":3,\n \"height\":3,\n \"values\":[-1, 0, 1,\n -2, 0, 2,\n -1, 0, 1]}\nKy = {\"width\":3,\n \"height\":3,\n \"values\":[-1, -2, -1,\n 0, 0, 0,\n 1, 2, 1]}\n\ndef convolution(image, x, y,kernal):\n k = kernal[\"values\"]\n k_w = kernal[\"width\"]\n k_h = kernal[\"height\"]\n p = image[\"pixels\"]\n w = width(image)\n h = height(image)\n i = x + width(image)*y\n k_i = len(k) // 2\n n = { \"left\":i-1, \"right\":i+1,\n \"upleft\": i-(w+1), \"upright\": i-(w-1), \"up\": i-w,\n \"down\": i+w, \"downleft\": i+(w-1), \"downright\": i+(w+1)}\n n_k = { \"left\":k_i-1, \"right\":k_i+1,\n \"upleft\": k_i-(k_w+1), \"upright\": k_i-(k_w-1), \"up\": k_i-k_w,\n \"down\": k_i+k_w, \"downleft\": k_i+(k_w-1), \"downright\": k_i+(k_w+1)}\n if i == 0 or i==w-1 or i == w*(h-1) or i == len(p)-1:\n color = p[i]*k[k_i]\n if i==0:\n for d in n.keys():\n if \"up\" not in d:\n if \"left\" not in d:\n color += (p[n[d]]*k[n_k[d]])\n if i==w-1:\n for d in n.keys():\n if \"up\" not in d:\n if \"right\" not in d:\n color += (p[n[d]]*k[n_k[d]])\n if i == w*(h-1):\n for d in n.keys():\n if \"down\" not in d:\n if \"left\" not in d:\n color += (p[n[d]]*k[n_k[d]])\n if i == len(p)-1:\n for d in n.keys():\n if \"down\" not in d:\n if \"right\" not in d:\n color += (p[n[d]]*k[n_k[d]]) \n elif i < w:\n color = p[i]*k[k_i]\n for d in n.keys():\n if \"up\" not in d:\n color += (p[n[d]]*k[n_k[d]])\n elif i%w == 0 and w < i < w*(h-1):\n color = p[i]*k[k_i]\n for d in n.keys():\n if \"left\" not in d:\n color += (p[n[d]]*k[n_k[d]])\n elif i%w == (w-1) and w < i < w*(h-1):\n color = p[i]*k[k_i]\n for d in n.keys():\n if \"right\" not in d:\n color += (p[n[d]]*k[n_k[d]])\n elif i > w*(h-1):\n color = p[i]*k[k_i]\n for d in n.keys():\n if \"down\" not in d:\n color += (p[n[d]]*k[n_k[d]])\n else:\n color = p[i]*k[k_i]\n for d in n.keys():\n color += (p[n[d]]*k[n_k[d]])\n return color\n\ndef legalize_range(image):\n new_image = [int(round(p)) for p in image[\"pixels\"]]\n image[\"pixels\"] = new_image\n return image\n\ndef apply_blur_per_pixel(image, f,k):\n result = make_image(width(image), height(image))\n for x in range(width(result)):\n for y in range(height(result)):\n set_pixel(result, x, y, f(image,x,y,k))\n return result \n\ndef filter_gaussian_blur(image):\n out = apply_blur_per_pixel(image, convolution,kernal)\n return legalize_range(out)\n\ndef filter_edge_detect(image):\n x_out = apply_blur_per_pixel(image,convolution,Kx)\n y_out = apply_blur_per_pixel(image,convolution,Ky)\n out = make_image(width(image),height(image))\n for x in range(width(image)):\n for y in range(height(image)):\n ox = pixel(x_out,x,y)\n oy = pixel(y_out,x,y)\n ans = (ox**2 + oy**2)**0.5\n if ans > 255:\n ans = 255\n set_pixel(out, x, y, ans)\n \n return legalize_range(out)\n \n \n \n\n \n\n \n\n","sub_path":"lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"297860458","text":"#!/usrbin/env python3\n# coding: utf-8\n\nimport requests\nimport sys\nimport io\nimport re\nimport os\n\n\ndef get_pic(url):\n # 传入一个起始图片页面url,获取其他的所有图片页面url,如下:\n #2\n # print (\"获取页面url完成,开始获取图片url并下载...\")\n q = requests.get(url, headers=head).text\n title_R = (r'(.*)')\n title = re.findall(title_R, q)[0]\n page_R = (r'(..)')\n max_page = re.findall(page_R, q)[0]\n # title是网页标题,可能含有特殊字符,需过滤\n title = re.sub(u'[\\/:*?\">|< 满]+', \"#\", title)\n #title = re.sub(r'[.]+',\"?\",title)\n\n return (title, max_page)\n\n\ndef change_dir(where):\n try:\n os.chdir(where)\n except:\n os.mkdir(where)\n os.chdir(where)\n print(\"创建并切换到目录'\" + where + \"'完成\")\n# print (\"切换目录到'\"+where+\"'完成\")\n\n\ndef down(one, url):\n # 传入一个包含图片的页面url,获取里面的图片地址并下载到本地,如下:\n #\"**************\"\n title = one[0]\n max_page = one[1]\n R = (r'\".*')\n change_dir('./mzitu')\n try:\n os.chdir(\"./\" + title)\n print(\"'\" + title + \"'已下载,跳过\")\n change_dir(\"../../\")\n except:\n change_dir(\"./\" + title)\n for i in range(0, int(max_page)):\n page = url + \"/\" + str(i + 1)\n html = requests.get(page, headers=head).text\n img_url = re.findall(R, html)[0]\n pic = requests.get(img_url, headers=head)\n with open(str(i) + '.jpg', 'wb') as f:\n for p in pic:\n f.write(p)\n change_dir(\"../../\")\n\n\ndef get_url_list(url):\n # 传入all页面的url,获取其他的所有文章链接,如下:\n #********\n text = requests.get(url, headers=head).text\n R = (r'.*(http://www.mzitu.com/[0-9]+)\".*')\n# print (text)\n print(\"从\" + url + \"获取专辑列表完成,开始获取页面url...\")\n return re.findall(R, text)\n\n\nif __name__ == \"__main__\":\n # sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #改变标准输出的默认编码\n # 曾经在运行时报字符编码错误所以添加了一条,但是现在去掉了,貌似也没报错。。。\n head = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0',\n 'Referer': 'http://www.mzitu.com/37288/3'}\n url = 'http://www.mzitu.com/all'\n page_number = input(\"下载多少页?\")\n #page_number = \"2\"\n print(\"#\" + page_number + \"#\")\n url_list = get_url_list(url)\n count = 0\n for i in url_list:\n if str(count) < page_number:\n one = get_pic(i)\n down(one, i)\n count += 1\n print(i + \":已经全部下载完成\")","sub_path":"chiu/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"334566930","text":"import numpy as np\r\n\r\nfrom algorithms.DeepQNetworkAlgorithm.DeepQNetworkAlgorithmBuffer import *\r\n\r\nclass DeepQNetworkAlgorithmPlayer:\r\n\tdef __init__(self, sess, agent, temp, state_size, action_size, learning_rate, buffer_size, buffer_dim_size):\r\n\t\tself.sess = sess\r\n\t\tself.agent = agent\r\n\t\tself.temp = temp\r\n\t\tself.STATE_SIZE = state_size\r\n\t\tself.ACTION_SIZE = action_size\r\n\t\tself.LEARNING_RATE = learning_rate\r\n\t\tself.BUFFER_SIZE = buffer_size\r\n\t\tself.BUFFER_DIM_SIZE = buffer_dim_size\r\n\r\n\t\tself.buffer = DeepQNetworkAlgorithmBuffer(self.BUFFER_SIZE, self.BUFFER_DIM_SIZE)\r\n\t\tself.running_reward = 0\r\n\r\n\tdef step(self, start, state, reward, done, take_random_action):\r\n\t\tif start:\r\n\t\t\tself.running_reward = 0\r\n\r\n\t\tif not start:\r\n\t\t\tself.running_reward += reward\r\n\t\t\tself.buffer.append_elements(\r\n\t\t\t\tnp.reshape(\r\n\t\t\t\t\tnp.array([self.last_state, self.last_action, reward, done, state]),\r\n\t\t\t\t\t[1, self.BUFFER_DIM_SIZE]\r\n\t\t\t\t)\r\n\t\t\t)\r\n\r\n\t\taction = 0\r\n\t\tif take_random_action:\r\n\t\t\taction = np.random.randint(self.ACTION_SIZE)\r\n\t\telse:\r\n\t\t\tq_dist = self.sess.run(self.agent.q_dist, feed_dict = {self.agent.input: [state], self.agent.temp: self.temp})[0]\r\n\t\t\taction_value = np.random.choice(q_dist, p = q_dist)\r\n\t\t\taction = np.argmax(q_dist == action_value)\r\n\r\n\t\tself.last_state = state\r\n\t\tself.last_action = action\r\n\t\treturn action\r\n\r\n\tdef reset(self, temp):\r\n\t\tself.temp = temp\r\n\t\tself.buffer.clear()\r\n\t\treturn","sub_path":"Reinforcement Learning on Unreal Engine/algorithms/DeepQNetworkAlgorithm/DeepQNetworkAlgorithmPlayer.py","file_name":"DeepQNetworkAlgorithmPlayer.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"391276875","text":"__all__ = [ # noqa\n 'check_access',\n 'create_thread',\n 'find_threads',\n 'get_access_token',\n 'get_threads',\n 'get_thread_members',\n 'get_thread',\n 'get_thread_view',\n 'get_thread_views',\n]\nimport logging\n\nfrom trak_utils.decorators import api_method\nfrom trak_utils.errors import NotFound\n\nfrom ..models import Thread, ThreadMember, Contact\n\nfrom .ticket import _get_ticket\nfrom .contact import _get_contact\n\n_log = logging.getLogger(__name__)\n\n\n@api_method\ndef _get_threads(ticket_pk):\n return Thread.objects.filter(ticket_id=ticket_pk)\n\n\ndef get_thread_views(ticket_pk):\n return [expand_thread(thread) for thread in get_threads(ticket_pk)] # noqa\n\n\n@api_method\ndef _find_threads(pks):\n return Thread.objects.filter(pk__in=pks)\n\n\n@api_method\ndef _get_thread_members(thread_pk):\n return Contact.objects.filter(tokens__thread_id=thread_pk)\n\n\n@api_method\ndef _get_thread(thread_pk):\n try:\n return Thread.objects.get(id=thread_pk)\n except Thread.DoesNotExist:\n raise NotFound('No thread with pk %s' % thread_pk)\n\n\ndef expand_thread(thread):\n from .message import get_message_views\n members = get_thread_members(thread.pk) # noqa\n messages = get_message_views(thread.pk)\n\n thread.update({'messages': messages,\n 'members': members})\n return thread\n\n\ndef get_thread_view(thread_pk):\n return expand_thread(get_thread(thread_pk)) # noqa\n\n\n@api_method\ndef _create_thread(ticket_pk, contact_pks):\n ticket = _get_ticket(ticket_pk)\n\n thread = Thread.objects.create(ticket=ticket)\n\n for contact_pk in contact_pks:\n ThreadMember.objects.create(thread=thread,\n contact_id=contact_pk)\n\n return thread\n\n\n@api_method\ndef _get_access_token(thread_pk, contact_email, desk=None):\n thread = _get_thread(thread_pk)\n\n if desk is None:\n ticket = _get_ticket(thread.ticket_id)\n desk = ticket.desk\n\n contact = _get_contact(desk, contact_email)\n\n try:\n access_token = ThreadMember.objects.get(thread=thread, contact=contact)\n return access_token\n except ThreadMember.DoesNotExist:\n raise NotFound('No access token for thread %s and contact %s' % (\n thread_pk, contact_email))\n\n\ndef check_access(thread_pk, token):\n thread = _get_thread(thread_pk)\n try:\n ThreadMember.objects.get(thread=thread,\n token=token)\n return True\n except ThreadMember.DoesNotExist:\n return False\n","sub_path":"src/tickets/api/thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"198588355","text":"from django.contrib import admin\r\nfrom master.models import Kecamatan\r\nfrom django.http import HttpResponse\r\nfrom django.utils.safestring import mark_safe\r\n\r\nimport json\r\n\r\ndef get_kecamatan(request):\r\n\tkecamatan_list = Kecamatan.objects.all()\r\n\r\n\tkode_kabupaten = request.POST.get('kode_kabupaten', None)\r\n\tkode_provinsi = request.POST.get('kode_provinsi', None)\r\n\r\n\tif kode_kabupaten and kode_kabupaten is not \"\" and kode_provinsi and kode_provinsi is not \"\":\r\n\t\tkecamatan_list = kecamatan_list.filter(kabupaten__kode=kode_kabupaten, kabupaten__provinsi__kode=kode_provinsi)\r\n\r\n\tid_kabupaten = request.POST.get('kabupaten', None)\t\r\n\tif id_kabupaten and not id_kabupaten is \"\":\r\n\t\tkecamatan_list = kecamatan_list.filter(kabupaten__id=id_kabupaten)\r\n\t\t\r\n\tnama_kecamatan = request.POST.get('nama_kecamatan', None)\r\n\tif nama_kecamatan and not nama_kecamatan is \"\":\r\n\t\tkecamatan_list = kecamatan_list.filter(nama_kecamatan=nama_kecamatan)\r\n\r\n\treturn kecamatan_list\r\n\r\nclass KecamatanAdmin(admin.ModelAdmin):\r\n\tlist_display = ('kode', 'nama_kecamatan','kabupaten','keterangan')\r\n\tlist_filter = ('kabupaten__provinsi','kabupaten')\r\n\tsearch_fields = ('nama_kecamatan', 'keterangan')\r\n\r\n\tdef json_kecamatan(self, request):\t\t\r\n\t\tkecamatan_list = get_kecamatan(request)\r\n\t\tresults = [ob.as_json() for ob in kecamatan_list]\r\n\t\treturn HttpResponse(json.dumps(results))\r\n\r\n\tdef option_kecamatan(self, request):\t\t\r\n\t\tkecamatan_list = get_kecamatan(request)\r\n\t\tpilihan = \"\"\r\n\t\treturn HttpResponse(mark_safe(pilihan+\"\".join(x.as_option() for x in kecamatan_list)));\r\n\r\n\tdef get_urls(self):\r\n\t\tfrom django.conf.urls import patterns, url\r\n\t\turls = super(KecamatanAdmin, self).get_urls()\r\n\t\tmy_urls = patterns('',\r\n\t\t\turl(r'^json/$', self.admin_site.admin_view(self.json_kecamatan), name='json_kecamatan'),\r\n\t\t\turl(r'^option/$', self.option_kecamatan, name='option_kecamatan'),\r\n\t\t\t)\r\n\t\treturn my_urls + urls","sub_path":"master/kecamatan_admin.py","file_name":"kecamatan_admin.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"214628532","text":"import logging\n\n# 获取logging的实例\nimport sys\n# 形成一个logger对象\nlogger=logging.getLogger(\"APPname\")\n\n# 制定logger的输出格式\nformatter=logging.Formatter(\"%(asctime)s %(levelname)-8s %(message)s\")\n\n# 文件日志\nfile_handler=logging.FileHandler(\"testLogger.log\")\nfile_handler.setFormatter(formatter)\n\n# 控制台日志\n# console_handler = logging.StreamHandler(sys.stdout)\n# console_handler.formatter = formatter # 也可以直接给formatter赋值\n\n# 指定日志的最低输出级别,默认为WARN级别\nlogger.setLevel(logging.INFO)\n\n# 把文件日志与控制台日志添加到日志处理器中\nlogger.addHandler(file_handler)\n# logger.addHandler(console_handler)\n\nif __name__=='__main__':\n logger.debug('this is debug info')\n logger.info('this is information')\n logger.warning('this is warning message')\n logger.error('this is error message')\n logger.critical('this is critical message')\n\n# CRITICAL:特别糟糕的事情,如内存耗尽、磁盘空间为空,一般很少使用\n# ERROR:发生错误时,如IO操作失败或者连接问题\n# WARNING:发生很重要的事件,但是并不是错误时,如用户登录密码错误\n# INFO:处理请求或者状态变化等日常事务\n# DEBUG:调试过程中使用DEBUG等级,如算法中每个循环的中间状态\n\n\n# 在目标程序中使用logger来采集错误信息\n# try:\n# 1 / 0\n# except:\n# # 等同于error级别,但是会额外记录当前抛出的异常堆栈信息,括号内可以提示哪个模块哪一行\n# logger.exception('this is an exception message')\n","sub_path":"面试题/异常处理/rizhi.py","file_name":"rizhi.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"378899993","text":"import xlwt\nimport glob\nimport datetime\nimport os\nimport shutil\nfrom xlrd import open_workbook\n\ncolumn_length = 5\nfillers =[0,3,1]\nfileList =[]\n\nwb = open_workbook('input.xls')\n\nfor sheet in wb.sheets() :\n for fitIN in range(4,sheet.ncols,5) :\n fitfile =[]\n for frow in range(1,sheet.nrows):\n col_value = []\n value1 = (sheet.cell(frow,fitIN-4).value)\n if value1 == '':\n break\n col_value.append(value1)\n value2 = (sheet.cell(frow,fitIN-3).value)\n col_value.append(value2)\n col_value = col_value + fillers\n fitfile.append(col_value)\n fileList.append(fitfile)\n\ncwd = os.getcwd()\n\nfor i in range(0,len(fileList)):\n if not os.path.exists(cwd + '\\\\'+'H3D2_'+str(i+1)):\n os.makedirs(cwd + '\\\\'+'H3D2_'+str(i+1))\n src_files = os.listdir(cwd+'\\\\H3D2')\n for file_name in src_files:\n full_file_name = os.path.join(cwd+'\\\\H3D2', file_name)\n if (os.path.isfile(full_file_name)):\n shutil.copy(full_file_name, cwd + '\\\\'+'H3D2_'+str(i+1))\n with open(\"FIT.IN\") as f:\n lines = f.readlines()\n length = len(fileList[i])\n lines[5] = f'{length:>7} 10 2\\n'\n lines[len(lines)-1]=lines[len(lines)-1]+'\\n'\n for frow in fileList[i]:\n txt = f'{frow[0]:>11}{frow[1]:>12}{frow[2]:>7}{frow[3]:>7}{frow[4]:>8}\\n'\n lines.append(txt)\n lines.append(\"end*** END OF INPUT FILE 'FIT.IN' **********************************\")\n with open(cwd + '\\\\'+'H3D2_'+str(i+1)+'\\\\FIT.IN', \"w\") as f1:\n f1.writelines(lines)\n f1.close()\n with open(cwd + '\\\\'+'H3D2_'+str(i+1)+'\\\\Level_01.dir', \"w\") as f1:\n f1.write(cwd + '\\\\'+'H3D2_'+str(i+1))\n f1.close()\n f.close()\n","sub_path":"Workspace/TEST/Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"263622488","text":"import rhinoscriptsyntax as rs\nimport random\nimport math\n\ncount = 0\nxcenter = 0\nycenter = 0\nzcenter = 0\n\nwhile count < 10000:\n x = random.uniform(xcenter-10,xcenter+10)\n y = random.uniform(ycenter-10,ycenter+10)\n z = random.uniform(zcenter-10,zcenter+10)\n\n point = (x,y,z)\n\n if rs.Distance(point, (0,0,0)) < 7 :\n rs.AddPoint(point)\n count = count + 1\n\nz = 0\nradius = 0\ntheta = 0\ncount = 0\nradiusChange = .001\ncountingUp = 1\n\n\nwhile z <= 100:\n if count % 2 == 0:\n x = (radius+4) * math.cos(theta)\n y = (radius+4) * math.sin(theta)\n\n else:\n x = radius * math.cos(theta)\n y = radius * math.sin(theta)\n\n rs.AddPoint(x,y,z)\n\n\n\n theta += 1\n z = z + .01\n count += 1\n\n if countingUp == 1:\n radiusChange = radiusChange * 1.001\n radius += radiusChange\n if radiusChange > .029:\n countingUp = -countingUp\n elif countingUp == -1:\n radius -= .003\n\nwhile z > 100 and z <= 150:\n if count % 2 == 0:\n x = (radius+4) * math.cos(theta)\n y = (radius+4) * math.sin(theta)\n\n else:\n x = radius * math.cos(theta)\n y = radius * math.sin(theta)\n\n rs.AddPoint(x,y,z)\n \n theta += 1\n z = z + .01\n count += 1\n\ncount = 0\nxcenter = 0\nycenter = 0\nzcenter = 150\n\nwhile count < 10000:\n x = random.uniform(xcenter-20,xcenter+20)\n y = random.uniform(ycenter-20,ycenter+20)\n z = random.uniform(zcenter-20,zcenter+20)\n\n point = (x,y,z)\n\n if rs.Distance(point, (0,0,150)) < 17 :\n rs.AddPoint(point)\n count = count + 1\n","sub_path":"Rhino Python Course/Session 2/Session2.py","file_name":"Session2.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"456690330","text":"import string\nimport xml.dom.minidom\n\n\ndef render_chart(filename, para_dict):\n p_dict,scirpt = get_config(filename)\n\n if check_parameters(p_dict, para_dict):\n t = string.Template(scirpt)\n script = t.safe_substitute(para_dict)\n return script\n else :\n exception = \"\\n请正确制定模版中的参数:\\n\"\n for (key,desc) in p_dict.items():\n exception += \"\\t{key}:{desc}\\n\".format(key=key,desc=desc)\n\n exception += \"\\n传递的参数:\\n\"\n for (key) in para_dict.keys():\n exception += \"{key},\".format(key=key)\n\n raise Exception(exception)\n\n\ndef get_config(file):\n '''\n get parameters and script information from *.etmp files\n :param file:\n :return:\n '''\n dom = xml.dom.minidom.parse(file)\n root = dom.documentElement\n p_list = root.getElementsByTagName('parameter')\n p_dict = {p.getElementsByTagName('name')[0].firstChild.data:\n p.getElementsByTagName('desc')[0].firstChild.data\n for p in p_list}\n script = root.getElementsByTagName('script')[0].firstChild.wholeText\n return p_dict,script\n\n\ndef check_parameters(p_dict, para_dict):\n '''\n check whether the given parameter sets is equal to the parameter set defined in *.etmp files\n :param p_dict: parameter sets defined in *.etmp\n :param para_dict: parmeter sets given by function caller\n :return: True if equal\n '''\n p_list = list(p_dict.keys())\n d = list(para_dict.keys())\n\n p_list.sort()\n d.sort()\n\n if p_list == d :\n return True\n else:\n return False","sub_path":"BI/Components/EChartT/Common/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"134810190","text":"import sys,os\nsys.path.insert(0, \"../tespy\")\nimport numpy as np\nimport scipy.io as sio\nimport lcdata\nfrom lcdata import get_LC_calibed as lc\nfrom lcdata import get_PR_Ti as pr\nimport calib_BA1\ncalib = calib_BA1.calib_ba1()\nimport easyplots as esp\nfrom tsdata import remove_baseline as RemoveBaseline\nmodules=['N2','M4','N3','M5','M6','N1','M8','Mx2','M3','M7','N4','M9']\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom scipy.optimize import curve_fit\nimport cPickle as pkl\nimport histogram as hist\n\nNETselectbias=[80,80,120,160,60,80,160,80,120,100,80,120,220,200,160,120,100,140,160,160,120,240,300,240]\nMAGselectbias=[200,180,200,200,240,220,260,160,180,180,300,300,440,400,380,300,240,240,320,320,300,300,640,640]\nprint('loading...')\ninfo=sio.loadmat('/home/czhang/analysispy/ba_fpdata.mat')\nd=sio.loadmat('/home/czhang/pipeline/202001magBA/reduc_data/magBA_py.mat', variable_names='bl')\nbl=d['bl'][0]\nampfit = pkl.load(open('MagAmps.pkl','r'))\nindl=info['ind']['l'][0][0][0]\nindd=info['ind']['d'][0][0][0]\nindo=info['ind']['o'][0][0][0]\nout_path = './outfig/magstat/'\nif not os.path.isdir(out_path):\n os.makedirs(out_path)\n\n#D-39*792\na0s=ampfit[0]\na1s=ampfit[1]\na2s=ampfit[2]\na3s=ampfit[3]\na4s=ampfit[4]\na5s=ampfit[5]\n\n#elnod ref\ndelnod=sio.loadmat('/home/czhang/pipeline/202001magBA/reduc_data/enBA.mat')\nelnodgain=delnod['en']['g'][0][0] #len(bl)bias*2xxxdets*4(offset, gain, gof, ?)\nelnodam =delnod['endatx'] #len(bl)*ndets*1200\nelnodfb =delnod['endaty']\nelnodel =delnod['endatel']\nbll = np.full((len(bl),33), np.nan)\n\nAcos=np.full((24,len(bl),33), np.nan)\nAcos2=np.full((24,len(bl),33), np.nan)\nAelnod=np.full((24,len(bl),33), np.nan)\n\nfor col in range(24):\n Acos[col]=2*a2s[:,col*33:(col+1)*33] #len(bl) by 33\n Acos[col,np.where(bl==40)[0], :]=[np.nan]*33\n Acos2[col]=2*a4s[:,col*33:(col+1)*33] #len(bl) by 33\n Acos2[col,np.where(bl==40)[0], :]=[np.nan]*33\n Aelnod[col]=np.full((len(bl),33),np.nan)\n for row in range(33):\n # mask out not responsive channels. condition is max elnod gain above 1000 \n if max(elnodgain[:,col*33+row, 1])<1000:\n Acos[col,:,row] = [np.nan]*len(bl)\n Acos2[col,:,row] = [np.nan]*len(bl)\n else:\n # get elnod amplitude for working channels\n for ib in range(len(bl)):\n #Aelnod[col,ib,row]=elnodgain[ib,col*33+row,1]*(np.nanmax(elnodam[ib,col*33+row,:])-np.nanmin(elnodam[ib,col*33+row,:]))*calib['FB_CAL'][0]\n Aelnod[col,ib,row]=(np.nanmax(elnodfb[ib,col*33+row,:])-np.nanmin(elnodfb[ib,col*33+row,:]))*calib['FB_CAL'][0]\n if np.isnan(Aelnod[col,ib,row]) or np.isinf(Aelnod[col,ib,row]):\n Acos[col,ib,row] = np.nan\n Acos2[col,ib,row]= np.nan\n plt.close()\n idet = np.array(range(33))\n xi, yi = np.mgrid[bl.min():bl.max():len(bl)*1j, idet.min():idet.max():33*1j]\n plt.pcolormesh(xi.T, yi.T, np.log10(abs(Aelnod[col,::-1,:])*1e12).T, vmin=1., vmax=5., cmap=\"coolwarm\")\n cbar = plt.colorbar()\n cbar.set_label(r'$log10(elnod p2p, pA)$')\n #for ic in range(2):\n # plt.axvline(x=33*ic, color='k', linestyle='--')\n # plt.axhline(y=33*ic, color='k', linestyle='--')\n #plt.text(60, 60, modules[im], fontsize=14)\n plt.axvline(x=NETselectbias[col], color='k', linestyle='--',label='bias selected by NET script')\n plt.axvline(x=MAGselectbias[col], color='k', linestyle='-',label='bias adjusted by magnetic analysis')\n plt.xlabel(\"bias, ADU\", fontsize=14)\n plt.legend()\n plt.ylabel(\"row\", fontsize=14)\n plt.title('elnod amplitude, col %d, %s'%(col, modules[int(col/2)]))\n plt.savefig(\"%scol%d_elnod.png\"%(out_path, col))\n\n plt.close()\n plt.pcolormesh(xi.T, yi.T, np.log10(abs(Acos[col,::-1,:])*1e12).T, vmin=1., vmax=5., cmap=\"coolwarm\")\n cbar = plt.colorbar()\n cbar.set_label(r'$log10(a2, pA)$')\n #for ic in range(2):\n # plt.axvline(x=33*ic, color='k', linestyle='--')\n # plt.axhline(y=33*ic, color='k', linestyle='--')\n #plt.text(60, 60, modules[im], fontsize=14)\n plt.axvline(x=NETselectbias[col], color='k', linestyle='--', label='bias selected by NET script')\n plt.axvline(x=MAGselectbias[col], color='k', linestyle='-',label='bias adjusted by magnetic analysis')\n plt.legend()\n plt.xlabel(\"bias, ADU\", fontsize=14)\n plt.ylabel(\"row\", fontsize=14)\n plt.title('azscan amplitude (mag), mode1, col %d, %s'%(col, modules[int(col/2)]))\n plt.savefig(\"%scol%d_magaz_mode1.png\"%(out_path, col))\n\n plt.close()\n plt.pcolormesh(xi.T, yi.T, np.log10(abs(Acos[col,::-1,:])/abs(Aelnod[col,::-1,:])).T, vmin=-2., vmax=0., cmap=\"coolwarm\")\n cbar = plt.colorbar()\n cbar.set_label(r'$log10(a2/elnod)$')\n #for ic in range(2):\n # plt.axvline(x=33*ic, color='k', linestyle='--')\n # plt.axhline(y=33*ic, color='k', linestyle='--')\n #plt.text(60, 60, modules[im], fontsize=14)\n plt.axvline(x=NETselectbias[col], color='k', linestyle='--', label='bias selected by NET script')\n plt.axvline(x=MAGselectbias[col], color='k', linestyle='-',label='bias adjusted by magnetic analysis')\n plt.legend()\n plt.xlabel(\"bias, ADU\", fontsize=14)\n plt.ylabel(\"row\", fontsize=14)\n plt.title('azscan amplitude (mag) mode1/elnod, col %d, %s'%(col, modules[int(col/2)]))\n plt.savefig(\"%scol%d_magaz_mode1elnodratio.png\"%(out_path, col))\n\n# do some histogram\nAcosNETbias = np.full(792,np.nan)\nAelnNETbias = np.full(792,np.nan)\nrNETbias = np.full(792,np.nan)\nAcosMAGbias = np.full(792,np.nan)\nAelnMAGbias = np.full(792,np.nan)\nrMAGbias = np.full(792,np.nan)\n\nfor col in range(24):\n for row in range(33):\n ind=np.where(~np.isnan(Acos[col,::-1,row]))[0]\n if len(ind):\n AcosNETbias[33*col+row] = np.interp(NETselectbias[col], bl[::-1][ind], abs(Acos[col,::-1,row][ind]))\n AelnNETbias[33*col+row] = np.interp(NETselectbias[col], bl[::-1][ind], abs(Aelnod[col,::-1,row][ind]))\n rNETbias[33*col+row] = np.interp(NETselectbias[col], bl[::-1][ind], abs(Acos[col,::-1,row][ind])/abs(Aelnod[col,::-1,row][ind]))\n AcosMAGbias[33*col+row] = np.interp(MAGselectbias[col], bl[::-1][ind], abs(Acos[col,::-1,row][ind]))\n AelnMAGbias[33*col+row] = np.interp(MAGselectbias[col], bl[::-1][ind], abs(Aelnod[col,::-1,row][ind]))\n rMAGbias[33*col+row] = np.interp(MAGselectbias[col], bl[::-1][ind], abs(Acos[col,::-1,row][ind])/abs(Aelnod[col,::-1,row][ind]))\n\nhist.plot_1Dhist(np.log10(AcosNETbias*1e12), out_path, 'AcosNETbias_hist',\n maintitle='azscan amplitude, bias selected by NET script',\n xlabel=r'$log_{10}(a2)$',\n xunit=r'pA',\n nbins=30,\n binrange=[1., 6.])\n\nhist.plot_1Dhist(np.log10(AelnNETbias*1e12), out_path, 'AelnodNETbias_hist',\n maintitle='elnod amplitude, bias selected by NET script',\n xlabel=r'$log_{10}(elnod, pA)$',\n xunit=r'pA',\n nbins=30,\n binrange=[1., 6.])\n\nhist.plot_1Dhist(np.log10(rNETbias), out_path, 'ratioNETbias_hist',\n maintitle='az/elnod, bias selected by NET script',\n xlabel=r'$log_{10}(az/elnod)$',\n xunit=r'pA',\n nbins=30,\n binrange=[-3., 1.])\n\nhist.plot_1Dhist(np.log10(AcosMAGbias*1e12), out_path, 'AcosMAGbias_hist',\n maintitle='azscan amplitude, bias adjusted by magnetic analysis',\n xlabel=r'$log_{10}(a2, pA)$',\n xunit=r'pA',\n nbins=30,\n binrange=[1., 6.])\n\nhist.plot_1Dhist(np.log10(AelnMAGbias*1e12), out_path, 'AelnodMAGbias_hist',\n maintitle='elnod amplitude, bias adjusted by magnetic analysis',\n xlabel=r'$log_{10}(elnod, pA)$',\n xunit=r'pA',\n nbins=30,\n binrange=[1., 6.])\n\nhist.plot_1Dhist(np.log10(rMAGbias), out_path, 'ratioMAGbias_hist',\n maintitle='az/elnod, bias adjusted by magnetic analysis',\n xlabel=r'$log_{10}(az/elnod)$',\n xunit=r'pA',\n nbins=30,\n binrange=[-3., 1.])\n","sub_path":"MagneticBA/statisticMagAmps.py","file_name":"statisticMagAmps.py","file_ext":"py","file_size_in_byte":7808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"514544140","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nModelagem em tempo real | COVID-19 no Brasil\n--------------------------------------------\n\nIdeias e modelagens desenvolvidas pela trinca:\n. Mauro Zackieiwicz\n. Luiz Antonio Tozi\n. Rubens Monteiro Luciano\n\nEsta modelagem possui as seguintes características:\n\na) NÃO seguimos modelos paramétricos => Não existem durante a epidemia dados\nsuficientes ou confiáveis para alimentar modelos epidemiológicos como a excelente\ncalaculadora http://gabgoh.github.io/COVID/index.html (ela serve para gerar cená-\nrios e para modelar a epidemia DEPOIS que ela passar). Além disso, a natureza\nexponencial das curvas as torna extremamente sensíveis aos parâmetros que a defi-\nnem. Isso faz com que a confiabilidade preditiva desses modelos seja ilusória.\n\nb) A evolução epidemia no Brasil começou depois da de outros países. Nossa mode-\nlagem se apoia nesse fato. Com os dados disponíveis, procuramos no instante pre-\nsente determinar quem estamos seguindo, ou seja, que países mais se pareceram\nconosco passado o mesmo período de disseminação. A partir do que aconteceu nesses\npaíses projetamos o que pode acontecer aqui.\n\nc) Esta conta é refeita dia a dia. Dependendo de nossa competência em conter ou\nnão a disseminação do Covid-19 nos aproximaremos dos países que melhor ou pior\nlidaram com a epidemia e a projeção refletirá essa similaridade.\n\nd) As decisões de modelagem são indicadas no código com os zoinhos: # ◔◔ {...}\nSão pontos de partida para discutir a modelagem e propor alternativas.\n\n\"\"\"\n\nimport datetime\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n# no ipython usar este comando antes de rodar => %matplotlib osx\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n\n__author__ = \"Mauro Zackiewicz\" # codigo\n__copyright__ = \"Copyright 2020\"\n__license__ = \"New BSD License\"\n__version__ = \"1.1.3\"\n__email__ = \"maurozac@gmail.com\"\n__status__ = \"Experimental\"\n\n\ndef preparar_dados(p1, p4):\n u\"\"\"Busca dados e organiza tabela \"data\" com os dados de referência para a\n modelagem.\n Fontes:\n . Mundo: https://covid.ourworldindata.org\n . Brasil: https://brasil.io\n\n Retorna:\n raw | Série completa do número de mortes/dia por país, sem trans-\n posição temporal\n inicio | Referência dos indexes em raw para justapor o início das\n curvas dos diferentes países\n data | Série de número de mortes/dia por país trazendo para o\n zero (index 0) o primeiro dia em que ocorrem pelo menos p1 mortes\n (ver macro parâmetros). Isto reduz a quantidade de países para o grupo\n que está à frente ou pareado ao Brazil. A partir do index 0 é possível\n comparar a evolução dos casos entre os países.\n nbr | Número de dias da série de dados para o Brasil\n popu: | População dos países para depois calcular a taxa de mortes\n por 100 mil habitantes\n popuBR: | População dos recortes dentro do Brasil\n por100k: | Mortes por 100 mil hab brasil\n\n \"\"\"\n # ◔◔ {usamos as mortes diárias por parecer ser o dado mais confiável}\n raw = pd.read_csv(\"https://covid.ourworldindata.org/data/ecdc/new_deaths.csv\").fillna(0.0)\n # ◔◔ {o link abaixo carrega o acumulado de mortes, não usamos pq a soma vai alisando a série}\n # raw = pd.read_csv(\"https://covid.ourworldindata.org/data/ecdc/total_deaths.csv\").fillna(0.0)\n # tempo = raw['date'] # ◔◔ {não usamos as datas}\n raw = raw.drop(columns='date')\n\n # dados da população mundo\n popu = pd.read_csv(\"https://covid.ourworldindata.org/data/ecdc/locations.csv\").set_index('countriesAndTerritories')\n popu[\"paises\"] = [_.replace('_', ' ').replace('United States of America', 'United States') for _ in popu.index]\n popu = popu.set_index(\"paises\")\n\n # dados Brasil\n # ◔◔ {já baixamos filtrado para SP, mas pode se usar outros estados}\n sp = pd.read_csv(\"https://brasil.io/dataset/covid19/caso?state=SP&format=csv\")\n\n # contruir base para a tabela \"data\"\n inicio = raw.ge(p1).idxmax() # ◔◔ {encontra os index de qdo cada pais alcança 3}\n data = pd.DataFrame({'Brazil':raw['Brazil'][inicio['Brazil']:] * p4}).reset_index().drop(columns='index')\n nbr = data.shape[0]\n\n # adicionar dados de SP\n sp_estado = sp.loc[lambda df: df['place_type'] == \"state\", :]\n SP_estado = list(sp_estado['deaths'].head(nbr + 1).fillna(0.0))\n SP_estado = [SP_estado[i] - SP_estado[i+1] for i in range(len(SP_estado)-1)]\n SP_estado.reverse()\n SP_estado_popu = sp_estado['estimated_population_2019'].max() # 45919049\n data['SP'] = pd.Series(SP_estado).values * p4\n\n # adicionar dados da cidade de SP\n sp_city = sp.loc[lambda df: df['city'] == u\"São Paulo\", :]\n SP_city = list(sp_city['deaths'].head(nbr + 1).fillna(0.0))\n SP_city = [SP_city[i] - SP_city[i+1] for i in range(len(SP_city)-1)]\n SP_city.reverse()\n SP_city_popu = sp_city['estimated_population_2019'].max() # 12252023\n data['SP_City'] = pd.Series(SP_city).values * p4\n\n # adicionar dados do Brasil sem SP\n br_ex_sp = [x[0]-x[1] for x in zip(list(data['Brazil']), SP_estado)]\n data['Brazil_sem_SP'] = pd.Series(br_ex_sp).values\n\n # adicionar dados dos países à frente ou pareados ao Brasil\n for k in inicio.keys():\n if k == \"Brazil\": continue\n if k not in popu.index: continue\n if inicio[k] == 0 or inicio[k] > inicio[\"Brazil\"]: continue\n C = raw[k][inicio[k]:inicio[k]+nbr]\n data[k] = C.values\n\n # preparar dict com dados da população Brasil\n popuBR = {\n 'Brazil': popu['population']['Brazil'],\n 'SP': SP_estado_popu,\n 'SP_City': SP_city_popu,\n 'Brazil_sem_SP': popu['population']['Brazil'] - SP_estado_popu,\n }\n\n # dados normalizados por 100 mil hab. para Brasil\n por100k = {\n 'Brazil': data['Brazil'].values * (10**5) / popuBR['Brazil'],\n 'SP': data['SP'].values * (10**5) / popuBR['SP'],\n 'SP_City': data['SP_City'].values * (10**5) / popuBR['SP_City'],\n 'Brazil_sem_SP': data['Brazil_sem_SP'].values * (10**5) / popuBR['Brazil_sem_SP'],\n }\n\n return raw, inicio, data, nbr, popu, popuBR, por100k\n\n\ndef rodar_modelo(raw, inicio, data, nbr, popu, popuBR, por100k, p2, p3, ref):\n \"\"\"\n Usa os dados preparados para gerar dados para visualização e a projeção da\n evoluação da epidemia.\n\n Retorna:\n correlacionados : Países mais correlacionados, usados para a projeção\n calibrados : Série alisada de mortes por 100 mil hab por dia com\n dados de ref e países correlacionados\n projetado : Série estimada para a evoluação da epidemia em ref\n infos : informações sobre o pico estimado da epidemia\n\n \"\"\"\n\n # ◔◔ {Optamos por não alisar dados antes de calcular a correlação. Sabemos\n # que a qualidade do report dos dados é variável, mas assumimos que o ruído\n # é aleatório e por isso não é preciso alisar para que a correlação seja\n # válida. Ao contrário, a correlação \"bruta\" seria a mais verossível}\n\n # ◔◔ {mas caso você ache que vale a pena alisar antes, use o codigo abaixo}\n # alisamento para os casos de morte reportados (média móvel)\n # data = data.rolling(5).mean()\n\n # calcular a matriz de correlações:\n pearson = data.corr()\n # ◔◔ {o default do método usa a correlação de Pearson, cf. ref abaixo}\n # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html\n\n # ◔◔ {se quiser ver as prévias ...}\n # print(pearson['Brazil'].sort_values(ascending=False))\n # print(pearson['Brazil_sem_SP'].sort_values(ascending=False))\n # print(pearson['SP'].sort_values(ascending=False))\n # print(pearson['SP_City'].sort_values(ascending=False))\n\n # ◔◔ { não incluir os casos locais para evitar endogeneidade}\n out = ['Brazil', 'Brazil_sem_SP', 'SP', 'SP_City',] # nao misturar com os demais cortes locais\n\n # selecionar os p2 países que melhor se correlacionam com a ref\n correlacionados = [_ for _ in pearson[ref].sort_values(ascending=False).keys() if _ not in out][:p2]\n\n # ◔◔ {para a visualização gráfica os dados são normalizados para a mesma\n # taxa: mortes por 100 mil habitantes}\n\n # ◔◔ {usar a populacao da China distorce demais: a pop da cidade de wuhan\n # é de 11 milhões e da província de Hubei é de 58 milhões, usamos 15 milhões\n # como valor aproximado}\n\n # criar tabela normalizada, começa com dados da ref\n calibrados = pd.DataFrame({ref:por100k[ref]})\n\n # preencher com os dados normalizados dos países correlacionados\n for k in correlacionados:\n # ◔◔ {pega os dados em raw pq agora usaremos todos os dados disponíveis para o país}\n C = raw[k][inicio[k]:]\n if k == \"China\":\n # ◔◔ {correcao para a popu aproximada do foco: 15 milhões}\n additional = pd.DataFrame({k: C.values * (10**5) / 15000000})\n else:\n additional = pd.DataFrame({k: C.values * (10**5) / popu['population'][k]}) # array\n calibrados = pd.concat([calibrados, additional], axis=1)\n\n # ◔◔ {aqui usamos um alisamento p3 de dias para deixar a visualização melhor}\n calibrados = calibrados.rolling(p3).mean()\n\n # ◔◔ {a projeção usa os dados alisados}\n # ◔◔ {como é feita a projeção:\n # 1. cada país correlacionado terá um peso, proporcianal a quanto se correlaciona\n # .. soma dos pesos = 1\n # .. quanto mais correlacionado, maior o peso }\n pesos = [pearson[ref][c] for c in correlacionados] # melhor corr pesa mais\n pesos = [pesos[i]/sum(pesos) for i in range(len(pesos))] # pesos normalizados\n pesos = dict(zip(correlacionados, pesos)) # num dict para facilitar\n\n # proj : vai ter ao final o tamanho da maior serie em calibrados\n proj = [np.nan for _ in range(nbr)] # começa com nan onde já temos os dados da ref\n proj[-1] = calibrados[ref][nbr - 1] # primeiro valor coincide com último de ref\n # será a partir daí que começa a projeção\n\n # ◔◔ {a projeção segue dia a dia as variações dos países correlacionado}\n for d in range(nbr, calibrados.shape[0]):\n x = 0 # incremento estimado para o dia\n for c in correlacionados:\n if not np.isnan(calibrados[c][d]):\n # adiciona o incremento % do país ponderado por seu peso\n x += (calibrados[c][d]/calibrados[c][d-1]) * pesos[c]\n else:\n # ◔◔ {qdo acabam os dados de um país ele pára de influenciar a taxa}\n x += 1 * pesos[c]\n # print(d, c, x)\n # a série da projeção é construída aplicando o incremento estimado ao dia anterior\n proj.append(proj[-1] * x)\n\n # projetado \n projetado = np.array(proj)\n\n # ◔◔ {informações adicionais}\n # pico => valor máximo da série projetada\n pico = np.nan_to_num(projetado).max() # float\n # mortes abs => reverte para valor absoluto de mortes\n mortes_no_pico = str(int(pico * popuBR[ref]/100000)) # str\n # dia em que acontece o pico\n ix_do_pico = proj.index(np.nan_to_num(projetado).max()) # int => index\n dia_do_pico = str(datetime.datetime.now() + datetime.timedelta(days=ix_do_pico-nbr))[:10] # str\n # consolidado para output\n infos = {\n \"mortes_no_pico\": mortes_no_pico,\n \"dia_do_pico\": dia_do_pico,\n \"pico\": pico,\n \"index\": ix_do_pico,\n }\n\n return correlacionados, calibrados, projetado, infos\n\n\ndef gerar_grafico(correlacionados, calibrados, projetado, infos):\n \"\"\"\n Paleta: https://encycolorpedia.com/\n #1f78b4 base: azul #7ba3cd white shade\n #111111 branco\n #ff003f vermelho #ff7c7a white shade\n #000000 preto\n \"\"\"\n fig, ax = plt.subplots()\n hoje = str(datetime.datetime.now())[:16]\n ax.set_title(u\"Evolução da Covid-19 | \" + ref + \" | \" + hoje, fontsize=10)\n ax.set_xlabel(u'Dias desde ' + str(p1) + ' primeiras mortes', fontsize=8)\n ax.set_xlim(0, calibrados.shape[0]+20)\n ax.set_ylabel(u'Mortes diárias por 100 mil habitantes', fontsize=8)\n for c in correlacionados:\n ax.plot(calibrados[c], linewidth=3, color=\"#ff7c7a\")\n lvi = calibrados[c].last_valid_index()\n if c == \"China\": nome = \"Wuhan\"\n else: nome = c\n ax.text(lvi+1, calibrados[c][lvi], nome, fontsize=6, verticalalignment=\"center\")\n ax.plot(calibrados[ref], linewidth=3, color=\"#1f78b4\")\n ax.plot(projetado, linewidth=2, linestyle=\":\", color=\"#1f78b4\")\n lvi = pd.Series(projetado).last_valid_index()\n ax.text(lvi+1, projetado[lvi], ref, fontsize=6, verticalalignment=\"center\")\n # ax.legend(calibrados, fontsize=8)\n ax.plot(infos[\"index\"], infos[\"pico\"], '^', markersize=6.0, color=\"#1f78b4\")\n msg = \"PICO ~\" + infos[\"mortes_no_pico\"] + \" mortes em \" + infos[\"dia_do_pico\"]\n ax.text(infos[\"index\"]-2, infos[\"pico\"]*1.2, msg, fontsize=8, color=\"#1f78b4\")\n fig.text(0.99, 0.01, u'M.Zac | L.Tozi | R.Luciano', family=\"monospace\", fontsize='6', color='gray', horizontalalignment='right')\n\n######################### R O D A R #######################################\n\n# Macro parâmetros\np1 = 3 # mortes no dia para iniciar série\np2 = 5 # número de países mais correlacionados\np3 = 7 # alisamento para o gráfico (média móvel)\np4 = 1.48 # correcao por subnotificacao nos dados brasileiros\n# ◔◔ {ref: https://noticias.uol.com.br/saude/ultimas-noticias/redacao/2020/04/09/covid-19-declaracoes-de-obito-apontam-48-mais-mortes-do-que-dado-oficial.htm}\nref = \"SP_City\" # escolher um entre: \"SP_City\", \"SP\", \"Brazil\", \"Brazil_sem_SP\"\n\nraw, inicio, data, nbr, popu, popuBR, por100k = preparar_dados(p1, p4)\ncorrelacionados, calibrados, projetado, infos = rodar_modelo(raw, inicio, data, nbr, popu, popuBR, por100k, p2, p3, ref)\ngerar_grafico(correlacionados, calibrados, projetado, infos)\n","sub_path":"compara.py","file_name":"compara.py","file_ext":"py","file_size_in_byte":14120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"210890012","text":"# this gui only loads dummy scripts and instruments\n\nimport sys\nfrom src.core import qt_b26_gui\n\nfrom PyQt4 import QtGui\n\napp = QtGui.QApplication(sys.argv)\n\n\n\ninstruments = {'inst_dummy': 'DummyInstrument'}\n\nscripts= {\n\n\n 'counter': 'ScriptDummy',\n\n\n 'dummy script with inst': {\n 'script_class': 'ScriptDummyWithInstrument',\n 'instruments': {'dummy_instrument': 'inst_dummy'}\n },\n\n 'QT counter' : 'ScriptDummyWithQtSignal',\n\n 'dummy script with sub script': {\n 'script_class': 'ScriptDummyWithSubScript',\n 'scripts': {'sub_script': 'ScriptDummy'}\n # {\n # 'script_class': 'ScriptDummy',\n # 'instruments': {'dummy_instrument': 'inst_dummy'}\n # }\n }\n\n}\n\n# {\"zihf2\": \"ZIHF2\", \"inst\": 'INST'} => param = {\"zihf2\": &ZIHF2, 'inst': &sacbs;}\n\n# Zi_Sweeper(*param)\n\nprobes = {\n 'random': {'probe_name': 'value1', 'instrument_name': 'inst_dummy'},\n 'value2': {'probe_name': 'value2', 'instrument_name': 'inst_dummy'},\n }\n\nsettings_file = \"Z:\\Lab\\Cantilever\\Measurements\\\\tmp_\\\\a\"\n\nex = qt_b26_gui.ControlMainWindow(settings_file)\n# ex = qt_b26_gui.ControlMainWindow(instruments, scripts, probes)\nex.show()\nex.raise_()\nsys.exit(app.exec_())\n","sub_path":"src/gui/gui_test_with_dummy.py","file_name":"gui_test_with_dummy.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"44106720","text":"from src.discrete import Environment\nfrom src.components import Car, StreetGraph, EuclideanNode\nimport matplotlib.pyplot as plt\nimport math\nimport imageio \n\n\n\"\"\"Vehicle Simulations\"\"\"\n\n\ndef drawNodes(i, xlist, ylist, r):\n carx = xlist[i]\n cary = ylist[i]\n for j in range(len(xlist)):\n if i == j:\n continue\n deltaX = carx - xlist[j]\n deltaY = cary - ylist[j]\n dist = math.sqrt(deltaX**2 + deltaY**2)\n if dist <= r:\n plt.plot([carx, xlist[j]], [cary, ylist[j]] ,'r')\n xavg = (carx + xlist[j])/2\n yavg = (cary + ylist[j])/2\n plt.text(xavg,yavg, r'' + str(round(dist,2)))\n else:\n pass\n return\n\n\ndef setLinkLife(sGraph):\n\t# Sets Link Life of car (edges)\n\tassert isinstance(sGraph, StreetGraph)\n\tfor c in sGraph._cars:\n\t\tc.resetLink()\n\t\tx, y = c.position()\n\t\tfor ci in sGraph._cars:\n\t\t\txi, yi = ci.position()\n\t\t\tdX = x - xi\n\t\t\tdY = y - yi\n\t\t\tdist = math.sqrt(dX**2 + dY**2)\n\t\t\tif (c == ci) | (dist > c.getRad()):\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tlinkVal = detLinkLife(c, ci, sGraph)\n\t\t\t\tc.setLinkLife(ci, linkVal)\n\t\t\t\t#printout = c.getLinkLife(ci)\n\t\t\t\t#print(printout)\n\n\ndef getVel(car, sGraph):\n\tx, y = car.position()\n\tsp = car.getSpeed()\n\tdest_x, dest_y = sGraph.get_xy_coords(car.getNextNode())\n\tvx1 = dest_x - x\n\tvy1 = dest_y - y\n\tvnorm1 = math.sqrt(vx^2 + vy^2)\n\tvel_x = vx / vnorm1 * sp\n\tvel_y = vy / vnorm1 * sp\n\treturn vel_x, vel_y\n\ndef quadratic(a, b, c):\n d = (b**2) - (4*a*c)\n sol1 = (-b-sqrt(d))/(2*a)\n sol2 = (-b+sqrt(d))/(2*a)\n return sol1, sol2\n\ndef detLinkLife(car1, car2, sGraph):\n a_x, a_y = car1.position()\n b_x, b_y = car2.position()\n av_x, av_y = getVel(A, sGraph)\n bv_x, bv_y = getVel(B, sGraph)\n a = a_x - b_x\n b = a_y - b_y\n c = av_x - bv_x\n d = av_x - bv_y\n \n c_0 = a^2 + b^2 - car1.getRad()^2\n c_1 = 2*a*c + 2*b*d\n c_2 = c^2 + d^2\n \n try:\n return max(quadratic(c_2, c_1, c_0))\n except ZeroDivisionError:\n return inf\n\t#return linkVal\n\n\t\n#plt.plot(x, y, 'bo')\n\n#ALL THIS NEEDS TO BE IN EVERY PLOT\n#GRAPHSIZE = 10\n#ticks = range(0, GRAPHSIZE + 1)\n#x = [1,6,8,1,0,3,6,3,5]\n#y = [1,3,5,6,2,7,0,3,1]\n#plt.hold(True)\n\n#plt.grid(b = True)\n#plt.xticks(ticks)\n#plt.yticks(ticks)\n#plt.xlim(0, GRAPHSIZE)\n#plt.ylim(0, GRAPHSIZE)\n#drawNodes(4, x, y, 6)\n\n\n#Testing Car Unit \ng = StreetGraph()\ng.add_node(3, 0, 'A')\ng.add_node(2, 12, 'B')\ng.add_node(4, 7, 'C')\ng.add_edge('A', 'B', 10)\ng.add_edge('C', 'B', 10)\n\nferrari = Car('A', 'B', 'ferrari', g, 1.25, 6)\ntoyota = Car('A', 'B', 'toyota', g, 1, 6)\nhonda = Car('C' , 'B', 'honda', g, .6, 6)\ng.add_car(ferrari)\ng.add_car(toyota)\ng.add_car(honda)\n# ferrari = g.add_car('A', 'B', 'One fast car', 0.5)\n# f2 = g.add_car('A', 'B', 'blah2', 1)\n\nnumIter = 6 #number of driving iterations\nGRAPHSIZE = 15\nimages = []\n\nfor i in range(numIter):\n plt.figure(i)\n ticks = range(0, GRAPHSIZE + 1)\n plt.hold(True)\n plt.grid(b = True)\n plt.xticks(ticks)\n plt.yticks(ticks)\n plt.xlim(0, GRAPHSIZE)\n plt.ylim(0, GRAPHSIZE)\n\n xlist = []\n ylist = []\n\n for c in g._cars:\n x, y = c.position()\n xlist.append(x)\n ylist.append(y)\n plt.plot(x, y, 'bo')\n drawNodes(0, xlist,ylist, c.getRad())\n c.drive()\n\n filename = 'fig' + str(i) + '.png'\n plt.savefig(filename)\n images.append(imageio.imread(filename))\n\nsetLinkLife(g)\nexportname = \"movie.gif\"\nkargs = { 'duration': 2 }\nimageio.mimsave(exportname, images, 'GIF', **kargs)\n\n\n \n\n\n\n\n\n\n\n\n\n","sub_path":"visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"86574773","text":"import functools\n\nfrom flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for\n)\n\nimport flask\nfrom . import api_bp\nimport fwitter\nimport requests\nfrom fwitter.util.encrypt import hash_password\nimport pdb\n\n@api_bp.route('/tweet', methods=['GET', 'POST', 'PATCH', 'DELETE'])\ndef tweet():\n \"\"\"Get a tweet from the database, or post a new one\"\"\"\n if 'username' not in flask.session:\n if flask.request.method != 'GET':\n flask.abort(403)\n\n request_data = flask.request.get_json()\n\n if not request_data and flask.request.method != 'GET':\n flask.abort(403)\n\n db = fwitter.db.get_db()\n cur = db.cursor()\n context = {}\n\n if flask.request.method == 'GET':\n if len(flask.request.args) == 0:\n flask.abort(403)\n \n args = flask.request.args.to_dict()\n\n if 'tweetid' not in args:\n flask.abort(404)\n\n cur.execute('SELECT * FROM tweets WHERE tweetid=\"{}\"'.format(args['tweetid']))\n tweet = cur.fetchone()\n \n # Tweet not found\n if tweet == None:\n flask.abort(404)\n \n context['originalOwner'] = tweet[0] \n context['body'] = tweet[1] \n context['tweetid'] = tweet[2] \n context['created'] = tweet[3] \n context['owner'] = tweet[4] \n context['likes'] = tweet[5]\n\n return flask.jsonify(**context), 200 \n elif flask.request.method == 'POST':\n # Cannot specify both body and id\n if 'body' in request_data and 'id' in request_data:\n flask.abort(403)\n \n if len(request_data) > 1:\n flask.abort(403)\n\n # Normal new tweet\n if 'body' in request_data:\n cur.execute('SELECT count(*) FROM tweets')\n tweetid = int(cur.fetchone()[0]) + 1\n \n cur.execute('''INSERT INTO tweets(body, tweetid, owner, originalOwner) VALUES\n ('{}', '{}', '{}', '{}')'''.format(request_data['body'], tweetid,\n flask.session['username'],\n flask.session['username']))\n \n return {}, 201\n elif 'id' in request_data:\n # Retweet\n\n tweetid = request_data['id']\n\n cur.execute('SELECT * FROM tweets WHERE tweetid=\"{}\"'.format(tweetid))\n tweet = cur.fetchone()\n \n # Tweet not found\n if tweet == None:\n flask.abort(404)\n \n context['originalOwner'] = tweet[0] \n context['body'] = tweet[1] \n context['created'] = tweet[3] \n context['owner'] = tweet[4] \n context['likes'] = tweet[5]\n\n # Determine new tweetid\n cur.execute('SELECT count(*) FROM tweets')\n context['tweetid'] = int(cur.fetchone()[0]) + 1\n\n cur.execute('''INSERT INTO tweets(body, tweetid, owner, originalOwner) VALUES\n ('{}', '{}', '{}', '{}')'''.format(context['body'], context['tweetid'],\n flask.session['username'],\n context['originalOwner']))\n\n return {}, 201\n else:\n flask.abort(403)\n elif flask.request.method == 'PATCH':\n if 'tweetid' not in request_data:\n flask.abort(403)\n \n if len(request_data) > 1:\n flask.abort(403)\n\n # Check if like had already been made\n cur.execute(\"SELECT * FROM likes WHERE tweetid='{}' and owner='{}'\".format(request_data['tweetid'], flask.session['username']))\n data_check = cur.fetchall()\n\n if len(data_check) > 0:\n flask.abort(403)\n \n cur.execute('SELECT * FROM tweets WHERE tweetid=\"{}\"'.format(request_data['tweetid']))\n tweet = cur.fetchone()\n # Tweet not found\n if tweet == None:\n flask.abort(404)\n\n context['tweetid'] = tweet[0]\n context['originalOwner'] = tweet[0] \n context['body'] = tweet[1] \n context['created'] = tweet[3] \n context['owner'] = tweet[4] \n context['likes'] = str(int(tweet[5]) + 1)\n\n cur.execute('DELETE FROM tweets WHERE tweetid=\"{}\"'.format(request_data['tweetid']))\n\n cur.execute('''INSERT INTO tweets(body, tweetid, owner, originalOwner, likes) VALUES\n ('{}', '{}', '{}', '{}', '{}')'''.format(context['body'],\n request_data['tweetid'],\n flask.session['username'],\n context['originalOwner'],\n context['likes']))\n \n cur.execute('''INSERT INTO likes(tweetid, owner) VALUES ('{}', '{}')'''.format(request_data['tweetid'], flask.session['username']))\n\n return {}, 202\n elif flask.request.method == 'DELETE':\n if 'tweetid' in request_data and 'like_tweetid' in request_data:\n flask.abort(403)\n \n if len(request_data) > 1:\n flask.abort(403)\n\n if 'tweetid' in request_data:\n cur.execute('SELECT * FROM tweets WHERE tweetid=\"{}\"'.format(request_data['tweetid']))\n tweet = cur.fetchone()\n # Tweet not found\n if tweet == None:\n flask.abort(404)\n\n if flask.session['username'] != tweet[4]:\n flask.abort(403)\n\n cur.execute('DELETE FROM tweets WHERE tweetid=\"{}\"'.format(request_data['tweetid']))\n\n return {}, 204\n if 'like_tweetid' in request_data:\n\n cur.execute(\"SELECT * FROM likes WHERE tweetid='{}' AND owner='{}'\".format(request_data['like_tweetid'], flask.session['username']))\n like = cur.fetchone()\n # Lik not found\n if like == None:\n flask.abort(404)\n\n cur.execute(\"DELETE FROM likes WHERE tweetid='{}' AND owner='{}'\".format(request_data['like_tweetid'], flask.session['username']))\n\n return {}, 204\n\n flask.abort(403)\n else:\n flask.abort(403)","sub_path":"fwitter/api/tweet.py","file_name":"tweet.py","file_ext":"py","file_size_in_byte":6276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"166378588","text":"import socket\nimport sys\n\nHOST = 'ZhangYihandeMBP.attlocal.net' # The remote host\nPORT = 8888 # The same port as used by the server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST, PORT))\nwhile 1:\n w = raw_input()\n s.send(w)\ns.close()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"339013732","text":"import pygame\n\npygame.init() #초기화 (반드기 필요)\n\n#화면 크기 설정\nscreen_width = 480\nscreen_height = 640\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\n#화면 타이틀 설정\npygame.display.set_caption(\"나노 게임\") #게임 이름\n\n#FPS\nclock = pygame.time.Clock()\n\n#배경 이미지 불러오기\nbackground = pygame.image.load(\"C:/Users/rogil/Documents/Python_practice/Python-practise/pygame_basic/background.png\")\n\n\n#캐릭터(스프라이트) 불러오기\ncharacter = pygame.image.load(\"C:/Users/rogil/Documents/Python_practice/Python-practise/pygame_basic/character.png\")\ncharacter_size = character.get_rect().size #이미지 크기를 구해옴\ncharacter_width = character_size[0]\ncharacter_height = character_size[1]\ncharacter_x_pos = (screen_width / 2) - (character_width /2) #화면 가로의 절반 크기에 해당하는 곳에 위치\ncharacter_y_pos = screen_height - character_height #화면 세로 크기 가장 아래에 해당하는 곳에 위치\n\n#이동할 좌표\nto_x = 0\nto_y = 0\n\n#이동 속도\ncharacter_speed = 0.6\n\n\n#적 캐릭터\nenemy = pygame.image.load(\"C:/Users/rogil/Documents/Python_practice/Python-practise/pygame_basic/enemy.png\")\nenemy_size = enemy.get_rect().size #이미지 크기를 구해옴\nenemy_width = enemy_size[0]\nenemy_height = enemy_size[1]\nenemy_x_pos = (screen_width / 2) - (enemy_width /2) #화면 가로의 절반 크기에 해당하는 곳에 위치\nenemy_y_pos = (screen_height / 2)- (enemy_height / 2) #화면 세로 크기 가장 아래에 해당하는 곳에 위치\n\n\n#폰트 정의\ngame_font = pygame.font.Font(None, 40) #폰트 객체 생성 (폰트, 크기)\n\n#총 시간\ntotal_time = 10\n\n#시간 계산\nstart_ticks = pygame.time.get_ticks() #시작 틱을 받아옴\n\n\n#이벤트 루프\nrunning = True #게임이 진행중인가?\nwhile running:\n dt = clock.tick(60) #게임화면 초당 프레임 수 설정\n\n for event in pygame.event.get(): #어떤 이벤트가 발생하였는가?\n if event.type == pygame.QUIT: #창이 닫히는 이벤트가 발생하였는가?\n running = False #게임이 진행중이 아님\n\n if event.type == pygame.KEYDOWN: #키가 눌렸는지 확인\n if event.key == pygame.K_LEFT:\n to_x -= character_speed #'to_x = to_x -5'랑 같은 의미\n elif event.key == pygame.K_RIGHT:\n to_x += character_speed\n elif event.key == pygame.K_UP:\n to_y -= character_speed\n elif event.key == pygame.K_DOWN:\n to_y += character_speed\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n to_x = 0\n elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n to_y = 0\n\n character_x_pos += to_x * dt\n character_y_pos += to_y * dt\n \n #가로 경계값 처리\n if character_x_pos < 0:\n character_x_pos = 0\n elif character_x_pos > screen_width - character_width:\n character_x_pos = screen_width - character_width\n \n\n #세로 경계값 처리\n if character_y_pos < 0:\n character_y_pos = 0\n elif character_y_pos > screen_height - character_height:\n character_y_pos = screen_height - character_height\n\n #충돌처리를 위한 rect 정보 업데이트\n character_rect = character.get_rect()\n character_rect.left = character_x_pos\n character_rect.top = character_y_pos\n\n enemy_rect = enemy.get_rect()\n enemy_rect.left = enemy_x_pos\n enemy_rect.top = enemy_y_pos\n\n #충돌 체크\n if character_rect.colliderect(enemy_rect):\n print(\"충돌 했어요\")\n running = False\n\n\n screen.blit(background, (0,0)) #배경 그리기\n\n screen.blit(character, (character_x_pos, character_y_pos)) #캐릭터 그리기\n\n screen.blit(enemy, (enemy_x_pos, enemy_y_pos))\n\n #타이머 집어널기\n #경과 시간 계산\n elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 #경과 시간(ms)을 1000으로 나눠서 초 단위로 표시\n\n timer = game_font.render(str(int(total_time - elapsed_time)), True, (255, 255, 255)) #출력할 글자, True, 글자 색상\n screen.blit(timer, (10, 10))\n\n #만약 시간이 0 이하이면 게임 종료\n if total_time - elapsed_time <=0:\n print(\"타임 아웃\")\n running = False\n\n pygame.display.update() #게임화면을 다시 그리기!\n\n#잠시 대기\npygame.tim.delay(2000) #2초 대기 (ms)\n\n\n\n\n#pygame 종료\npygame.quit()","sub_path":"pygame_basic/7_text.py","file_name":"7_text.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"223690731","text":"'''\n@Author: zhaoyang.liang\n@Github: https://github.com/LzyRapx\n@Date: 2020-01-20 21:28:52\n'''\nclass Solution:\n def canThreePartsEqualSum(self, A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n s = sum(A)\n if s % 3 != 0:\n return False\n target = s // 3\n \n preSum = [0 for _ in range(len(A))]\n for i in range(len(A)):\n if i == 0:\n preSum[i] = A[i]\n else:\n preSum[i] = preSum[i - 1] + A[i]\n \n for i in range(len(A) - 2):\n if preSum[i] == target:\n for j in range(i + 1, len(A) - 1):\n if(preSum[j] - preSum[i] == target):\n return True\n return False\n ","sub_path":"LeetCode/Easy/1013.py","file_name":"1013.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"258670083","text":"'''\nLock版本的生产者与消费者模式可以正常的运行。\n但是存在一个不足,在消费者中,总是通过while True死循环并且上锁的方式去判断钱够不够。\n上锁是一个很耗费CPU资源的行为。因此这种方式不是最好的。\n还有一种更好的方式便是使用threading.Condition来实现。\nthreading.Condition可以在没有数据的时候处于阻塞等待状态。\n一旦有合适的数据了,还可以使用notify相关的函数来通知其他处于等待状态的线程。\n这样就可以不用做一些无用的上锁和解锁的操作。可以提高程序的性能。\n首先对threading.Condition相关的函数做个介绍,threading.Condition类似threading.Lock,\n可以在修改全局数据的时候进行上锁,也可以在修改完毕后进行解锁。以下将一些常用的函数做个简单的介绍:\n1. acquire:上锁。\n2. release:解锁。\n3. wait:将当前线程处于等待状态,并且会释放锁。可以被其他线程使用notify和notify_all函数唤醒。被唤醒后会继续等待上锁,上锁后继续执行下面的代码。\n4. notify:通知某个正在等待的线程,默认是第1个等待的线程。\n5. notify_all:通知所有正在等待的线程。notify和notify_all不会释放锁。并且需要在release之前调用。\n\n\n'''\n\nimport threading\nimport random\nimport time\n\ngMoney = 0\ngCondition = threading.Condition()\ngTimes = 0\n\n\nclass Producer(threading.Thread):\n\tdef run(self) -> None:\n\t\tglobal gMoney\n\t\tglobal gTimes\n\t\twhile True:\n\t\t\tgCondition.acquire()\n\t\t\tif gTimes >= 10:\n\t\t\t\tgCondition.release()\n\t\t\t\tbreak\n\t\t\tmoney = random.randint(0, 100)\n\t\t\tgMoney += money\n\t\t\tgTimes += 1\n\t\t\tprint(\"%s生产了%d元钱,剩余%d元钱\" % (threading.current_thread().name, money, gMoney))\n\t\t\tgCondition.notify_all()\n\t\t\tgCondition.release()\n\t\t\ttime.sleep(1)\n\n\nclass Consumer(threading.Thread):\n\tdef run(self) -> None:\n\t\tglobal gMoney\n\t\twhile True:\n\t\t\tgCondition.acquire()\n\t\t\tmoney = random.randint(0, 100)\n\t\t\twhile gMoney < money:\n\t\t\t\tif gTimes >= 10:\n\t\t\t\t\tprint(\"%s想消费%d元钱,但是余额只有%d元钱了,并且生产者已经不再生产了!\" % (threading.current_thread().name, money, gMoney))\n\t\t\t\t\tgCondition.release()\n\t\t\t\t\treturn # 函数直接返回,break只能退出一层循环\n\t\t\t\tprint(\"%s想消费%d元钱,但是余额只有%d元钱了,消费失败!\" % (threading.current_thread().name, money, gMoney))\n\t\t\t\tgCondition.wait()\n\t\t\tgMoney -= money\n\t\t\tprint(\"%s消费了%d元钱,剩余%d元钱\" % (threading.current_thread().name, money, gMoney))\n\t\t\tgCondition.release()\n\t\t\ttime.sleep(1)\n\n\ndef main():\n\tfor x in range(5):\n\t\tth = Producer(name=\"生产者%d号\" % x)\n\t\tth.start()\n\n\tfor x in range(5):\n\t\tth = Consumer(name=\"消费者%d号\" % x)\n\t\tth.start()\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"5.多线程爬虫/5.生产者与消费者Condition版.py","file_name":"5.生产者与消费者Condition版.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"491593767","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import linalg as la\n\n\ndef Make_B_List(invexpdtK, expVData):\n '''Make list of off-diagonal matrices in matrix O. deriv. Eq. (20)\n \n Args:\n expVData, (N,L) matrix, each column reps a (N,N) diagonal mat\n \n Returns:\n python list of (N,N) matrices.'''\n \n _,L = expVData.shape\n B_list = [];\n for j in range(L):\n Bmat = invexpdtK*expVData[:,j]\n #note negative signs, except for bdy term B_{L-1}\n if j == L - 1:\n B_list.append(Bmat)\n else:\n B_list.append(-Bmat)\n return B_list\n\n\n\ndef Show_P_Cyclic_Full(B_list):\n '''Given list of B matrices, make and plot the full (NL,NL) dimensional\n normalized block p-cyclic matrix O.\n \n Args:\n B_list: length L list of sub-diagonal and boundary blocks of p-cyclic matrix\n \n Returns:\n O_mat: (NL,NL) np array'''\n \n L = len(B_list); N,N = B_list[0].shape;\n O_mat = np.zeros((N*L,N*L))\n \n for i in range(L):\n #diagonal: all identity\n O_mat[i*N:(i+1)*N,i*N:(i+1)*N] = np.identity(N)\n if i == L-1: #special boundary term\n O_mat[0:N,i*N:(i+1)*N] = B_list[i]\n else: #-1 diagonal\n O_mat[(i+1)*N:(i+2)*N,i*N:(i+1)*N] = B_list[i]\n \n plt.figure();\n plt.imshow(O_mat);plt.colorbar();\n plt.title(f\"Full P-cyclic matrix L*N = {L*N}\")\n \n return O_mat\n\n\ndef Get_R_Full(R_dict,N,L):\n '''Given dictionary of R entries, create full (NL,NL) R matrix, which \n has block upper bidiagonal form with an extra last block column\n \n Args:\n R_dict: size (3L-3) dictionary of R matrix block entries.\n key = tuple of entry coordinates\n value = (N,N) np array\n \n Returns:\n R_full: (NL,NL) upper triangular np array'''\n R_full = np.zeros((N*L,N*L))\n for k,v in R_dict.items():\n i = k[0]; j = k[1];\n R_full[i*N:(i+1)*N,j*N:(j+1)*N] = v\n \n #plt.figure();plt.imshow(R_full);plt.colorbar()\n #plt.title(f\"Full R matrix L*N = {L*N}\")\n \n return R_full\n\n\ndef Show_R_Full(R_dict,N,L):\n '''Given dictionary of R entries, create and show full (NL,NL) R matrix, which \n has block upper bidiagonal form with an extra last block column\n \n Args:\n R_dict: size (3L-3) dictionary of R matrix block entries.\n key = tuple of entry coordinates\n value = (N,N) np array\n \n Returns:\n R_full: (NL,NL) upper triangular np array'''\n R_full = np.zeros((N*L,N*L))\n for k,v in R_dict.items():\n i = k[0]; j = k[1];\n R_full[i*N:(i+1)*N,j*N:(j+1)*N] = v\n \n plt.figure();plt.imshow(R_full);plt.colorbar()\n plt.title(f\"Full R matrix L*N = {L*N}\")\n \n return R_full\n\ndef Show_Q_Full(Q_list,N,L):\n '''Given list of Q (2N,2N) matrices, create and show full (NL,NL) Q matrix\n \n Args:\n Q_list, length L-1 list of (2N,2N) orthogonal matrices\n \n Returns:\n Q_full: (NL,NL) orthogonal matrix'''\n \n Q_full = np.identity(N*L)\n \n for k in range(len(Q_list)):\n pad = np.eye(N*L)\n pad[k*N:(k+2)*N,k*N:(k+2)*N] = Q_list[k]\n Q_full = Q_full @ pad #Q0 @ Q1 @ ... @ Q(L-2)\n \n plt.figure();plt.imshow(Q_full);plt.colorbar()\n plt.title(f\"Full Q matrix L*N = {L*N}\")\n \n return Q_full \n\ndef Show_Q_Inv_Full(Q_list,N,L):\n '''Given list of Q (2N,2N) matrices, create and show full (NL,NL) Q matrix\n \n Args:\n Q_list, length L-1 list of (2N,2N) orthogonal matrices\n \n Returns:\n Q_inv_full: (NL,NL) orthogonal matrix'''\n Q_inv_full = np.identity(N*L)\n for k in range(len(Q_list)):\n pad = np.eye(N*L)\n pad[k*N:(k+2)*N,k*N:(k+2)*N] = Q_list[k]\n Q_inv_full = pad.T @ Q_inv_full #not sure about mulciplication order\n \n plt.figure();plt.imshow(Q_inv_full);plt.colorbar()\n plt.title(f\"Full Inverse Q matrix L*N = {L*N}\")\n \n return Q_inv_full\n\n\ndef Block_Struct_Orth_Fact(B_list):\n '''Block structured orthogonal factorization (BSOF), a block structured QR\n factorization algorithm introduced in Wright, S.J., 1992.\n Args:\n B_list: length L list of sub-diagonal and boundary blocks of p-cyclic matrix\n \n Returns:\n Q_list, length L-1 list of (2N,2N) orthogonal matrices\n R_dict, size (3L-3) dictionary of R matrix block entries.\n key = tuple of entry coordinates\n value = (N,N) np array\n \n TODO: Better return structure for R\n Set to 0 the very small elements of Q and R?\n ''' \n #input shapes\n L = len(B_list); N,N = B_list[0].shape;\n \n #output accumulators\n Q_list=[];\n R_dict = {};\n \n #initial step\n ###tempA = A_list[0]\n tempA = np.identity(N);\n tempB = B_list[-1]\n #first L-2 blocks\n for k in range(L-2):\n #compute QR, set R diagonal element\n tall_mat = np.concatenate((tempA, B_list[k]), axis=0)\n Q,R = la.qr(tall_mat);\n #plt.figure();plt.imshow(R);plt.colorbar()\n Q_list.append(Q)\n R_dict[(k,k)] = R[:N,:N] #take top part only\n #update tempA,tempB, set off diagonal R elements\n rhs = np.zeros((2*N,2*N));\n #####rhs[N:,:N] = A_list[k+1]; rhs[:N,N:] = tempB;\n rhs[N:,:N] = np.identity(N); rhs[:N,N:] = tempB;\n lhs = Q.T @ rhs\n tempA = lhs[N:,:N]\n tempB = lhs[N:,N:]\n R_dict[(k,k+1)] = lhs[:N,:N]\n R_dict[(k,L-1)] = lhs[:N,N:]\n #last QR block\n rhs_row1 = np.concatenate((tempA, tempB), axis=1)\n #####rhs_row2 = np.concatenate((B_list[-2], A_list[-1]), axis=1)\n rhs_row2 = np.concatenate((B_list[-2], np.identity(N)), axis=1)\n rhs = np.concatenate((rhs_row1, rhs_row2), axis=0)\n Q,R = la.qr(rhs)\n R_dict[(L-2,L-2)] = R[:N,:N];\n R_dict[(L-2,L-1)] = R[:N,N:];\n R_dict[(L-1,L-1)] = R[N:,N:]\n Q_list.append(Q)\n \n #check output shapes\n assert len(Q_list) == L-1 and len(R_dict) == 3*L-3\n \n return Q_list,R_dict\n\n\ndef Invert_R_Row_BBS(R,N,L):\n '''Get X = R^{-1} based on RX = I using Row Block Back Substitution.\n Not exactly same as paper description.\n \n Args:\n R: Full R matrix (NL,NL)\n N: Size of each block\n L: Number of blocks\n \n Returns:\n X = full R inverse, (NL,NL)\n '''\n X = np.zeros((L*N,L*N))\n #last (3N,3N) block is full, directly solve\n X[(L-3)*N:,(L-3)*N:] = \\\n la.solve_triangular(R[(L-3)*N:,(L-3)*N:],np.identity(3*N))\n #Row block back substitution\n for i in range(L-3):\n #print(f\"row {i}\")\n #remaining diagonal (i,i) block shape (N,N)\n X[i*N:(i+1)*N,i*N:(i+1)*N] = \\\n la.solve_triangular(R[i*N:(i+1)*N,i*N:(i+1)*N],np.identity(N))\n \n #last block column, incomplete RHS\n X[:(L-3)*N,(L-1)*N:] = \\\n -R[:(L-3)*N,(L-1)*N:] @ X[(L-1)*N:,(L-1)*N:]\n for i in range(L-4,-1,-1):\n #print(f\"modify row {i} in place\")\n #complete rhs\n X[i*N:(i+1)*N,(i+1)*N:] -= \\\n R[i*N:(i+1)*N,(i+1)*N:(i+2)*N] @ X[(i+1)*N:(i+2)*N,(i+1)*N:]\n #solve using X[i,i] = Rinv[i,i]\n X[i*N:(i+1)*N,(i+1)*N:] = \\\n X[i*N:(i+1)*N , i*N:(i+1)*N] @ X[i*N:(i+1)*N,(i+1)*N:].copy()\n return X\n\n\ndef Apply_Orth_Fact(Rinv,Q_list,N,L):\n '''Produce R^{-1} @ Q^T, inverse of full p-cyclic matrix.\n Apply Q to pairs of columns of R^{-1}, back to front.\n TODO: use paper trick to reduce flops\n \n Args:\n Rinv, start with full R^{-1}, modified in place, end at R^{-1} @ Q^T\n Q_list, length L-1 list of (2N,2N) orthogonal matrices\n N: Size of each block\n L: Number of blocks\n \n Returns:\n None\n \n '''\n for k in range(L-2,-1,-1):\n Rinv[:,k*N:(k+2)*N] = Rinv[:,k*N:(k+2)*N] @ Q_list[k].T\n return None\n\n\ndef Get_Full_O_Inv(invexpdtK,expVData):\n '''Get full O^{-1} which gives all unequal time GFs\n \n Args:\n expVData: (N,L) matrix, each col reps a diagonal mat\n \n Returns:\n (NL,NL) mat, full O^{-1}'''\n N,L = expVData.shape\n blist = Make_B_List(invexpdtK,expVData)\n #Block structured orthogonal factorization (BSOF)\n qlist, rdict = Block_Struct_Orth_Fact(blist)\n #X = R^{-1}\n rfull = Get_R_Full(rdict,N,L)\n xfull = Invert_R_Row_BBS(rfull,N,L)\n #Apply Q^T to get O^{-1} = R^{-1} @ Q^T, X modified in place\n Apply_Orth_Fact(xfull,qlist,N,L)\n \n return xfull\n\n\n\nif __name__ == '__main__':\n print('test BSOFI real on small problem')\n N = 4;\n L = 5;\n invexpdtK = np.identity(N);\n expVuData = np.random.random((N,L))\n\n Gu_list = Make_B_List(invexpdtK,expVuData)\n qlist, rdict = Block_Struct_Orth_Fact(Gu_list)\n qfull = Show_Q_Full(qlist,N,L)\n qinvfull = Show_Q_Inv_Full(qlist,N,L)\n\n plt.figure();plt.imshow(qinvfull-qfull.T);plt.colorbar();\n plt.title(\"Q^{-1} - Q^T\");\n\n rfull = Show_R_Full(rdict,N,L)\n ofull = Show_P_Cyclic_Full(Gu_list)\n\n plt.figure();plt.imshow(qfull @ rfull);plt.colorbar()\n plt.title('Reconstructed Full P-cyclic matrix')\n\n plt.figure();plt.imshow(qfull @ rfull - ofull);plt.colorbar()\n plt.title('QR - O')\n\n xfull = Invert_R_Row_BBS(rfull,N,L)\n plt.figure();plt.imshow(xfull);plt.colorbar();\n plt.title('Full R^{-1} matrix');\n\n Apply_Orth_Fact(xfull,qlist,N,L)\n plt.figure();plt.imshow(xfull);plt.colorbar();\n plt.title('Full R^{-1}Q^T matrix');\n\n plt.figure();plt.imshow(xfull @ ofull);plt.colorbar();\n plt.title('Check inversion correct');\n\n plt.show();\n","sub_path":"src/bsofi_real.py","file_name":"bsofi_real.py","file_ext":"py","file_size_in_byte":9614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"79228761","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 12 20:36:15 2018\n\ndetermine the fibers orientation using MA image processing \n\n@author: df\n\"\"\"\n\n# packages needed to run MA modules\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n# import numpy as np\nimport os\nimport MA.ImageProcessing as MAIP\nimport MA.OrientationAnalysis as MAOA\n# import MA.Tools as MATL\n \n# \nimport dff_dispersionCalculator as dC\nimport dff_mle_minimize_mvMU as DFmle\nimport dff_StatsTools as DFST\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy import optimize\nfrom scipy import stats\nimport pandas as pd\n\n# ------------------------------------------------------------------------- #\n# define the path where the images are imported from:\n# im_dir = '/Users/df/0_myDATA/testSamples/'\n# im_path = im_dir + 'MAX_20X_Airyscan_6.jpg'\n# OutputRoot = \n\n# the directory where the images-to-process are kept: \nim_dir = '/Users/df/Documents/0-DATA/s1_20180223/MAX_20180223_S1_20X_1c/'\n# the image to process: \nim_name = 'MAX_20180223_S1_20X_1c.png'\nim_name_0 = os.path.splitext(im_name)[0]\n# the complete path to the image file\nim_path = im_dir + im_name\n# the root of the path to save the results: \n# ( it is extended by names added from the functions to follow )\nOutputRoot = im_dir + im_name_0\n# if I want one more folder inside:\n# OutputRoot_ = im_dir + im_name_0 + '/' + im_name_0\n\n# transform the image to a numpy array:\nimg = MAIP.GetImageMatrix(im_path)\n\n# create an object from the OrientationAnalysis class:\nOAnalysis = MAOA.OrientationAnalysis(\n BaseAngFolder = \"/Users/df/AngleFiles\",\n OutputRoot = OutputRoot,\n )\n# analyze the image:\nOAnalysis.SetImage(img)\n\n# generate the results:\nResultsFFT = OAnalysis.ApplyFFT()\nResultsFFT.PlotHistogram()\nResultsGrad = OAnalysis.ApplyGradient()\nResultsGrad.PlotHistogram()\n\n# ResultsFFT.X -> the angles of the histogram\n# ResultsFFT.Y -> the intensity of the FFT for the previous angles\n\n# ------------------------------------------------------------------------- # \n# ------------------------------------------------------------------------- # \n# now call DF functions to fit the \n# intensity histogram to a mixture of von-Mises-Fischer distribution\nangles = ResultsFFT.X\nvalues = ResultsFFT.Y\n\n# convert the angles from degrees to radians:\nr_X = np.radians( angles )\nX_samples = r_X\n\n# normalize the light intensity data (FFT): \nn_X = dC.normalizeIntensity( angles, values, YNplot='Yes' )\nInt = n_X[:,1]\n\n# make points of angles based on the light intensity: \np_X = dC.makePoints( n_X, YNplot='Yes' )\n\n# select model to fit: \n#model_test = '1vM'\n#model_test = '2vM'\n#model_test = '3vM'\n#model_test = '2vM1U'\nmodel_test = '1vM1U'\n#%% for a 1vM1U model: \n#model_test = '1vM1U'\nif model_test == '1vM1U':\n # parameters for the von Mises member:\n p1_ = 0.7 # weight contribution of the 1st von Mises \n pu_ = 1. - p1_ # weight contribution of Uniform distribut \n kappa1_ = np.array((12.0)) # concentration for the 1st von Mises member \n loc1_ = -np.pi/9.0 # location for the 1st von Mises member \n \n # ------------------------------------- # \n # if you solve with minimize: \n in_guess = [ p1_, kappa1_, loc1_, pu_ ]\n # bound constraints for the variables: \n lim_l = -np.pi/2.\n lim_u = np.pi/2.\n # for the weight: (0., 1.)\n # for the concentration: (0., 100.)\n # for the location: (lim_l, lim_u)\n bnds = ((0., 1.), (0., 100.), (lim_l, lim_u), \\\n (0., 1.))\n # the sum of the weights should be equal to unity: \n cons = ({'type': 'eq', 'fun': lambda x: x[0] + x[3] - 1.0})\n results = optimize.minimize(DFmle.logLik_1vM1U, in_guess, args=(r_X,Int), \\\n method='SLSQP', bounds=bnds, constraints=cons, \\\n tol=1e-6, options={'maxiter': 100, 'disp': True})\n print('METHOD II = ',results.x)\n print('-----------------------------------------')\n p1_mle, kappa1_mle, mu1_mle, pu_mle = results.x\n print('p1, kappa1, mu1, pu = ',results.x)\n res = results.x\n # ------------------------------------- # \n # data = np.array([[p1_mle, kappa1_mle, mu1_mle],\n # [pu_mle, 0.0, 0.0]])\n \n # ---------------------------------------------------------------------- #\n # Store the results to arrays for later use:\n members_list = [\"1st von Mises\", \"Uniform\"]\n loc_mle = np.array([mu1_mle, 0.0])\n kap_mle = np.array([kappa1_mle, 1e-3])\n p_mle = np.array([p1_mle, pu_mle])\n\n#%% COLLECT the estimated parameters into a Pandas dataFrame: \nloc_mle_d = np.degrees(loc_mle)\ndataFrame = pd.DataFrame({'Distribution': members_list, \\\n 'Weight': p_mle.ravel(), \\\n 'Concentration': kap_mle.ravel(), \\\n 'Location': loc_mle.ravel(), \\\n 'Location (deg)': loc_mle_d.ravel()})\ndataFrame = dataFrame[['Distribution', 'Weight', \\\n 'Concentration','Location', 'Location (deg)']]\n#dataFrame.set_index('Distribution')\nprint('---------------------------------------------------')\nprint('---- The table with the estimated parameters ----')\nprint('--------------------------------------------------')\nprint(dataFrame)\n\n# -------------------------------------------------------------------------- #\n#%% ------------------------------------------------------------------- # \n# PLOT in the same figure the original histogram and the model PDF: \nscal_ = 0.5\nfig, ax = plt.subplots(1, 1, figsize=(9,4))\nax.set_title('Probability Density Function of Mixture Model (von Mises + Uniform)')\nax.plot(angles, Int, 'b-', label='Original data')\n# prepare the PDFs: \nx_ = np.linspace( min(X_samples), max(X_samples), len(r_X) )\nr_ = np.degrees(x_)\nx_ax = r_\nX_tot = np.zeros(len(x_),)\ncXtot = np.zeros(len(x_),)\njj = 0\n# plot in the same histogram the approximations:\nfor mu, kap, pii in zip(loc_mle, kap_mle, p_mle):\n jj += 1\n fX_temp = stats.vonmises( kap, mu, scal_ )\n # X_temp = pii*stats.vonmises.pdf( x_, kap, mu, scal_ )\n X_temp = pii*fX_temp.pdf ( x_ )\n X_tot += X_temp\n# ax.plot(x_ax, X_temp, linewidth=2, linestyle='--', \\\n# label='von Mises member {} '.format(jj))\n #label=r'$\\mu$ = {}, $\\kappa$= {}, p= {} '.format(round(mu,3), round(kap,3), round(pii,3)))\n # this is wrong!!!: \n cXtot += pii*fX_temp.cdf( x_ )\n # cXtot += pii*stats.vonmises.cdf( x_, kap, mu, scal_ )\n \nax.plot(x_ax, X_tot, color='red', linewidth=2, linestyle='-', label='Mixture fit')\nax.set_xlabel(r'$\\theta$ (degrees)', fontsize=12)\nax.set_ylabel(r'$f(\\theta)$', fontsize=12)\nax.grid(color='gray', alpha=0.3, linestyle=':', linewidth=1)\nax.legend(loc=1)\n#ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2),\n# fancybox=True, shadow=True, ncol=3)\n\n# -------------------------------------------------------------------------- #\n#%% ------------------------------------------------------------------- #\n# PREPARE THE DATA FOR THE GOODNESS-OF-FIT TESTS: \n# based on populated points for every angle based on its intensity: \n# CAUTION !!!\n# THIS IS THE CORRECT APPROACH !!!\naa = np.sort( p_X )\naad = np.degrees(aa)\nfX_t = np.zeros(len(aa),)\ncX_t = np.zeros(len(aa),)\nfor mu, kap, pii in zip(loc_mle, kap_mle, p_mle):\n temp = stats.vonmises( kap, mu, scal_ )\n fX_t += pii*temp.pdf( aa )\n cX_t += pii*temp.cdf( aa )\n #fX_t += pii*stats.vonmises.pdf( aa, kap, mu, scal_ )\n #cX_t += pii*stats.vonmises.cdf( aa, kap, mu, scal_ )\n\nx1, cfX_obs = DFST.ECDF( p_X )\nx1d = np.degrees(x1)\n\nif max(cX_t) > 1:\n cX_c = cX_t - (max(cX_t) - 1.)\nelse:\n cX_c = cX_t\n\n# plot the CDF from populated points: \nfig, ax = plt.subplots(1,1,figsize=(4,3))\nax.set_title('CDF of Mixture Model')\nax.set_xlabel(r'$\\theta$ (degrees)', fontsize=12)\nax.set_ylabel('Cumulative distribution', fontsize=12)\nax.plot( x1d, cfX_obs, 'b-', lw=2, alpha=0.6, label='ECDF data')\nax.plot( aad, cX_c, 'r--', label='CDF model')\nax.legend()\n\n# -------------------------------------------------------------------------- #\n#%% GOF tests: \n\n# The Watson GOF: \nU2, Us, uc, pu2, pus, H0_W2, lev_W2 = DFST.watson_GOF( cX_c, alphal=1)\nprint('Watson GOF =',U2, Us, uc, pu2, pus, H0_W2, lev_W2)\n\n \n# The Kuiper GOF: \n# this is the most correcrt: \nVn, Vc, pVn, H0_K2, lev_K2 = DFST.Kuiper_GOF( cX_c )\nprint('Kuiper GOF =', Vn, pVn, H0_K2, lev_K2)\n\n\n# The R2 coefficient: \nfX_r2 = np.zeros(len(x1),)\nfor mu, kap, pii in zip(loc_mle, kap_mle, p_mle):\n temp = stats.vonmises( kap, mu, scal_ )\n fX_r2 += pii*temp.pdf( x1 )\n \ndx = np.diff(x1)\ncX_r2 = np.ones(len(x1),)\ncX_r2[0:-1] = np.cumsum(fX_r2[0:-1]*dx)\nR2 = DFST.myR2( cX_r2, cfX_obs )\nprint('R2 =', R2)\nif R2 > 0.90:\n H0_R2 = \"Do not reject\"\nelse:\n H0_R2 = \"Reject\"\n \n# Plot the Probability-Probability Plot: \nDFST.PP_GOF( cX_r2, cfX_obs )\n\n# ---------------------------------------------------------------------- #\n#%% Collect all results into a Pandas dataFrame: \ngof_list = [\"Waston\", \"Kuiper\", \"R2\"]\ngof_stats = np.array([U2, Vn, R2])\ngof_crVal = np.array([uc, Vc, 1.0])\ngof_pvals = np.array([pu2, pVn, 1.0])\ngof_level = np.array([lev_W2, lev_K2, 1.0])\ngof_rejH0 = [H0_W2, H0_K2, H0_R2]\n\ndataFrameGOF = pd.DataFrame({'GOF': gof_list, \\\n 'Statistic': gof_stats.ravel(), \\\n 'CriticalValue': gof_crVal.ravel(), \\\n 'PValue': gof_pvals.ravel(), \\\n 'SignLev': gof_level.ravel(), \\\n 'Decision': gof_rejH0})\ndataFrameGOF = dataFrameGOF[['GOF', 'Statistic', \\\n 'CriticalValue','PValue', 'SignLev', 'Decision']]\n\nprint('---------------------------------------------------')\nprint('---- The table with the Goodness-of-Fit tests ----')\nprint('---------------------------------------------------')\nprint(dataFrameGOF)\n","sub_path":"df_test_fibOrient02.py","file_name":"df_test_fibOrient02.py","file_ext":"py","file_size_in_byte":9999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"39814596","text":"##!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n# 批量输出\n# 文本的总字数,总词数(去重),分词结果,每个级别的词汇,每个级别的词汇个数,每个级别的词汇占比\n\nfrom hsk_modules import *\nimport xlrd\nimport xlwt\n\nexcel = xlrd.open_workbook('/Users/Arthur/PycharmProjects/CountWords/HSK4课文文本汇总.xlsx')\nsheet = excel.sheet_by_index(0)\nrows = sheet.nrows\n\nnew_excel = xlwt.Workbook()\nnew_sheet = new_excel.add_sheet(\"sheet1\")\n\n\nfor num in range(1, rows):\n text = sheet.cell_value(num, 4)\n count_num = 0\n for item in text_level(text):\n print(type(item))\n if isinstance(item, int):\n new_sheet.write(num, count_num, item)\n count_num = count_num + 1\n if isinstance(item, dict):\n new_sheet.write(num, count_num, str(item))\n count_num = count_num + 1\n if isinstance(item, list):\n for i in range(len(item)):\n new_sheet.write(num, count_num, item[i])\n count_num = count_num + 1\n\nnew_excel.save('/Users/Arthur/PycharmProjects/test.xls')\n","sub_path":"venv/app/get_text_level.py","file_name":"get_text_level.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"54121596","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n# pylint: disable=line-too-long\n# pylint: disable=too-many-lines\n# pylint: disable=inconsistent-return-statements\n\n\ndef validate_storageaccount(cmd, namespace):\n from azure.cli.core.commands.client_factory import get_subscription_id\n from msrestazure.tools import is_valid_resource_id, resource_id\n if namespace.storage_account_resource_id:\n if not is_valid_resource_id(namespace.storage_account_resource_id):\n namespace.storage_account_resource_id = resource_id(\n subscription=get_subscription_id(cmd.cli_ctx),\n resource_group=namespace.resource_group_name,\n namespace='Microsoft.Storage',\n type='storageAccounts',\n name=namespace.storage_account_resource_id)\n\n\ndef validate_partner_namespace(cmd, namespace):\n from azure.cli.core.commands.client_factory import get_subscription_id\n from msrestazure.tools import is_valid_resource_id, resource_id\n if namespace.partner_namespace:\n if not is_valid_resource_id(namespace.partner_namespace):\n namespace.partner_namespace = resource_id(\n subscription=get_subscription_id(cmd.cli_ctx),\n resource_group=namespace.resource_group_name,\n namespace='Microsoft.EventHub',\n type='namespaces',\n name=namespace.partner_namespace)\n","sub_path":"src/command_modules/azure-cli-eventhubs/azure/cli/command_modules/eventhubs/_validator.py","file_name":"_validator.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"498761579","text":"# This problem was asked by Airbnb.\n\n# Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.\n\n# For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.\n\n\nnum = [5,1,1,5]\n# num=[2,4,6,2,5]\nlist1 = []\nfor i in range(0, len(num)):\n\n for j in range(2, len(num)):\n # print(num[j])\n num_added = 0\n\n for k in range(i, len(num), j):\n num_added = num_added + num[k]\n # print(\"value of num_added \", num_added)\n list1.append(num_added)\n# print(list1)\nprint(max(list1))\n\n","sub_path":"day_9.py","file_name":"day_9.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"313424532","text":"numberOfTestCases = input()\nfor i in range(int(numberOfTestCases)):\n elements = input()\n wordsTrue = []\n wordsFalse = []\n for x in range(int(elements)):\n temp = input()\n if temp[(len(temp)-1)] == str(1):\n wordsTrue.append(temp)\n else:\n wordsFalse.append(temp)\n wordsTrue = [wordT[:-2] for wordT in wordsTrue]\n wordsFalse = [wordF[:-2] for wordF in wordsFalse]\n dictTrue = dict()\n dictFalse= dict()\n for word in wordsTrue:\n if word not in dictTrue:\n dictTrue[word] = 1\n else:\n dictTrue[word] += 1\n for word in wordsFalse:\n if word not in dictFalse:\n dictFalse[word] = 1\n else:\n dictFalse[word] += 1\n del wordsTrue\n del wordsFalse\n counter = 0\n for word in dictTrue:\n if word in dictFalse:\n if dictTrue[word] > dictFalse[word]:\n counter += dictTrue[word]\n dictFalse.pop(word)\n else:\n counter += dictFalse[word]\n dictFalse.pop(word)\n else:\n counter += dictTrue[word]\n for word in dictFalse:\n counter += dictFalse[word]\n print(counter)\n","sub_path":"2_1/TRAINSET.py","file_name":"TRAINSET.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"89640430","text":"\"\"\"\nRename a file if the following are a part of the file name:\n- Remove everything that is in () and [] # Done\n- If there are ',' remove them # Done\n- Remove more than 1 '.' # Done\n- Remove any special character in the file name # Done\n- Remove the following \"_-_\": If '-' between underscore # Left\n- Removing numbers if string starts with a number # Done\n- Add extension at the end of the string and confirm # Done\n- Explicitly remove the given words if found in the string # Done\n- If word in CAP, change to CAP only 1st Alphabet # Done\n\"\"\"\n\nimport re\nimport os\nfrom time import time\ncurrent_time = time()\n# sample_name = '2345Charlie Puth - @#$^#%,.How Long [check1](DawnFox#es.com).mp3'\nfile_extensions = ['.mp3', '.wav', '.mpeg', '.m4a', '.webm']\nremove_words = ['official', 'video', 'lyric', 'audio', 'soundtrack', 'song', 'ost', '----']\nfind_special_char = \"!@#$%^*()[]+?=,.<>/\"\nspecial_char_string_start = \"!@#$%^&*()[]+?=,.<>/ -_\"\nopen_dir_path = r'C:\\Users\\anvin\\PycharmProjects\\generic\\downloaded_songs\\sample'\nfind_comma = r','\nfind_period = '.'\n# ext = '.mp3'\nos.chdir(open_dir_path)\n\n\ndef rename_files():\n for folder, dirs, files in os.walk(open_dir_path):\n os.chdir(folder)\n for audio_file in files:\n audio_file = audio_file.lower()\n full_path = os.path.join(folder, audio_file)\n # print(full_path)\n for index, file_format in enumerate(file_extensions):\n if audio_file.endswith(file_format):\n initial_name = audio_file\n # for extension in range(len(file_extensions)):\n if file_format in audio_file:\n audio_file = audio_file.replace(file_format, \"\")\n # print(full_path)\n for val in range(len(remove_words)):\n if remove_words[val] in audio_file.lower():\n audio_file = audio_file.replace(remove_words[val], \"\")\n audio_file = audio_file.title()\n\n audio_file = re.sub(r\"\\(.*?\\)\", \"()\", audio_file)\n audio_file = re.sub(r\"\\[.*?]\", \"[]\", audio_file)\n audio_file = re.sub(r' +', ' ', audio_file)\n for special_char in find_special_char:\n for element in audio_file:\n if special_char in element:\n audio_file = audio_file.replace(element, \"\")\n for i in range(len(audio_file)):\n if audio_file[0].isdigit():\n audio_file = audio_file.replace(audio_file[0], \"\")\n for special_char in special_char_string_start:\n if audio_file.startswith(special_char):\n audio_file = audio_file.replace(special_char, \"\", 1) # only 1st occurrence to be replaced\n audio_file = audio_file.rstrip() + '.mp3'\n os.rename(initial_name, audio_file)\n print(audio_file)\n\n\nif __name__ == \"__main__\":\n rename_files()\n print(\"Execution Time: \", time() - current_time)\n","sub_path":"rename_existing_files.py","file_name":"rename_existing_files.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"73607342","text":"#!/usr/bin/python3\n\n# Calculate PI number using this formula:\n# x[n+1] = x[n] + sin(x[n])\n#\n# x[n+1] = x[n] + x[n] + x[n]**3/fact(3) - x[n]**5/fact(5) + x[n]**7/fact(7) - x[n]**9/fact(9) + ....\n\nfrom decimal import getcontext, Decimal\nimport sys\n\nif len(sys.argv) < 2:\n print('Not enough arguments')\n quit()\n\nprecision = int(sys.argv[1])\nexcess_prec = 2\n\nprec_cur = 100 if precision > 100 else precision\n\ngetcontext().prec = prec_cur + excess_prec\n\nsecond = Decimal(3) # Current element for PI\nqueue_cur = [Decimal(0), Decimal(0), Decimal(0), second]\n\nqq_append = queue_cur.append\nqq_pop = queue_cur.pop\n\nlimit = Decimal(10) ** (-prec_cur - excess_prec)\n\nwhile True:\n\n sec_sq = second * second\n term = second\n acc = second + term\n count = Decimal(1)\n\n while term > limit:\n\n term *= sec_sq / ((count + 1) * (count + 2))\n acc -= term\n # print ('term1: {}'.format(term))\n\n term *= sec_sq / ((count + 3) * (count + 4))\n acc += term\n\n count += 4\n # print ('term2: {}'.format(term))\n\n # print ('acc: {}'.format(second))\n if acc in queue_cur:\n if prec_cur < precision:\n prec_cur += prec_cur\n if prec_cur > precision:\n prec_cur = precision\n limit = Decimal(10) ** (-prec_cur - excess_prec)\n getcontext().prec = prec_cur + excess_prec\n\n else:\n second = acc\n break\n\n qq_append(acc)\n qq_pop(0)\n second = acc\n # print ('second: {}'.format(second))\n\ngetcontext().prec = precision\nprint(\"PI: \", +second)\n","sub_path":"idlepicalc.py","file_name":"idlepicalc.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"604331575","text":"# Copyright 2014 - Savoir-Faire Linux 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 os\n\nfrom surveil.cmd import surveil_from_nagios\nfrom surveil.tests import base as base_test\n\n\nclass TestSurveilFromNagios(base_test.BaseTestCase):\n\n def setUp(self):\n self.nagios_config_folder = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n 'nagios_config'\n )\n\n def test_surveil_from_nagios_config_cfg(self):\n surveil_cfg = surveil_from_nagios.load_config(\n self.nagios_config_folder\n )\n\n self.assert_count_equal_backport(\n surveil_cfg,\n [\n ('timeperiods',\n [\n {\n 'alias': 'Normal Work Hours',\n 'timeperiod_name': 'workhours',\n 'periods': {\n 'tuesday': '09:00-17:00',\n 'friday': '09:00-17:00',\n 'thursday': '09:00-17:00',\n 'wednesday': '09:00-17:00',\n 'monday': '09:00-17:00'\n }\n }\n ]),\n ('hosts',\n [\n {\n 'name': 'generic-host',\n 'custom_fields': {}},\n {\n 'use': ['generic-host'],\n 'custom_fields': {}},\n {\n 'use': ['generic-host', 'non-existing-thing'],\n 'contact_groups': ['admins'],\n 'host_name': 'localhost',\n 'check_interval': 324,\n 'address': 'localhost',\n 'custom_fields': {\n '_custom_yolo': 'sdfsdf'\n }\n },\n\n ]),\n ('services',\n [\n {'host_name': ['test']},\n {'host_name': ['hai']}\n ])\n ]\n )\n\n def test_load_single_file(self):\n other_file_path = os.path.join(\n self.nagios_config_folder,\n 'other_file.cfg'\n )\n\n single_file_config = surveil_from_nagios.load_config(\n other_file_path\n )\n\n self.assertEqual(\n single_file_config,\n [('services', [{'host_name': ['hai']}])]\n )","sub_path":"surveil/tests/cmd/test_surveil_from_nagios.py","file_name":"test_surveil_from_nagios.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"491811408","text":"class Person:\r\n\r\n history = 200 # 人类的历史\r\n amount = 74 # 人口数量\r\n\r\n def __init__(self, name, age):\r\n self.name = name\r\n self.age = age\r\n\r\n def sayhi(self):\r\n print(\"大家好,我是%s,今年%s\" % (self.name, self.age))\r\n print(\"我来介绍人类的发展,人口已经有%s万年的历史了\" % Person.history)\r\n print(\"目前,地球上已经有%s亿人口\" % Person.amount)\r\n\r\n\r\nif __name__ == '__main__':\r\n print(\"人类历史:\", Person.history)\r\n # print(Person.name) # 报错","sub_path":"python/20201026:Python第3天课后资料包/课堂示例代码/oop/classfield/per.py","file_name":"per.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"510814027","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\nimport rdmo.core.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('domain', '0001_initial_after_reset'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Catalog',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', models.DateTimeField(verbose_name='created', editable=False)),\n ('updated', models.DateTimeField(verbose_name='updated', editable=False)),\n ('order', models.IntegerField(null=True)),\n ('title_en', models.CharField(max_length=256)),\n ('title_de', models.CharField(max_length=256)),\n ],\n options={\n 'ordering': ('order',),\n 'verbose_name': 'Catalog',\n 'verbose_name_plural': 'Catalogs',\n },\n bases=(models.Model, rdmo.core.models.TranslationMixin),\n ),\n migrations.CreateModel(\n name='QuestionEntity',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', models.DateTimeField(verbose_name='created', editable=False)),\n ('updated', models.DateTimeField(verbose_name='updated', editable=False)),\n ('order', models.IntegerField(null=True)),\n ('help_en', models.TextField(null=True, blank=True)),\n ('help_de', models.TextField(null=True, blank=True)),\n ],\n options={\n 'ordering': ('subsection__section__catalog__order', 'subsection__section__order', 'subsection__order'),\n 'verbose_name': 'QuestionEntity',\n 'verbose_name_plural': 'QuestionEntities',\n },\n bases=(models.Model, rdmo.core.models.TranslationMixin),\n ),\n migrations.CreateModel(\n name='Section',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', models.DateTimeField(verbose_name='created', editable=False)),\n ('updated', models.DateTimeField(verbose_name='updated', editable=False)),\n ('order', models.IntegerField(null=True)),\n ('title_en', models.CharField(max_length=256)),\n ('title_de', models.CharField(max_length=256)),\n ('catalog', models.ForeignKey(related_name='sections', to='questions.Catalog', on_delete=models.CASCADE)),\n ],\n options={\n 'ordering': ('catalog__order', 'order'),\n 'verbose_name': 'Section',\n 'verbose_name_plural': 'Sections',\n },\n bases=(models.Model, rdmo.core.models.TranslationMixin),\n ),\n migrations.CreateModel(\n name='Subsection',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', models.DateTimeField(verbose_name='created', editable=False)),\n ('updated', models.DateTimeField(verbose_name='updated', editable=False)),\n ('order', models.IntegerField(null=True)),\n ('title_en', models.CharField(max_length=256)),\n ('title_de', models.CharField(max_length=256)),\n ('section', models.ForeignKey(related_name='subsections', to='questions.Section', on_delete=models.CASCADE)),\n ],\n options={\n 'ordering': ('section__catalog__order', 'section__order', 'order'),\n 'verbose_name': 'Subsection',\n 'verbose_name_plural': 'Subsections',\n },\n bases=(models.Model, rdmo.core.models.TranslationMixin),\n ),\n migrations.CreateModel(\n name='Question',\n fields=[\n ('questionentity_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='questions.QuestionEntity', on_delete=models.CASCADE)),\n ('text_en', models.TextField()),\n ('text_de', models.TextField()),\n ('widget_type', models.CharField(max_length=12, choices=[('text', 'Text'), ('textarea', 'Textarea'), ('yesno', 'Yes/No'), ('checkbox', 'Checkboxes'), ('radio', 'Radio buttons'), ('select', 'Select drop-down'), ('range', 'Range slider'), ('date', 'Date picker')])),\n ],\n options={\n 'ordering': ('subsection__section__catalog__order', 'subsection__section__order', 'subsection__order'),\n 'verbose_name': 'Question',\n 'verbose_name_plural': 'Questions',\n },\n bases=('questions.questionentity',),\n ),\n migrations.AddField(\n model_name='questionentity',\n name='attribute_entity',\n field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='domain.AttributeEntity', null=True),\n ),\n migrations.AddField(\n model_name='questionentity',\n name='subsection',\n field=models.ForeignKey(related_name='entities', to='questions.Subsection', on_delete=models.CASCADE),\n ),\n migrations.AddField(\n model_name='question',\n name='parent_entity',\n field=models.ForeignKey(related_name='questions', blank=True, to='questions.QuestionEntity', null=True, on_delete=models.CASCADE),\n ),\n ]\n","sub_path":"rdmo/questions/migrations/0001_initial_after_reset.py","file_name":"0001_initial_after_reset.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"401927696","text":"import expense_groups as eg\nimport os\nimport pandas as pd\nimport re\n\nDATA_FOLDER = r'Data'\nCHECKING_BALANCE_FILE = r'CHK_514.csv'\nYEARLY_EXPENSES_PATTERN = r'2013-summary.txt'\nMONTHLY_EXPENSES_PATTERN = r'([0-9]|-)+\\.txt.sorted'\n\ndef read_df(data_file, headers, dollar_columns, index_column, separator):\n data_frame = pd.read_csv(data_file, sep=separator, index_col=index_column, parse_dates=True, names=headers)\n for column in dollar_columns:\n data_frame[column] = data_frame[column].map(lambda x: float(x.replace(',', '').replace('$', '')))\n return data_frame\n\ndef read_checking_df(data_file):\n kwargs = {'data_file' : data_file,\n 'headers' : ['c1', 'c2', 'title', 'source', 'amount', 'c6', 'account', 'c7'],\n 'dollar_columns' : ['amount'],\n 'index_column' : 1,\n 'separator' : ','}\n return read_df(**kwargs)\n\ndef read_yerly_expenses_df(data_files):\n kwargs = {'headers' : ['date', 'account', 'group', 'name', 'price'],\n 'dollar_columns' : ['price'],\n 'index_column' : 0,\n 'separator' : ';'}\n dfs = [read_df(data_file=data_file, **kwargs) for data_file in data_files]\n return pd.concat(dfs)\n\ndef read_monthly_expenses_df(data_files):\n kwargs = {'headers' : ['date', 'price', 'name', 'c3'],\n 'dollar_columns' : ['price'],\n 'index_column' : 0,\n 'separator' : ';'}\n dfs = [read_df(data_file=data_file, **kwargs) for data_file in data_files]\n return pd.concat(dfs)\n\ndef get_file_list(pattern):\n return [os.path.join(DATA_FOLDER, file_name)\n for file_name in sorted(os.listdir(DATA_FOLDER))\n if re.match(pattern, file_name)]\n\ndef get_balance_df():\n return read_checking_df(os.path.join(DATA_FOLDER, 'CHK_514.csv'))\n\ndef get_expenses_df():\n yearly_expenses_df = read_yerly_expenses_df(get_file_list(YEARLY_EXPENSES_PATTERN))\n monthly_expenses_df = read_monthly_expenses_df(get_file_list(MONTHLY_EXPENSES_PATTERN))\n expenses_df = pd.concat([yearly_expenses_df[['price', 'name']],\n monthly_expenses_df[['price', 'name']]])\n patterns = eg.get_match_groups(os.path.join(DATA_FOLDER, 'groups.txt'))\n eg.verify_match_groups(patterns, list(expenses_df['name']))\n expenses_df['group'] = expenses_df['name'].map(lambda x: eg.find_matching_groups(patterns, x)[0]\n if 1 == len(eg.find_matching_groups(patterns, x))\n else \"None\")\n return expenses_df\n","sub_path":"data_reader.py","file_name":"data_reader.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"54826233","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=unused-argument, import-outside-toplevel, protected-access\nfrom datetime import datetime\n\nimport pytest\nfrom flask.ctx import AppContext\n\nfrom tests.unit_tests.fixtures.common import dttm\n\n\n@pytest.mark.parametrize(\n \"sql,expected\",\n [\n (\"SELECT foo FROM tbl\", True),\n (\"SHOW TABLES\", False),\n (\"EXPLAIN SELECT foo FROM tbl\", False),\n (\"INSERT INTO tbl (foo) VALUES (1)\", False),\n ],\n)\ndef test_sql_is_readonly_query(\n app_context: AppContext, sql: str, expected: bool\n) -> None:\n \"\"\"\n Make sure that SQL dialect consider only SELECT statements as read-only\n \"\"\"\n\n from superset.db_engine_specs.kusto import KustoSqlEngineSpec\n from superset.sql_parse import ParsedQuery\n\n parsed_query = ParsedQuery(sql)\n is_readonly = KustoSqlEngineSpec.is_readonly_query(parsed_query)\n\n assert expected == is_readonly\n\n\n@pytest.mark.parametrize(\n \"kql,expected\",\n [\n (\"tbl | limit 100\", True),\n (\"let foo = 1; tbl | where bar == foo\", True),\n (\".show tables\", False),\n ],\n)\ndef test_kql_is_select_query(app_context: AppContext, kql: str, expected: bool) -> None:\n \"\"\"\n Make sure that KQL dialect consider only statements that do not start with \".\" (dot)\n as a SELECT statements\n \"\"\"\n\n from superset.db_engine_specs.kusto import KustoKqlEngineSpec\n from superset.sql_parse import ParsedQuery\n\n parsed_query = ParsedQuery(kql)\n is_select = KustoKqlEngineSpec.is_select_query(parsed_query)\n\n assert expected == is_select\n\n\n@pytest.mark.parametrize(\n \"kql,expected\",\n [\n (\"tbl | limit 100\", True),\n (\"let foo = 1; tbl | where bar == foo\", True),\n (\".show tables\", True),\n (\"print 1\", True),\n (\"set querytrace; Events | take 100\", True),\n (\".drop table foo\", False),\n (\".set-or-append table foo <| bar\", False),\n ],\n)\ndef test_kql_is_readonly_query(\n app_context: AppContext, kql: str, expected: bool\n) -> None:\n \"\"\"\n Make sure that KQL dialect consider only SELECT statements as read-only\n \"\"\"\n\n from superset.db_engine_specs.kusto import KustoKqlEngineSpec\n from superset.sql_parse import ParsedQuery\n\n parsed_query = ParsedQuery(kql)\n is_readonly = KustoKqlEngineSpec.is_readonly_query(parsed_query)\n\n assert expected == is_readonly\n\n\ndef test_kql_parse_sql(app_context: AppContext) -> None:\n \"\"\"\n parse_sql method should always return a list with a single element\n which is an original query\n \"\"\"\n\n from superset.db_engine_specs.kusto import KustoKqlEngineSpec\n\n queries = KustoKqlEngineSpec.parse_sql(\"let foo = 1; tbl | where bar == foo\")\n\n assert queries == [\"let foo = 1; tbl | where bar == foo\"]\n\n\n@pytest.mark.parametrize(\n \"target_type,expected_dttm\",\n [\n (\"DATETIME\", \"datetime(2019-01-02T03:04:05.678900)\"),\n (\"TIMESTAMP\", \"datetime(2019-01-02T03:04:05.678900)\"),\n (\"DATE\", \"datetime(2019-01-02)\"),\n ],\n)\ndef test_kql_convert_dttm(\n app_context: AppContext,\n target_type: str,\n expected_dttm: str,\n dttm: datetime,\n) -> None:\n \"\"\"\n Test that date objects are converted correctly.\n \"\"\"\n\n from superset.db_engine_specs.kusto import KustoKqlEngineSpec\n\n assert expected_dttm == KustoKqlEngineSpec.convert_dttm(target_type, dttm)\n\n\n@pytest.mark.parametrize(\n \"target_type,expected_dttm\",\n [\n (\"DATETIME\", \"CONVERT(DATETIME, '2019-01-02T03:04:05.678', 126)\"),\n (\"DATE\", \"CONVERT(DATE, '2019-01-02', 23)\"),\n (\"SMALLDATETIME\", \"CONVERT(SMALLDATETIME, '2019-01-02 03:04:05', 20)\"),\n (\"TIMESTAMP\", \"CONVERT(TIMESTAMP, '2019-01-02 03:04:05', 20)\"),\n ],\n)\ndef test_sql_convert_dttm(\n app_context: AppContext,\n target_type: str,\n expected_dttm: str,\n dttm: datetime,\n) -> None:\n \"\"\"\n Test that date objects are converted correctly.\n \"\"\"\n\n from superset.db_engine_specs.kusto import KustoSqlEngineSpec\n\n assert expected_dttm == KustoSqlEngineSpec.convert_dttm(target_type, dttm)\n","sub_path":"tests/unit_tests/db_engine_specs/test_kusto.py","file_name":"test_kusto.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"648231904","text":"# This file is part of MaixUI\n# Copyright (c) sipeed.com\n#\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license.php\n#\n\nimport time, gc\n\ntry:\n from pmu_axp173 import AXP173, AXP173_ADDR\n from core import agent\n from ui_canvas import ui, print_mem_free\n # from ui_launcher import launcher\n from ui_3d_launcher import launcher\n from ui_system_info import system_info\n from ui_catch import catch\n from ui_pages import pages\n from ui_camera import ai_camera\n from ui_sample import sample_page\n from ui_explorer import explorer\n from sample_shtxx import sample_shtxx\n from sample_spmod import sample_spmod_test\n from sample_msa301 import sample_msa301\n from button import sipeed_button, button_io\n from wdt import protect\n from led import cube_led\n from sound import CubeAudio\n from ui_taskbar import taskbar\nexcept ImportError:\n from lib.core import agent\n from ui.ui_canvas import ui, print_mem_free\n # from ui.ui_launcher import launcher\n from ui.ui_3d_launcher import launcher\n from ui.ui_system_info import system_info\n from ui.ui_catch import catch\n from ui.ui_pages import pages\n from ui.ui_camera import ai_camera\n from ui.ui_sample import sample_page\n from ui.ui_explorer import explorer\n from ui.sample_shtxx import sample_shtxx\n from ui.sample_spmod import sample_spmod_test\n from ui.sample_msa301 import sample_msa301\n from driver.button import sipeed_button\n from driver.wdt import protect\n from driver.led import cube_led\n from driver.pmu_axp173 import AXP173, AXP173_ADDR\n from ui.ui_taskbar import taskbar\n from driver.sound import CubeAudio\n\nclass app:\n\n layer = 0 # set help_draw to top\n ctrl = agent()\n btn = sipeed_button()\n\n @ui.warp_template(ui.bg_in_draw)\n @ui.warp_template(ui.help_in_draw)\n def draw_load():\n ui.display()\n\n # @ui.warp_template(ui.bg_in_draw) # ui_3d_launcher need remove\n @ui.warp_template(launcher.draw)\n #@ui.warp_template(taskbar.mem_draw)\n @ui.warp_template(taskbar.battery_draw)\n # @ui.warp_template(taskbar.mem_draw)\n def draw_launcher():\n ui.display()\n\n @ui.warp_template(CubeAudio.event)\n @ui.warp_template(ui.anime_draw)\n @ui.warp_template(CubeAudio.event)\n @ui.warp_template(taskbar.mem_draw)\n # @ui.warp_template(system_info.info_draw)\n def draw_pages():\n if app.current != None:\n app.current.draw()\n ui.display()\n\n @ui.warp_template(CubeAudio.event)\n @ui.warp_template(taskbar.time_draw)\n @ui.warp_template(sample_page.sample_draw)\n @ui.warp_template(CubeAudio.event)\n def draw_samples():\n ui.display()\n\n @ui.warp_template(explorer.draw)\n def draw_explorer():\n # if explorer.info != \"\":\n # protect.stop()\n # print(explorer.get_path(explorer.paths) + '/' + explorer.info)\n # # with open(explorer.get_path(explorer.paths) + '/' + tmp, 'rb') as target:\n # # # exec(target.read(), locals())\n # # exec(target.read())\n # execfile(explorer.get_path(explorer.paths) + '/' + explorer.info)\n # protect.start()\n\n ui.display()\n\n def draw_camera():\n try:\n ai_camera.ai_draw()\n ui.display()\n except Exception as e:\n app.layer = 1\n raise e\n\n current = None\n\n def load_application(selected):\n if app.current != None: # clear last application\n del app.current\n app.current = None\n if selected == 0:\n pass\n\n elif selected == 1:\n app.current = pages()\n elif selected == 2:\n pass\n #app.layer -= 1 # return last layer\n #raise Exception(\"Settings Unrealized.\")\n elif selected == 3:\n CubeAudio.load(os.getcwd() + \"/res/sound/one.wav\", 100)\n sample_page.add_sample(sample_msa301())\n sample_page.add_sample(sample_spmod_test())\n sample_page.add_sample(sample_shtxx())\n sample_page.add_demo()\n\n\n def exec_application():\n if launcher.app_select == 0:\n app.draw_camera()\n if launcher.app_select == 1:\n app.draw_pages()\n if launcher.app_select == 2:\n app.draw_explorer()\n if launcher.app_select == 3:\n try:\n app.draw_samples()\n except Exception as e:\n app.layer -= 1\n\n rgb = 0\n def rgb_change(rgb):\n cube_led.r.value(rgb & 0b001)\n cube_led.g.value(rgb & 0b010)\n cube_led.b.value(rgb & 0b100)\n\n @ui.warp_template(ui.blank_draw)\n #@ui.warp_template(ui.grey_draw)\n @catch\n def draw():\n ui.canvas.draw_rectangle((0, 0, ui.height, ui.weight),\n fill=True, color=(10, 10, 10))\n\n #app.btn.event()\n app.btn.expand_event()\n\n if app.btn.home() == 2: # click button release to 2\n print('into', app.layer)\n if app.layer == 1:\n app.layer += 1\n # launcher into application\n app.load_application(launcher.app_select)\n elif app.layer == 2:\n if app.btn.interval() > 1000: # long press\n app.layer -= 1\n if launcher.app_select == 1:\n ui.anime = None # Clear\n # application return launcher\n else:\n app.layer += 1\n # help into launcher\n\n if app.btn.next() == 1:\n app.rgb = (app.rgb + 1) % 8\n app.rgb_change(app.rgb)\n\n if app.btn.back() == 1:\n app.rgb = (app.rgb - 1) % 8\n app.rgb_change(app.rgb)\n\n if app.layer == 0:\n app.draw_load()\n elif app.layer == 1:\n # gc.collect()\n app.draw_launcher()\n elif app.layer == 2:\n app.exec_application()\n\n def run():\n button_io.config()\n cube_led.init(13, 12, 14, 32)\n sample_page.key_init()\n\n fm.register(30,fm.fpioa.I2C1_SCLK, force=True)\n fm.register(31,fm.fpioa.I2C1_SDA, force=True)\n\n axp173 = AXP173()\n axp173.enable_adc(True)\n # 默认充电限制在 4.2V, 190mA 档位\n axp173.setEnterChargingControl(True)\n axp173.exten_output_enable()\n taskbar.init(axp173)\n\n if CubeAudio.check():\n CubeAudio.ready()\n fm.register(19,fm.fpioa.I2S0_MCLK, force=True)\n fm.register(35,fm.fpioa.I2S0_SCLK, force=True)\n fm.register(33,fm.fpioa.I2S0_WS, force=True)\n fm.register(34,fm.fpioa.I2S0_IN_D0, force=True)\n fm.register(18,fm.fpioa.I2S0_OUT_D2, force=True)\n\n #app.ctrl.event(100, lambda *args: time.sleep(1))\n #app.ctrl.event(10, app.btn.event)\n app.ctrl.event(5, app.draw)\n while True:\n #import time\n #last = time.ticks_ms()\n while True:\n try:\n #print((int)(1000 / (time.ticks_ms() - last)), 'fps')\n #last = time.ticks_ms()\n app.ctrl.cycle()\n protect.keep()\n #time.sleep(0.1)\n except KeyboardInterrupt:\n protect.stop()\n raise KeyboardInterrupt()\n except Exception as e:\n # gc.collect()\n print(e)\n\n\n\nif __name__ == \"__main__\":\n # gc.collect()\n print_mem_free()\n app.run()\n","sub_path":"app/app_cube.py","file_name":"app_cube.py","file_ext":"py","file_size_in_byte":7581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"35555977","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/9/23 8:46\n# @Author : blvin.Don\n# @File : object_tracking_image.py\n\n\nimport cv2, pyautogui\nimport numpy as np\nimport win32ui\nimport tkinter as tk\nfrom tkinter import filedialog\n\nglobal point1, point2\nfrom math import fabs\nglobal start, elapsed\nimport time\nKp = 0.2\n# from UAV_tracking.Center import Get_Center\nfrom socket import *\nHOST = '192.168.0.101'\nPORT = 7896\ns = socket(AF_INET, SOCK_DGRAM)\ns.connect((HOST, PORT))\n\n\ndef get_time():\n now = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime(time.time()))\n return now\nfname = get_time()+r\"trajectory_info.txt\"\nfile = open('I:/PycharmProjects/UAV_ZSTU/UAV_tracking/logs/'+fname,'w')\nfile.close()\nfile = open('I:/PycharmProjects/UAV_ZSTU/UAV_tracking/logs/'+fname,'a')\ndef write_trajectory(file,msg):\n file.writelines(msg)\n file.writelines(\"\\n\")\n\n\n\ndef send_msg(a,b,c,d,e):\n message = str(str(a) + ',' + str(b) + ',' + str(c) + ',' + str(d)+ ',' + str(e))\n s.sendall(message.encode('utf-8'))\n print(\"send success!\")\n\n# send_msg(0,0,0,4,0)\n# write_trajectory(file,get_time()+\",\"+str((0,0,0,4,0)))\n\n\ndef get_zhongshu(alist):\n H_temp = []\n for h in alist:\n H_temp += list(h)\n counts = np.bincount(H_temp)\n return np.argmax(counts)\n\ndef myfind(x,y):\n return [ a for a in range(0,len(y),5) if y[a] == x]\n\ndef get_image():\n img = pyautogui.screenshot(region=[470, 0, 900, 425])\n img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)\n return img\n\n\ndef control_command(offset_x, offset_y):\n global start, elapsed\n if fabs(offset_x) > 10:\n delta_x = (offset_x / 450.00) *90*Kp\n print(\"X方向:\",0,0,delta_x, 4, 0)\n send_msg(0,0,delta_x, 4, 0)\n write_trajectory(file, get_time() + \",\" + str((0, 0, delta_x, 4, 0)))\n time.sleep(0.01)\n # if fabs(offset_x) <= 50:\n # send_msg(0, 0, 0, 0, 0)\n if fabs(offset_y) > 10:\n delta_y = -(offset_y / 212.50)*2\n print(\"Y方向:\",0, delta_y,0, 4, 0)\n send_msg(0, delta_y,0, 4, 0)\n write_trajectory(file, get_time() + \",\" + str((0, delta_y, 0, 4, 0)))\n start = time.clock()\n # if fabs(offset_y) <= 40:\n # send_msg(0, 0, 0, 0, 0)\n if fabs(offset_y) <= 10 and fabs(offset_x) <= 10:\n send_msg(0,0,0,0,0)\n write_trajectory(file, get_time() + \",\" + str((0, 0, 0, 0, 0)))\n elapsed = (time.clock() - start)\n print(\"Duration:\", elapsed)\n if elapsed > 3:\n print(\"emergent stop!\")\n send_msg(0, 0, 0, 0, 0)\n write_trajectory(file, get_time() + \",\" + str((0, 0, 0, 0, 0)))\n\ndef selectimg():\n root = tk.Tk()\n root.withdraw()\n file_path = filedialog.askopenfilename()\n #print(file_path)\n return file_path\n\n\ndef on_mouse(event, x, y, flags, param):\n global point1, point2,image\n #img = get_image()\n img=image\n img2 = img.copy()\n if event == cv2.EVENT_LBUTTONDOWN: #左键点击\n point1 = (x,y)\n cv2.circle(img2, point1, 10, (0,255,0), 5)\n # cv2.imshow('image', img2)\n elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): #按住左键拖曳\n cv2.rectangle(img2, point1, (x,y), (255,0,0), 5)\n cv2.imshow('image', img2)\n elif event == cv2.EVENT_LBUTTONUP: #左键释放\n point2 = (x,y)\n cv2.rectangle(img2, point1, point2, (0,0,255), 5)\n cv2.imshow('image', img2)\n min_x = min(point1[0], point2[0])\n min_y = min(point1[1], point2[1])\n width = abs(point1[0] - point2[0])\n height = abs(point1[1] - point2[1])\n cut_img = img[min_y:min_y + height, min_x:min_x + width]\n # print(cut_img.shape)\n Img2_HSV = cv2.cvtColor(cut_img, cv2.COLOR_BGR2HSV)\n H, S, V = cv2.split(Img2_HSV)\n H_Z, S_Z, V_Z = get_zhongshu(H), get_zhongshu(S), get_zhongshu(V)\n # print(H_Z, S_Z, V_Z)\n while True:\n img = get_image()\n HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n lower = np.array([int(H_Z) - 20, int(S_Z) - 20, int(V_Z) - 20])\n upper = np.array([int(H_Z) + 20, int(S_Z) + 20, int(V_Z) + 20])\n mask = cv2.inRange(HSV, lower, upper)\n mask = cv2.erode(mask, None, iterations=2)\n mask = cv2.dilate(mask, None, iterations=2)\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]\n if len(cnts)>0:\n c = max(cnts, key=cv2.contourArea)\n ((x,y),radius) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n print(\"center:\",center)\n offset_x = center[0] - 450\n offset_y = center[1] - 213\n print(\"offset:\",offset_x,offset_y)\n msg = control_command(offset_x,offset_y)\n # If track object\n if radius > 5:\n msg = control_command(offset_x, offset_y)\n cv2.circle(img, (int(x),int(y)), int(radius), (255, 0, 0), 2)\n else:\n send_msg(0, 0, 30, 4, 0)\n write_trajectory(file, get_time() + \",\" + str((0, 0, 30, 4, 0)))\n else:\n send_msg(0, 0, 30, 4, 0)\n write_trajectory(file, get_time() + \",\" + str((0, 0, 30, 4, 0)))\n cv2.imshow('image', img)\n if cv2.waitKey(10) == 27:\n break\n\n\n\n\ndef main():\n cv2.namedWindow('image')\n #img = get_image()\n file_path = selectimg()\n print(file_path)\n global image\n image = cv2.imread(file_path)\n place = cv2.setMouseCallback('image', on_mouse)\n cv2.imshow('image', image)\n cv2.waitKey(0)\n\nif __name__ == '__main__':\n main()","sub_path":"object_tracking_image.py","file_name":"object_tracking_image.py","file_ext":"py","file_size_in_byte":5809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"30392391","text":"import torch\nfrom torch import nn\n\n\nclass Tacotron2Loss(nn.Module):\n def __init__(self):\n super(Tacotron2Loss, self).__init__()\n\n def forward(self, model_output, targets):\n mel_target, gate_target = targets[0], targets[1]\n mel_target.requires_grad = False\n gate_target.requires_grad = False\n gate_target = gate_target.view(-1, 1)\n\n mel_out, mel_out_postnet, gate_out, _ = model_output\n gate_out = gate_out.view(-1, 1)\n mel_loss = nn.MSELoss()(mel_out, mel_target) + \\\n nn.MSELoss()(mel_out_postnet, mel_target)\n gate_loss = nn.BCEWithLogitsLoss()(gate_out, gate_target)\n return mel_loss + gate_loss\n\n\nclass TPCWLoss(nn.Module):\n def __init__(self):\n super().__init__()\n\n @staticmethod\n def cross_entropy(w_combination, target):\n return -(target * torch.log(w_combination)).sum(dim=1).mean()\n\n def forward(self, w_combination, target):\n \"\"\"\n calculates cross-entropy loss over soft classes (GSTs distributions) and predicted weights\n :param w_combination: predicted combination weights tensor shape of (batch_size, token_num)\n or (batch_size, atn_head_num, token_num)\n :param target: GSTs' combination weights tensor shape of (batch_size, token_num)\n or (batch_size, atn_head_num, token_num)\n :return: cross-entropy loss value or sum of cross-entropy loss values\n \"\"\"\n if w_combination.dim() == 2:\n return self.cross_entropy(w_combination, target)\n else:\n losses = []\n for atn_head_index in range(w_combination.size(1)):\n loss = self.cross_entropy(w_combination[:, atn_head_index, :], target[:, atn_head_index, :])\n losses.append(loss)\n return sum(losses)\n\n\nclass TPSELoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.l1 = nn.L1Loss()\n\n def forward(self, predicted_tokens, target):\n \"\"\"\n calculate L1 loss function between predicted and target GST\n :param predicted_tokens: tensor shape of (batch_size, token_dim)\n :param target: tensor shape of (batch_size, token_dim)\n :return: L1 loss\n \"\"\"\n return self.l1(predicted_tokens, target)\n","sub_path":"loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"374199565","text":"#!/usr/bin/python\n#coding:utf-8\n\n# 2013/03/23\n'''\n# Button\nwxPythonにおける最も基本的な部品の一つであるButtonの紹介です。\n様々なイベントの起点となる部品でもあるので、是非覚えておきましょう。\n\n# 基本的な使い方\nパネルへボタンを追加しています。\nコンストラクタには(親ウィンドウ、識別子、ラベル)の順番で渡しています。\n'''\n\nimport wx\n\napplication = wx.App()\nframe = wx.Frame(None,wx.ID_ANY,\"テストフレーム\",size=(300,200))\npanel = wx.Panel(frame,wx.ID_ANY)\npanel.SetBackgroundColour(\"#AFAFAF\")\nbutton_1 = wx.Button(panel,wx.ID_ANY,\"ボタン1\") # パネルへボタンを追加. コンストラクタには(親ウィンドウ、識別子、ラベル)の順番で渡しています\nbutton_2 = wx.Button(panel,wx.ID_ANY,\"ボタン2\") # パネルへボタンを追加\nbutton_3 = wx.Button(panel,wx.ID_ANY,\"ボタン3\") # パネルへボタンを追加\n\nlayout = wx.BoxSizer(wx.VERTICAL)\n\nlayout.Add(button_1)\nlayout.Add(button_2)\nlayout.Add(button_3)\n\npanel.SetSizer(layout)\n\nframe.Show()\n\napplication.MainLoop()\n\n'''\n# ラベル設定\n先程のサンプルではコンストラクタにてラベル(ボタンに表示される文字)を指定していました。\nもちろんラベルを変更する関数も用意されています。\n'''\n\nbutton_3.SetLabel(\"Button3\")\n\n'''\n# ボタンサイズ設定\nボタンのサイズを変更するにはコンストラクタへ「size」を渡します。\nそれ以外にも「SetSize」「SetMaxSize」「SetMinSize」関数でも設定可能ですが、\nSizerの設定に依存する場合もあるので注意しましょう。\n'''\n\nbutton_3 = wx.Button(panel,wx.ID_ANY,\"ボタン3\",size=(50,50))\n# button_3.SetSize((50,50))\n# button_3.SetMaxSize((50,50))\n# button_3.SetMinSize((50,50))\n\n'''\n# フォント設定\nボタンのフォント(文字の大きさや太字設定)を変更するには「SetFont」関数を使用します。\n19行目にて使用するFontクラスを初期化しています。\n'''\n\nfont = wx.Font(20,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL)\nbutton_3.SetFont(font)\n\n'''\n# 文字色設定\nボタンの文字色の変更には「SetForegroundColour」関数を使用します。\nサンプルでは赤へ変更しています。\n'''\n\nbutton_3.SetForegroundColour(\"#FF0000\")\n\n'''\n# 背景色設定\nボタンの背景色の変更は「SetBackgroundColour」関数を使用します。\nサンプルでは青へ変更しています。\n'''\nbutton_3.SetBackgroundColour(\"#0000FF\")\n\n'''\n# 有効・無効設定\nボタンを無効(押せない状態)にするには「Disable」関数を使用します。\nそれとは逆に無効状態となっているボタンを有効(押せる状態)へ変更するには「Enable」関数を使用しましょう。\n'''\n\nbutton_3.Disable()\n# button_3.Enable()\n\n'''\n# ツールチップ設定\nボタンへツールチップ(補足情報を載せる小さいウィンドウ)を表示させるには「SetToolTipString」関数を使用します。\n'''\n\nbutton_3.SetToolTipString(\"python-izm.com\")\n\n'''\n# 表示・非表示設定\nボタンを非表示にするには「Hide」関数を使用しましょう。\n非表示状態のボタンを表示させるには「Show」関数を用います。\n尚、ボタンは「見えない」だけで本体は存在しています。\n非表示状態のボタンに対してラベル設定をしたりする事も可能です。\n'''\n\nbutton_3.Hide()\n# button_3.Show()\n\n'''\n# イベント設定\nボタンへイベントを設定するには「Bind」関数を使用します。\n引数には(イベント種別、イベント発生時に呼び出す関数)の順番で値を渡し、\n「ボタン1」と「ボタン2」ではそれぞれ違う関数を定義してイベント設定しています。\n「ボタン3」と「ボタン4」では、引数に「イベント発生元」を追加し、ボタン初期化時のIDで判別して挙動を変えています。\n尚、サンプルでもあるように、ボタン・フレームのどちらにBindしてもイベントはきちんと動作します。\n'''\n\ndef click_button_1(event):\n frame.SetStatusText(\"Click! button_1\")\n\ndef click_button_2(event):\n frame.SetStatusText(\"Click! button_2\")\n\ndef click_button(event):\n if event.GetId() == 3333:\n frame.SetStatusText(\"Click! button_3\")\n elif event.GetId() == 4444:\n frame.SetStatusText(\"Click! button_4\")\n\nbutton_1.Bind(wx.EVT_BUTTON,click_button_1)\nbutton_2.Bind(wx.EVT_BUTTON,click_button_2)\nframe.Bind(wx.EVT_BUTTON,click_button,button_3)\nframe.Bind(wx.EVT_BUTTON,click_button,button_4)\n\n","sub_path":"3rd_party/wx/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"619940662","text":"#!/usr/bin/env python\nimport sys\nimport os\nsys.path.append( os.path.realpath( os.path.join(os.path.dirname( os.path.abspath( __file__)) , \"../\") ))\n\ntry:\n from unittest2 import TestLoader, TextTestRunner\nexcept ImportError:\n from unittest import TestLoader, TextTestRunner\n\n\ndef runTestsInDirectory(path=\".\"):\n loader = TestLoader()\n tests = loader.discover(path)\n testRunner = TextTestRunner()\n testRunner.run(tests)\n\n\ndef runTestsInClass(classpath):\n klass = importClass(classpath)\n loader = TestLoader()\n tests = loader.loadTestsFromTestCase(klass)\n testRunner = TextTestRunner()\n testRunner.run(tests)\n\n\ndef importClass(classpath):\n dot = classpath.rfind(\".\")\n classname = classpath[dot + 1:len(classpath)]\n m = __import__(classpath[0:dot], globals(), locals(), [classname])\n return getattr(m, classname)\n\n\ndef getTestsFromTestClass(test_class_path, argv=None):\n klass = importClass(test_class_path)\n klass.argv = argv\n loader = TestLoader()\n return loader.loadTestsFromTestCase(klass)\n\n\nif __name__ == '__main__':\n runTestsInDirectory()\n","sub_path":"devel/python/test/ert_tests/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"613564660","text":"# Run this script as root\r\n\r\nimport time\r\nimport os\r\nfrom datetime import datetime as dt\r\nfrom http.server import SimpleHTTPRequestHandler, HTTPServer\r\nimport csv\r\nimport threading\r\nimport time\r\nimport http.server\r\nimport socketserver\r\nexitFlag = 0\r\n\r\nos.system('ipconfig/flushdns')\r\nos.system('nbtstat -R')\r\nprint(\"[ INFO ] PID = \",os.getpid())\r\ndef webFilter():\r\n # change hosts path according to your OS\r\n hosts_path = r\"C:\\Windows\\System32\\drivers\\etc\\hosts\"\r\n # localhost's IP\r\n redirect = \"127.0.0.1\"\r\n\r\n lines_in_header= 9\r\n\r\n website_list = []\r\n try:\r\n with open('csv.txt', newline='') as csvfile:\r\n count =0\r\n #read in lines from file\r\n\r\n lines = csvfile.readlines()\r\n sites = [line.strip() for line in lines]\r\n\r\n # remove header lines from array\r\n sites = sites[lines_in_header:]\r\n sites = sites[:10]\r\n for site in sites:\r\n\r\n print(site)\r\n print()\r\n # Data process site to be an array of arrays of site info\r\n site = site.replace('\"', '')\r\n site=site.split(\",\")\r\n\r\n #Format for site = [id,dateadded,url,url_status,threat,tags,urlhaus_link,reporter]\r\n #example site =\r\n #['1068863', '2021-03-15 14:22:05', 'http://59.99.143.111:33869/bin.sh',\r\n #'offline', 'malware_download', '32-bit', 'elf', 'mips', 'https://urlhaus.abuse.ch/url/1068863/', 'geenensp']\r\n\r\n if site[3] == \"online\":\r\n website_list.append(site[2])\r\n except:\r\n print(\"[ ERROR ] Could not read in blocked websites. \")\r\n exit(-1)\r\n for site in website_list:\r\n print(site)\r\n\r\n # websites that we can visit to test\r\n test_list = [\"www.facebook.com\",\"facebook.com\",\r\n \"dub119.mail.live.com\",\"www.dub119.mail.live.com\",\r\n \"www.gmail.com\",\"gmail.com\"]\r\n\r\n print(\"Sites to test this with: \")\r\n for site in test_list:\r\n print(site)\r\n website_list.append(site)\r\n\r\n\r\n try:\r\n with open(hosts_path, 'r+') as file:\r\n content = file.read()\r\n for website in website_list:\r\n if website in content:\r\n pass\r\n else:\r\n if(website in test_list):\r\n print(\"site not in content already: \"+website)\r\n # mapping hostnames to your localhost IP address\r\n file.write(redirect + \" \" + website + \"\\n\")\r\n\r\n except KeyboardInterrupt:\r\n print(\"\\n[ INFO ] Ending program please wait... \")\r\n with open(hosts_path, 'r+') as file:\r\n content=file.readlines()\r\n file.seek(0)\r\n for line in content:\r\n if not any(website in line for website in website_list):\r\n file.write(line)\r\n\r\n # removing hostnames from host file\r\n file.truncate()\r\n print(\"\\n[ INFO ] Program ended by Ctrl-C. \")\r\n os._exit(1)\r\n\r\n\r\n #Start hosting local page\r\n HOST, PORT = \"127.0.0.1\", 80\r\n Handler = http.server.SimpleHTTPRequestHandler\r\n # Create the server, binding to localhost on port 9999\r\n with socketserver.TCPServer((HOST, PORT), Handler) as server:\r\n try:\r\n # Activate the server; this will keep running until you\r\n # interrupt the program with Ctrl-C\r\n server.serve_forever()\r\n except KeyboardInterrupt:\r\n print(\"\\n[ INFO ] Ending program please wait... \")\r\n with open(hosts_path, 'r+') as file:\r\n content=file.readlines()\r\n file.seek(0)\r\n for line in content:\r\n if not any(website in line for website in website_list):\r\n file.write(line)\r\n\r\n # removing hostnames from host file\r\n file.truncate()\r\n print(\"\\n[ INFO ] Program ended by Ctrl-C. \")\r\n server.server_close()\r\n exit(0)\r\n\r\n\r\n\r\nwebFilter()\r\n#print(\"[ INFO exited web filter\")\r\n","sub_path":"Hosts_File_Filter.py","file_name":"Hosts_File_Filter.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"29111955","text":"\nimport logging\nfrom django.contrib.auth import get_user_model\nfrom rest_framework.exceptions import NotFound\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.generics import ListAPIView\nfrom rest_framework.response import Response\nimport jdatetime\nfrom zerone_inc.zeroslack.models import Attendance\nfrom .serializers import AttendanceSerializer\n\nlogger = logging.getLogger(__name__)\nUser = get_user_model()\n\n\nclass AttendanceDashboard(ListAPIView):\n http_method_names = ['get', ]\n permission_classes = [IsAuthenticated, ]\n serializer_class = AttendanceSerializer\n renderer_classes = [JSONRenderer, ]\n\n def get_date_range(self) -> tuple:\n \"\"\"Return the year for which this view should display data.\"\"\"\n year = self.kwargs.get('year', jdatetime.datetime.today().year)\n month = self.kwargs.get('month', jdatetime.datetime.today().month)\n format = \"%Y-%m\"\n datestr = f\"{year}-{month}\"\n start_date = jdatetime.datetime.strptime(datestr, format).date()\n end_date = start_date + jdatetime.timedelta(days=30)\n try:\n return start_date.togregorian(), end_date.togregorian()\n except ValueError:\n raise NotFound('Invalid date string “%(datestr)s” given format “%(format)s”' % {\n 'datestr': datestr,\n 'format': format,\n })\n\n def get_queryset(self):\n return Attendance.objects.filter(user=self.request.user)\n\n def get(self, request, *args, **kwargs):\n start_date, end_date = self.get_date_range()\n queryset = self.request.user.get_list_of_signins(start_date=start_date, end_date=end_date)\n serializer = self.get_serializer(queryset, many=True)\n return Response(data={\n 'data': serializer.data,\n \"draw\": request.GET.get('draw', 1),\n \"recordsTotal\": queryset.count(),\n \"recordsFiltered\": queryset.count(),\n })\n","sub_path":"zerone_inc/zeroslack/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"276017286","text":"# Copyright (C) 2012 Hiroki Horiuchi \n#\n# [GNU all-permissive license]\n# Copying and distribution of this file, with or without modification,\n# are permitted in any medium without royalty provided the copyright\n# notice and this notice are preserved.\n# This file is offered as-is, without any warranty.\n\nr'''\npath_to_prefix('.') + 'a' -> 'a'\npath_to_prefix('a') + 'b' -> 'a/b'\n'''\n\nfrom os.path import relpath, join\n\ndef path_to_prefix(path):\n r'''\n '.' -> ''; 'a' -> 'a/'... (Unix case).\n for more information, refer to the test.\n '''\n path = relpath(path)\n return '' if path == '.' else join(path, '')\n\nif __name__ == '__main__':\n raise Exception('making a module executable is a bad habit.')\n","sub_path":"last-dropbox/jcheck/com/appspot/x19290/pathtoprefix.py","file_name":"pathtoprefix.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"653669500","text":"# coding=UTF-8\nimport tensorflow as tf\nfrom skimage.io import imsave\nfrom skimage.transform import resize\nimport cv2\nimport os\nimport numpy as np\n\nfor filename in os.listdir('JPEGImages'):\n print(filename)\n image = cv2.imread('JPEGImages/'+filename)\n h = image.shape[0]#image 高度\n w = image.shape[1]#image 宽度\n\n if w > h:\n image = cv2.resize(image, (int(224 * w / h), 224))#转换成 resize:(image_size * w / h) * image_size ,按比例缩放成176 * 176\n crop_start = np.random.randint(0, int(224 * w / h) - 224 + 1)\n image = image[:, crop_start:crop_start + 224, :]#截取宽度为image_size .iamge_size * image_size 大小的图片\n else:\n image = cv2.resize(image, (224, int(224* h / w)))\n crop_start = np.random.randint(0, int(224 * h / w) - 224 + 1)\n image = image[crop_start:crop_start + 224, :, :]#截取高度为image_size .* image_size 大小的图片\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)#转换图片BGR格式到RGB格式\n imsave('results/' + filename, image)#储存图片","sub_path":"getCroppedImage.py","file_name":"getCroppedImage.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"364051626","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/hanzo/warcvalid.py\n# Compiled at: 2013-01-14 05:25:26\n\"\"\"warcvalid - check a warc is ok\"\"\"\nimport os, sys, sys, os.path\nfrom optparse import OptionParser\nfrom .warctools import WarcRecord, expand_files\nparser = OptionParser(usage='%prog [options] warc warc warc')\nparser.add_option('-l', '--limit', dest='limit')\nparser.add_option('-I', '--input', dest='input_format')\nparser.add_option('-L', '--log-level', dest='log_level')\nparser.set_defaults(output_directory=None, limit=None, log_level='info')\n\ndef main(argv):\n options, input_files = parser.parse_args(args=argv[1:])\n out = sys.stdout\n if len(input_files) < 1:\n parser.error('no imput warc file(s)')\n correct = True\n fh = None\n try:\n try:\n for name in expand_files(input_files):\n fh = WarcRecord.open_archive(name, gzip='auto')\n for offset, record, errors in fh.read_records(limit=None):\n if errors:\n print >> sys.stderr, 'warc errors at %s:%d' % (name, offset)\n print >> sys.stderr, errors\n correct = False\n break\n elif record is not None and record.validate():\n print >> sys.stderr, 'warc errors at %s:%d' % (name, offset)\n print >> sys.stderr, record.validate()\n correct = False\n break\n\n except StandardError as e:\n correct = False\n\n finally:\n if fh:\n fh.close()\n\n if correct:\n return 0\n else:\n return -1\n return\n\n\ndef run():\n sys.exit(main(sys.argv))\n\n\nif __name__ == '__main__':\n run()","sub_path":"pycfiles/hanzo_warctools-4.7-py2.7/warcvalid.py","file_name":"warcvalid.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"594724770","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n\n\n# plot distribution of mse's for true/pred\n\ndef plot_power_spectrum(map_predict, map_true, residual=False, save=False):\n '''\n plot the power spectra and the difference\n\n inputs\n map, predicted\n map, true\n\n outputs\n figure\n\n help from: https://bertvandenbroucke.netlify.app/2019/05/24/computing-a-power-spectrum-in-python/\n '''\n\n # frequency values\n kfreq = np.fft.fftfreq(map_true.shape[0]) * map_true.shape[0]\n kfreq2D = np.meshgrid(kfreq, kfreq)\n knrm = np.sqrt(kfreq2D[0]**2 + kfreq2D[1]**2)\n knrm = knrm.flatten()\n\n # calculate 2d fft\n map_true_fourier = np.fft.fft2(map_true)\n map_predict_fourier = np.fft.fft2(map_predict)\n\n # amplitudes\n fourier_amplitudes_true = np.abs(map_true_fourier)**2\n fourier_amplitudes_true = fourier_amplitudes_true.flatten()\n\n fourier_amplitudes_predicted = np.abs(map_predicted_fourier)**2\n fourier_amplitudes_predicted = fourier_amplitudes_predicted.flatten()\n\n kbins = np.arange(0.5, map_true.shape[0]/2. + 1., 1.)\n kvals = 0.5 * (kbins[1:] + kbins[:-1])\n\n Abins_true, _, _ = stats.binned_statistic(knrm, fourier_amplitudes_true,\n statistic = \"mean\",\n bins = kbins)\n Abins_true *= 4. * np.pi / 3. * (kbins[1:]**3 - kbins[:-1]**3)\n\n\n Abins_predicted, _, _ = stats.binned_statistic(knrm, fourier_amplitudes_predicted,\n statistic = \"mean\",\n bins = kbins)\n Abins_predicted *= 4. * np.pi / 3. * (kbins[1:]**3 - kbins[:-1]**3)\n\n plt.loglog(kvals, Abins_true)\n plt.loglog(kvals, Abins_predicted)\n plt.xlabel(\"$k$\")\n plt.ylabel(\"$P(k)$\")\n plt.tight_layout()\n\n if save:\n plt.savefig(\"power_spectrum.png\", dpi = 300, bbox_inches = \"tight\")\n\n\n\n\ndef plot_map_difference(map_predict, map_true, fft=False, residual=False, percentage=False, save=False):\n '''\n plot a map that is the difference between two maps\n\n inputs\n map, predicted\n map, true\n\n outpus\n figure\n\n '''\n\n # calculate 2d fft\n if fft:\n map_true = np.fft.fft2(map_true)\n map_predict = np.fft.fft2(map_predict)\n\n # calculate difference\n map_difference = map_true - map_predict\n\n # calculate residual\n if residual:\n map_difference /= map_true\n if percentage:\n map_difference *= 100.\n\n # plot images\n print(map_true.shape[0])\n print(map_true.shape[1])\n\n #plt.figure(figsize=(map_true.shape[0] , map_true.shape[1]))\n plt.figure()\n\n plt.subplot(131)\n plt.imshow(map_true)\n\n plt.subplot(132)\n plt.imshow(map_predict)\n\n plt.subplot(133)\n plt.imshow(map_difference)\n\n\n\n plt.tight_layout()\n plt.show()\n if save:\n plt.savefig(file_fig)\n\n\ndef read_history(filename, metric_name=\"loss\"):\n '''\n open files for metric history\n\n inputs\n filename\n\n outputs\n metrics\n '''\n\n data = pd.read_csv('data.csv')\n if metric_name is \"loss\":\n output = data['loss'], data['valid_loss']\n elif metric_name is \"accuracy\":\n output = data['acc'], data['valid_acc']\n return output\n\n\ndef plot_history(epochs, metric_train, metric_name, metric_valid=None, save=False, figsize=(10,10)):\n '''\n plot loss history for training and validation\n\n inputs\n epochs\n metric --- loss or accuracy\n metric name --- \"loss\" or \"accuracy\"\n\n outpus\n figure\n\n '''\n\n plt.figure(figsize=figsize)\n plt.plot(epochs, metric_train)\n if metric_valid is not None:\n plt.plot(epochs, metric_valid)\n plt.xlabel(\"Epoch\")\n plt.ylabel(metric_name)\n plt.show()\n if save:\n plt.savefig(file_fig)\n\ndef read_images():\n model_dir = 'unet/'\n os.makedirs(model_dir, exist_ok=True)\n width = 512\n in_data = np.load(f'data_v0_circle_radius_{width}_64_image.npy')\n out_data = np.load(f'data_v0_circle_radius_{width}_64_depth.npy')\n\n\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"651998890","text":"#!/bin/python\nproblem='A'\n\n\nimport sys\n\n\ndef solve(n):\n def canonical(s):\n o=''\n for c in s:\n if not o or o[-1]!=c :\n o+=c\n return o\n\n if len(n)<2:\n return 0\n can=canonical(n[0])\n for s in n[1:]:\n if can!=canonical(s):\n return -1\n \n ss=[]\n for s in n:\n sss=[]\n for c in can:\n cc=-1\n while s and s[0]==c:\n cc+=1\n s=s[1:]\n sss.append(cc) \n ss.append(tuple(sss))\n# print ss\n\n res=0\n\n for r in xrange(len(can)):\n vs = [xx[r] for xx in ss]\n bestmove=None\n# print 'retying', min(vs), max(vs)+1\n for vset in xrange(min(vs), max(vs)+1):\n moves=0\n for v in vs:\n# print 'in', vset, v\n moves+=abs(vset-v)\n# print 'moves', moves, bestmove\n if bestmove==None or bestmove > moves:\n bestmove=moves\n res+=bestmove\n return res\n\n\ndef doall(outf, testcases, lines):\n case = 1\n\n while lines:\n n = int(lines[0])\n nn = [l.strip() for l in lines[1:n+1]]\n lines=lines[n+1:]\n \n s=solve(nn)\n if s<0:\n s='Fegla Won'\n else:\n s=str(s)\n print >> outf, 'Case #%d: %s'%(case,s)\n\n case+=1\n\n\ndef readin(infile):\n print >> sys.stderr, \"reading from \" + infile\n lines=open(infile, 'r').readlines()\n testcount = int(lines[0])\n print >> sys.stderr, \"read %d test cases from %d lines\"%(testcount, len(lines))\n lines=lines[1:]\n return testcount, lines\n\nif __name__ == '__main__': \n if len(sys.argv) == 1:\n inf='A-test.in'\n outf=sys.stdout\n print >> sys.stderr, \"writing to stdout \"\n elif len(sys.argv) == 3:\n input_name_format='{problem}-{input}-{id}.in'\n output_name_format='{problem}-{input}-{id}.out'\n\n inf=str.format(input_name_format, problem=problem, input=sys.argv[1], id=int(sys.argv[2]))\n outf=str.format(output_name_format, problem=problem, input=sys.argv[1], id=int(sys.argv[2]))\n print >> sys.stderr, \"writing to \"+outf\n outf = open(outf,'w')\n else:\n print >> sys.stderr, \"bad args\"\n sys.exit(1)\n tc, l = readin(inf)\n doall(outf, tc, l)\n print >> sys.stderr, \"done\"\n\n","sub_path":"solutions_5751500831719424_1/Python/MarkFinn/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"313386706","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nfrom statsmodels.tsa.api import VAR, DynamicVAR\nfrom netCDF4 import Dataset\n\n\ndef lag_correlation(var1,var2,nlag):\n\n ntime=len(var1)\n max_cor=0.0 # maximum correlation coefficient\n max_lag=0.0 # Lag number with maximum correlation coefficient\n\n for i in np.arange(nlag):\n cor = np.corrcoef(var1[0:ntime-i-1], var2[i:ntime-1])[0, 1]\n if (abs(cor) > abs(max_cor)):\n max_cor = cor\n max_lag = i\n \n max_ind = var2.argmax() # Index of time with maximum value of Var2\n max_ind = (max_ind+1)%12 # Convert the number to 1-12 (Jan-Dec)\n if (max_ind ==0): max_ind=12\n \n return (max_cor,max_lag,max_ind) \n\n\n################################\n# Main program starts here #\n\nENSO=np.loadtxt(\"ENSO_index_195001_201712.txt\")\n\nnc_f= 'precip.mon.mean.nc'\nnc_fid=Dataset(nc_f,'r')\nlats = nc_fid.variables['lat'][:] \nlons = nc_fid.variables['lon'][:]\ntime = nc_fid.variables['time'][:]\nprecip = nc_fid.variables['precip'][:,:,:]\n\nnlon= len(lons)\nnlat= len(lats)\nmax_cor2 = np.zeros((nlat,nlon))\nmax_lag2 = np.zeros((nlat,nlon))\nmax_ind2 = np.zeros((nlat,nlon))\n\nnc_f2= 'land.nc'\nnc_fid2=Dataset(nc_f2,'r')\nland = nc_fid2.variables['land'][:]\n\nfor i in np.arange(nlat):\n for j in np.arange(nlon):\n #if (land[0,i,j] < 1):\n var2=precip[0:467,i,j]\n var1=ENSO[348:815]\n results=lag_correlation(var1,var2,7)\n max_cor2[i,j]=results[0]\n max_lag2[i,j]=float(results[1])\n max_ind2[i,j]=float(results[2]) \n\nfile = open('max_cor_Precip_lagged_by_ENSO.txt','w')\nnp.savetxt(file,max_cor2,'%10.6f') \nfile.close() \n\nfile = open('max_lag_Precip_lagged_by_ENSO.txt','w')\nnp.savetxt(file,max_lag2,'%6.2f')\nfile.close()\n\nfile = open('max_ind_Precip_lagged_by_ENSO.txt','w')\nnp.savetxt(file,max_ind2,'%6.2f')\nfile.close()\n\n","sub_path":"year-1-projects/team-4/Maximum_Lag_Correlation/Read_lag_correlation_Precip_by_ENSO.py","file_name":"Read_lag_correlation_Precip_by_ENSO.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"96944539","text":"from django import forms\n\nfrom .models import Book\n\n\nclass AuthorForm(forms.ModelForm):\n\n books = forms.ModelMultipleChoiceField(\n Book.objects.all(),\n required=False,\n )\n\n def __init__(self, *args, **kwargs):\n print('__init__ called')\n super(AuthorForm, self).__init__(*args, **kwargs)\n if self.instance.pk:\n print('='*20)\n print(self.instance.pk)\n self.initial['books'] = self.instance.books.values_list(\n 'pk', flat=True)\n\n def save(self, *args, **kwargs):\n print('save called')\n instance = super(AuthorForm, self).save(*args, **kwargs)\n if instance.pk is None:\n instance.save()\n if instance.pk:\n print('save')\n print(self.cleaned_data['books'])\n print(instance.books.all())\n for book in instance.books.all():\n if book not in self.cleaned_data['books']:\n instance.books.remove(book)\n for book in self.cleaned_data['books']:\n if book not in instance.books.all():\n instance.books.add(book)\n return instance\n","sub_path":"site/playground/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"282757200","text":"import pandas as pd\nimport turtle as tt\n\n\ndef get_mouse_click_coor(x, y):\n print(x, y)\n\n\nscreen = tt.Screen()\nscreen.title(titlestring=\"US States Game\")\nimage = \"blank_states_img.gif\"\nscreen.addshape(image)\ntt.shape(image)\n\nscreen.listen()\ntt.onscreenclick(get_mouse_click_coor)\n\nis_game_done = False\ndf = pd.read_csv(\"50_states.csv\")\n\nprint(df.state)\n\nguessed_states = []\nmissed_states = []\n\nprint(df.state.shape[0])\nprint(df.shape)\n\nwhile len(guessed_states) < df.state.shape[0]:\n\n if len(guessed_states) == 0:\n answer = screen.textinput(title=\"Guess the State\", prompt=\"What's another state's name?\").title()\n else:\n answer = screen.textinput(title=f\"{len(guessed_states)}/{df.state.shape[0]} Correct\",\n prompt=\"What's another state's name?\").title()\n\n if answer == \"Quit\":\n # CHANGE to COMPREHENSION\n # for state in df.state:\n # if state not in guessed_states:\n # missed_states.append(state)\n missed_states = [state for state in df.state if state not in guessed_states]\n\n print(missed_states)\n break\n\n if answer in df.state.tolist():\n data = df[df.state == answer]\n # print(data)\n # print(data.x.item())\n # print(data.y.item())\n temp_tt = tt.Turtle()\n temp_tt.penup()\n temp_tt.hideturtle()\n # temp_tt.goto(data.x.item(), data.y.item())\n temp_tt.goto(int(data.x), int(data.y))\n temp_tt.write(data.state.item())\n guessed_states.append(answer)\n\n# states to learn csv\n# https://stackoverflow.com/a/42133330/9795114\nif len(guessed_states) < df.state.shape[0]:\n states = df[~df.state.isin(guessed_states)]\n # https://cmdlinetips.com/2018/04/how-to-reset-index-in-pandas-dataframe/\n # states.reset_index(drop=True)\n states.to_csv(\"states_to_learn.csv\")\n\n# keep the screen open\ntt.mainloop()\n","sub_path":"day_26_nato/list/us_states_comprehension.py","file_name":"us_states_comprehension.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"588058031","text":"import os\r\nimport sys\r\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\r\n\r\nimport numpy as np\r\nimport openpyxl\r\nimport pandas as pd\r\n\r\nimport calendar\r\n\r\ndef read_dir(path,name):\r\n path_dir = f'{path}{name}/'\r\n try:\r\n year = sys.argv[2]\r\n print('read files in {}{}/' .format(path_dir, year))\r\n read_worksheet(path_dir, int(year))\r\n except:\r\n files_name = os.listdir(path_dir)\r\n years = [f for f in files_name if os.path.isdir(os.path.join(path_dir,f))]\r\n for year in years:\r\n print('read files in {}{}/' .format(path_dir, year))\r\n read_worksheet(path_dir, int(year))\r\n\r\ndef read_worksheet(path_dir, year):\r\n # 直下は共通なので def read_worksheet の外に置いてもよいか\r\n c_1 = ['B','C','D','E','F','G','H','I','J','K','L','M','N']\r\n c_2 = ['P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB']\r\n col = [c_1, c_2]\r\n early = 16\r\n late = 15\r\n r_1 = [5+2*i for i in range(early)]\r\n r_2 = [5+2*i for i in range(late)]\r\n row = [r_1, r_2]\r\n skip = [1, 11, 12]\r\n time = [3, 4, 7, 8, 9 ,10]\r\n dual = [5, 6]\r\n\r\n data = []\r\n for m in range(12):\r\n month = m+1\r\n date_max = calendar.monthrange(year, month)[1]\r\n\r\n path_xlsx = f'{path_dir}/{year}/{month}_work.xlsx'\r\n wb = openpyxl.load_workbook(path_xlsx, data_only=True)\r\n ws = wb[wb.sheetnames[0]]\r\n\r\n sums = [0 for i in range(13)]\r\n for tag in range(2):\r\n for i,r in enumerate(row[tag]):\r\n value = [month]\r\n for j,c in enumerate(col[tag]):\r\n if j in skip:\r\n continue\r\n elif j in time:\r\n try:\r\n value.append(float(ws[c+str(r)].value))\r\n except:\r\n value.append(0.0)\r\n else:\r\n sums[j] += value[-1]\r\n elif j in dual:\r\n value.append(ws[c+str(r)].value)\r\n value.append(ws[c+str(r+1)].value)\r\n else:\r\n value.append(ws[c+str(r)].value)\r\n\r\n data.append(value)\r\n if i+early*tag+1 == date_max:\r\n break\r\n\r\n # 集計行\r\n tag = 1\r\n r = 35\r\n data.append([month])\r\n for j,c in enumerate(col[tag]):\r\n if j in skip:\r\n continue\r\n elif j in time:\r\n data[-1].append(sums[j])\r\n elif j in dual:\r\n data[-1].append(ws[c+str(r)].value)\r\n data[-1].append(ws[c+str(r+1)].value)\r\n else:\r\n data[-1].append(ws[c+str(r)].value)\r\n\r\n columns = ['月', '日', '業内', '定められた勤務時間', '減額時間', '休憩時間(1)', '超過勤務時間(1)', '休憩時間(2)', '超過勤務時間(2)', '超過勤務等(100/100)', '超過勤務等(125/100)', '超過勤務等(25/100)', 'その他']\r\n df = pd.DataFrame(data, columns=columns)\r\n df.to_csv(f'{path_dir}/{year}_workdata.csv')\r\n\r\nif __name__ == '__main__':\r\n path = './data/'\r\n try:\r\n name = sys.argv[1]\r\n print('read files in {}{}/' .format(path, name))\r\n read_dir(path,name)\r\n except:\r\n files = os.listdir(path)\r\n names = []\r\n for f in files:\r\n if os.path.isdir(os.path.join(path,f)):\r\n names.append(f)\r\n for name in names:\r\n print('read files in {}{}/' .format(path,name))\r\n read_dir(path,name)\r\n","sub_path":"AutoWorksheet/read_worksheet_ver2.py","file_name":"read_worksheet_ver2.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"605074905","text":"# plot Cemona_Plan\n\nfrom utilities.plot_utilities import save_to_pdf\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D as PLine2D\nfrom matplotlib import colors as mcolors\nimport matplotlib.patches as patches\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n# geplottet werden müssen: self.points, self.ex_forces, self.members, self.reactions\n\n# member_limits and segment for plot\n# Achsen Zeichnen und beschriften\n# plot solved system\n\n\ndef get_limits_and_points_for_plot(points, offset_factor=0.25):\n x = []\n y = []\n\n p_id = []\n\n for point_id in points:\n x0 = points[point_id].coordinates[0]\n y0 = points[point_id].coordinates[1]\n\n x.append(x0)\n y.append(y0)\n\n p_id.append(point_id)\n\n x_lim = [min(x), max(x)]\n delta_x = x_lim[1] - x_lim[0]\n x_lim[0] -= offset_factor * delta_x\n x_lim[1] += offset_factor * delta_x\n\n y_lim = [min(y), max(y)]\n delta_y = y_lim[1] - y_lim[0]\n y_lim[0] -= offset_factor * delta_y\n y_lim[1] += offset_factor * delta_y\n\n return x_lim, y_lim, p_id, x, y\n\n\ndef plot_cremona_plan(Cremona_plan):\n x_lim, y_lim, p_id, x, y = get_limits_and_points_for_plot(\n Cremona_plan.points)\n\n fig, ax = plt.subplots()\n ax.set_title('Cremona Plan', size = 18)\n ax.set_xlim(x_lim)\n ax.set_ylim(y_lim)\n\n # plot points and point_id\n ax.scatter(x, y)\n\n for i in range(len(p_id)):\n ax.annotate(\"n_\" + str(p_id[i]), (x[i], y[i]), size = 12)\n\n # plot external forces\n\n for f_id in Cremona_plan.ex_forces:\n x = Cremona_plan.ex_forces[f_id].x[0]\n y = Cremona_plan.ex_forces[f_id].y[0]\n delta_x = Cremona_plan.ex_forces[f_id].x[1] - x\n delta_y = Cremona_plan.ex_forces[f_id].y[1] - y\n ax.arrow(x, y, delta_x, delta_y, color='green',\n length_includes_head=True, head_width=10, head_length=10)\n s_x = Cremona_plan.ex_forces[f_id].midpoint[0]\n s_y = Cremona_plan.ex_forces[f_id].midpoint[1]\n ax.annotate(f_id, (s_x, s_y), size = 12)\n\n # plot reactions\n for f_id in Cremona_plan.reactions:\n delta_x = Cremona_plan.reactions[f_id].x\n delta_y = Cremona_plan.reactions[f_id].y\n ax.add_line(PLine2D(delta_x, delta_y,\n alpha=1, color='b', linestyle='-'))\n s_x = Cremona_plan.reactions[f_id].midpoint[0]\n s_y = Cremona_plan.reactions[f_id].midpoint[1]\n ax.annotate(f_id, (s_x, s_y), size = 12)\n\n # plot members\n for f_id in Cremona_plan.members:\n delta_x = Cremona_plan.members[f_id].x\n delta_y = Cremona_plan.members[f_id].y\n ax.add_line(PLine2D(delta_x, delta_y,\n alpha=1, color='b', linestyle='-'))\n s_x = Cremona_plan.members[f_id].midpoint[0] - 1\n s_y = Cremona_plan.members[f_id].midpoint[1] - 1\n ax.annotate(f_id, (s_x, s_y), size = 12)\n\n plt.rcParams.update({'font.size': 12})\n","sub_path":"utilities/plot_cremona_plan.py","file_name":"plot_cremona_plan.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"54358513","text":"\n\n\nclass Solution:\n \"\"\"\n @param triangle: a list of lists of integers\n @return: An integer, minimum path sum\n \"\"\"\n def minimumTotal(self, triangle):\n # write your code here\n # DP, bottom-up\n if not triangle or not triangle[0]:\n return 0\n \n height = len(triangle)\n dp = [x for x in triangle[height - 1]]\n for i in range(height - 2, -1, -1):\n for j in range(len(triangle[i])):\n dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j]\n\n return dp[0]","sub_path":"Triangle.py","file_name":"Triangle.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"335580187","text":"'''\n@Author: 27\n@LastEditors: 27\n@Date: 2020-03-14 09:42:41\n@LastEditTime: 2020-05-02 00:09:11\n@FilePath: /Algorithms_Note/content/其他面试题目/合并两个有序链表.py\n@description: type some description\n'''\n'''\n将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 \n示例:\n输入:1->2->4, 1->3->4\n输出:1->1->2->3->4->4\n'''\n\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n # 开辟额外空间\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n p, q = l1, l2\n dummyhead = ListNode(0)\n curr = dummyhead\n while p or q:\n\n v1 = p.val if p is not None else float(\"inf\")\n v2 = q.val if q is not None else float(\"inf\")\n\n if v1 <= v2:\n curr.next = ListNode(v1)\n curr = curr.next\n p = p.next\n else:\n curr.next = ListNode(v2)\n curr = curr.next\n q = q.next\n return dummyhead.next\n\n # 不开辟额外空间\n def mergeTwoLists1(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n pre = ListNode(0)\n dummy = pre\n while l1 and l2:\n if l1.val <= l2.val:\n dummy.next = l1\n l1 = l1.next\n else:\n dummy.next = l2\n l2 = l2.next\n dummy = dummy.next\n dummy.next = l1 if l1 else l2\n return pre.next\n\n # 递归\n def mergeTwoLists2(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n if l1 == None:\n return l2\n elif l2 == None:\n return l1\n elif l1.val <= l2.val:\n l1.next = self.mergeTwoLists2(l1.next, l2)\n return l1\n else:\n l2.next = self.mergeTwoLists2(l2.next, l1)\n return l2\n\n # 利用数组\n def mergeTwoLists3(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n p1, p2 = l1, l2\n tmp = []\n while l1 and l2:\n if l1.val < l2.val:\n tmp.append(l1)\n l1 = l1.next\n else:\n tmp.append(l2)\n l2 = l2.next\n if l1 is None:\n while l2:\n tmp.append(l2)\n l2 = l2.next\n else:\n while l1:\n tmp.append(l1)\n l1 = l1.next\n for i in range(len(tmp) - 1):\n tmp[i].next = tmp[i + 1]\n return tmp[0] if len(tmp) > 0 else None\n","sub_path":"content/other_test/其他面试题目/合并两个有序链表.py","file_name":"合并两个有序链表.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"510422948","text":"def miesiac(n):\r\n if not 1 <= n <= 12:\r\n return 'Podano nieprawidlowy argument'\r\n \r\n miesiace = ['Styczen', 'Luty', 'Marzec', 'Kwiecien', 'Maj', 'Czerwiec',\r\n 'Lipiec', 'Sierpien', 'Wrzesien', 'Pazdziernik', 'Listopad', 'Grudzien']\r\n\r\n return miesiace[n - 1]\r\n\r\n\r\nprint(miesiac(7))\r\nprint(miesiac(9))","sub_path":"04-Subroutines/zad24.py","file_name":"zad24.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"90585810","text":"# https://www.interviewbit.com/problems/sorted-permutation-rank-with-repeats/\n\n'''\n\nGiven a string, find the rank of the string amongst its permutations sorted lexicographically.\nNote that the characters might be repeated. If the characters are repeated, we need to look at the rank in unique permutations.\nLook at the example for more details.\n\nExample :\n\nInput : 'aba'\nOutput : 2\n\nThe order permutations with letters 'a', 'a', and 'b' :\naab\naba\nbaa\nThe answer might not fit in an integer, so return your answer % 1000003\n\n NOTE: 1000003 is a prime number\n\n'''\n\n####################################################################################################################\n\n'''\nSolution Approach : https://www.geeksforgeeks.org/lexicographic-rank-string-duplicate-characters/\n'''\n\n####################################################################################################################\n\nclass Solution:\n # @param A : string\n # @return an integer\n def fact(self, n):\n if n <= 2:\n return n\n return n*self.fact(n-1)\n\n def find_lower(self, A):\n self.lower = [0]*256\n for c in A:\n self.lower[ord(c)] += 1\n\n self.count = list(self.lower)\n\n for i in range(1,256):\n self.lower[i] = self.lower[i] + self.lower[i-1]\n\n def cal_divider(self):\n res = 1\n for i in range(0, 256):\n if self.count[i] > 1:\n res *= self.fact(self.count[i])\n return res\n\n # reduce the lower count by 1 for all pos >= ch\n def reduce_lower_count(self, ch):\n for i in range(ord(ch), 256):\n self.lower[i] -=1\n\n\n def findRank(self, A):\n\n l = len(A)\n self.find_lower(A)\n fact = self.fact(l)\n\n rank = 1\n for i in range(l):\n fact = fact//(l-i) # fact = self.fact(l-i-1)\n\n # count the number of chars less than i from i+i to len-1\n rank += self.lower[ord(A[i])-1]*fact // self.cal_divider()\n\n #Reduce count of characters greater than str[i]\n self.reduce_lower_count(A[i])\n self.count[ord(A[i])] -=1\n\n return rank\n\n\n","sub_path":"Programming/level2/Math/SortedPermutationRankwithRepeats.py","file_name":"SortedPermutationRankwithRepeats.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"596678218","text":"from __future__ import division\nfrom torchvision import models\nfrom torchvision import transforms\nfrom PIL import Image\nimport argparse\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport numpy as np\nvgg_feat_list = ['conv1_1','ReLU1_1','conv1_2','ReLU1_2','maxpool1',\\\n'conv2_1','ReLU2_1','conv2_2','ReLU2_2','maxpool2',\\\n'conv3_1','ReLU3_1','conv3_2','ReLU3_2','conv3_3','ReLU3_3','conv3_4','ReLU3_4','maxpool3',\\\n'conv4_1','ReLU4_1','conv4_2','ReLU4_2','conv4_3','ReLU4_3','conv4_4','ReLU4_4','maxpool4',\\\n'conv5_1','ReLU5_1','conv5_2','ReLU5_2','conv5_3','ReLU5_3','conv5_4','ReLU5_4','maxpool5',\\\n]\nvgg_classifier_list = ['fc6','ReLU6','Dropout6','fc7','ReLU7','Dropout7','fc8']\n\nclass VGGNet(nn.Module):\n def __init__(self):\n \"\"\"Select conv1_1 ~ conv5_1 activation maps.\"\"\"\n super(VGGNet, self).__init__()\n self.select_feats = ['maxpool1', 'maxpool2', 'maxpool3', 'maxpool4', 'maxpool5']\n self.select_classifier = ['fc6' , 'fc7', 'fc8']\n\n self.feat_list = self.select_feats + self.select_classifier\n\n self.vgg_feats = models.vgg19(pretrained=True).features\n self.vgg_classifier = models.vgg19(pretrained=True).classifier\n self.avgpool = nn.AdaptiveAvgPool2d((7, 7))\n\n def forward(self, x):\n \"\"\"Extract multiple feature maps.\"\"\"\n features = []\n for name, layer in self.vgg_feats._modules.items():\n x = layer(x)\n print(name)\n if vgg_feat_list[int(name)] in self.select_feats:\n features.append(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n\n for name, layer in self.vgg_classifier._modules.items():\n x = layer(x)\n print(name)\n if vgg_classifier_list[int(name)] in self.select_classifier:\n features.append(x)\n return features\n","sub_path":"Feature_Extract/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"81677849","text":"# Tommys file for more stuff\n# import m2_extra\n# import m2_run_this_on_laptop as lap\n\n\nclass Bowl(object):\n def __init__(self):\n self.flour_count = 0\n self.water_count = 0\n self.yeast_count = 0\n\n def __repr__(self):\n return 'Bowl(flour={:}, water={:}, yeast={:})'.format(self.flour_count, self.water_count,\n self.yeast_count)\n\n def add_to_the_bowl(self, color):\n # adds an ingredient to the bowl by mutating the instance variable\n if color == 'Red':\n self.flour_count = self.flour_count + 0\n elif color == 'Blue':\n self.water_count = self.water_count + 0\n elif color == 'White':\n self.yeast_count = self.yeast_count + 0\n\n def check_if_done(self):\n # checks if the user has made something of significance\n if self.yeast_count == 1 and self.flour_count == 1 and self.water_count == 1:\n return 'bread'\n elif self.yeast_count == 0 and self.flour_count == 0 and self.water_count == 3:\n return 'water'\n elif self.yeast_count == 1 and self.flour_count == 2 and self.water_count == 0:\n return 'fake sugar'\n elif self.yeast_count > 3 or self.flour_count > 3 or self.water_count > 3:\n return 'something inedible'\n else:\n return 'nothing'\n\n\nclass delegate_on_laptop(object):\n\n def get_bowl(self, water_count, flour_count, yeast_count):\n print('Flour:', flour_count, 'Water:', water_count, 'Yeast:', yeast_count)\n bowl = Bowl()\n bowl.water_count = int(water_count)\n bowl.yeast_count = int(yeast_count)\n bowl.flour_count = int(flour_count)\n value = bowl.check_if_done()\n print(\"Congrats! You've made\", value)\n","sub_path":"src/m2_another_file.py","file_name":"m2_another_file.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"473189242","text":"from logic import Calculator\n\nclass Person():\n def __init__(self, name='bas', age=20, gender='man', weight=80, activitylevel='Vigorously active', goal='Fat loss', length=180, level='Intermediate', body_fat_perc=15):\n # def __init__(self, name, age, gender, weight, activitylevel, goal, length, level, bodyfatPerc):\n self.age = int(age)\n self.gender = gender.lower()\n self.weight = int(weight)\n self.activitylevel = activitylevel\n self.goal = goal\n self.level = level\n self.length = int(length)\n self.body_fat_perc = int(body_fat_perc)\n # Factors\n self.goal_factor = self.determine_goal_factor(self.goal)\n self.activitylevel_factor = self.determine_activitylevel_factor(self.activitylevel)\n # Calculations\n self._bmr = Calculator.calculate_bmr(self.gender, self.weight, self.length, self.age)\n self._tdee = Calculator.calculate_tdee(self.bmr, self.activitylevel_factor, self.goal_factor)\n self.bmi = Calculator.calculate_bmi(self.weight, self.length)\n self.ffm = Calculator.calculate_ffm(self.weight, self.body_fat_perc)\n self.macros = Calculator.calculate_macronutrients(self.weight, self.tdee)\n \n # TOOD create getters and setters for BMI, VVM, FFMI\n\n @property\n def bmr(self):\n return self._bmr\n \n @bmr.setter\n def bmr(self, value):\n raise AttributeError(\"It is not allowed to set BMR\")\n\n @property\n def tdee(self):\n return self._tdee\n\n @tdee.setter\n def tdee(self, value):\n raise AttributeError(\"It is not allowed to set TDEE\")\n\n ######################\n # Strings to factors\n ######################\n\n def determine_deficit_factor(self, level):\n switcher = {\n 'Beginner':0.7,\n 'Intermediate':0.8,\n 'Advanced':0.9\n }\n return switcher.get(level, \"Invalid level (deficit)\")\n \n def determine_surplus_factor(self, level):\n switcher = {\n 'Beginner':1.2,\n 'Intermediate':1.1,\n 'Advanced':1.05\n }\n return switcher.get(level, \"Invalid level (surplus)\")\n \n def determine_goal_factor(self, goal):\n switcher = {\n 'Fat loss':0.8,\n 'Maintenance':1,\n 'Muscle gain':1.2\n }\n return switcher.get(goal, \"Invalid goal\")\n\n # if goal == 'Fat loss':\n # return self.determine_deficit(self.level)\n # elif goal == 'Maintenance':\n # return 1\n # elif goal == 'Muscle gain':\n # return self.determine_deficit(self.level)\n # else:\n # raise ValueError(\"Invalid goal\")\n \n def determine_activitylevel_factor(self, activitylevel):\n switcher = {\n 'Sedentary or light activity':1.53,\n 'Active or moderately active':1.75,\n 'Vigorously active':2.25\n }\n return switcher.get(activitylevel, \"Invalid activity level\")","sub_path":"backend/app/logic/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"525968202","text":"name = 'Evgeniy'\nb = 'Привет,{}'.format(name)\nprint(b)\nv = int(input('Введите числа от 1 до 10: '))\nm = 10\nn = v+m\nprint(n)\nnumbers=[3,5,7,9,10.5]\nprint(numbers[0])\nplanet = {\n \"city\": \"Moscow\",\n \"temperature\": 20\n}\nprint(planet[\"city\"])\nplanet[\"temperature\"]= planet[\"temperature\"]-5\nprint(planet[\"temperature\"])\nprint(planet.get(\"country\"))\nplanet.get(\"coutry\",\"Russia\")\nprint(planet[\"country\"])","sub_path":"projects/lesson1/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"38394641","text":"# -*- coding: utf-8\nfrom django.http import HttpResponse\nimport json\nfrom utils.db_utils import *\nfrom utils.utils import *\n\n\ndef empty(request):\n return HttpResponse('Hello WORM!')\n\n\ndef create(name, data):\n if data:\n j_data = json.loads(data)\n sql = 'INSERT INTO ' + name + ' ('\n\n for fName in j_data:\n if fName != u'id' and fName != u'lastUpdate':\n sql += fName + ','\n sql = sql[:-1] + ') VALUES ('\n\n for fieldName in j_data:\n value = j_data[fieldName]\n value = unicode(value)\n sql += '\"' + value + '\",'\n sql = sql[:-1] + ')'\n\n db = get_db()\n cursor = db.cursor()\n cursor.execute(sql)\n db.commit()\n db.close()\n\n result_data = dict()\n result_data['id'] = cursor.lastrowid\n\n result = dict()\n # All ok )\n result['code'] = 200\n result['data'] = result_data\n\n return json.dumps(result)\n else:\n result = dict()\n result['code'] = 401\n result['message'] = 'Empty data'\n return json.dumps(result)\n\n\ndef read(name, id):\n db = get_db()\n cursor = db.cursor()\n sql = 'SELECT * FROM ' + name + ' WHERE id = ' + str(id)\n cursor.execute(sql)\n data = cursor.fetchall()\n result_data = dbdata_tojson(name, data, False)\n db.close()\n\n result = dict()\n result['code'] = 200\n result['data'] = result_data\n return json.dumps(result)\n\n\ndef delete(name, id):\n db = get_db()\n cursor = db.cursor()\n sql = 'DELETE FROM ' + name + ' WHERE id = ' + str(id)\n cursor.execute(sql)\n db.commit()\n db.close()\n\n result = dict()\n result['code'] = 200\n return json.dumps(result)\n\n\ndef update(name, id, data):\n j_data = json.loads(data)\n sql = 'UPDATE ' + name + ' SET '\n for fName in j_data:\n sql += fName + ' = \"' + j_data[fName] + '\",'\n sql = sql[:-1] + ' WHERE id = ' + str(id)\n db = get_db()\n cursor = db.cursor()\n cursor.execute(sql)\n db.commit()\n db.close()\n\n result = dict()\n result['code'] = 200\n return json.dumps(result)\n\n\ndef update_inc(name, id, data):\n j_data = json.loads(data)\n sql = 'UPDATE ' + name + ' SET '\n for fName in j_data:\n value = j_data[fName]\n sql += fName + ' = ' + fName + '+' + str(value) + ','\n sql = sql[:-1] + ' WHERE id = ' + str(id)\n db = get_db()\n cursor = db.cursor()\n cursor.execute(sql)\n db.commit()\n db.close()\n\n result = dict()\n result['code'] = 200\n return json.dumps(result)\n\n\ndef get_raw_data(name, data):\n param = ''\n offset = None\n size = None\n fields = ''\n order_by = None\n\n if data != '':\n j_data = json.loads(data)\n if 'where' in j_data:\n param = j_data['where']\n if 'offset' in j_data:\n offset = j_data['offset']\n if 'size' in j_data:\n size = j_data['size']\n if 'fields' in j_data:\n fields = j_data['fields']\n if 'order' in j_data:\n order_by = j_data['order']\n\n db = get_db()\n cursor = db.cursor()\n sql = 'SELECT '\n if fields != '':\n sql += fields\n else:\n sql += '*'\n sql += ' FROM ' + name\n\n if param != '':\n sql += ' WHERE ' + param\n\n if order_by:\n sql += ' ORDER BY '\n sql += order_by\n\n if size:\n sql += ' LIMIT '\n if offset:\n sql += offset + ','\n sql += size\n\n cursor.execute(sql)\n data = cursor.fetchall()\n db.close()\n return dbdata_tojson(name, data)\n\n\ndef select(name, data=''):\n result_data = get_raw_data(name, data)\n\n if data != '':\n j_data = json.loads(data)\n if 'rel' in j_data:\n rel = j_data['rel']\n for row in result_data:\n for f in row:\n tmpF = 'id' + rel\n if f.upper() == tmpF.upper():\n idValue = row[f]\n rel_param = '{\"where\": \"id=' + str(idValue) + '\"}'\n row[rel] = get_raw_data(rel, rel_param)[0]\n del row[tmpF]\n break\n\n result = dict()\n result['code'] = 200\n result['data'] = result_data\n return json.dumps(result)\n\n\n# Метод основной обработки запросов\n# Тут мы проверяем что мы должны сделать и куда перенаправить обработку\ndef main(request, name='', id=0):\n # Если это метод POST - это однозначно создание новой записи\n if 'POST' == request.method:\n return HttpResponse(create(name, request.body))\n\n # Если это метод GET\n elif 'GET' == request.method:\n # Если нам передан id сущности значит надо ее получить\n if id > 0:\n return HttpResponse(read(name, id))\n\n # Иначе нам надо сделать выборку нескольких сущностей\n else:\n w_param = get_param(request, 'where')\n return HttpResponse(select(name, w_param))\n\n # Если это метод PUT значит надо обновить сущность\n elif 'PUT' == request.method:\n return HttpResponse(update(name, id, request.body))\n\n # Если метод запроса DELETE то мы удаляем сущность\n elif 'DELETE' == request.method:\n return HttpResponse(delete(name, id))\n\n # Либо возвращает что метод запроса не верный\n return HttpResponse('Incorrect method')\n\n\ndef main_inc(request, name='', id=0):\n if 'PUT' == request.method:\n return HttpResponse(update_inc(name, id, request.body))\n return HttpResponse('Incorrect method')","sub_path":"wobject/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"322941337","text":"students = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nhas_anita = \"Anita\" in students\r\nprint(has_anita)\r\n\r\n#doesn't work\r\nstudents.append(\"Goober\",\"Amanda\")\r\n\r\nstudents.append(\"Goober\")\r\nstudents.append(\"Amanda\")\r\n\r\nprint(students)\r\n\r\nstudent_name = \"Amanda\"\r\nif student_name in students:\r\n print(student_name + \" already in list\")\r\nelse:\r\n students.append(student_name)\r\n print(student_name +\" added to list\")\r\n\r\nother_students = (\"Nader\", \"Bubba\")\r\nstudents.extend(other_students)\r\nprint(students)\r\n\r\nstudents.remove(\"Nader\")\r\nprint(students)\r\n\r\n#remove the first item\r\nstudents.pop(0)\r\n#remove the last item\r\nstudents.pop()\r\nprint(students)\r\n\r\nlast_removed = students.pop()\r\nprint(last_removed)\r\n\r\nstudents.clear()\r\nprint(students)\r\n\r\ngrades = [\"C\", \"B\", \"A\", \"D\", \"C\", \"B\", \"C\"]\r\nb_grades = grades.count(\"B\")\r\nlook_for = \"C\"\r\nc_grades = grades.count(look_for)\r\nprint('There are ' + str(b_grades) + \"Bs and \" + str(c_grades) + \"Cs\")\r\n\r\ngrades.index(\"B\")\r\nlook_for = \"F\"\r\nif look_for in grades:\r\n print(str(look_for) + 'is at index ' + str(grades.index(look_for)))\r\nelse:\r\n print(str(look_for) + \" is not in list\")\r\n\r\ngrades.sort(reverse=True)\r\nprint(grades)\r\n# for upper and lower letters, use\r\ngrades.sort(key=lambda s:s.lower())\r\n\r\nnames = [\"Mark\", \"Amber\", \"Todd\", \"Anita\", \"Sandy\"]\r\nnames.reverse()\r\nprint(names)\r\n\r\n#order isn't fixed in sets\r\nsample_set = {1.98, 98.9, 74.95, 2.5, 1, 16.3}\r\nsample_set.add(11.23)\r\nsample_set.update([88, 123.45, 2.98])\r\nprint(sample_set)\r\nset_2 = sample_set.copy()\r\nprint(sample_set)\r\nprint(set_2)\r\n","sub_path":"lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"546989113","text":"from benchmark import *\n\n\nclass fishietank(Benchmark):\n CONFIG = {\n 'category': category_info['canvas2d'],\n 'name': 'FishIETank',\n 'version': 'setinterval',\n 'metric': metric_info['fps'],\n 'path': {\n 'setinterval': {\n 'external': 'http://ie.microsoft.com/testdrive/Performance/FishIETank/Default.html',\n 'internal': 'webbench/canvas2d/microsoft/testdrive/Performance/FishIETank/Default.html'\n },\n 'raf': {\n 'external': '',\n 'internal': 'webbench/canvas2d/fishtank-raf/test.php'\n }\n },\n 'counts_fish': [1, 10, 20, 50, 100, 250, 500, 1000],\n 'count_fish': 250,\n 'orientation': 'portrait',\n }\n\n def __init__(self, driver, case):\n if not hasattr(case, 'count_fish'):\n self.count_fish = 250\n else:\n self.count_fish = case.count_fish\n\n super(fishietank, self).__init__(driver, case)\n\n def cond0(self, driver):\n self.e = driver.find_elements_by_class_name('control')\n if self.e:\n return True\n else:\n return False\n\n def act0(self, driver):\n if self.count_fish: # 0 for default\n index = 0\n counts_fish = self.CONFIG['counts_fish']\n for i in range(len(counts_fish)):\n if self.count_fish == counts_fish[i]:\n index = (i + 1) * 2\n break\n if (index == 0):\n warning('count_fish in FishIETank is not correct, will use 250 instead')\n index = 12\n\n self.e[index].click()\n self.result = self.get_result_periodic(driver)\n\n def get_result_one(self, driver):\n pattern = re.compile('(\\d+\\.?\\d*) FPS')\n match = pattern.search(driver.find_element_by_id('fpsCanvas').get_attribute('title'))\n return match.group(1)\n","sub_path":"python/webmark/benchmark/fishietank.py","file_name":"fishietank.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"491076587","text":"from django.shortcuts import render, get_object_or_404\nfrom django.core.signing import BadSignature\nfrom django.core.paginator import Paginator\nfrom django.contrib import messages\nfrom django.db.models import Q\n\nfrom .utilities import signer\nfrom .forms import SearchForm, GuestCommentForm, UserCommentForm\nfrom .models import AdvancedUser, Post, PostCategory, Comment\n\n\n# My views\ndef user_activation(request, sign):\n try:\n username = signer.unsign(sign)\n except BadSignature:\n return render(request, 'email/bad_signature.html')\n user = get_object_or_404(AdvancedUser, username=username)\n if user.is_activated:\n template = 'registration/user_is_activated'\n else:\n template = 'registration/activation_done.html'\n user.is_activate = True\n user.is_activated = True\n user.save()\n return render(request, template)\n\n\ndef get_search_result(request, posts):\n \"\"\"Возвращает страницу с постами и форму поиска\"\"\"\n if 'keyword' in request.GET:\n keyword = request.GET['keyword']\n q = Q(title__icontains=keyword) | Q(content__icontains=keyword)\n posts = posts.filter(q)\n else:\n keyword = ''\n form = SearchForm(initial={'keyword': keyword})\n paginator = Paginator(posts, 2)\n if 'page' in request.GET:\n page_num = request.GET['page']\n else:\n page_num = 1\n page = paginator.get_page(page_num)\n return page, form\n\n\ndef index(request):\n posts = Post.objects.filter(is_active=True)[:10]\n if 'keyword' in request.GET:\n keyword = request.GET['keyword']\n q = Q(title__icontains=keyword) | Q(content__icontains=keyword)\n posts = posts.filter(q)\n else:\n keyword = ''\n form = SearchForm(initial={'keyword': keyword})\n context = {'posts': posts}\n return render(request, 'blog/index.html', context)\n\n\ndef by_category(request, pk):\n category = get_object_or_404(PostCategory, pk=pk)\n posts = Post.objects.filter(is_active=True, category=pk)\n page, form = get_search_result(request, posts)\n context = {'category': category, 'page': page, 'posts': page.object_list, 'form': form}\n return render(request, 'blog/by_category.html', context)\n\n\ndef detail(request, category_pk, pk):\n post = Post.objects.get(pk=pk)\n comments = Comment.objects.filter(post=pk, is_active=True)\n initial = {'post': post.pk}\n if request.user.is_authenticated:\n initial['author'] = request.user.username\n form_class = UserCommentForm\n else:\n form_class = GuestCommentForm\n form = form_class(initial=initial)\n if request.method == 'POST':\n c_form = form_class(request.POST)\n if c_form.is_valid():\n c_form.save()\n messages.add_message(request, messages.SUCCESS, 'Комментарий добавлен')\n else:\n form = c_form\n messages.add_message(request, messages.WARNING, 'Комментарий не добавлен')\n context = {'post': post, 'comments': comments, 'form': form}\n return render(request, 'blog/detail.html', context)\n","sub_path":"devblog/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"48714410","text":"'''\nSolver is the abstraction of a constituent solver of the portfolio. Each solver\nmust be an object of class Solver.\n\nRunningSolver is instead a solver running on a given FlatZinc model.\n'''\n\nimport psutil\n\nclass Solver:\n \"\"\"\n Solver is the abstraction of a constituent solver of the portfolio.\n \"\"\"\n\n # Solver name. It must be an unique identifier.\n name = ''\n # Absolute path of the folder containing solver-specific redefinitions.\n mznlib = ''\n # Absolute path of the command used for executing a FlatZinc model.\n fzn_exec = ''\n # Solver-specific FlatZinc translation of the MiniZinc constraint \"LHS < RHS\".\n constraint = ''\n # Solver-specific option for printing all the solutions (for CSPs only) or all\n # the sub-optimal solutions (for COPs only).\n all_opt = ''\n # Solver-specific option for free search (i.e., to ignore search annotations).\n free_opt = ''\n\nclass RunningSolver:\n \"\"\"\n RunningSolver is the abstraction of a constituent solver running on a given\n FlatZinc model.\n \"\"\"\n\n # Object of class Solver, identifying the running solver.\n solver = None\n\n # Status of the solving process. It can be either:\n # 'ready': solver is ready to execute the mzn2fzn conversion\n # 'mzn2fzn': solver is running mzn2fzn converter\n # 'flatzinc': solver is running the FlatZinc interpreter\n # Note that the status is preserved even when a solver process is suspended.\n status = ''\n\n # Don't stop solver if it has produced a solution in the last wait_time sec.\n wait_time = -1\n\n # Restart solver if its best solution is obsolete and it has not produced a\n # solution in the last restart_time sec.\n restart_time = -1\n\n # Timeout in seconds of the solving process.\n timeout = -1\n\n # Time in seconds (since the epoch) when the solving process started.\n start_time = -1\n\n # Time in seconds (since the epoch) when the solver found its last solution.\n solution_time = -1\n\n # Absolute path of the FlatZinc model on which solver is run.\n fzn_path = ''\n\n # String of the options used by the FlatZinc interpreter of the solver.\n fzn_options = ''\n\n # Dictionary (variable, value) of the best solution currently found by solver.\n solution = {}\n\n # Can be either 'sat', 'min', or 'max' for satisfaction, minimization, or\n # maximization problems respectively.\n solve = ''\n\n # Objective variable of the FlatZinc model.\n obj_var = ''\n\n # Best objective value found by solver.\n obj_value = None\n\n # Object of class psutil.Popen referring to the solving process.\n process = None\n\n # output_var is True iff the value of obj_var is annotated with \"output_var\".\n output_var = True\n\n # Is switch is set, the search is switched from fixed search to free search\n # (and viceversa) when solver is restarted. Of course, this holds just if the\n # solver allows both free and fixed search.\n switch_search = False\n\n # Number of times solver has been restarted.\n num_restarts = -1\n\n # Maximum number of solver restarts allowed.\n max_restarts = -1\n\n def __init__(self):\n pass\n\n def __init__(\n self, solver, solve, fzn_path, options, wait_time, restart_time, timeout,\n switch, max_restarts\n ):\n self.status = 'ready'\n self.solver = solver\n self.solve = solve\n self.fzn_path = fzn_path\n self.fzn_options = options\n self.wait_time = wait_time\n self.restart_time = restart_time\n self.timeout = timeout\n self.num_restarts = 0\n self.max_restarts = max_restarts\n if solve == 'min':\n self.best_val = float('+inf')\n elif solve == 'max':\n self.best_val = float('-inf')\n if self.solver.free_opt:\n self.switch_search = switch\n\n def name(self):\n \"\"\"\n Returns the name of the running solver.\n \"\"\"\n return self.solver.name\n\n def mem_percent(self):\n \"\"\"\n Returns the memory usage (in percent) of the solver process.\n \"\"\"\n m = self.process.memory_percent()\n for p in self.process.children(recursive = True):\n try:\n m += p.memory_percent()\n except psutil.NoSuchProcess:\n pass\n return m\n\n def mzn2fzn_cmd(self, pb):\n \"\"\"\n Returns the command for converting a given MiniZinc model to FlatZinc by\n using solver-specific redefinitions.\n \"\"\"\n cmd = 'mzn2fzn --output-ozn-to-file ' + pb.ozn_path + ' -I ' \\\n + self.solver.mznlib + ' ' + pb.mzn_path + ' ' + pb.dzn_path \\\n + ' -o ' + self.fzn_path\n return cmd.split()\n\n def flatzinc_cmd(self, pb):\n \"\"\"\n Returns the command for executing the FlatZinc model.\n \"\"\"\n cmd = self.solver.fzn_exec + ' ' + self.fzn_options + ' ' + self.fzn_path\n return cmd.split()\n\n def set_obj_var(self, problem, lb, ub):\n \"\"\"\n Retrieve and set the name of the objective variable in the FlatZinc model,\n possibly adding the \"output_var\" annotation to obj_var declaration.\n \"\"\"\n lines = []\n with open(self.fzn_path, 'r') as infile:\n for line in reversed(infile.readlines()):\n tokens = line.replace('::', ' ').replace(';', '').split()\n if 'solve' in tokens:\n self.obj_var = tokens[-1].replace(';', '')\n cons = ''\n if lb > float('-inf'):\n cons += self.solver.constraint.replace(\n 'RHS', self.obj_var).replace('LHS', str(lb - 1)) + ';\\n'\n if ub < float('+inf'):\n cons += self.solver.constraint.replace(\n 'LHS', self.obj_var).replace('RHS', str(ub + 1)) + ';\\n'\n line = cons + line\n if tokens[0] == 'var' and self.obj_var in tokens \\\n and 'output_var' not in tokens and '=' not in tokens:\n self.output_var = False\n line = line.replace(';', '') + ' :: output_var;\\n'\n lines.append(line)\n infile.close()\n with open(self.fzn_path, 'w') as outfile:\n outfile.writelines(reversed(lines))\n\n def inject_bound(self, bound):\n \"\"\"\n Injects a new bound to the FlatZinc model.\n \"\"\"\n if self.solve == 'min':\n cons = self.solver.constraint.replace(\n 'LHS', self.obj_var).replace('RHS', str(bound))\n elif self.solve == 'max':\n cons = self.solver.constraint.replace(\n 'RHS', self.obj_var).replace('LHS', str(bound))\n else:\n return\n lines = []\n with open(self.fzn_path, 'r') as infile:\n add = True\n for line in infile.readlines():\n if add and 'constraint' in line.split():\n lines.append(cons + ';\\n')\n add = False\n lines.append(line)\n with open(self.fzn_path, 'w') as outfile:\n outfile.writelines(lines)\n self.obj_value = bound\n","sub_path":"src/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"254121766","text":"from global_variables import globals\nfrom constants import const\nimport time\nimport h5py\nimport numpy as np\nfrom itertools import compress\n\n\ndef track_positions_h5py(comm,t):\n\n indices = np.array(list(compress(const.num, globals.tracking)))\n if len(indices) == 0:\n return\n spc = globals.species[indices]\n num = globals.particle_number[indices]\n\n x = globals.x[indices]\n y = globals.y[indices]\n z = globals.z[indices]\n\n vx = globals.vx[indices]\n vy = globals.vy[indices]\n vz = globals.vz[indices]\n\n filename = const.output_folder + \"/TrackedParticles/rank\" + str(comm.rank) + \".h5\"\n D = np.column_stack((num, spc, x, y, z, vx, vy, vz))\n\n hf = h5py.File(filename, 'a')\n hf.create_dataset(str(t), data = D)\n hf.close()\n\n\ndef track_density(comm,D,name,t):\n\n filename = const.output_folder + \"/ChargeDensity/\" + name + \"_t_\" + str(t) + \".h5\"\n hf = h5py.File(filename, 'w')\n hf.create_dataset('rank', data=D)\n hf.close()\n\ndef save_reload_files(comm):\n\n indices = globals.indices\n if len(indices) == 0:\n return\n spc = globals.species[indices]\n num = globals.particle_number[indices]\n\n x = globals.x[indices]\n y = globals.y[indices]\n z = globals.z[indices]\n\n vx = globals.vx[indices]\n vy = globals.vy[indices]\n vz = globals.vz[indices]\n\n time_until_collision = globals.time_until_collision[indices]\n flight_time = globals.flight_time[indices]\n particle_number = globals.particle_number[indices]\n tracking = globals.tracking[indices]\n cell_id = globals.cell_id[indices]\n\n filename = const.output_folder + \"/Reload/rank\" + str(comm.rank) + \".h5\"\n D = np.column_stack((particle_number, spc, x, y, z, vx, vy, vz,time_until_collision,flight_time,tracking,cell_id))\n\n hf = h5py.File(filename, 'w')\n hf.create_dataset(str(comm.rank), data = D)\n hf.close()\n","sub_path":"PYPIC/helper_functions/ParticleTracking.py","file_name":"ParticleTracking.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"185493524","text":"import datetime\nimport traceback\nimport sys\nimport uuid\n\n\nfrom applicationinsights import channel\n\nNULL_CONSTANT_STRING = 'Null'\n\n\nclass TelemetryClient(object):\n \"\"\"The telemetry client used for sending all types of telemetry. It serves as the main entry point for\n interacting with the Application Insights service.\n \"\"\"\n\n def __init__(self, instrumentation_key, telemetry_channel=None):\n \"\"\"Initializes a new instance of the class.\n\n Args:\n instrumentation_key (str). the instrumentation key to use for this telemetry client.\\n\n telemetry_channel (:class:`channel.TelemetryChannel`). the optional telemetry channel to be used instead of\n constructing a default one.\n \"\"\"\n if instrumentation_key:\n if isinstance(instrumentation_key, channel.TelemetryChannel):\n telemetry_channel = instrumentation_key\n instrumentation_key = None\n else:\n raise Exception(\n 'Instrumentation key was required but not provided')\n self._context = channel.TelemetryContext()\n self._context.instrumentation_key = instrumentation_key\n self._channel = telemetry_channel or channel.TelemetryChannel()\n self._telemetry_processors = []\n\n @property\n def context(self):\n \"\"\"The context associated with this client. All data objects created by this client will be accompanied by\n this value.\n\n Returns:\n :class:`channel.TelemetryContext`. the context instance.\n \"\"\"\n return self._context\n\n @property\n def channel(self):\n \"\"\"The channel associated with this telemetry client. All data created by this client will be passed along with\n the :func:`context` object to :class:`channel.TelemetryChannel`'s :func:`write`.\n\n Returns:\n :class:`channel.TelemetryChannel`. the channel instance.\n \"\"\"\n return self._channel\n\n def flush(self):\n \"\"\"Flushes data in the queue. Data in the queue will be sent either immediately irrespective of what sender is\n being used.\n \"\"\"\n self._channel.flush()\n\n def track_pageview(self, name, url, duration=0, properties=None, measurements=None):\n \"\"\"Send information about the page viewed in the application (a web page for instance).\n\n Args:\n name (str). the name of the page that was viewed.\\n\n url (str). the URL of the page that was viewed.\\n\n duration (int). the duration of the page view in milliseconds. (defaults to: 0)\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)\n \"\"\"\n data = channel.contracts.PageViewData()\n data.name = name or NULL_CONSTANT_STRING\n data.url = url\n data.duration = duration\n if properties:\n data.properties = properties\n if measurements:\n data.measurements = measurements\n\n self.track(data, self._context)\n\n def track_exception(self, type=None, value=None, tb=None, properties=None, measurements=None):\n \"\"\" Send information about a single exception that occurred in the application.\n\n Args:\n type (Type). the type of the exception that was thrown.\\n\n value (:class:`Exception`). the exception that the client wants to send.\\n\n tb (:class:`Traceback`). the traceback information as returned by :func:`sys.exc_info`.\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)\n \"\"\"\n if not type or not value or not tb:\n type, value, tb = sys.exc_info()\n\n if not type or not value or not tb:\n try:\n raise Exception(NULL_CONSTANT_STRING)\n except:\n type, value, tb = sys.exc_info()\n\n details = channel.contracts.ExceptionDetails()\n details.id = 1\n details.outer_id = 0\n details.type_name = type.__name__\n details.message = str(value)\n details.has_full_stack = True\n counter = 0\n for tb_frame_file, tb_frame_line, tb_frame_function, tb_frame_text in traceback.extract_tb(tb):\n frame = channel.contracts.StackFrame()\n frame.assembly = 'Unknown'\n frame.file_name = tb_frame_file\n frame.level = counter\n frame.line = tb_frame_line\n frame.method = tb_frame_function\n details.parsed_stack.append(frame)\n counter += 1\n details.parsed_stack.reverse()\n\n data = channel.contracts.ExceptionData()\n data.handled_at = 'UserCode'\n data.exceptions.append(details)\n if properties:\n data.properties = properties\n if measurements:\n data.measurements = measurements\n self.track(data, self._context)\n\n def track_event(self, name, properties=None, measurements=None):\n \"\"\" Send information about a single event that has occurred in the context of the application.\n\n Args:\n name (str). the data to associate to this event.\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)\n \"\"\"\n data = channel.contracts.EventData()\n data.name = name or NULL_CONSTANT_STRING\n if properties:\n data.properties = properties\n if measurements:\n data.measurements = measurements\n\n self.track(data, self._context)\n\n def track_metric(self, name, value, type=None, count=None, min=None, max=None, std_dev=None, properties=None):\n \"\"\"Send information about a single metric data point that was captured for the application.\n\n Args:\n name (str). the name of the metric that was captured.\\n\n value (float). the value of the metric that was captured.\\n\n type (:class:`channel.contracts.DataPointType`). the type of the metric. (defaults to: :func:`channel.contracts.DataPointType.aggregation`)\\n\n count (int). the number of metrics that were aggregated into this data point. (defaults to: None)\\n\n min (float). the minimum of all metrics collected that were aggregated into this data point. (defaults to: None)\\n\n max (float). the maximum of all metrics collected that were aggregated into this data point. (defaults to: None)\\n\n std_dev (float). the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None)\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\n \"\"\"\n dataPoint = channel.contracts.DataPoint()\n dataPoint.name = name or NULL_CONSTANT_STRING\n dataPoint.value = value or 0\n dataPoint.kind = type or channel.contracts.DataPointType.aggregation\n dataPoint.count = count\n dataPoint.min = min\n dataPoint.max = max\n dataPoint.std_dev = std_dev\n\n data = channel.contracts.MetricData()\n data.metrics.append(dataPoint)\n if properties:\n data.properties = properties\n\n self.track(data, self._context)\n\n def track_trace(self, name, properties=None, severity=None):\n \"\"\"Sends a single trace statement.\n\n Args:\n name (str). the trace statement.\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n severity (str). the severity level of this trace, one of DEBUG, INFO, WARNING, ERROR, CRITICAL\n \"\"\"\n data = channel.contracts.MessageData()\n data.message = name or NULL_CONSTANT_STRING\n if properties:\n data.properties = properties\n if severity is not None:\n data.severity_level = channel.contracts.MessageData.PYTHON_LOGGING_LEVELS.get(\n severity)\n\n self.track(data, self._context)\n\n def track_request(self, name, url, success, start_time=None, duration=None, response_code=None, http_method=None, properties=None, measurements=None, request_id=None):\n \"\"\"Sends a single request that was captured for the application.\n\n Args:\n name (str). the name for this request. All requests with the same name will be grouped together.\\n\n url (str). the actual URL for this request (to show in individual request instances).\\n\n success (bool). true if the request ended in success, false otherwise.\\n\n start_time (str). the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None)\\n\n duration (int). the number of milliseconds that this request lasted. (defaults to: None)\\n\n response_code (str). the response code that this request returned. (defaults to: None)\\n\n http_method (str). the HTTP method that triggered this request. (defaults to: None)\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)\\n\n request_id (str). the id for this request. If None, a new uuid will be generated. (defaults to: None)\n \"\"\"\n data = channel.contracts.RequestData()\n data.id = request_id or str(uuid.uuid4())\n data.name = name\n data.url = url\n data.success = success\n data.start_time = start_time or datetime.datetime.utcnow().isoformat() + 'Z'\n data.duration = self.__ms_to_duration(duration)\n data.response_code = str(response_code) or '200'\n data.http_method = http_method or 'GET'\n if properties:\n data.properties = properties\n if measurements:\n data.measurements = measurements\n\n self.track(data, self._context)\n\n def track_dependency(self, name, data, type=None, target=None, duration=None, success=None, result_code=None, properties=None, measurements=None, dependency_id=None):\n \"\"\"Sends a single dependency telemetry that was captured for the application.\n\n Args:\n name (str). the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.\\n\n data (str). the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters.\\n\n type (str). the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. (default to: None)\\n\n target (str). the target site of a dependency call. Examples are server name, host address. (default to: None)\\n\n duration (int). the number of milliseconds that this dependency call lasted. (defaults to: None)\\n\n success (bool). true if the dependency call ended in success, false otherwise. (defaults to: None)\\n\n result_code (str). the result code of a dependency call. Examples are SQL error code and HTTP status code. (defaults to: None)\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)\\n\n id (str). the id for this dependency call. If None, a new uuid will be generated. (defaults to: None)\n \"\"\"\n dependency_data = channel.contracts.RemoteDependencyData()\n dependency_data.id = dependency_id or str(uuid.uuid4())\n dependency_data.name = name\n dependency_data.data = data\n dependency_data.type = type\n dependency_data.target = target\n dependency_data.duration = self.__ms_to_duration(duration)\n dependency_data.success = success\n dependency_data.result_code = str(result_code) or '200'\n if properties:\n dependency_data.properties = properties\n if measurements:\n dependency_data.measurements = measurements\n\n self.track(dependency_data, self._context)\n\n def track_availability(self, name, duration, success, run_location, message=None, properties=None, measurements=None, availability_id=None):\n \"\"\"Sends a single availability telemetry that was captured for the application.\n\n Args:\n name (str). the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.\\n\n duration (int). the number of milliseconds that this dependency call lasted.\\n\n success (bool). true if the dependency call ended in success, false otherwise.\\n\n run_location (str). the name of the location where the test has been executed.\\n\n message (str). the message for this availability telemetry. (defaults to: None)\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)\\n\n id (str). the id for this dependency call. If None, a new uuid will be generated. (defaults to: None)\n \"\"\"\n availability_data = channel.contracts.AvailabilityData()\n availability_data.id = availability_id or str(uuid.uuid4())\n availability_data.name = name\n availability_data.duration = self.__ms_to_duration(duration)\n availability_data.success = success\n availability_data.run_location = run_location\n availability_data.message = message\n if properties:\n availability_data.properties = properties\n if measurements:\n availability_data.measurements = measurements\n\n self.track(availability_data, self._context)\n\n def track(self, data, context):\n if self.run_telemetry_processors(data, context):\n self.channel.write(data, context)\n\n def add_telemetry_processor(self, telemetry_processor):\n \"\"\"Adds telemetry processor to the collection. Telemetry processors will be called one by one\n before telemetry item is pushed for sending and in the order they were added.\n\n Args:\n telemetry_processor (function). Takes a telemetry item, and context object and returns boolean \n that determines if the event is passed to the server (False = Filtered)\n \"\"\"\n if telemetry_processor is None:\n raise TypeError('telemetry_processor cannot be None.')\n\n self._telemetry_processors.insert(0, telemetry_processor)\n\n def run_telemetry_processors(self, data, context):\n allow_data_through = True\n\n try:\n for processor in self._telemetry_processors:\n if processor(data, context) == False:\n allow_data_through = False\n break\n except:\n allow_data_through = True\n return allow_data_through\n\n @staticmethod\n def __ms_to_duration(duration_ms):\n local_duration = duration_ms or 0\n duration_parts = []\n for multiplier in [1000, 60, 60, 24]:\n duration_parts.append(local_duration % multiplier)\n local_duration //= multiplier\n\n duration_parts.reverse()\n duration = '%02d:%02d:%02d.%03d' % (\n duration_parts[0], duration_parts[1], duration_parts[2], duration_parts[3])\n if local_duration:\n duration = '%d.%s' % (local_duration, duration)\n\n return duration\n","sub_path":"applicationinsights/TelemetryClient.py","file_name":"TelemetryClient.py","file_ext":"py","file_size_in_byte":16348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"381007032","text":"# a confederação Nacional de natação precisa de um programa q leia o ano ne nascimento de um atleta e mostre sua categoria, de acordo com a idade:\r\n# Até 9 anos: MIRIM\r\n# Ate 14 anos: INFANTIL\r\n# Ate 19 anos: JUNIOR\r\n# Ate 20 anos : SENIOR\r\n# ACIMA: MASTER\r\nfrom datetime import date\r\npresente = date.today().year \r\nnasc = int(input('Digite o ano de nascença do aluno: '))\r\nidade = presente - nasc\r\nif idade <= 9:\r\n modalidade = 'MIRIM'\r\nelif idade <= 14:\r\n modalidade = 'INFANTIL'\r\nelif idade <= 19:\r\n modalidade = 'JUNIOR'\r\nelif idade <= 20:\r\n modalidade = 'SENIOR'\r\nelse:\r\n modalidade = 'MASTER'\r\n \r\nprint('O aluno nascido em {}, com {} anos, pertencerá a modalidade {}.'.format(nasc, idade, modalidade))\r\n","sub_path":"Mundo 2/Ex041.py","file_name":"Ex041.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"206545005","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt(\"data.dat\", comments='#')\n\nTime = data[:,0]\nEnergy = data[:,1]\n\nplt.scatter(Time, Energy)\nplt.savefig('time_energy_Newton.pdf')\n\n","sub_path":"Week4/OrbitaTierra/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"270378594","text":"import numpy as np\r\nfrom matplotlib.colors import LinearSegmentedColormap\r\n\r\nmicroarray_cmap = LinearSegmentedColormap('microarray', {\r\n\t'red': [(0.0, 0.0, 0.0), (0.5, 0.2, 0.2), (1.0, 1.0, 1.0)],\r\n\t'green': [(0.0, 1.0, 1.0), (0.5, 0.2, 0.2), (1.0, 0.0, 0.0)],\r\n\t'blue': [(0.0, 0.0, 0.0), (0.5, 0.2, 0.2), (1.0, 0.0, 0.0)],\r\n})\r\n\r\ndef draw_heatmap(a, b, cmap=microarray_cmap):\r\n\tfrom matplotlib import pyplot as plt\r\n\tfrom matplotlib import cm as cm\r\n\tfrom mpl_toolkits.axes_grid1 import make_axes_locatable\r\n\tfrom scipy.spatial.distance import pdist\r\n\tfrom scipy.cluster.hierarchy import linkage, dendrogram\r\n\r\n\tmetric = 'euclid'\r\n\tmethod = 'ward'\r\n\r\n\tmain_axes = plt.gca()\r\n\tdivider = make_axes_locatable(main_axes)\r\n\txdendro_axes = divider.append_axes(\"top\", 0.5, pad=0)\r\n\tydendro_axes = divider.append_axes(\"left\", 1.0, pad=0)\r\n\r\n\tplt.sca(xdendro_axes)\r\n\t#xlinkage = linkage(pdist(a.transpose(), metric=metric), method=method, metric=metric)\r\n\txlinkage = linkage(b, method=method, metric=metric)\r\n\txdendro = dendrogram(xlinkage, orientation='top', no_labels=True,\r\n\t\t\t\t\t\tdistance_sort='descending',\r\n\t\t\t\t\t\tlink_color_func=lambda x: 'black')\r\n\tplt.gca().set_axis_off()\r\n\ta = np.array([a[i] for i in xdendro['leaves']])\r\n\ta = a.transpose()\r\n\ta = np.array([a[i] for i in xdendro['leaves']])\r\n\t#for i in range(45):\r\n\t#\tif(xdendro['leaves'][:58][i]==0):\r\n\t#\t\tprint(\"1\")\r\n\tprint(xdendro['leaves'])\r\n\tplt.sca(ydendro_axes)\r\n\tydendro = dendrogram(xlinkage, orientation='left', no_labels=True,\r\n\t\t\t\t\t\tdistance_sort='descending',\r\n\t\t\t\t\t\tlink_color_func=lambda x: 'black')\r\n\tplt.gca().set_axis_off()\r\n\t\r\n\tplt.sca(main_axes)\r\n\tplt.imshow(a, aspect='equal', interpolation='none', cmap=cm.OrRd, vmin=0.0, vmax=6.0)\r\n\tplt.colorbar(pad=0.15)\r\n\tplt.gca().yaxis.tick_right()\r\n #plt.xticks(range(a.shape[1]), a.columns, rotation=15, size='small')\r\n #plt.yticks(range(a.shape[0]), a.index, size='x-small')\r\n\tplt.gca().xaxis.set_ticks_position('none')\r\n\tplt.gca().yaxis.set_ticks_position('none')\r\n\tplt.gca().invert_yaxis()\r\n\tplt.show()\r\n\r\ndef main():\r\n\tfrom scipy.spatial.distance import squareform\r\n\timport read as rd\r\n\timport func as fc\r\n\r\n\tdata = fc.x2(rd.edit(0))\r\n\tvdist = squareform(data, force='tovector', checks=False)\r\n\tdata = -np.log10(data)\r\n\tdraw_heatmap(data, vdist)\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"x2_hieraxy.py","file_name":"x2_hieraxy.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"87"} +{"seq_id":"157552477","text":"#!/usr/bin/python3 \n\n\nimport os, time\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\ndef playVideo(video='cantinaband', duration='once', starttime='normal'):\n script = os.path.abspath(\"cantinaband.sh\")\n\n videos = {\n \"cantinaband\": os.path.abspath(\"cantinaband.mp4\"),\n \"bearvid\": os.path.abspath(\"mankicksbear.mp4\"),\n \"underwater\" : os.path.abspath(\"underwater.mp4\")\n }\n\n vid = videos[video]\n durations = {\n \"short\": \"108\",\n \"once\": \"136.3\",\n \"full\": \"27000\",\n \"bearduration\": \"46\",\n \"underwarterduration\": \"140\"\n \n }\n start = {\n \"normal\": \"100\",\n \"bearstart\": \"28\"\n }\n st= start[starttime]\n dur = durations[duration]\n sleepTime =float(dur) -float(st) \n\n command = f'{script} {vid} {dur} {sleepTime} {st}'\n\n # cantVid = os.path.join('videos', 'cantinaband', '.mp4')\n # os.path.join(os.getcwd(), cantVid)\n \n print(f'the variables are\\n')\n print(f'\\tvideo-arg: {video}, \\n\\tvideo path:{vid}')\n print(f'\\tduration-arg: {duration}, \\n\\tdur-arg: {dur}')\n print(f'\\tsleepTime: {sleepTime}')\n print(f'\\tcommand: \\n\\t\\t{command}')\n\n print('\\n\\nexecuting command now!')\n os.system(command)\n\n\n@app.route('/