90:\n under.append(ang)\n else:\n over.append(ang)\n AeffOver=[]\n AeffUnder=[]\n reco_eff=0.01\n A_times_recoeff=A_geom*10**-4*reco_eff*90/len(over) #area in m^2 \n \n #working configuration\n #for ene in energy:\n #AeffOver.append(sum(final_prbability(ene,over)))\n # AeffOver.append(final_prbability(ene,over[1]))\n #AeffUnder.append(sum(final_prbability(ene,under)))\n # AeffUnder.append(final_prbability(ene,under[-1]))\n for ang in theta:\n ciccio1=[]\n ciccio2=[]\n if ang < 90:\n for ene in energy:\n ciccio1.append(A_times_recoeff*final_prbability(ene,ang))\n AeffOver.append(ciccio1)\n else:\n for ene in energy:\n ciccio2.append(A_times_recoeff*final_prbability(ene,ang))\n AeffUnder.append(ciccio2)\n #print(len(AeffOver))\n #AeffOver=np.array(AeffOver)#*A_times_recoeff\n #AeffUnder=np.array(AeffUnder)#*A_times_recoeff\n return (AeffOver,AeffUnder)\n \ndef nu_flux(energy):\n ss=[]\n if hasattr(energy, \"__len__\"):\n for ene in energy:\n ss.append(ene**-2*10**-8) #evts/GeV*s*cm^2\n \n return ss\n else:\n return 10**-8*energy**-2\n \n \ndef Numb_events(energy,theta):\n \"\"\"\n differetial number of events in energy and in theta\n \"\"\"\n reco_eff=0.01\n numb_Lint,status=number_of_Lint(energy,theta)\n factor=year*A_geom*2*np.pi*reco_eff\n proba=final_prbability(energy,theta)\n flux=nu_flux(energy)\n if status==1:\n binwidth=(energy[-1]-energy[0])/len(energy)\n # print(binwidth)\n events=np.zeros((len(energy),len(theta)))\n for ene in range(len(energy)):\n for ang in range(len(theta)):\n events[ene][ang]=proba[ene][ang]*flux[ene]*factor*binwidth\n return events\n elif status==2:\n binwidth=(energy[-1]-energy[0])/len(energy)\n events=[]\n for ene in range(len(energy)):\n events.append(proba[ene]*flux[ene]*factor*binwidth)\n return events\n \n elif status==3:\n events=[]\n binwidth=(theta[-1]-theta[0])/len(theta)\n for ang in range(len(theta)):\n events.append(proba[ang]*flux*factor*binwidth)\n return events\n elif status==4:\n return proba*flux*factor*np.sin(np.radians(theta))\n\n\ndef sum_of_events(energy,theta):\n #limit1=a\n #limit2=b\n #events=Numb_events(energy,theta)\n sums=[]\n for ang in theta:\n sums.append(sum(Numb_events(energy,ang)))\n return sums\n\ndef check(energy,theta):\n events=sum_of_events(energy,theta)\n selection=[]\n cumulative=[]\n binwidth=(theta[-1]-theta[0])/len(theta)\n for ang in range(len(theta)):\n if theta[ang]>90:\n selection.append(events[ang]*binwidth*abs(np.sin(np.radians(ang))))\n cumulative.append(sum(selection))\n else:\n cumulative.append(0)\n print(\"CUMULATIVE\",sum(cumulative))\n return cumulative\n \n#-------------------------------------------------------------\n# Plotting functions\n#-------------------------------------------------------------\n\nx_lint = np.logspace(1,11, 100)#np.linspace(10,0.99*10**12, 100000)\nx_lineO = np.logspace(6,12, 100)#x_lineO = np.linspace(10**6,10**12, 100)\ny_lineO=fitfuncOVE(constCC,indexCC,x_lineO)\ny_lineNC=fitfuncOVE(constNC,indexNC,x_lineO)\ny_line_total=[]\nfor a in range(len(y_lineO)):\n y_line_total.append(y_lineO[a]+y_lineNC[a])\n \nradius=np.linspace(0,EarthRadius,100)\nhatm=np.linspace(EarthRadius+5,EarthRadius+atm_sup_limit,100)\nhsea=np.linspace(EarthRadius+0.1,EarthRadius+4.9999,100)\nttheta=np.linspace(0.1,89.9,100)\nstheta=np.linspace(90.01,179.9,100)\ncc=[]\nff=[]\nfor aa in stheta:\n cc.append(int_lentgth_earth(aa)) \n ff.append(sea_profile(aa))\n #print(stheta)\ndd=[]\nfor bb in stheta:\n dd.append(int_length_atm(bb))\n\n#-------------------------------------------------------------\n#surface plot number generators\n#-------------------------------------------------------------\nNumber_of_points=50\n#x_energy = np.linspace(10,10**11, Number_of_points)\nx_energy = np.logspace(1,7, Number_of_points)\nzenithy=np.linspace(0,179.9,Number_of_points)\n#zenithy=np.logspace(0,2,Number_of_points)\n\n#-------------------------------------------------------------\n# Neutrino functions: Cross Section CC, Bjorken y, Interaction Length in (g/cm^2)\n#-------------------------------------------------------------\nf=plt.figure()\nax1=f.add_subplot(311)\ndf.plot(kind='scatter',x='Energy (GeV)',y='CrossSectionCC',color='green',ax=ax1, logx=True, logy=True)\nsimulated.plot(kind='scatter',x='Energy (GeV)',y='Total_CS',color='red',ax=ax1, logx=True, logy=True)\nsimulated.plot(kind='scatter',x='Energy (GeV)',y='CrossSCC',color='green',ax=ax1, logx=True, logy=True)\nsimulated.plot(kind='scatter',x='Energy (GeV)',y='CrossNC',color='blue',ax=ax1, logx=True, logy=True)\n#ax1.plot(x_line,y_line,'b--')\nax1.plot(x_lineO,y_lineO,'+',markersize=2, color='g')#'g--')\nax1.plot(x_lineO,y_lineNC,'+',markersize=2, color='b')#'b--')\nax1.plot(x_lineO,y_line_total,'+',markersize=2, color='r')\nax1.set_title('nu N CC Cross Section')\nax2=f.add_subplot(312)\ndf.plot(kind='scatter',x='Energy (GeV)',y='minelasticityCC',color='g',ax=ax2,logx=True,logy=True)\nax2.plot(x_lint,Bjorken(x_lint),'+',markersize=2, color='r')\nax2.set_title('Mean Bjorken y nu N CC')\nax3=f.add_subplot(313)\n#ax3.plot(x_line,Lint(x_line),'r--')\nax3.plot(x_lint,Lint(x_lint,'CC'),'+',markersize=2, color='g')#'g--')\nax3.plot(x_lint,Lint(x_lint,'Total'),'+',markersize=2, color='r')#'r--')\nax3.plot(x_lint,Lint(x_lint,'NC'),'+',markersize=2, color='b')#'b--')\nax3.set_yscale('log')\nax3.set_xscale('log')\nax3.set_ylabel('Lint (g/cm^2)')\nax3.set_xlabel('E_nu (GeV)')\nax3.set_title('Interaction Length')\nf.suptitle('Neutrino property functions')\n#-------------------------------------------------------------\n# Earth: 0) density profile vs radius; 4) slant depth (g/cm^2) vs angle\n#-------------------------------------------------------------\n\nf2=plt.figure()\nax=f2.add_subplot(121)\nax.plot(radius, density_profile(radius),'b-')\nax.set_ylabel('Density')\nax.set_xlabel('Earth radius (km)')\nax.set_title('Earth density profile')\nax4=f2.add_subplot(122)\n#ax4.plot(stheta,int_lentgth_earth(stheta),'b--')\nax4.plot(stheta,cc,'+',markersize=2, color='b')\nax4.set_title('slant depth')\nax4.set_ylabel('x rho (g/cm^2)')\nax4.set_xlabel('zenith angle (deg)')\nf2.suptitle('Earth')\n#-------------------------------------------------------------\n# Atmosphere: 5) density profile vs height ; 6) slanth depth (g/cm^2) vs angle\n#-------------------------------------------------------------\n\nf3=plt.figure()\nax5=f3.add_subplot(121)\nax5.plot(hatm, atmosphere(hatm),'+',markersize=2, color='g')\nax5.set_ylabel('Density')\nax5.set_xlabel('Atmoosphere height (km)')\nax5.set_yscale('log')\nax6=f3.add_subplot(122)\n#ax6.plot(stheta,int_length_atm(stheta),'b--')\nax6.plot(stheta,dd,'+',markersize=2, color='b')#'g--')\nax6.set_ylabel('x rho (g/cm^2)')\nax6.set_xlabel('zenith angle (deg)')\nax6.set_yscale('log')\nf3.suptitle('Atmosphere')\n#-------------------------------------------------------------\n# Sea: 7) density profile vs height (0 = sea bed, 3.5*10**5 sea level for ARCA;\n# 8) slanth depth (g/cm^2) vs angle\n#-------------------------------------------------------------\n\nf4=plt.figure()\nax7=f4.add_subplot(121)\nax7.plot(hsea, sea(hsea),'+',markersize=2, color='b')\nax7.set_ylabel('Sea Density')\nax7.set_xlabel('Sea height (km)')\nax8=f4.add_subplot(122)\n#ax6.plot(stheta,int_length_atm(stheta),'b--')\n#ax8.plot(ttheta,sea_profile((3.5+EarthRadius)*10**5,ttheta),'g--')\nax8.plot(stheta,ff,'g--')\n#ax8.plot(stheta,sea_profile(3.5+EarthRadius),'g--')\nax8.set_ylabel('x rho (g/cm^2)')\nax8.set_xlabel('zenith angle (deg)')\nax8.set_yscale('log')\nf4.suptitle('Sea')\n\n#-------------------------------------------------------------\n# TOTAL SLANT DEPTH vs ZENITH ANGLE\n#-------------------------------------------------------------\nf5=plt.figure()\nax9=f5.add_subplot(111)\nax9.plot(zenithy,total_slant(zenithy),'+',markersize=2, color='r')\n#ax9.plot(stheta,cc,'b--')\n#ax9.plot(stheta,dd,'g--')\n#ax9.plot(stheta,sea_profile(stheta),'g--')\nax9.set_ylabel('x rho (g/cm^2)')\nax9.set_xlabel('zenith angle (deg)')\nax9.set_yscale('log')\nf5.suptitle('TOTAL SLANT DEPTH vs ZENITH')\n\n\n\n#-------------------------------------------------------------\n# SURFACE PLOTS:\n# 10) Number on Lint; 11) survival probability; 12) survival at can level\n# 13) Interaction inside can; 14) 12*13= final probability\n#-------------------------------------------------------------\nfig = plt.figure()\nax10 = fig.add_subplot(121, projection='3d')\nax10.set_title('zenith energy # of Lint')\nX1=x_energy\nY1=zenithy\nZ1=number_of_Lint(X1,Y1)[0]\nX1, Y1 = np.meshgrid(X1, Y1)\nsurf = ax10.plot_surface(X1, Y1, Z1, cmap=cm.coolwarm,linewidth=0, antialiased=False)\nax10.set_xlabel('energy (GeV)')\nax10.set_ylabel('zenith angle (deg)')\n#ax10.colorbar(surf, shrink=0.5, aspect=5)\nax11 = fig.add_subplot(122, projection='3d')\nZ2=Survival_probability_mean(x_energy,zenithy)\nax11.set_xlabel('energy (GeV)')\nax11.set_ylabel('zenith angle (deg)')\nsurf1=ax11.plot_surface(X1, Y1, Z2, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n#plt.imshow(number_of_Lint(x_lint,zenithy),origin='lower',interpolation='none')\n#fig.suptitle(\"distribution\")\nfig.colorbar(surf1, shrink=0.5, aspect=5)\n\nfigg= plt.figure()\naxmuon = figg.add_subplot(111)\naxmuon.set_title('muon range')\naxmuon.plot(x_energy,muon_range(x_energy),'+',markersize=2, color='r')\naxmuon.plot(x_energy,radius_can(x_energy),'+',markersize=2, color='g')\naxmuon.set_xlabel('energy (GeV)')\naxmuon.set_ylabel('Range (g/cm^2)')\naxmuon.set_xscale('log')\n\n\nfigmuon = plt.figure()\nax12 = figmuon.add_subplot(231, projection='3d')\nX2=x_energy\nY2=zenithy\nZ3=nu_survival_can_level(X2,Y2)\nZ4=nu_interaction_inside_can(X2,Y2)\nZ5=final_prbability(X2,Y2)\nX2, Y2 = np.meshgrid(X2, Y2)\nax12.set_xlabel('energy (GeV)')\nax12.set_ylabel('zenith angle (deg)')\nax12.set_title(\"survival at can level\")\nsurf2=ax12.plot_surface(X2, Y2, Z3, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n\n\nax13 = figmuon.add_subplot(232, projection='3d')\nax13.set_xlabel('energy (GeV)')\nax13.set_ylabel('zenith angle (deg)')\nsurf3=ax13.plot_surface(X2, Y2, Z4, cmap=cm.coolwarm,linewidth=0, antialiased=False)\nax13.set_title(\"Interaction inside can\")\n#plt.imshow(number_of_Lint(x_lint,zenithy),origin='lower',interpolation='none')\nax14 = figmuon.add_subplot(233, projection='3d')\nax14.set_xlabel('energy (GeV)')\nax14.set_ylabel('zenith angle (deg)')\nax14.set_title(\"Final Probability\")\nsurf2=ax14.plot_surface(X2, Y2, Z5, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n\n\n#print(\"_---------------______________------___DEBUG_______------_______---_--_-__-_-_-_--_-__\")\nE_fixed=10**7\nax15 = figmuon.add_subplot(234)\nax15.plot(zenithy,nu_survival_can_level(E_fixed,zenithy),'+',markersize=2)\n\nax16 = figmuon.add_subplot(235)\nax16.plot(zenithy,nu_interaction_inside_can(E_fixed,zenithy),'+',markersize=2)\n\nax17 = figmuon.add_subplot(236)\nax17.plot(zenithy,final_prbability(E_fixed,zenithy),'+',markersize=2)\n\n#TeVSky = np.logspace(3,6, Number_of_points)\n#PeVSky = np.logspace(6,9, Number_of_points)\n#EeVSky = np.logspace(9,11, Number_of_points)\n\n#TeVSky = np.linspace(10**3,10**6, Number_of_points)\n#PeVSky = np.linspace(10**6,10**9, Number_of_points)\n#EeVSky = np.linspace(10**9,10**11, Number_of_points)\n\nTeVSky = np.geomspace(10**3,10**6, Number_of_points)\nPeVSky = np.geomspace(10**6,10**9, Number_of_points)\nEeVSky = np.geomspace(10**9,10**11, Number_of_points)\n\nNevents=plt.figure()\nax18=Nevents.add_subplot(231,projection='3d')\nax18.set_title('Number of events')\nX3=x_energy\nY3=zenithy\nZ6=Numb_events(X3,Y3)\nX3, Y3 = np.meshgrid(X3, Y3)\nsurf3=ax18.plot_surface(X3, Y3, Z6, cmap=cm.coolwarm,linewidth=0, antialiased=False)\nax19=Nevents.add_subplot(232)\nax19.set_title(Decimal(str(E_fixed)))\nax19.plot(zenithy,Numb_events(E_fixed,zenithy),'+',markersize=2)\nax20=Nevents.add_subplot(233)\nax20.set_title('TeV Sky (1 TeV-1PeV)')\nax20.plot(zenithy,sum_of_events(TeVSky,zenithy),'+',markersize=2,color='r')\nax20_1=Nevents.add_subplot(234)\nax20_1.set_title('Cumulative 90-180 (1 TeV-1 PeV)')\nax20_1.plot(zenithy,check(TeVSky,zenithy),'+',markersize=2,color='r')\n\nax21=Nevents.add_subplot(235)\nax21.set_title('PeV Sky (1PeV-1EeV)')\nax21.plot(zenithy,sum_of_events(PeVSky,zenithy),'+',markersize=2,color='b')\nax22=Nevents.add_subplot(236)\nax22.set_title('EeV Sky (1EeV-$10^21$ eV)')\nax22.plot(zenithy,sum_of_events(EeVSky,zenithy),'+',markersize=2,color='g')\n\naeff=plt.figure()\naeff.suptitle('$A_{eff}$ TeV Sky')\nax23=aeff.add_subplot(121)\nOver,Under=A_eff(TeVSky,zenithy)\nax23.set_title('$A_{eff}$ Over')\nsumsOver=np.zeros(len(Over[0]))\nfor aefff in range(len(Over)):\n ax23.plot(TeVSky,Over[aefff],'+',markersize=2)#,color='g')\n sumsOver=sumsOver+np.array(Over[aefff])\nax23.plot(TeVSky,sumsOver,'g--')\nax23.set_xscale('log')\nax23.set_yscale('log')\n\nax24=aeff.add_subplot(122)\nax24.set_title('$A_{eff}$ Under')\nsumsUnder=np.zeros(len(Under[0]))\nfor ae in range(len(Under)):\n ax24.plot(TeVSky,Under[ae],'+',markersize=2)#,color='g')\n sumsUnder=sumsUnder+np.array(Under[ae])\nax24.plot(TeVSky,sumsUnder,'g--')\nax24.set_xscale('log')\nax24.set_yscale('log')\n\naeff1=plt.figure()\naeff1.suptitle('$A_{eff}$ PeV Sky')\nax25=aeff1.add_subplot(121)\nOver1,Under1=A_eff(PeVSky,zenithy)\nax25.set_title('$A_{eff}$ Over')\nsumsOver1=np.zeros(len(Over1[0]))\nfor aefff1 in range(len(Over1)):\n ax25.plot(PeVSky,Over1[aefff1],'+',markersize=2)#,color='g')\n sumsOver1=sumsOver1+np.array(Over1[aefff1])\nax25.plot(PeVSky,sumsOver1,'g--')\nax25.set_xscale('log')\nax25.set_yscale('log')\n\nax26=aeff1.add_subplot(122)\nax26.set_title('$A_{eff}$ Under')\nsumsUnder1=np.zeros(len(Under1[0]))\nfor ae1 in range(len(Under1)):\n ax26.plot(PeVSky,Under1[ae1],'+',markersize=2)#,color='g')\n sumsUnder1=sumsUnder1+np.array(Under1[ae1])\nax26.plot(PeVSky,sumsUnder1,'g--')\nax26.set_xscale('log')\nax26.set_yscale('log')\nax26.set_ylim([10**-1, 10**5])\n\naeff2=plt.figure()\naeff2.suptitle('$A_{eff}$ EeV Sky')\nax27=aeff2.add_subplot(121)\nOver2,Under2=A_eff(EeVSky,zenithy)\nax27.set_title('$A_{eff}$ Over')\nsumsOver2=np.zeros(len(Over2[0]))\nfor aefff2 in range(len(Over2)):\n ax27.plot(EeVSky,Over2[aefff2],'+',markersize=2)#,color='g')\n sumsOver2=sumsOver2+np.array(Over2[aefff2])\nax27.plot(EeVSky,sumsOver2,'g--')\nax27.set_xscale('log')\nax27.set_yscale('log')\n\nax28=aeff2.add_subplot(122)\nax28.set_title('$A_{eff}$ Under')\nsumsUnder2=np.zeros(len(Under2[0]))\nfor ae2 in range(len(Under2)):\n ax28.plot(EeVSky,Under2[ae2],'+',markersize=2)#,color='g')\n sumsUnder2=sumsUnder2+np.array(Under2[ae2])\nax28.plot(EeVSky,sumsUnder2,'g--')\nax28.set_xscale('log')\nax28.set_yscale('log')\nax28.set_ylim([10**-5, 10**4])\nplt.show()\n \n","sub_path":"ARCA_UP_SKY/Final.py","file_name":"Final.py","file_ext":"py","file_size_in_byte":41023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"302067155","text":"# Copyright 2017 Ruben Decrop\n\nimport datetime, urllib.request, sys, io\nfrom chessapi.models.ranking import Belplayer\n\ndef fetchplayerdbf():\n now = datetime.datetime.now()\n year = now.year\n month = (now.month - 1) // 3 * 3 + 1\n period = '{0:4d}{1:02d}'.format(year, month)\n print('period', period)\n url = 'http://www.frbe-kbsb.be/sites/manager/ELO/PLAYER_{0}.ZIP'.format(\n period)\n try:\n f = urllib.request.urlopen(url)\n except urllib.request.URLError:\n print('Cannot open url %s', url)\n return False\n fdata = f.read()\n f.close()\n return Belplayer.readzipfile(io.BytesIO(fdata), period)\n\n\nif __name__ == '__main__':\n print('fetching player.dbf')\n if fetchplayerdbf():\n print('success')\n\n\n","sub_path":"chessapi/scripts/fetchplayerdbf.py","file_name":"fetchplayerdbf.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"435967520","text":"def get_jaccard_sim( genres1 , genres2 ):\n len1 = len( genres1 )\n len2 = len( genres2 )\n # print( \"len1\" , len1 )\n # print( \"len2\" , len2 )\n if len1 == 1 and genres1[0] == 'Genre not found.':\n genres1 = []\n if len2 == 1 and genres2[0] == 'Genre not found.':\n genres2 = []\n len1 = len( genres1 )\n len2 = len( genres2 )\n if len1 == 0 and len2 == 0:\n return -2\n if len1 == 0 or len2 == 0:\n return -3\n num = 0\n den = len1 + len2\n for genre in genres1:\n if genre in genres2:\n num = num + 1\n den = den - 1\n # print( \"num\" , num )\n # print( \"den\" , den )\n return num / den","sub_path":"src/get_jaccard_sim.py","file_name":"get_jaccard_sim.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"49796200","text":"#!/usr/bin/env python\n# Lint as: python3\n\"\"\"Functions to run individual GRR components during self-contained testing.\"\"\"\n\nimport atexit\nimport os\nimport shutil\nimport signal\nimport subprocess\nimport sys\nimport tempfile\nimport threading\nimport time\n\nfrom typing import Dict, Iterable, List, Optional, Tuple, Union\n\nimport portpicker\n\nfrom grr_response_core.lib import package\nfrom grr_response_test.lib import api_helpers\n\nComponentOptions = Dict[str, Union[int, str]]\n\n\nclass Error(Exception):\n \"\"\"Module-specific base error class.\"\"\"\n\n\nclass ConfigInitializationError(Error):\n \"\"\"Raised when a self-contained config can't be written.\"\"\"\n\n\ndef _ComponentOptionsToArgs(options):\n if options is None:\n return []\n\n args = []\n for k, v in options.items():\n args.extend([\"-p\", \"%s=%s\" % (k, v)])\n return args\n\n\ndef _GetServerComponentArgs(config_path):\n \"\"\"Returns a set of command line arguments for server components.\n\n Args:\n config_path: Path to a config path generated by\n self_contained_config_writer.\n\n Returns:\n An iterable with command line arguments to use.\n \"\"\"\n\n primary_config_path = package.ResourcePath(\n \"grr-response-core\", \"install_data/etc/grr-server.yaml\")\n secondary_config_path = package.ResourcePath(\n \"grr-response-test\", \"grr_response_test/test_data/grr_test.yaml\")\n return [\n \"--config\",\n primary_config_path,\n \"--secondary_configs\",\n \",\".join([secondary_config_path, config_path]),\n \"-p\",\n \"Monitoring.http_port=%d\" % portpicker.pick_unused_port(),\n \"-p\",\n \"AdminUI.webauth_manager=NullWebAuthManager\",\n ]\n\n\ndef _GetRunEndToEndTestsArgs(\n client_id,\n server_config_path,\n tests = None,\n manual_tests = None):\n \"\"\"Returns arguments needed to configure run_end_to_end_tests process.\n\n Args:\n client_id: String with a client id pointing to an already running client.\n server_config_path: Path to the server configuration file.\n tests: (Optional) List of tests to run.\n manual_tests: (Optional) List of manual tests to not skip.\n\n Returns:\n An iterable with command line arguments.\n \"\"\"\n port = api_helpers.GetAdminUIPortFromConfig(server_config_path)\n\n api_endpoint = \"http://localhost:%d\" % port\n args = [\n \"--api_endpoint\",\n api_endpoint,\n \"--api_user\",\n \"admin\",\n \"--api_password\",\n \"admin\",\n \"--client_id\",\n client_id,\n \"--ignore_test_context\",\n \"True\",\n ]\n if tests is not None:\n args += [\"--whitelisted_tests\", \",\".join(tests)]\n if manual_tests is not None:\n args += [\"--manual_tests\", \",\".join(manual_tests)]\n\n return args\n\n\ndef _StartComponent(main_package, args):\n \"\"\"Starts a new process with a given component.\n\n This starts a Python interpreter with a \"-m\" argument followed by\n the main package name, thus effectively executing the main()\n function of a given package.\n\n Args:\n main_package: Main package path.\n args: An iterable with program arguments (not containing the program\n executable).\n\n Returns:\n Popen object corresponding to a started process.\n \"\"\"\n popen_args = [sys.executable, \"-m\", main_package] + args\n print(\"Starting %s component: %s\" % (main_package, \" \".join(popen_args)))\n process = subprocess.Popen(popen_args)\n print(\"Component %s pid: %d\" % (main_package, process.pid))\n\n def KillOnExit():\n if process.poll() is None:\n print(\"Killing %s.\" % main_package)\n process.kill()\n process.wait()\n\n atexit.register(KillOnExit)\n\n return process\n\n\ndef InitConfigs(mysql_database,\n mysql_username = None,\n mysql_password = None,\n logging_path = None,\n osquery_path = None):\n \"\"\"Initializes server and client config files.\"\"\"\n\n # Create 2 temporary files to contain server and client configuration files\n # that we're about to generate.\n #\n # TODO(user): migrate to TempFilePath as soon grr.test_lib is moved to\n # grr_response_test.\n fd, built_server_config_path = tempfile.mkstemp(\".yaml\")\n os.close(fd)\n print(\"Using temp server config path: %s\" % built_server_config_path)\n fd, built_client_config_path = tempfile.mkstemp(\".yaml\")\n os.close(fd)\n print(\"Using temp client config path: %s\" % built_client_config_path)\n\n def CleanUpConfigs():\n os.remove(built_server_config_path)\n os.remove(built_client_config_path)\n\n atexit.register(CleanUpConfigs)\n\n # Generate server and client configs.\n config_writer_flags = [\n \"--dest_server_config_path\",\n built_server_config_path,\n \"--dest_client_config_path\",\n built_client_config_path,\n \"--config_mysql_database\",\n mysql_database,\n ]\n\n if mysql_username is not None:\n config_writer_flags.extend([\"--config_mysql_username\", mysql_username])\n\n if mysql_password is not None:\n config_writer_flags.extend([\"--config_mysql_password\", mysql_password])\n\n if logging_path is not None:\n config_writer_flags.extend([\"--config_logging_path\", logging_path])\n\n if osquery_path is not None:\n config_writer_flags.extend([\"--config_osquery_path\", osquery_path])\n\n p = _StartComponent(\n \"grr_response_test.lib.self_contained_config_writer\",\n config_writer_flags)\n if p.wait() != 0:\n raise ConfigInitializationError(\"ConfigWriter execution failed: {}\".format(\n p.returncode))\n\n return (built_server_config_path, built_client_config_path)\n\n\ndef StartServerProcesses(\n server_config_path,\n component_options = None\n):\n\n def Args():\n return _GetServerComponentArgs(\n server_config_path) + _ComponentOptionsToArgs(component_options)\n\n return [\n _StartComponent(\n \"grr_response_server.gui.admin_ui\",\n Args()),\n _StartComponent(\n \"grr_response_server.bin.frontend\",\n Args()),\n _StartComponent(\n \"grr_response_server.bin.worker\",\n Args()),\n ]\n\n\ndef StartClientProcess(client_config_path,\n component_options = None,\n verbose = False):\n return _StartComponent(\n \"grr_response_client.client\",\n [\"--config\", client_config_path] + ([\"--verbose\"] if verbose else []) +\n _ComponentOptionsToArgs(component_options))\n\n\ndef RunEndToEndTests(client_id,\n server_config_path,\n tests = None,\n manual_tests = None):\n \"\"\"Runs end to end tests on a given client.\"\"\"\n p = _StartComponent(\n \"grr_response_test.run_end_to_end_tests\",\n _GetServerComponentArgs(server_config_path) + _GetRunEndToEndTestsArgs(\n client_id, server_config_path, tests=tests,\n manual_tests=manual_tests))\n if p.wait() != 0:\n raise RuntimeError(\"RunEndToEndTests execution failed.\")\n\n\ndef RunBuildTemplate(server_config_path,\n component_options = None,\n version_ini = None):\n \"\"\"Runs end to end tests on a given client.\"\"\"\n output_dir = tempfile.mkdtemp()\n\n def CleanUpTemplate():\n shutil.rmtree(output_dir)\n\n atexit.register(CleanUpTemplate)\n\n options = dict(component_options or {})\n if version_ini:\n fd, version_ini_path = tempfile.mkstemp(\".ini\")\n try:\n os.write(fd, version_ini.encode(\"ascii\"))\n finally:\n os.close(fd)\n\n options[\"ClientBuilder.version_ini_path\"] = version_ini_path\n\n p = _StartComponent(\n \"grr_response_client_builder.client_build\",\n _GetServerComponentArgs(server_config_path) +\n _ComponentOptionsToArgs(options) + [\"build\", \"--output\", output_dir])\n if p.wait() != 0:\n raise RuntimeError(\"RunBuildTemplate execution failed.\")\n\n return os.path.join(output_dir, os.listdir(output_dir)[0])\n\n\ndef RunRepackTemplate(\n server_config_path,\n template_path,\n component_options = None):\n \"\"\"Runs 'grr_client_builder repack' to repack a template.\"\"\"\n output_dir = tempfile.mkdtemp()\n\n def CleanUpInstaller():\n shutil.rmtree(output_dir)\n\n atexit.register(CleanUpInstaller)\n\n p = _StartComponent(\n \"grr_response_client_builder.client_build\",\n _GetServerComponentArgs(server_config_path) +\n _ComponentOptionsToArgs(component_options) +\n [\"repack\", \"--template\", template_path, \"--output_dir\", output_dir])\n if p.wait() != 0:\n raise RuntimeError(\"RunRepackTemplate execution failed.\")\n\n # Repacking may apparently generate more than one file. Just select the\n # biggest one: it's guaranteed to be the template.\n paths = [os.path.join(output_dir, fname) for fname in os.listdir(output_dir)]\n sizes = [os.path.getsize(p) for p in paths]\n _, biggest_path = max(zip(sizes, paths))\n\n return biggest_path\n\n\ndef RunUploadExe(server_config_path,\n exe_path,\n platform,\n component_options = None):\n \"\"\"Runs 'grr_config_upater upload_exe' to upload a binary to GRR.\"\"\"\n p = _StartComponent(\n \"grr_response_server.bin.config_updater\",\n _GetServerComponentArgs(server_config_path) +\n _ComponentOptionsToArgs(component_options) + [\n \"upload_exe\", \"--file\", exe_path, \"--platform\", platform,\n \"--upload_subdirectory\", \"test\"\n ])\n if p.wait() != 0:\n raise RuntimeError(\"RunUploadExe execution failed.\")\n\n return \"%s/test/%s\" % (platform, os.path.basename(exe_path))\n\n\n_PROCESS_CHECK_INTERVAL = 0.1\n\n\ndef _DieIfSubProcessDies(processes,\n already_dead_event):\n \"\"\"Synchronously waits for processes and dies if one dies.\"\"\"\n while True:\n for p in processes:\n if p.poll() not in [None, 0]:\n # Prevent a double kill. When the main process exits, it kills the\n # children. We don't want a child's death to cause a SIGTERM being\n # sent to a process that's already exiting.\n if already_dead_event.is_set():\n return\n\n # DieIfSubProcessDies runs in a background thread, raising an exception\n # will just kill the thread while what we want is to fail the whole\n # process.\n print(\"Subprocess %s died unexpectedly. Killing main process...\" %\n p.pid)\n for kp in processes:\n try:\n os.kill(kp.pid, signal.SIGTERM)\n except OSError:\n pass\n # sys.exit only exits a thread when called from a thread.\n # Killing self with SIGTERM to ensure the process runs necessary\n # cleanups before exiting.\n os.kill(os.getpid(), signal.SIGTERM)\n time.sleep(_PROCESS_CHECK_INTERVAL)\n\n\ndef DieIfSubProcessDies(\n processes):\n \"\"\"Kills the process if any of given processes dies.\n\n This function is supposed to run in a background thread and monitor provided\n processes to ensure they don't die silently.\n\n Args:\n processes: An iterable with multiprocessing.Process instances.\n\n Returns:\n Background thread started to monitor the processes.\n \"\"\"\n already_dead_event = threading.Event()\n t = threading.Thread(\n target=_DieIfSubProcessDies, args=(processes, already_dead_event))\n t.daemon = True\n t.start()\n\n def PreventDoubleDeath():\n already_dead_event.set()\n\n atexit.register(PreventDoubleDeath)\n\n return t\n","sub_path":"grr/test/grr_response_test/lib/self_contained_components.py","file_name":"self_contained_components.py","file_ext":"py","file_size_in_byte":11051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"289303594","text":"import sys\nimport traceback\n\nimport Qt.QtWidgets as QtWidgets\nimport Qt.QtCore as QtCore\nimport Qt.QtGui as QtGui\n\nfrom gazupublisher.views.MainWindow import MainWindow\nfrom gazupublisher.ui_data.color import main_color, text_color\nfrom gazupublisher.utils.error_window import ResizableMessageBox\nfrom gazupublisher.working_context import (\n set_working_context,\n get_working_context,\n is_maya_context,\n is_blender_context,\n)\nfrom qtazu.widgets.login import Login\n\n\n# Hack to allow to close the application with Ctrl+C\nimport signal\n\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\n\n\ndef excepthook(exc_type, exc_value, exc_traceback):\n \"\"\"\n Handle unexpected errors by popping an error window and restarting the app.\n \"\"\"\n\n string_tb = traceback.format_exception(exc_type, exc_value, exc_traceback)\n from_gazupublisher = any(\n \"gazupublisher\" in tb_step for tb_step in string_tb\n )\n if not from_gazupublisher:\n sys.__excepthook__(exc_type, exc_value, exc_traceback)\n return\n\n header = \"\\n=== An error occured !=== \\nError message:\\n\"\n traceback_print = \"\".join(string_tb)\n\n message = \"%s%s\" % (header, traceback_print)\n if is_blender_context():\n from dccutils.dcc_blender import BlenderContext\n\n BlenderContext.software_print(message)\n else:\n print(message)\n app = QtWidgets.QApplication.instance()\n create_error_dialog(app.current_window, traceback_print)\n app.current_window.close()\n launch_main_app(app)\n\n\ndef create_error_dialog(parent, message):\n \"\"\"\n Create an error dialog window.\n \"\"\"\n error_dialog = ResizableMessageBox(parent)\n error_dialog.setWindowTitle(\"ERROR\")\n error_dialog.setModal(True)\n error_dialog.setText(\"An error has occurred\")\n error_dialog.setDetailedText(message)\n error_dialog.setStandardButtons(QtWidgets.QMessageBox.Cancel)\n error_dialog.show()\n error_dialog.raise_()\n error_dialog.activateWindow()\n\n\ndef launch_main_app(app):\n \"\"\"\n Launch the main application.\n \"\"\"\n window = create_main_window(app)\n window.show()\n\n\ndef on_emit(is_success, app, login_window):\n \"\"\"\n Activated on emit from the login window.\n \"\"\"\n if is_success:\n login_window.deleteLater()\n launch_main_app(app)\n\n\ndef gazu_login_window(app):\n \"\"\"\n Creates the login window.\n \"\"\"\n login_window = Login()\n login_window.logged_in.connect(\n lambda is_success: on_emit(is_success, app, login_window)\n )\n return login_window\n\n\ndef setup_dark_mode(app):\n \"\"\"\n Set up dark mode.\n \"\"\"\n palette = QtGui.QPalette()\n palette.setColor(QtGui.QPalette.Window, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.WindowText, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.Base, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.ToolTipBase, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.ToolTipText, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.Text, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.Button, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red)\n palette.setColor(QtGui.QPalette.Link, QtGui.QColor(42, 130, 218))\n palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(42, 130, 218))\n palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black)\n palette.setColor(\n QtGui.QPalette.Disabled,\n QtGui.QPalette.WindowText,\n QtGui.QColor(text_color).darker(170),\n )\n palette.setColor(\n QtGui.QPalette.Disabled,\n QtGui.QPalette.ButtonText,\n QtGui.QColor(text_color).darker(170),\n )\n app.setPalette(palette)\n\n\ndef setup_style(app):\n \"\"\"\n Setup style. 'Fusion' is the wanted default style for this app.\n Maya already defines its own style.\n \"\"\"\n if \"Fusion\" in QtWidgets.QStyleFactory.keys() and not is_maya_context():\n app.setStyle(\"Fusion\")\n\n\ndef create_app():\n app = QtCore.QCoreApplication.instance()\n if app:\n try:\n import maya.cmds\n\n set_working_context(\"MAYA\")\n except:\n pass\n else:\n app = QtWidgets.QApplication(sys.argv)\n setup_style(app)\n setup_dark_mode(app)\n sys.excepthook = excepthook\n return app\n\n\ndef create_login_window(app):\n login_window = gazu_login_window(app)\n app.current_window = login_window\n return login_window\n\n\ndef create_main_window(app):\n main_window = MainWindow(app)\n app.current_window = main_window\n main_window.setObjectName(\"main_window\")\n main_window.setWindowTitle(\"Kitsu\")\n main_window.setStyleSheet(\n \"QMainWindow{background-color: %s;} \"\n \"QToolTip{color: %s; background-color: %s; border: 0px;}\"\n % (main_color, text_color, main_color)\n )\n return main_window\n\n\ndef main():\n try:\n app = create_app()\n login_window = create_login_window(app)\n login_window.show()\n sys.exit(app.exec_())\n\n except KeyboardInterrupt:\n sys.exit()\n\n\nif __name__ == \"__main__\":\n set_working_context(\"STANDALONE\")\n print(\"Working context : \" + get_working_context())\n main()\n","sub_path":"gazupublisher/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"398763002","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 03 10:53:45 2018\r\n@author: Animesh Paul\r\nReferences:\r\n 1. https://docs.opencv.org/\r\n 2. https://www.stackoverflow.com/\r\n\"\"\"\r\nimport cv2 as cv\r\nimport numpy as np\r\nimport os\r\nfrom matplotlib import pyplot as plt\r\n\r\nUBIT = 'animeshp'\r\nnp.random.seed(sum([ord(c) for c in UBIT]))\r\n\r\nRESULT_DIR = \"./Results/Task3/\"\r\nif not os.path.exists(RESULT_DIR):\r\n os.makedirs(RESULT_DIR)\r\n\r\ndef save_img(filename, img):\r\n # Saves image with passed filename in the results folder\r\n if not os.path.exists(RESULT_DIR):\r\n os.makedirs(RESULT_DIR)\r\n filename = os.path.join(RESULT_DIR, filename)\r\n cv.imwrite(filename, img)\r\n\r\ndef compute_euc_dist(X, Mu):\r\n #X and Mu are two 1D Lists\r\n return(np.sqrt((X[0]- Mu[0]) ** 2 + (X[1] - Mu[1]) ** 2))\r\n \r\ndef assign(X, Mu):\r\n \"\"\" First Step is Computation of Euclidean Distance \"\"\"\r\n d_matrix = []\r\n index = []\r\n for i in range(0,len(X)):\r\n l = []\r\n for j in range(0,len(Mu)):\r\n d = compute_euc_dist(X[i], Mu[j])\r\n l.append(d)\r\n d_matrix.append(l)\r\n \r\n for i in range(0,len(d_matrix)):\r\n t = d_matrix[i].index(min(d_matrix[i]))\r\n index.append(t+1) # Class Vector\r\n return (index)\r\n\r\ndef plot_points(index, X, Mu, s):\r\n r_x = []\r\n r_y = []\r\n g_x = []\r\n g_y = []\r\n b_x = []\r\n b_y = []\r\n for i in range(0,len(index)):\r\n if index[i] == 1:\r\n r_x.append(X[i][0])\r\n r_y.append(X[i][1])\r\n if index[i] == 2:\r\n g_x.append(X[i][0])\r\n g_y.append(X[i][1])\r\n if index[i] == 3:\r\n b_x.append(X[i][0])\r\n b_y.append(X[i][1])\r\n \r\n plt.scatter(r_x, r_y, marker = '^', edgecolor = 'red', facecolor = 'white')\r\n plt.scatter(g_x, g_y, marker = '^', edgecolor = 'green', facecolor = 'white')\r\n plt.scatter(b_x, b_y, marker = '^', edgecolor = 'blue', facecolor = 'white')\r\n plt.scatter(Mu[0][0], Mu[0][1], marker = 'o', color = 'red')\r\n plt.scatter(Mu[1][0], Mu[1][1], marker = 'o', color = 'green')\r\n plt.scatter(Mu[2][0], Mu[2][1], marker = 'o', color = 'blue')\r\n \r\n for i in range(0,len(X)):\r\n plt.text(X[i][0], X[i][1] - 0.08, f'({X[i][0]}{X[i][1]})', fontsize = 4.5)\r\n \r\n for i in range(0,len(Mu)):\r\n plt.text(Mu[i][0], Mu[i][1] - 0.08, f'({Mu[i][0]}{Mu[i][1]})', fontsize = 4.5)\r\n \r\n plt.savefig(os.path.join(RESULT_DIR, 'task3_iter'+str(s)+'.jpg'))\r\n plt.gcf().clear()\r\n #print(\"Current Centroids are:= \" +str(Mu))\r\n \r\ndef recompute_mu(index, X, Mu):\r\n s1x = 0\r\n s1y = 0\r\n s2x = 0\r\n s2y = 0\r\n s3x = 0\r\n s3y = 0\r\n c1 = index.count(1)\r\n c2 = index.count(2)\r\n c3 = index.count(3)\r\n for i in range(0,len(index)):\r\n if index[i] == 1:\r\n s1x = s1x + X[i][0]\r\n s1y = s1y + X[i][1]\r\n if index[i] == 2:\r\n s2x = s2x + X[i][0]\r\n s2y = s2y + X[i][1]\r\n if index[i] == 3:\r\n s3x = s3x + X[i][0]\r\n s3y = s3y + X[i][1]\r\n \r\n s1x = s1x/c1\r\n s1y = s1y/c1\r\n s2x = s2x/c2\r\n s2y = s2y/c2\r\n s3x = s3x/c3\r\n s3y = s3y/c3\r\n \r\n Mu1 = [[s1x, s1y], [s2x, s2y], [s3x, s3y]]\r\n return (Mu1) \r\n\r\n#def plot_mu(Mu1):\r\n \r\n#Main Starts here\r\n\r\nX = [[5.9, 3.2], [4.6, 2.9], [6.2, 2.8], [4.7, 3.2], [5.5, 4.2], \r\n [5.0, 3.0], [4.9, 3.1], [6.7, 3.1], [5.1, 3.8], [6.0, 3.0]] #Set of Points to be clustered\r\n\r\nMu = [[6.2, 3.2], [6.6, 3.7], [6.5, 3.0]] #Initial Centroids, Last Term indicates class\r\n\r\ncolor_map = {1:'red', 2:'green', 3:'blue'} #Corresponding Colors of Class Labels\r\n\r\nj = 1\r\nfor i in range(0,2): \r\n index=assign(X, Mu)\r\n print(index)\r\n plot_points(index, X, Mu, j)\r\n j = j+1\r\n Mu = recompute_mu(index, X, Mu)\r\n plot_points(index, X, Mu, j)\r\n j = j+1","sub_path":"Task3_Kmeans.py","file_name":"Task3_Kmeans.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"150066079","text":"import graphene\nfrom django.contrib.contenttypes.models import ContentType\nfrom crm.schema.mutation import SngyMutation\nfrom synergycrm.exceptions import SngyException\nfrom ..models import Comment\nfrom notice.models import Notification\nfrom users.models import User\n\n\nclass CreateComments(SngyMutation):\n\tresult = graphene.Boolean()\n\n\tclass Input:\n\t\tname = graphene.String(required=True)\n\t\tobject_id = graphene.Int(required=True)\n\t\tcomment = graphene.String(required=True)\n\t\ttargets = graphene.List(of_type=graphene.Int)\n\n\tdef mutate_and_get_payload(self, info, name, object_id, comment, targets):\n\t\tif not '.' in name:\n\t\t\traise SngyException('Неправильное имя')\n\t\tapp_label, model = name.lower().split('.')\n\t\tcontent_type = ContentType(app_label=app_label, model=model)\n\t\tcontent_object = content_type.get_object_for_this_type(id=object_id)\n\t\tComment.objects.create(content_object=content_object, user=info.context.user, comment=comment)\n\n\t\tusers_id = [u.id for u in User.objects.all()]\n\t\tif not targets:\n\t\t\ttargets = list(set([c.user_id for c in Comment.objects.filter(content_type__app_label=app_label,\n\t\t\t content_type__model=model, object_id=object_id)]))\n\t\t\tif info.context.user.id in targets:\n\t\t\t\ttargets.remove(info.context.user.id)\n\t\tfor t in targets:\n\t\t\tif t in users_id:\n\t\t\t\ttext = 'Комментарий: ' + comment\n\t\t\t\tNotification.objects.create(purpose_id=t, created=info.context.user, text=text)\n\n\t\treturn CreateComments(result=True)\n\n\nclass Mutation(graphene.ObjectType):\n\tcreate_comments = CreateComments.Field()\n\n","sub_path":"backend_v3/comments/schema/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"542321799","text":"import numpy as np\n\n#Ones Counter\ndef Ones_Counter(GameBoard):\n\t#Ones Amount for Position(i,j)\n\tOAPOSij = [] \n\tfor p in range(0,len(Starting_Positions)):\n\t\ti = Starting_Positions[p][0]\n\t\tj = Starting_Positions[p][1]\n\t\tOAPOSij.append(np.sum(GameBoard[i][j:]) + np.sum(GameBoard.transpose()[j][i+1:]))\n\treturn(OAPOSij)\n\n#Permutations Generator\ndef CrossCombine(St_Pos_List):\n\t#Knot positions\t\n\tPos_Moves = [St_Pos_List]\n\tComb_Vec = [Pos_Moves]\n\tprint(\"CV: \",Comb_Vec)\n\t#Vertical\n\tfor i in range(St_Pos_List[0]+1, n):\n\t\tPos_Moves.append([i, St_Pos_List[1]])\n\t\tprint(\"PM: \",Pos_Moves)\n\t\t#Comb_Vec.extend([Pos_Moves])\n\t\t#print(\"CV: \",Comb_Vec)\n\t#Horizontal\n\tPos_Moves = [St_Pos_List]\n\tfor j in range(St_Pos_List[1]+1, n):\n\t\tPos_Moves.append([St_Pos_List[0],j])\n\t\tprint(\"PM: \",Pos_Moves)\n\t\t#Comb_Vec.extend([Pos_Moves])\n\t\t#print(\"CV: \",Comb_Vec)\n\t#Return Cross elements from Knot position\n\treturn(Pos_Moves)\n\t#return(Pos_Moves)\n\n#Algorithm Starting Positions\nStarting_Positions = []\n\n#GameBoard creation\nGameBoard = np.array([[1]*n]*n)\n\n#Algorithm Starting Positions Generator \nfor i in range(0,n):\n\tfor j in range(0,n):\n\t\tStarting_Positions.append([i,j])\n\n#All Possible Moves Amount for current GameBoard\nPMA = np.sum(Ones_Counter(GameBoard))\n\n","sub_path":"balls.py","file_name":"balls.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"61798828","text":"#from app.gui.write import write_dict\n#from app.gui.write import write_network\nimport subprocess\nimport networkx as nx\nimport json\nimport read\nimport write\n\npath = \"files/\"\ninfile = path\noutfile = path\nexecutable = \"./bin/all.out\"\n\n\n# 1. Get graph and write it\n# 2. Networkx to json\n# 3. Exec binary and algorithm\n# 4. Read result graph and display\n\n# 3. Exec algorithm\n#\n# ALGORITHMS\n# GRAPH\n#\n# 1: Graph operations\n# 2: Calculate if graph is bipartite & partitions\n# 3: Calculate euler path (Fleury's Algorithm)\n# 4: BFS expansion tree\n# 5: DFS expansion tree\n# 6: Kruskal minimun spanning forest\n# 7: Prim minimum spanning tree\n# \n# DIGRAPH \n#\n# 8: Shortest path (Dijkstra's algorithm)\n# 9: Shortest paths (Floyd-Warshall Algorithm)\n# \n# NETWORK\n#\n# 10: Maximun flow in a network (Ford-Fulkerson Algorithm)\n# 11: Primal algorithm\n# 12: Dual algorithm\n# 13: Simplex algorithm\n\n\ndef run_graph(g, algo):\n global infile\n global outfile\n\n infile = \"files/graph/input/g.json\"\n outfile = \"files/graph/output/g.json\"\n\n g.graph[\"weighted\"] = True\n g.graph[\"type\"] = \"graph\"\n #print(params)\n \n # All graph algorithms works same\n graph = write.write_dict(g)\n #print(graph)\n with open(infile, 'w') as out:\n json.dump(graph, out)\n\n bashCommand = f'{executable} {infile} {outfile} {algo}'\n print(f'executing {bashCommand}')\n\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, _ = process.communicate()\n print(output)\n\n gres = nx.MultiGraph()\n res, info, gres = read.read_graph(outfile,algo)\n print(\"RESULTS\")\n print(res)\n print(info)\n print(gres.nodes())\n print(gres.edges())\n return res, info, gres\n\n\n\ndef receive_graph(G):\n graph_data = nx.node_link_data(G)\n print(graph_data)\n\ndef run_digraph(d, algorithm, params):\n global infile\n global outfile\n\n infile = \"files/digraph/input/g.json\"\n outfile = \"files/digraph/output/g.json\"\n\n d.graph[\"weighted\"] = True\n d.graph[\"type\"] = \"digraph\"\n\n d_json = write.write_digraph(d)\n d_json[\"initial_tag\"] = params[0]\n print(\"param etros\")\n print(len(params))\n print(params)\n print(type(params))\n if algorithm == 8 and len(params) != 1:\n d_json[\"destination_tag\"] = params[1]\n print(d_json)\n\n with open(infile, 'w') as out:\n json.dump(d_json, out)\n\n bashCommand = f'{executable} {infile} {outfile} {algorithm}'\n print(f'executing {bashCommand}')\n\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, _ = process.communicate()\n print(output)\n\n #read result\n g_json = json.load(open(outfile))\n print(g_json)\n res, info, gres = read.read_digraph(outfile, algorithm, params)\n return res, info, gres\n\ndef run_network(n, algorithm, params):\n global infile\n global outfile\n\n infile = \"files/network/input/g.json\"\n outfile = \"files/network/output/g.json\"\n\n n.graph[\"weighted\"] = True\n n.graph[\"type\"]=\"network\"\n\n net = write.write_network(n)\n \n #ford fulkerson\n if len(params) != 0:\n net[\"target_flow\"] = params[0]\n \n print(net)\n\n with open(infile, 'w') as out:\n json.dump(net, out)\n\n bashCommand = f'{executable} {infile} {outfile} {algorithm}'\n print(f'executing {bashCommand}')\n\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, _ = process.communicate()\n print(output)\n\n #read result\n g_json = json.load(open(outfile))\n print(\"results read\")\n if len(params) != 0:\n g_json[\"target_flow\"] = params[0]\n print(g_json)\n res, info, gres = read.read_network(g_json, algorithm, params)\n print(\"from controller got results\")\n print(gres)\n print(res)\n print(info)\n return res, info, gres\n\n\n\n\n #return res\n \n\n\n \n #print(params)\n \n # All graph algorithms works same\n# graph = write.write_dict(g)\n #print(graph)\n# with open(infile, 'w') as out:\n# json.dump(graph, out)\n\n# bashCommand = f'{executable} {infile} {outfile} {algo}'\n# print(f'executing {bashCommand}')\n\n# process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n# output, _ = process.communicate()\n# print(output)\n\n #read result\n #g_json = json.load(open(outfile))\n #print(g_json)\n# gres = nx.MultiGraph()\n# return res, info, gres\n","sub_path":"app/gui/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"583503045","text":"#!/usr/bin/env python\n\n\"\"\"\n##########################################################################\n# * * * PySynth * * *\n# A very basic audio synthesizer in Python (www.python.org)\n#\n# Martin C. Doege, 2017-06-20 (mdoege@compuserve.com)\n##########################################################################\n# Based on a program by Tyler Eaves (tyler at tylereaves.com) found at\n# http://mail.python.org/pipermail/python-list/2000-August/041308.html\n##########################################################################\n\n# 'song' is a Python list (or tuple) in which the song is defined,\n# the format is [['note', value]]\n\n# Notes are 'a' through 'g' of course,\n# optionally with '#' or 'b' appended for sharps or flats.\n# Finally the octave number (defaults to octave 4 if not given).\n# An asterisk at the end makes the note a little louder (useful for the beat).\n# 'r' is a rest.\n\n# Note value is a number:\n# 1=Whole Note; 2=Half Note; 4=Quarter Note, etc.\n# Dotted notes can be written in two ways:\n# 1.33 = -2 = dotted half\n# 2.66 = -4 = dotted quarter\n# 5.33 = -8 = dotted eighth\n\"\"\"\n\nfrom __future__ import division\nfrom demosongs import *\nfrom mkfreq import getfreq\n\npitchhz, keynum = getfreq(pr = True)\n\n##########################################################################\n#### Main program starts below\n##########################################################################\n# Some parameters:\n\n# Beats (quarters) per minute\n# e.g. bpm = 95\n\n# Octave shift (neg. integer -> lower; pos. integer -> higher)\n# e.g. transpose = 0\n\n# Pause between notes as a fraction (0. = legato and e.g., 0.5 = staccato)\n# e.g. pause = 0.05\n\n# Volume boost for asterisk notes (1. = no boost)\n# e.g. boost = 1.2\n\n# Output file name\n#fn = 'pysynth_output.wav'\n##########################################################################\n\nimport wave, math, struct\nfrom mixfiles import mix_files\n\nfrom math import sin,cos\nfrom math import exp\nfrom math import pi\n\n\ndef make_wav(song,bpm=120,transpose=0,pause=.05,boost=1.1,repeat=0,fn=\"out.wav\", silent=False):\n\tf=wave.open(fn,'w')\n\n\tf.setnchannels(1)\n\tf.setsampwidth(2)\n\tf.setframerate(44100)\n\tf.setcomptype('NONE','Not Compressed')\n\n\tbpmfac = 120./bpm\n\n\tdef length(l):\n\t\treturn 88200./l*bpmfac\n\n\tdef waves2(hz,l):\n\t\ta=44100./hz\n\t\tb=float(l)/44100.*hz\n\t\treturn [a,round(b)]\n\n\tdef sixteenbit(x):\n\t\treturn struct.pack('h', round(32000*x))\n\n\tdef render2(a,b,vol,note):\n\t\tprint('a,b,vol,note:',a,b,vol,note)\n\t\tb2 = (1. - pause) * b\n\t\tl = waves2(a, b2)\n\t\tow = b''\n\t\tq = int(l[0] * l[1])\n\t\t# print('q',q)\n\n\t\thalfp = l[0] / 2.\n\t\tsp = 0\n\t\tfade = 1\n\n\t\tnotes = (\n\t\t\t# 'a', 'a#', 'b', 'c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#'\n\t\t\t# ('note',('frequencies'),('amplitude'),('phase'))\n\t\t\t('a',(886.658,1326.6,1772.5),(2150.2,171.1,35.6),(-80.525,-163.703,36.81)),\n\t\t\t('a#',(943.029,1886.2,2829.1),(2893.2,230.8,90),(170.928,-66.58,-123)),\n\n\t\t\t('b',(998.325,1995.5,2993.7),(1716.6,225.9,120.1),(-20.607,29.063,-41.767)),\n\n\t\t\t('c',(526.205,1051.5,1579.7,2103.2,2633.1),(1522.4,611.3,412.6,195.7,66.1),(-110.194,-122.091,-142,-160.32,-17.5336)),\n\t\t\t('c#',(558.039,1115.9,1674.5,2232.3,2786.4),(1086.9,438.5,243.4,69.7,54.7),(-101.194,-124.59,-39.76,175.142,149.439)),\n\n\t\t\t('d',(589.977,1176.9,1765.6,2360.1,2942.7),(809.6,646.93,177.55,104.92,56.93),(-86.14,60.59,49.29,50.76,-65.445)),\n\t\t\t('d#',(624.512,1248.8,1873.9,2494.2),(1108.1,467.8,219.7,85.6),(155.295,-141.48,169.528,23.577)),\n\n\t\t\t('e', (662.061,1324.3,1986.6), (1358.2,404.9,345.9),(-40.598,60.433,-5.727)),\n\n\t\t\t('f', (700.045,1399.5,2099), (2137.4,504.1,392.4),(16.463,144.473,54.86)),\n\t\t\t('f#', (747.028,1493.4,2239), (1876.7,482,216),(134.864,19.184,75.995)),\n\n\t\t\t('g', (786.977,1573.4,2360.2), (1649.2,228.8,184.2),(11.556,-561.7,-70.358)),\n\t\t\t('g#', (833.219,1666.3,2489.6), (1328.3,501.3,38.6),(131.78,91.116,120.36)),\n\n\t\t)\n\n\t\tproper_note_usued = False\n\n\t\tfor l in notes:\n\t\t\t# print('l',l)\n\t\t\t# l[0] is the note\n\t\t\tif(l[0] == note):\n\t\t\t\tprint('note',note)\n\t\t\t\tfrequencies_note = l[1]\n\t\t\t\tamplitudes_note = l[2]\n\t\t\t\tphases_note = l[3]\n\t\t\t\t# print('frequencies_note',frequencies_note)\n\t\t\t\t# print('amplitudes_note',amplitudes_note)\n\t\t\t\t# print('phases_note',phases_note)\n\t\t\t\t# number_harms = len(l[1])\n\t\t\t\t# for k in range(number_harms):\n\t\t\t\t# \tbreak\n\t\t\t\tif(len(l[1])!=len(l[2])):\n\t\t\t\t\t# something is wrong in spectrum\n\t\t\t\t\tprint(\"something is wrong in spectrum\")\n\t\t\t\t\texit()\n\t\t\t\telse:\n\t\t\t\t\tproper_note_usued = True\n\t\t\t\t\tprint(\"proper_note_usued = True\")\n\t\t\t\t\tfor x in range(q):\n\t\t\t\t\t\tfactor = 1 / b\n\t\t\t\t\t\t# sp = amplitudes_note[]\n\t\t\t\t\t\t# print('\"proper note\"')\n\t\t\t\t\t\t# ('note',('frequencies'),('amplitude'),('phase'))\n\t\t\t\t\t\t# for a,g,p in zip(amplitudes_note,frequencies_note,phases_note):\n\n\t\t\t\t\t\t# # todo:check this: https://www.audacity-forum.de/download/edgar/nyquist/nyquist-doc/manual/part5.html\n\t\t\t\t\t\t# for fr,am,ph in zip(frequencies_note,amplitudes_note,phases_note):\n\t\t\t\t\t\t# \t# print(\"fr,am,ph\",fr,am,ph)\n\t\t\t\t\t\t# \tsp = 0.01*am*sin( factor * fr * x *2*pi)\n\n\t\t\t\t\t\t# designed ('a', 2) to get 440Hz\n\t\t\t\t\t\tsp = sin( 2*pi*(a * x ) / b )\n\n\t\t\t\t\t\tow = ow + sixteenbit(.1 * vol * sp)\n\t\t\t\t\t\t# print('lol1')\n\t\t\t\t\tfill = max(int(ex_pos - curpos - q), 0)\n\t\t\t\t\tf.writeframesraw((ow) + (sixteenbit(0) * fill))\n\t\t\t\t\treturn q + fill\n\t\t# if(proper_note_usued ==False):\n\t\t# \tprint(\"if(proper_note_usued ==False):\")\n\t\t# \tfor x in range(q):\n\t\t# \t\t# print('lol3')\n\t\t# \t\t# factor = .0001\n\t\t# \t\tfactor = 1 / b * 2 * pi\n\t\t# \t\t# sp = amplitudes_note[]\n\t\t# \t\t# sp = .3 * sin(a * (1) * factor * x)\n\t\t# \t\t# sp = sp + (.3 / 4) * sin(a * (1 + 1) * factor * x)\n\t\t# \t\tsp=0\n\t\t# \t\t# sp = sp + .3*sin(a * (1 + 2) * factor * x)\n\t\t# \t\t# sp = sp + .1*sin(a * (1 + 3) * factor * x)\n\t\t# \t\t# sp = sp * (1 + .1* sin(0.001*x))\n #\n\t\t# \t\tow = ow + sixteenbit(.5 * vol * sp)\n\t\t# \tfill = max(int(ex_pos - curpos - q), 0)\n\t\t# \tf.writeframesraw((ow) + (sixteenbit(0) * fill))\n\n\t\treturn q + fill\n\n\t##########################################################################\n\t# Write to output file (in WAV format)\n\t##########################################################################\n\n\tif silent == False:\n\t\tprint(\"Writing to file\", fn)\n\tcurpos = 0\n\tex_pos = 0.\n\tfor rp in range(repeat+1):\n\t\tfor nn, x in enumerate(song):\n\t\t\tif not nn % 4 and silent == False:\n\t\t\t\tprint(\"[%u/%u]\\t\" % (nn+1,len(song)))\n\t\t\tif x[0]!='r':\n\t\t\t\tif x[0][-1] == '*':\n\t\t\t\t\tvol = boost\n\t\t\t\t\tnote = x[0][:-1]\n\t\t\t\telse:\n\t\t\t\t\tvol = 1.\n\t\t\t\t\tnote = x[0]\n\t\t\t\ttry:\n\t\t\t\t\tprint(\"note:\",note)\n\t\t\t\t\ta=pitchhz[note]\n\t\t\t\texcept:\n\n\t\t\t\t\ta=pitchhz[note + '4']\t# default to fourth octave\n\t\t\t\ta = a * 2**transpose\n\t\t\t\tif x[1] < 0:\n\t\t\t\t\tb=length(-2.*x[1]/3.)\n\t\t\t\telse:\n\t\t\t\t\tb=length(x[1])\n\t\t\t\tex_pos = ex_pos + b\n\t\t\t\tcurpos = curpos + render2(a,b,vol,note)\n\n\t\t\tif x[0]=='r':\n\t\t\t\tb=length(x[1])\n\t\t\t\tex_pos = ex_pos + b\n\t\t\t\tf.writeframesraw(sixteenbit(0)*int(b))\n\t\t\t\tcurpos = curpos + int(b)\n\n\tf.writeframes(b'')\n\tf.close()\n\tprint()\n\n##########################################################################\n# Synthesize demo songs\n##########################################################################\n\nif __name__ == '__main__':\n\tprint()\n\tprint(\"Creating Demo Songs... (this might take about a minute)\")\n\tprint()\n\n\t# LOL1\n\t# make_wav(lol1, fn = \"lol1.wav\")\n\n\t# # SONG 1\n\t# make_wav(song1, fn = \"pysynth_scale.wav\")\n #\n\t# # SONG 2\n\t# make_wav(song2, bpm = 95, boost = 1.2, fn = \"pysynth_anthem.wav\")\n\tmake_wav(song5, bpm = 120, boost = 1, fn = \"pysynth_anthem_.wav\")\n #\n\t# # SONG 3\n\t# make_wav(song3, bpm = 132/2, pause = 0., boost = 1.1, fn = \"pysynth_chopin.wav\")\n\n\t# SONG 4\n\t# right hand part\n\t# make_wav(song4_rh, bpm = 130, transpose = 1, pause = .1, boost = 1.15, repeat = 1, fn = \"pysynth_bach_rh.wav\")\n\t# left hand part\n\t# make_wav(song4_lh, bpm = 130, transpose = 1, pause = .1, boost = 1.15, repeat = 1, fn = \"pysynth_bach_lh.wav\")\n\t# mix both files together\n\t# mix_files(\"pysynth_bach_rh.wav\", \"pysynth_bach_lh.wav\", \"pysynth_bach.wav\")\n\n","sub_path":"pysynth_d_mod_single_sin_tone.py","file_name":"pysynth_d_mod_single_sin_tone.py","file_ext":"py","file_size_in_byte":7944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"209509574","text":"class Categorias:\n CategoriaModel = None\n CategoriaSquema = None\n def __init__(self,db,ma):\n class CategoriaModel(db.Model):\n __tablename__ = \"tbl_categorias\"\n\n categoria_id = db.Column(db.Integer, primary_key=True)\n nombre = db.Column(db.String(40), unique=True)\n productos = db.relationship('ProductosModel', backref='CategoriaModel')\n\n def __init__(self, nombre):\n self.nombre = nombre\n\n class CategoriaSquema(ma.Schema):\n class Meta:\n fields = ('categoria_id', 'nombre')\n\n self.CategoriaModel = CategoriaModel\n self.CategoriaSquema = CategoriaSquema","sub_path":"entidades/Categorias.py","file_name":"Categorias.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"11158918","text":"import cv2\nimport numpy as np\nimport face_recognition\nimport os\n\n# 설정\npath = 'ImageBasic'\nimages = []\nclassNames = []\nmyList = os.listdir(path)\n\n# 사진 디렉토리 내 이미지 경로 리스트 추출\nfor cl in myList:\n curImg = cv2.imread(f'{path}/{cl}')\n images.append(curImg)\n classNames.append(os.path.splitext(cl)[0])\nprint(classNames)\n\n\n# 각 사진별 인코딩 함수\ndef find_encodings(image_paths):\n encode_list = []\n\n for image_path in image_paths:\n inner_image = cv2.cvtColor(image_path, cv2.COLOR_BGR2RGB)\n encode = face_recognition.face_encodings(inner_image)[0]\n encode_list.append(encode)\n return encode_list\n\n\n# 인코딩 리스트 받기\nencodeListKnown = find_encodings(images)\nprint(f'Encoding Complete {len(encodeListKnown)}')\n\n# 캠 영상 받아서 처리\ncap = cv2.VideoCapture(0)\n\nwhile True:\n success, cap_img = cap.read()\n imgS = cv2.resize(cap_img, (0, 0), None, 0.25, 0.25)\n imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)\n\n # 캠 얼굴 인코딩\n faceCurFrame = face_recognition.face_locations(imgS)\n encodesCurFrame = face_recognition.face_encodings(imgS, faceCurFrame)\n\n # 캠 얼굴과 메모리상 인코딩 데이터간의 비교\n for encodeFace, faceLoc in zip(encodesCurFrame, faceCurFrame):\n matches = face_recognition.compare_faces(encodeListKnown, encodeFace)\n faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)\n\n matchIndex = np.argmin(faceDis)\n\n if matches[matchIndex]:\n name = classNames[matchIndex].upper()\n\n y1, x2, y2, x1 = faceLoc\n y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4\n cv2.rectangle(cap_img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n cv2.rectangle(cap_img, (x1, y2 - 35), (x2, y2),\n (0, 255, 0), cv2.FILLED)\n cv2.putText(cap_img, name, (x1 + 6, y2 - 6),\n cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)\n cv2.imshow('cam', cap_img)\n cv2.waitKey(1)\n","sub_path":"modules/face_recognition/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"52249087","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\n# Action1:求2+4+6+8+...+100的求和,用Python该如何写\n\n# 求从0开始到N的所有偶数之和,定义函数SumEven(N)\n\ndef SumEven(N):\n sumeven = 0\n for i in range(0,N+1,2):\n sumeven = sumeven + i\n return sumeven\n\nN = 100\nprint(SumEven(N)) \n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"L1-1.py","file_name":"L1-1.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"359143590","text":"#!/srv/home/wconnell/anaconda3/envs/lightning\n\n\"\"\"\nAuthor: Will Connell\nDate Initialized: 2020-09-27\nEmail: connell@keiserlab.org\n\nScript to preprocess data.\n\"\"\" \n\n\n###########################################################################################################################################\n# # # # # # # # # # # # # # # # # # \n# IMPORT MODULES \n# # # # # # # # # # # # # # # # # # \n###########################################################################################################################################\n\n\n# I/O\nimport os\nimport sys\nimport argparse\nfrom pathlib import Path\nimport joblib\nimport pyarrow.feather as feather\n\n# Data handling\nimport numpy as np\nimport pandas as pd\nfrom sklearn import model_selection\n\n# Chem\nfrom rdkit import DataStructs\nfrom rdkit.Chem import MolFromSmiles\nfrom rdkit.Chem import AllChem\n\n# Transforms\nfrom sklearn.preprocessing import StandardScaler\n\n\n###########################################################################################################################################\n# # # # # # # # # # # # # # # # # # \n# PRIMARY FUNCTIONS \n# # # # # # # # # # # # # # # # # # \n###########################################################################################################################################\n\n\ndef smiles_to_bits(smiles, nBits):\n mols = [MolFromSmiles(s) for s in smiles]\n fps = [AllChem.GetMorganFingerprintAsBitVect(m,2,nBits=nBits) for m in mols]\n np_fps = []\n for fp in fps:\n arr = np.zeros((1,), dtype=np.int8)\n DataStructs.ConvertToNumpyArray(fp, arr)\n np_fps.append(arr)\n df = pd.DataFrame(np_fps)\n return df\n\n\ndef process(out_path):\n np.random.seed(2299)\n ## Read data\n # Paths\n out_path = Path(out_path)\n out_path.mkdir(parents=True, exist_ok=True)\n ds_path = Path(\"../../film-gex-data/drug_screens/\")\n cm_path = Path(\"../../film-gex-data/cellular_models/\")\n # CCLE\n meta_ccle = pd.read_csv(cm_path.joinpath(\"sample_info.csv\"))\n ccle = pd.read_csv(cm_path.joinpath(\"CCLE_expression.csv\"), index_col=0)\n # L1000 genes\n genes = pd.read_csv(cm_path.joinpath(\"GSE70138_Broad_LINCS_gene_info_2017-03-06.txt.gz\"), sep=\"\\t\", index_col=0)\n # CTRP\n cp_ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.meta.per_compound.txt\"), sep=\"\\t\", index_col=0)\n cl_ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.meta.per_cell_line.txt\"), sep=\"\\t\", index_col=0)\n exp_ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.meta.per_experiment.txt\"), sep=\"\\t\", index_col=0)\n ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.data.per_cpd_post_qc.txt\") ,sep='\\t', index_col=0)\n\n ## Merge data\n data = ctrp.join(exp_ctrp['master_ccl_id']).drop_duplicates()\n data = data.merge(cl_ctrp['ccl_name'], left_on='master_ccl_id', right_index=True)\n data = data.merge(cp_ctrp[['broad_cpd_id', 'cpd_smiles']], left_on='master_cpd_id', right_index=True)\n data = data.merge(meta_ccle[['stripped_cell_line_name', 'DepMap_ID']], left_on='ccl_name', right_on='stripped_cell_line_name')\n\n ## Generate Fingerprints\n nBits=512\n cpd_data = data[['broad_cpd_id', 'cpd_smiles']].drop_duplicates()\n bits = smiles_to_bits(cpd_data['cpd_smiles'], nBits=nBits)\n bits.index = cpd_data['broad_cpd_id']\n bits.columns =[\"FP_{}\".format(i) for i in range(len(bits.columns))]\n\n ## Subset L1000 gene features by Entrez ID\n genes_lm = genes[genes['pr_is_lm']==1]\n ccle_cols = np.array([[gene[0], gene[1].strip(\"()\")] for gene in ccle.columns.str.split(\" \")])\n ccle.columns = ccle_cols[:,1]\n ccle = ccle[genes_lm.index.astype(str)]\n\n ## Merge bits and GEX\n data = data.merge(bits, left_on=\"broad_cpd_id\", right_index=True)\n data = data.merge(ccle, left_on=\"DepMap_ID\", right_index=True)\n print(\"{} unique compounds and {} unique cell lines comprising {} data points\".format(data['broad_cpd_id'].nunique(),\n data['stripped_cell_line_name'].nunique(),\n data.shape[0]))\n \n ## Generate folds\n target = \"cpd_avg_pv\"\n group = \"stripped_cell_line_name\"\n n_splits = 5\n gene_cols = ccle.columns.to_numpy()\n fp_cols = bits.columns.to_numpy()\n \n data[\"fold\"] = -1\n data = data.sample(frac=1).reset_index(drop=True)\n gkf = model_selection.GroupKFold(n_splits=n_splits)\n for fold, (train_idx, val_idx) in enumerate(gkf.split(X=data, y=data[target].to_numpy(), groups=data[group].to_numpy())):\n print(len(train_idx), len(val_idx))\n data.loc[val_idx, 'fold'] = fold\n \n ## Generate transforms & write\n for fold in range(0, n_splits):\n train = data[data['fold'] != fold]\n val = data[data['fold'] == fold]\n # Transform\n scaler = StandardScaler()\n train.loc[:,gene_cols] = scaler.fit_transform(train.loc[:,gene_cols])\n val.loc[:,gene_cols] = scaler.transform(val.loc[:,gene_cols])\n # Write\n train.reset_index(drop=True).to_feather(out_path.joinpath(\"train_fold_{}.feather\".format(fold)))\n val.reset_index(drop=True).to_feather(out_path.joinpath(\"val_fold_{}.feather\".format(fold)))\n # Testing set\n train.sample(frac=0.05).reset_index(drop=True).to_feather(out_path.joinpath(\"sub_train_fold_{}.feather\".format(fold)))\n val.sample(frac=0.05).reset_index(drop=True).to_feather(out_path.joinpath(\"sub_val_fold_{}.feather\".format(fold)))\n \n ## Write out\n joblib.dump(gene_cols, out_path.joinpath(\"gene_cols.pkl\"))\n joblib.dump(fp_cols, out_path.joinpath(\"fp_cols.pkl\"))\n data.sample(frac=0.05).reset_index(drop=True).to_feather(out_path.joinpath(\"data_sub.feather\"))\n data.reset_index(drop=True).to_feather(out_path.joinpath(\"data.feather\"))\n \n return \"Complete\"\n\n\n###########################################################################################################################################\n# # # # # # # # # # # # # # # # # # \n# CLI \n# # # # # # # # # # # # # # # # # # \n###########################################################################################################################################\n\ndef main():\n \"\"\"Parse Arguments\"\"\"\n desc = \"Script for preprocessing data for reproducibility.\"\n parser = argparse.ArgumentParser(description=desc,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n # positional\n parser.add_argument(\"path\", type=str,\n help=\"Directory to write processed data.\")\n args = parser.parse_args()\n \n return process(args.path)\n\n\nif __name__ == \"__main__\": # pragma: no cover\n sys.exit(main()) ","sub_path":"project/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"67036499","text":"import signal\nimport os\nimport datetime\nfrom logging import getLogger, Formatter, FileHandler, StreamHandler, DEBUG\n\ntoday = datetime.date.today()\ntoday = today.strftime(\"%Y%m%d\")\n\npath_to_log = \"{0}/log/{1}.log\".format(os.path.dirname(__file__), today)\nfmt = \"%(asctime)s %(name)s %(lineno)d [%(levelname)s][%(funcName)s] %(message)s\"\nlog_fmt = Formatter(fmt)\n\ndef get_logger(module_name):\n logger = getLogger(module_name)\n handler = StreamHandler()\n handler.setLevel(\"INFO\")\n handler.setFormatter(log_fmt)\n logger.addHandler(handler)\n\n handler = FileHandler(path_to_log, 'a')\n handler.setLevel(DEBUG)\n handler.setFormatter(log_fmt)\n logger.setLevel(DEBUG)\n logger.addHandler(handler)\n\n return logger\n\ndef ctrlc_handler(signal, frame):\n print(\"\\nKeyboardInterrupt\")\n exit()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"104902173","text":"import numpy as np\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd \nfrom keras.utils import np_utils\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.models import Sequential\nfrom sklearn.model_selection import train_test_split \nfrom keras.layers import Dense\nimport time\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n\n\ndata_set= pd.read_csv('/content/drive/MyDrive/BTP/kddcup.data.csv') \nx= data_set.iloc[:, 0:41].values \ny= data_set.iloc[:, 41].values \nd = {}\n# Counting data poihnts of each class\nfor val in y:\n if val in d:\n d[val] = d[val]+1\n else:\n d[val] = 1\n\nprint(d)\n\nlabel_encoder_x1= LabelEncoder() \nlabel_encoder_x2= LabelEncoder() \nlabel_encoder_x3= LabelEncoder() \n \nx[:, 1]= label_encoder_x1.fit_transform(x[:, 1]) \nx[:, 2]= label_encoder_x2.fit_transform(x[:, 2]) \nx[:, 3]= label_encoder_x3.fit_transform(x[:, 3]) \n\nattack_class = {'normal.': 'Normal', 'back.': 'DOS', 'smurf.':'DOS', 'neptune.':'DOS', 'pod.': 'DOS', 'teardrop.':'DOS', 'land.': 'DOS',\n 'multihop.':'R2L', 'ftp_write.': 'R2L', 'guess_passwd.': 'R2L', 'imap.': 'R2L', 'phf.': 'R2L', 'spy.':'R2L', 'warezmaster.':'R2L', 'warezclient.':'R2L',\n 'rootkit.':'U2R', 'loadmodule.':'U2R', 'buffer_overflow.': 'U2R', 'perl.': 'U2R',\n 'portsweep.':'PROBE', 'satan.':'PROBE', 'ipsweep.': 'PROBE', 'nmap.':'PROBE'}\n\n \nfor i in range(len(y)):\n y[i] = attack_class[y[i]]\n\nencoder = LabelEncoder()\nencoder.fit(y)\nencoded_Y = encoder.transform(y)\ndummy_y = np_utils.to_categorical(encoded_Y)\n\nx_train, x_test, y_train, y_test= train_test_split(x, dummy_y, test_size= 0.30, random_state=0)\n\n\n\n\nmodel = Sequential()\nmodel.add(Dense(12, input_dim=41, activation='relu'))\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(5, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\ny_train = np.asarray(y_train).astype('float32')\nx_train = np.asarray(x_train).astype('float32')\nprint(y_train[:10])\ntime_start = time.time()\nmodel.fit(x_train, y_train, epochs=10, batch_size=10)\ntime_end = time.time()\nprint(\"Training time: \", time_end - time_start)\n\ny_test = np.asarray(y_test).astype('float32')\nx_test = np.asarray(x_test).astype('float32')\n\n_, accuracy = model.evaluate(x_test, y_test)\nprint(\"Accuracy: \", accuracy)\n\n\ntime_start = time.time()\ny_pred = model.predict(x_test)\ntime_end = time.time()\nprint(\"Testing time: \", time_end - time_start)\n\ny_pred = np.argmax(y_pred, axis=1)\ny_test = np.argmax(y_test, axis=1)\n\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))","sub_path":"Phase 2/Code/DL Models/5 Classes/dl_5_3HiddenLayer.py","file_name":"dl_5_3HiddenLayer.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"359333906","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 31 22:57:29 2020\n\n@author: vismujum\n\"\"\"\n#import numpy as np\n\nimport pandas as pd\nimport numpy as np\nimport statsmodels.formula.api as sm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn import tree\n\n#pip install pandas\n#pip install numpy\ndef vif_cal(input_data, dependent_col):\n x_vars=input_data.drop([dependent_col], axis=1)\n xvar_names=x_vars.columns\n for i in range(0,xvar_names.shape[0]):\n y1=x_vars[xvar_names[i]]\n x1=x_vars[xvar_names.drop(xvar_names[i])]\n rsq=sm.ols(formula=\"y1~x1\", data=x_vars).fit().rsquared\n vif=round(1/(1-rsq),2)\n print (xvar_names[i], \" VIF = \" , vif)\n\n\n\ndef mktDetails_pTest():\n # Read CSV File to capture Marketing Details\n df = pd.read_csv('C:\\codeRepository\\machine-learning\\Marketing_Details.csv')\n \n # Replace all rows that has missing values\n df.dropna(inplace = True)\n \n # Information on attributes\n df.info()\n\n # Number of Data Entries - Marketing details\n df.shape\n df.head()\n\n df.rename(columns={'Visits':'visits','Unique Visitors':'unique_visitors' ,'Leads':'leads','MQL':'mql','Pipeline Count':'pipeline_count','Opportunity Accounts':'opportunity_accounts','MC Subscriptions':'mc_subscriptions','MC Net Adds':'mc_net_adds'},inplace=True)\n\n # Lets identify Less impactful variables when we are identifying total subscription (mc_subscriptions) are received based for a given campaign \n # Visits and Unique visitirs are independent variable and rest all are dependent variables.\n\n # visits, unique_visitors,leads',mql , pipeline_count,opportunity_accounts,mc_subscriptions, mc_net_adds'\n # Impactful variables to determin MC Net Additions \n model_mcNetAdds = sm.ols(formula='mc_net_adds~visits+unique_visitors+leads+mql+pipeline_count+opportunity_accounts+mc_subscriptions' , data=df)\n fitted_mcNetAdds = model_mcNetAdds.fit()\n fitted_mcNetAdds.summary()\n \n model_mcNetAdds = sm.ols(formula='mc_net_adds~unique_visitors+leads+mql+pipeline_count+opportunity_accounts+mc_subscriptions' , data=df)\n fitted_mcNetAdds = model_mcNetAdds.fit()\n fitted_mcNetAdds.summary()\n\n # Apart from Visits attribute all other paraemters are required to predict no. of Net Addition in Subsctions\n\n\n # Impactful variables to determin MC Subscriptions \n model_mcSubs = sm.ols(formula='mc_subscriptions~visits+unique_visitors+leads+mql+pipeline_count+opportunity_accounts' , data=df)\n fitted_mcSubs = model_mcSubs.fit()\n fitted_mcSubs.summary()\n # All paraemters are required to predict No of Subsctions achived by Given Campaign\n\n # Impactful variables to determin Pipeline Count\n model_pipeLine = sm.ols(formula='pipeline_count~visits+unique_visitors+leads+mql+opportunity_accounts' , data=df)\n fitted_pipeLine = model_pipeLine.fit()\n fitted_pipeLine.summary()\n # Visits , Leads and MQL play an important role in identifying Pipeline count for a marketing campaign\n \n # Impactful variables to determin Opportunity Accounts\n model_opporAcc = sm.ols(formula='opportunity_accounts~visits+unique_visitors+leads+mql' , data=df)\n fitted_opporAcc = model_opporAcc.fit()\n fitted_opporAcc.summary()\n # All parameters are required to predict Number of opportunity accounts that are acived from Marketing campaign\n \n # Impactful variables to determin MQL\n model_mql = sm.ols(formula='mql~visits+unique_visitors+leads' , data=df)\n fitted_mql = model_mql.fit()\n fitted_mql.summary()\n # All parameters are required to predict Number of opportunity accounts that are acived from Marketing campaign\n\n # Impactful variables to determin Leads\n model_leads = sm.ols(formula='mql~visits+unique_visitors' , data=df)\n fitted_leads = model_leads.fit()\n fitted_leads.summary()\n\ndef mktDetails_decisionTree():\n # Read CSV File to capture Marketing Details\n df = pd.read_csv('C:\\codeRepository\\machine-learning\\Marketing_Details.csv')\n \n # Replace all rows that has missing values\n df.dropna(inplace = True)\n # Information on attributes\n df.info()\n # Number of Data Entries - Marketing details\n df.shape\n df.head()\n df.rename(columns={'Visits':'visits','Unique Visitors':'unique_visitors' ,'Leads':'leads','MQL':'mql','Pipeline Count':'pipeline_count','Opportunity Accounts':'opportunity_accounts','MC Subscriptions':'mc_subscriptions','MC Net Adds':'mc_net_adds'},inplace=True)\n\n features = list(df.columns[0:6])\n x = df[features]\n y = df['mc_net_adds']\n clf = tree.DecisionTreeClassifier(max_depth=3)\n clf.fit(x,y)\n from IPython.display import Image\n from sklearn.externals.six import StringIO\n from sklearn import tree\n import pydotplus\n #import graphviz\n\n dot_data = StringIO()\n tree.export_graphviz(clf,out_file=dot_data,feature_names=features , filled=True,rounded=True, impurity=False)\n graph = pydotplus.graph_from_dot_data(dot_data.getvalue())\n\n Image(graph.create_png())\n\ndef mktDetails_VIFTest():\n df = pd.read_csv('C:\\codeRepository\\machine-learning\\Marketing_Details.csv')\n # Replace all rows that has missing values\n df.dropna(inplace = True)\n # Information on attributes\n df.info()\n # Number of Data Entries - Marketing details\n df.shape\n df.head()\n df.rename(columns={'Visits':'visits','Unique Visitors':'unique_visitors' ,'Leads':'leads','MQL':'mql','Pipeline Count':'pipeline_count','Opportunity Accounts':'opportunity_accounts','MC Subscriptions':'mc_subscriptions','MC Net Adds':'mc_net_adds'},inplace=True)\n df1 = df.drop('visits')\n vif_cal(df1 , \"mc_net_adds\")\n\n\n \nif __name__ == \"__main__\":\n print(\"Executing as main program\")\n print(\"Value of __name__ is: \", __name__)\n mktDetails_pTest()\n\n","sub_path":"python-files/marketing_details.py","file_name":"marketing_details.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"61453262","text":"#!/usr/bin/python\n# Copyright (c) 2017 Dell 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 http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT\n# LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS\n# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n\n\n\"\"\"Module for creation of the VxLAN Interface\"\"\"\nimport dn_base_ip_tool\nimport dn_base_br_tool\nimport ifindex_utils\nimport nas_os_if_utils as nas_if\nimport nas_vtep_config_obj as if_vtep_config\nimport copy\nimport cps_utils\nimport cps\n\nop_attr_name = 'dell-base-if-cmn/set-interface/input/operation'\n\nuse_linux_path = False\n\n''' Helper Methods '''\ndef _get_op_id(cps_obj):\n op_id_to_name_map = {1: 'create', 2: 'delete', 3: 'set'}\n op_id = None\n try:\n op_id = cps_obj.get_attr_data(op_attr_name)\n except ValueError:\n nas_if.log_err('No operation attribute in object')\n return None\n if not op_id in op_id_to_name_map:\n nas_if.log_err('Invalid operation type '+str(op_id))\n return None\n return op_id_to_name_map[op_id]\n\ndef __if_present(name):\n \"\"\"Method to check if the interface is present in linux\"\"\"\n if len(dn_base_ip_tool.get_if_details(name)) > 0:\n nas_if.log_info(\"Interface exists \" + str(name))\n return True\n nas_if.log_info(\"Interface doesn't exist \" + str(name))\n return False\n\ndef __create_vtep_if(vtep_name, vni, src_ip, addr_family):\n \"\"\"Method to create vtep interface in Linux\"\"\"\n if __if_present(vtep_name) is False and \\\n dn_base_ip_tool.create_vxlan_if(str(vtep_name), str(vni),\n str(src_ip), addr_family) is True:\n nas_if.log_info(\"Successfully created VTEP Interface \" + str(vtep_name))\n if_index = ifindex_utils.if_nametoindex(vtep_name)\n return True, if_index\n nas_if.log_err(\"Failed to create VTEP Interface \" + str(vtep_name))\n return False, None\n\ndef __delete_vtep_if(vtep_name):\n \"\"\"Method to delete vtep interface in Linux\"\"\"\n if __if_present(vtep_name) is True and \\\n dn_base_ip_tool.delete_if(vtep_name):\n nas_if.log_info(\"Successfully deleted VTEP Interface \" + str(vtep_name))\n return True\n nas_if.log_err(\"Failed to delete VTEP Interface \" + str(vtep_name))\n return False\n\ndef __add_remote_endpoints(vtep_name, remote_endpoints):\n \"\"\"Method to Add Remote Endpoints for the VxLAN in Linux\"\"\"\n rlist = {}\n for src_ip in remote_endpoints:\n remote_endpoint = remote_endpoints[src_ip]\n if dn_base_br_tool.add_learnt_mac_to_vtep_fdb(vtep_name, src_ip, \\\n remote_endpoint.addr_family, \\\n remote_endpoint.mac_addr) is False:\n nas_if.log_err(\"Failed to add remote endpoints \" + str(src_ip) + \" to VTEP Interface \" + str(vtep_name))\n return False, rlist\n rlist[src_ip] = remote_endpoints[src_ip]\n nas_if.log_info(\"Successfully added remote endpoint %s to Bridge Interface\" % (str(src_ip)))\n return True, rlist\n\ndef __remove_remote_endpoints(vtep_name, remote_endpoints):\n \"\"\"Method to Remove Remote Endpoints for the VxLAN in Linux\"\"\"\n rlist = {}\n for src_ip in remote_endpoints:\n remote_endpoint = remote_endpoints[src_ip]\n if dn_base_br_tool.del_learnt_mac_from_vtep_fdb(vtep_name, src_ip, \\\n remote_endpoint.addr_family, \\\n remote_endpoint.mac_addr) is False:\n nas_if.log_err(\"Failed to remove remote endpoints \" + str(src_ip) + \" to VTEP Interface \" + str(vtep_name))\n return False, rlist\n rlist[src_ip] = remote_endpoints[src_ip]\n nas_if.log_info(\"Successfully removed remote endpoint %s to Bridge Interface\" % (str(src_ip)))\n return True, rlist\n\n\n''' Create, Update and Delete '''\ndef update(cps_obj, params, cfg_obj):\n \"\"\"Method to set attributes for the VTEP in Linux\"\"\"\n _remote_endpoints = remote_endpoints = []\n member_op = if_vtep_config.get_member_op(cps_obj)\n ret, remote_endpoints = if_vtep_config.get_remote_endpoint_list(cps_obj)\n\n while True:\n if member_op == 'add':\n ret, _remote_endpoints = __add_remote_endpoints(cfg_obj.name, remote_endpoints)\n if ret is False:\n break\n else:\n ret, _remote_endpoints = __remove_remote_endpoints(cfg_obj.name, remote_endpoints)\n if ret is False:\n break\n return True\n\n nas_if.log_err(\"Update VTEP Failed, Rolling back\")\n if member_op == 'add':\n __remove_remote_endpoints(cfg_obj.name, _remote_endpoints)\n else:\n __add_remote_endpoints(cfg_obj.name, _remote_endpoints)\n return False\n\ndef create(cps_obj, params, cfg_obj):\n \"\"\"Method to create the VTEP in Linux\"\"\"\n _remote_endpoints = []\n while(True):\n ret, if_index = __create_vtep_if(cfg_obj.name, cfg_obj.vni, cfg_obj.ip, cfg_obj.addr_family)\n if ret is False:\n break\n ret, _remote_endpoints = __add_remote_endpoints(cfg_obj.name, cfg_obj.remote_endpoints)\n if ret is False:\n break\n return True\n\n nas_if.log_err(\"Create VTEP Failed, Rolling back\")\n __remove_remote_endpoints(cfg_obj.name, _remote_endpoints)\n __delete_vtep_if(cfg_obj.name)\n return False\n\ndef delete(cps_obj, params, cfg_obj):\n \"\"\"Method to delete the VTEP in Linux\"\"\"\n __remove_remote_endpoints(cfg_obj.name, cfg_obj.remote_endpoints)\n __delete_vtep_if(cfg_obj.name)\n return True\n\ndef _send_obj_to_base(cps_obj,op):\n nas_if.log_info('Sending vxlan object to base')\n in_obj = copy.deepcopy(cps_obj)\n in_obj.set_key(cps.key_from_name('target', 'dell-base-if-cmn/if/interfaces/interface'))\n obj = in_obj.get()\n if 'operation' in obj:\n del obj['operation']\n upd = (op, obj)\n _ret = cps_utils.CPSTransaction([upd]).commit()\n if not _ret:\n nas_if.log_err('BASE transaction for vxlan failed')\n return False\n return True\n\ndef handle_vtep_intf(cps_obj, params):\n \"\"\"Method to handle VTEP interface set, create or delete operations\"\"\"\n op = _get_op_id(cps_obj)\n if op is None:\n return False\n\n if not use_linux_path:\n return _send_obj_to_base(cps_obj,op)\n\n cfg_obj = if_vtep_config.create(cps_obj)\n if cfg_obj is None:\n return False\n\n if op == 'create' and create(cps_obj, params, cfg_obj) is True:\n return if_vtep_config.cache_add(cfg_obj.name, cfg_obj)\n if op == 'delete' and delete(cps_obj, params, cfg_obj) is True:\n return if_vtep_config.cache_del(cfg_obj.name)\n if op == 'set' and update(cps_obj, params, cfg_obj) is True:\n return if_vtep_config.cache_update(cfg_obj.name, cfg_obj)\n return False\n\n","sub_path":"scripts/lib/python/nas_if_vtep.py","file_name":"nas_if_vtep.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"627232930","text":"# -*- coding: utf-8 -*-\n__copyright__ = \"Copyright (c) 2014-2017 Agora.io, Inc.\"\n\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom src.AccessToken2 import *\n\n\ndef main():\n app_id = \"970CA35de60c44645bbae8a215061b33\"\n app_certificate = \"5CFd2fd1755d40ecb72977518be15d3b\"\n channel_name = \"7d72365eb983485397e3e3f9d460bdda\"\n uid = 2882341273\n account = \"2882341273\"\n chat_user_id = \"2882341273\"\n expiration_in_seconds = 3600\n\n rtc_service = ServiceRtc(channel_name, uid)\n rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expiration_in_seconds)\n\n rtm_service = ServiceRtm(account)\n rtm_service.add_privilege(ServiceRtm.kPrivilegeLogin, expiration_in_seconds)\n\n chat_service = ServiceChat(chat_user_id)\n chat_service.add_privilege(ServiceChat.kPrivilegeUser, expiration_in_seconds)\n\n token = AccessToken(app_id=app_id, app_certificate=app_certificate, expire=expiration_in_seconds)\n token.add_service(rtc_service)\n token.add_service(rtm_service)\n token.add_service(chat_service)\n\n print(\"Token for RTC, RTM and CHAT: {}\".format(token.build()))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DynamicKey/AgoraDynamicKey/python/sample/AccessToken2Sample.py","file_name":"AccessToken2Sample.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"287575495","text":"import json\nimport requests\n\n\ndef main():\n delete_all_people()\n post_people()\n get_people()\n\n\ndef url_for(endpoint, url='localhost', port=5000):\n return f'http://{url}:{port}/{endpoint}/'\n\n\ndef delete_all_people():\n r = requests.delete(url_for('people'))\n print(f\"'people' deleted, server response: {r.status_code}\")\n\n\ndef post_people():\n data = [\n {'firstname': 'John', 'lastname': 'Doe'},\n {'firstname': 'Mike', 'lastname': 'Green'},\n ]\n\n r = requests.post(\n url_for('people'),\n json.dumps(data),\n headers={'Content-Type': 'application/json'}\n )\n print(f\"'people' posted, server response: {r.status_code}\")\n\n\ndef get_people():\n r = requests.get(url_for('people'))\n print(f\"'people' downloaded, server response: {r.status_code}\")\n\n if r.status_code == 200:\n people = r.json()['_items']\n print(f'{len(people)} people:')\n [print(f\"\\t{person['firstname']}, {person['_id']}\") for person in people]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"my_code/clients/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"473930097","text":"#coding=utf-8\nimport requests\nimport threading\nimport re\nimport time\npage_s=input('请输入开始页码(1-92):')\npage_e=input('请输入结束页码(1-92):')\nwhile int(page_s)>int(page_e):#除了开始页码大于结束页码的输入都会被要求重新输入\n print('请重新输入页码')\n page_s = input('请输入开始页码(1-92):')\n page_e = input('请输入结束页码(1-92):')\n\ndef get_pic(page):\n\n url = 'http://jandan.net/ooxx/page-%s#comments' % page\n req=requests.get(url)\n try:\n txt=req.text\n id1 = re.findall(r'data-id=\"([0-9]*)\"', txt)\n id = list(set(id1)) # 去除重复\n data = [] #【1.id,2.图片连接,3.点赞数,4.反对数】\n for i in id:\n pic = re.findall(i+r'[\\s\\S]*?(.*)\\]\", txt)\n unlike = re.findall(r\"comment-unlike.*\" + i + \".*\\[(.*)\\]\", txt)\n data.append([i, pic[0][0], like[0], unlike[0]])\n except not req.ok:\n print(\"获取网页内容失败\")\n for each in data:\n try:\n html=requests.get('http://'+each[1],timeout=1)\n except not req.ok:\n print(\"获取图片内容失败\")\n with open(\"D:\\python study\\crossin\\Qimozuoye\\pic\\\\\"+each[0]+'赞'+each[2]+'反对'+each[3]+each[1][-4:],'wb') as f:\n f.write(html.content)\n print(each[0]+'下载完成')\n\nfor page in range(int(page_s),int(page_e)+1):\n #get_pic(page)\n t = threading.Thread(target=get_pic,args=(str(page),))\n t.start()\n","sub_path":"Qimozuoye/jiandan(beta).py","file_name":"jiandan(beta).py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"583436023","text":"import matplotlib.pyplot as plt\nfrom pylab import rcParams\nimport yfinance as yf\nimport datetime as dt\nimport warnings\nimport talib \nimport ta\n\nwarnings.filterwarnings(\"ignore\")\nyf.pdr_override()\n\n# input\nsymbol = str(input('Enter a ticker: '))\nnum_of_years = 1\nstart = dt.date.today() - dt.timedelta(days = int(365.25 * num_of_years))\nend = dt.date.today()\n\n# Read data \ndata = yf.download(symbol,start,end)\n\n# ## SMA and EMA\n#Simple Moving Average\ndata['SMA'] = talib.SMA(data['Adj Close'], timeperiod = 20)\n\n# Exponential Moving Average\ndata['EMA'] = talib.EMA(data['Adj Close'], timeperiod = 20)\n\n# Plot\nrcParams['figure.figsize'] = 15,10\ndata[['Adj Close','SMA','EMA']].plot(figsize=(15, 10))\nplt.xlabel('Dates')\nplt.ylabel('Close Price')\nplt.title(f'SMA vs. EMA for {symbol.upper()}')\nplt.show()\n\n\n# ## Bollinger Bands\n# Bollinger Bands\ndata['upper_band'], data['middle_band'], data['lower_band'] = talib.BBANDS(data['Adj Close'], timeperiod =20)\n\n# Plot\ndata[['Adj Close','upper_band','middle_band','lower_band']].plot(figsize=(15,10))\nplt.show()\n\n\n# ## MACD (Moving Average Convergence Divergence)\n# MACD\ndata['macd'], data['macdsignal'], data['macdhist'] = talib.MACD(data['Adj Close'], fastperiod=12, slowperiod=26, signalperiod=9)\ndata[['macd','macdsignal']].plot(figsize=(15,10))\nplt.xlabel('Dates')\nplt.ylabel('MACD')\nplt.title(f'Moving Average Convergence Divergence for {symbol.upper()}')\nplt.show()\n\n\n# ## RSI (Relative Strength Index)\n# RSI\ndata['RSI'] = talib.RSI(data['Adj Close'], timeperiod=14)\n# Plotting RSI\nfig,ax = plt.subplots(figsize=(15, 10))\nax.plot(data.index, data.RSI, label='RSI')\nax.fill_between(data.index, y1=30, y2=70, color = 'lightcoral', alpha=0.3)\nax.set_xlabel('Date')\nax.set_ylabel('RSI')\nax.set_title(f'Relative Strength Index for {symbol.upper()}')\nplt.show()\n\n\n# ## OBV (On Balance Volume)\n# OBV\ndata['OBV'] = talib.OBV(data['Adj Close'], data['Volume'])/10**6\n\nfig, (ax1, ax2) = plt.subplots(2)\nfig.suptitle(f'Close Price vs. On Balance Volume for {symbol.upper()}')\nax1.plot(data['Adj Close'])\nax1.set_ylabel('Close')\nax2.plot(data['OBV'])\nax2.set_ylabel('On Balance Volume (in millions)')\nplt.show()\n\n## CCI (Commodity Channel Index)\n# CCI\ncci = ta.trend.cci(data['High'], data['Low'], data['Close'], n=31, c=0.015)\nplt.subplots()\nrcParams['figure.figsize'] = 15,10\nplt.plot(cci)\nplt.axhline(y=0, color='r', linestyle='-')\nplt.xlabel('Dates')\nplt.ylabel('Commodity Channel Index')\nplt.title(f'Commodity Channel Index for {symbol.upper()}')\nplt.show()","sub_path":"Portfolio_Strategies/main_indicators_mult_graphs.py","file_name":"main_indicators_mult_graphs.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"56562137","text":"from django.shortcuts import render, redirect\nfrom myapp.item.models import Product\nfrom myapp.item.models import Ingredient\nfrom .forms import ProductQueryForm\nfrom .forms import ProductDetailForm\n\n# Create your views here.\ndef index(request):\n products = Product.objects.all()\n return render(request, 'index.html', {'products': products})\n\n\ndef show_ingredient(request):\n ingredients = Ingredient.objects.all()\n return render(request, 'ingredients.html', {'ingredients': ingredients})\n\n\n# 상품 목록 조회하기\ndef product_list(request):\n form = ProductQueryForm()\n\n if request.GET.get('skin_type') is not None:\n skin_type = request.GET.get('skin_type')\n # category = request.GET.get('category')\n page = request.GET.get('page')\n # exclude_in = request.GET.get('exclude_ingredient')\n # include_in = request.GET.get('include_ingredient')\n products, fitness = products_print(skin_type, 50, None, page, None, None)\n return render(request, 'product_list.html', {'form': form, 'products': products, 'fitness': fitness})\n\n return render(request, 'product_list.html', {'form': form})\n\n\n# 상품 상세 정보 조회하기\ndef product_detail(request, id):\n form = ProductDetailForm()\n\n product = Product.objects.get(id=id)\n base_url = \"https://grepp-programmers-challenges.s3.ap-northeast-2.amazonaws.com/2020-birdview/\"\n image_dir = \"image/\"\n thumbnail_dir = \"thumbnail/\"\n image_url = base_url + image_dir\n thumbnail_url = base_url + thumbnail_dir\n # 추천 상품 3개 보여주는 경우\n if request.GET.get('skin_type') is not None:\n skin_type = request.GET.get('skin_type')\n recommended, _ = products_print(skin_type, 3)\n return render(request, 'product_detail.html', {'product': product, 'image_url': image_url,\n 'thumbnail_url': thumbnail_url, 'recommended': recommended})\n\n return render(request, 'product_detail.html', {'form': form, 'product': product, 'image_url': image_url,\n 'thumbnail_url': thumbnail_url})\n\n\n# -------------inner function in product_list---------------\n# 보여질 50개의 제품\ndef products_print(skin_type, num_of_product=50, category=None, page=None, exclude_str=None, include_str=None):\n if page is None:\n page = 1\n else:\n page = int(page)\n\n products = set_products(category, exclude_str, include_str)\n id_score = {} # 제품 id에 현재 피부타임 점수를 key-value로 저장\n\n for product in products:\n score = 0\n ingredients = product.ingredients.split(',')\n for ingredient in ingredients:\n cur_ingre = Ingredient.objects.get(name=ingredient)\n if Ingredient.get_effect(cur_ingre, skin_type) == 'O':\n score += 1\n elif Ingredient.get_effect(cur_ingre, skin_type) == 'X':\n score -= 1\n id_score[product.id] = score\n\n\n # id_score을 score를 기준으로 정렬 후, 페이지에 맞는 요소들을 꺼내옴\n sorted_id_score = sorted(id_score.items(), reverse=True, key=lambda id_score:id_score[1])\n\n id_list = []\n ans_list = []\n for i in range(num_of_product*(page-1), num_of_product*page):\n if i < len(sorted_id_score):\n id_list.append(sorted_id_score[i][0])\n ans_list.append(Product.objects.filter(id=sorted_id_score[i][0]))\n\n return Product.objects.filter(id__in=id_list), ans_list\n\n\n# 상품 카테고리가 정해진 경우 해당 상품만 list로 반환\ndef set_products(category, exclude_str, include_str):\n products = []\n if category is None:\n products = Product.objects.all()\n else:\n products = Product.objects.filter(category=category)\n if exclude_str is not None:\n products = exclude_ingredient(products, exclude_str)\n if include_str is not None:\n products = include_ingredient(products, include_str)\n return products\n\n\n# 제외할 성분을 하나라도 갖는 경우 리스트에서 제외시킴\ndef exclude_ingredient(products, exclude_str):\n delete_list =[]\n exclude_list = exclude_str.split(',')\n for product in products:\n is_delete = False\n ingredients = product.ingredients.split(',')\n for ingredient in ingredients:\n if isdelete is True:\n break\n for exclude in exclude_lst:\n if ingredient == exclude:\n is_delete = True\n if isdelete is True:\n break\n if is_delete is True:\n delete_list.append(product.id)\n\n products = products.exclude(id__in=delete_list)\n\n return products\n\n\n# 포함할 성분을 하나라도 포함하지 않은 경우 리스트에서 제외시킴\ndef include_ingredient(products, include_str):\n delete_list = []\n include_list = include_str.split(',')\n for product in products:\n is_delete = False\n ingredients = product.ingredients.split(',')\n for ingredient in ingredients:\n is_include = False\n for include in include_list:\n if include == ingredient:\n is_include = True\n if is_include is True:\n break\n\n if is_include is False:\n is_delete = True\n if is_delete is True:\n delete_list.append(product.id)\n\n products = products.exclude(id__in=delete_list)\n return products\n\n\n# 재료명과 피부타입이 주어지면, 점수를 반환해줌\n# ingredient : Ingredient class\n# type : oily dry sensitive\ndef ingredient_effect(ingredient, skin_type):\n if ingredient.get_effect(skin_type) == 'O':\n return 1\n elif ingredient.get_effect(skin_type) == 'X':\n return -1\n else:\n return 0\n\n\n\n \n\n\n\n\n","sub_path":"django 리스팅/myapp/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"605970222","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2013 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nHandlers dealing with disks\n\"\"\"\n\nfrom ..manager import DisksFormatConvertor\nfrom ..validators.disks import NodeDisksValidator\nfrom nailgun.api.v1.handlers.base import BaseHandler\nfrom nailgun.api.v1.handlers.base import content\nfrom nailgun import objects\n\n\nclass NodeDisksHandler(BaseHandler):\n\n validator = NodeDisksValidator\n\n @content\n def GET(self, node_id):\n \"\"\":returns: JSONized node disks.\n\n :http: * 200 (OK)\n * 404 (node not found in db)\n \"\"\"\n from ..objects.volumes import VolumeObject\n\n node = self.get_object_or_404(objects.Node, node_id)\n node_volumes = VolumeObject.get_volumes(node)\n return DisksFormatConvertor.format_disks_to_simple(node_volumes)\n\n @content\n def PUT(self, node_id):\n \"\"\":returns: JSONized node disks.\n\n :http: * 200 (OK)\n * 400 (invalid disks data specified)\n * 404 (node not found in db)\n \"\"\"\n from ..objects.volumes import VolumeObject\n\n node = self.get_object_or_404(objects.Node, node_id)\n data = self.checked_data(\n self.validator.validate,\n node=node\n )\n\n if node.cluster:\n objects.Cluster.add_pending_changes(\n node.cluster,\n 'disks',\n node_id=node.id\n )\n\n volumes_data = DisksFormatConvertor.format_disks_to_full(node, data)\n VolumeObject.set_volumes(node, volumes_data)\n\n return DisksFormatConvertor.format_disks_to_simple(\n VolumeObject.get_volumes(node))\n\n\nclass NodeDefaultsDisksHandler(BaseHandler):\n\n @content\n def GET(self, node_id):\n \"\"\":returns: JSONized node disks.\n\n :http: * 200 (OK)\n * 404 (node or its attributes not found in db)\n \"\"\"\n node = self.get_object_or_404(objects.Node, node_id)\n if not node.attributes:\n raise self.http(404)\n\n volumes = DisksFormatConvertor.format_disks_to_simple(\n node.volume_manager.gen_volumes_info())\n\n return volumes\n\n\nclass NodeVolumesInformationHandler(BaseHandler):\n\n @content\n def GET(self, node_id):\n \"\"\":returns: JSONized volumes info for node.\n\n :http: * 200 (OK)\n * 404 (node not found in db)\n \"\"\"\n node = self.get_object_or_404(objects.Node, node_id)\n if node.cluster is None:\n raise self.http(404, 'Cannot calculate volumes info. '\n 'Please, add node to an environment.')\n volumes_info = DisksFormatConvertor.get_volumes_info(node)\n return volumes_info\n","sub_path":"nailgun/nailgun/extensions/volume_manager/handlers/disks.py","file_name":"disks.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"529493131","text":"import Logger.Logger as log\n\nclass Joint:\n \n #a list of x and y coordinates for the polygon, each odd is x and even is y\n polygon = []\n \n #if shapename is not \"custom\", *arg contains arguments for preset shapes\n #otherwise it contains list of coordinates for a custom polygon\n def __init__(self, shapeName, *arg):\n \n if shapeName == \"custom\":\n \n cnt = len(arg)\n #zero or uneven number of coordinate arguments\n if cnt == 0 or cnt % 2 != 0:\n log.UnexpectedArgumentCountForShape(cnt)\n \n \n ","sub_path":"Joint.py","file_name":"Joint.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"203753027","text":"import time\nimport requests\nimport datetime\nfrom urllib.parse import urlencode\nimport json\nimport pandas as pd\nfrom lovelyrita.config import API_KEY\n\nAPI_URL = \"https://maps.googleapis.com/maps/api/geocode/\"\n\nclass Geocoder(object):\n def __init__(self, geocodes=None, api_url=API_URL, api_key=API_KEY):\n if geocodes is None:\n geocodes = pd.DataFrame(columns=('lat', 'lng', 'place_id', 'timestamp'))\n geocodes.index.name='address'\n self.geocodes = geocodes\n self.api_url = API_URL\n self.api_key = API_KEY\n\n def geocode(self, address):\n \"\"\"\n Pull data from Google Maps API\n\n Parameters\n ----------\n address : str\n \"\"\"\n # check if query has already been run\n try:\n g = self.geocodes.loc[address]\n return g['lat'], g['lng'], g['place_id']\n except KeyError:\n pass\n\n query = {'address': address,\n 'key': self.api_key}\n url = self.api_url + 'json?' + urlencode(query)\n response = requests.get(url)\n if response.status_code == 404:\n raise Exception(\"404 error for {}\".format(url))\n\n content = response.json()\n if content['status'] != 'OK':\n raise Exception(\"Status not OK for {}\".format(url))\n\n place_id = content['results'][0]['place_id']\n lat = content['results'][0]['geometry']['location']['lat']\n lng = content['results'][0]['geometry']['location']['lng']\n timestamp = str(datetime.datetime.now())\n\n new_geocode = pd.Series({'place_id': place_id,\n 'lat': lat, 'lng': lng,\n 'timestamp': timestamp},\n name=address)\n self.geocodes = self.geocodes.append(new_geocode)\n return lat, lng, place_id\n \n @classmethod\n def load(cls, geocode_path):\n return cls(load_geocodes(geocode_path))\n def save(self, geocode_path):\n save_geocodes(self.geocodes, geocode_path)\n \ndef save_addresses(addresses, path):\n with open(path, 'w') as f:\n f.write('\\n'.join(addresses))\n\ndef load_addresses(path):\n with open(path, 'r') as f:\n addresses = f.read().split('\\n')\n return addresses\n\ndef save_geocodes(geocodes, path):\n geocodes.to_hdf(path, 'geocodes')\n\ndef load_geocodes(path):\n return pd.read_hdf(path)\n","sub_path":"lovelyrita/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"125956850","text":"\"\"\"\nCode that goes along with the Airflow located at:\nhttp://airflow.readthedocs.org/en/latest/tutorial.html\n\"\"\"\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom datetime import datetime, timedelta\nfrom airflow.models import Variable\nimport requests\nimport psycopg2\nfrom requests.auth import HTTPBasicAuth\nfrom star_count_helper.star_count_helper import star_count_helper\n\n \ndefault_args = {\n \"owner\": \"airflow\",\n \"depends_on_past\": False,\n \"start_date\": datetime(2021, 7, 16),\n \"schedule_interval\": None,\n \"email\": [\"airflow@airflow.com\"],\n \"email_on_failure\": False,\n \"email_on_retry\": False,\n \"retries\": 1,\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n\ndag = DAG(\"rohit\", default_args=default_args, schedule_interval=timedelta(1))\n\ngit_conf = {\n 'github_repo_name' : Variable.get(\"repo_name\"),\n 'username' : Variable.get(\"username\"),\n 'password' : Variable.get(\"password\")\n} \n#git_conf\n\ndb_conf = {\n 'db_name' : Variable.get(\"db_name\"),\n 'db_user' : Variable.get(\"db_user\"),\n 'db_password' : Variable.get(\"db_password\"),\n 'db_host' : Variable.get(\"db_host\"),\n 'db_port' : Variable.get(\"db_port\") \n}\n\n# execution starts here\ndef github_star_count():\n\n # API CALL\n r = star_count_helper.call_api(git_conf)\n #r = requests.get('https://api.github.com/repos/'+ github_repo_name, auth = HTTPBasicAuth(username, password)).json()\n #r = requests.get('https://api.github.com/repos/'+ github_repo_name).json()\n print(\"stargazers_count: \",r[\"stargazers_count\"])\n print(\"watchers_count: \",r[\"watchers_count\"])\n print(\"forks: \",r[\"forks\"])\n star_count = int(r[\"stargazers_count\"])\n\n # Ingest data to DB \n star_count_helper.insert_data(db_conf, git_conf.get('github_repo_name'), star_count)\n\n return (str,200)\n\n\nt1 = PythonOperator(\n task_id='GithubStarCount',\n python_callable= github_star_count,\n #op_kwargs = {\"x\" : \"Apache Airflow\"},\n dag=dag,\n)\n","sub_path":"dags/rohit.py","file_name":"rohit.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"392365957","text":"\nimport logging\nimport numpy as np\nimport torch\n\nfrom . import network as networks\nfrom .game import import_game\nfrom .search_tree import SearchTree\n\n\ndef create_network(network_type, board_size, num_blocks, base_chans):\n Net = getattr(networks, network_type)\n return Net(board_size=board_size,\n num_blocks=num_blocks,\n base_chans=base_chans)\n\n\nclass Policy:\n def __init__(self, config):\n \"\"\"Construct new policy\"\"\"\n self.gamelib = import_game(config['game'])\n self.device = torch.device(config['device'])\n if self.device.type == 'cuda':\n # enable cudnn auto-tuner\n torch.backends.cudnn.benchmark = True\n\n def initialize(self, config):\n \"\"\"Initialize policy for training\"\"\"\n self.net = create_network(config['network'],\n config['board_size'],\n config['num_blocks'],\n config['base_chans'])\n self.net.to(self.device)\n # don't train anything by default\n self.net.eval()\n # network params\n self.network_type = config['network']\n self.board_size = config['board_size']\n self.num_blocks = config['num_blocks']\n self.base_chans = config['base_chans']\n # search params\n self.simulations = config['simulations']\n self.search_batch_size = config['search_batch_size']\n self.exploration_coef = config['exploration_coef']\n self.exploration_depth = config['exploration_depth']\n self.exploration_noise_alpha = config['exploration_noise_alpha']\n self.exploration_noise_scale = config['exploration_noise_scale']\n self.exploration_temperature = config['exploration_temperature']\n\n @property\n def net(self):\n try:\n return self._net\n except AttributeError:\n raise RuntimeError('Policy must be initialized or loaded before use')\n\n @net.setter\n def net(self, net):\n self._net = net\n\n def reset(self, game):\n \"\"\"Start new game\n :returns: Initial node\n \"\"\"\n self.tree = SearchTree(self.gamelib,\n self.net,\n self.device,\n self.simulations,\n self.search_batch_size,\n self.exploration_coef,\n self.exploration_noise_alpha)\n self.tree.reset(game)\n return self.tree.root\n\n def load_state_dict(self, state):\n \"\"\"Load model state\n \"\"\"\n # load network architecture and params\n self.network_type = state['network_type']\n self.board_size = state['board_size']\n self.num_blocks = state['num_blocks']\n self.base_chans = state['base_chans']\n self.net = create_network(self.network_type,\n self.board_size,\n self.num_blocks,\n self.base_chans)\n self.net.load_state_dict(state['net'])\n self.net.to(self.device)\n\n # load search params\n self.simulations = state['simulations']\n self.search_batch_size = state['search_batch_size']\n self.exploration_coef = state['exploration_coef']\n self.exploration_depth = state['exploration_depth']\n self.exploration_noise_alpha = state['exploration_noise_alpha']\n self.exploration_noise_scale = state['exploration_noise_scale']\n self.exploration_temperature = state['exploration_temperature']\n\n def state_dict(self):\n \"\"\"Return model state\n \"\"\"\n return {\n 'net': self.net.state_dict(),\n 'network_type': self.network_type,\n 'board_size': self.board_size,\n 'num_blocks': self.num_blocks,\n 'base_chans': self.base_chans,\n 'simulations': self.simulations,\n 'search_batch_size': self.search_batch_size,\n 'exploration_coef': self.exploration_coef,\n 'exploration_depth': self.exploration_depth,\n 'exploration_noise_alpha': self.exploration_noise_alpha,\n 'exploration_noise_scale': self.exploration_noise_scale,\n 'exploration_temperature': self.exploration_temperature,\n }\n\n def choose_action(self, game, node, depth,\n temperature=None,\n noise_scale=None):\n \"\"\"Choose next move.\n can raise SearchTreeFull\n :param game: Current game state\n :returns: action - action id,\n node - child node following action,\n probs - 1d array of action probabilities\n \"\"\"\n assert not game.result()\n moves = game.legal_moves()\n if temperature is None:\n temperature = self.exploration_temperature\n if noise_scale is None:\n noise_scale = self.exploration_noise_scale\n if depth >= self.exploration_depth:\n temperature = 0.\n probs, metrics = self.tree.search(game, node, temperature, noise_scale)\n action = np.argmax(np.random.multinomial(1, probs))\n node = self.tree.get_child(node, action, moves)\n assert node\n return action, node, probs, metrics\n\n def make_action(self, game, node, action, moves):\n \"\"\"Update search tree with opponent action.\n can raise SearchTreeFull\n \"\"\"\n node = self.tree.move(game, node, action, moves)\n return node\n\n def tree_stats(self):\n return self.tree.stats()\n\n @classmethod\n def load(cls, config, path):\n \"\"\"Create policy and load weights from checkpoint\n Paths can be local filenames or s3://... URL's (please install\n smart_open library for S3 support).\n Loads tensors according to config['device']\n :param path: Either local or S3 path of policy file\n \"\"\"\n policy = cls(config)\n location = policy.device.type\n if location == 'cuda':\n location += f':{policy.device.index or 0}'\n if path.startswith('s3://'):\n # smart_open is optional dependency\n import smart_open\n with smart_open.smart_open(path) as f:\n state = torch.load(f, map_location=location)\n else:\n state = torch.load(path, map_location=location)\n policy.load_state_dict(state['policy'])\n policy.net.eval()\n return policy\n","sub_path":"azalea/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"202398515","text":"import random\n\nn = int(input(\"list length = \"))\na = int(input(\"min = \"))\nb = int(input(\"max = \"))\narr = []\narr2 = []\n\nfor i in range(n):\n arr.append(random.randint(a, b))\n\nprint(\"X = \"+str(arr))\n\nfor i in arr:\n if i > 0:\n arr2.append(i)\n arr2.append(0)\n else:\n arr2.append(i)\n\nprint(\"Y = \"+str(arr2))\n","sub_path":"hometask_8/+bonus/314.py","file_name":"314.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"410781000","text":"import requests\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom datetime import date\nimport talib\nimport mpl_finance as mpf\nimport seaborn as sns\nimport numpy as np\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nimport csv\nimport time\nplt.rcParams['font.family']='SimHei' # 顯示中文('SimHei' for MacOS)\nfrom sklearn import preprocessing\n\nglobal df1\n\n\ndef RSI(n, index):\n global df1\n mean_up=0\n mean_down=0\n data=df1.loc[index-(n-1):index+1,'漲跌價差']\n for i in data :\n if float(i)>0:\n mean_up+=float(i)\n else:\n mean_down-=float(i)\n mean_up/=n\n mean_down/=n\n if mean_down == 0 :\n return np.nan\n else :\n rs=mean_up/mean_down\n rsi=100*rs/(1+rs)\n return rsi\n\ndef KD(n, index, K_before, D_before):\n global df1\n Mtoday=float(df1.at[index,'收盤價'])\n data=df1.loc[index-(n-1):index+1,'收盤價']\n Max=float(max(data))\n Min=float(min(data))\n RSV=(Mtoday-Min)/(Max-Min) *100\n K=K_before*0.6667+RSV*0.3333\n D=D_before*0.6667+K*0.3333\n return (K, D)\n \ndef BIAS(n, index):\n global df1\n Mtoday=float(df1.at[index,'收盤價'])\n data=np.asarray(df1.loc[index-(n-1):index+1,'收盤價'].astype(float))\n Mean=np.mean(data)\n ans=100*(Mtoday-Mean)/Mean\n return ans\ndef WMR(n, index):\n global df1\n Mtoday=float(df1.at[index,'收盤價'])\n H=np.asarray(df1.loc[index-(n-1):index+1,'最高價'].astype(float))\n L=np.asarray(df1.loc[index-(n-1):index+1,'最低價'].astype(float))\n Hn=np.max(H)\n Ln=np.min(L)\n ans=100*(Hn-Mtoday)/(Hn-Ln)\n return ans\n\ndef EMA(index, N):\n global df1\n S='EMA_'+str(N)\n ans=((float(df1.at[index,'收盤價'])*2)+(N-1)*(float(df1.at[index-1,S])))/(N+1)\n return ans\n\ndef MACD(index, N, dif):\n global df1\n ans=((dif*2)+(N-1)*(float(df1.at[index-1,'MACD'])))/(N+1)\n return ans\n'''\nPSY = 有上漲的天數( N日內 ) / N * 100\n上漲天數係指週期天數( N日 )內,股價上漲的天數和由於其一定在 0 ~ 100之間移動\n故研判PSY的數值當線路介於 20 ~ 80之間移動時為盤整狀態;\n當數值低於10時則可能出現反彈機會,應注意買點的出現;\n數值若高於90以上時,則可能短線過熱,市場心理過於超買,極可能出現回檔的現象。\nPSY的應用\n1. 一般心理線介於25%~75%是合理變動範圍。 \n2. 超過75%或低於25%,就有買超或賣超現象,股價回跌或回升機會增加,此時可準備賣出或買進。\n在大多頭或大空頭市場初期,可將超買、超賣點調整至83%、17%值到行情尾聲,再調回70%、25%。\n3. 當行情出現低於10%或高於90%時;是真正的超賣和超買現象,\n行情反轉的機會相對提高,此時為賣出和買進時機\n'''\ndef psy(index, N):\n global df1\n riseday=0\n for i in range(index-N,index):\n isrise=(float(df1.at[i,'漲跌價差']))\n if (isrise>0):\n riseday+=1\n ans=riseday/N*100\n return ans\n'''\nMTM=C-Cn\n其中:C為當日收市價,Cn為N日前收市價,N為設定參數,一般選設10日,亦可在6日至14日之間選擇。\n(1)一般情況下,MTM由上向下跌破中心線時為賣出時機,相反,MTM由下向上突破中心線時為買進時機。\n(2)因選設10日移動平均線情況下,當MTM在中心線以上,由上向下跌穿平均為賣出訊號,反之,當MTM在中心線以下,由下向上突破平均線為買入訊號。\n(3)股價在上漲行情中創新高點,而MTM未能配合上升,出現背馳現象,意味上漲動力減弱,此時應關註行情,慎防股價反轉下跌。\n(4)股價在下跌行情中走出新低點,而MTM未能配合下降,出現背馳,該情況意味下跌動力減弱,此時應註意逢低承接。\n(5)若股價與MTM在低位同步上升,顯示短期將有反彈行情;若股價與MTM在高位同步下降,則顯示短期可能出現股價回落。\n'''\ndef MTM(index, N):\n global df1\n C=(float(df1.at[index,'收盤價']))\n Cn=(float(df1.at[index-N,'收盤價']))\n return C - Cn\n \n\ndef SAR(index, n_day, AF,SAR_col_name):\n global df1\n\n if index < n_day: # for init\n return 0\n flut_cumu = sum(df1.loc[index-n_day:index-1,'漲跌價差'])\n \n # 算區間極值\n if flut_cumu >= 0: # 上漲\n extrema = float(max(df1.loc[index-n_day:index-1, \"最高價\"]))\n else: # 下跌\n extrema = float(min(df1.loc[index-n_day:index-1, \"最低價\"]))\n \n # 更新 AF值\n if index > n_day+1:\n # 上次是上漲且上漲創新高 或 上次是下跌且下跌創新低\n if (SAR.last_up_down == 0 and flut_cumu < 0 and SAR.last_extrema > extrema) or (SAR.last_up_down == 1 and flut_cumu >= 0 and SAR.last_extrema < extrema):\n AF = 0.2 if AF>=0.2 else AF+0.02 \n \n # 保存漲跌資訊到下一次\n if flut_cumu >= 0: # 上漲\n SAR.last_up_down = 1\n else: # 下跌\n SAR.last_up_down= 0\n \n # 計算 SAR\n if index == n_day: # for init\n SAR.last_extrema = extrema\n return extrema\n else:\n last_SAR = float(df1.loc[index-1, SAR_col_name])\n return last_SAR+AF*(extrema - last_SAR)\n'''\n一. 先計算股票價位的變動值;分別以DM+ 或 DM- 來代表其上漲或下跌的趨向變動值DM:\n\n DM+ = 本日最高價 - 一日前最高價 ( 上漲的趨向變動值 )\n DM- = 本日最低價 - 一日前最低價 ( 下跌的趨向變動值 )\n\n二. 無論其DM+ 或DM- 接取其絕對值較大之數值為當日之趨向變動值。由此原則可得此趨向之變動值在於求取每日價格波動幅度之增減的真正幅度。\n\n三. 找出TR,該變動值需比較下列三種差價的『絕對值』後,取其中最大者為本日之TR。\n\n A = 今日最高價 - 今日最低價\n B = 今日最高價 - 一日前收盤價\n C = 今日最低價 - 一日前收盤價\n \n\n四. 計算DI:\n\n +DI = (DM+) 14日平均 / (TR) 14日平均 *100\n -DI = (DM-) 14日平均 / (TR) 14日平均 *100\n 求出其14日移動平均值\n 第一日:採用+DI及-DI的14日移動平均值\n 第二日:開始以平滑移動方式修正:\n 本日的(+DI)十日平均 = 一日前(DI+)值 * 13/14 + 本日(+DI) * 1/14\n 本日的(-DI)十日平均 = 一日前(DI-)值 * 13/14 + 本日(-DI) * 1/14\n\n五. ADX計算方式:\n ADX= [(+DI)- (-DI)] / [(+DI)+(-DI)] *100\n 求出ADX其10日移動平均值\n 第一日:直接採用ADX的14日移動平均值\n 第二日:開始以平滑移動方式修正:\n ADX= (一日前的ADX * 13/14) + (本日的ADX * 1/14)\n'''\n\ndef DM(index):\n global df1\n if index==0:\n return (0,0)\n DMP = float(df1.at[index, \"最高價\"]) - float(df1.at[index-1, \"最高價\"])\n DMN = float(df1.at[index, \"最低價\"]) - float(df1.at[index-1, \"最低價\"])\n return (DMP, DMN)\n\ndef TR(index):\n global df1\n if index==0:\n return 0\n A = abs(float(df1.at[index, \"最高價\"]) - float(df1.at[index, \"最低價\"]))\n B = abs(float(df1.at[index, \"最高價\"]) - float(df1.at[index-1, \"收盤價\"]))\n C = abs(float(df1.at[index, \"最低價\"]) - float(df1.at[index-1, \"收盤價\"]))\n \n return max([A, B, C])\n\ndef DI(index, n_day):\n global df1\n if index < n_day:\n return (0, 0)\n elif index == n_day:\n PDI = float(sum(df1.loc[index-n_day:index-1, \"DM+(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n NDI = float(sum(df1.loc[index-n_day:index-1, \"DM-(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n \n return (PDI, NDI)\n else:\n PDI = float(sum(df1.loc[index-n_day:index-1, \"DM+(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n NDI = float(sum(df1.loc[index-n_day:index-1, \"DM-(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n \n return (float(df1.loc[index-1, \"+DI(DMI)\"])*(1-1/n_day) + PDI/n_day, float(df1.loc[index-1, \"-DI(DMI)\"])*(1-1/n_day) + NDI/n_day)\n \n \ndef ADX(index, n_day):\n global df1\n # ADX= [(+DI)- (-DI)] / [(+DI)+(-DI)] *100\n \n if index < n_day:\n return 0\n elif index == n_day:\n PDI = float(df1.loc[index, \"+DI(DMI)\"])\n NDI = float(df1.loc[index, \"-DI(DMI)\"])\n ADX = (PDI - NDI) / (PDI + NDI) * 100\n return ADX\n else:\n PDI = float(df1.loc[index, \"+DI(DMI)\"])\n NDI = float(df1.loc[index, \"-DI(DMI)\"])\n ADX = float(df1.loc[index-1, \"ADX(DMI)\"])*(1-1/n_day) + ((PDI - NDI)/(PDI + NDI)*100)/n_day\n \n return ADX\n'''\n1. 先求出昨日行情的CDP值(亦稱均價)\n CDP = (最高價 + 最低價 + 2*收盤價) /4\n \n2. 再分別計算昨天行情得最高值(AH)、近高值(NH)、近低值(NL)及最低值(AL)\n AH = CDP + (最高價 - 最低價)\n NH = 2*CDP - 最低價\n NL = 2*CDP - 最高價\n AL = CDP - (最高價 - 最低價\n \n3. 以最高值(AH)附近開盤應追價買進\n 盤中高於近高值(NH)時可以賣出\n 盤中低於近低值(NL)時可��買進\n 以最低值(AL)附近開盤應追價賣出\n CDP為當天軋平的超短線操作法,務必當天沖銷(利用融資融卷)軋平。若當天盤中無法達到所設定理想的買賣價位時,亦應以當日的收盤價軋平 \n\n'''\n\ndef CDP(index):\n global df1\n ans = (float(df1.at[index-1,'最高價']) + float(df1.at[index-1,'最低價']) + (float(df1.at[index-1,'收盤價'])*2)) / 4\n return ans\n\ndef KDX(index):\n global df1\n ky1 = float(df1.at[index-1,'K'])\n ky2 = float(df1.at[index,'K'])\n dy1 = float(df1.at[index-1,'D'])\n dy2 = float(df1.at[index,'D'])\n \n k1 = ky2 - ky1\n b1 = ky1 - k1\n k2 = dy2 - dy1\n b2 = dy1 - k2\n \n x = (b2 - b1) / (k1 - k2)\n y = (k1*x) + b1\n return y\n \ndef stock_index_generator(df_in,stockcode):\n global df1\n df1 = df_in\n \n for index, row in df1.iteritems():\n indexNames = df1[df1[index] == '--'].index\n df1 = df1.drop(indexNames)\n df1 = df1.reset_index(drop=True)\n df1.sort_index(inplace=True)\n #RSI_6\n N_day=6\n rsi=RSI(N_day,N_day-1)\n df1.loc[N_day-1,'RSI_6']=rsi\n for i in range(N_day,len(df1)):\n rsi=RSI(N_day,i)\n df1.loc[i,'RSI_6']=rsi\n #RSI_12\n N_day=12\n rsi=RSI(N_day,N_day-1)\n df1.loc[N_day-1,'RSI_12']=rsi\n for i in range(N_day,len(df1)):\n rsi=RSI(N_day,i)\n df1.loc[i,'RSI_12']=rsi\n\n for i in range(len(df1)-1):\n dif=float(df1.loc[i+1,'最高價'])-float(df1.loc[i,'最高價'])\n if dif > 0:\n df1.loc[i,'Ans']=1\n else:\n df1.loc[i,'Ans']=-1\n #KD_5\n N_day=5\n K,D=KD(N_day,N_day-1,50,50)\n df1.loc[N_day-1,'K']=K\n df1.loc[N_day-1,'D']=D\n for i in range(N_day,len(df1)):\n K,D=KD(N_day,i,K,D)\n df1.loc[i,'K']=K\n df1.loc[i,'D']=D\n for i in range(12,len(df1)):\n Yesterday=df1.loc[i-1,'RSI_12']-df1.loc[i-1,'RSI_6']\n Today =df1.loc[i,'RSI_12']-df1.loc[i,'RSI_6']\n Product = Yesterday*Today\n if Product < 0 or (abs(Product-0)<0.0001) :\n if Yesterday > 0:\n df1.loc[i,'RSI_DIF']=1\n else :\n df1.loc[i,'RSI_DIF']=-1\n else :\n df1.loc[i,'RSI_DIF']=0\n #BIAS\n\n N_day=6\n bias=BIAS(N_day,N_day-1)\n df1.loc[N_day-1,'BIAS']=bias\n for i in range(N_day,len(df1)):\n bias=BIAS(N_day,i)\n df1.loc[i,'BIAS']=bias\n #WMR\n\n N_day=6\n wmr=WMR(N_day,N_day-1)\n df1.loc[N_day-1,'WMR']=wmr\n for i in range(N_day,len(df1)):\n wmr=WMR(N_day,i)\n df1.loc[i,'WMR']=wmr\n #MACD\n\n df1.loc[0,'EMA_12']=float(df1.at[0,'收盤價'])\n df1.loc[0,'EMA_26']=float(df1.at[0,'收盤價'])\n df1.loc[0,'MACD']=0\n for i in range(1,len(df1)):\n A=EMA(i,12)\n B=EMA(i,26)\n dif=A-B\n macd=MACD(i,14,dif)\n df1.loc[i,'EMA_12']=A\n df1.loc[i,'EMA_26']=B\n df1.loc[i,'MACD']=macd\n #psy心理線\n \n #psy_6\n for i in range(0,6):\n df1.loc[i,'psy_6']=0\n for i in range(6,len(df1)):\n df1.loc[i,'psy_6']=psy(i,6)\n #MTM動量指標\n \n #MTM_6\n for i in range(0,6):\n df1.loc[i,'MTM_6']=0\n for i in range(6,len(df1)):\n df1.loc[i,'MTM_6']=MTM(i,6)\n # SAR 停損點轉向操作系統\n '''\n inti:\n 上升波段:SAR 設定於近期n日中最高價\n 下跌波段:SAR 設定於近期n日中最低價\n\n SAR:\n 當天SAR=前一天SAR+AF*(區間極值–前一天SAR)\n \n AF:\n 則是SAR分析指標的特有產物,叫作加速因子,起始值為0.02,\n 當趨勢正在走上漲(下跌)波段的時候,只要最高(低)價再創新高(低),AF就增加0.02,而最高限制為0.2。\n \n 區間極值:\n 上漲的波段當中,取最高價當作區間極值;相反的,在下跌波段當中,則取最低價當作區間極值。\n '''\n\n AF = 0.02\n n_day=6\n SAR_col_name = 'SAR_%d' % n_day\n\n\n for i in range(0,len(df1)):\n df1.loc[i, SAR_col_name] = SAR(i,n_day,AF,SAR_col_name)\n\n # DMI 趨向指標\n \n\n n_day = 14\n\n\n for i in range(0,len(df1)):\n (df1.loc[i, \"DM+(DMI)\"], df1.loc[i, \"DM-(DMI)\"]) = DM(i)\n df1.loc[i, \"TR(DMI)\"] = TR(i)\n (df1.loc[i, \"+DI(DMI)\"], df1.loc[i, \"-DI(DMI)\"]) = DI(i, n_day)\n df1.loc[i, \"ADX(DMI)\"] = ADX(i, n_day)\n\n #CDP逆勢操作系統\n\n\n df1.loc[0,'CDP']=np.nan\n df1.loc[0,'AH']=np.nan\n df1.loc[0,'NH']=np.nan\n df1.loc[0,'NL']=np.nan\n df1.loc[0,'AL']=np.nan\n\n for i in range(1,len(df1)):\n cdp = CDP(i)\n df1.loc[i,'CDP'] = cdp\n ah = float(df1.at[i,'CDP']) + ( float(df1.at[i-1,'最高價']) - float(df1.at[i-1,'最低價']) )\n nh = ( float(df1.at[i,'CDP']) * 2 ) - float(df1.at[i-1,'最低價'])\n nl = ( float(df1.at[i,'CDP']) * 2 ) - float(df1.at[i-1,'最高價'])\n al = float(df1.at[i,'CDP']) - ( float(df1.at[i-1,'最高價']) - float(df1.at[i-1,'最低價']) )\n\n df1.loc[i,'AH'] = ah\n df1.loc[i,'NH'] = nh\n df1.loc[i,'NL'] = nl\n df1.loc[i,'AL'] = al\n \n st = float(df1.at[i,'開盤價'])\n \n if st >= ah :\n df1.loc[i,'Trend'] = 6\n elif st >= nh :\n df1.loc[i,'Trend'] = 5\n elif st >= cdp :\n df1.loc[i,'Trend'] = 4\n elif st >= nl :\n df1.loc[i,'Trend'] = 3\n elif st >= al :\n df1.loc[i,'Trend'] = 2\n else :\n df1.loc[i,'Trend'] = 1\n \n '''\n 6 = 大漲\n 5 = 漲\n 4 = 偏漲\n 3 = 偏跌\n 2 = 跌\n 1 = 大跌\n '''\n \n N_day=5\n\n for i in range(N_day,len(df1)):\n Yesterday=df1.loc[i-1,'D']-df1.loc[i-1,'K']\n Today =df1.loc[i,'D']-df1.loc[i,'K']\n Product = Yesterday*Today\n\n if Product < 0 or (abs(Product-0)<0.0001) :\n if Yesterday > 0:\n a=1\n else :\n a=-1\n else :\n a=0 \n df1=df1.fillna(0)\n df1=df1.drop(range(14))\n df1=df1.reset_index(drop=True)\n\n df1.to_json('./stock_data_index/' + stockcode + '_index.json')\n return df1\n\n#Normalize\ndef Normalize_pd(df1):\n df2=df1[['RSI_6','RSI_12','K','D','BIAS','WMR','EMA_12','EMA_26','MACD','psy_6','MTM_6','SAR_6','DM+(DMI)','DM-(DMI)','TR(DMI)','+DI(DMI)','-DI(DMI)','ADX(DMI)','Trend']].copy()\n\n def min_max(inputCol,df2):\n arr=np.array( [float(i) for i in df2[inputCol]])\n arr = np.reshape(arr, (-1,1))\n min_max_scaler=preprocessing.MinMaxScaler()\n a=min_max_scaler.fit_transform(arr) \n min_maxdf[inputCol]=np.reshape(a*255, (-1)).tolist()\n\n min_maxdf = pd.DataFrame()\n for i in ['RSI_6','RSI_12','K','D','BIAS','WMR','EMA_12','EMA_26','MACD','psy_6','MTM_6','SAR_6','DM+(DMI)','DM-(DMI)','TR(DMI)','+DI(DMI)','-DI(DMI)','ADX(DMI)','Trend']:\n min_max(i,df2)\n return min_maxdf\n\ndef Normalize_pd_V2(new_idx):\n\n def min_max2(inputCol,new_idx):\n arr=np.array( [float(i) for i in new_idx[inputCol]])\n arr = np.reshape(arr, (-1,1))\n min_max_scaler=preprocessing.MinMaxScaler()\n a=min_max_scaler.fit_transform(arr) \n min_maxdf2[inputCol]=np.reshape(a*255, (-1)).tolist()\n min_maxdf2 = pd.DataFrame()\n for i in ['RSI','KD','BIAS','WMR','MACD','PSY','SAR','CDP','+DI(DMI)','-DI(DMI)','ADX(DMI)']:\n min_max2(i,new_idx)\n return min_maxdf2\n\n\ndef stock_index_generator_V2(df_in,stockcode):\n df2=df_in[['RSI_6','RSI_12','K','D','BIAS','WMR','EMA_12','EMA_26','MACD','psy_6','MTM_6','SAR_6','DM+(DMI)','DM-(DMI)','TR(DMI)','+DI(DMI)','-DI(DMI)','ADX(DMI)','Trend']].copy()\n new_idx=pd.DataFrame()\n #rsi\n rsi6=np.array([float(i) for i in df2['RSI_6']])\n rsi12=np.array([float(i) for i in df2['RSI_12']])\n rst=np.array(0)\n for i in range(1,rsi6.size):\n tmp=0\n if(rsi6[i]>90):\n tmp=-1\n elif(rsi6[i]>80):\n tmp=-0.5\n elif(rsi6[i]<10):\n tmp=1\n elif(rsi6[i]<20):\n tmp=0.5\n dif=rsi6[i]-rsi12[i]\n mul=(rsi6[i-1]-rsi12[i-1])*dif\n if (abs(mul-0) < 0.0000001) or (mul < 0):\n if (dif > 0) or ((abs(dif-0) < 0.0000001) and rsi6[i-1] < rsi12[i-1]):\n tmp=tmp+2\n else:\n tmp=tmp-2\n rst=np.append(rst,tmp)\n new_idx['RSI']=np.reshape(rst, (-1)).tolist()\n #KD\n k=np.array([float(i) for i in df2['K']])\n d=np.array([float(i) for i in df2['D']])\n rst=np.array(0)\n for i in range(1,k.size):\n dif=k[i]-d[i]\n mul=dif*(k[i-1]*d[i-1])\n tmp=0\n if (abs(mul-0) < 0.0000001) or (mul < 0):\n if (dif > 0) or ((abs(dif-0) < 0.0000001) and k[i-1] < d[i-1]):\n tmp=1\n else:\n tmp=-1\n w=0\n if k[i]>80 or k[i]<20 :\n w=2\n elif k[i]>70 or k[i]<30 :\n w=1\n rst=np.append(rst,w*tmp)\n new_idx['KD']=np.reshape(rst, (-1)).tolist()\n #BIAS\n bias=np.array([float(i) for i in df2['BIAS']])\n if(bias[0]<-4.5):\n rst=np.array(2)\n elif(bias[0]<-3):\n rst=np.array(1)\n elif(bias[0]>5):\n rst=np.array(-2)\n elif(bias[0]>3.5):\n rst=np.array(-1)\n else:\n rst=np.array(0)\n for i in range(1,bias.size):\n if(bias[i]<-4.5):\n rst=np.append(rst,2)\n elif(bias[i]<-3):\n rst=np.append(rst,1)\n elif(bias[i]>5):\n rst=np.append(rst,-2)\n elif(bias[i]>3.5):\n rst=np.append(rst,-1)\n else:\n rst=np.append(rst,0)\n new_idx['BIAS']=np.reshape(rst, (-1)).tolist()\n #WMR\n wr=np.array([float(i) for i in df2['WMR']])\n if(wr[0]<=20):\n rst=np.array(-2)\n elif(wr[0]<35):\n rst=np.array(-1)\n elif(wr[0]<65):\n rst=np.array(0)\n elif(wr[0]<80):\n rst=np.array(1)\n else:\n rst=np.array(2)\n for i in range(1,wr.size):\n if(wr[i]<=20):\n rst=np.append(rst,-2)\n elif(wr[i]<35):\n rst=np.append(rst,-1)\n elif(wr[i]<65):\n rst=np.append(rst,0)\n elif(wr[i]<80):\n rst=np.append(rst,1)\n else:\n rst=np.append(rst,2)\n new_idx['WMR']=np.reshape(rst, (-1)).tolist()\n #MACD\n macd=np.array([float(i) for i in df2['MACD']])\n dif=np.array([float(i) for i in df2['EMA_12']])-np.array([float(i) for i in df2['EMA_26']])\n if macd[0]>0 and dif[0]>0:\n rst=np.array(2)\n elif dif[0]>0:\n rst=np.array(1)\n elif macd[0]>0:\n rst=np.array(-1)\n else:\n rst=np.array(-2)\n for i in range(1,macd.size):\n if macd[i]>0 and dif[i]>0:\n rst=np.append(rst,2)\n elif dif[i]>0:\n rst=np.append(rst,1)\n elif macd[i]>0:\n rst=np.append(rst,-1)\n else:\n rst=np.append(rst,-2)\n new_idx['MACD']=np.reshape(rst, (-1)).tolist()\n #PSY\n new_idx['PSY']=df2['psy_6'].copy()\n #SAR\n sar=np.array([float(i) for i in df2['SAR_6']])\n dif=k-sar\n rst=np.array(0)\n for i in range(1,k.size):\n mul=dif[i]*dif[i-1]\n tmp=0\n if (abs(mul-0) < 0.0000001) or (mul < 0):\n if (dif[i] > 0) or ((abs(dif[i]-0) < 0.0000001) and dif[i-1]<0):\n tmp=1\n else:\n tmp=-1\n rst=np.append(rst,tmp)\n new_idx['SAR']=np.reshape(rst, (-1)).tolist()\n #CDP\n new_idx['CDP']=df2['Trend'].copy()\n #DMI\n l=['+DI(DMI)','-DI(DMI)','ADX(DMI)']\n for i in l:\n new_idx[i]=df2[i].copy()\n pd.set_option('display.max_rows', 1000)\n pd.set_option('display.max_columns', 1000)\n new_idx.to_json('./stock_data_index_V2/' + stockcode + '_index_V2.json')\n\n return new_idx\n\n\n\nif __name__ == \"__main__\":\n stockcode='0050'\n PATH_input_json = './stock_data/'+stockcode+'.json'\n df=stock_index_generator(pd.read_json(PATH_input_json),stockcode)\n print(df)\n min_maxdf=Normalize_pd(df)\n print(min_maxdf)\n\n df_v2 = stock_index_generator_V2(df,stockcode)\n print(df_v2)\n min_maxdfV2 = Normalize_pd_V2(df_v2)\n print(min_maxdfV2)\n\n pass\n\n\n","sub_path":"Model/lstm_w/index_generate.py","file_name":"index_generate.py","file_ext":"py","file_size_in_byte":21368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"544504190","text":"# 5번_B735042_김대겸\r\n\r\n# main()함수 선언.\r\ndef main():\r\n inputString = input(\"정수 리스트 입력: \")\r\n # inputString을 list1으로 변환한다\r\n list1 = list(map(int, inputString.split()))\r\n print(\"평균=\", getMean(list1))\r\n print(\"표준 편차\", getDeviation(list1))\r\n\r\n# getMean()함수 선언.(평균과 구하고 그 값을 반환하는 함수)\r\ndef getMean(lst):\r\n lst_total = 0\r\n for i in lst:\r\n lst_total += i\r\n lst_average = (lst_total / len(lst))\r\n return lst_average\r\n\r\n# getDeviation()함수 선언.(표준편차를 구하고 그 값을 반환하는 함수)\r\ndef getDeviation(lst): \r\n ave = getMean(lst)\r\n cha_total = 0\r\n for i in lst:\r\n cha_total += ((i - ave)**2)\r\n devi = ((cha_total / (len(lst)))**(1/2))\r\n return devi\r\n\r\n# main()함수 호출.\r\nmain()\r\n","sub_path":"김대겸 (5).py","file_name":"김대겸 (5).py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"612878436","text":"import cv2\r\nimport numpy as np\r\n\r\ndef main():\r\n \r\n windowname=\"live video\"\r\n \r\n cv2.namedWindow(windowname)\r\n \r\n cap=cv2.VideoCapture(0)\r\n \r\n if cap.isOpened():\r\n ret, frame=cap.read()\r\n else:\r\n ret = False\r\n \r\n while ret:\r\n \r\n ret, frame=cap.read()\r\n \r\n hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n \r\n low = np.array([100,50,50])\r\n high= np.array([140,255,255])\r\n \r\n image_mask=cv2.inRange(hsv, low, high)\r\n \r\n output=cv2.bitwise_and(frame,frame,mask=image_mask)\r\n cv2.imshow(windowname,output)\r\n \r\n if cv2.waitKey(1)== 27:\r\n break\r\n \r\n print(image_mask) \r\n cv2.destroyWindow(windowname)\r\n cap.release()\r\n\r\nif __name__==\"__main__\":\r\n main() ","sub_path":"color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"492278814","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom astropy.io import fits\nfrom .get_ephem import get_ephemerides, naif_lookup\nfrom nirc2_reduce.image import Image\nfrom nirc2_reduce.phot import nearest_stand_filt\nfrom datetime import datetime, timedelta\nimport warnings\nfrom skimage import feature\nfrom image_registration.chi2_shifts import chi2_shift\nfrom image_registration.fft_tools.shift import shiftnd, shift2d\nfrom scipy.interpolate import interp2d, RectBivariateSpline, NearestNDInterpolator, griddata\n#from .fit_gaussian import fitgaussian\nfrom astropy.modeling import models, fitting\nfrom scipy.ndimage.measurements import center_of_mass\nfrom scipy.ndimage.interpolation import zoom\n\n#from mpl_toolkits import basemap\nimport pyproj\n\n\ndef lat_lon(x,y,ob_lon,ob_lat,pixscale_km,np_ang,req,rpol):\n '''Find latitude and longitude on planet given x,y pixel locations and\n planet equatorial and polar radius'''\n np_ang = -np_ang\n x1 = pixscale_km*(np.cos(np.radians(np_ang))*x - np.sin(np.radians(np_ang))*y)\n y1 = pixscale_km*(np.sin(np.radians(np_ang))*x + np.cos(np.radians(np_ang))*y)\n olrad = np.radians(ob_lat)\n \n #set up quadratic equation for ellipsoid\n r2 = (req/rpol)**2\n a = 1 + r2*(np.tan(olrad))**2 #second order\n b = 2*y1*r2*np.sin(olrad) / (np.cos(olrad)**2) #first order\n c = x1**2 + r2*y1**2 / (np.cos(olrad))**2 - req**2 #constant\n\n radical = b**2 - 4*a*c\n #will equal nan outside planet since radical < 0\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking sqrt nan\n x3s1=(-b+np.sqrt(radical))/(2*a)\n x3s2=(-b-np.sqrt(radical))/(2*a)\n z3s1=(y1+x3s1*np.sin(olrad))/np.cos(olrad)\n z3s2=(y1+x3s2*np.sin(olrad))/np.cos(olrad)\n odotr1=x3s1*np.cos(olrad)+z3s1*np.sin(olrad)\n odotr2=x3s2*np.cos(olrad)+z3s2*np.sin(olrad)\n #the two solutions are front and rear intersections with planet\n #only want front intersection\n \n #tricky way of putting all the positive solutions into one array\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking < nan\n odotr2[odotr2 < 0] = np.nan\n x3s2[odotr2 < 0] = np.nan\n z3s2[odotr2 < 0] = np.nan\n odotr1[odotr1 < 0] = odotr2[odotr1 < 0]\n x3s1[odotr1 < 0] = x3s2[odotr1 < 0]\n z3s1[odotr1 < 0] = z3s2[odotr1 < 0]\n \n odotr,x3,z3 = odotr1,x3s1,z3s1\n y3 = x1\n r = np.sqrt(x3**2 + y3**2 + z3**2)\n \n #lon_w = np.degrees(np.arctan(y3/x3)) + ob_lon\n lon_w = np.degrees(np.arctan2(x3,y3)-np.pi/2) + ob_lon \n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking < nan\n lon_w[lon_w < 0] += 360\n lon_w = lon_w%360\n lat_c = np.degrees(np.arcsin(z3/r))\n lat_g = np.degrees(np.arctan(r2*np.tan(np.radians(lat_c))))\n #plt.imshow(lon_w, origin = 'lower left')\n #plt.show()\n return lat_g, lat_c, lon_w\n\ndef surface_normal(lat_g, lon_w, ob_lon):\n '''Returns the normal vector to the surface of the planet.\n Take dot product with sub-obs or sub-sun vector to find cosine of emission angle'''\n nx = np.cos(np.radians(lat_g))*np.cos(np.radians(lon_w-ob_lon))\n ny = np.cos(np.radians(lat_g))*np.sin(np.radians(lon_w-ob_lon))\n nz = np.sin(np.radians(lat_g))\n return np.asarray([nx,ny,nz])\n\ndef emission_angle(ob_lat, surf_n):\n '''Return the cosine of the emission angle of surface wrt observer'''\n ob = np.asarray([np.cos(np.radians(ob_lat)),0,np.sin(np.radians(ob_lat))])\n return np.dot(surf_n.T, ob).T\n \n#def sun_angle(ob_lon, ob_lat, sun_lon, sun_lat):\n# return\n \ndef get_filt_info(filt):\n '''Helper to I/F. Will find flux of sun in given filter'''\n with open('/Users/emolter/Python/nirc2_reduce/filter_passbands/sun_fluxes.txt','r') as f:\n f.readline() #header\n for line in f:\n l = line.split(',')\n fl = l[0].strip(', \\n')\n if fl == filt:\n wl = float(l[1].strip(', \\n'))\n sun_mag = float(l[2].strip(', \\n'))\n return wl, sun_mag\n \ndef find_airmass(observatory, time, object):\n '''Use the power of astropy to retrieve airmass of standard\n star automatically... obvs not done yet'''\n return\n \ndef airmass_correction(air_t, air_c, filt):\n '''Helper to I/F. Computes correction factor to photometry based on airmass.\n Multiply \n air_t is airmass of science target.\n air_c is airmass of calibrator.\n filt options are j, h, k, l, m. Use nearest one for narrowband filters'''\n cdict = {'j': 0.102,\n 'h': 0.059,\n 'k': 0.088,\n 'l': 0.093,\n 'm': 0.220} #from https://www2.keck.hawaii.edu/realpublic/inst/nirc/exts.html\n if filt == None:\n return 1.0\n tau = cdict[filt]\n factor = np.exp(tau*air_t)/np.exp(tau*air_c)\n return factor\n\nclass CoordGrid:\n \n def __init__(self, infile, lead_string = None, req = 24764, rpol = 24341, scope = 'keck'):\n '''Pull ephemeris data, calculate lat and lon. Pixscale in arcsec, req and rpol in km'''\n \n self.im = Image(infile)\n self.req = req\n self.rpol = rpol\n scope = str.lower(scope)\n\n if scope == 'keck':\n pixscale = 0.009942\n elif scope == 'lick':\n pixscale = 0.033\n elif scope == 'alma':\n pixscale = np.abs(self.im.header['CDELT1']) * 3600 #deg to arcsec\n elif scope == 'hst':\n pixscale = np.abs(self.im.header['PIXSCAL'])\n else:\n pixscale = 0.0\n self.pixscale_arcsec = pixscale\n if scope == 'vla' or scope == 'alma':\n self.data = self.im.data[0,0,:,:]\n else:\n self.data = self.im.data\n \n #pull and reformat header info\n if not scope == 'hst_wfc3':\n targ = self.im.header['OBJECT'].split('_')[0]\n targ = targ.split(' ')[0]\n self.target = targ\n else:\n targ = 'Neptune'\n self.target = 'Neptune'\n if scope == 'vla' or scope == 'alma':\n date = self.im.header['DATE-OBS']\n expstart = date.split('T')[1]\n date = date.split('T')[0]\n elif scope == 'hst':\n date = self.im.header['DATE-OBS']\n expstart = self.im.header['TIME-OBS']\n elif scope == 'keck':\n expstart = self.im.header['EXPSTART']\n date = self.im.header['DATE-OBS']\n imsize_x = self.data.shape[0]\n imsize_y = self.data.shape[1]\n if scope == 'lick':\n tstart = datetime.strptime(self.im.header['DATE-BEG'][:-7],'%Y-%m-%dT%H:%M')\n else:\n tstart = datetime.strptime(date+' '+expstart[:5],'%Y-%m-%d %H:%M')\n tend = tstart + timedelta(minutes=1)\n tstart = datetime.strftime(tstart, '%Y-%m-%d %H:%M')\n tend = datetime.strftime(tend, '%Y-%m-%d %H:%M')\n self.date_time = tstart\n \n #pull ephemeris data\n naif = naif_lookup(targ)\n if scope == 'keck':\n obscode = 568\n elif scope == 'vla':\n obscode = -5\n elif scope == 'lick':\n obscode = 662\n elif scope == 'alma':\n obscode = -7\n elif scope == 'hst_wfc3' or scope == 'hst_opal' or scope == 'hst_wfc2':\n obscode = '500@-48'\n else:\n obscode = input('Enter Horizons observatory code: ')\n \n ## check ephem inputs\n #print(naif) \n #print(obscode)\n #print(tstart)\n #print(tend)\n \n ephem = get_ephemerides(naif, obscode, tstart, tend, '1 minutes')[0][0] #just the row for start time\n ephem = [val.strip(' ') for val in ephem]\n time = ephem[0]\n ra, dec = ephem[3], ephem[4]\n dra, ddec = float(ephem[5]), float(ephem[6])\n if not scope == 'hst_wfc3':\n az, el = float(ephem[7]), float(ephem[8])\n self.airmass, extinction = float(ephem[9]), float(ephem[10])\n apmag, sbrt = float(ephem[11]), float(ephem[12])\n self.ang_diam = float(ephem[15])\n self.ob_lon, self.ob_lat = float(ephem[16]), float(ephem[17])\n self.sun_lon, self.sun_lat = float(ephem[18]), float(ephem[19])\n #self.sun_ang = sun_angle(ob_lon, ob_lat, sun_lon, sun_lat)\n self.np_ang, self.np_dist = float(ephem[20]), float(ephem[21])\n self.sun_dist = float(ephem[22])*1.496e8 #from AU to km\n self.dist = float(ephem[24])*1.496e8 #from AU to km \n \n self.pixscale_km = self.dist*np.radians(pixscale/3600)\n avg_circumference = 2*np.pi*((req + rpol)/2.0)\n self.deg_per_px = self.pixscale_km * (1/avg_circumference) * 360 #approximate conversion between degrees and pixels at sub-observer point\n \n if lead_string != None:\n #if you already did the edge detection and centering and are loading centered image\n self.centered = self.im.data\n self.lat_g = Image(lead_string+'_latg.fits').data\n self.lon_w = Image(lead_string+'_lonw.fits').data\n self.model_planet = np.nan_to_num(self.lat_g * 0.0 + 1.0)\n try:\n self.err_x = Image(lead_string+'_errx.fits').data\n self.err_y = Image(lead_string+'_erry.fits').data\n except:\n pass\n try:\n self.projected = Image(lead_string+'_proj.fits').data\n except:\n pass\n try:\n self.mu = Image(lead_string+'_mu.fits').data\n except:\n self.surf_n = surface_normal(self.lat_g, self.lon_w, self.ob_lon)\n self.mu = emission_angle(self.ob_lat, self.surf_n)\n try:\n self.mu_projected = Image(lead_string+'_mu_proj.fits').data\n except:\n pass\n \n else:\n xcen, ycen = int(imsize_x/2), int(imsize_y/2) #pixels at center of planet\n xx = np.arange(imsize_x) - xcen\n yy = np.arange(imsize_y) - ycen\n x,y = np.meshgrid(xx,yy)\n self.lat_g, self.lat_c, self.lon_w = lat_lon(x,y,self.ob_lon,self.ob_lat,self.pixscale_km,self.np_ang,req,rpol)\n self.surf_n = surface_normal(self.lat_g, self.lon_w, self.ob_lon)\n self.mu = emission_angle(self.ob_lat, self.surf_n)\n\n def ioverf(self, filt, flux_per, stand_airmass):\n '''Compute I/F ratio given an image in cts s-1 and a conversion between\n cts s-1 and erg s-1 cm-2 um-1 sr-1'''\n wl, sun_flux_earth = get_filt_info(filt)\n sun_flux = sun_flux_earth * (1/np.pi)*(1.496e8/self.sun_dist)**2 #factor of pi because F = pi*B\n sr_per_px = np.radians(self.pixscale_arcsec/3600)**2\n sun_flux_density = sun_flux * sr_per_px # from erg s-1 cm-2 um-1 sr-1 to erg s-1 cm-2 um-1 px-1\n print('Sun flux density ', sun_flux_density)\n \n #photometry correction\n airmass_filt = nearest_stand_filt[filt]\n air_corr = airmass_correction(self.airmass, stand_airmass, airmass_filt)\n print('Airmass correction ',air_corr)\n self.data = self.data * flux_per * air_corr / sun_flux_density\n if hasattr(self, 'centered'):\n self.centered = self.centered * flux_per * air_corr / sun_flux_density\n \n #def minnaert(self, k):\n # '''Applies Minnaert correction to remove effects of limb darkening\n # k is an empirically determined constant between 0 and 1, 0.7 for Io'''\n # self.data = self.data * self.sun_ang**k * self.mu**(k - 1)\n # if hasattr(self, 'centered'):\n # self.centered = self.centered * mu0**k * self.mu**(k - 1)\n \n def write_photonly(self, outstr):\n '''If you want to just run ioverf and then write'''\n hdulist_out = self.im.hdulist\n #centered data\n hdulist_out[0].header['OBJECT'] = self.target+'_calibrated'\n hdulist_out[0].data = self.data\n hdulist_out[0].writeto(outstr, overwrite=True)\n\n def edge_detect(self, low_thresh = 0.01, high_thresh = 0.05, sigma = 5, plot = True):\n '''Uses skimage canny algorithm to find edges of planet, correlates\n that with edges of model, '''\n \n self.model_planet = np.nan_to_num(self.lat_g * 0.0 + 1.0)\n edges = feature.canny(self.data/np.max(self.data), sigma=sigma, low_threshold = low_thresh, high_threshold = high_thresh)\n model_edges = feature.canny(self.model_planet, sigma=sigma, low_threshold = low_thresh, high_threshold = high_thresh)\n \n [dx,dy,dxerr,dyerr] = chi2_shift(model_edges,edges)\n self.x_shift = -dx #need if we want to shift another filter the same amount\n self.y_shift = -dy\n print('Pixel shift X, Y = ', self.x_shift, self.y_shift)\n \n #error in position on surface is approximately equal to projected error times emission angle - in reality there is some asymmetry that would be important if error bars are large\n #These are lat/lon error in the x-hat and y-hat directions; their magnitude is correct for lat-lon space but their direction is not\n self.err_x = dxerr/(self.deg_per_px*self.mu)\n self.err_y = dyerr/(self.deg_per_px*self.mu)\n print(' Lat/Lon error at sub-obs point in x-hat direction = '+str(dxerr/self.deg_per_px))\n print(' Lat/Lon error at sub-obs point in y-hat direction = '+str(dyerr/self.deg_per_px)) \n \n self.centered = shift2d(self.data,-1*dx,-1*dy)\n self.edges = shift2d(edges,-1*dx,-1*dy)\n\n if plot:\n fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(10, 5))\n \n ax0.imshow(self.data, origin = 'lower left')\n ax0.set_title('Image')\n \n ax1.imshow(edges, origin = 'lower left')\n ax1.set_title('Canny filter, $\\sigma=$%d'%sigma)\n \n ax2.imshow(self.edges, origin = 'lower left', alpha = 0.5)\n ax2.imshow(model_edges, origin = 'lower left', alpha = 0.5)\n ax2.set_title('Overlay model and data')\n \n plt.show()\n \n \n def edge_detect_error(self, niter, perturb_l, perturb_dist, low_thresh = 0.002, dist = 0.02, sigma = 5, doplot = True):\n '''Perturbs parameters of Canny algorithm to produce a variety of \n edge detection solutions. Finds most probable one, and takes \n standard deviation of those to produce an error\n perturb_l, perturb_dist Factor by which low_thresh and distance between low and high threshold are changed. must be >= 1\n sigmavals List of sigma values to use. Usually some subset of [3,5,7]\n niter Number of iterations for each low, high threshold value'''\n \n #set up the model planet\n self.model_planet = np.nan_to_num(self.lat_g * 0.0 + 1.0)\n model_edges = feature.canny(self.model_planet, sigma=sigma, low_threshold = low_thresh, high_threshold = low_thresh + dist)\n\n if doplot:\n inp = False\n while not inp:\n \n #set up arrays of values\n l_vals = np.arange(low_thresh/perturb_l, low_thresh*perturb_l, (low_thresh*perturb_l - low_thresh/perturb_l)/niter)\n dist_vals = np.arange(dist/perturb_dist, dist*perturb_dist, (dist*perturb_dist - dist/perturb_dist)/niter)\n \n #check that lowest, middle, and highest params give you what is expected\n l_bounds = [l_vals[0], low_thresh, l_vals[-1]]\n d_bounds = [dist_vals[0], dist, dist_vals[-1]]\n fig, axes = plt.subplots(3, 3, figsize=(8, 12), sharex = True, sharey = True)\n \n for i in range(3):\n #do the edges \n l = l_bounds[i]\n d = d_bounds[i]\n edges = feature.canny(self.data/np.max(self.data), sigma=sigma, low_threshold = l, high_threshold = l + d)\n [dx,dy,dxerr,dyerr] = chi2_shift(model_edges,edges)\n shift_edges = shift2d(edges,-1*dx,-1*dy)\n \n #plot things\n axarr = axes[i]\n axarr[0].imshow(self.data, origin = 'lower left')\n axarr[1].imshow(edges, origin = 'lower left')\n axarr[2].imshow(shift_edges, origin = 'lower left', alpha = 0.5)\n axarr[2].imshow(model_edges, origin = 'lower left', alpha = 0.5) \n \n #cosmetics\n if i == 0:\n axarr[0].set_title('Image')\n axarr[1].set_title('Edges, $\\sigma=$%d'%sigma)\n axarr[2].set_title('Overlay model and data')\n \n for ax in axarr:\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_ylim([0, edges.shape[1]])\n ax.set_xlim([0, edges.shape[0]])\n \n axarr[0].set_ylabel('l = '+str(l)[:6]+', d = '+str(d)[:6])\n \n plt.subplots_adjust(wspace = 0, hspace = 0)\n plt.show() \n \n yn = input('Are you okay with these? (y/n): ')\n if yn.lower().strip() == 'y' or yn.lower().strip() == 'yes':\n inp = True\n else:\n low_thresh = float(input('New value of low_thresh: '))\n dist = float(input('New value of dist: '))\n perturb_l = float(input('New value of perturb_l: '))\n perturb_dist = float(input('New value of perturb_dist: '))\n else:\n l_vals = np.arange(low_thresh/perturb_l, low_thresh*perturb_l, (low_thresh*perturb_l - low_thresh/perturb_l)/niter)\n dist_vals = np.arange(dist/perturb_dist, dist*perturb_dist, (dist*perturb_dist - dist/perturb_dist)/niter)\n \n #now iterate over the parameter space and determine x,y for each\n dx_vals, dy_vals = [], []\n dxerr_vals , dyerr_vals = [], []\n for lt in l_vals:\n for d in dist_vals:\n ht = lt + d\n edges = feature.canny(self.data/np.max(self.data), sigma=sigma, low_threshold = lt, high_threshold = ht)\n [dx,dy,dxerr,dyerr] = chi2_shift(model_edges,edges)\n dx_vals.append(dx)\n dy_vals.append(dy)\n dxerr_vals.append(dxerr)\n dyerr_vals.append(dyerr)\n #print(d, dx, dy)\n plotevery = False\n if plotevery:\n fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(10, 5))\n \n ax0.imshow(self.data, origin = 'lower left')\n ax0.set_title('Image')\n \n ax1.imshow(edges, origin = 'lower left')\n ax1.set_title('Canny filter, $\\sigma=$%d'%sigma)\n \n ax2.imshow(shift2d(edges,-1*dx,-1*dy), origin = 'lower left', alpha = 0.5)\n ax2.imshow(model_edges, origin = 'lower left', alpha = 0.5)\n ax2.set_title('Overlay model and data') \n \n plt.show() \n dx_vals = np.asarray(dx_vals)\n dy_vals = np.asarray(dy_vals)\n dxerr_vals = np.asarray(dxerr_vals)\n dyerr_vals = np.asarray(dyerr_vals)\n print('Best X, Y = ', np.mean(dx_vals), np.mean(dy_vals))\n print('Sigma X, Y = ', np.std(dx_vals), np.std(dy_vals))\n print('Typical shift error X, Y = ', np.mean(dxerr_vals), np.mean(dyerr_vals))\n print('Spread in shift error X, Y = ', np.std(dxerr_vals), np.std(dyerr_vals))\n print('Total error X, Y = ', np.sqrt(np.std(dx_vals)**2 + np.mean(dxerr_vals)**2), np.sqrt(np.std(dy_vals)**2 + np.mean(dyerr_vals)**2))\n \n if doplot:\n #histogram of the samples\n fig, (ax0, ax1) = plt.subplots(2,1, figsize = (6,8))\n \n ax0.hist(dx_vals, bins = niter)\n ax1.hist(dy_vals, bins = niter)\n \n ax0.set_xlabel('Shift in X')\n ax0.set_ylabel('Number')\n ax1.set_xlabel('Shift in Y')\n ax1.set_ylabel('Number')\n plt.show()\n \n \n def manual_shift(self,dx,dy):\n self.centered = shift2d(self.data,dx,dy)\n \n def plot_latlon(self):\n '''Make pretty plot of lat_g and lon_w overlaid on planet'''\n fig, (ax0, ax1) = plt.subplots(1,2, figsize = (12,6))\n \n #little circle around planet - now does not depend on self.edges existing\n planetedge = np.copy(self.lat_g)\n nans = np.isnan(planetedge)\n planetedge[np.invert(nans)] = 100\n planetedge[nans] = 0\n \n #latitudes\n ax0.imshow(self.centered, origin = 'lower left')\n levels_lat = np.arange(-90,105,15)\n label_levels_lat = np.arange(-90,60,30)\n ctr_lat = ax0.contour(self.lat_g, levels_lat, colors='white', linewidths=2)\n ax0.clabel(ctr_lat, label_levels_lat, inline=1, inline_spacing = 2, fontsize=16, fmt='%d')\n ax0.contour(planetedge, colors = 'white', linewidths = 1)\n #ax0.set_title('Latitudes', fontsize = 18)\n ax0.get_xaxis().set_ticks([])\n ax0.axes.get_yaxis().set_ticks([])\n \n #longitudes\n ax1.imshow(self.centered, origin = 'lower left')\n #hack here to avoid discontinuity in contours - split longs in half\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking < nan\n lon_w1 = np.copy(self.lon_w)\n lon_w1[lon_w1 >= 180] = np.nan\n lon_w2 = np.copy(self.lon_w)\n lon_w2[lon_w2 < 180] = np.nan\n \n levels_lon = range(0,360,30)\n levels_lon_hack = [1] + list(levels_lon[1:]) #make contour at zero actually 1 - otherwise won't plot it since it's at the edge\n ctr_lon1 = ax1.contour(lon_w1, levels_lon_hack, colors='white', linewidths=2)\n ctr_lon2 = ax1.contour(lon_w2, levels_lon_hack, colors='white', linewidths=2)\n \n fmt = {}\n vals = np.arange(0,360,30)\n for l, v in zip(levels_lon_hack, vals):\n fmt[l] = str(int(v)) #make it so the labels say the right things despite hack\n ax1.clabel(ctr_lon1, levels_lon_hack, fmt = fmt, inline=1, inline_spacing = 2, fontsize=16)\n ax1.clabel(ctr_lon2, levels_lon_hack, fmt = fmt, inline=1, inline_spacing = 2, fontsize=16)\n ax1.contour(planetedge, colors = 'white', linewidths = 1)\n #ax1.set_title('Longitudes', fontsize = 18)\n ax1.get_xaxis().set_ticks([])\n ax1.axes.get_yaxis().set_ticks([]) \n \n plt.tight_layout()\n plt.savefig('lat_lon_overlay.png')\n plt.show()\n \n def write(self, lead_string):\n '''Tertiary data products'''\n hdulist_out = self.im.hdulist\n #centered data\n hdulist_out[0].header['OBJECT'] = self.target+'_CENTERED'\n hdulist_out[0].data = self.centered\n hdulist_out[0].writeto(lead_string + '_centered.fits', overwrite=True)\n #latitudes\n hdulist_out[0].header['OBJECT'] = self.target+'_LATITUDES'\n hdulist_out[0].data = self.lat_g\n hdulist_out[0].writeto(lead_string + '_latg.fits', overwrite=True)\n #longitudes\n hdulist_out[0].header['OBJECT'] = self.target+'_LONGITUDES'\n hdulist_out[0].data = self.lon_w\n hdulist_out[0].writeto(lead_string + '_lonw.fits', overwrite=True)\n #errors only exist if edge_detect was run. if manual shift, just ignore\n try:\n #error in x*mu\n hdulist_out[0].header['OBJECT'] = self.target+'_XERR'\n hdulist_out[0].data = self.err_x\n hdulist_out[0].writeto(lead_string + '_errx.fits', overwrite=True)\n #error in y*mu\n hdulist_out[0].header['OBJECT'] = self.target+'_YERR'\n hdulist_out[0].data = self.err_y\n hdulist_out[0].writeto(lead_string + '_erry.fits', overwrite=True)\n except:\n pass\n\n def bootstrap_func(self, order = 2):\n '''Takes a navigated image, plots flux as function of emission angle,\n fits (to nth order) to the minimum flux vs emission angle curve.\n returns the fit coefficients to IoverF(mu)'''\n \n onplanet = np.copy(self.centered)\n onplanet *= self.model_planet\n \n vals = onplanet.flatten()\n mus = self.mu.flatten()\n \n vals_2 = vals[vals > 0] #remove zeros on outside of image\n mus_2 = mus[vals > 0]\n \n np.savetxt('flux_vs_mu.txt', np.asarray([mus_2, vals_2]))\n \n '''It looks like the minimum value at each emission angle follows a fairly\n regular distribution. Try to make a function fit the bottom of it.'''\n bins = np.arange(0,1.01,0.01)\n x = np.digitize(mus_2, bins)\n mins = [np.min(vals_2[np.where(x == i)]) if len(vals_2[np.where(x == i)]) > 0 else 0.0 for i in range(bins.shape[0])]\n mins = np.asarray(mins)\n bins = bins[np.where(mins > 0)]\n mins = mins[np.where(mins > 0)]\n \n z = np.polyfit(bins,mins, order)\n func = np.poly1d(z)\n \n plt.semilogy(mus_2, vals_2, linestyle = '', marker = '.', color = 'k', markersize = 1)\n plt.semilogy(bins, func(bins), color = 'r')\n #plt.semilogy(bins, z[0]*bins**2 + z[1]*bins*1.1 + z[2])\n plt.xlabel(r'Emission angle $\\mu$')\n plt.ylabel('I/F')\n plt.show()\n \n print('Polynomial parameters ... + A2*x**2 + A1*x + A2 = ',z)\n return z\n \n def locate_feature(self, outfile=None):\n plt.imshow(self.centered, origin = 'lower left')\n plt.show()\n print('Define a box around the feature you want to track. Note x,y are reversed in image due to weird Python indexing!')\n pix_l = input('Enter lower left pixel x,y separated by a comma: ')\n pix_u = input('Enter upper right pixel x,y separated by a comma: ')\n \n p0x, p0y = int(pix_l.split(',')[0].strip(', \\n')),int(pix_l.split(',')[1].strip(', \\n'))\n p1x, p1y = int(pix_u.split(',')[0].strip(', \\n')),int(pix_u.split(',')[1].strip(', \\n'))\n region = self.centered[p0x:p1x,p0y:p1y] \n\n #Brightest spot in feature\n maxloc = np.where(self.centered == np.max(region))\n maxlat, maxlon = self.lat_g[maxloc], self.lon_w[maxloc]\n \n #Gaussian fit\n A0 = np.sum(region)\n x0, y0 = (p1x - p0x)/2, (p1y - p0y)/2\n x_std0, y_std0 = region.shape[0]/2, region.shape[1]/2\n theta0 = 0.0\n g_init = models.Gaussian2D(A0, x0, y0, x_std0, y_std0, theta0)\n xx, yy = np.mgrid[:region.shape[0], :region.shape[1]]\n fit_g = fitting.LevMarLSQFitter()\n g = fit_g(g_init, xx, yy, region)\n \n xfg, yfg = g.x_mean + p0x, g.y_mean + p0y\n latfg, lonfg = self.lat_g[int(round(xfg)),int(round(yfg))], self.lon_w[int(round(xfg)), int(round(yfg))]\n \n ''' #estimate lat and lon errors\n frac = 0.5 #can probably constrain the center much more, but depends on morphology of storm over time\n fracmax = np.where(g_overlay/np.max(g_overlay) > frac)\n inlat, inlon = self.lat_g[fracmax], self.lon_w[fracmax]\n minlat, maxlat = np.min(inlat), np.max(inlat)\n minlon, maxlon = np.min(inlon), np.max(inlon) #wrapping issues still present!\n \n lat_errl, lat_erru = np.abs(latf - minlat), np.abs(maxlat - latf) \n lon_wrrl, lon_wrru = np.abs(lonf - minlon), np.abs(maxlon - lonf)'''\n\n #Contour method after Martin, de Pater, Marcus 2012\n def ctr_region(rgn, frac):\n rgn = np.copy(rgn)\n rgn[rgn < frac*np.max(rgn)] = 0.0\n rgn[rgn > 0.0] = 1.0\n xf, yf = center_of_mass(rgn)\n return xf, yf\n \n def interp_latlon_atpt(xd,yd):\n x, y = int(round(xd)), int(round(yd))\n xcoords, ycoords = np.arange(x-3, x+4), np.arange(y-3, y+4)\n latgrid = self.lat_g[x-3:x+4,y-3:y+4]\n longrid = self.lon_w[x-3:x+4,y-3:y+4]\n #RectBivariateSpline and interp2d both fail if lat/lon grid has NaNs, i.e. if near edge of planet\n if np.any(np.isnan(latgrid[2:5,2:5])):\n #Check to see if you are way too close\n print(' WARNING! DANGER! ERROR! HELP! OMG!')\n print(' Trying to find pixel locations very near edge of planet')\n print(' Lat-lon errors are probably wrong!!')\n latgrid[np.isnan(latgrid)] = 0.0\n longrid[np.isnan(longrid)] = 0.0\n interpf_lat = RectBivariateSpline(xcoords, ycoords, latgrid)\n interpf_lon = RectBivariateSpline(xcoords, ycoords, longrid)\n return interpf_lat.ev(xd, yd), interpf_lon.ev(xd, yd)\n #interpf_lat = interp2d(xcoords, ycoords, latgrid, kind = 'cubic')\n #interpf_lon = interp2d(xcoords, ycoords, longrid, kind = 'cubic')\n #return interpf_lat(xd, yd), interpf_lon(xd, yd)\n \n def ctr_fit(rgn, frac):\n (px, py) = ctr_region(rgn, frac)\n xfc, yfc = px + p0x, py + p0y\n #latfc, lonfc = self.lat_g[int(round(xfc)),int(round(yfc))], self.lon_w[int(round(xfc)), int(round(yfc))] #old way - fails if error is <~ 1 pixel\n latfc, lonfc = interp_latlon_atpt(xfc, yfc)\n return xfc, yfc, latfc, lonfc\n \n poslist = [] \n for val in np.arange(0.68, 0.96, 0.01):\n xfc, yfc, latfc, lonfc = ctr_fit(region, val)\n poslist.append([xfc, yfc, latfc, lonfc])\n poslist = np.asarray(poslist)\n medposlist = np.median(poslist, axis = 0)\n meanposlist = np.mean(poslist, axis = 0)\n minposlist = np.min(poslist, axis = 0)\n maxposlist = np.max(poslist, axis = 0)\n sigmaposlist = np.std(poslist, axis = 0) \n ## there will be longitude wrapping issues here later - will need to fix at some point\n\n print('Error in X,Y,lat,lon', sigmaposlist)\n print('Best X,Y,lat,lon (contour method)', medposlist)\n \n #write to file\n if outfile != None:\n print('Writing detailed outputs to file.')\n rows = ['# ','X_pixel', 'Y_pixel', 'Latitude', 'Longitude']\n columns = ['Brightest', 'Contour_Median','Contour_Mean','Contour_Sigma','Contour_Min','Contour_Max','Gaussian_Center','Gaussian_Sigma','Edge_Detect_Err']\n with open(outfile, 'w') as f:\n f.write('#Finding center of extended feature with a few techniques.\\n')\n f.write('#Note that edge detection error in lat, lon is actually edge detection lat/lon err in x-hat, y-hat\\n')\n f.write(' '.join(rows)+'\\n')\n f.write(columns[0]+' '+str(maxloc[0])+' '+str(maxloc[1])+' '+str(maxlat[0])+' '+str(maxlon[0])+'\\n')\n f.write(columns[1]+' '+str(medposlist[0])+' '+str(medposlist[1])+' '+str(medposlist[2])+' '+str(medposlist[3])+'\\n')\n f.write(columns[2]+' '+str(meanposlist[0])+' '+str(meanposlist[1])+' '+str(meanposlist[2])+' '+str(meanposlist[3])+'\\n')\n f.write(columns[3]+' '+str(sigmaposlist[0])+' '+str(sigmaposlist[1])+' '+str(sigmaposlist[2])+' '+str(sigmaposlist[3])+'\\n')\n f.write(columns[4]+' '+str(minposlist[0])+' '+str(minposlist[1])+' '+str(minposlist[2])+' '+str(minposlist[3])+'\\n')\n f.write(columns[5]+' '+str(maxposlist[0])+' '+str(maxposlist[1])+' '+str(maxposlist[2])+' '+str(maxposlist[3])+'\\n')\n f.write(columns[6]+' '+str(xfg)+' '+str(yfg)+' '+str(latfg)+' '+str(lonfg)+'\\n')\n f.write(columns[7]+' '+str(g.x_stddev + 0)+' '+str(g.y_stddev + 0)+' '+str(-999)+' '+str(-999)+'\\n')\n f.write(columns[8]+' '+str(-999)+' '+str(-999)+' '+str(self.err_x[int(round(medposlist[0])),int(round(medposlist[1]))])+' '+str(self.err_y[int(round(medposlist[0])),int(round(medposlist[1]))])+'\\n')\n \n #replace Gaussian onto grid we had before for plotting\n eval_g = g(xx, yy)\n g_overlay = np.zeros(self.centered.shape)\n g_overlay[p0x:p1x,p0y:p1y] = eval_g\n #plot things up \n fig, (ax0) = plt.subplots(1,1, figsize = (8,5))\n ax0.imshow(region, origin = 'lower left')\n levels = [0.68, 0.815, 0.95]\n cs = ax0.contour(region/np.max(region), levels, colors = 'white')\n cs_g = ax0.contour(eval_g/np.max(eval_g), [0.68], colors = 'red')\n plt.show() \n \n \n def project(self, outstem = 'h', pixsz = None, interp = 'cubic'):\n '''Project the data onto a flat x-y grid.\n pixsz is in arcsec. if pixsz = None, translates the pixel scale\n of the image to a distance at the sub-observer point.\n interp asks whether to regrid using a nearest neighbor, linear, or cubic'''\n \n #determine the number of pixels in resampled image\n if pixsz == None:\n pixsz = self.pixscale_arcsec\n npix_per_degree = (1/self.deg_per_px) * (self.pixscale_arcsec / pixsz) # (old pixel / degree lat) * (arcsec / old pixel) / (arcsec / new pixel) = new pixel / degree lat\n npix = int(npix_per_degree * 180) + 1 #(new pixel / degree lat) * (degree lat / planet) = new pixel / planet\n print('New image will be %d by %d pixels'%(2*npix + 1, npix))\n print('Pixel scale %f km = %f pixels per degree'%(self.pixscale_km, npix_per_degree))\n \n #create new lon-lat grid\n extra_wrap_dist = 180\n newlon, newlat = np.arange(-extra_wrap_dist,360 + extra_wrap_dist, 1/npix_per_degree), np.arange(-90,90, 1/npix_per_degree)\n gridlon, gridlat = np.meshgrid(newlon, newlat)\n nans = np.isnan(self.lon_w.flatten())\n def input_helper(arr, nans):\n '''removing large region of NaNs speeds things up significantly'''\n return arr.flatten()[np.logical_not(nans)]\n inlon, inlat, indat = input_helper(self.lon_w, nans), input_helper(self.lat_g, nans), input_helper(self.centered, nans)\n\n #fix wrapping by adding dummy copies of small lons at > 360 lon\n inlon_near0 = inlon[inlon < extra_wrap_dist]\n inlon_near0 += 360\n inlon_near360 = inlon[inlon > 360 - extra_wrap_dist]\n inlon_near360 -= 360\n inlon_n = np.concatenate((inlon_near360, inlon, inlon_near0))\n inlat_n = np.concatenate((inlat[inlon > 360 - extra_wrap_dist], inlat, inlat[inlon < extra_wrap_dist]))\n indat_n = np.concatenate((indat[inlon > 360 - extra_wrap_dist], indat, indat[inlon < extra_wrap_dist]))\n\n #do the regridding\n datsort = griddata((inlon_n, inlat_n), indat_n, (gridlon, gridlat), method = interp)\n \n #trim extra data we got from wrapping\n wrap_i_l = len(gridlon[0][gridlon[0] < 0]) - 1\n wrap_i_u = len(gridlon[0][gridlon[0] >= 360])\n datsort = datsort[:,wrap_i_l:-wrap_i_u]\n gridlon = gridlon[:,wrap_i_l:-wrap_i_u]\n gridlat = gridlat[:,wrap_i_l:-wrap_i_u]\n \n # make far side of planet into NaNs\n snorm = surface_normal(gridlat, gridlon, self.ob_lon)\n #emang = emission_angle(self.ob_lat, snorm).T\n emang = emission_angle(self.ob_lat, snorm)\n farside = np.where(emang < 0.0)\n datsort[farside] = np.nan\n self.projected = datsort\n self.mu_projected = emang\n \n #write data to fits file \n hdulist_out = self.im.hdulist\n ## projected data\n hdulist_out[0].header['OBJECT'] = self.target+'_projected'\n hdulist_out[0].data = datsort\n hdulist_out[0].writeto(outstem + '_proj.fits', overwrite=True)\n ## emission angles\n hdulist_out[0].header['OBJECT'] = self.target+'_mu_proj'\n hdulist_out[0].data = emang\n hdulist_out[0].writeto(outstem + '_mu_proj.fits', overwrite=True)\n print('Writing files %s'%outstem + '_proj.fits and %s'%outstem + '_mu_proj.fits')\n \n def plot_projected(self, outfname, ctrlon = 180, lat_limits = [-90, 90], lon_limits = [0, 360], cbarlabel = 'I/F'):\n '''Once projection has been run, plot it using this function''' \n \n #apply center longitude to everything\n npix = self.projected.shape[1]\n npix_per_degree = 1.0 / self.deg_per_px\n print(npix_per_degree)\n offset = (ctrlon + 180)%360\n offsetpix = np.round(offset*npix_per_degree)\n uoffsetpix = npix - offsetpix\n newim = np.copy(self.projected)\n lefthalf = self.projected[:,:offsetpix]\n righthalf = self.projected[:,offsetpix:]\n newim[:,uoffsetpix:] = lefthalf #switch left and right halves\n newim[:,:uoffsetpix] = righthalf\n \n #extent = [ctrlon - 180, ctrlon + 180, -90, 90]\n extent = [ctrlon + 180, ctrlon - 180, -90, 90]\n parallels = np.arange(lat_limits[0],lat_limits[1] + 30, 30.)\n #meridians = np.arange(lon_limits[0],lon_limits[1] + 60, 60.)\n meridians = np.arange(lon_limits[1], lon_limits[0] - 60, -60.)\n \n #plot it\n fs = 14 #fontsize for plots\n fig, ax0 = plt.subplots(1,1, figsize = (10,7))\n \n cim = ax0.imshow(np.fliplr(newim), origin = 'lower left', cmap = 'gray', extent = extent)\n for loc in parallels:\n ax0.axhline(loc, color = 'cyan', linestyle = ':')\n for loc in meridians:\n ax0.axvline(loc, color = 'cyan', linestyle = ':')\n\n ax0.set_xlabel('Longitude (W)', fontsize = fs)\n ax0.set_ylabel('Latitude', fontsize = fs)\n ax0.set_ylim(lat_limits)\n ax0.set_xlim(lon_limits[::-1])\n ax0.set_title(self.date_time, fontsize = fs + 2)\n ax0.tick_params(which = 'both', labelsize = fs - 2)\n \n #plot the colorbar\n divider = make_axes_locatable(ax0)\n cax = divider.append_axes('right', size='5%', pad=0.05)\n cbar = fig.colorbar(cim, cax = cax, orientation = 'vertical')\n cbar.set_label(cbarlabel, fontsize = fs)\n cax.tick_params(which = 'both', labelsize = fs - 2)\n \n plt.savefig(outfname, bbox = None)\n plt.show()\n \n def feature_size_projected(self):\n '''Find a feature, tell how big it is in lat-lon space'''\n \n if not hasattr(self, 'projected'):\n print('Must run on projected data. Run coords.project() first. Returning')\n return\n \n plt.imshow(self.projected, origin = 'lower left')\n plt.show()\n print('Define a box around the feature you want to track. Note x,y are reversed in image due to weird Python indexing!')\n pix_l = input('Enter lower left pixel x,y separated by a comma: ')\n pix_u = input('Enter upper right pixel x,y separated by a comma: ')\n \n p0x, p0y = int(pix_l.split(',')[0].strip(', \\n')),int(pix_l.split(',')[1].strip(', \\n'))\n p1x, p1y = int(pix_u.split(',')[0].strip(', \\n')),int(pix_u.split(',')[1].strip(', \\n'))\n region = self.projected[p0x:p1x,p0y:p1y]\n \n def build_contour(rgn, frac):\n rgn = np.copy(rgn)\n rgn[rgn < frac*np.max(rgn)] = 0.0\n rgn[rgn > 0.0] = 1.0\n return rgn\n \n level = 0.5\n fwhm_2d = build_contour(region, level)\n \n # find the longest rays in the x and y direction across the amorphous fwhm region\n collapse_x = np.sum(fwhm_2d, axis = 1)\n collapse_y = np.sum(fwhm_2d, axis = 0)\n fwhm_x, wherefwhm_x = np.max(collapse_x), np.argmax(collapse_x)\n fwhm_y, wherefwhm_y = np.max(collapse_y), np.argmax(collapse_y)\n \n # convert to lat-lon\n deg_lat, deg_lon = fwhm_x * self.deg_per_px, fwhm_y * self.deg_per_px\n km_lat, km_lon = fwhm_x * self.pixscale_km, fwhm_y * self.pixscale_km\n print('%f degrees lat, %f degrees lon'%(deg_lat, deg_lon))\n print('%f km in zonal direction, %f km in meridional direction'%(km_lat, km_lon))\n \n # for plotting, find min point and max point for each of these rays\n ray_x = np.where(fwhm_2d[wherefwhm_x, :] == 1)[0]\n ray_y = np.where(fwhm_2d[:, wherefwhm_y] == 1)[0]\n \n plt.imshow(region, origin = 'lower left', cmap = 'gray')\n plt.contour(fwhm_2d, levels = [level], colors = ['red'])\n plt.plot(ray_x, np.full(ray_x.shape, wherefwhm_x), color = 'r', lw = 2)\n plt.plot(np.full(ray_y.shape, wherefwhm_y), ray_y, color = 'r', lw = 2)\n plt.title('%s'%self.date_time[:-6])\n plt.savefig('storm_size.png')\n plt.show()\n \n \n \n def help(self):\n \n helpstr = '''\n Contains tasks for image navigation, image projection, calculating I/F, and\n other things that require Horizons ephemeris data to compute\n \n Functions (see DOCUMENTATION.py for use):\n ioverf(self, filt, flux_per, stand_airmass)\n write_photonly(self, outstr)\n edge_detect(self, low_thresh = 0.01, high_thresh = 0.05, sigma = 5, plot = True)\n edge_detect_error(self, niter, perturb_l, perturb_dist, low_thresh = 0.002, dist = 0.02, sigma = 5, doplot = True)\n manual_shift(self,dx,dy)\n plot_latlon(self)\n write(self, lead_string)\n bootstrap_func(self, order = 2)\n locate_feature(self, outfile=None)\n project(self, outstem = 'h', pixsz = None, interp = 'cubic')\n plot_projected(self, outfname, ctrlon = 180, lat_limits = [-90, 90], lon_limits = [0, 360], cbarlabel = 'I/F')\n \n Attributes:\n im: image object for infile\n req: equatorial radius\n rpol: polar radius\n data: the image data\n pixscale_arcsec: pixel scale of image in arcsec\n target: name of planet\n date_time: datetime object for start time\n airmass:\n ang_diam:\n ob_lon: sub observer longitude\n ob_lat: sub observer latitude\n sun_lon: sub solar longitude\n sun_lat: sub solar latitude\n np_ang: north pole position angle (CCW, or east, wrt celestial north)\n np_dist: angular dist of np from sub observer point\n sun_dist: distance from target to sun\n dist: distance from target to observer \n pixscale_km: pixel scale of image in km\n deg_per_px: lat/lon degrees on planet per pixel at sub obs point\n lat_g: grid of planetographic latitudes on planet\n lat_c: grid of planetocentric latitudes on planet\n lon_w: grid of west longitudes on planet (west for IAU standard, as output by Horizons)\n err_x: lat/lon error from navigation in x direction, in px\n err_y: lat/lon error from navigation in y direction, in px\n centered: centered data after edge detection\n model_planet: ellipse with planet's projected shape based on ephemeris\n projected: image on regular lat/lon grid after projection\n mu: grid of emission angles on planet\n surf_n: grid of normal vectors to the surface of planet\n x_shift: pixel shift in x direction from edge detect\n y_shift: pixel shift in x direction from edge detect\n edges: map of edges found by edge detect\n '''\n print(helpstr)\n \n \n \n \n \n ''' \n def change_projection(self):\n not written yet but would use basemap, or Charles Goullaud replacement, to reproject arbitrarily\n \n ''' \n ","sub_path":"coordgrid.py","file_name":"coordgrid.py","file_ext":"py","file_size_in_byte":44351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"252174803","text":"import sys\nimport json\nimport re\nimport os\n\ncompanion_data_dir = sys.argv[1]\noutdir = sys.argv[2]\nhyphen_re = re.compile(r'[–—−]')\nfor filename in os.listdir(companion_data_dir):\n mrp_companion = {}\n with open(companion_data_dir+filename) as infile:\n for line in infile:\n if line.startswith('#'):\n id = line[1:].strip()\n mrp_companion[id] = {'tokenization':[], 'spans':{}}\n elif not line.startswith('\\n'):\n line = line.split()\n token = line[1]\n token = re.sub(r'[–—−]', '-', token).lower()\n if \"’\" in token:\n token = token.replace(\"’\", \"'\")\n #if \"”\" in token:\n # token = token.replace(\"”\", '\"')\n #if \"“\" in token:\n # token = token.replace(\"“\", '\"')\n if \"…\" in token:\n token = token.replace(\"…\", \"...\")\n #if '-' in token:\n # token = token.replace('-', '—')\n mrp_companion[id]['tokenization'].append(token)\n span = line[-1][11:]\n index = line[0]\n mrp_companion[id]['spans'][span] = int(index) -1\n json.dump(mrp_companion, open(outdir+ filename[:-7]+'.json', 'w', encoding='utf8'), ensure_ascii=False)\n","sub_path":"ucca/get_companion_tokenization.py","file_name":"get_companion_tokenization.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"500675045","text":"#OOPR-Assgn-10\r\n\r\nclass CallDetail:\r\n def __init__(self,phoneno,called_no,duration,call_type):\r\n self.__phoneno=phoneno\r\n self.__called_no=called_no\r\n self.__duration=duration\r\n self.__call_type=call_type \r\n \r\n \r\nclass Util:\r\n def __init__(self):\r\n self.list_of_call_objects=None\r\n\r\n def parse_customer(self,list_of_call_string):\r\n self.list_of_call_objects=[]\r\n b=[]\r\n for i in list_of_call_string:\r\n b.append(i.split(','))\r\n a=b\r\n for i in range(0,len(a)):\r\n self.list_of_call_objects.append(CallDetail(a[i][0],a[i][1],a[i][2],a[i][3]))\r\n return self.list_of_call_objects\r\ncall='9990000001,9330000001,23,STD'\r\ncall2='9990000001,9330000002,54,Local'\r\ncall3='9990000001,9330000003,6,ISD'\r\n\r\nlist_of_call_string=[call,call2,call3]\r\nUtil().parse_customer(list_of_call_string)\r\n\r\n","sub_path":"OOPS/day2/Assignment10.py","file_name":"Assignment10.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"64247508","text":"from flask import Flask, redirect, url_for, render_template, jsonify, request\nimport os\n\napp = Flask(__name__, static_url_path=\"/static\")\n\n@app.route(\"/\", methods=[\"GET\"])\ndef blank():\n return redirect(\"/whoops/\")\n\n@app.route(\"//\", methods=[\"GET\"])\ndef main(location):\n pages = [\"home\", \"upcoming_events\", \"current_members\", \"contact_us\"]\n if location not in pages:\n location = \"whoops\"\n cocntents = \"\"\n realpath = os.path.dirname(os.path.realpath(__file__))+\"/templates/\"\n with open(realpath+location+\".html\", \"r\") as fin:\n contents = fin.read()\n pretty = {\n \"home\": \"Home\",\n \"upcoming_events\": \"Upcoming Events\",\n \"current_members\": \"Current Members\",\n \"contact_us\": \"Contact Us\",\n \"whoops\": \"Whoops\"\n }\n return render_template(\"index.html\", url=location, page=pretty[location], html=contents)\n\n@app.route(\"/load_page/\", methods=[\"GET\"])\ndef load_page():\n print(\"here\")\n return jsonify(url=request.args[\"goal\"], page=request.args[\"goal\"], html=\"WORKED
\")\n\nif __name__ == \"__main__\":\n app.run(debug=True, threaded=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"237495494","text":"# coding:utf-8\n\nfrom flask import Blueprint, request, jsonify\n\nfrom ..service import locationService\nfrom ..results import multi_location_result\nfrom ..helpers import crossdomain\n\nbp = Blueprint('location_user', __name__, url_prefix=\"/locations\")\n\n\n@bp.route(\"/search_by_geo\", methods=[\"GET\"])\n@crossdomain(origin=\"*\")\ndef search_article_by_geo():\n poi_longitude = float(request.args.get(\"longitude\")) if request.args.get(\"longitude\") else None\n poi_latitude = float(request.args.get(\"latitude\")) if request.args.get(\"latitude\") else None\n poi_distance = float(request.args.get(\"distance\")) if request.args.get(\"distance\") else None\n location_id_list = locationService. \\\n location_id_by_geo(poi_longitude=poi_longitude, poi_latitude=poi_latitude, poi_distance=poi_distance)\n\n location_list = multi_location_result(location_id_list)\n return jsonify(data=dict(locations=location_list, success=True))","sub_path":"program/frontend/location_user.py","file_name":"location_user.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"375700840","text":"from minesweeper import Board\nimport curses\n\n_UP = \"up\"\n_DOWN = \"down\"\n_RIGHT = \"right\"\n_LEFT = \"left\"\n\nclass MineBoardKey(Board):\n def __init__(self, width, height, mines):\n Board.__init__(self, width, height, mines)\n curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)\n self.colormap = {'n':curses.color_pair(1), 'h':curses.color_pair(2)}\n self.marker = [0,0]\n\n def move_marker(self, direction):\n \"\"\" move marker over board \"\"\"\n if direction == _UP and self.marker[1]+1 < self.height:\n self.marker[1] += 1\n elif direction == _DOWN and self.marker[1] > 0:\n self.marker[1] += -1\n elif direction == _LEFT and self.marker[0] > 0:\n self.marker[0] += -1\n elif direction == _RIGHT and self.marker[0]+1 < self.width:\n self.marker[0] += 1\n \n def keypress(self, c):\n \"\"\" deals with keypresses \"\"\"\n if c == ord('q'):\n return None\n elif c == 259:\n self.move_marker(_DOWN)\n elif c == 258:\n self.move_marker(_UP)\n elif c == 260:\n self.move_marker(_LEFT)\n elif c == 261:\n self.move_marker(_RIGHT)\n elif c == ord('d'):\n self.reveal(self.marker[0], self.marker[1])\n elif c == ord('s'):\n self.switchMark(self.marker[0], self.marker[1])\n elif c == ord('r'):\n self.reset()\n \n return self\n\n def print_to_screen(self, screen):\n \"\"\" prints itself to the curses screen \"\"\"\n h = \"arrows to move, q to return, r to reveal, e to mark\"\n screen.addstr(1,2,h)\n n = 5\n\n for i in xrange(self.width):\n for j in xrange(self.height):\n if [i,j] == self.marker:\n color = self.colormap[\"h\"]\n else:\n color = self.colormap[\"n\"]\n screen.addstr(n+j, i+1, str(self.board[i][j]), color)\n \n","sub_path":"games/minesweeperkey.py","file_name":"minesweeperkey.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"641752727","text":"from __future__ import print_function\nimport argparse\nimport sys\nimport os\nfrom glob import glob\nimport webbrowser\nfrom datetime import datetime\n\nfrom auth import get_anon_client, log_in\nfrom utils import get_metadata\n\n# file extensions accepted by imgur\nfile_extensions = ['.png', '.jpg', '.gif', '.tif',\n '.bmp', '.tiff', '.pdf', '.xcf']\n\n\nclass Uploader:\n\n \"\"\"A class that interacts with imgur's api in order to\n upload local images to imgur.com from the command line.\n \"\"\"\n\n def __init__(self, args):\n self.args = args\n self.metadata = dict(title=self.args.title,\n description=self.args.description)\n self.init_client()\n\n def init_client(self):\n \"\"\"Sets ImgurClient scope based on user preference\"\"\"\n self.client = get_anon_client()\n if self.args.user:\n self.client = log_in(self.client)\n\n def upload_pic(self, path, data, album_id=None):\n # as of now, does not check for valid file extension\n anon = self.client.auth is None\n if album_id:\n data['album'] = album_id\n image = self.client.upload_from_path(path, data, anon)\n\n self.log_upload(image)\n\n return image['id'] # return image if more data is needed\n\n def upload_album(self):\n album_data = get_metadata(\n True) if self.args.metadata else self.metadata\n album = self.client.create_album(album_data)\n print('Created album named \"{}\"'.format(album_data.get('title')))\n self.log_upload(album)\n\n album_id = album['id'] if self.client.auth else album['deletehash']\n\n # get all images in the folder with approved file extensions\n files = [glob(os.path.join(self.args.path, '*' + ext))\n for ext in file_extensions]\n files = sum(files, []) # ugly way to flatten list\n\n for f in files:\n print('Uploading {}'.format(os.path.basename(f)))\n img_data = get_metadata() if self.args.metadata else dict()\n self.upload_pic(f, img_data, album_id)\n\n return album['id'] # return album if more data is needed\n\n def log_upload(self, entity):\n \"\"\"Record time of upload and deletion links of upload in\n local file log.txt\n \"\"\"\n with open('log.txt', 'a+') as f:\n deletehash = entity['deletehash']\n link = 'http://imgur.com/delete/{}'.format(deletehash)\n record = '{} {}'.format(datetime.now().strftime('%c'), link)\n f.write(record+'\\n')\n return link\n\n def main(self):\n args = self.args\n if args.screenshot:\n if args.path.endswith('.png') or args.path.endswith('.bmp'):\n from screenshot import take_screenshot\n take_screenshot(args.path, args.delay)\n pic_id = self.upload_pic(args.path, self.metadata)\n print('Upload complete.')\n webbrowser.open(self.client.get_image(pic_id).link)\n else:\n sys.exit('File must be saved as a bitmap or png.')\n\n elif os.path.isfile(args.path):\n pic_id = self.upload_pic(args.path, self.metadata)\n print('Upload complete.')\n webbrowser.open(self.client.get_image(pic_id).link)\n\n elif os.path.isdir(self.args.path):\n album_id = self.upload_album()\n print('Upload complete.')\n webbrowser.open(self.client.get_album(album_id).link)\n\n else:\n sys.exit(\"\\nWhat you are trying to upload does not exist\")\n\n\nif __name__ == \"__main__\":\n description = \"\"\"A command line wrapper for imgur's api\"\"\"\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('path', action='store',\n help='path to file or folder to upload')\n parser.add_argument('-t', '--title',\n action='store', help='title of upload')\n parser.add_argument('-d', '--description',\n action='store', help='upload description')\n parser.add_argument('-u', '--user', action='store_true',\n help='upload to stored user account')\n parser.add_argument('-m', '--metadata', action='store_true',\n help='add data to images when uploading album')\n parser.add_argument('-s', '--screenshot', action='store_true',\n help='take screenshot and upload it')\n parser.add_argument('--delay', default=3, type=int,\n help='delay (s) before taking screenshot')\n args = parser.parse_args()\n Uploader(args=args).main()\n","sub_path":"climgur/climgur.py","file_name":"climgur.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"466940988","text":"class Solution(object):\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l, r = 0, len(nums) - 1\n if r == 0: return nums[0]\n while r - l >= 2:\n mid = (l + r) // 2\n if nums[mid] > nums[l]:\n l = mid\n elif nums[mid] < nums[r]:\n r = mid\n mid = (l + r) // 2 \n return min(nums[(mid + 1) % len(nums)], nums[(mid + 2) % len(nums)]) # nums[mid + 1 + 1] for no-rotation case.\n\n\nif __name__ == '__main__':\n # inputs\n nums = list(range(10))\n k = 0\n nums = nums[-k:] + nums[:-k]\n print(nums)\n print('-' * 30)\n res = Solution().findMin(nums)\n print(res)\n ","sub_path":"153_findMin.py","file_name":"153_findMin.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"479869104","text":"import asyncio\nimport aioredis\n\n\nREDIS_SERVER = ('localhost', 6379)\n\n\nasync def run():\n print('[~] start connection to Redis server')\n redis = await aioredis.create_redis(REDIS_SERVER)\n\n print('[~] connection established')\n print(str.format('[~] Redis database: {}', redis.db))\n\n await redis.delete('foo', 'bar')\n\n tr = redis.multi_exec()\n tr.incr('foo')\n tr.incr('bar')\n\n await tr.execute()\n redis.close()\n\n print(str.format('[~] Redis connection is closed: {}', redis.closed))\n\n await redis.wait_closed()\n\n\ndef main():\n loop = asyncio.get_event_loop()\n\n try:\n loop.run_until_complete(run())\n except KeyboardInterrupt:\n print('[x] Event loop interrupted by Ctrl + C')\n finally:\n print('[x] Event loop is closed')\n loop.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"packages/async_packages/aioredis_package/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"239048917","text":"def min(arr):\r\n amin = arr[0]\r\n for i in arr:\r\n if i < amin:\r\n amin = i\r\n return amin\r\n\r\ndef avg(arr):\r\n s = 0\r\n for i in arr:\r\n s += i\r\n return s//len(arr)\r\n\r\narr1 = [10,8,12,0]\r\nprint(min(arr1))\r\nprint(avg(arr1))\r\n\r\n","sub_path":"LICENSE.md/arr_algs.py","file_name":"arr_algs.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"21355415","text":"import numpy as np\nfrom sigmoid import sigmoid_\n\ndef vec_reg_logistic_grad(y, x, theta, lambda_):\n \"\"\"Computes the regularized linear gradient of three non-empty numpy.ndarray, without any for-loop. The three arrays must have compatible dimensions.\"\"\"\n if isinstance(x, np.ndarray) == 1 and isinstance(y, np.ndarray) == 1 and isinstance(theta, np.ndarray) == 1:\n if isinstance(lambda_, (int, float)) == 1:\n if len(y) == len(x) and len(x[0]) == len(theta):\n y_pred = sigmoid_(np.dot(x, theta))\n temp = np.dot(x.T, (y_pred - y)) / len(x)\n res = np.dot(x.T, (y_pred - y)) / len(x) + np.dot(lambda_ / len(x), theta)\n res[0] = temp[0]\n return (res)\n else:\n print(\"vec_reg_log_gradient: error in size of x, y or theta\")\n else:\n print(\"vec_reg_log_gradient: lamda is not a scalar\")\n else:\n print(\"vec_reg_log_gradient: error in type of x, y or theta\")\n\nX = np.array([\n [ -6, -7, -9],\n [ 13, -2, 14],\n [ -7, 14, -1],\n [ -8, -4, 6],\n [ -5, -9, 6],\n [ 1, -5, 11],\n [ 9, -11, 8]])\nY = np.array([1,0,1,1,1,0,0])\nZ = np.array([1.2,0.5,-0.32])\n\nprint(vec_reg_logistic_grad(Y, X, Z, 1))\nprint(vec_reg_logistic_grad(Y, X, Z, 0.5))\nprint(vec_reg_logistic_grad(Y, X, Z, 0.0))\n","sub_path":"day03/ex07/vec_reg_linear_grad.py","file_name":"vec_reg_linear_grad.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"401918244","text":"\"\"\"\nOpens up magnetometer, inclinometer, and stepper motor HDF5 files. \nCalculates heading (magnetic and true) with tilt compensation. \nAlso calculates inclination based on elevation motor movement.\n\nSummer 2021\nTested On:\nStarfire (ubuntu 18.04)\nInflux 2.0.4\nGrafana 7.4.2\n\"\"\"\n\nimport serial\nimport numpy as np\nimport h5py\nimport time\nimport math\nimport requests\nimport sys\nimport os\nimport glob\n\n\n\n\"\"\"---Authorization/QUERY initialization---\"\"\"\n#Starting with Influx 2.0, authorization tokens are necessary to access databases\n#Stringing together query access\nINFLUX_TOKEN='AjsrNgY_k97FMvgfCsgc2tPTx-lOVM-aYaCMjymNVIWpoSCkYh7H4AqIV9pLQHHk07zJa5pxTn4lo-3Ashwu5Q=='\nORG=\"tim@upenn\"\nINFLUX_CLOUD_URL='localhost'\nBUCKET_NAME='sensors'\n\n#Can change precision if needed. Currently set to nanoseconds (ns).\nQUERY_URI='http://{}:8086/api/v2/write?org={}&bucket={}&precision=ns'.format(INFLUX_CLOUD_URL,ORG,BUCKET_NAME)\n\nheaders = {}\nheaders['Authorization'] = 'Token {}'.format(INFLUX_TOKEN)\n\n#Parameters for line protocol that will be sent to Influx\nlocation_tag = 'lab'\nmeasurement_name = 'heading'\n\n\n\"\"\"---Open Files---\"\"\"\nstart_time = time.perf_counter()\ndatestamp = time.strftime(\"%Y-%m-%d\")\n\n\n#A series of directory checks. Will exit from program if no folder/files are detected.\nif os.path.isdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Mag\") == 0:\n print(\"No Directory Detected\")\n sys.exit()\n \nif os.path.isdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Inclin\") == 0:\n print(\"No Directory Detected\")\n sys.exit()\nif os.path.isdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Stepper\") == 0:\n print(\"No Directory Detected\")\n sys.exit()\n\n\nif len(os.listdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Mag\")) == 0:\n print(\"No Files Detected\")\n sys.exit()\nelse:\n file_list = glob.glob(\"/home/user/tim-daq/data/\"+datestamp+\"-Mag/*.hdf5\")\n mag_file_name = max(file_list, key=os.path.getctime)\n #print(mag_file_name)\n \nif len(os.listdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Inclin\")) == 0:\n print(\"No Files Detected\")\n sys.exit()\nelse:\n file_list = glob.glob(\"/home/user/tim-daq/data/\"+datestamp+\"-Inclin/*.hdf5\")\n inclin_file_name = max(file_list, key=os.path.getctime)\n #print(inclin_file_name)\nif len(os.listdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Stepper\")) == 0:\n print(\"No Files Detected\")\n sys.exit()\nelse:\n file_list = glob.glob(\"/home/user/tim-daq/data/\"+datestamp+\"-Stepper/*.hdf5\")\n stepper_file_name = max(file_list, key=os.path.getctime)\n #print(inclin_file_name)\n \n\n#Opens HDF5 files \nmag_file = h5py.File(mag_file_name, 'r', libver = 'latest', swmr = True)\ninclin_file = h5py.File(inclin_file_name, 'r', libver = 'latest', swmr = True)\nstepper_file = h5py.File(stepper_file_name, 'r', libver = 'latest', swmr = True)\n\n#Opens appropriate datasets\nmag_x = mag_file['x']\nmag_len = mag_x.shape[0]\nmag_y = mag_file['y']\nmag_z = mag_file['z']\nmag_timestamp = mag_file['time']\n\ninclin_x = inclin_file['x']\ninclin_y = inclin_file['y']\ninclin_len = inclin_x.shape[0]\n\nstepper_az = stepper_file['az']\nstepper_el = stepper_file['el']\nstepper_len = stepper_az.shape[0]\n\nmag_heading_list = [] \ntrue_heading_list = []\nel_list = []\nzero_mag_deg = 0\nzero_true_deg = 0\nzero_el = 0\n\n\n\"\"\"---Main Loop---\"\"\"\nwhile True:\n \n #Grabs the latest data point index (from file dataset)\n mag_index_num = mag_file['index'][0] \n inclin_index_num = inclin_file['index'][0]\n stepper_index_num = stepper_file['index'][0]\n \n #Must refresh constantly..\n mag_file['index'].id.refresh()\n mag_x.id.refresh()\n mag_y.id.refresh()\n mag_z.id.refresh()\n mag_timestamp.refresh()\n \n inclin_file['index'].id.refresh()\n inclin_x.id.refresh()\n inclin_y.id.refresh()\n \n stepper_file['index'].id.refresh()\n stepper_az.id.refresh()\n stepper_el.id.refresh()\n \n #Creates list copies\n mag_x_list = mag_x[:]\n mag_y_list = mag_y[:]\n mag_z_list = mag_z[:]\n mag_timestamp_list = mag_timestamp[:]\n inclin_x_list = inclin_x[:]\n inclin_y_list = inclin_y[:]\n stepper_az_list = stepper_az[:]\n stepper_el_list = stepper_el[:]\n \n #Grabs latest data values\n mag_x_dat = mag_x_list[mag_index_num]\n mag_y_dat = mag_y_list[mag_index_num]\n mag_z_dat = mag_z_list[mag_index_num]\n mag_timestamp_dat = mag_timestamp_list[mag_index_num]\n \n inclin_x_dat = inclin_x_list[inclin_index_num]\n inclin_y_dat = inclin_y_list[inclin_index_num]\n\n stepper_az_dat = stepper_az_list[stepper_index_num]\n stepper_el_dat = stepper_el_list[stepper_index_num]\n \n\t\n###Heading calculations###\n declination = 11 #Found declination value online.\n \n pitch = np.deg2rad(inclin_y_dat)\n roll = -np.deg2rad(inclin_x_dat)\n\n #Calculate X and Y components of Magnetic North vector, with tilt compensation from inclinometer data \n Xh = mag_x_dat * np.cos(pitch) + mag_y_dat * np.sin(roll) * np.sin(pitch) - mag_z_dat * np.cos(roll) * np.sin(pitch) \n Yh = mag_y_dat * np.cos(roll) + mag_z_dat * np.sin(roll)\n \n \n magnetic_north = np.rad2deg(math.atan2(Yh,Xh))\n true_north = magnetic_north - declination\n \n if magnetic_north < 0: #Converts from -180-180 range to 0-360 range\n magnetic_north += 360\n if true_north < 0:\n true_north += 360\n \n #Generates a \"zero\" heading/elevatoin reading at the start of program. Future changes in angle will be added to this \"zero\" value.\n while time.perf_counter() - start_time< .05: \n mag_heading_list.append(magnetic_north)\n true_heading_list.append(true_north)\n el_list.append(inclin_x_dat)\n\n zero_mag_deg = mag_heading_list[-1]\n zero_true_deg = true_heading_list[-1]\n zero_el = el_list[-1]\n \n \n \n stepper_heading_mag = zero_mag_deg - stepper_az_dat\n if stepper_heading_mag < 0: #Converts from -180-180 range to 0-360 range\n stepper_heading_mag += 360\n stepper_elevation = zero_el - stepper_el_dat\n\n###Pushing to Influx and Grafana###\n #Line protocol setup\n line = '{measurement},location={location} mag_heading={heading},true_heading={heading2},stepper_heading_mag={heading3},elevation={elevation} {timestamp}'.format(measurement=measurement_name,location=location_tag, heading=magnetic_north,heading2=true_north,heading3 = stepper_heading_mag,elevation = stepper_elevation, timestamp=mag_timestamp_dat)\n \n #Sends data into Influx\n r = requests.post(QUERY_URI, data=line, headers=headers)\n #print(r.status_code)\n #print(line)\n \n \n #Once the end of the file has been reached, get ready to open the new one.\n if mag_index_num >= mag_len - 2:\n \n next_file_num = mag_file['filenames'][1] #Next file number taken from current open file\n next_file = str(next_file_num)\n \n mag_index_num = 0\n \n \n #Check if the next file (with correct number) exists\n file_path = \"/home/user/tim-daq/data/\"+datestamp+\"-Mag/\"+\"*\"+next_file.zfill(5)+\"*\"\n while glob.glob(file_path) == []: #If it doesn't exist, wait\n time.sleep(0.05)\n \n mag_file.close() #Close current file\n \n\n #Opens the next HDF5 file \n mag_file = h5py.File(glob.glob(file_path)[0], 'r', libver = 'latest', swmr = True)\n mag_x = mag_file['x']\n mag_len = mag_x.shape[0]\n mag_y = mag_file['y']\n mag_z = mag_file['z']\n mag_timestamp = mag_file['time']\n \n #Repeat for other sensor files.\n if inclin_index_num >= inclin_len -1:\n next_file_num = inclin_file['filenames'][1]\n next_file = str(next_file_num)\n inclin_index_num = 0\n \n \n file_path = \"/home/user/tim-daq/data/\"+datestamp+\"-Inclin/\"+\"*\"+next_file.zfill(5)+\"*\"\n while glob.glob(file_path) == []:\n time.sleep(0.05) \n inclin_file.close()\n \n inclin_file = h5py.File(glob.glob(file_path)[0], 'r', libver = 'latest', swmr = True)\n inclin_x = inclin_file['x']\n inclin_len = inclin_x.shape[0]\n inclin_y = inclin_file['y'] \n \n\n if stepper_index_num >= stepper_len - 2:\n next_file_num = stepper_file['filenames'][1]\n next_file = str(next_file_num)\n stepper_index_num = 0\n \n \n file_path = \"/home/user/tim-daq/data/\"+datestamp+\"-Stepper/\"+\"*\"+next_file.zfill(5)+\"*\"\n while glob.glob(file_path) == []:\n time.sleep(0.05) \n stepper_file.close()\n stepper_file = h5py.File(glob.glob(file_path)[0], 'r', libver = 'latest', swmr = True)\n stepper_az = stepper_file['az']\n stepper_el = stepper_file['el']\n stepper_len = stepper_az.shape[0]\n \n \n\n","sub_path":"HDF5_calculations.py","file_name":"HDF5_calculations.py","file_ext":"py","file_size_in_byte":8719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"469169186","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /home/jesse/code/confab/confab/tests/data/default/example.py\n# Compiled at: 2013-05-14 18:47:53\nenvironmentdefs = {'environment1': [\n 'host1', 'host2']}\nroledefs = {'role1': [\n 'host1']}\ncomponentdefs = {'role1': [\n 'component1']}","sub_path":"pycfiles/confapp-1.1.11-py3-none-any/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"53309350","text":"\"Helper functions for runfiles\"\n\ndef CopyRunfiles(ctx, runfiles, copy, symlink, executable, subdir):\n \"\"\"Copies all runfile to the same directory and returns new runfiles \n\n Args:\n ctx: [DotnetContext](api.md#DotnetContext)\n runfiles: depset(File) to copy to target directory of executable\n copy: target for utility copy tool\n symlink: target for utility symlink tool\n executable: [DotnetLibrary](api.md#DotnetLibrary) which directory is used as a base dir for the runfiles\n subdir: additional subdirectory to copy files to\n\n Returns:\n [runfiles](https://docs.bazel.build/versions/master/skylark/lib/runfiles.html)\n \"\"\"\n copied = {}\n created = []\n nocopy_dir = executable.result.dirname\n for f in runfiles.files.to_list():\n found = copied.get(f.basename)\n if found:\n continue\n copied[f.basename] = True\n\n if f.basename == \"mono\" or f.basename == \"mono.exe\":\n newfile = ctx.actions.declare_file(subdir + f.basename)\n ctx.actions.run(\n outputs = [newfile],\n inputs = [f] + symlink.files.to_list(),\n executable = symlink.files.to_list()[0],\n arguments = [newfile.path, f.path],\n mnemonic = \"LinkFile\",\n )\n created.append(newfile)\n elif f.dirname != nocopy_dir:\n if f.basename.find(\"hostfxr\") >= 0:\n version = f.path.split(\"/\")\n newfile = ctx.actions.declare_file(\"{}/host/fxr/{}/{}\".format(subdir, version[-2], version[-1]))\n else:\n newfile = ctx.actions.declare_file(subdir + f.basename)\n ctx.actions.run(\n outputs = [newfile],\n inputs = [f] + copy.files.to_list(),\n executable = copy.files.to_list()[0],\n arguments = [newfile.path, f.path],\n mnemonic = \"CopyFile\",\n )\n created.append(newfile)\n else:\n created.append(f)\n\n return ctx.runfiles(files = created)\n\ndef CopyDataWithDirs(dotnet, data_with_dirs, copy, subdir):\n \"\"\" Handles data targets provided with directories. Returns runfiles.\n\n Args:\n dotnet: DotnetContextInfo provider\n data_with_dirs: dict(Taret, string)\n copy: program to use for copying files\n subdir: subdirectory to use when placing provider data files\n\n Returns:\n [runfiles](https://docs.bazel.build/versions/master/skylark/lib/runfiles.html)\n\n \"\"\"\n copied = {}\n created = []\n for (k, v) in data_with_dirs.items():\n for f in k.files.to_list():\n targetpath = subdir + \"/\" + v + \"/\" + f.basename\n found = copied.get(targetpath)\n if found:\n continue\n copied[targetpath] = True\n\n newfile = dotnet.actions.declare_file(targetpath)\n dotnet.actions.run(\n outputs = [newfile],\n inputs = [f] + copy.files.to_list(),\n executable = copy.files.to_list()[0],\n arguments = [newfile.path, f.path],\n mnemonic = \"CopyFile\",\n )\n created.append(newfile)\n\n return dotnet._ctx.runfiles(files = created)\n","sub_path":"dotnet/private/rules/runfiles.bzl","file_name":"runfiles.bzl","file_ext":"bzl","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"298278969","text":"import pandas as pd\nimport json\n\nfilename='zone5'\ninfo = json.load(open(filename))\n\ntab=pd.read_csv('eplusout.csv')\n\n# solar radiation\t\nsol=[]\nfor key in info[\"solar\"]:\n sol.append(info[\"solar\"][key])\n\n# zone information\nzones=[]\nfor key in sorted(info[\"inputs\"][\"zones\"]):\n zones.append(info[\"inputs\"][\"zones\"][key])\n\nadjzones=[]\nfor key in sorted(info[\"inputs\"][\"adjzones\"]):\n adjzones.append(info[\"inputs\"][\"adjzones\"][key])\n \n# terminal information\ntermoutlet=[]\nfor key in sorted(info[\"inputs\"][\"termoutlet\"]):\n termoutlet.append(info[\"inputs\"][\"termoutlet\"][key])\n \n\ntout=info[\"tout\"]\n#hsp=info[\"hsp\"]\n\n\nzmt=[]\nadjt=[]\nzmdm=[] # zone supply air flow rate\nzmdt=[] # zone supply air temperature\nint=[] # internal load\ninlet=[] # reheat coil inlet water temperature\noutlet=[] # reheat coil outlet water temperature\nmrh=[] # reheat coil water mass flow rate\n#rh=[]\n#sol=['Environment:Site Diffuse Solar Radiation Rate per Area [W/m2](TimeStep)','Environment:Site Direct Solar Radiation Rate per Area [W/m2](TimeStep)']\nfor i in range(len(zones)):\n zmt.append(str(zones[i]).upper()+':Zone Mean Air Temperature [C](TimeStep)')\n int.append(str(zones[i]).upper()+':Zone Total Internal Total Heating Rate [W](TimeStep)')\n zmdm.append(str(termoutlet[i]).upper()+':System Node Mass Flow Rate [kg/s](TimeStep)')\n zmdt.append(str(termoutlet[i]).upper()+':System Node Temperature [C](TimeStep)')\n# inlet.append(str(rhtinlet[i]).upper()+':System Node Temperature [C](TimeStep)')\n# outlet.append(str(rhtoutlet[i]).upper()+':System Node Temperature [C](TimeStep)')\n# mrh.append(str(rhtoutlet[i]).upper()+':System Node Mass Flow Rate [kg/s](TimeStep)')\n #rh.append(str(zones[i]).upper()+' RHT COIL:Heating Coil Heating Rate [W](TimeStep)')\nfor i in range(len(adjzones)):\n adjt.append(str(adjzones[i]).upper()+':Zone Mean Air Temperature [C](TimeStep)')\n\ntab['t1']=[0]*len(tab)\ntab['m1']=[0]*len(tab)\ntab['i']=[0]*len(tab)\ntab['s']=[0]*len(tab)\ntab['adjt']=[0]*len(tab)\n\nfor i in range(len(zones)):\n tab['t1']=tab['t1']+tab[zmt[i]]*tab[zmdm[i]]\n tab['i']=tab['i']+tab[int[i]]\n tab['m1']=tab['m1']+tab[zmdm[i]]\n\nfor i in range(len(adjzones)):\n tab['adjt']=tab['adjt']+tab[adjt[i]]\n\nfor i in range(len(sol)):\t\n tab['s']=tab['s']+tab[sol[i]]\t\n\t\n\t\ntab2=pd.DataFrame()\n\n#for j in range(len(walls)):\n# tab2['w'+str(j)]=tab['w'+str(j+1)]\ntab2['tout']=tab[tout]\ntab2['s']=tab['s']\ntab2['i']=tab['i']\ntab2['t1']=tab['t1']/tab['m1']\n\n# adjacent zone temperatures\ntab2['t2']=(tab[adjt[0]]+tab[adjt[1]]+tab[adjt[2]]+tab[adjt[3]])/4\ntab2['t3']=tab[adjt[4]]\n#tab2['t2']=tab['adjt']/5\n#for i in range(len(adjzones)):\n# name='t'+str(i+2)\n# tab2[name]=tab[adjt[i]]\n\n\ntab2['m']=tab[zmdm[0]]\ntab2['tret']=tab[zmdt[0]]\n #name='rh'+str(i)\n #tab2[name]=tab[mrh[i]]*(tab[inlet[i]]-tab[outlet[i]])*4200\n#tab2['rh']=tab['rh']\n\n\n\ntab2.to_csv(filename+'rawdata.csv')\n","sub_path":"office/winter/option4/sine_sp/data_process_plenum_o31.py","file_name":"data_process_plenum_o31.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"32049110","text":"import tensorflow as tf\nfrom tensorflow.contrib import slim\n\nfrom .base_model import BaseModel, Mode\nfrom .backbones import resnet_v1 as resnet\n\n\ndef normalize_image(image, pixel_value_offset=128.0, pixel_value_scale=128.0):\n return tf.div(tf.subtract(image, pixel_value_offset), pixel_value_scale)\n\n\nclass Delf(BaseModel):\n input_spec = {\n 'image': {'shape': [None, None, None, None], 'type': tf.float32}\n }\n required_config_keys = []\n default_config = {\n 'normalize_input': False,\n 'use_attention': False,\n 'attention_kernel': 1,\n 'normalize_average': True,\n 'normalize_feature_map': True\n }\n\n def _model(self, inputs, mode, **config):\n image = inputs['image']\n if image.shape[-1] == 1:\n image = tf.tile(image, [1, 1, 1, 3])\n if config['normalize_input']:\n image = normalize_image(image)\n\n with slim.arg_scope(resnet.resnet_arg_scope()):\n _, encoder = resnet.resnet_v1_50(image,\n is_training=(mode == Mode.TRAIN),\n global_pool=False,\n scope='resnet_v1_50')\n feature_map = encoder['resnet_v1_50/block3']\n\n if config['use_attention']:\n with tf.variable_scope('attonly/attention/compute'):\n with slim.arg_scope(resnet.resnet_arg_scope()):\n with slim.arg_scope([slim.batch_norm],\n is_training=(mode == Mode.TRAIN)):\n attention = slim.conv2d(\n feature_map, 512, config['attention_kernel'], rate=1,\n activation_fn=tf.nn.relu, scope='conv1')\n attention = slim.conv2d(\n attention, 1, config['attention_kernel'], rate=1,\n activation_fn=None, normalizer_fn=None, scope='conv2')\n attention = tf.nn.softplus(attention)\n if config['normalize_feature_map']:\n feature_map = tf.nn.l2_normalize(feature_map, -1)\n descriptor = tf.reduce_sum(feature_map*attention, axis=[1, 2])\n if config['normalize_average']:\n descriptor /= tf.reduce_sum(attention, axis=[1, 2])\n else:\n descriptor = tf.reduce_max(feature_map, [1, 2])\n\n return {'descriptor': descriptor}\n\n def _loss(self, outputs, inputs, **config):\n raise NotImplementedError\n\n def _metrics(self, outputs, inputs, **config):\n raise NotImplementedError\n","sub_path":"retrievalnet/retrievalnet/models/delf.py","file_name":"delf.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"513663505","text":"\"\"\"15-8. Три кубика: при броске 3 кубиков D6 наименьший возможный результат равен 3,\nа наибольший — 18. Создайте визуализацию, которая показывает, что происходит при бро-\nске трех кубиков D6.\"\"\"\nimport pygal\nfrom die import Die\n\n# Создание двух кубиков D8.\ndie_1 = Die()\ndie_2 = Die()\ndie_3 = Die()\n\n# Моделирование серии бросков с сохранением результатов в списке.\nresults = []\nfor roll_num in range(1000):\n result = die_1.roll() + die_2.roll() + die_3.roll()\n results.append(result)\n\n# Анализ результатов.\nfrequencies = []\nmax_result = die_1.num_sides + die_2.num_sides + die_3.num_sides\nfor value in range(3, max_result + 1):\n frequency = results.count(value)\n frequencies.append(frequency)\n\n# Визуализация результатов.\nhist = pygal.Bar()\nhist.title = \"Results of rolling three D6 dice 1000 times.\"\nhist.x_labels = [str(i) for i in range(3, 19)]\nhist.x_title = \"Result\"\nhist.y_title = \"Frequency of Result\"\nhist.add('D6 + D6 + D6', frequencies)\nhist.render_to_file('three_visual.svg')\n","sub_path":"Мэтиз: Изучаем Python/projects/visual_data/pygal/15-8/three_visual.py","file_name":"three_visual.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"614251158","text":"from argparse import ArgumentParser\nfrom dataclasses import dataclass, field\nfrom typing import Sequence, Mapping, Union, ClassVar\nimport json\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport cflowpost.plotting as cfplot\n\n\nCONFIG_DIR = \"config\"\nPLOT_FORMAT_JSON = \"plot_format.json\"\nPOSITIONS_JSON = \"positions.json\"\nVARIABLES_JSON = \"variables.json\"\n\n\n@dataclass\nclass CaseComparisonPlotter:\n case_dir: str\n plot_format: OrderedDict\n positions: OrderedDict[str, str]\n variables: OrderedDict\n basewidth: float = field(default=2., repr=False)\n baseheight: float = field(default=2.2, repr=False)\n sharex: Union[str, bool] = field(default=\"col\", repr=False)\n sharey: str = field(default=\"row\", repr=False)\n tight_layout: bool = field(default=True, repr=False)\n base_fontsize: float = field(default=10, repr=False)\n _model_color_key: ClassVar[str] = \"Model colors\"\n _experimental_color_key: ClassVar[str] = \"Experimental color\"\n _markevery_key: ClassVar[str] = \"markevery\"\n _xlim_key: ClassVar[str] = \"xlim\"\n _xlabel_key: ClassVar[str] = \"xlabel\"\n\n def __post_init__(self):\n cls = CaseComparisonPlotter\n self.plot_format.setdefault(\n cls._experimental_color_key, \"tab:olive\")\n self.plot_format.setdefault(cls._markevery_key, None)\n self.plot_format.setdefault(cls._xlim_key, None)\n self.plot_format.setdefault(cls._xlabel_key, None)\n\n def create_figure(self):\n nrows, ncols = len(self.variables), len(self.positions)\n figsize = (ncols*self.basewidth, nrows*self.baseheight)\n return plt.subplots(nrows, ncols,\n figsize=figsize,\n sharex=self.sharex,\n sharey=self.sharey,\n tight_layout=self.tight_layout)\n\n def read_data(self):\n models = self.plot_format[\"models\"]\n positions = self.positions.keys()\n models = [os.path.join(self.case_dir, model) for model in models]\n experimental = os.path.join(self.case_dir,\n self.plot_format[\"experimental\"])\n model_paths_by_position = OrderedDict(\n {position: [os.path.join(model, position) for model in models]\n for position in positions})\n model_data_map = {\n position: [pd.read_csv(path)\n for path in model_paths_by_position[position]]\n for position in positions}\n exp_data_map = {\n position: pd.read_csv(os.path.join(experimental, position))\n for position in positions}\n return model_data_map, exp_data_map\n\n def plot(self, ):\n model_data_map, exp_data_map = self.read_data()\n fig, axs = self.create_figure()\n positions = list(self.positions.keys())\n y_variables = list(self.variables.keys())\n model_labels = self.plot_format[\"models\"]\n experimental_label = self.plot_format[\"experimental\"]\n x_var_key = self.plot_format[\"x_var\"]\n xlabel = self.plot_format[self.__class__._xlabel_key]\n xlabel = xlabel if xlabel is not None else x_var_key\n exp_color = self.plot_format[self.__class__._experimental_color_key]\n markevery = self.plot_format[self.__class__._markevery_key]\n xlim = self.plot_format[self.__class__._xlim_key]\n for position, ax in zip(positions, axs[0]):\n ax.set_title(self.positions[position],\n fontsize=self.base_fontsize*1.5)\n for y_var_key, axs_row in zip(y_variables, axs):\n for position, ax in zip(positions, axs_row):\n model_frames = model_data_map[position]\n experimental_frame = exp_data_map[position]\n self._plot_single_ax(model_frames=model_frames,\n experimental_frame=experimental_frame,\n x_var_key=x_var_key,\n y_var_key=y_var_key,\n model_labels=model_labels,\n exp_label=experimental_label,\n exp_color=[exp_color],\n markevery=markevery,\n xlim=xlim,\n ax=ax)\n axs_row[0].set_ylabel(self.variables[y_var_key],\n fontsize=self.base_fontsize * 1.4)\n for ax in axs[-1]:\n ax.set_xlabel(xlabel, fontsize=self.base_fontsize*1.4)\n axs[0][-1].legend()\n fig.align_ylabels()\n return fig, axs\n\n @staticmethod\n def _plot_single_ax(\n model_frames,\n experimental_frame,\n x_var_key,\n y_var_key,\n model_labels,\n exp_label,\n exp_color,\n markevery,\n xlim=None,\n ax=None,):\n if ax is None:\n fig, ax = plt.subplots(1, 1)\n x_var_series = np.column_stack([data[x_var_key].to_numpy()\n for data in model_frames])\n y_var_series = np.column_stack([data[y_var_key].to_numpy()\n for data in model_frames])\n x_exp_series = experimental_frame[x_var_key]\n y_exp_series = experimental_frame[y_var_key]\n plotter = cfplot.NumericalValidation1DPlotter(num_x=x_var_series,\n num_y=y_var_series,\n exp_x=x_exp_series,\n exp_y=y_exp_series,\n num_labels=model_labels,\n exp_labels=exp_label,\n exp_colors=exp_color,\n markevery=markevery,\n legend=False)\n plotter.plot(ax=ax)\n if xlim is not None:\n ax.set_xlim(*xlim)\n return\n\n\ndef read_json_as_ordereddict(fileloc):\n with open(fileloc, \"r\") as f:\n return json.loads(f.read(), object_pairs_hook=OrderedDict)\n\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument(\"-c\", \"--case-dir\",\n default=\".\",\n help=\"Path to case directory.\")\n parser.add_argument(\"--dpi\", type=float, default=220)\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n run(case_dir=args.case_dir, dpi=args.dpi)\n\n\ndef run(case_dir, dpi, **kwargs):\n config_dir = os.path.join(case_dir, CONFIG_DIR)\n json_files = (PLOT_FORMAT_JSON, POSITIONS_JSON, VARIABLES_JSON)\n json_files = [os.path.join(config_dir, file) for file in json_files]\n plot_format, positions, variables = [read_json_as_ordereddict(file)\n for file in json_files]\n plotter = CaseComparisonPlotter(plot_format=plot_format,\n case_dir=case_dir,\n positions=positions,\n variables=variables,\n **kwargs)\n fig, axs = plotter.plot()\n output_file = os.path.join(case_dir, \"plot.png\")\n fig.savefig(output_file, dpi=dpi)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"thesis-main/bin/thesis-chapter4-figures/bin/plot_radial_profile_comparison.py","file_name":"plot_radial_profile_comparison.py","file_ext":"py","file_size_in_byte":7524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"324075815","text":"# How to use VS Code debugger with Locust\nimport locust_plugins.utils\n\nlocust_plugins.utils.gevent_debugger_patch()\nfrom locust_plugins.listeners import PrintListener\nfrom locust import task, TaskSet\nfrom locust.wait_time import constant\nfrom locust.contrib.fasthttp import FastHttpLocust\n\n\nclass UserBehavior(TaskSet):\n @task\n def my_task(self):\n self.client.get(\"/\")\n\n\nclass MyHttpLocust(FastHttpLocust):\n task_set = UserBehavior\n wait_time = constant(1)\n if __name__ == \"__main__\":\n host = \"https://www.example.com\"\n\n\n# allow running as executable, to support attaching the debugger\nif __name__ == \"__main__\":\n PrintListener()\n MyHttpLocust._catch_exceptions = False\n MyHttpLocust().run()\n","sub_path":"examples/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"134988469","text":"# -*- coding: utf-8 -*-\nfrom utilities.logs import get_logger\nfrom proof.apis import APP_DB\n\nlog = get_logger(__name__)\n\n\nclass Initializer(object):\n def __init__(self, services):\n if APP_DB == 'rapydo_tests':\n mongo = services.get('mongo')\n mongo.Article.objects.all().delete()\n\n import nltk\n nltk.download('punkt')\n\n\n\"\"\"\nclass Customizer(object):\n\n def custom_user_properties(self, properties):\n\n log.pp(properties)\n # properties[\"irods_cert\"] = get_random_name(len=12)\n return properties\n\n def custom_post_handle_user_input(self, auth, user_node, properties):\n\n print(\"TEST\", auth, user_node, properties)\n return True\n\n try:\n group = auth.db.Group.nodes.get(shortname=\"default\")\n except auth.db.Group.DoesNotExist:\n log.warning(\"Unable to find default group, creating\")\n group = auth.db.Group()\n group.fullname = \"Default user group\"\n group.shortname = \"default\"\n group.save()\n\n log.info(\"Link %s to group %s\", user_node.email, group.shortname)\n user_node.belongs_to.connect(group)\n\n return True\n\"\"\"\n\n\n\n\n\n","sub_path":"projects/proof/backend/initialization/initialization.py","file_name":"initialization.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"7040324","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\n\nfrom libmozdata.bugzilla import BugzillaProduct\n\nfrom auto_nag.bzcleaner import BzCleaner\nfrom auto_nag.nag_me import Nag\nfrom auto_nag.team_managers import TeamManagers\nfrom auto_nag.user_activity import UserActivity\n\n\nclass TriageOwnerVacant(BzCleaner, Nag):\n def __init__(self):\n super(TriageOwnerVacant, self).__init__()\n self.query_url = None\n self.inactive_weeks_number = self.get_config(\"inactive_weeks_number\", 26)\n\n def description(self):\n return \"Components with triage owner need to be assigned\"\n\n def fetch_products(self):\n data = []\n include_fields = [\n \"name\",\n \"is_active\",\n \"components.id\",\n \"components.name\",\n \"components.team_name\",\n \"components.triage_owner\",\n \"components.is_active\",\n ]\n\n def product_handler(product, data):\n data.append(product)\n\n BugzillaProduct(\n product_names=self.get_products(),\n include_fields=include_fields,\n product_handler=product_handler,\n product_data=data,\n ).wait()\n\n return data\n\n def nag_template(self):\n return self.template()\n\n def identify_vacant_components(self):\n # Filter out products and components that are not active\n products = [\n {\n **product,\n \"components\": [\n component\n for component in product[\"components\"]\n if component[\"is_active\"]\n ],\n }\n for product in self.fetch_products()\n if product[\"is_active\"]\n ]\n\n triage_owners = set()\n for product in products:\n for component in product[\"components\"]:\n triage_owners.add(component[\"triage_owner\"])\n\n user_activity = UserActivity(self.inactive_weeks_number)\n inactive_users = user_activity.check_users(triage_owners)\n\n team_managers = TeamManagers()\n vacant_components = []\n for product in products:\n for component in product[\"components\"]:\n triage_owner = component[\"triage_owner\"]\n if triage_owner not in inactive_users:\n continue\n\n manager = team_managers.get_team_manager(component[\"team_name\"])\n\n info = {\n \"id\": component[\"id\"],\n \"manager\": manager[\"name\"],\n \"team\": component[\"team_name\"],\n \"product\": product[\"name\"],\n \"component\": component[\"name\"],\n \"triage_owner\": triage_owner,\n \"status\": user_activity.get_string_status(\n inactive_users[triage_owner][\"status\"]\n ),\n }\n\n vacant_components.append(info)\n self.add(manager[\"mozilla_email\"], info)\n\n return vacant_components\n\n def get_email_data(self, date, bug_ids):\n return self.identify_vacant_components()\n\n def organize_nag(self, data):\n return data\n\n def get_cc(self):\n return set()\n\n\nif __name__ == \"__main__\":\n TriageOwnerVacant().run()\n","sub_path":"auto_nag/scripts/vacant_triage_owner.py","file_name":"vacant_triage_owner.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"210647384","text":"import json\nimport os\nfrom datetime import timedelta\nfrom functools import wraps\n\nfrom flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate, MigrateCommand\n\nfrom flask_jwt_extended import JWTManager, verify_jwt_in_request, get_jwt_claims\n\nfrom flask_script import Manager\n\n#using flask-cors to solve all the problems?\nfrom flask_cors import CORS\n\napp = Flask(__name__) # app.root location\nCORS(app)\n\n#not disabling loading .env\n#fadhil using dotenv for not hard-coding database URL\nfrom dotenv import load_dotenv\nfrom pathlib import Path # python3 only\nenv_path = Path('.') / '.envdummy'\nload_dotenv(dotenv_path=env_path)\nusername = os.getenv('DATABASE_USER')\npassword = os.getenv('DATABASE_PASSWORD')\nhostport = os.getenv('DATABASE_URL')\nname = os.getenv('DATABASE_NAME')\n\n\n#jwt secret, generated from random.org\n#regenerated for final project\napp.config['JWT_SECRET_KEY'] = 'bsNb0Tne6KMuuy6zE8M6ekjWaHb2XOKL'\napp.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)\n\njwt = JWTManager(app)\n\n#declare wrapper for admin, user-specific cases\ndef admin_required(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n verify_jwt_in_request()\n claims= get_jwt_claims()\n if not claims['isadmin']:\n return {'status': 'FORBIDDEN', 'message': 'Admin Only!'}, 403\n else:\n return fn(*args, **kwargs)\n return wrapper\n\ndef user_required(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n verify_jwt_in_request()\n claims= get_jwt_claims()\n if claims['isadmin']:\n return {'status': 'FORBIDDEN', 'message': 'User Only!'}, 403\n else:\n return fn(*args, **kwargs)\n return wrapper\n\n#################### TESTING\n# try:\n# env = os.environ.get('FLASK_ENV', 'development') #nama, default\n# if env == 'testing':\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:JalanTidarno.23@localhost:3306/restDB_test'\n# else:\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:JalanTidarno.23@localhost:3306/restDB'\n# except Exception as e:\n# raise e\n\n##### HARUS DI ATAS ##########\n\napp.config['APP_DEBUG'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{db_user}:{db_pass}@{db_host_port}/{db_name}'.format(db_user=username,db_pass=password,db_host_port=hostport,db_name=name)\n##.format(os.getenv(\"DATABASE_USER\"),os.getenv(\"DATABASE_PASSWORD\"),os.getenv(\"DATABASE_HOST_PORT\"),os.getenv(\"DATABASE_NAME\"))\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\n########## MIDDLEWARE #############\n\n\n@app.after_request\ndef after_request(response):\n try:\n requestData = request.get_json()\n except Exception as e:\n requestData = request.args.to_dict()\n if response.status_code == 200:\n app.logger.info(\"REQUEST_LOG\\t%s\", json.dumps({ \n 'status_code': response.status_code, # ini ngebuat 400 gak bisa masuk \n 'request': requestData, 'response': json.loads(response.data.decode('utf-8'))}))\n else:\n app.logger.error(\"REQUEST_LOG\\t%s\", json.dumps({ \n 'status_code': response.status_code,\n 'request': requestData, 'response': json.loads(response.data.decode('utf-8'))}))\n\n return response\n\n##add blueprint here\nfrom blueprints.user.resources import bp_user\napp.register_blueprint(bp_user, url_prefix='/users')\n\nfrom blueprints.auth import bp_auth\napp.register_blueprint(bp_auth, url_prefix='/auth')\n\nfrom blueprints.tag.resources import bp_tag\napp.register_blueprint(bp_tag, url_prefix='/tags')\n\nfrom blueprints.posting.resources import bp_posting\napp.register_blueprint(bp_posting, url_prefix='/posting')\n\nfrom blueprints.upload import bp_upload\napp.register_blueprint(bp_upload, url_prefix='/upload')\n\nfrom blueprints.point.resources import bp_point\napp.register_blueprint(bp_point, url_prefix='/point')\n\nfrom blueprints.admin import bp_admin\napp.register_blueprint(bp_admin, url_prefix='/admin')\n\nfrom blueprints.notification.resources import bp_nofity\napp.register_blueprint(bp_nofity, url_prefix='/notification')\n\ndb.create_all()","sub_path":"blueprints/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"450358517","text":"import sys\nimport re\nfrom collections import defaultdict\n\nwords = defaultdict(bool)\n\ndef get_words():\n global possible_tags\n training = open(sys.argv[1], 'r')\n line = training.readline()\n while line:\n l = line.strip()\n if l:\n vals = l.split(' ')\n words[vals[0]] = True\n line = training.readline()\n\ndef convert():\n data = open(sys.argv[2], 'r')\n out = open(sys.argv[3], 'w')\n line = data.readline()\n firstCaps = re.compile('[A-Z].+')\n AllCaps = re.compile('[A-Z]+$')\n startNumerals = re.compile('\\d+')\n allCapsWithDot = re.compile('[A-Z]+\\.[A-Z]+$')\n phoneNumber = re.compile('\\d\\d\\d.\\d\\d\\d.\\d\\d\\d\\d')\n location = re.compile('[A-Z][a-z][a-z][a-z][a-z][a-z][a-z]+$')\n while line:\n l = line.strip()\n if l:\n vals = l.split(' ')\n word = vals[0]\n if not words.get(word, False):\n if AllCaps.match(word):\n word = \"_AllCaps_\"\n elif location.match(word):\n word = \"_location_\"\n elif allCapsWithDot.match(word):\n word = \"_allCapsWithDot_\"\n elif firstCaps.match(word):\n word = \"_firstCaps_\"\n elif phoneNumber.match(word):\n word = \"_phoneNumber_\"\n elif startNumerals.match(word):\n word = \"_startNumerals_\"\n else:\n word = \"_RARE_\"\n out.write('{0} '.format(word))\n for i in range(1,len(vals)-1):\n out.write('{0} '.format(vals[i]))\n if not len(vals) == 1:\n out.write('{0}'.format(vals[len(vals)-1]))\n out.write('\\n')\n line = data.readline()\n\nget_words()\nconvert()\n","sub_path":"testing/original_code/rare_specific_conversion.py","file_name":"rare_specific_conversion.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"159106922","text":"#!/usr/bin/python3\n#My old and obsolete checker -- options are just too messy\n#Copyright Adamos - MIT license\nimport os\nimport sys, getopt\n\nimport subprocess\n\nimport zipfile\n\nimport colorful\nfrom shutil import copyfile\nimport time\nimport json\n\nuserName =\"\"\nselectedTask =\"\"\nselectedFile =\"\"\npauseOnWA = False\ndef main(argv):\n\n conFile = open(\"config.txt\")\n global userName, selectedTask, selectedFile\n userName = conFile.readline().rstrip()\n selectedTask = conFile.readline().rstrip()\n selectedFile = conFile.readline().rstrip()\n greet()\n try:\n opts, args = getopt.getopt(argv, \"n:,r:,l:,d,a:,p,z:,t:,f:,u:,c,e,g:,s:,F\", [\"pause\", \"files\", \"tasks\", \"done\"])\n except getopt.GetoptError:\n print(\"Use -h for help\")\n sys.exit(2)\n \n for opt, arg in opts:\n if opt == '-l':\n x = arg.split(',')\n runLocal(x[0], x[1])\n if opt == '-p':\n print(\"Available packs:\")\n for a in listDirs(\"./tasks/\" + selectedTask + \"/pack\"):\n print(a)\n if opt == '-a':\n print(colorful.red(\"Running on all packs!\"))\n print(\"Comparing with \" + arg +\"'s results\")\n for a in listDirs(\"./tasks/\" + selectedTask + \"/pack\"):\n runLocal(a, arg)\n if opt == '-z':\n unpackZIP(arg)\n if(opt == '-n'):\n createNewTask(arg)\n if(opt == '-r'):\n runSolution(arg)\n if(opt == '-t'):\n if arg:\n selectedTask = arg\n saveConfig()\n if(opt == '-u'):\n userName = arg\n saveConfig()\n if(opt == '-f'):\n selectedFile = arg\n saveConfig()\n if(opt == \"-c\"):\n compileFile(selectedFile)\n if(opt == '-e'):\n subprocess.call(\"geany.bat \" + \"./tasks/\"+selectedTask + \"/src/\" + selectedFile + \".cpp\")\n if(opt == '-g'):\n if not os.path.exists(\"./tasks/\" + selectedTask + \"/pack/\" + arg):\n os.makedirs(\"./tasks/\" + selectedTask + \"/pack/\" + arg)\n copyfile(\"./template/compare.txt\", \"./tasks/\"+selectedTask + \"/pack/\" + arg + \"/compare.txt\")\n if not os.path.exists(\"./tasks/\" + selectedTask + \"/pack/\" + arg + \"/in\"):\n os.makedirs(\"./tasks/\" + selectedTask + \"/pack/\" + arg + \"/in\")\n copyfile(\"./template/gen.sh\", \"./tasks/\"+selectedTask + \"/pack/\" + arg + \"/gen.sh\")\n if(opt == '-s'):\n x = arg.split(',')\n fileFromTemplate(x[0], x[1])\n if(opt == '-F'):\n x = [i for i in listDirs('./template') if i.find('.cpp') != -1]\n for i in x:\n print(i)\n if(opt == '--pause'):\n global pauseOnWA\n pauseOnWA = True\n if(opt == '--files'):\n x = [i for i in listDirs(\"./tasks/\" + selectedTask + \"/src/\") if i.find('.cpp') != -1]\n for i in x:\n print(i)\n if(opt == '--tasks'):\n print(colorful.green(\"Available tasks\"))\n for a in listDirs(\"./tasks\"):\n s_file = open(\"./tasks/\" + a + \"/status.json\")\n task_info = json.load(s_file)\n print(a + \" \" + colorful.green(task_info['done']))\n if(opt == '--done'):\n s_file = open(\"./tasks/\" + selectedTask + \"/status.json\", \"r\")\n task_info = json.load(s_file)\n s_file.close()\n task_info['done'] = 'OK'\n s_file = open(\"./tasks/\" + selectedTask + \"/status.json\", \"w\")\n json.dump(task_info, s_file, indent=4)\n\ndef greet():\n print(\"Task checker by Adamos\")\n print(colorful.red(\"username: \") + userName)\n print(colorful.red(\"selected Task: \") + selectedTask)\n print(colorful.red(\"selected Executable: \") + selectedFile)\n print()\n\ndef saveConfig():\n conf = open(\"config.txt\", \"w+\")\n conf.write(userName + \"\\n\")\n conf.write(selectedTask + \"\\n\")\n conf.write(selectedFile)\n greet()\n\ndef fileFromTemplate(fileName, templateName):\n copyfile(\"./template/\" + templateName + \".cpp\", \"./tasks/\" + selectedTask + \"/src/\" + fileName + \".cpp\")\n\ndef createNewTask(taskName):\n print(colorful.green(\"Creating task \" + taskName))\n if not os.path.exists(\"./tasks/\"+taskName):\n os.makedirs(\"./tasks/\"+taskName)\n else:\n print(colorful.red(\"This task already exists\"))\n print(\"Choose a different name\")\n sys.exit()\n if not os.path.exists(\"./tasks/\"+taskName + \"/bin\"):\n os.makedirs(\"./tasks/\"+taskName + \"/bin\")\n if not os.path.exists(\"./tasks/\"+taskName + \"/pack\"):\n os.makedirs(\"./tasks/\"+taskName + \"/pack\")\n if not os.path.exists(\"./tasks/\"+taskName + \"/src\"):\n os.makedirs(\"./tasks/\"+taskName + \"/src\")\n copyfile(\"./template/template.cpp\", \"./tasks/\" + taskName + \"/src/\" + taskName + \".cpp\")\n copyfile(\"./template/status.json\", \"./tasks/\" + taskName + \"/status.json\")\n\n\ndef compileFile(fileName):\n print(colorful.red(\"Compiling \" + fileName + \".cpp\"))\n tStart = time.time()\n subprocess.call(\"g++ -Wall -Wextra -std=c++11 -Wl,--stack,64000000 -O2 -static -I /utils/include -o \" + \" ./tasks/\" + selectedTask + \"/bin/\" + fileName + \".exe\" + \" ./tasks/\" + selectedTask + \"/src/\" + fileName +\".cpp\" )\n print(colorful.green(\"Took \" + str(time.time() - tStart)))\n\ndef unpackZIP(path):\n print(colorful.green(\"Unpacking tests from \" + path))\n zf = zipfile.ZipFile(path, 'r')\n zf.extractall(\"./tasks/\" + selectedTask + \"/pack\")\n zf.close()\n\ndef listDirs(path):\n dirList = os.listdir(path)\n sort_nicely(dirList)\n return dirList\n\ndef runSolution(packName):\n global selectedFile\n path = \"./tasks/\" + selectedTask + \"/pack/\" + packName\n if not os.path.exists(path + \"/out/\" + userName):\n os.makedirs(path + \"/out/\" + userName)\n\n print(colorful.orange(\"Generating outs for \" + packName + \": \" + selectedFile))\n for testFile in listDirs(path + \"/in\"):\n tStart = time.time() \n subprocess.call(\"./tasks/\" + selectedTask +\"/bin/\" + selectedFile, stdin=open(path + \"/in/\" + testFile), stdout=open(path + \"/out/\" + userName + \"/\" + testFile, mode=\"w+\"))\n print(colorful.green(testFile + \" took \" + str(time.time() - tStart)))\n\n\ndef runLocal(packName, compareTo):\n print(colorful.blue(\"Running testpack: \" + packName))\n path = \"./tasks/\" + selectedTask + \"/pack/\" + packName\n\n if not os.path.exists(path + \"/out/\" + userName):\n os.makedirs(path + \"/out/\" + userName)\n\n compareExe=\"\"\n compareFormat=\"\"\n cFile = open(\"./tasks/\" + selectedTask + \"/pack/\" + packName + \"/compare.txt\")\n c_comparator = cFile.readline().rstrip()\n comparators = json.load(open(\"./compare.json\"))\n print(c_comparator)\n for x in comparators:\n if(x['name'] == c_comparator):\n compareExe = \"./utils/\" + x['file']\n compareFormat = x['format']\n\n print(compareExe)\n for testFile in listDirs(path + \"/in\"):\n print(colorful.orange(\"TEST \" + testFile))\n compareArgs = [c_arg.replace(\"$in\", path + \"/in/\" + testFile).replace(\"$user_out\", path + \"/out/\" + userName + \"/\" + testFile).replace(\"$other_out\", path + \"/out/\" + compareTo + \"/\" + testFile) for c_arg in compareFormat.split()]\n \n if not os.path.isfile(path + \"/out/\" + userName + \"/\" + testFile):\n print(colorful.orange(\"Generating outs for \" + testFile))\n tStart = time.time()\n subprocess.call(\"./tasks/\" + selectedTask +\"/bin/\" + selectedFile, stdin=open(path + \"/in/\" + testFile), stdout=open(path + \"/out/\" + userName + \"/\" + testFile, mode=\"w+\"))\n print(colorful.yellow(testFile + \" took \" + str(time.time() - tStart)))\n\t\t\n outputVal = subprocess.run([compareExe] + compareArgs, stdout=subprocess.PIPE, encoding='utf8')\n if str(outputVal.stdout) == \"\":\n print(colorful.green(\"OK\"))\n else:\n print(colorful.red(\"WA\"))\n print(str(outputVal.stdout))\n if(pauseOnWA):\n xt = input()\n if(xt == \"0\"):\n sys.exit()\n\n#Better sorting of filenames with numbers\nimport re\n\ndef tryint(s):\n try:\n return int(s)\n except:\n return s\n\ndef alphanum_key(s):\n \"\"\" Turn a string into a list of string and number chunks.\n \"z23a\" -> [\"z\", 23, \"a\"]\n \"\"\"\n return [ tryint(c) for c in re.split('([0-9]+)', s) ]\n\ndef sort_nicely(l):\n \"\"\" Sort the given list in the way that humans expect.\n \"\"\"\n l.sort(key=alphanum_key)\n#end block\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":8630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"449316603","text":"def getAvailableLetters(lettersGuessed):\n '''\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters that represents what letters have not\n yet been guessed.\n '''\n # FILL IN YOUR CODE HERE...\n letters = []\n for i in range(97, 123):\n z = chr(i) #ASCII arithmetic to create a list which contains all the alphabetical characters\n letters.append(z) #inserting each character to letters[] list\n for letter in lettersGuessed:\n for index in letters:\n if letter == index:\n letters.remove(index)\n return ''.join(letters)\n","sub_path":"Problem_Set_3/printing_out_all_available_letters.py","file_name":"printing_out_all_available_letters.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"160090475","text":"# puzzle input\ninputFile = open(\"C:/Users/Natasha/Desktop/Advent-of-Code-2017/input_5.txt\", \"r\")\norigInput = inputFile.readlines()\norigInput = [int(line.rstrip()) for line in origInput]\ninputFile.close()\n\n# challenge part 1\ninput = origInput[:]\ncurrentPos = 0\nsteps = 0\nwhile currentPos < len(input):\n newPos = currentPos + input[currentPos]\n input[currentPos] += 1\n currentPos = newPos\n steps += 1\nprint(\"The number of steps it takes to reach the exit is:\", steps)\n\n# challenge part 2\ninput = origInput[:]\ncurrentPos = 0\nsteps = 0\nwhile currentPos < len(input):\n newPos = currentPos + input[currentPos]\n if input[currentPos] >= 3:\n input[currentPos] -= 1\n else:\n input[currentPos] += 1\n currentPos = newPos\n steps += 1\nprint(\"The number of steps it takes to reach the exit is now:\", steps)","sub_path":"Day 5.py","file_name":"Day 5.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"347459705","text":"# -*- coding: utf-8 -*-\nfrom django.http import HttpResponse # Importamos el modulo HttpResponse\nimport datetime\nfrom django.template import Template, Context\n\nclass Persona(object):\n\t\"\"\"docstring for Persona\"\"\"\n\tdef __init__(self, nombre, apellido):\n\t\tself.nombre = nombre\n\t\tself.apellido = apellido\n\n\ndef saludo(request): # primera vista\n\tp1 = Persona(\"Ing. José\", \"Gómez\")\n\t# nombre = \"José\"\n\t# apellido = \"Gómez\"\n\n\ttemas_del_curso = [\"Plantillas\", \"Modelos\", \"Formularios\", \"Vistas\", \"Despliegue\"]\n\n\tfecha_actual = datetime.datetime.now()\n\tdoc_externo = open(\"Proyecto1/template/template1.html\")\n\t\n\tplt = Template(doc_externo.read()) # Creacion de un objeto template\n\tdoc_externo.close() # Se cierra el documento para que no se consuman recursos innecesarios\n\n\tctx = Context({\"nombre_persona\": p1.nombre, \"apellido_persona\": p1.apellido, \"fecha_actual\": fecha_actual, \"temas\":temas_del_curso}) # Contexto se usa para pasar valores y funciones del template\n\n\tdocumento = plt.render(ctx)\n\treturn HttpResponse(documento)\n\ndef despedida(request): # Segunda vista\n\treturn HttpResponse(\"Una despedida al estilo de Django Fecha\")\n\ndef dameFecha(request): # Tercera vista\n\tfechaActual = datetime.datetime.now()\n\n\tdocumento = \"\"\"\n\t\n\t\n\t\n\t\t\n\t\tCurso de Django Pildora Informaticas\n\t\n\t\n\t\tFecha y Hora Actuales %s
\n\t\tEdades\n\t\n\t\n\t\"\"\" %fechaActual\n\n\treturn HttpResponse(documento)\n\ndef calculaEdad(request, edad, anio): # Cuarta vista\n\t# edadActual = 23\n\tperiodo = anio - 2019\n\tedadFutura = edad + periodo\n\n\tdocumento = \"\"\"\n\t\n\t\n\t\n\t\t\n\t\tCurso de Django Pildora Informaticas\n\t\n\t\n\t\tEn el año %s tendras %s años
\n\t\tSaludo\n\t\n\t\n\t\"\"\" %(anio, edadFutura)\n\n\treturn HttpResponse(documento)","sub_path":"3.VIDEO_7/Proyecto1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"264879479","text":"from scipy.spatial import distance\nfrom matplotlib import pyplot as plt\n\n#method to compute error between numpy arrays with each row as tuple\ndef get_err( true_out, pred_out, plot=False ):\n if true_out.shape!=pred_out.shape :\n print(\"bad input dimensions to compute err: \",true_out.shape,pred_out.shape)\n\n aggreg_dist = 0\n\n for row_idx in range( len(true_out) ):\n true_point = tuple( true_out[ row_idx ] )\n pred_point = tuple( pred_out[ row_idx ] )\n curr_dist = distance.euclidean( true_point, pred_point )\n aggreg_dist += curr_dist if curr_dist > 0 else -curr_dist\n\n if plot:\n plt.plot( true_out[:,0],color=\"red\",label=\"true\" )\n plt.plot( pred_out[:,0],color=\"blue\",label=\"pred\" )\n plt.legend(loc='best')\n plt.show()\n #plt.show()\n #plt.plot( true_out[1] ) \n #plt.plot( pred_out[1] ) \n #plt.show()\n \n return aggreg_dist / len( true_out )\n\n","sub_path":"Fly_Brain_Analysis/predicting_neural_frame_analysis/generative_attempt_normal/err.py","file_name":"err.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"128843282","text":"class Solution:\n def findWords(self, words: List[str]) -> List[str]:\n if not words:\n return []\n\n rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']\n output = []\n\n for w in words:\n for r in rows:\n if len(set(w.lower()) - set(r)) == 0:\n output.append(w)\n break\n\n return output","sub_path":"leetcode/keyboard_row.py","file_name":"keyboard_row.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"553841829","text":"import math\n\nMIN_LAT = math.radians(-90.0)\nMAX_LAT = math.radians(90.0)\nMIN_LON = math.radians(-180.0)\nMAX_LON = math.radians(180.0)\nEARTH_RADIUS = 6371.01\n\n\ndef bounding_coordinates(lat, lon, distance):\n \"\"\"\n Berechnung zweier Refernezpunkte die ein Rechteck ergeben,\n dass ungefähr einem Kreis mit Suchradius entspricht.\n\n siehe: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates\n \"\"\"\n if distance <= 0:\n raise ValueError('distance must be greater than zero')\n dist_radians = distance / EARTH_RADIUS\n lat_radians = math.radians(lat)\n lon_radians = math.radians(lon)\n\n minLat = lat_radians - dist_radians\n maxLat = lat_radians + dist_radians\n\n if minLat > MIN_LAT and maxLat < MAX_LAT:\n deltaLon = math.asin(math.sin(dist_radians) / math.cos(lat_radians))\n minLon = lon_radians - deltaLon\n if minLon < MIN_LON:\n minLon += 2 * math.pi\n maxLon = lon_radians + deltaLon\n if maxLon > MAX_LON:\n maxLon -= 2 * math.pi\n else:\n minLat = max(minLat, MIN_LAT)\n maxLat = min(maxLat, MAX_LAT)\n minLon = MIN_LON\n maxLon = MAX_LON\n return (\n math.degrees(minLat), math.degrees(minLon),\n math.degrees(maxLat), math.degrees(maxLon)\n )\n\n\ndef normalize_lat(lat):\n while lat < -90.0:\n lat += 180.0\n while lat > 90.0:\n lat -= 180.0\n return lat\n\n\ndef normalize_lon(lon):\n while lon < -180.0:\n lon += 360.0\n while lon > 180.0:\n lon -= 360.0\n return lon\n","sub_path":"stimmungspegel/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"375531963","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport sys\n\nfrom flask import Flask\n\nfrom lib import db, login_manager, admin\n\nfrom auth.models import User\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_object('settings')\n\n # init database\n db.init_app(app)\n\n # init flask-login\n login_manager.init_app(app)\n\n # init admin\n admin.init_app(app)\n for path in app.config['ADMINS']:\n __import__(path)\n\n # register blueprint\n for path, prefix in app.config['BLUEPRINTS']:\n path = path.split('.')\n module = __import__('.'.join(path[:-1]), fromlist=[path[-2]])\n if hasattr(module, path[-1]):\n bp = getattr(module, path[-1])\n app.register_blueprint(bp, url_prefix=prefix)\n\n return app\n\napp = create_app()\n\n\n# @app.before_request\n# def before_request():\n# if request.endpoint in current_app.config['SAFE_ENDPOINTS']: return\n# if current_user.is_anonymous():\n# print current_user\n# else:\n# pass\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n if sys.argv[1] == 'syncdb':\n db.syncdb()\n from auth.models import User\n session = db.Session()\n if not session.query(User).filter(User.username == 'admin').first():\n admin = User(username='admin', password='1', is_admin=True)\n session.add(admin)\n session.commit()\n else:\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"555830049","text":"# Author:duguiming\n# Description:训练RNN模型\n# Date:2019-07-08\nimport time\nimport os\nimport tensorflow as tf\nfrom data_helper.data_process import DataProcess\nfrom config.config import RNNConfig, PathConfig\nfrom model.text_model import TextRNN\n\n\ndef feed_data(x_batch, y_batch, keep_prob):\n feed_dict = {\n model.input_x: x_batch,\n model.input_y: y_batch,\n model.keep_prob: keep_prob\n }\n return feed_dict\n\n\ndef evaluate(sess, x_, y_):\n \"\"\"验证集测试\"\"\"\n data_len = len(x_)\n batch_eval = dp.batch_iter(x_, y_, 128)\n total_loss = 0.0\n total_acc = 0.0\n for x_batch, y_batch in batch_eval:\n batch_len = len(x_batch)\n feed_dict = feed_data(x_batch, y_batch, 1.0)\n loss, acc = sess.run([model.loss, model.acc], feed_dict=feed_dict)\n total_loss += loss * batch_len\n total_acc += acc * batch_len\n return total_loss / data_len, total_acc / data_len\n\n\ndef train():\n start_time = time.time()\n print(\"Loading training ...\")\n X_train, y_train = dp.process_file(pathcnfig.train_dir, word2id, cat2id, rnnconfig.seq_length)\n X_val, y_val = dp.process_file(pathcnfig.val_dir, word2id, cat2id, rnnconfig.seq_length)\n print('Time coat:{:.3f}'.format(time.time() - start_time))\n\n tf.summary.scalar('loss', model.loss)\n tf.summary.scalar('accuracy', model.acc)\n merged_summary = tf.summary.merge_all()\n writer = tf.summary.FileWriter(pathcnfig.rnn_tensorboard_dir)\n saver = tf.train.Saver()\n\n session = tf.Session()\n session.run(tf.global_variables_initializer())\n writer.add_graph(session.graph)\n\n print(\"Training and evaling...\")\n best_val_accuracy = 0\n last_improved = 0\n require_improvement = 1000\n flag = False\n\n for epoch in range(rnnconfig.num_epochs):\n batch_train = dp.batch_iter(X_train, y_train, rnnconfig.batch_size)\n start = time.time()\n for x_batch, y_batch in batch_train:\n feed_dict = feed_data(x_batch, y_batch, rnnconfig.dropout_keep_prob)\n _, global_step, train_summaries, train_loss, train_accuracy = session.run([model.optim, model.global_step,\n merged_summary, model.loss,\n model.acc], feed_dict=feed_dict)\n if global_step % rnnconfig.print_per_batch == 0:\n end = time.time()\n val_loss, val_accuracy = evaluate(session, X_val, y_val)\n writer.add_summary(train_summaries, global_step)\n\n # If improved, save the model\n if val_accuracy > best_val_accuracy:\n saver.save(session, pathcnfig.rnn_best_model_dir)\n best_val_accuracy = val_accuracy\n last_improved = global_step\n improved_str = '*'\n else:\n improved_str = ''\n print(\"step: {},train loss: {:.3f}, train accuracy: {:.3f}, val loss: {:.3f}, \"\n \"val accuracy: {:.3f},training speed: {:.3f}sec/batch {}\\n\".format(\n global_step, train_loss, train_accuracy, val_loss, val_accuracy,\n (end - start) / rnnconfig.print_per_batch, improved_str))\n start = time.time()\n\n if global_step - last_improved > require_improvement:\n print(\"No optimization over 1000 steps, stop training\")\n flag = True\n break\n if flag:\n break\n\n\nif __name__ == \"__main__\":\n pathcnfig = PathConfig()\n rnnconfig = RNNConfig()\n dp = DataProcess()\n filenames = [pathcnfig.train_dir, pathcnfig.val_dir, pathcnfig.test_dir]\n if not os.path.exists(pathcnfig.vocab_dir):\n dp.build_vocab(filenames, pathcnfig.vocab_dir, rnnconfig.vocab_size)\n\n # 读取词表和类别\n categories, cat2id = dp.read_category()\n words, word2id = dp.read_vocab(pathcnfig.vocab_dir)\n\n # 转化为向量\n if not os.path.exists(pathcnfig.vector_word_npz):\n dp.export_word2vec_vectors(word2id, pathcnfig.word2vec_save_path, pathcnfig.vector_word_npz)\n rnnconfig.pre_training = dp.get_training_word2vec_vectors(pathcnfig.vector_word_npz)\n\n model = TextRNN(rnnconfig)\n train()","sub_path":"DL/TF_CNN_RNN/train_rnn.py","file_name":"train_rnn.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"554236416","text":"import os\nimport logging\n\nfrom pyTuttle import tuttle\n\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtQuick\n\nfrom quickmamba.patterns import Singleton\nfrom pySequenceParser import sequenceParser\nfrom .sequenceWrapper import SequenceWrapper\n\nfrom quickmamba.models import QObjectListModel\n\n\nclass FileItem(QtCore.QObject):\n\n _isSelected = False\n\n class Type():\n \"\"\" Enum \"\"\"\n File = 'File'\n Folder = 'Folder'\n Sequence = 'Sequence'\n\n def __init__(self, folder, fileName, fileType, seq, supported):\n super(FileItem, self).__init__()\n\n self._filepath = os.path.join(folder, fileName)\n self._fileType = fileType\n self._isSupported = supported\n\n if fileType == FileItem.Type.File:\n if supported:\n self._fileImg = 'image://buttleofx/' + self._filepath\n else:\n self._fileImg = \"../../img/buttons/browser/file-icon.png\"\n\n try:\n # May throw exception on bad symlink\n self._fileWeight = os.stat(self._filepath).st_size\n except FileNotFoundError:\n self._fileWeight = 0\n\n self._fileExtension = os.path.splitext(fileName)[1]\n self._seq = None\n\n elif fileType == FileItem.Type.Folder:\n self._fileImg = \"../../img/buttons/browser/folder-icon.png\"\n self._seq = None\n self._fileWeight = 0.0\n self._fileExtension = \"\"\n\n elif fileType == FileItem.Type.Sequence:\n time = int(seq.getFirstTime() + (seq.getLastTime() - seq.getFirstTime()) * 0.5)\n seqPath = seq.getAbsoluteFilenameAt(time)\n\n if not os.path.exists(seqPath):\n time = seq.getFirstTime()\n seqPath = seq.getAbsoluteFilenameAt(time)\n\n seqPath = seq.getAbsoluteStandardPattern()\n\n if supported:\n self._fileImg = 'image://buttleofx/' + seqPath\n else:\n self._fileImg = \"../../img/buttons/browser/file-icon.png\"\n\n self._seq = SequenceWrapper(seq)\n self._fileWeight = self._seq.getWeight()\n (_, extension) = os.path.splitext(seqPath)\n self._fileExtension = extension\n\n # ############################################ Methods exposed to QML ############################################ #\n\n @QtCore.pyqtSlot(result=str)\n def getFilepath(self):\n return self._filepath\n\n @QtCore.pyqtSlot(result=str)\n def getFileType(self):\n return self._fileType\n\n @QtCore.pyqtSlot(result=QtCore.QSizeF)\n def getImageSize(self):\n g = tuttle.Graph()\n node = g.createNode(tuttle.getReaders(self._fileExtension)[0], self._fileImg).asImageEffectNode()\n g.setup()\n timeMin = self.getFileTime().min\n g.setupAtTime(timeMin)\n rod = node.getRegionOfDefinition(timeMin)\n width = rod.x2 - rod.x1\n height = rod.y2 - rod.y1\n return QtCore.QSizeF(width, height)\n\n @QtCore.pyqtSlot(result=bool)\n def getSupported(self):\n return self._isSupported\n\n # ######################################## Methods private to this class ####################################### #\n\n # ## Getters ## #\n\n def getFileImg(self):\n return self._fileImg\n\n def getFileName(self):\n return os.path.basename(self._filepath)\n\n def getFileWeight(self):\n return self._fileWeight\n\n def getFileTime(self):\n g = tuttle.Graph()\n node = g.createNode(tuttle.getReaders(self._fileExtension)[0], self._filepath).asImageEffectNode()\n g.setup()\n time = node.getTimeDomain()\n return time\n\n def getSelected(self):\n return self._isSelected\n\n def getSequence(self):\n return self._seq\n\n # ## Setters ## #\n\n def setFileName(self, newName):\n os.rename(self.filepath, os.path.join(os.path.dirname(self._filepath), newName))\n\n def setFilepath(self, newpath):\n import shutil\n shutil.move(self.filepath, os.path.join(newpath, self.fileName))\n\n def setSelected(self, isSelected):\n self._isSelected = isSelected\n self.isSelectedChange.emit()\n\n # ############################################# Data exposed to QML ############################################## #\n\n filepath = QtCore.pyqtProperty(str, getFilepath, setFilepath, constant=True)\n fileType = QtCore.pyqtProperty(str, getFileType, constant=True)\n fileName = QtCore.pyqtProperty(str, getFileName, setFileName, constant=True)\n fileWeight = QtCore.pyqtProperty(float, getFileWeight, constant=True)\n\n imageSize = QtCore.pyqtProperty(QtCore.QSize, getImageSize, constant=True)\n isSelectedChange = QtCore.pyqtSignal()\n isSelected = QtCore.pyqtProperty(bool, getSelected, setSelected, notify=isSelectedChange)\n fileImg = QtCore.pyqtProperty(str, getFileImg, constant=True)\n seq = QtCore.pyqtProperty(QtCore.QObject, getSequence, constant=True)\n\n\nclass FileModelBrowser(QtQuick.QQuickItem):\n \"\"\"Class FileModelBrowser\"\"\"\n\n _folder = \"\"\n _firstFolder = \"\"\n _fileItems = []\n _fileItemsModel = None\n _nameFilter = \"*\"\n\n def __init__(self, parent=None):\n super(FileModelBrowser, self).__init__(parent)\n self._fileItemsModel = QObjectListModel(self)\n self._showSeq = False\n\n # ############################################ Methods exposed to QML ############################################ #\n\n # ## Getters ## #\n\n @QtCore.pyqtSlot(str, result=QtCore.QObject)\n def getFilteredFileItems(self, fileFilter):\n suggestions = []\n\n try:\n _, dirs, _ = next(os.walk(os.path.dirname(fileFilter)))\n dirs = sorted(dirs, key=lambda v: v.upper())\n\n for d in dirs:\n if d.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n if d.startswith(os.path.basename(fileFilter)):\n suggestions.append(FileItem(os.path.dirname(fileFilter), d, FileItem.Type.Folder, \"\", True))\n\n except Exception:\n pass\n suggestions.sort(key=lambda fileItem: fileItem.fileName.lower())\n\n suggestionsQt = QObjectListModel(self)\n suggestionsQt.setObjectList(suggestions)\n return suggestionsQt\n\n @QtCore.pyqtSlot(result=QtCore.QObject)\n def getFileItems(self):\n return self._fileItemsModel\n\n @QtCore.pyqtSlot(result=str)\n def getFirstFolder(self):\n return self._firstFolder\n\n @QtCore.pyqtSlot(result=QtCore.QObject)\n def getLastSelected(self):\n for item in reversed(self._fileItems):\n if item.isSelected:\n return item\n return None\n\n @QtCore.pyqtSlot(result=QtCore.QObject)\n def getSelectedItems(self):\n selectedList = QObjectListModel(self)\n for item in self._fileItems:\n if item.isSelected:\n selectedList.append(item)\n return selectedList\n\n # ## Setters ## #\n\n @QtCore.pyqtSlot(str)\n def setFirstFolder(self, firstFolder):\n self._firstFolder = firstFolder\n\n # ## Others ## #\n\n @QtCore.pyqtSlot(str, int)\n def changeFileName(self, newName, index):\n if index < len(self._fileItems):\n self._fileItems[index].fileName = newName\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(str)\n def createFolder(self, path):\n os.mkdir(path)\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(int)\n def deleteItem(self, index):\n if index < len(self._fileItems):\n if self._fileItems[index].fileType == FileItem.Type.Folder:\n import shutil\n shutil.rmtree(self._fileItems[index].filepath)\n if self._fileItems[index].fileType == FileItem.Type.File:\n os.remove(self._fileItems[index].filepath)\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(result=bool)\n def isEmpty(self):\n return not self._fileItems\n\n @QtCore.pyqtSlot(int, str)\n def moveItem(self, index, newpath):\n if index < len(self._fileItems):\n self._fileItems[index].filepath = newpath\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(int)\n def selectItem(self, index):\n for item in self._fileItems:\n item.isSelected = False\n if index < len(self._fileItems):\n self._fileItems[index].isSelected = True\n\n @QtCore.pyqtSlot(int)\n def selectItems(self, index):\n if index < len(self._fileItems):\n self._fileItems[index].isSelected = True\n\n @QtCore.pyqtSlot(int, int)\n def selectItemsByShift(self, begin, end):\n if begin > end:\n tmp = begin\n begin = end\n end = tmp\n for i in range(begin, end + 1):\n if i < len(self._fileItems):\n self._fileItems[i].isSelected = True\n\n @QtCore.pyqtSlot(str)\n def updateFileItems(self, folder):\n logging.debug('updateFileItems: %s' % folder)\n if not folder:\n return\n\n self._fileItems = []\n self._fileItemsModel.clear()\n allDirs = []\n allFiles = []\n allSeqs = []\n\n items = sequenceParser.browse(folder)\n dirs = [item.getFilename() for item in items if item.getType() == sequenceParser.eTypeFolder]\n seqs = [item.getSequence() for item in items if item.getType() == sequenceParser.eTypeSequence]\n files = [item.getFilename() for item in items if item.getType() == sequenceParser.eTypeFile]\n\n for d in dirs:\n if d.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n allDirs.append(FileItem(folder, d, FileItem.Type.Folder, \"\", True))\n\n if self._showSeq:\n for s in seqs:\n sPath = s.getStandardPattern()\n if sPath.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n readers = tuttle.getReaders(sPath)\n logging.debug('SEQ readers: %s' % readers)\n supported = bool(readers)\n if not supported and self._nameFilter != \"*\":\n continue\n allSeqs.append(FileItem(folder, sPath, FileItem.Type.Sequence, s, supported))\n\n for f in files:\n if f.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n readers = tuttle.getReaders(f)\n logging.debug('FILE readers: %s' % readers)\n supported = bool(readers)\n if not supported and self._nameFilter != \"*\":\n continue\n allFiles.append(FileItem(folder, f, FileItem.Type.File, \"\", supported))\n\n allDirs.sort(key=lambda fileItem: fileItem.fileName.lower())\n allFiles.sort(key=lambda fileItem: fileItem.fileName.lower())\n allSeqs.sort(key=lambda fileItem: fileItem.fileName.lower())\n self._fileItems = allDirs + allFiles + allSeqs\n\n self._fileItemsModel.setObjectList(self._fileItems)\n\n # ######################################## Methods private to this class ######################################## #\n\n # ## Getters ## #\n\n def getFilter(self):\n return self._nameFilter\n\n def getFolder(self):\n return self._folder\n\n def getFolderExists(self):\n return os.path.exists(self._folder)\n\n def getParentFolder(self):\n return os.path.dirname(self._folder)\n\n def getShowSeq(self):\n return self._showSeq\n\n def getSize(self):\n return len(self._fileItems) - 1\n\n # ## Setters ## #\n\n def setFilter(self, nameFilter):\n self._nameFilter = nameFilter\n self.updateFileItems(self._folder)\n self.nameFilterChange.emit()\n\n def setFolder(self, folder):\n logging.debug('fileModelBrowser.setFolder(\"%s\")' % folder)\n self._folder = folder\n self.updateFileItems(folder)\n self.folderChanged.emit()\n\n def setShowSeq(self, checkSeq):\n self._showSeq = checkSeq\n self.updateFileItems(self._folder)\n self.showSeqChanged.emit()\n\n # ############################################# Data exposed to QML ############################################# #\n\n folderChanged = QtCore.pyqtSignal()\n folder = QtCore.pyqtProperty(str, getFolder, setFolder, notify=folderChanged)\n exists = QtCore.pyqtProperty(bool, getFolderExists, notify=folderChanged)\n parentFolder = QtCore.pyqtProperty(str, getParentFolder, constant=True)\n\n fileItems = QtCore.pyqtProperty(QtCore.QObject, getFileItems, notify=folderChanged)\n nameFilterChange = QtCore.pyqtSignal()\n nameFilter = QtCore.pyqtProperty(str, getFilter, setFilter, notify=nameFilterChange)\n size = QtCore.pyqtProperty(int, getSize, constant=True)\n showSeqChanged = QtCore.pyqtSignal()\n showSeq = QtCore.pyqtProperty(bool, getShowSeq, setShowSeq, notify=showSeqChanged)\n\n","sub_path":"buttleofx/gui/browser/fileModelBrowser.py","file_name":"fileModelBrowser.py","file_ext":"py","file_size_in_byte":13145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"281458129","text":"from sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\n\nfrom feature_engine.imputation import (\n AddMissingIndicator,\n MeanMedianImputer,\n CategoricalImputer,\n)\n\nfrom feature_engine.encoding import (\n RareLabelEncoder,\n OneHotEncoder,\n)\n\nfrom classification_model.config.core import config\nfrom classification_model.processing import features as pp\n\n\ntitanic_pipe = Pipeline([\n\n # ==== IMPUTATION ====\n # imputer categorical varaibles with string 'missing\"\n ('categorical_imputation', CategoricalImputer(\n imputation_method=\"missing\",\n variables=config.model_config.categorical_vars,\n )\n ),\n\n # add missing indicator to numerical variables\n ('missing_indicator', AddMissingIndicator(\n variables=config.model_config.numerical_vars\n )\n ),\n\n # imputer numerical variables with the median\n ('median_imputation', MeanMedianImputer(\n imputation_method=\"median\",\n variables=config.model_config.numerical_vars\n )\n ),\n\n # ==== CATEGORICAL ENCODING ====\n # remove categories present in less than 5% of the obeservations\n # group thme into one category called 'Rare'\n ('rare_label_encoder', RareLabelEncoder(\n tol=config.model_config.tol,\n n_categories=config.model_config.n_categories,\n variables=config.model_config.categorical_vars,\n )\n ),\n\n # encode categorical variables using one-hot encoding into k-1 variables\n ('categorical_encoder', OneHotEncoder(\n variables=config.model_config.categorical_vars,\n drop_last=True,\n )\n ),\n\n # scale using standardization\n ('scaler', StandardScaler()),\n\n # logistic regression\n ('Logit', LogisticRegression(\n C=config.model_config.c,\n random_state=config.model_config.random_state,\n )\n ),\n])","sub_path":"assignment-4-titantic-prod/classification_model/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"110340643","text":"def quardrequat(a,b,c):\r\n import math\r\n if not all ([ isinstance(a,(int,float)) , isinstance(b,(int,float)) , isinstance(c,(int,float))]):\r\n raise TypeError('\\n bad input.\\n check if all the input are integars or floats.')\r\n else:\r\n a=float(a)\r\n b=float(b)\r\n c=float(c)\r\n delta=b**2-4*a*c\r\n if delta<0:\r\n return 'No answer exists.'\r\n if delta==0:\r\n x=-b/(2*a)\r\n x=float(' %.4f ' %x )\r\n return x\r\n if delta>0:\r\n x1=(-b+math.sqrt(delta))/(2*a)\r\n x2=(-b-math.sqrt(delta))/(2*a)\r\n x1=float(' %.4f ' %x1 )\r\n x2=float(' %.4f ' %x2 )\r\n return x1 , x2\r\n","sub_path":"equationsolver-function.py","file_name":"equationsolver-function.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"404749824","text":"from odoo import models, fields, api,_\r\nfrom datetime import date,datetime,time,timedelta\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom odoo.exceptions import UserError\r\n\r\n\r\nclass HrExpensesExpenses(models.Model):\r\n _name = 'hr.expenses.expenses'\r\n _rec_name = 'expensescc_id'\r\n\r\n expensescc_id = fields.Many2one(comodel_name=\"hr.expense\", string=\"Expenses\",)\r\n date = fields.Date(string=\"Date\", required=False, )\r\n total_amount = fields.Float(string=\"Total Amount\", required=False, )\r\n expen_id = fields.Many2one(comodel_name=\"hr.expense\", string=\"\", required=False, )\r\n\r\n\r\n\r\n\r\nclass HRExpensesInherit(models.Model):\r\n _inherit = 'hr.expense'\r\n\r\n sales_id = fields.Many2one(comodel_name=\"operation.operation\", string=\"Operation\",)\r\n sales_state = fields.Char(string=\"Sales State\",compute='compute_sales_state')\r\n operations_type = fields.Many2one(comodel_name=\"product.operation.type\", string=\"Operation Type\",)\r\n is_sales = fields.Boolean(string=\"IS Sales\",related='product_id.is_sales_order')\r\n\r\n # expenses_ids = fields.Many2many(comodel_name=\"hr.expense\", relation=\"expenses_relation\", column1=\"expenses_col1\", column2=\"expenses_col2\", string=\"Expenses\",)\r\n expenses_lines_ids = fields.One2many(comodel_name=\"hr.expenses.expenses\", inverse_name=\"expen_id\", string=\"\", required=False, )\r\n is_expenses_ids = fields.Boolean(string=\"\",compute='filter_sales_id' )\r\n\r\n partner_surgeon_id = fields.Many2one(comodel_name=\"res.partner\", string=\"Surgeon\")\r\n event_id = fields.Many2one(comodel_name=\"hr.expenses.event\", string=\"Event\", )\r\n sale_order_mandatory = fields.Boolean(string=\"Sale Order Mandatory\",related='product_id.property_account_expense_id.sale_order_mandatory')\r\n\r\n total_expense_amount = fields.Float(string=\"Total Amount\",compute='compute_total_expense_amount')\r\n\r\n num_day_expire = fields.Integer(compute='compute_num_day_expire' )\r\n\r\n\r\n def get_all_operation_type(self):\r\n for rec in self.search([]):\r\n if not rec.operations_type:\r\n rec.operations_type = rec.sales_id.operation_type\r\n\r\n @api.onchange('sales_id')\r\n def compute_operations_type(self):\r\n self.operations_type = self.sales_id.operation_type\r\n\r\n # def write(self, vals):\r\n # res=super(HRExpensesInherit, self).write(vals)\r\n # if self.env.user.has_group('surgi_sales_expenses.expenses_only_view_group') and vals:\r\n # print(res,\"HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\")\r\n # raise UserError(_('Permission Denied.'))\r\n #\r\n # return res\r\n\r\n def compute_num_day_expire(self):\r\n expiration_rec = self.env['hr.expense.expiration'].search([],limit=1)\r\n for rec in self:\r\n rec.num_day_expire=expiration_rec.num_day_expire\r\n if rec.num_day_expire:\r\n\r\n rec.filter_value_sales()\r\n\r\n # @api.depends('sales_id','expenses_lines_ids')\r\n def compute_total_expense_amount(self):\r\n for rec in self:\r\n total_expense_amount=0.0\r\n for line in rec.expenses_lines_ids:\r\n total_expense_amount+=line.total_amount\r\n rec.total_expense_amount=total_expense_amount\r\n @api.depends('sales_id')\r\n def compute_sales_state(self):\r\n for rec in self:\r\n rec.sales_state=''\r\n if rec.sales_id:\r\n rec.sales_state =rec.sales_id.state\r\n\r\n\r\n\r\n @api.onchange('name','date','sales_id')\r\n def filter_value_sales(self):\r\n sales_list=[]\r\n today_date = datetime.strptime(str(date.today()), '%Y-%m-%d').date()\r\n operation_rec = self.env['operation.operation'].search([])\r\n expiration_rec = self.env['hr.expense.expiration'].search([],limit=1)\r\n for rec in operation_rec:\r\n if rec.start_datetime:\r\n date_order = datetime.strptime(str(rec.start_datetime).split(\".\")[0],\r\n '%Y-%m-%d %H:%M:%S').date()\r\n\r\n if expiration_rec and int(str((today_date - date_order).days))<=expiration_rec.num_day_expire:\r\n sales_list.append(rec.id)\r\n return {\r\n 'domain': {'sales_id': [('id', 'in',sales_list )]}\r\n }\r\n\r\n @api.depends('sales_id')\r\n def filter_sales_id(self):\r\n for expen in self:\r\n line_list = [(5,0,0)]\r\n expen.is_expenses_ids=False\r\n for rec in self.search([]):\r\n if expen._origin.id !=rec.id and expen.sales_id.id==rec.sales_id.id:\r\n line_list.append((0,0,{\r\n 'expensescc_id': rec.id,\r\n 'date': rec.date,\r\n 'total_amount': rec.total_amount,\r\n }))\r\n expen.is_expenses_ids=True\r\n if expen.sales_id and line_list:\r\n expen.update({'expenses_lines_ids':line_list})\r\n else:\r\n expen.expenses_lines_ids=False\r\n\r\n @api.onchange('employee_id','product_id')\r\n def filter_product_id(self):\r\n product_list=[]\r\n\r\n for rec in self.env['product.product'].search([('can_be_expensed', '=', True)]):\r\n if self.employee_id.department_id.id in rec.department_ids.ids:\r\n product_list.append(rec.id)\r\n\r\n return {\r\n 'domain': {'product_id': [('id', 'in', product_list)]}\r\n }\r\n\r\nclass HrExpenseSheetInherit(models.Model):\r\n _inherit = 'hr.expense.sheet'\r\n\r\n account_reviewed= fields.Boolean(string=\"Account Reviewed\", )\r\n treasury_manager= fields.Boolean(string=\"Treasury Manager\", )\r\n check_access_expense = fields.Boolean(compute=\"compute_check_access_expense\")\r\n\r\n\r\n\r\n\r\n @api.depends('state')\r\n def compute_check_access_expense(self):\r\n for rec in self:\r\n\r\n if rec.state in ['draft','submit']:\r\n\r\n rec.check_access_expense = True\r\n elif not self.env.user.has_group('surgi_sales_expenses.expenses_add_line_group') and rec.state=='approve' :\r\n\r\n rec.check_access_expense = False\r\n elif self.env.user.has_group('surgi_sales_expenses.expenses_add_line_group') :\r\n\r\n rec.check_access_expense = True\r\n else:\r\n\r\n rec.check_access_expense = False\r\n\r\n def button_account_reviewed(self):\r\n self.account_reviewed=True\r\n def button_treasury_manager(self):\r\n self.treasury_manager=True\r\n\r\n def action_sheet_move_create(self):\r\n res=super(HrExpenseSheetInherit, self).action_sheet_move_create()\r\n if self.account_move_id:\r\n self.account_move_id.date=date.today()\r\n # for rec in self.expense_line_ids:\r\n # for line in self.account_move_id.line_ids:\r\n # # if rec.product_id==line.product_id:\r\n # line.name= \"[\"+rec.product_id.default_code+\"]\" +\" \" +rec.product_id.name\r\n return res\r\n\r\nclass AccountAccountInherit(models.Model):\r\n _inherit = 'account.account'\r\n\r\n sale_order_mandatory = fields.Boolean(string=\"Sale Order Mandatory\", )\r\n","sub_path":"surgi_sales_expenses/models/expenses.py","file_name":"expenses.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"278520491","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 25 18:37:27 2019\n\n@author: Poor\n\"\"\"\n\nfrom flask import Blueprint,request,session\nfrom .blog_sql import get_sql,close_sql\n\nbp=Blueprint('record',__name__,url_prefix='/record')\n\n@bp.route('/view',methods=['POST'])\ndef view_rec():\n error=None\n try:\n user_id=int(session.get('user_id'))\n except:\n user_id=None\n try:\n article_id=int(request.args.get('article_id',0))\n except ValueError:\n error='{\"code\":400,\"errmsg\":\"article_id is expected to be a int\"}'\n user_ip=request.headers.get('user_ip')\n if user_ip is None:\n error='{\"code\":400,\"errmsg\":\"unknown ip\"}'\n if error is not None:\n return error\n \n try:\n sql_conn=get_sql()\n with sql_conn.begin() as connection:\n sql_insert='''\n insert ignore into \n my_viewer \n (viewer_ip,viewer_id,article_id) \n values \n (@vip,@vid,@aid) \n '''\n connection.execute(\"set @vip = '{}'\".format(user_ip))\n connection.execute(\"set @vid = '{}'\".format(user_id))\n connection.execute(\"set @aid = '{}'\".format(article_id))\n connection.execute(sql_insert)\n return '{\"code\":200,\"errmsg\":\"OK\"}'\n finally:\n close_sql()\n","sub_path":"rear/blog_server/blog_record.py","file_name":"blog_record.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"2766524","text":"# Random Forest Algorithm\r\n# data preparation\r\nimport math\r\nfrom utils import *\r\nimport pandas as pd\r\n\r\ntraining = \"training_result.csv\"\r\ntrain_data = pd.read_csv(training, sep=',')\r\n\r\ntesting = \"testing_result.csv\"\r\ntest_data = pd.read_csv(testing, sep=',')\r\nID = test_data.ix[:, :1].values\r\ntest_data = test_data.ix[:, 1:].values\r\n\r\n# training~~~~~~~~~~~~~~~~~~\r\nn_folds = 3\r\nmax_depth = 10\r\nmin_size = 1\r\nsample_size = 1.0\r\nn_trees = 5\r\nn_features = 11\r\ntest_ratio = 0.8\r\n\r\n# initial and fit random_forest with train_data\r\nrf = random_forest(train_data, n_folds, max_depth, min_size, sample_size, n_trees, n_features, test_ratio)\r\nrf.best_trained_tree() # select best trees amount all folds\r\n\r\n# testing~~~~~~~~~~~~~~~~~~\r\npredictions = rf.predict_test_data(test_data)\r\n\r\n# write the testing result in a text file\r\nfile = open('max_output.txt', 'w')\r\nfor i in range(len(predictions)):\r\n temp = str(ID[i]) + \": \" + str(int(predictions[i]))\r\n file.write(temp)\r\n file.write('\\n')\r\nfile.close()\r\n","sub_path":"data_classification.py","file_name":"data_classification.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"422978156","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime\nimport re\n\nSYS_UPGRADE_LOG_FILENAME = '/var/log/pacman.log'\nUPGRADE_MESSAGE_PATTERN = r'full system upgrade'\nUPGRADE_DATE_PATTERN = r'(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})'\nSUCCESS_COLOR = '#3b7008'\nFAILURE_COLOR = '#4d0b0b'\n\nwith open(SYS_UPGRADE_LOG_FILENAME) as logfile:\n loglines = logfile.readlines()\n for line in reversed(loglines):\n if re.search(UPGRADE_MESSAGE_PATTERN, line):\n match = re.search(UPGRADE_DATE_PATTERN, line)\n if match:\n log_datetime = match.group(1)\n upgrade_datetime = datetime.strptime(\n log_datetime,\n '%Y-%m-%d %H:%M'\n )\n daydiff = (datetime.now() - upgrade_datetime).days\n print(daydiff)\n print(daydiff)\n if daydiff > 1:\n print(FAILURE_COLOR)\n else:\n print(SUCCESS_COLOR)\n break\n","sub_path":"pacman_last_sys_upgrade.py","file_name":"pacman_last_sys_upgrade.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"593964974","text":"# coding=utf-8\r\n\r\n\"\"\"\r\nFind all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.\r\n\r\n\r\nExample 1:\r\n\r\nInput: k = 3, n = 7\r\n\r\nOutput:\r\n\r\n[[1,2,4]]\r\n\r\nExample 2:\r\n\r\nInput: k = 3, n = 9\r\n\r\nOutput:\r\n\r\n[[1,2,6], [1,3,5], [2,3,4]]\r\n\"\"\"\r\n\r\n\r\n# Definition for a binary tree node.\r\nclass Solution(object):\r\n def combinationSum3(self, k, n):\r\n \"\"\"\r\n :type k: int\r\n :type n: int\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n\r\n def _dfs(nums, k, n, usedNumIndex, path, ret):\r\n if k < 0 or n < 0: return\r\n if k == 0 and n == 0: ret.append(path)\r\n for i in range(usedNumIndex, len(nums)):\r\n _dfs(nums, k - 1, n - nums[i], i + 1, path + [nums[i]], ret)\r\n\r\n ret = []\r\n _dfs(range(1, 10), k, n, 0, [], ret)\r\n return ret\r\n\r\n\r\nif __name__ == '__main__':\r\n print(Solution().combinationSum3(4, 15))\r\n","sub_path":"zishell/solution/medium/solution216_combinationSumIII.py","file_name":"solution216_combinationSumIII.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"328501246","text":"#!/usr/bin/env python2.7\n\"\"\"\nThin wrapper for vcfeval, as a convenience to stick a vcfeval output directory\nalong with the other toil-vg output. Can be run standalone as well.\n\"\"\"\nfrom __future__ import print_function\nimport argparse, sys, os, os.path, random, subprocess, shutil, itertools, glob\nimport json, time, timeit, errno\nfrom uuid import uuid4\nimport logging\n\nfrom toil.common import Toil\nfrom toil.job import Job\nfrom toil.realtimeLogger import RealtimeLogger\nfrom toil_vg.vg_common import *\nfrom toil_vg.context import Context, run_write_info_to_outstore\n\nlogger = logging.getLogger(__name__)\n\ndef vcfeval_subparser(parser):\n \"\"\"\n Create a subparser for vcf evaluation. Should pass in results of subparsers.add_parser()\n \"\"\"\n\n # Add the Toil options so the job store is the first argument\n Job.Runner.addToilOptions(parser)\n\n # General options\n parser.add_argument(\"--call_vcf\", type=make_url, required=True,\n help=\"input vcf (must be bgzipped and have .tbi\")\n parser.add_argument(\"out_store\",\n help=\"output store. All output written here. Path specified using same syntax as toil jobStore\")\n # Add common options shared with everybody\n add_common_vg_parse_args(parser)\n\n # Add common calling options shared with toil_vg pipeline\n vcfeval_parse_args(parser)\n\n # Add common docker options shared with toil_vg pipeline\n add_container_tool_parse_args(parser)\n\ndef vcfeval_parse_args(parser):\n \"\"\" centralize reusable vcfevaling parameters here \"\"\"\n\n parser.add_argument(\"--vcfeval_baseline\", type=make_url,\n help=\"Path to baseline VCF file for comparison (must be bgzipped and have .tbi)\")\n\n parser.add_argument(\"--vcfeval_fasta\", type=make_url,\n help=\"Path to DNA sequence file, required for vcfeval. Maybe be gzipped\")\n\n parser.add_argument(\"--vcfeval_bed_regions\", type=make_url,\n help=\"BED file of regions to consider\")\n parser.add_argument(\"--vcfeval_opts\", type=str,\n help=\"Additional options for vcfeval (wrapped in \\\"\\\")\",\n default=None)\n parser.add_argument(\"--vcfeval_cores\", type=int,\n default=1,\n help=\"Cores to use for vcfeval\")\n parser.add_argument(\"--vcfeval_score_field\", default=None,\n help=\"vcf FORMAT field to use for ROC score. overrides vcfeval_opts\")\n parser.add_argument(\"--vcfeval\", action=\"store_true\",\n help=\"run rtg vcfeval comparison. (will be run by default if no other tool specified)\")\n parser.add_argument(\"--happy\", action=\"store_true\",\n help=\"run hap.py comparison.\")\n parser.add_argument(\"--sveval\", action=\"store_true\",\n help=\"run bed-based sv comparison.\")\n parser.add_argument(\"--min_sv_len\", type=int, default=20,\n help=\"minimum length to consider when doing bed sv comparison (using --sveval)\")\n parser.add_argument(\"--sv_region_overlap\", type=float, default=1.0,\n help=\"sv must overlap bed region (--vcfeval_bed_regions) by this fraction to be considered\")\n parser.add_argument(\"--sv_overlap\", type=float, default=0.5,\n help=\"minimum reciprical overlap required for bed intersection to count as TP\")\n parser.add_argument(\"--sv_smooth\", type=int, default=0,\n help=\"mege up svs (in calls and truth) that are at most this many bases apart\")\n\ndef validate_vcfeval_options(options):\n \"\"\" check some options \"\"\"\n # we can relax this down the road by optionally doing some compression/indexing\n assert options.vcfeval_baseline and options.vcfeval_baseline.endswith(\".vcf.gz\")\n assert options.call_vcf.endswith(\".vcf.gz\")\n\n assert not (options.happy or options.vcfeval) or options.vcfeval_fasta\n\n \ndef parse_f1(summary_path):\n \"\"\" grab the best f1 out of vcfeval's summary.txt \"\"\"\n\n # get the F1 out of summary.txt\n # expect header on 1st line and data on 3rd and below\n # we take the best F1 found over these lines (which should correspond to best\n # point on quality ROC curve)\n # todo: be more robust\n f1 = None\n with open(summary_path) as sum_file:\n header = sum_file.readline().split()\n assert header[-1] == 'F-measure' \n line = sum_file.readline()\n for line in sum_file:\n data = line.strip().split()\n assert len(data) == len(header)\n line_f1 = float(data[-1])\n if f1 is None or line_f1 > f1:\n f1 = line_f1\n return f1\n\ndef parse_happy_summary(summary_path):\n \"\"\" Turn the happy summary into a dictionary we can easily get F1 scores etc. from \"\"\"\n results = {} # make something like: results[INDEL][METRIC.F1_Score] = 0.9x\n with open(summary_path) as sum_file:\n header = sum_file.readline().split(',')\n for line in sum_file:\n row = line.split(',')\n cat = row[0]\n if row[1] == 'ALL':\n cat += '.ALL'\n assert cat not in results\n results[cat] = {}\n for column in range(1, len(header)):\n results[cat][header[column]] = row[column] if len(row[column]) else '0'\n return results\n\ndef run_vcfeval_roc_plot(job, context, roc_table_ids, names=[], kind=None, number=0, title=None,\n show_scores=False, line_width=2, ps_plot=False):\n \"\"\"\n Draw some rocs from the vcfeval output. Return (snps_id, nonsnps_id,\n weighted_id)\n \n kind specifies the subtype of roc plot (e.g. 'snp-unclipped'). number gives\n the number of this plot in all plots of that kind. title gives an optional\n human-readable title.\n \"\"\"\n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # dummy default names\n if not names:\n names = ['vcfeval_output-{}'.format(i) for i in range(len(roc_table_ids))]\n\n # rely on unique input names\n assert len(names) == len(set(names))\n \n # download the files\n table_file_paths = [os.path.join(work_dir, name, name) + '.tsv.gz' for name in names]\n table_file_rel_paths = [os.path.join(name, name) + '.tsv.gz' for name in names]\n for table_path, name, file_id in zip(table_file_paths, names, roc_table_ids):\n # rtg gets naming information from directory structure, so we read each file into\n # its own dir\n os.makedirs(os.path.join(work_dir, name))\n job.fileStore.readGlobalFile(file_id, table_path)\n RealtimeLogger.info('Downloaded {} to {}'.format(file_id, table_path))\n\n # Make sure the kind has 'roc' in it\n if kind is None:\n kind = 'roc'\n else:\n kind = 'roc-{}'.format(kind)\n \n plot_filename = title_to_filename(kind, number, title, 'svg')\n out_roc_path = os.path.join(work_dir, plot_filename)\n\n roc_opts = []\n if title:\n roc_opts += ['--title', title]\n if show_scores:\n roc_opts += ['--scores']\n if line_width:\n roc_opts += ['--line-width', line_width]\n if ps_plot:\n roc_opts += ['precision-sensitivity']\n\n out_ids = []\n\n roc_cmd = ['rtg', 'rocplot', '--svg', os.path.basename(out_roc_path)]\n roc_cmd += roc_opts + table_file_rel_paths\n \n context.runner.call(job, roc_cmd, work_dir = work_dir)\n\n return context.write_output_file(job, out_roc_path, os.path.join('plots', plot_filename))\n\ndef run_extract_sample_truth_vcf(job, context, sample, input_baseline_id, input_baseline_tbi_id):\n \"\"\"\n \n Extract a single-sample truth VCF from the given truth VCF .vcf.gz and .vcf.gz.tbi.\n \n Returns a pair of file IDs for the resulting .vcf.gz and .vcf.gz.tbi.\n \n Filtering the truth down is useful because it can save memory.\n \n TODO: use this in toil-vg vcfeval, instead of just providing it as a utility.\n \n \"\"\"\n \n # Make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n \n # Download the truth vcf\n vcfeval_baseline_name = 'full-truth.vcf.gz'\n job.fileStore.readGlobalFile(input_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(input_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi')) \n \n # Make the single-sample VCF\n single_name = 'single-truth-{}.vcf.gz'.format(sample)\n context.runner.call(job, ['bcftools', 'view', vcfeval_baseline_name, '-s', sample, '-o', single_name, '-O', 'z'], work_dir=work_dir)\n \n # Index it\n context.runner.call(job, ['tabix', '-f', '-p', 'vcf', single_name], work_dir=work_dir)\n \n # Upload file and index\n single_vcf_id = context.write_output_file(job, os.path.join(work_dir, single_name))\n single_vcf_tbi_id = context.write_output_file(job, os.path.join(work_dir, single_name + '.tbi'))\n \n return single_vcf_id, single_vcf_tbi_id\n\ndef run_vcfeval(job, context, sample, vcf_tbi_id_pair, vcfeval_baseline_id, vcfeval_baseline_tbi_id, \n fasta_path, fasta_id, bed_id, out_name = None, score_field=None):\n \"\"\"\n \n Run RTG vcf_eval to compare VCFs.\n \n Return a results dict like:\n \n {\n \"f1\": f1 score as float,\n \"summary\": summary file ID,\n \"archive\": output archive ID,\n \"snp\": ROC .tsv.gz data file ID for SNPs,\n \"non_snp\": ROC .tsv.gz data file ID for non-SNP variants,\n \"weighted\": ROC .tsv.gz data file ID for a weighted combination of SNP and non-SNP variants\n }\n \n Some ROC data file IDs may not be present if they were not calculated.\n \n \"\"\"\n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # download the vcf\n call_vcf_id, call_tbi_id = vcf_tbi_id_pair[0], vcf_tbi_id_pair[1]\n call_vcf_name = \"calls.vcf.gz\"\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[0], os.path.join(work_dir, call_vcf_name))\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[1], os.path.join(work_dir, call_vcf_name + '.tbi'))\n\n # and the truth vcf\n vcfeval_baseline_name = 'truth.vcf.gz'\n job.fileStore.readGlobalFile(vcfeval_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(vcfeval_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi')) \n # download the fasta (make sure to keep input extension)\n fasta_name = \"fa_\" + os.path.basename(fasta_path)\n job.fileStore.readGlobalFile(fasta_id, os.path.join(work_dir, fasta_name))\n\n # download the bed regions\n bed_name = \"bed_regions.bed\" if bed_id else None\n if bed_id:\n job.fileStore.readGlobalFile(bed_id, os.path.join(work_dir, bed_name))\n\n # use out_name if specified, otherwise sample\n if sample and not out_name:\n out_name = sample \n if out_name:\n out_tag = '{}_vcfeval_output'.format(out_name)\n else:\n out_tag = 'vcfeval_output'\n \n # output directory\n out_name = out_tag\n # indexed sequence\n sdf_name = fasta_name + \".sdf\"\n \n # make an indexed sequence (todo: allow user to pass one in)\n context.runner.call(job, ['rtg', 'format', fasta_name, '-o', sdf_name], work_dir=work_dir) \n\n # run the vcf_eval command\n cmd = ['rtg', 'vcfeval', '--calls', call_vcf_name,\n '--baseline', vcfeval_baseline_name,\n '--template', sdf_name, '--output', out_name,\n '--threads', str(context.config.vcfeval_cores)]\n\n if bed_name is not None:\n cmd += ['--evaluation-regions', bed_name]\n\n if context.config.vcfeval_opts:\n cmd += context.config.vcfeval_opts\n\n # override score field from options with one from parameter\n if score_field:\n for opt in ['-f', '--vcf-score-field']:\n if opt in cmd:\n opt_idx = cmd.index(opt)\n del cmd[opt_idx]\n del cmd[opt_idx]\n cmd += ['--vcf-score-field', score_field]\n \n if sample:\n # Pass the sample name along, since it is needed if the truth VCF has multiple samples\n cmd += ['--sample', sample]\n\n \n try:\n context.runner.call(job, cmd, work_dir=work_dir)\n except:\n # Dump everything we need to replicate the alignment\n logging.error(\"VCF evaluation failed. Dumping files.\")\n context.write_output_file(job, os.path.join(work_dir, call_vcf_name))\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name))\n # TODO: Dumping the sdf folder doesn't seem to work right. But we can dump the fasta\n context.write_output_file(job, os.path.join(work_dir, fasta_name))\n if bed_name is not None:\n context.write_output_file(job, os.path.join(work_dir, bed_name))\n \n raise\n\n\n # copy results to outstore \n \n # vcfeval_output_summary.txt\n out_summary_id = context.write_output_file(job, os.path.join(work_dir, out_tag, 'summary.txt'),\n out_store_path = '{}_summary.txt'.format(out_tag))\n\n # vcfeval_output.tar.gz -- whole shebang\n context.runner.call(job, ['tar', 'czf', out_tag + '.tar.gz', out_tag], work_dir = work_dir)\n out_archive_id = context.write_output_file(job, os.path.join(work_dir, out_tag + '.tar.gz'))\n\n # truth VCF\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name))\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name + '.tbi'))\n \n # vcfeval_output_f1.txt (used currently by tests script)\n f1 = parse_f1(os.path.join(work_dir, os.path.basename(out_name), \"summary.txt\"))\n f1_path = os.path.join(work_dir, \"f1.txt\") \n with open(f1_path, \"w\") as f:\n f.write(str(f1))\n context.write_output_file(job, f1_path, out_store_path = '{}_f1.txt'.format(out_tag))\n\n # Start the output dict\n out_dict = {\n \"f1\": f1, \n \"summary\": out_summary_id, \n \"archive\": out_archive_id\n }\n\n # roc data (written to outstore to allow re-plotting)\n for roc_name in ['snp', 'non_snp', 'weighted']:\n roc_file = os.path.join(work_dir, out_tag, '{}_roc.tsv.gz'.format(roc_name))\n if os.path.isfile(roc_file):\n # Save this one\n dest_file = os.path.join('roc', out_tag, '{}_roc.tsv.gz'.format(roc_name))\n out_dict[roc_name] = context.write_output_file(job, roc_file, dest_file)\n\n return out_dict\n\ndef run_happy(job, context, sample, vcf_tbi_id_pair, vcfeval_baseline_id, vcfeval_baseline_tbi_id, \n fasta_path, fasta_id, bed_id, fasta_idx_id = None, out_name = None):\n \"\"\"\n \n Run hap.py to compare VCFs.\n \n Return a results dict like:\n \n {\n \"parsed_summary\": parsed summary file dict, including F1 scores,\n \"summary\": summary file ID,\n \"archive\": output archive ID\n }\n \n The parsed summary dict is by variant type ('SNP', 'INDEL'), and then by metric name (like 'METRIC.F1_Score').\n \n \"\"\"\n \n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # download the vcf\n call_vcf_id, call_tbi_id = vcf_tbi_id_pair[0], vcf_tbi_id_pair[1]\n call_vcf_name = \"calls.vcf.gz\"\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[0], os.path.join(work_dir, call_vcf_name))\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[1], os.path.join(work_dir, call_vcf_name + '.tbi'))\n\n # and the truth vcf\n vcfeval_baseline_name = 'truth.vcf.gz'\n job.fileStore.readGlobalFile(vcfeval_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(vcfeval_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi'))\n \n # download the fasta (make sure to keep input extension)\n fasta_name = \"fa_\" + os.path.basename(fasta_path)\n job.fileStore.readGlobalFile(fasta_id, os.path.join(work_dir, fasta_name))\n\n # download or create the fasta index which is required by hap.py\n if fasta_idx_id:\n job.fileStore.readGlobalFile(fasta_idx_id, os.path.join(work_dir, fasta_name + '.fai'))\n else:\n context.runner.call(job, ['samtools', 'faidx', fasta_name], work_dir=work_dir)\n\n # download the bed regions\n bed_name = \"bed_regions.bed\" if bed_id else None\n if bed_id:\n job.fileStore.readGlobalFile(bed_id, os.path.join(work_dir, bed_name))\n\n # use out_name if specified, otherwise sample\n if sample and not out_name:\n out_name = sample \n if out_name:\n out_tag = '{}_happy'.format(out_name)\n else:\n out_tag = 'happy_output'\n \n # output directory\n out_name = os.path.join(out_tag, 'happy')\n os.makedirs(os.path.join(work_dir, out_tag))\n \n # run the hap.py command\n cmd = ['hap.py', vcfeval_baseline_name, call_vcf_name,\n '--report-prefix', out_name, '--reference', fasta_name, '--write-vcf', '--write-counts', '--no-roc',\n '--threads', str(job.cores)]\n\n if bed_name:\n cmd += ['--false-positives', bed_name]\n \n try:\n context.runner.call(job, cmd, work_dir=work_dir)\n except:\n # Dump everything we need to replicate the alignment\n logging.error(\"hap.py VCF evaluation failed. Dumping files.\")\n context.write_output_file(job, os.path.join(work_dir, call_vcf_name))\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name))\n # TODO: Dumping the sdf folder doesn't seem to work right. But we can dump the fasta\n context.write_output_file(job, os.path.join(work_dir, fasta_name))\n if bed_name is not None:\n context.write_output_file(job, os.path.join(work_dir, bed_name))\n \n raise\n\n\n # copy results to outstore \n \n # happy_output_summary.csv\n out_summary_id = context.write_output_file(job, os.path.join(work_dir, out_name + '.summary.csv'),\n out_store_path = '{}_summary.csv'.format(out_tag))\n\n # happy_output.tar.gz -- whole shebang\n context.runner.call(job, ['tar', 'czf', out_tag + '.tar.gz', out_tag], work_dir = work_dir)\n out_archive_id = context.write_output_file(job, os.path.join(work_dir, out_tag + '.tar.gz'))\n\n # happy_output_f1.txt Snp1-F1 TAB Indel-F1 (of variants marked as PASS)\n happy_results = parse_happy_summary(os.path.join(work_dir, out_name + '.summary.csv'))\n f1_path = os.path.join(work_dir, \"happy_f1.txt\") \n with open(f1_path, \"w\") as f:\n f.write('{}\\t{}\\n'.format(happy_results['SNP']['METRIC.F1_Score'], happy_results['INDEL']['METRIC.F1_Score']))\n context.write_output_file(job, f1_path, out_store_path = '{}_f1.txt'.format(out_tag))\n \n return {\n \"parsed_summary\": happy_results,\n \"summary\": out_summary_id,\n \"archive\": out_archive_id\n }\n\ndef run_sv_eval(job, context, sample, vcf_tbi_id_pair, vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n min_sv_len, sv_overlap, sv_region_overlap, sv_smooth = 0, bed_id = None, out_name = ''):\n \"\"\" Run something like Peter Audano's bed-based comparison. Uses bedtools and bedops to do\n overlap comparison between indels. Of note: the actual sequence of insertions is never checked!\"\"\"\n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # download the vcf\n call_vcf_id, call_tbi_id = vcf_tbi_id_pair[0], vcf_tbi_id_pair[1]\n call_vcf_name = \"{}calls.vcf.gz\".format(out_name)\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[0], os.path.join(work_dir, call_vcf_name))\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[1], os.path.join(work_dir, call_vcf_name + '.tbi'))\n\n # and the truth vcf\n vcfeval_baseline_name = '{}truth.vcf.gz'.format(out_name)\n job.fileStore.readGlobalFile(vcfeval_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(vcfeval_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi'))\n\n # and the regions bed\n if bed_id:\n regions_bed_name = '{}regions.bed'.format(out_name)\n job.fileStore.readGlobalFile(bed_id, os.path.join(work_dir, regions_bed_name))\n else:\n regions_bed_name = None\n\n if out_name and not out_name.endswith('_'):\n out_name = '{}_'.format(out_name)\n\n # convert vcfs to BEDs\n call_bed_name = '{}calls.bed'.format(out_name)\n baseline_bed_name = '{}truth.bed'.format(out_name)\n for vcf_name, bed_name in zip([call_vcf_name, vcfeval_baseline_name], [call_bed_name, baseline_bed_name]):\n # vg call sometimes makes IDs that are too long for bedops. we zap the ids here just in case\n temp_vcf_name = 'idfix-{}.vcf'.format(os.path.splitext(os.path.basename(vcf_name))[0])\n with open(os.path.join(work_dir, temp_vcf_name), 'w') as temp_vcf_file:\n context.runner.call(job, ['bcftools', 'view', '-h', vcf_name],\n work_dir = work_dir, outfile = temp_vcf_file)\n context.runner.call(job, [['bcftools', 'view', '-H', vcf_name],\n ['awk', '-F', '\\t', '-v', 'OFS=\\t', '{$3=\\\".\\\"; print $0;}']],\n work_dir = work_dir, outfile = temp_vcf_file)\n # then convert the fixed if vcf into bed with bedops\n with open(os.path.join(work_dir, bed_name + '.1del'), 'w') as bed_file:\n vcf2bed_cmd = [['cat', temp_vcf_name], ['vcf2bed']]\n context.runner.call(job, vcf2bed_cmd, work_dir = work_dir, outfile = bed_file, tool_name = 'bedops')\n \n # then expand the deletions, as vcf2bed writes them all with 1-sized intervals for some reason\n expand_deletions(os.path.join(work_dir, bed_name + '.1del'), os.path.join(work_dir, bed_name))\n\n # if the region bed's there, intersect both the calls and baseline \n if bed_id:\n clipped_calls_name = \"{}clipped_calls.bed\".format(out_name)\n clipped_baseline_name = \"{}clipped_baseline.bed\".format(out_name)\n\n \"\"\"\n bedtools intersect -a SV_FILE.bed -b sd_regions_200_0.bed -wa -f 0.50 -u\n\n * Get all SV variants that intersect SDs\n * -wa: Print whole SV record (not just the intersecting part)\n * -f 0.50: Require 50% of the SV to be in the SD\n * Prevents very large DELs from being tagged if they intersect with part of a region.\n * -u: Print matching SV call only once (even if it intersects with multiple variants)\n * Probably has no effect because of -f 0.50 and the way merging is done, but I leave it in in case I tweak something.\n \"\"\"\n for bed_name, clipped_bed_name in zip([call_bed_name, baseline_bed_name],\n [clipped_calls_name, clipped_baseline_name]):\n with open(os.path.join(work_dir, clipped_bed_name), 'w') as clipped_bed_file:\n context.runner.call(job, ['bedtools', 'intersect', '-a', bed_name, '-b', regions_bed_name,\n '-wa', '-f', str(sv_region_overlap), '-u'],\n work_dir = work_dir, outfile = clipped_bed_file)\n else:\n clipped_calls_name = call_bed_name\n clipped_baseline_name = baseline_bed_name\n \n # now do the intersection comparison\n\n \"\"\"\n To compare SV calls among sets, I typically use a 50% reciprocal overlap. A BED record of an insertion is only the point of insertion (1 bp) regardless of how large the insertion is. To compare insertions, I add the SV length (SVLEN) to the start position and use bedtools overlap. WARNING: Remember to collapse the insertion records back to one bp. If you accidentally intersected with SDs or TRF regions, SVs would arbitrarily hit records they don't actually intersect. I have snakemake pipelines handle this (bed files in \"byref\" or \"bylen\" directories) so it can never be mixed up.\n\n Intersect SVs:\n\n bedtools intersect -a SV_FILE_A.bed -b SV_FILE_B -wa -f 0.50 -r -u\n\n * Same bedtools command as before, but with \"-r\" to force A to overlap with B by 50% AND B to overlap with A by 50%. \"-u\" becomes important because clustered insertions (common in tandem repeats) will overlap with more than one variant.\n \"\"\"\n\n # expand the bed regions to include the insertion lengths for both sets.\n # we also break insertions and deletions into separate file. Otherwise, insertions can\n # intersect with deletions, inflating our accuracy.\n clipped_calls_ins_name = '{}ins_calls.bed'.format(out_name)\n clipped_baseline_ins_name = '{}ins_calls_baseline.bed'.format(out_name)\n clipped_calls_del_name = '{}del_calls.bed'.format(out_name)\n clipped_baseline_del_name = '{}del_calls_baseline.bed'.format(out_name)\n expand_insertions(os.path.join(work_dir, clipped_calls_name), os.path.join(work_dir, clipped_calls_ins_name),\n os.path.join(work_dir, clipped_calls_del_name), min_sv_len)\n expand_insertions(os.path.join(work_dir, clipped_baseline_name), os.path.join(work_dir, clipped_baseline_ins_name),\n os.path.join(work_dir, clipped_baseline_del_name), min_sv_len)\n\n tp_ins_name = '{}ins-TP-call.bed'.format(out_name)\n tp_del_name = '{}del-TP-call.bed'.format(out_name)\n tp_ins_rev_name = '{}ins-TP-baseline.bed'.format(out_name)\n tp_del_rev_name = '{}del-TP-baseline.bed'.format(out_name)\n fp_ins_name = '{}ins-FP.bed'.format(out_name)\n fp_del_name = '{}del-FP.bed'.format(out_name)\n fn_ins_name = '{}ins-FN.bed'.format(out_name)\n fn_del_name = '{}del-FN.bed'.format(out_name) \n for tp_indel_name, tp_indel_rev_name, calls_bed_indel_name, baseline_bed_indel_name, fp_indel_name, fn_indel_name in \\\n [(tp_ins_name, tp_ins_rev_name, clipped_calls_ins_name, clipped_baseline_ins_name, fp_ins_name, fn_ins_name),\n (tp_del_name, tp_del_rev_name, clipped_calls_del_name, clipped_baseline_del_name, fp_del_name, fn_del_name)]:\n\n # smooth out features so, say, two side-by-side deltions get treated as one. this is in keeping with\n # the coarse-grained nature of the analysis and is optional\n if sv_smooth > 0:\n calls_merge_name = calls_bed_indel_name[:-4] + '_merge.bed'\n baseline_merge_name = baseline_bed_indel_name[:-4] + '_merge.bed' \n with open(os.path.join(work_dir, calls_merge_name), 'w') as calls_merge_file:\n context.runner.call(job, ['bedtools', 'merge', '-d', str(sv_smooth), '-i', calls_bed_indel_name],\n work_dir = work_dir, outfile = calls_merge_file)\n with open(os.path.join(work_dir, baseline_merge_name), 'w') as baseline_merge_file:\n context.runner.call(job, ['bedtools', 'merge', '-d', str(sv_smooth), '-i', baseline_bed_indel_name],\n work_dir = work_dir, outfile = baseline_merge_file)\n calls_bed_indel_name = calls_merge_name\n baseline_bed_indel_name = baseline_merge_name\n \n # run the 50% overlap test described above for insertions and deletions\n with open(os.path.join(work_dir, tp_indel_name), 'w') as tp_file:\n context.runner.call(job, ['bedtools', 'intersect', '-a', calls_bed_indel_name,\n '-b', baseline_bed_indel_name, '-wa', '-f', str(sv_overlap), '-r', '-u'],\n work_dir = work_dir, outfile = tp_file) \n # we run other way so we can get false positives from the calls and true positives from the baseline \n with open(os.path.join(work_dir, tp_indel_rev_name), 'w') as tp_file: \n context.runner.call(job, ['bedtools', 'intersect', '-b', calls_bed_indel_name,\n '-a', baseline_bed_indel_name, '-wa', '-f', str(sv_overlap), '-r', '-u'],\n work_dir = work_dir, outfile = tp_file)\n # put the false positives in their own file\n with open(os.path.join(work_dir, fp_indel_name), 'w') as fp_file:\n context.runner.call(job, ['bedtools', 'subtract', '-a', calls_bed_indel_name,\n '-b', tp_indel_name], work_dir = work_dir, outfile = fp_file)\n # and the false negatives\n with open(os.path.join(work_dir, fn_indel_name), 'w') as fn_file:\n context.runner.call(job, ['bedtools', 'subtract', '-a', baseline_bed_indel_name,\n '-b', tp_indel_rev_name], work_dir = work_dir, outfile = fn_file)\n # todo: should we write them out in vcf as well?\n\n # summarize results into a table\n results = summarize_sv_results(os.path.join(work_dir, tp_ins_name),\n os.path.join(work_dir, tp_ins_rev_name),\n os.path.join(work_dir, fp_ins_name),\n os.path.join(work_dir, fn_ins_name),\n os.path.join(work_dir, tp_del_name),\n os.path.join(work_dir, tp_del_rev_name),\n os.path.join(work_dir, fp_del_name),\n os.path.join(work_dir, fn_del_name))\n\n # write the results to a file\n summary_name = os.path.join(work_dir, '{}sv_accuracy.tsv'.format(out_name))\n with open(summary_name, 'w') as summary_file:\n header = ['Cat', 'TP', 'TP-baseline', 'FP', 'FN', 'Precision', 'Recall', 'F1']\n summary_file.write('#' + '\\t'.join(header) +'\\n')\n summary_file.write('\\t'.join(str(x) for x in ['Total'] + [results[c] for c in header[1:]]) + '\\n')\n summary_file.write('\\t'.join(str(x) for x in ['INS'] + [results['{}-INS'.format(c)] for c in header[1:]]) + '\\n')\n summary_file.write('\\t'.join(str(x) for x in ['DEL'] + [results['{}-DEL'.format(c)] for c in header[1:]]) + '\\n')\n summary_id = context.write_output_file(job, os.path.join(work_dir, summary_name))\n\n # tar up some relavant data\n tar_dir = os.path.join(work_dir, '{}sv_evaluation'.format(out_name))\n os.makedirs(tar_dir)\n for dir_file in os.listdir(work_dir):\n if os.path.splitext(dir_file)[1] in ['.bed', '.tsv', '.vcf.gz', '.vcf.gz.tbi']:\n shutil.copy2(os.path.join(work_dir, dir_file), os.path.join(tar_dir, dir_file))\n context.runner.call(job, ['tar', 'czf', os.path.basename(tar_dir) + '.tar.gz', os.path.basename(tar_dir)],\n work_dir = work_dir)\n archive_id = context.write_output_file(job, os.path.join(work_dir, tar_dir + '.tar.gz'))\n\n return results\n\ndef expand_deletions(in_bed_name, out_bed_name):\n \"\"\"\n Expand every deletion in a BED file and update its end coordinate to reflect its length.\n with open(in_bed_name) as in_bed, open(out_ins_bed_name, 'w') as out_ins, open(out_del_bed_name, 'w') as out_del:\n ** We do this before intersection with regions of interest **\n \"\"\"\n with open(in_bed_name) as in_bed, open(out_bed_name, 'w') as out_bed:\n for line in in_bed:\n if line.strip():\n toks = line.strip().split('\\t')\n ref_len = len(toks[5])\n alt_len = len(toks[6])\n if ref_len > alt_len:\n assert int(toks[2]) == int(toks[1]) + 1\n # expand the deletion\n toks[2] = str(int(toks[1]) + ref_len)\n out_bed.write('\\t'.join(toks) + '\\n')\n else:\n # leave insertions as is for now\n out_bed.write(line)\n\ndef expand_insertions(in_bed_name, out_ins_bed_name, out_del_bed_name, min_sv_size):\n \"\"\"\n Go through every insertion in a BED file and update its end coordinate to reflect its length. This is done\n to compare two sets of insertions. We also break out deletions into their own file. \n ** We do this after intersection with regions of interest but before comparison **\n \"\"\"\n with open(in_bed_name) as in_bed, open(out_ins_bed_name, 'w') as out_ins, open(out_del_bed_name, 'w') as out_del:\n for line in in_bed:\n if line.strip():\n toks = line.strip().split('\\t')\n ref_len = len(toks[5])\n alt_len = len(toks[6])\n # filter out some vg call nonsense\n if toks[5] == '.' or toks[6] == '.':\n continue\n if ref_len < alt_len and alt_len >= min_sv_size:\n assert int(toks[2]) == int(toks[1]) + 1\n # expand the insertion\n toks[2] = str(int(toks[1]) + alt_len)\n out_ins.write('\\t'.join(toks) + '\\n')\n elif ref_len >= min_sv_size:\n # just filter out the deletion\n out_del.write(line)\n\ndef summarize_sv_results(tp_ins, tp_ins_baseline, fp_ins, fn_ins,\n tp_del, tp_del_baseline, fp_del, fn_del):\n \"\"\"\n Use the various bed files to compute accuracies. Also return a tarball of \n all the files used.\n \"\"\"\n def wc(f):\n with open(f) as ff:\n return sum(1 for line in ff)\n\n def pr(tp, fp, fn):\n prec = float(tp) / float(tp + fp) if tp + fp else 0\n rec = float(tp) / float(tp + fn) if tp + fn else 0\n f1 = 2.0 * tp / float(2 * tp + fp + fn) if tp else 0\n return prec, rec, f1\n\n header = []\n row = []\n\n # results in dict\n results = {}\n results['TP-INS'] = wc(tp_ins)\n results['TP-baseline-INS'] = wc(tp_ins_baseline)\n results['FP-INS'] = wc(fp_ins)\n results['FN-INS'] = wc(fn_ins)\n ins_pr = pr(results['TP-INS'], results['FP-INS'], results['FN-INS'])\n results['Precision-INS'] = ins_pr[0]\n results['Recall-INS'] = ins_pr[1]\n results['F1-INS'] = ins_pr[2]\n\n results['TP-DEL'] = wc(tp_del)\n results['TP-baseline-DEL'] = wc(tp_del_baseline)\n results['FP-DEL'] = wc(fp_del)\n results['FN-DEL'] = wc(fn_del)\n del_pr = pr(results['TP-DEL'], results['FP-DEL'], results['FN-DEL'])\n results['Precision-DEL'] = del_pr[0]\n results['Recall-DEL'] = del_pr[1]\n results['F1-DEL'] = del_pr[2]\n\n results['TP'] = results['TP-INS'] + results['TP-DEL']\n results['TP-baseline'] = results['TP-baseline-INS'] + results['TP-baseline-DEL'] \n results['FP'] = results['FP-INS'] + results['FP-DEL']\n results['FN'] = results['FN-INS'] + results['FN-DEL']\n tot_pr = pr(results['TP'], results['FP'], results['FN'])\n results['Precision'] = tot_pr[0]\n results['Recall'] = tot_pr[1]\n results['F1'] = tot_pr[2]\n\n return results \n\ndef vcfeval_main(context, options):\n \"\"\" command line access to toil vcf eval logic\"\"\"\n\n # check some options\n validate_vcfeval_options(options)\n \n # How long did it take to run the entire pipeline, in seconds?\n run_time_pipeline = None\n \n # Mark when we start the pipeline\n start_time_pipeline = timeit.default_timer()\n\n # Default to vcfeval\n if not options.happy and not options.sveval:\n options.vcfeval = True\n\n with context.get_toil(options.jobStore) as toil:\n if not toil.options.restart:\n start_time = timeit.default_timer()\n \n # Upload local files to the remote IO Store\n vcfeval_baseline_id = toil.importFile(options.vcfeval_baseline)\n call_vcf_id = toil.importFile(options.call_vcf)\n vcfeval_baseline_tbi_id = toil.importFile(options.vcfeval_baseline + '.tbi')\n call_tbi_id = toil.importFile(options.call_vcf + '.tbi') \n fasta_id = toil.importFile(options.vcfeval_fasta) if options.vcfeval_fasta else None\n bed_id = toil.importFile(options.vcfeval_bed_regions) if options.vcfeval_bed_regions is not None else None\n\n end_time = timeit.default_timer()\n logger.info('Imported input files into Toil in {} seconds'.format(end_time - start_time))\n\n # Init the outstore\n init_job = Job.wrapJobFn(run_write_info_to_outstore, context, sys.argv)\n \n # Make a root job\n if options.vcfeval:\n vcfeval_job = Job.wrapJobFn(run_vcfeval, context, None,\n (call_vcf_id, call_tbi_id),\n vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n options.vcfeval_fasta, fasta_id, bed_id,\n score_field=options.vcfeval_score_field,\n cores=context.config.vcfeval_cores, memory=context.config.vcfeval_mem,\n disk=context.config.vcfeval_disk)\n init_job.addFollowOn(vcfeval_job)\n \n if options.happy:\n happy_job = Job.wrapJobFn(run_happy, context, None,\n (call_vcf_id, call_tbi_id),\n vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n options.vcfeval_fasta, fasta_id, bed_id,\n cores=context.config.vcfeval_cores, memory=context.config.vcfeval_mem,\n disk=context.config.vcfeval_disk)\n init_job.addFollowOn(happy_job)\n\n if options.sveval: \n sv_job = Job.wrapJobFn(run_sv_eval, context, None,\n (call_vcf_id, call_tbi_id),\n vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n options.min_sv_len, options.sv_overlap, options.sv_region_overlap,\n options.sv_smooth, bed_id, \n cores=context.config.vcfeval_cores, memory=context.config.vcfeval_mem,\n disk=context.config.vcfeval_disk)\n init_job.addFollowOn(sv_job)\n\n # Run the job\n toil.start(init_job)\n else:\n toil.restart()\n\n end_time_pipeline = timeit.default_timer()\n run_time_pipeline = end_time_pipeline - start_time_pipeline\n \n print(\"All jobs completed successfully. Pipeline took {} seconds.\".format(run_time_pipeline))\n \n \n","sub_path":"src/toil_vg/vg_vcfeval.py","file_name":"vg_vcfeval.py","file_ext":"py","file_size_in_byte":38332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"573880016","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2019 Chris Osterwood for Capable Robot Components\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport time\n\nimport board\nimport digitalio\nimport analogio\nfrom micropython import const\n\nfrom adafruit_bus_device.i2c_device import I2CDevice\n\n# pylint: disable=bad-whitespace\n_I2C_ADDR_USB = const(0x2D)\n_REVISION = const(0x0000)\n_VENDOR_ID = const(0x3000)\n_PRODUCT_ID = const(0x3002)\n_DEVICE_ID = const(0x3004)\n_HUB_CONFIG_1 = const(0x3006)\n_HUB_CONFIG_2 = const(0x3007)\n_HUB_CONFIG_3 = const(0x3008)\n_PORT_SWAP = const(0x30FA)\n_HUB_CTRL = const(0x3104)\n_SUSPEND = const(0x3197)\n_POWER_STATUS = const(0x30E5)\n_REMAP_12 = const(0x30FB)\n_REMAP_34 = const(0x30FC)\n_POWER_STATE = const(0x3100)\n_CONNECTION = const(0x3194)\n_DEVICE_SPEED = const(0x3195)\n_POWER_SELECT_1 = const(0x3C00)\n_POWER_SELECT_2 = const(0x3C04)\n_POWER_SELECT_3 = const(0x3C08)\n_POWER_SELECT_4 = const(0x3C0C)\n_CHARGE_CONFIG = const(0x343C)\n \n_CFG_REG_CMD = bytearray([0x99, 0x37, 0x00])\n_DEFAULT_PORT_MAP = [1, 2, 3, 4]\n_CUSTOM_PORT_MAP = [2, 4, 1, 3]\n\n_I2C_ADDR_MCP = const(0x20)\n_GPIO = const(0x09)\n# pylint: enable=bad-whitespace\n\ndef _register_length(addr):\n if addr in [_REVISION]:\n return 4\n\n if addr in [_VENDOR_ID, _PRODUCT_ID, _DEVICE_ID, _POWER_STATE]:\n return 2\n\n return 1\n\ndef bytearry_to_int(b, lsb_first=True):\n if lsb_first:\n x = 0\n shift = 0\n for char in b:\n x |= (char << shift*8)\n shift += 1\n else:\n x = 0\n for char in b:\n x <<= 8\n x |= char\n return x\n\ndef set_bit(value, bit):\n return value | (1< 0 \n\nclass USBHub:\n\n def __init__(self, i2c1_bus, i2c2_bus, force=False):\n\n ## Setup pins so that statue upon switchign to output\n ## is identical to the board electrical default. This\n ## allows object to be created an no state change occur.\n self.pin_rst = digitalio.DigitalInOut(board.USBRESET)\n self.pin_rst.switch_to_output(value=True)\n\n self.pin_hen = digitalio.DigitalInOut(board.USBHOSTEN)\n self.pin_hen.switch_to_output(value=False)\n\n try:\n self.pin_bcen = digitalio.DigitalInOut(board.USBBCEN)\n self.pin_bcen.switch_to_output(value=False)\n except AttributeError:\n print(\"WARN : Firmware does not define pin for battery charge configuration\")\n self.pin_bcen = None\n\n self.vlim = analogio.AnalogIn(board.ANVLIM)\n self.vlogic = analogio.AnalogIn(board.AN5V)\n\n self.i2c_device = I2CDevice(i2c2_bus, _I2C_ADDR_USB, probe=False)\n self.mcp_device = I2CDevice(i2c1_bus, _I2C_ADDR_MCP, probe=False)\n\n ## Here we are using the port remapping to determine if the hub\n ## has been previously configured. If so, we don't need to reset\n ## it or configure it and can just control it as-is.\n ##\n ## If the hub has not been configured (e.g. when the board is first \n ## powered on), this call will raise an OSError. That will then trigger\n ## the normal reset & configure process.\n try:\n self.remap = self.get_port_remap()\n print(\"USB Hub has been configured\")\n except OSError:\n self.remap = _DEFAULT_PORT_MAP\n print(\"USB Hub is in default state\")\n\n if self.remap == _DEFAULT_PORT_MAP or force:\n self.reset()\n self.configure()\n self.set_mcp_config()\n\n def _write_register(self, address, xbytes):\n\n if len(xbytes) != _register_length(address):\n raise ValueError(\"Incorrect payload length for register %d\" % address)\n\n ## 2 bytes for 'write' and count\n ## 4 bytes for address (base + offset)\n ## num bytes actually get written\n length = 2+4+len(xbytes)\n\n ## Prepare the pre-amble\n out = [\n 0x00,\n 0x00,\n length, # Length of rest of packet\n 0x00, # Write configuration register\n len(xbytes) & 0xFF, # Will be writing N bytes (later)\n 0xBF, 0x80,\n (address >> 8) & 0xFF, address & 0xFF\n ]\n\n ## Print address registers and data payload\n # row = [out[7], out[8], len(xbytes)] + list(xbytes)\n # print(row)\n\n with self.i2c_device as i2c:\n ## Write the pre-amble and then the payload\n i2c.write(bytearray(out+xbytes))\n\n ## Execute the Configuration Register Access command\n i2c.write(_CFG_REG_CMD)\n\n def _read_register(self, address):\n length = _register_length(address)\n\n ## Prepare the pre-amble\n out = [\n 0x00,\n 0x00,\n 0x06, # Length of rest of packet\n 0x01, # Read configuration register\n length & 0xFF, # Will be reading N bytes (later)\n 0xBF, 0x80,\n (address >> 8) & 0xFF, address & 0xFF\n ]\n\n inbuf = bytearray(length+1)\n\n with self.i2c_device as i2c:\n ## Write the pre-amble\n i2c.write(bytearray(out))\n\n ## Execute the Configuration Register Access command\n i2c.write(_CFG_REG_CMD)\n\n ## Access the part of memory where our data is\n i2c.write_then_readinto(bytearray([0x00, 0x06]), inbuf, stop=False)\n\n ## First byte is the length of the rest of the message.\n ## We don't want to return that to the caller\n return inbuf[1:length+1]\n\n # pylint: disable=invalid-name\n @property\n def id(self):\n buf = self._read_register(_REVISION)\n device_id = (buf[3] << 8) + buf[2]\n revision_id = buf[0]\n\n return device_id, revision_id\n\n @property\n def vendor_id(self):\n return bytearry_to_int(self._read_register(_VENDOR_ID))\n\n @property\n def product_id(self):\n return bytearry_to_int(self._read_register(_PRODUCT_ID))\n\n @property\n def speeds(self):\n conn = bytearry_to_int(self._read_register(_CONNECTION))\n speed = bytearry_to_int(self._read_register(_DEVICE_SPEED))\n\n out = [0]*5\n\n ## Have to follow logical to physical remapping\n for idx, port in enumerate(self.remap):\n out[port] = (speed >> (idx*2)) & 0b11\n\n ## Upstream port is not in the speed register, so take data from\n ## the connection register. Unfortunately, no way to know speed.\n out[0] = (conn & 0b1)*3\n\n return out\n\n def attach(self):\n ## 0xAA 0x55 : Exit SOC_CONFIG and Enter HUB_CONFIG stage\n ## 0xAA 0x56 : Exit SOC_CONFIG and Enter HUB_CONFIG stage with SMBus slave enabled\n out = [0xAA, 0x56, 0x00]\n\n with self.i2c_device as i2c:\n i2c.write(bytearray(out))\n\n def reset(self): \n time.sleep(0.05)\n\n if self.pin_bcen is not None:\n # Turn on 10 ohm resistor for charge strapping\n self.pin_bcen.value = True\n \n # Put in reset for at least 10 ms\n self.pin_rst.value = False\n time.sleep(0.05)\n\n # Must wait at least 1 ms after RESET_N deassertion for straps to be read\n # Testing has found this delay must be MUCH longer than 1 ms for subsequent\n # I2C calls to suceed.\n self.pin_rst.value = True\n time.sleep(0.05)\n\n if self.pin_bcen is not None:\n # Turn 10 ohm resistor off, so that SPI bus can operate properly\n self.pin_bcen.value = False\n\n def configure(self, opts={}):\n \n if \"highspeed_disable\" in opts.keys():\n highspeed_disable = opts[\"highspeed_disable\"]\n else:\n highspeed_disable = False\n \n self.set_hub_config_1(highspeed_disable=highspeed_disable, multitt_enable=True)\n\n ## Reverse DP/DM pints of upstream port and ports 3 & 4\n self.set_port_swap(values=[True, False, False, True, True])\n self.set_hub_control(lpm_disable=True)\n self.set_hub_config_3(port_map_enable=True)\n\n ## Remap ports so that case physcial markings match the USB\n self.set_port_remap(ports=_CUSTOM_PORT_MAP)\n\n self.set_charging_config()\n\n self.attach()\n\n time.sleep(0.02)\n\n\n def upstream(self, state):\n self.pin_hen.value = not state\n\n def set_port_swap(self, values=[False, False, False, False, False]):\n value = 0\n\n for idx, bit in enumerate(values):\n if bit:\n value = set_bit(value, idx)\n\n self._write_register(_PORT_SWAP, [value])\n\n def set_hub_control(self, lpm_disable=False, reset=False):\n value = lpm_disable << 1 | \\\n reset\n\n self._write_register(_HUB_CTRL, [value])\n\n def set_hub_config_1(self, self_powered=True, vsm_disable=False, highspeed_disable=False, multitt_enable=False, \n eop_disable=False, individual_current_sense=True, individual_port_power=True):\n\n ## individual_current_sense : 0 -> ganged sensing, 1 -> individual, 2 or 3 -> current sense not supported\n\n value = self_powered << 7 | \\\n vsm_disable << 6 | \\\n highspeed_disable << 5 | \\\n multitt_enable << 4 | \\\n eop_disable << 3 | \\\n individual_current_sense << 1 | \\\n individual_port_power\n\n self._write_register(_HUB_CONFIG_1, [value])\n\n def set_hub_config_3(self, port_map_enable=True, string_descriptor_enable=False):\n value = port_map_enable << 3 | \\\n string_descriptor_enable\n\n self._write_register(_HUB_CONFIG_3, [value])\n\n def set_port_remap(self, ports=[1, 2, 3, 4]):\n self.remap = ports\n\n port12 = ((ports[1] << 4) & 0xFF) | (ports[0] & 0xFF)\n port34 = ((ports[3] << 4) & 0xFF) | (ports[2] & 0xFF)\n\n self._write_register(_REMAP_12, [port12])\n self._write_register(_REMAP_34, [port34])\n\n def set_charging_config(self, ports=[1,2,3,4], ucs_lim=0b11, enable=True, dcp=True, se1=0b00, china_mode=False):\n\n ## ucs_lim : When controlling UCS through I2C, this sets the current limit.\n ## 0b00 : 500 mA\n ## 0b01 : 1000 mA\n ## 0b10 : 1500 mA\n ## 0b11 : 2000 mA\n\n ## 'dcp' is Dedicated Charging Mode. Ignored if china_mode is enabled.\n ## This mode only active when a USB Host is not present. When a host is \n ## present, CDP mode is used.\n\n ## Bit 1 & 2 are SE1. Enables SE1 charging mode for certain devices. \n ## This mode is only activated when a USB host is not present. When a \n ## host is present, the mode of operation is CDP. When SE1 mode and DCP \n ## mode are both enabled, the hub toggles between the two modes of \n ## operation as necessary to ensure the device can charge.\n ##\n ## 0b00 : Mode Disabled\n ## 0b01 : 1A mode (D-: 2.7V, D+: 2.0V)\n ## 0b10 : 2A mode (D-: 2.0V, D+: 2.7V)\n ## 0b11 : 2.5A mode enabled (D-: 2.7V, D+: 2.7V)\n\n ## Bit 0 is Battery Charging Support Enable. This bit enables CDP and \n ## must be set for any battery charging functions to be enabled. Other \n ## functions in addi- tion to CDP are enabled by setting their \n ## respective bits in addition to this bit.\n\n value = (ucs_lim & 0b11) << 6 | \\\n dcp << 5 | \\\n china_mode << 4 | \\\n (se1 & 0b11) << 1 | \\\n enable \n\n for port in ports:\n ## Register address is based on the port number\n self._write_register(_CHARGE_CONFIG+port-1, [value])\n\n def set_mcp_config(self, inputs=[False, False, False, False]):\n \"\"\"Set direction on MCP IO pins. 'inputs' list will set GP0 thru GP4 to inputs, if respective position is true\"\"\"\n\n ## Bits 7 thru 4 control USB data enables on downstream ports 1 thru 4, respectively.\n ## They must be set to 0 to make them outputs.\n value = 0b00000000 | \\\n inputs[3] << 3 | \\\n inputs[2] << 2 | \\\n inputs[1] << 1 | \\\n inputs[0]\n\n with self.mcp_device as i2c:\n ## Write to IODIR register and defaults to other registers.\n ## 0x09 (GPIO) register has to be 0b0000_0000 so that downstream ports default to enabled\n i2c.write(bytearray([0x00, value, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))\n\n def _read_mcp_register(self, addr):\n inbuf = bytearray(1)\n\n with self.mcp_device as i2c:\n i2c.write_then_readinto(bytearray([addr]), inbuf)\n \n return inbuf[0]\n\n def data_state(self):\n value = self._read_mcp_register(_GPIO)\n return [not get_bit(value, 7), not get_bit(value, 6), not get_bit(value, 5), not get_bit(value, 4)]\n\n def data_enable(self, ports=[]):\n inbuf = bytearray(1)\n\n with self.mcp_device as i2c:\n i2c.write_then_readinto(bytearray([_GPIO]), inbuf)\n\n for port in ports:\n inbuf[0] = clear_bit(inbuf[0], 8-port)\n\n i2c.write(bytearray([_GPIO])+inbuf)\n\n def data_disable(self, ports=[]):\n inbuf = bytearray(1)\n\n with self.mcp_device as i2c:\n i2c.write_then_readinto(bytearray([_GPIO]), inbuf)\n\n for port in ports:\n inbuf[0] = set_bit(inbuf[0], 8-port)\n\n i2c.write(bytearray([_GPIO])+inbuf)\n\n\n def get_port_remap(self):\n port12 = bytearry_to_int(self._read_register(_REMAP_12))\n port34 = bytearry_to_int(self._read_register(_REMAP_34))\n\n return [port12 & 0x0F, (port12 >> 4) & 0x0F, port34 & 0x0F, (port34 >> 4) & 0x0F]\n\n def power_state(self, ports=[1,2,3,4]):\n out = []\n\n for port in ports:\n data = self._read_register(_POWER_SELECT_1+(port-1)*4)[0]\n\n ## Bits 3:0 mapping:\n ## 0b000 : Port power is disabled\n ## 0b001 : Port is on if USB2 port power is on\n ## 0b010 : Port is on if designated GPIO is on\n\n ## Upstream disconnect and downstream connection cause 0b010\n ## So, we need to check for value > 0 (not just bit 0) to determine\n ## if port power is on or not.\n out.append((data & 0b111) > 0)\n\n return out\n\n def power_disable(self, ports=[]):\n for port in ports:\n self._write_register(_POWER_SELECT_1+(port-1)*4, [0x80])\n\n def power_enable(self, ports=[]):\n for port in ports:\n self._write_register(_POWER_SELECT_1+(port-1)*4, [0x81])\n\n @property\n def rails(self):\n vlim, vlogic = None, None\n\n if self.vlim is not None:\n voltage = float(self.vlim.value) / 65535.0 * self.vlim.reference_voltage \n vlim = voltage * (1870 + 20000) / 1870\n \n if self.vlogic is not None:\n voltage = float(self.vlogic.value) / 65535.0 * self.vlogic.reference_voltage \n vlogic = voltage * 2\n\n return vlim, vlogic\n \n","sub_path":"capablerobot_usbhub.py","file_name":"capablerobot_usbhub.py","file_ext":"py","file_size_in_byte":16216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"615444650","text":"import json\nimport os\nfrom urllib.parse import urlparse\n\nsites_to_domains = dict()\ndomains_to_ip = dict()\nip = dict()\ndomains = set()\nos.system('export PATH=$PATH:~/go/bin')\n\nwith open(\"1.json\") as f:\n i = 0\n for line in f:\n i += 1\n obj = json.loads(line)\n url = urlparse(obj[\"requestURL\"])\n domain = url.netloc\n sites_to_domains.setdefault(obj['siteURL'],set()).add(domain)\n cmd = 'echo ' + domain + ' | zdns A -retries 10'\n output = os.popen(cmd).readlines()\n for op in output:\n obj = json.loads(op)\n try:\n domain = obj['name']\n if obj['status'] == 'NOERROR':\n answers = obj['data']['answers']\n for answer in answers:\n domains_to_ip.setdefault(domain, set()).add(answer['answer'])\n ip.setdefault(answer['answer'], 0)\n ip[answer['answer']] += 1\n else:\n domains_to_ip.setdefault(domain, set()).add(obj['status'])\n except Exception as e:\n print(\"Exception: \", e)\n print(i)\n\nfor key in sites_to_domains:\n domain_list = \", \".join(sites_to_domains[key])\n sites_to_domains[key] = domain_list\n\nfor key in domains_to_ip:\n ip_list = \", \".join(domains_to_ip[key])\n domains_to_ip[key] = ip_list\n\nwith open(\"sites_to_domains_single.txt\", \"w\") as f:\n json.dump(sites_to_domains, f)\n\nwith open(\"domains_to_ip_single.txt\", \"w\") as f:\n json.dump(domains_to_ip, f)\n\nwith open(\"ip_freq_single.txt\", \"w\") as f:\n json.dump(ip, f)\n","sub_path":"src/ipsets_single.py","file_name":"ipsets_single.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"404385240","text":"import re\nimport os\nimport os.path as osp\nfrom fuzzywuzzy import process, fuzz\nfrom unidecode import unidecode\nimport pandas as pd\nfrom multiprocessing import Pool\nfrom functools import partial\n\nif os.path.exists('./config.ini'):\n import configparser\n config = configparser.ConfigParser()\n config.read('./config.ini')\n dst_path = config.get('config','BASE_MODEL_PATH')\nelse:\n dst_path = os.environ['BASE_MODEL_PATH']\n\nprint('bas path for references is : %s'%dst_path)\nref_marque_modele_path = dict(\n siv=osp.join(dst_path, 'esiv_marque_modele_genre.csv'),\n caradisiac=osp.join(dst_path, 'caradisiac_marque_modele.csv'),\n siv_caradisiac=osp.join(dst_path, 'esiv_caradisiac_marque_modele_genre.csv')\n )\n\nref_marque_modele = dict()\nfor key, value in ref_marque_modele_path.items():\n if os.path.exists(value):\n ref_marque_modele[key] = pd.read_csv(value).rename(columns={'alt': 'modele'})\n\ndef hash_table1(x):\n assert 'marque' in ref_marque_modele[x].columns\n assert 'modele' in ref_marque_modele[x].columns\n\n return ref_marque_modele[x].groupby(['marque']).apply(lambda x: x['modele'].to_list()).to_dict()\n\n\ndef hash_table2(x):\n assert 'marque' in ref_marque_modele[x].columns\n assert 'modele' in ref_marque_modele[x].columns\n #assert 'href' in ref_marque_modele[x].columns # link ref\n #assert 'src' in ref_marque_modele[x].columns # image ref source\n gp = ref_marque_modele[x].groupby(['marque', 'modele'])\n if not (gp.size() == 1).all():\n print(\"Be careful, your mapping %s is not unique\"%x)\n print(\"take first of :\")\n print(gp.size()[gp.size()>1])\n # assert (gp == 1).all(),\n\n return gp.first().to_dict('index')\n\n# dictionnaire pour acceder rapidement à tous les modeles d'une marque\nmarques_dict = {x: hash_table1(x) for x in ref_marque_modele.keys()}\n\n# dictionnaire pour acceder rapidement à href et src (images de caradisiac)\nsrc_dict = {x: hash_table2(x) for x in ref_marque_modele.keys()}\n\n\ndef reg_class(x):\n return '^(CLASSE ?)?{x} *[0-9]+(.*)'.format(x=x)\n\n\ndef reg_no_class(x):\n # '^(CLASSE ?){x}(?:\\w)(.*)'\n return '^(CLASSE ?){x}'.format(x=x)\n\n\nreplace_regex = {\n 'marque': {\n 'BW|B\\.M\\.W\\.|B\\.M\\.W|BMW I': 'BMW',\n 'FIAT\\.': 'FIAT',\n 'MERCEDES BENZ|MERCEDESBENZ|MERCEDES-BENZ': 'MERCEDES',\n 'NISSAN\\.': 'NISSAN',\n 'VOLKSWAGEN VW': 'VOLKSWAGEN',\n 'NON DEFINI|NULL': ''\n },\n 'modele': {\n 'KA\\+': 'KA',\n 'MEGANERTE\\/|MEGANERTE': 'MEGANE',\n 'MEGANE SCENIC': 'SCENIC',\n 'MEGANESCENIC': 'SCENIC',\n '(.*)ARA PIC(.*)': 'XSARA PICASSO', # XARA PICA -> XSARA PICASSO\n '(.*)ARAPIC(.*)': 'XSARA PICASSO',\n #'CLIOCHIPIE|CLIOBEBOP\\/|CLIORN\\/RT|CLIOBACCAR': 'CLIO I',\n #'CLIOSTE': 'CLIO I',\n 'CLIORL\\/RN\\/|CLIORL\\/RN|CLIOS' : 'CLIO',\n ' III$': ' 3',\n ' IV$': ' 4',\n '\\+2$': ' 2',\n 'NON DEFINI|NULL': '',\n 'BLUETEC|TDI|CDI': '',\n 'BLUETEC|TDI|CDI': '',\n 'REIHE': 'SERIE',\n 'DIESEL|ESSENCE': '',\n '\\s3P\\s': '', #3 PORTES\n '\\d+KWH':'' #KWH\n },\n 'MERCEDES': {**{reg_class(x): 'CLASSE %s'%x for x in ['A','B','C','E','G','S','V','X']},\n **{reg_no_class(x): '%s'%x for x in ['CL', 'GL', 'SL']}\n },\n 'RENAULT': {' ?(SOCIETE)': ''},\n 'BMW': {**{'(SERIE ?){x}'.format(x=x): '{x}'.format(x=x) for x in ['I', 'M', 'Z', 'X']},\n 'XDRIVE.*?\\s' : \"\" # Remove XDRIVEXXX unitil the next \\s\n },\n 'PEUGEOT': {\n 'EXPERT TRAVELLER': 'TRAVELLER' # undetermined case -> most recent\n },\n 'CITROEN' : {\n 'AIRCROSS': '',\n 'C4 SPACETOURER' : 'C4 PICASSO',\n 'JUMPY SPACE TOURER':'JUMPY' # undetermined case -> most recent\n },\n 'TOYOTA' : {\n 'PLUS|\\+':'',\n 'HYBRID':''\n },\n 'VOLKSWAGEN' : {\n 'PLUS|\\+':'',\n 'PASSAT CC':'CC'\n },\n 'FIAT': {\n '(X|L|C)$':'' # Letter at the end is removed\n },\n 'AUDI': {\n 'SPORTBACK|LIMOUSINE|ALLROAD|QUATRO|AVANT|LIMOUSINE':''\n },\n 'LAND ROVER': {\n 'SPORT$':''\n },\n 'OPEL': {\n '\\sX$':'' # X at the end is removed. eg. GRANDLAND X --> GRANDLAND\n },\n 'VOLVO': {\n 'CROSS COUNTRY':''\n },\n 'SEAT': {\n '\\sXL$|\\sXL\\s':'' # XL is removed at the end or between spaces\n },\n 'FORD': {\n 'CUSTOM|COURRIER|CONNECT' : ''\n }\n }\n\n\ndef cleaning(row: dict, column: str):\n \"\"\"Cleaning function\n\n Args:\n row: Detected boxes\n column: Image used for detection\n\n Returns:\n row: Cleaned marque and model\n \"\"\"\n if column == 'marque':\n row['marque'] = (\n unidecode(row['marque'])\n .replace('[^\\w\\s]', '')\n .replace('_', ' ')\n .replace('-', '')\n .upper()\n .strip()\n )\n\n elif column == 'modele':\n row['modele'] = (\n unidecode(row['modele'])\n .strip()\n .upper()\n .strip()\n )\n\n if row['marque'] not in ['MINI', 'DS']:\n row['modele'] = row['modele'].replace(row['marque'], '').strip()\n\n for a, b in replace_regex[column].items():\n row[column] = re.sub(a, b, row[column])\n\n # Renplacement conditionnel du modele\n if column == 'modele':\n if row['marque'] in replace_regex.keys():\n for a, b in replace_regex[row['marque']].items():\n row['modele'] = re.sub(a, b, row['modele'])\n\n return row\n\n\ntol = dict(marque=0.85, modele=0.7)\n\n\ndef fuzzymatch(row, column='marque', table_ref_name='siv'):\n score = 0\n match = ''\n\n if row[column] == '' or (column == 'modele' and row['score_marque'] < tol['marque']):\n row[column] = match\n row['score_%s'%column] = score\n return row\n\n try:\n if column == 'marque':\n choices = ref_marque_modele[table_ref_name][column].to_list()\n match, score = process.extractOne(\n str(row[column]),\n choices,\n )\n elif column == 'modele':\n choices = marques_dict[table_ref_name][row['marque']]\n match, score = process.extractOne(\n str(row[column]),\n choices,\n scorer=fuzz.WRatio\n )\n\n except Exception as e:\n print(e)\n print('Error in matching: {}'.format(column))\n print('Input {}'.format(row[column]))\n\n # print(\"%s => %s (%d)\"%(row[column], match, score))\n\n if score > tol[column]:\n row[column] = match\n\n row['score_%s'%column] = score\n\n return row\n\n\ndef wrap_cleaning(column, key_row):\n key = key_row[0]\n row = key_row[1]\n new_row = {'index': key}\n res = cleaning(row, column)\n\n new_row.update(res)\n return new_row\n\n\ndef wrap_fuzzymatch(table_ref_name, column, key_row):\n key = key_row[0]\n row = key_row[1]\n new_row = {'index': key}\n res = fuzzymatch(row, column, table_ref_name)\n new_row.update(res)\n return new_row\n\n\ndef df_cleaning(df, column, num_workers):\n if num_workers == 0:\n res = [wrap_cleaning(column, key_row) for key_row in df.iterrows()]\n else:\n # multiprocess le nettoyage\n pool = Pool(num_workers)\n func = partial(wrap_cleaning, column)\n res = pool.map(func, df.iterrows())\n pool.close()\n\n df_res = pd.DataFrame(res)\n return df_res.set_index('index').sort_index()\n\n\ndef df_fuzzymatch(df, column, table_ref_name, num_workers):\n # fuzzy match pour marque et modele hors des references\n if column == 'marque':\n filter = df[column].isin(ref_marque_modele[table_ref_name][column].to_list())\n elif column == 'modele':\n filter = df.eval('marque + modele').isin(ref_marque_modele[table_ref_name].eval('marque + modele'))\n\n df.loc[filter,'score_%s'%column] = 100\n df.loc[~filter,'score_%s'%column] = 0\n\n if num_workers == 0:\n res = [wrap_fuzzymatch(table_ref_name, column, key_row) for key_row in df.iterrows()]\n else:\n # multiprocess le fuzzy\n pool = Pool(num_workers)\n func = partial(wrap_fuzzymatch, table_ref_name, column)\n res = pool.map(func, df[~filter].iterrows())\n pool.close()\n\n df_res = pd.DataFrame(res)\n return pd.concat([df_res, df[filter].reset_index()]).set_index('index').sort_index()\n\ndict_post_cleaning = {'caradisiac':\n {\n ('CITROEN', 'DS3') : ('DS', 'DS 3')\n }\n }\n\n\ndef df_post_cleaning(df, table_ref_name):\n for before, after in dict_post_cleaning.get(table_ref_name, {}).items():\n # mitght wnat to instal numexp for optim\n filter = df.eval('marque == \"%s\" and modele == \"%s\"'%before)\n df.loc[filter, 'marque'] = after[0]\n df.loc[filter, 'modele'] = after[1]\n\n return df\n\n\ndef df_process(df, table_ref_name, num_workers):\n for column in ['marque', 'modele']:\n df = df_cleaning(df, column, num_workers)\n df = df_fuzzymatch(df, column, table_ref_name, num_workers)\n\n df = df_post_cleaning(df, table_ref_name)\n\n df['score'] = (df['score_marque'] + df['score_modele']) / 200\n\n return df[['marque', 'modele', 'score']]\n\n\ndef test_process():\n row = dict(modele='renault clio', marque='renault')\n res = fuzzymatch(cleaning(row))\n assert res == {\"marque\": \"RENAULT\", \"modele\": \"CLIO\", \"score\": 1}, res\n row = dict(modele='', marque='renault')\n cleaned = cleaning(row)\n res = fuzzymatch(cleaned)\n assert res == {\"marque\": \"RENAULT\", \"modele\": \"\", \"score\": 0.5}, res\n\n\nif __name__ == '__main__':\n test_process()\n","sub_path":"sivnorm/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":9972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"514608787","text":"#!/usr/bin/env python3\n# encoding=utf-8\ncf = open(\"commentslist.txt\").readlines()\nclist = []\nfor lines in cf:\n clist.append(lines.split())\n\ngf = open(\"gradeslist.txt\").read()\nglist = gf.split()\n\nwordfreq = dict()\nfor comments in clist:\n for word in comments:\n wordfreq[word] = wordfreq.get(word, 0) + 1\n\nworddict = dict()\ni = 0\nfor word in (word for word in wordfreq.keys() if wordfreq[word] > 1):\n worddict[word] = i\n i = i + 1\n\nsvmfile = open(\"svm.txt\", \"w\")\nfor g, c in zip(glist, clist):\n svmfile.write(str(g) + \" \")\n cdict = dict()\n for word in worddict.keys():\n if word in c:\n cdict[worddict[word]] = c.count(word)\n for (word, freq) in cdict.items():\n svmfile.write(str(word) + \":\" + str(freq) + \" \")\n svmfile.write(\"\\n\")\nsvmfile.close()\n","sub_path":"code/make_svm_file.py","file_name":"make_svm_file.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"54578110","text":"from func import primes\n\n__author__ = \"Bungogood\"\n\n'''\nProblem 7\n\n10001st prime\n'''\n\ndef f(x):\n p = primes()\n for _ in range(x-1):\n next(p)\n return next(p)\n\nif __name__ == \"__main__\":\n print(f(10001))","sub_path":"Problem-007.py","file_name":"Problem-007.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"388044238","text":"# pylint: disable=W0621,C0114,C0115,C0116,W0212,W0613\n\nclass ExonMock:\n # pylint: disable=too-few-public-methods\n def __init__(self, start, stop, frame):\n self.start = start\n self.stop = stop\n self.frame = frame\n\n\nclass TranscriptModelMock:\n # pylint: disable=too-many-instance-attributes\n def __init__(\n self, strand, cds_start, cds_end, exons, coding=None, is_coding=True\n ):\n self.strand = strand\n self.cds = [cds_start, cds_end]\n self.exons = exons\n self.chrom = \"1\"\n self.gene = \"B\"\n self.tr_id = \"123\"\n self.tr_name = \"123\"\n\n if coding is None:\n self.coding = self.exons\n else:\n self.coding = coding\n self._is_coding = is_coding\n\n def CDS_regions(self): # pylint: disable=invalid-name\n return self.coding\n\n def is_coding(self):\n return self._is_coding\n\n def all_regions(self):\n return self.exons\n\n\nclass ReferenceGenomeMock:\n # pylint: disable=no-self-use\n def get_sequence(self, chromosome, pos, pos_last):\n print((\"get\", chromosome, pos, pos_last))\n return \"\".join([chr(i) for i in range(pos, pos_last + 1)])\n\n\nclass CodeMock:\n # pylint: disable=too-few-public-methods\n startCodons = [\"ABC\", \"DEF\"]\n CodonsAaKeys: dict = {}\n\n\nclass AnnotatorMock:\n # pylint: disable=too-few-public-methods\n\n def __init__(self, reference_genome):\n self.reference_genome = reference_genome\n self.code = CodeMock()\n","sub_path":"dae/dae/effect_annotation/tests/mocks.py","file_name":"mocks.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"558526029","text":"from selenium import webdriver\r\nimport time, random\r\n\r\n# --------------------------------\r\n# - Meeting Bot by © Jared Turck -\r\n# --------------------------------\r\n\r\n# enter meeting ID 700-760-517\r\n# enter the same meeting with 200 bots\r\n\r\n\r\ndef timeout(cm, tm=1):\r\n time.sleep(tm)\r\n\r\ndef input_meeting_id():\r\n meeting_ID = input(\"Enter meeting ID: \")\r\n while False in (lambda m : [m.isdigit() == True, len(m) == 9])(meeting_ID.replace(\"-\", \"\")):\r\n meeting_ID = input(\"Incorrect input!\\nEnter meeting ID: \")\r\n return meeting_ID\r\n\r\ndef read_meeting_id_from_file():\r\n with open(\"meeting_id.txt\", \"r\") as file:\r\n return file.read()\r\n\r\ndef add_bot(current_bot_name):\r\n meeting_ID = read_meeting_id_from_file()\r\n driver = webdriver.Chrome(\"chromedriver.exe\")\r\n\r\n driver.get(\"https://app.gotomeeting.com/home.html\")\r\n input1 = driver.find_element_by_id(\"meetingId\")\r\n timeout(input1.send_keys((lambda x : x[:3]+\"-\"+x[3:6]+\"-\"+x[6:])(meeting_ID.replace(\"-\",\"\"))), tm=3)\r\n timeout(driver.find_element_by_id(\"joinMeeting\").click(), tm=1)\r\n timeout(driver.find_element_by_xpath('//button[@data-automation-id=\"onboarding-continue-no-audio\"]').click(), tm=1)\r\n\r\n # add a bot to the meeting\r\n driver.find_element_by_id(\"attendee-name\").send_keys(current_bot_name)\r\n driver.find_element_by_xpath('//button[@data-automation-id=\"change-name-and-email-dialog__submit\"]').click()\r\n\r\n\r\nadd_bot(\"bot_\" + str(random.randint(1,999999)))\r\ninput(\"end...\")\r\n","sub_path":"Python/!PYTHON/py/meeting bot/add_bot.py","file_name":"add_bot.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"418588121","text":"from yahoo_finance import Share\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\n\ndef get_yahoo_csv(symbols, years_before):\n '''\n INPUT: historical price for symbols in seleted period of time.\n OUTPUT: save as .csv file in each symbols.\n '''\n days_before = years_before * 365 #trasfer years into days\n today = datetime.now().strftime('%Y-%m-%d') #make today as str\n date = datetime.now() - timedelta(days=days_before) #date is days before from today\n\n symbol = Share(symbols) \n sym = pd.DataFrame(symbol.get_historical(date.strftime('%Y-%m-%d'), today))[::-1]\n sym.columns = map(str.lower, sym.columns)\n sym.index = sym['date']\n sym = sym.drop(['symbol', 'date'], axis=1)\n \n print(\"Inserted {} days {} data.\".format(days_before, symbol.get_name()))\n sym.to_csv(\"{}.csv\".format(symbol.get_name()))\n return sym","sub_path":"[DSCI6005] LSTM_TimeSeries_Analysis_YAHOO_API/getData_yahoo.py","file_name":"getData_yahoo.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"290554793","text":"#!/home/arcsight/miniconda/bin/python2.7\n\n__date__ = \"07/19/2015\"\n__author__ = \"AlienOne\"\n__copyright__ = \"MIT\"\n__credits__ = [\"Justin Jessup\"]\n__license__ = \"MIT\"\n__version__ = \"1.0\"\n__maintainer__ = \"AlienOne\"\n__email__ = \"Jessup.Justin@target.com\"\n__status__ = \"Production\"\n\n\nimport os\nimport csv\nimport psutil\nimport datetime\nimport smtplib\nimport socket\nimport subprocess\nimport threading\nfrom datetime import timedelta\nfrom email.mime.text import MIMEText\n\n\ndef git_backup_report(working_dir):\n \"\"\"\n GitHub backup of critical files\n :param working_dir: Current working directory\n :return: GitHub sync standard output\n \"\"\"\n os.chdir(working_dir)\n git_pull = subprocess.Popen(['git', 'pull', '-q'], stdout=subprocess.PIPE).communicate()\n git_add = subprocess.Popen(['git', 'add', '-A'], stdout=subprocess.PIPE).communicate()\n git_commit = subprocess.Popen(['git', 'commit', '-m', ' \"updates\"'], stdout=subprocess.PIPE).communicate()\n git_push = subprocess.Popen(['git', 'push', '-q'], stdout=subprocess.PIPE).communicate()\n git_actions = [git_pull, git_add, git_commit, git_push]\n for action in git_actions:\n return action\n\n\ndef email_alert(textfile, sender, rcpts, subject, smtp_server):\n \"\"\"\n Generic email function to send an email alert\n :param textfile: Attachment\n :param sender: Email address\n :param rcpts: List email addresses\n :param subject: String\n :param smtp_server: String\n :return: None\n \"\"\"\n fp = open(textfile, 'r')\n msg = MIMEText(fp.read())\n fp.close()\n msg['Subject'] = subject\n msg['From'] = ', '.join(sender)\n msg['To'] = ', '.join(rcpts)\n s = smtplib.SMTP(smtp_server)\n s.sendmail(sender, rcpts, msg.as_string())\n s.quit()\n\n\ndef get_stats():\n report_dict = {}\n\n \"\"\"CPU\"\"\"\n count = psutil.cpu_count(logical=True)\n utilization = str(psutil.cpu_percent(interval=1)) + \"%\"\n report_dict.update({'CPU Count': count, 'CPU Utilization': utilization})\n\n \"\"\"OS Tier Memory\"\"\"\n memory = psutil.virtual_memory()\n keys = [key.title() for key in dir(memory) if not key.startswith('_') and not key.startswith('__')]\n keys.remove('Count')\n keys.remove('Index')\n keys.remove('Percent')\n values = [(str(round(float(getattr(memory, key.lower())/1024/1024/1024), 2)) + 'GB') for key in keys]\n keys = [('Memory ' + key) for key in keys]\n report_dict.update(dict(zip(keys, values)))\n\n \"\"\"JVM Memory Utilization\"\"\"\n cmd = \"/usr/java/jdk1.7.0_79/bin/jstat -gc `lsof -i TCP:9999| grep LISTEN | tail -n 1 | awk '{print $2}'`| \" \\\n \"tail -n 1 | awk '{ print $3, $4, $6, $8, $9 }'\"\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n output = output.decode(\"utf-8\")\n jvm_mem_max = 4096\n jvm_mem_used = round(sum([float(x.strip()) for x in output.split(' ')])/1024, 2)\n jvm_mem_free = jvm_mem_max - jvm_mem_used\n report_dict.update({'JVM Mem Max': (str(jvm_mem_max) + \"MB\"),\n 'JVM Mem Used': (str(jvm_mem_used) + \"MB\"),\n 'JVM Mem Free': (str(jvm_mem_free) + \"MB\")})\n\n \"\"\"Disk Usage\"\"\"\n arc_partition = \"/opt/data\"\n disk = psutil.disk_usage(arc_partition)\n keys = [key.title() for key in dir(disk) if not key.startswith('_') and not key.startswith('__')]\n keys.remove('Count')\n keys.remove('Index')\n keys.remove('Percent')\n values = [(str(round(float(getattr(disk, key.lower())/1024/1024/1024), 2)) + 'GB') for key in keys]\n keys = [('Disk ' + key) for key in keys]\n report_dict.update(dict(zip(keys, values)))\n\n \"\"\"Boot Time\"\"\"\n boot = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(\"%Y-%m-%d %H:%M:%S\")\n report_dict.update({'Last Reboot': boot})\n\n \"\"\"OS Uptime\"\"\"\n with open('/proc/uptime', 'r') as f:\n uptime_seconds = float(f.readline().split()[0])\n uptime_string = str(timedelta(seconds = uptime_seconds))\n report_dict.update({'OS Uptime': uptime_string})\n\n \"\"\"JVM UpTime\"\"\"\n cmd = \"ps -p `lsof -i TCP:9999| grep LISTEN | \" \\\n \"tail -n 1 | awk '{print $2}'` -o etime \"\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n output = output.decode(\"utf-8\")\n output = output.split(' ' )\n output = output[len(output) - 1].split('\\n')[0]\n report_dict.update({'JVM Uptime': output})\n\n \"\"\"Build CSV Report\"\"\"\n hostname = socket.gethostname()\n the_date = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n csv_filename = \"/home/arcsight/LoggerStats/simlogc17/stats_report.csv\"\n report_dict.update({'DateTime': the_date, 'Hostname': hostname})\n headers = [\"Hostname\", \"DateTime\", \"OS Uptime\", \"Last Reboot\", \"Memory Total\", \"Memory Used\",\n \"Memory Available\", \"Memory Free\", \"Memory Buffers\", \"Memory Cached\", \"Memory Active\",\n \"Memory Inactive\", \"JVM Uptime\", \"JVM Mem Max\", \"JVM Mem Used\", \"JVM Mem Free\",\n \"CPU Count\", \"CPU Utilization\", \"Disk Total\", \"Disk Free\", \"Disk Used\"]\n products = [report_dict]\n if not os.path.isfile(csv_filename):\n with open(csv_filename, 'w') as fh:\n w = csv.DictWriter(fh, headers)\n w.writer.writerow(headers)\n w.writerows(products)\n else:\n with open(csv_filename, 'a') as fh:\n w = csv.DictWriter(fh, headers)\n w.writerows(products)\n working_dir = \"/home/arcsight/LoggerStats/simlogc17\"\n git_backup_report(working_dir)\n threading.Timer(300, get_stats).start()\n\n\ndef email_report():\n csv_filename = \"/home/arcsight/LoggerStats/simlogc17/stats_report.csv\"\n email_file = csv_filename\n sender = \"root@localhost\"\n rcpts = \"Jessup.Justin@target.com\"\n subject = \"ESM Metrics Report\"\n smtp_server = \"localhost\"\n #email_alert(email_file, sender, rcpts, subject, smtp_server)\n threading.Timer(86400, email_report).start()\n\n\ndef main():\n get_stats()\n #email_report()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"get_logger_stats.py","file_name":"get_logger_stats.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"513428688","text":"from tkinter import *\n\n# root = Tk()\n\n# img = PhotoImage(file=\"../../Pictures/FinishHim.png\")\n\n# Label(root, image=img).pack(side=\"right\")\n\n# explanation = \"\"\"\n# \t\t\t\tAt present, only GIF and PPM/PGM\n# \t\t\t\tformats are supported, but an interface \n# \t\t\t\texists to allow additional image file\n# \t\t\t\tformats to be added easily.\n# \t\t\t \"\"\"\n# Label(root, \n# \t\t\tjustify=LEFT,\n# \t\t\tpadx = 10, \n# \t\t\ttext=explanation).pack(side=\"left\")\n\n# root.mainloop()\n\n\n\n\nroot = Tk()\n# logo = PhotoImage(file=\"../images/python_logo_small.gif\")\nimg = PhotoImage(file=\"../../Pictures/FinishHim.png\")\n\nLabel(root, \n compound = CENTER,\n text=\"\"\"At present, only GIF and PPM/PGM\n\t\t\t\t\tformats are supported, but an interface \n\t\t\t\t\texists to allow additional image file\n\t\t\t\t\tformats to be added easily.\"\"\", \n image=img).pack(side=\"right\")\n\nroot.mainloop()\n\n# We can have the image on the right side and the text left justified with a padding of 10 pixel on the left and right side by changing the Label command like this: \n'''\nw = Label(root, \n\t\t justify=LEFT,\n\t\t compound = LEFT,\n\t\t padx = 10, \n\t\t text=explanation, \n\t\t image=logo).pack(side=\"right\")\n'''\n","sub_path":"Area52/Modules/tkinter/tkinter Image pack.py","file_name":"tkinter Image pack.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"220985575","text":"# Copyright (c) 2015-present, Facebook, Inc.\n# All rights reserved.\n# model settings\nnorm_cfg = dict(type='SyncBN', requires_grad=True)\nmodel = dict(\ntype='EncoderDecoder',\n pretrained=None,\n backbone=dict(\n type='XCiT',\n patch_size=16,\n embed_dim=384,\n depth=12,\n num_heads=8,\n mlp_ratio=4,\n qkv_bias=True,\n ),\n neck=dict(\n type='FPN',\n in_channels=[384, 384, 384, 384],\n out_channels=384,\n num_outs=4),\n decode_head=dict(\n type='FPNHead',\n in_channels=[384, 384, 384, 384],\n in_index=[0, 1, 2, 3],\n feature_strides=[16, 16, 16, 16],\n channels=128,\n dropout_ratio=0.1,\n num_classes=150,\n norm_cfg=norm_cfg,\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n # model training and testing settings\n train_cfg=dict(),\n test_cfg=dict(mode='whole'))\n","sub_path":"semantic_segmentation/configs/_base_/models/sem_fpn_xcit_p16.py","file_name":"sem_fpn_xcit_p16.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"366664056","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nfrom multiprocessing import Process, Value, Lock\n\n\ndef func(val, lock):\n\tfor i in range(50):\n\t\ttime.sleep(0.01)\n\t\twith lock:\n\t\t\tval.value += 1\n\t\t\nif __name__ == \"__main__\":\n\t # 多进程无法使用全局变量,multiprocessing 提供的 Value 是一个代理器,\n\t # 可以实现在多进程中共享这个变量\n\tv = Value('i', 0)\n\tlock = Lock()\n\tprocs = [Process(target=func, args=(v, lock)) for i in range(10)]\n\t\n\tfor p in procs:\n\t\tp.start()\n\tfor p in procs:\n\t\tp.join()\n\t\t\n\tprint(v.value)","sub_path":"linux_lou_plus/step_7/multiprocess/process_sys.py","file_name":"process_sys.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"318877850","text":"import psutil, os\nimport pdb\nimport subprocess as sp\nid = 0\np = None\n\nwhile p == None:\n\tfor proc in psutil:\n\t\tpsutil.process_iter()\n\t\tif \"PROCEXP\" in str(proc.name):\n\t\t\t\tp = proc\nfor maps in p.memory_maps():\n\tfor m in maps:\n\t\tprint(m)\np = pdb.Pdb()","sub_path":"getpid.py","file_name":"getpid.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"210825744","text":"import subprocess\nimport argparse\nimport pandas as pd\nimport os\nimport glob\nimport shutil\nimport sys\n\n#local imports\nfrom plink_helper.plink_driver import Driver\n\n#QC and data cleaning\nclass QC(Driver):\n def __init__(self, geno_path, rare=False):\n super().__init__(geno_path)\n # create new names for each step\n self.geno_call_rate = geno_path + \"_call_rate\"\n self.geno_het = self.geno_call_rate + \"_het\"\n self.geno_sex = self.geno_het + \"_sex\"\n self.geno_relatedness = self.geno_sex + \"_relatedness\"\n self.geno_variant = self.geno_relatedness + \"_variant\"\n self.geno_final = self.geno_variant + \"_final\"\n self.tmp_file_list = [self.geno_call_rate, self.geno_het, self.geno_sex, self.geno_relatedness, self.geno_variant]\n self.rare = rare\n\n def call_rate_pruning(self, geno_path):\n\n out_path = self.out_path\n\n step = \"PRUNING FOR CALL RATE\"\n print(step)\n bash1 = \"awk '{print $1,$2,$6}' \" + geno_path + '.fam > ' + geno_path + '.phenos'\n bash2 = \"plink --bfile \" + geno_path + \" --mind 0.05 --make-bed --out \" + geno_path + \"_call_rate\"\n bash3 = \"mv \" + geno_path + \"_call_rate.irem \" + out_path + \"CALL_RATE_OUTLIERS.txt\"\n\n cmds = [bash1, bash2, bash3]\n\n self.run_cmds(cmds, step)\n \n \n def het_pruning(self, geno_path):\n\n out_path = self.out_path\n \n step = \"PRUNING FOR HETEROZYGOSITY\"\n print(step)\n \n \n bash1 = \"plink --bfile \" + geno_path + \" --geno 0.01 --maf 0.05 --indep-pairwise 50 5 0.5 --out \" + out_path + \"pruning\"\n bash2 = \"plink --bfile \" + geno_path + \" --extract \" + out_path + \"pruning.prune.in --make-bed --out \" + out_path + \"pruned_data\"\n bash3 = \"plink --bfile \" + out_path + \"pruned_data --het --out \" + out_path + \"prunedHet\"\n bash4 = \"awk '{if ($6 <= -0.25) print $0 }' \" + out_path + \"prunedHet.het > \" + out_path + \"outliers1.txt\" \n bash5 = \"awk '{if ($6 >= 0.25) print $0 }' \" + out_path + \"prunedHet.het > \" + out_path + \"outliers2.txt\" \n bash6 = \"cat \" + out_path + \"outliers2.txt \" + out_path + \"outliers1.txt > \" + out_path + \"HETEROZYGOSITY_OUTLIERS.txt\"\n bash7 = \"plink --bfile \" + geno_path + \" --remove \" + out_path + \"HETEROZYGOSITY_OUTLIERS.txt --make-bed --out \" + geno_path + \"_het\"\n\n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7]\n \n self.run_cmds(cmds, step)\n\n \n def sex_check(self, geno_path):\n\n out_path = self.out_path\n \n step = \"CHECKING SEXES\"\n print(step)\n\n bash1 = \"plink --bfile \" + geno_path + \" --check-sex 0.25 0.75 --maf 0.05 --out \" + out_path + \"gender_check1\"\n bash2 = \"plink --bfile \"+ geno_path + \" --chr 23 --from-bp 2699520 --to-bp 154931043 --maf 0.05 --geno 0.05 --hwe 1E-5 --check-sex 0.25 0.75 --out \" + out_path + \"gender_check2\"\n bash3 = \"grep 'PROBLEM' \" + out_path + \"gender_check1.sexcheck > \" + out_path + \"problems1.txt\"\n bash4 = \"grep 'PROBLEM' \" + out_path + \"gender_check2.sexcheck > \" + out_path + \"problems2.txt\"\n bash5 = \"cat \" + out_path + \"problems1.txt \" + out_path + \"problems2.txt > \" + out_path + \"GENDER_FAILURES.txt\"\n bash6 = \"cut -f 1,2 \" + out_path + \"GENDER_FAILURES.txt > \" + out_path + \"samples_to_remove.txt\"\n bash7 = \"plink --bfile \" + geno_path + \" --remove \" + out_path + \"samples_to_remove.txt --make-bed --out \" + geno_path + \"_sex\"\n\n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7]\n\n self.run_cmds(cmds, step)\n\n\n def ancestry_comparison(self, geno_path, ref_path):\n \n out_path = self.out_path\n step = \"PCA for Ancestry Comparison\"\n print(step)\n \n # set up files to add numbers for plotting (as done in Cornelis's script)\n \n bash1 = f\"plink --bfile {geno_path} --bmerge {ref_path} --out {out_path}bin_snplis --make-bed\"\n bash2 = f\"plink --bfile {geno_path} --flip {out_path}bin_snplis-merge.missnp --make-bed --out {geno_path}_flip\"\n bash3 = f\"plink --bfile {geno_path}_flip --bmerge {ref_path} --out {out_path}bin_snplis --make-bed\"\n bash4 = f\"plink --bfile {geno_path}_flip --exclude {out_path}bin_snplis-merge.missnp --out {geno_path}_flip_pruned --make-bed\"\n bash5 = f\"plink --bfile {geno_path}_flip_pruned --bmerge {ref_path} --out {out_path}bin_snplis --make-bed\"\n bash6 = f\"plink --bfile {out_path}bin_snplis --geno 0.01 --out {out_path}pca --make-bed --pca 4\"\n \n # then add some names here and there\n bash7 = f'grep \"EUROPE\" {out_path}pca.eigenvec > {out_path}eur.txt'\n bash8 = f'grep \"ASIA\" {out_path}pca.eigenvec > {out_path}asia.txt'\n bash9 = f'grep \"AFRICA\" {out_path}pca.eigenvec > {out_path}afri.txt'\n bash10 = f'grep -v -f {out_path}eur.txt {out_path}pca.eigenvec | grep -v -f {out_path}asia.txt | grep -v -f {out_path}afri.txt > {out_path}new_samples.txt'\n bash11 = f'cut -d \" \" -f 3 {geno_path}.fam > {out_path}new_samples_add.txt'\n bash12 = f'paste {out_path}new_samples_add.txt {out_path}new_samples.txt > {out_path}new_samples2.txt'\n bash13 = f\"awk -v label='1' -v OFS=' ' '{{print label, $0}}' {out_path}eur.txt > {out_path}euro.txt\"\n bash14 = f\"awk -v label='2' -v OFS=' ' '{{print label, $0}}' {out_path}asia.txt > {out_path}asiao.txt\"\n bash15 = f\"awk -v label='3' -v OFS=' ' '{{print label, $0}}' {out_path}afri.txt > {out_path}afrio.txt\"\n bash16 = f'cat {out_path}new_samples2.txt {out_path}euro.txt {out_path}asiao.txt {out_path}afrio.txt > {out_path}pca.eigenvec2'\n \n # R script for PCA plotting and filtering\n bash17 = f\"cp gwas/PCA_in_R.R {out_path}\"\n \n # eventually convert this to python and add to qc as function\n bash18 = f\"Rscript {out_path}PCA_in_R.R {out_path} --no-save\"\n \n # then back to plink to remove outliers\n bash19 = f\"plink --bfile {geno_path} --keep {out_path}PCA_filtered_europeans.txt --make-bed --out {geno_path}_heterozyg_hapmap\"\n bash20 = f\"cat {out_path}PCA_filtered_asians.txt {out_path}PCA_filtered_africans.txt {out_path}PCA_filtered_mixed_race.txt > {out_path}hapmap_outliers.txt\"\n \n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7, bash8, bash9, bash10, bash11, bash12, bash13, bash14, bash15, bash16, bash17, bash18, bash19, bash20]\n \n self.run_cmds(cmds, step) \n\n \n def relatedness_pruning(self, geno_path):\n\n out_path = self.out_path\n \n step = \"RELATEDNESS PRUNING\"\n print(step)\n\n bash1 = \"gcta --bfile \" + geno_path + \" --make-grm --out \" + out_path + \"GRM_matrix --autosome --maf 0.05\" \n bash2 = \"gcta --grm-cutoff 0.125 --grm \" + out_path + \"GRM_matrix --out \" + out_path + \"GRM_matrix_0125 --make-grm\"\n bash3 = \"plink --bfile \" + geno_path + \" --keep \" + out_path + \"GRM_matrix_0125.grm.id --make-bed --out \" + geno_path + \"_relatedness\"\n\n cmds = [bash1, bash2, bash3]\n\n self.run_cmds(cmds, step)\n\n\n ##variant checks\n def variant_pruning(self, geno_path):\n\n out_path = self.out_path\n \n step = \"VARIANT-LEVEL PRUNING\"\n print(step)\n\n # variant missingness\n bash1 = \"plink --bfile \" + geno_path + \" --make-bed --out \" + geno_path + \"_geno --geno 0.05\"\n\n #missingness by case control (--test-missing), using P > 1E-4\n bash2 = \"plink --bfile \" + geno_path + \"_geno --test-missing --out \" + out_path + \"missing_snps\" \n bash3 = \"awk '{if ($5 <= 0.0001) print $2 }' \" + out_path + \"missing_snps.missing > \" + out_path + \"missing_snps_1E4.txt\"\n bash4 = \"plink --bfile \" + geno_path + \"_geno --exclude \" + out_path + \"missing_snps_1E4.txt --make-bed --out \" + geno_path + \"_geno_missingsnp\"\n\n #missingness by haplotype (--test-mishap), using P > 1E-4\n bash5 = \"plink --bfile \" + geno_path + \"_geno_missingsnp --test-mishap --out \" + out_path + \"missing_hap\" \n bash6 = \"awk '{if ($8 <= 0.0001) print $9 }' \" + out_path + \"missing_hap.missing.hap > \" + out_path + \"missing_haps_1E4.txt\"\n bash7 = \"cat \" + out_path + \"missing_haps_1E4.txt | tr '|' '\\n' > \" + out_path + \"missing_haps_1E4_final.txt\"\n bash8 = \"plink --bfile \" + geno_path + \"_geno_missingsnp --exclude \" + out_path + \"missing_haps_1E4_final.txt --make-bed --out \" + geno_path + \"_geno_missingsnp_missinghap\"\n\n\n ###### THIS DOES NOT WORK WITHOUT PHENOTYPES!!!!!!!!\n #HWE from controls only using P > 1E-4\n bash9 = \"plink --bfile \" + geno_path + \"_geno_missingsnp_missinghap --filter-controls --hwe 1E-4 --write-snplist --out \" + out_path + \"hwe\"\n bash10 = \"plink --bfile \" + geno_path + \"_geno_missingsnp_missinghap --extract \" + out_path + \"hwe.snplist --make-bed --out \" + geno_path + \"_geno_missingsnp_missinghap_hwe\"\n bash11 = \"#### moved \" + geno_path + \"_geno_missingsnp_missinghap_hwe to \" + geno_path + \"_variant #####\"\n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7, bash8, bash9, bash10, bash11]\n\n self.run_cmds(cmds, step)\n\n exts = [\".bed\",\".bim\",\".fam\",\".log\"]\n for ext in exts:\n \n shutil.move(geno_path + \"_geno_missingsnp_missinghap_hwe\" + ext, geno_path + \"_variant\" + ext)\n\n\n def rare_prune(self, geno_path):\n\n out_path = self.out_path\n rare = self.rare\n # OPTIONAL STEP: if --rare flag included when running, rare variants will be left alone, otherwise they will be pruned with --maf 0.01\n bash = \"plink --bfile \" + geno_path + \" --maf 0.01 --make-bed --out \" + geno_path + \"_MAF\"\n \n if rare:\n print(\"SKIPPING FINAL MAF PRUNING (0.01)... RARE VARIANTS LEFT ALONE\")\n # call logging to do some custom logging\n log = self.logging()\n log.write(\"SKIPPING FINAL MAF PRUNING (0.01)... RARE VARIANTS LEFT ALONE\")\n log.write(\"\\n\")\n log.write(\"\\n\")\n\n exts = [\".bed\",\".bim\",\".fam\",\".log\"]\n for ext in exts:\n shutil.move(geno_path + ext, geno_path + \"_final\" + ext)\n\n log.write(\"MOVED \" + geno_path + \" to \" + geno_path + \"_final\")\n log.write(\"\\n\") \n\n else:\n print(\"RARE VARIANTS (MAF <= 0.01) PRUNING\")\n # call logging to do some custom logging\n log = self.logging()\n log.write(\"RARE VARIANTS (MAF <= 0.01) PRUNING WITH THE FOLLOWING COMMANDS:\")\n log.write(\"\\n\")\n log.write(\"\\n\")\n subprocess.run(bash, shell=True)\n log.write(bash)\n log.write(\"\\n\")\n\n new_log = open(geno_path + \".log\", \"r\")\n new_log_read = new_log.read()\n new_log.close()\n\n log.write(new_log_read)\n log.write(\"\\n\")\n log.write(\"***********************************************\")\n log.write(\"\\n\")\n log.write(\"\\n\")\n\n exts = [\".bed\",\".bim\",\".fam\",\".log\"]\n for ext in exts:\n shutil.move(geno_path + \"_MAF\" + ext, geno_path + \"_final\" + ext)\n\n log.write(\"MOVED \" + geno_path + \"_MAF to \" + geno_path + \"_final\")\n log.write(\"\\n\")\n log.close()\n \n \n def cleanup(self):\n print(\"CLEANING UP THE DIRECTORY OF INTERMEDIATE FILES\")\n print(\"***********************************************\")\n print()\n \n save_files = [self.geno_path + ext for ext in ['.bim','.bed','.fam','.log','.hh', '.phenos', '.PLINK_STEPS.log']] + [self.geno_final + ext for ext in ['.bim','.bed','.fam','.hh']] + [self.out_path + 'imputed']\n all_files = glob.glob(self.out_path + '*')\n rm_files = [x for x in all_files if x not in save_files]\n for file in rm_files:\n os.remove(file)\n \n","sub_path":"gwas/qc.py","file_name":"qc.py","file_ext":"py","file_size_in_byte":11954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"124418501","text":"#\n# Copyright (C) 2017 NEC, Corp.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nfrom neutron_lib.plugins import constants as nlib_const\nfrom neutron_lib.plugins import directory\nfrom oslo_config import cfg\nfrom oslo_log import helpers as log_helpers\nfrom oslo_log import log as logging\n\nfrom neutron_lbaas.drivers import driver_base\nfrom neutron_lbaas.drivers import driver_mixins\n\nfrom networking_odl.common import constants as odl_const\nfrom networking_odl.journal import full_sync\nfrom networking_odl.journal import journal\n\ncfg.CONF.import_group('ml2_odl', 'networking_odl.common.config')\nLOG = logging.getLogger(__name__)\n\nLBAAS_RESOURCES = {\n odl_const.ODL_LOADBALANCER: odl_const.ODL_LOADBALANCERS,\n odl_const.ODL_LISTENER: odl_const.ODL_LISTENERS,\n odl_const.ODL_POOL: odl_const.ODL_POOLS,\n odl_const.ODL_MEMBER: odl_const.ODL_MEMBERS,\n odl_const.ODL_HEALTHMONITOR: odl_const.ODL_HEALTHMONITORS\n}\n\n\nclass OpenDaylightLbaasDriverV2(driver_base.LoadBalancerBaseDriver):\n @log_helpers.log_method_call\n def __init__(self, plugin):\n super(OpenDaylightLbaasDriverV2, self).__init__(plugin)\n LOG.debug(\"Initializing OpenDaylight LBaaS driver\")\n self.load_balancer = ODLLoadBalancerManager(self)\n self.listener = ODLListenerManager(self)\n self.pool = ODLPoolManager(self)\n self.member = ODLMemberManager(self)\n self.health_monitor = ODLHealthMonitorManager(self)\n\n\nclass OpenDaylightManager(driver_mixins.BaseManagerMixin):\n \"\"\"OpenDaylight LBaaS Driver for the V2 API\n\n This code is the backend implementation for the OpenDaylight\n LBaaS V2 driver for OpenStack Neutron.\n \"\"\"\n\n @log_helpers.log_method_call\n def __init__(self, driver, obj_type):\n LOG.debug(\"Initializing OpenDaylight LBaaS driver\")\n super(OpenDaylightManager, self).__init__(driver)\n self.journal = journal.OpenDaylightJournalThread()\n self.obj_type = obj_type\n full_sync.register(nlib_const.LOADBALANCERV2, LBAAS_RESOURCES,\n self.get_resources)\n self.driver = driver\n\n def _journal_record(self, context, obj_type, obj_id, operation, obj):\n obj_type = (\"lbaas/%s\" % obj_type)\n journal.record(context, obj_type, obj_id, operation, obj)\n self.journal.set_sync_event()\n\n @staticmethod\n def get_resources(context, resource_type):\n plugin = directory.get_plugin(nlib_const.LOADBALANCERV2)\n if resource_type == odl_const.ODL_MEMBER:\n return full_sync.get_resources_require_id(plugin, context,\n plugin.get_pools,\n 'get_pool_members')\n\n obj_getter = getattr(plugin, 'get_%s' % LBAAS_RESOURCES[resource_type])\n return obj_getter(context)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def create(self, context, obj):\n self._journal_record(context, self.obj_type, obj.id,\n odl_const.ODL_CREATE, obj)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def update(self, context, obj):\n self._journal_record(context, self.obj_type, obj.id,\n odl_const.ODL_UPDATE, obj)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def delete(self, context, obj):\n self._journal_record(context, self.obj_type, obj.id,\n odl_const.ODL_DELETE, obj)\n\n\nclass ODLLoadBalancerManager(OpenDaylightManager,\n driver_base.BaseLoadBalancerManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLLoadBalancerManager, self).__init__(\n driver, odl_const.ODL_LOADBALANCER)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def refresh(self, context, lb):\n # TODO(lijingjing): implement this method\n # This is intended to trigger the backend to check and repair\n # the state of this load balancer and all of its dependent objects\n pass\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def stats(self, context, lb):\n # TODO(rajivk): implement this method\n pass\n\n # NOTE(mpeterson): workaround for pylint\n # pylint raises false positive of abstract-class-instantiated\n @property\n def db_delete_method(self):\n return driver_base.BaseLoadBalancerManager.db_delete_method\n\n\nclass ODLListenerManager(OpenDaylightManager,\n driver_base.BaseListenerManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLListenerManager, self).__init__(\n driver, odl_const.ODL_LISTENER)\n\n\nclass ODLPoolManager(OpenDaylightManager,\n driver_base.BasePoolManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLPoolManager, self).__init__(\n driver, odl_const.ODL_POOL)\n\n\nclass ODLMemberManager(OpenDaylightManager,\n driver_base.BaseMemberManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLMemberManager, self).__init__(\n driver, odl_const.ODL_MEMBER)\n\n journal.register_url_builder(odl_const.ODL_MEMBER,\n self.lbaas_member_url_builder)\n\n @staticmethod\n def lbaas_member_url_builder(row):\n return (\"lbaas/pools/%s/member\" % row.data.pool.id)\n\n\nclass ODLHealthMonitorManager(OpenDaylightManager,\n driver_base.BaseHealthMonitorManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLHealthMonitorManager, self).__init__(\n driver, odl_const.ODL_HEALTHMONITOR)\n","sub_path":"networking_odl/lbaas/lbaasv2_driver_v2.py","file_name":"lbaasv2_driver_v2.py","file_ext":"py","file_size_in_byte":6264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"88664227","text":"import sys\n\ndef lun(x):\n d = {}\n for y in set(x):\n cnt = x.count(y)\n d.setdefault(cnt, list())\n d[cnt].append(y)\n f = sorted(d.keys())[0]\n print(0 if f > 1 else x.index(sorted(d[f])[0]) + 1)\n\nwith open(sys.argv[1], \"r\") as f:\n _ = list(map(lun, [[int(z) for z in x.split(\" \")] for x in f.read().split(\"\\n\") if x]))\n","sub_path":"Easy/lowest_unique_number.py","file_name":"lowest_unique_number.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"576905808","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport urllib.request\r\nimport time\r\nfrom PIL import Image\r\nimport os\r\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\r\n\r\nComicNumber = 1\r\npages_to_delete = [0] #First page is 0\r\n\r\ncomlink = str(input('Enter link of site '))\r\n\r\nresponse = requests.get(comlink) \r\n\r\nsoup = BeautifulSoup(response.text, 'html.parser')\r\n\r\nfirst = True\r\nissue = str(input('Enter name of download '))\r\nkeyword = str(input('Input keyword for img '))\r\n\r\ndirectory = r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Comics\\Manga\\\\\" + issue\r\nos.makedirs(directory)\r\nprint(directory)\r\nfor links in soup.find_all('a'):\r\n link = links.get('href')\r\n print(link)\r\n if '136' not in str(link):\r\n if 'chapter' in str(link):\r\n print(link)\r\n\r\n l = 1\r\n\r\n imagelist= []\r\n\r\n response = requests.get(link) \r\n\r\n soup = BeautifulSoup(response.text, 'html.parser')\r\n\r\n for page in soup.find_all('img'):\r\n if 'ldkmanga' not in str(page.get('src')):\r\n if keyword in str(page.get('src')):\r\n try:\r\n print(page.get('src'))\r\n urllib.request.urlretrieve(page.get('src'), r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Python Files\\Tests\\\\\" + str(l) + \".jpg\")\r\n photo = Image.open(r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Python Files\\Tests\\\\\" + str(l) + \".jpg\")\r\n pdf = photo.convert('RGB')\r\n imagelist.append(pdf)\r\n os.remove(r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Python Files\\Tests\\\\\" + str(l) + \".jpg\")\r\n except:\r\n print('fel')\r\n l = l + 1\r\n\r\n ComicNumber = ComicNumber + 1\r\n\r\n link =link.replace(link[:34], '')\r\n link =link.replace('/', '')\r\n link =link.replace('-', ' ')\r\n print(link)\r\n\r\n comicname = link\r\n print(directory + '\\\\' + link)\r\n\r\n photo.save(directory + '\\\\' +comicname + '.pdf', save_all=True, append_images=imagelist)\r\n print('PDF MADE')\r\n\r\n #issue = str(int(issue) + 1)\r\n infile = PdfFileReader(directory+ '\\\\' + comicname + '.pdf', 'rb')\r\n output = PdfFileWriter()\r\n\r\n for i in range(infile.getNumPages()):\r\n if i not in pages_to_delete:\r\n p = infile.getPage(i)\r\n output.addPage(p)\r\n\r\n with open(directory + '\\\\' + comicname + '.pdf', 'wb') as f:\r\n output.write(f)\r\n\r\n print('Spoiler Fixed')\r\n","sub_path":"hooray.py","file_name":"hooray.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"555799546","text":"from flask import Flask, render_template\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n\treturn render_template('./home.html')\n\n@app.route('/resorts/')\ndef resorts_page():\n\treturn render_template(\"./mainpage_resorts.html\")\n\n@app.route('/resorts//')\ndef resort_page(resort):\n\tif resort == '1':\n\t\treturn render_template('./Steamboat.html')\n\tif resort == '2':\n\t\treturn render_template('./Vail.html')\n\tif resort == '3':\n\t\treturn render_template('./Breckenridge.html')\n\treturn 'nothing found'\n\n@app.route('/trails/')\ndef trails_page():\n\treturn render_template(\"./mainpage_trails.html\")\n\n@app.route('/trails//')\ndef trail_page(trail):\n\tif trail == '1':\n\t\treturn render_template('./flash_of_gold.html')\n\tif trail == '2':\n\t\treturn render_template('./strawberry_lane.html')\n\tif trail == '3':\n\t\treturn render_template('./aspen_alley_trail.html')\n\treturn 'nothing found'\n\n@app.route('/photos/')\ndef photos_page():\n\treturn render_template(\"./mainpage_photos.html\")\n\n@app.route('/photos//')\ndef photo_page(photo):\n\tif photo == '1':\n\t\treturn render_template('./flash_of_gold_pic.html')\n\tif photo == '2':\n\t\treturn render_template('./strawberry_lane_pic.html')\n\tif photo == '3':\n\t\treturn render_template('./aspen_alley_trail_pic.html')\n\treturn 'nothing found'\n\n@app.route('/about/')\ndef about_page():\n\treturn render_template('./about.html')\n\n@app.route('/carousel/')\ndef cmove():\n\treturn render_template('./carousel.html')\n\n@app.route('/githubstats/')\ndef githubstats():\n\tgithub_commits = \"https://api.github.com/repos/RobertHale/HikingAdventure/stats/contributors\"\n\tgithub_issues = \"https://api.github.com/repos/RobertHale/HikingAdventure/issues?state=all\"\n\n\t# Grab Total Commits\n\tresponse_c = requests.get(github_commits)\n\tcommit_array = response_c.json()\n\tperson = commit_array[0]\n\tcommits = 0\n\tcommits_each = {};\n\tfor person in commit_array:\n\t\tcommits = commits + person['total']\n\t\t# Stores each person's commit count separately\n\t\tcommits_each[person['author']['login']] = person['total']\n\n\n\t# Grab Total issues\n\tresponse_i = requests.get(github_issues)\n\tissue_array = response_i.json()\n\tlatest_issue = issue_array[0]\n\tissues = latest_issue['number']\n\n\n\t# Return data in a string\n\tdata = str(commits) + \" \" + str(issues) + \" \" + str(commits_each.get(\"victor40\", 0)) + \" \" + str(commits_each.get(\"duoALopez\", 0)) + \" \" + str(commits_each.get(\"alexdai186\", 0)) + \" \" + str(commits_each.get(\"RobertHale\", 0)) + \" \" + str(commits_each.get(\"vponakala\", 0)) + \" \" + str(commits_each.get(\"davepcast\", 0))\n\treturn data\n\nif __name__ == \"__main__\":\n\tapp.run()\n","sub_path":"flaskapp.py","file_name":"flaskapp.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"46006973","text":"\"\"\"\nMicro Service that overrides attributes based on Registration Authority\n\"\"\"\nimport logging\n\nfrom satosa.internal_data import InternalResponse\nfrom satosa.micro_services.base import ResponseMicroService\n\nlogger = logging.getLogger('satosa')\n\nclass AttributeOverride(ResponseMicroService):\n \"\"\"\n Metadata info extracting micro_service\n \"\"\"\n\n def __init__(self, config, internal_attributes, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.overrides = config.get('overrides', {})\n logger.info(\"AttributeOverride micro_service is active\")\n\n def process(self, context, internal_response):\n logger.info(\"Process AttributeOverride\")\n try:\n ra = context.state['metadata']['ra']\n overrides = self.overrides[ra]\n logger.debug(f\"ra: {ra}\")\n for src, values in overrides.items():\n logger.debug(f\" src attribute: {src}\")\n for value, destination in values.items():\n dst_a = destination[0]\n dst_v = destination[1]\n logger.debug(f\" value: {value}\")\n logger.debug(f\" will replace dst attribute: {dst_a}\")\n logger.debug(f\" with value: {dst_v}\")\n # First, clear all the dst attribute values\n internal_response.attributes[dst_a] = [ v for v in internal_response.attributes[dst_a] if v != dst_v ]\n # Add the override value if the source contains the condition value\n if value in internal_response.attributes[src]:\n internal_response.attributes[dst_a].append(dst_v)\n\n except Exception as e:\n logger.debug(\"AttributeOverride {}\".format(e))\n\n return super().process(context, internal_response)\n","sub_path":"src/svs/attribute_override.py","file_name":"attribute_override.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"277396154","text":"# USAGE\n# python correct_skew.py --image images/neg_28.png\n\n\nimport numpy as np\nimport argparse\nimport cv2\nimport os\nimport sys\nfrom datetime import datetime\nimport logging\n\n'''\n# import mylogging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s:%(level)s:%(filename)s:%(lineno)s: %(message)s\")\nfile_handler = logging.FileHandler(\"mylogger.log\")\nfile_handler.setLevel(logging.DEBUG)\nfile_handler.setFormatter(formatter)\n\nstream_handler = logging.StreamHandler()\nstream_handler.setLevel(logging.DEBUG)\nstream_handler.setFormatter(formatter)\n\nlogger.addHandler(file_handler)\nlogger.addHandler(stream_handler)\n'''\n\n\ndef getDeskewedFilename(srcName, id=None):\n\tfilename_w_ext = os.path.basename(srcName)\n\tfilename, file_extension = os.path.splitext(filename_w_ext)\n\thms = datetime.now().strftime('%d%H%M%S')\n\tif id != None:\n\t\tnewName = srcName.replace(filename, 'de'+filename+\"_\"+id+\"_\"+hms)\n\telse:\n\t\tnewName = srcName.replace(filename, 'de'+filename+\"_\"+hms)\n\treturn newName\n\n\ndef deskewImage(filename):\n\tlogging.info(filename)\n\ttry:\n\t\timage = cv2.imread(filename)\n\texcept:\n\t\tlogging.exception(\"message\")\n\n\t# cv2.imshow(\"Original\", image)\n\t# logging.info(\"Image...\\n\", image)\n\tret, image = cv2.threshold(image, 170, 255, cv2.THRESH_BINARY)\n\t# cv2.imshow(\"Original after threshold\", image)\n\n\t# convert the image to grayscale and flip the foreground\n\t# and background to ensure foreground is now \"white\" and\n\t# the background is \"black\"\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\t# logging.info(\"\\nGray...\\n\", gray)\n\tgray = cv2.bitwise_not(gray)\n\t# cv2.imshow(\"Gray\", gray)\n\n\t# threshold the image, setting all foreground pixels to 255 and all background pixels to 0\n\tthresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\t# logging.info(\"Thresh...\\n\", thresh)\n\t# cv2.imshow(\"Thresh\", thresh)\n\n\t# cv2.waitKey(0)\n\n\t# grab the (x, y) coordinates of all pixel values that\n\t# are greater than zero, then use these coordinates to\n\t# compute a rotated bounding box that contains all\n\t# coordinates\n\t# logging.info(\"np.where....\\n\", np.where(thresh > 0))\n\tcoords = np.column_stack(np.where(thresh > 0))\n\t# logging.info(\"coords..\\n\", coords)\n\tangle = cv2.minAreaRect(coords)[-1]\n\tlogging.info(\"angle: {}\".format(angle))\n\n\t'''\n\tlogging.info('----------------------------')\n\tcntrs, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\tfor cntr in cntrs:\n\t\tapprox = cv2.approxPolyDP(cntr, 0.01 * cv2.arcLength(cntr, True), True)\n\n\t\tif len(approx) == 4 and cv2.contourArea(cntr) > 10:\n\t\t\tlogging.info(\"size: \", cv2.contourArea(cntr))\n\t\t\tcv2.drawContours(image, [cntr], -1, (0, 0, 255), 1)\n\t\t\tcv2.imshow('Contour selected', image)\n\t\t\tcv2.waitKey(0)\n\tlogging.info('----------------------------')\n\t'''\n\n\t# the `cv2.minAreaRect` function returns values in the\n\t# range [-90, 0); as the rectangle rotates clockwise the\n\t# returned angle trends to 0 -- in this special case we\n\t# need to add 90 degrees to the angle\n\tif abs(angle) != 0.0:\n\t\tlogging.info(\"Angle needs to be adjusted..\")\n\t\tif angle < -45:\n\t\t\tangle = -(90 + angle)\n\n\t\t# otherwise, just take the inverse of the angle to make\n\t\t# it positive\n\t\telse:\n\t\t\tangle = -angle\n\n\t# rotate the image to deskew it\n\t(h, w) = image.shape[:2]\n\tcenter = (w // 2, h // 2)\n\tmiddle = cv2.getRotationMatrix2D(center, angle, 1.0)\n\trotated = cv2.warpAffine(image, middle, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\n\n\trotated = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY)\n\n\t'''\n\t# save rotated image to new file\n\tdeskewedFileName = getDeskewedFilename(filename)\n\tcv2.imwrite(deskewedFileName, rotated)\n\t'''\n\n\t# height, width, channels = rotated.shape\n\theight, width = rotated.shape\n\t# logging.info(\"Heiht:{}, Width:{}, Channels:{}\".format(height, width, channels))\n\t# dim2 = rotated.reshape(channels, height, width)\n\t# logging.info(dim2)\n\n\t# draw the correction angle on the image so we can validate it\n\t# cv2.putText(rotated, \"Angle: {:.2f} degrees\".format(angle), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n\t# show the output image\n\tlogging.info(\"[INFO] angle: {:.5f}\".format(angle))\n\t# cv2.imshow(\"Input\", image)\n\tcv2.imshow(\"Deskewed\", rotated)\n\tcv2.waitKey(0)\n\n\t'''\n\tShould have some logic to avoid memory leak.... like below\n\t'''\n\t# thresh.release()\n\t# gray.release()\n\t# image.release()\\\n\tdel thresh\n\tdel gray\n\tdel image\n\treturn deskewedFileName, rotated\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) == 1:\n\t\t# deskewImage(\"../images/hkli_image4of5-2.png\")\n\t\t# deskewImage(\"../images/hkli_image1of5-1.png\")\n\t\t# deskewImage(\"../images/hkli_image1of5-2.png\")\n\t\t# deskewImage(\"../images/hkli_deskewed1.png\")\n\t\tdeskewImage(\"../images/hkli_skewed1_ppt.png\")\n\telse:\n\t\t# construct the argument parse and parse the argumentss\n\t\tap = argparse.ArgumentParser()\n\t\tap.add_argument(\"-i\", \"--image\", required=True, help=\"path to input image file\")\n\t\targs = vars(ap.parse_args())\n\t\tfilename = args[\"image\"]\n\t\tdeskewImage(filename)","sub_path":"hkfmi_apps/correct_skew.py","file_name":"correct_skew.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"625701328","text":"class MyStatic:\n def reset(self): # 파이썬 메소드 선언 방식\n self.x = 0\n self.y = 0\n\na = MyStatic()\nMyStatic.reset(a) # 클래스 메소드\n# a.reset() 인스턴스 메소드\n\nprint('x의 값', a.x)\nprint('y의 값', a.y)\n\n\n","sub_path":"py_oop/py_static.py","file_name":"py_static.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"81496867","text":"from lxml import etree\nfrom copy import deepcopy\nimport json\nimport requests\n\nclass spiderLOLData():\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/48.0.2564.116 Safari/537.36\"}\n playerDetailUrl = \"http://lolbox.duowan.com/playerDetail.php\"\n testUrl = \"http://httpbin.org/get\"\n baseUrl = \"http://lolbox.duowan.com\"\n def __init__(self,serverName, playerName):\n self.data = {'serverName':serverName,'playerName':playerName}\n listUrl = self.baseUrl + '/matchList.php'\n r = requests.get(listUrl,params=self.data,headers = self.headers)\n self.html = etree.HTML(r.text)\n\n def getPageNum(self):\n result = self.html.xpath('//span[@class=\"page-num\"]')\n pageNum = result[0].text[3]\n return int(pageNum)\n\n def getPage(self,num):\n listUrl = self.baseUrl + '/matchList.php'\n data = deepcopy(self.data)\n data['page'] = num\n r = requests.get(listUrl,params=data,headers = self.headers)\n html = etree.HTML(r.text)\n return html\n\n def getRecordId(self,html):\n result = html.xpath('//li/@id')\n resList = []\n for item in result:\n item = item[3:]\n resList.append(item)\n return resList\n\n def getRecordIdAll(self):\n num = self.getPageNum()\n list = []\n for i in range(num):\n html = spl.getPage(i + 1)\n list.extend(spl.getRecordId(html))\n return list\n\n def getGameDetails(self,matchId):\n perGameDetailUrl = self.baseUrl + '/matchList/ajaxMatchDetail2.php'\n data = deepcopy(self.data)\n list = self.getRecordIdAll()\n data['favorate'] = '0'\n data['matchId'] = matchId\n r = requests.get(perGameDetailUrl,params=data,headers=self.headers)\n html = etree.HTML(r.text)\n listName = html.xpath('//div[@id=\"zj-table--A\"]//img/@data-playername')\n listMoney = html.xpath('//div[@id=\"zj-table--A\"]//td[@class=\"col2\"]')\n listKill = html.xpath('//div[@id=\"zj-table--A\"]//td[@class=\"col3\"]')\n listEquip = html.xpath('//div[@id=\"zj-table--A\"]//td[@class=\"col4\"]')\n gameInfo = {}\n gameList = []\n for i in range(len(listName)):\n info = {}\n info['name'] = listName[i]\n info['money'] = listMoney[i].text\n info['KDA'] = listKill[i].text\n gameList.append(info)\n gameInfo[\"胜利\"] = gameList\n listName = html.xpath('//div[@id=\"zj-table--B\"]//img/@data-playername')\n listMoney = html.xpath('//div[@id=\"zj-table--B\"]//td[@class=\"col2\"]')\n listKill = html.xpath('//div[@id=\"zj-table--B\"]//td[@class=\"col3\"]')\n listEquip = html.xpath('//div[@id=\"zj-table--B\"]//td[@class=\"col4\"]')\n gameList = []\n for i in range(len(listName)):\n info = {}\n info['Name'] = listName[i]\n info['Money'] = listMoney[i].text\n info['KDA'] = listKill[i].text\n gameList.append(info)\n gameInfo['失败'] = gameList\n return gameInfo\n\n def getGameDetailsAll(self):\n recordList = self.getRecordIdAll()\n dc = {}\n for record in recordList:\n dc[record] = self.getGameDetails(record)\n jsGameInfo = json.dumps(dc,indent=2,separators=(',',':'),sort_keys= True,ensure_ascii=False)\n print(jsGameInfo)\n #jsGameInfo = json.dumps(gameInfo,indent=2,separators=(',',':'),sort_keys= True,ensure_ascii=False)\n\nspl = spiderLOLData('电信九','cxllxn')\nspl.getGameDetailsAll()\n\n\n\n\n\n\n","sub_path":"Spider/spiderLOL.py","file_name":"spiderLOL.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"579113725","text":"sql_list = [\r\n\t'DROP TABLE IF EXISTS id_source',\r\n\tf'CREATE TABLE id_source( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tversion \tTEXT, \\\r\n\t\tbatch_key \tBOOLEAN, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS batch_audit',\r\n\tf'CREATE TABLE batch_audit( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS proc_audit',\r\n\tf'CREATE TABLE proc_audit( \\\r\n\t\trow_id \t\tINTEGER PRIMARY KEY, \\\r\n\t\tbatch_id \tINTEGER, \\\r\n\t\tproc_action\tINTEGER, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS proc_action',\r\n\tf'CREATE TABLE proc_action( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\taction \t\tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS proc_status',\r\n\tf'CREATE TABLE proc_status( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tstatus \t\tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS etl_audit',\r\n\tf'CREATE TABLE etl_audit( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tbatch_id \tINTEGER, \\\r\n\t\tproc_id \tINTEGER, \\\r\n\t\tline_id\t\tINTEGER, \\\r\n\t\tstatus_id \tINTEGER, \\\r\n\t\tupdated_on \tTEXT, \\\r\n\t\tupdated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS etl_outcome',\r\n\tf'CREATE TABLE etl_outcome( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tetl_id \t\tINTEGER, \\\r\n\t\tmessage \tINTEGER, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS outcome_messages',\r\n\tf'CREATE TABLE outcome_messages( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tmessage \tTEXT \\\r\n\t)',\r\n\r\n\tf'INSERT INTO proc_status(status) VALUES \\\r\n\t(\\'PENDING\\'), \\\r\n\t(\\'ERROR\\'), \\\r\n\t(\\'SKIPPED\\'), \\\r\n\t(\\'COMPLETE\\')',\r\n\r\n\tf'INSERT INTO outcome_messages(message) VALUES \\\r\n\t(\\'MATCH\\'), \\\r\n\t(\\'NO MATCH\\'), \\\r\n\t(\\'SUGGEST A CORRECTION\\')',\r\n]","sub_path":"__model__.py","file_name":"__model__.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"385837944","text":"\"\"\"\nCameraSystem\nSystem responsible for:\n\n\nWorks on entities with components:\n[\"CameraComponent\",\"TransformComponent\"]\n\"\"\"\nfrom engine.base.systems import System\nfrom engine.core.utils.mipy.py_extensions import overrides,implements\nfrom engine.core.utils.rect import *\nfrom engine.core.utils.vector import *\nfrom engine.core import GLOBAL\n\n\nclass CameraSystem(System):\n\n\tdef __init__(self,scene):\n\t\tsuper(CameraSystem,self).__init__(scene)\n\t\tself.updateCollection()\n\n\t@overrides(System.updateCollection)\n\tdef updateCollection(self):\n\t\tself.collection = self.getEntitiesWithComponents((\"TransformComponent\",\"CameraComponent\"))\n\t\n\n\t@overrides(System.updateLate)\n\tdef updateLate(self,dt,messenger):\n\t\tfor ent in self.collection:\n\t\t\tif ent.getComponent(\"CameraComponent\").active == 1:\n\t\t\t\ttransform_component = ent.getComponent(\"TransformComponent\")\n\t\t\t\tcamera_component \t= ent.getComponent(\"CameraComponent\")\n\t\t\t\tGLOBAL.G_camera.y \t= int(transform_component.position.y)\n\t\t\t\tGLOBAL.G_camera.x \t= int(transform_component.position.x)\n\t\t\t\tGLOBAL.G_camera.angle \t= int(camera_component.angle) \n\t\t\t\tGLOBAL.G_camera.zoom \t= float(camera_component.zoom)\t\n\t\t\t\tbreak\n","sub_path":"engine/base/systems/camerasystem.py","file_name":"camerasystem.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"617586327","text":"from flask import Blueprint, render_template, abort, session, flash, redirect\nfrom flask import url_for, request\nfrom conference_app.models import Session\nfrom datetime import datetime\n\nadmin_add_session_page = Blueprint('admin_add_session_page', __name__)\nadmin_show_sessions_page = Blueprint('admin_show_sessions_page', __name__)\nadmin_delete_session_page = Blueprint('admin_delete_session_page', __name__)\n\n\n@admin_add_session_page.route('/add', methods=['POST'])\ndef add_session():\n session = Session(c_title=request.form['c_title'],\n c_description=request.form['c_description'],\n c_venue=request.form['c_venue'],\n c_date=datetime.strptime(request.form['c_date'],\n '%Y%m%d%H%M'))\n session.save()\n flash('New session was successfully posted')\n return redirect(url_for('admin_show_sessions_page.show_sessions'))\n\n@admin_show_sessions_page.route('/show')\ndef show_sessions():\n sessions = Session.query.all()\n return render_template('admin/show_sessions.html', sessions=sessions)\n\n@admin_delete_session_page.route('/delete/')\ndef delete_session(c_id):\n session = Session.query.get(c_id)\n session.delete()\n return redirect(url_for('admin_show_sessions_page.show_sessions'))\n\n\n \n","sub_path":"conference/conference_app/views/session_admin.py","file_name":"session_admin.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"452574585","text":"ans = []\n\ndef dfs(path, cnt, tickets, T, use):\n if cnt == T:\n ans.append(path)\n return\n for i in range(T):\n if not use[i] and tickets[i][0] == path[-1]:\n use[i] = True\n dfs(path+[tickets[i][1]], cnt+1, tickets, T, use)\n use[i] = False\n\n\ndef solution(tickets):\n T = len(tickets)\n use = [False]*T\n for i in range(T):\n if tickets[i][0] == 'ICN':\n use[i] = True\n dfs([tickets[i][0], tickets[i][1]], 1, tickets, T, use)\n use[i] = False\n\n ans.sort()\n return ans[0]","sub_path":"programmers/201904/여행경로.py","file_name":"여행경로.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"182377581","text":"from config.dbconfig import pg_config\nimport psycopg2\n\nclass IceDAO:\n\n def __init__(self):\n\n connection_url = \"dbname=%s user=%s password=%s host=127.0.0.1\" % (pg_config['dbname'],\n pg_config['user'],\n pg_config['passwd'])\n self.conn = psycopg2._connect(connection_url)\n\n def getAllIce(self):\n cursor = self.conn.cursor()\n query = \"select ice_id, ice_bagSize from ice;\"\n cursor.execute(query)\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceById(self, ice_id):\n cursor = self.conn.cursor()\n query = \"select ice_id, ice_bagSize from ice where ice_id = %s;\"\n cursor.execute(query, (ice_id,))\n result = cursor.fetchone()\n return result\n\n def getIceByBagSize(self, ice_bagSize):\n cursor = self.conn.cursor()\n query = \"select * from ice where ice_bagSize = %s;\"\n cursor.execute(query, (ice_bagSize,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceByLocation(self, resr_location):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Resources where resr_location = %s;\"\n cursor.execute(query, (resr_location,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceConfirmed(self, confirmation_status):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Resources natural inner join Confirmation where confirmation_status = %s;\"\n cursor.execute(query, (confirmation_status,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceBySupplier(self, s_id):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Resources natural inner join Provides natural inner join supplier where s_id = %s;\"\n cursor.execute(query, (s_id,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIcePurchased(self):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Purchases;\"\n cursor.execute(query, ())\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def insert(self, ice_bagSize, resr_id):\n cursor = self.conn.cursor()\n query = \"insert into ice(ice_bagSize, resr_id) values (%s, %s) returning ice_id;\"\n cursor.execute(query, (ice_bagSize, resr_id,))\n iceid = cursor.fetchone()[0]\n self.conn.commit()\n return iceid\n\n def delete(self, ice_id):\n cursor = self.conn.cursor()\n query = \"delete from ice where ice_id = %s;\"\n cursor.execute(query, (ice_id,))\n self.conn.commit()\n return ice_id\n\n def update(self, ice_id, ice_bagSize):\n cursor = self.conn.cursor()\n query = \"update ice set ice_bagSize = %s where ice_id = %s;\"\n cursor.execute(query, (ice_id, ice_bagSize,))\n self.conn.commit()\n return ice_id","sub_path":"dao/ice.py","file_name":"ice.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"620670254","text":"\r\nrow1 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nrow2 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nrow3 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nmap = [row1, row2, row3]\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")\r\nposition = input(\"Where do you want to put the treasure? \")\r\n\r\n# print(map) \r\n\r\n\r\ncolumn_position = int(position[0]) - 1\r\nrow_position = int(position[1]) - 1\r\n# row_position[column_position]\r\nmap[column_position][row_position] = \"💰\"\r\n\r\n\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")","sub_path":"treasure_map.py","file_name":"treasure_map.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"636176347","text":"import pickle\r\nimport numpy as np\r\n# Disable GPU if model uses LSTM instead of GPU-optimized CuDNNLSTM\r\n# import os\r\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout, BatchNormalization, LSTM, TimeDistributed, \\\r\n CuDNNLSTM\r\nfrom keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint\r\n\r\n\r\n# Define RNN model for 10-dimensional data of unknown length; three layers; 32-16-2\r\ndef discriminator(dropout=0.2):\r\n model = Sequential()\r\n model.add(LSTM(32, input_shape=(None, 10), return_sequences=True))\r\n # model.add(CuDNNLSTM(32, input_shape=(None, 10), return_sequences=True))\r\n model.add(Dropout(dropout))\r\n model.add(LSTM(16, return_sequences=False))\r\n # model.add(CuDNNLSTM(16, return_sequences=False))\r\n model.add(Dropout(dropout))\r\n model.add(Dense(2, activation='softmax'))\r\n model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n return model\r\n\r\n\r\n# Read in cleaned/encoded data from pickle file\r\npickle_in = open('cleanData', \"rb\")\r\nrealMatches = pickle.load(pickle_in) # real matched sequence pairs\r\nfakeMatches = pickle.load(pickle_in) # fake matched sequence pairs\r\nX = pickle.load(pickle_in) # encoded matched sequence pairs\r\nY = pickle.load(pickle_in) # associated label: 1 for real, 0 for fake\r\npickle_in.close()\r\n\r\n# Initialize model\r\nmodel = discriminator()\r\n\r\n# Print model summary\r\nmodel.summary()\r\n\r\n# Set ratio for portion of data set reserved for training\r\ntrainRatio = 0.9\r\n\r\n# Set number of iterations for validation set\r\nnumVal = int(len(X) * (1 - trainRatio))\r\n\r\n\r\n# Split the encoded data into validation set and training set\r\n# Last numVal elements will be for validation, rest of them are for training\r\n\r\n\r\n# Validation set generator on which losses will be evaluated and metrics given\r\ndef validation_generator():\r\n i = -1\r\n m = numVal\r\n while True:\r\n i = (i + 1) % m\r\n yield X[-numVal + i], Y[-numVal + i]\r\n\r\n\r\n# Training set generator that composes single batch;\r\ndef train_generator():\r\n i = -1\r\n m = len(X) - numVal\r\n while True:\r\n i = (i + 1) % m\r\n yield X[i], Y[i]\r\n\r\n\r\n# Collect logging data during training\r\ntensorboard = TensorBoard(log_dir='logs', histogram_freq=0, write_graph=True, write_images=True)\r\n\r\n# Stop if no improvement in validation_loss between epochs\r\nearlystopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=50, verbose=1, restore_best_weights=True)\r\n\r\n# Save each epoch's model separately\r\nmodelcheckpoint = ModelCheckpoint(\"discriminator-improvement--{epoch:02d}--{val_loss:.2f}.h5\", monitor='val_loss',\r\n save_best_only=True, mode='auto', verbose=0)\r\n\r\n# Train the model with provided data sets\r\nstepsPerEpoch = 100 # batch size\r\nnumEpochs = int(4 * (len(X) - numVal) / (stepsPerEpoch * 5)) # keep numEpochs reasonable, i.e. < 1000\r\n\r\nhistoryObject = model.fit_generator(train_generator(), validation_data=validation_generator(),\r\n steps_per_epoch=stepsPerEpoch, epochs=numEpochs, verbose=1,\r\n validation_steps=numVal, callbacks=[tensorboard, earlystopping, modelcheckpoint],\r\n workers=8)\r\n\r\n# Organize history of discriminator training for later plotting\r\nval_loss = np.array(historyObject.history['val_loss'])\r\nval_acc = np.array(historyObject.history['val_accuracy'])\r\nloss = np.array(historyObject.history['loss'])\r\nacc = np.array(historyObject.history['accuracy'])\r\n\r\nhist = np.vstack((val_loss, val_acc, loss, acc)).T\r\n\r\n# Save the organized history into a txt file\r\nnp.savetxt(str(trainRatio * 100) + \"_history.txt\", hist, delimiter=\",\")\r\n\r\n# Save the fitted model as an h5 file\r\n# Contains model architecture, weights, training configuration (loss, optimizer), state of optimizer\r\nmodel.save('discriminator_model.h5')\r\n","sub_path":"src/discriminator_train.py","file_name":"discriminator_train.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"19820195","text":"# RUN WITH /usr/bin/python3 minet.py (python 3.6)\n\nimport sys\nimport numpy as np\nfrom sklearn.metrics import roc_curve, auc\nimport pandas as pd\n\n\nmatricesdirname = \"/home/user/Sirius/dimasdata\"\ntruematricesdirname = \"/home/user/Sirius/gene_network_sirius_2019/Matrices_1\"\npredictedfilename = matricesdirname + \"/{0}/{0}_{1}.csv\"\ntruefilename = truematricesdirname + \"/{1}_{0}_true.txt\"\ndatalist = ['exps_10', 'exps_10_2', 'exps_10_bgr', 'exps_50', 'exps_50_2', 'exps_50_bgr', 'exps_100', 'exps_100_2', 'exps_100_bgr', 'genes_200_exps_10_bgr', 'genes_400_exps_10_bgr', 'genes_600_exps_10_bgr', 'genes_700_exps_10_bgr', 'genes_1000_exps_10_bgr']\n# algolist = ['BR', 'ET', 'GB', 'Lasso_0.001', 'Lasso_0.0001', 'Lasso_0.00001', 'Lasso_0.000001', 'Lasso_0.0000001', 'RF', 'XGB']\nalgolist = ['BR', 'ET', 'GB', 'Lasso_0.001', 'Lasso_0.0001', 'Lasso_0.00001', 'Lasso_0.000001', 'Lasso_0.0000001', 'RF', 'XGB']\nsaveresultsfile = \"/home/user/Sirius/dimasdata/res2.txt\"\n\n\n\ndef matrix_stringify(m):\n \"\"\"Transform top-triangle matrix to one-dimensional array\n Parameters\n ----------\n m: np.ndarray\n two-dimensional matrix to transform\n Returns\n -------\n one-dimensional np.array\n \"\"\"\n arr = np.array([])\n for i in range(m.shape[0] - 1):\n arr = np.concatenate([arr, m[i, i+1:]])\n return arr\n\n\nif __name__ == \"__main__\":\n results = np.zeros(shape=(len(datalist), len(algolist)))\n\n for i, dataname in enumerate(datalist):\n for j, algo in enumerate(algolist):\n\n true_df = pd.read_csv(truefilename.format(dataname, 'aracne'), index_col=0, sep='\\t')\n predicted_df = pd.read_csv(predictedfilename.format(dataname, algo), index_col=0, sep=',').abs().fillna(0)\n # print(predicted_df)\n # print(1/0)\n # true_df.to_csv(savematricesdirname + \"/{0}_true.txt\".format(dataname), index=True, header=True, sep='\\t')\n # print(true_df)\n\n true_array = true_df.values[np.triu_indices(true_df.values.shape[0], k=1)]\n predicted_array = predicted_df.values[np.triu_indices(predicted_df.values.shape[0], k=1)]\n \n roc_auc = 0\n # try:\n # fpr, tpr, thresholds = roc_curve(true_array, predicted_array)\n # roc_auc = auc(fpr, tpr)\n # except:\n # print(\"error\", dataname, algo)\n fpr, tpr, thresholds = roc_curve(true_array, predicted_array)\n roc_auc = auc(fpr, tpr)\n fpr1, tpr1, thresholds1 = roc_curve(matrix_stringify(true_df.values), matrix_stringify(predicted_df.values))\n roc_auc1 = auc(fpr1, tpr1)\n\n print(\"ME AND DIMA\", roc_auc, roc_auc1)\n results[i][j] = roc_auc\n\n print(\"done\", dataname, algo, results[i][j])\n with open(saveresultsfile, \"a\") as f:\n f.write(\"done \" + dataname + \" \" + algo + \" \" + str(results[i][j]) + '\\n')\n \n # print(\"done\", dataname, algo)\n\n print(results)\n\n\n","sub_path":"RankAggregation/ComputeAucsForExternalData.py","file_name":"ComputeAucsForExternalData.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"368859847","text":"\"\"\"\nExtension of keras ImageDataGenerator for image segmentation data,\nwhere input and label are arrays of the same shape and need to be\ndistorted in the same way.\n\"\"\"\nimport keras.preprocessing.image as _image\nimport numpy as _np\nfrom builtins import super\n\n\nclass ImageDataGenerator(_image.ImageDataGenerator):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n \n def random_transform_covariant(self, x, y, seed=None):\n \"\"\"\n Randomly augment a single image tensor and its label.\n\n # Arguments\n x: 3D tensor, single image.\n y: 3D tensor, single image label.\n seed: random seed.\n\n # Returns\n A randomly transformed version of the inputs (same shape).\n \"\"\"\n # x is a single image, so it doesn't have image number at index 0\n img_row_axis = self.row_axis - 1\n img_col_axis = self.col_axis - 1\n img_channel_axis = self.channel_axis - 1\n\n if seed is not None:\n _np.random.seed(seed)\n\n # use composition of homographies\n # to generate final transform that needs to be applied\n if self.rotation_range:\n theta = _np.pi / 180 * _np.random.uniform(\n -self.rotation_range,\n self.rotation_range\n )\n else:\n theta = 0\n\n if self.height_shift_range:\n tx = _np.random.uniform(\n -self.height_shift_range,\n self.height_shift_range\n ) * x.shape[img_row_axis]\n else:\n tx = 0\n\n if self.width_shift_range:\n ty = _np.random.uniform(\n -self.width_shift_range,\n self.width_shift_range\n ) * x.shape[img_col_axis]\n else:\n ty = 0\n\n if self.shear_range:\n shear = _np.random.uniform(-self.shear_range, self.shear_range)\n else:\n shear = 0\n\n if self.zoom_range[0] == 1 and self.zoom_range[1] == 1:\n zx, zy = 1, 1\n else:\n zx, zy = _np.random.uniform(\n self.zoom_range[0],\n self.zoom_range[1],\n 2\n )\n\n # Initialise transformation matrix with identity matrix (no transformation)\n transform_matrix = _np.eye(3)\n \n if theta != 0:\n rotation_matrix = _np.array([\n [_np.cos(theta), -_np.sin(theta), 0],\n [_np.sin(theta), _np.cos(theta), 0],\n [0, 0, 1]\n ])\n transform_matrix = rotation_matrix\n\n if tx != 0 or ty != 0:\n shift_matrix = _np.array([\n [1, 0, tx],\n [0, 1, ty],\n [0, 0, 1]\n ])\n \n transform_matrix = _np.dot(transform_matrix, shift_matrix)\n\n if shear != 0:\n shear_matrix = _np.array([\n [1, -_np.sin(shear), 0],\n [0, _np.cos(shear), 0],\n [0, 0, 1]\n ])\n transform_matrix = _np.dot(transform_matrix, shear_matrix)\n\n if zx != 1 or zy != 1:\n zoom_matrix = _np.array([\n [zx, 0, 0],\n [0, zy, 0],\n [0, 0, 1]\n ])\n transform_matrix = _np.dot(transform_matrix, zoom_matrix)\n\n height, width = x.shape[img_row_axis], x.shape[img_col_axis]\n transform_matrix = _image.transform_matrix_offset_center(\n transform_matrix,\n height,\n width\n )\n \n x = _image.apply_transform(x, transform_matrix, img_channel_axis,\n fill_mode=self.fill_mode, cval=self.cval)\n y = _image.apply_transform(y, transform_matrix, img_channel_axis,\n fill_mode=self.fill_mode, cval=self.cval)\n\n if self.horizontal_flip and _np.random.random() < 0.5:\n x = _image.flip_axis(x, img_col_axis)\n y = _image.flip_axis(y, img_col_axis)\n\n return x, y\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"136442959","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.eventhub import EventHubManagementClient\n\n\"\"\"\n# PREREQUISITES\n pip install azure-identity\n pip install azure-mgmt-eventhub\n# USAGE\n python eh_event_hub_create.py\n\n Before run the sample, please set the values of the client ID, tenant ID and client secret\n of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,\n AZURE_CLIENT_SECRET. For more info about how to get the value, please see:\n https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal\n\"\"\"\n\n\ndef main():\n client = EventHubManagementClient(\n credential=DefaultAzureCredential(),\n subscription_id=\"5f750a97-50d9-4e36-8081-c9ee4c0210d4\",\n )\n\n response = client.event_hubs.create_or_update(\n resource_group_name=\"Default-NotificationHubs-AustraliaEast\",\n namespace_name=\"sdk-Namespace-5357\",\n event_hub_name=\"sdk-EventHub-6547\",\n parameters={\n \"properties\": {\n \"captureDescription\": {\n \"destination\": {\n \"name\": \"EventHubArchive.AzureBlockBlob\",\n \"properties\": {\n \"archiveNameFormat\": \"{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}\",\n \"blobContainer\": \"container\",\n \"storageAccountResourceId\": \"/subscriptions/e2f361f0-3b27-4503-a9cc-21cfba380093/resourceGroups/Default-Storage-SouthCentralUS/providers/Microsoft.ClassicStorage/storageAccounts/arjunteststorage\",\n },\n },\n \"enabled\": True,\n \"encoding\": \"Avro\",\n \"intervalInSeconds\": 120,\n \"sizeLimitInBytes\": 10485763,\n },\n \"messageRetentionInDays\": 4,\n \"partitionCount\": 4,\n \"status\": \"Active\",\n }\n },\n )\n print(response)\n\n\n# x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/EventHubs/EHEventHubCreate.json\nif __name__ == \"__main__\":\n main()\n","sub_path":"sdk/eventhub/azure-mgmt-eventhub/generated_samples/eh_event_hub_create.py","file_name":"eh_event_hub_create.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"99411016","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 22:42:04 2020\n\n@author: ken\n\nref: https://www.fullstackpython.com/blog/export-pandas-dataframes-sqlite-sqlalchemy.html\n\n\"\"\"\n\nimport argparse\nimport sys\nimport os\nimport tempfile\nimport pandas as pd\nfrom sqlalchemy import create_engine\npd.set_option('display.max_rows', 150)\npd.set_option('display.max_columns', 10)\npd.set_option('display.max_colwidth', 100)\npd.set_option('display.width', 200)\n\n\ndef main():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description='Program converts a csv file to a sqlite database ' +\n 'file. The csv file is derived from the database data of ' +\n \"Dekker's original Drawing Log program, or from the \" +\n 'sqlite database from the Drawing Log 2 program. The latter ' +\n 'program is a replacement for the former.')\n parser.add_argument('file_in', help='Name of file to import.')\n parser.add_argument('file_out', help='Name of file to export.')\n \n if len(sys.argv)==1:\n parser.print_help(sys.stderr)\n sys.exit(1)\n args = parser.parse_args() \n dwglog2_convert(args.file_in, args.file_out)\n \n \ndef dwglog2_convert(fn_in, fn_out):\n _, file_extension = os.path.splitext(fn_in)\n if (file_extension.lower() == '.csv' or file_extension.lower() == '.txt' or\n file_extension.lower() == '.xls' or file_extension.lower() == '.xlsx'):\n df = import_excel(fn_in)\n export2db(fn_out, df)\n elif file_extension.lower() == '.db':\n pass\n else:\n print('Invalid file type')\n \n \ndef import_excel(fn_in):\n try:\n _, file_extension = os.path.splitext(fn_in)\n if file_extension.lower() == '.csv' or file_extension.lower() == '.txt':\n data = make_csv_file_stable(fn_in)\n temp = tempfile.TemporaryFile(mode='w+t')\n for d in data:\n temp.write(d)\n temp.seek(0)\n df = pd.read_csv(temp, na_values=[' '], sep='$',\n encoding='iso8859_1', engine='python',\n dtype = str)\n temp.close()\n elif file_extension.lower() == '.xlsx' or file_extension.lower() == '.xls':\n df = pd.read_excel(fn_in, na_values=[' '])\n colnames = []\n for colname in df.columns: # rid colname of '\\n' char if exists\n colnames.append(colname.replace('\\n', ''))\n df.columns = colnames\n print('Data sucessfully imported')\n except:\n printStr = '\\nError processing file: ' + fn_in + '\\nIt has been excluded from the BOM check.\\n'\n print(printStr)\n return df\n \n \n\ndef export2db(fn_out, df):\n pass\n\ndef export2excel():\n pass\n\n\n\ndef make_csv_file_stable(filename):\n ''' Except for any commas in a parts DESCRIPTION, replace all commas\n in a csv file with a $ character. Commas will sometimes exist in a\n DESCRIPTION field, e.g, \"TANK, 60GAL\". But commas are intended to be field\n delimeters; commas in a DESCRIPTION field are not. Excess commas in\n a line from a csv file will cause a program crash. Remedy: change those \n commas meant to be delimiters to a dollor sign character, $.\n \n Parmeters\n =========\n\n filename: string\n Name of SolidWorks csv file to process.\n\n Returns\n =======\n\n out: list\n A list of all the lines (rows) in filename is returned. Commas in each\n line are changed to dollar signs except for any commas in the\n DESCRIPTION field.\n '''\n with open(filename, encoding=\"ISO-8859-1\") as f:\n data1 = f.readlines()\n # n1 = number of commas in 2nd line of filename (i.e. where column header\n # names located). This is the no. of commas that should be in each row.\n n1 = data1[1].count(',')\n n2 = data1[1].upper().find('Description') # locaton of the word DESCRIPTION within the row.\n n3 = data1[1][:n2].count(',') # number of commas before the word DESCRIPTION\n data2 = list(map(lambda x: x.replace(',', '$') , data1)) # replace ALL commas with $\n data = []\n for row in data2:\n n4 = row.count('$')\n if n4 != n1:\n # n5 = location of 1st ; character within the DESCRIPTION field\n # that should be a , character\n n5 = row.replace('$', '?', n3).find('$')\n # replace those ; chars that should be , chars in the DESCRIPTION field:\n data.append(row[:n5] + row[n5:].replace('$', ',', (n4-n1))) # n4-n1: no. commas needed\n else:\n data.append(row)\n return data","sub_path":"dwglog2_convert.py","file_name":"dwglog2_convert.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"68121292","text":"from __future__ import absolute_import\n\nfrom appium import webdriver\nimport time\n\nfrom shishito.runtime.environment.shishito import ShishitoEnvironment\n\n\nclass ControlEnvironment(ShishitoEnvironment):\n \"\"\" Appium control environment. \"\"\"\n\n def call_browser(self, config_section):\n \"\"\" Start webdriver for given config section. Prepare capabilities for the webdriver. If saucelabs setting has value,\n webdriver will be connected to saucelabs. Otherwise appium_url setting will be used.\n\n :param str config_section: section in platform/environment.properties config\n :return: created webdriver\n \"\"\"\n\n # get browser capabilities\n capabilities = self.get_capabilities(config_section)\n browserstack = self.shishito_support.get_opt('browserstack')\n\n if browserstack:\n try:\n bs_user, bs_password = self.shishito_support.get_opt('browserstack').split(':', 1)\n except (AttributeError, ValueError):\n raise ValueError('Browserstack credentials were not specified! Unable to start browser.')\n\n if bs_user:\n #remote_url = 'http://%s@ondemand.saucelabs.com:80/wd/hub' % saucelabs\n remote_url = 'http://{0}:{1}@hub-cloud.browserstack.com/wd/hub'.format(bs_user, bs_password)\n else:\n remote_url = self.shishito_support.get_opt('appium_url')\n\n # get driver\n return self.start_driver(capabilities, remote_url)\n\n def get_capabilities(self, config_section):\n \"\"\" Return dictionary of capabilities for specific config combination.\n\n :param str config_section: section in platform/environment.properties config\n :return: dict with capabilities\n \"\"\"\n\n get_opt = self.shishito_support.get_opt\n\n return {\n 'os': get_opt(config_section, 'os'),\n 'os_version': get_opt(config_section, 'os_version'),\n 'device': get_opt(config_section, 'device'),\n 'app': get_opt('app') or get_opt(config_section, 'app'),\n 'name': self.get_test_name() + time.strftime('_%Y-%m-%d'),\n 'browserstack.debug': get_opt('browserstack_debug').lower() or False,\n 'browserstack.appium_version': get_opt(config_section, 'browserstack.appium_version') or None,\n 'browserstack.chrome.driver': get_opt(config_section, 'browserstack.chrome.driver') or None,\n 'deviceOrientation': get_opt(config_section, 'deviceOrientation') or 'portrait',\n 'autoGrantPermissions': get_opt(config_section, 'autoGrantPermissions') or None,\n 'automationName': get_opt(config_section, 'automationName') or None,\n 'autoAcceptAlerts': get_opt(config_section, 'autoAcceptAlerts') or None,\n 'no-reset': get_opt(config_section, 'no-reset') or True,\n 'full-reset': get_opt(config_section, 'full-reset') or False,\n 'autoWebview': get_opt(config_section, 'autoWebview') or False,\n 'waitForQuiescence': get_opt(config_section, 'waitForQuiescence') or None,\n }\n\n def get_pytest_arguments(self, config_section):\n \"\"\" Get environment specific arguments for pytest.\n\n :param config_section: section in platform/environment.properties config\n :return: dict with arguments for pytest or None\n \"\"\"\n\n pytest_args = {\n '--os_version': '--os_version=%s' % self.shishito_support.get_opt(config_section, 'os_version'),\n '--device': '--device=%s' % self.shishito_support.get_opt(config_section, 'device'),\n '--app': '--app=%s' % (self.shishito_support.get_opt('app') or self.shishito_support.get_opt(config_section, 'app'))\n }\n browserstack = self.shishito_support.get_opt('browserstack')\n if browserstack:\n pytest_args['--browserstack'] = '--browserstack=%s' % browserstack\n\n return pytest_args\n\n def start_driver(self, capabilities, remote_driver_url, **kwargs):\n \"\"\" Prepare selenium webdriver.\n\n :param capabilities: capabilities used for webdriver initialization\n :param remote_driver_url: url to which the driver will be connected\n \"\"\"\n\n driver = webdriver.Remote(\n command_executor=remote_driver_url,\n desired_capabilities=capabilities,\n )\n\n return driver\n","sub_path":"shishito/runtime/environment/appium_bs.py","file_name":"appium_bs.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"641884561","text":"import numpy as np\r\nfrom rpi_d3m_primitives.featSelect.helperFunctions import normalize_array, joint\r\nfrom rpi_d3m_primitives.featSelect.mutualInformation import mi, joint_probability\r\n\"\"\"---------------------------- CONDITIONAL MUTUAL INFORMATION ----------------------------\"\"\"\r\ndef mergeArrays(firstVector, secondVector, length):\r\n \r\n if length == 0:\r\n length = firstVector.size\r\n \r\n results = normalize_array(firstVector, 0)\r\n firstNumStates = results[0]\r\n firstNormalisedVector = results[1]\r\n \r\n results = normalize_array(secondVector, 0)\r\n secondNumStates = results[0]\r\n secondNormalisedVector = results[1]\r\n \r\n stateCount = 1\r\n stateMap = np.zeros(shape = (firstNumStates*secondNumStates,))\r\n merge = np.zeros(shape =(length,))\r\n\r\n joint_states = np.column_stack((firstVector,secondVector))\r\n uniques,merge = np.unique(joint_states,axis=0,return_inverse=True)\r\n stateCount = len(uniques)\r\n results = []\r\n results.append(stateCount)\r\n results.append(merge)\r\n return results\r\n\r\n\r\ndef conditional_entropy(dataVector, conditionVector, length):\r\n condEntropy = 0\r\n jointValue = 0\r\n condValue = 0\r\n if length == 0:\r\n length = dataVector.size\r\n \r\n results = joint_probability(dataVector, conditionVector, 0)\r\n jointProbabilityVector = results[0]\r\n numJointStates = results[1]\r\n numFirstStates = results[3]\r\n secondProbabilityVector = results[4]\r\n \r\n for i in range(0, numJointStates):\r\n jointValue = jointProbabilityVector[i]\r\n condValue = secondProbabilityVector[int(i / numFirstStates)]\r\n if jointValue > 0 and condValue > 0:\r\n condEntropy -= jointValue * np.log2(jointValue / condValue);\r\n\r\n return condEntropy\r\n\r\n\r\ndef cmi(dataVector, targetVector, conditionVector, length = 0):\r\n if (conditionVector.size == 0):\r\n return mi(dataVector,targetVector,0)\r\n if (len(conditionVector.shape)>1 and conditionVector.shape[1]>1):\r\n conditionVector = joint(conditionVector)\r\n cmi = 0;\r\n firstCondition = 0\r\n secondCondition = 0\r\n \r\n if length == 0:\r\n length = dataVector.size\r\n \r\n results = mergeArrays(targetVector, conditionVector, length)\r\n mergedVector = results[1]\r\n \r\n firstCondition = conditional_entropy(dataVector, conditionVector, length)\r\n secondCondition = conditional_entropy(dataVector, mergedVector, length)\r\n cmi = firstCondition - secondCondition\r\n \r\n return cmi","sub_path":"featSelect/conditionalMI.py","file_name":"conditionalMI.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"553268705","text":"import gspread\nimport hmac\nfrom hashlib import sha1\nimport json\nimport logging\nfrom oauth2client.client import SignedJwtAssertionCredentials\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.core.exceptions import ValidationError\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom rest_framework.authtoken.models import Token\n\nfrom api.exceptions import Kromeo2015ValidationError\nfrom api.forms import SpreadsheetUserDataGetForm\nfrom api.models import UserProfile\n\nRANGE_MASK = 'A{}:J{}'\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpreadsheetService(object):\n\n @classmethod\n def _get_worksheet(cls):\n json_key = json.load(open('../serverdeploy/kromeo2015-012bacfe8afc.json'))\n scope = ['https://spreadsheets.google.com/feeds']\n credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)\n google_connection = gspread.authorize(credentials)\n worksheet = google_connection.open_by_key(settings.GDRIVE_DOC_KEY).sheet1\n return worksheet, len(worksheet.get_all_values())\n\n @classmethod\n def update_cells(cls, cells):\n for cell in cells:\n logger.info(cell.__dict__)\n worksheet, num_of_rows = cls._get_worksheet()\n worksheet.update_cells(cells)\n\n # TODO: This needs some significant refactoring as gspread is currently not testable\n @classmethod\n def retrieve_remote_data(cls):\n from api.tasks import initial_guest_creation_task\n\n worksheet, num_of_rows = cls._get_worksheet()\n\n errors = []\n\n for row in range(2, num_of_rows + 1):\n cells = worksheet.range(RANGE_MASK.format(row, row))\n\n form = SpreadsheetUserDataGetForm(\n {\n 'username': cells[0].value,\n 'full_name': cells[1].value,\n 'friendly_name': cells[2].value,\n 'email': cells[3].value,\n 'save_date_url': cells[4].value,\n # 'date_emailed': cells[5].value,\n # 'date_viewed': cells[6].value,\n 'address': cells[7].value,\n 'rsvp_response': cells[8].value,\n 'rsvp_count': cells[9].value,\n }\n )\n\n if not form.is_valid():\n errors.append({\"R{}\".format(row): form.errors})\n continue\n\n is_new = True\n if form.cleaned_data['username']:\n is_new = False\n\n if not is_new:\n user = User.objects.get(username=form.cleaned_data['username'])\n else:\n password = UserService.generate_password()\n\n user = User(\n password=password\n )\n\n user.email = form.cleaned_data['email']\n user.full_name = form.cleaned_data['full_name']\n\n try:\n user.save()\n except ValidationError as e:\n errors.append({\"R{}\".format(row): str(e)})\n continue\n\n if not is_new:\n user_profile = user.userprofile\n else:\n user_profile = UserProfile(user=user)\n\n user_profile.address = form.cleaned_data['address']\n user_profile.friendly_name = form.cleaned_data['friendly_name']\n # user_profile.date_viewed = form.cleaned_data['date_viewed']\n # user_profile.date_emailed = form.cleaned_data['date_emailed']\n\n try:\n user_profile.save()\n except ValidationError as e:\n errors.append({\"R{}\".format(row): str(e)})\n continue\n\n if is_new:\n token = Token(user=user)\n token.key = token.generate_key()\n token.save()\n\n cells[0].value = user.username\n cells[4].value = UserService.get_absolute_save_the_date_url(user)\n initial_guest_creation_task.delay(cells=[cells[0], cells[4]], user=user)\n\n if errors:\n raise Kromeo2015ValidationError(message=str(errors))\n\n @classmethod\n def update_remote_data(cls, user):\n if not settings.ENABLE_SPREADSHEET_UPDATE_SIGNALS:\n return\n\n worksheet, num_of_rows = cls._get_worksheet()\n\n cell = worksheet.find(user.username)\n\n if cell.col != 1:\n raise ValidationError(\"Clash of IDs %s\", user.username)\n\n cells = worksheet.range(RANGE_MASK.format(cell.row, cell.row))\n\n cells[0].value = user.username\n cells[1].value = user.get_full_name()\n cells[2].value = user.userprofile.friendly_name\n cells[3].value = user.email\n cells[4].value = UserService.get_absolute_save_the_date_url(user)\n cells[5].value = user.userprofile.date_emailed.replace(microsecond=0).isoformat() if user.userprofile.date_emailed else None\n cells[6].value = user.userprofile.date_viewed.replace(microsecond=0).isoformat() if user.userprofile.date_viewed else None\n cells[7].value = user.userprofile.address\n cells[8].value = user.userprofile.rsvp_response\n\n cells_for_update = []\n for cell in cells:\n if cell.value:\n cells_for_update.append(cell)\n\n # a null value of 0 is still legit for the RSVP Count\n cells[9].value = user.userprofile.rsvp_count\n cells_for_update.append(cells[9])\n\n worksheet.update_cells(cells_for_update)\n\n\nclass UserService(object):\n @classmethod\n def get_absolute_save_the_date_url(cls, user):\n return 'https://{}{}'.format(\n Site.objects.get_current().domain,\n reverse('web-save-the-date', kwargs={'username': user.username})\n )\n\n @classmethod\n def generate_username(cls):\n hmac_gen = hmac.new(settings.USERNAME_SHA1_KEY, timezone.now().isoformat(), sha1)\n return \"u{}\".format(hmac_gen.digest().encode('hex')[:5])\n\n @classmethod\n def generate_password(cls):\n hmac_gen = hmac.new(settings.USERNAME_SHA1_KEY, timezone.now().isoformat(), sha1)\n return hmac_gen.digest().encode('hex')[:30]\n","sub_path":"kromeo2015/api/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":6258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"263979750","text":"\"\"\"\n\nMisc. helper functions used in Empire.\n\nIncludes:\n\n validate_ip() - validate an IP\n validate_ntlm() - checks if the passed string is an NTLM hash\n random_string() - returns a random string of the specified number of characters\n chunks() - used to split a string into chunks\n strip_python_comments() - strips Python newlines and comments\n enc_powershell() - encodes a PowerShell command into a form usable by powershell.exe -enc ...\n powershell_launcher() - builds a command line powershell.exe launcher\n parse_powershell_script() - parses a raw PowerShell file and return the function names\n strip_powershell_comments() - strips PowerShell newlines and comments\n get_powerview_psreflect_overhead() - extracts some of the psreflect overhead for PowerView\n get_dependent_functions() - extracts function dependenies from a PowerShell script\n find_all_dependent_functions() - takes a PowerShell script and a set of functions, and returns all dependencies\n generate_dynamic_powershell_script() - takes a PowerShell script and set of functions and returns a minimized script\n parse_credentials() - enumerate module output, looking for any parseable credential sections\n parse_mimikatz() - parses the output of Invoke-Mimikatz\n get_config() - pulls config information from the database output of normal menu execution\n get_listener_options() - gets listener options outside of normal menu execution\n get_datetime() - returns the current date time in a standard format\n get_file_datetime() - returns the current date time in a format savable to a file\n get_file_size() - returns a string representing file size\n lhost() - returns the local IP\n color() - used for colorizing output in the Linux terminal\n unique() - uniquifies a list, order preserving\n uniquify_tuples() - uniquifies Mimikatz tuples based on the password\n decode_base64() - tries to base64 decode a string\n encode_base64() - tries to base64 encode a string\n complete_path() - helper to tab-complete file paths\n dict_factory() - helper that returns the SQLite query results as a dictionary\n KThread() - a subclass of threading.Thread, with a kill() method\n slackMessage() - send notifications to the Slack API\n\"\"\"\nimport base64\nimport binascii\nimport ipaddress\nimport json\nimport logging\nimport os\nimport random\nimport re\nimport socket\nimport string\nimport sys\nimport threading\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom builtins import range, str\nfrom datetime import datetime\n\nimport netifaces\n\nfrom empire.server.utils.math_util import old_div\n\nlog = logging.getLogger(__name__)\n\n\n###############################################################\n#\n# Global Variables\n#\n################################################################\n\nglobentropy = random.randint(1, datetime.today().day)\nglobDebug = False\n\n\n###############################################################\n#\n# Validation methods\n#\n###############################################################\n\n\ndef validate_ip(IP):\n \"\"\"\n Validate an IP.\n \"\"\"\n try:\n ipaddress.ip_address(IP)\n return True\n except Exception:\n return False\n\n\ndef validate_ntlm(data):\n \"\"\"\n Checks if the passed string is an NTLM hash.\n \"\"\"\n allowed = re.compile(\"^[0-9a-f]{32}\", re.IGNORECASE)\n if allowed.match(data):\n return True\n else:\n return False\n\n\n####################################################################################\n#\n# Randomizers/obfuscators\n#\n####################################################################################\ndef random_string(length=-1, charset=string.ascii_letters):\n \"\"\"\n Returns a random string of \"length\" characters.\n If no length is specified, resulting string is in between 6 and 15 characters.\n A character set can be specified, defaulting to just alpha letters.\n \"\"\"\n if length == -1:\n length = random.randrange(6, 16)\n random_string = \"\".join(random.choice(charset) for x in range(length))\n return random_string\n\n\ndef obfuscate_call_home_address(data):\n \"\"\"\n Poowershell script to base64 encode variable contents and execute on command as if clear text in powershell\n \"\"\"\n tmp = \"$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('\"\n tmp += (enc_powershell(data)).decode(\"UTF-8\") + \"')))\"\n return tmp\n\n\ndef chunks(s, n):\n \"\"\"\n Generator to split a string s into chunks of size n.\n Used by macro modules.\n \"\"\"\n for i in range(0, len(s), n):\n yield s[i : i + n]\n\n\n####################################################################################\n#\n# Python-specific helpers\n#\n####################################################################################\n\n\ndef strip_python_comments(data):\n \"\"\"\n *** DECEMBER 2017 - DEPRECATED, PLEASE DO NOT USE ***\n\n Strip block comments, line comments, empty lines, verbose statements, docstring,\n and debug statements from a Python source file.\n \"\"\"\n log.warning(\"strip_python_comments is deprecated and should not be used\")\n\n # remove docstrings\n data = re.sub(r'\"(?\", re.DOTALL), \"\\n\", data)\n\n # strip blank lines, lines starting with #, and verbose/debug statements\n strippedCode = \"\\n\".join(\n [\n line\n for line in strippedCode.split(\"\\n\")\n if (\n (line.strip() != \"\")\n and (not line.strip().startswith(\"#\"))\n and (not line.strip().lower().startswith(\"write-verbose \"))\n and (not line.strip().lower().startswith(\"write-debug \"))\n )\n ]\n )\n\n return strippedCode\n\n\n####################################################################################\n#\n# PowerView dynamic generation helpers\n#\n####################################################################################\n\n\ndef get_powerview_psreflect_overhead(script):\n \"\"\"\n Helper to extract some of the psreflect overhead for PowerView/PowerUp.\n \"\"\"\n\n if \"PowerUp\" in script[0:100]:\n pattern = re.compile(r\"\\n\\$Module =.*\\[\\'kernel32\\'\\]\", re.DOTALL)\n else:\n # otherwise extracting from PowerView\n pattern = re.compile(r\"\\n\\$Mod =.*\\[\\'wtsapi32\\'\\]\", re.DOTALL)\n\n try:\n return strip_powershell_comments(pattern.findall(script)[0])\n except Exception:\n log.error(\"Error extracting psreflect overhead from script!\")\n return \"\"\n\n\ndef get_dependent_functions(code, functionNames):\n \"\"\"\n Helper that takes a chunk of PowerShell code and a set of function\n names and returns the unique set of function names within the script block.\n \"\"\"\n\n dependentFunctions = set()\n for functionName in functionNames:\n # find all function names that aren't followed by another alpha character\n if re.search(\"[^A-Za-z']+\" + functionName + \"[^A-Za-z']+\", code, re.IGNORECASE):\n # if \"'AbuseFunction' \\\"%s\" % (functionName) not in code:\n # TODO: fix superflous functions from being added to PowerUp Invoke-AllChecks code...\n dependentFunctions.add(functionName)\n\n if re.search(\"\\$Netapi32|\\$Advapi32|\\$Kernel32|\\$Wtsapi32\", code, re.IGNORECASE):\n dependentFunctions |= set(\n [\"New-InMemoryModule\", \"func\", \"Add-Win32Type\", \"psenum\", \"struct\"]\n )\n\n return dependentFunctions\n\n\ndef find_all_dependent_functions(functions, functionsToProcess, resultFunctions=[]):\n \"\"\"\n Takes a dictionary of \"[functionName] -> functionCode\" and a set of functions\n to process, and recursively returns all nested functions that may be required.\n\n Used to map the dependent functions for nested script dependencies like in\n PowerView.\n \"\"\"\n\n if isinstance(functionsToProcess, str):\n functionsToProcess = [functionsToProcess]\n\n while len(functionsToProcess) != 0:\n # pop the next function to process off the stack\n requiredFunction = functionsToProcess.pop()\n\n if requiredFunction not in resultFunctions:\n resultFunctions.append(requiredFunction)\n\n # get the dependencies for the function we're currently processing\n try:\n functionDependencies = get_dependent_functions(\n functions[requiredFunction], list(functions.keys())\n )\n except Exception:\n functionDependencies = []\n log.error(\n f\"Error in retrieving dependencies for function {requiredFunction} !\"\n )\n\n for functionDependency in functionDependencies:\n if (\n functionDependency not in resultFunctions\n and functionDependency not in functionsToProcess\n ):\n # for each function dependency, if we haven't already seen it\n # add it to the stack for processing\n functionsToProcess.append(functionDependency)\n resultFunctions.append(functionDependency)\n\n resultFunctions = find_all_dependent_functions(\n functions, functionsToProcess, resultFunctions\n )\n\n return resultFunctions\n\n\ndef generate_dynamic_powershell_script(script, function_names):\n \"\"\"\n Takes a PowerShell script and a function name (or array of function names,\n generates a dictionary of \"[functionNames] -> functionCode\", and recursively\n maps all dependent functions for the specified function name.\n\n A script is returned with only the code necessary for the given\n functionName, stripped of comments and whitespace.\n\n Note: for PowerView, it will also dynamically detect if psreflect\n overhead is needed and add it to the result script.\n \"\"\"\n\n new_script = \"\"\n psreflect_functions = [\n \"New-InMemoryModule\",\n \"func\",\n \"Add-Win32Type\",\n \"psenum\",\n \"struct\",\n ]\n\n if type(function_names) is not list:\n function_names = [function_names]\n\n # build a mapping of functionNames -> stripped function code\n functions = {}\n pattern = re.compile(r\"\\n(?:function|filter).*?{.*?\\n}\\n\", re.DOTALL)\n\n script = re.sub(re.compile(\"<#.*?#>\", re.DOTALL), \"\", script)\n for func_match in pattern.findall(script):\n name = func_match[:40].split()[1]\n functions[name] = func_match\n\n # recursively enumerate all possible function dependencies and\n # start building the new result script\n function_dependencies = []\n\n for functionName in function_names:\n function_dependencies += find_all_dependent_functions(\n functions, functionName, []\n )\n function_dependencies = unique(function_dependencies)\n\n for function_dependency in function_dependencies:\n try:\n new_script += functions[function_dependency] + \"\\n\"\n except Exception:\n log.error(f\"Key error with function {function_dependency} !\")\n\n # if any psreflect methods are needed, add in the overhead at the end\n if any(el in set(psreflect_functions) for el in function_dependencies):\n new_script += get_powerview_psreflect_overhead(script)\n\n new_script = strip_powershell_comments(new_script)\n\n return new_script + \"\\n\"\n\n\n###############################################################\n#\n# Parsers\n#\n###############################################################\n\n\ndef parse_credentials(data):\n \"\"\"\n Enumerate module output, looking for any parseable credential sections.\n \"\"\"\n if isinstance(data, str):\n data = data.encode(\"UTF-8\")\n parts = data.split(b\"\\n\")\n\n # tag for Invoke-Mimikatz output\n if parts[0].startswith(b\"Hostname:\"):\n return parse_mimikatz(data)\n\n # powershell/collection/prompt output\n elif parts[0].startswith(b\"[+] Prompted credentials:\"):\n parts = parts[0].split(b\"->\")\n if len(parts) == 2:\n username = parts[1].split(b\":\", 1)[0].strip()\n password = parts[1].split(b\":\", 1)[1].strip()\n\n if \"\\\\\" in username:\n domain = username.split(\"\\\\\")[0].strip()\n username = username.split(\"\\\\\")[1].strip()\n else:\n domain = \"\"\n\n return [(\"plaintext\", domain, username, password, \"\", \"\")]\n\n else:\n log.error(\"Error in parsing prompted credential output.\")\n return None\n\n # python/collection/prompt (Mac OS)\n elif b\"text returned:\" in parts[0]:\n parts2 = parts[0].split(b\"text returned:\")\n if len(parts2) >= 2:\n password = parts2[-1]\n return [(\"plaintext\", \"\", \"\", password, \"\", \"\")]\n\n else:\n return None\n\n\ndef parse_mimikatz(data):\n \"\"\"\n Parse the output from Invoke-Mimikatz to return credential sets.\n \"\"\"\n\n # cred format:\n # credType, domain, username, password, hostname, sid\n creds = []\n\n # regexes for \"sekurlsa::logonpasswords\" Mimikatz output\n regexes = [\n \"(?s)(?<=msv :).*?(?=tspkg :)\",\n \"(?s)(?<=tspkg :).*?(?=wdigest :)\",\n \"(?s)(?<=wdigest :).*?(?=kerberos :)\",\n \"(?s)(?<=kerberos :).*?(?=ssp :)\",\n \"(?s)(?<=ssp :).*?(?=credman :)\",\n \"(?s)(?<=credman :).*?(?=Authentication Id :)\",\n \"(?s)(?<=credman :).*?(?=mimikatz)\",\n ]\n\n hostDomain = \"\"\n domainSid = \"\"\n hostName = \"\"\n if isinstance(data, str):\n data = data.encode(\"UTF-8\")\n lines = data.split(b\"\\n\")\n for line in lines[0:2]:\n if line.startswith(b\"Hostname:\"):\n try:\n domain = line.split(b\":\")[1].strip()\n temp = domain.split(b\"/\")[0].strip()\n domainSid = domain.split(b\"/\")[1].strip()\n\n hostName = temp.split(b\".\")[0]\n hostDomain = b\".\".join(temp.split(\".\")[1:])\n except Exception:\n pass\n\n for regex in regexes:\n p = re.compile(regex)\n for match in p.findall(data.decode(\"UTF-8\")):\n lines2 = match.split(\"\\n\")\n username, domain, password = \"\", \"\", \"\"\n\n for line in lines2:\n try:\n if \"Username\" in line:\n username = line.split(\":\", 1)[1].strip()\n elif \"Domain\" in line:\n domain = line.split(\":\", 1)[1].strip()\n elif \"NTLM\" in line or \"Password\" in line:\n password = line.split(\":\", 1)[1].strip()\n except Exception:\n pass\n\n if username != \"\" and password != \"\" and password != \"(null)\":\n sid = \"\"\n\n # substitute the FQDN in if it matches\n if hostDomain.startswith(domain.lower()):\n domain = hostDomain\n sid = domainSid\n\n if validate_ntlm(password):\n credType = \"hash\"\n\n else:\n credType = \"plaintext\"\n\n # ignore machine account plaintexts\n if not (credType == \"plaintext\" and username.endswith(\"$\")):\n creds.append((credType, domain, username, password, hostName, sid))\n\n if len(creds) == 0 and len(lines) >= 13:\n # check if we have lsadump output to check for krbtgt\n # happens on domain controller hashdumps\n for x in range(8, 13):\n if lines[x].startswith(b\"Domain :\"):\n domain, sid, krbtgtHash = b\"\", b\"\", b\"\"\n\n try:\n domainParts = lines[x].split(b\":\")[1]\n domain = domainParts.split(b\"/\")[0].strip()\n sid = domainParts.split(b\"/\")[1].strip()\n\n # substitute the FQDN in if it matches\n if hostDomain.startswith(domain.decode(\"UTF-8\").lower()):\n domain = hostDomain\n sid = domainSid\n\n for x in range(0, len(lines)):\n if lines[x].startswith(b\"User : krbtgt\"):\n krbtgtHash = lines[x + 2].split(b\":\")[1].strip()\n break\n\n if krbtgtHash != b\"\":\n creds.append(\n (\n \"hash\",\n domain.decode(\"UTF-8\"),\n \"krbtgt\",\n krbtgtHash.decode(\"UTF-8\"),\n hostName.decode(\"UTF-8\"),\n sid.decode(\"UTF-8\"),\n )\n )\n except Exception:\n pass\n\n if len(creds) == 0:\n # check if we get lsadump::dcsync output\n if b\"** SAM ACCOUNT **\" in lines:\n domain, user, userHash, dcName, sid = \"\", \"\", \"\", \"\", \"\"\n for line in lines:\n if line.strip().endswith(b\"will be the domain\"):\n domain = line.split(b\"'\")[1]\n elif line.strip().endswith(b\"will be the DC server\"):\n dcName = line.split(b\"'\")[1].split(b\".\")[0]\n elif line.strip().startswith(b\"SAM Username\"):\n user = line.split(b\":\")[1].strip()\n elif line.strip().startswith(b\"Object Security ID\"):\n parts = line.split(b\":\")[1].strip().split(b\"-\")\n sid = b\"-\".join(parts[0:-1])\n elif line.strip().startswith(b\"Hash NTLM:\"):\n userHash = line.split(b\":\")[1].strip()\n\n if domain != \"\" and userHash != \"\":\n creds.append(\n (\n \"hash\",\n domain.decode(\"UTF-8\"),\n user.decode(\"UTF-8\"),\n userHash.decode(\"UTF-8\"),\n dcName.decode(\"UTF-8\"),\n sid.decode(\"UTF-8\"),\n )\n )\n\n return uniquify_tuples(creds)\n\n\n###############################################################\n#\n# Miscellaneous methods (formatting, sorting, etc.)\n#\n###############################################################\n\n\ndef get_datetime():\n \"\"\"\n Return the local current date/time\n \"\"\"\n return datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\ndef get_file_datetime():\n \"\"\"\n Return the current date/time in a format workable for a file name.\n \"\"\"\n return datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n\n\ndef get_file_size(file):\n \"\"\"\n Returns a string with the file size and highest rating.\n \"\"\"\n byte_size = sys.getsizeof(file)\n kb_size = old_div(byte_size, 1024)\n if kb_size == 0:\n byte_size = \"%s Bytes\" % (byte_size)\n return byte_size\n mb_size = old_div(kb_size, 1024)\n if mb_size == 0:\n kb_size = \"%s KB\" % (kb_size)\n return kb_size\n gb_size = old_div(mb_size, 1024) % (mb_size)\n if gb_size == 0:\n mb_size = \"%s MB\" % (mb_size)\n return mb_size\n return \"%s GB\" % (gb_size)\n\n\ndef lhost():\n \"\"\"\n Return the local IP.\n \"\"\"\n\n if os.name != \"nt\":\n import fcntl\n import struct\n\n def get_interface_ip(ifname):\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(\n fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack(\"256s\", ifname[:15].encode(\"UTF-8\")),\n )[20:24]\n )\n except IOError:\n return \"\"\n\n ip = \"\"\n try:\n ip = socket.gethostbyname(socket.gethostname())\n except socket.gaierror:\n pass\n except Exception:\n log.error(\"Unexpected error:\", exc_info=True)\n return ip\n\n if (ip == \"\" or ip.startswith(\"127.\")) and os.name != \"nt\":\n interfaces = netifaces.interfaces()\n for ifname in interfaces:\n if \"lo\" not in ifname:\n try:\n ip = get_interface_ip(ifname)\n if ip != \"\":\n break\n except Exception:\n log.error(\"Unexpected error:\", exc_info=True)\n pass\n return ip\n\n\ndef color(string, color=None):\n \"\"\"\n Change text color for the Linux terminal.\n \"\"\"\n\n attr = []\n # bold\n attr.append(\"1\")\n\n if color:\n if color.lower() == \"red\":\n attr.append(\"31\")\n elif color.lower() == \"green\":\n attr.append(\"32\")\n elif color.lower() == \"yellow\":\n attr.append(\"33\")\n elif color.lower() == \"blue\":\n attr.append(\"34\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n\n else:\n if string.strip().startswith(\"[!]\"):\n attr.append(\"31\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n elif string.strip().startswith(\"[+]\"):\n attr.append(\"32\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n elif string.strip().startswith(\"[*]\"):\n attr.append(\"34\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n elif string.strip().startswith(\"[>]\"):\n attr.append(\"33\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n else:\n return string\n\n\ndef unique(seq, idfun=None):\n \"\"\"\n Uniquifies a list, order preserving.\n\n from http://www.peterbe.com/plog/uniqifiers-benchmark\n \"\"\"\n if idfun is None:\n\n def idfun(x):\n return x\n\n seen = {}\n result = []\n for item in seq:\n marker = idfun(item)\n # in old Python versions:\n # if seen.has_key(marker)\n # but in new ones:\n if marker in seen:\n continue\n seen[marker] = 1\n result.append(item)\n return result\n\n\ndef uniquify_tuples(tuples):\n \"\"\"\n Uniquifies Mimikatz tuples based on the password.\n\n cred format- (credType, domain, username, password, hostname, sid)\n \"\"\"\n seen = set()\n return [\n item\n for item in tuples\n if \"%s%s%s%s\" % (item[0], item[1], item[2], item[3]) not in seen\n and not seen.add(\"%s%s%s%s\" % (item[0], item[1], item[2], item[3]))\n ]\n\n\ndef decode_base64(data):\n \"\"\"\n Try to decode a base64 string.\n From http://stackoverflow.com/questions/2941995/python-ignore-incorrect-padding-error-when-base64-decoding\n \"\"\"\n missing_padding = 4 - len(data) % 4\n if isinstance(data, str):\n data = data.encode(\"UTF-8\")\n\n if missing_padding:\n data += b\"=\" * missing_padding\n\n try:\n result = base64.decodebytes(data)\n return result\n except binascii.Error:\n # if there's a decoding error, just return the data\n return data\n\n\ndef encode_base64(data):\n \"\"\"\n Encode data as a base64 string.\n \"\"\"\n return base64.encodebytes(data).strip()\n\n\nclass KThread(threading.Thread):\n \"\"\"\n A subclass of threading.Thread, with a kill() method.\n From https://web.archive.org/web/20130503082442/http://mail.python.org/pipermail/python-list/2004-May/281943.html\n \"\"\"\n\n def __init__(self, *args, **keywords):\n threading.Thread.__init__(self, *args, **keywords)\n self.killed = False\n\n def start(self):\n \"\"\"Start the thread.\"\"\"\n self.__run_backup = self.run\n self.run = self.__run # Force the Thread toinstall our trace.\n threading.Thread.start(self)\n\n def __run(self):\n \"\"\"Hacked run function, which installs the trace.\"\"\"\n sys.settrace(self.globaltrace)\n self.__run_backup()\n self.run = self.__run_backup\n\n def globaltrace(self, frame, why, arg):\n if why == \"call\":\n return self.localtrace\n else:\n return None\n\n def localtrace(self, frame, why, arg):\n if self.killed:\n if why == \"line\":\n raise SystemExit()\n return self.localtrace\n\n def kill(self):\n self.killed = True\n\n\ndef slackMessage(slack_webhook_url, slack_text):\n message = {\"text\": slack_text}\n req = urllib.request.Request(slack_webhook_url, json.dumps(message).encode(\"UTF-8\"))\n urllib.request.urlopen(req)\n","sub_path":"empire/server/common/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":25787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"292319443","text":"import discord\nimport asyncio\nimport requests\nimport time\nimport string\nimport random\n\nDISCORD_BOT_TOKEN = 'NDM0MjM2MjI2NTczNDM0ODkx.DbIc-w.ufvbmB_MSVQqd7kIHrUFMQxdxnc'\n\nBTC_PRICE_URL_coinmarketcap = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=RUB'\n\nclient = discord.Client()\n#http = discord.http\n\nsave_channel = 0\nadmin_list = ['265474107666202634', '282660110545846272']\nadmin_channel_list = ['434056729362169857', '433267590937444364', '43568779755939430']\n\nprefix = '!'\nstops = 0\n#lock = 0\n\nquiz_channel = 0\nquiz = 0\nquiz_number = -1\nquiz_numbers = -1\nset_answer = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n\nquestion = ['1) https://sun9-6.userapi.com/c840724/v840724591/74499/x8hB5rkgIkU.jpg',\n\t\t\t'2) https://pp.userapi.com/c846320/v846320591/23582/SClHqmmWE0Y.jpg',\n\t\t\t'3) https://pp.userapi.com/c834100/v834100591/116733/OuwBfc0GKwc.jpg',\n\t\t\t'4) https://pp.userapi.com/c841639/v841639591/7ee08/UC7dluXRGgI.jpg',\n\t\t\t'5) https://pp.userapi.com/c834202/v834202591/d6b84/AnYJtA--lE0.jpg',\n\t\t\t'6) https://pp.userapi.com/c824411/v824411591/1164c1/5mZIEYsbHAI.jpg',\n\t\t\t'7) https://pp.userapi.com/c846017/v846017591/24701/Bh25snWBCl8.jpg',\n\t\t\t'8) https://pp.userapi.com/c846219/v846219591/23a84/EV5tVSseGj4.jpg',\n\t\t\t'9) https://pp.userapi.com/c847020/v847020591/2557b/K21NUu_G_ec.jpg',\n\t\t\t'10) https://pp.userapi.com/c834203/v834203591/117502/4NYjkoSAtnU.jpg',\n\t\t\t'11) https://pp.userapi.com/c831508/v831508591/d3c68/qtlwIGrbvwc.jpg',\n\t\t\t'12) https://pp.userapi.com/c830609/v830609591/cf56e/NIfBShi_EGM.jpg',\n\t\t\t'13) https://pp.userapi.com/c834104/v834104533/112c65/A2mmg_mLiK4.jpg',\n\t\t\t'14) https://pp.userapi.com/c845019/v845019533/2c064/t6Z4_1yxetE.jpg',\n\t\t\t'15) https://pp.userapi.com/c844720/v844720523/28eed/Im1kZS1WoKI.jpg',\n\t\t\t'16) https://pp.userapi.com/c834100/v834100897/114102/qeXr4eut2oU.jpg',\n\t\t\t'17) https://pp.userapi.com/c847123/v847123209/2630f/QZKvAWreGN4.jpg',\n\t\t\t'18) https://pp.userapi.com/c830108/v830108944/d1c82/ZnnQbYyVA-g.jpg',\n\t\t\t'19) https://pp.userapi.com/c841221/v841221058/74759/2qj4ClVx0GQ.jpg',\n\t\t\t'20) https://pp.userapi.com/c831309/v831309589/ca39f/_2ATdwnWZVE.jpg',\n\t\t\t'21) http://animeru.tv/assets/images/resources/1575/1791ca9d6eb0fa2c28e5f15000d518258641d54a.jpg',\n\t\t\t'22) https://scontent-arn2-1.cdninstagram.com/vp/ae79ff0ec82053fc68d40dae663466c8/5B2FD62C/t51.2885-15/e35/23164144_587504724707054_4524634221112721408_n.jpg',\n\t\t\t'23) https://awesomereviews.ru/wp-content/uploads/2017/09/%D0%91%D0%BB%D0%B8%D1%82%D1%86-%D0%A2%D0%BE%D0%BB%D0%BA%D0%B5%D1%80.jpg',\n\t\t\t'24) http://i.imgur.com/QYr2C7c.jpg',\n\t\t\t'25) https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQYVb09iGL5Fe63aMQx8hXnsECcuqpxupUciSbXnHf2j10Ue_4dTg',\n\t\t\t'26) https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQIuyzrQBascnms3B1vOeTJF6NHfQYIw4HlJZMdt9KsHtKVe64Jfw',\n\t\t\t'27) http://nisamerica.com/lovelive/images/screenshots/9.jpg',\n\t\t\t'28) https://pbs.twimg.com/media/C9xjyVFXkAIiyhs.jpg']\n\nquiz_answer = [['врата штейна', 'врата штайнера'],\n\t\t ['сегодняшний ужин для эмии', 'сегодняшнее меню для эмии'],\n\t\t ['проект воспитания девочек-волшебниц'],\n\t\t ['кейон!', 'кейон', 'легкая музыка!', 'легкая музыка', 'клуб легкой музыки'],\n\t\t ['созданный в бездне'],\n\t\t ['невероятные приключения джоджо', 'джоджо', 'жожо'],\n\t\t ['девочка-волшебница мадока магика', 'девочка-волшебница мадока', 'девочка волшебница мадока'],\n\t\t ['загадочная история коноханы', 'сказания о конохане', 'история коноханы'],\n\t\t ['садистская смесь'],\n\t\t ['любовь и тьма неприятностей'],\n\t\t ['судный день', 'день гнева'],\n\t\t ['ведьмина магия в деле', 'ведьма за работой'],\n\t\t ['бтууум!', 'взрыв', 'взрыв!', 'бтууум'],\n\t\t ['сердцу хочеться кричать', 'сердцу хочеться петь'],\n\t\t ['шарлотта'],\n\t\t ['связанные'],\n\t\t ['город, в котором меня нет', 'город в котором меня нет', 'город, в котором пропал лишь я', 'город в котором пропал лишь я'],\n\t\t ['слуга вампир', 'сервамп'],\n\t\t ['проклятие мультивыбора превратило мою жизнь в ад', 'проклятие мультивыбора', 'проклятье мультивыбора превратило мою жизнь в ад', 'проклятье мультивыбора'],\n\t\t ['полулюди', 'получеловек', 'аджин'],\n\t\t ['скучный мир в котором не существует понятия грязные шуточки', 'скучный мир, в котором не существует понятия грязные шуточки', 'скучный мир, в котором не существует самой концепции похабных шуток', 'скучный мир в котором не существует самой идеи похабных шуток', 'трусонюх'],\n\t\t ['повар-боец сома: в поисках божественного рецепта', 'повар боец сома', 'боевой повар сома', 'в поисках божественного рецепта', 'повар-боец сома'],\n\t\t ['возрождающие'],\n\t\t ['притворная любовь'],\n\t\t ['кейджо', 'кэйджо!!!!!!!!', 'кейджо!!!!!!!!', 'кэйджо'],\n\t\t ['баскетбол куроко'],\n\t\t ['живая любовь'],\n\t\t ['эроманга-сенсей', 'эроманга сенсей']]\n\nmat_list = []\n\n#------------------------------------------------------------------------------------------------------------------------------\n# Economics\n#------------------------------------------------------------------------------------------------------------------------------\ndaily_id = []\nnames = []\ncookie = []\n\n\nreport = 0\n\nchannel_list = []\nf = open('channel_list', 'r')\nline1 = f.readline()\nline2 = f.readline()\nc = 0\nwhile line1:\n\tchannel_list.append(line1)\n\tchannel_list.append(line2)\n\tline1 = f.readline()\n\tline2 = str(f.readline())\n\tprint(str((c // 2) + 1) + ')' + channel_list[c][:-1] + ' ' + channel_list[c + 1][:-1])\n\tc = c + 2\nf.close()\n\nprint('------')\n\nf = open('daily', 'r')\nline1 = f.readline()\nc = 0\nwhile line1:\n\tdaily_id.append(line1[:-1])\n\tline1 = f.readline()\n\tprint(str(c + 1) + ')' + daily_id[c])\n\tc = c + 1\nf.close()\n\nf = open('cookie', 'r')\nline1 = f.readline()\nline2 = f.readline()\nwhile line1:\n\tnames.append(line1[:-1])\n\tcookie.append(line2[:-1])\n\tline1 = f.readline()\n\tline2 = f.readline()\nf.close()\n\nf = open('mat', 'r')\nline1 = f.readline()\nwhile line1:\n\tmat_list.append(line1[:-1])\n\tline1 = f.readline()\nprint('mat_list is ready.')\nf.close()\n\nprint('------')\n\nrandom.seed()\n\n\nasync def daily_cookie():\n\tglobal daily_id\n\tawait client.wait_until_ready()\n\twhile not client.is_closed:\n\t\tdaily_id = []\n\t\tf = open('daily', 'w')\n\t\tfor s in daily_id:\n\t\t\tf.write(s + \"\\n\")\n\t\tf.close()\n\t\tprint('---------[command]:daily_cookie')\n\t\tawait asyncio.sleep(3600)\n\nclient.loop.create_task(daily_cookie())\n\n\n@client.event\nasync def on_ready():\n\tprint('Logged in as')\n\tprint(client.user.name)\n\tprint(client.user.id)\n\tprint('------')\n\tawait client.change_presence(game=discord.Game(name='My Code Is Dead'))\n\n@client.event\nasync def on_message(message):\n\n\tprint('<' + message.channel.name+ '>'+ '[' + message.author.name + '|' + message.author.id + ']' + message.content)\n\n\tglobal stops\n\tglobal save_channel\n\tglobal question\n\tglobal quiz_channel\n\tglobal quiz\n\tglobal quiz_number\n\tglobal quiz_numbers\n\tglobal set_answer\n\tglobal quiz_answer\n\tglobal daily_id\n\tglobal mat_list\n\tglobal cookie\n\tglobal names\n\tglobal report\n\n\tif message.content.startswith(prefix + 'btcprice'):\n\t\tprint('---------[command]: btcprice ')\n\t\tf = open('config', 'w')\n\t\tf.write(message.author)\n\t\tf.close()\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]: btcprice\\n```')\n\t\tbtc_price_usd, btc_price_rub = get_btc_price()\n\t\tawait client.send_message(message.channel, 'USD: ' + str(btc_price_usd) + ' | RUB: ' + str(btc_price_rub))\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'login') and message.author.id == '282660110545846272':\n\t\tprint('---------[command]:!login')\n\t\treport = message.author\n\t\tawait client.delete_message(message)\n\n\t#if '<@282660110545846272>' in message.content and message.author.id != '282660110545846272' and message.author.id != '434785638840008738':\n\t# print('---------[command]:mention cookie')\n\t# #await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:mention cookie\\n```')\n\t# await client.send_message(message.channel, 'Хватит ддосить моего Создателя!!!')\n\t# await client.delete_message(message)\n\n\t#if '<@175571075931963393>' in message.content:\n\t# print('---------[command]:mention soya')\n\t# #await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:mention soya\\n```')\n\t# await client.send_message(message.channel, ':sparkles::regional_indicator_s: :regional_indicator_o: :regional_indicator_y: :regional_indicator_a: :regional_indicator_j: :regional_indicator_o: :regional_indicator_n: :regional_indicator_e: :regional_indicator_s::sparkles:')\n\t# #await client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'ddos'):\n\t\tif message.author.id in admin_list:\n\t\t\tprint('---------[command]:!ddos ' + message.content[6:])\n\t\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!ddos ' + message.content[6:] + '\\n```')\n\t\t\ti = 0\n\t\t\tstops = 0\n\t\t\twhile i < 30:\n\t\t\t\ti = i + 1\n\t\t\t\tif(stops == 1):\n\t\t\t\t\tbreak\n\t\t\t\tawait client.send_message(message.channel, message.content[6:])\n\t\t\t\ttime.sleep(0.5)\n\t\t\tstops = 0\n\t\tawait client.delete_message(message)\n\n\tif (strcmp(message.content, prefix + 'stop') == 1):\n\t\tprint('---------[command]:!stop')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!stop\\n```')\n\t\tstops = 1\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content.lower(), 'печенюха') or strcmp(message.content.lower(), 'печенька'):\n\t\tprint('---------[command]:!cookie')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!cookie\\n```')\n\t\tawait client.send_message(message.channel, \"О, я тоже хочу, поделитесь?:cookie:\")\n\n\tif strcmp(message.content, prefix + 'hi'):\n\t\tprint('---------[command]:!hi')\n\t #await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!hi')\n\t\tawait client.send_message(message.channel, ':sparkles:' + message.author.name + ' приветствует всех:sparkles:\\n')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'pic'):\n\t\tprint('---------[command]:!pic')\n\t\tawait client.send_message(message.channel, 'Держи арт!')\n\t\tawait client.send_file(message.channel, 'pic/konachan.jpg')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'gm'):\n\t\tprint('---------[command]:!gm')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!gm\\n```')\n\t\tawait client.send_message(message.channel, ':hugging:С добрым утречком:hugging:')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'help'):\n\t\tprint('---------[command]:!help')\n\t\tawait client.send_message(message.channel, '```css\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '[Pineapple Cookie help]\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'daily - Получить часовую порцию печенюх.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'cookie / ' + prefix +'me - Узнать свой баланс печенюх.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'roll <ставка> - Поставить печенюхи на рулетке.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'give <кому> <сколько> - Поделиться печенюхами с другом.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'rang - Посмотреть на обжор.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Печенюха/печенька - Попросит вкуснях. Это две команды. Буквы могут быть любого размера.\\nПишется без префикса.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Меншн Сони выдаст интересный набор смайликов))). Но не стоит слишком часто юзать эту функцию.\\nГрозит перманентным баном по айди на доступ к этой команде.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'say <текст> - Напишет ваше сообщение.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'hi - Поприветствует всех от вашего имени.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'gm - Охайё, т.е доброе утро)).\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'help - Вызов этой справки.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'report <текст> - Отправить сообщение разработчику. Баги, пожелания, предложения руки и сердца кидать сюда-ня.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '```')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'oldhelp') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!oldhelp')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!help\\n```')\n\t\tawait client.send_message(message.channel, '```css\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '[cookie help]\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Печенюха/печенька - Попросит вкуснях. Это две команды. Буквы могут быть любого размера.\\nПишется без префикса.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Меншн Сони выдаст интересный набор смайликов))). Но не стоит слишком часто юзать эту функцию.\\nГрозит перманентным баном по айди на доступ к этой команде.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'say <текст> - Напишет ваше сообщение.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'hi - Поприветствует всех от вашего имени.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'gm - Охайё, т.е доброе утро)).\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'help - Вызов этой справки.' +\n\t\t\t\t\t\t\t\t\t\t\t\t '```')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'save') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!save')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!save```')\n\t\tsave_channel = message.channel\n\t\tf = open('channel_list', 'a')\n\t\tf.write(save_channel.name + '\\n' + save_channel.id)\n\t\tf.close\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'say '):\n\t\tprint('---------[command]:!say')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!say```')\n\t\tawait client.send_message(message.channel, message.content[5:])\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'report '):\n\t\tprint('---------[command]:!report')\n\t\tawait client.send_message(report, '<' + message.author.name + '|' + message.author.id+ '>'+ ' ' + message.content[8:])\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'sayhim') and message.author.id in admin_list:\n\t\tprint('---------[command]:!sayhim')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!sayhim```')\n\t\tawait client.send_message(client.get_channel(channel_list[int(message.content[8]) * 2 - 1][:-1]), message.content[10:])\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'start quiz') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!start quiz')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!start quiz\\n```')\n\t\tquiz_channel = message.channel\n\t\tquiz = 1\n\t\tawait client.send_message(message.channel, 'Викторина началась!')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'stop quiz') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!stop quiz')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!stop quiz\\n```')\n\t\tquiz_channel = 0\n\t\tquiz = 0\n\t\tawait client.send_message(message.channel, 'Викторина окончена))\\n\\nОгромное спасибо спонсорам сегодняшней викторины - Rumata и <@265474107666202634>')\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'quiz ') and message.author.id in admin_list and quiz == 1 and message.channel != quiz_channel:\n\t\tquiz_number = int(message.content[6:]) - 1\n\t\tquiz_numbers = quiz_number\n\t\tprint('---------[command]:!quiz ' + str(quiz_number))\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quiz ' + str(quiz_number) + '\\n```')\n\t\tawait client.send_message(quiz_channel, question[quiz_number])\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'quizans') and message.author.id in admin_list:\n\t\tprint('---------[command]:!quizans ' + message.content[9:])\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quizans ' + message.content[9:] + '\\n```')\n\t\tif quiz_number == -1:\n\t\t\tawait client.send_message(quiz_channel, 'А что же произошло? Грац, вы нашли недоработку с нашей стороны, а раз так, то победил челик ниже:')\n\t\tset_answer[quiz_numbers] = str(quiz_numbers + 1) + ')' + message.content[9:]\n\t\tawait client.send_message(quiz_channel, message.content[9:] + ', верно!')\n\t\tawait client.delete_message(message)\n\n\tif message.channel == quiz_channel and quiz:\n\t\tprint('---------[command]:!quiz answer - ' + message.content)\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quiz answer - ' + message.content + '\\n```')\n\t\tif quiz_number != -1:\n\t\t\tif message.content.lower() in quiz_answer[quiz_number]:\n\t\t\t\tif quiz_number != -1:\n\t\t\t\t\tquiz_number = -1\n\t\t\t\t\tset_answer[quiz_number] = str(quiz_number + 1) + ')' + message.author.id + ' ' + message.author.name\n\t\t\t\t\tawait client.send_message(quiz_channel, '<@' + message.author.id+ '>'+ ', верно!')\n\n\tif strcmp(message.content, prefix + 'quizstat') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!quiz stat')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quiz stat\\n```')\n\t\tret = '```css'\n\t\tfor s in set_answer:\n\t\t\tret = ret + '\\n' + s\n\t\tret = ret + '\\n```'\n\t\tawait client.send_message(message.channel, ret)\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'quizquestions') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!quizquestions')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quizquestions\\n```')\n\t\tret = '```css'\n\t\tfor s in question:\n\t\t\tret = ret + '\\n' + s\n\t\tret = ret + '\\n```'\n\t\tawait client.send_message(message.channel, ret)\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'quizanswers') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!quizanswers')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quizanswers\\n```')\n\t\tret = '```css'\n\t\tfor s in quiz_answer:\n\t\t\tret = ret + '\\n' + s\n\t\tret = ret + '\\n```'\n\t\tawait client.send_message(message.channel, ret)\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content.lower(), 'соня'):\n\t\tprint('---------[command]:!sonya')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!sonya\\n```')\n\t\tawait client.send_message(message.channel, 'Соня лучшая!!!')\n\t\tawait client.delete_message(message)\n\n\n\tif message.content.lower() in mat_list:\n\t\tprint('---------[command]:!sukablyat')\n\t\tawait client.send_message(message.author, 'Не матерись, пожалуйста)) ')\n\t\tawait client.delete_message(message)\n\n\n#------------------------------------------------------------------------------------------------------------------------------\n# Economics\n#------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'daily reset') == 1 and message.author.id in admin_list and message.channel.id in admin_channel_list:\n\t\tprint('---------[command]:!daily reset')\n\t\tdaily_id = []\n\t\tf = open('daily', 'w')\n\t\tfor s in daily_id:\n\t\t\tf.write(s + \"\\n\")\n\t\tf.close()\n\t\tawait client.send_message(message.channel, 'Ежедневка сброшена.')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'daily'):\n\t\tprint('---------[command]:!daily')\n\t\tif message.author.id in daily_id:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ ', вы уже получили печенюхи)')\n\t\telse:\n\t\t\tdaily_id.append(str(message.author.id))\n\t\t\tf = open('daily', 'w')\n\t\t\tc = 0\n\t\t\tfor s in daily_id:\n\t\t\t\tf.write(s + \"\\n\")\n\t\t\t\tc = c + 1\n\t\t\tf.close()\n\t\t\tcookie_count = 100\n\t\t\tif message.author.id in names:\n\t\t\t\tc = 0\n\t\t\t\twhile(names[c] != message.author.id):\n\t\t\t\t\tc = c + 1\n\t\t\t\tcookie[c] = str(int(cookie[c]) + cookie_count)\n\t\t\t\tf = open('cookie', 'w')\n\t\t\t\tc = 0\n\t\t\t\tfor s in cookie:\n\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\tc = c + 1\n\t\t\t\tf.close()\n\t\t\telse:\n\t\t\t\tnames.append(message.author.id)\n\t\t\t\tcookie.append(str(cookie_count))\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', держи ' + str(cookie_count) + ':cookie:!')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif (strcmp(message.content.lower(), prefix + 'cookie') == 1 or strcmp(message.content.lower(), prefix + 'me') == 1):\n\t\tprint('---------[command]:!cookie')\n\t\tif message.author.id in names:\n\t\t\tc = 0\n\t\t\twhile(names[c] != message.author.id):\n\t\t\t\tc = c + 1\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя ' + cookie[c] + ':cookie:!')\n\t\telse:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя нет:cookie: :(')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif message.content.startswith(prefix + 'roll '):\n\t\tprint('---------[command]:!roll')\n\t\tif not message.content[6:].isdigit():\n\t\t\tawait client.send_message(message.channel, '```css\\nError!!! Введенное значение не является числом\\nExample: ' + prefix + 'roll 20\\n```')\n\t\telif message.author.id in names:\n\t\t\tc = 0\n\t\t\twhile(names[c] != message.author.id):\n\t\t\t\tc = c + 1\n\t\t\tif (int(message.content[6:]) > int(cookie[c])):\n\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя нет столько:cookie: :(')\n\t\t\telse:\n\t\t\t\tif (random.randint(0, 100) + 7) > 50:\n\t\t\t\t#if (random.random() == 1):\n\t\t\t\t\tcookie[c] = str(int(cookie[c]) + int(message.content[6:]))\n\t\t\t\t\tf = open('cookie', 'w')\n\t\t\t\t\tc = 0\n\t\t\t\t\tfor s in cookie:\n\t\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\t\tc = c + 1\n\t\t\t\t\tf.close()\n\t\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, ты выиграл ' + str(int(message.content[6:])) + ':cookie:')\n\t\t\t\telse:\n\t\t\t\t\tcookie[c] = str(int(cookie[c]) - int(message.content[6:]))\n\t\t\t\t\tf = open('cookie', 'w')\n\t\t\t\t\tc = 0\n\t\t\t\t\tfor s in cookie:\n\t\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\t\tc = c + 1\n\t\t\t\t\tf.close()\n\t\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, ты проиграл ' + (message.content[6:]) + ':cookie:')\n\t\telse:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, у тебя нет:cookie: :(')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'cookie update'):\n\t\tprint('---------[command]:!cookie update')\n\t\tf = open('cookie', 'r')\n\t\tnames = []\n\t\tcookie = []\n\t\tline1 = f.readline()\n\t\tline2 = f.readline()\n\t\tc = 0\n\t\twhile line1:\n\t\t\tnames.append(line1[:-1])\n\t\t\tcookie.append(line2[:-1])\n\t\t\tline1 = f.readline()\n\t\t\tline2 = f.readline()\n\t\tf.close()\n\t\tawait client.send_message(message.channel, 'Обновлено из файла.')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif message.content.startswith(prefix + 'give '):\n\t\tprint('---------[command]:!give')\n\t\tparams = message.content.lower().split(' ')\n\t\tif not message.author.id in names:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя нет:cookie: :(')\n\t\telif params[1][2:-1] in names:\n\t\t\tc = 0\n\t\t\twhile(names[c] != params[1][2:-1]):\n\t\t\t\tc = c + 1\n\t\t\tk = 0\n\t\t\twhile(names[k] != message.author.id):\n\t\t\t\tk = k + 1\n\t\t\tif not params[2].isdigit():\n\t\t\t\tawait client.send_message(message.channel, '```css\\nError!!! Введенное значение не является числом\\nExample: ' + prefix + 'give 500\\n```')\n\t\t\telif (int(params[2]) > int(cookie[k])):\n\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, у тебя нет столько:cookie: :(')\n\t\t\telse:\n\t\t\t\tcookie[c] = str(int(cookie[c]) + int(params[2]))\n\t\t\t\tcookie[k] = str(int(cookie[k]) - int(params[2]))\n\t\t\t\tf = open('cookie', 'w')\n\t\t\t\tc = 0\n\t\t\t\tfor s in cookie:\n\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\tc = c + 1\n\t\t\t\tf.close()\n\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, подарил ' + params[1] + ' ' + params[2] + ':cookie:')\n\t\telse:\n\t\t\tawait client.send_message(message.channel, 'Нет такого пользователя :(')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'rang'):\n\t\tprint('---------[command]:!rang')\n\t\tnam = names\n\t\tcoo = cookie\n\t\tc = 0\n\t\tp = 0\n\t\tret = 'Leaderboards:\\n'\t\n\t\twhile c < 10:\n\t\t\tif len(nam) > 0:\n\t\t\t\tp = max(cookie)\n\t\t\t\tret = ret + str(c + 1) + ') <@' + nam.pop(p) + '> - ' + coo.pop(p) + ':cookie:\\n'\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\tc = c + 1\n\t\tem = discord.Embed(description=ret, colour=0xC5934B)\n\t\tawait client.send_message(message.channel, embed=em)\n\t\tawait client.delete_message(message)\n\n\n\tif strcmp(message.content.lower(), prefix + 'embed'):\n\t\tem = discord.Embed(title='Крутим пальчиками.', colour=0xC5934B)\n\t\tem.set_image(url='http://i0.kym-cdn.com/photos/images/original/000/448/492/bfa.gif')\n\t\tawait client.send_message(message.channel, embed=em)\n\t\tawait client.delete_message(message)\n\n\n\n#if message.content.lower() in mat_list:\n# print('Удаляю мат!')\n# await client.send_message(message.channel, 'Извени но я вырезала твой мат \\nhttps://iichan.hk/a/arch/src/1331445120492.gif%27')\n# msg = await client.send_message(message.author, 'Не матерись, пожалуста)) ')\n# await client.edit_message(msg,'Извени но я вырезала твой мат')\n\n\ndef max(list):\n maximum = 0\n p = 0\n for s in range(len(list)):\n if int(list[s]) > maximum:\n maximum = int(list[s])\n p = s\n return p\n\n\ndef strcmp(s1, s2):\n\ti1 = 0\n\ti2 = 0\n\ts1 = s1 + '\\0'\n\ts2 = s2 + '\\0'\n\twhile ((s1[i1] != '\\0') & (s2[i2] != '\\0')):\n\t\tif(s1[i1] != s2[i2]):\n\t\t\treturn 0\n\t\ti1 = i1 + 1\n\t\ti2 = i2 + 1\n\tif(s1[i1] != s2[i2]):\n\t\treturn 0\n\telse:\n\t\treturn 1\n\n\ndef get_btc_price():\n\tr = requests.get(BTC_PRICE_URL_coinmarketcap)\n\tresponse_json = r.json()\n\tusd_price = response_json[0]['price_usd']\n\trub_rpice = response_json[0]['price_rub']\n\treturn usd_price, rub_rpice\n\nclient.run(DISCORD_BOT_TOKEN)\n","sub_path":"Pineapple_Cookie/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":29335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"190758472","text":"from ordenacoes.lista_gen.ListGen import ListGen\n\nif __name__ == '__main__':\n lg = ListGen()\n\n str = \"[aa, [bb,cc], [dd,[ee], ff,gg], hh]\"\n\n lg.insertStr(str)\n lg.showString()\n\n\n\"\"\"\n[aa, [bb,cc], [dd,[ee], ff,gg], hh]\n[aa, [bb,cc], hh]\n[aa, [bb]]\n[[dd, [ee],ff, []], [hh]]\n[aa, [[bb]], [[[dd,lll]]]]\n[aaaaaaaaaaaaa,ccccccccccccc,[a],[dd,[dd],[aa]]]\n[[[[cc]]]]\n[[[]]]\n\n\"\"\"","sub_path":"ordenacoes/lista_gen/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"581387236","text":"# Ref: https://jakevdp.github.io/PythonDataScienceHandbook/04.04-density-and-contour-plots.html\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nProblem1='capacitor'\nProblem2='mirror_charge'\nProblem3='charge_plate'\n\nFile1=Problem1+\".dat\"\nFile2=Problem2+\".dat\"\nFile3=Problem3+\".dat\"\n\nX1,Y1,Charge1,P1 = np.loadtxt(File1, unpack=True)\nX2,Y2,Charge2,P2 = np.loadtxt(File2, unpack=True)\nX3,Y3,Charge3,P3 = np.loadtxt(File3, unpack=True)\n\nX1 = X1.reshape(128,128)\nY1 = Y1.reshape(128,128)\nP1 = P1.reshape(128,128)\n\nX2 = X2.reshape(128,128)\nY2 = Y2.reshape(128,128)\nP2 = P2.reshape(128,128)\n\nX3 = X3.reshape(128,128)\nY3 = Y3.reshape(128,128)\nP3 = P3.reshape(128,128)\n\n\nx1 = X1[0::5,0::5]\ny1 = Y1[0::5,0::5]\nx2 = X2[0::5,0::5]\ny2 = Y2[0::5,0::5]\nx3 = X3[0::5,0::5]\ny3 = Y3[0::5,0::5]\n\n\n\n# Plots direction of the electrical vector field\ndX1, dY1 = np.gradient( P1 )\ndX2, dY2 = np.gradient( P2 )\ndX3, dY3 = np.gradient( P3 )\n\nfig,ax=plt.subplots(3,2, figsize=(12,18))\n\n\n\ndx1 = dX1[0::5,0::5]\ndy1 = dY1[0::5,0::5]\ndx2 = dX2[0::5,0::5]\ndy2 = dY2[0::5,0::5]\ndx3 = dX3[0::5,0::5]\ndy3 = dY3[0::5,0::5]\n\n\n#ax[0][0].quiver(x1, y1, dx1, dy1, color='r', zorder=1, width=0.007, headwidth=3., headlength=4., units='x')\nax[0][0].quiver(x1, y1, dx1, dy1, color='r')\nax[0][1].contourf(X1, Y1, P1, 100, cmap='RdGy')\n\nax[0][0].set_title(Problem1+\": E lines\")\nax[0][1].set_title(Problem1+\": potential\")\n\nax[0][0].set_xlim(0.0,1.0)\nax[0][0].set_ylim(0.0,1.0)\nax[0][1].set_xlim(0.0,1.0)\nax[0][1].set_ylim(0.0,1.0)\n\n#ax[1][0].quiver(x2, y2, dx2, dy2, color='r', zorder=1, width=0.007, headwidth=3., headlength=4., units='x')\nax[1][0].quiver(x2, y2, dx2, dy2, color='r')\nax[1][1].contourf(X2, Y2, P2, 100, cmap='RdGy')\n\nax[1][0].set_title(Problem2+\": E lines\")\nax[1][1].set_title(Problem2+\": potential\")\n\nax[1][0].set_xlim(0.0,1.0)\nax[1][0].set_ylim(0.0,1.0)\nax[1][1].set_xlim(0.0,1.0)\nax[1][1].set_ylim(0.0,1.0)\n\n\n#ax[2][0].quiver(x3, y3, dx3, dy3, color='r', units='xy', zorder=1, width=0.007, headwidth=3., headlength=4.)\nax[2][0].quiver(x3, y3, dx3, dy3, color='r')\nax[2][1].contourf(X3, Y3, P3, 100, cmap='RdGy')\n\nax[2][0].set_title(Problem3+\": E lines\")\nax[2][1].set_title(Problem3+\": potential\")\n\nax[2][0].set_xlim(0.0,1.0)\nax[2][0].set_ylim(0.0,1.0)\nax[2][1].set_xlim(0.0,1.0)\nax[2][1].set_ylim(0.0,1.0)\n\n\n\n#plt.show()\nplt.savefig('fff.png')\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"571201791","text":"from abc import ABC\nimport pandas as pd\nfrom .base import BaseFactor\nfrom collections import defaultdict\nfrom ccbacktest.utils.pandas_utils import concat_dataframes, concat_series, add_parent_level\n\n\nclass Factor(BaseFactor, ABC):\n \"\"\"\n Base class for all factors, it supports arithmetic operations with a scaler or another factor, creating\n a Lambda Factor (a class to represent factors created from a function)\n \"\"\"\n\n def __init__(self):\n self.name = None\n self._history = None\n self._periods = None\n\n def rename(self, name):\n \"\"\"\n Rename the factor to another name\n :arg name: the new name for the factor\"\"\"\n # TODO : raise Exception when the factor has already been applied to a dataset (renaming it would\n # result in creating two different pandas columns with different names)\n self.name = name\n return self\n\n @property\n def history(self) -> dict:\n \"\"\"\n :return: return the relevant history for the factor in order for it to compute futur values of the factor,\n it's sentinel value is None\n \"\"\"\n if not hasattr(self, '_history'):\n self._history = None\n return self._history\n\n @history.setter\n def history(self, d):\n self._history = d\n\n @property\n def periods(self):\n \"\"\" returns the number of periods necessary to compute next value\n \"\"\"\n return self._periods\n\n @periods.setter\n def periods(self, value):\n self._periods = value\n\n def update_history(self, series, new_value):\n \"\"\" Update the history when a new value is computed,\n :arg series: the new observation (ohlcv current value if ohlcv is used)\n :arg new_value: new computed factor value\n \"\"\"\n\n self.history['data_history'] = self.history['data_history'].append(series).iloc[1:]\n self.history['factor_history'] = self.history['factor_history'].append(new_value).iloc[1:]\n\n def apply(self, df: pd.DataFrame) -> pd.DataFrame:\n \"\"\" apply the factor to a historical dataset at once\n :arg df: historical data to which we apply the factor\n :return factor values for each timestamp\n \"\"\"\n\n values = self.func(df)\n if self.periods is not None:\n self.history = {\"data_history\": df.iloc[-self.periods:],\n 'factor_history': values.iloc[-self.periods:]}\n if not isinstance(values, pd.DataFrame):\n values = values.rename(self.name).to_frame()\n return values\n\n def step(self, series: pd.Series) -> pd.Series:\n \"\"\" compute the factor value for the next timestamp\n :arg series: new observation\n :return computed factor value for the observation\n \"\"\"\n\n df = self.history['data_history']\n updated = df.append(series)\n value = self.func(updated).iat[-1]\n to_return = pd.Series([value], name=series.name, index=[self.name])\n self.update_history(series, to_return)\n return series\n\n def __add__(self, other):\n if isinstance(other, Factor):\n # compute a default name for the su factor\n name = f'({self.name} + {other.name})'\n # the necessary history is the max of both histories\n # TODO: raise exception if the two factors have different timeframes\n periods = max(self.periods, other.periods)\n\n def func(df):\n return self.func(df) + other.func(df)\n\n return LambdaFactor(func, name, periods)\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} + {other})\"\n periods = self.periods\n\n def func(df):\n return other + self.func(df)\n\n return LambdaFactor(func, name, periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __radd__(self, other):\n if isinstance(other, Factor):\n return other.__add__(self)\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({other} + {self.name})\"\n\n def func(df):\n return other + self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __sub__(self, other):\n if isinstance(other, Factor):\n name = f'({self.name} - {other.name})'\n periods = max(self.periods, other.periods)\n\n def func(df):\n return self.func(df) - other.func(df)\n\n return LambdaFactor(func, name, periods)\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} - {other})\"\n\n def func(df):\n return self.func(df) - other\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __rsub__(self, other):\n\n if isinstance(other, int) or isinstance(other, float):\n name = f\"({other} - {self.name})\"\n\n def func(df):\n return other - self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __mul__(self, other):\n if isinstance(other, Factor):\n name = f'({self.name} x {other.name})'\n\n def func(df):\n return self.func(df) * other.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} x {other})\"\n\n def func(df):\n return other * self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __rmul__(self, other):\n if isinstance(other, Factor):\n name = f'({other.name} x {self.name})'\n\n def func(df):\n return self.func(df) * other.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({other} + {self.name})\"\n\n def func(df):\n return other * self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __truediv__(self, other):\n if isinstance(other, Factor):\n name = f'({self.name} / {other.name})'\n\n def func(df):\n return self.func(df) / other.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} / {other})\"\n\n def func(df):\n return self.func(df) / other\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __rtruediv__(self, other):\n if isinstance(other, Factor):\n name = f'({other.name} / {self.name})'\n\n def func(df):\n return other.func(df) / self.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({other} / {self.name})\"\n\n def func(df):\n return other / self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n\nclass LambdaFactor(Factor):\n __slots__ = ['name', '_func']\n \"\"\" A class used to create a factor from a function, a history depth and a name, the \n rest of the factor operation is inherited from the Factor class, it's used mainly to create arithmetic operations\n between other factors. \n \"\"\"\n def __init__(self, func, name, periods):\n super(Factor, self).__init__()\n self.name = name\n self._func = func\n self.periods = periods\n\n def func(self, df):\n return self._func(df)\n\n\nclass MovingAverage(Factor):\n __slots__ = ['periods', '_on', 'name', '_history']\n \"\"\" Moving averge on price data\n \"\"\"\n def __init__(self, periods, on=\"close\"):\n assert isinstance(periods, int), \"Periods parameter should be an integer\"\n assert (on in ['close', 'open']), 'Only open and close are supported'\n super(Factor, self).__init__()\n self.periods = periods\n self._on = on\n self._history = None\n self.name = f'MA_{self.periods}'\n\n def func(self, df):\n return df.rolling(self.periods)[self._on].mean()\n\n def step(self, series: pd.Series):\n df = self.history['data_history']\n factor = self.history['factor_history']\n s = factor.iat[-1]\n r = df[self._on].iat[-self.periods]\n value = (self.periods * s - r + series[self._on]) / self.periods\n to_return = pd.Series([value], index=[self.name], name=series.name)\n self.update_history(series, to_return)\n return to_return\n\n\nclass RelativeStrengthIndex(Factor):\n def __init__(self, periods=14):\n self.periods = periods\n self.name = f'RSI_{periods}'\n super(Factor, self).__init__()\n\n def func(self, df):\n if df.shape[0] <= self.periods:\n raise TooSmallHistoryError('History data frame is too small to compute the moving average with '\n f'{self.periods} periods, on {df.shape[0]} time steps')\n diff = df.close - df.open\n pos = diff >= 0\n pos_mean = diff.where(pos, 0).rolling(self.periods).mean()\n neg_mean = -diff.where(~pos, 0).rolling(self.periods).mean()\n factor = (100 - (100 / (1 + (pos_mean / neg_mean)).abs()))\n return factor\n\n\nclass VolumeWeightedAveragePrice(Factor):\n def __init__(self, periods):\n super(Factor, self).__init__()\n self.periods = periods\n self.name = f'VWAP_{self.periods}'\n\n def func(self, df: pd.DataFrame) -> pd.Series:\n product = df['open'] * df['volume']\n product_sum = product.rolling(self.periods).sum()\n vol_sum = df['volume'].rolling(self.periods).sum()\n return product_sum / vol_sum\n\n\nclass MovingAverageConvergenceDivergence(Factor):\n def __init__(self, fast_period, slow_period, on='close'):\n self.fast_period = fast_period\n self.slow_period = slow_period\n self.periods = self.slow_period\n self._on = on\n self.name = f'MACD_{fast_period}_{slow_period}'\n\n def func(self, df):\n fast_series = df.rolling(self.fast_period)[self._on].mean().rename('fast')\n slow_series = df.rolling(self.slow_period)[self._on].mean().rename('slow')\n return_df = pd.concat([fast_series, slow_series], axis=1)\n return_df.columns = pd.MultiIndex.from_product([[self.name], return_df.columns])\n return return_df\n\n def step(self, series: pd.Series) -> pd.Series:\n df = self.history['data_history']\n updated = df.append(series)\n value = self.func(updated).iloc[-1, :]\n self.update_history(series, value)\n return value\n\n def update_history(self, series, new_value):\n self.history['data_history'] = self.history['data_history'].append(series).iloc[1:]\n self.history['factor_history'] = self.history['factor_history'].append(new_value).iloc[1:]\n\n\nMACD = MovingAverageConvergenceDivergence\nMA = MovingAverage\nRSI = RelativeStrengthIndex\nVWAP = VolumeWeightedAveragePrice\n\n\nclass TooSmallHistoryError(Exception):\n pass\n","sub_path":"build/lib/ccbacktest/factors/factors.py","file_name":"factors.py","file_ext":"py","file_size_in_byte":11780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"404702767","text":"#\n# @lc app=leetcode id=92 lang=python3\n#\n# [92] Reverse Linked List II\n#\n# https://leetcode.com/problems/reverse-linked-list-ii/description/\n#\n# algorithms\n# Medium (37.74%)\n# Total Accepted: 253.8K\n# Total Submissions: 671.8K\n# Testcase Example: '[1,2,3,4,5]\\n2\\n4'\n#\n# Reverse a linked list from position m to n. Do it in one-pass.\n# \n# Note: 1 ≤ m ≤ n ≤ length of list.\n# \n# Example:\n# \n# \n# Input: 1->2->3->4->5->NULL, m = 2, n = 4\n# Output: 1->4->3->2->5->NULL\n# \n# \n#\n# Definition for singly-linked list.\n\n\nclass ListNode:\n # https://zhuanlan.zhihu.com/p/86745433?utm_source=\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def __init__(self):\n self.successor = None\n\n def reverseN(self, head, n):\n \"\"\"\n 反转链表的前n个节点\n \"\"\"\n if n == 1:\n self.successor = head.next\n return head\n\n last = head.next\n new_head = self.reverseN(head.next, n - 1)\n last.next = head\n head.next = self.successor\n\n return new_head\n\n def reverseBetween(self, head, m, n):\n \"\"\"\n 递归,代码简洁\n 时间复杂度:o(n)\n 空间复杂度:o(n)\n \"\"\"\n if m == 1:\n return self.reverseN(head, n)\n head.next = self.reverseBetween(head.next, m - 1, n - 1)\n return head\n\n # def reverseBetween(self, head, m, n):\n # dummy = ListNode(-1)\n # dummy.next = head\n # pre = dummy\n # # 找到翻转链表部分的前一个节点, 1->2->3->4->5->NULL, m = 2, n = 4 指的是 节点值为1\n # for _ in range(m - 1):\n # pre = pre.next\n # # 用双指针,进行链表翻转(原地翻转)\n # node = None # 翻转后链表的表头\n # cur = pre.next # 链表前进的指针\n # for _ in range(n - m + 1):\n # tmp = cur.next # 把下一个结点先保存起来\n # cur.next = node\n # node = cur\n # cur = tmp # cur指针继续前进\n # # 将翻转部分 和 原链表拼接\n # pre.next.next = cur\n # pre.next = node\n # return dummy.next\n\n\nif __name__ == '__main__':\n head = ListNode(None) # head指针指向链表表头\n pos = head\n for i in [1, 2, 3, 4, 5, 6]:\n node = ListNode(i)\n pos.next = node # 链表插入结点\n pos = pos.next # pos指针向前移动\n\n s = Solution()\n result = s.reverseBetween(head.next, 2, 4)\n while result:\n print(result.val)\n result = result.next\n","sub_path":"linked_list/recursively/92.reverse-linked-list-ii.py","file_name":"92.reverse-linked-list-ii.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"268080786","text":"import numpy as np\n\nclass DecisionTree:\n\n def __init__(self, labels, mode, prune_thr):\n np.set_printoptions(threshold = np.inf, suppress = True)\n self.class_labels = np.unique(labels)\n self.num_labels = len(self.class_labels)\n self.mode = mode\n self.prune_thr = prune_thr\n\n\n # Nodes used for the tree returned\n class TreeNode:\n # attr is the index of a row in data\n # thresh is the value to split on\n # less than goes left\n # greater than or equal to goes right\n def __init__(self, attr, thresh, node_id, gain = 0.0, dist = None):\n self.id = node_id\n self.attr = attr\n self.thresh = thresh\n self.distr = dist\n self.gain = gain\n self.left = None\n self.right = None\n\n #\n # end TreeNode class\n #\n\n # default is a distribution over the labels\n # returns a TreeNode\n def dtl(self, ex, labels, default, node_id) -> TreeNode:\n if len(ex) < self.prune_thr:\n newNode = self.TreeNode(-1, -1, node_id, dist = default)\n return newNode\n\n if len(np.unique(labels)) == 1:\n dist = self.distribution(labels)\n newNode = self.TreeNode(-1, -1, node_id, dist = dist)\n return newNode\n\n if self.mode == 'optimized':\n thresh, attr, gain = self.choose_optimized(ex, labels)\n else:\n thresh, attr, gain = self.choose_random(ex, labels)\n\n root = self.TreeNode(attr, thresh, node_id, gain = gain)\n\n left_cond = np.where(ex[:,attr] < thresh)\n right_cond = np.where(ex[:,attr] >= thresh)\n\n new_default = self.distribution(labels)\n\n root.left = self.dtl(ex[left_cond], labels[left_cond], new_default, 2 * node_id)\n root.right = self.dtl(ex[right_cond], labels[right_cond], new_default, 2 * node_id + 1)\n \n return root\n\n\n def choose_random(self, ex, labels):\n max_gain = -1\n best_thresh = -1\n\n random_attr = np.random.randint(len(ex[0]))\n l = np.amin(ex[:,random_attr])\n m = np.amax(ex[:,random_attr])\n for i in range(1, 51):\n thresh = l + i * (m - l) / 51\n gain = self.information_gain(ex, labels, random_attr, thresh)\n\n if gain > max_gain:\n max_gain = gain\n best_thresh = thresh\n\n return best_thresh, random_attr, max_gain\n\n\n def choose_optimized(self, ex, labels):\n max_gain = -1\n best_attr = -1\n best_thresh = -1\n\n for i in range(0, len(ex[0])):\n l = np.amin(ex[:,i])\n m = np.amax(ex[:,i])\n \n for k in range(1, 51):\n thresh = l + k * (m - l) / 51\n gain = self.information_gain(ex, labels, i, thresh)\n \n if gain > max_gain:\n max_gain = gain\n best_thresh = thresh\n best_attr = i\n\n return best_thresh, best_attr, max_gain\n\n\n # attr is an index of the attribute \n def information_gain(self, ex, labels, attr, thresh):\n parent_entropy = self.entropy(labels)\n\n left_labels = labels[np.where(ex[:,attr] < thresh)]\n right_labels = labels[np.where(ex[:,attr] >= thresh)]\n left_entropy = self.entropy(left_labels)\n right_entropy = self.entropy(right_labels)\n\n info_gain = parent_entropy - (\n len(left_labels) * left_entropy / len(labels) +\n len(right_labels) * right_entropy / len(labels)\n )\n return info_gain\n\n\n def entropy(self, labels):\n k = len(labels)\n uniq, counts = np.unique(labels, return_counts = True)\n interim = np.multiply(np.divide(counts, k), np.log2(np.divide(counts, k)))\n entropy = np.negative(np.sum(interim))\n return entropy\n\n\n def distribution(self, labels):\n k = len(labels)\n uniq, counts = np.unique(labels, return_counts = True)\n distr = np.zeros(self.num_labels)\n for i in range(0, len(uniq)):\n index = np.argwhere(self.class_labels == uniq[i])\n distr[index] = counts[i]\n \n return np.divide(distr, k)\n\n\n def test(self, tree, test_data):\n while tree.attr != -1:\n if test_data[tree.attr] < tree.thresh:\n tree = tree.left\n else:\n tree = tree.right\n return tree.distr\n","sub_path":"fall2018/4309/hw4/dectree.py","file_name":"dectree.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"378064004","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n# from skimage import data\n# from skimage.morphology import skeletonize, thin\n# from skimage.util import invert \nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef find_color(img,x,y):\n\treturn img[y,x]\n\ndef find_gradient(img,x,y):\n\treturn 255 - img[y,x]\n\ndef remove_duplicates(x):\n return list(dict.fromkeys(x))\n\ndef find_middle(x1, y1, x2, y2):\n\tif x1 >= x2:\n\t\tmax_x = x1\n\t\tmin_x = x2\n\telse:\n\t\tmax_x = x2\n\t\tmin_x = x1\n\n\tif y1 >= y2:\n\t\tmax_y = y1\n\t\tmin_y = y2\n\telse:\n\t\tmax_y = y2\n\t\tmin_y = y1\n\txx = int(min_x + ((max_x-min_x)/2))\n\tyy = int(min_y + ((max_y-min_y)/2))\n\treturn (xx,yy)\n\ndef top_to_bot(list_is):\n ans = list_is[1:len(list_is)]\n ans.append(list_is[0])\n return ans\n\t\ndef find_num_point(x1,y1,x2,y2):\n if abs( x1 - x2 ) >= abs( y1 - y2 ):\n return int(abs( x1 - x2 ))\n else:\n return int(abs( y1 - y2 ))\n\ndef sampling(x1,y1,x2,y2):\n dx = x2-x1\n dy = y2-y1\n if abs( x1 - x2 ) >= abs( y1 - y2 ):\n n = int(abs( x1 - x2 ) /2)\n else:\n n = int(abs( y1 - y2 ) /2)\n dxn = dx/n\n dyn = dy/n \n output = []\n for i in range(n):\n output.append((int(x1+(i*dxn)),int(y1+(i*dyn))))\n return output\n\nimage = cv2.imread(r'C:\\Users\\aminb\\Desktop\\FIBO\\Image\\Moduel_image\\test_field.jpg')\nimage1 = cv2.imread(r'C:\\Users\\aminb\\Desktop\\FIBO\\Image\\Moduel_image\\test_field.jpg')\npop = image.copy()\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nblur = cv2.GaussianBlur(gray, (5,5), 0)\n# blur = cv2.GaussianBlur(gray, (101,101), -10)\n# blur = cv2.threshold(blur1,0,255,cv2.THRESH_BINARY)\n# highboost = cv2.subtract(blur,gray)\n# cv2.imshow(\"Contour\", highboost)\n# cv2.waitKey(0)\n# black_image = np.zeros((738, 778, 1),np.uint8)\n# black_image = np.zeros((image1.shape[0], image1.shape[1], 1), np.uint8)\n\n# Find Canny edges \nedge = cv2.Canny(blur,40,100) \n\n# bi = cv2.cvtColor(edge,cv2.THRESH_BINARY)\nkernel = np.ones((3,3))\n# closing = cv2.dilate(edge,kernel,iterations = 1)\ndilation = cv2.dilate(edge,kernel,iterations = 1)\nclosing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)\ncontours, hierarchy = cv2.findContours(closing , cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) \n# cv2.imshow(\"Contour\",closing)\n# cv2.waitKey(0)\n\n# cv2.drawContours(image,contours, -1, (0, 0, 255), 3)\n\n# filled_contour = cv2.fillPoly(black_image, conc, color=(255,255,255))\n# ret3,filled_contour_binary = cv2.threshold(filled_contour,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\nprint(\"Number of Contours found = \" + str(len(contours))) \n# cv2.imshow('thresh', filled_contour_binary )\n# cv2.waitKey(0)\n# Draw all contours \n# -1 signifies drawing all contours\n\nlist_all_point_path = []\nlist_contours_symbol = []\nlist_contours_box_symbol_inside = []\nlist_contours_path = []\n# cv2.approxPolyDP()\nfor i in hierarchy.tolist()[0]: #ADD list_contours\n\tParent_check = (i[3] == 0) # check in case\n\tChild_check_symbol = (i[2] != -1) # Symbol\n\tChild_check_path = (i[2] == -1) # PATH\n\tif Parent_check:\n\t\tif Child_check_symbol:\n\t\t\tlist_contours_box_symbol_inside.append(hierarchy.tolist()[0].index(i))\n\t\tif Child_check_path:\n\t\t\tlist_contours_path.append(hierarchy.tolist()[0].index(i))\n\t\nfor j in list_contours_box_symbol_inside:\n\tcont = 20\n\tlist_x = []\n\tlist_y = []\n\tfor i in contours[j]:\n\t\tlist_x.append(i.tolist()[0][0])\n\t\tlist_y.append(i.tolist()[0][1])\n\tdiff_x = int((max(list_x)-min(list_x))/2)\n\tdiff_y = int((max(list_y)-min(list_y))/2)\n\tX = int(min(list_x) + diff_x)\n\tY = int(min(list_y) + diff_y)\n\tconst_x = diff_x + cont\n\tconst_y = diff_y + cont\n\t\n\t# cv2.circle(image,(center_x,center_y), 3, (0,0,255), -1)\n\toffset_right = X + const_x\n\toffset_left = X - const_x\n\toffset_up = Y + const_y\n\toffset_down = Y - const_y\n\n\tif find_color( gray,offset_right,Y) != 255:\n\t\tfor i in sampling(*(X,Y),*(offset_right , Y)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t# cv2.line(image,(center_x,center_y),(center_x + cont_x , center_y),(0,0,255),3)\n\n\tif find_color(\tgray,offset_left,Y) != 255:\n\t\tfor i in sampling(*(X,Y),*(offset_left , Y)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t# cv2.line(image,(center_x,center_y),(center_x - cont_x , center_y),(0,0,255),3)\n\n\tif find_color(\tgray,\tX,\toffset_up) != 255:\n\t\tfor i in sampling(*(X,Y),*(X , offset_up)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t\t\n\t\t# cv2.line(image,(center_x,center_y),(center_x , center_y + cont_y),(0,0,255),3)\n\n\tif find_color(\tgray,\tX,\toffset_down) != 255:\n\t\tfor i in sampling(*(X,Y),*(X , offset_down)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t# cv2.line(image,(center_x,center_y),(center_x , center_y - cont_y),(0,0,255),3)\n\t\n\t# cv2.circle(image,Centor, 3, (0,0,255), -1)\n\t\n\nprint(list_contours_box_symbol_inside)\n# print(list_contours_symbol)\n# print(list_contours_path)\nfor k in list_contours_path:\n\tepsilon = 0.003 * cv2.arcLength(contours[k], True)\n\tapprox = cv2.approxPolyDP(contours[k], epsilon, True)\n\tlist_approx = []\n\tfor j in approx.tolist():\n\t\tlist_approx.append(j[0])\n\t\n\tif len(list_approx) >= 7:\n\t\ta = 0\n\t\tb = -1\n\t\tlist_line = []\n\t\tfor _ in range(int(len(list_approx)/2)):\n\t\t\tpoint_xy_midle = find_middle(*tuple(list_approx[a]), *tuple(list_approx[b]))\n\t\t\t# cv2.circle(image, point_xy_midle , 3, (0, 255, 0), -1)\n\t\t\tlist_line.append(point_xy_midle)\n\t\t\ta += 1\n\t\t\tb -= 1\n\t\tfor i in range(1,len(list_line)):\n\t\t\tfor j in sampling(*list_line[i-1],*list_line[i]):\n\t\t\t\tcv2.circle(image,j,2,(0,0,255),-1)\n\t\t\t\tlist_all_point_path.append(j+(find_gradient(gray,*j),))\n\t\n\telse:\n\t\tlist_approx = top_to_bot(list_approx)\n\t\ta = 0\n\t\tb = -1\n\t\tlist_line = []\n\t\tfor _ in range(int(len(list_approx)/2)):\n\t\t\tpoint_xy_midle = find_middle(*tuple(list_approx[a]), *tuple(list_approx[b]))\n\t\t\t# cv2.circle(image, point_xy_midle , 3, (0, 255, 0), -1)\n\t\t\tlist_line.append(point_xy_midle)\n\t\t\ta += 1\n\t\t\tb -= 1\n\t\t\n\t\tfor i in range(1,len(list_line)):\n\t\t\tfor j in sampling(*list_line[i-1],*list_line[i]):\n\t\t\t\tcv2.circle(image,j,2,(0,0,255),-1)\n\t\t\t\tlist_all_point_path.append(j+(find_gradient(gray,*j),))\n\n\n# cv2.imshow(\"kkkk\",image) \n# cv2.waitKey(0)\n\n\n# skeleton = skeletonize(filled_contour)\n# cv2.imshow('skeleton',skeleton)\n# cv2.waitKey(0)\n# skeleton_lee = skeletonize(filled_contour, method='lee')\n# cv2.imshow('skeleton_lee', skeleton_lee)\n# cv2.waitKey(0)\n\n# thinned = thin(filled_contour_binary)\n# cv2.imwrite(\"000.png\",filled_contour_binary)\n# # display results\n\n\n# fig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)\n# ax = axes.ravel()\n\n# ax[0].imshow(thinned, cmap=plt.cm.gray)\n# ax[0].set_title('thinned')\n# ax[0].axis('off')\n\n# ax[1].imshow(skeleton_lee, cmap=plt.cm.gray)\n# ax[1].axis('off')\n# ax[1].set_title('skeleton_lee', fontsize=20)\n\n# ax[2].imshow(skeleton, cmap=plt.cm.gray)\n# ax[2].axis('off')\n# ax[2].set_title('skeleton', fontsize=20)\n\n\n# fig.tight_layout()\n# plt.show()\n\n# f = open(\"pointcloud.txt\", \"w\")\n# f.write(repr(list_all_point_path))\n# f.close()\n\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection='3d')\n# for i in list_all_point_path:\n# ax.scatter(i[1],i[0],i[2])\n# plt.show()\n# cv2.waitKey(0)\n\n# print(list_contours_box_symbol_inside)\nfrom math import copysign, log10\nfor j in list_contours_box_symbol_inside:\n\t# cv2.drawContours(pop,contours,i,(255,0,0),2)\n\tcont = 0\n\tlist_x = []\n\tlist_y = []\n\tfor i in contours[j]:\n\t\tlist_x.append(i.tolist()[0][0])\n\t\tlist_y.append(i.tolist()[0][1])\n\tdiff_x = int((max(list_x)-min(list_x))/2)\n\tdiff_y = int((max(list_y)-min(list_y))/2)\n\tX = int(min(list_x) + diff_x)\n\tY = int(min(list_y) + diff_y)\n\tconst_x = diff_x + cont\n\tconst_y = diff_y + cont\n\toffset_right = X + const_x\n\toffset_left = X - const_x\n\toffset_up = Y + const_y\n\toffset_down = Y - const_y\n\tim = cv2.cvtColor(pop[offset_down:offset_up,offset_left:offset_right], cv2.COLOR_BGR2GRAY)\n\tcv2.imwrite(str(offset_down)+\".png\",pop[offset_down:offset_up,offset_left:offset_right])\n\t# cv2.imshow(\"222kkkk\",pop[offset_down:offset_up,offset_left:offset_right]) \n\t# cv2.waitKey(0)\n\t_,im = cv2.threshold(im, 128, 255, cv2.THRESH_BINARY)\n\tmoments = cv2.moments(im)\n\thuMoments = cv2.HuMoments(moments)\n\tfor q in range(0,7):\n\t\thuMoments[q] = (-1* copysign(1.0, huMoments[q]) * log10(abs(huMoments[q])))\n\tprint(huMoments)\n\tcv2.imshow(\"kkkk\",pop[offset_down:offset_up,offset_left:offset_right]) \n\tcv2.waitKey(0)\n\ncv2.destroyAllWindows() \n\n\n\n\n","sub_path":"Old_Version/Flush_Image/Detect_edge/Useful.py","file_name":"Useful.py","file_ext":"py","file_size_in_byte":8376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"375635626","text":"#!/usr/bin/env python3\n\nimport math\nimport random\n\nSMALL_NUMBER_LIMIT = pow(2,24)\n\ndef small_units(n):\n return [x for x in range(1, min(SMALL_NUMBER_LIMIT, n-1)) if math.gcd(x,n) == 1]\n\ndef multiply_mod(a, b, mod):\n result = 0\n a %= mod\n b %= mod\n while a > 0:\n if a%2 == 1:\n result = (b + result) % mod\n b = (2 * b) % mod\n a = a//2\n return result\n\n\ndef xgcd(a,b):\n prevx, x = 1, 0; prevy, y = 0, 1\n while b:\n q = a//b\n x, prevx = prevx - q*x, x\n y, prevy = prevy - q*y, y\n a, b = b, a % b\n return a, prevx, prevy\n \ndef modinv(a, n):\n factor, a, b = xgcd(a, n)\n if factor == 1:\n return a\n return None\n\n# doesn't catch carmichaels\ndef fermat_test(p):\n return pow(2, p-1, p) == 1 and pow(3, p-1, p) == 1\n\n# next fermat pseudoprime/prime\ndef next_fermat(n):\n while not fermat_test(n):\n n += 1\n return n\n\ndef small_factor(n):\n for x in range(2, min(SMALL_NUMBER_LIMIT, round(math.sqrt(n) + 1))):\n # print(n, x)\n if n%x == 0:\n result = small_factor(n//x)\n result.insert(0, x)\n return result\n return [n]\n\nprint(small_factor(277777788888899))\n\n# use a random walk multiplying by fibonacci powers a^1 a^2 a^3 a^5 to try to find a a^x = a^y collision. \ndef search_unit_order(elem, n, accumulator = None, recurrence = lambda x, n, a: (2*x + 1) % n**2, limit = pow(2,19)):\n # map of exponent expression, to values.\n seen = {}\n a = 1\n test_count = 0\n for i in range(2, limit):\n test_count += 1\n a, accumulator = recurrence(a, n, accumulator)\n if a in seen or a == 0:\n continue\n value = pow(elem, a, n)\n seen[a] = value\n #if random.random() < 0.0001:\n #print(\" testing %s ^ %s\" % (elem, a))\n if value == 1:\n return a, test_count\n if value in seen:\n old_a = seen[value]\n #print(\"%s^%s = %s^%s\" % (elem, a, elem, old_a))\n return abs(a - old_a), test_count\n \"\"\"\n \"\"\"\n return None, test_count\n\n\ndef main():\n digits = 16 \n #TODO a better prime test that excludes carmichaels.\n p = next_fermat(pow(2,digits//2 + 1))\n q = next_fermat(pow(2,digits//2 - 2))\n n = p * q\n print(\"p, q, n: \", p, q, n)\n print(\"totient(n) = %s * %s = %s\" % (p-1, q-1, (p-1)*(q-1)))\n\n\n tests = range(2,30)\n # TODO are there easy ways to determine whether two elements have the same order, without actually finding that value?\n recurrences = [\n lambda a, n, accumulator: ((2 * a + 1) % (n), None),\n lambda a, n, accumulator: ((3 * a + 1) % (n*n), None),\n lambda a, n, accumulator: ((2 * a + 1), None),\n ]\n\n for recurrence in recurrences:\n search_steps = []\n order_multiples = []\n for elem in tests:\n result, test_count = search_unit_order(elem, n, recurrence=recurrence)\n search_steps.append(test_count)\n order_multiples.append(result)\n #print('|%s| mod %s divides %s'% (elem, n, result))\n #print(' tests: %s' % (test_count,))\n print()\n print('search steps', search_steps)\n print('order multiples', order_multiples)\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\nprint(small_units(pow(2,100))[-1])\nprint(modinv(2039, 2**100))\n#print(units(100))\n#print(xgcd(29, 35))\nn = 2390204820439820942390482390\n#n = 1012300\nl = factor(n)\nprint(l)\nresult = 1\nfor x in l:\n result *= x\nprint(result)\n\"\"\"\n\n","sub_path":"semiprimes.py","file_name":"semiprimes.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"452385552","text":"#! /usr/bin/python\n\n# Copyright 2019 Extreme Networks, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport errno\nimport subprocess\nimport random\nimport re\n\nfrom st2common.runners.base_action import Action\n\n\nclass DigAction(Action):\n\n def run(self, rand, count, nameserver, hostname, queryopts):\n opt_list = []\n output = []\n\n cmd_args = ['dig']\n if nameserver:\n nameserver = '@' + nameserver\n cmd_args.append(nameserver)\n\n if re.search(',', queryopts):\n opt_list = queryopts.split(',')\n else:\n opt_list.append(queryopts)\n for k, v in enumerate(opt_list):\n cmd_args.append('+' + v)\n\n cmd_args.append(hostname)\n\n try:\n result_list = filter(None, subprocess.Popen(cmd_args,\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE)\n .communicate()[0]\n .split('\\n'))\n\n # NOTE: Python3 supports the FileNotFoundError, the errono.ENOENT is for py2 compat\n # for Python3:\n # except FileNotFoundError as e:\n\n except OSError as e:\n if e.errno == errno.ENOENT:\n return False, \"Can't find dig installed in the path (usually /usr/bin/dig). If \" \\\n \"dig isn't installed, you can install it with 'sudo yum install \" \\\n \"bind-utils' or 'sudo apt install dnsutils'\"\n else:\n raise e\n\n if int(count) > len(result_list) or count <= 0:\n count = len(result_list)\n\n output = result_list[0:count]\n if rand is True:\n random.shuffle(output)\n return output\n","sub_path":"contrib/linux/actions/dig.py","file_name":"dig.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"516362745","text":"import matplotlib\nmatplotlib.use('Agg')\n\nimport coreapi\nimport numpy as np\nimport astropy\nimport astropy.table as at\nimport sys\nimport matplotlib.pyplot as plt\nimport os\nimport csv\nfrom jumpssh import SSHSession\nimport sqlite3\nfrom datetime import datetime as dt\nimport requests, re\nimport texas\nfrom astropy.io import ascii\nfrom config import lc_cfg\nfrom astropy.time import Time\nfrom candidate_generator import Save_space\n\ndef tess_obs(ra, dec):\n\n tess_date = lc_cfg['tess_date']\n\n url = 'https://heasarc.gsfc.nasa.gov/cgi-bin/tess/webtess/'\n url += 'wtv.py?Entry={ra}%2C{dec}'\n r = requests.get(url.format(ra=str(ra), dec=str(dec)))\n if r.status_code!=200:\n print('status message:',r.text)\n error = 'ERROR: could not get {url}, status code {code}'\n raise RuntimeError(error.format(url=url, code=r.status_code))\n return(None)\n\n reg = r\"observed in camera \\w+.\\nSector \\w+\"\n info = re.findall(reg, r.content.decode())\n sectors=[]\n for k in info:\n sectors.append(int(re.split(r'\\s', k)[5])-1)\n \n time = []\n if len(sectors)>0:\n for sector in sectors:\n time.append([tess_date[int(sector)-1], tess_date[int(sector)]])\n \n return(time)\n\n\ndef to_array(somelist, column, start = 1):\n array_raw = np.asarray(somelist[start:])[:,column]\n array = [float(i) for i in array_raw]\n return array\n\ndef search_atlas(ra, dec):\n atlas_info = lc_cfg['atlas_info']\n gateway_session1 = SSHSession(atlas_info[0]['address'],atlas_info[0]['username'], password=atlas_info[0]['password']).open()\n if len(atlas_info)==3:\n gateway_session2 = gateway_session1.get_remote_session(atlas_info[1]['address'],atlas_info[1]['username'], password=atlas_info[2]['password'])\n remote_session = gateway_session2.get_remote_session(atlas_info[2]['address'], password=atlas_info[2]['password'])\n elif len(atlas_info)==2:\n remote_session = gateway_session1.get_remote_session(atlas_info[1]['address'], password=atlas_info[1]['password'])\n else: \n print('wrong format for atlas_params: too many jump connection')\n\n today = dt.today()\n con = sqlite3.connect(\":memory:\")\n tdate = ' '+str(list(con.execute(\"select julianday('\"+today.strftime(\"%Y-%m-%d\")+\"')\"))[0][0]-lc_cfg['lookback_days']-2400000)\n\n result=remote_session.get_cmd_output('./mod_force.sh '+str(ra)+' '+ str(dec)+tdate)\n\n atlas_lc = at.Table(names=('jd','mag', 'mag_err','flux', 'fluxerr', 'filter','maj', 'min', 'apfit', 'sky', 'zp', 'zpsys'), dtype=('f8', 'f8', 'f8', 'f8', 'f8', 'S1' , 'f8', 'f8', 'f8', 'f8','f8', 'U8'))\n\n split = result.split('\\r\\n')\n\n for i in split[1:]:\n k = i.split()\n# if int(k[3])>int(k[4]):\n atlas_lc.add_row([float(k[0]), float(k[1]), float(k[2]), float(k[3]), float(k[4]), k[5], float(k[12]), float(k[13]), float(k[15]), float(k[16]), float(k[17]), 'ab'])\n\n return atlas_lc\n\n\ndef get_ztf(ra, dec):\n ztfurl = 'https://mars.lco.global/?format=json&sort_value=jd&sort_order=desc&cone=%.7f%%2C%.7f%%2C0.0014'%(ra, dec)\n client = coreapi.Client()\n schema = client.get(ztfurl)\n return schema\n \ndef ztf2lc(ztf_obj):\n\n lc = at.Table(names=('jd','mag', 'mag_err', 'filter'), dtype=('f8', 'f8', 'f8', 'S1'))\n for i in range(len(ztf_obj['results'])):\n phot = ztf_obj['results'][i]['candidate']\n if phot['isdiffpos'] == 'f':\n continue\n lc.add_row([phot['jd'], phot['magap'], phot['sigmagap'], phot['filter']])\n return lc\n \ndef plot(ax,lc, survey):\n if survey =='atlas':\n limit =lc['flux']0\n for i in set(lc['filter']):\n index = lc['filter']==i\n jd = lc['jd'][index]\n if jd[0] > 2400000:\n jd = jd -2400000\n mag = abs(lc['mag'][index])\n err = lc['mag_err'][index]\n if survey =='atlas':\n flux = lc['flux'][index]\n fluxerr = lc['fluxerr'][index]\n limit =flux 2400000:\n jd = jd -2400000\n flux = lc['flux'][lc['filter']==i]\n err = lc['fluxerr'][lc['filter']==i]\n ax.errorbar(jd, flux, err, label = survey +' '+ i, fmt='o',color = lc_cfg['color'][i])\n\n# ax = plt.gca()\n\n #ax.grid(True)\n return ax\n\n\n \ndef lc(ra, dec, out_fig, atlas_data_file, disc_t):\n ztf_obj = get_ztf(ra, dec)\n\n lc = ztf2lc(ztf_obj)\n \n fig, (ax1, ax2)=plt.subplots(2, figsize = (6,10), sharex = True)\n\n try:\n atlas_lc = search_atlas(ra, dec)\n print('got lc')\n mask = (abs(atlas_lc['mag'])>10)\n atlas_lc = atlas_lc[mask]\n# print(atlas_lc)\n if len(atlas_lc)>0:\n print(atlas_data_file)\n ascii.write(atlas_lc, atlas_data_file, overwrite=True)\n# print(3)\n ax1 = plot(ax1,atlas_lc, 'atlas')\n ax2 = plot_atflux(ax2, atlas_lc, 'atlas')\n ax2.set_ylim(-0.1*max(atlas_lc['flux']), 1.2*max(atlas_lc['flux']))\n if len(lc)>0: \n ax1 = plot(ax1,lc, 'ztf')\n ymin = min(max([max(abs(lc['mag'])), max(abs(atlas_lc['mag']))])+0.5, 21)\n ax1.set_ylim(ymin, min([min(abs(lc['mag'])), min(abs(atlas_lc['mag']))]) -0.5)\n else:\n ymin = min(max(abs(atlas_lc['mag']))+0.5,21)\n ax1.set_ylim(ymin, min(abs(atlas_lc['mag']))-0.5)\n ax1.plot(disc_t, ymin, marker = \"^\")\n except:\n print('unable to get atlas lc')\n if len(lc)>0:\n ax1 = plot(ax1,lc, 'ztf')\n ax1.set_ylim(min(max(abs(lc['mag']))+0.5, 21), min(abs(lc['mag']))-0.5)\n \n tess_ob = tess_obs(ra, dec)\n# print(tess_ob)\n tess_cover = False\n \n today = dt.today()\n con = sqlite3.connect(\":memory:\")\n tdate = list(con.execute(\"select julianday('\"+today.strftime(\"%Y-%m-%d\")+\"')\"))[0][0]-2400000\n \n for [t1, t2] in tess_ob:\n x1= np.arange(t1-2400000, (t1+t2)/2-2400000-1., 0.1)\n x2= np.arange((t1+t2)/2-2400000+1, t2-2400000, 0.1)\n# print(t2,tdate + lc_cfg['xlim'][0] , t1,tdate+lc_cfg['xlim'][1])\n if x2[-1]> tdate + lc_cfg['xlim'][0] and x1[0]< tdate+lc_cfg['xlim'][1]:\n ax1.fill_between(x1, 10, 22, facecolor='grey', alpha=0.5, label = 'TESS')\n ax1.fill_between(x2, 10, 22, facecolor='grey', alpha=0.5)\n ax2.fill_between(x1, 0, 10000, facecolor='grey', alpha=0.5, label = 'TESS')\n ax2.fill_between(x2, 0, 10000, facecolor='grey', alpha=0.5)\n if disc_t>t1 and disc_t0:\n flux = 10**(-0.4*(k['mag']-27.5))\n fluxerr= k['mag_err']*10**(-0.4*(k['mag']-27.5))\n else:\n flux = -10**(-0.4*(-k['mag']-27.5))\n fluxerr= k['mag_err']*10**(-0.4*(-k['mag']-27.5))\n mag = k['mag']\n magerr = k['mag_err']\n f.write('OBS: ' + str(k['jd']) +' '+ flt+' '+ str(flux)+ ' '+str(fluxerr)+' '+ str(mag)+' '+ str(magerr)+' 0 \\n')\n\n os.system('python ./yse/uploadTransientData.py -e -s ./yse/settings.ini -i '+outname+' --instrument ACAM1 --fluxzpt 27.5')\n\n\n\n#if __name__ == \"__main__\":\ndef main(argv):\n# print(argv)\n# ra, dec, name, date= argv[0:]\n ra = float(argv[0])\n dec = float(argv[1])\n date = argv[3]\n name = argv[2]\n disc_t = 0.\n\n \n home_dir = lc_cfg['home_dir']+name+'/'\n Save_space(home_dir)\n\n out_fig = home_dir + name + date + '_lc.'+lc_cfg['img_suffix'] \n atlas_data_file = home_dir+name+date+'_atlas.csv'\n\n# print([ra, dec, '3', name + date+'_texas'])\n# if os.path.exists(home_dir+name+'_texas.txt'):\n# galcan = ascii.read(home_dir+name+'_texas.txt')\n# else:\n# try:\n# galcan = texas.main([argv[0], argv[1], '3', home_dir + name + '_texas'])\n# ascii.write(galcan, home_dir+name+'_texas.txt', overwrite=True) \n# except:\n# print('unable to access PanSTARRS')\n \n ra = float(ra)\n dec = float(dec) \n# tess_cover = False \n if len(argv)>4: \n disc_t = argv[4]\n else:\n disc_t = Time.now().jd\n \n if not os.path.exists(out_fig): # changed when server down.. will be back\n tess_cover = lc(ra, dec, out_fig, atlas_data_file, disc_t)\n else: \n tess_ob = tess_obs(ra, dec)\n tess_cover = False\n for [t1, t2] in tess_ob:\n if disc_t>t1 and disc_t0:\n# return tess_cover\n # else:\n return tess_cover\n \n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n","sub_path":"website/lc_ex.py","file_name":"lc_ex.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"412524883","text":"import copy\nimport json\nimport os\n\nimport discord\nfrom unidecode import unidecode\n\nfrom chatbot import libchatbot\n\ntry: # Unicode patch for Windows\n import win_unicode_console\n\n win_unicode_console.enable()\nexcept:\n if os.name == 'nt':\n import sys\n\n if sys.version_info < (3, 6):\n print(\"Please install the 'win_unicode_console' module.\")\n\ndo_logging = True\nlog_name = \"Discord-Chatbot.log\"\n\nmodel = \"reddit\"\nsave_dir = \"models/\" + model\n\ndef_max_input_length = 1000\ndef_max_length = 125\n\ndef_beam_width = 2\ndef_relevance = -1\ndef_temperature = 1.0\ndef_topn = -1\n\nmax_input_length = def_max_input_length\nmax_length = def_max_length\n\nbeam_width = def_beam_width\nrelevance = def_relevance\ntemperature = def_temperature\ntopn = def_topn\n\nstates_main = \"states\" + \"_\" + model\n\nstates_folder = states_main + \"/\" + \"server_states\"\nstates_folder_dm = states_main + \"/\" + \"dm_states\"\n\nstates_saves = states_main + \"/\" + \"saves\"\n\nuser_settings_folder = \"user_settings\"\nult_operators_file = user_settings_folder + \"/\" + \"ult_operators.cfg\"\noperators_file = user_settings_folder + \"/\" + \"operators.cfg\"\nbanned_users_file = user_settings_folder + \"/\" + \"banned_users.cfg\"\n\nprocessing_users = []\n\nmention_in_message = True\nmention_message_separator = \" - \"\n\nmessage_prefix = \">\"\ncommand_prefix = \"--\" # Basically treated as message_prefix + command_prefix\n\nult_operators = []\noperators = []\nbanned_users = []\n\nstates_queue = {}\n\nprint('Loading Chatbot-RNN...')\nlib_save_states, lib_get_states, consumer = libchatbot(\n save_dir=save_dir, max_length=max_length)\nprint('Chatbot-RNN has been loaded.')\n\nprint('Preparing Discord Bot...')\nclient = discord.Client()\n\n\n@client.event\nasync def on_ready():\n print()\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print()\n print('Discord Bot ready!')\n\n\ndef log(message):\n if do_logging:\n with open(log_name, \"a\", encoding=\"utf-8\") as log_file:\n log_file.write(message)\n\n\ndef load_states(states_id):\n global states_folder, states_folder_dm\n\n make_folders()\n\n states_file = get_states_file(states_id)\n\n if os.path.exists(states_file + \".pkl\") and os.path.isfile(states_file + \".pkl\"):\n return lib_get_states(states_file)\n else:\n return lib_get_states()\n\n\ndef make_folders():\n if not os.path.exists(states_folder):\n os.makedirs(states_folder)\n\n if not os.path.exists(states_folder_dm):\n os.makedirs(states_folder_dm)\n\n if not os.path.exists(user_settings_folder):\n os.makedirs(user_settings_folder)\n\n if not os.path.exists(states_saves):\n os.makedirs(states_saves)\n\n\ndef get_states_file(states_id):\n if states_id.endswith(\"p\"):\n states_file = states_folder_dm + \"/\" + states_id\n else:\n states_file = states_folder + \"/\" + states_id\n\n return states_file\n\n\ndef save_states(states_id, states=None): # Saves directly to the file, recommended to use states queue\n make_folders()\n\n states_file = get_states_file(states_id)\n\n lib_save_states(states_file, states=states)\n\n\ndef add_states_to_queue(states_id, states_diffs):\n current_states_diffs = None\n\n if states_id in states_queue:\n current_states_diffs = states_queue[states_id]\n\n for num in range(len(states_diffs)):\n if current_states_diffs is not None and current_states_diffs[num] is not None:\n states_diffs[num] += current_states_diffs[num]\n\n states_queue.update({states_id: states_diffs})\n\n\ndef get_states_id(message):\n if message.guild is None or isinstance(message.channel, discord.abc.PrivateChannel):\n return str(message.channel.id) + \"p\"\n else:\n return str(message.guild.id) + \"s\"\n\n\ndef write_state_queue():\n for states_id in states_queue:\n states = load_states(states_id)\n\n states_diff = states_queue[states_id]\n if get_states_size(states) > len(states_diff):\n states = states[0]\n\n elif get_states_size(states) < len(states_diff):\n states = [copy.deepcopy(states), copy.deepcopy(states)]\n\n new_states = copy.deepcopy(states)\n\n total_num = 0\n for num in range(len(states)):\n for num_two in range(len(states[num])):\n for num_three in range(len(states[num][num_two])):\n for num_four in range(len(states[num][num_two][num_three])):\n new_states[num][num_two][num_three][num_four] = states[num][num_two][num_three][num_four] - \\\n states_diff[total_num]\n total_num += 1\n\n lib_save_states(get_states_file(states_id), states=new_states)\n states_queue.clear()\n\n\ndef get_states_size(states):\n total_num = 0\n if states is not None:\n for num in range(len(states)):\n for num_two in range(len(states[num])):\n for num_three in range(len(states[num][num_two])):\n for num_four in range(len(states[num][num_two][num_three])):\n total_num += 1\n return total_num\n\n\ndef is_discord_id(user_id):\n # Quick general check to see if it matches the ID formatting\n return (isinstance(user_id, int) or user_id.isdigit) and len(str(user_id)) == 18\n\n\ndef remove_invalid_ids(id_list):\n for user in id_list:\n if not is_discord_id(user):\n id_list.remove(user)\n\n\ndef save_ops_bans():\n global ult_operators, operators, banned_users\n\n make_folders()\n\n # Sort and remove duplicate entries\n ult_operators = list(set(ult_operators))\n operators = list(set(operators))\n banned_users = list(set(banned_users))\n\n # Remove from list if ID is invalid\n remove_invalid_ids(ult_operators)\n\n # Remove them from the ban list if they were added\n # Op them if they were removed\n for user in ult_operators:\n operators.append(user)\n if user in banned_users:\n banned_users.remove(user)\n\n # Remove from list if ID is invalid\n remove_invalid_ids(operators)\n\n # Remove from list if ID is invalid\n remove_invalid_ids(banned_users)\n\n # Sort and remove duplicate entries\n ult_operators = list(set(ult_operators))\n operators = list(set(operators))\n banned_users = list(set(banned_users))\n\n with open(ult_operators_file, 'w') as f:\n f.write(json.dumps(ult_operators))\n with open(operators_file, 'w') as f:\n f.write(json.dumps(operators))\n with open(banned_users_file, 'w') as f:\n f.write(json.dumps(banned_users))\n\n\ndef load_ops_bans():\n global ult_operators, operators, banned_users\n\n make_folders()\n\n if os.path.exists(ult_operators_file) and os.path.isfile(ult_operators_file):\n with open(ult_operators_file, 'r') as f:\n try:\n ult_operators = json.loads(f.read())\n except json.decoder.JSONDecodeError:\n ult_operators = []\n\n if os.path.exists(operators_file) and os.path.isfile(operators_file):\n with open(operators_file, 'r') as f:\n try:\n operators = json.loads(f.read())\n except json.decoder.JSONDecodeError:\n operators = []\n\n if os.path.exists(banned_users_file) and os.path.isfile(banned_users_file):\n with open(banned_users_file, 'r') as f:\n try:\n banned_users = json.loads(f.read())\n except json.decoder.JSONDecodeError:\n banned_users = []\n\n save_ops_bans()\n\n\n# Prepare the operators and ban lists\nload_ops_bans()\n\n\ndef matches_command(content, command):\n try:\n content = content[:content.index(\" \")]\n except ValueError:\n pass\n\n return content.lower() == command_prefix.lower() + command.lower()\n\n\ndef remove_command(content):\n try:\n content = content[content.index(\" \") + 1:]\n except ValueError:\n content = \"\"\n\n return content\n\n\ndef user_id_cleanup(uid):\n return uid.replace(\"<@\", \"\").replace(\"!\", \"\").replace(\">\", \"\")\n\n\ndef get_args(content):\n return split_args(remove_command(content))\n\n\ndef split_args(full_args):\n return [] if full_args == \"\" else full_args.split(\" \")\n\n\ndef get_user_perms(message):\n load_ops_bans()\n\n user_perms = {\n \"banned\": message.author.id in banned_users,\n \"op\": message.author.id in operators,\n \"ult_op\": message.author.id in ult_operators,\n \"server_admin\": message.guild is None or message.author.guild_permissions.administrator,\n \"private\": message.channel is discord.abc.PrivateChannel,\n }\n\n return user_perms\n\n\ndef process_response(response, result):\n # 0 = OK\n # 1 = Generic error in arguments\n # 2 = Too many arguments\n # 3 = Not enough arguments\n # 4 = Generic error\n # 5 = No permissions error\n # 6 = User not found error\n # 7 = Command not found error\n\n error_code_print = False\n\n if result == 0:\n if response == \"\":\n response = \"Command successful\"\n\n response = \"System: \" + response\n elif result == 1:\n if response == \"\":\n response = \"Invalid argument(s)\"\n\n response = \"Error: \" + response\n elif result == 2:\n if response == \"\":\n response = \"Too many arguments\"\n\n response = \"Error: \" + response\n elif result == 3:\n if response == \"\":\n response = \"Not enough arguments\"\n\n response = \"Error: \" + response\n elif result == 4:\n if response == \"\":\n response = \"Generic error\"\n error_code_print = True\n\n response = \"Error: \" + response\n elif result == 5:\n if response == \"\":\n response = \"Insufficient permissions\"\n\n response = \"Error: \" + response\n elif result == 6:\n if response == \"\":\n response = \"User not found\"\n\n response = \"Error: \" + response\n elif result == 7:\n if response == \"\":\n response = \"Command not found\"\n\n response = \"Error: \" + response\n\n if error_code_print:\n response += \" (Error Code \" + str(result) + \")\"\n\n return response\n\n\nasync def process_command(msg_content, message):\n global max_input_length, max_length, beam_width, relevance, temperature, topn\n\n result = 0\n\n response = \"\"\n\n load_ops_bans()\n user_perms = get_user_perms(message)\n\n cmd_args = get_args(msg_content)\n\n if matches_command(msg_content, \"help\"):\n response = \"Available Commands:\\n\" \\\n \"```\\n\" \\\n \"help, restart, reset, save, load, op, deop, ban, unban, param_reset, \" \\\n \"max_input_length, max_length, beam_width, temperature, relevance, topn\\n\" \\\n \"```\"\n\n elif matches_command(msg_content, \"restart\"):\n if user_perms[\"ult_op\"]:\n print()\n print(\"[Restarting...]\")\n response = \"System: Restarting...\"\n await send_message(message, response)\n await client.close()\n exit()\n else:\n result = 5\n\n elif matches_command(msg_content, \"reset\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n reset_states = lib_get_states()\n\n save_states(get_states_id(message), states=reset_states)\n\n print()\n print(\"[Model state reset]\")\n response = \"Model state reset\"\n else:\n result = 5\n\n elif matches_command(msg_content, \"save\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n if input_text.endswith(\".pkl\"):\n input_text = input_text[:len(input_text) - len(\".pkl\")]\n\n make_folders()\n\n lib_save_states(states_saves + \"/\" + input_text,\n states=lib_get_states(get_states_file(get_states_id(message))))\n\n print()\n print(\"[Saved states to \\\"{}.pkl\\\"]\".format(input_text))\n response = \"Saved model state to \\\"{}.pkl\\\"\".format(input_text)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"load\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n if input_text.endswith(\".pkl\"):\n input_text = input_text[:len(input_text) - len(\".pkl\")]\n\n make_folders()\n\n save_states(get_states_id(message), states=lib_get_states(states_saves + \"/\" + input_text))\n\n print()\n print(\"[Loaded saved states from \\\"{}.pkl\\\"]\".format(\n input_text))\n response = \"Loaded saved model state from \\\"{}.pkl\\\"\".format(\n input_text)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"op\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if not int(input_text) in operators:\n if not int(input_text) in banned_users:\n load_ops_bans()\n operators.append(int(input_text))\n save_ops_bans()\n print()\n print(\"[Opped \\\"{}\\\"]\".format(input_text))\n response = \"Opped \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to op user \\\"{}\\\", they're banned\".format(input_text)\n result = 4\n else:\n response = \"Unable to op user \\\"{}\\\", they're already OP\".format(input_text)\n result = 4\n else:\n response = \"Unable to op user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to op user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to op user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"deop\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if int(input_text) in operators:\n load_ops_bans()\n if int(input_text) in operators:\n operators.remove(int(input_text))\n save_ops_bans()\n print()\n print(\"[De-opped \\\"{}\\\"]\".format(input_text))\n response = \"De-opped \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to de-op user \\\"{}\\\", they're not OP\".format(input_text)\n result = 4\n else:\n response = \"Unable to de-op user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to de-op user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to de-op user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"ban\"):\n if user_perms[\"op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if not int(input_text) in banned_users:\n load_ops_bans()\n banned_users.append(int(input_text))\n save_ops_bans()\n print()\n print(\"[Banned \\\"{}\\\"]\".format(input_text))\n response = \"Banned \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to ban user \\\"{}\\\", they're already banned\".format(input_text)\n result = 4\n else:\n response = \"Unable to ban user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to ban user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to ban user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"unban\"):\n if user_perms[\"op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if int(input_text) in banned_users:\n load_ops_bans()\n if int(input_text) in banned_users:\n banned_users.remove(int(input_text))\n save_ops_bans()\n print()\n print(\"[Un-banned \\\"{}\\\"]\".format(input_text))\n response = \"Un-banned \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to un-ban user \\\"{}\\\", they're not banned\".format(input_text)\n result = 4\n else:\n response = \"Unable to un-ban user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to un-ban user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to un-ban user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"param_reset\"):\n if user_perms[\"ult_op\"]:\n max_input_length = def_max_input_length\n max_length = def_max_length\n\n beam_width = def_beam_width\n relevance = def_relevance\n temperature = def_temperature\n topn = def_topn\n\n print()\n print(\"[User \\\"{}\\\" reset all params]\".format(message.author.id))\n response = \"All parameters have been reset.\"\n else:\n result = 5\n\n elif matches_command(msg_content, \"max_input_length\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n max_input_length = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the max input length to {}]\".format(message.author.id, max_input_length))\n response = \"Max input length changed to {}.\".format(max_input_length)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"max_length\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n max_length = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the max response length to {}]\".format(message.author.id, max_length))\n response = \"Max response length changed to {}.\".format(max_length)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"beam_width\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n beam_width = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the beam width to {}]\".format(message.author.id, beam_width))\n response = \"Beam width changed to {}.\".format(beam_width)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"temperature\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n temperature = float(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the temperature to {}]\".format(message.author.id, temperature))\n response = \"Temperature changed to {}.\".format(temperature)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"relevance\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n relevance = float(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the relevance to {}]\".format(message.author.id, relevance))\n response = \"Relevance changed to {}.\".format(relevance)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"topn\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n topn = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the topn to {}]\".format(message.author.id, topn))\n response = \"TopN filter changed to {}.\".format(topn)\n else:\n result = 3\n else:\n result = 5\n\n else:\n result = 7\n\n return process_response(response, result)\n\n\ndef has_channel_perms(message):\n return message.guild is None or message.channel.permissions_for(\n message.guild.get_member(client.user.id)).send_messages;\n\n\nasync def send_message(message, text):\n if (mention_in_message or (not mention_in_message and not text == \"\")) and has_channel_perms(message):\n user_mention = \"\"\n\n if mention_in_message:\n user_mention = \"<@\" + str(message.author.id) + \">\" + mention_message_separator\n\n await message.channel.send(user_mention + text)\n\n\n@client.event\nasync def on_message(message):\n global max_input_length, max_length, beam_width, relevance, temperature, topn, lib_save_states, lib_get_states, consumer\n\n if message.content.lower().startswith(message_prefix.lower()) or message.channel is discord.abc.PrivateChannel and not message.author.bot and has_channel_perms(message):\n msg_content = message.content\n\n if msg_content.startswith(message_prefix):\n msg_content = msg_content[len(message_prefix):]\n if msg_content.startswith(\" \"):\n msg_content = msg_content[len(\" \"):]\n\n response = \"Error: Unknown error...\"\n\n async with message.channel.typing():\n user_perms = get_user_perms(message)\n if user_perms[\"banned\"] and not user_perms[\"private\"]:\n response = process_response(\"You have been banned and can only use this bot in DMs\", 5)\n\n elif msg_content.lower().startswith(command_prefix.lower()):\n response = await process_command(msg_content, message)\n\n else:\n if not (message.author.id in processing_users):\n if not msg_content == \"\":\n if not len(msg_content) > max_input_length:\n # Possibly problematic: if something goes wrong,\n # then the user couldn't send messages anymore\n processing_users.append(message.author.id)\n\n states = load_states(get_states_id(message))\n\n old_states = copy.deepcopy(states)\n\n clean_msg_content = unidecode(message.clean_content)\n\n if clean_msg_content.startswith(message_prefix):\n clean_msg_content = clean_msg_content[len(message_prefix):]\n if clean_msg_content.startswith(\" \"):\n clean_msg_content = clean_msg_content[len(\" \"):]\n\n print() # Print out new line for formatting\n print(\"> \" + clean_msg_content) # Print out user message\n\n # Automatically prints out response as it's written\n result, states = await consumer(clean_msg_content, states=states, beam_width=beam_width, relevance=relevance, temperature=temperature, topn=topn, max_length=max_length)\n\n # Purely debug\n # print(states[0][0][0]) Prints out the lowest level array\n # for state in states[0][0][0]: Prints out every entry in the lowest level array\n # print(state)\n\n # Remove whitespace before the message\n while result.startswith(\" \"):\n result = result[1:]\n\n if not mention_in_message and result == \"\":\n result = \"...\"\n\n response = result\n\n print() # Move cursor to next line after response\n\n log(\"\\n> \" + msg_content + \"\\n\" + result + \"\\n\") # Log entire interaction\n if len(old_states) == len(states):\n # Get the difference in the states\n\n states_diff = []\n for num in range(len(states)):\n for num_two in range(len(states[num])):\n for num_three in range(len(states[num][num_two])):\n for num_four in range(len(states[num][num_two][num_three])):\n states_diff.append(old_states[num][num_two][num_three][num_four] -\n states[num][num_two][num_three][num_four])\n\n add_states_to_queue(get_states_id(message), states_diff)\n write_state_queue()\n # save_states(get_states_id(message)) Old saving\n else:\n # Revert to old saving to directly write new array dimensions\n save_states(get_states_id(message))\n\n processing_users.remove(message.author.id)\n else:\n response = \"Error: Your message is too long (\" + str(len(msg_content)) + \"/\" + str(\n max_input_length) + \" characters)\"\n else:\n response = \"Error: Your message is empty\"\n else:\n response = \"Error: Please wait for your response to be generated before sending more messages\"\n\n await send_message(message, response)\n\n\nclient.run(\"Token Goes Here\", reconnect=True)\n","sub_path":"discord_bot.py","file_name":"discord_bot.py","file_ext":"py","file_size_in_byte":30759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"11272830","text":"\"\"\"\nName: Erel Shtossel\nID: 316297696\n\"\"\"\n\nimport random\nimport threading\nimport my_utils\nimport breadcrumbs\nimport copy\nfrom igraph import *\n\n\nclass learner(object):\n def __init__(self, q_table, last_state=None, last_action=None):\n self.table = q_table.table\n self.time_running = q_table.time_running\n self.meta_data = q_table\n self.last_state = last_state\n self.last_action = last_action\n self.last_valid_actions = []\n self.list_of_actions_with_no_impact = q_table.list_of_actions_with_no_impact\n self.save_format_for_graph = \"graphml\"\n\n self.track_finished_goals = list()\n self.num_of_finished_subgoals = 0\n self.points_of_interest = None\n\n self.time_from_last_save = 100\n self.save_q_table_func = lambda x: x.save_to_file(q_table.path)\n\n self.learning_rate = 0.8\n self.discount_factor = 0.8\n self.explore_level = 1 - q_table.time_running * 0.09\n\n def initialize(self, services):\n self.services = services\n self.meta_data.goal_states[\"start\"] = my_utils.to_state(\n self.services.parser.copy_state(self.services.perception.get_state()))\n try:\n file_name = self.services.parser.domain_name + my_utils.to_state(\n self.services.parser.objects) + \".\" + self.save_format_for_graph\n self.states_graph = Graph.Read(file_name.replace('/', '#'), self.save_format_for_graph)\n except:\n self.states_graph = Graph(directed=True)\n if self.time_running > 0 and len(self.meta_data.goal_states) > 0:\n graph_actions = breadcrumbs.graph_actions(self.states_graph, copy.deepcopy(self.meta_data.goal_states))\n self.breadcrumbs, self.sub_goals_order = graph_actions.calculate_best_path()\n\n all_actions = list()\n all_goal_actions = list()\n for i in range(len(self.breadcrumbs) - 1):\n action = \\\n self.states_graph.es.find(self.states_graph.get_eid(self.breadcrumbs[i], self.breadcrumbs[i + 1]))[\n \"name\"]\n all_actions.append(action)\n if self.breadcrumbs[i + 1] in self.sub_goals_order[0]:\n all_goal_actions.append(action)\n\n # Extract a list of actions that we want to do before other actions based on knowledge from the state graph\n self.points_of_interest = dict()\n index_of_last_sub_goal = 0\n place_in_permutation = 0\n for sub_goals in all_goal_actions:\n index_of_sub_goal = all_actions.index(sub_goals)\n path_to_sub_goal = all_actions[index_of_last_sub_goal:index_of_sub_goal + 1]\n path_to_sub_goal.reverse()\n # Remove actions with no impact on the way:\n # i = 1\n # while i < len(path_to_sub_goal):\n # # Not touching the first element because it is the sub-goal\n # if path_to_sub_goal[i] in self.list_of_actions_with_no_impact:\n # path_to_sub_goal.remove(path_to_sub_goal[i])\n # continue\n # i += 1\n # goal_words = path_to_sub_goal[0].strip(\")\").strip(\"(\").split()[1:]\n # i = 1\n # while i in range(len(path_to_sub_goal)):\n # if not any(x in path_to_sub_goal[i] for x in goal_words):\n # path_to_sub_goal.remove(path_to_sub_goal[i])\n # continue\n # i += 1\n self.points_of_interest[self.sub_goals_order[2][place_in_permutation]] = path_to_sub_goal\n place_in_permutation += 1\n index_of_last_sub_goal = index_of_sub_goal\n\n self.way_to_groups_of_same_action_dict = dict()\n for task in self.sub_goals_order[2]:\n self.way_to_groups_of_same_action_dict[task] = self.way_to_groups_of_same_action(task)\n\n if self.breadcrumbs is not None:\n for i in range(len(self.breadcrumbs) - 1):\n source = self.breadcrumbs[i]\n target = self.breadcrumbs[i + 1]\n edge_id = self.states_graph.get_eid(source, target)\n action = self.states_graph.es.find(edge_id)[\"name\"].strip(source).strip(target)\n # Every run- the data from the graph is better\n self.table[source][action] += 1.0 / (pow(2, 6 - self.time_running))\n\n def save_graph(self):\n file_name = self.services.parser.domain_name + my_utils.to_state(\n self.services.parser.objects) + \".\" + self.save_format_for_graph\n self.states_graph.save(file_name.replace('/', '#'), format=self.save_format_for_graph)\n\n def __del__(self):\n curr_state = my_utils.to_state(self.services.parser.copy_state(self.services.perception.get_state()))\n self.update_states_graph(curr_state)\n\n finished_goals = my_utils.done_subgoals(self.services.goal_tracking.completed_goals,\n self.services.perception.get_state())\n\n if len(self.services.goal_tracking.uncompleted_goals) == 0:\n # We won- find the last sub_goal\n try:\n self.meta_data.goal_states[curr_state] = self.track_finished_goals.index(False)\n except:\n 0 # Only one goal\n self.update_table(1000)\n else:\n self.update_table(-1000)\n\n self.save_q_table_func(self.meta_data)\n self.save_graph()\n\n def reward_function(self, state, action, new_state):\n # walking is a waist of time\n reward = -1\n if self.time_running > 0 and self.breadcrumbs is not None:\n if self.states_graph.vs.find(state).index in self.breadcrumbs and self.states_graph.vs.find(\n new_state).index in self.breadcrumbs:\n if self.breadcrumbs.index(self.states_graph.vs.find(state).index) + 1 == self.breadcrumbs.index(\n self.states_graph.vs.find(new_state).index):\n reward = 0\n if state == new_state:\n # the last action failed - maybe a better probability can be achieved with an other action\n reward -= 0.1\n # the final reward is given when the simulation ends- so it is in the goal check\n # the final reward is 1000\n return reward\n\n def update_table(self, reward=None, curr_state=None, curr_seen_best_option_value=None):\n # This function updates the q table\n if reward == None:\n reward = self.reward_function(self.last_state, self.last_action, curr_state)\n else:\n curr_seen_best_option_value = reward\n\n if not self.table[self.last_state].has_key(self.last_action):\n self.table[self.last_state][self.last_action] = 0\n self.table[self.last_state][self.last_action] = self.table[self.last_state][\n self.last_action] + self.learning_rate * (\n reward + self.discount_factor * curr_seen_best_option_value -\n self.table[self.last_state][self.last_action])\n\n def explore(self, curr_state, curr_valid_actions):\n action_grades = dict()\n high_graded_action = None\n choose_from = list()\n for iter in curr_valid_actions:\n if (iter not in self.table[curr_state]):\n # This is a new option opened because of our actions\n self.table[curr_state][iter] = 0\n if (self.table[curr_state][iter]) == 0:\n # Go to a place never evaluated\n choose_from.append(iter)\n\n # Goal analyze\n goal_keywords = self.extract_goal_keywords(self.services.goal_tracking.uncompleted_goals)\n for action in curr_valid_actions:\n for keyword_tuple in goal_keywords:\n update_val = 1\n for keyword in keyword_tuple:\n if action.find(keyword) != -1:\n if action_grades.has_key(action):\n action_grades[action] = update_val\n else:\n action_grades[action] = update_val\n update_val += 1\n if (len(action_grades) > 1):\n high_graded_action = max(random.sample(action_grades.keys(), len(action_grades)), key=action_grades.get)\n\n if high_graded_action != None:\n if random.random() > math.pow(0.5, action_grades[high_graded_action]):\n return high_graded_action\n\n if len(curr_valid_actions) > 0:\n try:\n # Choose the least walked in vertex\n vertex = self.states_graph.vs.find(curr_state)\n neighbors = vertex.neighbors()\n y = min(random.sample(neighbors, len(neighbors)), key=lambda x: x[\"count\"])\n for edge in vertex.out_edges():\n if edge.source == vertex.index and edge.target == y.index:\n return edge[\"name\"].strip(vertex[\"name\"]).strip(y[\"name\"])\n except:\n 0\n return random.choice(curr_valid_actions)\n\n if len(curr_valid_actions) == 0:\n # Dead end\n return None\n\n def extract_goal_keywords(self, uncompleted_goals):\n keywords = set()\n for sub_condition in uncompleted_goals:\n for part in sub_condition.parts:\n keywords.add(part.args)\n return keywords\n\n def next_action(self):\n # find current state\n raw_state_info = self.services.parser.copy_state(self.services.perception.get_state())\n curr_state = my_utils.to_state(raw_state_info)\n curr_valid_actions = self.services.valid_actions.get()\n\n self.register_new_state(curr_state, curr_valid_actions)\n # Dead end checking\n curr_seen_best_option = my_utils.key_max_value_from_actions(self.table[curr_state])\n if curr_seen_best_option == -1:\n # This is the end - no path from here\n self.update_table(reward=-1500)\n self.update_states_graph(curr_state)\n self.save_graph()\n return None\n\n list_of_opened_options = list(set(curr_valid_actions).difference(set(self.last_valid_actions)))\n if len(list_of_opened_options) == 0:\n # last action didn't change nothing\n self.list_of_actions_with_no_impact.add(self.last_action)\n\n if self.last_state != None:\n self.update_states_graph(curr_state)\n\n finished_goals = my_utils.done_subgoals(self.services.goal_tracking.uncompleted_goals,\n raw_state_info)\n curr_subgoals_finished = my_utils.num_of_done_subgoals(finished_goals)\n\n if curr_subgoals_finished > self.num_of_finished_subgoals or len(\n self.services.goal_tracking.uncompleted_goals) == 0:\n # We got a sub goal!\n if len(self.services.goal_tracking.uncompleted_goals) != 0:\n self.meta_data.goal_states[curr_state] = my_utils.diff(self.track_finished_goals, finished_goals)\n else:\n self.meta_data.goal_states[curr_state] = 0\n if len(finished_goals) != 0:\n self.track_finished_goals = finished_goals\n if self.points_of_interest is not None and self.points_of_interest.has_key(\n self.meta_data.goal_states[curr_state]):\n del self.points_of_interest[self.meta_data.goal_states[curr_state]]\n\n self.update_table(1000)\n self.num_of_finished_subgoals = curr_subgoals_finished\n if self.services.goal_tracking.reached_all_goals():\n # We got all goals!\n self.save_graph()\n return None\n elif curr_subgoals_finished < self.num_of_finished_subgoals:\n # We lost a sub goal\n self.update_table(-1100)\n\n self.track_finished_goals = finished_goals\n\n # observe and update the q table\n self.update_table(reward=None, curr_state=curr_state,\n curr_seen_best_option_value=self.table[curr_state][curr_seen_best_option])\n\n try_action = self.choose_explore_or_exploit(curr_seen_best_option, curr_state, curr_valid_actions)\n\n # save this state as the last one done:\n self.last_state = curr_state\n self.last_action = try_action\n self.last_valid_actions = curr_valid_actions\n\n self.time_from_last_save -= 1\n if self.time_from_last_save == 0:\n threading.Thread(target=self.save_q_table_func(deepcopy(self.meta_data))).start()\n # threading.Thread(target=self.save_graph).start()\n self.save_graph()\n self.time_from_last_save = 5000\n\n # Keep the q_table as clean as possible\n for iter in curr_valid_actions:\n if self.table[curr_state][iter] == 0:\n del self.table[curr_state][iter]\n if len(self.table[curr_state]) == 0:\n self.table[curr_state][try_action] = 0\n\n return try_action\n\n def update_states_graph(self, curr_state):\n try:\n vertex = self.states_graph.vs.find(name=str(curr_state))\n vertex[\"count\"] += 1\n except:\n vertex = self.states_graph.add_vertex(str(curr_state))\n vertex[\"count\"] = 1\n try:\n vertex = self.states_graph.vs.find(name=str(self.last_state))\n vertex[\"count\"] += 1\n except:\n vertex = self.states_graph.add_vertex(str(self.last_state))\n vertex[\"count\"] = 1\n try:\n edge = self.states_graph.es.find(name=str(self.last_state) + self.last_action + str(curr_state))\n except:\n edge = self.states_graph.add_edge(str(self.last_state), str(curr_state))\n edge[\"name\"] = self.last_action # str(self.last_state) + self.last_action + str(curr_state)\n\n def exploit_graph(self, curr_valid_actions,curr_seen_best_option):\n task = [x for x in self.sub_goals_order[2] if x in self.points_of_interest.keys()][0]\n if not hasattr(self, 'last_task'):\n self.last_task = task\n if not hasattr(self, 'place_on_way') or self.last_task != task:\n if self.meta_data.has_keys == False:\n self.place_on_way = len(self.points_of_interest[task])\n else:\n self.place_on_way = 0\n # TODO: try it once- if it does not work- leave this system (we have keys in this problem)\n if self.meta_data.has_keys == False:\n i = 0\n for action_in_best_path in self.points_of_interest[task]:\n if action_in_best_path in curr_valid_actions:\n if self.place_on_way != None and self.place_on_way >= i:\n self.place_on_way = i\n return action_in_best_path\n else:\n # Don't return to this system anymore\n self.place_on_way = 0\n self.meta_data.has_keys = True\n return random.choice(curr_valid_actions)\n i += 1\n else:\n # TODO: if they are 2 actions of the same kind one after one - try not doing the second one\n\n way_as_groups = self.way_to_groups_of_same_action_dict[task]\n for group_of_actions in way_as_groups[self.place_on_way:]:\n group_of_possible_actions = set(curr_valid_actions).intersection(group_of_actions)\n if len(group_of_possible_actions) > 0:\n self.place_on_way += 1\n if curr_seen_best_option in group_of_possible_actions:\n return curr_seen_best_option\n return random.choice(list(group_of_possible_actions))\n else:\n # We can't do what we wanted\n return curr_seen_best_option\n\n return None\n\n def way_to_groups_of_same_action(self, task):\n # Can be calculated only once\n way_as_group = []\n\n for action in self.points_of_interest[task]:\n if len(way_as_group) > 0:\n last_node = way_as_group.pop()\n else:\n way_as_group.append([action])\n continue\n if last_node is not None and last_node[0].strip(\"(\").split()[0] == action.strip(\"(\").split()[0]:\n # This is the same kind of action\n last_node.append(action)\n way_as_group.append(last_node)\n else:\n way_as_group.append(last_node)\n way_as_group.append([action])\n way_as_group.reverse()\n return way_as_group\n\n def choose_explore_or_exploit(self, curr_seen_best_option, curr_state, curr_valid_actions):\n x = random.random()\n if x < self.explore_level:\n # time to explore:\n try_action = self.explore(curr_state, curr_valid_actions)\n else:\n # time to exploite:\n if self.breadcrumbs is not None:\n try_action = self.exploit_graph(curr_valid_actions,curr_seen_best_option)\n if try_action is None:\n try_action = curr_seen_best_option\n return try_action\n\n def register_new_state(self, curr_state, curr_valid_actions):\n if self.table.get(curr_state) is None:\n # this is a new state that we need to evaluate and add to the table\n self.table[curr_state] = dict()\n for iter in curr_valid_actions:\n self.table[curr_state][iter] = 0\n else:\n for iter in curr_valid_actions:\n if not self.table[curr_state].has_key(iter):\n self.table[curr_state][iter] = 0\n","sub_path":"learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":18153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"445874619","text":"from abc import ABC\n\nfrom Mesh.System.SpaceFactor import MatterType\nfrom Mesh.util import Logger\n\n\nclass Entity(ABC):\n identifier = 'entity'\n\n def __init__(self, uuid):\n self.uuid = uuid\n self.dimension = (0, 0, 0)\n self.matter_type = MatterType.ETHER\n\n self.context = None\n self.preference = None\n self.action = None\n self.intent = None\n\n self.runnable = False\n\n self.logger = Logger.get_logger(self.__class__.__name__)\n\n def get_shape(self):\n return None\n\n def run(self, mp_space_factors, mp_task_pipe):\n pass\n\n def __str__(self):\n return '%s(uuid=.%s)' % (type(self).__class__.__name__, str(self.uuid)[-8:])\n","sub_path":"Mesh/System/Entity/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"588477183","text":"# Copyright 2012 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport glob\nimport os\n\nimport lxml.etree\n\nfrom nova import test\n\nSCHEMAS = \"nova/api/openstack/compute/schemas\"\n\n\nclass RelaxNGSchemaTestCase(test.NoDBTestCase):\n \"\"\"various validation tasks for the RelaxNG schemas\n\n lxml.etree has no built-in way to validate an entire namespace\n (i.e., multiple RelaxNG schema files defining elements in the same\n namespace), so we define a few tests that should hopefully reduce\n the risk of an inconsistent namespace\n \"\"\"\n\n def _load_schema(self, schemafile):\n return lxml.etree.RelaxNG(lxml.etree.parse(schemafile))\n\n def _load_test_cases(self, path):\n \"\"\"load test cases from the given path.\"\"\"\n rv = dict(valid=[], invalid=[])\n path = os.path.join(os.path.dirname(__file__), path)\n for ctype in rv.keys():\n for cfile in glob.glob(os.path.join(path, ctype, \"*.xml\")):\n rv[ctype].append(lxml.etree.parse(cfile))\n return rv\n\n def _validate_schema(self, schemafile):\n \"\"\"validate a single RelaxNG schema file.\"\"\"\n try:\n self._load_schema(schemafile)\n except lxml.etree.RelaxNGParseError as err:\n self.fail(\"%s is not a valid RelaxNG schema: %s\" %\n (schemafile, err))\n\n def _api_versions(self):\n \"\"\"get a list of API versions.\"\"\"\n return [''] + [os.path.basename(v)\n for v in glob.glob(os.path.join(SCHEMAS, \"v*\"))]\n\n def _schema_files(self, api_version):\n return glob.glob(os.path.join(SCHEMAS, api_version, \"*.rng\"))\n\n def test_schema_validity(self):\n for api_version in self._api_versions():\n for schema in self._schema_files(api_version):\n self._validate_schema(schema)\n\n def test_schema_duplicate_elements(self):\n for api_version in self._api_versions():\n elements = dict()\n duplicates = dict()\n for schemafile in self._schema_files(api_version):\n schema = lxml.etree.parse(schemafile)\n fname = os.path.basename(schemafile)\n if schema.getroot().tag != \"element\":\n # we don't do any sort of validation on grammars\n # yet\n continue\n el_name = schema.getroot().get(\"name\")\n if el_name in elements:\n duplicates.setdefault(el_name,\n [elements[el_name]]).append(fname)\n else:\n elements[el_name] = fname\n self.assertEqual(len(duplicates), 0,\n \"Duplicate element definitions found: %s\" %\n \"; \".join(\"%s in %s\" % dup\n for dup in duplicates.items()))\n\n def test_schema_explicit_cases(self):\n cases = {'v1.1/flavors.rng': self._load_test_cases(\"v1.1/flavors\"),\n 'v1.1/images.rng': self._load_test_cases(\"v1.1/images\"),\n 'v1.1/servers.rng': self._load_test_cases(\"v1.1/servers\")}\n\n for schemafile, caselists in cases.items():\n schema = self._load_schema(os.path.join(SCHEMAS, schemafile))\n for case in caselists['valid']:\n self.assertTrue(schema.validate(case),\n \"Schema validation failed against %s: %s\\n%s\" %\n (schemafile, schema.error_log, case))\n\n for case in caselists['invalid']:\n self.assertFalse(\n schema.validate(case),\n \"Schema validation succeeded unexpectedly against %s: %s\"\n \"\\n%s\" % (schemafile, schema.error_log, case))\n","sub_path":"nova/tests/unit/api/openstack/compute/schemas/test_schemas.py","file_name":"test_schemas.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413906199","text":"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\ndata = []\nfor i in range(140, 149):\n data += pickle.load(open('data/local/experiment/hopper_restfoot_seed6_seg_target1/mp_rew_' + str(i) + '.pkl', 'rb'))\n\n\nx = []\ny = []\nfor d in data:\n x.append(d[0])\n y.append(d[1])\n\nx = np.array(x)\n\nplt.scatter(x[:,0], x[:, 1], c = y, alpha=0.3)\nplt.colorbar()\nplt.show()\n","sub_path":"examples/test_datacollection.py","file_name":"test_datacollection.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"295629994","text":"import os\r\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\nimport sys\r\n\r\nfrom keras import backend as K\r\nfrom keras.applications import vgg16\r\nfrom keras.layers import Input, merge, BatchNormalization\r\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\r\nfrom keras.layers.core import Activation, Dense, Dropout, Flatten, Lambda\r\nfrom keras.models import Sequential, Model\r\nfrom keras.utils import np_utils\r\nfrom keras.callbacks import CSVLogger, ModelCheckpoint\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfrom random import shuffle\r\nfrom scipy.misc import imresize\r\nimport itertools\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport logging\r\nfrom sklearn.utils import shuffle\r\n\r\nDATA_DIR = \"/home/rsilva/datasets/vqa/\"\r\nIMAGE_DIR = os.path.join(DATA_DIR,\"mscoco\")\r\nLOG_DIR = \"/home/rsilva/logs/\"\r\n\r\nlogging.basicConfig(level=logging.INFO,\r\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\r\n datefmt='%m-%d %H:%M',\r\n filename=os.path.join(LOG_DIR, 'basic_siamese_batch_norm.log'),\r\n filemode='w')\r\nlogger = logging.getLogger(__name__)\r\n\r\ndef get_random_image(img_groups, group_names, gid):\r\n gname = group_names[gid]\r\n photos = img_groups[gname]\r\n pid = np.random.choice(np.arange(len(photos)), size=1)[0]\r\n pname = photos[pid]\r\n return pname\r\n\r\ndef criar_triplas(image_dir):\r\n data = pd.read_csv(lista_imagens, sep=\",\", header=0, names=[\"image_id\",\"filename\",\"category_id\"])\r\n img_groups = {}\r\n \r\n for index, row in data.iterrows():\r\n pid = row[\"filename\"]\r\n gid = row[\"category_id\"]\r\n \r\n if gid in img_groups:\r\n img_groups[gid].append(pid)\r\n else:\r\n img_groups[gid] = [pid]\r\n \r\n pos_triples, neg_triples = [], []\r\n #A triplas positivas são a combinação de imagens com a mesma categoria\r\n for key in img_groups.keys():\r\n triples = [(x[0], x[1], 1) \r\n for x in itertools.combinations(img_groups[key], 2)]\r\n pos_triples.extend(triples)\r\n # é necessário o mesmo número de exemplos negativos\r\n group_names = list(img_groups.keys())\r\n for i in range(len(pos_triples)):\r\n g1, g2 = np.random.choice(np.arange(len(group_names)), size=2, replace=False)\r\n left = get_random_image(img_groups, group_names, g1)\r\n right = get_random_image(img_groups, group_names, g2)\r\n neg_triples.append((left, right, 0))\r\n pos_triples.extend(neg_triples)\r\n shuffle(pos_triples)\r\n return pos_triples \r\ndef carregar_imagem(image_name):\r\n logging.debug(\"carragendo imagem : %s\" % image_name)\r\n if image_name not in image_cache:\r\n logging.debug(\"cache miss\")\r\n image = plt.imread(os.path.join(IMAGE_DIR, image_name)).astype(np.float32)\r\n image = imresize(image, (224, 224))\r\n image = np.divide(image, 256)\r\n image_cache[image_name] = image\r\n else:\r\n logging.debug(\"cache hit\")\r\n return image_cache[image_name]\r\n\r\ndef gerar_triplas_em_lote(image_triples, batch_size, shuffle=False):\r\n logging.info(\"Gerando triplas\")\r\n while True:\r\n \r\n # loop once per epoch\r\n if shuffle:\r\n indices = np.random.permutation(np.arange(len(image_triples)))\r\n else:\r\n indices = np.arange(len(image_triples))\r\n shuffled_triples = [image_triples[ix] for ix in indices]\r\n num_batches = len(shuffled_triples) // batch_size\r\n \r\n logging.info(\"%s batches of %s generated\" % (num_batches, batch_size))\r\n \r\n for bid in range(num_batches):\r\n # loop once per batch\r\n images_left, images_right, labels = [], [], []\r\n batch = shuffled_triples[bid * batch_size : (bid + 1) * batch_size]\r\n for i in range(batch_size):\r\n lhs, rhs, label = batch[i]\r\n images_left.append(carregar_imagem(lhs))\r\n images_right.append(carregar_imagem(rhs)) \r\n labels.append(label)\r\n Xlhs = np.array(images_left)\r\n Xrhs = np.array(images_right)\r\n Y = np_utils.to_categorical(np.array(labels), num_classes=2)\r\n yield ([Xlhs, Xrhs], Y)\r\n\r\ndef calcular_distancia(vecs, normalizar=False):\r\n x, y = vecs\r\n if normalizar:\r\n x = K.l2_normalize(x, axis=0)\r\n y = K.l2_normalize(x, axis=0)\r\n return K.prod(K.stack([x, y], axis=1), axis=1)\r\n\r\ndef formato_saida_distancia(shapes):\r\n return shapes[0]\r\n\r\ndef computar_precisao(predicoes, rotulos):\r\n return rotulos[predicoes.ravel() < 0.5].mean()\r\n\r\ndef criar_instancia_rede_neural(entrada):\r\n seq = Sequential()\r\n \r\n # CONV => RELU => POOL\r\n seq.add(Conv2D(20, kernel_size=5, padding=\"same\", input_shape=entrada))\r\n seq.add(Activation(\"relu\"))\r\n seq.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n \r\n seq.add(BatchNormalization())\r\n\r\n # CONV => RELU => POOL\r\n seq.add(Conv2D(50, kernel_size=5, padding=\"same\"))\r\n seq.add(Activation(\"relu\"))\r\n seq.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n \r\n seq.add(BatchNormalization())\r\n\r\n # Flatten => RELU\r\n seq.add(Flatten())\r\n seq.add(Dense(500))\r\n \r\n return seq\r\n\r\n####################### Inicio da Execucao #######################\r\n\r\nlogger.info(\"####################### Inicio da Execucao #######################\")\r\n\r\nlogging.info(\"Gerando triplas\")\r\nlista_imagens = os.path.join(DATA_DIR, 'train_2014_1k.csv')\r\ntriplas = criar_triplas(lista_imagens)\r\n\r\nlogging.debug(\"# triplas de imagens: %d\" % len(triplas))\r\n\r\nTAMANHO_LOTE = 64 \r\n\r\ndivisor = int(len(triplas) * 0.7)\r\ndados_treino, dados_teste = triplas[0:divisor], triplas[divisor:]\r\n\r\n################### Processamento das Imagens ##################\r\n\r\nformato_entrada = (224, 224, 3)\r\nrede_neural = criar_instancia_rede_neural(formato_entrada)\r\n\r\nimagem_esquerda = Input(shape=formato_entrada)\r\nimagem_direita = Input(shape=formato_entrada)\r\n\r\nvetor_saida_esquerda = rede_neural(imagem_esquerda)\r\nvetor_saida_direita = rede_neural(imagem_direita)\r\n\r\ndistancia = Lambda(calcular_distancia, \r\n output_shape=formato_saida_distancia)([vetor_saida_esquerda, vetor_saida_direita])\r\n\r\n############# Computando os vetorese de similaridade #############\r\n\r\nfc1 = Dense(128, kernel_initializer=\"glorot_uniform\")(distancia)\r\nfc1 = Dropout(0.2)(fc1)\r\nfc1 = Activation(\"relu\")(fc1)\r\n\r\npred = Dense(2, kernel_initializer=\"glorot_uniform\")(fc1)\r\npred = Activation(\"softmax\")(pred)\r\nmodel = Model(inputs=[imagem_esquerda, imagem_direita], outputs=pred)\r\n#model.summary()\r\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\r\n\r\nNUM_EPOCAS = 1 \r\n\r\nimage_cache = {}\r\nlote_de_treinamento = gerar_triplas_em_lote(dados_treino, TAMANHO_LOTE, shuffle=True)\r\nlote_de_validacao = gerar_triplas_em_lote(dados_teste, TAMANHO_LOTE, shuffle=False)\r\n\r\nnum_passos_treinamento = len(dados_treino) // NUM_EPOCAS\r\nnum_passos_validacao = len(dados_teste) // NUM_EPOCAS\r\n\r\ncsv_logger = CSVLogger(os.path.join(LOG_DIR, 'training_epochs_batch_norm.log'))\r\nmodel_checkpoint = ModelCheckpoint(\"models/best_batch_norm.hdf\", monitor='val_acc', verbose=1, save_best_only=True, mode='max')\r\n\r\ncallbacks_list = [csv_logger, model_checkpoint]\r\n\r\nhistorico = model.fit_generator(lote_de_treinamento,\r\n steps_per_epoch=num_passos_treinamento,\r\n epochs=NUM_EPOCAS,\r\n validation_data=lote_de_validacao,\r\n validation_steps=num_passos_validacao,\r\n callbacks=callbacks_list)\r\n\r\nlogging.info(\"Salvando o modelo em disco\")\r\n# serialize model to JSON\r\nmodel_json = model.to_json()\r\nwith open(\"models/vqa_batch_norm.json\", \"w\") as json_file:\r\n json_file.write(model_json)\r\n\r\n# serialize weights to HDF5\r\nmodel.save_weights(\"models/vqa_weights_batch_norm.h5\")\r\nlogging.info(\"Modelo salvo\")\r\n\r\nlogging.info(\"Finalizado\")\r\n","sub_path":"vqa_basic_bn.py","file_name":"vqa_basic_bn.py","file_ext":"py","file_size_in_byte":8092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"456597719","text":"__author__ = 'koohyh'\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef main():\n\n regions_overlapping_up_regulated_genes = ['5:22000000-22250000', '1:167000000-167250000', '1:126500000-126750000',\n '12:71750000-72000000', '5:22250000-22500000']\n regions_overlapping_down_regulated_genes = ['1:194750000-195000000', '8:41000000-41250000', '1:173500000-173750000']\n\n hic_df = read_hic_data(\"/bi/group/sysgen/Hashem/ISP_3D/from_Cshilla/PCA_250kb_P5e-2_delta3sigma_with_scores.txt\",\n regions_overlapping_up_regulated_genes, regions_overlapping_down_regulated_genes)\n\ndef read_hic_data(hic_fname, up_regions, down_regions):\n \"\"\"\n To read the HiC data (from Cshill) and return it as a pandas data frame so that I can compare the z-scores\n and if needed more analysis\n :param hic_fname:\n :up_regions : a list containing ids of regions overlapping with our up-regulated genes\n :down_regions: a list containing ids of regions overlapping with our down-regulated genes.\n :return: hic_df\n \"\"\"\n df = pd.read_csv(hic_fname, header=False, engine='python', sep='\\t')\n\n z1_from_all_regions = df['Z1'].values\n z2_from_all_regions = df['Z2'].values\n Z_ratios_from_all_regions = np.array(np.log(z1_from_all_regions/z2_from_all_regions))\n\n z1_from_up_regions = df[ np.in1d(df['label'], up_regions)]['Z1']\n z2_from_up_regions = df[ np.in1d(df['label'], up_regions)]['Z2']\n z_ratio_from_up_regions = np.array(np.log(z1_from_up_regions/z2_from_up_regions))\n\n print(z_ratio_from_up_regions)\n\n z1_from_down_regions = df[ np.in1d(df['label'], down_regions)]['Z1']\n z2_from_down_regions = df[ np.in1d(df['label'], down_regions)]['Z2']\n z_ratio_from_down_regions = np.array(np.log(z1_from_down_regions/z2_from_down_regions))\n\n z_ratios = np.append(z_ratio_from_up_regions, z_ratio_from_down_regions)\n condition = np.append(['Up' for _ in range(len(z_ratio_from_up_regions))], [\"Down\" for _ in range(len(z_ratio_from_down_regions))])\n up_and_down_df = pd.DataFrame({'ZScore_Ratio':z_ratios, 'condition':condition})\n\n sns.set(style=\"whitegrid\",font_scale=1.5)\n f, (ax1, ax2) = plt.subplots(1, 2)\n ax1.set_xlabel('log(ratio(ZScores))')\n ax1.set_ylabel('Frequency')\n ax1.set_title('Comparison of ZSCores')\n sns.distplot(Z_ratios_from_all_regions, ax=ax1, color='red')\n sns.factorplot(data=up_and_down_df, y='ZScore_Ratio', x='condition', ax=ax2)\n ax2.set_title('Comparison of ZSCores Up and Down Regions')\n ax2.set_ylabel('log(ratio(ZScores))')\n ax2.set_xlabel('Condition')\n plt.grid()\n plt.show()\n\n\n #\n # z1 = df['Z1'].values\n # z2 = df['Z2'].values\n # sns.distplot(z1, color='red', label='Z1', bins=5)\n # sns.distplot(z2, color='blue', label='Z2', bins=5)\n # plt.legend(loc='upper right')\n # plt.show()\n # return(df)\n\nif __name__ == '__main__':\n main()\n","sub_path":"pyChIP/pyChIP/compare_zscores_from_HiC_data.py","file_name":"compare_zscores_from_HiC_data.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"188996920","text":"import numpy as np\r\nfrom PIL import Image\r\nimport util\r\nimport cv2\r\nimport random\r\nimport pyclipper\r\nimport Polygon as plg\r\nimport tensorflow as tf\r\n\r\nctw_root_dir = './data/mtwi/'\r\nctw_train_data_dir = ctw_root_dir + 'train/text_image/'\r\nctw_train_gt_dir = ctw_root_dir + 'train/text_label_curve/'\r\nctw_test_data_dir = ctw_root_dir + 'test/text_image/'\r\nctw_test_gt_dir = ctw_root_dir + 'test/text_label_curve/'\r\n\r\nrandom.seed(123456)\r\n\r\ndef get_img(img_path):\r\n try:\r\n img = cv2.imread(img_path)\r\n img = img[:, :, [2, 1, 0]]\r\n except Exception as e:\r\n print(img_path)\r\n raise\r\n return img\r\n\r\n# #this is for polygon box label\r\n# def get_bboxes(img, gt_path):\r\n# h, w = img.shape[0:2]\r\n# lines = util.io.read_lines(gt_path)\r\n# bboxes = []\r\n# tags = []\r\n# for line in lines:\r\n# line = util.str.remove_all(line, '\\xef\\xbb\\xbf')\r\n# gt = util.str.split(line, ',')\r\n#\r\n# x1 = np.int(gt[0])\r\n# y1 = np.int(gt[1])\r\n#\r\n# bbox = [np.int(gt[i]) for i in range(4, 32)]\r\n# bbox = np.asarray(bbox) + ([x1 * 1.0, y1 * 1.0] * 14)\r\n# bbox = np.asarray(bbox) / ([w * 1.0, h * 1.0] * 14)\r\n#\r\n# bboxes.append(bbox)\r\n# tags.append(True)\r\n# return np.array(bboxes), tags\r\n\r\n\r\n##this is for quadra box label\r\ndef get_bboxes(img, gt_path):\r\n h, w = img.shape[0:2]\r\n lines = util.io.read_lines(gt_path)\r\n bboxes = []\r\n tags = []\r\n for line in lines:\r\n line = util.str.remove_all(line, '\\xef\\xbb\\xbf')\r\n gt = util.str.split(line, ',')\r\n\r\n bbox = [np.float(gt[i]) for i in range(8)]\r\n bbox = np.asarray(bbox) / ([w * 1.0, h * 1.0] * 4)\r\n\r\n bboxes.append(bbox)\r\n tags.append(True)\r\n return np.array(bboxes), tags\r\n\r\n\r\ndef random_horizontal_flip(imgs):\r\n if random.random() < 0.5:\r\n for i in range(len(imgs)):\r\n imgs[i] = np.flip(imgs[i], axis=1).copy()\r\n return imgs\r\n\r\ndef random_rotate(imgs):\r\n max_angle = 10\r\n angle = random.random() * 2 * max_angle - max_angle\r\n for i in range(len(imgs)):\r\n img = imgs[i]\r\n w, h = img.shape[:2]\r\n rotation_matrix = cv2.getRotationMatrix2D((h / 2, w / 2), angle, 1)\r\n img_rotation = cv2.warpAffine(img, rotation_matrix, (h, w))\r\n imgs[i] = img_rotation\r\n return imgs\r\n\r\ndef scale(img, long_size=2240):\r\n h, w = img.shape[0:2]\r\n scale = long_size * 1.0 / max(h, w)\r\n img = cv2.resize(img, dsize=None, fx=scale, fy=scale)\r\n return img\r\n\r\ndef random_scale(img, min_size):\r\n h, w = img.shape[0:2]\r\n if max(h, w) > 1280:\r\n scale = 1280.0 / max(h, w)\r\n img = cv2.resize(img, dsize=None, fx=scale, fy=scale)\r\n\r\n h, w = img.shape[0:2]\r\n random_scale = np.array([0.5, 1.0, 2.0, 3.0])\r\n scale = np.random.choice(random_scale)\r\n if min(h, w) * scale <= min_size:\r\n scale = (min_size + 10) * 1.0 / min(h, w)\r\n img = cv2.resize(img, dsize=None, fx=scale, fy=scale)\r\n return img\r\n\r\ndef random_crop(imgs, img_size):\r\n h, w = imgs[0].shape[0:2]\r\n th, tw = img_size\r\n if w == tw and h == th:\r\n return imgs\r\n \r\n if random.random() > 3.0 / 8.0 and np.max(imgs[1]) > 0:\r\n tl = np.min(np.where(imgs[1] > 0), axis = 1) - img_size\r\n tl[tl < 0] = 0\r\n br = np.max(np.where(imgs[1] > 0), axis = 1) - img_size\r\n br[br < 0] = 0\r\n br[0] = min(br[0], h - th)\r\n br[1] = min(br[1], w - tw)\r\n \r\n i = random.randint(tl[0], br[0])\r\n j = random.randint(tl[1], br[1])\r\n else:\r\n i = random.randint(0, h - th)\r\n j = random.randint(0, w - tw)\r\n \r\n # return i, j, th, tw\r\n for idx in range(len(imgs)):\r\n if len(imgs[idx].shape) == 3:\r\n imgs[idx] = imgs[idx][i:i + th, j:j + tw, :]\r\n else:\r\n imgs[idx] = imgs[idx][i:i + th, j:j + tw]\r\n return imgs\r\n\r\ndef dist(a, b):\r\n return np.sqrt(np.sum((a - b) ** 2))\r\n\r\ndef perimeter(bbox):\r\n peri = 0.0\r\n for i in range(bbox.shape[0]):\r\n peri += dist(bbox[i], bbox[(i + 1) % bbox.shape[0]])\r\n return peri\r\n\r\ndef shrink(bboxes, rate, max_shr=20):\r\n rate = rate * rate\r\n shrinked_bboxes = []\r\n for bbox in bboxes:\r\n area = plg.Polygon(bbox).area()\r\n peri = perimeter(bbox)\r\n\r\n pco = pyclipper.PyclipperOffset()\r\n pco.AddPath(bbox, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)\r\n offset = min((int)(area * (1 - rate) / (peri + 0.001) + 0.5), max_shr)\r\n \r\n shrinked_bbox = pco.Execute(-offset)\r\n if len(shrinked_bbox) == 0:\r\n shrinked_bboxes.append(bbox)\r\n continue\r\n \r\n shrinked_bbox = np.array(shrinked_bbox[0])\r\n if shrinked_bbox.shape[0] <= 2:\r\n shrinked_bboxes.append(bbox)\r\n continue\r\n \r\n shrinked_bboxes.append(shrinked_bbox)\r\n \r\n return np.array(shrinked_bboxes)\r\n\r\nclass CTW1500Loader():\r\n def __init__(self, is_transform=False, img_size=None, kernel_num=7, min_scale=0.4):\r\n self.is_transform = is_transform\r\n \r\n self.img_size = img_size if (img_size is None or isinstance(img_size, tuple)) else (img_size, img_size)\r\n self.kernel_num = kernel_num\r\n self.min_scale = min_scale\r\n\r\n data_dirs = [ctw_train_data_dir]\r\n gt_dirs = [ctw_train_gt_dir]\r\n \r\n self.img_paths = []\r\n self.gt_paths = []\r\n\r\n for data_dir, gt_dir in zip(data_dirs, gt_dirs):\r\n img_names = util.io.ls(data_dir, '.jpg')\r\n img_names.extend(util.io.ls(data_dir, '.png'))\r\n # img_names.extend(util.io.ls(data_dir, '.gif'))\r\n\r\n img_paths = []\r\n gt_paths = []\r\n for idx, img_name in enumerate(img_names):\r\n img_path = data_dir + img_name\r\n img_paths.append(img_path)\r\n\r\n gt_name = img_name.split('.jpg')[0] + '.txt'\r\n gt_path = gt_dir + gt_name\r\n gt_paths.append(gt_path)\r\n\r\n self.img_paths.extend(img_paths)\r\n self.gt_paths.extend(gt_paths)\r\n \r\n\r\n def __len__(self):\r\n return len(self.img_paths)\r\n\r\n def __getitem__(self, index):\r\n img_path = self.img_paths[index]\r\n gt_path = self.gt_paths[index]\r\n\r\n img = get_img(img_path)\r\n bboxes, tags = get_bboxes(img, gt_path)\r\n \r\n if self.is_transform:\r\n img = random_scale(img, self.img_size[0])\r\n\r\n gt_text = np.zeros(img.shape[0:2], dtype='uint8')\r\n training_mask = np.ones(img.shape[0:2], dtype='uint8')\r\n if bboxes.shape[0] > 0:\r\n #bboxes = np.reshape(bboxes * ([img.shape[1], img.shape[0]] * 14), (bboxes.shape[0], bboxes.shape[1] / 2, 2)).astype('np.int32')\r\n #bboxes = bboxes * ([img.shape[1], img.shape[0]] * 14)\r\n bboxes = bboxes * ([img.shape[1], img.shape[0]] * 4)\r\n bboxes = bboxes.reshape((bboxes.shape[0], np.int(bboxes.shape[1] / 2), 2)).astype('int32')\r\n for i in range(bboxes.shape[0]):\r\n cv2.drawContours(gt_text, [bboxes[i]], -1, i + 1, -1)\r\n if not tags[i]:\r\n cv2.drawContours(training_mask, [bboxes[i]], -1, 0, -1)\r\n \r\n gt_kernals = []\r\n for i in range(1, self.kernel_num):\r\n rate = 1.0 - (1.0 - self.min_scale) / (self.kernel_num - 1) * i\r\n gt_kernal = np.zeros(img.shape[0:2], dtype='uint8')\r\n kernal_bboxes = shrink(bboxes, rate)\r\n for i in range(bboxes.shape[0]):\r\n cv2.drawContours(gt_kernal, [kernal_bboxes[i]], -1, 1, -1)\r\n gt_kernals.append(gt_kernal)\r\n\r\n if self.is_transform:\r\n imgs = [img, gt_text, training_mask]\r\n imgs.extend(gt_kernals)\r\n\r\n imgs = random_horizontal_flip(imgs)\r\n imgs = random_rotate(imgs)\r\n imgs = random_crop(imgs, self.img_size)\r\n\r\n img, gt_text, training_mask, gt_kernals = imgs[0], imgs[1], imgs[2], imgs[3:]\r\n \r\n gt_text[gt_text > 0] = 1\r\n gt_kernals = np.array(gt_kernals)\r\n \r\n if self.is_transform:\r\n img = (img / 255.).astype('float32')\r\n img = tf.image.random_brightness(img, 32.0/255)\r\n img = tf.image.random_saturation(img, 0.5, 1.5)\r\n\r\n mean = tf.constant([0.485, 0.456, 0.406])\r\n std = tf.constant([0.229, 0.224, 0.225])\r\n img = (img - mean) / std\r\n\r\n gt_text = tf.convert_to_tensor(gt_text, dtype=tf.float32)\r\n gt_kernals = tf.convert_to_tensor(gt_kernals, dtype=tf.float32)\r\n training_mask = tf.convert_to_tensor(training_mask, dtype=tf.float32)\r\n\r\n return img, gt_text, gt_kernals, training_mask\r\n \r\ndef ctw_train_loader(dataset, batch_size, shuffle=True, drop_last=True): # shuffle, drop_last 的判断省略\r\n data_length = len(dataset)\r\n num_iter = data_length // batch_size\r\n shf = np.arange(data_length)\r\n np.random.shuffle(shf)\r\n for i in range(num_iter):\r\n imgs, gt_texts, gt_kernals, training_masks = [], [], [], []\r\n for j in range(batch_size):\r\n sample = dataset[shf[i*batch_size+j]]\r\n #imgs.append(tf.transpose(sample[0],(2,0,1)))\r\n imgs.append(sample[0])\r\n gt_texts.append(sample[1])\r\n gt_kernals.append(sample[2])\r\n #gt_kernals.append(tf.transpose(sample[2],(1,2,0)))\r\n training_masks.append(sample[3])\r\n imgs = tf.stack(imgs, 0)\r\n gt_texts = tf.stack(gt_texts, 0)\r\n gt_kernals = tf.stack(gt_kernals, 0)\r\n training_masks = tf.stack(training_masks, 0)\r\n yield imgs, gt_texts, gt_kernals, training_masks, data_length","sub_path":"dataset/mtwi_loader.py","file_name":"mtwi_loader.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"292457087","text":"import socket\r\nimport json, types,string\r\nHOST = '127.0.0.1'\r\nPORT = 7000\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\ns.bind((HOST, PORT))\r\ns.listen(5)\r\n\r\nprint('server start at: %s:%s' % (HOST, PORT))\r\nprint('wait for connection...')\r\n\r\nwhile True:\r\n conn, addr = s.accept()\r\n print('connected by ' + str(addr))\r\n\r\n while True:\r\n indata = conn.recv(1024)\r\n if len(indata) == 0: # connection closed\r\n conn.close()\r\n print('client closed connection.')\r\n break\r\n jdata = json.loads(indata)\r\n print (\"Receive jdata from '%r'\" %(jdata))\r\n #print('recv: ' + indata.decode())\r\n\r\n outdata = 'echo ' + indata.decode()\r\n conn.send(outdata.encode())\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"442278405","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 02.04.2015\n\n@author: Andreas\n'''\n\nimport sys\nimport codecs\nimport logging\nfrom nltk.util import ngrams\nfrom nltk.tag import pos_tag\nfrom nltk.tokenize import word_tokenize\nfrom config import config\nfrom config.config import word_ngram_prefix,character_ngram_prefix, pos_tag_prefix\nfrom config.config import fv_basis\n\nlogger = logging.getLogger(__name__)\n\ntweets = [] # a list of all tweets (String, not Tweet object)\ntokens = set() # a set of all tokens in the svm data\n\ndef generate_fv_basis(fp):\n global tweets,tokens\n extract_tweets_and_tokens(fp)\n create_feature_vector_basis_file()\n \"\"\" cleanup \"\"\"\n tweets = []\n tokens = set()\n \ndef create_feature_vector_basis_file():\n add_word_ngrams(5,4,3,2)\n add_char_ngrams(6,5,4,3,2)\n add_pos_categories()\n\ndef remove_unavailable_tweets(fpin,fpout,train_data_limit=0):\n \"\"\"\n Cleans an input file of all lines with \"Not Available\" and writes a new file containing only all other lines.\n \n Keyword arguments:\n train_data_limit -- specifies how man tweets (lines) the output file will contain. \n A value of 0 (zero) equals all tweets (lines).\n \"\"\"\n fin = codecs.open(fpin, 'r', \"utf-8\")\n fout = codecs.open(fpout,'w', \"utf-8\")\n \n if train_data_limit == 0: train_data_limit = sys.maxint\n counter = 0\n for line in fin: \n if counter < train_data_limit:\n tmp = line.rstrip().split(\"\\t\")\n if tmp[3] != \"Not Available\":\n fout.write(line)\n counter += 1 \n fin.close()\n fout.close()\n \ndef extract_tweets_and_tokens(fp):\n global tweets\n global tokens\n f = codecs.open(fp, 'r', \"utf-8\")\n for i,line in enumerate(f):\n if i= thresholds[i]:\n f.write(word_ngram_prefix+\" \".join(key)+\"\\n\")\n logger.debug(word_ngram_prefix+\" \".join(key))\n f.close()\n\ndef add_char_ngrams(uni_threshold=500,bi_threshold=300,tri_threshold=150,four_threshold=100,five_threshold=50):\n \"\"\"Writes a file containing all character-1-5-grams above or equal to a certain threshold. \n Thresholds can be defined individually. Based on the data of the global variable \"tweets\".\n\n Keyword arguments:\n uni_threshold -- character unigram occurence threshold necessary to be included in the output file\n bi_threshold -- ...\n \"\"\"\n uni, bi, tri, four, five = ({},{},{},{},{})\n ngram_list = [uni,bi,tri,four,five]\n thresholds = [uni_threshold,bi_threshold,tri_threshold,four_threshold,five_threshold]\n global tokens\n \n # generate char_ngrams and save them in the respective dictionaries\n for token in tokens:\n for n in range (1,6):\n tmp = ngrams(token,n)\n for charseq in tmp:\n if charseq in ngram_list[n-1]:\n ngram_list[n-1][charseq] += 1\n else:\n ngram_list[n-1][charseq] = 1\n \n # print dictionaries to file\n f = codecs.open(fv_basis, 'a', \"utf-8\")\n for i, dic in enumerate(ngram_list):\n for key in sorted(dic):\n if dic[key] >= thresholds[i]:\n f.write(character_ngram_prefix+\"\".join(key)+\"\\n\")\n logger.debug(character_ngram_prefix+\"\".join(key))\n f.close()\n\ndef add_pos_categories():\n global tweets\n pos_tags = set()\n for tweet in tweets: \n tweet_pos_tagged = pos_tag(word_tokenize(tweet))\n for pair in tweet_pos_tagged:\n pos_tags.add(pair[1])\n # print dictionaries to file\n f = codecs.open(fv_basis, 'a', \"utf-8\")\n for item in pos_tags:\n f.write(pos_tag_prefix+item+\"\\n\")\n logger.debug(pos_tag_prefix+item)\n f.close()","sub_path":"src/preprocessing/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"48926796","text":"import xlsxwriter\nimport datetime\n\n\nclass PortfolioExporter(object):\n\n def __init__(self, longs, shorts):\n self.workbook = None\n self.longs = longs\n self.shorts = shorts\n\n def export(self, analyst, direction):\n filename = \"aim best ideas {} {}.xlsx\".format(analyst, direction)\n output_path = \"/var/www/output/{}\".format(filename)\n self.workbook = xlsxwriter.Workbook(output_path)\n try:\n self.__write_headers('Sheet1')\n self.__write_data('Sheet1', direction, analyst)\n except Exception as e:\n print(str(e))\n finally:\n self.workbook.close()\n return output_path, filename\n\n def __write_headers(self, sheet):\n worksheet = self.workbook.add_worksheet(sheet)\n merge_format = self.workbook.add_format({'bold': 1, 'align': 'center', 'valign': 'vcenter', 'border': 1})\n worksheet.write('A1', 'Portfolio Name', merge_format)\n worksheet.write('B1', 'Security ', merge_format)\n worksheet.write('C1', 'Weight', merge_format)\n worksheet.write('D1', 'Date', merge_format)\n worksheet.write('E1', 'Reason For Change', merge_format)\n worksheet.write('F1', 'CDE Weight', merge_format)\n worksheet.write('G1', 'CDE Portfolio Name', merge_format)\n\n def __write_data(self, sheet, direction, analyst):\n worksheet = self.workbook.get_worksheet_by_name(sheet)\n percentage_format = self.workbook.add_format()\n percentage_format.set_num_format(0x0a)\n count = 2\n\n if direction == 'long':\n for stock, (weight, rfc) in self.longs.items():\n worksheet.write('A{}'.format(count), 'AIM BEST IDEAS {} LONG'.format(analyst))\n worksheet.write('B{}'.format(count), stock)\n worksheet.write('C{}'.format(count), weight*100)\n now = datetime.datetime.now()\n worksheet.write('D{}'.format(count), now.strftime('%m/%d/%y'))\n worksheet.write('E{}'.format(count), rfc)\n worksheet.write('F{}'.format(count), weight*100)\n worksheet.write('G{}'.format(count), 'AIM BEST IDEAS {} LONG'.format(analyst))\n count += 1\n elif direction == 'short':\n for stock, (weight, rfc) in self.shorts.items():\n worksheet.write('A{}'.format(count), 'AIM BEST IDEAS {} SHORT'.format(analyst))\n worksheet.write('B{}'.format(count), stock)\n worksheet.write('C{}'.format(count), -weight*100)\n now = datetime.datetime.now()\n worksheet.write('D{}'.format(count), now.strftime('%m/%d/%y'))\n worksheet.write('E{}'.format(count), rfc)\n worksheet.write('F{}'.format(count), -weight*100)\n worksheet.write('G{}'.format(count), 'AIM BEST IDEAS {} SHORT'.format(analyst))\n count += 1\n\n","sub_path":"exporter/portfolio/portfolio_exporter.py","file_name":"portfolio_exporter.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"428167706","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2016 NORDUnet A/S\n# Copyright (c) 2018 SUNET\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# 3. Neither the name of the NORDUnet nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\nimport json\nfrom typing import Any, Dict, Mapping, Optional\n\nfrom mock import patch\n\nfrom eduid_common.api.exceptions import ApiException\nfrom eduid_common.api.testing import EduidAPITestCase\n\nfrom eduid_webapp.personal_data.app import PersonalDataApp, pd_init_app\n\n\nclass PersonalDataTests(EduidAPITestCase):\n app: PersonalDataApp\n\n def setUp(self):\n super(PersonalDataTests, self).setUp(copy_user_to_private=True)\n\n def load_app(self, config: Mapping[str, Any]) -> PersonalDataApp:\n \"\"\"\n Called from the parent class, so we can provide the appropriate flask\n app for this test case.\n \"\"\"\n return pd_init_app('testing', config)\n\n def update_config(self, config: Dict[str, Any]) -> Dict[str, Any]:\n config.update(\n {\n 'available_languages': {'en': 'English', 'sv': 'Svenska'},\n 'msg_broker_url': 'amqp://dummy',\n 'am_broker_url': 'amqp://dummy',\n 'celery_config': {'result_backend': 'amqp', 'task_serializer': 'json'},\n }\n )\n return config\n\n # parameterized test methods\n\n def _get_user(self, eppn: Optional[str] = None):\n \"\"\"\n Send a GET request to get the personal data of a user\n\n :param eppn: the eppn of the user\n \"\"\"\n response = self.browser.get('/user')\n self.assertEqual(response.status_code, 302) # Redirect to token service\n\n eppn = eppn or self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n response2 = client.get('/user')\n\n return json.loads(response2.data)\n\n def _get_user_all_data(self, eppn: Optional[str] = None):\n \"\"\"\n Send a GET request to get all the data of a user\n\n :param eppn: the eppn of the user\n \"\"\"\n response = self.browser.get('/all-user-data')\n self.assertEqual(response.status_code, 302) # Redirect to token service\n\n eppn = eppn or self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n response2 = client.get('/all-user-data')\n\n return json.loads(response2.data)\n\n @patch('eduid_common.api.am.AmRelay.request_user_sync')\n def _post_user(self, mock_request_user_sync: Any, mod_data: Optional[dict] = None):\n \"\"\"\n POST personal data for some user\n\n :param eppn: the eppn of the user\n \"\"\"\n mock_request_user_sync.side_effect = self.request_user_sync\n eppn = self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n with self.app.test_request_context():\n with client.session_transaction() as sess:\n data = {\n 'given_name': 'Peter',\n 'surname': 'Johnson',\n 'display_name': 'Peter Johnson',\n 'language': 'en',\n 'csrf_token': sess.get_csrf_token(),\n }\n if mod_data:\n data.update(mod_data)\n response = client.post('/user', data=json.dumps(data), content_type=self.content_type_json)\n return json.loads(response.data)\n\n def _get_user_nins(self, eppn: Optional[str] = None):\n \"\"\"\n GET a list of all the nins of some user\n\n :param eppn: the eppn of the user\n \"\"\"\n response = self.browser.get('/nins')\n self.assertEqual(response.status_code, 302) # Redirect to token service\n\n eppn = eppn or self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n response2 = client.get('/nins')\n\n return json.loads(response2.data)\n\n # actual test methods\n\n def test_get_user(self):\n user_data = self._get_user()\n self.assertEqual(user_data['type'], 'GET_PERSONAL_DATA_USER_SUCCESS')\n self.assertEqual(user_data['payload']['given_name'], 'John')\n self.assertEqual(user_data['payload']['surname'], 'Smith')\n self.assertEqual(user_data['payload']['display_name'], 'John Smith')\n self.assertEqual(user_data['payload']['language'], 'en')\n # Check that unwanted data is not serialized\n self.assertIsNotNone(self.test_user.to_dict().get('passwords'))\n self.assertIsNone(user_data['payload'].get('passwords'))\n\n def test_get_unknown_user(self):\n with self.assertRaises(ApiException):\n self._get_user(eppn='fooo-fooo')\n\n def test_get_user_all_data(self):\n user_data = self._get_user_all_data()\n self.assertEqual(user_data['type'], 'GET_PERSONAL_DATA_ALL_USER_DATA_SUCCESS')\n self.assertEqual(user_data['payload']['given_name'], 'John')\n self.assertEqual(user_data['payload']['surname'], 'Smith')\n self.assertEqual(user_data['payload']['display_name'], 'John Smith')\n self.assertEqual(user_data['payload']['language'], 'en')\n phones = user_data['payload']['phones']\n self.assertEqual(len(phones), 2)\n self.assertEqual(phones[0]['number'], u'+34609609609')\n self.assertTrue(phones[0]['verified'])\n nins = user_data['payload']['nins']\n self.assertEqual(len(nins), 2)\n self.assertEqual(nins[0]['number'], u'197801011234')\n self.assertTrue(nins[0]['verified'])\n emails = user_data['payload']['emails']\n self.assertEqual(len(emails), 2)\n self.assertEqual(emails[0]['email'], u'johnsmith@example.com')\n self.assertTrue(emails[0]['verified'])\n\n # Check that unwanted data is not serialized\n self.assertIsNotNone(self.test_user.to_dict().get('passwords'))\n self.assertIsNone(user_data['payload'].get('passwords'))\n\n def test_get_unknown_user_all_data(self):\n with self.assertRaises(ApiException):\n self._get_user_all_data(eppn='fooo-fooo')\n\n def test_post_user(self):\n resp_data = self._post_user()\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_SUCCESS')\n self.assertEqual(resp_data['payload']['surname'], 'Johnson')\n self.assertEqual(resp_data['payload']['given_name'], 'Peter')\n self.assertEqual(resp_data['payload']['display_name'], 'Peter Johnson')\n self.assertEqual(resp_data['payload']['language'], 'en')\n\n def test_post_user_bad_csrf(self):\n resp_data = self._post_user(mod_data={'csrf_token': 'wrong-token'})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['csrf_token'], ['CSRF failed to validate'])\n\n def test_post_user_no_given_name(self):\n resp_data = self._post_user(mod_data={'given_name': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['given_name'], ['pdata.field_required'])\n\n def test_post_user_blank_given_name(self):\n resp_data = self._post_user(mod_data={'given_name': ' '})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['given_name'], ['pdata.field_required'])\n\n def test_post_user_no_surname(self):\n resp_data = self._post_user(mod_data={'surname': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['surname'], ['pdata.field_required'])\n\n def test_post_user_blank_surname(self):\n resp_data = self._post_user(mod_data={'surname': ' '})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['surname'], ['pdata.field_required'])\n\n def test_post_user_no_display_name(self):\n resp_data = self._post_user(mod_data={'display_name': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['display_name'], ['pdata.field_required'])\n\n def test_post_user_no_language(self):\n resp_data = self._post_user(mod_data={'language': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['language'], [\"Language '' is not available\"])\n\n def test_post_user_unknown_language(self):\n resp_data = self._post_user(mod_data={'language': 'es'})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['language'], [\"Language 'es' is not available\"])\n\n def test_get_user_nins(self):\n nin_data = self._get_user_nins()\n self.assertEqual(nin_data['type'], 'GET_PERSONAL_DATA_NINS_SUCCESS')\n self.assertEqual(nin_data['payload']['nins'][1]['number'], '197801011235')\n self.assertEqual(len(nin_data['payload']['nins']), 2)\n","sub_path":"src/eduid_webapp/personal_data/tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":10627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"484545018","text":"import unittest.mock\nimport xml.etree.ElementTree as ET\nfrom broadsoft.requestobjects.UserThirdPartyVoiceMailSupportModifyRequest import UserThirdPartyVoiceMailSupportModifyRequest\n\n\nclass TestUserThirdPartyVoiceMailSupportModifyRequest(unittest.TestCase):\n def test_validate(self):\n u = UserThirdPartyVoiceMailSupportModifyRequest()\n with self.assertRaises(ValueError):\n u.validate()\n\n @unittest.mock.patch.object(UserThirdPartyVoiceMailSupportModifyRequest, 'validate')\n def test_build_command_xml_calls_validate(\n self,\n validate_patch\n ):\n u = UserThirdPartyVoiceMailSupportModifyRequest(sip_user_id='6175551212@broadsoft-dev.mit.edu')\n u.build_command_xml()\n self.assertTrue(validate_patch.called)\n\n def test_build_command_xml(self):\n self.maxDiff = None\n u = UserThirdPartyVoiceMailSupportModifyRequest(sip_user_id='6175551212@broadsoft-dev.mit.edu',\n is_active=True, busy_redirect_to_voice_mail=False,\n no_answer_redirect_to_voice_mail=True,\n server_selection='User Specific Mail Server',\n user_server='617-253-0000',\n mailbox_id_type='User Or Group Phone Number',\n no_answer_number_of_rings=3, always_redirect_to_voice_mail=False,\n out_of_primary_zone_redirect_to_voice_mail=True)\n target_xml = \\\n '' + \\\n '6175551212@broadsoft-dev.mit.edu' + \\\n 'true' + \\\n 'false' + \\\n 'true' + \\\n 'User Specific Mail Server' + \\\n '6172530000' + \\\n 'User Or Group Phone Number' + \\\n '3' +\\\n 'false' + \\\n 'true' + \\\n ''\n\n xml = u.to_xml()\n cmd = xml.findall('./command')[0]\n self.assertEqual(\n target_xml,\n ET.tostring(cmd).decode('utf-8')\n )\n\n # change the results to ensure no mix ups\n u = UserThirdPartyVoiceMailSupportModifyRequest(sip_user_id='6175551213@broadsoft-dev.mit.edu',\n is_active=False, busy_redirect_to_voice_mail=True,\n no_answer_redirect_to_voice_mail=False,\n server_selection='garbanzo',\n user_server='617-253-0001',\n mailbox_id_type='ham',\n no_answer_number_of_rings=4,\n always_redirect_to_voice_mail=True,\n out_of_primary_zone_redirect_to_voice_mail=False)\n target_xml = \\\n '' + \\\n '6175551213@broadsoft-dev.mit.edu' + \\\n 'false' + \\\n 'true' + \\\n 'false' + \\\n 'garbanzo' + \\\n '6172530001' + \\\n 'ham' + \\\n '4' + \\\n 'true' + \\\n 'false' + \\\n ''\n\n xml = u.to_xml()\n cmd = xml.findall('./command')[0]\n self.assertEqual(\n target_xml,\n ET.tostring(cmd).decode('utf-8')\n )\n","sub_path":"broadsoft/tests/requestobjects/test_UserThirdPartyVoiceMailSupportModifyRequest.py","file_name":"test_UserThirdPartyVoiceMailSupportModifyRequest.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"524054721","text":"# There are 4 lanes on the bridge road and 1 to 4 bikes to control. There can\r\n# only be one moto per lane and they are always vertically aligned.\r\n\r\n# Each game turn, you can send a single instruction to every bike. Since the\r\n# bikes operate on the same frequency, they will all synchronize on the\r\n# commands you send them.\r\n\r\n# The possible commands are:\r\n# - SPEED to speed up by 1.\r\n# - SLOW to slow down by 1.\r\n# - JUMP to jump.\r\n# - WAIT to go straight on.\r\n# - UP to send all motorbikes one lane up.\r\n# - DOWN to send all motorbikes one lane down.\r\n\r\n# The starting speeds of the bikes are synced, and can be 0. After every game\r\n# turn, the bikes will move a number of squares equal to their current speed\r\n# across the X axis.\r\n\r\n# The UP and DOWN instructions will make the bikes move across the Y axis i\r\n# addition to the movement across the X axis (Y = 0 corresponds to the highest\r\n# lane). If a motorbike is prevented from moving up or down by the bridge's\r\n# guard rails, none of the bikes will move on the Y axis that turn.\r\n\r\n# When a motorbike goes in a straight line and does not jump, if there is a\r\n# hole between the current position and the next position (after the move),\r\n# then the motorbike is lost forever. For example, if X=2 and S=3, the next\r\n# position of the bike will have X=5: if there is a hole in X=3, X=4 or X=5,\r\n# the bike will be destroyed.\r\n\r\n# Going up or down will put you at risk of falling in any hole situated in the\r\n# black zone (consider the holes on the current and next lane):\r\n# - The mission is a success if the minimum amount of required bikes gets to\r\n# the far side of the bridge.\r\n# - You fail if too many motorbikes fall into holes.\r\n# - You fail if the motorbikes do not cross the entire bridge after 50 turns.\r\n\r\n\r\nfrom itertools import product\r\n\r\n\r\nM = int(input())\r\ninput()\r\nroad = [input() for _ in range(4)]\r\nend = len(road[0])\r\nACTIONS = ['SPEED', 'UP', 'DOWN', 'JUMP', 'SLOW']\r\n\r\nwhile 1:\r\n speed = int(input())\r\n bikes = [list(map(int, input().split())) for i in range(M)]\r\n heuristics = {k: 0 for k in product(ACTIONS, ACTIONS, ACTIONS, ACTIONS)}\r\n for k in heuristics:\r\n t_speed = speed\r\n t_alive = [b[:] for b in bikes if b[2]]\r\n x = t_alive[0][0]\r\n for action in k:\r\n if t_alive:\r\n if action == 'SPEED':\r\n t_speed += 1\r\n for _, y, a in t_alive:\r\n if '0' in road[y][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n heuristics[k] += 1\r\n elif action == 'SLOW':\r\n t_speed -= 1\r\n if t_speed > 1:\r\n for _, y, a in t_alive:\r\n if '0' in road[y][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n heuristics[k] += 1\r\n else:\r\n heuristics[k] -= 10\r\n elif action == 'UP':\r\n if t_alive[0][1]:\r\n for i, (_, y, a) in enumerate(t_alive):\r\n if '0' in road[y][x+1:min(end, x+t_speed)] + road[y-1][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n t_alive[i] = [x, y-1, 1]\r\n heuristics[k] += 1\r\n else:\r\n action = 'JUMP'\r\n elif action == 'DOWN':\r\n if t_alive[-1][1] < len(road)-1:\r\n for i, (_, y, a) in enumerate(t_alive):\r\n if '0' in road[y][x+1:min(end, x+t_speed)] + road[y+1][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n t_alive[i] = [x, y+1, 1]\r\n heuristics[k] += 1\r\n else:\r\n action = 'JUMP'\r\n elif action == 'JUMP':\r\n for _, y, a in t_alive:\r\n if x + t_speed < end and road[y][x+t_speed] == '0':\r\n t_alive.remove([_, y, a])\r\n else:\r\n heuristics[k] += 1\r\n x += t_speed\r\n \r\n best = max(heuristics, key=lambda k:(heuristics[k], -ACTIONS.index(k[0])))\r\n print(best[0])","sub_path":"CG/hard_the-bridge-episode-2.py","file_name":"hard_the-bridge-episode-2.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"466141680","text":"print(\"Starting Py program\")\n\ndef f():\n x=1\n y=2\n if(x==1):\n t= x+y\n print(\"here\")\n return t\nx=1+3*100/2+f()\ny=x*100+10*3\nprint(\"x=\",x)\nprint(\"y=\",y)","sub_path":"hw4/hw2_testcase.py","file_name":"hw2_testcase.py","file_ext":"py","file_size_in_byte":174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"506465523","text":"import site\r\nimport socket\r\n\r\nif socket.gethostbyaddr(socket.gethostname())[0] == 'QFR1L0611.viola.local':\r\n site.addsitedir('/home/rk/pylib')\r\nelse:\r\n site.addsitedir(\"D:\\\\Analytics\\\\NetworkAnalytics\\\\trunk\\\\UserSpace\\\\Kelzenberg\\\\pylib\")\r\n\r\nimport mx.DateTime.Feasts as feasts\r\nimport matplotlib as mpl\r\nfrom datetime import date, datetime, timedelta\r\n#from scipy import sin\r\nimport matplotlib.pyplot as plt\r\nimport numpy\r\nfrom scipy import signal, convolve\r\nfrom matplotlib.dates import date2num, num2date\r\nfrom oracle_connect import get_oracle_cursor_rkna1\r\nfrom scipy import optimize\r\nimport xlwt\r\n\r\nmpl.rcParams['font.size'] = 8.0\r\nmpl.rcParams['figure.figsize'] = 12.69, 8.27\r\nmpl.rcParams['savefig.dpi'] = 300\r\nmpl.rcParams['pdf.compression'] = 3\r\nmpl.rcParams['pdf.fonttype'] = 42\r\n\r\nlbound = lambda p, x: 1e4 * numpy.sqrt(p - x) + 1e-3 * (p - x) if (x < p) else 0\r\nubound = lambda p, x: 1e4 * numpy.sqrt(x - p) + 1e-3 * (x - p) if (x > p) else 0\r\nbound = lambda p, x: lbound(p[0], x) + ubound(p[1], x)\r\nfixed = lambda p, x: bound((p, p), x)\r\n\r\n\r\nticketfilter = \"\"\"\r\nA_AUFTRAGSKLASSE = 'SK'\r\nand A_BEARBEITUNGSZUSTAND <> 'st'\r\nand a_orgetyp = 'P'\r\nand a_auftragsart = 'Aufgabe'\r\n\"\"\"\r\n\r\nlinear = lambda p, x: p[0]*(x - p[-1]) + p[1]\r\nsquared = lambda p, x: p[0]*(x - p[-1]) ** 2 + p[1]*(x - p[-1]) + p[2]\r\nsineline = lambda p, x: (p[0]*numpy.sin(2 * numpy.pi * (x - p[-1]) / p[1] + p[2]) + p[4]) * p[3]*(x - p[-1]) + p[5]\r\nexponential = lambda p, x: p[0]*p[1]**(x - p[-1]) + p[2]\r\n\r\n\r\ndef holiday_correction(dates, values, reduction):\r\n for i in range(len(dates)):\r\n if isinstance(dates[i], float):\r\n datum = num2date(dates[i])\r\n datum = datetime(datum.year, datum.month, datum.day)\r\n else:\r\n datum = dates[i]\r\n year = datum.year\r\n himmelfahrt = feasts.Himmelfahrt(year)\r\n himmelfahrt = datetime(year, himmelfahrt.month, himmelfahrt.day)\r\n karfreitag = feasts.Karfreitag(year)\r\n karfreitag = datetime(year, karfreitag.month, karfreitag.day)\r\n ostermontag = feasts.Ostermontag(year)\r\n ostermontag = datetime(year, ostermontag.month, ostermontag.day)\r\n fronleichnam = feasts.Fronleichnam(year)\r\n fronleichnam = datetime(year, fronleichnam.month, fronleichnam.day)\r\n pfingstmontag = feasts.Pfingstmontag(year)\r\n pfingstmontag = datetime(year, pfingstmontag.month, pfingstmontag.day)\r\n feiertage = [datetime(year, 1, 1), datetime(year, 5, 1), datetime(year, 10, 3),\r\n datetime(year, 11, 1), datetime(year, 10, 31), #allerheiligen, reformationstag .. .\r\n datetime(year, 12, 25), datetime(year, 12, 26),\r\n datetime(year, 12, 24), datetime(year, 12, 31),\r\n himmelfahrt, fronleichnam, karfreitag, ostermontag, pfingstmontag]\r\n #feiertage = [x for x in feiertage if x.weekday() not in (5, 6)]\r\n if set([datum + timedelta(days=x) for x in range(5)]).intersection(set(feiertage)):\r\n values[i] = values[i]*reduction\r\n\r\n\r\ndef getdesc(p):\r\n if len(p) != 7:\r\n return \"\"\r\n phase = num2date(p[-1] - p[2] / 2 / numpy.pi)\r\n parameters = \"Offset: {:d}, Base: {:d}, Amplitude {:d}: Increase: {:.4}/day, Phase: {}, Period: {:d} days\"\r\n return parameters.format(int(round(p[5])), int(round(p[4])), int(round(p[0])), p[3], phase, int(round(p[1])))\r\n\r\nkai = {}\r\nkai[\"dienstkategorie\"] = 'KAI'\r\nkai[\"holidaycorrection\"] = 1#0.85\r\nkai[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nkai[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nkai[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [sineline, [100, 300, 0, 0, 100, 0], datetime(2010, 4, 10), datetime(2011, 10, 4),\r\n datetime(2010, 4, 10), datetime(2012, 2, 1), \"forecast\", \"r\", 0]\r\n ]\r\nkai[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n ]\r\n\r\nkav = {}\r\nkav[\"dienstkategorie\"] = 'KAV'\r\nkav[\"holidaycorrection\"] = 1#0.85\r\nkav[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nkav[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nkav[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\", \"color\", \"errors\"],\r\n [sineline, [50, 300, 0, 0, 100, 0], datetime(2010, 4, 10), datetime(2011, 10, 4),\r\n datetime(2010, 4, 10), datetime(2012, 2, 1), \"forecast\", \"r\", 0]\r\n ]\r\nkav[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n ]\r\n\r\nhdw = {}\r\nhdw[\"dienstkategorie\"] = 'HDW'\r\nhdw[\"holidaycorrection\"] = 1#0.90\r\nhdw[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nhdw[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nhdw[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [sineline, [200, 300, 0, 1, 200, 0], datetime(2010, 4, 10), datetime(2011, 10, 10),\r\n datetime(2010, 4, 10), datetime(2011, 9, 5), \"forecast\", \"r\", 0]\r\n ]\r\nhdw[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n [\"forecast\", \"forecast\", [0, 0, 0, -0.001, 0, 20, 0], datetime(2011, 9, 5), datetime(2012, 2, 1), \"r\", 50],\r\n ]\r\n\r\nkad = {}\r\nkad[\"dienstkategorie\"] = 'KAD'\r\nkad[\"holidaycorrection\"] = 1#0.80\r\nkad[\"startdate\"] = datetime.now() - timedelta(days=1500)\r\nkad[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]]\r\nkad[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\", \"color\"],\r\n #[linear, [1.,1.], datetime.now()-timedelta(days=700), datetime(2011,6,19),\r\n # datetime.now()-timedelta(days=700), datetime(2011,6,19), \"pre SMB 1 year linear\", \"r\", 0],\r\n [sineline, [400, 350, 0, 1, 1000, 0], datetime(2011, 11, 14) - timedelta(days=700), datetime(2011, 6, 19),\r\n datetime.now() - timedelta(days=600), datetime(2011, 6, 19), \"pre SMB 1 year sine\", \"r\", 0],\r\n #[linear, [1.,1.], datetime(2011,6,19)-timedelta(days=90), datetime(2011,6,19),\r\n # datetime(2011,6,19)-timedelta(days=90), datetime(2011,6,19), \"pre SMB 90 days\", \"m\", 0]\r\n ]\r\nkad[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\", \"plotstart\", \"plotend\", \"color\"],\r\n #[\"post SMB 1 year linear\", \"pre SMB 1 year linear\", [0,500,90], datetime(2011,9,19),datetime(2012,1,1), \"r\", 0],\r\n [\"post SMB 1 year sine\", \"pre SMB 1 year sine\", [0, 0, 0, 0, 0, 650, 0], datetime(2011, 6, 19), datetime(2012, 2, 1), \"r\", 100],\r\n #[\"post SMB 1 year sine, slow\", \"pre SMB 1 year sine\", [0,0,0,-0.01,0,600,0], datetime(2011,6,19),datetime(2012,1,1), \"r\",100],\r\n #[\"post SMB 90 days\", \"pre SMB 90 days\", [0,600,0], datetime(2011,6,19),datetime(2012,1,1), \"m\", 0]\r\n ]\r\nkaa = {}\r\nkaa[\"dienstkategorie\"] = 'KAA'\r\nkaa[\"holidaycorrection\"] = 1#0.80\r\nkaa[\"startdate\"] = datetime.now() - timedelta(days=1300)\r\nkaa[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=300), datetime.now()]\r\n ]\r\nkaa[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [linear, [1., 1.], datetime(2011, 7, 12), datetime(2011, 11, 30),\r\n datetime(2011, 7, 12), datetime.now(), \"DAB+\", \"m\", 0],\r\n [sineline, [150, 350, 100, 0, 1000, 0], datetime(2011, 11, 14) - timedelta(days=1200), datetime(2011, 6, 19),\r\n datetime.now() - timedelta(days=600), datetime(2011, 6, 19), \"pre SMB\", \"r\", 0],\r\n ]\r\nkaa[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\", \"plotstart\", \"plotend\"],\r\n [\"post SMB forecast\", \"pre SMB\", [1.5, 0, 200, 0, 0, 600, 0], datetime(2011, 6, 19), datetime(2011, 6, 20), \"r\", 100],\r\n ]\r\ndabstart = date(2011, 7, 17)\r\nkaa[\"extras\"] = [\r\n [\"linename\", \"color\", \"fitadd\", \"fitmodadd\", \"dates\", \"values\"],\r\n [\"DAB forecast\", \"red\", \"\", \"post SMB forecast\", [dabstart + timedelta(i * 7) for i in range(24)], [2.7 ** (-x / 10.) * 300 + 25 for x in xrange(24)]]\r\n ]\r\n\r\n#[1.5, 0, 200, 0, 0, 600, 00],\r\n#[2.7 ** (-x / 10.) * 300 + 25 for x in xrange(25)]]\r\n#[x ** 2 / 1.5 for x in xrange(-25, -1)]\r\n#[0, 0, 0, 0, 0, 500, 00],\r\n\r\nnet = {}\r\nnet[\"dienstkategorie\"] = 'NET'\r\nnet[\"holidaycorrection\"] = 1#0.88\r\nnet[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nnet[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nnet[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [sineline, [1000, 350, 0, 0.001, 2500, 0], datetime(2010, 4, 10), datetime(2011, 9, 10),\r\n datetime(2010, 4, 10), datetime(2012, 2, 1), \"forecast\", \"r\", 0]\r\n ]\r\nnet[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n ]\r\n\r\n\r\n\r\ndef iso_year_start(iso_year):\r\n \"The gregorian calendar date of the first day of the given ISO year\"\r\n fourth_jan = datetime(iso_year, 1, 4)\r\n delta = timedelta(fourth_jan.isoweekday() - 1)\r\n return fourth_jan - delta\r\n\r\ndef iso_to_gregorian(iso_year, iso_week, iso_day):\r\n \"Gregorian calendar date for the given ISO year, week and day\"\r\n year_start = iso_year_start(iso_year)\r\n return year_start + timedelta(days=iso_day - 1, weeks=iso_week - 1)\r\n\r\ndef todate(date):\r\n year = date[:2]\r\n week = date[2:]\r\n year = int(\"20\" + year)\r\n week = int(week)\r\n return iso_to_gregorian(year, week, 1)\r\n\r\n\r\ndef forecast(dienstkategorie, startdate, fitlines, fitmods, holidaycorrection, extras=[], tickets=[]):\r\n returndict = {}\r\n returndict[\"category\"] = dienstkategorie\r\n con, cur = get_oracle_cursor_rkna1()\r\n sql = u\"select a_annahmezeitpunkt_yyiw, sum(Anzahl) from rk.tickets_by_iw_dst_at_110930 \"\r\n sql += \"where a_dienstkategorie = '{}' and cast(a_annahmezeitpunkt_yyiw as integer) < 1139 group by a_annahmezeitpunkt_yyiw order by a_annahmezeitpunkt_yyiw \".format(dienstkategorie)\r\n result = []\r\n print(sql)\r\n cur.execute(sql)\r\n for row in cur:\r\n datum = todate(row[0])\r\n if datum >= startdate:\r\n result += [[todate(row[0]), row[1]]]\r\n switchdate = date(2011, 9, 21)\r\n switchdate = \"to_date('{}', 'dd.mm.yyyy')\".format(switchdate.strftime(\"%d.%m.%Y\"))\r\n startdate = \"to_date('{}', 'dd.mm.yyyy')\".format(startdate.strftime(\"%d.%m.%Y\"))\r\n nowdate = date.today() - timedelta(days=7)\r\n nowdate = \"to_date('{}', 'dd.mm.yyyy')\".format(nowdate.strftime(\"%d.%m.%Y\"))\r\n sql = u\"select trunc(A_annahmezeitpunkt, 'iw'), count(*) from tickets \"\r\n sql += \"where trunc(A_annahmezeitpunkt, 'iw') >= {0} \".format(switchdate)\r\n sql += \"and trunc(A_annahmezeitpunkt, 'iw') <= {0} \".format(nowdate)\r\n sql += \"and A_dienstkategorie = '{}' \".format(dienstkategorie)\r\n sql += \"and \" + ticketfilter\r\n sql += \"group by trunc(A_annahmezeitpunkt, 'iw') order by trunc(A_annahmezeitpunkt, 'iw')\"\r\n print(sql)\r\n print(dienstkategorie)\r\n cur.execute(sql)\r\n for row in cur:\r\n result += [list(row)]\r\n\r\n xdata = [x[0] for x in result]\r\n ydata = [x[1] for x in result]\r\n f = plt.figure()\r\n plt.title(dienstkategorie + \" Feldticket Forecast\", fontsize=12)\r\n fitpars = {}\r\n fitfuncs = {}\r\n fitmodfuncs = {}\r\n fitmodpars = {}\r\n\r\n returndict[\"xdata\"] = xdata\r\n returndict[\"ydata\"] = ydata\r\n\r\n\r\n\r\n for fitline in fitlines[1:]:\r\n fitfunc = fitline[0]\r\n fitparam = fitline[1]\r\n fitstart = fitline[2]\r\n fitend = fitline[3]\r\n plotstart = fitline[4]\r\n plotend = fitline[5]\r\n linename = fitline[6]\r\n color = fitline[7]\r\n error = fitline[8]\r\n\r\n errfunc = lambda p, x, y: fitfunc(p, x) - y\r\n\r\n xfitdata = [date2num(x[0]) for x in result if x[0] >= fitstart and x[0] <= fitend]\r\n yfitdata = [x[1] for x in result if x[0] >= fitstart and x[0] <= fitend]\r\n p0 = fitparam + [xfitdata[0]]\r\n print(p0)\r\n holiday_correction(xfitdata, yfitdata, 1 / holidaycorrection)\r\n p1, success = optimize.leastsq(errfunc, p0[:], args=(numpy.array(xfitdata), numpy.array(yfitdata)))\r\n holiday_correction(xfitdata, yfitdata, holidaycorrection)\r\n print(p1)\r\n print(getdesc(p1))\r\n fitpars[linename] = p1\r\n fitfuncs[linename] = fitfunc\r\n xplotdata = [x[0] for x in result if x[0] >= plotstart and x[0] <= plotend]\r\n while xplotdata[-1] < plotend - timedelta(days=7):\r\n xplotdata += [xplotdata[-1] + timedelta(days=7)]\r\n fitplotdata = [fitfunc(p1, date2num(x)) for x in xplotdata]\r\n holiday_correction(xplotdata, fitplotdata, holidaycorrection)\r\n plt.plot_date(xplotdata, fitplotdata, marker=\"None\", linestyle=\"-\",\r\n color=color, label=linename)\r\n if error:\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x + error for x in fitplotdata])\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x - error for x in fitplotdata])\r\n\r\n returndict[\"switchdate\"] = plotend\r\n returndict[\"fitpars\"] = p1\r\n\r\n if len(fitmods) > 1:\r\n for fitmod in fitmods[1:]:\r\n linename = fitmod[0]\r\n fitline = fitmod[1]\r\n pars = fitmod[2]\r\n plotstart = fitmod[3]\r\n plotend = fitmod[4]\r\n color = fitmod[5]\r\n error = fitmod[6]\r\n fitfunc = fitfuncs[fitline]\r\n for p in range(len(fitpars[fitline])):\r\n pars[p] += fitpars[fitline][p]\r\n print(pars)\r\n xplotdata = [x[0] for x in result if x[0] >= plotstart and x[0] <= plotend]\r\n while xplotdata[-1] < plotend - timedelta(days=7):\r\n xplotdata += [xplotdata[-1] + timedelta(days=7)]\r\n fitplotdata = [fitfunc(pars, date2num(x)) for x in xplotdata]\r\n holiday_correction(xplotdata, fitplotdata, holidaycorrection)\r\n plt.plot_date(xplotdata, fitplotdata, marker=\"None\", linestyle=\"-\",\r\n color=color, label=linename)\r\n if error:\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x + error for x in fitplotdata])\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x - error for x in fitplotdata])\r\n fitmodpars[linename] = pars\r\n fitmodfuncs[linename] = fitfunc\r\n returndict[\"extrpars\"] = pars\r\n\r\n\r\n\r\n\r\n if tickets:\r\n xtemp = []\r\n ytemp = []\r\n for i in range(len(xdata)):\r\n if xdata[i] >= tickets[1][0] and xdata[i] <= tickets[1][1]:\r\n xtemp += [xdata[i]]\r\n ytemp += [ydata[i]]\r\n xdata = xtemp\r\n ydata = ytemp\r\n\r\n\r\n plt.plot_date(xdata, ydata, markersize=4, label=\"tickets per week\")\r\n plt.ylim(0, max(ydata) * 1.1)\r\n holiday_correction(xdata, ydata, 1 / holidaycorrection)\r\n smoothdates = xdata\r\n winsize = 13\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [ydata[0] for x in range(winhalf)] + ydata + [ydata[-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"green\", label=\"3 month average\")\r\n winsize = 3\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [ydata[0] for x in range(winhalf)] + ydata + [ydata[-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"orange\", label=\"3 week average\")\r\n\r\n\r\n for extra in extras[1:]:\r\n linename = extra[0]\r\n color = extra[1]\r\n fitadd = extra[2]\r\n fitmodadd = extra[3]\r\n dates = extra[4]\r\n values = extra[5]\r\n\r\n if fitadd:\r\n func = fitfuncs[fitadd]\r\n pars = fitpars[fitadd]\r\n elif fitmodadd:\r\n func = fitmodfuncs[fitmodadd]\r\n pars = fitmodpars[fitmodadd]\r\n\r\n if fitmodadd or fitadd:\r\n values = [values[i] + func(pars, date2num(dates[i])) for i in range(len(values))]\r\n plt.plot_date(dates, values, marker=\"None\", linestyle=\"-\",\r\n color=color, label=linename)\r\n\r\n\r\n kundenkategorie = dienstkategorie\r\n if kundenkategorie == 'NET':\r\n kundenkategorie = 'KAI'\r\n elif kundenkategorie == 'HDW':\r\n kundenkategorie = \"KAI','KAD\"\r\n sql = u\"select datum, sum(einheiten_angeschlossen) from we_history where Region = 10 \"\r\n sql += \"and datum >= {0} \".format(startdate)\r\n sql += \"and A_dienstkategorie in ('{}') \".format(kundenkategorie)\r\n sql += \"group by datum order by datum \"\r\n #print(sql)\r\n cur.execute(sql)\r\n result = []\r\n for row in cur:\r\n result += [list(row)]\r\n xdata = [x[0] for x in result]\r\n ydata = [x[1] for x in result]\r\n if tickets:\r\n xtemp = []\r\n ytemp = []\r\n for i in range(len(xdata)):\r\n if xdata[i] >= tickets[1][0] and xdata[i] <= tickets[1][1]:\r\n xtemp += [xdata[i]]\r\n ytemp += [ydata[i]]\r\n xdata = xtemp\r\n ydata = ytemp\r\n leg = plt.legend(loc=\"upper left\", fancybox=True, shadow=True)\r\n frame = leg.get_frame()\r\n frame.set_facecolor('1.0')\r\n leg.set_zorder(10)\r\n ax = plt.gca()\r\n ax.grid(zorder=2)\r\n ax.set_ylabel(\"tickets\")\r\n ax.set_xlabel(\"date\")\r\n f.autofmt_xdate()\r\n ax2 = plt.twinx()\r\n ax2.set_ylabel(\"customers\")\r\n plt.plot_date(xdata, ydata, marker=\"None\", linestyle=\"-\", color=\"gray\", label=\"customers\", zorder=5)\r\n ydelta = [(ydata[i] - ydata[i - 7]) * 100 for i in range(7, len(ydata)) if xdata[i] > datetime(2011, 4, 1)]\r\n xdelta = xdata[-len(ydelta):]\r\n winsize = 7\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [ydelta[0] for x in range(winhalf)] + ydelta + [ydelta[-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(xdelta, smoothdat, marker=\"None\", linestyle=\"--\", color=\"gray\", label=\"weekly new customers * 100\", zorder=5)\r\n leg = plt.legend(loc=\"lower right\", fancybox=True, shadow=True)\r\n frame = leg.get_frame()\r\n frame.set_facecolor('1.0')\r\n leg.set_zorder(20)\r\n ax.set_zorder(ax2.get_zorder() + 1) # put ax in front of ax2\r\n ax.patch.set_visible(False) # hide the 'canvas'\r\n\r\n\r\n\r\n\r\n #plt.show()\r\n f.autofmt_xdate()\r\n plt.savefig(\"forecast_\" + dienstkategorie + \".pdf\")\r\n return returndict\r\n\r\n\r\ndef plot_all(dicts, startdate, enddate):\r\n datums = []\r\n for dic in dicts:\r\n datums += dic[\"xdata\"]\r\n datums = sorted(list(set(datums)))\r\n tickets = [0 for x in datums]\r\n for dic in dicts:\r\n for i in range(len(dic[\"ydata\"])):\r\n if dic[\"xdata\"][i] in datums:\r\n index = datums.index(dic[\"xdata\"][i])\r\n tickets[index] += dic[\"ydata\"][i]\r\n f = plt.figure()\r\n plotdatums = [x for x in datums if x > startdate]\r\n plottickets = tickets[-len(plotdatums):]\r\n plt.plot_date(plotdatums, plottickets)\r\n smoothdates = plotdatums\r\n winsize = 13\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [plottickets[0] for x in range(winhalf)] + plottickets + [plottickets [-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"green\")\r\n winsize = 3\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [plottickets [0] for x in range(winhalf)] + plottickets + [plottickets [-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"orange\")\r\n switchdate = plotdatums[-1]\r\n while plotdatums[-1] < enddate:\r\n plotdatums += [plotdatums[-1] + timedelta(days=7)]\r\n fittickets = [0 for x in plotdatums]\r\n for dic in dicts:\r\n for i in range(len(plotdatums)):\r\n if (plotdatums[i] <= dic[\"switchdate\"]) or \"extrpars\" not in dic:\r\n fittickets[i] += sineline(dic[\"fitpars\"], date2num(plotdatums[i]))\r\n else:\r\n fittickets[i] += sineline(dic[\"extrpars\"], date2num(plotdatums[i]))\r\n plt.plot_date(plotdatums, fittickets, marker=\"None\", linestyle=\"-\",\r\n color=\"red\")\r\n errordatums = [x for x in plotdatums if x > switchdate]\r\n errlen = len(errordatums)\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] + (200 + 10 * x) for x in range(errlen)], color=\"r\")\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] - (200 + 5 * x) for x in range(errlen)], color=\"r\")\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] + (50 + 10 * x) for x in range(errlen)], color=\"g\")\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] - (50 + 5 * x) for x in range(errlen)], color=\"g\")\r\n\r\n plt.title(\"Gesamtforecast\", fontsize=12)\r\n ax = plt.gca()\r\n ax.set_ylabel(\"Tickets\")\r\n ax.set_xlabel(\"Datum\")\r\n plt.savefig(\"all.pdf\")\r\n wb = xlwt.Workbook()\r\n sheet = wb.add_sheet(\"data\")\r\n sheet.write(0, 0, \"Datum\")\r\n sheet.write(0, 1, \"Fit-Extrapolation\")\r\n sheet.write(0, 2, \"Tickets\")\r\n xf = xlwt.easyxf(num_format_str='YYYYMMDD')\r\n for i in range(len(plotdatums)):\r\n sheet.write(i + 1, 0, plotdatums[i], xf)\r\n sheet.write(i + 1, 1, fittickets[i])\r\n if i < len(plottickets):\r\n sheet.write(i + 1, 2, plottickets[i])\r\n sheet.write(i + 1, 3, \"gesamt\")\r\n row = len(plotdatums) + 1\r\n for dic in dicts:\r\n for i in range(len(plotdatums)):\r\n sheet.write(row, 0, plotdatums[i], xf)\r\n if (plotdatums[i] <= dic[\"switchdate\"]) or \"extrpars\" not in dic:\r\n fitval = sineline(dic[\"fitpars\"], date2num(plotdatums[i]))\r\n else:\r\n fitval = sineline(dic[\"extrpars\"], date2num(plotdatums[i]))\r\n sheet.write(row, 1, fitval)\r\n if plotdatums[i] in dic[\"xdata\"]:\r\n sheet.write(row, 2, dic[\"ydata\"][dic[\"xdata\"].index(plotdatums[i])])\r\n sheet.write(row, 3, dic[\"category\"])\r\n row += 1\r\n\r\n wb.save(\"data.xls\")\r\n\r\n\r\n\r\ndicts = []\r\ndicts.append(forecast(**net))\r\ndicts.append(forecast(**kai))\r\ndicts.append(forecast(**kav))\r\ndicts.append(forecast(**kaa))\r\ndicts.append(forecast(**kad))\r\ndicts.append(forecast(**hdw))\r\nplot_all(dicts, datetime(2011, 4, 1), datetime(2012, 4, 1))\r\n\r\n\r\n","sub_path":"naos-python/Source/RK/forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":22772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"45852529","text":"import pygame\r\nimport copy\r\n\r\nhidden_rows = 4\r\n\r\nclass Board:\r\n\r\n\tdef __init__(self):\r\n\t\tself.x = 10\r\n\t\tself.y = 20 + hidden_rows\r\n\r\n\t\tself.locked_board = [[(255,255,255) for _ in range(self.x)] for _ in range(self.y)]\r\n\t\tself.temp_board = copy.deepcopy(self.locked_board)\r\n\t\tself.temp_input_board = copy.deepcopy(self.locked_board)\r\n\r\n\t\tself.level = 0\r\n\t\tself.lines = 0\r\n\t\tself.score = 0\r\n\r\n\t\tself.height = 0\r\n\r\n\r\n\tdef update_board(self, piece):\r\n\r\n\t\t# Given a piece, this function updates the colour of the board data.\r\n\t\t# update_validation must be called before this to check feasibility.\r\n\t\t#\r\n\t\t# param piece \t\tTetromino\r\n\r\n\t\tself.temp_board = copy.deepcopy(self.locked_board)\r\n\t\t\r\n\t\tfor i, line in enumerate(piece.shape[piece.rotation%len(piece.shape)]):\r\n\t\t\tfor j, char in enumerate(line):\r\n\r\n\t\t\t\tif char == '0':\r\n\t\t\t\t\tself.temp_board[piece.y+j][piece.x+i] = piece.colour\r\n\r\n\r\n\tdef update_validation(self, piece):\r\n\r\n\t\t# Checks whether position of piece is feasible on the board.\r\n\t\t#\r\n\t\t# param piece \t\tTetromino\r\n\r\n\t\t# potential positions\r\n\t\taccepted_positions = [] \t\r\n\t\tfor i in range(self.x):\r\n\t\t\tfor j in range(self.y):\r\n\t\t\t\tif self.locked_board[j][i] == (255,255,255):\r\n\t\t\t\t\taccepted_positions.append( (j,i) )\r\n\r\n\t\tfor i, line in enumerate(piece.shape[piece.rotation%len(piece.shape)]):\r\n\t\t\tfor j, char in enumerate(line):\r\n\t\t\t\tif char == '0':\r\n\t\t\t\t\tif (piece.y+j,piece.x+i) not in accepted_positions:\r\n\t\t\t\t\t\treturn False\r\n\r\n\t\treturn True\r\n\r\n\r\n\tdef lock_piece(self, piece):\r\n\r\n\t\t# Locks piece in locked data.\r\n\t\t#\r\n\t\t# param piece \t\tTetromino\r\n\r\n\t\tfor i, line in enumerate(piece.shape[piece.rotation%len(piece.shape)]):\r\n\t\t\tfor j, char in enumerate(line):\r\n\r\n\t\t\t\tif char == '0':\r\n\t\t\t\t\tself.locked_board[piece.y+j][piece.x+i] = piece.colour\r\n\r\n\r\n\tdef scoring(self):\r\n\r\n\t\t# Given a successful tetris, this function will implement the Original Sega scoring \r\n\t\t#system.\r\n\r\n\t\tline = 0\r\n\t\tpoints = 0\r\n\r\n\t\t# Check for completed lines in board\r\n\t\tfor old_row in range(self.y-1,0,-1):\r\n\t\t\tif (255,255,255) not in self.locked_board[old_row]:\r\n\t\t\t\tline += 1\r\n\r\n\t\t\t\tdel self.locked_board[old_row]\r\n\t\t\t\tself.locked_board.insert(0, [(255,255,255) for _ in range(self.x)])\r\n\r\n\r\n\t\t# Original Sega Scoring System\r\n\t\t# line_multiplier = {1:1, 2:4, 3:9, 4:20}\r\n\t\t# if line == 0:\r\n\t\t# \tpass\r\n\t\t# elif 0 <= self.level <= 1:\r\n\t\t# \tpoints += 100*line_multiplier[line]\r\n\t\t# elif 2 <= self.level <= 3:\r\n\t\t# \tpoints += 200*line_multiplier[line]\r\n\t\t# elif 4 <= self.level <= 5:\r\n\t\t# \tpoints += 300*line_multiplier[line]\r\n\t\t# elif 6 <= self.level <= 7:\r\n\t\t# \tpoints += 400*line_multiplier[line]\r\n\t\t# elif self.level <= 8:\r\n\t\t# \tpoints += 500*line_multiplier[line]\r\n\t\tif line == 0:\r\n\t\t\tpass\r\n\t\telif line == 1:\r\n\t\t\tpoints += 40\r\n\t\telif line == 2:\r\n\t\t\tpoints += 120\r\n\t\telif line == 3:\r\n\t\t\tpoints += 300\r\n\t\telif line == 4:\r\n\t\t\tpoints += 1200\r\n\r\n\r\n\t\t# Check for Perfect Clear\r\n\t\tperfect_clear = all([x == (255,255,255) for x in self.locked_board[i]] for i in range(len(self.locked_board)))\r\n\t\tif perfect_clear:\r\n\t\t\tpoints *= 10\r\n\r\n\t\tself.lines += line\r\n\t\tself.score += points\r\n\r\n\t\t# Tetris(NES, Nintendo) level system\r\n\t\tif self.lines < 200:\r\n\t\t\tself.level = self.lines // 10\r\n\r\n\r\n\tdef draw_board(self ,win, board_x, board_y, block_size):\r\n\r\n\t\t# Draws the board and grid lines using pygame.\r\n\t\t#\t\r\n\t\t# param win\t\t\tPygame window\r\n\t\t# param board_x\t\tStarting x point of board\r\n\t\t# param board y \tStarting y point of board\r\n\t\t# param block_size\tBlock size\r\n\r\n\t\tborder_size = 3\r\n\r\n\r\n\t\tfor i in range(self.x):\r\n\t\t\tfor j in range(hidden_rows,self.y):\r\n\r\n\t\t\t\t# Draw board\r\n\t\t\t\tpygame.draw.rect(win, self.temp_board[j][i], \r\n\t\t\t\t\t(board_x + i*block_size, board_y + j*block_size, block_size, block_size), 0)\t\r\n\r\n\t\t\t\t# Draw grid line\r\n\t\t\t\tpygame.draw.line(win, (128,128,128), \r\n\t\t\t\t\t(board_x + i*block_size, board_y + (hidden_rows*block_size)), \r\n\t\t\t\t\t(board_x + i*block_size, board_y + block_size*self.y))\t\r\n\t\t\t\tpygame.draw.line(win, (128,128,128), \r\n\t\t\t\t\t(board_x, board_y + j*block_size), \r\n\t\t\t\t\t(board_x + self.x*block_size, board_y + j*block_size))\r\n\r\n\r\n\t\t# Draw border line\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x, board_y + (hidden_rows*block_size)), \r\n\t\t\t(board_x + self.x*block_size, board_y + (hidden_rows*block_size)),\r\n\t\t\tborder_size)\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x, board_y + self.y*block_size), \r\n\t\t\t(board_x + self.x*block_size, board_y + self.y*block_size),\r\n\t\t\tborder_size)\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x, board_y + (hidden_rows*block_size)), \r\n\t\t\t(board_x, board_y + (self.y*block_size)),\r\n\t\t\tborder_size)\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x + self.x*block_size, board_y + (hidden_rows*block_size)), \r\n\t\t\t(board_x + self.x*block_size, board_y + (self.y*block_size)),\r\n\t\t\tborder_size)\r\n\r\n\r\n\tdef input_data(self, piece):\r\n\r\n\t\t# Calculates the input data for genetic algorithm given the tetromino piece.\r\n\t\t#\r\n\t\t# param piece \t\t\t\tTetromino\r\n\t\t# output sum(heights)\t\tAggregrated height\r\n\t\t# output completed_lines\tLines completed\r\n\t\t# output holes \t\t\t\tHoles within stack\r\n\t\t# output bumpiness\t\t\tBumpiness within height\r\n\r\n\r\n\t\t# Updates temp_board with hard-dropped piece to conduct analysis\r\n\t\tfor i in range(30):\r\n\t\t\tpiece.y += 1\r\n\r\n\t\t\tif not self.update_validation(piece):\r\n\t\t\t\tpiece.y -= 1\r\n\t\t\t\tself.update_board(piece)\r\n\t\t\t\tpiece.y -= i\r\n\t\t\t\tbreak\r\n\r\n\r\n\t\t# Calculate input data\r\n\t\theights = [0 for i in range(self.x)]\r\n\t\theight_counted = [False for i in range(self.x)]\r\n\r\n\t\tholes = 0\r\n\t\tcompleted_lines = 0\r\n\t\tbumpiness = 0\r\n\r\n\r\n\t\tfor j in range(hidden_rows, self.y):\r\n\r\n\t\t\tif not (255,255,255) in self.temp_board[j]:\r\n\t\t\t\tcompleted_lines += 1\r\n\r\n\t\t\tfor i in range(self.x):\r\n\r\n\t\t\t\t# Find height if column not empty\r\n\t\t\t\tif not self.temp_board[j][i] == (255,255,255) and not height_counted[i]:\r\n\t\t\t\t\theights[i] = self.y - j\r\n\t\t\t\t\theight_counted[i] = True\r\n\r\n\t\t\t\t# Count holes if column height acquired\r\n\t\t\t\tif self.temp_board[j][i] == (255,255,255) and height_counted[i]:\r\n\t\t\t\t\tholes += 1\r\n\r\n\t\t# Calculate bumpiness\r\n\t\tfor i in range(self.x - 2):\r\n\t\t\tbumpiness += abs(heights[i] - heights[i+1])\r\n\r\n\r\n\t\treturn [sum(heights), completed_lines, holes, bumpiness]\r\n\t\t#return (*heights, completed_lines, holes, bumpiness)\r\n\t\t#return sum(heights), completed_lines, holes, bumpiness\r\n\r\n\r\n\r\n\r\n\tdef board_heuristic_inputs(self, piece):\r\n\r\n\t\t# Calculates heursitic inputs for every combination of rotation and position in x axis.\r\n\t\t#\r\n\t\t# param\t piece \t\tTetromino\r\n\t\t# output inputs\t\tInputs (size: [160])\r\n\r\n\t\tinputs = [0 for i in range(40*4)]\r\n\r\n\t\tfor k in range(piece.rotations):\r\n\t\t\tpiece.rotation = k\r\n\r\n\t\t\t# Move furthest to left\r\n\t\t\tfor j in range(5):\r\n\t\t\t\tpiece.x -= 1\r\n\t\t\t\tif not self.update_validation(piece):\r\n\t\t\t\t\tpiece.x += 1\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t# Obtain heuristic inputs for each combination of rotation and column position\r\n\t\t\tfor j in range(10):\t\t\t\t\r\n\t\t\t\tif self.update_validation(piece):\r\n\t\t\t\t\tinputs[ 10*k + 4*j : 10*k + 4*(j+1) ] = self.input_data(piece)\r\n\t\t\t\tpiece.x += 1\r\n\r\n\t\t# Reset to original piece parameters\r\n\t\tpiece.x = 0\r\n\t\tpiece.rotation = 0\r\n\r\n\t\treturn inputs\r\n","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"197579467","text":"\nfrom js9 import j\nfrom pprint import pprint as print\nimport os\nimport struct\nimport copy\n\nTEMPLATE = \"\"\"\naddr = \"localhost\"\nport = \"9900\"\nnamespace = \"\"\nadminsecret_ = \"\"\nsecret_ = \"\"\nmode = \"direct\"\nid_enable = true\ndelete = false\n\"\"\"\n\nJSConfigBase = j.tools.configmanager.base_class_config\n\n\nclass ZDBClient(JSConfigBase):\n\n def __init__(self, instance, data={}, parent=None, interactive=False,started=True):\n \"\"\"\n is connection to ZDB\n\n - secret is also the name of the directory where zdb data is for this namespace/secret\n\n config params:\n secret {str} -- is same as namespace id, is a secret to access the data (default: {None})\n port {[int} -- (default: 9900)\n mode -- user,direct,sequential see https://github.com/rivine/0-db/blob/master/README.md\n id_enabled -- if mode: user or sequential then key_enabled needs to be False, there will be pos_id for each change in the DB\n namespace -- zdb supports namespace\n adminsecret does not have to be set, but when you want to create namespaces it is a must\n\n \"\"\"\n self.init(instance=instance, data=data, parent=parent, interactive=interactive,started=started)\n\n def init(self, instance, data={}, parent=None, interactive=False, reset=False,started=True):\n\n JSConfigBase.__init__(self, instance=instance, data=data,\n parent=parent, template=TEMPLATE, ui=None, interactive=interactive)\n\n if self.config.data[\"id_enable\"]:\n ipath = j.dirs.VARDIR + \"/zdb/index/%s.db\" % instance\n j.sal.fs.createDir(j.dirs.VARDIR + \"/zdb/index\")\n if reset:\n j.sal.fs.remove(ipath)\n self._indexfile = j.data.indexfile.get(name=instance, path=ipath, nrbytes=6)\n else:\n self._indexfile = None\n \n if not started:\n return\n\n redis = j.clients.redis.get(ipaddr=self.config.data['addr'],\n port=self.config.data['port'],\n fromcache=False)\n\n self.client = self._patch_redis_client(redis)\n\n if self.config.data[\"adminsecret_\"] is not \"\" and self.config.data[\"adminsecret_\"] is not None:\n self.client.execute_command(\"AUTH\", self.config.data[\"adminsecret_\"])\n\n self.id_enable = bool(self.config.data[\"id_enable\"])\n\n if self.id_enable:\n self.config.data[\"mode\"] == \"direct\"\n\n self.key_enable = False\n if self.config.data[\"mode\"] == \"user\":\n if self.id_enable:\n raise RuntimeError(\"cannot have id_enable and user mode on db\")\n self.key_enable = True\n if self.config.data[\"mode\"] == \"direct\":\n self.key_enable = False\n if self.config.data[\"mode\"] == \"seq\":\n self.key_enable = False\n if self.id_enable:\n raise RuntimeError(\"cannot have id_enable and seq mode on db\")\n\n nsname = self.config.data[\"namespace\"]\n secret = self.config.data[\"secret_\"]\n\n self.mode = self.config.data[\"mode\"]\n\n def namespace_init(nsname, secret):\n # means the namespace does already exists\n if secret is \"\":\n self.client.execute_command(\"SELECT\", nsname)\n else:\n self.client.execute_command(\"SELECT\", nsname, secret)\n self.namespace = nsname\n\n if self.namespace_exists(nsname):\n namespace_init(nsname, secret)\n self.logger.debug(\"namespace:%s exists\" % nsname)\n else:\n self.client.execute_command(\"NSNEW\", nsname)\n namespace_init(nsname, secret)\n if secret is not \"\":\n self.client.execute_command(\n \"NSSET\", self.namespace, \"password\", secret)\n self.client.execute_command(\n \"NSSET\", self.namespace, \"public\", \"no\")\n self.logger.debug(\"namespace:%s NEW\" % nsname)\n\n self.logger.debug(self.nsinfo)\n\n def _patch_redis_client(self, redis):\n # don't auto parse response for set, cause it's not 100% redis compatible\n # 0-db does return a key after in set\n del redis.response_callbacks['SET']\n return redis\n\n def set(self, data, id=None, key=None, checknew=False):\n \"\"\"[summary]\n\n Arguments:\n data {str or binary} -- the payload can be e.g. capnp binary\n\n Keyword Arguments:\n id {int} -- needs id_enabled to be on true, can be used to find info back based on id (default: {None})\n if None and id_enabled==True then will autoincrement if not given\n\n key {[type]} -- string, only usable if key_enable == True\n\n @PARAM checknew, if True will return (key,new) and new is bool\n \"\"\"\n if self.mode==\"seq\":\n if id is None:\n id=\"\"\n else:\n id = struct.pack(\" end:\n break\n \n else: \n if self.id_enable == False:\n raise RuntimeError(\"only id_enable supported for iterate\")\n\n if start is not None:\n id = start\n else:\n id = 0\n\n self._indexfile._f.seek(self._indexfile._offset(id))\n\n while True:\n pos = self._indexfile._f.read(self._indexfile.nrbytes)\n if len(pos) < self._indexfile.nrbytes:\n break # EOF\n\n data = self.client.execute_command(\"GET\", pos)\n\n result = method(id, data, result=result)\n id += 1\n if end is not None and id > end:\n break\n\n return result\n\n def namespace_exists(self, name):\n try:\n self.client.execute_command(\"NSINFO\", name)\n return True\n except Exception as e:\n if not \"Namespace not found\" in str(e):\n raise RuntimeError(\"could not check namespace:%s, error:%s\" % (name, e))\n return False\n\n def namespace_new(self, name, secret=\"\", maxsize=0, instance=None):\n if self.namespace_exists(name):\n raise RuntimeError(\"namespace already exists:%s\" % name)\n\n data = copy.copy(self.config.data)\n data[\"namespace\"] = name\n data[\"secret_\"] = secret\n if instance is not None:\n self.instance = instance\n self.init(self.instance, data=data, reset=True)\n\n if maxsize is not 0:\n self.client.execute_command(\"NSSET\", self.namespace, \"maxsize\", maxsize)\n\n @property\n def count(self):\n i = self.nsinfo\n if self.id_enable:\n return self._indexfile.count\n else:\n return i[\"entries\"]\n\n def test(self):\n\n nr = self.nsinfo[\"entries\"]\n assert nr == 0\n # do test to see that we can compare\n id = self.set(b\"r\")\n assert id == 0\n assert self.get(id) == b\"r\"\n newid, exists = self.set(b\"r\", id=id, checknew=True)\n assert exists is False\n assert newid == id\n\n nr = self.nsinfo[\"entries\"]\n\n self.set(\"test\", 1)\n print (self.nsinfo)\n\n # test the list function\n assert self.list(0, 0) == [0]\n assert self.list(0, 1) == [0, 1]\n assert self.list(1, 1) == [1]\n\n res = self.list()\n assert res == [0, 1]\n\n print(res)\n\n result = {}\n\n def test(id, data, result):\n print(\"%s:%s\" % (id, data))\n result[id] = data\n return result\n\n result = self.iterate(test, result={})\n\n assert self.list(start=newid, end=newid) == [newid]\n\n result = self.iterate(test, result={}, start=newid, end=newid)\n\n assert result == {newid: b'r'}\n\n assert self.exists(newid)\n\n def dumpdata():\n\n if self.key_enable:\n inputs = {}\n for i in range(4):\n data = os.urandom(4096)\n key = self.set(data, key=str(i))\n inputs[key] = data\n\n elif self.id_enable:\n inputs = {}\n for i in range(4):\n data = os.urandom(4096)\n key = self.set(data)\n inputs[key] = data\n\n for k, expected in inputs.items():\n actual = self.get(k)\n assert expected == actual\n\n dumpdata() # is in default namespace\n\n for i in range(1000):\n nsname = \"testns_%s\" % i\n exists = self.namespace_exists(nsname)\n if not exists:\n break\n\n print (\"count:%s\" % self.count)\n\n self.namespace_new(nsname, secret=\"1234\", maxsize=1000, instance=None)\n\n assert self.nsinfo[\"data_limits_bytes\"] == 1000\n assert self.nsinfo[\"data_size_bytes\"] == 0\n assert self.nsinfo[\"data_size_mb\"] == 0.0\n assert self.nsinfo[\"entries\"] == 0\n assert self.nsinfo[\"index_size_bytes\"] == 0\n assert self.nsinfo[\"index_size_kb\"] == 0.0\n assert self.nsinfo[\"name\"] == nsname\n assert self.nsinfo[\"password\"] == \"yes\"\n assert self.nsinfo[\"public\"] == \"no\"\n\n assert self.namespace == nsname\n\n # both should be same\n id = self.set(b\"a\")\n assert self.get(id) == b\"a\"\n assert self._indexfile.count == 1\n assert self.nsinfo[\"entries\"] == 1\n\n try:\n dumpdata()\n except Exception as e:\n assert \"No space left\" in str(e)\n\n self.namespace_new(nsname+\"2\", secret=\"1234\", instance=None)\n\n nritems = 100000\n j.tools.timer.start(\"zdb\")\n\n print(\"perftest for 100.000 records, should get above 10k per sec\")\n for i in range(nritems):\n id = self.set(b\"a\")\n\n j.tools.timer.stop(nritems)\n","sub_path":"JumpScale9RecordChain/clients/zdb/ZDBClient.py","file_name":"ZDBClient.py","file_ext":"py","file_size_in_byte":14585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"566830694","text":"import sys\r\nfrom random import random\r\n\r\nw = 100\r\nh = 150\r\nhodnoty = []\r\n\r\nfor i in range(w):\r\n\thodnoty.append([0]*h)\r\n\r\nminers = []\r\n\r\nsmery = [(1, 0), (0, 1), (-1, 0), (0, -1)]\r\ndef new_cross(x, y, smery):\r\n\t#nesmi byt slepa\r\n\thodnoty[x][y] = 1\r\n\tsmer1 = smery[int(random()*len(smery))]\r\n\tMiner(x, y, smer1)\r\n\tsmery.remove(smer1)\r\n\tfor smer in smery:\r\n\t\tif random() < 0.7:\r\n\t\t\tMiner(x, y, smer)\r\n\r\n\r\n\r\nclass Miner():\r\n\tdef __init__(self, x, y, smer):\r\n\t\tself.x = x\r\n\t\tself.y = y\r\n\t\tself.smer = smer\r\n\t\tminers.append(self)\r\n\t\tself.fuel = 3 + int(random()*7)\r\n\r\n\t\tself.vertical = (smer[0] == 0)\r\n\r\n\r\n\tdef update(self):\r\n\t\tself.fuel -= 1\r\n\r\n\t\tself.x += self.smer[0]\r\n\t\tself.y += self.smer[1]\r\n\r\n\t\t#vyjel z mapy\r\n\t\tif self.x < 0 or self.y < 0 or self.x >= w or self.y >= h:\r\n\t\t\tminers.remove(self)\r\n\t\t\treturn\r\n\t\t#narazil na cestu\r\n\t\tif hodnoty[self.x][self.y] == 1:\r\n\t\t\tminers.remove(self)\r\n\t\t\treturn\r\n\r\n\t\tif self.vertical:\r\n\t\t\tif self.x < w - 1 and hodnoty[self.x + 1][self.y] == 1:\r\n\t\t\t\tif (hodnoty[self.x + 1][self.y - self.smer[1]] == 0 and \r\n\t\t\t\t\thodnoty[self.x - 1][self.y - self.smer[1]] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\t\t\tif self.x > 1 and hodnoty[self.x - 1][self.y] == 1:\r\n\t\t\t\tif (hodnoty[self.x + 1][self.y - self.smer[1]] == 0 and \r\n\t\t\t\t\thodnoty[self.x - 1][self.y - self.smer[1]] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\t\telse:\r\n\t\t\tif self.y < h - 1 and hodnoty[self.x][self.y + 1] == 1:\r\n\t\t\t\tif (hodnoty[self.x - self.smer[0]][self.y + 1] == 0 and \r\n\t\t\t\t\thodnoty[self.x - self.smer[0]][self.y - 1] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\t\t\tif self.y > 1 and hodnoty[self.x][self.y - 1] == 1:\r\n\t\t\t\tif (hodnoty[self.x - self.smer[0]][self.y + 1] == 0 and \r\n\t\t\t\t\thodnoty[self.x - self.smer[0]][self.y - 1] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\r\n\r\n\t\t#vyčerpal palivo\r\n\t\tif not self.fuel:\r\n\t\t\tminers.remove(self)\r\n\t\t\ttry:\r\n\t\t\t\tif hodnoty[self.x + self.smer[0]][self.y + self.smer[1]] != 1:\r\n\t\t\t\t\tsm = smery[:]\r\n\t\t\t\t\tsm.remove(self.smer)\r\n\t\t\t\t\tnew_cross(self.x, self.y, sm)\r\n\t\t\t\telse:\r\n\t\t\t\t\thodnoty[self.x + self.smer[0]][self.y + self.smer[1]] = 1\r\n\t\t\texcept:\r\n\t\t\t\tpass\r\n\r\n\t\telse:\r\n\t\t\thodnoty[self.x][self.y] = 1\r\n\r\ndef generate(width, height):\r\n\tglobal hodnoty, w, h\r\n\tw = width\r\n\th = height\r\n\thodnoty = []\r\n\t\r\n\tfor i in range(w):\r\n\t\thodnoty.append([0]*h)\r\n\r\n\tnew_cross(w//3, h//3, smery[:])\r\n\tnew_cross(w//3*2, h//3, smery[:])\r\n\tnew_cross(w//3, h//3*2, smery[:])\r\n\tnew_cross(w//3*2, h//3*2, smery[:])\r\n\twhile len(miners):\r\n\t\tfor m in miners:\r\n\t\t\tm.update()\r\n\r\n\t#zahrada = Robot(0,0)\r\n\t#zahrada.fill()\r\n\treturn hodnoty\r\n\r\n\r\nclass Robot():\r\n\tsmery = [(1, 0), (0, 1), (-1, 0), (0, -1)]\r\n\r\n\tdef __init__(self,x,y):\r\n\t\tself.alive = 1\r\n\t\tself.otoceni = 0\r\n\t\tself.x = 0\r\n\t\tself.y = 0\r\n\t\thodnoty[self.x][self.y] = 3\r\n\t\tself.smer = smery[0]\r\n\t\r\n\tdef left(self):\r\n\t\ti = smery.index(self.smer)\r\n\t\tself.smer = smery[i - 1]\r\n\r\n\r\n\r\n\tdef go(self):\r\n\r\n\t\tif self.x+self.smer[0] > -1 and self.x+self.smer[0] < w and self.y+self.smer[1] > -1 and self.y+self.smer[1] < h:\r\n\t\t\tprint('cisla ok')\r\n\t\t\tif hodnoty[self.x+self.smer[0]][self.y+self.smer[1]] == 1 or hodnoty[self.x+self.smer[0]][self.y+self.smer[1]] == 3:\r\n\t\t\t\tself.left()\r\n\t\t\t\tself.otoceni += 1\r\n\t\t\t\tprint('vlevo')\r\n\t\t\telse:\r\n\t\t\t\tprint('vpred')\r\n\t\t\t\tself.otoceni = 0\r\n\t\t\t\tself.x += self.smer[0]\r\n\t\t\t\tself.y += self.smer[1]\r\n\t\t\t\thodnoty[self.x][self.y] = 3\r\n\t\telse:\t\r\n\t\t\tself.left()\r\n\t\t\tself.otoceni += 1\r\n\r\n\t\r\n\tdef fill(self):\r\n\t\twhile self.alive:\r\n\t\t\tprint('alive')\r\n\t\t\tprint(self.x, self.y)\r\n\t\t\tself.go()\r\n\t\t\tif self.otoceni >= 4:\r\n\t\t\t\tself.alive = 0\r\n\r\ndef tisk():\r\n\tfor line in hodnoty:\r\n\t\tbuf = ''\r\n\t\tfor i in line:\r\n\t\t\tif i == 0:\r\n\t\t\t\tbuf += '.'\r\n\t\t\telif i == 1:\r\n\t\t\t\tbuf += 'X'\r\n\t\t\telif i == 2:\r\n\t\t\t\tbuf += '!'\r\n\t\t\telif i == 3:\r\n\t\t\t\tbuf += 'M'\r\n\t\tprint(buf)\r\n\t\r\n\r\nif __name__ == '__main__':\r\n\r\n\ttisk()\r\n\t#new_cross(w//2, h//2, smery[:])\r\n\r\n\tnew_cross(w//3, h//3, smery[:])\r\n\tnew_cross(w//3*2, h//3, smery[:])\r\n\tnew_cross(w//3, h//3*2, smery[:])\r\n\tnew_cross(w//3*2, h//3*2, smery[:])\r\n\twhile len(miners):\r\n\t\tfor m in miners:\r\n\t\t\tm.update()\r\n\t\ttisk()\r\n\t\tinput()\r\n\t\r\n\r\n\ttisk()\r\n\tfinished = 0\r\n\tprevious = 0","sub_path":"games/gamejam/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"404152375","text":"def main():\n info = input().split()\n house_prices = [int(x) for x in input().split()]\n\n n = int(info[0])\n m = int(info[1])\n k = int(info[2])\n min_distance = 10**10\n for i in range(len(house_prices)):\n if house_prices[i] < k and house_prices[i] != 0:\n distance = abs(i+1-m)*10\n if min_distance > distance:\n min_distance = distance\n\n print(min_distance)\n\nif __name__ == '__main__':\n main()","sub_path":"codeforces/900/buying_a_house.py","file_name":"buying_a_house.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"347624679","text":"# protocol = 'http'\n# server = 'https://httpbin.org/post'\n\nimport logging\nimport logging.handlers\nimport tempfile\nimport os\n\n# USER SETTINGS\nlog_level = logging.DEBUG\n# END\n\nformatter = logging.Formatter(\"== %(levelname)7s %(asctime)s [%(filename)s:%(lineno)s - %(funcName)s()] :\\n%(message)s\")\n\nenviroment = 'production'\nlog_file = os.path.join(tempfile.gettempdir(), \"renderownia.log\")\nlogger = logging.getLogger(enviroment)\n\nlogger.handlers[:] = []\n\nlogger.setLevel(log_level)\nch = logging.handlers.RotatingFileHandler(log_file, maxBytes=52428800, backupCount=2)\nch.setFormatter(formatter)\nch.setLevel(log_level)\nlogger.addHandler(ch)\n\n\nserver = 'http://localhost:5000/job'\n","sub_path":"cis_render/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"644061627","text":"from pyspark.sql import SparkSession\nwarehouseLocation = \"/datalake/landing\"\nspark = SparkSession\\\n.builder.appName(\"TestSparkCTIC\")\\\n.config(\"spark.sql.warehouse.dir\", warehouseLocation)\\\n.enableHiveSupport()\\\n.getOrCreate()\n\ndata2 = [1, 2, 3, 4, 5, 6 , 7, 8, 9, 10]\ndistData2 = spark.sparkContext.parallelize(data2)\ndistData3 = distData2.map(lambda x:x*2)#narrow transformation map\ndemo = distData3.collect()#Action\nprint(\"resultado\")\nprint(demo)","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"104844022","text":"##\n## Imprima la suma de la columna 2 por cada letra \n## de la columna 4, ordnados alfabeticamente.\n##\n## a,114\n## b,40\n## c,91\n## d,65\n## e,79\n## f,110\n## g,35\n##\nmail=open('data.csv','r').readlines()\nmail=[row.split('\\t') for row in mail]\nmail=[[row[3].split(','), row[1]] for row in mail]\na=dict()\nfor row in mail: \n for k in range(len(row[0])):\n if row[0][int(k)] not in a.keys():\n a[row[0][int(k)]]=0\n a[row[0][int(k)]]=a[row[0][int(k)]]+int(row[1])\nfor i in sorted(a.keys()):\n print(i,',',a[i],sep='')\n","sub_path":"q12.py","file_name":"q12.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"33642642","text":"# pylint: disable=E1101\nfrom collections import namedtuple\nfrom unittest.mock import MagicMock\n\nimport MySQLdb\nimport pytest\n\nimport libs.db.maria_db_handler as db_handler\nfrom libs.db.maria_db_handler import InsertRowObject, InvalidRowFormatError\n\nxfail = pytest.mark.xfail\n\nInvalidRowNamedTuple = namedtuple(\"InvalidRowNamedTuple\", ['data1', 'data2', 'data3'])\nFAKE_ROW_NAMED_TUPLE = InvalidRowNamedTuple('some', 'fake', 'data')\nFAKE_ROW_MAP = {\n 'column1': 'data1',\n 'column2': 'data2',\n 'column3': 'data3',\n 'column4': 'data4',\n 'column5': 'data5',\n}\nFAKE_ROW_MAP_COLUMNS = *FAKE_ROW_MAP,\nFAKE_ROW_MAP_ROW_DATA = *FAKE_ROW_MAP.values(),\nFAKE_ROW_MAP_PARAMS = '%s, %s, %s, %s, %s'\nFAKE_ROW_PRIM_KEYS = ('column1', 'column2')\nFAKE_SIMPLE_INSERT_QUERY = 'INSERT INTO sample_table_name(column1, column2) VALUES (%s, %s)'\nFAKE_SIMPLE_INSERT_QUERY_ON_DUPLICATE = (\n 'INSERT INTO sample_table_name(column1, column2) VALUES (%s, %s) ON'\n ' DUPLICATE KEY UPDATE column1 = column1, column2 = column2')\nFAKE_TABLE_NAME = 'FAKE_TABLE_NAME'\n\n\n@pytest.fixture(autouse=True)\ndef cleanup_db():\n db_handler.db = None\n\nclass MockMariaDB:\n def connect(self):\n return MagicMock()\n\n\ndef test_form_insert_query(mocker):\n FAKE_BASIC_INSERT_QUERY = 'BASIC QUERY'\n FAKE_COMPLETE_INSERT_QUERY = 'COMPLETE QUERY'\n mocker.patch.object(db_handler, '_insert_into_with_values',\n return_value=FAKE_BASIC_INSERT_QUERY)\n mocker.patch.object(db_handler, '_on_duplicate_key_update',\n return_value=FAKE_COMPLETE_INSERT_QUERY)\n db_handler._form_insert_query(FAKE_TABLE_NAME, FAKE_ROW_MAP_COLUMNS,\n FAKE_ROW_MAP_PARAMS, FAKE_ROW_PRIM_KEYS)\n\n db_handler._insert_into_with_values.assert_called_once_with(\n FAKE_TABLE_NAME, FAKE_ROW_MAP_COLUMNS, FAKE_ROW_MAP_PARAMS)\n db_handler._on_duplicate_key_update(FAKE_BASIC_INSERT_QUERY, FAKE_ROW_PRIM_KEYS)\n\n\n@pytest.mark.parametrize('table_name, columns, param_string, expected_query', [\n ('sample_table_name', ('column1', 'column2'), '%s, %s',\n 'INSERT INTO sample_table_name(column1, column2) VALUES (%s, %s)'),\n ('sample_table_name_deux', (\"column1\", \"column2\"), '%s, %s',\n 'INSERT INTO sample_table_name_deux(column1, column2) VALUES (%s, %s)'),\n ('cr@z33_t@bl3', ('#4389%$', '^&*())_+)*/\\\\'), '%s, %s',\n 'INSERT INTO cr@z33_t@bl3(#4389%$, ^&*())_+)*/\\\\\\\\) VALUES (%s, %s)'),\n ('RidicCoin_table', (\"ridic's column1\", \"ridic's column2\", \"ridic's column3\"), '%s, %s, %s',\n 'INSERT INTO RidicCoin_table(ridic\\'s column1, ridic\\'s column2, ridic\\'s column3) VALUES (%s, %s, %s)')\n])\ndef test_insert_into_with_values(table_name, columns, param_string, expected_query):\n query = db_handler._insert_into_with_values(table_name, columns, param_string)\n assert query == expected_query\n\n@pytest.mark.parametrize('prim_keys, insert_query, expected_query', [\n (None, FAKE_SIMPLE_INSERT_QUERY, FAKE_SIMPLE_INSERT_QUERY),\n ((), FAKE_SIMPLE_INSERT_QUERY, FAKE_SIMPLE_INSERT_QUERY),\n (FAKE_ROW_PRIM_KEYS, FAKE_SIMPLE_INSERT_QUERY, FAKE_SIMPLE_INSERT_QUERY_ON_DUPLICATE)\n])\ndef test_on_duplicate_key_update(prim_keys, insert_query, expected_query):\n query = db_handler._on_duplicate_key_update(insert_query, prim_keys)\n assert query == expected_query\n\n@pytest.mark.parametrize('table_columns, exp_result', [\n ([], {}),\n (['column1', 'column2'], {\n 'column1': 'data1',\n 'column2': 'data2'\n }),\n pytest.param(['mangled_column1', 'mangled_column2'], {}, marks=xfail(\n raises=KeyError, reason=\"table_columns must exist in map_data\", strict=True)),\n (['column1', 'column2', 'column3', 'column4', 'column5'], FAKE_ROW_MAP)\n])\ndef test_build_row(table_columns, exp_result):\n result = db_handler.build_row(table_columns, FAKE_ROW_MAP)\n assert result == exp_result\n\ndef test_commit_all(mocker):\n db_handler.db = MockMariaDB().connect()\n db_handler.commit_all()\n db_handler.db.commit.assert_called_once_with()\n\n\n@pytest.mark.parametrize('insert_obj, exp_columns, exp_row_data, exp_params', [\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, {}, FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must not be empty\", strict=True)),\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, FAKE_ROW_NAMED_TUPLE, FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must be a dict\", strict=True)),\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, ('some', 'tuple'), FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must be a dict\", strict=True)),\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, ['some', 'list'], FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must be a dict\", strict=True)),\n (InsertRowObject(FAKE_TABLE_NAME, FAKE_ROW_MAP, ()), FAKE_ROW_MAP_COLUMNS, FAKE_ROW_MAP_ROW_DATA, FAKE_ROW_MAP_PARAMS),\n (InsertRowObject(FAKE_TABLE_NAME, FAKE_ROW_MAP, FAKE_ROW_PRIM_KEYS), FAKE_ROW_MAP_COLUMNS, FAKE_ROW_MAP_ROW_DATA, FAKE_ROW_MAP_PARAMS)\n])\ndef test_insert_row(mocker, insert_obj, exp_columns, exp_row_data, exp_params):\n mock_cursor = MagicMock()\n mock_query = MagicMock()\n db_handler.db = MockMariaDB().connect()\n\n mocker.patch.object(db_handler, '_form_insert_query', return_value=mock_query)\n mocker.patch.object(db_handler.db, 'cursor', return_value=mock_cursor)\n\n db_handler.insert_row(insert_obj)\n\n db_handler.db.cursor.assert_called_once_with()\n mock_cursor.execute.assert_called_once_with(mock_query, exp_row_data)\n db_handler._form_insert_query.assert_called_once_with(\n FAKE_TABLE_NAME, exp_columns, exp_params, insert_obj.prim_key_columns)\n mock_cursor.close.assert_called_once_with()\n\n\ndef test_ping_db(mocker):\n db = mocker.patch.object(db_handler, 'db')\n db_handler.ping_db()\n db.ping.assert_called_once_with()\n\n\n@pytest.mark.parametrize('db_started', [ True, False ])\ndef test_start_db(mocker, db_started):\n FAKE_USER = 'fake_user'\n FAKE_PASSWORD = 'fake_password'\n FAKE_DB_NAME = 'fake_name'\n\n if db_started:\n db_handler.db = MockMariaDB().connect()\n\n mocker.patch.object(MySQLdb, 'connect')\n db_handler.start_db(FAKE_USER, FAKE_PASSWORD, FAKE_DB_NAME)\n\n if db_started is False:\n MySQLdb.connect.assert_called_once_with(user=FAKE_USER, passwd=FAKE_PASSWORD, db=FAKE_DB_NAME)\n else:\n MySQLdb.connect.assert_not_called()\n","sub_path":"tests/unit/libs/db/test_maria_db_handler.py","file_name":"test_maria_db_handler.py","file_ext":"py","file_size_in_byte":6561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"540235969","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ResnetBlock(nn.Module):\n def __init__(self, size_in, size_out):\n super().__init__()\n size_h = min(size_in, size_out)\n\n self.fc_0 = nn.Linear(size_in, size_h)\n self.fc_1 = nn.Linear(size_h, size_out)\n self.fc_2 = nn.Linear(size_in, size_out, bias=False)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n dx = self.fc_0(self.relu(x))\n dx = self.fc_1(self.relu(dx))\n\n x_skip = self.fc_2(x)\n\n return x_skip + dx\n\n\nclass PointNetEncoder(nn.Module):\n def __init__(self):\n super(PointNetEncoder, self).__init__()\n self.fc1 = nn.Linear(3, 512)\n self.resnet_1 = ResnetBlock(512, 256)\n self.resnet_2 = ResnetBlock(512, 256)\n self.resnet_3 = ResnetBlock(512, 256)\n self.resnet_4 = ResnetBlock(512, 256)\n self.fc_final = nn.Linear(256, 256)\n\n def forward(self, x):\n x = x.squeeze(dim=3)\n x = x.permute(0, 2, 1)\n\n x = F.relu(self.fc1(x))\n\n x = self.resnet_1(x)\n\n n, k, c = x.size()\n x = x.permute(0, 2, 1)\n\n pooled = F.max_pool1d(x, k).expand(x.size())\n x = torch.cat([x, pooled], dim=1)\n\n x = x.permute(0, 2, 1)\n\n x = F.relu(x)\n\n x = self.resnet_2(x)\n\n n, k, c = x.size()\n\n x = x.permute(0, 2, 1)\n\n pooled = F.max_pool1d(x, k).expand(x.size())\n x = torch.cat([x, pooled], dim=1)\n\n x = x.permute(0, 2, 1)\n\n x = F.relu(x)\n x = self.resnet_3(x)\n\n n, k, c = x.size()\n\n x = x.permute(0, 2, 1)\n\n pooled = F.max_pool1d(x, k).expand(x.size())\n x = torch.cat([x, pooled], dim=1)\n\n x = x.permute(0, 2, 1)\n\n x = self.resnet_4(x)\n n, k, c = x.size()\n x = x.permute(0, 2, 1)\n\n x = F.max_pool1d(x, k)\n\n x = x.squeeze(dim=2)\n pts = self.fc_final(x)\n\n return pts\n\n\nclass Block(nn.Module):\n def __init__(self):\n super(Block, self).__init__()\n self.fc1 = nn.Conv2d(256, 256, kernel_size=1)\n self.fc2 = nn.Conv2d(256, 256, kernel_size=1)\n self.bn1 = nn.BatchNorm2d(256, affine=False, track_running_stats=True)\n self.bn2 = nn.BatchNorm2d(256, affine=False, track_running_stats=True)\n self.gammaLayer1 = nn.Conv1d(256, 256, kernel_size=1)\n self.gammaLayer2 = nn.Conv1d(256, 256, kernel_size=1)\n self.betaLayer1 = nn.Conv1d(256, 256, kernel_size=1)\n self.betaLayer2 = nn.Conv1d(256, 256, kernel_size=1)\n\n def forward(self, y):\n x = y['ex']\n n, c, k, d = x.size()\n\n encoding = y['enc']\n gamma = self.gammaLayer1(encoding)\n\n # Need to stack the beta and gamma\n # so that we multiply all the points for one mesh\n # by the same value\n gamma = torch.stack([gamma for _ in range(k)], dim=2)\n\n beta = self.betaLayer1(encoding)\n beta = torch.stack([beta for _ in range(k)], dim=2)\n\n # First apply Conditional Batch Normalization\n out = gamma * self.bn1(x) + beta\n # Then ReLU activation function\n out = F.relu(out)\n # fully connected layer\n out = self.fc1(out)\n # Second CBN layer\n gamma = self.gammaLayer2(encoding)\n gamma = torch.stack([gamma for _ in range(k)], dim=2)\n\n beta = self.betaLayer2(encoding)\n beta = torch.stack([beta for _ in range(k)], dim=2)\n\n out = gamma * self.bn2(out) + beta\n # RELU activation\n out = F.relu(out)\n # 2nd fully connected\n out = self.fc2(out)\n # Add to the input of the ResNet Block\n out = x + out\n\n return {'ex': out, 'enc': encoding}\n\n\nclass OccupancyModel(nn.Module):\n def __init__(self):\n super(OccupancyModel, self).__init__()\n self.blocks = self.makeBlocks()\n self.encoderModel = PointNetEncoder()\n self.gammaLayer = nn.Conv1d(256, 256, kernel_size=1)\n self.betaLayer = nn.Conv1d(256, 256, kernel_size=1)\n self.cbn = nn.BatchNorm2d(256, affine=False, track_running_stats=True)\n self.fc1 = nn.Conv2d(3, 256, kernel_size=1)\n self.fc2 = nn.Conv2d(256, 1, kernel_size=1)\n\n def makeBlocks(self):\n blocks = []\n for _ in range(5):\n blocks.append(Block())\n return nn.Sequential(*blocks)\n\n def forward(self, x, pointcloud):\n n, c, k, d = x.size()\n pt_cloud = self.encoderModel(pointcloud)\n pt_cloud = pt_cloud.view(-1, 256, 1) # Add's another dimension? dunno why\n x = self.fc1(x)\n # 5 pre-activation ResNet-blocks\n x = self.blocks({'enc': pt_cloud, 'ex': x})\n x = x['ex']\n # CBN\n gamma = self.gammaLayer(pt_cloud)\n gamma = torch.stack([gamma for _ in range(k)], dim=2)\n beta = self.betaLayer(pt_cloud)\n beta = torch.stack([beta for _ in range(k)], dim=2)\n x = gamma.mul(self.cbn(x)).add_(beta)\n x = F.relu(x)\n x = self.fc2(x)\n x = x.view(-1, 1)\n x = torch.sigmoid(x)\n\n return x\n","sub_path":"point_completion_occupancy_model/models/point_completion.py","file_name":"point_completion.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"297590558","text":"class BConv:\r\n txt = None\r\n\r\n def __init__(self, text):\r\n self.txt = text\r\n\r\n def convert(self):\r\n toOriginal = []\r\n split_text = list(self.txt)\r\n for i in range(0, len(split_text) - 1):\r\n current = split_text[i]\r\n next = split_text[i + 1]\r\n if current.lower() == \"a\" or current.lower() == \"e\" or current.lower() == \"i\" or current.lower() == \"o\" or current.lower() == \"u\" or current.isspace():\r\n\r\n if next.lower() == \"a\" or next.lower() == \"e\" or next.lower() == \"i\" or next.lower() == \"o\" or next.lower() == \"u\":\r\n toOriginal.append(current + \"+\")\r\n else:\r\n toOriginal.append(current)\r\n else:\r\n toOriginal.append(current + \"+\")\r\n\r\n if next.lower() == \"a\" or next.lower() == \"e\" or next.lower() == \"i\" or next.lower() == \"o\" or next.lower() == \"u\":\r\n toOriginal.append(next)\r\n else:\r\n toOriginal.append(next + \"+\")\r\n\r\n new_str = \" \"\r\n\r\n for item in toOriginal:\r\n new_str += item\r\n\r\n return new_str\r\n\r\n @staticmethod\r\n def listToString(s):\r\n str1 = None\r\n\r\n for ele in s:\r\n str1 += ele\r\n\r\n return str1\r\n","sub_path":"BaybayinConverter/BConv.py","file_name":"BConv.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"497568289","text":"#! python3\n'''Cleans all the recipes in the folder, does not do anything to already\nclean recipes. Ignores any file that starts with an underscore'''\n\nimport sys\nimport os\nimport re\nfrom os.path import join as join_path\n\n\nbad = r\"1/2 1/3 1/4 1/8 2/3 3/4 3/8 5/8 7/8 tsp tbsp Tbsp tbs(?!p) Tbs(?!p) cup Oz Lb\".split(\" \")\ngood = \"½ ⅓ ¼ ⅛ ⅔ ¾ ⅜ ⅝ ⅞ tsp Tbsp Tbsp Tbsp Tbsp Cup oz lb\".split(\" \")\nrepls = list(zip(bad, good))\n\ndef fix_title(title):\n new_title = re.sub(r\"\\.|'|,\", \"\", title)\n new_title = re.sub(\"&\", \"and\", new_title)\n new_title = re.sub(\" \", \"-\", new_title)\n new_title = re.sub(\"---\", \"--\", new_title)\n new_title = re.sub(r\"\\(|\\)\", \"_\", new_title)\n return new_title.strip()\n\ndef clean(text):\n \"\"\"fix measures, fractions, and some other things\"\"\"\n #clean structure\n text = re.sub(r\"(? \").casefold()\n \n if chap == \"savory\".casefold():\n dest_folder = savory_folder\n page_template = savory_template\n \n elif chap == \"sweet\".casefold():\n dest_folder = sweet_folder\n page_template = sweet_template\n \n else:\n input(\"I don't know what {} means \".format(chap))\n sys.exit(1)\n \n found = all_local_files(source_folder, dest_folder)\n if not found:\n print(\"No new files found? Updating index anyway.\")\n else:\n print(\"Updating index.\")\n \n items = generate_list(dest_folder, list_entry_template)\n index_text = page_template+''.join(items)\n\n with open(join_path(dest_folder, \"index.markdown\"), \"w\", encoding=\"utf8\") as file:\n file.write(index_text)\n print(\"New index generated.\")\n\n input(\"press enter to end. \")\n\nmain()","sub_path":"markdown pages/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"372862947","text":"#coding = utf-8\n'''\n删除圈子浏览历史记录\n\n'''\n\nimport requests\nimport hashlib\nimport json\nfrom USER.Login import login\nfrom pprint import pprint\n\n\nu_id,u_token = login()#直接使用两个变量来接收login()函数返回的两个值,这就是利用了 Python 提供的序列解包功能。\napp_key_old = 'c40e32c6ac99617b'\napp_key = '193dd7cc7845df55'\nsign_new = '6cefaf5e35a382e6'\nget_id = '39938'\n\n'''\n获取帖子浏览历史\n'''\n\ndef get_history():\n data = 'appkey=%s&pg=1&token=%s&userId=%s|%s'%(app_key,u_token,u_id,sign_new)\n signs = hashlib.md5(data.encode(encoding='utf-8')).hexdigest()\n return signs\n\ndef history_list():\n url = 'http://a.api1.peiyinxiu.com/Api/Topic/GetTopicHistoryList'\n header = {'Content-Type':'application/json'}\n data = {'appkey':app_key,'pg':'1','token':u_token,'userId':u_id,'sign':get_history()}\n resq = requests.get(url,params=data,headers= header)\n # pprint(resq.text)\n # 编码:把一个Python对象编码转换成Json字符串\n # json.dumps()\n # 解码:把Json格式字符串解码转换成Python对象\n # json.loads()\n get_date = json.loads(resq.text)\n dates = get_date['data']\n pprint(dates)\n '''取出帖子ID'''\n ID_list = []\n for id in range(len(dates)):\n ID = dates[id]['id']\n ID_list.append(ID)\n print(ID_list)\n\ndef get_sign():\n data = 'appkey=%s&id=%s&token=145e1bdddacaaa7038e5be88fddbb209&userId=%s|%s'%(app_key,get_id,use_id,sign_new)\n signs = hashlib.md5(data.encode(encoding='utf-8')).hexdigest()\n return signs\n\ndef deletehistory():\n url = 'http://a.api1.peiyinxiu.com/Api/Topic/DeleteTopicHistory'\n headers = {'Content-Type':'application/json'}\n data ={'appkey':app_key,'id':get_id,'token':'145e1bdddacaaa7038e5be88fddbb209','userId':use_id,'sign':get_sign()}\n resq = requests.post(url,params=data,headers=headers)\n print(resq.text)\n\n'''\n清空所有圈子浏览历史记录\n'''\ndef deletehistory_all():\n sign_data = 'appkey=%s&token=145e1bdddacaaa7038e5be88fddbb209&userId=%s|%s'%(app_key,use_id,sign_new)\n signs = hashlib.md5(sign_data.encode(encoding='utf-8')).hexdigest()\n\n url = 'http://a.api1.peiyinxiu.com/Api/Topic/DeleteTopicHistoryAll'\n headers = {'Content-Type':'application/json'}\n data = {\n 'appkey' : app_key ,\n 'token' : '145e1bdddacaaa7038e5be88fddbb209' ,\n 'userId' : use_id ,\n 'sign' : signs\n }\n\n resp = requests.post(url,params= data,headers= headers)\n print(resp.text)\n\n\nif __name__==\"__main__\":\n # deletehistory()\n # deletehistory_all()\n history_list()\n","sub_path":"Circle/DeleteHistory.py","file_name":"DeleteHistory.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"569322681","text":"import parse_data\nimport difflib\nimport sys\nimport os\nimport pickle\nimport random\n\ndef build_ngrams(inDocs, outDocs, n):\n igrams = []\n ograms = []\n for di, do in zip(inDocs, outDocs):\n if len(di) < len(do):\n di = di + ['NULL' for i in range(len(do) - len(di))]\n elif len(do) < len(di):\n do = do + ['NULL' for i in range(len(di) - len(do))]\n for i in range(len(di) - n + 1):\n igrams.append(di[i:i+n])\n ograms.append(do[i:i+n])\n\n return igrams, ograms\n\ndef countPairs(igrams, ograms):\n counts = {}\n for ig, og in zip(igrams, ograms):\n ig = ' '.join(ig)\n og = ' '.join(og)\n if ig not in counts:\n counts[ig] = {}\n\n counts[ig][og] = counts[ig].get(og, 0) + 1\n\n return counts\n\n# Count common replacements\ndef countReplacements(toks):\n cts = {}\n i=0\n for di, do in toks:\n sys.stdout.write('\\r{:d}'.format(i))\n i+=1\n diff = difflib.ndiff(di, do)\n\n prevWord = None\n addChain = []\n delChain = []\n for x in diff:\n prefix = x[0]\n text = x[2:]\n if prefix == ' ':\n addText = ' '.join(addChain)\n\n # If just an insertion, no deleted words\n # Treat it as a replacement of adjacent words with more text\n if len(addChain) > 0 and len(delChain) == 0:\n if prevWord is not None:\n if prevWord not in cts:\n cts[prevWord] = {}\n addBeforeText = prevWord + ' ' + addText\n cts[prevWord][addBeforeText] = cts[prevWord].get(addBeforeText, 0) + 1\n\n if text not in cts:\n cts[text] = {}\n addAfterText = addText + ' ' + text\n cts[text][addAfterText] = cts[text].get(addAfterText, 0) + 1\n # Otherwise, it is a replacement if either chain is non-empty\n elif len(addChain) > 0 or len(delChain) > 0:\n delText = ' '.join(delChain)\n if delText not in cts:\n cts[delText] = {}\n cts[delText][addText] = cts[delText].get(addText, 0) + 1\n\n addChain = []\n delChain = []\n prevWord = text\n elif prefix == '+':\n addChain.append(text)\n elif prefix == '-':\n delChain.append(text)\n\n # A replacement at the end of the document\n addText = ' '.join(addChain)\n delText = ' '.join(delChain)\n if len(addChain) > 0 and len(delChain) == 0:\n if prevWord is not None:\n if prevWord not in cts:\n cts[prevWord] = {}\n addBeforeText = prevWord + ' ' + addText\n cts[prevWord][addBeforeText] = cts[prevWord].get(addBeforeText, 0) + 1\n elif len(addChain) > 0 or len(delChain) > 0:\n if delText not in cts:\n cts[delText] = {}\n cts[delText][addText] = cts[delText].get(addText, 0) + 1\n\n print()\n return cts\n\ndef ngramTermFreq(toks, n=3):\n tf = {}\n it=0\n for di, do in toks:\n sys.stdout.write('\\r{:d}'.format(it))\n it+=1\n for i in range(1, n+1):\n igrams, ograms = build_ngrams([di], [do], i)\n for w in igrams:\n w = ' '.join(w)\n tf[w] = tf.get(w,0) + 1\n print()\n return tf\n\n\n\ndef relativeReplaceFreq(toks, thresh=10):\n cts = countReplacements(toks)\n tf = ngramTermFreq(toks, 2)\n res = {w: {k: v/tf[w] for k,v in cts[w].items()} for w in cts if tf.get(w,0) > thresh}\n return res\n\n\n\ndef doReplace(grams, cts):\n igrams, ograms = grams\n res = []\n for x in igrams:\n x = ' '.join(x)\n if x in cts:\n bestRep = max(cts[x], key=lambda y: cts[x][y])\n if sum(cts[x].values()) > 30:\n res += bestRep.split(' ')\n else:\n res.append([x])\n else:\n res.append([x])\n return res\n\ndef doReplaceFreqReplace(docs, cts, n=5):\n res = []\n for d in docs:\n rd = []\n j = 0\n while j < len(d):\n rep = False\n for k in range(1, n+1):\n if j+k <= len(d):\n w = ' '.join(d[j:j+k])\n if w in cts:\n rd += cts[w].split(' ')\n j+=k\n rep=True\n break\n if not rep:\n rd.append(d[j])\n j+=1\n res.append(rd)\n return res\n\n\ndef termFreq(docs):\n cts = {}\n for di, do in docs:\n for w in di:\n cts[w] = cts.get(w,0) + 1\n return cts\n\n\ndef loadOrElse(path, func):\n if os.path.exists(path):\n with open(path, 'rb') as inFile:\n res = pickle.load(inFile)\n else:\n res = func()\n with open(path, 'wb') as outFile:\n pickle.dump(res, outFile)\n return res\n\ndef testReplacementModel(cts, tf, N, testToks, countThresh, freqThresh):\n cts = {w: {k: v/tf[w] for k,v in cts[w].items()} for w in cts if tf.get(w,0) > countThresh}\n cts = {w: max(cts[w].items(), key=lambda x: x[1]) for w in cts}\n cts = {k: v[0] for k,v in cts.items() if v[1] >= freqThresh}\n print(\"Num replacements: \" + str(len(cts)))\n print(\"Doing replacements\")\n res = doReplaceFreqReplace(map(lambda x: x[0], testToks), cts, N)\n print(\"Scoring\")\n sumRep = 0\n for r, t in zip(res, testToks):\n dr = r\n di, do = t\n sumRep += difflib.SequenceMatcher(None, dr, do).ratio()\n\n\n return sumRep/len(testToks), cts\n\n\n#Current best: 0.815602 acc, 87 count, 0.343530 freq\ndef replacementModelFineTune():\n N = 5\n # toks = parse_data.readTokens('data/train.uniq.tsv')\n print('Reading data')\n toks = loadOrElse('toks.pkl', lambda: parse_data.readTokens('/home/henry/Downloads/5gram-edits-train.uniq.tsv'))\n testToks = parse_data.readTokens('data/dev.tsv.nopunc.tsv')\n\n # cts = countReplacements(toks)\n print('Doing counts')\n cts = loadOrElse('counts.pkl', lambda: countReplacements(toks))\n tf = loadOrElse('termFreq{:d}.pkl'.format(N), lambda: ngramTermFreq(toks, N))\n\n bestParams = (86,0.310787)\n bestAcc = 0.815564\n while True:\n countThresh = random.randint(1,100)\n freqThresh = random.random()\n acc, model = testReplacementModel(cts, tf, N, testToks, countThresh, freqThresh)\n if acc > bestAcc:\n bestAcc = acc\n bestParams = (countThresh, freqThresh)\n # Save the model for later\n with open('replacementModel.best.pkl', 'wb') as outFile:\n pickle.dump(model, outFile)\n print(\"Last: {:.6f} acc, {:d} count, {:.6f} freq\".format(acc, countThresh, freqThresh))\n print(\"Current best: {:.6f} acc, {:d} count, {:.6f} freq\".format(bestAcc, *bestParams))\n\ndef testPairedModel():\n return 0\n\nif __name__ == '__main__':\n replacementModelFineTune()\n\n\n\n\n","sub_path":"ngram_replace.py","file_name":"ngram_replace.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"33281472","text":"# Copyright 2016 Mellanox Technologies, Ltd\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\nfrom oslo_config import cfg\n\nfrom networking_mlnx._i18n import _\nfrom networking_mlnx.plugins.ml2.drivers.sdn import constants as sdn_const\n\nsdn_opts = [\n cfg.BoolOpt('sync_enabled',\n help=_(\"Whether synchronising state to an SDN provider is \"\n \"enabled.\"),\n default=True),\n cfg.StrOpt('url',\n help=_(\"HTTP URL of SDN Provider.\"),\n ),\n cfg.StrOpt('domain',\n help=_(\"Cloud domain name in SDN provider \"\n \"(for example: cloudx)\"),\n default='cloudx'\n ),\n cfg.StrOpt('username',\n help=_(\"HTTP username for authentication.\"),\n ),\n cfg.StrOpt('password',\n help=_(\"HTTP password for authentication.\"),\n secret=True,\n default='123456'\n ),\n cfg.IntOpt('timeout',\n help=_(\"HTTP timeout in seconds.\"),\n default=10\n ),\n cfg.IntOpt('sync_timeout', default=10,\n help=_(\"Sync thread timeout in seconds.\")),\n cfg.IntOpt('retry_count', default=-1,\n help=_(\"Number of times to retry a row \"\n \"before failing.\"\n \"To disable retry count value should be -1\")),\n cfg.IntOpt('maintenance_interval', default=300,\n help=_(\"Journal maintenance operations interval \"\n \"in seconds.\")),\n cfg.IntOpt('completed_rows_retention', default=600,\n help=_(\"Time to keep completed rows in seconds.\"\n \"Completed rows retention will be checked every \"\n \"maintenance_interval by the cleanup thread.\"\n \"To disable completed rows deletion \"\n \"value should be -1\")),\n cfg.IntOpt('processing_timeout', default='100',\n help=_(\"Time in seconds to wait before a \"\n \"processing row is marked back to pending.\")),\n cfg.ListOpt('physical_networks',\n default=sdn_const.ANY,\n help=_(\"Comma-separated list of \"\n \"that it will send notification. * \"\n \"means all physical_networks\")),\n]\n","sub_path":"networking_mlnx/plugins/ml2/drivers/sdn/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"133358517","text":"#!/usr/bin/env python\n\n__author__ = 'Adam R. Smith'\n__license__ = 'Apache 2.0'\n\nfrom pyon.core.process import GreenProcess, PythonProcess, GreenProcessSupervisor\nfrom pyon.util.int_test import IonIntegrationTestCase\nfrom unittest import SkipTest\nfrom nose.plugins.attrib import attr\n\nimport time\n\n@attr('UNIT', group='process')\nclass ProcessTest(IonIntegrationTestCase):\n def setUp(self):\n self.counter = 0\n\n def increment(self, amount=1):\n self.counter += amount\n\n def test_green(self):\n self.counter = 0\n proc = GreenProcess(self.increment, 2)\n proc.start()\n self.assertEqual(self.counter, 0)\n proc.join()\n self.assertEqual(self.counter, 2)\n\n def test_supervisor(self):\n self.counter = 0\n sup = GreenProcessSupervisor()\n sup.start()\n proc = sup.spawn(('green', self.increment), amount=2)\n self.assertEqual(self.counter, 0)\n sup.join_children()\n self.assertEqual(self.counter, 2)\n\n def test_supervisor_shutdown(self):\n \"\"\" Test shutdown joining/forcing with timeouts. \"\"\"\n sup = GreenProcessSupervisor()\n sup.start()\n\n import gevent\n self.assertIs(time.sleep, gevent.hub.sleep)\n\n # Test that it takes at least the given timeout to join_children, but not much more\n proc_sleep_secs, proc_count = 0.01, 5\n [sup.spawn(('green', time.sleep), proc_sleep_secs) for i in xrange(5)]\n elapsed = sup.shutdown(2*proc_sleep_secs)\n # MM, 1/12: Ok, I loosened the timing boundaries. Do the tests still work?\n # Enabled 0.2s of slack for all tests\n\n self.assertLess(elapsed - proc_sleep_secs, 0.2)\n\n # this could be trouble\n self.assertLess(elapsed, 0.2 + proc_sleep_secs*3)\n\n # Test that a small timeout forcibly shuts down without waiting\n wait_secs = 0.0001\n [sup.spawn(('green', time.sleep), proc_sleep_secs) for i in xrange(5)]\n elapsed = sup.shutdown(wait_secs)\n self.assertLess(elapsed - wait_secs, 0.2)\n\n # this could be trouble too\n self.assertLess(elapsed, 0.2 + proc_sleep_secs)\n\n # Test that no timeout waits until all finished\n [sup.spawn(('green', time.sleep), proc_sleep_secs) for i in xrange(5)]\n elapsed = sup.shutdown()\n self.assertLess(elapsed - proc_sleep_secs, 0.2)\n\n def test_python(self):\n raise SkipTest('Need a better test here')\n self.counter = 0\n proc = PythonProcess(self.increment, 2)\n proc.start()\n self.assertEqual(self.counter, 0)\n proc.join()\n self.assertEqual(self.counter, 2)\n","sub_path":"pyon/core/test/test_process.py","file_name":"test_process.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"569382243","text":"import dash\nimport dash_table\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\nimport pandas as pd\nimport numpy as np\nfrom textwrap import dedent as d\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nimport plotly.express as px\nfrom plotly.offline import plot\nimport dash_table.FormatTemplate as FormatTemplate\nfrom dash_table.Format import Sign\n#from sklearn.externals import joblib\nimport joblib\nfrom util import dynamic_predict\n\nfrom visualization import analysis \n# from visualization import plots \n\ncsv_path = 'data/bank-additional-full.csv'\nmy_analysis = analysis.Analysis(csv_path)\nmyList, labels = my_analysis.map_age()\n\n# Read and modify prediction data\npredictions = pd.read_csv('data/predictions.csv')\n\ndf = predictions.copy()\n\ndf = df[['customer_id', 'age', 'job_transformed', 'poutcome', 'pred', 'prob_1']] # prune columns for example\ndf.sort_values(by = ['prob_1'], ascending = False, inplace = True)\ndf['prob_1'] = np.around(df['prob_1'], decimals = 2)\ndf['is_called'] = 'Not Called'\n\ndf.loc[df['job_transformed'] == 'no_income', 'job_transformed'] = 'No Income'\ndf.loc[df['job_transformed'] == 'higher_income', 'job_transformed'] = 'Higher Income'\ndf.loc[df['job_transformed'] == 'lower_income', 'job_transformed'] = 'Lower Income'\ndf.loc[df['job_transformed'] == 'unknown', 'job_transformed'] = 'Unknown'\n\ndf.loc[df['poutcome'] == 'success', 'poutcome'] = 'Success'\ndf.loc[df['poutcome'] == 'nonexistent', 'poutcome'] = 'None'\ndf.loc[df['poutcome'] == 'failure', 'poutcome'] = 'Failure'\n\ndef marital_state_distribution():\n '''\n This function gives the plot of distribution of people based on marital status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n\n\n '''\n percents = my_analysis.percentage_of_population('marital')\n v = my_analysis.get_count('marital')['y']\n values = [v[1], v[0], v[2], v[3]]\n labels = ['Married', 'Divorced', 'Single', 'Unknown']\n my_analysis.get_count('marital')\n explode = (0.2, 0, 0)\n fig = px.pie(percents, values= values, names = labels, \n title = '% of Population based on marital status')\n return fig\n \ndef marital_status_probab():\n '''\n This function gives the plot of probability of success based on people's marital status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n marital_status_probab = my_analysis.get_probabilities('marital')\n data = marital_status_probab\n data['y'] = data['y']*100\n fig = px.bar(data, x='marital', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'marital': 'Marital Status'},\n height=400, title = 'Probability of success by marital status')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef education_level_distribution():\n '''\n This function gives plot of distribution of people based on education level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n \n percents = my_analysis.percentage_of_population('education')\n v = my_analysis.get_count('education')['y']\n values = [v[1], v[0], v[2], v[3], v[4], v[5], v[6], v[7]]\n labels = ['basic_4y', 'basic_6y', 'basic_9y', 'high school', 'illiterate', 'professional course', 'university degree', 'unknown']\n fig = px.pie(percents, values= values, names = labels, \n title = '% of Population based on education')\n return fig\n\ndef education_level_prob():\n '''\n This function gives the plot of probability of success based on people's education level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n data = my_analysis.get_probabilities('education')\n data['y'] = data['y']*100\n fig = px.bar(data, x='education', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'education': 'Education Level'},\n height=400, title = 'Probability of success by education')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef income_level_distribution():\n '''\n This function gives plot of distribution of people based on income level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n percents = my_analysis.percentage_of_population('job')\n v = my_analysis.get_count('job')['y']\n values = [v[1], v[0], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11]]\n labels = ['admin', 'blue-collar', 'entrepreneur', 'house maid', 'management', 'retired', 'self-employed', 'services', 'student', 'technician', 'unemployed', 'unknown']\n fig = px.pie(percents, values= values, names = labels, \n title = '% of Population based on job')\n return fig\n\ndef job_prob():\n '''\n This function gives the plot of probability of success based on people's job level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n job_prob = my_analysis.get_probabilities('job')\n data = job_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='job', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'job': 'Job'},\n height=400, title = 'Probability of success by job')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef contact_way_distribution():\n '''\n This function gives plot of distribution of people based on how they were contacted, i.e, cell phone or telephone.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n contact_count = my_analysis.get_count('contact')\n contact_success_count = my_analysis.get_success_count('contact')\n status=['cellular', 'telephone']\n\n fig = go.Figure(data=[\n go.Bar(name='Not Successful', x=status, y=contact_count['y']-contact_success_count['y']),\n go.Bar(name='Success', x=status, y=contact_success_count['y'])\n ])\n # Change the bar mode\n fig.update_layout(barmode='stack', xaxis_title=\"Contact type\", yaxis_title=\"Number of people\", title = 'Number of people contacted on cellular phone or telephone')\n return fig\n\ndef contact_prob():\n '''\n This function gives plot of probability of success based on how people were contacted, i.e, cell phone or telephone.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n contact_prob = my_analysis.get_probabilities('contact')\n data = contact_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='contact', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'contact': 'Contact type'},\n height=400, title = 'Probability of success by method of contact')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef loan_status():\n '''\n This function gives the plot of distribution of people based on loan status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n loan_count = my_analysis.get_count('loan')\n loan_success_count = my_analysis.get_success_count('loan')\n status=['yes', 'no', 'Info Not Available']\n\n fig = go.Figure(data=[\n go.Bar(name='Not Successful', x=status, y=loan_count['y']-loan_success_count['y']),\n go.Bar(name='Success', x=status, y=loan_success_count['y'])\n ])\n # Change the bar mode\n fig.update_layout(barmode='stack', title = \"Do people have a loan?\", xaxis_title = \"Loan status\", yaxis_title=\"Number of people\", height=400)\n return fig\n\ndef loan_prob():\n '''\n This function gives plot of probability of success based on people's loan status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n loan_prob = my_analysis.get_probabilities('loan')\n data = loan_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='loan', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'loan': 'Loan status'},\n height=400, title = 'Probability of success by loan status')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef house_status_distribution():\n '''\n This function gives the plot of distribution of people based on housing status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n housing_count = my_analysis.get_count('housing')\n housing_success_count = my_analysis.get_success_count('housing')\n status=['yes', 'no', 'Info Not Available']\n\n fig = go.Figure(data=[\n go.Bar(name='Not Successful', x=status, y=housing_count['y']-housing_success_count['y']),\n go.Bar(name='Success', x=status, y=housing_success_count['y'])\n ])\n # Change the bar mode\n fig.update_layout(barmode='stack', xaxis_title=\"Housing Status\", yaxis_title=\"Number of people\", height=400, title = 'Housing status of the population')\n return fig\n\ndef house_prob():\n '''\n This function gives plot of probability of success based on people's housing status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n housing_prob = my_analysis.get_probabilities('housing')\n data = housing_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='housing', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'housing': 'Housig Status'},\n height=400, title = 'Probability of success by housing status')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef prediction_pie_chart():\n '''\n Plot predicted telecaller success ratios on the test data.\n \n :return: Plots the prediction pie chart.\n :rtype: plotly.graph_objs._figure.Figure\n '''\n fig = px.pie(predictions, \n values=[1 for i in range(len(predictions))], \n names= np.where(predictions['pred'] == 1, 'Purchase', 'No Purchase'), \n title='Overall Telemarketing Success Predictions')\n return fig\n\ndef predicted_prob_hist():\n '''\n Plot the histogram of the predicted probabilities.\n \n :return: Plots the prediction probability histogram.\n :rtype: plotly.graph_objs._figure.Figure\n '''\n fig = px.histogram(predictions, \n x=\"prob_1\", \n nbins=5, \n labels = {'prob_1' : 'Success Probabilty'},\n title='Histogram of Success Probabilities')\n return fig\n\ndef age_distribution():\n '''\n This function gives the plot of distribution of people's responses based on age groups that they fall in.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n No = [x[0] for x in myList]\n Yes = [x[1] for x in myList]\n x = np.arange(len(labels)) \n width = 0.20 \n\n fig = go.Figure()\n fig.add_trace(go.Bar(\n x=x - width/2,\n y = No,\n name='NO',\n marker_color='indianred'\n ))\n fig.add_trace(go.Bar(\n x=x + width/2,\n y = Yes,\n name='YES',\n marker_color='lightsalmon'\n ))\n\n fig.update_layout(\n title = 'Count of yes/no response for different age groups',\n xaxis_title=\"Age Group\",\n yaxis_title=\"Number of People\",\n xaxis = dict(\n tickmode = 'array',\n tickvals = [i for i in range(len(labels))],\n ticktext = labels\n )\n )\n return fig\n\ndef age_prob():\n '''\n This function gives the plot of distribution of people's responses based on age groups that they fall in.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n data = my_analysis.get_success_count(\"age\")\n fig = px.bar(data, x='age', y='y',\n hover_data=data, labels={'y':'Number of Success (%)', 'age': 'Age'},\n height=400, title = 'Success for different ages')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n#app.scripts.config.serve_locally = True\n\napp.config['suppress_callback_exceptions'] = True\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\ntab_style = {\n 'fontWeight': 'bold'\n}\nvis_tab_style = {\n 'borderBottom': '1px solid #d6d6d6',\n 'padding': '12px',\n}\n\ntab_selected_style = {\n 'borderTop': '1px solid #d6d6d6',\n 'borderBottom': '1px solid #d6d6d6',\n 'backgroundColor': '#119DFF',\n 'color': 'white',\n 'padding': '12px'\n}\napp.layout = html.Div(children = [\n dcc.Tabs(id=\"tabs\", value='tab-1', children=[\n dcc.Tab(label='Manager Dashboard', value='tab-1', style=tab_style),\n dcc.Tab(label='Telecaller Dashboard', value='tab-2', style=tab_style),\n dcc.Tab(label='Live Prediction Dashboard', value='tab-new', style=tab_style),\n ]),\n html.Div(id='tabs-content')\n])\nlayout_tab_1 = html.Div(children = [\n dcc.Tabs(id = \"vis-tabs\", value = \"vistab\", vertical=True, parent_style={'float': 'left','width': '40'},children =[\n dcc.Tab(label='Marital Status', value='tab-3', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Educational Level', value='tab-4', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Income&Job', value='tab-5', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Contact Type', value='tab-6', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Loan Status', value='tab-7', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Housing Status', value='tab-8', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Age', value='tab-9', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Prediction Overview', value='tab-10', style=vis_tab_style, selected_style=tab_selected_style),\n ]),\n html.Div(id='vis-tabs-content',style={'float': 'right'})\n])\n\nmarital_status_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = marital_state_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center' }),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = marital_status_probab()\n )],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n ])\neducational_Level_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = education_level_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = education_level_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\nincome_vis = html.Div(children =[\n\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = income_level_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = job_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\ncontact_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = contact_way_distribution()\n ) ],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = contact_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\nloan_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = loan_status()\n ) ],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = loan_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\nhouse_vis = html.Div(children =[ \n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = house_status_distribution()\n ) ],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = house_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\n\nprediction_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"prediction_pie_chart\",\n figure = prediction_pie_chart()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"predicted_prob_hist\",\n figure = predicted_prob_hist()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n ])\n\nage_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"prediction_pie_chart\",\n figure = age_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"predicted_prob_hist\",\n figure = age_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n ])\n\n@app.callback(Output('vis-tabs-content', 'children'),\n [Input('vis-tabs', 'value')])\ndef render_content(tab):\n if tab == 'tab-3':\n return marital_status_vis\n elif tab == 'tab-4':\n return educational_Level_vis\n elif tab == 'tab-5':\n return income_vis \n elif tab == 'tab-6':\n return contact_vis \n elif tab == 'tab-7':\n return loan_vis \n elif tab == 'tab-8':\n return house_vis \n elif tab == 'tab-9':\n return age_vis\n elif tab == \"tab-10\":\n return prediction_vis\n else:\n return marital_status_vis\n\n\nlayout_tab_2 = html.Div(children =[\n \n html.Div(dash_table.DataTable(\n columns=[\n {'name': 'Customer ID', 'id': 'customer_id', 'type': 'numeric', 'editable': False},\n {'name': 'Age', 'id': 'age', 'type': 'numeric', 'editable': False},\n {'name': 'Income', 'id': 'job_transformed', 'type': 'text', 'editable': False},\n {'name': 'Previously Contacted', 'id': 'poutcome', 'type': 'text', 'editable': False},\n {'name': 'Probability of Success', 'id': 'prob_1', 'type': 'numeric', 'editable': False, 'format': FormatTemplate.percentage(1)},\n {'name': 'Call Result', 'id': 'is_called', 'type': 'any', 'editable': True, 'presentation': 'dropdown'}\n ],\n data=df.to_dict('records'),\n filter_action='native',\n dropdown={\n 'is_called': {\n 'options': [\n {'label': i, 'value': i}\n for i in ['Not Called', 'Success', 'Failure']\n ]\n }\n }, \n style_table={\n 'maxHeight': '50ex',\n 'overflowY': 'scroll',\n 'width': '100%',\n 'minWidth': '100%',\n },\n style_data={\n 'width': '150px', 'minWidth': '150px', 'maxWidth': '150px',\n 'overflow': 'hidden',\n 'textOverflow': 'ellipsis',\n },\n style_cell = {\n 'font_family': 'arial',\n 'font_size': '16px',\n 'text_align': 'center'\n },\n# style_cell_conditional=[\n# {\n# 'if': {'column_id': c},\n# 'textAlign': 'left'\n# } for c in ['customer_id', 'job_transformed', 'poutcome', 'is_called']\n# ],\n style_data_conditional=[\n {\n 'if': {'row_index': 'odd'},\n 'backgroundColor': 'rgb(248, 248, 248)'\n }, {\n 'if': {\n 'column_id': 'is_called',\n 'filter_query': '{is_called} eq \"Not Called\"'\n },\n 'backgroundColor': '#E0E280'\n }, {\n 'if': {\n 'column_id': 'is_called',\n 'filter_query': '{is_called} eq \"Success\"'\n },\n 'backgroundColor': '#8CE280'\n }, {\n 'if': {\n 'column_id': 'is_called',\n 'filter_query': '{is_called} eq \"Failure\"'\n },\n 'backgroundColor': '#E28080'\n }\n ],\n style_header={\n 'backgroundColor': 'rgb(230, 230, 230)',\n 'fontWeight': 'bold'\n },\n page_action=\"native\",\n page_current= 0,\n sort_action=\"native\",\n sort_mode=\"multi\"\n ) \n ) \n \n ])\n\nlayout_tab_new = html.Div(children =[\n html.Div(children =[\n html.Div(children =[\n html.Label('Enter number of employees (quarterly indicator): '),\n dcc.Input(id='nremployed', placeholder='# employees', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the outcome of the previous marketing campaign: '),\n dcc.Input(id='poutcome_success', placeholder='prev.', type='number', min = 0, max = 1, step = 1)],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the employment variation rate - quarterly indicator: '),\n dcc.Input(id='emp', placeholder='emp. variation rate', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the number of days since the last call (999 if NA): '),\n dcc.Input(id='pdays', placeholder='# days since last call', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the consumer confidence index (monthly indicator): '),\n dcc.Input(id='consconfidx', placeholder='consumer conf. index', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the euribor 3 month rate (daily indicator): '),\n dcc.Input(id='euribor3m', placeholder='euribor rate', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the no income indicator, 1 if the customer job retired, student or unemployed: '),\n dcc.Input(id='job_transformed_no_income', placeholder='inc', type='number', min = 0, max = 1, step = 1)],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n ]),\n \n html.Div(children=[\n html.H1(children='Probability of Success: '),\n html.Div(id='pred-output')\n ], style={'textAlign': 'center', 'justify-content': 'center'}),\n])\n@app.callback(\n Output('pred-output', 'children'),\n [Input('nremployed', 'value'),\n Input('poutcome_success', 'value'),\n Input('emp', 'value'),\n Input('pdays', 'value'),\n Input('consconfidx', 'value'),\n Input('euribor3m', 'value'),\n Input('job_transformed_no_income', 'value')])\ndef show_success_probability(nr_employed, poutcome_success, emp_var_rate, pdays, cons_conf, euribor, no_income):\n if not nr_employed: \n nr_employed = 0\n if not poutcome_success: \n poutcome_success = 0\n if not emp_var_rate: \n emp_var_rate = 0\n if not pdays: \n pdays = 0\n if not cons_conf: \n cons_conf = 0\n if not euribor: \n euribor = 0\n if not no_income:\n no_income = 0\n \n #raise PreventUpdate\n #else:\n prob = dynamic_predict(nr_employed, poutcome_success, emp_var_rate, pdays, cons_conf, euribor, no_income)[0]*100\n return html.Div(children =[\n html.H1(children=f'{round(prob, ndigits = 2)}'+\"%\")\n ])\n\n\n@app.callback(Output('tabs-content', 'children'),\n [Input('tabs', 'value')])\ndef render_content(tab):\n if tab == 'tab-1':\n return layout_tab_1\n elif tab == 'tab-2':\n return layout_tab_2\n elif tab == \"tab-new\":\n return layout_tab_new\n\nserver = app.server\n\nif __name__ == '__main__':\n model = joblib.load(\"LR_prediction.joblib\")\n #app.run_server(debug=True)\n #application.run_server(host='0.0.0.0', port=8050, debug=True)\n #application.run(debug=True, port=8080)\n #application.run_server(host='0.0.0.0')\n #app.run_server(host=\"0.0.0.0\")\n app.run_server()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":29384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"569657963","text":"captain_list= ['Ajinkya Rahane\\n', 'Virat Kohli\\n', 'Mahendra Singh Dhoni\\n', 'Anil Kumble\\n', 'Virender Sehwag\\n', 'Rahul Dravid\\n',\n 'Sourav Ganguly\\n', 'Sachin Tendulkar\\n', 'Mohammad Azharuddin\\n', 'Krishnamachari Srikkanth\\n', 'Ravi Shastri\\n',\n 'Dilip Vengsarkar\\n', 'Kapil Dev\\n', 'Gundappa Viswanath\\n', 'Bishan Singh Bedi\\n', 'Sunil Gavaskar\\n']\n\n\nfile_name = 'indian_cricket_captains.txt'\ndef write_line_to_file():\n try:\n f = open(file_name,'a')\n name = input('Enter Name of the Captains \\t:\\t')\n f.write(name+'\\n')\n except Exception as e:\n print(e)\n finally:\n f.close()\n\n\ndef write_multiple_lines_to_file():\n try:\n f = open(file_name, 'a')\n f.writelines(captain_list)\n except Exception as e:\n print(e)\n finally:\n f.close()\n\n\ndef read_all_line_from_file(number_of_chars = 0, seek_pos=0):\n try:\n with open(file_name, 'r') as read_file:\n if number_of_chars >=1:\n # data = read_file.read(number_of_chars)\n # print(data)\n # print(read_file.tell())\n # read_file.seek(seek_pos)\n data = read_file.read(number_of_chars)\n print(data)\n print(read_file.tell())\n read_file.seek(80)\n print(read_file.tell())\n print(read_file.read(80))\n print(read_file.tell())\n else:\n data = read_file.read()\n print(data)\n print(read_file.tell())\n except Exception as e:\n print(e)\n\n\ndef read_line_from_file():\n try:\n with open(file_name, 'r') as read_file:\n data1 = read_file.readline()\n print(data1, end='')\n data2 = read_file.readline()\n print(data2, end='')\n # for data in read_file:\n # print(data)\n except Exception as e:\n print(e)\n\n\ndef read_lines_from_file():\n try:\n with open(file_name, 'r') as read_file:\n data = read_file.readlines()\n print(data)\n except Exception as e:\n print(e)\n\n\n# write_line_to_file()\n# write_multiple_lines_to_file()\n# read_line_from_file()\n# read_lines_from_file()\n# read_all_line_from_file(40,90)\n\n\nimport os, sys\ndef file_exists():\n try:\n if os.path.isfile(file_name):\n print(True)\n f = open(file_name, 'r')\n else:\n print(False)\n\n if os.path.exists(file_name):\n print(True)\n else:\n print(False)\n\n lcount = wcount = ccount = 0\n for line in f:\n lcount = lcount+1\n ccount = ccount + len(line)\n words = line.split()\n wcount = wcount + len(words)\n print('Line Counts\\t:\\t',lcount)\n print('Word Counts\\t:\\t',wcount)\n print('Char Counts\\t:\\t',ccount)\n\n except Exception as e:\n print(e)\nfile_exists()","sub_path":"files_practise/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"111875137","text":"from django.urls import path\nfrom .views import *\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', post_list, name='post_list'),\n path('/', post_detail, name='post_detail'),\n path('category//', show_category, name='category'),\n path('category///', post_detail, name='post_detail'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"485733613","text":"\"\"\"\nCreated on 11/13/2019\n@author: Jingchao Yang\n\nhttps://www.kaggle.com/robikscube/tutorial-time-series-forecasting-with-xgboost\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport xgboost as xgb\nfrom xgboost import plot_importance, plot_tree\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\nplt.style.use('fivethirtyeight')\n\n\ndef create_features(df, label=None):\n \"\"\"\n Creates time series features from datetime index\n \"\"\"\n df['date'] = df.index\n df['hour'] = df['date'].dt.hour\n df['dayofweek'] = df['date'].dt.dayofweek\n df['quarter'] = df['date'].dt.quarter\n df['month'] = df['date'].dt.month\n df['year'] = df['date'].dt.year\n df['dayofyear'] = df['date'].dt.dayofyear\n df['dayofmonth'] = df['date'].dt.day\n df['weekofyear'] = df['date'].dt.weekofyear\n\n X = df[['hour', 'dayofweek', 'quarter', 'month', 'year',\n 'dayofyear', 'dayofmonth', 'weekofyear']]\n if label:\n y = df[label]\n return X, y\n return X\n\n\npjme = pd.read_csv('sampleData/PJME_hourly.csv', index_col=[0], parse_dates=[0])\nsplit_date = '01-Jan-2015'\npjme_train = pjme.loc[pjme.index <= split_date].copy()\npjme_test = pjme.loc[pjme.index > split_date].copy()\n\nX_train, y_train = create_features(pjme_train, label='PJME_MW')\nX_test, y_test = create_features(pjme_test, label='PJME_MW')\n\nreg = xgb.XGBRegressor(n_estimators=1000)\nreg.fit(X_train, y_train,\n eval_set=[(X_train, y_train), (X_test, y_test)],\n early_stopping_rounds=50,\n verbose=False) # Change verbose to True if you want to see it train\n\npjme_test['MW_Prediction'] = reg.predict(X_test)\npjme_all = pd.concat([pjme_test, pjme_train], sort=False)\n\npjme_all[['PJME_MW', 'MW_Prediction']].plot(figsize=(15, 5))\nplt.show()\n","sub_path":"Timeseries_Forecasting/XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"257036198","text":"first_name = 'alysson'\nlast_name = \"machado\"\n\n# programmer format \"i like complicated things, love me\"\nidiot_format = first_name.capitalize().__add__(\" \" + last_name.capitalize())\n\n# cool programmer format\ncool_format = first_name + \" \" + last_name\n\nprint(idiot_format)\nprint(cool_format.title())","sub_path":"content_b_variables/ex5_string_concatenation.py","file_name":"ex5_string_concatenation.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"355893430","text":"from django import forms\n#from Customers.autocomplete import CustomersAutocomplete\nfrom Project.models import Project\nfrom Customers.models import Customer\nimport autocomplete_light\n\nclass ProjectForm(autocomplete_light.ModelForm): \n customer = forms.ModelChoiceField(Customer.objects.all(),\n widget=autocomplete_light.ChoiceWidget('CustomersAutocomplete')) \n def __init__(self, *args, **kwargs):\n super(ProjectForm, self).__init__(*args, **kwargs) \n self.fields['description'].widget.attrs = {'cols': 60, 'rows': 15}\n self.fields['project'].widget.attrs = {'size': 80}\n\n class Meta:\n model = Project \n exclude = ( 'invoice', 'first_created', \n 'last_changed', 'last_accessed',\n 'created_by', 'changed_by', 'company_id', 'change_counter',) ","sub_path":"Project/forms/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"163578388","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nget_ipython().system('jupyter nbconvert --to script Sonar.ipynb')\n\n\n# In[49]:\n\n\n# imports\n\nimport numpy as np\nimport random\nimport pickle\nimport os \n\n\n# In[50]:\n\n\n# activation function\n\ndef perceptron(z):\n return -1 if z<=0 else 1\n\n# loss functions\n\ndef ploss(yhat, y):\n return max(0, -yhat*y)\n\n\n# In[51]:\n\n\nclass Sonar_Model:\n \n \n def __init__(self, dimension=None, weights=None, bias=None, activation=(lambda x: x), predict=ppredict):\n \n self._dim = dimension\n self.w = weights or np.random.normal(size=self._dim)\n self.w = np.array(self.w)\n self.b = bias if bias is not None else np.random.normal()\n self._a = activation\n #self.predict = predict.__get__(self)\n \n def __str__(self):\n \n return \"Simple cell neuron\\n \\tInput dimension: %d\\n \\tBias: %f\\n \\tWeights: %s\\n \\tActivation: %s\" % (self._dim, self.b, self.w, self._a.__name__)\n \n #Sonar class should have a predict(v) method that uses internal weights to make prediction on new data \n \n def __call__(self, v):\n\n yhat = self._a(np.dot(self.w, np.array(v)) + self.b)\n return yhat\n \n def ppredict(self, x):\n return self(x)\n\n \n def load_model(self, file_path):\n '''\n open the pickle file and update the model's parameters\n '''\n \n file = pickle.load(open(file_path,'rb'))\n \n self._dim = file._dim\n self.w = file.w\n self.b = file.b\n self._a = file._a\n \n\n\n def save_model(self):\n '''\n save your model as 'sonar_model.pkl' in the local path\n '''\n saved = open('sonar_model.pkl','wb')\n cat_model = pickle.dump(self, saved)\n saved.close\n \n \n \n \n \n \n\n\n# In[52]:\n\n\nclass Sonar_Trainer:\n \n def __init__(self, dataset, model):\n \n self.dataset = dataset\n self.model = model\n self.loss = ploss\n\n def accuracy(self, data):\n '''\n return the accuracy on data given data iterator\n '''\n acc = 100*np.mean([1 if self.model.ppredict(x) == y else 0 for x, y in data])\n return acc\n \n \n \n #Sonar class should have a public method train, which trains the perceptron on loaded data\n def train(self, lr, ne):\n '''\n This method should:\n 1. display initial accuracy on the training data loaded in the constructor\n 2. update parameters of the model instance in a loop for ne epochs using lr learning rate\n 3. display final accuracy\n '''\n \n print(\"training model on data...\")\n accuracy = self.accuracy(self.dataset)\n print(\"initial accuracy: %.3f\" % (accuracy))\n \n for epoch in range(ne+1):\n self.dataset._shuffle()\n for d in self.dataset:\n x, y = d\n x = np.array(x)\n yhat = self.model(x)\n error = y - yhat\n self.model.w += lr*(y-yhat)*x \n self.model.b += lr*(y-yhat)\n accuracy = self.accuracy(self.dataset) \n print('>epoch=%d, learning_rate=%.3f, accuracy=%.3f' % (epoch+1, lr, accuracy))\n \n print(\"training complete\")\n \n #Train method returns a single float representing the mean squarre error on the trained set\n print(\"final accuracy: %.3f\" % (accuracy))\n\n\n# In[55]:\n\n\nclass Sonar_Data:\n\n\n#Sonar Class should have the datafile relative path (string) and name (string) as contrustor arguments\n \n def __init__(self, relative_path='C:/Users/gigi-/OneDrive/Documents/MA2/GitHub/ProjetAI/IntroAI/keio2019aia/data/assignment1', data_file_name='sonar_data.pkl'):\n '''\n initialize self.index; load and preprocess data; shuffle the iterator\n '''\n self.index = -1\n full_path = os.path.join(relative_path,data_file_name)\n self.raw = pickle.load(open(full_path,'rb'))\n self.simple = [(list(d), -1) for d in self.raw['r']]+[(list(d), 1) for d in self.raw['m']]\n \n def __iter__(self):\n '''\n See example code (ngram) in lecture slides\n '''\n return self\n\n def __next__(self):\n '''\n See example code (ngram) in slides\n '''\n self.index += 1\n \n if self.index == len(self.simple):\n self.index = -1\n raise StopIteration\n \n return self.simple[self.index][0], self.simple[self.index][1]\n\n def _shuffle(self):\n '''\n shuffle the data iterator\n '''\n return random.shuffle(self.simple)\n \n \n\n\n# In[94]:\n\n\ndef main():\n\n data = Sonar_Data()\n model = Sonar_Model(dimension=60, activation=perceptron) # specify the necessary arguments\n trainer = Sonar_Trainer(data, model)\n trainer.train(0.01,300) # experiment with learning rate and number of epochs\n model.save_model()\n\n\nif __name__ == '__main__':\n\n main()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"assignment1/sonar.py","file_name":"sonar.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"240132939","text":"#!/usr/bin/env python3\n\nfrom cgitb import enable\nenable()\nfrom cgi import FieldStorage, escape\nfrom http.cookies import SimpleCookie\nfrom os import environ\nimport os\nfrom PIL import Image\nimport base64\n\n\n#os.environ['http_proxy']=\"http://4c.ucc.ie:80\"\n#os.environ['https_proxy']=\"http://4c.ucc.ie:80\"\n\nresult = \"problem\"\n\ncookie = SimpleCookie()\nhttp_cookie_header = environ.get(\"HTTP_COOKIE\")\nif http_cookie_header:\n cookie.load(http_cookie_header)\n if 'token' in cookie:\n token = cookie['token'].value\n path = \"/var/www/html/tmp_fold/usr_\" + token + \"/profile.png\"\n form_data = FieldStorage()\n if len(form_data) != 0:\n image = escape(form_data.getfirst(\"image\", \"\").strip())\n image = image.split(',')\n image = image[1]\n image = str.encode(photo)\n with open( path , \"wb\") as fh:\n fh.write(base64.decodestring(image))\n im = Image.open(path)\n im.convert(\"RGB\").save(path)\n result = \"good\"\nprint(\"Content-Type: text/plain\")\nprint()\nprint(result)\n","sub_path":"GUI/cam.py","file_name":"cam.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"544924430","text":"p = [\n [17, -7, -11],\n [1, 4, -1],\n [6, -2, -6],\n [19, 11, 9],\n]\n\nv = [\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n]\n\nfor i in range(1000):\n # gravity\n\n for ai, a in enumerate(p):\n for bi, b in enumerate(p):\n if ai == bi:\n continue\n for d in [0, 1, 2]:\n apos = a[d]\n bpos = b[d]\n if apos < bpos:\n v[ai][d] += 1\n v[bi][d] -= 1\n elif bpos > apos:\n v[ai][d] -= 1\n v[bi][d] += 1\n else:\n pass\n # momentum\n for ai, a in enumerate(p):\n for d in [0, 1, 2]:\n p[ai][d] += v[ai][d]\n\n # print(p)\n\nprint(p)\ns = 0\n\nfor ai, a in enumerate(p):\n vel = v[ai]\n pos = a\n\n s += sum([abs(_pos) for _pos in pos]) * sum([abs(_v) for _v in vel])\nprint(s)\n\n# 40\n# 11423\n","sub_path":"day12/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"115673921","text":"# coding=utf8\n\n# Copyright 2018 JDCLOUD.COM\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# NOTE: This class is auto generated by the jdcloud code generator program.\n\n\nclass ClusterDetailInfo(object):\n\n def __init__(self, materNum=None, masterCore=None, masterMemory=None, masterDiskType=None, masterDiskVolume=None, masterInstanceType=None, masterInstanceInfo=None, slaveNum=None, slaveCore=None, slaveMemory=None, slaveDiskType=None, slaveDiskVolume=None, slaveInstanceType=None, slaveInstanceInfo=None):\n \"\"\"\n :param materNum: (Optional) Master节点数量\n :param masterCore: (Optional) Master节点CPU\n :param masterMemory: (Optional) Master节点内存(推荐至少8G内存,否则服务可能会部署失败)\n :param masterDiskType: (Optional) \"Master节点云盘类型,可传类型为(以下以“/”分割各类型)\"\n\"NBD/NBD_SATA\"\n\"分别代表:性能型/容量型\"\n\n :param masterDiskVolume: (Optional) Master节点云盘容量,必须是10的整数倍,且大于20小于3000\n :param masterInstanceType: (Optional) Master节点规格,比如:g.n1.xlarge,更多规格请参考[文档](https://www.jdcloud.com/help/detail/296/isCatalog/1)\n :param masterInstanceInfo: (Optional) master节点实例信息\n :param slaveNum: (Optional) Slave节点数量\n :param slaveCore: (Optional) Slave节点CPU\n :param slaveMemory: (Optional) Slave节点内存(推荐至少4G内存,否则服务可能会部署失败)\n :param slaveDiskType: (Optional) \"Slave节点云盘类型,可传类型为(以下以“/”分割各类型)\"\n\"NBD/NBD_SATA\"\n\"分别代表:性能型/容量型\"\n\n :param slaveDiskVolume: (Optional) Slave节点云盘容量,必须是10的整数倍,且大于20小于3000\n :param slaveInstanceType: (Optional) Slave节点规格,比如:g.n1.xlarge,更多规格请参考[文档](https://www.jdcloud.com/help/detail/296/isCatalog/1)\n :param slaveInstanceInfo: (Optional) Slave节点实例信息\n \"\"\"\n\n self.materNum = materNum\n self.masterCore = masterCore\n self.masterMemory = masterMemory\n self.masterDiskType = masterDiskType\n self.masterDiskVolume = masterDiskVolume\n self.masterInstanceType = masterInstanceType\n self.masterInstanceInfo = masterInstanceInfo\n self.slaveNum = slaveNum\n self.slaveCore = slaveCore\n self.slaveMemory = slaveMemory\n self.slaveDiskType = slaveDiskType\n self.slaveDiskVolume = slaveDiskVolume\n self.slaveInstanceType = slaveInstanceType\n self.slaveInstanceInfo = slaveInstanceInfo\n","sub_path":"python_code/vnev/Lib/site-packages/jdcloud_sdk/services/jmr/models/ClusterDetailInfo.py","file_name":"ClusterDetailInfo.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"229513049","text":"#!/usr/global/paper/bin/python\nfrom __future__ import print_function\nimport ddr_compress.dbi as ddbi\nfrom sqlalchemy import func\nimport curses,time,os\nfrom paper.ganglia import dbi as pyg\n\n#setup my output file\nfile_log = []\nfile_status = {}\nfile_time = {}\nfile_pid = {}\nfile_start = {}\nfile_end = {}\n\n#setup my curses stuff following\n# https://docs.python.org/2/howto/curses.html\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\nstdscr.nodelay(1)\n\n#setup my db connection\ndbi = ddbi.DataBaseInterface()\npyg_dbi = pyg.DataBaseInterface()\n\nstdscr.addstr('PAPER Distiller Status Board')\nstdscr.addstr(1,0,'Press \"q\" to exit')\nstatheight = 50\nstatusscr = curses.newwin(statheight,200,5,0)\nstatusscr.keypad(1)\nstatusscr.nodelay(1)\ncurline = 2\ncolwidth = 50\nobslines = 20\ni=0\nstat = ['\\\\','|','/','-','.']\ntry:\n\ttable = getattr(ddbi, 'Observation')\n\twhile(1):\n\t\ttimestamp = int(time.time())\n\t\tlog_info = []\n\t\t#get the screen dimensions\n\n\t\t#load the currently executing files\n\t\ti += 1\n\t\tcurline = 2\n\t\tstdscr.addstr(0,30,stat[i%len(stat)])\n\t\ts = dbi.Session()\n\t\ttotalobs = s.query(table).count()\n\t\tstdscr.addstr(curline, 0, 'Number of observations currently in the database: {totalobs}'.format(totalobs=totalobs))\n\t\tcurline += 1\n\t\tOBSs = s.query(table).filter(getattr(table, 'status') != 'NEW').filter(getattr(table, 'status') != 'COMPLETE').all()\n\t\t#OBSs = s.query(table).all()\n\t\tobsnums = [OBS.obsnum for OBS in OBSs]\n\t\tstdscr.addstr(curline, 0, 'Number of observations currently being processed {num}'.format(num=len(obsnums)))\n\t\tcurline += 1\n\t\tstatusscr.erase()\n\t\tstatusscr.addstr(0, 0 ,' ---- Still Idle ---- ')\n\t\tfor j, obsnum in enumerate(obsnums):\n\t\t\ttry:\n\t\t\t\thost, path, filename= dbi.get_input_file(obsnum)\n\t\t\t\tstatus = dbi.get_obs_status(obsnum)\n\t\t\t\tstill_host = dbi.get_obs_still_host(obsnum)\n\t\t\t\tcurrent_pid = dbi.get_obs_pid(obsnum)\n\t\t\texcept:\n\t\t\t\thost, path, filename = 'host', '/path/to/', 'zen.2345672.23245.uv'\n\t\t\t\tstatus = 'WTF'\n\t\t\tcol = int(j/statusscr.getmaxyx()[0])\n\t\t\t#print(col*colwidth)\n\t\t\tif j == 0 or col == 0:\n\t\t\t\trow = j\n\t\t\telse:\n\t\t\t\trow = j % statheight\n\t\t\ttry:\n\t\t\t\tstatusscr.addstr(row, col * colwidth,\n\t\t\t\t\t'{filename} {status} {still_host}'.format(col=col, filename=os.path.basename(filename),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstatus=status, still_host=still_host))\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\t#check for new filenames\n\t\t\tpath = os.path.dirname(filename)\n\t\t\tfile_name = os.path.basename(filename)\n\t\t\tfull_path = ':'.join(still_host, filename)\n\t\t\tif filename not in file_pid.keys():\n\t\t\t\tfile_pid.update({filename:current_pid})\n\t\t\t\ttime_start = int(time.time())\n\t\t\t\tfile_start.update({filename:time_start})\n\t\t\t\tfile_end.update({filename:-1})\n\t\t\tif file_pid[filename] not in [current_pid]:\n\t\t\t\ttime_end = int(time.time())\n\t\t\t\tfile_end.update({filename:time_end})\n\t\t\t\tdel_time = -1\n\t\t\t\tfull_stats = ''.join((full_path, status))\n\t\t\t\tentry_dict = {'host':still_host,\n\t\t\t\t\t\t\t'path':path,\n\t\t\t\t\t\t\t'filename':file_name,\n\t\t\t\t\t\t\t'full_path':full_path,\n\t\t\t\t\t\t\t'status':status,\n\t\t\t\t\t\t\t'full_stats':full_stats,\n\t\t\t\t\t\t\t'del_time':del_time,\n\t\t\t\t\t\t\t'time_start':file_start[filename],\n\t\t\t\t\t\t\t'time_end':file_end[filename],\n\t\t\t\t\t\t\t'timestamp':timestamp}\n\t\t\t\tfile_log.append(entry_dict)\n\t\t\t\tfile_pid.update({filename:current_pid})\n\t\t\t\ttime_start = int(time.time())\n\t\t\t\tfile_start.update({filename:time_start})\n\t\t\t\tfile_end.update({filename:-1})\n\t\t\tif filename not in file_status.keys():\n\t\t\t\tfile_status.update({filename:status})\n\t\t\t\tdel_time = 0\n\t\t\t\tfull_stats = ''.join((full_path, status))\n\t\t\t\tentry_dict = {'host':still_host,\n\t\t\t\t\t\t\t'path':path,\n\t\t\t\t\t\t\t'filename':file_name,\n\t\t\t\t\t\t\t'full_path':full_path,\n\t\t\t\t\t\t\t'status':status,\n\t\t\t\t\t\t\t'full_stats':full_stats,\n\t\t\t\t\t\t\t'del_time':del_time,\n\t\t\t\t\t\t\t'time_start':file_start[filename],\n\t\t\t\t\t\t\t'time_end':file_end[filename],\n\t\t\t\t\t\t\t'timestamp':timestamp}\n\t\t\t\tfile_log.append(entry_dict)\n\t\t\t\tfile_time.update({filename:time.time()})\n\t\t\t#write output log\n\t\t\tif file_status[filename] not in [status]:\n\t\t\t\tdel_time = time.time() - file_time[filename]\n\t\t\t\tfull_stats = ''.join((full_path, status))\n\t\t\t\tentry_dict = {'host':still_host,\n\t\t\t\t\t\t\t'path':path,\n\t\t\t\t\t\t\t'filename':file_name,\n\t\t\t\t\t\t\t'full_path':full_path,\n\t\t\t\t\t\t\t'status':status,\n\t\t\t\t\t\t\t'full_stats':full_stats,\n\t\t\t\t\t\t\t'del_time':del_time,\n\t\t\t\t\t\t\t'time_start':file_start[filename],\n\t\t\t\t\t\t\t'time_end':file_end[filename],\n\t\t\t\t\t\t\t'timestamp':timestamp}\n\t\t\t\tfile_log.append(entry_dict)\n\t\t\t\tfile_status.update({filename:status})\n\t\t\t\tfile_time.update({filename:time.time()})\n\t\twith pyg_dbi.session_scope as s:\n\t\t\tfor monitor_data in file_log:\n\t\t\t\tpyg_dbi.add_entry_dict(s, 'Monitor', monitor_data)\n\t\tfile_log = []\n\t\ts.close()\n\t\tstatusscr.refresh()\n\t\tc = stdscr.getch()\n\t\tif c == ord('q'):\n\t\t\tbreak\n\t\ttime.sleep(1)\nexcept(KeyboardInterrupt):\n\ts.close()\n\tpass\n#terminate\ncurses.nocbreak(); stdscr.keypad(0); curses.echo()\ncurses.endwin()\n","sub_path":"paper/ganglia/scripts/monitor_folio_still.py","file_name":"monitor_folio_still.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"222776691","text":"#!/usr/bin/env python\nimport sys\nimport time\n\nsys.path.append('../libs')\n\nfrom common import *\nimport thrift_clients\nimport persistent_backends\n\ntask_manager_c = thrift_clients.TaskManagerClient(host='127.0.0.1', port=9090)\nregister_info_backend = persistent_backends.StickyRedis(port=6380, db=REGISTER_INFO_DB)\nhostfile = open('./host_list', 'r')\nlogfile = open('./host_updated.log', 'a+')\n\nupdate_cmd = \"uptime\"\n\nclient_need_updates = []\nfor host in hostfile.readlines():\n client_need_updates.append(host.strip('\\n'))\n\nwhile client_need_updates:\n client_ready_updates = []\n alived_hosts = register_info_backend.keys()\n\n for host in alived_hosts:\n if host in client_need_updates:\n client_ready_updates.append(host)\n client_need_updates.remove(host)\n\n if client_ready_updates:\n task_manager_c.perform_tasks(client_need_updates, cmd=update_cmd)\n logfile.write('\\n'.join(client_ready_updates))\n logfile.write('\\n')\n time.sleep(2)\n\n\n","sub_path":"server/scripts/client_update.py","file_name":"client_update.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"41131621","text":"import socket\nimport time\nimport threading\nfrom time import sleep\n#from mysql_connector import *\nfrom pprint import pprint\nfrom pprint import pformat\nfrom queue import Queue\nimport sys\nfrom threading import Thread, Lock\n\n\nopenPorts = []\nhostnameOpenPorts = {} #storing result for one hostname and list of open ports\nipHostnameOpenPorts = {} #storing result for one ip, its hostname and opened ports\nfinalResults = {} #storing all results\ntargetHosts = {'ec2-18-185-241-122.eu-central-1.compute.amazonaws.com': '35.158.160.236'}\nqueue = Queue()\n\nsocket.setdefaulttimeout(0.25)\nprint_lock = threading.Lock()\n\nprint(\"The scanner is started. Please wait for results\")\n\ndef portscan(port):\n for hostname, ip in targetHosts.items():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n\n con = s.connect((ip, port))\n with print_lock:\n\n openPorts.append(port)\n hostnameOpenPorts = {\"hostname\": hostname,\n \"openports\": list(set(openPorts))}\n result = {ip: hostnameOpenPorts}\n finalResults.update(result)\n con.close()\n except:\n pass\n\n\ndef threader():\n while True:\n worker = queue.get()\n portscan(worker)\n queue.task_done()\n\n\nstartTime = time.time()\nfor x in range(100):\n t = threading.Thread(target=threader)\n t.daemon = True\n t.start()\n\nfor worker in range(1, 10000):\n queue.put(worker)\n\nqueue.join()\n\nprint('Time taken:', time.time() - startTime)\n\nprint(\"----------------------------------------------\")\npprint(finalResults)\nprint(len(finalResults))\n","sub_path":"ip_scanner.py","file_name":"ip_scanner.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"438813554","text":"from fabric.contrib.files import append, exists, sed, is_link\nfrom fabric.api import env, local, run, sudo, settings\nimport random\n\nREPO_URL = 'https://github.com/exquest/daysheets.git'\n\ndef _create_directory_structure_if_nessecary(site_folder):\n\tfor subfolder in ('database', 'static', 'virtualenv', 'source'):\n\t\trun('mkdir -p %s/%s' % (site_folder, subfolder))\n\t\t\ndef _get_latest_source(source_folder):\n\tif exists(source_folder + '/.git'):\n\t\trun('cd %s && git fetch' % source_folder)\n\telse:\n\t\trun('git clone %s %s' % (REPO_URL, source_folder))\n\tcurrent_commit = local(\"git log -n 1 --format=%H\", capture=True)\n\trun('cd %s && git reset --hard %s' % (source_folder, current_commit))\n\t\ndef _update_settings(source_folder, site_name):\n\tsettings_path = source_folder + '/settings/base.py'\n#\tsed(settings_path, \"DEBUG = True\", \"DEBUG = False\")\n#\tsed(settings_path,\n#\t\t'ALLOWED_HOSTS =.+$',\n#\t\t'ALLOWED_HOSTS = [\"%s\"]' % (site_name,)\n#\t)\n\tsecret_key_file = source_folder + '/settings/secret_key.py'\n\tif not exists(secret_key_file):\n\t\tchars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'\n\t\tkey = ''.join(random.SystemRandom().choice(chars) for _ in range(50))\n\t\tappend(secret_key_file, \"SECRET_KEY = '%s'\" % (key,))\n\tappend(settings_path, '\\nfrom .secret_key import SECRET_KEY')\n\t\ndef _update_wsgi(source_folder, settings):\n\twsgi_path = source_folder + '/daysheets/wsgi.py'\n\tsed(wsgi_path, \"daysheets.settings\", settings)\n\t\ndef _update_virtualenv(source_folder):\n\tvirtualenv_folder = source_folder + '/../virtualenv'\n\tif not exists(virtualenv_folder + '/bin/pip'):\n\t\trun('virtualenv --python=python3 %s' % (virtualenv_folder,))\n\trun('%s/bin/pip install -r %s/requirements.txt' % (\n\t\tvirtualenv_folder, source_folder\n\t))\n\t\ndef _update_static_files(source_folder, settings):\n\trun('cd %s && ../virtualenv/bin/python3 manage.py collectstatic --settings=%s --noinput' % (\n\t\tsource_folder, settings\n\t))\n\t\ndef _update_database(source_folder, settings):\n\trun('cd %s && ../virtualenv/bin/python3 manage.py migrate --settings=%s --noinput' % (\n\t\tsource_folder, settings\n\t))\n\t\ndef _create_nginx_files_and_links_if_nessecary(source_folder, deploy_tools_folder, site_name):\n\tnginx_path = '/etc/nginx'\n\tsites_available_path = nginx_path + '/sites-available/'\n\tsites_enabled_path = nginx_path + '/sites-enabled/'\n\tsites_enabled_link = sites_enabled_path + site_name\n\tnginx_conf_file = sites_available_path + site_name\n\tnginx_conf_template_file = deploy_tools_folder + 'nginx.template.conf'\n\t\n\tif not exists(nginx_conf_file, use_sudo=True, verbose=True):\n\t\tsudo('cp %s %s' % (nginx_conf_template_file, nginx_conf_file))\n\t\tsed(nginx_conf_file, \"SITENAME\", site_name, use_sudo=True, backup='')\n\tif not is_link(sites_enabled_link, verbose=True):\n\t\tsudo('ln -s %s %s' % (nginx_conf_file, sites_enabled_link))\n\t\ndef _create_guincorn_files_if_nessecary(site_name, deploy_tools_folder, gunicorn_init_location):\n\tgunicorn_template_file = deploy_tools_folder + 'gunicorn-upstart.template.conf'\n\tif not exists(gunicorn_init_location):\n\t\tsudo('cp %s %s' % (gunicorn_template_file, gunicorn_init_location))\n\t\tsed(gunicorn_init_location, \"SITENAME\", site_name, use_sudo=True, backup='')\n\ndef _restart_nginx_and_gunicorn(gunicorn_init):\n\tsudo('service nginx reload')\n\twith settings(warn_only=True):\n\t\tresult = sudo('restart %s' % (gunicorn_init))\n\tif result.failed:\n\t\tsudo('start %s' % (gunicorn_init))\n\ndef deploy():\n\tsite_folder = '/home/%s/sites/%s' % (env.user, env.host)\n\tsource_folder = site_folder + '/source'\n\tdeploy_tools_folder = source_folder + '/deploy_tools/'\n\tsettings = 'settings.production'\n\tgunicorn_init = 'gunicorn-%s' % (env.host)\n\tgunicorn_init_location = '/etc/init/' + gunicorn_init + '.conf'\n\t_create_directory_structure_if_nessecary(site_folder)\n\t_get_latest_source(source_folder)\n\t_update_settings(source_folder, env.host)\n\t_update_wsgi(source_folder, settings)\n\t_update_virtualenv(source_folder)\n\t_update_static_files(source_folder, settings)\n\t_update_database(source_folder, settings)\n\t_create_nginx_files_and_links_if_nessecary(source_folder, deploy_tools_folder, env.host)\n\t_create_guincorn_files_if_nessecary(env.host, deploy_tools_folder, gunicorn_init_location)\n\t_restart_nginx_and_gunicorn(gunicorn_init)\n\t\n","sub_path":"deploy_tools/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"305065779","text":"#1\ndef anagram_number():\n num = str(input(\"Nhập số nguyên: \")) \n reverse_num = num[::-1]\n if int(num) == int(reverse_num):\n print('True')\n else:\n print('False')\n pass\n# anagram_number()\n\n#2\ndef roman_to_int():\n roman = input(\"Nhập chữ số la mã cần chuyển đổi: \")\n roman_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}\n i = 0\n num = 0\n while i < len(roman):\n if i + 1 < len(roman) and roman[i:i+2] in roman_dict:\n num += roman_dict[roman[i:i+2]]\n i += 2\n else:\n num += roman_dict[roman[i]]\n i += 1\n print(\"Số la mã \",roman,\" có giá trị bằng \",num)\n# roman_to_int()","sub_path":"hackathon1_midterm/medium.py","file_name":"medium.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"499106528","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n===Description===\nModule for tests\n\nRecommended to run with nosetests as:\nnosetests --exe --with-coverage --cover-erase --cover-html\n\"\"\"\n\nimport unittest\nimport logging\nimport os\nimport json\nimport sqlite3\nfrom PyQt4.QtTest import QTest\nfrom PyQt4 import QtGui, QtCore\nfrom gui_export import MainWindow, ExportDialog, StatisticsDialog,\\\n AboutDialog, NotificationDialog, ExceptionDialog,\\\n Results\nfrom handler import Kindle\nfrom service import Lingualeo\n\nTEST_DB = 'test.db'\nTEST_TXT = 'test.txt'\n\n\ndef leftMouseClick(widget):\n QTest.mouseClick(widget, QtCore.Qt.LeftButton)\n\n\ndef createTxtFile():\n with open(TEST_TXT, 'w') as f:\n f.write('bacon')\n f.write('simple')\n\n\ndef createSqlBase(malformed=False, empty=False, valid=True):\n \"\"\"\n create test SQL base with name test.db\n \"\"\"\n conn = sqlite3.connect('test.db')\n if valid:\n conn.execute(\"\"\"\n CREATE TABLE WORDS\n (id TEXT PRIMARY KEY NOT NULL,\n word TEXT, stem TEXT, lang TEXT,\n category INTEGER DEFAULT 0,\n timestamp INTEGER DEFAULT 0,\n profileid TEXT);\n \"\"\")\n if valid and not empty:\n conn.execute(\"\"\"\n INSERT INTO \"WORDS\"\n VALUES('en:intending',\n 'intending',\n 'intend',\n 'en',\n 0,\n 1450067334997,\n '')\n \"\"\")\n conn.commit()\n if malformed:\n with open(TEST_DB, 'wb') as f:\n f.write(b'tt')\n\n\ndef createLingualeoUser(premium=False):\n \"\"\"return test Lingualeo user\"\"\"\n return {\"premium_type\": +premium,\n \"fullname\": \"Bob Gubko\",\n \"meatballs\": 1500,\n \"avatar_mini\": 'https://d144fqpiyasmrr'\n '.cloudfront.net/uploads'\n '/avatar/0s100.png',\n \"xp_level\": 34}\n\n\nclass BaseTest(unittest.TestCase):\n \"\"\"\n Base class for tests\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Construct QApplication\n \"\"\"\n self.app = QtGui.QApplication([])\n\n def tearDown(self):\n \"\"\"\n Prevent gtk-Critical messages.\n Remove app\n \"\"\"\n self.app.quit()\n self.app.processEvents()\n self.app.sendPostedEvents(self.app, 0)\n self.app.flush()\n self.app.deleteLater()\n\n\nclass TestMainWindow(BaseTest):\n \"\"\"\n Class for testing MainWindow\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Turn off logger\n Set english language\n Set credentials from json file\n \"\"\"\n super(TestMainWindow, self).setUp()\n logging.disable(logging.CRITICAL)\n self.ui = MainWindow()\n self.ui.language = 'en'\n self.ui.loadTranslation()\n self.ui.email_edit.setText('b346059@trbvn.com')\n self.ui.pass_edit.setText('1234567890')\n\n def tearDown(self):\n \"\"\"\n Prevent gtk-Critical messages\n Remove test.db in case if it's present\n \"\"\"\n super(TestMainWindow, self).tearDown()\n if os.path.exists(TEST_DB):\n os.remove(TEST_DB)\n if os.path.exists(TEST_TXT):\n os.remove(TEST_TXT)\n\n def test_only_input_checked(self):\n \"\"\"\n Initial state of GUI: Only input_radio is checked\n \"\"\"\n self.assertEqual(self.ui.input_radio.isChecked(), True)\n self.assertEqual(self.ui.text_radio.isChecked(), False)\n self.assertEqual(self.ui.kindle_radio.isChecked(), False)\n\n def test_kindle_radios_disabled(self):\n \"\"\"\n All_words and new_words should be disabled\n \"\"\"\n self.assertEqual(self.ui.all_words_radio.isEnabled(), False)\n self.assertEqual(self.ui.new_words_radio.isEnabled(), False)\n\n def test_kindle_radio_only_one_checked(self):\n \"\"\"\n Checking new_words should uncheck all_words\n \"\"\"\n self.ui.kindle_radio.setChecked(True)\n self.ui.new_words_radio.setChecked(True)\n self.assertEqual(self.ui.all_words_radio.isChecked(), False)\n\n def test_input_validator(self):\n \"\"\"\n No non-Unicode is allowed in input\n \"\"\"\n\n validator = self.ui.input_word_edit.validator()\n text = \"work раве\"\n state, word, pos = validator.validate(text, 0)\n self.assertEqual(state == QtGui.QValidator.Acceptable, False)\n\n def test_empty_login_pass(self):\n \"\"\"\n No email/password is specified - show an error in statusbar.\n \"\"\"\n self.ui.email_edit.setText(\"\")\n self.ui.pass_edit.setText(\"\")\n self.ui.input_word_edit.setText(\"test\")\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Email or password are incorrect\")\n\n def test_dialog_not_run(self):\n \"\"\"\n Nothing is selected - ExportDialog shouldn't be constructed.\n \"\"\"\n self.ui.email_edit.setText(\"\")\n self.ui.pass_edit.setText(\"\")\n leftMouseClick(self.ui.export_button)\n with self.assertRaises(AttributeError):\n self.ui.dialog\n\n def test_input_not_run(self):\n \"\"\"\n No word in input - show an error in statusbar.\n \"\"\"\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"No input\")\n\n def test_text_no_file_not_run(self):\n \"\"\"\n If no text file is selected - show an error in statusbar.\n \"\"\"\n self.ui.text_radio.setChecked(True)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"No txt file\")\n\n def test_kindle_no_base_not_run(self):\n \"\"\"\n No Kindle database is selected - show an error in statusbar.\n \"\"\"\n self.ui.kindle_radio.setChecked(True)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"No Kindle database\")\n\n def test_kindle_wrong_format_not_run(self):\n \"\"\"\n No '.db' in file extension for Kindle - show an error in statusbar.\n \"\"\"\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_TXT)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Not database\")\n\n def test_kindle_not_valid_base_not_run(self):\n \"\"\"\n No WORDS in Kindle table - show an error in statusbar.\n \"\"\"\n createSqlBase(valid=False)\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_DB)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Not valid database\")\n\n def test_kindle_empty_base_not_run(self):\n \"\"\"\n Table WORDS in Kindle database is empty - show an error in statusbar\n \"\"\"\n createSqlBase(empty=True)\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_DB)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Kindle database is empty\")\n\n def test_kindle_malformed_not_run(self):\n \"\"\"\n Kindle database malformed - show 'Repair' and error in statusbar.\n \"\"\"\n createSqlBase(malformed=True)\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_DB)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.repair_button.isHidden(), False)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Database is malformed. Click 'Repair'\")\n\n def test_run_export(self):\n \"\"\"\n Email/password set, set word in 'Input' - ExportDialog appears\n \"\"\"\n\n\n def test_russian_translation(self):\n \"\"\"\n Selecting RU from Language menu - russian translation is loaded\n \"\"\"\n lang_item = self.ui.language_menu.actions()[1]\n lang_item.trigger()\n self.assertEqual(self.ui.export_button.text(), \"Экспорт\")\n\n\nclass TestExportDialog(BaseTest):\n \"\"\"\n Class for testing ExportDialog\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Set up initial condition:\n -special lingualeo user\n \"\"\"\n super(TestExportDialog, self).setUp()\n self.lingualeo = Lingualeo(\"aaa@mail.com\", \"12345\")\n\n def tearDown(self):\n \"\"\"\n Prevent gtk-Critical messages.\n Remove test.db and test.txt in case if they're present.\n \"\"\"\n super(TestExportDialog, self).tearDown()\n if os.path.exists(TEST_DB):\n os.remove(TEST_DB)\n if os.path.exists(TEST_TXT):\n os.remove(TEST_TXT)\n\n def test_export_kindle_premium(self):\n \"\"\"\n Test for unlimited sign if user is premium\n \"\"\"\n createSqlBase()\n handler = Kindle(TEST_DB)\n array = handler.get()\n duplicates = 0\n total = len(array)\n self.lingualeo.auth_info = createLingualeoUser(premium=True)\n self.lingualeo.initUser()\n dialog = ExportDialog(array, total, duplicates, self.lingualeo)\n self.assertEqual(\"∞\", dialog.meatballs_value_label.text())\n\n\nclass TestStatisticsDialog(BaseTest, Results):\n \"\"\"\n Class for testing StatisticsDialog\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Set up initial condition:\n -prepared list of dictionaries with results\n \"\"\"\n self.array = []\n row = {}\n words = [\"cat\", \"dog\", \"cockatoo\", \"smile\"]\n contexts = [\"I have a cat.\",\n \"I have a dog.\",\n \"\",\n \"Let's smile.\"\n ]\n translations = [\"кот\", \"cобака\", \"какаду\", \"улыбка\"]\n results = sorted(self.RESULTS.values())\n for index, (word, tword, context)\\\n in enumerate(zip(words, translations, contexts)):\n row = {\n \"word\": word,\n \"result\": results[index],\n \"tword\": tword,\n \"context\": context\n }\n self.array.append(row)\n super(TestStatisticsDialog, self).setUp()\n self.stat_dialog = StatisticsDialog(self.array)\n\n def test_correct_counts(self):\n \"\"\"\n Every label has its own count of words\n Total = 4\n Not added = 1\n Added = 1\n No translation = 1\n Exist = 1\n \"\"\"\n self.assertEqual('4', self.stat_dialog.values[0].text())\n self.assertEqual('1', self.stat_dialog.values[1].text())\n self.assertEqual('1', self.stat_dialog.values[2].text())\n self.assertEqual('1', self.stat_dialog.values[3].text())\n self.assertEqual('1', self.stat_dialog.values[4].text())\n\n def test_correct_table_colors(self):\n \"\"\"\n Every row in table has its own color\n 1) added - green.\n 2) exists - red.\n 3) no translation - yellow.\n 4) not added - white.\n \"\"\"\n self.assertEqual(self.stat_dialog.table.item(0, 0).backgroundColor(),\n QtCore.Qt.green)\n self.assertEqual(self.stat_dialog.table.item(1, 0).backgroundColor(),\n QtCore.Qt.red)\n self.assertEqual(self.stat_dialog.table.item(2, 0).backgroundColor(),\n QtCore.Qt.yellow)\n self.assertEqual(self.stat_dialog.table.item(3, 0).backgroundColor(),\n QtCore.Qt.white)\n\n def test_correct_table_row_counts(self):\n \"\"\"\n Table has four rows\n \"\"\"\n self.assertEqual(self.stat_dialog.table.rowCount(), 4)\n\n\nclass TestAboutDialog(BaseTest):\n \"\"\"\n Class for testing 'About' dialog.\n \"\"\"\n JSON_FILE = os.path.join(\"src\", \"data\", \"data.json\")\n\n def setUp(self):\n \"\"\"\n Set up initial condition:\n -prepared json file\n -version, author, idea, email loaded\n \"\"\"\n super(TestAboutDialog, self).setUp()\n with open(self.JSON_FILE) as f:\n data_info = json.loads(f.read())\n self.version = data_info['version']\n self.author = data_info['author']\n self.idea = data_info['idea']\n self.email = data_info['e-mail']\n self.about = AboutDialog()\n\n def tearDown(self):\n\n super(TestAboutDialog, self).tearDown()\n\n def test_version_present(self):\n \"\"\"\n Data in json == data in 'About'\n \"\"\"\n text = self.about.about_label.text()\n version_text = self.about.version_label.text()\n email_text = self.about.email_label.text()\n self.assertIn(self.author, text)\n self.assertIn(self.idea, text)\n self.assertIn(self.email, email_text)\n self.assertIn(self.version, version_text)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_gui.py","file_name":"test_gui.py","file_ext":"py","file_size_in_byte":13105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"239828066","text":"from typing import List\nfrom collections import OrderedDict\n\nfrom ray.experimental.dag import (\n DAGNode,\n ClassNode,\n ClassMethodNode,\n PARENT_CLASS_NODE_KEY,\n)\nfrom ray.experimental.dag.function_node import FunctionNode\nfrom ray.experimental.dag.input_node import InputNode\nfrom ray.experimental.dag.utils import DAGNodeNameGenerator\nfrom ray.serve.deployment import Deployment\nfrom ray.serve.pipeline.deployment_method_node import DeploymentMethodNode\nfrom ray.serve.pipeline.deployment_node import DeploymentNode\nfrom ray.serve.pipeline.deployment_function_node import DeploymentFunctionNode\n\n\ndef transform_ray_dag_to_serve_dag(\n dag_node: DAGNode, node_name_generator: DAGNodeNameGenerator\n):\n \"\"\"\n Transform a Ray DAG to a Serve DAG. Map ClassNode to DeploymentNode with\n ray decorated body passed in, and ClassMethodNode to DeploymentMethodNode.\n \"\"\"\n if isinstance(dag_node, ClassNode):\n deployment_name = node_name_generator.get_node_name(dag_node)\n return DeploymentNode(\n dag_node._body,\n deployment_name,\n dag_node.get_args(),\n dag_node.get_kwargs(),\n dag_node.get_options(),\n # TODO: (jiaodong) Support .options(metadata=xxx) for deployment\n other_args_to_resolve=dag_node.get_other_args_to_resolve(),\n )\n\n elif isinstance(dag_node, ClassMethodNode):\n other_args_to_resolve = dag_node.get_other_args_to_resolve()\n # TODO: (jiaodong) Need to capture DAGNodes in the parent node\n parent_deployment_node = other_args_to_resolve[PARENT_CLASS_NODE_KEY]\n\n return DeploymentMethodNode(\n parent_deployment_node._deployment,\n dag_node._method_name,\n dag_node.get_args(),\n dag_node.get_kwargs(),\n dag_node.get_options(),\n other_args_to_resolve=dag_node.get_other_args_to_resolve(),\n )\n elif isinstance(\n dag_node,\n FunctionNode\n # TODO (jiaodong): We do not convert ray function to deployment function\n # yet, revisit this later\n ) and dag_node.get_other_args_to_resolve().get(\"is_from_serve_deployment\"):\n deployment_name = node_name_generator.get_node_name(dag_node)\n return DeploymentFunctionNode(\n dag_node._body,\n deployment_name,\n dag_node.get_args(),\n dag_node.get_kwargs(),\n dag_node.get_options(),\n other_args_to_resolve=dag_node.get_other_args_to_resolve(),\n )\n else:\n # TODO: (jiaodong) Support FunctionNode or leave it as ray task\n return dag_node\n\n\ndef extract_deployments_from_serve_dag(\n serve_dag_root: DAGNode,\n) -> List[Deployment]:\n \"\"\"Extract deployment python objects from a transformed serve DAG. Should\n only be called after `transform_ray_dag_to_serve_dag`, otherwise nothing\n to return.\n\n Args:\n serve_dag_root (DAGNode): Transformed serve dag root node.\n Returns:\n deployments (List[Deployment]): List of deployment python objects\n fetched from serve dag.\n \"\"\"\n deployments = OrderedDict()\n\n def extractor(dag_node):\n if isinstance(dag_node, (DeploymentNode, DeploymentFunctionNode)):\n deployment = dag_node._deployment\n # In case same deployment is used in multiple DAGNodes\n deployments[deployment.name] = deployment\n return dag_node\n\n serve_dag_root.apply_recursive(extractor)\n\n return list(deployments.values())\n\n\ndef get_pipeline_input_node(serve_dag_root_node: DAGNode):\n \"\"\"Return the InputNode singleton node from serve dag, and throw\n exceptions if we didn't find any, or found more than one.\n\n Args:\n ray_dag_root_node: DAGNode acting as root of a Ray authored DAG. It\n should be executable via `ray_dag_root_node.execute(user_input)`\n and should have `InputNode` in it.\n Returns\n pipeline_input_node: Singleton input node for the serve pipeline.\n \"\"\"\n\n input_nodes = []\n\n def extractor(dag_node):\n if isinstance(dag_node, InputNode):\n input_nodes.append(dag_node)\n\n serve_dag_root_node.apply_recursive(extractor)\n assert len(input_nodes) == 1, (\n \"There should be one and only one InputNode in the DAG. \"\n f\"Found {len(input_nodes)} InputNode(s) instead.\"\n )\n\n return input_nodes[0]\n\n\ndef process_ingress_deployment_in_serve_dag(\n deployments: List[Deployment],\n) -> List[Deployment]:\n \"\"\"Mark the last fetched deployment in a serve dag as exposed with default\n prefix.\n \"\"\"\n if len(deployments) == 0:\n return deployments\n\n # Last element of the list is the root deployment if it's applicable type\n # that wraps an deployment, given Ray DAG traversal is done bottom-up.\n ingress_deployment = deployments[-1]\n if ingress_deployment.route_prefix in [None, f\"/{ingress_deployment.name}\"]:\n # Override default prefix to \"/\" on the ingress deployment, if user\n # didn't provide anything in particular.\n new_ingress_deployment = ingress_deployment.options(route_prefix=\"/\")\n deployments[-1] = new_ingress_deployment\n\n # Erase all non ingress deployment route prefix\n for i, deployment in enumerate(deployments[:-1]):\n if (\n deployment.route_prefix is not None\n and deployment.route_prefix != f\"/{deployment.name}\"\n ):\n raise ValueError(\n \"Route prefix is only configurable on the ingress deployment. \"\n \"Please do not set non-default route prefix: \"\n f\"{deployment.route_prefix} on non-ingress deployment of the \"\n \"serve DAG. \"\n )\n else:\n # Earse all default prefix to None for non-ingress deployments to\n # disable HTTP\n deployments[i] = deployment.options(route_prefix=None)\n\n return deployments\n","sub_path":"python/ray/serve/pipeline/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"359257010","text":"\"\"\"Tests for SignalViewer node\"\"\"\nimport pytest\nfrom cognigraph.nodes.outputs import SignalViewer\nfrom cognigraph.nodes.sources import FileSource\n\nfrom cognigraph.nodes.tests.prepare_tests_data import info, data_path # noqa\nimport numpy as np\n\n\n@pytest.fixture # noqa\ndef signal_viewer(info, data_path): # noqa\n signal_viewer = SignalViewer()\n signal_viewer.mne_info = info\n N_SEN = len(info['ch_names'])\n signal_viewer.input = np.random.rand(N_SEN)\n parent = FileSource(data_path)\n parent.output = np.random.rand(info['nchan'], 1)\n parent.mne_info = info\n signal_viewer.parent = parent\n return signal_viewer\n\n\ndef test_change_api_attributes(signal_viewer):\n \"\"\"Check that appropriate method is defined\"\"\"\n signal_viewer._on_critical_attr_change(None, None, None)\n\n\n# Doesn't work in headless mode\n# commenting out signal_viewer.initialize() doesn't help either\n# def test_input_hist_invalidation_resets_statistics(signal_viewer):\n# \"\"\"Check that upstream history change doesn't break the node\"\"\"\n# signal_viewer.parent.initialize()\n# signal_viewer.initialize()\n# signal_viewer.parent.source_name = 'new_name' # triggers reset for source\n","sub_path":"cognigraph/nodes/tests/test_SignalViewer.py","file_name":"test_SignalViewer.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"61586667","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# -----------------\n# Реализуйте функцию best_hand, которая принимает на вход\n# покерную \"руку\" (hand) из 7ми карт и возвращает лучшую\n# (относительно значения, возвращаемого hand_rank)\n# \"руку\" из 5ти карт. У каждой карты есть масть(suit) и\n# ранг(rank)\n# Масти: трефы(clubs, C), пики(spades, S), червы(hearts, H), бубны(diamonds, D)\n# Ранги: 2, 3, 4, 5, 6, 7, 8, 9, 10 (ten, T), валет (jack, J), дама (queen, Q), король (king, K), туз (ace, A)\n# Например: AS - туз пик (ace of spades), TH - дестяка черв (ten of hearts), 3C - тройка треф (three of clubs)\n\n# Задание со *\n# Реализуйте функцию best_wild_hand, которая принимает на вход\n# покерную \"руку\" (hand) из 7ми карт и возвращает лучшую\n# (относительно значения, возвращаемого hand_rank)\n# \"руку\" из 5ти карт. Кроме прочего в данном варианте \"рука\"\n# может включать джокера. Джокеры могут заменить карту любой\n# масти и ранга того же цвета, в колоде два джокерва.\n# Черный джокер '?B' может быть использован в качестве треф\n# или пик любого ранга, красный джокер '?R' - в качестве черв и бубен\n# любого ранга.\n\n# Одна функция уже реализована, сигнатуры и описания других даны.\n# Вам наверняка пригодится itertools\n# Можно свободно определять свои функции и т.п.\n# -----------------\nfrom itertools import combinations, product\n\n\ndef hand_rank(hand):\n \"\"\"Возвращает значение определяющее ранг 'руки'\"\"\"\n ranks = card_ranks(hand)\n if straight(ranks) and flush(hand):\n return 8, max(ranks)\n elif kind(4, ranks):\n return 7, kind(4, ranks), kind(1, ranks)\n elif kind(3, ranks) and kind(2, ranks):\n return 6, kind(3, ranks), kind(2, ranks)\n elif flush(hand):\n return 5, ranks\n elif straight(ranks):\n return 4, max(ranks)\n elif kind(3, ranks):\n return 3, kind(3, ranks), ranks\n elif two_pair(ranks):\n return 2, two_pair(ranks), ranks\n elif kind(2, ranks):\n return 1, kind(2, ranks), ranks\n else:\n return 0, ranks\n\n\ndef card_ranks(hand):\n \"\"\"Возвращает список рангов (его числовой эквивалент),\n отсортированный от большего к меньшему\"\"\"\n ranks = ['0123456789TJQKA'.index(r) for r, s in hand]\n ranks.sort(reverse=True)\n if ranks == [14, 5, 4, 3, 2]:\n ranks = [5, 4, 3, 2, 1]\n return ranks\n\n\ndef flush(hand):\n \"\"\"Возвращает True, если все карты одной масти\"\"\"\n suits = set(s for r, s in hand)\n return len(suits) == 1\n\n\ndef straight(ranks):\n \"\"\"Возвращает True, если отсортированные ранги формируют последовательность 5ти,\n где у 5ти карт ранги идут по порядку (стрит)\"\"\"\n return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5\n\n\ndef kind(n, ranks):\n \"\"\"Возвращает первый ранг, который n раз встречается в данной руке.\n Возвращает None, если ничего не найдено\"\"\"\n for r in ranks:\n if ranks.count(r) == n:\n return r\n return None\n\n\ndef two_pair(ranks):\n \"\"\"Если есть две пары, то возврщает два соответствующих ранга,\n иначе возвращает None\"\"\"\n pair = kind(2, ranks)\n pair_2 = kind(2, ranks[::-1])\n if pair and pair_2 != pair:\n return pair, pair_2\n else:\n return None\n\n\ndef best_hand(hand):\n \"\"\"Из \"руки\" в 7 карт возвращает лучшую \"руку\" в 5 карт \"\"\"\n return max(combinations(hand, 5), key=hand_rank)\n\n\ndef with_jokers(card, hand):\n \"\"\"Возвращаем просто карту, если не джокер,\n иначе возврщаем все возможные варианты для замены джокера\"\"\"\n if not card.startswith('?'):\n return [card]\n suits = 'SC' if card[1] == 'B' else 'HD'\n # из получаемого набора для джокера нужно удалить карты, которые уже есть в руке\n return set(r+s for r in '23456789TJQKA' for s in suits) - set(hand)\n\n\ndef best_wild_hand(hand):\n \"\"\"best_hand но с джокерами\"\"\"\n var_hands = (with_jokers(c, hand) for c in hand)\n hands = product(*var_hands)\n best = set(best_hand(h) for h in hands)\n return max(best, key=hand_rank)\n\n\ndef test_best_hand():\n print(\"test_best_hand...\")\n assert (sorted(best_hand(\"6C 7C 8C 9C TC 5C JS\".split()))\n == ['6C', '7C', '8C', '9C', 'TC'])\n assert (sorted(best_hand(\"TD TC TH 7C 7D 8C 8S\".split()))\n == ['8C', '8S', 'TC', 'TD', 'TH'])\n assert (sorted(best_hand(\"JD TC TH 7C 7D 7S 7H\".split()))\n == ['7C', '7D', '7H', '7S', 'JD'])\n print('OK')\n\n\ndef test_best_wild_hand():\n print(\"test_best_wild_hand...\")\n assert (sorted(best_wild_hand(\"6C 7C 8C 9C TC 5C ?B\".split()))\n == ['7C', '8C', '9C', 'JC', 'TC'])\n assert (sorted(best_wild_hand(\"TD TC 5H 5C 7C ?R ?B\".split()))\n == ['7C', 'TC', 'TD', 'TH', 'TS'])\n assert (sorted(best_wild_hand(\"JD TC TH 7C 7D 7S 7H\".split()))\n == ['7C', '7D', '7H', '7S', 'JD'])\n print('OK')\n\nif __name__ == '__main__':\n test_best_hand()\n test_best_wild_hand()\n","sub_path":"homework1/poker.py","file_name":"poker.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"160487214","text":"from typing import Optional\nfrom json import loads\n\nfrom numpy import array\nfrom numpy import uint64\nfrom fastapi import FastAPI\nfrom fastapi import Request\n\nfrom ..utils import get_cg\n\napi = FastAPI()\n\n\n@api.get(\"/table/{graph_id}/manifest/{node_id}:0\")\nasync def manifest(\n request: Request,\n graph_id: str,\n node_id: int,\n verify: Optional[bool] = True,\n return_seg_ids: Optional[bool] = False,\n prepend_seg_ids: Optional[bool] = False,\n bounds: Optional[str] = \"\",\n):\n from json.decoder import JSONDecodeError\n from .utils import manifest_response\n\n try:\n data = loads(await request.body())\n except JSONDecodeError:\n data = {}\n bbox = None\n if bounds:\n bbox = array([b.split(\"-\") for b in bounds.split(\"_\")], dtype=int).T\n\n cg = get_cg(graph_id)\n start_layer = cg.meta.custom_data.get(\"mesh\", {}).get(\"max_layer\", 2)\n if \"start_layer\" in data:\n start_layer = int(data[\"start_layer\"])\n\n flexible_start_layer = None\n if \"flexible_start_layer\" in data:\n flexible_start_layer = int(data[\"flexible_start_layer\"])\n\n args = (\n node_id,\n verify,\n return_seg_ids,\n prepend_seg_ids,\n start_layer,\n flexible_start_layer,\n bbox,\n data,\n )\n return manifest_response(cg, args)\n\n\n@api.post(\"/table/{graph_id}/remesh\")\nasync def remesh(request: Request, graph_id: str):\n from .utils import remesh\n\n data = loads(await request.body())\n return remesh(\n get_cg(graph_id), data[\"operation_id\"], array(data[\"l2ids\"], dtype=uint64)\n )\n","sub_path":"app/meshing/v1.py","file_name":"v1.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"318759","text":"# -*- coding: cp1254 -*-\r\nimport random\r\ndef getModeMedian():\r\n list_1=[]\r\n n=random.randint(3, 10)#dizi uzunluðu\r\n r_min=-4#dizinin içinde yer alabilecek en küçük deðer\r\n r_max=4#dizinin içinde yer alabilecek en büyük deðer\r\n \r\n #Diziye rastgele deðer atanmasý\r\n #karmaþýklýk O(n)\r\n for i in range(n):\r\n list_1.append(random.randint(r_min,r_max))\r\n print (\"liste\", list_1)\r\n \r\n \r\n #Dizinin histogram deðerinin hesaplanmasý\r\n #Karmaþýklýk O(n*n)\r\n histogram_list=[]\r\n for i in range(len(list_1)):\r\n s=False\r\n for j in range(len(histogram_list)):\r\n if (list_1[i]==histogram_list[j][0]):\r\n histogram_list[j][1]=histogram_list[j][1]+1\r\n s=True\r\n if(s==False):\r\n histogram_list.append([list_1[i],1])\r\n \r\n print(\"histogram_list\", histogram_list)\r\n \r\n #Dizinin mod hesabýnýn yapýlmasý\r\n #Karmaþýklýk O(n)\r\n frekans_max = -1\r\n mod = -1\r\n for item, frekans in histogram_list:\r\n print(\"item\", item, \"frekans\", frekans)\r\n if(frekans > frekans_max):\r\n frekans_max = frekans\r\n mod = item\r\n print(\"mod\", mod, \"max_f\", frekans_max)\r\n\r\n #Dizinin buble sort ile sýralanmasý\r\n #Karmaþýklýk O(n*n)\r\n m = len(list_1)\r\n for i in range(m-1, -1, -1):\r\n for j in range(0, i):\r\n if not(list_1[j] < list_1[j+1]):\r\n temp = list_1[j]\r\n list_1[j] = list_1[j+1]\r\n list_1[j+1] = temp\r\n print(list_1)\r\n \r\n \r\n #Dizinin median hesabýnýn yapýlmasý\r\n #Yukarýda sýralanan diziyi kullanacaðýmýz için karmaþýklýkk O(n)\r\n \r\n if(m % 2 == 1):\r\n ortanca = int(m/2) \r\n median = list_1[ortanca]\r\n print(\"Median = \", median)\r\n else:\r\n ort_1 = list_1[int(m/2)]\r\n ort_2 = list_1[int(m/2) - 1]\r\n median = (ort_1 + ort_2) / 2\r\n print(\"Median = \", median)\r\n \r\n return mod, median \r\n","sub_path":"getModeMedian.py","file_name":"getModeMedian.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"169650409","text":"#! /usr/bin/python2\n#\n# Copyright (c) 2020 Intel Corporation\n#\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"\n\"\"\"\n\nimport errno\nimport logging\nimport os\nimport time\nimport werkzeug\n\ntry:\n import functools32\nexcept ImportError as e:\n try:\n import backports.functools_lru_cache as functools32\n except ImportError as e:\n logging.error(\"Can't import neither functools32 nor backports.functools_lru_cache\")\n raise\n\nimport commonl\nimport ttbl\nimport ttbl.config\nimport ttbl.user_control\n\npath = None\n\nclass exception(Exception):\n pass\n\nclass invalid_e(exception):\n def __init__(self, allocationid):\n exception.__init__(\n self, \"%s: non-existing allocation\" % allocationid)\n\nstates = {\n \"invalid\": \"allocation is not valid (might have expired)\",\n \"queued\": \"allocation is queued\",\n \"rejected\": \"allocation of %(targets)s not allowed: %(reason)s\",\n \"active\": \"allocation is being actively used\",\n # one of your targets was kicked out and another one assigned on\n # its place, so go call GET /PREFIX/allocation/ALLOCATIONID to get\n # the new targets and restart your run\n \"restart-needed\": \"allocation has been changed by a higher priority allocator\",\n \"expired\": \"allocation idle timer has expired and has been revoked\",\n}\n\nclass one_c(object):\n\n def __init__(self, allocationid, dirname):\n self.path = dirname\n self.allocationid = allocationid\n if not os.path.isdir(path):\n raise invalid_e(allocationid)\n\n def timestamp(self):\n # Just open the file and truncate it, so if it does not exist,\n # it will be created.\n with open(os.path.join(self.state_dir, \"timestamp\"), \"w\") as f:\n f.write(time.strftime(\"%c\\n\"))\n\n def set(self, field, value):\n if value != None:\n assert isinstance(value, basestring)\n assert len(value) < 1023\n location = os.path.join(self.path, field)\n if value == None:\n try:\n os.unlink(location)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n else:\n # New location, add a unique thing to it so there is no\n # collision if more than one process is trying to modify\n # at the same time; they can override each other, that's\n # ok--the last one wins.\n location_new = location + \"-%s-%s-%s\" \\\n % (os.getpid(), self.uuid_seed, time.time())\n commonl.rm_f(location_new)\n os.symlink(value, location_new)\n os.rename(location_new, location)\n\n def get(self, field, default = None):\n location = os.path.join(self.path, field)\n try:\n return os.readlink(location)\n except OSError as e:\n if e.errno == errno.ENOENT:\n return default\n raise\n\n\ndef target_is_valid(target_name):\n # FIXME: validate with the inventory\n # FIXME: LRU cache this? target's won't change that much\n return True\n\n\n#@functools32.lru_cache(maxsize = 200)\n#def get\n\ndef request(groups, user, obo_user,\n priority = None, preempt = False,\n queue = False, reason = None):\n \"\"\"\n :params list(str) groups: list of groups of targets\n\n \"\"\"\n assert isinstance(groups, dict)\n for group_name, target_list in groups.items():\n assert isinstance(group_name, basestring)\n assert isinstance(target_list, list)\n # FIXME: verify not empty\n for target_name in target_list:\n assert isinstance(target_name, basestring)\n assert target_is_valid(target_name)\n\n user = user._get_current_object()\n obo_user = obo_user._get_current_object()\n assert isinstance(user, ttbl.user_control.User), \\\n \"user is %s (%s)\" % (user, type(user))\n assert isinstance(obo_user, ttbl.user_control.User)\n\n if priority != None:\n assert priority > 0\n # FIXME: verify calling user has this priority\n else:\n priority = 500 # DEFAULT FROM USER\n\n assert isinstance(preempt, bool)\n assert isinstance(queue, bool)\n assert reason == None or isinstance(reason, basestring)\n\n allocationid = commonl.mkid(obo_user.get_id() + str(time.time()))\n\n dirname = os.path.join(path, allocationid)\n commonl.makedirs_p(dirname + \"/guests\")\n commonl.makedirs_p(dirname + \"/groups\")\n alloc = one_c(allocationid, dirname)\n\n alloc.set(\"user\", obo_user.get_id())\n alloc.set(\"creator\", user.get_id())\n alloc.timestamp()\n for group in groups:\n # FIXME: this is severly limited in size, we need a normal file to set this info with one target per file\n alloc.set(\"groups/\" + group, \" \".join(group))\n\n result = {\n # { 'busy', 'queued', 'allocated', 'rejected' },\n \"state\": 'rejected',\n \"allocationid\": allocationid,\n #\"allocationid\": None, # if queued; derived from OWNER's cookie\n # \"not allowed on TARGETNAMEs\"\n # \"targets TARGETNAMEs are busy\"\n \"message\": \"not implemented yet\"\n }\n return result\n\n\ndef query():\n # list all allocations\n return {\n \"result\": {\n \"ALLOCATIONID\": {\n # \"unknown\", \"allocated\", \"queued\", \"rejected\"\n \"state\": \"unknown\",\n # \"groupname\": [ target1, target 2... ]\t# if queued\n # \"guests\": [ \"user1\", \"user2\" ... ]\t# if allocated\n # \"user\":\"user1\"\t\t\t# if allocated, allocation owner\n }\n }\n }\n\n\ndef get(allocationid):\n return {\n # \"unknown\", \"allocated\", \"queued\", \"rejected\"\n \"state\": \"unknown\",\n # \"groupname\": [ target1, target 2... ]\t# if queued\n # \"guests\": [ \"user1\", \"user2\" ... ]\t# if allocated\n # \"user\":\"user1\"\t\t\t# if allocated, allocation owner\n }\n\n\ndef keepalive(allocations):\n # {\n # \"allocationid1\": state,\n # \"allocationid2\": state,\n # \"allocationid3\": state,\n # ...\n # }\n # {\n # \"allocationid4\": new_state,\n # \"allocationid3\": new_state,\n # ...\n # }\n return {}\n\n\ndef delete(allocationid):\n # if pending, remove all queuing of it\n # if allocated, release all targets\n return {\n # \"unknown\", \"allocated\", \"queued\", \"rejected\"\n \"state\": \"unknown\",\n # \"groupname\": [ target1, target 2... ]\t\t# if queued\n }\n\n\ndef guest_add(allocationid, user):\n # verify user is valid\n return { }\n\ndef guest_remove(allocationid, user):\n # verify user is valid\n # verify user in allocation\n return { }\n","sub_path":"ttbd/ttbl/allocation.py","file_name":"allocation.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"349056722","text":"import pika\nimport sys\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n\nchannel = connection.channel()\n\nchannel.exchange_declare(\n exchange='direct_msgs',\n exchange_type='direct'\n)\n\nresult = channel.queue_declare(\n queue='',\n exclusive=True\n)\n\nqueue_name = result.method.queue\n\nroute = sys.argv[1]\n\nchannel.queue_bind(\n exchange='direct_msgs',\n queue=queue_name,\n routing_key=route\n)\n\ndef callback(ch, method, properties, body):\n print(f\" [x] {method.routing_key}: {body}\")\n\n\nchannel.basic_consume(\n queue=queue_name,\n on_message_callback=callback,\n auto_ack=True\n)\n\ntry:\n channel.start_consuming()\nexcept KeyboardInterrupt:\n print('Interrupted')","sub_path":"RabbitMQ/Routing/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"451397025","text":"from django import forms\r\n\r\n\r\nfrom models import Workout_Event\r\n\r\n\r\nclass CreateForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Workout_Event\r\n fields = ('event_name', 'event_type', 'location', 'date',\r\n 'time_start', 'time_end', 'workout_description',\r\n 'experience_level', 'number_of_spots',)\r\n","sub_path":"project_code/joinmyworkout/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"376254486","text":"#!/usr/bin/env python\nStr= ['1950 0025',\n'1950 0022',\n'1950 0011',\n'1949 0031', \n'1949 0111',\n'1949 0078',\n'1948 0023',\n'1948 0019']\n(last_key, tot_val, avg_val, ctr, cum_val) = (None, 0, 0, 0, 0)\nfor line in Str:\n (key, val) = line.strip().split(\" \")\n if last_key and last_key != key:\n avg_val = float(cum_val/ctr)\n print(last_key, avg_val)\n (ctr, cum_val) = (1, 0)\n (last_key, tot_val) = (key, int(val))\n cum_val = cum_val + tot_val\n else:\n (last_key,tot_val) = (key,int(val))\n ctr = ctr + 1\n cum_val = cum_val + tot_val\n last_key = key\n #(last_key, tot_val) = (key, sum(int(val)))\nif last_key:\n #ctr = ctr + 1\n avg_val = float(cum_val/ctr)\n print(last_key, avg_val)\n","sub_path":"PycharmProjects/python/venv/Lib/site-packages/Avg_func.py","file_name":"Avg_func.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"482103178","text":"import sys\nimport logging\nimport pymongo\nimport traceback\n\n\n# Requires pymongo==3.6.0\nclass MongoManager:\n def __init__(self, logger=None, uri=None, host=\"localhost\", port=27017, use_uri=True, db=\"test_db\",\n collection=\"test_collection\"):\n if not logger:\n self.logger = logging.getLogger(\"Mongo Logger\")\n self.logger.setLevel(logging.DEBUG)\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n else:\n self.logger = logger\n\n if use_uri:\n self.client = pymongo.MongoClient(uri)\n else:\n self.client = pymongo.MongoClient(host=host, port=port)\n\n self.db = self.client[db]\n self.collection = self.db[collection]\n\n def insert_one(self, document):\n \"\"\"\n Inserts a document into Mongo\n :param document: (Dict) Mongo Document\n :return: (String) _id of the inserted document\n \"\"\"\n try:\n return self.collection.insert_one(document=document).inserted_id\n except Exception:\n self.logger.error(\"Error inserting one object to mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def find_one(self):\n \"\"\"\n Returns a random document from a collection\n :return: (Dict)\n \"\"\"\n try:\n return self.collection.find_one()\n except Exception:\n self.logger.error(\"Error finding one object from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def find_by_id(self, id):\n \"\"\"\n Returns the document matching that _id\n :param id: (String) _id\n :return: (Dict) if found, None is not Found\n \"\"\"\n try:\n return self.collection.find_one({\"_id\": id})\n except Exception:\n self.logger.error(\"Error finding object from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def get_all(self, max_docs=0):\n \"\"\"\n Returns a list of all docs\n :return:\n \"\"\"\n try:\n docs = list()\n result = self.collection.find({}).limit(max_docs)\n for entry in result:\n docs.append(entry)\n\n return docs\n except Exception:\n self.logger.error(\"Error finding object from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def query(self, query):\n \"\"\"\n Query using proper query dictionary\n :param query:\n :return: (list) of documents. returns [] if no match\n \"\"\"\n try:\n docs = list()\n result = self.collection.find(query)\n for entry in result:\n docs.append(entry)\n\n return docs\n except Exception:\n self.logger.error(\"Error finding objects from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def save(self, document):\n \"\"\"\n Returns _id of the Saved document\n :param document: (Dict) JSON containing the _id field\n :return:\n \"\"\"\n try:\n return self.collection.save(document, manipulate=True)\n except Exception:\n self.logger.error(\"Error saving object to mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None","sub_path":"utils/mongo_manager.py","file_name":"mongo_manager.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"420414757","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\nThis module contains implementations of the old compound model interfaces that\nare now deprecated.\n\nThe classes exported by this module should be imported from `astropy.modeling`\nrather than from `astropy.modeling.core` or from this module directly.\n\"\"\"\n\nfrom __future__ import (absolute_import, unicode_literals, division,\n print_function)\n\nimport functools\nimport operator\nimport warnings\n\nimport numpy as np\n\nfrom ..utils import deprecated, indent\nfrom ..utils.compat.odict import OrderedDict\nfrom ..utils.exceptions import AstropyDeprecationWarning\nfrom .core import Model\n\n\n__all__ = ['LabeledInput', 'SerialCompositeModel', 'SummedCompositeModel']\n\n\n@deprecated('1.0', alternative=':ref:`compound-models` as described in the '\n 'Astropy documentation')\nclass LabeledInput(OrderedDict):\n \"\"\"\n Used by `SerialCompositeModel` and `SummedCompositeModel` to choose input\n data using labels.\n\n This is a container assigning labels (names) to all input data arrays to a\n composite model.\n\n Parameters\n ----------\n data : list\n List of all input data\n labels : list of strings\n names matching each coordinate in data\n\n Examples\n --------\n >>> y, x = np.mgrid[:5, :5]\n >>> l = np.arange(10)\n >>> labeled_input = LabeledInput([x, y, l], ['x', 'y', 'pixel'])\n >>> labeled_input.x\n array([[0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4]])\n >>> labeled_input['x']\n array([[0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4]])\n \"\"\"\n\n def __init__(self, data, labels):\n if len(labels) != len(data):\n raise TypeError(\"Number of labels and data doesn't match\")\n\n super(LabeledInput, self).__init__(zip(labels, data))\n\n def __getattr__(self, label):\n try:\n return self[label]\n except KeyError:\n raise AttributeError(label)\n\n def __setattr__(self, label, data):\n if label.startswith('_'):\n super(LabeledInput, self).__setattr__(label, data)\n else:\n self[label] = data\n\n def __delattr__(self, label):\n try:\n del self[label]\n except KeyError:\n raise AttributeError(label)\n\n @property\n def labels(self):\n return tuple(self.keys())\n\n def add(self, label=None, value=None, **kw):\n \"\"\"\n Add input data to a LabeledInput object\n\n Parameters\n --------------\n label : str\n coordinate label\n value : numerical type\n coordinate value\n kw : dictionary\n if given this is a dictionary of ``{label: value}`` pairs\n \"\"\"\n\n if ((label is None and value is not None) or\n (label is not None and value is None)):\n raise TypeError(\"Expected label and value to be defined\")\n\n kw[label] = value\n\n self.update(kw)\n\n def copy(self):\n return LabeledInput(self.values(), self.labels)\n\n\nclass _LabeledInputMapping(Model):\n def __init__(self, labeled_input, inmap, outmap):\n self._labeled_input = labeled_input\n self._inmap = tuple(inmap)\n self._outmap = tuple(outmap)\n super(_LabeledInputMapping, self).__init__()\n\n def __repr__(self):\n return '<{0}>'.format(self.name)\n\n @property\n def inputs(self):\n return self._outmap\n\n @property\n def outputs(self):\n return self._inmap\n\n @property\n def name(self):\n return '{0}({1} -> {2})'.format(self.__class__.__name__,\n self._outmap, self._inmap)\n\n def evaluate(self, *inputs):\n for idx, label in enumerate(self._outmap):\n self._labeled_input[label] = inputs[idx]\n\n result = tuple(self._labeled_input[label] for label in self._inmap)\n\n if len(result) == 1:\n return result[0]\n else:\n return result\n\n\nclass _CompositeModel(Model):\n \"\"\"Base class for all composite models.\"\"\"\n\n _operator = None\n fittable = False\n\n def __init__(self, transforms, n_inputs, n_outputs, inmap=None,\n outmap=None):\n self._transforms = transforms\n param_names = []\n for tr in self._transforms:\n param_names.extend(tr.param_names)\n super(_CompositeModel, self).__init__()\n self.param_names = param_names\n self._n_inputs = n_inputs\n self._n_outputs = n_outputs\n self._basic_transform = None\n\n self._inmap = inmap\n self._outmap = outmap\n\n def __repr__(self):\n return '<{0}([\\n{1}\\n])>'.format(\n self.__class__.__name__,\n indent(',\\n'.join(repr(tr) for tr in self._transforms),\n width=4))\n\n def __str__(self):\n parts = ['Model: {0}'.format(self.__class__.__name__)]\n for tr in self._transforms:\n parts.append(indent(str(tr), width=4))\n return '\\n'.join(parts)\n\n @property\n def inputs(self):\n return self._transforms[0].inputs\n\n @property\n def outputs(self):\n return self._transforms[-1].outputs\n\n @property\n def n_inputs(self):\n return self._n_inputs\n\n @n_inputs.setter\n def n_inputs(self, val):\n warnings.warn(\n 'Setting n_inputs on {0} objects is undefined and should not '\n 'be used.'.format(self.__class__.__name__),\n AstropyDeprecationWarning)\n self._n_inputs = val\n\n @property\n def n_outputs(self):\n return self._n_outputs\n\n @n_outputs.setter\n def n_outputs(self, val):\n warnings.warn(\n 'Setting n_outputs on {0} objects is undefined and should not '\n 'be used.'.format(self.__class__.__name__),\n AstropyDeprecationWarning)\n self._n_outputs = val\n\n def invert(self):\n raise NotImplementedError(\"Subclasses should implement this\")\n\n @property\n def parameters(self):\n raise NotImplementedError(\n \"Composite models do not currently support the .parameters \"\n \"array.\")\n\n def evaluate(self, *inputs):\n \"\"\"\n Specialized `Model.evaluate` implementation that allows `LabeledInput`\n inputs to be handled when calling this model.\n\n This ignores any passed in parameter values, as _CompositeModels can't\n be fitted anyways.\n \"\"\"\n\n # Drop parameter arguments\n inputs = inputs[:self.n_inputs]\n\n if len(inputs) == 1 and isinstance(inputs[0], LabeledInput):\n labeled_input = inputs[0].copy()\n transform = self._make_labeled_transform(labeled_input)\n inputs = [labeled_input[label] for label in self._inmap[0]]\n result = transform(*inputs)\n\n if self._transforms[-1].n_outputs == 1:\n labeled_input[self._outmap[-1][0]] = result\n else:\n for label, output in zip(self._outmap[-1], result):\n labeled_input[label] = output\n\n return labeled_input\n else:\n if self._basic_transform is None:\n transform = self._transforms[0]\n for t in self._transforms[1:]:\n transform = self._operator(transform, t)\n\n self._basic_transform = transform\n\n return self._basic_transform(*inputs)\n\n def __call__(self, *inputs):\n \"\"\"\n Specialized `Model.__call__` implementation that allows\n `LabeledInput` inputs to be handled when calling this model.\n \"\"\"\n\n return self.evaluate(*inputs)\n\n def _param_sets(self, raw=False):\n all_params = tuple(m._param_sets(raw=raw) for m in self._transforms)\n return np.vstack(all_params)\n\n def _make_labeled_transform(self, labeled_input):\n \"\"\"\n Build up a transformation graph that incorporates the instructions\n encoded in the `LabeledInput` object.\n\n This requires use of the ``_inmap`` and ``_outmap`` attributes set\n when instantiating this `_CompositeModel`.\n \"\"\"\n\n if self._inmap is None:\n raise TypeError(\"Parameter 'inmap' must be provided when \"\n \"input is a labeled object.\")\n if self._outmap is None:\n raise TypeError(\"Parameter 'outmap' must be provided when \"\n \"input is a labeled object\")\n\n transforms = [self._transforms[0]]\n previous_outmap = self._outmap[0]\n for model, inmap, outmap in zip(self._transforms[1:], self._inmap[1:],\n self._outmap[1:]):\n mapping = _LabeledInputMapping(labeled_input, inmap,\n previous_outmap)\n transforms.append(mapping | model)\n previous_outmap = outmap\n\n return functools.reduce(self._operator, transforms)\n\n\n@deprecated('1.0', alternative=':ref:`compound-models` as described in the '\n 'Astropy documentation')\nclass SerialCompositeModel(_CompositeModel):\n \"\"\"\n Composite model that evaluates models in series.\n\n Parameters\n ----------\n transforms : list\n a list of transforms in the order to be executed\n inmap : list of lists or None\n labels in an input instance of LabeledInput\n if None, the number of input coordinates is exactly what\n the transforms expect\n outmap : list or None\n labels in an input instance of LabeledInput\n if None, the number of output coordinates is exactly what\n the transforms expect\n n_inputs : int\n dimension of input space (e.g. 2 for a spatial model)\n n_outputs : int\n dimension of output\n\n Notes\n -----\n Output values of one model are used as input values of another.\n Obviously the order of the models matters.\n\n Examples\n --------\n Apply a 2D rotation followed by a shift in x and y::\n\n >>> import numpy as np\n >>> from astropy.modeling import models, LabeledInput, SerialCompositeModel\n >>> y, x = np.mgrid[:5, :5]\n >>> rotation = models.Rotation2D(angle=23.5)\n >>> offset_x = models.Shift(-4.23)\n >>> offset_y = models.Shift(2)\n >>> labeled_input = LabeledInput([x, y], [\"x\", \"y\"])\n >>> transform = SerialCompositeModel([rotation, offset_x, offset_y],\n ... inmap=[['x', 'y'], ['x'], ['y']],\n ... outmap=[['x', 'y'], ['x'], ['y']])\n >>> result = transform(labeled_input)\n \"\"\"\n\n _operator = operator.or_\n\n def __init__(self, transforms, inmap=None, outmap=None, n_inputs=None,\n n_outputs=None):\n if n_inputs is None:\n n_inputs = max([tr.n_inputs for tr in transforms])\n # the output dimension is equal to the output dim of the last\n # transform\n n_outputs = transforms[-1].n_outputs\n else:\n if n_outputs is None:\n raise TypeError(\"Expected n_inputs and n_outputs\")\n\n if transforms and inmap and outmap:\n if not (len(transforms) == len(inmap) == len(outmap)):\n raise ValueError(\"Expected sequences of transform, \"\n \"inmap and outmap to have the same length\")\n\n super(SerialCompositeModel, self).__init__(\n transforms, n_inputs, n_outputs, inmap=inmap, outmap=outmap)\n\n def inverse(self):\n try:\n transforms = []\n for transform in self._transforms[::-1]:\n transforms.append(transform.inverse)\n except NotImplementedError:\n raise NotImplementedError(\n \"An analytical inverse has not been implemented for \"\n \"{0} models.\".format(transform.__class__.__name__))\n if self._inmap is not None:\n inmap = self._inmap[::-1]\n outmap = self._outmap[::-1]\n else:\n inmap = None\n outmap = None\n return SerialCompositeModel(transforms, inmap, outmap)\n\n\n@deprecated('1.0', alternative=':ref:`compound-models` as described in the '\n 'Astropy documentation')\nclass SummedCompositeModel(_CompositeModel):\n \"\"\"\n Composite model that evaluates models in parallel.\n\n Parameters\n --------------\n transforms : list\n transforms to be executed in parallel\n inmap : list or None\n labels in an input instance of LabeledInput\n if None, the number of input coordinates is exactly what the\n transforms expect\n outmap : list or None\n\n Notes\n -----\n Evaluate each model separately and add the results to the input_data.\n \"\"\"\n\n _operator = operator.add\n\n def __init__(self, transforms, inmap=None, outmap=None):\n n_inputs = transforms[0].n_inputs\n n_outputs = n_inputs\n for transform in transforms:\n if not (transform.n_inputs == transform.n_outputs == n_inputs):\n raise ValueError(\"A SummedCompositeModel expects n_inputs = \"\n \"n_outputs for all transforms\")\n\n super(SummedCompositeModel, self).__init__(transforms, n_inputs,\n n_outputs, inmap=inmap,\n outmap=outmap)\n","sub_path":"lib/python2.7/site-packages/astropy/modeling/_compound_deprecated.py","file_name":"_compound_deprecated.py","file_ext":"py","file_size_in_byte":13559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"255323951","text":"import time\nimport os\nimport sys\n\nif sys.version_info[0] < 3:\n raise Exception(\"Must be using Python 3\\nRun using python3 instead of python\")\n\nos.system(\"sudo apt-get install -qq python3-pip < /dev/null > /dev/null\")\ntry:\n import requests\nexcept ImportError:\n os.system(\"pip3 install requests\")\n print(\"Installing Dependencies...\\n\")\n time.sleep(3)\n import requests\ntry:\n from bs4 import BeautifulSoup\nexcept ImportError:\n os.system(\"sudo apt-get install python3-bs4\")\n time.sleep(3)\n from bs4 import BeautifulSoup\ntry:\n from mailjet_rest import Client\nexcept ImportError:\n os.system(\"pip3 install mailjet_rest\")\n time.sleep(3)\n from mailjet_rest import Client\n\ntimer = 60 * 60\n\n\ndef smtp_send_email(email, nameam, priceam, namefl, pricefl, URL, j):\n api_key = '9c357ca9d2e695d571117648c47680c8'\n api_secret = '3b51faf454e90309d8b9ec695b25a8c1'\n mailjet = Client(auth=(api_key, api_secret), version='v3.1')\n expectedprice = expected_prompt()\n URL2 = \"https://www.amazon.in/s?k=\" + title2.replace(' ', '+').replace('(', '%28').replace(')', '%29').replace(',',\n '%2C')\n\n if j == 1:\n URL2 = \"https://www.amazon.in/s?k=\" + title2.replace(' ', '+').replace('(', '%28').replace(')', '%29').replace(\n ',', '%2C')\n data = {\n 'Messages': [\n {\n 'From': {\n 'Email': 'dr_pricetracker@mailinator.com',\n 'Name': 'Price Tracker'\n },\n\n 'To': [\n {\n 'Email': email\n }\n ],\n\n 'Subject': 'Price Drop Alert for ' + nameam + ' on Amazon',\n 'TextPart': 'Dear User, the price of ' + nameam + ' has dropped below Rs.' + str(\n expectedprice) + '.\\nCheck it out: ' + URL2\n }\n ]\n }\n\n if j == 2:\n data = {\n 'Messages': [\n {\n 'From': {\n 'Email': 'dr_pricetracker@mailinator.com',\n 'Name': 'Price Tracker'\n },\n\n 'To': [\n {\n 'Email': email\n }\n ],\n\n 'Subject': 'Price Drop Alert for ' + namefl + ' on Flipkart',\n 'TextPart': 'Dear User, the price of ' + namefl + ' has dropped below Rs.' + str(\n expectedprice) + '.\\nCheck it out: ' + URL\n }\n ]\n }\n\n while True:\n if j == 1:\n if priceam < expectedprice:\n result = mailjet.send.create(data=data)\n print(\"Email sent successfully!\\nExitting!\\n\")\n exit(0)\n else:\n print(\n \"\\nThe price right now is above your target price\\nThis program will check every hour for price drop\\nKeep this program running to get notified!\")\n time.sleep(timer)\n (priceam, namefl) = price_amazon_search(URL2, headers)\n continue\n\n if j == 2:\n if pricefl < expectedprice:\n result = mailjet.send.create(data=data)\n print(\"Email sent successfully!\\nExitting!\\n\")\n exit(0)\n else:\n print(\n \"\\nThe price right now is above your target price\\nThis program will check every hour for price drop\\nKeep this program running to get notified!\")\n time.sleep(timer)\n (pricefl, namefl) = price_flipkart_search(namefl, headers)\n continue\n\n if j == 3:\n # if pricefl expectedprice) or (j == 2 and pricefl > expectedprice) or (\n j == 3 and pricefl > expectedprice and priceam > expectedprice):\n print(\n \"\\nThe price right now is above your target price\\nThis program will check every hour for price drop\\nKeep this program running to get notified!\")\n time.sleep(timer)\n (priceam, nameam) = price_amazon_search(URL2, headers)\n (pricefl, namefl) = price_flipkart_search(URL, headers)\n continue\n\n result = str(mailjet.send.create(data=data))\n if result == '':\n print(\"Email sent successfully!\\nExitting!\\n\")\n exit(0)\n else:\n print(\"There was some trouble sending the email\\n\")\n print(\"Error Code: \" + str(result) + '\\n')\n\n\ndef expected_prompt():\n while (1):\n expectedpricein = input(\"\\nEnter the price below which you want to get notified:\\nRs.\")\n\n try:\n expectedprice = int(expectedpricein)\n return expectedprice\n except ValueError:\n print(\"Please enter a valid number!\")\n\n\ndef track_prompt(email, nameam, priceam, namefl, pricefl, URL):\n j = 9\n while True:\n j = int(input(\n \"\\nChoose an option:\\n1. Track on Amazon\\n2. Track on Flipkart\\n3. Track on both\\n0. Go back to previous menu\\n9. Exit\\n\"))\n if j == 0:\n return j, email\n if j == 9:\n exit(0)\n if j == 1 or j == 2 or j == 3:\n if email == '':\n email = str(input(\"Enter your Email ID: \"))\n smtp_send_email(email, nameam, priceam, namefl, pricefl, URL, j)\n else:\n print(\"Invalid option!\\nTry Again\\n\")\n\n\ndef price_amazon(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n title = soup.find(id='productTitle').get_text()\n\n price = soup.find(id='priceblock_ourprice').get_text()\n converted_price = float(price.replace(',', '').replace('Rs.', '').strip())\n\n return converted_price, title.strip()\n\n\ndef price_flipkart(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n mydivs2 = soup.find(\"div\", {\"class\": \"_1vC4OE\" and \"_3qQ9m1\"}).encode('utf-8')\n\n if mydivs2 == 'None':\n mydivs = soup.find(\"div\", {\"class\": \"_1vC4OE\"}).get_text().encode('utf-8')\n else:\n mydivs = soup.find(\"div\", {\"class\": \"_1vC4OE\" and \"_3qQ9m1\"}).get_text().encode('utf-8')\n\n price = mydivs[3:]\n converted_price = float(price.replace(',', '').replace('Rs.', '').strip())\n title2 = str(soup.find(\"span\", {'class': '_35KyD6'}))\n\n if title2 == 'None':\n title = str(soup.find(\"a\", {'class': '_2cLu-l'})['title'])\n else:\n title = str(soup.find(\"span\", {'class': '_35KyD6'}).get_text())\n\n return converted_price, title.strip()\n\n\n# Search by product:\ndef price_flipkart_search(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n mydivs2 = soup.find(\"div\", {\"class\": \"_1vC4OE\"}).encode('utf-8')\n if mydivs2 == 'None':\n mydivs = soup.find(\"div\", {\"class\": \"_1vC4OE\" and \"_2rQ-NK\"}).get_text().strip().encode('utf-8')\n else:\n mydivs = str(soup.find(\"div\", {\"class\": \"_1vC4OE\"}).get_text().strip())\n #print(mydivs)\n price = mydivs[1:]\n converted_price = float(price.replace(',', '').strip())\n __title2 = soup.find('div', {\"class\": \"_3wU53n\"})\n if str(__title2) != 'None':\n __title = str(__title2.get_text().strip())\n else:\n __title2 = soup.find('a', {\"class\": \"_2cLu-l\"})['title']\n __title = str(__title2.strip())\n return converted_price, __title\n\n\ndef price_amazon_search(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n allSponsored = soup.find_all(\"a\", {\"class\": \"a-link-normal\" and \"a-text-normal\"})\n\n i = 0\n allprice = soup.find_all(\"span\", {\"class\": \"a-price-whole\"})\n alltitle = soup.find_all(\"span\", {\"class\": \"a-size-medium\" and \"a-color-base\" and \"a-text-normal\"})\n price = str('')\n __title = str('')\n\n i = 0\n\n for element in allSponsored:\n if element['href'][0:11] == '/gp/slredir':\n i += 1\n else:\n break\n\n j = 0\n for element in allprice:\n if j == i:\n price = element.get_text().strip()\n break\n else:\n j += 1\n\n k = 0\n for element in alltitle:\n if k == i / 2:\n __title = element.get_text().strip()\n break\n else:\n k += 1\n\n converted_price = float(price.replace(',', '').replace('Rs.', '').strip())\n # print(converted_price)\n return converted_price, __title\n\n\nemail = ''\nexpectedprice = int(0)\nheaders = {\n \"User-Agent\": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\n\nwhile True:\n i2 = input(\"Choose an option:\\n1. Search by URL\\n2. Search by product name\\n9. Exit\\n\")\n try:\n i = int(i2)\n except ValueError:\n print(\"Please enter a valid number\\n\")\n continue\n if i == 1:\n URL = str(input(\"Enter URL of product:\"))\n\n # headers = {\"User-Agent\": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\n\n if URL.find(\"amazon.in\") < len(URL) and URL.find(\"amazon.in\") > 0:\n (priceam, nameam) = price_amazon(URL, headers)\n print('\\n')\n print(\"Amazon:\\n\" + nameam + ': Rs.' + str(int(priceam)))\n\n flipurl = \"https://www.flipkart.com/search?q=\" + nameam.replace(' ', '%20').replace('(', '%20').replace(')',\n '%20')\n (pricefl, namefl) = price_flipkart_search(flipurl, headers)\n\n print(\"Flipkart:\\n\" + namefl + ': Rs.' + str(int(pricefl)) + '\\n')\n\n if pricefl < priceam:\n print(\"Cheaper on Flipkart by Rs.\" + str(priceam - pricefl) + '\\n')\n if priceam < pricefl:\n print(\"Cheaper on Amazon by Rs.\" + str(pricefl - priceam) + '\\n')\n if priceam == pricefl:\n print(\"Same price on Amazon and Flipkart.\\n\")\n\n track_prompt(email, nameam, priceam, namefl, pricefl, URL)\n\n else:\n if URL.find(\"flipkart.com\") < len(URL) and URL.find(\"flipkart.com\") > 0:\n (pricefl, namefl) = price_flipkart(URL, headers)\n print(\"\\nFlipkart:\\n\" + namefl + ': Rs.' + str(int(pricefl)) + '\\n')\n\n amazurl = \"https://www.amazon.in/s?k=\" + namefl.replace(' ', '+').replace('(', '%28').replace(')',\n '%29').replace(\n ',', '%2C')\n (priceam, nameam) = price_amazon_search(amazurl, headers)\n print(\"Amazon:\\n\" + nameam + ': Rs.' + str(int(priceam)) + '\\n')\n\n if pricefl < priceam:\n print(\"Cheaper on Flipkart by Rs.\" + str(priceam - pricefl) + '\\n')\n if priceam < pricefl:\n print(\"Cheaper on Amazon by Rs.\" + str(pricefl - priceam) + '\\n')\n if priceam == pricefl:\n print(\"Same price on Amazon and Flipkart.\\n\")\n\n track_prompt(email, nameam, priceam, namefl, pricefl, URL)\n\n else:\n print(\"Invalid URL\")\n continue\n\n if i == 2:\n title = str(input(\"Enter name of product: \"))\n title2 = title\n URL = \"https://www.flipkart.com/search?q=\" + title.replace(' ', '%20')\n # headers = {\"User-Agent\": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\n\n (price, namefl) = price_flipkart_search(URL, headers)\n\n URL2 = \"https://www.amazon.in/s?k=\" + title2.replace(' ', '+')\n # print(URL2)\n (price2, nameam) = price_amazon_search(URL2, headers)\n\n print('\\n')\n print(\"Flipkart:\")\n print(namefl + ': Rs.' + str(int(price)))\n print(\"Amazon:\")\n print(nameam + ': Rs.' + str(int(price2)) + '\\n')\n\n if price < price2:\n print(\"Cheaper on Flipkart by Rs.\" + str(price2 - price) + '\\n')\n if price2 < price:\n print(\"Cheaper on Amazon by Rs.\" + str(price - price2) + '\\n')\n if price == price2:\n print(\"Same price on Amazon and Flipkart.\\n\")\n\n track_prompt(email, nameam, price2, namefl, price, URL)\n\n if i == 4:\n # test\n print(\"Sending Email\")\n smtp_send_email()\n\n if i == 9:\n print(\"\\nThank You for using this tool\\nHave a nice day\\n\")\n exit(0)\n\n if i == 404:\n print(\n \"\\nYou've chosen the option to change your user agent\\nTo change your user agent, simply Google 'What's my user agent' and paste the result here: \")\n agentcustom = str(input())\n headers = {\"User-Agent\": agentcustom}\n\n if i != 1 and i != 2 and i != 404 and i != 9:\n print(\"Please Choose a valid option\")\n","sub_path":"price_checker_mail_final_universal.py","file_name":"price_checker_mail_final_universal.py","file_ext":"py","file_size_in_byte":16734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"107391507","text":"# 分片结构\nimport conn_redis\nimport binascii\nimport datetime\nimport math\nimport uuid\n\nSHARD_SIZE = 512\nDAILY_EXPECTED = 1000000\nEXPECTED = {}\n\n\ndef shard_key(base, key, total_elements, shard_size):\n \"\"\"\n 获取分片后的key\n @param base: 基础key\n @param key: 要存的map key\n @param total_elements: 预计的成员总数\n @param shard_size: 每个分片的尺寸\n @return:\n \"\"\"\n\n if isinstance(key, int) or key.isdigit():\n shard_id = int(str(key), 10) // shard_size\n else:\n shards = 2 * total_elements // shard_size\n shard_id = binascii.crc32(key.encode()) % shards\n return \"%s%s\" % (base, shard_id)\n\n\ndef shard_hset(conn, base, key, value, total_elements, shard_size):\n \"\"\" 分片版 hset\n\n @param conn:\n @param base:\n @param key:\n @param value:\n @param total_elements:\n @param shard_size:\n @return:\n \"\"\"\n\n shard = shard_key(base, key, total_elements, shard_size)\n return conn.hset(shard, key, value)\n\n\ndef shard_hget(conn, base, key, total_elements, shard_size):\n \"\"\" 分片版 hget\n\n @param conn:\n @param base:\n @param key:\n @param total_elements:\n @param shard_size:\n @return:\n \"\"\"\n\n shard = shard_key(base, key, total_elements, shard_size)\n return conn.hget(shard, key)\n\n\ndef shard_sadd(conn, base, member, total_elements, shard_size):\n \"\"\" 分片sadd\n\n @param conn:\n @param base:\n @param member:\n @param total_elements:\n @param shard_size:\n @return:\n \"\"\"\n shard_id = shard_key(base, \"X\" + str(member), total_elements, shard_size)\n return conn.sadd(shard_id, member)\n\n\ndef count_visit(conn, uid):\n \"\"\" 计算唯一访客量\n\n @param conn:\n @param str uid:\n @return:\n \"\"\"\n today = datetime.date.today()\n key = \"unique:%s\" % today.isoformat()\n expected = get_expected(conn, key, today)\n member = int(uid.replace(\"-\", \"\")[:15], 16)\n if shard_sadd(conn, key, member, expected, SHARD_SIZE):\n conn.incr(key)\n\n\ndef get_expected(conn, key, today):\n \"\"\" 每天预计的访问量\n\n @param conn:\n @param key:\n @param today:\n @return:\n \"\"\"\n if key in EXPECTED:\n return EXPECTED[key]\n ex_key = key + \":expected\"\n expected = conn.get(ex_key)\n if not expected:\n yesterday = (today - datetime.timedelta(days=1)).isoformat()\n expected = conn.get(\"unique:%s\" % yesterday)\n expected = int(expected or DAILY_EXPECTED)\n expected = 2 ** int(math.ceil(math.log(expected * 1.5, 2)))\n if not conn.setnx(ex_key, expected):\n expected = conn.get(ex_key)\n EXPECTED[key] = expected\n return EXPECTED[key]\n\n\nif __name__ == '__main__':\n for i in range(100000):\n session_id = uuid.uuid4()\n conn1 = conn_redis.conn\n count_visit(conn1, str(session_id))\n","sub_path":"Unit9/FragmentStructure.py","file_name":"FragmentStructure.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"185380160","text":"import cv2\n \ncapture = cv2.VideoCapture(0)\n \nwhile(True):\n \n ret, img = capture.read()\n #Choose what you want boiii\n img =cv2.Canny(img,20,100)\n # img = cv2.Laplacian(img,cv2.CV_8U)\n # img = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)\n # img = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3) \n cv2.imshow('video', img)\n \n if cv2.waitKey(1) == 27:\n break\n \ncapture.release()\ncv2.destroyAllWindows()","sub_path":"OpenCV/q32.py","file_name":"q32.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"273797210","text":"# -*- coding: utf-8 -*-\n# This file is part of RRMPG.\n#\n# RRMPG is free software with the aim to provide a playground for experiments\n# with hydrological rainfall-runoff-models while achieving competitive\n# performance results.\n#\n# You should have received a copy of the MIT License along with RRMPG. If not,\n# see \n\n\"\"\"Implementation of the educational version of the HBV model.\"\"\"\n\nimport numbers\n\nimport numpy as np\n\nfrom numba import njit\nfrom scipy import optimize\nfrom .basemodel import BaseModel\nfrom ..utils.metrics import mse\nfrom ..utils.array_checks import check_for_negatives, validate_array_input\n\n\nclass HBVEdu(BaseModel):\n \"\"\"Implementation of the educational version of the HBV model.\n\n Original publication:\n Aghakouchak, Amir, and Emad Habib. \"Application of a conceptual\n hydrologic model in teaching hydrologic processes.\" International\n Journal of Engineering Education 26.4 (S1) (2010).\n\n If no model parameters are passed upon initialization, generates random\n parameter set.\n\n Args:\n area: Area of the basin.\n params: (optional) Dictonary containing all model parameters as a\n seperate key/value pairs.\n\n Raises:\n ValueError: If Area isn't a positive numerical value or on model\n parameter is missing in the passed dictonary.\n\n \"\"\"\n\n # List of model parameters\n _param_list = ['T_t', 'DD', 'FC', 'Beta', 'C', 'PWP', 'K_0', 'K_1', 'K_2',\n 'K_p', 'L']\n\n # Dictionary with default parameter bounds\n _default_bounds = {'T_t': (-1, 1),\n 'DD': (3, 7),\n 'FC': (100, 200),\n 'Beta': (1, 7),\n 'C': (0.01, 0.07),\n 'PWP': (90, 180),\n 'K_0': (0.05, 0.2),\n 'K_1': (0.01, 0.1),\n 'K_2': (0.01, 0.05),\n 'K_p': (0.01, 0.05),\n 'L': (2, 5)}\n\n # Custom numpy datatype needed for numba input\n _dtype = np.dtype([('T_t', np.float64),\n ('DD', np.float64),\n ('FC', np.float64),\n ('Beta', np.float64),\n ('C', np.float64),\n ('PWP', np.float64),\n ('K_0', np.float64),\n ('K_1', np.float64),\n ('K_2', np.float64),\n ('K_p', np.float64),\n ('L', np.float64)])\n\n def __init__(self, area, params=None):\n \"\"\"Initialize a HBVEdu model object.\n\n Args:\n area: Area of the basin.\n params: (optional) Dictonary containing all model parameters as a\n seperate key/value pairs.\n\n Raises:\n ValueError: If Area isn't a positive numerical value or on model\n parameter is missing in the passed dictonary.\n\n \"\"\"\n super().__init__(params=params)\n # Parse inputs\n if (isinstance(area, numbers.Number) and (area > 0)):\n self.area = area\n else:\n raise ValueError(\"Area must be a positiv numercial value.\")\n\n def simulate(self, temp, prec, month, PE_m, T_m, snow_init=0, soil_init=0,\n s1_init=0, s2_init=0, return_storage=False):\n \"\"\"Simulate rainfall-runoff process for given input.\n\n This function bundles the model parameters and validates the\n meteorological inputs, then calls the optimized model routine. Due\n to restrictions with the use of numba, this routine is kept outside\n of this model class.\n The meteorological inputs can be either list, numpy array or pandas \n Series.\n\n Args:\n temp: Array of (mean) temperature for each timestep.\n prec: Array of (summed) precipitation for each timestep.\n month: Array of integers indicating for each timestep to which\n month it belongs [1,2, ..., 12]. Used for adjusted\n potential evapotranspiration.\n PE_m: long-term mean monthly potential evapotranspiration.\n T_m: long-term mean monthly temperature.\n snow_init: (optional) Initial state of the snow reservoir.\n soil_init: (optional) Initial state of the soil reservoir.\n s1_init: (optional) Initial state of the near surface flow\n reservoir.\n s2_init: (optional) Initial state of the base flow reservoir.\n return_storage: (optional) Boolean, indicating if the model \n storages should also be returned.\n\n Returns:\n An array with the simulated streamflow and optional one array for\n each of the four reservoirs.\n\n Raises:\n ValueError: If one of the inputs contains invalid values.\n TypeError: If one of the inputs has an incorrect datatype.\n RuntimeErrror: If the monthly arrays are not of size 12 or there \n is a size mismatch between precipitation, temperature and the\n month array.\n\n \"\"\"\n # Validation check of the temperature, precipitation and input\n temp = validate_array_input(temp, np.float64, 'temperature')\n prec = validate_array_input(prec, np.float64, 'precipitation')\n # Check if there exist negative precipitation\n if check_for_negatives(prec):\n raise ValueError(\"In the precipitation array are negative values.\")\n \n month = validate_array_input(month, np.int8, 'month')\n if any(len(arr) != len(temp) for arr in [prec, month]):\n msg = [\"The arrays of the temperature, precipitation and month \",\n \"data must be of equal size.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Validation check for PE_m and T_m\n PE_m = validate_array_input(PE_m, np.float64, 'PE_m')\n T_m = validate_array_input(T_m, np.float64, 'T_m')\n if any(len(arr) != 12 for arr in [PE_m, T_m]):\n msg = [\"The monthly potential evapotranspiration and temperature\",\n \" array must be of length 12.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Check if entires of month array are between 1 and 12\n if (np.min(month) < 1) or (np.max(month) > 12):\n msg = [\"The month array must be between an integer1 (Jan) and \",\n \"12 (Dec).\"]\n raise ValueError(\"\".join(msg))\n\n # For correct python indexing [start with 0] subtract 1 of month array\n month -= 1\n\n # Make sure all initial storage values are floats\n snow_init = float(snow_init)\n soil_init = float(soil_init)\n s1_init = float(s1_init)\n s2_init = float(s2_init)\n\n # bundle model parameters in custom numpy array\n model_params = np.zeros(1, dtype=self._dtype)\n for param in self._param_list:\n model_params[param] = getattr(self, param)\n \n if return_storage:\n # call the actual simulation function\n qsim, snow, soil, s1, s2 = _simulate_hbv_edu(temp, prec, month, \n PE_m, T_m, snow_init,\n soil_init, s1_init, \n s2_init, model_params)\n\n # TODO: conversion from qobs in m³/s for different time resolutions\n # At the moment expects daily input data\n qsim = (qsim * self.area * 1000) / (24 * 60 * 60)\n \n return qsim, snow, soil, s1, s2\n \n else:\n # call the actual simulation function\n qsim, _, _, _, _ = _simulate_hbv_edu(temp, prec, month, PE_m, T_m, \n snow_init, soil_init, s1_init, \n s2_init, model_params)\n\n # TODO: conversion from qobs in m³/s for different time resolutions\n # At the moment expects daily input data\n qsim = (qsim * self.area * 1000) / (24 * 60 * 60)\n \n return qsim\n\n return qsim\n\n def fit(self, qobs, temp, prec, month, PE_m, T_m, snow_init=0.,\n soil_init=0., s1_init=0., s2_init=0.):\n \"\"\"Fit the HBVEdu model to a timeseries of discharge.\n\n This functions uses scipy's global optimizer (differential evolution)\n to find a good set of parameters for the model, so that the observed \n discharge is simulated as good as possible.\n\n Args:\n qobs: Array of observed streamflow discharge.\n temp: Array of (mean) temperature for each timestep.\n prec: Array of (summed) precipitation for each timestep.\n month: Array of integers indicating for each timestep to which\n month it belongs [1,2, ..., 12]. Used for adjusted\n potential evapotranspiration.\n PE_m: long-term mean monthly potential evapotranspiration.\n T_m: long-term mean monthly temperature.\n snow_init: (optional) Initial state of the snow reservoir.\n soil_init: (optional) Initial state of the soil reservoir.\n s1_init: (optional) Initial state of the near surface flow\n reservoir.\n s2_init: (optional) Initial state of the base flow reservoir.\n\n Returns:\n res: A scipy OptimizeResult class object.\n \n Raises:\n ValueError: If one of the inputs contains invalid values.\n TypeError: If one of the inputs has an incorrect datatype.\n RuntimeErrror: If the monthly arrays are not of size 12 or there \n is a size mismatch between precipitation, temperature and the\n month array.\n\n \"\"\"\n # Validation check of the temperature, precipitation and qobs input\n temp = validate_array_input(temp, np.float64, 'temperature')\n prec = validate_array_input(prec, np.float64, 'precipitation')\n qobs = validate_array_input(qobs, np.float64, 'observed discharge')\n # Check if there exist negative precipitation\n if check_for_negatives(prec):\n raise ValueError(\"In the precipitation array are negative values.\")\n \n month = validate_array_input(month, np.int8, 'month')\n if any(len(arr) != len(temp) for arr in [prec, month]):\n msg = [\"The arrays of the temperature, precipitation and month \",\n \"data must be of equal size.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Validation check for PE_m and T_m\n PE_m = validate_array_input(PE_m, np.float64, 'PE_m')\n T_m = validate_array_input(T_m, np.float64, 'T_m')\n if any(len(arr) != 12 for arr in [PE_m, T_m]):\n msg = [\"The monthly potential evapotranspiration and temperature\",\n \" array must be of length 12.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Check if entires of month array are between 1 and 12\n if (np.min(month) < 1) or (np.max(month) > 12):\n msg = [\"The month array must be between an integer1 (Jan) and \",\n \"12 (Dec).\"]\n raise ValueError(\"\".join(msg))\n\n # For correct python indexing [start with 0] subtract 1 of month array\n month -= 1\n\n # Make sure all initial storage values are floats\n snow_init = float(snow_init)\n soil_init = float(soil_init)\n s1_init = float(s1_init)\n s2_init = float(s2_init)\n\n # pack input arguments for scipy optimizer\n args = (qobs, temp, prec, month, PE_m, T_m, snow_init, soil_init,\n s1_init, s2_init, self._dtype, self.area)\n bnds = tuple([self._default_bounds[p] for p in self._param_list])\n \n # call scipy's global optimizer\n res = optimize.differential_evolution(_loss, bounds=bnds, args=args)\n\n return res\n\n\ndef _loss(X, *args):\n \"\"\"Return the loss value for the current parameter set.\"\"\"\n # Unpack static arrays\n qobs = args[0]\n temp = args[1]\n prec = args[2]\n month = args[3]\n PE_m = args[4]\n T_m = args[5]\n snow_init = args[6]\n soil_init = args[7]\n s1_init = args[8]\n s2_init = args[9]\n dtype = args[10]\n area = args[11]\n\n # Create custom numpy array of model parameters\n params = np.zeros(1, dtype=dtype)\n params['T_t'] = X[0]\n params['DD'] = X[1]\n params['FC'] = X[2]\n params['Beta'] = X[3]\n params['C'] = X[4]\n params['PWP'] = X[5]\n params['K_0'] = X[6]\n params['K_1'] = X[7]\n params['K_2'] = X[8]\n params['K_p'] = X[9]\n params['L'] = X[10]\n\n # Calculate simulated streamflow\n qsim,_,_,_,_ = _simulate_hbv_edu(temp, prec, month, PE_m, T_m, snow_init,\n soil_init, s1_init, s2_init, params)\n \n # transform discharge to m³/s\n qsim = (qsim * area * 1000) / (24 * 60 * 60)\n\n # Calculate the Mean-Squared-Error as optimization criterion\n loss_value = mse(qobs, qsim)\n\n return loss_value\n\n\n@njit\ndef _simulate_hbv_edu(temp, prec, month, PE_m, T_m, snow_init, soil_init,\n s1_init, s2_init, model_params):\n \"\"\"Run the educational HBV model for given inputs and model parameters.\"\"\"\n # Unpack the model parameters\n T_t = model_params['T_t'][0]\n DD = model_params['DD'][0]\n FC = model_params['FC'][0]\n Beta = model_params['Beta'][0]\n C = model_params['C'][0]\n PWP = model_params['PWP'][0]\n K_0 = model_params['K_0'][0]\n K_1 = model_params['K_1'][0]\n K_2 = model_params['K_2'][0]\n K_p = model_params['K_p'][0]\n L = model_params['L'][0]\n\n # get number of simulation timesteps\n num_timesteps = len(temp)\n\n # initialize empty arrays for all reservoirs and outflow\n snow = np.zeros(num_timesteps, np.float64)\n soil = np.zeros(num_timesteps, np.float64)\n s1 = np.zeros(num_timesteps, np.float64)\n s2 = np.zeros(num_timesteps, np.float64)\n qsim = np.zeros(num_timesteps, np.float64)\n\n # set initial values\n snow[0] = snow_init\n soil[0] = soil_init\n s1[0] = s1_init\n s2[0] = s2_init\n\n # Start the model simulation as loop over all timesteps\n for t in range(1, num_timesteps):\n\n # Check if temperature is below threshold\n if temp[t] < T_t:\n # accumulate snow\n snow[t] = snow[t-1] + prec[t]\n # no liquid water\n liquid_water = 0\n else:\n # melt snow\n snow[t] = max(0, snow[t-1] - DD * (temp[t] - T_t))\n # add melted snow to available liquid water\n liquid_water = prec[t] + min(snow[t-1], DD * (temp[t] - T_t))\n\n # calculate the effective precipitation\n prec_eff = liquid_water * (soil[t-1] / FC) ** Beta\n\n # Calculate the potential evapotranspiration\n pe = (1 + C * (temp[t] - T_m[month[t]])) * PE_m[month[t]]\n\n # Calculate the actual evapotranspiration\n if soil[t-1] > PWP:\n ea = pe\n else:\n ea = pe * (soil[t-1] / PWP)\n\n # calculate the actual level of the soil reservoir\n soil[t] = soil[t-1] + liquid_water - prec_eff - ea\n\n # calculate the actual level of the near surface flow reservoir\n s1[t] = (s1[t-1]\n + prec_eff\n - max(0, s1[t-1] - L) * K_0\n - s1[t-1] * K_1\n - s1[t-1] * K_p)\n\n # calculate the actual level of the base flow reservoir\n s2[t] = (s2[t-1]\n + s1[t-1] * K_p\n - s2[t-1] * K_2)\n\n qsim[t] = ((max(0, s1[t-1] - L)) * K_0\n + s1[t] * K_1\n + s2[t] * K_2)\n \n return qsim, snow, soil, s1, s2\n","sub_path":"rrmpg/models/hbvedu.py","file_name":"hbvedu.py","file_ext":"py","file_size_in_byte":15837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"473363988","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n\ndf = pd.read_csv(\"https://raw.githubusercontent.com/AC2005/covid-learning/main/output/sc_predicts.csv\")\n\ndef calc_percent_error(data, startdate):\n individual_percent_error = list()\n dates = list()\n predict = list()\n actual = list()\n filtered_data = df.loc[df[\"Date\"] >= startdate]\n filtered_data.reset_index(drop=True, inplace=True)\n for i in range(len(filtered_data)):\n actual_data = int(filtered_data['ActualCases'][i])\n predicts = int(filtered_data[\"Predicts\"][i])\n if predicts == 0 or actual_data == 0:\n continue\n dates.append(filtered_data['Date'][i])\n predict.append(predicts)\n actual.append(actual_data)\n temp_perc_error = np.abs((actual_data - predicts)/(predicts))\n individual_percent_error.append(temp_perc_error)\n\n std = np.std(individual_percent_error)\n avg = np.average(individual_percent_error)\n\n max_list = [predict[i] * (1+2*std) for i in range(len(predict))]\n min_list = [predict[i] * (1-2*std) for i in range(len(predict))]\n adjusted_data_set = pd.DataFrame(\n {'Date': dates,\n 'ActualCases': actual,\n 'Preidcts': predict,\n '+2 STD': max_list,\n '-2 STD': min_list\n })\n return adjusted_data_set\n\nnew_data = calc_percent_error(data=df, startdate=\"2020-10-01\")\n\n# plt.plot(max)\n# plt.plot(min)\n# plt.show()\n\n\nprint(max)\nprint(min)\n","sub_path":"model/output_visualization.py","file_name":"output_visualization.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"62969377","text":"# -*- coding: utf-8 -*-\n\n__all__ = ['ArticleDetails', 'ArticleStaying', 'ArticleComments', 'ArticleCommentDetails', 'ArticleLikes',\n 'ArticleShares', 'ArticleUnlike', 'ArticleReport', 'ArticleRedirect']\n\nfrom corelib.views import BaseAPIView\nfrom corelib.response import STATUS_OK_RESPONSE\nfrom corelib.keys import KEY_COUNT, KEY_READ_TAG, KEY_MODE\nfrom corelib.consts import OFFLINE_MODE, REONLINE_MODE\nfrom corelib.exceptions.base import RequestParamInvalid\nfrom corelib.recommendation.engine import RecommendationEngine\n\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom django.http.response import HttpResponseRedirect\n\nfrom article.models import Article\nfrom article.keys import KEY_PLATFORM, KEY_REASON, KEY_CONTENT, KEY_DURATION, ARTICLE_RELATE_COUNT\nfrom article.serializers import CommentCompactSerializer, ArticleProfileSerializer, ArticleCompactSerializer\nfrom article.utils import get_article_view_swith_params\nfrom article.exceptions import CommentNoContent\nfrom category.consts import REC_CATE\n\n\nclass ArticleBaseView(BaseAPIView):\n def initial(self, request, article_id, *args, **kwargs):\n self.article_id = article_id\n self.article = Article.get(article_id)\n super(ArticleBaseView, self).initial(request, *args, **kwargs)\n\n\nclass ArticleDetails(ArticleBaseView):\n def update_data(self, data, switch):\n if not switch:\n return\n del data['content']\n del data['related_images']\n del data['top_images']\n data['switch'] = True\n\n def get(self, request, *args, **kwargs):\n user = request.user\n req_mode = request.QUERY_PARAMS.get(KEY_MODE, '')\n req_user = None\n if not req_mode == OFFLINE_MODE:\n if not user.is_anonymous():\n user.add_read_log(self.article)\n user.update_feature(self.article.feature_matrix)\n req_user = user\n if req_mode == REONLINE_MODE:\n return STATUS_OK_RESPONSE\n\n for cate in self.article.category:\n if cate != \"Top Stories\":\n try:\n category = CATE_NAME_MAPPING[cate]\n except:\n category = REC_CATE\n\n article_seq_ids = RecommendationEngine.fetch_n_article(user, category, ARTICLE_RELATE_COUNT * 2)\n import random\n article_seq_ids = random.sample(article_seq_ids, ARTICLE_RELATE_COUNT * 2)\n articles = Article.objects(seq_id__in=article_seq_ids).exclude('text', 'feature')\n usable_articles = (article for article in articles if article.usable)\n indeed_articles = []\n for article in usable_articles:\n if len(indeed_articles) < ARTICLE_RELATE_COUNT:\n indeed_articles.append(ArticleCompactSerializer(article).data)\n\n data = ArticleProfileSerializer(self.article, req_user, indeed_articles).data\n switch = get_article_view_swith_params(request)\n self.update_data(data, switch)\n\n return Response(data)\n\n\nclass ArticleRedirect(ArticleBaseView):\n def get(self, request, *args, **kwargs):\n return HttpResponseRedirect(self.article.source_url)\n\n\nclass ArticleStaying(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n user = request.user\n duration = request.DATA.get(KEY_DURATION, 0)\n try:\n duration = float(duration)\n except ValueError:\n duration = 0\n if not duration:\n raise RequestParamInvalid\n user.add_duration_to_read_log(self.article, duration)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleComments(ArticleBaseView):\n def get(self, request, *args, **kwargs):\n read_tag = request.QUERY_PARAMS.get(KEY_READ_TAG)\n count = request.QUERY_PARAMS.get(KEY_COUNT, 10)\n comments = self.article.get_comments(count, read_tag)\n return Response([CommentCompactSerializer(comment).data for comment in comments])\n\n def post(self, request, *args, **kwargs):\n content = request.DATA.get(KEY_CONTENT)\n if not content:\n raise CommentNoContent\n comment = self.article.add_comment(request.user, content)\n return Response(CommentCompactSerializer(comment).data)\n\nclass NotificationClickReport(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n user = request.user\n push_id = request.DATA.get('push_id', -1)\n user.mark_notifications(self.article, int(push_id))\n\n return STATUS_OK_RESPONSE\n\n\nclass ArticleCommentDetails(ArticleBaseView):\n def get(self, request, comment_id, *args, **kwargs):\n comment = self.article.get_comment(comment_id)\n return Response(CommentCompactSerializer(comment).data)\n\n def delete(self, request, comment_id, *args, **kwargs):\n self.article.delete_comment(request.user, comment_id)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleLikes(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n self.article.add_like(request.user)\n return STATUS_OK_RESPONSE\n\n def delete(self, request, *args, **kwargs):\n self.article.cancel_like(request.user)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleShares(ArticleBaseView):\n permission_classes = (AllowAny,)\n\n def post(self, request, *args, **kwargs):\n platform = request.DATA.get(KEY_PLATFORM)\n self.article.sharing(request.user, platform)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleUnlike(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n reason = request.DATA.get(KEY_REASON)\n self.article.add_unlike(request.user, reason)\n user = request.user\n if self.article.feature_matrix is not None:\n user.update_feature(-1 * self.article.feature_matrix)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleReport(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n reason = request.DATA.get(KEY_REASON)\n self.article.add_report(request.user, reason)\n self.article.frozen()\n return STATUS_OK_RESPONSE\n","sub_path":"prometheus/article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"402605271","text":"from flask import Flask,jsonify, request\nfrom flaskext.mysql import MySQL \nfrom flask_cors import CORS\n\napp = Flask(__name__)\n\n#Configuracion DB\napp.config['MYSQL_DATABASE_HOST'] = 'localhost'\napp.config['MYSQL_DATABASE_PORT'] = 3306\napp.config['MYSQL_DATABASE_DB'] = 'games_db'\napp.config['MYSQL_DATABASE_USER'] = 'root'\napp.config['MYSQL_DATABASE_PASSWORD'] = ''\n\nmysql = MySQL()\nmysql.init_app(app)\nCORS(app)\n\n#Test que funcione el servidor\n@app.route('/')\ndef ping():\n return 'pong'\n\n\n@app.route('/api/games', methods=['GET'])\ndef get_games():\n cur = mysql.get_db().cursor()\n cur.execute('SELECT * FROM games')\n game_list = cur.fetchall()\n games = []\n for game in game_list:\n new_game = {\"id\":game[0], \"title\":game[1], \"description\":game[2], \"image\":game[3]}\n games.append(new_game)\n return jsonify(games)\n\n@app.route('/api/games/', methods=['GET'])\ndef get_game(id):\n if request.method == 'GET':\n cur = mysql.get_db().cursor()\n cur.execute('SELECT * FROM games WHERE id = %s',(id))\n game_list = cur.fetchall()\n games = []\n for game in game_list:\n new_game = {\"id\":game[0], \"title\":game[1], \"description\":game[2], \"image\":game[3]}\n games.append(new_game)\n return jsonify(games)\n\n\n@app.route('/api/games', methods=['POST'])\ndef add_game():\n if request.method == 'POST':\n title = request.json['title']\n description = request.json['description']\n image = request.json['image']\n cur = mysql.get_db().cursor()\n cur.execute('INSERT INTO games (title,description,image) VALUES (%s,%s,%s)',(title,description,image))\n mysql.get_db().commit()\n return jsonify({'message':'game added successfully'})\n\n@app.route('/api/games/', methods=['PUT'])\ndef edit_game(id):\n if request.method == 'PUT':\n title = request.json['title']\n description = request.json['description']\n image = request.json['image']\n cur = mysql.get_db().cursor()\n cur.execute('UPDATE games SET title=%s, description=%s, image=%s WHERE id=%s',(title,description,image,id))\n mysql.get_db().commit()\n games = [{'id':id,'title':title,'description':description,'image':image}]\n return jsonify(games)\n\n@app.route('/api/games/', methods=['DELETE'])\ndef delete_game(id):\n if request.method == 'DELETE':\n cur = mysql.get_db().cursor()\n cur.execute('DELETE FROM games WHERE id=%s',id)\n mysql.get_db().commit()\n return jsonify({\"message\":\"game deleted successfully\"})\n\n\n#Arranco el servidor en modo prueba en el puerto 3000\nif __name__ == \"__main__\":\n app.run(debug=True,port=3000)\n\n ","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"179158287","text":"from django.core.urlresolvers import reverse\nfrom django_webtest import WebTest\nimport webtest\n\nfrom django.contrib.auth.models import User\nfrom evap.evaluation.models import Semester, Questionnaire\n\nimport os.path\n\n\ndef lastform(page):\n return page.forms[max(page.forms.keys())]\n\n\nclass UsecaseTests(WebTest):\n fixtures = ['usecase-tests']\n \n extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}\n \n def test_import(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new semester\n page = page.click(\"[Ss]emesters\")\n page = page.click(\"[Nn]ew [Ss]emester\")\n semester_form = lastform(page)\n semester_form['name_de'] = \"Testsemester\"\n semester_form['name_en'] = \"test semester\"\n page = semester_form.submit().follow()\n \n # retrieve new semester\n semester = Semester.objects.get(name_de=\"Testsemester\",\n name_en=\"test semester\")\n \n self.assertEqual(semester.course_set.count(), 0, \"New semester is not empty.\")\n \n # safe original user count\n original_user_count = User.objects.all().count()\n \n # import excel file\n page = page.click(\"[Ii]mport\")\n upload_form = lastform(page)\n upload_form['vote_start_date'] = \"02/29/2000\"\n upload_form['vote_end_date'] = \"02/29/2012\"\n upload_form['excel_file'] = (os.path.join(os.path.dirname(__file__), \"fixtures\", \"samples.xls\"),)\n page = upload_form.submit().follow()\n \n self.assertEqual(semester.course_set.count(), 23, \"Wrong number of courses after Excel import.\")\n self.assertEqual(User.objects.count(), original_user_count + 24, \"Wrong number of users after Excel import.\")\n \n check_student = User.objects.get(username=\"Diam.Synephebos\")\n self.assertEqual(check_student.first_name, \"Diam\")\n self.assertEqual(check_student.email, \"Diam.Synephebos@student.hpi.uni-potsdam.de\")\n \n check_lecturer = User.objects.get(username=\"Sanctus.Aliquyam\")\n self.assertEqual(check_lecturer.first_name, \"Sanctus\")\n self.assertEqual(check_lecturer.last_name, \"Aliquyam\")\n self.assertEqual(check_lecturer.email, \"567@web.de\")\n \n def test_logon_key(self):\n with self.assertRaises(webtest.app.AppError):\n self.app.get(reverse(\"evap.results.views.index\"))\n \n user = User.objects.all()[0]\n userprofile = user.get_profile()\n userprofile.generate_logon_key()\n userprofile.save()\n \n url_with_key = reverse(\"evap.results.views.index\") + \"?userkey=%s\" % userprofile.logon_key\n self.app.get(url_with_key)\n \n def test_create_questionnaire(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new questionnaire\n page = page.click(\"[Qq]uestionnaires\")\n page = page.click(\"[Nn]ew [Qq]uestionnaire\")\n questionnaire_form = lastform(page)\n questionnaire_form['name_de'] = \"Test Fragebogen\"\n questionnaire_form['name_en'] = \"test questionnaire\"\n questionnaire_form['public_name_de'] = \"Oeffentlicher Test Fragebogen\"\n questionnaire_form['public_name_en'] = \"Public Test Questionnaire\"\n questionnaire_form['question_set-0-text_de'] = \"Frage 1\"\n questionnaire_form['question_set-0-text_en'] = \"Question 1\"\n questionnaire_form['question_set-0-kind'] = \"T\"\n page = questionnaire_form.submit().follow()\n \n # retrieve new questionnaire\n questionnaire = Questionnaire.objects.get(name_de=\"Test Fragebogen\", name_en=\"test questionnaire\")\n self.assertEqual(questionnaire.question_set.count(), 1, \"New questionnaire is empty.\")\n \n def test_create_empty_questionnaire(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new questionnaire\n page = page.click(\"[Qq]uestionnaires\")\n page = page.click(\"[Nn]ew [Qq]uestionnaire\")\n questionnaire_form = lastform(page)\n questionnaire_form['name_de'] = \"Test Fragebogen\"\n questionnaire_form['name_en'] = \"test questionnaire\"\n questionnaire_form['public_name_de'] = \"Oeffentlicher Test Fragebogen\"\n questionnaire_form['public_name_en'] = \"Public Test Questionnaire\"\n page = questionnaire_form.submit()\n \n assert \"You must have at least one of these\" in page\n \n # retrieve new questionnaire\n with self.assertRaises(Questionnaire.DoesNotExist):\n Questionnaire.objects.get(name_de=\"Test Fragebogen\", name_en=\"test questionnaire\")\n \n def test_copy_questionnaire(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new questionnaire\n page = page.click(\"[Qq]uestionnaires\")\n page = page.click(\"Copy\")\n questionnaire_form = lastform(page)\n questionnaire_form['name_de'] = \"Test Fragebogen (kopiert)\"\n questionnaire_form['name_en'] = \"test questionnaire (copied)\"\n questionnaire_form['public_name_de'] = \"Oeffentlicher Test Fragebogen (kopiert)\"\n questionnaire_form['public_name_en'] = \"Public Test Questionnaire (copied)\"\n page = questionnaire_form.submit().follow()\n \n # retrieve new questionnaire\n questionnaire = Questionnaire.objects.get(name_de=\"Test Fragebogen (kopiert)\", name_en=\"test questionnaire (copied)\")\n self.assertEqual(questionnaire.question_set.count(), 2, \"New questionnaire is empty.\")\n \n def test_assign_questionnaires(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # assign questionnaire to courses\n page = page.click(\"Semester 1 \\(en\\)\", index=0)\n page = page.click(\"Assign Questionnaires\")\n assign_form = lastform(page)\n assign_form['Seminar'] = [1]\n assign_form['Vorlesung'] = [1]\n page = assign_form.submit().follow()\n \n # get semester and check\n semester = Semester.objects.get(pk=1)\n questionnaire = Questionnaire.objects.get(pk=1)\n for course in semester.course_set.all():\n self.assertEqual(course.general_assignment.questionnaires.count(), 1)\n self.assertEqual(course.general_assignment.questionnaires.get(), questionnaire)\n","sub_path":"evap/fsr/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}