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
Ghernandez1991/Spotify-Top-100
https://github.com/Ghernandez1991/Spotify-Top-100
fe4b803a8b4feee31b50f24e2a24dc47215306df
e05652a32c18df1e0612d93a652ca061f0a303bb
9341e8d2767606b88389fac7b1a46382a9f9ecea
refs/heads/master
2020-08-28T18:27:47.500816
2019-10-27T00:16:31
2019-10-27T00:16:31
217,784,335
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5827193856239319, "alphanum_fraction": 0.5912591814994812, "avg_line_length": 22.702381134033203, "blob_id": "315ac52747f2b007a50999773c0aacfa71966abd", "content_id": "906a8055700a2516f71660eb3dc38ffb20c3e75e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5972, "license_type": "no_license", "max_line_length": 70, "num_lines": 252, "path": "/app.py", "repo_name": "Ghernandez1991/Spotify-Top-100", "src_encoding": "UTF-8", "text": "import pandas as pd \nimport os\nfrom flask import Flask, jsonify, render_template, g\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine\nimport sqlite3\n\nfrom flask_sqlalchemy import SQLAlchemy \n\n\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///spotify.sqlite\"\n\ndb = SQLAlchemy(app)\n\n# from .models import Songs, Features\n\nclass Songs(db.Model):\n __tablename__ = 'artists_songs'\n\n Artist = db.Column(db.String)\n Song = db.Column(db.String, primary_key=True)\n \n def __repr__(self):\n return '<Songs %r>' % (self.Artist)\n\n\nclass Features(db.Model):\n __tablename__ = 'artists_songs_analyzed'\n\n Artist = db.Column(db.String) \n Song = db.Column(db.String, primary_key=True) \n acousticness = db.Column(db.Float) \n analysis_url = db.Column(db.String) \n danceability = db.Column(db.Float) \n duration_ms = db.Column(db.Float) \n energy = db.Column(db.Float) \n id = db.Column(db.String) \n instrumentalness = db.Column(db.Float) \n key = db.Column(db.Integer) \n liveness = db.Column(db.Float) \n loudness = db.Column(db.Float) \n mode = db.Column(db.Integer) \n speechiness = db.Column(db.Float) \n tempo = db.Column(db.Float) \n time_signature = db.Column(db.Integer) \n track_href = db.Column(db.String) \n type = db.Column(db.String) \n uri = db.Column(db.String) \n valence = db.Column(db.Float)\n \n\n def __repr__(self):\n return '<Features %r>' % (self.Artist)\n\n\n\n\n\n\n\n\n\n\n\n\n# reflect an existing database into a new model\n# Base = automap_base()\n# # reflect the tables\n# Base.prepare(db.engine, reflect=True)\n# # Save references to each table\n# songs = Base.classes.artists_songs\n# analyzed = Base.classes.artists_songs_analyzed\n\[email protected](\"/\")\ndef index():\n return render_template('index.html')\n\[email protected](\"/tracks\")\ndef tracks():\n results = db.session.query(Songs.Song).all()\n results2 = results[0:100]\n\n return jsonify(results2)\n\n\[email protected](\"/trackfeatures/<song>\")\ndef trackfeatures(song):\n \"\"\"Return the MetaData for a given sample.\"\"\"\n \n sel = [\n Features.Artist,\n Features.Song,\n Features.acousticness,\n Features.analysis_url,\n Features.danceability,\n Features.duration_ms,\n Features.energy,\n Features.id,\n Features.instrumentalness,\n Features.key,\n Features.liveness,\n Features.loudness,\n Features.mode,\n Features.speechiness,\n Features.tempo,\n Features.time_signature,\n Features.track_href,\n Features.type,\n Features.uri,\n Features.valence\n ]\n \n results = db.session.query(*sel).filter(Features.Song==song).all()\n\n feature_dict = {}\n\n for result in results:\n feature_dict[\"Artist\"] = result[0]\n feature_dict[\"Song\"] = result[1]\n feature_dict[\"acousticness\"] = result[2]\n feature_dict[\"analysis_url\"] = result[3]\n feature_dict[\"danceability\"] = result[4]\n feature_dict[\"duration_ms\"] = result[5]\n feature_dict[\"energy\"] = result[6]\n feature_dict[\"id\"] = result[7]\n feature_dict[\"instrumentalness\"] = result[8]\n feature_dict[\"key\"] = result[9]\n feature_dict[\"liveness\"] = result[10]\n feature_dict[\"loudness\"] = result[11]\n feature_dict[\"mode\"] = result[12]\n feature_dict[\"speechiness\"] = result[13]\n feature_dict[\"tempo\"] = result[14]\n feature_dict[\"time_signature\"] = result[15]\n feature_dict[\"track_href\"] = result[16]\n feature_dict[\"type\"] = result[17]\n feature_dict[\"uri\"] = result[18]\n feature_dict[\"valence\"] = result[19]\n\n #if sample_metadata in sample_metadata:\n #sample_metadata[sample].append(result[0])\n #else:\n #sample_metadata[sample] = [result[0]]\n\n\n #sample_metadata.append(result)\n print(feature_dict)\n return jsonify(feature_dict)\n\[email protected](\"/alltrackfeatures\")\ndef alltrackfeatures():\n \"\"\"Return the MetaData for a given sample.\"\"\"\n \n # conn = sqlite3.connect(\"sqlite:///spotify.sqlite\")\n # conn.row_factory = sqlite3.Row\n # c = conn.cursor()\n # c.execute('select * from artists_songs_analyzed')\n\n # total_info = c.fetchall()\n \n \n sel = [\n Features.Artist,\n Features.Song,\n Features.acousticness,\n Features.analysis_url,\n Features.danceability,\n Features.duration_ms,\n Features.energy,\n Features.id,\n Features.instrumentalness,\n Features.key,\n Features.liveness,\n Features.loudness,\n Features.mode,\n Features.speechiness,\n Features.tempo,\n Features.time_signature,\n Features.track_href,\n Features.type,\n Features.uri,\n Features.valence\n ]\n \n results5 = db.session.query(*sel).filter().all()\n\n\n\n list_of_keys = [\"Artist\",\n \"Song\",\n \"acousticness\",\n \"analysis_url\",\n \"danceability\",\n \"duration_ms\",\n \"energy\",\n \"id\",\n \"instrumentalness\",\n \"key\",\n \"liveness\",\n \"loudness\",\n \"mode\",\n \"speechiness\",\n \"tempo\",\n \"time_signature\",\n \"track_href\",\n \"type\",\n \"uri\",\n \"valence\"]\n\n \n list_of_values = []\n data = {}\n master_list = []\n\n for result in results5:\n for j in range(0,20):\n list_of_values.append(result[j])\n data = dict(zip(list_of_keys, list_of_values))\n master_list.append(data)\n data = {}\n list_of_values = []\n \n\n \n\n\n\n\n\n\n \n \n #print(results5)\n # df4 = pd.DataFrame(results5)\n # test1 = df4.to_dict()\n\n\n #sample_metadata.append(result)\n #print(feature_dict)\n return jsonify(master_list)\n\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)" }, { "alpha_fraction": 0.5752800107002258, "alphanum_fraction": 0.5857860445976257, "avg_line_length": 30.362499237060547, "blob_id": "3ea763434d157ec005298762ab8a1281be964df3", "content_id": "c1bc9de3c39b8a54cdee70576320d7810a105844", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12945, "license_type": "no_license", "max_line_length": 112, "num_lines": 400, "path": "/static/js/logic.js", "repo_name": "Ghernandez1991/Spotify-Top-100", "src_encoding": "UTF-8", "text": "// Submit Button handler\r\nfunction handleSubmit() {\r\n // Prevent the page from refreshing\r\n d3.event.preventDefault();\r\n\r\n var text1 =document.getElementById(\"selDataset\").value\r\n console.log(text1);\r\n \r\n // clear the input value\r\n d3.select(\"selDataset\").node().value = \"\";\r\n\r\n // Build the plot with the new stock\r\n buildCharts(text1);\r\n}\r\n\r\n\r\n\r\n//grab the use sample from the drop down menu creating constant variable \r\nvar text1 =document.getElementById(\"selDataset\").value\r\n//create function to build the meta data\r\n\r\nfunction buildMetadata() {\r\n //grab the use sample from the drop down menu \r\n var text1 =document.getElementById(\"selDataset\").value\r\n \r\n //create url for d3.json to go to using f print with the value the user selects\r\n var defaulturl = `trackfeatures/${text1}`;\r\n \r\n //use d3.json to go to the url, grab the data and then console log it out\r\n d3.json(defaulturl).then(function(response) {\r\n console.log(response);\r\n\r\n // Grab values from the response json object to build the plots\r\n var Artist = response.Artist;\r\n var Song = response.Song;\r\n var Danceability = response.danceability;\r\n var Energy = response.energy;\r\n var Key = response.key;\r\n var Loudness = response.loudness;\r\n var Mode = response.mode;\r\n var Speechiness = response.speechiness;\r\n var Acousticness = response.acousticness;\r\n var Instrumentalness = response.instrumentalness;\r\n var Liveness = response.liveness;\r\n var Valence = response.valence;\r\n var Tempo = response.tempo;\r\n var Type = response.type;\r\n var Id = response.id;\r\n var Uri = response.uri;\r\n var Track_href = response.track_href;\r\n var Analysis_url = response.analysis_url;\r\n var Duration_ms = response.duration_ms;\r\n var Time_signature = response.time_signature;\r\n //console log a variable to ensure it is working\r\n console.log(Time_signature);\r\n \r\n \r\n var data = response;\r\n\r\n // Use d3 to select the panel with id of `#sample-metadata`\r\n var panel = d3.select(\".panel-body\");\r\n // Use `.html(\"\") to clear any existing metadata\r\n panel.html(\"\")\r\n //for loop down the panel 1 time, each time adding a row with data, then another row with 1 piece of data\r\n for (var i = 0; i < 1; i++) {\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Artist:${Artist}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Song:${Song}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Danceability:${Danceability}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Energy:${Energy}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Key:${Key}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Loudness:${Loudness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Mode:${Mode}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Speechiness:${Speechiness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Acousticness:${Acousticness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Instrumentalness:${Instrumentalness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Liveness:${Liveness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Valence:${Valence}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Tempo:${Tempo}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Duration Ms:${Duration_ms}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Time Signature:${Time_signature}`);}\r\n }); \r\n \r\n \r\n var text2 =document.getElementById(\"selDataset1\").value\r\n \r\n //create url for d3.json to go to using f print with the value the user selects\r\n var defaultur1 = `trackfeatures/${text2}`;\r\n \r\n //use d3.json to go to the url, grab the data and then console log it out\r\n d3.json(defaultur1).then(function(response) {\r\n console.log(response);\r\n \r\n // Grab values from the response json object to build the plots\r\n var Artist = response.Artist;\r\n var Song = response.Song;\r\n var Danceability = response.danceability;\r\n var Energy = response.energy;\r\n var Key = response.key;\r\n var Loudness = response.loudness;\r\n var Mode = response.mode;\r\n var Speechiness = response.speechiness;\r\n var Acousticness = response.acousticness;\r\n var Instrumentalness = response.instrumentalness;\r\n var Liveness = response.liveness;\r\n var Valence = response.valence;\r\n var Tempo = response.tempo;\r\n var Type = response.type;\r\n var Id = response.id;\r\n var Uri = response.uri;\r\n var Track_href = response.track_href;\r\n var Analysis_url = response.analysis_url;\r\n var Duration_ms = response.duration_ms;\r\n var Time_signature = response.time_signature;\r\n //console log a variable to ensure it is working\r\n console.log(Time_signature);\r\n \r\n \r\n var data = response;\r\n \r\n // Use d3 to select the panel with id of `#sample-metadata`\r\n var panel = d3.select(\".panel-body1\");\r\n // Use `.html(\"\") to clear any existing metadata\r\n panel.html(\"\")\r\n //for loop down the panel 1 time, each time adding a row with data, then another row with 1 piece of data\r\n for (var i = 0; i < 1; i++) {\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Artist:${Artist}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Song:${Song}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Danceability:${Danceability}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Energy:${Energy}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Key:${Key}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Loudness:${Loudness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Mode:${Mode}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Speechiness:${Speechiness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Acousticness:${Acousticness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Instrumentalness:${Instrumentalness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Liveness:${Liveness}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Valence:${Valence}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Tempo:${Tempo}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Duration Ms:${Duration_ms}`);\r\n trow = panel.append(\"tr\");\r\n trow.append(\"td\").text(`Time Signature:${Time_signature}`);}\r\n }); \r\n\r\n}\r\n\r\nfunction buildCharts(text1) {\r\n\r\n\r\n //create event handler to campute the users selection \r\n var text2 =document.getElementById(\"selDataset\").value\r\n //console log to ensure we are getting a value\r\n console.log(text2)\r\n //create a new url taking the sample selected- change the route to sample api\r\n var defaulturl1 = `/alltrackfeatures`;\r\n //console log to ensure we are getting an accurate api url\r\n console.log(defaulturl1)\r\n //use d3.json to go to the api url to gather the data- print the data\r\n d3.json(defaulturl1).then(function(response){\r\n var song_keys = [];\r\n var song_names = [];\r\n var song_energy = [];\r\n var song_dance = [];\r\n for (i=0; i<response.length; i++){\r\n song_keys.push(response[i].key);\r\n song_names.push(response[i].Song);\r\n song_energy.push(response[i].energy);\r\n song_dance.push(response[i].danceability);\r\n }\r\n\r\n \r\n\r\n\r\n // @TODO: Build a Bubble Chart to populate the field when the app is first initiated. \r\n //create a trace first \r\n //Build a Scatter Plot to populate the field when the app is first initiated\r\n var trace_scatter = {\r\n x: song_energy,\r\n y: song_dance,\r\n text: song_names,\r\n mode: 'markers',\r\n type: 'scatter'\r\n };\r\n var data_scatter = [trace_scatter];\r\n var layout_scatter = {\r\n title: \"Energy vs. Danceability\"\r\n };\r\n Plotly.newPlot(\"scatter\", data_scatter, layout_scatter);\r\n\r\n\r\n\r\n \r\n var values = [];\r\n var bin1_count = 0;\r\n var bin2_count = 0;\r\n var bin3_count = 0;\r\n var bin4_count = 0;\r\n for (i=0; i<song_keys.length; i++){\r\n if (song_keys[i] < 3) {\r\n bin1_count++;\r\n } else if (song_keys[i]<6 && song_keys[i]>2) {\r\n bin2_count++;\r\n } else if (song_keys[i]<9 && song_keys[i]>5) {\r\n bin3_count++;\r\n } else {\r\n bin4_count++;\r\n }\r\n }\r\n values.push(bin1_count);\r\n values.push(bin2_count);\r\n values.push(bin3_count);\r\n values.push(bin4_count);\r\n var trace2 = {\r\n labels: [\"0 to 2\", \"3 to 5\", \"6 to 8\", \"9 to 11\"],\r\n values: values,\r\n type: 'pie',\r\n };\r\n var data2 = [trace2];\r\n var layout2 = {\r\n title: \"Songs by Key\"\r\n }\r\n Plotly.newPlot(\"pie\", data2, layout2);\r\n });\r\n\r\n\r\n\r\n\r\n//Build radar chart\r\n\r\n\r\n\r\n\r\n let songone = document.getElementById(\"selDataset\").value;\r\n let songtwo = document.getElementById(\"selDataset1\").value;\r\n var songone_url = `/trackfeatures/${songone}`;\r\n var songtwo_url = `/trackfeatures/${songtwo}`;\r\n \r\n\r\n \r\n\r\n d3.json(songone_url).then(function(response){\r\n var Song = response.Song;\r\n var Danceabilityradar = response.danceability;\r\n var Energyradar = response.energy;\r\n var Speechinessradar = response.speechiness;\r\n var Acousticnessradar = response.acousticness;\r\n var Livenessradar = response.liveness;\r\n var Valenceradar = response.valence;\r\n \r\n d3.json(songtwo_url).then(function(response){\r\n var Song2 = response.Song;\r\n var Danceabilityradar2 = response.danceability;\r\n var Energyradar2 = response.energy;\r\n var Speechinessradar2 = response.speechiness;\r\n var Acousticnessradar2 = response.acousticness;\r\n var Livenessradar2 = response.liveness;\r\n var Valenceradar2 = response.valence;\r\n \r\n \r\n let myChart = document.getElementById('myChart').getContext('2d');\r\n // Global Options\r\n Chart.defaults.global.defaultFontFamily = 'Lato';\r\n Chart.defaults.global.defaultFontsize = 18;\r\n Chart.defaults.global.defaultFontColor = '#777';\r\n let PrPopChart = new Chart(myChart, {\r\n type:'radar', \r\n data:{\r\n labels:['Danceability', 'Energy', 'Speechiness', 'Acousticness', 'Liveness\t', 'Valence'],\r\n datasets:[{\r\n label: `${Song}`,\r\n backgroundColor: 'rgba(250, 0, 0, 0.5)',\r\n borderColor: \"white\",\r\n pointBackgroundColor: \"white\",\r\n data: [\r\n Danceabilityradar,\r\n Energyradar,\r\n Speechinessradar,\r\n Acousticnessradar,\r\n Livenessradar,\r\n Valenceradar\r\n ]\r\n },\r\n {\r\n label: `${Song2}`,\r\n backgroundColor: 'rgba(0, 0, 300, 0.5)',\r\n borderColor: \"white\",\r\n pointBackgroundColor: \"white\",\r\n data: [\r\n Danceabilityradar2,\r\n Energyradar2,\r\n Speechinessradar2,\r\n Acousticnessradar2,\r\n Livenessradar2,\r\n Valenceradar2\r\n ]\r\n } ]\r\n \r\n },\r\n options:{\r\n title:{\r\n display: true,\r\n text: 'Radar Chart',\r\n fontSize:25\r\n },\r\n legend:{\r\n display:false,\r\n position:'right',\r\n labels:{\r\n fontColor: '#000'\r\n }\r\n },\r\n layout:{\r\n padding:{\r\n left:0,\r\n right:0,\r\n bottom:0,\r\n top:0\r\n }\r\n },\r\n tooltips:{\r\n enabled:true\r\n }\r\n }\r\n \r\n })})});\r\n\r\n \r\n}\r\n\r\nfunction init() {\r\n // Grab a reference to the dropdown select element\r\n var selector = d3.select(\"#selDataset\");\r\n \r\n // Use the list of sample names to populate the select options\r\n d3.json(\"/tracks\").then((Song) => {\r\n Song.forEach((song) => {\r\n selector\r\n .append(\"option\")\r\n .text(song)\r\n .property(\"value\", song);\r\n });\r\n\r\n // Use the first sample from the list to build the initial plots\r\n const firstsong = Song[0];\r\n buildCharts(firstsong);\r\n buildMetadata(firstsong);\r\n });\r\n\r\n var selector1 = d3.select(\"#selDataset1\");\r\n d3.json(\"/tracks\").then((Song) => {\r\n Song.forEach((song) => {\r\n selector1\r\n .append(\"option\")\r\n .text(song)\r\n .property(\"value\", song);\r\n });\r\n\r\n // Use the first sample from the list to build the initial plots\r\n const firstsong1 = Song[0];\r\n buildCharts(firstsong1);\r\n buildMetadata(firstsong1);\r\n });\r\n}\r\n\r\nfunction optionChanged(newSong) {\r\n // Fetch new data each time a new sample is selected\r\n buildCharts(newSong);\r\n buildMetadata(newSong);\r\n}\r\n\r\n// Initialize the dashboard\r\ninit();\r\n" }, { "alpha_fraction": 0.700560450553894, "alphanum_fraction": 0.7074993252754211, "avg_line_length": 69.69811248779297, "blob_id": "e83164d0b294ce6a7867fd70043cf36c559780de", "content_id": "119170b6a5449e47549fbe260452797ef56abbe3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3753, "license_type": "no_license", "max_line_length": 485, "num_lines": 53, "path": "/README.md", "repo_name": "Ghernandez1991/Spotify-Top-100", "src_encoding": "UTF-8", "text": "# Spotify-Top-100\n\n\n![Alt text](images/image.PNG?raw=true \"Optional Title\")\n\n\n\n1-Webscraping\nUsing spotify’s website, scrape the top 100 streamed songs of all time.\nhttps://open.spotify.com/playlist/2YRe7HRKNRvXdJBp9nXFza\nSongs were stored based in a div class\nLooped through the beautiful soup object, found all the div classes and stored into a python list.\nDid the same for both the songs and artists. Store both lists in a Dataframes\n\n\n--------------------------------------------------------------------------------------------------\n2-Api Calls.\nRealized that Spotify’s documentation was written CURL and not python. Took us way too long to realize we were not reading python\nUsed spotipy python library to make successive API calls to Spotify’s API endpoint.\nThis API required a client id and client secret.\nAfter many challenges, we were able to pull down song features for every song in our list.\nWe joined these song results with our prior dataframe for a master list.\nUsing SQLite2, we were able to push both data frames to a SQLite file.\n\n--------------------------------------------------------------------------------------------------\n3-Flask APP.\nCreated a flask app with four separate routes.\nA- Home route- Used to render index.html\nB- /tracks- used to render song track titles in json format\nC- /trackfeatures/<song>- used to render track features when the user selects a song\nD- /alltrackfeatures- used to render all track features for all songs.\nThe most difficult part of the creation of the flask app were.\nA- Realizing you cannot auto map a database table that did not have a primary key. Workaround was to created a class to access each table.\nB- Returning the data in a usable json format because the API calls already returned in a nest list of list of dictionaries.\n \n \n --------------------------------------------------------------------------------------------------\n4- Visualization\nWe decided to create an interactive dash board featuring 3 views and a couple of drop down menus.\nThe drop downs show each songs respective metadata(go over definitions) and allow the user to combine each song on a radar chart to compare their qualities.\nWe also created a scatter plot comparing song energy vs danceability. Lastly, we created a pie chart showing the percentages of the top 100 songs in every key.\nThe visualization was created using D3 and Charts.JS.\nVisualization challenges-\nScatter plot- Chart.js wanted a list of x,y dictionaries/coordinates which did not match our back end data format. We had to substitute plotly which was more forgiving to the data format.\nPie Chart- In order the create the required pie chart, we needed to learn javascript binning in order to bin the api results in their respective key before they could be charted.\nRadar Chart- Challenges arose trying to make two separate d3.json calls to our flask app. Since the user is passing in two separate songs, two separate calls needed to be made to the /trackfeatures/<song> end point. We had issues with scoping since we could not call the first song variables, in the second d3.json call. We had to create a work around by nesting the d3.json functions inside of one another so the variables from both songs were available when plotting the radar chart.\n \n --------------------------------------------------------------------------------------------------\n5-IF WE HAD MORE TIME\nAdd functionality to swap between x and y variables on the scatter plot to let the user select which variables to compare between the top 100 charts\nCustomize the radar chart and map the color to the color of the drop down menus for each respective song\nCreate functionality to play each song when the user selects it.\nPublish to Heroku\n" } ]
3
hysds/chimera
https://github.com/hysds/chimera
39d9197ce0e64850dff2d4791e0e798f3a1ce4b5
b9716b309fbf9f1cf2a27dbbc065a540276be04f
0ee4cdfcb97dbf3e57cee7f4ae63bba728587f4c
refs/heads/develop
2023-01-11T08:05:55.985192
2022-06-13T17:08:02
2022-06-13T17:08:02
165,933,791
0
0
null
2019-01-15T22:31:42
2022-01-07T15:12:38
2022-12-27T15:33:47
Python
[ { "alpha_fraction": 0.6275894641876221, "alphanum_fraction": 0.6403013467788696, "avg_line_length": 44.191490173339844, "blob_id": "c4c0f4010e8b39ddf439150c23b8fe7ed0f680cc", "content_id": "ecbb37274d03cfe8b30cd9c2d7228f856e5e53c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2124, "license_type": "no_license", "max_line_length": 147, "num_lines": 47, "path": "/tests/test_run_pge_docker.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import json\nimport os\nfrom swot_chimera import run_pge_docker\n\nif __name__ == '__main__':\n \"\"\"\n This is for testing of PGE Job Submission JSON\n Comment out from hysds.celery import app in query_util.py\n Comment out from hysds_commons.job_utils import resolve_hysds_job in run_pge_docker.py\n\n In commons/query_util.py, overwrite GRQ URL with:\n ES_URL = \"http://127.0.0.1:9300\"\n\n In run_pge_docker.construct_job_payload()\n make the following change:\n if test_mode is False:\n #job = resolve_hysds_job(job_type, job_queue, params=params, job_name= job_name, enable_dedup= True, tags=tags, payload_hash= payload_hash)\n job = {}\n\n Update the following sample files:\n sf_context: should be the sciflo context of an actual workflow run\n runconfig: output from the input preprocessor\n job_json: this is optional, it is used to determine if the workflow has been retried.\n This is currently only used at step PGE_L0B_Radiometer.\n It should be the _job.json of an actual workflow run\n\n If not testing for an L0B run please update:\n pge_config_file: path to PGE's config file\n\n run this script\n \"\"\"\n\n # Testing L0B PGE job submission\n os.path.dirname(os.path.realpath(__file__))\n sf_context = os.path.dirname(os.path.realpath(\n __file__))+\"/test-files/L1B_HR_SLC-sfcontext.json\"\n runconfig = json.loads(open(os.path.dirname(os.path.realpath(__file__))+\"/test-files/L1B_HR_SLC-runconfig.json\", \"r\")\n .read())\n pge_config_file = os.path.abspath(os.path.join(os.path.realpath(__file__), \"../../\",\n \"swot_chimera/configs/pge_configs/examples/PGE_L1B_HR_SLC.json\"))\n sys_config_file = os.path.abspath(\n os.path.join(os.path.realpath(__file__), \"../..\", \"swot_chimera/configs/sys.config.json\"))\n job_json = os.path.dirname(os.path.realpath(\n __file__))+\"/test-files/L0B_job.json\"\n\n run_pge_docker.submit_pge_job(sf_context, runconfig, pge_config_file, sys_config_file,\n wuid=\"1213\", job_num=\"231232\")\n" }, { "alpha_fraction": 0.629915177822113, "alphanum_fraction": 0.629915177822113, "avg_line_length": 26.595745086669922, "blob_id": "c3d6b05e78685807e0c0a7ceeed09987e7c90e7a", "content_id": "d748bcef930ca4686da9bccb3e3c8e1a2c11db78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1297, "license_type": "no_license", "max_line_length": 108, "num_lines": 47, "path": "/chimera/logger.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import logging\n\nfrom enum import Enum\n\n# set logger and custom filter to handle being run from sciflo\nlog_format = \"[%(asctime)s: %(levelname)s/%(funcName)s] %(message)s\"\nlogging.basicConfig(format=log_format, level=logging.INFO)\n\n\nclass LogLevels(Enum):\n DEBUG = \"DEBUG\"\n INFO = \"INFO\"\n WARNING = \"WARNING\"\n ERROR = \"ERROR\"\n\n @staticmethod\n def list():\n return list(map(lambda c: c.value, LogLevels))\n\n def __str__(self):\n return self.value\n\n @staticmethod\n def set_level(level):\n if level == LogLevels.DEBUG.value:\n logger.setLevel(logging.DEBUG)\n elif level == LogLevels.INFO.value:\n logger.setLevel(logging.INFO)\n elif level == LogLevels.WARNING.value:\n logger.setLevel(logging.WARNING)\n elif level == LogLevels.ERROR.value:\n logger.setLevel(logging.ERROR)\n else:\n raise RuntimeError(\"{} is not a valid logging level. Should be one of the following: {}\".format(\n level, LogLevels.list()))\n\n\nclass LogFilter(logging.Filter):\n def filter(self, record):\n if not hasattr(record, 'id'):\n record.id = '--'\n return True\n\n\nlogger = logging.getLogger('nisar_chimera')\nlogger.setLevel(logging.INFO)\nlogger.addFilter(LogFilter())\n" }, { "alpha_fraction": 0.7409282922744751, "alphanum_fraction": 0.7409282922744751, "avg_line_length": 33.85293960571289, "blob_id": "926b6caa96ceca417de6ab938fa4691f32946f4c", "content_id": "0608d6762b5d89e47d0d835faa05da2c38d149ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1185, "license_type": "no_license", "max_line_length": 117, "num_lines": 34, "path": "/chimera/input_preprocessor.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nContributors:\n- Sujen Shah\n- Michael Cayanan\n- Namrata Malarout\n\nThis is the first step of Chimera called Input Preprocessor (IPP)\nThe Input preprocessor runs all the preconditions and constructs the configuration required to run an algorithm (PGE)\n\"\"\"\n\nfrom chimera.logger import logger\nfrom chimera.precondition_evaluator import PreConditionEvaluator\n\n\ndef process(sf_context, chimera_config_file, pge_config_filepath, settings_file):\n \"\"\"\n Process the inputs to check if the preconditions for the provided PGE are satisfied.\n :param sf_context: Input context (sciflow context or post processor output)\n :param chimera_config_file: Chimera config file.\n :param pge_config_filepath: path to the pge config json file\n :param settings_file: Settings file.\n\n :return: python dict containing context for the PGE to run\n \"\"\"\n logger.info(\"Starting input_preprocessor step.\")\n pre_cond_evaluator = PreConditionEvaluator(sf_context, chimera_config_file, pge_config_filepath, settings_file)\n output_context = pre_cond_evaluator.evaluate()\n logger.info(\"Finished input_preprocessor step.\")\n return output_context\n\n\nif __name__ == '__main__':\n pass\n" }, { "alpha_fraction": 0.6911274194717407, "alphanum_fraction": 0.6964643001556396, "avg_line_length": 30.893617630004883, "blob_id": "71f103820c346d3f97a2adcfdee043ff934f17d4", "content_id": "e22a247c16e5543a7698983d8f1871b549820f76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1499, "license_type": "no_license", "max_line_length": 112, "num_lines": 47, "path": "/chimera/post_processor.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nContributors:\n- Namrata Malarout\n- Michael Cayanan\n- Sujen Shah\n\nThe Post Processor queries:\n1. Mozart for job infor\n2. GRQ for product metadata\nand creates a context.json (not the same as _context.json)\n\"\"\"\n\nfrom chimera.logger import logger\nfrom chimera.postprocess_evaluator import PostProcessor\n\n\ndef post_process(sf_context, job_result, chimera_config_file, pge_config_file, settings_file, test_mode=False):\n \"\"\"\n The main task of the post processor is\n to create a file [PGE_type]_context.json.\n The file's purpose is to pass metadata of\n the previous smap_sciflo process (PGE run) to\n the next one's input preprocessor.\n product produced and the job status of the PGE run.\n\n JOB Status Codes:\n -3 -> job deduped against a failed, queued/updated job\n -2 -> job deduped against a completed job\n -1 -> failed (handled at commoms.sciflo_util)\n 0 -> never ran (default value in document)\n 1 -> running (set in run_pge_docker.py)\n 2 -> completed successfully\n Parameters:\n @job_result - job_id of the PGE run\n @pge_type - type of SMAP PGE run\n @pge_config_file - path of the config file of specific PGE type\n \"\"\"\n logger.info(\"Starting post_preprocessor step.\")\n post_processor = PostProcessor(sf_context, chimera_config_file, pge_config_file, settings_file, job_result)\n output_context = post_processor.process()\n logger.info(\"Finished post_processor step.\")\n return output_context\n\n\nif __name__ == '__main__':\n pass\n" }, { "alpha_fraction": 0.5561015605926514, "alphanum_fraction": 0.5561015605926514, "avg_line_length": 37.761905670166016, "blob_id": "1aaf045dc46df2bef4f51e2e2ddc732465470710", "content_id": "9d89e0ccee2fe64306d014b7b545c88144ba0d7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4884, "license_type": "no_license", "max_line_length": 91, "num_lines": 126, "path": "/chimera/postprocess_evaluator.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport traceback\n\nfrom importlib import import_module\n\nfrom chimera.logger import logger\nfrom chimera.commons.conf_util import YamlConf, load_config\nfrom chimera.commons.constants import ChimeraConstants\nfrom chimera.postprocess_functions import PostProcessFunctions\n\n\nclass PostProcessor(object):\n def __init__(\n self,\n sf_context,\n chimera_config_filepath,\n pge_config_filepath,\n settings_file,\n job_result\n ):\n # load context file\n if isinstance(sf_context, dict):\n self._sf_context = sf_context\n elif isinstance(sf_context, str):\n self._sf_context = json.load(open(sf_context, \"r\"))\n logger.debug(\"Loaded context file: {}\".format(json.dumps(self._sf_context)))\n\n # load pge config file\n self._pge_config = load_config(pge_config_filepath)\n logger.debug(\"Loaded PGE config file: {}\".format(json.dumps(self._pge_config)))\n\n # load PP config file\n try:\n self._chimera_config = YamlConf(chimera_config_filepath).cfg\n self._module_path = self._chimera_config.get(\"postprocessor\", {}).get(\n \"module_path\", None\n )\n if not self._module_path:\n raise RuntimeError(\n \"'module_path' must be defined in the 'preprocessor' section of the \"\n \"Chimera Config file '{}'\".format(chimera_config_filepath)\n )\n self._class_name = self._chimera_config.get(\"postprocessor\", {}).get(\n \"class_name\", None\n )\n if not self._class_name:\n raise RuntimeError(\n \"'class_name' must be defined in the 'preprocessor' section of the \"\n \"Chimera Config file '{}'\".format(chimera_config_filepath)\n )\n except Exception as e:\n raise RuntimeError(\n \"Could not read preconditions definition file : {}\".format(e)\n )\n\n # load Settings file\n try:\n if settings_file:\n settings_file = os.path.abspath(os.path.normpath(settings_file))\n self._settings = YamlConf(settings_file).cfg\n except Exception as e:\n if settings_file:\n file_name = settings_file\n else:\n file_name = \"~/verdi/etc/settings.yaml\"\n raise RuntimeError(\n \"Could not read settings file '{}': {}\".format(file_name, e)\n )\n\n # load PGE job result\n if isinstance(job_result, dict):\n self._job_result = job_result\n elif isinstance(job_result, str):\n self._job_result = json.load(open(job_result, \"r\"))\n self._job_result[\"work_dir\"] = os.path.dirname(sf_context)\n logger.debug(\"Loaded job result: {}\".format(json.dumps(self._job_result)))\n\n def prepare_psuedo_context(self, psuedo_context):\n \"\"\"\n Write the gathered job and product metadata information to the psuedo context file.\n :return: dict\n \"\"\"\n logger.debug(\n \"Preparing psuedo_context file after {} run\".format(\n self._pge_config.get(\"pge_name\")\n )\n )\n # write out job context\n psu_context = open(\n \"{}_context.json\".format(self._pge_config.get(\"pge_name\")), \"w\"\n )\n psu_context.write(json.dumps(psuedo_context))\n psu_context.close()\n return \"{}_context.json\".format(self._pge_config.get(\"pge_name\"))\n\n def process(self):\n new_context = dict()\n try:\n module = import_module(self._module_path)\n cls = getattr(module, self._class_name)\n if not issubclass(cls, PostProcessFunctions):\n raise RuntimeError(\n \"Class must be a subclass of {}: {}\".format(\n PostProcessFunctions.__name__, cls.__name__\n )\n )\n # run mandatory post process funtions\n # new_context.update(self.required_post_process_steps())\n # run custom post processing steps and update the psuedo context content\n cls_object = cls(\n self._sf_context, self._pge_config, self._settings, self._job_result\n )\n new_context.update(\n cls_object.run(\n self._pge_config.get(ChimeraConstants.POSTPROCESS, list())\n )\n )\n # write to output context file\n new_context_file = self.prepare_psuedo_context(new_context)\n return new_context_file\n except Exception as e:\n logger.error(\n \"Post processor failure: {}. {}\".format(e, traceback.format_exc())\n )\n raise RuntimeError(\"Post processor failure: {}\".format(e))\n" }, { "alpha_fraction": 0.6917454600334167, "alphanum_fraction": 0.6917454600334167, "avg_line_length": 32.21428680419922, "blob_id": "b0617f91de3d0d008a0c41d202121389134e97ce", "content_id": "36f763a0a796dd60a947893acefc4724546adfa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2326, "license_type": "no_license", "max_line_length": 82, "num_lines": 70, "path": "/chimera/run_sciflo.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "\n\"\"\"\nRun the NRT production pipeline\n\"\"\"\n\nimport argparse\nimport os\nimport json\nimport sys\nfrom importlib import import_module\n\nfrom chimera.logger import logger\nfrom chimera.commons.accountability import Accountability\nfrom chimera.commons.sciflo_util import run_sciflo\n\n# Set up logging\nLOGGER = logger\n\n\nBASE_PATH = os.path.dirname(__file__)\n\n\n# grabs accountability class if implemented and set in the sciflo jobspecs\ndef get_accountability_class(context_file):\n work_dir = None\n context = None\n if isinstance(context_file, str):\n work_dir = os.path.dirname(context_file)\n with open(context_file, \"r\") as f:\n context = json.load(f)\n path = context.get(\"module_path\")\n if \"accountability_module_path\" in context:\n path = context.get(\"accountability_module_path\")\n accountability_class_name = context.get(\"accountability_class\", None)\n accountability_module = import_module(path, \"nisar-pcm\")\n if accountability_class_name is None:\n LOGGER.error(\n \"No accountability class specified\"\n )\n return Accountability(context, work_dir)\n cls = getattr(accountability_module, accountability_class_name)\n if not issubclass(cls, Accountability):\n LOGGER.error(\n \"accountability class does not extend Accountability\"\n )\n return Accountability(context, work_dir)\n cls_object = cls(context, work_dir)\n return cls_object\n\n\ndef main(sfl_file, context_file, output_folder):\n \"\"\"Main.\"\"\"\n\n sfl_file = os.path.abspath(sfl_file)\n context_file = os.path.abspath(context_file)\n output_file = os.path.abspath(output_folder)\n LOGGER.info(\"sfl_file: %s\" % sfl_file)\n LOGGER.info(\"context_file: %s\" % context_file)\n accountability = get_accountability_class(context_file)\n accountability.create_job_entry()\n result = run_sciflo(sfl_file, [\"sf_context=%s\" % context_file], output_folder)\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"sfl_file\", help=\"SciFlo workflow\")\n parser.add_argument(\"context_file\", help=\"HySDS context file\")\n parser.add_argument(\"output_folder\", help=\"Sciflo output file\")\n args = parser.parse_args()\n sys.exit(main(args.sfl_file, args.context_file, args.output_folder))\n" }, { "alpha_fraction": 0.695852518081665, "alphanum_fraction": 0.695852518081665, "avg_line_length": 26.125, "blob_id": "fa096f2e4320a68bb5650748429956cda5ba355d", "content_id": "31966b9e2d5a9765634b27541ba92791f6e916c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2387, "license_type": "no_license", "max_line_length": 83, "num_lines": 88, "path": "/chimera/commons/constants.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "\"\"\"\nAdd field names from PGE config files, names of functions,\nmatch patterns or key names that can be referenced throughout code base\n\nNote: To add new keys, please follow an alphabetical order\n\ne.g.\nLOCALIZE_KEY = \"localize\" # name of key found in input preprocessor output\nGET_PGE_NAME = \"pge_name\" # name of key found in PGE config file\nGET_ICE_SCLK = \"getIceSclk\" # name of function\n\"\"\"\n\n\nclass ChimeraConstants(object):\n def __init__(self):\n pass\n\n # PGE's name\n PGE_NAME = \"pge_name\"\n\n # To identify the preconditions to check for\n PRECONDITIONS = \"preconditions\"\n\n # To identify the post processing steps to run\n POSTPROCESS = \"postprocess\"\n\n # Key identifying the payload in the _context file\n RUNCONFIG = \"runconfig\"\n\n # To Specify which group elements to localize\n LOCALIZE_GROUPS = \"localize_groups\"\n\n # To specify which filepaths to localize in the worker. Used by Mozart\n LOCALIZE = \"localize\"\n CONFIGURATION = \"configuration\"\n PRODUCTION_DATETIME = \"ProductionDateTime\"\n\n # Key in runconfig for list of inputs\n RC_INPUT = \"InputFilePath\"\n\n # To identify file type level conditions\n CONDITIONS = \"conditions\"\n\n # Keys for identifying in the post_processor produced context.json\n PRODUCTS_ID = \"product_ids\"\n\n # primary input key in PGE config\n PRIMARY_INPUT = \"primary_input\"\n\n # identifier token to specify empty runconfig values to be filled\n EMPTY_FIELD_IDENTIFIER = \"empty_field_identifier\"\n\n # field to specify optionals runconfig fields\n OPTIONAL_FIELDS = \"optionalFields\"\n\n # Key used in post processor to identify the metadata of all products generated\n # This is a list of dictionaries\n PRODUCTS_METADATA = \"product_metadata\"\n\n # Key used to identify output products from the previous PGE run\n PRODUCT_NAMES = \"product_names\"\n\n # Key used to identify the path of the products created by the previous PGE\n PRODUCT_PATHS = \"product_paths\"\n\n RELEASE_VERSION = \"release_version\"\n\n SIMULATE_OUTPUTS = \"simulate_outputs\"\n\n PGE_SIM_MODE = \"PGE_SIMULATION_MODE\"\n\n OUTPUT_TYPES = \"output_types\"\n\n LAST_MOD_TIME = \"LastModifiedTime\"\n\n JOB_INFO = \"job_info\"\n\n JOB_PAYLOAD = \"job_payload\"\n\n PAYLOAD_TASK_ID = \"payload_task_id\"\n\n JOB_ID_FIELD = \"job_id\"\n\n JOB_TYPES = \"JOB_TYPES\"\n\n JOB_QUEUES = \"JOB_QUEUES\"\n\n WORK_DIR = \"work_dir\"\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7621832489967346, "avg_line_length": 29.117647171020508, "blob_id": "485252330a146551898c17126bf458577b87c34b", "content_id": "405d29e7e8f135ac0f0c6fdd125fedc0e5f2bb7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 513, "license_type": "no_license", "max_line_length": 242, "num_lines": 17, "path": "/README.md", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "# Chimera\nFull Documentation: https://hysds-core.atlassian.net/wiki/spaces/HYS/pages/545914885/Chimera\n\nThis is a workflow concept implemented using SciFLo. It is a basic skeleton for creating a workflows using SciFlo and generalized to be easily adapted by any project. SciFlo is the workflow infrastructure integrated with the HySDS framework. \n\nAny PGE can be run by running 3 steps:\n1. Input Preprocessor \n2. PGE Execution \n3. Post Processor \n\n\nContributors:\n- Michael Cayanan \n- Sujen Shah git \n- Namrata Malarout \n- Gerald Manipon\n- Frank Greguska " }, { "alpha_fraction": 0.5072117447853088, "alphanum_fraction": 0.5094596147537231, "avg_line_length": 38.39852523803711, "blob_id": "faeea2d66e00f64678dc0dd8f39503fb8a63816b", "content_id": "3269cb3e6c987cbcdcab3c351dc1941b638d8884", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21354, "license_type": "no_license", "max_line_length": 120, "num_lines": 542, "path": "/chimera/postprocess_functions.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import traceback\nimport time\nimport json\n\nfrom hysds.es_util import get_grq_es, get_mozart_es\n\nfrom chimera.commons.accountability import Accountability\nfrom chimera.commons.constants import ChimeraConstants as chimera_consts\n\nfrom chimera.logger import logger\n\n\nclass PostProcessFunctions(object):\n MOZART_ES_ENDPOINT = \"MOZART\"\n GRQ_ES_ENDPOINT = \"GRQ\"\n\n def __init__(self, context, pge_config, settings, job_result, mozart_es=None, grq_es=None):\n self._context = context\n self._pge_config = pge_config\n self._settings = settings\n self._job_result = job_result\n self.accountability = Accountability(self._context, self._job_result.get(chimera_consts.WORK_DIR))\n if mozart_es:\n self._mozart_es = mozart_es\n else:\n self._mozart_es = get_mozart_es()\n\n if grq_es:\n self._grq_es = grq_es\n else:\n self._grq_es = get_grq_es()\n\n def run(self, function_list):\n \"\"\"\n Runs the set of post processing functions passed into the given list.\n\n :param function_list: A list of post process methods that will be defined in the subclasses.\n\n :return: a dictionary containing information about the results of the post PGE processes.\n \"\"\"\n output_context = dict()\n logger.info(\n \"function_list: {}\".format(function_list)\n )\n for func in function_list:\n self._job_result.update(getattr(self, func)())\n \n return self._job_result\n\n def _check_job_status(self):\n \"\"\"\n Check if job is completed or deduped. If any other status then raise an error.\n :return:\n \"\"\"\n # getting the job paylooad and status\n job_id = str(self._job_result[\"payload_id\"])\n job_status = str(self._job_result[\"status\"])\n\n logger.info(\"Recieved JOB ID: {} with status: {}\".format(job_id, job_status))\n\n if job_status != \"job-completed\" and job_status != \"job-deduped\":\n logger.info(\n \"Job with job_id: {} was not completed. Status: {}\".format(\n job_id, job_status\n )\n )\n raise ValueError(\n \"Job with job_id: {} was not completed. Status: {}\".format(\n job_id, job_status\n )\n )\n return job_status\n\n def _get_job(self):\n \"\"\"\n This function gets the staged products and context of previous PGE job\n :return: tuple(products_staged, prev_context, message)\n \"\"\"\n job_id = str(self._job_result[\"payload_id\"])\n endpoint = self.MOZART_ES_ENDPOINT\n return_job_id = None\n\n \"\"\"\n Check if Jobs ES has updated job status and gets job information if completed/ deduped\n \"\"\"\n try:\n if self._check_job_status():\n try:\n response = self.query_es(endpoint=endpoint, doc_id=job_id)\n # check if job not found\n if len(response[\"hits\"][\"hits\"]) == 0:\n raise Exception(\n \"Couldn't find record with ID in MOZART: %s, at %s\"\n % (job_id, endpoint)\n )\n except Exception as ex:\n logger.error(\n \"Error querying MOZART for doc {}. {}. {}\".format(\n job_id, str(ex), traceback.format_exc()\n )\n )\n raise Exception(\n \"Error querying MOZART for doc {}. {}\".format(job_id, str(ex))\n )\n except Exception as ex:\n logger.error(\n \"Failed to find job in MOZART. {}. {}. {}\".format(\n job_id, str(ex), traceback.format_exc()\n )\n )\n raise Exception(\n \"Failed to find job in MOZART. {}. {}. {}\".format(\n job_id, str(ex), traceback.format_exc()\n )\n )\n\n \"\"\"\n Parse job's full information to get products staged, job context\n If job deduped then find original job's information\n \"\"\"\n result = response[\"hits\"][\"hits\"][0]\n products_staged = None\n prev_context = None\n message = None # using this to store information regarding deduped jobs,\n status = str(result[\"_source\"][\"status\"])\n\n # if job was deduped then find the original job status and what products (if any) were created\n if status == \"job-deduped\":\n logger.info(\"Job was deduped\")\n # query ES for the original job's status\n orig_job_id = result[\"_source\"][\"dedup_job\"]\n return_job_id = orig_job_id\n try:\n orig_job_info = self.query_es(endpoint=endpoint, doc_id=orig_job_id)\n if len(response[\"hits\"][\"hits\"]) == 0:\n raise Exception(\n \"Couldn't find record with ID: {}, at {}\".format(\n job_id, endpoint\n )\n )\n except Exception as ex:\n logger.error(\n \"Error querying ES for doc {}. {}. {}\".format(\n job_id, str(ex), traceback.format_exc()\n )\n )\n raise Exception(\n \"Error querying ES for doc {}. {}\".format(job_id, str(ex))\n )\n\n \"\"\"\n check if original job failed -> this would happen when at the moment\n of deduplication, the original job was in 'running state', but soon\n afterwards failed. So, by the time the status is checked in this\n function, it may be shown as failed.\n \"\"\"\n\n orig_job_info = orig_job_info[\"hits\"][\"hits\"][0]\n orig_job_status = str(orig_job_info[\"_source\"][\"status\"])\n if orig_job_status == \"job-failed\":\n message = (\n \"Job was deduped against a failed job with id: {},\"\n \" please retry sciflo.\".format(orig_job_id)\n )\n logger.info(\n \"Job was deduped against a job which has now failed \"\n \"with id: {}, Please retry sciflo.\".format(orig_job_id)\n )\n elif orig_job_status == \"job-started\" or orig_job_status == \"job-queued\":\n logger.info(\n \"Job was deduped against a queued/started job with \"\n \"id: {}. Please look at already running sciflo with \"\n \"same params.\".format(orig_job_id)\n )\n message = (\n \"Job was deduped against a queued/started job with \"\n \"id: {}. Please look at already running sciflo with \"\n \"same params.\".format(orig_job_id)\n )\n\n elif orig_job_status == \"job-completed\":\n products_staged = orig_job_info[\"_source\"][\"job\"][\"job_info\"][\n \"metrics\"\n ][\"products_staged\"]\n prev_context = orig_job_info[\"_source\"][\"context\"]\n logger.info(\"Queried ES to get Job context and staged files info\")\n message = \"success\"\n elif status == \"job-completed\":\n logger.info(\"Job completed\")\n products_staged = result[\"_source\"][\"job\"][\"job_info\"][\"metrics\"][\n \"products_staged\"\n ]\n prev_context = result[\"_source\"][\"context\"]\n logger.info(\"Queried ES to get Job context and staged files info\")\n message = \"success\"\n return_job_id = job_id\n else:\n logger.info(\n \"Job was not completed. Status: {}\".format(result[\"_source\"][\"status\"])\n )\n message = \"Job was not completed. Status: {}\".format(\n result[\"_source\"][\"status\"]\n )\n\n return products_staged, prev_context, message, return_job_id\n\n def _create_products_list(self, products):\n \"\"\"\n This function creates a list of the product URLs and metadata required\n for the next PGE's input preprocessor.\n :param products: list of products staged after PGE run\n :return: tuple( product's id, list of products' URLs, list of products'\n metadata)\n \"\"\"\n product_id = None\n products_url_list = []\n products_metadata_list = []\n\n for product in products:\n input_product_id = product[\"id\"]\n # get information required for next PGE's input preprocessor\n product_id = input_product_id\n\n try:\n product_url, metadata = self.get_product_info(\n product_id=input_product_id\n )\n product_info = dict()\n product_info[\"id\"] = input_product_id\n product_info[\"url\"] = product_url\n product_info[\"metadata\"] = metadata\n products_metadata_list.append(product_info)\n products_url_list.append(product_url)\n except Exception as ex:\n raise Exception(\n \"Failed to get product information, {}. {}\".format(\n str(ex), traceback.format_exc()\n )\n )\n\n return product_id, products_url_list, products_metadata_list\n\n def query_es(\n self,\n endpoint,\n doc_id=None,\n query=None,\n request_timeout=30,\n retried=False,\n size=1,\n ):\n \"\"\"\n This function queries ES. Not using the query util because the ES\n connection is set\n for the GRQ ES.\n :param endpoint: the value specifies which ES endpoint to send query\n can be MOZART or GRQ\n :param doc_id: id of product or job\n :param query: query to run\n :param request_timeout: how long to wait for ES request\n :param retried: flag to specify if the query has already been retried\n :param size: number of results to be returned\n :return: result of query\n \"\"\"\n result = None\n if query is None and doc_id is None:\n raise ValueError(\"Both doc_id and query cannot be None\")\n\n es, es_url, es_index = None, None, None\n if endpoint == self.GRQ_ES_ENDPOINT:\n es_index = \"grq\"\n es = self._grq_es\n if endpoint == self.MOZART_ES_ENDPOINT:\n es_index = \"job_status-current\"\n es = self._mozart_es\n\n if doc_id is not None:\n query = {\"query\": {\"bool\": {\"must\": [{\"term\": {\"_id\": doc_id}}]}}}\n\n try:\n result = es.search(\n index=es_index, body=query, size=size, request_timeout=request_timeout\n )\n # retry in case of time out\n if \"timed_out\" in result and result.get(\"timed_out\"):\n logger.warning(\n \"ES responded with a timed out result, \"\n \"retrying....: {}\".format(json.dumps(result))\n )\n raise RuntimeWarning(\n \"ES responded with a timed out result, retrying....\"\n )\n except Exception as e:\n logger.warning(\n \"Caught exception from elasticsearch \"\n \"retrying: {}\".format(traceback.format_exc())\n )\n # Retry querying, this is incase ES takes too long to respond\n if not retried:\n self.query_es(\n endpoint=endpoint,\n doc_id=doc_id,\n size=size,\n request_timeout=int(request_timeout + 30),\n retried=True,\n )\n else:\n raise Exception(str(e))\n\n return result\n\n def product_in_grq(self, doc_id):\n \"\"\"\n Checks if the product has been indexed in ES\n :param doc_id:\n :return: True if product found else throw suitable exception\n \"\"\"\n query = {\n \"_source\": [\"id\"],\n \"query\": {\"bool\": {\"must\": [{\"term\": {\"_id\": doc_id}}]}},\n }\n\n try:\n if self.wait_for_doc(endpoint=self.GRQ_ES_ENDPOINT, query=query, timeout=120):\n return True\n except Exception as ex:\n logger.error(\n \"Error querying GRQ for product {}. {}. {}\".format(\n doc_id, str(ex), traceback.format_exc()\n )\n )\n raise Exception(\n \"Error querying GRQ for product {}. {}\".format(doc_id, str(ex))\n )\n\n def wait_condition(self, endpoint, result):\n results_exist = len(result.get(\"hits\").get(\"hits\")) == 0\n if endpoint == self.MOZART_ES_ENDPOINT:\n return results_exist or str(result.get(\"hits\").get(\"hits\")[0].get(\n \"_source\").get(\"status\")) == \"job-started\"\n if endpoint == self.GRQ_ES_ENDPOINT:\n return results_exist\n\n def wait_for_doc(self, endpoint, query, timeout):\n \"\"\"\n This function executes the search query for specified wait time until\n document is found\n :param endpoint: GRQ or MOZART\n :param query: search query\n :param timeout: time to wait in seconds\n :return: True if document found else raise suitable Exception\n \"\"\"\n try:\n result = self.query_es(\n endpoint=endpoint, query=query, request_timeout=30, size=1\n )\n slept_seconds = 0\n sleep_seconds = 2\n\n while self.wait_condition(endpoint=endpoint, result=result):\n if result.get(\"timed_out\", True):\n slept_seconds += 30\n\n if slept_seconds + sleep_seconds < timeout:\n logger.debug(\"Slept for {} seconds\".format(slept_seconds))\n logger.debug(\"Sleeping for {} seconds\".format(sleep_seconds))\n else:\n sleep_seconds = timeout - slept_seconds\n logger.debug(\"Slept for {} seconds\".format(slept_seconds))\n logger.debug(\n \"Sleeping for {} seconds to conform to timeout \"\n \"of {} seconds\".format(sleep_seconds, timeout)\n )\n\n if slept_seconds >= timeout:\n if len(result.get(\"hits\").get(\"hits\")) == 0:\n raise Exception(\n \"{} ES taking too long to index document\".format(endpoint)\n )\n if endpoint == self.MOZART_ES_ENDPOINT:\n if (\n str(result[\"hits\"][\"hits\"][0][\"_source\"][\"status\"])\n == \"job-started\"\n ):\n raise Exception(\n \"{} ES taking too long to update status of \"\n \"job\".format(endpoint)\n )\n\n time.sleep(sleep_seconds)\n result = self.query_es(\n endpoint=endpoint, query=query, request_timeout=30, size=1\n )\n slept_seconds += sleep_seconds\n sleep_seconds *= 2\n return True\n except Exception as e:\n raise Exception(\"ElasticSearch Operation failed due to : {}\".format(str(e)))\n\n def get_product_info(self, product_id):\n \"\"\"\n This function gets the product's URL and associated metadata from Elastic\n Search\n :param product_id: id of product\n :return: tuple(product_url, metadata)\n \"\"\"\n response = None\n try:\n if self.product_in_grq(doc_id=product_id):\n try:\n response = self.query_es(\n endpoint=self.GRQ_ES_ENDPOINT, doc_id=product_id\n )\n if len(response.get(\"hits\").get(\"hits\")) == 0:\n raise Exception(\n \"ES taking too long to index product with id \"\n \"%s.\" % product_id\n )\n except Exception as ex:\n raise Exception(\n \"ElasticSearch Operation failed due to : {}\".format(str(ex))\n )\n except Exception as ex:\n raise Exception(\n \"Failed to find product in GRQ. {}. {}\".format(\n str(ex), traceback.format_exc()\n )\n )\n\n try:\n result = response.get(\"hits\").get(\"hits\")[0]\n product_urls = result.get(\"_source\").get(\"urls\")\n product_url = None\n for url in product_urls:\n if url.startswith(\"s3://\"):\n product_url = url\n metadata = result.get(\"_source\").get(\"metadata\")\n except Exception as ex:\n raise Exception(\n \"Failed to get product info. {}. {}\".format(\n str(ex), traceback.format_exc()\n )\n )\n\n return product_url, metadata\n\n def core_post_process_steps(self):\n \"\"\"\n The mandatory post processing steps of Chimera are:\n 1. check submitted job's status\n 2. Get complete job run information i.e job's context, products produced, job id\n (in case job submitted by sciflo was deduped, the original job ID is tracked down)\n 3.\n\n :return:\n \"\"\"\n pseudo_context = dict()\n\n \"\"\"\n check submitted job's status\n \"\"\"\n job_status = self._check_job_status()\n\n \"\"\"\n get the products staged, context of job and job's ID (incase job submitted by sciflo was deduped)\n \"\"\"\n try:\n products, prev_context, message, job_id = self._get_job()\n except Exception as ex:\n logger.error(\n \"Couldn't get job info for {}. {}. {}\".format(\n job_id, str(ex), traceback.format_exc()\n )\n )\n job_status_code = -1\n logger.error(\"Job was not found.\")\n raise RuntimeError(\n \"Couldn't get job info for {}. {}. {}\".format(\n job_id, str(ex), traceback.format_exc()\n )\n )\n\n \"\"\"\n Handle job status codes for all outcomes of a deduped job\n # Case 1: if the original job is queued or has started, fail the current sciflo\n so that the original workflow can take care of the PGE run\n update the job status with -3\n \n # Case 2: if the original job has completed, then get products and prev _context from original job\n update job_status_code to 2\n \n # Case 3: if the original job was deduped (NOTE: Unlikely unrealistic case)\n set job_status_code to -2\n \"\"\"\n # case 1\n if products is None and prev_context is None:\n job_status_code = -3\n raise RuntimeError(message)\n else:\n # case 2\n if job_status == \"job-completed\":\n job_status_code = 2\n # case 3\n elif job_status == \"job-deduped\":\n job_status_code = -2\n\n \"\"\"\n Query to get information of all products staged.\n NOTE: Sciflo gets notification of the celery task completion and moves to the post processing step when\n it gets the PGE job submission results. The completion of a celery task is different than completion of\n a HySDS job. A HySDS job includes the celery task execution, worker post processing and dataset ingestion.\n We get to the step of querying a product's information before it has been indexed into GRQ. To handle this race\n condition we have an exponential backoff logic in the query to wait for the product to appear.\n Max wait time is 2 mins.\n \"\"\"\n try:\n (\n product_id,\n products_url_list,\n products_metadata_list,\n ) = self._create_products_list(products=products)\n except Exception as ex:\n job_status_code = -1\n logger.error(\"Setting Job failure status code as product was not found.\")\n raise RuntimeError(\n \"Failed PGE run as products list could not be made.\"\n \" {}. {}\".format(str(ex), traceback.format_exc())\n )\n\n \"\"\"\n Now that we have all job and products information we can put the psuedo context contents together.\n \"\"\"\n logger.info(\"Job Status Code: {}\".format(job_status_code))\n product_url_key = ChimeraConstants.PRODUCT_PATHS\n metadata_key = ChimeraConstants.PRODUCTS_METADATA\n\n pseudo_context[product_url_key] = products_url_list\n pseudo_context[metadata_key] = products_metadata_list\n pseudo_context[\"job_id\"] = job_id\n pseudo_context[\"job_context\"] = prev_context\n\n return pseudo_context\n" }, { "alpha_fraction": 0.5721784830093384, "alphanum_fraction": 0.5726783871650696, "avg_line_length": 45.51744079589844, "blob_id": "a7551c5482d676c3576b25b92e53269ad5c95170", "content_id": "f8c9219f59a371a4efd04ede858a00efc1754f72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8001, "license_type": "no_license", "max_line_length": 115, "num_lines": 172, "path": "/chimera/precondition_evaluator.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport copy\nimport traceback\n\nfrom importlib import import_module\n\nfrom chimera.logger import logger\nfrom chimera.commons.conf_util import YamlConf, load_config\nfrom chimera.commons.constants import ChimeraConstants\nfrom chimera.precondition_functions import PreConditionFunctions\n\nfrom urllib.parse import urlparse\n\n# Used to identify fields to be filled within the runconfig context.json of PGE\nEMPTY_FIELD_IDENTIFIER = \"__CHIMERA_VAL__\"\n\n\nclass PreConditionEvaluator(object):\n\n def __init__(self, sf_context, chimera_config_filepath, pge_config_filepath, settings_file):\n # load context file\n if isinstance(sf_context, dict):\n self._sf_context = sf_context\n elif isinstance(sf_context, str):\n self._sf_context = json.load(open(sf_context, 'r'))\n logger.debug(\"Loaded context file: {}\".format(json.dumps(self._sf_context)))\n\n # load pge config file\n self._pge_config = load_config(pge_config_filepath)\n logger.debug(\"Loaded PGE config file: {}\".format(json.dumps(self._pge_config)))\n\n # load IPP config file\n try:\n self._chimera_config = YamlConf(chimera_config_filepath).cfg\n self._module_path = self._chimera_config.get(\"preprocessor\", {}).get(\"module_path\", None)\n if not self._module_path:\n raise RuntimeError(\"'module_path' must be defined in the 'preprocessor' section of the \"\n \"Chimera Config file '{}'\".format(chimera_config_filepath))\n self._class_name = self._chimera_config.get(\"preprocessor\", {}).get(\"class_name\", None)\n if not self._class_name:\n raise RuntimeError(\"'class_name' must be defined in the 'preprocessor' section of the \"\n \"Chimera Config file '{}'\".format(chimera_config_filepath))\n except Exception as e:\n raise RuntimeError(\"Could not read preconditions definition file : {}\".format(e))\n\n # load Settings file\n try:\n if settings_file:\n settings_file = os.path.abspath(os.path.normpath(settings_file))\n self._settings = YamlConf(settings_file).cfg\n except Exception as e:\n if settings_file:\n file_name = settings_file\n else:\n file_name = '~/verdi/etc/settings.yaml'\n raise RuntimeError(\"Could not read settings file '{}': {}\".format(file_name, e))\n\n def repl_val_in_dict(self, d, val, job_params, root=None, optional_fields=None):\n \"\"\"\n Recursive function to replace occurences of val in a dict with values from the job_params.\n \"\"\"\n\n if root is None: root = []\n if optional_fields is None: optional_fields = []\n matched_keys = []\n for k, v in d.items():\n rt = copy.copy(root)\n rt.append(k)\n if isinstance(v, dict):\n matched_keys.extend(self.repl_val_in_dict(v, val, job_params, rt, optional_fields))\n if v == val:\n jp_key = '.'.join(rt)\n # use job_params with explicit dot notation\n if jp_key in job_params:\n d[k] = job_params[jp_key]\n matched_keys.append(jp_key)\n # maintain backwards-compatibility of using job_param values without dot notation\n elif k in job_params:\n d[k] = job_params[k]\n matched_keys.append(k)\n else:\n # check if optionalField; if so, set value to empty string\n if jp_key in optional_fields:\n logger.info(\"Explicit dot notation key {} is an optional field.\".format(jp_key))\n logger.info(\"Setting {} value to empty string.\".format(k))\n d[k] = \"\"\n elif k in optional_fields:\n logger.info(\"Key {} is an optional field.\".format(k))\n logger.info(\"Setting {} value to empty string.\".format(k))\n d[k] = \"\"\n else:\n logger.error(\"job_params: {}\".format(json.dumps(job_params, indent=2, sort_keys=True)))\n raise(ValueError(\"{} or {} has not been evaluated by the preprocessor.\".format(jp_key, k)))\n return matched_keys\n\n def localize_paths(self, output_context):\n \"\"\"\n To set file to localize in the docker\n :param output_context:\n \"\"\"\n logger.debug(\"Preparing to localize file paths\")\n\n # Deprecated function since not all values in localize_groups are on s3\n # for example SPS config files\n def is_url(val):\n parse_result = urlparse(val)\n schemes = [\"s3\", \"s3s\", \"http\", \"https\",\n \"ftp\", \"sftp\", \"azure\", \"azures\", \"rsync\"]\n return parse_result.scheme in schemes\n\n localize_paths_list = []\n for group in self._pge_config.get(ChimeraConstants.LOCALIZE_GROUPS, []):\n for elem in output_context.get(group, []):\n value = output_context.get(group).get(elem)\n\n # If the value is a list, example some InputFilGroups could be\n # scalars or vectors\n if isinstance(value, list):\n for v in value:\n if is_url(v):\n localize_paths_list.append(v)\n\n elif isinstance(value, str):\n if is_url(value):\n localize_paths_list.append(value)\n\n else:\n continue\n\n return localize_paths_list\n\n def prepare_runconfig(self, job_params):\n \"\"\"\n To prepare the final completed runconfig context.json which will be fed in\n to the pge\n :return: dict\n \"\"\"\n logger.debug(\"Preparing runconfig for {}\".format(self._pge_config.get('pge_name')))\n empty_field_identifier = self._pge_config.get(ChimeraConstants.EMPTY_FIELD_IDENTIFIER,\n EMPTY_FIELD_IDENTIFIER)\n logger.debug(\"Empty field identifier: {}\".format(empty_field_identifier))\n output_context = dict()\n optional_fields = self._pge_config.get(ChimeraConstants.OPTIONAL_FIELDS, [])\n if self._pge_config.get(ChimeraConstants.RUNCONFIG):\n output_context = copy.deepcopy(self._pge_config.get(ChimeraConstants.RUNCONFIG))\n matched_keys = self.repl_val_in_dict(output_context, empty_field_identifier,\n job_params, optional_fields=optional_fields)\n else:\n raise KeyError(\"Key runconfig not found in PGE config file\")\n\n # Add localized urls\n output_context[ChimeraConstants.LOCALIZE] = self.localize_paths(output_context)\n output_context[ChimeraConstants.SIMULATE_OUTPUTS] = self._settings[ChimeraConstants.PGE_SIM_MODE]\n\n return output_context\n\n def evaluate(self):\n job_params = dict()\n try:\n module = import_module(self._module_path)\n cls = getattr(module, self._class_name)\n if not issubclass(cls, PreConditionFunctions):\n raise RuntimeError(\"Class must be a subclass of {}: {}\".format(PreConditionFunctions.__name__,\n cls.__name__))\n cls_object = cls(self._sf_context, self._pge_config, self._settings, job_params)\n job_params.update(cls_object.run(self._pge_config.get(ChimeraConstants.PRECONDITIONS, list())))\n output_context = self.prepare_runconfig(job_params)\n return output_context\n except Exception as e:\n logger.error(\"Input precondition failure: {}. {}\".format(e, traceback.format_exc()))\n raise RuntimeError(\"Input precondition failure: {}\".format(e))\n" }, { "alpha_fraction": 0.644574761390686, "alphanum_fraction": 0.6744868159294128, "avg_line_length": 39.595237731933594, "blob_id": "981bd0470708d5ddd9d837a82307fbafd385cab3", "content_id": "90612426fde47c941da0557fc07a8c7f8df7b8e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1705, "license_type": "no_license", "max_line_length": 98, "num_lines": 42, "path": "/tests/test_post_processor.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import json\nimport os\nfrom smap_sciflo import post_processor\n\nif __name__ == '__main__':\n \"\"\"\n This is for testing of Production PGE Post Processing\n Comment out from hysds.celery import app in post_processor and query_util\n Setup 2 SSH tunnels:\n ssh -i [PEM file] -L 9200:localhost:9200 [username]@[MOZART_IP]\n ssh -i [PEM file] -L 9300:localhost:9200 [username]@[GRQ_IP]\n\n In post_processor, overwrite ES URLs with following:\n JOBS_ES_URL = \"http://127.0.0.1:9200\"\n GRQ_ES_URL = \"http://127.0.0.1:9300\"\n\n In commons/query_util.py, overwrite GRQ URL with:\n ES_URL = \"http://127.0.0.1:9300\"\n\n Update the following sample files:\n test-files/sf_context.json should be the sciflo context of an actual workflow run\n test-files/sample_job_submission_result.json with the result of a job submission corresponding\n If not testing for an L0B run please update:\n pge_type: Type of PGE\n pge_config_file: path to PGE's config file\n to the sciflo context above\n\n run this script\n \"\"\"\n\n # Testing L0B post processing\n os.path.dirname(os.path.realpath(__file__))\n job_result = json.loads(open(os.path.dirname(os.path.realpath(\n __file__))+\"/test-files/sample_job_submission_result.json\").read())\n sf_context = os.path.dirname(os.path.realpath(\n __file__))+\"/test-files/sf_context.json\"\n pge_type = \"L0A_Radiometer\"\n level_up_dir = os.path.dirname(os.path.realpath(__file__))\n pge_config_file = os.path.abspath(os.path.join(os.path.realpath(\n __file__), \"../..\", \"configs/examples/PGE_L0A_RADIOMETER.json\"))\n post_processor.create_context(\n sf_context, job_result, pge_type, pge_config_file, test_mode=True)\n" }, { "alpha_fraction": 0.8059701323509216, "alphanum_fraction": 0.8059701323509216, "avg_line_length": 33, "blob_id": "64303372cf781fd05a7743fc3f55212742b217b0", "content_id": "99785d39e4097cd5bc90b49b6742001f442ded13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 38, "num_lines": 2, "path": "/__init__.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom .chimera import commons" }, { "alpha_fraction": 0.8191125988960266, "alphanum_fraction": 0.8191125988960266, "avg_line_length": 145.5, "blob_id": "20f9de56b8e87bb5845c79211e8d86a9a79e3125", "content_id": "a7764ac8ed9511df7b7bf8f2cff440063ab76c8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 293, "license_type": "no_license", "max_line_length": 282, "num_lines": 2, "path": "/chimera/README.md", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "# chimera\nBasic skeleton for creating a workflows using SciFlo. SciFlo is the workflow infrastructure integrated with the HySDS framework. This is a generic layout that can be used by any project to write up workflows consisting of basic steps: Pre processing, PGE execution, Post Processing.\n" }, { "alpha_fraction": 0.6290223002433777, "alphanum_fraction": 0.646039605140686, "avg_line_length": 35.314605712890625, "blob_id": "60ce77ecbec7665eaf2be077929d0d32a5cb41c7", "content_id": "a0952c4e638b6d743a3cc212e17d70842284e7e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3232, "license_type": "no_license", "max_line_length": 126, "num_lines": 89, "path": "/chimera/run_pge_docker.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nContributors:\n- Namrata Malarout\n- Michael Cayanan\n- Sujen Shah\n\nThis is the second step of Chimera\nTakes the configuration generated by IPP and creates the HySDS job parameters for job submission\n\"\"\"\n\nfrom importlib import import_module\n\nfrom chimera.logger import logger\nfrom chimera.commons.conf_util import YamlConf\nfrom chimera.pge_job_submitter import PgeJobSubmitter\n\n\"\"\"\nThis is a sample mozart job payload\n{\n \"job_name\": \"%s-%s\" % (job_type, l0b_lr_raw_id),\n \"job_type\": \"job:%s\" % job_type,\n \"job_queue\": job_queue,\n \"container_mappings\": container_mappings,\n \"soft_time_limit\": 86400,\n \"time_limit\": 86700,\n \"payload\": {\n # smap_sciflo tracking info\n \"_sciflo_wuid\": wuid,\n \"_sciflo_job_num\": job_num,\n\n # job spec for dependencies\n \"job_specification\": {\n \"digest\": \"sha256:3debc246c9d86f45a317ae6af4fa82ef9faf1206faf8201ed94db511468d214b\", \n \"id\": \"container-aria-hysds_aria-pdl-clone:master\", \n \"url\": \"s3://s3-us-west-2.amazonaws.com/grfn-v2-ops-code-bucket/container-aria-hysds_aria-pdl-clone:master.tar.gz\", \n \"version\": \"master\"\n \"dependency_images\": dependency_images,\n },\n\n # job params\n \"context_blob\": job_payload, # one param - one JSON blob\n\n # v2 cmd\n \"_command\": \"/home/ops/verdi/ops/SPDM-with-HySDS/run_pge.sh\",\n\n # disk usage\n \"_disk_usage\": disk_usage,\n\n # localize urls\n \"localize_urls\": localize_urls,\n }\n}\n\"\"\"\n\n\ndef submit_pge_job(sf_context, runconfig, pge_config_file, settings_file, chimera_config_file,\n wuid=None, job_num=None):\n \"\"\"\n 'JOBS_ES_URL'\n This function returns the job payload that needs to be mapped by sciflo\n and run on a remote worker.\n :param sf_context: context of workflow job\n :param runconfig: Run config created by input preprocessor\n :param pge_config_file: PGE's config file name\n :param settings_file:\n :param chimera_config_file:\n :param wuid: wuid of sciflo\n :param job_num: job_num in sciflo\n :return: job payload of PGE job\n \"\"\"\n logger.info(\"Starting run_pge_docker step.\")\n chimera_config = YamlConf(chimera_config_file).cfg\n module_path = chimera_config.get(\"job_submitter\", {}).get(\"module_path\", None)\n if not module_path:\n raise RuntimeError(\"'module_path' must be defined in the 'job_submitter' section of the \"\n \"Chimera Config file '{}'\".format(chimera_config_file))\n class_name = chimera_config.get(\"job_submitter\", {}).get(\"class_name\", None)\n if not class_name:\n raise RuntimeError(\"'class_name' must be defined in the 'job_submitter' section of the Chimera \"\n \"Config file '{}'\".format(chimera_config_file))\n module = import_module(module_path)\n cls = getattr(module, class_name)\n if not issubclass(cls, PgeJobSubmitter):\n raise RuntimeError(\"Class must be a subclass of {}: {}\".format(PgeJobSubmitter.__name__, cls.__name__))\n cls_object = cls(sf_context, runconfig, pge_config_file, settings_file, wuid, job_num)\n job_json = cls_object.submit_job()\n logger.info(\"Finished run_pge_docker step.\")\n return job_json\n" }, { "alpha_fraction": 0.5630075335502625, "alphanum_fraction": 0.5651127696037292, "avg_line_length": 22.928056716918945, "blob_id": "7f4d23dfe0b7094efcae0edc0cf873c4fef7bed0", "content_id": "8e55b9a280c9b0e8a2e8fc59e86084bdfbb9b3af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3325, "license_type": "no_license", "max_line_length": 96, "num_lines": 139, "path": "/chimera/commons/conf_util.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom builtins import object\nimport re\nimport yaml\nimport os\nimport json\n\nfrom collections import OrderedDict\n\n# have yaml parse regular expressions\nyaml.SafeLoader.add_constructor(\n u\"tag:yaml.org,2002:python/regexp\", lambda l, n: re.compile(l.construct_scalar(n))\n)\n\n\nclass YamlConfEncoder(json.JSONEncoder):\n \"\"\"Custom encoder for YamlConf.\"\"\"\n\n def default(self, obj):\n if isinstance(obj, type(re.compile(r\"\"))):\n return obj.pattern\n return super(YamlConfEncoder, self).default(obj)\n\n\nclass YamlConfError(Exception):\n \"\"\"Exception class for YamlConf class.\"\"\"\n\n pass\n\n\nclass YamlConf(object):\n \"\"\"YAML configuration class.\"\"\"\n\n def __init__(self, file):\n \"\"\"Construct YamlConf instance.\"\"\"\n\n self._file = file\n with open(self._file) as f:\n self._cfg = yaml.safe_load(f)\n\n @property\n def file(self):\n return self._file\n\n @property\n def cfg(self):\n return self._cfg\n\n def get(self, key):\n try:\n return self._cfg[key]\n except KeyError:\n raise YamlConfError\n\n def __repr__(self):\n return json.dumps(self._cfg, cls=YamlConfEncoder, indent=2)\n\n\nclass JobContext(object):\n \"\"\"Job context class.\"\"\"\n\n def __init__(self, file):\n \"\"\"Construct JobContext instance.\"\"\"\n self._file = file\n with open(self._file) as f:\n self._ctx = json.load(f)\n\n @property\n def file(self):\n return self._file\n\n @property\n def ctx(self):\n return self._ctx\n\n def get(self, key):\n try:\n return self._ctx[key]\n except KeyError:\n raise (\n Exception(\n \"Context '{}' doesn't exist in {}.\".format(key, self._file)\n )\n )\n\n def set(self, key, val):\n self._ctx[key] = val\n\n def save(self):\n with open(self._file, \"w\") as f:\n json.dump(self._ctx, f, indent=2, sort_keys=True)\n\n\n\nclass DockerParams(object):\n \"\"\"Job context class.\"\"\"\n\n def __init__(self, file):\n \"\"\"Construct DockerParams instance.\"\"\"\n self._file = file\n with open(self._file) as f:\n self._params = json.load(f)\n\n @property\n def file(self):\n return self._file\n\n @property\n def params(self):\n return self._params\n\n def get(self, key):\n try:\n return self._params[key]\n except KeyError:\n raise (\n Exception(\n \"Docker params '{}' doesn't exist in {}.\".format(key, self._file)\n )\n )\n\n\ndef load_config(config_filepath):\n # load config file\n config_ext = os.path.splitext(config_filepath)[1]\n if config_ext == \".json\":\n try:\n config = json.load(open(config_filepath, 'r'), object_pairs_hook=OrderedDict)\n except Exception as e:\n raise RuntimeError(\"Could not load Config : {}\".format(e))\n elif config_ext == \".yaml\":\n try:\n config = YamlConf(config_filepath).cfg\n except Exception as e:\n raise RuntimeError(\"Could not load Config : {}\".format(e))\n else:\n raise RuntimeError(\"Config file must end in .yaml or .json: {}\".format(config_filepath))\n\n return config" }, { "alpha_fraction": 0.5612627267837524, "alphanum_fraction": 0.5644729733467102, "avg_line_length": 31.410404205322266, "blob_id": "17174cc98fea47221076a9191ebcf332f6b5d758", "content_id": "9f79b12ca43423dc35981f8cae9d4f2cd08c4015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5607, "license_type": "no_license", "max_line_length": 94, "num_lines": 173, "path": "/chimera/commons/sciflo_util.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport os\nimport json\nimport re\nimport shutil\n\nWORK_RE = re.compile(r\"\\d{5}-.+\")\n\n# sciflo PGE process names and mapping to their config files\n# This is the list of PGEs that need to report status to an explict index\nMAX_PLACEHOLDER_FILE_SIZE = 1000\nPLACEHOLDER_ERROR_FILE = \"_alt_error_hold.txt\"\nPLACEHOLDER_TB_FILE = \"_alt_traceback_hold.txt\"\nPLACEHOLDER_DOCKER_STATS_FILE = \"_docker_stats_hold.json\"\n\nPLACEHOLDER_FILES = [\n PLACEHOLDER_ERROR_FILE,\n PLACEHOLDER_TB_FILE,\n PLACEHOLDER_DOCKER_STATS_FILE,\n]\n\n\ndef __create_placeholder_alt_files():\n \"\"\"\n Due to possible disk space issues, this function will create temporary\n files in case we need to capture the _alt_error, _alt_traceback, and _docker_stats\n files\n\n :param work_dir:\n :return:\n \"\"\"\n with open(PLACEHOLDER_ERROR_FILE, \"wb\") as f:\n f.seek(MAX_PLACEHOLDER_FILE_SIZE)\n f.write(b\"\\0\")\n\n with open(PLACEHOLDER_TB_FILE, \"wb\") as f:\n f.seek(MAX_PLACEHOLDER_FILE_SIZE)\n f.write(b\"\\0\")\n\n with open(PLACEHOLDER_DOCKER_STATS_FILE, \"w\") as f:\n json.dump(dict(), f)\n\n\ndef __cleanup_placeholder_alt_files():\n for temp_file in PLACEHOLDER_FILES:\n if os.path.exists(temp_file):\n print(f\"Remove existing placeholder file: {temp_file}\")\n\n\ndef __write_error_files(error, traceback):\n alt_error_file = \"_alt_error.txt\"\n alt_tb_file = \"_alt_traceback.txt\"\n docker_stats_file = \"_docker_stats.json\"\n\n try:\n with open(alt_error_file, \"w\") as f:\n f.write(\"%s\\n\" % error)\n with open(alt_tb_file, \"w\") as f:\n f.write(\"%s\\n\" % traceback)\n except OSError as oe:\n print(\n f\"OSError encountered: {str(oe)}. Will write errors to placeholder files.\"\n )\n print(f\"Renaming {PLACEHOLDER_ERROR_FILE} to {alt_error_file}.\")\n os.rename(PLACEHOLDER_ERROR_FILE, alt_error_file)\n print(f\"Renaming {PLACEHOLDER_TB_FILE} to {alt_tb_file}.\")\n os.rename(PLACEHOLDER_TB_FILE, alt_tb_file)\n\n with open(alt_error_file, \"w\") as f:\n f.write(\"%s\\n\" % error[:MAX_PLACEHOLDER_FILE_SIZE])\n\n with open(alt_tb_file, \"w\") as f:\n f.write(\"%s\\n\" % traceback[:MAX_PLACEHOLDER_FILE_SIZE])\n print(f\"Successfully wrote the errors to {alt_error_file} and {alt_tb_file}\")\n\n if (\n os.path.exists(docker_stats_file)\n and os.path.getsize(docker_stats_file) == 0\n ):\n print(f\"Renaming {PLACEHOLDER_DOCKER_STATS_FILE} to {docker_stats_file}\")\n os.rename(PLACEHOLDER_DOCKER_STATS_FILE, docker_stats_file)\n print(\n f\"Successfully renamed {PLACEHOLDER_DOCKER_STATS_FILE} to {docker_stats_file}\"\n )\n\n\ndef copy_sciflo_work(output_dir):\n \"\"\"Move over smap_sciflo work dirs.\"\"\"\n\n # Instead of creating symlinks like it was initially doing, this has been updated\n # to copy the sciflo workunit directories to its human readable sciflo step.\n for root, dirs, files in os.walk(output_dir):\n for d in dirs:\n if not WORK_RE.search(d):\n continue\n path = os.path.join(root, d)\n if os.path.islink(path) and os.path.exists(path):\n real_path = os.path.realpath(path)\n os.unlink(path)\n base_name = os.path.basename(path)\n new_path = os.path.join(root, base_name)\n shutil.copytree(real_path, new_path)\n return\n\n\ndef extract_error(sfl_json):\n \"\"\"Extract SciFlo error and traceback for mozart.\"\"\"\n\n with open(sfl_json) as f:\n j = json.load(f)\n exc_message = j.get(\"exceptionMessage\", None)\n if exc_message is not None:\n try:\n exc_list = eval(exc_message)\n except Exception:\n exc_list = []\n if len(exc_list) == 3:\n proc = exc_list[0]\n exc = exc_list[1]\n tb = exc_list[2]\n accountability = None\n try:\n exc = eval(exc)\n except Exception:\n pass\n if isinstance(exc, tuple) and len(exc) == 2:\n err = exc[0]\n job_json = exc[1]\n if isinstance(job_json, dict):\n if \"job_id\" in job_json:\n err_str = (\n \"SciFlo step %s with job_id %s (task %s) failed: %s\"\n % (proc, job_json[\"job_id\"], job_json[\"uuid\"], err)\n )\n __write_error_files(err_str, job_json[\"traceback\"])\n else:\n err_str = \"SciFlo step %s failed: %s\" % (proc, exc)\n __write_error_files(err_str, tb)\n\n\ndef run_sciflo(sfl_file, sfl_args, output_dir):\n \"\"\"Run sciflo.\"\"\"\n\n # build paths to executables\n sflexec_path = os.path.join(os.environ[\"HOME\"], \"verdi\", \"bin\", \"sflExec.py\")\n __create_placeholder_alt_files()\n # execute sciflo\n cmd = [\n sflexec_path,\n \"-s\",\n \"-f\",\n \"-o\",\n output_dir,\n \"--args\",\n '\"%s\"' % \",\".join(sfl_args),\n sfl_file,\n ]\n print(\"Running sflExec.py command:\\n%s\" % \" \".join(cmd))\n status = os.system(\" \".join(cmd))\n sf_key, context_file = sfl_args[0].split(\"=\")\n print(\"Exit status is: %d\" % status)\n if status != 0:\n extract_error(\"%s/sciflo.json\" % output_dir)\n status = 1\n\n # copy smap_sciflo work and exec dir\n try:\n copy_sciflo_work(output_dir)\n except Exception:\n pass\n\n __cleanup_placeholder_alt_files()\n return status\n" }, { "alpha_fraction": 0.5874231457710266, "alphanum_fraction": 0.5875391364097595, "avg_line_length": 38.53669738769531, "blob_id": "818b2e96bda78e799e8ec4ab3b5a1d2ea8056688", "content_id": "549c2c49e0bd7412ec9148e87944ce051fd9218c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8619, "license_type": "no_license", "max_line_length": 117, "num_lines": 218, "path": "/chimera/pge_job_submitter.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "\"\"\"\nClass that submits a PGE job to HySDS. This class can be used as-is, which will rely on HySDS Core's feature\nof performing the hash calculation to determine dedup.\n\n\"\"\"\n\nimport json\nimport os\nfrom chimera.commons.constants import ChimeraConstants as chimera_const\nfrom chimera.commons.conf_util import load_config, YamlConf\nfrom chimera.logger import logger\n\nfrom hysds_commons.job_utils import resolve_hysds_job\n\n\nclass PgeJobSubmitter(object):\n def __init__(self, context, run_config, pge_config_file, settings_file, wuid=None, job_num=None):\n # load context file\n if isinstance(context, dict):\n self._context = context\n elif isinstance(context, str):\n self._context = json.load(open(context, 'r'))\n logger.debug(\"Loaded context file: {}\".format(json.dumps(self._context)))\n\n # This is intended to represent the top level working directory of the job. It's assumed to be at the same\n # level as the given context file.\n self._base_work_dir = os.path.dirname(os.path.abspath(context))\n\n # load pge config file\n self._pge_config = load_config(pge_config_file)\n logger.debug(\"Loaded PGE config file: {}\".format(json.dumps(self._pge_config)))\n\n self._wuid = wuid\n self._job_num = job_num\n\n # load Settings file\n try:\n if settings_file:\n settings_file = os.path.abspath(os.path.normpath(settings_file))\n self._settings = YamlConf(settings_file).cfg\n self._chimera_config = self._settings.get(\"CHIMERA\", None)\n if self._wuid and self._job_num is not None:\n if not self._chimera_config:\n raise RuntimeError(\"Must specify a CHIMERA area in {}\".format(settings_file))\n except Exception as e:\n if settings_file:\n file_name = settings_file\n else:\n file_name = '~/verdi/etc/settings.yaml'\n raise RuntimeError(\"Could not read settings file '{}': {}\".format(file_name, e))\n\n self._run_config = run_config\n\n def get_input_file_name(self, input_file_key=None):\n \"\"\"\n Function to grab the primary input file name out of the run config\n :param input_file_key: JSON key in runconfig containing the primary input\n value\n :return:\n \"\"\"\n\n input_products = self._run_config.get(chimera_const.RC_INPUT).get(input_file_key, None)\n if input_products is None:\n return None\n if isinstance(input_products, list):\n input_file = [os.path.basename(path) for path in input_products\n if not path.endswith(\".XFR\")]\n files = \"-\".join(input_file)\n else:\n input_file = os.path.basename(input_products)\n files = input_file\n return files\n\n def get_localize_urls(self, localize):\n \"\"\"\n create the list of products to be localized within the docker for the PGE\n run\n :param localize: list of urls to be localized\n :return: localize list that osaka understands\n \"\"\"\n localize_list = []\n\n for url in localize:\n element = {\"url\": url, \"path\": \"input/\"}\n localize_list.append(element)\n\n return localize_list\n\n def construct_params(self):\n \"\"\"\n Construct the params for the PGE job submission\n\n :return:\n \"\"\"\n try:\n localize_urls = self.get_localize_urls(self._run_config.get(chimera_const.LOCALIZE))\n except Exception:\n raise ValueError(\n \"Couldn't find {} in runconfig from input preprocessor\".format(\n chimera_const.LOCALIZE))\n\n job_params = {\n \"run_config\": self._run_config,\n \"pge_config\": self._pge_config,\n \"localize_urls\": localize_urls,\n \"simulate_outputs\": self._run_config[chimera_const.SIMULATE_OUTPUTS]\n }\n\n return job_params\n\n def get_payload_hash(self, job_type):\n \"\"\"\n Can be overwritten to calculate the payload hash to determine dedup. By returning None, we will use HySDS\n Core's hash calculation to determine dedup.\n\n :param job_type:\n\n :return:\n \"\"\"\n return None\n\n def perform_adaptation_tasks(self, job_json):\n \"\"\"\n Can be used to perform additional tasks prior to job submission.\n\n :param job_json:\n :return:\n \"\"\"\n return job_json\n\n def construct_job_payload(self, params=None, dataset_id=None, pge_config=None, job_type=None, job_queue=None,\n payload_hash=None):\n \"\"\"\n Uses resolve hysds job to get the job json\n :param params:\n :param dataset_id:\n :param pge_config:\n :param job_type:\n :param job_queue:\n :param payload_hash:\n :return:\n \"\"\"\n\n if dataset_id is not None:\n job_name = job_type + \"_\" + pge_config[\"pge_name\"] + \"_\" + dataset_id\n else:\n job_name = job_type + \"_\" + pge_config[\"pge_name\"]\n\n try:\n if dataset_id is not None:\n tags = [pge_config[\"pge_name\"], dataset_id]\n else:\n tags = [pge_config[\"pge_name\"]]\n job = resolve_hysds_job(job_type, job_queue,\n params=params, job_name=job_name, enable_dedup=True, tags=tags,\n payload_hash=payload_hash)\n except Exception as e:\n raise Exception(e)\n except:\n raise RuntimeError(\"Wasn't able to get Job JSON from resolve_hysds_job.\")\n\n print(json.dumps(job, sort_keys=True, indent=4, separators=(',', ': ')))\n return job\n\n def submit_job(self):\n if not isinstance(self._run_config, dict):\n raise RuntimeError(\"The output from input preprocessor is not a dictionary\")\n\n params = self.construct_params()\n\n # If wuid and job_num are not null, it is implied that we need to do job submission. In that case, we need to\n # construct the job payload.\n if self._wuid and self._job_num is not None:\n # get HySDS job type and queue information\n job_name = self._chimera_config.get(chimera_const.JOB_TYPES).get(\n self._pge_config.get(chimera_const.PGE_NAME))\n job_queue = self._chimera_config.get(chimera_const.JOB_QUEUES).get(\n self._pge_config.get(chimera_const.PGE_NAME))\n\n if chimera_const.RELEASE_VERSION in self._context:\n release_version = self._context[chimera_const.RELEASE_VERSION]\n else:\n release_version = self._context.get('container_specification').get('version')\n\n job_type = job_name + \":\" + release_version\n\n localize_hash = self.get_payload_hash(job_type)\n\n # Find what the primary input is to the job\n # input_file_key = self._pge_config.get(chimera_const.PRIMARY_INPUT, None)\n # dataset_id = self.get_input_file_name(input_file_key)\n\n # Nominally, the primary input is used as part of the job name. If we wanted to set something else in the\n # job\n # name, look to see if the pge_job_name field is specified in the run_config\n dataset_id = self._run_config.get(\"pge_job_name\", None)\n\n if dataset_id:\n logger.info(\"dataset_id is set to {}\".format(dataset_id))\n\n job_json = self.construct_job_payload(params, dataset_id=dataset_id, pge_config=self._pge_config,\n job_type=job_type, job_queue=job_queue, payload_hash=localize_hash)\n # Set the sciflo fields wuid and job num\n # these are internally passed context information available in sciflo processes\n job_json['payload']['_sciflo_wuid'] = self._wuid\n job_json['payload']['_sciflo_job_num'] = self._job_num\n\n logger.debug(\"Resolved Job JSON: {}\".format(json.dumps(job_json)))\n else:\n # If we're running inline, we will set the params as the job_json\n job_json = params\n # We also need to get the job_specification from _context.json as that contains dependency image\n # information, if specified\n if \"job_specification\" in self._context:\n job_json[\"job_specification\"] = self._context[\"job_specification\"]\n job_json = self.perform_adaptation_tasks(job_json)\n\n return job_json\n" }, { "alpha_fraction": 0.6857707500457764, "alphanum_fraction": 0.687747061252594, "avg_line_length": 32.733333587646484, "blob_id": "c6bf8b8c1d8883f0885f6c69362365d9c6bbbe16", "content_id": "a55e7b4f37146e7c58283cee680b0cb9514264b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 506, "license_type": "no_license", "max_line_length": 91, "num_lines": 15, "path": "/tests/test_product_counter.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import simplejson\nimport sys\n\nfrom smap_sciflo import input_preprocessor as ipp\n\n\nif __name__ == '__main__':\n\n context_file = \"test-files/sf_context.json\"\n context = simplejson.load(open(context_file, 'r'))\n pge_config = simplejson.load(open(\"../configs/PGE_TSURF.json\", \"r\"))\n # context = process_for_l0b_radiometer(context, simplejson.load(open(pge_config, 'r')))\n job_params = ipp.get_product_counter(pge_config, context)\n # test output of get_product_metadata)_\n print(job_params)\n" }, { "alpha_fraction": 0.6351931095123291, "alphanum_fraction": 0.6577253341674805, "avg_line_length": 27.24242401123047, "blob_id": "4868649320d50ad0e46c776ef53940303b8df3b4", "content_id": "3fffba6c1d2ec8121f28ca4047bf9e4f7fd42ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 932, "license_type": "no_license", "max_line_length": 107, "num_lines": 33, "path": "/chimera/run_sciflo.sh", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "#!/bin/bash\nBASE_PATH=$(dirname \"${BASH_SOURCE}\")\nBASE_PATH=$(cd \"${BASE_PATH}\"; pwd)\n\n# source PGE env\nexport chimera_HOME=$(dirname \"${BASE_PATH}\")\nexport PYTHONPATH=$BASE_PATH:$chimera_HOME:$PYTHONPATH\nexport PATH=$BASE_PATH:$PATH\nexport PGE=$(basename \"${BASE_PATH}\")\nexport PYTHONDONTWRITEBYTECODE=1\n\n# source environment\nsource $HOME/verdi/bin/activate\n\nMODULE_PATH=\"$1\"\nWF_DIR=\"$2\"\nWF_NAME=\"$3\"\n\nexport PYTHONPATH=${MODULE_PATH}:$PYTHONPATH\n\necho \"##########################################\" 1>&2\necho -n \"Running $PGE run_sciflo.py with params $WF_DIR/$WF_NAME.sf.xml and _context.json: \" 1>&2\ndate 1>&2\npython $BASE_PATH/run_sciflo.py $WF_DIR/$WF_NAME.sf.xml _context.json output > run_sciflo_$WF_NAME.log 2>&1\nSTATUS=$?\necho -n \"Finished running $PGE run_sciflo.py: \" 1>&2\ndate 1>&2\nif [ $STATUS -ne 0 ]; then\n echo \"Failed to run $PGE run_sciflo.py\" 1>&2\n cat run_sciflo_$WF_NAME.log 1>&2\n echo \"{}\"\n exit $STATUS\nfi\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5740740895271301, "avg_line_length": 20.600000381469727, "blob_id": "77e2f67c8dc128153629801bd1565ff540e55d6c", "content_id": "d05e150cdb4bf1545301c94f3a91428a0f3be4b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 43, "num_lines": 15, "path": "/setup.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nadaptation_path = \"folder/\"\n\nsetup(\n name='chimera',\n version='2.2.2',\n packages=find_packages(),\n install_requires=[\n 'elasticsearch>=7.0.0,<7.14.0',\n 'elasticsearch-dsl>=7.0.0,<=7.4.0',\n 'requests>=2.18.4',\n 'simplejson>=3.11.1'\n ]\n)\n" }, { "alpha_fraction": 0.5183486342430115, "alphanum_fraction": 0.6284403800964355, "avg_line_length": 17.16666603088379, "blob_id": "661ee0353525eff0229b780b25389e6051fbc675", "content_id": "1bfaa2e4c392e5f5c93c5499a1bc79f2c52d554e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 218, "license_type": "no_license", "max_line_length": 45, "num_lines": 12, "path": "/.flake8", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "[flake8] \nformat = pylint\nmax-line-length = 120\nignore =\n # E501: line too long\n E501,\n # W503: line break before binary operator\n W503,\n # E722: do not use bare 'except'\n E722\nstatistics = 1\ntee = 1\n" }, { "alpha_fraction": 0.6137930750846863, "alphanum_fraction": 0.6137930750846863, "avg_line_length": 29.20833396911621, "blob_id": "5083f5951bfb262bfdb92ac541c8cf928099b0d5", "content_id": "e5660e1ff52c54e1e97d424d3a1613ef31d3a7e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "no_license", "max_line_length": 137, "num_lines": 24, "path": "/chimera/commons/accountability.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport json\nfrom chimera.commons.constants import ChimeraConstants as chimera_const\n\nclass Accountability(object):\n def __init__(self, context, work_dir):\n self.context = context\n self.job_json = None\n self.job_id = None\n self.work_dir = work_dir\n if work_dir is not None:\n with open(\"{}/_job.json\".format(work_dir), \"r\") as f:\n self.job_json = json.load(f)\n\n self.job_id = self.job_json.get(chimera_const.JOB_INFO).get(chimera_const.JOB_PAYLOAD).get(chimera_const.PAYLOAD_TASK_ID)\n\n def get_entries(self):\n pass\n\n def create_job_entry(self):\n pass\n\n def set_products(self, job_results):\n pass\n" }, { "alpha_fraction": 0.6482269763946533, "alphanum_fraction": 0.6482269763946533, "avg_line_length": 36.105262756347656, "blob_id": "f348e2ae81fc35dd3917e0a2ac37c64771ed1591", "content_id": "e35c1dd967447afe967146809983ce4129d679bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "no_license", "max_line_length": 103, "num_lines": 19, "path": "/chimera/precondition_functions.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "class PreConditionFunctions(object):\n def __init__(self, context, pge_config, settings, job_params):\n self._context = context\n self._pge_config = pge_config\n self._settings = settings\n self._job_params = job_params\n\n def run(self, function_list):\n \"\"\"\n Runs the set of preconditions passed into the given list.\n\n :param function_list: A list of precondition methods that will be defined in the subclasses.\n\n :return: a dictionary containing information about the results of the precondition evaluations.\n \"\"\"\n for func in function_list:\n self._job_params.update(getattr(self, func)())\n\n return self._job_params\n" }, { "alpha_fraction": 0.5299999713897705, "alphanum_fraction": 0.7099999785423279, "avg_line_length": 15.666666984558105, "blob_id": "ecf0612e38fd2807bba9851532d6e7dbe9a4bfc4", "content_id": "66ab86a425801a80c043dcb035481ffb0ddd07bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 100, "license_type": "no_license", "max_line_length": 20, "num_lines": 6, "path": "/chimera/requirements.txt", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "hysds_commons==0.1\nsetuptools==38.2.5\nrequests==2.20.0\ncelery==5.2.2\nelasticsearch==6.2.0\nyaml==5.1\n" }, { "alpha_fraction": 0.6759999990463257, "alphanum_fraction": 0.6809999942779541, "avg_line_length": 44.45454406738281, "blob_id": "f776e1fb2b07f5a1e549a7a70c68d16ef38fd67a", "content_id": "4af82083f9d3aa382ecfadce920bf4a7077bf469", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 116, "num_lines": 22, "path": "/tests/test_input_preprocessor.py", "repo_name": "hysds/chimera", "src_encoding": "UTF-8", "text": "import simplejson\nfrom nisar_chimera import input_preprocessor as ipp\n\nif __name__ == '__main__':\n sys_config = \"../nisar_chimera/configs/sys.config.json\"\n test_configs = list()\n\n # For testing without sfl_exec L0A\n context = simplejson.load(\n open(\"test-files/L0A_sfcontext.json\", 'r'))\n ipp_def_filepath = \"../nisar_chimera/configs/precondition_definition.yaml\"\n pge_config = \"../nisar_chimera/configs/pge_configs/PGE_L0A.yaml\"\n settings_file = '../../nisar-pcm/conf/settings.yaml'\n test_configs.append((context, pge_config))\n\n # context = process_for_l0b_radiometer(context, simplejson.load(open(pge_config, 'r')))\n # Loop through all test configs\n for context, pge_config in test_configs:\n payload = ipp.process(sf_context=context, ipp_def_filepath=ipp_def_filepath, pge_config_filepath=pge_config,\n sys_config_file=sys_config, settings_file=settings_file, testmode=True)\n\n print(simplejson.dumps(payload, indent=2))\n" } ]
25
fiaasco/traefik-docker
https://github.com/fiaasco/traefik-docker
8a484163bdb6de0a9669da4f4129e1b562f11c5d
b3b916abfe4d22a85751623dc3f8a031022b067d
b90d4385dc53c8b82c08760304c53707bec2df6e
refs/heads/master
2021-02-16T08:30:47.592217
2020-03-10T20:34:08
2020-03-10T20:34:08
244,985,227
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6445698142051697, "alphanum_fraction": 0.6516219973564148, "avg_line_length": 17.657894134521484, "blob_id": "e7c55ba189a95b5ef95cac0a1dd3a91e07723c5c", "content_id": "72686facd7ba16fefcb923674c45b52581e996b8", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 709, "license_type": "permissive", "max_line_length": 127, "num_lines": 38, "path": "/README.md", "repo_name": "fiaasco/traefik-docker", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.com/fiaasco/traefik-docker.svg?branch=master)](https://travis-ci.com/fiaasco/traefik-docker)\n\nRole Name\n=========\n\nThis installs a traefik running on docker\n\nRequirements\n------------\n\nDocker running on the host, publically accessible tcp/80 and tcp/443\n\nRole Variables\n--------------\n\ntraefik_le_email: email address used for Letsencrypt registration\ntraefik_vhost: required variable for now to indicate the default virtualhost.\n\nDependencies\n------------\n\nExample Playbook\n----------------\n\n - hosts: traefik:&docker\n roles:\n - fiaasco.docker\n - fiaasco.traefik-docker\n\nLicense\n-------\n\nBSD\n\nAuthor Information\n------------------\n\nDieter Verhelst - [email protected]\n" }, { "alpha_fraction": 0.736947774887085, "alphanum_fraction": 0.736947774887085, "avg_line_length": 26.66666603088379, "blob_id": "291f525dcf0be01c4381f80dd5f40d3bcc3addc0", "content_id": "663b61cb3205198667d7346eb735675a50edbb89", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "permissive", "max_line_length": 75, "num_lines": 18, "path": "/molecule/default/tests/test_traefik.py", "repo_name": "fiaasco/traefik-docker", "src_encoding": "UTF-8", "text": "import os\nimport pytest\nimport testinfra.utils.ansible_runner\n\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')\n\n\ndef test_traefik_container(host):\n command = host.run(\"docker ps\")\n assert \"traefik\" in command.stdout\n\n\[email protected]('volume', ['traefik_logs', 'traefik_letsencrypt'])\ndef test_traefik_volumes(host, volume):\n command = host.run(\"docker volume ls\")\n assert (volume) in command.stdout\n" } ]
2
nguyenquyem99dt/SearchAlgorithms
https://github.com/nguyenquyem99dt/SearchAlgorithms
e6de0534be4fdbfae6d185a3ed356c27cb1ecca4
feba249428c6e761c9a112d1758a886c0db3c031
5384ed093447f3ccc738fbc06ac571ffd3668324
refs/heads/master
2022-12-13T23:48:12.931220
2020-08-30T06:22:26
2020-08-30T06:22:26
291,406,404
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4878329038619995, "alphanum_fraction": 0.5225138664245605, "avg_line_length": 30.433734893798828, "blob_id": "983d4787b229b96a8270dffc438c89f2d04c78d9", "content_id": "eb27211f3d29e2991028ba805ac4c4614aec2f82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5219, "license_type": "no_license", "max_line_length": 120, "num_lines": 166, "path": "/mapio.py", "repo_name": "nguyenquyem99dt/SearchAlgorithms", "src_encoding": "UTF-8", "text": "from shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\nfrom os import path\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nimport numpy as np\nimport math\n\n\nCOLOR = [[51, 153, 255], [255, 0, 255], [51, 204, 51]]\n\ndef load_map(map_name = \"input.txt\"):\n if not path.isfile(map_name):\n print('File \"'+map_name+ '\" is not exist!')\n return\n f = open(map_name, \"r\")\n height = 0\n width = 0\n vertex = []\n lines = f.readlines()\n \n width, height = np.array(lines[0].split(','), dtype = int)\n\n p_map = np.full((height + 1, width + 1, 3), 255)\n\n p_map[0] = [183, 183, 183]\n p_map[height] = [183, 183, 183]\n p_map[:,0] = [183, 183, 183]\n p_map[:, width] = [183, 183, 183]\n \n t = np.array(lines[1].split(','), dtype = int)\n for i in range(t.shape[0] // 2):\n vertex.append((t[2*i],height - t[2*i + 1]))\n\n for v in vertex:\n p_map[v[1], v[0]] = [255, 64, 0]\n\n n_polygons = int(lines[2])\n\n for i in range(n_polygons):\n t = np.array(lines[3 + i].split(','), dtype = int)\n v = []\n x = []\n y = []\n for j in range(t.shape[0] // 2):\n x.append(t[2*j])\n y.append(t[2*j + 1])\n x_max = max(x)\n x_min = min(x)\n y_min = min(y)\n y_max = max(y)\n for j in range(len(x)):\n v.append((x[j], y[j]))\n fill_polygon(p_map, v, x_min, x_max, y_min, y_max, height)\n f.close()\n \n return p_map, vertex\n\ndef fill_polygon(p_map, polygon_vertex, x_min, x_max, y_min, y_max, height):\n polygon = Polygon(polygon_vertex)\n d = [(0, 0), (-0.5, 0), (0, 0.5), (0.5, 0.5), (0.5, -0.5)]\n for i in range(y_min, y_max + 1):\n for j in range(x_min, x_max + 1):\n for dt in d:\n if polygon.contains(Point(j + dt[0], i + dt[1])) or polygon.touches(Point(j + dt[0], i + dt[1])):\n p_map[height - i, j] = [255, 255, 102]\n break\n\n\ndef create_graph(func, p_map, vertex):\n path = dict()\n cost = np.zeros((len(vertex), len(vertex)), dtype= int)\n mapping = dict()\n for i in range(len(vertex)):\n mapping[str(i)] = vertex[i]\n\n for i in range(len(vertex) - 1):\n for j in range(i + 1, len(vertex)):\n p, c = func(p_map, vertex[i], vertex[j])\n path[str(vertex[i])+str(vertex[j])] = p\n cost[i, j] = c\n p, c = func(p_map, vertex[j], vertex[i])\n path[str(vertex[j])+str(vertex[i])] = p\n cost[j, i] = c\n\n return path, mapping, cost\n\ndef find_best_path(k, n, curr_path, actual_path, min_cost, cost):\n if k == n:\n c = 0\n path = []\n path.append(0)\n for i in curr_path:\n path.append(i)\n path.append(n + 1)\n for j in range(len(path) - 1):\n c += cost[path[j], path[j + 1]]\n if min_cost[0] == -1 or c < min_cost[0]:\n while actual_path.__len__() > 0:\n actual_path.pop()\n for tmp in path:\n actual_path.append(tmp)\n min_cost[0] = c \n else:\n for i in range(k -1, n):\n curr_path[k - 1], curr_path[i] = curr_path[i], curr_path[k - 1]\n find_best_path(k + 1, n, curr_path, actual_path, min_cost, cost)\n curr_path[k - 1], curr_path[i] = curr_path[i], curr_path[k - 1]\n \n\ndef fill_color(p_map, path, start, goal, color): \n v = path[str(goal)]\n while not np.all(start == v):\n if not np.all(p_map[v[1], v[0]] == [255, 64, 0]):\n p_map[v[1], v[0]] = color\n v = path[str(v)]\n\ndef find_path(func, p_map, vertex):\n order_vertex = []\n order_vertex.append(vertex[0])\n tmp = vertex[2:]\n if len(tmp) > 0:\n for i in tmp:\n order_vertex.append(i)\n order_vertex.append(vertex[1])\n\n path, mapping, graph = create_graph(func, p_map, order_vertex)\n\n min_cost = [-1]\n actual_path = []\n if len(order_vertex) == 2:\n curr_path = []\n find_best_path(0, 0, curr_path, actual_path, min_cost, graph)\n else:\n curr_path = [i for i in range(1, len(order_vertex) - 1)]\n find_best_path(1, len(order_vertex) - 2, curr_path, actual_path, min_cost, graph)\n\n for i in range(len(actual_path) - 1):\n key = str(mapping[str(actual_path[i])]) + str(mapping[str(actual_path[i + 1])])\n curr_path = path[key]\n fill_color(p_map, curr_path, mapping[str(actual_path[i])], mapping[str(actual_path[i + 1])], color = COLOR[i%3])\n\ndef draw(p_map, nameWindow):\n width = p_map.shape[1]\n height = p_map.shape[0]\n\n fig = plt.figure()\n fig.canvas.set_window_title(nameWindow)\n ax = fig.gca()\n\n # Major ticks\n ax.set_xticks(np.arange(0, width, 1))\n ax.set_yticks(np.arange(0, height, 1))\n\n # Labels for major ticks\n ax.set_xticklabels(np.arange(0, width, 1))\n ax.set_yticklabels(np.arange(height - 1, -1, -1))\n\n # Minor ticks\n ax.set_xticks(np.arange(-.5, width, 1), minor=True)\n ax.set_yticks(np.arange(-.5, height, 1), minor=True)\n\n # Gridlines based on minor ticks\n ax.grid(which='minor', color='k', linestyle='-', linewidth=1)\n plt.imshow(p_map)\n plt.show()\n\n" }, { "alpha_fraction": 0.5141762495040894, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 35.27777862548828, "blob_id": "ebdc5151bb5f96c0b1ffc1891968a563fbb131e1", "content_id": "1950aa5d0a3a375dc539478244ab30eca9ad2104", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 153, "num_lines": 36, "path": "/bfs.py", "repo_name": "nguyenquyem99dt/SearchAlgorithms", "src_encoding": "UTF-8", "text": "import numpy as np\nimport mapio\n\ndef extend(p_map, current):\n dt = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]\n near = []\n for vt in dt:\n new_vertex = (current[0] + vt[0], current[1] + vt[1])\n if new_vertex[0] < p_map.shape[1] and new_vertex[0] > 0 and new_vertex[1] > 0 and new_vertex[1] < p_map.shape[0]:\n if not np.all(p_map[new_vertex[1], new_vertex[0]] == [255, 255, 102]) and not np.all(p_map[new_vertex[1], new_vertex[0]] == [183, 183, 183]):\n near.append(new_vertex)\n return near\n\ndef bfs(p_map,start,goal):\n queue=[]\n visited=[]\n previous=dict()\n _cost_to =dict()\n queue.append(start)\n _cost_to[str(start)]=0\n while len(queue)>0:\n current = queue.pop(0)\n visited.append(current)\n if np.all(current==goal):\n return previous,_cost_to[str(goal)]\n for point in extend(p_map,current):\n cost_to = _cost_to[str(current)]+1\n if point not in visited and point not in queue:\n _cost_to[str(point)]=cost_to\n previous[str(point)]=current\n queue.append(point)\n return previous, np.inf\n\n_map, vertex = mapio.load_map('input.txt')\nmapio.find_path(bfs,_map,vertex)\nmapio.draw(_map,'Breadth First Search')" }, { "alpha_fraction": 0.49621620774269104, "alphanum_fraction": 0.5329729914665222, "avg_line_length": 30.913793563842773, "blob_id": "ec48fa0fa3e2907463c304678d780ee14324a648", "content_id": "3ddad8e4bab2464083e3ad5057a1c3ff10368585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1850, "license_type": "no_license", "max_line_length": 157, "num_lines": 58, "path": "/astart.py", "repo_name": "nguyenquyem99dt/SearchAlgorithms", "src_encoding": "UTF-8", "text": "import mapio\nimport numpy as np\n\ndef a_star_search(p_map, start, goal):\n _from = dict()\n _cost_to = dict()\n q = []\n cost = np.zeros((p_map.shape[0], p_map.shape[1]), dtype = int)\n q.append(start)\n _from[str(start)] = start\n _cost_to[str(start)] = 0\n\n while q.__len__() > 0:\n current = get_promissing(q, cost)\n q.remove(current)\n if np.all(current == goal):\n return _from, _cost_to[str(goal)]\n\n for point in extend(p_map, current):\n cost_to = _cost_to[str(current)] + 1\n if str(point) not in _cost_to or cost_to < _cost_to[str(point)]:\n _cost_to[str(point)] = cost_to\n cost[point[1], point[0]] = cost_to + heuristic(point, goal)\n q.append(point)\n _from[str(point)] = current\n\n return _from, np.inf\n\n\n\ndef get_promissing(q, cost):\n min_cost = -1\n min_point = q[0]\n for point in q:\n if min_cost == -1 or cost[point[1], point[0]] < min_cost:\n min_point = point\n min_cost = cost[point[1], point[0]]\n return min_point\n\ndef extend(p_map, current):\n dt = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]\n near = []\n for vt in dt:\n new_vertex = (current[0] + vt[0], current[1] + vt[1])\n if new_vertex[0] < p_map.shape[1] and new_vertex[0] > 0 and new_vertex[1] > 0 and new_vertex[1] < p_map.shape[0]:\n if (not np.all(p_map[new_vertex[1], new_vertex[0]] == [255, 255, 102])) and (not np.all(p_map[new_vertex[1], new_vertex[0]] == [183, 183, 183])):\n near.append(new_vertex)\n return near\n\ndef heuristic(start, goal):\n return abs(start[0] - goal[0]) + abs(start[1] - goal[1])\n\n\n_map, vertex = mapio.load_map('input.txt')\n\nmapio.find_path(a_star_search, _map, vertex)\n\nmapio.draw(_map,'A* Search')" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.782608687877655, "avg_line_length": 33.5, "blob_id": "063786385780477a25b479d5614295fb5183a04b", "content_id": "bd035bc585ad9b92f11a9402494b600ef341c200", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "no_license", "max_line_length": 49, "num_lines": 2, "path": "/README.md", "repo_name": "nguyenquyem99dt/SearchAlgorithms", "src_encoding": "UTF-8", "text": "# SearchAlgorithms\nLab01 of Introduction to AI course - 2019 - HCMUS\n" } ]
4
Lukas-drz/pacman
https://github.com/Lukas-drz/pacman
4c38ee51899d3a84b8f627031b02fad4026c4869
b4d64f736cc2dab8abdbe0bac96f9390f9ccf28a
2c5f109f367da7ac99dc62413e5eff0c82d238bc
refs/heads/master
2020-05-23T15:54:53.117505
2019-05-19T17:27:08
2019-05-19T17:27:08
186,837,168
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5245791077613831, "alphanum_fraction": 0.5520538687705994, "avg_line_length": 41.180233001708984, "blob_id": "5e5691ee23dc8adcec9b6a688f2471119517e828", "content_id": "e83074e6637014ecb7d5fe1ad343a94af5241508", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7431, "license_type": "no_license", "max_line_length": 220, "num_lines": 172, "path": "/PacMan.py", "repo_name": "Lukas-drz/pacman", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\r\n# -*- coding: Utf-8 -*\r\nimport pygame\r\nfrom pygame.locals import *\r\nfrom classes import *\r\nfrom random import *\r\nimport time\r\npygame.init()\r\n\r\n#Affichage page d'accueil\r\nfenetre = pygame.display.set_mode((400, 400))\r\nicone = pygame.image.load(\"icone.png\")\r\npygame.display.set_icon(icone)\r\npygame.display.set_caption(\"PacMan ISN La Merci : Lukas Deronzier, Mathieu Dumarcel, Jules Majoulet\")\r\n\r\n#Déplacement continu\r\npygame.key.set_repeat(200, 20)\r\nderniere_touche = \"\"\r\n#variable lors de K_ESCAPE\r\nem=0\r\neh=0\r\nh=0\r\n\r\n#variable pour la boucle\r\ncontinuer = 1\r\n#Début boucle principale\r\nwhile continuer:\r\n accueil = pygame.image.load(\"Title screen/title screen.png\").convert()\r\n fenetre.blit(accueil,(0,0))\r\n pygame.display.flip()\r\n\r\n continuer_jeu = 1\r\n continuer_accueil = 1\r\n\r\n\r\n while continuer_accueil == 1:\r\n\r\n pygame.time.Clock()\r\n\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n continuer_jeu = 0\r\n continuer_accueil = 0\r\n continuer = 0\r\n\r\n #Echappe du menu\r\n if h==0 and event.type == KEYDOWN and event.key == K_ESCAPE or h==0 and event.type == MOUSEBUTTONDOWN and event.button == 1 and event.pos[0]<108 and event.pos[0]>20 and event.pos[1]<267 and event.pos[1]>232 :\r\n echappe_menu = pygame.image.load(\"Echappe/Echappe.png\").convert()\r\n fenetre.blit(echappe_menu,(0,133))\r\n pygame.display.flip()\r\n em=1\r\n choix = 0\r\n\r\n #Oui ou Non du Echappe du menu\r\n if em==1 and event.type == MOUSEBUTTONDOWN and event.button == 1 and event.pos[0]<147 and event.pos[0]>71 and event.pos[1]<232 and event.pos[1]>201:\r\n continuer_jeu = 0\r\n continuer_accueil = 0\r\n continuer = 0\r\n\r\n if em == 1 and event.type == MOUSEBUTTONDOWN and event.button == 1 and event.pos[0]<332 and event.pos[0]>243 and event.pos[1]<232 and event.pos[1]>201:\r\n fenetre.blit(accueil,(0,0))\r\n pygame.display.flip()\r\n em=0\r\n\r\n #Help pages\r\n if event.type == MOUSEBUTTONDOWN and event.button == 1 and event.pos[0]<109 and event.pos[0]>20 and event.pos[1]<225 and event.pos[1]>192:\r\n help1=pygame.image.load(\"Help screen/Help1.png\").convert()\r\n fenetre.blit(help1,(0,0))\r\n pygame.display.flip()\r\n h=1\r\n\r\n #Echappe du Help\r\n if h==1 and event.type == KEYDOWN and event.key == K_ESCAPE:\r\n echappe_help = pygame.image.load(\"Echappe/Echappe help.png\").convert()\r\n fenetre.blit(echappe_help,(0,133))\r\n pygame.display.flip()\r\n eh=1\r\n\r\n #Oui ou Non du Echappe du Help\r\n if eh==1 and event.type == MOUSEBUTTONDOWN and event.button == 1 and event.pos[0]<137 and event.pos[0]>72 and event.pos[1]<233 and event.pos[1]>208:\r\n fenetre.blit(accueil,(0,0))\r\n pygame.display.flip()\r\n eh=0\r\n h=0\r\n\r\n if eh == 1 and event.type == MOUSEBUTTONDOWN and event.button == 1 and event.pos[0]<322 and event.pos[0]>246 and event.pos[1]<230 and event.pos[1]>209:\r\n fenetre.blit(help1,(0,0))\r\n pygame.display.flip()\r\n\r\n #Lorsque l'on appuie sur PLAY\r\n if event.type == MOUSEBUTTONDOWN and event.button == 1 and event.pos[0]<108 and event.pos[0]>19 and event.pos[1]<184 and event.pos[1]>151:\r\n continuer_accueil = 0\r\n choix = 'n1'\r\n\r\n if choix != 0:\r\n fenetre_jeu = pygame.display.set_mode((810,750))\r\n fond = pygame.image.load(\"Structure/fond.jpg\").convert()\r\n fenetre_jeu.blit(fond,(0,0))\r\n niveau = Niveau(choix)\r\n niveau.generer()\r\n niveau.afficher(fenetre)\r\n pac_gomme = pac_gomme('pac_gommes')\r\n pac_gomme.generation()\r\n pac_gomme.affichage(fenetre)\r\n Pacman = Perso(\"Perso/droite.png\", \"Perso/gauche.png\", \"Perso/haut.png\", \"Perso/bas.png\", niveau)\r\n Ghost_red = Ghost_red(\"Ghost/Red/droite.png\", \"Ghost/Red/gauche.png\", \"Ghost/Red/haut.png\", \"Ghost/Red/bas.png\", niveau)\r\n Ghost_pink = Ghost_pink(\"Ghost/Pink/droite.png\", \"Ghost/Pink/gauche.png\", \"Ghost/Pink/haut.png\", \"Ghost/Pink/bas.png\", niveau)\r\n Ghost_cyan = Ghost_cyan(\"Ghost/Cyan/droite.png\", \"Ghost/Cyan/gauche.png\", \"Ghost/Cyan/haut.png\", \"Ghost/Cyan/bas.png\", niveau)\r\n Ghost_orange = Ghost_orange(\"Ghost/Orange/droite.png\", \"Ghost/Orange/gauche.png\", \"Ghost/Orange/haut.png\", \"Ghost/Orange/bas.png\", niveau)\r\n\r\n Baie = Baie(\"baie.png\", niveau)\r\n\r\n pygame.key.get_pressed()\r\n\r\n while continuer_jeu == 1:\r\n\r\n\t\t#Limitation de vitesse de la boucle\r\n pygame.time.Clock().tick(30)\r\n Ghost_red.ghost_deplacer()\r\n Ghost_orange.ghost_deplacer()\r\n Ghost_pink.ghost_deplacer()\r\n Ghost_cyan.ghost_deplacer()\r\n\r\n for event in pygame.event.get():\r\n\r\n if event.type == QUIT:\r\n continuer_jeu = 0\r\n continuer = 0\r\n elif event.type == KEYDOWN:\r\n if event.key == K_RIGHT or event.key == K_d:\r\n Pacman.deplacer('droite')\r\n #derniere_touche = \"right\"\r\n if event.key == K_LEFT or event.key == K_a: #a car pygame est en qwerty, a correspond à q sur un clavier azerty\r\n Pacman.deplacer('gauche')\r\n #derniere_touche = \"left\"\r\n if event.key == K_DOWN or event.key == K_s:\r\n Pacman.deplacer('bas')\r\n #derniere_touche = \"down\"\r\n if event.key == K_UP or event.key == K_w: #w car pygame est en qwerty, w correspond à z sur un clavier azerty\r\n Pacman.deplacer('haut')\r\n #derniere_touche = \"up\"\r\n if event.key == K_ESCAPE or event.key == K_F4 and bool(event.mod & KMOD_ALT):\r\n #echappe_jeu = pygame.image.load(\"Echappe/Echappe jeu.png\").convert()\r\n #fenetre_jeu.blit(echappe_jeu,(690,540))\r\n #pygame.display.flip()\r\n continuer = 0\r\n continuer_accueil = 0\r\n continuer_jeu = 0\r\n #while not pygame.key.get_focused():\r\n # if derniere_touche == \"right\":\r\n # Pacman.deplacer('droite')\r\n # if derniere_touche == \"left\":\r\n # Pacman.deplacer('gauche')\r\n # if derniere_touche == \"down\":\r\n # Pacman.deplacer('bas')\r\n # if derniere_touche == \"up\":\r\n # Pacman.deplacer('haut')\r\n\r\n\t\t#Affichages aux nouvelles positions\r\n fenetre.blit(fond, (0,0))\r\n niveau.afficher(fenetre)\r\n pac_gomme.affichage(fenetre)\r\n fenetre.blit(Baie.direction, (Baie.x, Baie.y))\r\n fenetre.blit(Pacman.direction, (Pacman.x, Pacman.y))\r\n fenetre.blit(Ghost_red.direction, (Ghost_red.x, Ghost_red.y))\r\n fenetre.blit(Ghost_pink.direction, (Ghost_pink.x, Ghost_pink.y))\r\n fenetre.blit(Ghost_orange.direction, (Ghost_orange.x, Ghost_orange.y))\r\n fenetre.blit(Ghost_cyan.direction, (Ghost_cyan.x, Ghost_cyan.y))\r\n pygame.display.flip()\r\n\r\n\r\npygame.quit()" }, { "alpha_fraction": 0.6173469424247742, "alphanum_fraction": 0.6328903436660767, "avg_line_length": 30.41538429260254, "blob_id": "d5511e8e82f481039a04a7c666ce8a3aa84c58d8", "content_id": "d27d2aaeb6adfb0e5415f996cf8eab45a67f88cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8444, "license_type": "no_license", "max_line_length": 70, "num_lines": 260, "path": "/classes.py", "repo_name": "Lukas-drz/pacman", "src_encoding": "UTF-8", "text": "import pygame\r\nfrom pygame.locals import *\r\nfrom random import *\r\nimport time\r\n\r\nclass Niveau:\r\n\r\n\tdef __init__(self, fichier):\r\n\t\tself.fichier = fichier\r\n\t\tself.structure = 0\r\n\r\n\tdef generer(self):\r\n\t\t#On ouvre le fichier\r\n\t\twith open(self.fichier, \"r\") as fichier:\r\n\t\t\tstructure_niveau = []\r\n\t\t\t#On parcourt les lignes du fichier\r\n\t\t\tfor ligne in fichier:\r\n\t\t\t\tligne_niveau = []\r\n\t\t\t\t#On parcourt les sprites (lettres) contenus dans le fichier\r\n\t\t\t\tfor sprite in ligne:\r\n\t\t\t\t\t#On ignore les \"\\n\" de fin de ligne\r\n\t\t\t\t\tif sprite != '\\n':\r\n\t\t\t\t\t\t#On ajoute le sprite à la liste de la ligne\r\n\t\t\t\t\t\tligne_niveau.append(sprite)\r\n\t\t\t\t#On ajoute la ligne à la liste du niveau\r\n\t\t\t\tstructure_niveau.append(ligne_niveau)\r\n\t\t\t#On sauvegarde cette structure\r\n\t\t\tself.structure = structure_niveau\r\n\r\n\r\n\tdef afficher(self, fenetre):\r\n\r\n\t\tmur = pygame.image.load(\"Structure/mur.png\").convert()\r\n\t\tnoir = pygame.image.load(\"Structure/noir.png\").convert()\r\n\t\t#On parcourt la liste du niveau\r\n\t\tnum_ligne = 0\r\n\t\tfor ligne in self.structure:\r\n\t\t\t#On parcourt les listes de lignes\r\n\t\t\tnum_case = 0\r\n\t\t\tfor sprite in ligne:\r\n\t\t\t\t#On calcule la position réelle en pixels\r\n\t\t\t\tx = num_case * 30\r\n\t\t\t\ty = num_ligne * 30\r\n\t\t\t\tif sprite == 'm':\t\t #m = Mur\r\n\t\t\t\t\tfenetre.blit(mur, (x,y))\r\n\t\t\t\t\tnum_case += 1\r\n\t\t\t\telif sprite == 'r' or sprite == 'p' or sprite == 'q':\r\n\t\t\t\t\tnum_case += 1\r\n\t\t\tnum_ligne += 1\r\n\r\nclass Perso:\r\n\tdef __init__(self, droite, gauche, haut, bas, niveau):\r\n\t\t#Sprites du personnage\r\n\t\tself.droite = pygame.image.load(droite).convert_alpha()\r\n\t\tself.gauche = pygame.image.load(gauche).convert_alpha()\r\n\t\tself.haut = pygame.image.load(haut).convert_alpha()\r\n\t\tself.bas = pygame.image.load(bas).convert_alpha()\r\n\t\t#Position du personnage en cases et en pixels\r\n\t\tself.case_x = 14\r\n\t\tself.case_y = 23\r\n\t\tself.x = 390\r\n\t\tself.y = 660\r\n\t\t#Direction par défaut\r\n\t\tself.direction = self.droite\r\n\t\t#Niveau dans lequel le personnage se trouve\r\n\t\tself.niveau = niveau\r\n\r\n\r\n\tdef deplacer(self, direction):\r\n\t\tnoir = pygame.image.load(\"Structure/noir.png\").convert_alpha()\r\n\t\t#Déplacement vers la droite\r\n\t\tif direction == 'droite':\r\n\t\t\tif self.niveau.structure[self.case_y][self.case_x+1] == 'p':\r\n\t\t\t\tself.case_x = 0\r\n\t\t\t#On vérifie que la case de destination n'est pas un mur\r\n\t\t\telif self.niveau.structure[self.case_y][self.case_x+1] != 'm':\r\n\t\t\t\t#Déplacement d'une case\r\n\t\t\t\tself.case_x += 1\r\n\t\t\t\t#Calcul de la position \"réelle\" en pixel\r\n\t\t\t\tself.x = self.case_x * 30\r\n\t\t\t#Image dans la bonne direction\r\n\t\t\tself.direction = self.droite\r\n\r\n\t\t#Déplacement vers la gauche\r\n\t\tif direction == 'gauche':\r\n\t\t\tif self.niveau.structure[self.case_y][self.case_x-1] == 'q':\r\n\t\t\t\tself.case_x = 26\r\n\t\t\telif self.niveau.structure[self.case_y][self.case_x-1] != 'm':\r\n\t\t\t\tself.case_x -= 1\r\n\t\t\t\tself.x = self.case_x * 30\r\n\t\t\tself.direction = self.gauche\r\n\r\n\t\t#Déplacement vers le haut\r\n\t\tif direction == 'haut':\r\n\t\t\tif self.niveau.structure[self.case_y-1][self.case_x] != 'm':\r\n\t\t\t\tself.case_y -= 1\r\n\t\t\t\tself.y = self.case_y * 30\r\n\t\t\tself.direction = self.haut\r\n\r\n\t\t#Déplacement vers le bas\r\n\t\tif direction == 'bas':\r\n\t\t\tif self.niveau.structure[self.case_y+1][self.case_x] != 'm':\r\n\t\t\t\tself.case_y += 1\r\n\t\t\t\tself.y = self.case_y * 30\r\n\t\t\tself.direction = self.bas\r\n\r\nclass Ghost:\r\n\tdef __init__(self, droite, gauche, haut, bas, niveau):\r\n\t\t#Sprites du personnage\r\n\t\tself.droite = pygame.image.load(droite).convert_alpha()\r\n\t\tself.gauche = pygame.image.load(gauche).convert_alpha()\r\n\t\tself.haut = pygame.image.load(haut).convert_alpha()\r\n\t\tself.bas = pygame.image.load(bas).convert_alpha()\r\n\r\n\tdef ghost_deplacer(self, direction = 'gauche'):\r\n\t\tfrom random import randint\r\n\t\ta=randint(1,4)\r\n\t\tif a == 1:\r\n\t\t\twhile self.niveau.structure[self.case_y-1][self.case_x] != 'm':\r\n\t\t\t\tif self.niveau.structure[self.case_y-1][self.case_x] != 'm':\r\n\t\t\t\t\tself.case_y -= 1\r\n\t\t\t\t\tself.y = self.case_y * 30\r\n\t\t\t\tself.direction = self.haut\r\n\t\tif a == 2:\r\n\t\t\twhile self.niveau.structure[self.case_y][self.case_x+1] != 'm':\r\n\t\t\t\tif self.niveau.structure[self.case_y][self.case_x+1] == 'p':\r\n\t\t\t\t\tself.case_x = 0\r\n\t\t\t\telif self.niveau.structure[self.case_y][self.case_x+1] != 'm':\r\n\t #Déplacement d'une case\r\n\t\t\t\t\tself.case_x += 1\r\n\t #Calcul de la position \"réelle\" en pixel\r\n\t\t\t\t\tself.x = self.case_x * 30\r\n\t #Image dans la bonne direction\r\n\t\t\t\tself.direction = self.droite\r\n\t\tif a == 3:\r\n\t\t\twhile self.niveau.structure[self.case_y+1][self.case_x] != 'm':\r\n\t\t\t\tif self.niveau.structure[self.case_y+1][self.case_x] != 'm':\r\n\t\t\t\t\tself.case_y += 1\r\n\t\t\t\t\tself.y = self.case_y * 30\r\n\t\t\t\tself.direction = self.bas\r\n\t\tif a == 4:\r\n\t\t\twhile self.niveau.structure[self.case_y][self.case_x-1] != 'm':\r\n\t\t\t\tif self.niveau.structure[self.case_y][self.case_x-1] == 'q':\r\n\t\t\t\t\tself.case_x = 26\r\n\t\t\t\telif self.niveau.structure[self.case_y][self.case_x-1] != 'm':\r\n\t\t\t\t\tself.case_x -= 1\r\n\t\t\t\t\tself.x = self.case_x * 30\r\n\t\t\t\tself.direction = self.gauche\r\n\t\t\r\nclass Ghost_red(Ghost):\r\n\tdef __init__(self, droite, gauche, haut, bas, niveau):\r\n\t\tself.droite = pygame.image.load(droite).convert_alpha()\r\n\t\tself.gauche = pygame.image.load(gauche).convert_alpha()\r\n\t\tself.haut = pygame.image.load(haut).convert_alpha()\r\n\t\tself.bas = pygame.image.load(bas).convert_alpha()\r\n\t\tself.case_x = 12\r\n\t\tself.case_y = 12\r\n\t\tself.x = 330\r\n\t\tself.y = 330\r\n\t\tself.direction = self.gauche\r\n\t\tself.niveau = niveau\r\n\t\tGhost.ghost_deplacer(self)\r\n\r\nclass Ghost_pink(Ghost):\r\n\tdef __init__(self, droite, gauche, haut, bas, niveau):\r\n\t\tself.droite = pygame.image.load(droite).convert_alpha()\r\n\t\tself.gauche = pygame.image.load(gauche).convert_alpha()\r\n\t\tself.haut = pygame.image.load(haut).convert_alpha()\r\n\t\tself.bas = pygame.image.load(bas).convert_alpha()\r\n\t\tself.case_x = 12\r\n\t\tself.case_y = 14\r\n\t\tself.x = 330\r\n\t\tself.y = 390\r\n\t\tself.direction = self.bas\r\n\t\tself.niveau = niveau\r\n\t\tGhost.ghost_deplacer(self)\r\n\r\nclass Ghost_cyan(Ghost):\r\n\tdef __init__(self, droite, gauche, haut, bas, niveau):\r\n\t\tself.droite = pygame.image.load(droite).convert_alpha()\r\n\t\tself.gauche = pygame.image.load(gauche).convert_alpha()\r\n\t\tself.haut = pygame.image.load(haut).convert_alpha()\r\n\t\tself.bas = pygame.image.load(bas).convert_alpha()\r\n\t\tself.case_x = 16\r\n\t\tself.case_y = 12\r\n\t\tself.x = 450\r\n\t\tself.y = 330\r\n\t\tself.direction = self.haut\r\n\t\tself.niveau = niveau\r\n\t\tGhost.ghost_deplacer(self)\r\n\r\nclass Ghost_orange(Ghost):\r\n\tdef __init__(self, droite, gauche, haut, bas, niveau):\r\n\t\tself.droite = pygame.image.load(droite).convert_alpha()\r\n\t\tself.gauche = pygame.image.load(gauche).convert_alpha()\r\n\t\tself.haut = pygame.image.load(haut).convert_alpha()\r\n\t\tself.bas = pygame.image.load(bas).convert_alpha()\r\n\t\tself.case_x = 16\r\n\t\tself.case_y = 14\r\n\t\tself.x = 450\r\n\t\tself.y = 390\r\n\t\tself.direction = self.droite\r\n\t\tself.niveau = niveau\r\n\t\tGhost.ghost_deplacer(self)\r\n\r\nclass pac_gomme:\r\n\tdef __init__(self, fichier):\r\n\t\tself.fichier = fichier\r\n\t\tself.structure = 0\r\n\t\timage_pac_gomme = pygame.image.load(\"pac_gomme.png\").convert_alpha()\r\n\r\n\tdef generation(self):\r\n\t\twith open(self.fichier, \"r\") as fichier:\r\n\t\t\tstructure_niveau = []\r\n\t\t\t#On parcourt les lignes du fichier\r\n\t\t\tfor ligne in fichier:\r\n\t\t\t\tligne_niveau = []\r\n\t\t\t\t#On parcourt les sprites (lettres) contenus dans le fichier\r\n\t\t\t\tfor sprite in ligne:\r\n\t\t\t\t\t#On ignore les \"\\n\" de fin de ligne\r\n\t\t\t\t\tif sprite != '\\n':\r\n\t\t\t\t\t\t#On ajoute le sprite à la liste de la ligne\r\n\t\t\t\t\t\tligne_niveau.append(sprite)\r\n\t\t\t\t#On ajoute la ligne à la liste du niveau\r\n\t\t\t\tstructure_niveau.append(ligne_niveau)\r\n\t\t\t#On sauvegarde cette structure\r\n\t\t\tself.structure = structure_niveau\r\n\r\n\tdef affichage(self, fenetre):\r\n\t\timage_pac_gomme = pygame.image.load(\"pac_gomme.png\").convert_alpha()\r\n\t\tnum_ligne = 0\r\n\t\tfor ligne in self.structure:\r\n\t\t\t#On parcourt les listes de lignes\r\n\t\t\tnum_case = 0\r\n\t\t\tfor sprite in ligne:\r\n\t\t\t\t#On calcule la position réelle en pixels\r\n\t\t\t\tx = num_case * 30\r\n\t\t\t\ty = num_ligne * 30\r\n\t\t\t\tif sprite == 'm':\r\n\t\t\t\t\tnum_case += 1\r\n\t\t\t\tif sprite == 'l':\t\t #m = Mur\r\n\t\t\t\t\tfenetre.blit(image_pac_gomme, (x,y))\r\n\t\t\t\t\tnum_case += 1\r\n\t\t\t\tif sprite == 'r':\r\n\t\t\t\t\tnum_case += 1\r\n\t\t\t\tif sprite == 'q':\r\n\t\t\t\t\tnum_case += 1\r\n\t\t\t\tif sprite == 'p':\r\n\t\t\t\t\tnum_case += 1\r\n\t\t\tnum_ligne += 1\r\n\r\nclass Baie:\r\n\tdef __init__(self, design, niveau):\r\n\t\tself.design = pygame.image.load(design).convert_alpha()\r\n\t\tself.niveau = niveau\r\n\t\tself.case_x = 2\r\n\t\tself.case_y = 2\r\n\t\tself.x = 30\r\n\t\tself.y = 30\r\n\t\tself.direction = self.design\r\n" } ]
2
real-kk/findme-backend
https://github.com/real-kk/findme-backend
4ea1d8da0074898eb5f04eeb2d93fcd108681e99
751f3a8d7ef139c5d6fa17bcfe59fd05fbe3818c
8baf680d2e66e78448ca0ffa82b6b167566c5ddc
refs/heads/main
2023-03-01T08:51:39.512365
2021-02-08T03:41:45
2021-02-08T03:41:45
301,883,517
4
1
null
2020-10-07T00:00:53
2020-11-08T17:52:43
2020-11-10T13:11:10
Python
[ { "alpha_fraction": 0.5968359708786011, "alphanum_fraction": 0.6080209612846375, "avg_line_length": 35.215328216552734, "blob_id": "a4829df76b76e24343f373441c66e8082f6a3d0a", "content_id": "0c45a4850f204361ba42a22357c7066cfefaf0ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10118, "license_type": "no_license", "max_line_length": 198, "num_lines": 274, "path": "/findme/diary/views.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom wordcloud import WordCloud\nfrom konlpy.tag import Mecab\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom .serializers import DiarySerializer, DiaryListSerializer, WholeContentSerializer, LineGraphSerializer\nfrom django.core.files.images import ImageFile\nfrom .models import Diary, DiaryWholeContent, LineGraph\nimport io\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom google.cloud import language_v1\nfrom datetime import datetime\nfrom google.oauth2 import service_account\nimport os\nimport re\nfrom users.models import User\nfrom PIL import Image\nimport requests\nimport numpy as np\n\n\ndef make_wordcloud(text):\n mecab = Mecab()\n text = re.compile('[|ㄱ-ㅎ|ㅏ-ㅣ]+').sub(\"\", text)\n morphs = mecab.pos(text)\n noun_adj_list = []\n for word, tag in morphs:\n if tag in ['VA', 'NNG', 'NNP', 'NNB', 'NNBC', 'NR', 'NP'] and len(word) > 1:\n noun_adj_list.append(word)\n counts = Counter(noun_adj_list)\n tags = counts.most_common(40)\n url = \"https://findme-app.s3.ap-northeast-2.amazonaws.com/home/cloud.png\"\n response = requests.get(url)\n cloud_mask = np.array(Image.open(io.BytesIO(response.content)))\n wordcloud = WordCloud(font_path='/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf', background_color=\"white\", width=300, height=300, mask=cloud_mask)\n cloud = wordcloud.generate_from_frequencies(dict(tags))\n plt.figure(figsize=(22, 22))\n plt.imshow(cloud, interpolation='lanczos')\n plt.axis('off')\n f = io.BytesIO()\n plt.savefig(f, format='png')\n plt.show()\n image = ImageFile(f)\n return image\n\ndef create_wordcloud_result(request, user):\n try:\n whole_content = DiaryWholeContent.objects.get(client=user)\n except DiaryWholeContent.DoesNotExist:\n return (\"400\", 'https://findme-app.s3.ap-northeast-2.amazonaws.com/home/ubuntu/findme-backend/findme/diary/not_existing_diary.png')\n if whole_content.renew_flag:\n image = whole_content.image\n else:\n image = make_wordcloud(whole_content.whole_content)\n whole_content.renew_flag = True\n whole_content.image.save('wordcloud' + datetime.now().strftime('%Y-%m-%d_%H%M%S') + '.png', image)\n whole_content.save()\n serializer = WholeContentSerializer(whole_content)\n return (\"200\", serializer.data)\n\ndef create_linegraph_result(request, user):\n scores = [score.get(\"sentiment_score\", -1) for score in Diary.objects.filter(client=user).values(\"sentiment_score\")]\n plt.figure(figsize=(8,8))\n if len(scores) == 1:\n x = [x_value for x_value in range(1, len(scores) + 1)]\n plt.plot(x, scores, 'ro')\n elif len(scores) < 7:\n x = [x_value for x_value in range(1, len(scores) + 1)]\n plt.plot(x, scores, 'r')\n else:\n x = [x_value for x_value in range(1, 8)]\n plt.plot(x, scores[-7:], 'r')\n plt.axis([1, 7, -1, 1])\n plt.xlabel('last 7 diary number')\n plt.ylabel('sentiment score')\n fig = plt.gcf()\n file_io = io.BytesIO()\n fig.savefig(file_io, format=\"png\")\n graph_image = ImageFile(file_io)\n try:\n line_graph = LineGraph.objects.get(client=user)\n except LineGraph.DoesNotExist:\n line_graph = LineGraph(client=user)\n line_graph.line_graph.save(\"line_graph\" + datetime.now().strftime('%Y-%m-%d_%H%M%S') + \".png\", graph_image)\n line_graph.save()\n plt.cla()\n serializer = LineGraphSerializer(line_graph)\n return serializer.data\n\nclass Text_extract_wordcloud(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n 감정일기 작성\n\n ---\n # /diaries/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - title : 감정일기 제목\n - content : 감정일기 내용\n \"\"\"\n serializer = DiarySerializer(data=request.data)\n if serializer.is_valid():\n\n today= datetime.now().strftime('%Y-%m-%d')\n is_exist = Diary.objects.filter(client=request.user).filter(create_date=today)\n if len(is_exist)>0:\n return Response(\"Today Diary Existed\", status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\n\n text = request.data['content'].encode('euc-kr').decode('euc-kr')\n # analyze sentiment\n credentials = service_account.Credentials.from_service_account_file(os.path.abspath('.') + '/diary/capstone-ed11e4ac6a67.json')\n client = language_v1.LanguageServiceClient(credentials=credentials)\n document = language_v1.Document(content=text, type_=language_v1.Document.Type.PLAIN_TEXT)\n sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment\n # Diary Model \n diary = Diary(title=request.data.get('title'), content=request.data.get('content'), client=request.user, create_date=datetime.now().strftime('%Y-%m-%d'), sentiment_score=sentiment.score)\n diary.save()\n # Whole Content Model Refresh\n try:\n pre_content = DiaryWholeContent.objects.get(client=request.user)\n pre_content.whole_content += text\n pre_content.renew_flag = False\n pre_content.save()\n except DiaryWholeContent.DoesNotExist:\n diary_whole_content = DiaryWholeContent(client=request.user, whole_content=request.data.get('content'), renew_flag=False)\n diary_whole_content.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n def get(self, request):\n \"\"\"\n 감정일기 조회\n\n ---\n # /diaries/\n ## headers\n - Authorization : Token \"key 값\" \n \"\"\"\n diary = Diary.objects.filter(client=request.user)\n serializer = DiaryListSerializer(diary, many=True)\n return Response(serializer.data,status=status.HTTP_200_OK)\n \n def delete(self,request,**kwargs):\n \"\"\"\n 감정일기 삭제\n\n ---\n # /diaries/<id:int>/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n\n \"\"\"\n if request.user.user_type != '0':\n return Response(\"Only Client can delete Task\", status=status.HTTP_403_FORBIDDEN)\n\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n diary_id = kwargs.get('id')\n diary_obj = Diary.objects.get(id=diary_id)\n diary_obj.delete()\n return Response(\"Diary was deleted\", status=status.HTTP_200_OK)\n def put(self,request,**kwargs):\n \"\"\"\n 감정일기 수정\n\n ---\n # /diaries/<id:int>/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n\n ## body parameter\n - content : 수정될 내용\n\n \"\"\"\n if request.user.user_type != '0':\n return Response(\"Only Client can modify Task\", status=status.HTTP_403_FORBIDDEN)\n\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n diary_id = kwargs.get('id')\n try:\n diary_obj = Diary.objects.get(id=diary_id)\n except:\n return Response(\"Diary not Found\", status=status.HTTP_400_BAD_REQUEST)\n\n content = request.data.get(\"content\")\n diary_obj.content= content\n diary_obj.save()\n return Response(\"Diary was updated\", status=status.HTTP_200_OK)\nclass Whole_content_to_wordcloud(APIView):\n\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n 워드클라우드 생성\n\n ---\n # /whole_content/\n ## headers\n - Authorization : Token \"key 값\" \n \"\"\"\n\n exist_status, data = create_wordcloud_result(request, request.user)\n if exist_status == '200':\n return Response(data,status=status.HTTP_201_CREATED)\n return Response(data, status=status.HTTP_200_OK)\n \n def get(self, request):\n \"\"\"\n 워드클라우드 조회\n\n ---\n # /whole_content/\n ## headers\n - Authorization : Token \"key 값\" \n ## body parameter\n - client : 내담자 이메일\n\n \"\"\"\n client_email = request.GET.get('client')\n client = User.objects.get(email=client_email)\n exist_status, data = create_wordcloud_result(request, client)\n if exist_status == '200':\n return Response(data,status=status.HTTP_200_OK)\n return Response(data, status=status.HTTP_200_OK) \n\nclass Text_extract_linegraph(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n 꺾은선그래프 생성\n\n ---\n # /linegraph/\n ## headers\n - Authorization : Token \"key 값\" \n \n \"\"\"\n\n data = create_linegraph_result(request, request.user)\n return Response(data,status=status.HTTP_201_CREATED)\n \n def get(self, request):\n \"\"\"\n 꺾은선그래프 조회\n\n ---\n # /linegraph/\n ## headers\n - Authorization : Token \"key 값\" \n ## body parameter\n - client : 내담자 이메일\n\n \"\"\"\n client_email = request.GET.get('client')\n client = User.objects.get(email=client_email)\n data = create_linegraph_result(request, client)\n return Response(data,status=status.HTTP_200_OK)\n\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.6730769276618958, "avg_line_length": 40.70000076293945, "blob_id": "969c1e2834014850560779a835a3284823613842", "content_id": "33bb3cc509ba67e10a3293f26beeeeaf4498f1f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 106, "num_lines": 10, "path": "/findme/review/urls.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from . import views\nfrom django.urls import path\n\n\nurlpatterns = [\n path('', views.Review_upload.as_view(), name='review_upload'),\n path('counselors/<int:id>/', views.Review_get_by_counselor.as_view(), name='Review_get_by_counselor'),\n path('<int:id>/', views.Review_upload.as_view(), name='Review_upload'),\n path('clients/<int:id>/', views.Review_get_by_client.as_view(), name='Review_get_by_client'),\n]" }, { "alpha_fraction": 0.5977521538734436, "alphanum_fraction": 0.6081041097640991, "avg_line_length": 40.74074172973633, "blob_id": "c07f07a6bb5a7a4268e8e0d6224f7fbe9f50a67e", "content_id": "243f6f513e1c3144a455575f53f893409c8954b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10349, "license_type": "no_license", "max_line_length": 252, "num_lines": 243, "path": "/findme/counsel/views.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.core.files.images import ImageFile\nfrom .models import Counsel, RegisterCounselDate\nfrom .serializer import CounselSerializer, CounselListSerializer,CounselCounselorSerializer, CounselDateSerializer, CounselClientSerializer, CounselPhotoSerializer\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom users.models import User\nfrom django.utils.timezone import now\nimport json\nfrom datetime import datetime\n\nclass Counsel_application(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n 신청서 작성\n\n ---\n # /counsels/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - counselor : 상담사 user\n - major : 전공\n - student_number : 학번\n - phone_number : 핸드폰 번호\n - time_table : 시간표\n - content : 상담 신청 이유\n \"\"\"\n selected_counselor_email= request.data.get(\"counselor\")\n counselor = User.objects.get(email=selected_counselor_email)\n counsel = Counsel(major=request.data.get(\"major\"), client=request.user,counselor=counselor, create_date=now(),phone_number=request.data.get(\"phone_number\"), student_number=request.data.get(\"student_number\"), content=request.data.get(\"content\"))\n serializer = CounselSerializer(counsel)\n if serializer.is_valid: \n counsel.save()\n return Response((serializer.data, counsel.pk), status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n def get(self, request):\n \"\"\"\n 신청서 조회\n\n ---\n # /counsels/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n \"\"\"\n if request.user.user_type==\"1\":\n counsel = Counsel.objects.filter(counselor_id=request.user.id)\n\n elif request.user.user_type==\"0\":\n counsel = Counsel.objects.filter(client_id=request.user.id)\n serializer = CounselListSerializer(counsel, many=True)\n return Response(serializer.data,status=status.HTTP_200_OK)\n\n def delete(self, request, **kwargs):\n \"\"\"\n 신청서 삭제\n\n ---\n # /counsels/<id:int>/?counsel_date_id=\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## query parameter\n - counsel_date_id : 신청 수락시 상담 id, 신청 보류시 -1\n\n \"\"\"\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n\n counsel_id = kwargs.get('id')\n try:\n counsel_obj = Counsel.objects.get(id=counsel_id)\n \n\n except:\n return Response(\"Counsel not found\", status=status.HTTP_400_BAD_REQUEST)\n\n if str(counsel_obj.counselor)== str(request.user.email):\n #parameter로 받아온 counseldate 의 id값으로 해당 counseldate 에 데이터 넣어주기\n if request.query_params.get('counsel_date_id')=='-1':\n counsel_obj.delete()\n return Response(\"Counsel was deleted\", status=status.HTTP_200_OK)\n\n else:\n counseldate = RegisterCounselDate.objects.get(id= int(request.query_params.get('counsel_date_id')))\n counseldate.counselor= counsel_obj.counselor\n counseldate.client=counsel_obj.client\n counseldate.major=counsel_obj.major\n counseldate.student_number=counsel_obj.student_number\n counseldate.phone_number=counsel_obj.phone_number\n counseldate.time_table=counsel_obj.time_table\n counseldate.content=counsel_obj.content\n counseldate.save()\n counsel_obj.delete()\n return Response(\"Counsel was deleted\", status=status.HTTP_200_OK)\n\n \n else:\n return Response(\"Can only Delete your own counsel applications\",status=status.HTTP_403_FORBIDDEN)\n\n def put(self, request, **kwargs):\n \"\"\"\n 신청서 수정\n\n ---\n # /counsels/<id:int>/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n \"\"\"\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n counsel_id = kwargs.get('id')\n try:\n counsel_obj = Counsel.objects.get(id=counsel_id)\n except:\n return Response(\"Counsel not found\", status=status.HTTP_400_BAD_REQUEST)\n\n if str(counsel_obj.client)== str(request.user.email):\n selected_counselor_email= request.data.get(\"counselor\")\n counselor = User.objects.get(email=selected_counselor_email)\n counsel_obj.counselor=counselor\n\n counsel_obj.content = request.data.get(\"content\")\n counsel_obj.phone_number=request.data.get(\"phone_number\")\n counsel_obj.student_number=request.data.get(\"student_number\")\n counsel_obj.major=request.data.get(\"major\")\n counsel_obj.time_table = request.data.get(\"time_table\")\n\n counsel_obj.save()\n return Response(\"Counsel was updated\", status=status.HTTP_200_OK)\n\n else:\n return Response(\"Can only Modify your own counsel application\",status=status.HTTP_403_FORBIDDEN)\n \n \n counsel = Counsel(major=request.data.get(\"major\"), client=request.user,counselor=counselor, create_date=now(),phone_number=request.data.get(\"phone_number\"), student_number=request.data.get(\"student_number\"), content=request.data.get(\"content\"))\n serializer = CounselSerializer(counsel)\n if serializer.is_valid: \n counsel.save()\n return Response((serializer.data, counsel.pk), status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass CounselPhoto(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request, **kwargs):\n\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n serializer = CounselPhotoSerializer(data=request.data)\n\n if serializer.is_valid():\n counsel = Counsel.objects.get(pk=kwargs.get(\"id\"))\n time_table = request.data.get(\"time_table\")\n counsel.time_table.save(\"time_table\" + datetime.now().strftime('%Y-%m-%d_%H%M%S') + \".png\", time_table)\n counsel.save()\n return Response(\"Counsel time table was updated\", status=status.HTTP_201_CREATED)\n import pprint\n pprint.pprint(serializer.errors)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass CounselDate(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n \n def post(self, request):\n \"\"\"\n 상담 등록\n\n ---\n # /counsels/date/\n ## headers\n - Authorization : Token\n ## body parameter\n - client : 내담자 이메일 [ex> [email protected]]\n - counsel_date : 상담 날짜 [ex> 2020-10-30T20:38:59Z]\n \"\"\"\n serializer = CounselDateSerializer(data=request.data)\n if serializer.is_valid():\n selected_client_email = request.data.get(\"client\")\n client = User.objects.get(email=selected_client_email)\n counsel_date1= RegisterCounselDate.objects.create(counselor=request.user, client=client)\n counsel_date_id = str(counsel_date1)[28:-1]\n return Response(data={\"id\":counsel_date_id} ,status=status.HTTP_201_CREATED)\n import pprint\n pprint.pprint(serializer.errors)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n def get(self, request):\n \"\"\"\n 등록된 상담 조회\n \n ---\n # /counsels/date/\n ## headers\n - Authorization : Token\n \"\"\"\n if request.user.user_type==\"1\":\n clients = RegisterCounselDate.objects.filter(counselor=request.user)\n if not clients.exists():\n return Response('Registered counsel does not exist',status=status.HTTP_200_OK)\n serializer = CounselClientSerializer(clients, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n counselor = RegisterCounselDate.objects.filter(client=request.user)\n if not counselor.exists():\n return Response('Registered counsel does not exist',status=status.HTTP_200_OK)\n serializer = CounselCounselorSerializer(counselor, many=True)\n return Response(serializer.data,status=status.HTTP_200_OK)\n \n def delete(self, request,**kwargs):\n \"\"\"\n 등록된 상담 삭제\n \n ---\n # /counsels/date/<id:int>/\n ## headers\n - Authorization : Token\n \"\"\"\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n registered_counsel_id = kwargs.get('id')\n try:\n registered_counsel_obj = RegisterCounselDate.objects.get(id=registered_counsel_id)\n except:\n return Response(\"Registered Counsel not found\", status=status.HTTP_400_BAD_REQUEST)\n if str(registered_counsel_obj.client)== str(request.user.email):\n registered_counsel_obj.delete()\n return Response(\"Registered Counsel was deleted\", status=status.HTTP_200_OK)\n else:\n return Response(\"Can only Delete your own registered Counsel\",status=status.HTTP_403_FORBIDDEN)\n" }, { "alpha_fraction": 0.7005347609519958, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 30.16666603088379, "blob_id": "be8e1cd57ee20e4c7d582e57e6589ba632847ea6", "content_id": "c80fcb4c5ce8473e812ac7dea921e013e7817d9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 187, "license_type": "no_license", "max_line_length": 71, "num_lines": 6, "path": "/findme/voice/models.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Voice(models.Model):\n voice = models.FileField(upload_to=\"voice/\", blank=True ,null=True)\n text = models.CharField(max_length=10000, null=True)\n" }, { "alpha_fraction": 0.5169230699539185, "alphanum_fraction": 0.709538459777832, "avg_line_length": 17.258426666259766, "blob_id": "441600bd126d121f06026286681a00ab24af3656", "content_id": "ed5985f9c35e13c58962a4f8d956c1a2333c3625", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1625, "license_type": "no_license", "max_line_length": 38, "num_lines": 89, "path": "/findme/requirement.txt", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "asgiref==3.2.10\nattrs==20.2.0\nazure-cognitiveservices-speech==1.14.0\nbcrypt==3.2.0\nbeautifulsoup4==4.6.0\nboto3==1.16.6\nbotocore==1.19.6\ncached-property==1.5.2\ncachetools==4.1.1\ncertifi==2020.6.20\ncffi==1.14.3\nchardet==3.0.4\ncolorama==0.4.4\ncoreapi==2.3.3\ncoreschema==0.0.4\ncryptography==3.2.1\ncycler==0.10.0\ndataclasses==0.7\ndefusedxml==0.6.0\ndistro==1.5.0\nDjango==3.1.2\ndjango-allauth==0.42.0\ndjango-cors-headers==3.5.0\ndjango-rest-auth==0.9.5\ndjango-storages==1.10.1\ndjangorestframework==3.12.1\ndocker==4.3.1\ndocker-compose==1.27.4\ndockerpty==0.4.1\ndocopt==0.6.2\ndrf-yasg==1.20.0\ngoogle-api-core==1.23.0\ngoogle-auth==1.22.1\ngoogle-cloud-language==2.0.0\ngoogleapis-common-protos==1.52.0\ngrpcio==1.33.1\ngunicorn==20.0.4\nidna==2.10\nimportlib-metadata==2.0.0\ninflection==0.5.1\nitypes==1.2.0\nJinja2==2.11.2\njmespath==0.10.0\nJPype1==1.1.1\njsonschema==3.2.0\nkiwisolver==1.2.0\nkonlpy==0.5.2\nlibcst==0.3.13\nlxml==4.6.1\nMarkupSafe==1.1.1\nmatplotlib==3.3.2\nmypy-extensions==0.4.3\nmysqlclient==2.0.1\nnumpy==1.19.2\noauthlib==3.1.0\npackaging==20.4\nparamiko==2.7.2\nPillow==8.0.1\nproto-plus==1.11.0\nprotobuf==3.13.0\npyasn1==0.4.8\npyasn1-modules==0.2.8\npycparser==2.20\nPyNaCl==1.4.0\npyparsing==2.4.7\npyrsistent==0.17.3\nPySocks==1.7.1\npython-dateutil==2.8.1\npython-dotenv==0.15.0\npython3-openid==3.2.0\npytz==2020.1\nPyYAML==5.3.1\nrequests==2.24.0\nrequests-oauthlib==1.3.0\nrsa==4.6\nruamel.yaml==0.16.12\nruamel.yaml.clib==0.2.2\ns3transfer==0.3.3\nsix==1.15.0\nsqlparse==0.4.1\ntexttable==1.6.3\ntweepy==3.9.0\ntyping-extensions==3.7.4.3\ntyping-inspect==0.6.0\nuritemplate==3.0.1\nurllib3==1.25.10\nwebsocket-client==0.57.0\nwordcloud==1.8.0\nzipp==3.4.0\n" }, { "alpha_fraction": 0.7149758338928223, "alphanum_fraction": 0.7185990214347839, "avg_line_length": 44.94444274902344, "blob_id": "d83a7a05581f77dbbb55aed69026828a6d170f93", "content_id": "358e6e65fd7e90989ffcac1ac6957c0961e85f0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 832, "license_type": "no_license", "max_line_length": 114, "num_lines": 18, "path": "/findme/task/models.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.conf import settings\n\ndef upload_image_to(instance, filename):\n import os\n filename_base, filename_ext = os.path.splitext(filename)\n return '%s%s' % (str(filename_base),filename_ext)\n\nclass Task(models.Model):\n question = models.CharField(max_length=200, blank=True)\n client = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n counselor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n create_date = models.DateTimeField(auto_now_add=True, null=True)\n video = models.FileField(upload_to=upload_image_to, blank=True ,null=True)\n graph = models.ImageField(upload_to=\"sentiment_graph\", blank=True, null=True) \n \n class Meta:\n verbose_name = '영상'\n\n" }, { "alpha_fraction": 0.705567479133606, "alphanum_fraction": 0.705567479133606, "avg_line_length": 31.241378784179688, "blob_id": "ad8ec54691370d306103cbe253ce9dda47c1b3d3", "content_id": "99b94842d4d1ab1e13e9154157330bb6538fe535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 934, "license_type": "no_license", "max_line_length": 92, "num_lines": 29, "path": "/findme/review/serializers.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import Review\nfrom rest_framework.serializers import ModelSerializer,ReadOnlyField\nfrom pytz import timezone\n\nclass ReviewSerializer(serializers.ModelSerializer):\n class Meta:\n model = Review\n fields = '__all__'\n\n\nclass ReviewListSerializer(serializers.ModelSerializer):\n id = ReadOnlyField()\n\n create_date = serializers.SerializerMethodField()\n counselor_name= serializers.SerializerMethodField()\n client_name= serializers.SerializerMethodField()\n\n def get_counselor_name(self,obj):\n return obj.counselor.username\n\n def get_client_name(self,obj):\n return obj.client.username\n \n def get_create_date(self, obj):\n return obj.create_date.astimezone(timezone('Asia/Seoul')).strftime('%Y-%m-%d %H:%M')\n class Meta:\n model = Review\n fields = ('id','counselor_name','client_name', 'create_date', 'content')" }, { "alpha_fraction": 0.6909975409507751, "alphanum_fraction": 0.6909975409507751, "avg_line_length": 36.3636360168457, "blob_id": "5b1b0d9087068ca687f25143e0217490bd48a74c", "content_id": "70a2f97330818aeb25a51424b454e81d734265b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 94, "num_lines": 11, "path": "/findme/counsel/urls.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from . import views\nfrom django.urls import path\n\n\nurlpatterns = [\n path('', views.Counsel_application.as_view(), name='counsel_application'),\n path('<int:id>/', views.Counsel_application.as_view(), name='delete_counsel_application'),\n path('date/', views.CounselDate.as_view(), name='update_counsel_for_date'),\n path('photo/<int:id>/', views.CounselPhoto.as_view(), name=\"update_counsel_photo\")\n\n]\n" }, { "alpha_fraction": 0.6791530847549438, "alphanum_fraction": 0.6889250874519348, "avg_line_length": 37.3125, "blob_id": "b5c403a6e46fea59b0893fff1349ebea410d3e02", "content_id": "19e1c77dd0f6e4d57a545359d4d9a83d92bc2b18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 114, "num_lines": 16, "path": "/findme/review/models.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.conf import settings\n\n\nclass Review(models.Model):\n client = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=False)\n counselor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n create_date = models.DateTimeField(auto_now_add=True, null=True)\n content = models.CharField(max_length=1000, null=True)\n\n \n class Meta:\n verbose_name = '후기'\n def __str__(self):\n now = str(self.create_date)\n return self.client.username+' 님의 후기'+\" \"+now[:10]\n\n" }, { "alpha_fraction": 0.5781780481338501, "alphanum_fraction": 0.5873391628265381, "avg_line_length": 41.427947998046875, "blob_id": "7409f0848b7a596c1ce8fecd5034efaadbca2c65", "content_id": "e6eae51981325512e747c7beedbf1c18ad08816a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10163, "license_type": "no_license", "max_line_length": 121, "num_lines": 229, "path": "/findme/diary/tests.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "import sys\nimport io\nfrom PIL import Image\nsys.path.append(\"..\")\nimport json \nimport tempfile\nfrom django.core.files.images import ImageFile\nfrom django.test import TestCase,Client\nfrom .models import Diary,DiaryWholeContent,LineGraph\nfrom django.db.models.fields.files import ImageField\nfrom users.models import User\nfrom .serializers import DiarySerializer,WholeContentSerializer ,DiaryListSerializer\nfrom rest_framework.authtoken.models import Token\nfrom django.db.models.fields.related import ForeignKey\nfrom datetime import datetime\n\nclass DiaryModelTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n\n # Set up non-modified objects used by all test methods\n Diary.objects.create(content='콘텐트', title='제목',client=self.user)\n \n def test_client_is_foreignkey(self):\n diary=Diary.objects.get(id=1)\n client = diary._meta.get_field('client')\n self.assertEquals(type(client),ForeignKey)\n\n def test_sentiment_score_label(self):\n diary=Diary.objects.get(id=1)\n field_label = diary._meta.get_field('sentiment_score').verbose_name\n self.assertEquals(field_label, '텍스트감정분석결과')\n\n def test_title_max_length(self):\n diary = Diary.objects.get(id=1)\n max_length = diary._meta.get_field('title').max_length\n self.assertEquals(max_length, 100)\n def test_content_max_length(self):\n diary = Diary.objects.get(id=1)\n max_length = diary._meta.get_field('content').max_length\n self.assertEquals(max_length, 1000)\n\n def test_diary_meta_verbose_name(self):\n diary = Diary.objects.get(id=1)\n self.assertEquals('감정일기', diary._meta.verbose_name)\n\nclass DiaryWholeContentModelTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n\n DiaryWholeContent.objects.create(whole_content='전체 내용',client=self.user)\n def test_client_is_foreignkey(self):\n diary_whole_content=DiaryWholeContent.objects.get(id=1)\n client = diary_whole_content._meta.get_field('client')\n self.assertEquals(type(client),ForeignKey)\n\n def test_renew_flag_default_is_False(self):\n diary_whole_content = DiaryWholeContent.objects.get(id=1)\n default = diary_whole_content.renew_flag\n self.assertFalse(default)\n\n def test_whole_content_max_length(self):\n diary_whole_content = DiaryWholeContent.objects.get(id=1)\n max_length = diary_whole_content._meta.get_field('whole_content').max_length\n self.assertEquals(max_length, 10000)\n\n def test_diary_meta_verbose_name(self):\n whole_diary = DiaryWholeContent.objects.get(id=1)\n self.assertEquals('감정일기 내용 모음', whole_diary._meta.verbose_name)\n\nclass LineGraphModelTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n \n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n LineGraph.objects.create(line_graph=image_mock,client=self.user)\n\n def test_client_is_foreignkey(self):\n line_graph=LineGraph.objects.get(id=1)\n client = line_graph._meta.get_field('client')\n self.assertEquals(type(client),ForeignKey)\n\n\n def test_line_graph_is_image_file(self):\n line_graph = LineGraph.objects.get(id=1)\n line_graph_img = line_graph._meta.get_field('line_graph')\n self.assertEquals(type(line_graph_img), ImageField)\n\n def test_line_graph_meta_verbose_name(self):\n line_graph = LineGraph.objects.get(id=1)\n self.assertEquals('꺾은선그래프 - 감정일기', line_graph._meta.verbose_name)\n\nclass SerializerTest(TestCase):\n def generate_photo_file(self):\n file = io.BytesIO()\n image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))\n image.save(file, 'png')\n file.name = 'test.png'\n file.seek(0)\n return file\n\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n\n # Set up non-modified objects used by all test methods\n Diary.objects.create(content='콘텐트', title='제목',client=self.user)\n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n DiaryWholeContent.objects.create(client= self.user, whole_content=\"아아아아어러러럴이잉\",image=image_mock,renew_flag=True)\n \n def test_diary_serializer(self):\n serializer = DiarySerializer(data= Diary.objects.values().all().first())\n if not serializer.is_valid():\n import pprint\n pprint.pprint(serializer.errors)\n self.assertEqual(serializer.is_valid(), True)\n def test_whole_content_serializer(self):\n #현재 S3에 올라가있는 이미지라서 에러가 뜨는듯함\n serializer = WholeContentSerializer(data= DiaryWholeContent.objects.values().all())\n # if not serializer.is_valid():\n # import pprint\n # pprint.pprint(serializer.errors)\n self.assertEqual(serializer.is_valid(), False)\n\nclass DiaryWordCloudTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩',\n user_type=0 \n )\n\n Diary.objects.create(content='콘텐트', title='제목',client=self.user,create_date= datetime.now().strftime('%Y-%m-%d'))\n\n def setUp(self):\n token, created = Token.objects.get_or_create(user=self.user) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n # 다이어리 업로드 + 워드클라우드 생성 test\n def test_A_text_extract_wordcloud_post(self):\n url = '/diaries/' \n dairy_data = { \n 'title':'오늘의 할일',\n 'content':'테스트 드리븐 개발은 나를 성장시켜주고 새로운 것을 배우게 도와주는 즐거운 일이다. 어렵고 복잡하지만, 잘 이겨내서 좋은 개발자가 될것이다.'\n }\n response= self.client.post(url,data=dairy_data)\n self.assertEquals(response.status_code,405)\n self.assertEquals(response.data,'Today Diary Existed')\n\n # 다이어리 워드클라우드 가져오기 test\n def test_B_text_extract_wordcloud_get_by_user(self):\n url='/diaries/'\n response= self.client.get(url,content_type='application/json')\n self.assertEqual(response.status_code,200)\n\n # 다이어리 삭제 test\n def test_C_text_extract_wordcloud_delete_by_id(self):\n url='/diaries/'\n kwargs=str(Diary.objects.values().first()['id'])\n response= self.client.delete(url+kwargs+'/',content_type='application/json')\n self.assertEqual(response.status_code,200)\n \n\n\nclass LineGraphTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n\n Diary.objects.create(content='1일차', title='제목1',client=self.user,sentiment_score=-0.1)\n Diary.objects.create(content='2일차', title='제목2',client=self.user,sentiment_score=0.1)\n Diary.objects.create(content='3일차', title='제목3',client=self.user,sentiment_score=-0.2)\n Diary.objects.create(content='4일차', title='제목4',client=self.user,sentiment_score=0.6)\n Diary.objects.create(content='5일차', title='제목5',client=self.user,sentiment_score=0.2)\n Diary.objects.create(content='6일차', title='제목6',client=self.user,sentiment_score=0.9)\n Diary.objects.create(content='7일차', title='제목7',client=self.user,sentiment_score=0.8)\n\n def setUp(self):\n token, created = Token.objects.get_or_create(user=self.user) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n def test_text_extract_linegraph_post(self):\n response= self.client.post('/linegraph/')\n self.assertEqual(response.status_code,201)\n self.assertEqual(response.data.get('line_graph')[:10],'https://fi')\n\n def test_text_extract_linegraph_get(self):\n\n response= self.client.get('/linegraph/',data={\"client\":\"[email protected]\"})\n self.assertEqual(response.status_code,200)\n\n\nclass WholeContentTest(TestCase):\n\n\n def Test_whole_content_post(self):\n \n response= self.client.post('/',data=review_info)\n self.assertEqual(response.status_code,201)\n def Test_whole_content_get(self):\n\n response= self.client.get('/reviews/'+kwargs+'/',content_type='application/json')\n self.assertEqual(response.status_code,201)" }, { "alpha_fraction": 0.5875746607780457, "alphanum_fraction": 0.59617680311203, "avg_line_length": 31.944881439208984, "blob_id": "01e0f349625578d8179fc04c3624cb23bf02d8de", "content_id": "22151325f2550741b706a6ceb83aacd1335c1fee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4293, "license_type": "no_license", "max_line_length": 107, "num_lines": 127, "path": "/findme/review/views.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .serializers import ReviewSerializer,ReviewListSerializer\nfrom rest_framework.views import APIView\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom users.models import User\nfrom datetime import datetime\nfrom .models import Review\nfrom django.forms.models import model_to_dict\nimport json\n\nclass Review_upload(APIView):\n \n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n 리뷰 생성\n\n ---\n # /reviews/\n ## headers\n - Authorization : Token \"key 값\" \n ## body parameter\n - counselor : 상담사 user\n - client : 내담자 user\n - content : 후기 내용\n\n \"\"\"\n\n selected_counselor_email= request.data.get(\"counselor\")\n counselor = User.objects.get(email=selected_counselor_email)\n content= request.data.get(\"content\")\n review = Review(client=request.user,counselor=counselor,create_date=datetime.now(),content=content)\n serializer=ReviewSerializer(review)\n if serializer.is_valid:\n\n review.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def put(self, request):\n \"\"\"\n 리뷰 수정\n\n ---\n # /reviews/\n ## headers\n - Authorization : Token \"key 값\" \n ## body parameter\n - review_id : 후기 id 값\n - content : 후기 내용\n\n \"\"\"\n try:\n selected_review = Review.objects.get(id=request.data.get(\"review_id\"))\n except : \n return Response('Review not exist' , status=status.HTTP_400_BAD_REQUEST)\n content= request.data.get(\"content\")\n selected_review.content =content\n try:\n selected_review.save()\n except : \n return Response( 'Review updated failed' ,status=status.HTTP_400_BAD_REQUEST)\n\n return Response( 'Review updated success' ,status=status.HTTP_201_CREATED)\n\n def delete(self, request, **kwargs):\n \"\"\"\n 리뷰 삭제\n\n ---\n # /reviews/<id:int>/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n \"\"\"\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n review_id = kwargs.get('id')\n try:\n review_obj = Review.objects.get(id=review_id)\n review_obj.delete()\n return Response(\"Review was deleted\", status=status.HTTP_200_OK)\n except:\n return Response(\"Review not Found\", status=status.HTTP_400_BAD_REQUEST)\n\n\nclass Review_get_by_counselor(APIView):\n def get(self, request,**kwargs):\n \"\"\"\n 특정 상담사의 리뷰 조회\n\n ---\n # /reviews/counselors/<int:id>/\n ## headers\n - Authorization : Token \"key 값\" \n \"\"\"\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n counselor = User.objects.get(id=kwargs.get('id'))\n review = Review.objects.filter(counselor=counselor)\n serializer = ReviewListSerializer(review, many=True)\n \n return Response(serializer.data,status=status.HTTP_200_OK)\n\nclass Review_get_by_client(APIView):\n def get(self, request,**kwargs):\n \"\"\"\n 특정 내담자의 리뷰 조회\n\n ---\n # /reviews/clients/<id : int>\n ## headers\n - Authorization : Token \"key 값\" \n \"\"\"\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n client = User.objects.get(id=kwargs.get('id'))\n review = Review.objects.filter(client=client)\n serializer = ReviewListSerializer(review, many=True)\n return Response(serializer.data,status=status.HTTP_200_OK)\n\n" }, { "alpha_fraction": 0.5853080749511719, "alphanum_fraction": 0.5947867035865784, "avg_line_length": 33.698631286621094, "blob_id": "e6bf76ee78068080423800367d35a435dcda7aa6", "content_id": "33c13a6bfab04af30a4042ac3f0fc7a1878094ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2644, "license_type": "no_license", "max_line_length": 116, "num_lines": 73, "path": "/findme/users/tests.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.test import TestCase, Client\nfrom .models import User\nfrom rest_framework.authtoken.models import Token\nfrom django.core.files.images import ImageFile\nimport tempfile\nfrom PIL import Image\nimport json\nfrom datetime import datetime\nimport base64\n\nclass UserTest(TestCase):\n # test용 데이터\n def setUp(self):\n self.client = Client()\n \n self.user=User.objects.create(email=\"[email protected]\")\n self.user.set_password('abcd123!!!')\n self.user.save()\n self.user_id = self.user.id\n token, created = Token.objects.get_or_create(user=self.user) \n\n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n # 회원가입 test\n def test_A_user_registration(self):\n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n regi_info ={\n \"username\": \"testname\",\n \"email\":\"[email protected]\",\n \"user_type\":\"1\",\n \"password1\":\"abcd123!!!\",\n \"password2\":\"abcd123!!!\",\n \"image\":image_mock \n }\n response= self.client.post('/rest-auth/registration/',data=regi_info)\n self.assertEqual(response.status_code,201)\n self.assertEqual(len(response.json().get(\"key\"))>10,True)\n # 이메일 중복 test\n def test_B_redundant_check(self):\n response = self.client.get('/users/email',data={'email':'[email protected]'})\n self.assertEqual(response.status_code, 403) \n\n\n #로그인 test\n def test_C_user_login(self):\n #smoke test\n login_info={\n 'email' : '[email protected]',\n 'password' : 'abcd123!!!',\n 'user_type': 1\n }\n response = self.client.post('/rest-auth/login/',data=login_info)\n self.assertEqual(response.status_code,200)\n self.assertEqual(len(response.json().get(\"key\"))>10,True)\n\n #유저정보 업데이트 test \n def test_D_user_information_update(self):\n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n\n data={\n 'introduce': \"저는 첫번째 상담사 입니다.\",\n 'username' : '김상담',\n 'career' : 'A대학 심리상담과 \\n B대학원 심리상담 석사과정',\n 'user_type' : '1'\n }\n response= self.client.put('/users/'+str(self.user_id)+'/',json.dumps(data), content_type='application/json')\n self.assertEqual(response.status_code,200)\n\n def test_E_get_user_info(self):\n response= self.client.get('/users/selfinfos/')\n self.assertTrue(0 <= response.data['id'])" }, { "alpha_fraction": 0.5055088400840759, "alphanum_fraction": 0.5129023194313049, "avg_line_length": 41.574073791503906, "blob_id": "120a670939c8d10b3683c6afd80be596c091878b", "content_id": "d59a8aa109fe65502443f24fd4c84d3c911c258b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6978, "license_type": "no_license", "max_line_length": 96, "num_lines": 162, "path": "/findme/task/tests.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nimport mock\nfrom django.core.files import File\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import TestCase,Client\nfrom users.models import User\nfrom .models import Task\nfrom .serializers import TaskSerializer,TaskQuestionSerializer\nfrom django.db.models.fields.files import ImageField\nfrom rest_framework.authtoken.models import Token\nfrom django.db.models.fields.related import ForeignKey\nfrom django.core.files.images import ImageFile\nimport tempfile\nfrom django.db.models.fields.files import FileField\nimport json \nfrom PIL import Image\nfrom datetime import datetime\nfrom django.db.models.fields import FloatField\nclass TaskModelTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='김상담',\n user_type=1 \n )\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='김내담',\n user_type=1 \n )\n self.video = SimpleUploadedFile(\"file.mp4\", b\"file_content\", content_type=\"video/mp4\")\n\n Task.objects.create(client=self.user_client,counselor=self.user_counselor,question=\"질문\")\n self.task_id = Task.objects.values().first()['id']\n def test_client_is_foreignkey(self):\n task=Task.objects.get(id=self.task_id)\n client = task._meta.get_field('client')\n self.assertEquals(type(client),ForeignKey)\n def test_counselor_is_foreignkey(self):\n task=Task.objects.get(id=self.task_id)\n counselor = task._meta.get_field('counselor')\n self.assertEquals(type(counselor),ForeignKey)\n\n\n\n\nclass SerializerTest(TestCase):\n\n @classmethod\n def setUpTestData(self):\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='김상담',\n user_type=1 \n )\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='김내담',\n user_type=1 \n )\n self.video = SimpleUploadedFile(\"file.mp4\", b\"file_content\", content_type=\"video/mp4\")\n\n Task.objects.create(client=self.user_client,counselor=self.user_counselor,question=\"질문\")\n self.task_id = Task.objects.values().first()['id']\n\n def test_task_serializer(self):\n serializer = TaskSerializer(Task.objects.values().all().first()['video'])\n #어렵다..\n\n\n\n\nclass TaskQuestionTest(TestCase):\n def setUp(self):\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='김상담',\n user_type=1 \n )\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='김내담',\n user_type=1 \n )\n Task.objects.create(client=self.user_client,counselor=self.user_counselor,question=\"질문\")\n\n token, created = Token.objects.get_or_create(user=self.user_counselor) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n \n def test_a_task_question_upload(self):\n url = '/tasks/questions/'\n data={\n \"client\":self.user_client.email,\n \"question\": \"질문입니다.\"\n }\n response =self.client.post(url,data=data)\n self.assertEqual(response.status_code,201)\n\n def test_b_task_question_get(self):\n url = '/tasks/questions/'\n response =self.client.get(url)\n self.assertEqual(response.status_code,200)\n\n def test_c_task_question_for_counselor_get(self):\n url = \"/tasks/questions_counselor/?client=\"+self.user_client.email\n response =self.client.get(url)\n self.assertEqual(response.status_code,200)\n\n\nclass TaskVideoTest(TestCase):\n\n @classmethod\n def setUpTestData(self):\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='김상담',\n user_type=1 \n )\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='김내담',\n user_type=1 \n )\n\n Task.objects.create(client=self.user_client,counselor=self.user_counselor,question=\"질문\")\n self.task_id = Task.objects.values().first()['id']\n\n def setUp(self):\n token, created = Token.objects.get_or_create(user=self.user_client) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n def test_a_task_question_get(self):\n url = '/tasks/questions/'\n response =self.client.get(url)\n self.assertEqual(response.status_code,200)\n\n def test_b_task_video_upload(self):\n url = \"/tasks/videos/\"+str(self.task_id) + \"/022db29c-d0e2-11e5-bb4c-60f81dca7676/\"\n self.video = SimpleUploadedFile(\"file.mp4\", b\"file_content\", content_type=\"video/mp4\")\n response =self.client.post(url,data={\"video\":self.video})\n self.assertEqual(response.status_code,201)\n\n def test_c_task_video_processing_upload(self):\n url =\"/tasks/process_videos/\"+str(self.task_id)+\"/\"\n response =self.client.get(url)\n self.assertEqual(\"Processed Video is not exist\" in response.data,True)\n\n \n def test_d_task_video_delete(self):\n task_id = Task.objects.values().first()['id']\n url = '/tasks/'+str(task_id)+\"/\"\n response =self.client.delete(url)\n self.assertEqual(response.status_code,200)\n\n" }, { "alpha_fraction": 0.6914153099060059, "alphanum_fraction": 0.70649653673172, "avg_line_length": 46.75, "blob_id": "652b3ddbda16dc9e762157974a9879dbfd5b7280", "content_id": "64cf9d604e9eb95df4deaded7bd809920eab5d88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1746, "license_type": "no_license", "max_line_length": 114, "num_lines": 36, "path": "/findme/counsel/models.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.conf import settings\n\n\ndef upload_image_to(instance, filename):\n import os\n filename_base, filename_ext = os.path.splitext(filename)\n return 'image/timetable/%s%s' % (filename_base,filename_ext )\n\nclass Counsel(models.Model):\n client = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n counselor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n major = models.CharField(max_length=100, null=True)\n student_number = models.CharField(max_length=100, null=True)\n phone_number = models.CharField(max_length=100, null=True)\n time_table = models.ImageField(upload_to=upload_image_to, blank=True, null=True)\n create_date = models.DateTimeField(auto_now_add=True, null=True)\n content = models.CharField(max_length=100, null=True)\n class Meta:\n verbose_name = '신청서'\n \n # def __str__(self):\n # now = str(self.create_date)\n # return self.client.username+'신청서'+\" \"+now[:10]\n\nclass RegisterCounselDate(models.Model):\n counselor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n client = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=False)\n major = models.CharField(max_length=100, null=True)\n student_number = models.CharField(max_length=100, null=True)\n phone_number = models.CharField(max_length=100, null=True)\n time_table = models.ImageField(upload_to=upload_image_to, blank=True, null=True)\n content = models.CharField(max_length=100, null=True)\n \n class Meta:\n verbose_name = \"등록된 상담\"\n \n" }, { "alpha_fraction": 0.8541666865348816, "alphanum_fraction": 0.8541666865348816, "avg_line_length": 28, "blob_id": "5110f9a65690c5c6fe10881f354f7926f153d596", "content_id": "5ed1623c72d3873b350ca6391f46671acea12df0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 47, "num_lines": 5, "path": "/findme/counsel/admin.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom counsel import models\n\nadmin.site.register(models.Counsel)\nadmin.site.register(models.RegisterCounselDate)" }, { "alpha_fraction": 0.7023004293441772, "alphanum_fraction": 0.7023004293441772, "avg_line_length": 51.78571319580078, "blob_id": "6a09878b067fa460de05ef0e0bab9bf3d0f87bb9", "content_id": "68da6adf758efe03305705e35bfaf6bc067188a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 104, "num_lines": 14, "path": "/findme/task/urls.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from . import views\nfrom django.urls import path\n\n\nurlpatterns = [\n path('videos/<int:id>/<str:uuid>/', views.TaskUpload.as_view(), name='taskUpload'),\n path('', views.TaskDetail.as_view(), name='TaskDetail'),\n path('<int:id>/', views.TaskDetail.as_view(), name='TaskDetail'),\n path('questions/', views.AddTaskQuestion.as_view(), name='TaskQuestion'),\n path('process_videos/<int:id>/', views.VideoProcessing.as_view(), name='VideoProcessing'),\n path('questions_counselor/', views.TaskQuestionForCounselor.as_view(), name=\"QuestionForCounselor\"),\n path('sentiment/', views.GetSentiment.as_view(), name='GetSentiment'),\n path('sentiment_graphs/', views.MakeSentimentLinegraph.as_view(), name='MakeSentimentGraph'),\n]\n" }, { "alpha_fraction": 0.8152173757553101, "alphanum_fraction": 0.8152173757553101, "avg_line_length": 17.399999618530273, "blob_id": "962e3000f6a9254a2cbf3ab432055956ccfc5504", "content_id": "92447f483aaa65a7c879552476d58d3c0cca97c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/findme/task/admin.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom task import models\n\nadmin.site.register(models.Task)\n" }, { "alpha_fraction": 0.5336060523986816, "alphanum_fraction": 0.5392557978630066, "avg_line_length": 34.40689468383789, "blob_id": "c72b8d52f7cdd6a83044225be0d11385be57aa90", "content_id": "a37e33653084505fc58350209b3e63ae24c8a865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5259, "license_type": "no_license", "max_line_length": 107, "num_lines": 145, "path": "/findme/review/tests.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append(\"..\")\nimport json \nfrom django.db.models.fields.related import ForeignKey\nfrom django.test import TestCase,Client\nfrom .models import Review\nfrom users.models import User\nfrom rest_framework.authtoken.models import Token\nclass ReviewModelTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n Review.objects.create(\n client=self.user,\n counselor=self.user,\n content=\"너무좋았어요\"\n )\n Review.objects.create(\n client=self.user,\n counselor=self.user,\n content=\"너무좋았어요\"\n \n )\n self.review_id= Review.objects.values().first()['id']\n\n def test_client_is_foreignkey(self):\n review=Review.objects.get(id=self.review_id)\n client = review._meta.get_field('client')\n self.assertEquals(type(client),ForeignKey)\n def test_counselor_is_foreignkey(self):\n review=Review.objects.get(id=self.review_id)\n counselor = review._meta.get_field('counselor')\n self.assertEquals(type(counselor),ForeignKey)\n\n \n def test_content_max_length(self):\n review = Review.objects.get(id=self.review_id)\n max_length = review._meta.get_field('content').max_length\n self.assertEquals(max_length, 1000)\n\n def test_review_meta_verbose_name(self):\n review = Review.objects.all().first()\n self.assertEquals('후기', review._meta.verbose_name)\n \nclass ReviewTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.review = Review()\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n \n client1 =self.user\n self.review=Review.objects.create(\n client=client1,\n counselor=client1,\n content=\"너무좋았어요\"\n )\n self.review=Review.objects.create(\n client=client1,\n counselor=client1,\n content=\"너무좋았어요\"\n )\n self.review_id= Review.objects.values().first()['id']\n\n def setUp(self):\n token, created = Token.objects.get_or_create(user=self.user) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n\n # 리뷰 업로드 test\n def test_A_review_upload(self):\n \n review_info ={\n \"counselor\":\"[email protected]\",\n \"content\":\"test review content\",\n }\n\n response= self.client.post('/reviews/',data=review_info)\n self.assertEqual(response.status_code,201)\n # 리뷰 수정 test\n def test_B_review_update(self):\n review_info={\n \"review_id\":self.review_id,\n \"content\" :\" 수정됨 \" \n }\n \n response= self.client.put('/reviews/',data=json.dumps(review_info),content_type='application/json')\n self.assertEqual(response.status_code,201)\n self.assertEqual(response.data ,'Review updated success')\n\n #리뷰 삭제 test\n def test_C_review_delete(self):\n \n kwargs=str(self.review_id)\n response= self.client.delete('/reviews/'+kwargs+'/',content_type='application/json')\n self.assertEqual(response.status_code,200)\n\n\n\nclass GETReviewTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.review = Review()\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n \n client1 =self.user\n self.review=Review.objects.create(\n client=client1,\n counselor=client1,\n content=\"너무좋았어요\"\n )\n self.review=Review.objects.create(\n client=client1,\n counselor=client1,\n content=\"너무좋았어요\"\n )\n self.review_id= Review.objects.values().first()['id']\n\n def setUp(self):\n token, created = Token.objects.get_or_create(user=self.user) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n def test_get_review_by_client(self):\n url=\"/reviews/counselors/\"\n kwargs=Review.objects.values().first()['client_id']\n response= self.client.get(url+str(kwargs)+'/',content_type='application/json')\n self.assertEqual(response.status_code,200)\n\n \n def test_get_review_by_client(self):\n url=\"/reviews/clients/\"\n kwargs=Review.objects.values().first()['counselor_id']\n response= self.client.get(url+str(kwargs)+'/',content_type='application/json')\n self.assertEqual(response.status_code,200)" }, { "alpha_fraction": 0.7635135054588318, "alphanum_fraction": 0.7770270109176636, "avg_line_length": 28.799999237060547, "blob_id": "67565bc55f426c9fd446631091684f4e2a16167f", "content_id": "ebbf2c15bad8e471cdd3b0671079bb545c30631f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 148, "license_type": "no_license", "max_line_length": 44, "num_lines": 5, "path": "/pytest.ini", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "[pytest]\nDJANGO_SETTINGS_MODULE = findme.settings\npython_files = tests.py test_*.py *_tests.py\nfilterwarnings =\n ignore::RemovedInDjango40Warning" }, { "alpha_fraction": 0.584762692451477, "alphanum_fraction": 0.591942548751831, "avg_line_length": 48.156864166259766, "blob_id": "58431067642e0af31e28ab03e16add6beec7a5d9", "content_id": "f737e1cb00f1924ebe14a0da6a31022a2592a99c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2567, "license_type": "no_license", "max_line_length": 152, "num_lines": 51, "path": "/findme/task/migrations/0001_initial.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-11-17 18:21\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport task.models\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='Task',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('question', models.CharField(blank=True, max_length=200)),\n ('create_date', models.DateTimeField(auto_now_add=True, null=True)),\n ('video', models.FileField(blank=True, null=True, upload_to=task.models.upload_image_to)),\n ('anger', models.FloatField(blank=True, null=True, verbose_name='화남')),\n ('contempt', models.FloatField(blank=True, null=True, verbose_name='경멸')),\n ('disgust', models.FloatField(blank=True, null=True, verbose_name='역겨움')),\n ('fear', models.FloatField(blank=True, null=True, verbose_name='두려움')),\n ('happiness', models.FloatField(blank=True, null=True, verbose_name='행복')),\n ('neutral', models.FloatField(blank=True, null=True, verbose_name='중립')),\n ('sadness', models.FloatField(blank=True, null=True, verbose_name='슬픔')),\n ('surprise', models.FloatField(blank=True, null=True, verbose_name='놀람')),\n ('client', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ('counselor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': '영상',\n },\n ),\n migrations.CreateModel(\n name='SentimentGraph',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('image', models.ImageField(blank=True, null=True, upload_to='sentiment_graph/')),\n ('client', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': '꺾은선그래프 - 영상감정',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6632652878761292, "alphanum_fraction": 0.6750805377960205, "avg_line_length": 41.318180084228516, "blob_id": "dc1fa7088c1fd0737eb25d6eb6f43bf43a0f7e74", "content_id": "241cc4c5db21102684466665ebcd79dd2550c2ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1876, "license_type": "no_license", "max_line_length": 81, "num_lines": 44, "path": "/findme/users/adapters.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from allauth.account.adapter import DefaultAccountAdapter\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.utils.encoding import force_bytes,force_text\nfrom django.utils.http import urlsafe_base64_decode,urlsafe_base64_encode\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.validators import validate_email\nfrom .token import account_activation_token\nfrom .text import message\nfrom users.models import User\n\nclass CustomUserAccountAdapter(DefaultAccountAdapter):\n\n def save_user(self, request, user, form, commit=True):\n \"\"\"\n Saves a new `User` instance using information provided in the\n signup form.\n \"\"\"\n from allauth.account.utils import user_field\n # data = form.cleaned_data\n # user.username = data.get('username')\n # user.email = data.get('email')\n # user.user_type = data.get('user_type')\n # if 'password1' in data:\n # user.set_password(data['password1'])\n # else:\n # user.set_unusable_password()\n\n user = super().save_user(request, user, form, False)\n user_field(user, 'user_type', request.data.get('user_type'))\n user_field(user, 'introduce', request.data.get('introduce'))\n user_field(user, 'career', request.data.get('career'))\n user.save()\n currnet_site =get_current_site(request)\n domain = \"http://ec2-13-209-32-113.ap-northeast-2.compute.amazonaws.com/\"\n uidb64 = urlsafe_base64_encode(force_bytes(user.email))\n token = account_activation_token.make_token(user)\n message_data= message(domain,uidb64,token)\n mail_title = \"FIND ME 인증 메일 입니다.\"\n mail_to = user.email \n email = EmailMessage(mail_title,message_data,to=[mail_to])\n email.send()\n\n return user\n" }, { "alpha_fraction": 0.7249283790588379, "alphanum_fraction": 0.7277936935424805, "avg_line_length": 36.39285659790039, "blob_id": "44c630f85c23b22d1aa020a4220a260745d30466", "content_id": "0033c0d2db85fab59340a1b5f953ad2c31ba01bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1047, "license_type": "no_license", "max_line_length": 91, "num_lines": 28, "path": "/findme/task/serializers.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom rest_framework.serializers import ModelSerializer,ReadOnlyField\nfrom .models import Task\n\n\nclass TaskSerializer(serializers.ModelSerializer):\n video = serializers.FileField(use_url=True,allow_null=False)\n class Meta:\n model = Task\n fields = ['video']\nclass TaskQuestionSerializer(serializers.ModelSerializer):\n id = ReadOnlyField()\n client_email = ReadOnlyField(source=\"client.email\")\n counselor_username = ReadOnlyField(source=\"counselor.username\")\n counselor_image = ReadOnlyField(source=\"counselor.image.name\")\n question = serializers.CharField(max_length=100)\n\n class Meta:\n model = Task\n fields = ['id', 'question', 'client_email', 'counselor_username','counselor_image']\n\nclass SentimentGraphSerializer(serializers.ModelSerializer):\n client_username = ReadOnlyField(source=\"client.username\")\n graph = serializers.ImageField(use_url=True, allow_null=True)\n\n class Meta:\n model = Task\n fields = ('client_username', 'graph')\n" }, { "alpha_fraction": 0.7528089880943298, "alphanum_fraction": 0.7528089880943298, "avg_line_length": 16.799999237060547, "blob_id": "648573bc7807b48cc175c92ee2e80f55833fbcfe", "content_id": "600aafad5a93eb61fd232ed831e0900e3a1110dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 89, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/findme/counsel/apps.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass CounselConfig(AppConfig):\n name = 'counsel'\n" }, { "alpha_fraction": 0.7152209281921387, "alphanum_fraction": 0.7152209281921387, "avg_line_length": 32.02702713012695, "blob_id": "7add74a63d3580e71dadfbf70397740fd02e1357", "content_id": "b0a857ab7016eb46b183c33211f877cb01e9bb10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1222, "license_type": "no_license", "max_line_length": 86, "num_lines": 37, "path": "/findme/diary/serializers.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import Diary, DiaryWholeContent, LineGraph\nfrom rest_framework.serializers import ModelSerializer, ReadOnlyField\nimport datetime\nfrom pytz import timezone\n\n\nclass DiarySerializer(serializers.ModelSerializer):\n client_username = ReadOnlyField(source=\"client.username\")\n class Meta:\n model = Diary\n fields = ('title', 'client_username', 'create_date', 'content')\n\n\nclass DiaryListSerializer(serializers.ModelSerializer):\n id = ReadOnlyField()\n\n create_date = serializers.SerializerMethodField()\n\n def get_create_date(self, obj):\n return obj.create_date.astimezone(timezone('Asia/Seoul')).strftime('%Y-%m-%d')\n class Meta:\n model = Diary\n fields = ('id','title', 'create_date', 'content')\n\nclass WholeContentSerializer(serializers.ModelSerializer):\n client_username = ReadOnlyField(source=\"client.username\")\n class Meta:\n model = DiaryWholeContent\n fields = ('client_username', 'image')\n\nclass LineGraphSerializer(serializers.ModelSerializer):\n client_username = ReadOnlyField(source=\"client.username\")\n\n class Meta:\n model = LineGraph\n fields = ('client_username', 'line_graph')\n" }, { "alpha_fraction": 0.6002846956253052, "alphanum_fraction": 0.6145207285881042, "avg_line_length": 33.736263275146484, "blob_id": "b40394224391cf31eb16ffed7c59c1254134bdef", "content_id": "3a08671671d19229712f25e42ac8295d50b3b116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6522, "license_type": "no_license", "max_line_length": 124, "num_lines": 182, "path": "/findme/users/views.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import User\nfrom django.http import HttpResponse,JsonResponse\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework.decorators import api_view\nfrom drf_yasg import openapi\nimport json\nfrom django.core.serializers import serialize\ntest_param = openapi.Parameter('test', openapi.IN_QUERY, type=openapi.TYPE_STRING)\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework import status\nfrom datetime import datetime\nfrom django.contrib.auth.hashers import check_password\nfrom django.core.exceptions import ValidationError\nfrom .token import account_activation_token\nfrom django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode\nfrom django.utils.encoding import force_text,force_bytes\n\n\nclass Activate(APIView):\n def get(self,request, uidb64, token):\n \"\"\"\n 이메일 인증 기능\n\n ---\n # /users/email/\n ## query parameter\n - email : 중복 체크하려는 이메일\n \"\"\"\n\n try:\n email= force_text( urlsafe_base64_decode(uidb64))\n user = User.objects.get(email=email)\n if account_activation_token.check_token(user,token):\n user.isactive = True\n user.save()\n return Response( \"Email verification was successful.\",status=status.HTTP_200_OK)\n return Response( \"Token Auth Fail\", status=status.HTTP_401_UNAUTHORIZED)\n except ValidationError:\n return Response(\"Type Error\",status=status.HTTP_400_BAD_REQUEST)\n except KeyError:\n return Response(\"Invalid Key\", status=status.HTTP_400_BAD_REQUEST)\n\nclass UserIsActive(APIView):\n def get(self, request):\n isactive = request.user.isactive\n return Response( isactive,status=status.HTTP_200_OK)\n\n\n@swagger_auto_schema(method='get', manual_parameters=[test_param])\n@api_view(['GET'])\ndef EamilRedundantCheck(request):\n \"\"\"\n 이메일 중복 체크 API\n\n ---\n # /users/email/\n ## query parameter\n - email : 중복 체크하려는 이메일\n \"\"\"\n if request.method == \"GET\":\n email = request.GET.get(\"email\")\n try:\n userExist=len(User.objects.filter(email=email))\n except:\n return HttpResponse('Server Error',status=404)\n\n \n if userExist ==False:\n return HttpResponse('Email Available',status=200)\n else:\n return HttpResponse('Email Redundant',status=403)\n\n\n\n@swagger_auto_schema(method='get', manual_parameters=[test_param])\n@api_view(['GET'])\ndef getUserListsByUserType(request):\n \"\"\"\n 내담자/상담자 리스트 조회 API\n\n --- \n # /users/\n ## query parameter\n - user_type : 상담자/내담자 구분 ( 내담자 : 0 ,상담자 : 1 )\n \"\"\"\n if request.method == \"GET\":\n user_type = request.GET.get(\"user_type\")\n try:\n list = User.objects.filter(user_type=user_type)\n userExist = len(list)\n except:\n return HttpResponse('Server Error',status=404)\n data = json.loads(serialize('json', list,fields=('email','user_type','username','introduce','image','career')))\n if userExist == False:\n return HttpResponse('Users Not Exists',status=403)\n else:\n return JsonResponse({'message':'Users Exists','users': data},status=200)\n\nclass getEachUserType(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n user_type = User.objects.filter(email=request.user).values('user_type')[0]\n return JsonResponse(user_type, status=200)\nclass UserInfo(APIView):\n def get(self,request):\n \"\"\"\n 유저 정보 상세조회\n\n ---\n # /users/selfinfos/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n \"\"\"\n\n return Response( User.objects.values().get(email=request.user.email),status=status.HTTP_200_OK)\n\n @csrf_exempt\n def put(self,request,**kwargs):\n \"\"\"\n 유저 정보 업데이트\n\n ---\n # /users/<id:int>/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n \"\"\"\n\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n user_id = kwargs.get('id')\n try:\n user_obj = User.objects.get(id=user_id)\n except:\n return Response(\"User not Found\", status=status.HTTP_400_BAD_REQUEST)\n user_obj.introduce = request.data.get(\"introduce\")\n if request.data.get('image') is not None:\n user_obj.image.save(\"user\" + datetime.now().strftime('%Y-%m-%d_%H%M%S') + \".jpg\", request.data.get(\"image\"))\n user_obj.username = request.data.get(\"username\")\n user_obj.user_type = request.data.get(\"user_type\")\n user_obj.career = request.data.get('career')\n user_obj.save()\n return Response(\"User was Updated\", status=status.HTTP_200_OK)\n \nclass PasswordReset(APIView):\n \n def post(self,request):\n \"\"\"\n 비밀번호 변경\n\n ---\n # /users/reset/password/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - origin_password : 기존 비밀번호\n - new_password1 : 새비밀번호1\n - new_password2 : 새비밀번호2\n\n \"\"\"\n body = json.loads(request.body.decode('utf-8'))\n context= {}\n current_password = body[\"origin_password\"]\n user = request.user\n if check_password(current_password, user.password):\n new_password = body[\"new_password1\"]\n password_confirm = body[\"new_password2\"]\n if new_password == password_confirm:\n user.set_password(new_password)\n user.save()\n return Response(\"User was Password Updated\", status=status.HTTP_200_OK)\n else:\n return Response(\"Does not match Password1 and Password2 \", status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response(\"Wrong password\", status=status.HTTP_403_FORBIDDEN)\n" }, { "alpha_fraction": 0.6520146727561951, "alphanum_fraction": 0.6643772721290588, "avg_line_length": 38, "blob_id": "9d9080a3f01e1c4d997be58d8805a43b69d4311f", "content_id": "ffcc18d406578f9693a7d09095bc4659a88b7978", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2210, "license_type": "no_license", "max_line_length": 97, "num_lines": 56, "path": "/findme/findme/urls.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import include, url\nfrom allauth.account.views import confirm_email\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom drf_yasg.views import get_schema_view\nfrom rest_framework.permissions import AllowAny\nfrom drf_yasg import openapi\n\nschema_url_v1_patterns = [\n url(r'', include(('diary.urls', 'diary'), namespace='diary')),\n url(r'', include(('users.urls', 'users'), namespace='email')),\n url(r'', include(('counsel.urls','counsel'), namespace='counsels')),\n url(r'', include(('task.urls','task'), namespace='tasks')),\n]\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"FINDME API\",\n default_version='v1',\n description =\n '''\n **2020 SW캡스톤디자인 real kk팀 - Find Me 백엔드 API입니다.**\n\n - API BASE URL : http://ec2-13-209-32-113.ap-northeast-2.compute.amazonaws.com:8000/\n ''',\n contact=openapi.Contact(email=\"[email protected]\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n validators=['flex'],#, 'ssv'],\n public=True,\n permission_classes=(AllowAny,),\n patterns=schema_url_v1_patterns,\n)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('rest-auth/', include('rest_auth.urls')),\n path('rest-auth/registration/', include('rest_auth.registration.urls')),\n url(r'^accounts-rest/registration/account-confirm-email/(?P<key>.+)/$', confirm_email,\n name='account_confirm_email'),\n path('users/', include('users.urls')),\n path('', include('diary.urls')),\n # API document generation with drf_yasg\n path('swagger<str:format>', schema_view.without_ui(cache_timeout=0), name='schema-json'),\n path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),\n path('docs/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc-v1'),\n path('tasks/', include('task.urls')),\n path('counsels/', include('counsel.urls')),\n path('reviews/', include('review.urls')),\n path('', include('diary.urls')),\n path('voices/', include('voice.urls')),\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" }, { "alpha_fraction": 0.7111597657203674, "alphanum_fraction": 0.7111597657203674, "avg_line_length": 44.79999923706055, "blob_id": "78a836ca80b9da0d9ef71dd3bda54564e55f51cd", "content_id": "9cb2feaf27f950d7da17cd20736213fc9fa4adae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 457, "license_type": "no_license", "max_line_length": 101, "num_lines": 10, "path": "/findme/diary/urls.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from . import views\nfrom django.urls import path\n\n\nurlpatterns = [\n path('diaries/', views.Text_extract_wordcloud.as_view(), name='text_extract_wordcloud'),\n path('diaries/<int:id>/', views.Text_extract_wordcloud.as_view(), name='text_extract_wordcloud'),\n path('whole_content/', views.Whole_content_to_wordcloud.as_view(), name=\"whole_content_to_wc\"),\n path('linegraph/', views.Text_extract_linegraph.as_view(), name=\"text_extract_linegraph\")\n]" }, { "alpha_fraction": 0.8418079018592834, "alphanum_fraction": 0.8418079018592834, "avg_line_length": 24.428571701049805, "blob_id": "548833dd5c0532849be82d05fddee12a17ca26ec", "content_id": "e52a144b573bf351c1eac827fb0c1a06c6a13a51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/findme/diary/admin.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom diary import models\n\nadmin.site.register(models.Diary)\nadmin.site.register(models.DiaryWholeContent)\nadmin.site.register(models.LineGraph)" }, { "alpha_fraction": 0.6780821681022644, "alphanum_fraction": 0.7054794430732727, "avg_line_length": 72, "blob_id": "16c0a32b4b75610dd043dec6520a80bf4c5504a6", "content_id": "6227dc74a5accadba9addc381a08ac685fa4a68a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 204, "license_type": "no_license", "max_line_length": 109, "num_lines": 2, "path": "/findme/users/text.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "def message(domain, uidb64, token):\n return f\"안녕하세요 FINDME 입니다.\\n\\n아래 링크를 클릭해서 회원 인증을 완료하세요 \\n\\n클릭 : {domain}/users/activate/{uidb64}/{token}\"\n" }, { "alpha_fraction": 0.8315789699554443, "alphanum_fraction": 0.8315789699554443, "avg_line_length": 22.75, "blob_id": "09d8d392eb8613cd6569d93b7c10ad18c7be33ed", "content_id": "e8cfeef74b6645a10812f1ea4f46e976aa6703c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/findme/review/admin.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom review import models\n\nadmin.site.register(models.Review)\n" }, { "alpha_fraction": 0.7406483888626099, "alphanum_fraction": 0.7456359267234802, "avg_line_length": 32.41666793823242, "blob_id": "42adb6d47e554b7d38292e7a6e54d0594fb6253f", "content_id": "b2fb9e35840292743aaca7019d512c6487fe5112", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 401, "license_type": "no_license", "max_line_length": 90, "num_lines": 12, "path": "/findme/Dockerfile", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "FROM python:3.6\nRUN mkdir /code\nWORKDIR /code\nADD requirement.txt /code/\nRUN pip install -r requirement.txt\nRUN apt-get update && \\\n apt-get install -y --no-install-recommends default-jre default-jdk\nRUN apt-get install -y fonts-nanum\nRUN ls -l /usr/share/fonts/truetype/ \nRUN java -version\nRUN curl -L https://raw.githubusercontent.com/konlpy/konlpy/master/scripts/mecab.sh | bash\nADD . /code/\n" }, { "alpha_fraction": 0.7035436630249023, "alphanum_fraction": 0.7139152884483337, "avg_line_length": 38.89655303955078, "blob_id": "4d8c86e807f9e637d0f49a2a5da6a63e9f92b380", "content_id": "b2e9a56014435048b10f2aca24ee9825132eae0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "no_license", "max_line_length": 111, "num_lines": 29, "path": "/findme/diary/models.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.conf import settings\n\n\nclass Diary(models.Model):\n client = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n title = models.CharField(max_length=100)\n create_date = models.DateTimeField( null=True)\n content = models.CharField(max_length=1000)\n sentiment_score = models.FloatField(verbose_name=\"텍스트감정분석결과\", null=True)\n\n class Meta:\n verbose_name = '감정일기'\n \nclass DiaryWholeContent(models.Model):\n client = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n whole_content = models.CharField(max_length=10000, null=True)\n image = models.ImageField(upload_to=\"wordcloud/\", blank=True, null=True)\n renew_flag = models.BooleanField(default=False)\n\n class Meta:\n verbose_name = \"감정일기 내용 모음\"\n\nclass LineGraph(models.Model):\n client = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=\"+\", on_delete=models.CASCADE, null=True)\n line_graph = models.ImageField(upload_to=\"linegraph/\", blank=True, null=True)\n\n class Meta:\n verbose_name = \"꺾은선그래프 - 감정일기\"\n" }, { "alpha_fraction": 0.6880000233650208, "alphanum_fraction": 0.6912000179290771, "avg_line_length": 47.153846740722656, "blob_id": "dbfd321e81bfa6f7be437e7720cdd62d4f521538", "content_id": "5df36c085d5c25b906dbc35dbd285f112cc66558", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "no_license", "max_line_length": 87, "num_lines": 13, "path": "/findme/users/urls.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.urls import path,include\nfrom users import views\n\nurlpatterns = [\n path('email', views.EamilRedundantCheck),\n path('<int:id>/', views.UserInfo.as_view(),name=\"user_info\"),\n path('selfinfos/', views.UserInfo.as_view(),name=\"user_info\"),\n path('', views.getUserListsByUserType),\n path('type/', views.getEachUserType.as_view(), name=\"get_each_user_type\"),\n path('isactive/',views.UserIsActive.as_view(),name=\"user_is_active\"),\n path('reset/password/', views.PasswordReset.as_view(), name=\"PasswordReset\"),\n path('activate/<str:uidb64>/<str:token>',views.Activate.as_view(), name=\"activate\")\n]" }, { "alpha_fraction": 0.5884166955947876, "alphanum_fraction": 0.5988119840621948, "avg_line_length": 32.79536819458008, "blob_id": "748cbae6e518f6962a21f1f2934f239029901f7d", "content_id": "6a63376d38e494080383be4f2d099a990c0c6f05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9094, "license_type": "no_license", "max_line_length": 113, "num_lines": 259, "path": "/findme/task/views.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom .serializers import *\nfrom django.core import serializers\nfrom rest_framework import status\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom .models import Task\nfrom django.core.files.storage import File\nimport json\nfrom users.models import User\nimport requests\nimport matplotlib.pyplot as plt\nimport io\nfrom django.core.files.images import ImageFile\nfrom datetime import datetime\n\n\ndef create_sentiment_graph_result(sentiments):\n length = len(sentiments)\n sentiment_scores = [[] for _ in range(8)]\n sentiment_type = [\"화남\", \"경멸\", \"역겨움\", \"공포\", \"행복\", \"무표정\", \"슬픔\", \"놀람\"]\n colors = ['red', 'maroon', 'orange', 'black', 'lime', 'indigo', 'cyan', 'yellow']\n for second in sentiments:\n sentiment_values = list(map(str, sentiments.get(second).split('\\n')))[:-1]\n for idx, each_value in enumerate(sentiment_values):\n sentiment_scores[idx].append(float(each_value.split(':')[1]))\n plt.rcParams['font.family'] = 'NanumGothic'\n plt.rcParams['font.size'] = 8\n plt.figure(figsize=(8,8))\n x = list(sentiments.keys())\n x.sort()\n for i in range(8):\n plt.plot(x, sentiment_scores[i], color=colors[i], label=sentiment_type[i])\n plt.legend()\n plt.axis([1, 7, 0, 1])\n plt.xlabel('second')\n plt.ylabel('sentiment_score')\n fig = plt.gcf()\n file_io = io.BytesIO()\n fig.savefig(file_io, format=\"png\")\n graph_image = ImageFile(file_io)\n return graph_image\n\nclass TaskUpload(APIView):\n\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n def post(self, request, **kwargs):\n \"\"\"\n 내담자가 질문에 비디오 등록\n\n ---\n # /tasks/<id:int>/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - video : 내담자 이메일 [ex> [email protected]]\n - question : 등록할 질문 내용 [ex> 가장 좋아하는 음식은?]\n \"\"\" \n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n serializers = TaskSerializer(data=request.data)\n if serializers.is_valid():\n try : \n task_id = kwargs.get('id')\n selected_task = Task.objects.get(id=task_id)\n except:\n return Response('task Not Founded',status= status.HTTP_404_NOT_FOUND)\n selected_task.video = request.data.get('video')\n selected_task.video.name = str(kwargs.get('uuid')) + '.mp4'\n selected_task.save()\n return Response(serializers.data, status=status.HTTP_201_CREATED)\n return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass TaskDetail(APIView):\n \n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def delete(self,request,**kwargs):\n \"\"\"\n 과제 삭제\n\n ---\n # /tasks/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n \"\"\"\n\n if request.user.user_type != '1':\n return Response(\"Only Counselor can delete Task\", status=status.HTTP_403_FORBIDDEN)\n\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n else:\n task_id = kwargs.get('id')\n try:\n task = Task.objects.get(id=task_id)\n task.delete()\n except:\n return Response(\"Task not founded\", status=status.HTTP_400_BAD_REQUEST)\n\n return Response(\"Task was deleted\", status=status.HTTP_200_OK)\n\nclass AddTaskQuestion(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n 내담자에게 질문 등록\n\n ---\n # /tasks/questions/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - client : 내담자 이메일 [ex> [email protected]]\n - question : 등록할 질문 내용 [ex> 가장 좋아하는 음식은?]\n \"\"\"\n\n serializer = TaskQuestionSerializer(data=request.data)\n if serializer.is_valid():\n client_email = request.data.get('client')\n client = User.objects.get(email=client_email)\n task = Task(question=request.data.get('question'), counselor=request.user, client=client)\n task.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def get(self, request):\n \"\"\"\n 내담자의 질문 조회\n\n ---\n # /tasks/questions/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n \"\"\"\n\n questions = Task.objects.filter(client=request.user)\n serializer = TaskQuestionSerializer(questions, many=True)\n return Response(serializer.data,status=status.HTTP_200_OK)\n\nclass TaskQuestionForCounselor(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n \"\"\"\n 상담사의 질문 조회\n\n ---\n # /tasks/questions_counselor/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - client : 내담자 이메일 [ex> [email protected]]\n\n \"\"\"\n\n\n client_email = request.GET.get('client')\n client = User.objects.get(email=client_email)\n questions = Task.objects.filter(client=client, counselor=request.user)\n serializer = TaskQuestionSerializer(questions, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\nclass VideoProcessing(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, request, **kwargs):\n \"\"\"\n 비디오 감정분석 진행\n\n ---\n # /tasks/process_videos/<id:int>/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n\n \"\"\"\n\n if kwargs.get('id') is None:\n return Response('invalid request', status=status.HTTP_400_BAD_REQUEST)\n new_video = Task.objects.get(pk=kwargs.get(\"id\"))\n #print(new_video.video.name)\n #url = 'https://processed-video-lambda.s3.ap-northeast-2.amazonaws.com/' + str(new_video.video.name)\n video_name = new_video.video.name.split('.')[0]\n url = \"http://d39zdwvmbp76zl.cloudfront.net/\" + video_name + \"/Default/HLS/\" + video_name + '.m3u8'\n response = requests.get(url)\n if str(response.status_code) == '200':\n return Response(url, status=status.HTTP_200_OK)\n return Response(\"Processed Video is not exist\", status=status.HTTP_404_NOT_FOUND)\n\n\nclass GetSentiment(APIView):\n def post(self, request):\n \"\"\"\n 분석된 감정 조회\n\n ---\n # /tasks/sentiment/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - sentiments : 내담자 이메일 [ex> [email protected]]\n - key : 파일 이름\n \"\"\"\n\n\n sentiments = request.data.get(\"sentiments\")\n filename = request.data.get(\"key\")\n task = Task.objects.filter(video=filename)[0]\n sentiment_graph = create_sentiment_graph_result(sentiments)\n task.graph.save(\"sentiment_graph\" + datetime.now().strftime('%Y-%m-%d_%H%M%S') + \".png\", sentiment_graph)\n task.save()\n plt.cla()\n return Response(request.data, status=status.HTTP_200_OK)\n\nclass MakeSentimentLinegraph(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n \"\"\"\n 감정 라인 그래프 생성\n\n ---\n # /tasks/sentiment_graphs/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - id : task의 아이디\n \"\"\"\n\n\n task = Task.objects.get(id=request.data.get('id'))\n serializer = SentimentGraphSerializer(task)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n \n def get(self, request):\n \"\"\"\n 감정 라인 그래프 조회\n\n ---\n # /tasks/sentiment_graphs/\n ## headers\n - Authorization : Token \"key 값\" [ex> Token 822a24a314dfbc387128d82af6b952191dd71651]\n ## body parameter\n - id : task의 아이디\n \"\"\"\n\n pk = request.GET.get('id')\n task = Task.objects.get(id=pk)\n serializer = SentimentGraphSerializer(task)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n" }, { "alpha_fraction": 0.5257731676101685, "alphanum_fraction": 0.5850515365600586, "avg_line_length": 20.55555534362793, "blob_id": "3b935f4b5a33db6e416fe26d7b6224e7a02bba1f", "content_id": "9f0c271391a1d23a6aabbdbcae7a18bc6b8d261d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 388, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/findme/review/migrations/0002_auto_20201117_2212.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.2 on 2020-11-17 13:12\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('review', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='review',\n name='content',\n field=models.CharField(max_length=1000, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6884456872940063, "alphanum_fraction": 0.7049518823623657, "avg_line_length": 39.38888931274414, "blob_id": "9fae9c12f015394847a15a40a2b68a3cd8aa2a0b", "content_id": "d4dcdd830ba0974abd64d57854df76e8adace8e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1536, "license_type": "no_license", "max_line_length": 89, "num_lines": 36, "path": "/findme/users/models.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom .managers import CustomUserManager\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\nfrom rest_framework.authtoken.models import Token\n\n\nclass User(AbstractUser):\n first_name = None\n last_name = None\n username = models.CharField('이름', max_length=50, null = True)\n email = models.EmailField('이메일', unique=True)\n password = models.CharField('비밀번호', max_length=128)\n user_type = models.CharField('유저타입', max_length= 10, default='') # {내담자 : 0, 상담사 : 1}\n introduce = models.CharField('자기소개', max_length=100, null=True)\n career = models.CharField('약력', max_length=1000, null=True)\n image = models.ImageField('프로필',upload_to=\"users/\", blank=True, null=True)\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['user_type','introduce']\n\n objects = CustomUserManager()\n isactive = models.BooleanField('인증유무',default=False)\n realname = models.CharField('이름', blank=True, max_length=50)\n phone = models.CharField('휴대폰번호', blank=True, max_length=100)\n address = models.CharField('주소', blank=True, max_length=200)\n date_of_birth = models.DateField('생년월일', blank=True, null=True)\n\n def __str__(self):\n return self.email\n\n@receiver(post_save, sender=User)\ndef handle_user_save(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n" }, { "alpha_fraction": 0.6764116883277893, "alphanum_fraction": 0.680016040802002, "avg_line_length": 40.599998474121094, "blob_id": "ed02e66bb251671870defc33a71e3163a72b1b7b", "content_id": "d05d50d9f7cb80dd31f9e11fe01ec49787f6e7bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2529, "license_type": "no_license", "max_line_length": 124, "num_lines": 60, "path": "/findme/voice/views.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .serializers import VoiceSerializer\nfrom .models import Voice\nimport azure.cognitiveservices.speech as speechsdk\nimport wave\nfrom .secret import voice_key\nimport time\nimport os\nfrom django.core.mail import send_mail\nfrom users.models import User\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\n\n\ndef speech_recognize_continuous(filename):\n recognized_str = \"\"\n speech_key, service_region = voice_key.SPEECH_KEY, \"koreacentral\"\n speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)\n\n audio_config = speechsdk.audio.AudioConfig(filename=filename)\n speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, language=\"ko-KR\", audio_config=audio_config)\n result = speech_recognizer.recognize_once_async()\n result = result.get()\n if result.reason == speechsdk.ResultReason.RecognizedSpeech:\n recognized_str += result.text\n return recognized_str\n\n\nclass VoiceSTT(APIView):\n authentication_classes = [TokenAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n serializer = VoiceSerializer(data=request.data)\n if serializer.is_valid():\n voice_file = request.data.get('voice')\n if not voice_file:\n return Response(\"voice file does not exist\", status=status.HTTP_400_BAD_REQUEST)\n obj = wave.open(voice_file, 'r')\n audio = wave.open('test.wav', 'wb')\n audio.setnchannels(obj.getnchannels())\n audio.setnframes(obj.getnframes())\n audio.setsampwidth(obj.getsampwidth())\n audio.setframerate(obj.getframerate())\n blob = voice_file.read()\n audio.writeframes(blob)\n recognized_string = speech_recognize_continuous(\"test.wav\")\n if os.path.isfile(\"test.wav\"):\n os.remove(\"test.wav\")\n send_mail(\n \"[FINDME] 녹음본을 텍스트로 변환한 결과입니다.\",\n recognized_string,\n '[email protected]',\n User.objects.filter(email=request.user.email).values_list('email', flat=True),\n fail_silently=False,\n )\n return Response(recognized_string, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n" }, { "alpha_fraction": 0.5455138087272644, "alphanum_fraction": 0.5599380731582642, "avg_line_length": 44.11397171020508, "blob_id": "e74c11c937e73da49650fe9187f2deda83a7b6e1", "content_id": "c72e60ce48687222a1d56538a5035935a2553ccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12807, "license_type": "no_license", "max_line_length": 126, "num_lines": 272, "path": "/findme/counsel/tests.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.test import TestCase,Client\nfrom users.models import User\nfrom .models import Counsel,RegisterCounselDate\nfrom .serializer import CounselSerializer,CounselListSerializer,CounselDateSerializer\nfrom django.db.models.fields.files import ImageField\nfrom rest_framework.authtoken.models import Token\nfrom django.db.models.fields.related import ForeignKey\nfrom django.core.files.images import ImageFile\nimport tempfile\nimport json \nimport io\nfrom PIL import Image\nfrom datetime import datetime\n\nclass CounselModelTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user = User.objects.create( \n email='[email protected]', \n password='test',\n username='강낭콩' \n )\n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n # Set up non-modified objects used by all test methods\n Counsel.objects.create(client=self.user,counselor=self.user,time_table=image_mock,\n major='소프트',student_number='201211222',phone_number='01031332322',content='신청합니다')\n self.counsel_id = Counsel.objects.values().first()['id']\n def test_client_is_foreignkey(self):\n counsel=Counsel.objects.get(id=self.counsel_id)\n client = counsel._meta.get_field('client')\n self.assertEquals(type(client),ForeignKey)\n def test_counselor_is_foreignkey(self):\n counsel=Counsel.objects.get(id=self.counsel_id)\n counselor = counsel._meta.get_field('counselor')\n self.assertEquals(type(counselor),ForeignKey)\n\n def test_max_length(self):\n counsel=Counsel.objects.get(id=self.counsel_id)\n max_length = counsel._meta.get_field('major').max_length\n self.assertEquals(max_length, 100)\n max_length = counsel._meta.get_field('student_number').max_length\n self.assertEquals(max_length, 100)\n \n max_length = counsel._meta.get_field('phone_number').max_length\n self.assertEquals(max_length, 100)\n max_length = counsel._meta.get_field('content').max_length\n self.assertEquals(max_length, 100)\n \n def test_diary_meta_verbose_name(self):\n counsel=Counsel.objects.get(id=self.counsel_id)\n self.assertEquals('신청서', counsel._meta.verbose_name)\n\n\n\nclass SerializerTest(TestCase):\n\n @classmethod\n def setUpTestData(self):\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='난상담',\n user_type=1 \n )\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='난내담',\n user_type=0\n ) \n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n\n # Set up non-modified objects used by all test methods\n Counsel.objects.create(client=self.user_client,counselor=self.user_counselor,time_table=image_mock,\n major='소프트',student_number='201211222',phone_number='01031332322',content='신청합니다')\n RegisterCounselDate.objects.create(client=self.user_client,counselor=self.user_counselor)\n self.counsel_id = Counsel.objects.values().first()['id']\n\n def test_counsel_serializer(self):\n serializer = CounselSerializer(data=Counsel.objects.values().all().first())\n if not serializer.is_valid():\n import pprint\n pprint.pprint(serializer.errors)\n self.assertEqual(serializer.is_valid(), True)\n def test_counsel_list_serializer(self):\n counsel = Counsel.objects.all()\n serializer = CounselListSerializer( counsel, many=True)\n def test_counsel_date_serializer(self): \n serializer = CounselDateSerializer(data=RegisterCounselDate.objects.values().all().first())\n if not serializer.is_valid():\n import pprint\n pprint.pprint(serializer.errors)\n self.assertEqual(serializer.is_valid(), True)\nclass CounselApplicationTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='난상담',\n user_type=1 \n )\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='난내담',\n user_type=0\n ) \n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n\n # Set up non-modified objects used by all test methods\n Counsel.objects.create(client=self.user_client,counselor=self.user_counselor,time_table=image_mock,\n major='소프트',student_number='201211222',phone_number='01031332322',content='신청합니다')\n self.counsel_id = Counsel.objects.values().first()['id']\n \n def setUp(self):\n RegisterCounselDate.objects.create(client=self.user_client,counselor=self.user_counselor)\n\n # token, created = Token.objects.get_or_create(user=self.user_client) \n token, created = Token.objects.get_or_create(user=self.user_counselor) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n # 상담 신청서 업로드 test\n def test_A_text_application_post(self):\n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n\n url = '/counsels/' \n counsels_data = { \n 'client':self.user_client,\n 'counselor':self.user_counselor,\n 'major':'공부나할과',\n 'student_number':'201512151',\n 'phone_number':'01099999999',\n 'content':'테스트 드리븐 개발은 나를 성장시켜주고 새로운 것을 배우게 도와주는 즐거운 일이다. 어렵고 복잡하지만, 잘 이겨내서 좋은 개발자가 될것이다.'\n }\n response= self.client.post(url,data=counsels_data)\n self.assertEquals(response.status_code,201)\n\n # 상담 신청서 가져오기 test\n def test_B_text_application_get(self):\n url='/counsels/'\n response= self.client.get(url,content_type='application/json')\n self.assertEqual(response.status_code,200)\n \n # 상담 신청서 수정 test /// token 을 client 로 해야됨\n def test_C_text_application_put(self):\n url='/counsels/'\n \n counsels_data = { \n 'client':self.user_client.email,\n 'counselor':self.user_counselor.email,\n 'major':'공부나할과',\n 'student_number':'201512151',\n 'phone_number':'01099999999',\n 'content':'테스트 드리븐 개발은 나를 성장시켜주고 새로운 것을 배우게 도와주는 즐거운 일이다. 어렵고 복잡하지만, 잘 이겨내서 좋은 개발자가 될것이다.'\n }\n kwargs=str(Counsel.objects.values().first()[\"id\"])\n response= self.client.put(url+kwargs+'/',data=json.dumps(counsels_data),content_type='application/json')\n self.assertEqual(response.status_code,403)\n self.assertEqual(response.data,'Can only Modify your own counsel application')\n\n\n\n # 상담 신청서 삭제(상담보류) test // token 을 counselor 로 해야함\n def test_D_text_application_delete_when_reject(self):\n url='/counsels/'\n kwargs=str(Counsel.objects.values().first()[\"id\"])\n response= self.client.delete(url+kwargs+'/?counsel_date_id=-1',content_type='application/json')\n self.assertEqual(response.status_code,200)\n self.assertEqual(response.data,'Counsel was deleted')\n # 상담 신청서 삭제(상담수락) test // token 을 counselor 로 해야함\n def test_E_text_application_delete_when_approved(self):\n url='/counsels/'\n kwargs=str(Counsel.objects.values().first()[\"id\"])\n register_counsel_date_id= str(RegisterCounselDate.objects.values().first()[\"id\"])\n\n response= self.client.delete(url+kwargs+'/?counsel_date_id='+register_counsel_date_id,content_type='application/json')\n self.assertEqual(response.status_code,200)\n self.assertEqual(response.data,'Counsel was deleted')\n\n\n\nclass CounselPhotoTest(TestCase):\n \n def generate_photo_file(self):\n file = io.BytesIO()\n image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))\n image.save(file, 'png')\n file.name = 'test.png'\n file.seek(0)\n return file\n @classmethod\n def setUpTestData(self):\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='난상담',\n user_type=1 \n )\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='난내담',\n user_type=0\n ) \n file = tempfile.NamedTemporaryFile(suffix='.png')\n image_mock= ImageFile(file, name=file.name)\n\n # Set up non-modified objects used by all test methods\n Counsel.objects.create(client=self.user_client,counselor=self.user_counselor,time_table=image_mock,\n major='소프트',student_number='201211222',phone_number='01031332322',content='신청합니다')\n self.counsel_id = Counsel.objects.values().first()['id']\n \n def setUp(self):\n token, created = Token.objects.get_or_create(user=self.user_client) \n # token, created = Token.objects.get_or_create(user=self.user_counselor) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n # 상담 신청서 업로드 test\n def test_A_counsel_photo_add(self):\n photo_file = self.generate_photo_file()\n kwargs=str(Counsel.objects.values().first()[\"id\"])\n url = '/counsels/photo/'+kwargs+'/'\n data={\n 'time_table': photo_file\n }\n response= self.client.post(url,data,format='multipart')\n self.assertEqual(response.status_code,201)\n self.assertEqual(response.data,\"Counsel time table was updated\")\n\n\n\nclass CounselDateTest(TestCase):\n @classmethod\n def setUpTestData(self):\n self.user_client = User.objects.create( \n email='[email protected]', \n password='test',\n username='난상담',\n user_type=1 \n )\n self.user_counselor = User.objects.create( \n email='[email protected]', \n password='test',\n username='난내담',\n user_type=0\n ) \n\n def setUp(self):\n RegisterCounselDate.objects.create(client=self.user_client,counselor=self.user_counselor)\n\n token, created = Token.objects.get_or_create(user=self.user_counselor) \n self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)\n\n # 상담 등록 test\n def test_A_counsel_date_add(self):\n url='/counsels/date/'\n data={\n 'client':self.user_counselor.email,\n 'counsel_date':datetime.now()\n }\n response= self.client.post(url,data=data) \n self.assertEqual(response.status_code,201)\n #등록된 상담 조회 test\n def test_B_counsel_date_get(self):\n url='/counsels/date/'\n response = self.client.get(url) \n self.assertEqual(response.status_code,200)\n" }, { "alpha_fraction": 0.5870165824890137, "alphanum_fraction": 0.7424033284187317, "avg_line_length": 30.478260040283203, "blob_id": "f8f0c8875c96c9af1bc02fbab4698d0aa1ad9864", "content_id": "f82b418824fa4e04e99242874dc3d1e27b68bfd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2262, "license_type": "no_license", "max_line_length": 175, "num_lines": 46, "path": "/README.md", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "# FindMe\n\n![FINDME 포스터](https://user-images.githubusercontent.com/49577850/102770389-695a2380-43c7-11eb-98f6-cf81f62cd576.png)\n\n---\n\n## 본 프로젝트는 심리 상담과정에서의 다음과 같은 불편함들을 SW적으로 개선하주고자 기획하게 되었다\n\n![문제점](https://user-images.githubusercontent.com/49577850/102770538-acb49200-43c7-11eb-8ea9-e8b085c0f4bf.png)\n\n---\n\n## 궁극적으로 다음과 같은 방식으로 상담의 효율을 높이고자 하였다\n\n![해결방안,최종목표](https://user-images.githubusercontent.com/49577850/102770804-17fe6400-43c8-11eb-83af-68dadfebadd9.png)\n\n---\n\n## 프로젝트 설계\n\n![계획,설계](https://user-images.githubusercontent.com/49577850/102771212-e0dc8280-43c8-11eb-9f21-f5faa62cd1c6.png)\n\n- **프론트 - iOS / Android 모두 구현하도록 크로스 플랫폼 React Native 를 이용해서 구현하였다.**\n\n- **백엔드 - 빠르고 안정되고 저렴한 서버를 구축하기 위해 Amazon AWS의 주요 서비스들을 적극 도입하였다. 감정 분석을 위해 GCP, Azure를 활용하였다. Docker 를 이용해 API 배포를 무중단화하였다.**\n\n---\n\n## TDD 활용\n\n- **90% 이상의 Test Coverage를 가져가며 서비스의 안정성을 향상시켜 개발하였다.**\n- **Django에서는 Python 의 Unit Teet 기반의 TestCase클래스를 제공한다. 이를 상속시켜 FindMe 서비스를 개발하며 테스트를 자동화 하였다**\n\n---\n\n## 애자일 활용\n\n빠르고 효율적인 개발 협업을 위해 팀내에서 BackLog, BurndownChart등을 작성했다.\n\n---\n\n## 경진대회 출품\n\n**아주대학교 LINK 경진대회, 교내 CAPSTONE 경진대회 에 출품하여 코로나19시대의 심리적 불안감들을 해소하는데 있어 비대면 상담이 활성화 되어야 하는데, 그 부분에 있어서 도움을 줄 것이라며 호평을 받았다. 또한 심리상담이라는 건강하고 건전한 주제의 우수성을 인정받으며 우수상, 장려상을 수상하였다.**\n![수상](https://user-images.githubusercontent.com/49577850/102774806-09677b00-43cf-11eb-958b-6346abe6967d.png)\n![캡스톤 발표](https://user-images.githubusercontent.com/49577850/107173369-f9513c80-6a0a-11eb-9286-28d62a95c271.png)\n" }, { "alpha_fraction": 0.7028985619544983, "alphanum_fraction": 0.7028985619544983, "avg_line_length": 22, "blob_id": "d0cca4fa51445d36f558c84327bd8d5dc68918db", "content_id": "0b7ba381246e342c3767a565091e92ee9ae116e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "no_license", "max_line_length": 56, "num_lines": 6, "path": "/findme/voice/urls.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from django.urls import path, include\nfrom voice import views\n\nurlpatterns = [\n path('', views.VoiceSTT.as_view(), name='VoiceSTT'),\n]\n" }, { "alpha_fraction": 0.7251212000846863, "alphanum_fraction": 0.7353863716125488, "avg_line_length": 48.39436721801758, "blob_id": "8e68dfd0304a15bd8fca11472fda9bf520dedd66", "content_id": "c936917fb1ca59186188241240851994085d5df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3507, "license_type": "no_license", "max_line_length": 200, "num_lines": 71, "path": "/findme/counsel/serializer.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom rest_framework.serializers import ModelSerializer, ReadOnlyField\nfrom .models import Counsel, RegisterCounselDate\nclass CounselSerializer(serializers.Serializer):\n id = ReadOnlyField()\n client_username = ReadOnlyField(source=\"client.username\")\n counselor_username = ReadOnlyField(source=\"counselor.username\")\n major = serializers.CharField(max_length=100)\n student_number = serializers.CharField(max_length=100)\n phone_number = serializers.CharField(max_length=100)\n create_date = serializers.DateTimeField(allow_null=True)\n content = serializers.CharField(max_length=100)\n class Meta:\n model = Counsel\n fields = ('id', 'student_number', 'phone_number', 'client_username', 'create_date' 'counselor_username', 'major', 'content')\n\nclass CounselPhotoSerializer(serializers.Serializer):\n time_table = serializers.ImageField(use_url=True, allow_null=True)\n class Meta:\n model = Counsel\n fields = ('time_table')\n\nclass CounselListSerializer(serializers.Serializer):\n id = ReadOnlyField()\n counselor_username= ReadOnlyField(source=\"counselor.username\")\n counselor_email = ReadOnlyField(source='counselor.email')\n client_image = ReadOnlyField(source='client.image.name')\n client_username = ReadOnlyField(source=\"client.username\")\n client_introduce = ReadOnlyField(source=\"client.introduce\")\n client_email = ReadOnlyField(source='client.email')\n major = serializers.CharField(max_length=100)\n student_number = serializers.CharField(max_length=100)\n phone_number = serializers.CharField(max_length=100)\n time_table = serializers.ImageField(use_url=True,allow_null=True)\n create_date = serializers.DateTimeField(allow_null=True)\n content = serializers.CharField(max_length=100)\n class Meta:\n model = Counsel\n fields = ('id','counselor_username','counselor_email','student_number', 'phone_number', 'time_table', 'client_email','client_username', 'create_date', 'counselor_username', 'major', 'content')\n \nclass CounselDateSerializer(serializers.Serializer):\n counselor_username = ReadOnlyField(source=\"counselor.username\")\n client_username = ReadOnlyField(source=\"client.username\")\n\n class Meta:\n model = RegisterCounselDate\n fields = ('counselor_username', 'client_username')\n\nclass CounselClientSerializer(serializers.Serializer):\n client_username = ReadOnlyField(source=\"client.username\")\n client_email = ReadOnlyField(source=\"client.email\")\n client_image = ReadOnlyField(source=\"client.image.name\")\n client_introduce = ReadOnlyField(source=\"client.introduce\")\n major = serializers.CharField(max_length=100)\n student_number = serializers.CharField(max_length=100)\n phone_number = serializers.CharField(max_length=100)\n time_table = serializers.ImageField(use_url=True,allow_null=True)\n create_date = serializers.DateTimeField(allow_null=True)\n content = serializers.CharField(max_length=100)\n\n class Meta:\n model = RegisterCounselDate\n fields = ('client_username', 'client','client_image','client_introduce','major','student_number','phone_number','time_table','content')\n\nclass CounselCounselorSerializer(serializers.Serializer):\n counselor_username = ReadOnlyField(source=\"counselor.username\")\n counselor_email = ReadOnlyField(source=\"counselor.email\")\n\n class Meta:\n model = RegisterCounselDate\n fields = ('counselor_username', 'counselor_email')\n" }, { "alpha_fraction": 0.7658730149269104, "alphanum_fraction": 0.7658730149269104, "avg_line_length": 30.5, "blob_id": "f2b4228fc3422f515ab9694d8608a1ebb5207f17", "content_id": "49434eb46525f13c187d4fdf73cd66cfcf8c8150", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 68, "num_lines": 8, "path": "/findme/voice/serializers.py", "repo_name": "real-kk/findme-backend", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom rest_framework.serializers import ModelSerializer,ReadOnlyField\nfrom .models import Voice\n\nclass VoiceSerializer(serializers.ModelSerializer):\n class Meta:\n model = Voice\n fields = ['voice']\n" } ]
42
barettog1/PyFR
https://github.com/barettog1/PyFR
77890cfefa44d8f03e720a02c49627e2a109cf8d
1eeed1d05a7bf1bdefd55a31f97da36daac899cc
c4503903ed63aa84094aa67ff247bc3fa4720951
refs/heads/master
2021-01-15T16:09:36.545881
2015-05-07T20:59:24
2015-05-07T20:59:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5147645473480225, "alphanum_fraction": 0.5161612033843994, "avg_line_length": 45.841121673583984, "blob_id": "3d25531870df84edb1923694aca41d8db2bb6917", "content_id": "39b1c7cc6f4478ac54822e170c9394e946cc7086", "detected_licenses": [ "BSD-3-Clause", "CC-BY-4.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5012, "license_type": "permissive", "max_line_length": 80, "num_lines": 107, "path": "/pyfr/solvers/navstokes/elements.py", "repo_name": "barettog1/PyFR", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom pyfr.backends.base.kernels import ComputeMetaKernel\nfrom pyfr.solvers.baseadvecdiff import BaseAdvectionDiffusionElements\nfrom pyfr.solvers.euler.elements import BaseFluidElements\nfrom pyfr.util import ndrange\n\n\nclass NavierStokesElements(BaseFluidElements, BaseAdvectionDiffusionElements):\n def set_backend(self, backend, nscalupts):\n super().set_backend(backend, nscalupts)\n backend.pointwise.register('pyfr.solvers.navstokes.kernels.tflux')\n\n visc_corr = self.cfg.get('solver', 'viscosity-correction', 'none')\n if visc_corr not in {'sutherland', 'none'}:\n raise ValueError('Invalid viscosity-correction option')\n tplargs = dict(ndims=self.ndims, nvars=self.nvars,\n visc_corr=visc_corr,\n c=self.cfg.items_as('constants', float))\n\n shock_capturing = self.cfg.get('solver', 'shock-capturing', 'none')\n if shock_capturing == 'artificial-viscosity':\n # Allocate required scratch space for artificial viscosity\n nupts, nfpts, neles = self.nupts, self.nfpts, self.neles\n tags = {'align'}\n avis_upts = backend.matrix((nupts, 1, neles), extent='avis_upts',\n tags=tags)\n\n if nfpts >= nupts:\n self._avis_fpts = backend.matrix((nfpts, 1, neles),\n extent='avis_fpts', tags=tags)\n avis_upts_temp = backend.matrix((nupts, 1, neles),\n aliases=self._avis_fpts,\n tags=tags)\n else:\n avis_upts_temp = backend.matrix((nupts, 1, neles),\n extent='avis_fpts', tags=tags)\n self._avis_fpts = backend.matrix((nfpts, 1, neles),\n aliases=avis_upts_temp,\n tags=tags)\n\n backend.pointwise.register('pyfr.solvers.navstokes.kernels.entropy')\n backend.pointwise.register('pyfr.solvers.navstokes.kernels.avis')\n\n def artf_vis():\n # Compute entropy and save to avis_upts\n ent = backend.kernel('entropy', tplargs=tplargs,\n dims=[self.nupts, self.neles],\n u=self.scal_upts_inb, s=avis_upts)\n\n # Compute modal coefficients of entropy\n rcpvdm = np.linalg.inv(self.basis.ubasis.vdm.T)\n rcpvdm = self._be.const_matrix(rcpvdm, tags={'align'})\n mul = backend.kernel('mul', rcpvdm, avis_upts,\n out=avis_upts_temp)\n\n # Additional constants for element-wise artificial viscosity\n ubdegs = self.basis.ubasis.degrees\n tplargs['c'].update(\n self.cfg.items_as('solver-artificial-viscosity', float)\n )\n tplargs.update(dict(nupts=self.nupts, nfpts=self.nfpts,\n order=self.basis.order, ubdegs=ubdegs))\n\n # Column view for avis_upts/fpts matrices\n def col_view(mat):\n vshape = (mat.nrow,)\n rcmap = np.array(list(ndrange(1, mat.ncol)))\n matmap = np.array([mat.mid]*mat.ncol)\n stridemap = np.array([[mat.leaddim]]*mat.ncol)\n\n return backend.view(matmap, rcmap, stridemap, vshape)\n\n avis_upts_cv = col_view(avis_upts)\n avis_fpts_cv = col_view(self._avis_fpts)\n avis_upts_temp_cv = col_view(avis_upts_temp)\n\n # Element-wise artificial viscosity kernel\n avis = backend.kernel('avis', tplargs, dims=[self.neles],\n ubdegs=ubdegs,\n s=avis_upts_temp_cv,\n amu_e=avis_upts_cv, amu_f=avis_fpts_cv)\n\n return ComputeMetaKernel([ent, mul, avis])\n\n self.kernels['avis'] = artf_vis\n tplargs['art_vis'] = 'mu'\n elif shock_capturing == 'none':\n avis_upts = None\n tplargs['art_vis'] = 'none'\n else:\n raise ValueError('Invalid shock-capturing option')\n\n if 'flux' in self.antialias:\n self.kernels['tdisf'] = lambda: backend.kernel(\n 'tflux', tplargs=tplargs, dims=[self.nqpts, self.neles],\n u=self._scal_qpts, smats=self.smat_at('qpts'),\n f=self._vect_qpts, amu=avis_upts\n )\n else:\n self.kernels['tdisf'] = lambda: backend.kernel(\n 'tflux', tplargs=tplargs, dims=[self.nupts, self.neles],\n u=self.scal_upts_inb, smats=self.smat_at('upts'),\n f=self._vect_upts, amu=avis_upts\n )\n" } ]
1
Line290/improve_partial_fc
https://github.com/Line290/improve_partial_fc
f22f70b978bb3b173cca1bd65a501ee2e8914754
9ee131b1a19f60fd4cda48b5519b9648cab25d7e
42b5039bd8b8c5809227a85f4dde0b1077c9178c
refs/heads/master
2020-03-27T01:38:07.612895
2018-09-20T01:08:47
2018-09-20T01:08:47
145,729,411
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5921578407287598, "alphanum_fraction": 0.6301198601722717, "avg_line_length": 33.52586364746094, "blob_id": "242052187e3e94a66c634f1e600a3f99beb636e1", "content_id": "c6381fff3b36cb3d03545eda94d041c26ab352b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4004, "license_type": "no_license", "max_line_length": 131, "num_lines": 116, "path": "/train.py", "repo_name": "Line290/improve_partial_fc", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np\nimport mxnet as mx\nimport time\nimport cPickle\n# import custom_layers\nimport logging\n\nimport skcuda.cublasxt as cublasxt\nimport math\nimport os\nimport scipy\n\nfrom data_iter import DataIter\nfrom mixmodule import create_net, mixModule\n\nprint 'mxnet version' + mx.__version__\n# ctx = [mx.gpu(i) for i in range(3)]\nctx = [mx.gpu(0)]\nhandle = cublasxt.cublasXtCreate()\n# mode = cublasxt.cublasXtGetPinningMemMode(handle)\ncublasxt.cublasXtSetPinningMemMode(handle, 1)\ncublasxt.cublasXtSetCpuRatio(handle, 0, 0, 0.9)\nnbDevices = len(ctx)\ndeviceId = np.array(range(nbDevices), np.int32)\ncublasxt.cublasXtDeviceSelect(handle, nbDevices, deviceId)\n\nnum_epoch = 1000000\nbatch_size = 64*nbDevices\nshow_period = 1000\n\nassert(batch_size%nbDevices==0)\nbsz_per_device = batch_size / nbDevices\nprint 'batch_size per device:', bsz_per_device\n\n# featdim = 128\nfeatdim = 512\ntotal_proxy_num = 285000\ndata_shape = (batch_size, 3, 240, 120)\n# proxy_Z_shape = (featdim, total_proxy_num)\nproxy_Z_fn = './proxy_Z.npy'\nproxy_Z = (np.random.rand(featdim, total_proxy_num)-0.5)*0.001\nproxy_Z = proxy_Z.astype(np.float32)\n# proxy_Z = mx.nd.random.uniform(low=-0.5, high=0.5, \n# shape=(featdim, total_proxy_num), \n# dtype='float32', \n# ctx=mx.cpu(0))\n# proxy_Z = proxy_Ztmp.astype(np.float32)\n\nif os.path.exists(proxy_Z_fn):\n proxy_Z = np.load(proxy_Z_fn)\n# proxy_Z = tmpZ[0].asnumpy()\n# proxy_Z = tmpZ\n# proxy_Z = mx.nd.load(proxy_Z_fn)[0]\n# print proxy_num, tmpZ[0].shape[0]\n assert(total_proxy_num==proxy_Z.shape[1])\n print 'load proxy_Z from', proxy_Z_fn\n\ndlr = 1050000/batch_size\nradius = 0\nhardratio = 10**-1\nlr_start = 0.1\nlr_min = 10**-5\nlr_reduce = 0.96 #0.99\nlr_stepnum = np.log(lr_min/lr_start)/np.log(lr_reduce)\nlr_stepnum = np.int(np.ceil(lr_stepnum))\ndlr_steps = [dlr*i for i in xrange(1, lr_stepnum+1)]\nprint 'lr_start:%.1e, lr_min:%.1e, lr_reduce:%.2f, lr_stepsnum:%d'%(lr_start, lr_min, lr_reduce, lr_stepnum)\n# print dlr_steps\nlr_scheduler = mx.lr_scheduler.MultiFactorScheduler(dlr_steps, lr_reduce)\n\n# param_prefix = 'MDL_PARAM/params5_proxy_nca-8wmargin_20180724_dim_512_bn/person_reid-back'\nparam_prefix = './'\nload_paramidx = 0 #None\n\n# DataBatch test\n# data_path_prefix = '/train/trainset/list_clean_28w_20180803'\ndata_path_prefix = '/train/execute/improve_partial_fc/dataset/list_clean_28w_20180803'\ndata_iter = DataIter(prefix = data_path_prefix, image_shapes = data_shape, data_nthreads = 4)\n\n# simple DataBatch test\n# data_batch = mx.random.normal(0, 1.0, shape=data_shape)\n# data_label = mx.nd.array(range(64), dtype='int32')\n# data_test = mx.io.DataBatch(data=[data_batch], label=[data_label])\n\ndata = mx.sym.Variable('data')\npart_net = create_net(data, radius)\nmxmod = mixModule(symbol=part_net, \n context=ctx, \n handle=handle, \n data_shape=data_shape, \n proxy_Z=proxy_Z, \n K = 999)\n\nmxmod.init_params(mx.init.Xavier(factor_type=\"in\", magnitude=2.34))\nmxmod.init_optimizer(optimizer=\"adam\", \n optimizer_params={\n \"learning_rate\": lr_start,\n 'lr_scheduler':lr_scheduler,\n 'clip_gradient':None,\n \"wd\": 0.0005,\n# \"beta1\": beta1,\n })\nfor epoch in range(num_epoch):\n print 'Epoch [%d] start...' % (epoch)\n data_iter.reset()\n start = time.time()\n for batch_iter in range(dlr):\n# print type(data_iter.next())\n# print data_iter.next().data[0].shape, data_iter.next().label[0].shape\n mxmod.update(data_iter.next())\n# mxmod.update(data_test)\n if batch_iter % 5 == 0:\n print 'Iter [%d] speed %.2f samples/sec loss = %.2f'%(batch_iter, batch_size/(time.time()-start), mxmod.get_loss())\n start = time.time()\n mxmod.save_proxy_Z(proxy_Z_fn = proxy_Z_fn)" }, { "alpha_fraction": 0.44507041573524475, "alphanum_fraction": 0.4676056206226349, "avg_line_length": 44.82258224487305, "blob_id": "28d3036a87c931870f39aeb956a4e5f5010f85c1", "content_id": "729fe898a12649564b1293ed606766f782f416c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2840, "license_type": "no_license", "max_line_length": 116, "num_lines": 62, "path": "/data_iter.py", "repo_name": "Line290/improve_partial_fc", "src_encoding": "UTF-8", "text": "import mxnet as mx\nimport time\n\ndef DataIter(prefix = '/train/trainset/list_clean_28w_20180803', image_shapes=(64, 3, 240, 120), data_nthreads = 8):\n# prefix = '/train/trainset/list_clean_28w_20180803'\n image_shape = (image_shapes[1], image_shapes[2], image_shapes[3])\n batch_size = image_shapes[0]\n # data_nthreads = 8\n train = mx.io.ImageRecordIter(\n path_imgrec = prefix + '.rec',\n path_imgidx = prefix + '.idx',\n label_width = 1,\n# mean_r = 127.5,\n# mean_g = 127.5,\n# mean_b = 127.5,\n # std_r = rgb_std[0],\n # std_g = rgb_std[1],\n # std_b = rgb_std[2],\n data_name = 'data',\n label_name = 'softmax_label',\n data_shape = image_shape,\n batch_size = batch_size,\n resize = max(image_shapes[2], image_shapes[3]),\n # rand_crop = args.random_crop,\n # max_random_scale = args.max_random_scale,\n # pad = args.pad_size,\n # fill_value = args.fill_value,\n # random_resized_crop = args.random_resized_crop,\n # min_random_scale = args.min_random_scale,\n # max_aspect_ratio = args.max_random_aspect_ratio,\n # min_aspect_ratio = args.min_random_aspect_ratio,\n # max_random_area = args.max_random_area,\n # min_random_area = args.min_random_area,\n # min_crop_size = args.min_crop_size,\n # max_crop_size = args.max_crop_size,\n # brightness = args.brightness,\n # contrast = args.contrast,\n # saturation = args.saturation,\n # pca_noise = args.pca_noise,\n # random_h = args.max_random_h,\n # random_s = args.max_random_s,\n # random_l = args.max_random_l,\n # max_rotate_angle = args.max_random_rotate_angle,\n # max_shear_ratio = args.max_random_shear_ratio,\n # rand_mirror = args.random_mirror,\n preprocess_threads = data_nthreads,\n shuffle = True,\n scale = 1.0/255\n # num_parts = nworker,\n # part_index = rank,\n )\n return train\n# print dir(train)\nif __name__ == '__main__':\n start = time.time()\n data_iter = DataIter()\n for i in range(1000):\n data_batch = data_iter.next()\n print 'cost time: %e' % (time.time()-start)\n print data_batch.data[0].shape\n print data_batch.label[0].shape\n data_iter.reset()" }, { "alpha_fraction": 0.5486097931861877, "alphanum_fraction": 0.5831311941146851, "avg_line_length": 37.28571319580078, "blob_id": "48fa836a8f77a7a038516e0877991d70204c03b2", "content_id": "8a23277c1c2df6d0c2e77e38c59476e60b02cade", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5359, "license_type": "no_license", "max_line_length": 196, "num_lines": 140, "path": "/train2.py", "repo_name": "Line290/improve_partial_fc", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np\nimport mxnet as mx\nimport time\nimport cPickle\n# import custom_layers\nimport logging\nimport os\nos.environ[\"MXNET_CPU_WORKER_NTHREADS\"] = \"32\"\nimport skcuda.cublasxt as cublasxt\nimport math\nimport os\nimport scipy\n\nfrom data_iter import DataIter\nfrom mixmodule3 import create_net, mixModule\nsys.path.append('/train/execute/')\nfrom DataIter import PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new\n\n# ctx = [mx.gpu(i) for i in range(3)]\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nlogging.info('mxnet version %s', mx.__version__)\nctx = [mx.gpu(0)]\nhandle = cublasxt.cublasXtCreate()\n# mode = cublasxt.cublasXtGetPinningMemMode(handle)\ncublasxt.cublasXtSetPinningMemMode(handle, 1)\ncublasxt.cublasXtSetCpuRatio(handle, 0, 0, 0.9)\nnbDevices = len(ctx)\ndeviceId = np.array(range(nbDevices), np.int32)\ncublasxt.cublasXtDeviceSelect(handle, nbDevices, deviceId)\n\nnum_epoch = 1000000\nbatch_size = 64*nbDevices\nshow_period = 1000\n\nassert(batch_size%nbDevices==0)\nbsz_per_device = batch_size / nbDevices\n\nlogging.info('batch_size per device: %d', bsz_per_device)\nfeatdim = 512\ntotal_proxy_num = 285000\ndata_shape = (batch_size, 3, 240, 120)\nproxy_yM_shape = (batch_size, 1)\n# proxy_Z_shape = (featdim, total_proxy_num)\nproxy_Z_fn = '../proxy_Z.params'\nproxy_Z_fn_save = 'proxy_Z.params'\nproxy_Z = mx.nd.random.uniform(low=-0.5, high=0.5, \n shape=(total_proxy_num, featdim), \n dtype='float32', \n ctx=mx.cpu(0))\nprint proxy_Z.shape\n\nif os.path.exists(proxy_Z_fn):\n proxy_Z = mx.nd.load(proxy_Z_fn)[0]\n assert(total_proxy_num==proxy_Z.shape[0])\n logging.info('load proxy_Z from : %s', proxy_Z_fn)\ndlr = 1050000/batch_size\nradius = 32\nhardratio = 10**-5\nlr_start = 0.06\nlr_min = 10**-5\nlr_reduce = 0.96 #0.99\nlr_stepnum = np.log(lr_min/lr_start)/np.log(lr_reduce)\nlr_stepnum = np.int(np.ceil(lr_stepnum))\ndlr_steps = [dlr*i for i in xrange(1, lr_stepnum+1)]\nlogging.info('lr_start:%.1e, lr_min:%.1e, lr_reduce:%.2f, lr_stepsnum:%d',lr_start, lr_min, lr_reduce, lr_stepnum)\n# print dlr_steps\nlr_scheduler = mx.lr_scheduler.MultiFactorScheduler(dlr_steps, lr_reduce)\n\n# param_prefix = 'MDL_PARAM/params5_proxy_nca-8wmargin_20180724_dim_512_bn/person_reid-back'\nsave_prefix = './'\n# load_paramidx = 0 #None\n\n# DataBatch\n# data_path_prefix = '/train/trainset/list_clean_28w_20180803'\n# data_path_prefix = '/train/execute/improve_partial_fc/dataset/list_clean_28w_20180803'\n# data_iter = DataIter(prefix = data_path_prefix, image_shapes = data_shape, data_nthreads = 4)\n\nproxy_batch = 1049287\nproxy_num = 285000\n\ndatafn_list = ['/train/execute/listFolder/trainlist_reid/list_all_20180723.list']\ndata_iter = PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new(['data'], [data_shape], \n ['proxy_yM'], [proxy_yM_shape], \n datafn_list, \n total_proxy_num, \n featdim, \n proxy_batch, \n proxy_num, 1)\n# simple DataBatch test\n# data_batch = mx.random.normal(0, 1.0, shape=data_shape)\n# data_label = mx.nd.array(range(64), dtype='int32')\n# data_test = mx.io.DataBatch(data=[data_batch], label=[data_label])\nparam_prefix = 'MDL_PARAM/params5_proxy_nca-8wmargin_20180724_dim_512_bn/person_reid-back'\nload_paramidx = 2 #None\n\ndata = mx.sym.Variable('data')\npart_net = create_net(data, radius)\nmxmod = mixModule(\n symbol = part_net, \n context = ctx, \n handle = handle,\n hardratio = hardratio,\n data_shape = data_shape, \n proxy_Z = proxy_Z, \n K = 999, \n param_prefix = param_prefix, \n load_paramidx = load_paramidx)\n\n# mxmod.init_params(mx.init.Xavier())\nmxmod.init_optimizer(optimizer=\"sgd\", \n optimizer_params={\n \"learning_rate\": lr_start,\n 'lr_scheduler':lr_scheduler,\n 'clip_gradient':None,\n# \"wd\": 0.0005,\n# \"beta1\": beta1,\n })\n\n\nfor epoch in range(num_epoch):\n# for epoch in range(1):\n logging.info('Epoch [%d] start...',epoch)\n data_iter.do_reset()\n start = time.time()\n# data_test = data_iter.next()\n for batch_iter in range(dlr):\n# for batch_iter in range(1):\n# print type(data_iter.next())\n# print data_iter.next().data[0].shape, data_iter.next().label[0].shape\n mxmod.update(data_iter.next())\n# mxmod.update(data_test)\n if batch_iter % 5 == 0:\n logging.info('Iter [%d] speed %.2f samples/sec loss = %.2f ang = %.2f', batch_iter, batch_size*5/(time.time()-start), mxmod.get_loss().asnumpy(), mxmod.get_ang(radius).asnumpy())\n start = time.time()\n if batch_iter % 100 == 0:\n mxmod.save_checkpoint(save_prefix, epoch)\n mxmod.save_proxy_Z(proxy_Z_fn = proxy_Z_fn_save)" }, { "alpha_fraction": 0.5826966762542725, "alphanum_fraction": 0.6253223419189453, "avg_line_length": 53.51193618774414, "blob_id": "f3435890bb9e43bb9fddca47bd9330aee03dc6c4", "content_id": "f76abd59f31fcd33ffb2569ccd5c9dc1a0f2c98c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20551, "license_type": "no_license", "max_line_length": 170, "num_lines": 377, "path": "/mixmodule.py", "repo_name": "Line290/improve_partial_fc", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np\nimport mxnet as mx\nimport time\nimport cPickle\n# import custom_layers\nimport logging\n\nimport skcuda.cublasxt as cublasxt\nimport math\nimport os\nimport scipy\n\n# FEAT_DIM = 128\nFEAT_DIM = 512\n\ndef ConvFactory(data, num_filter, kernel, stride=(1, 1), pad=(0, 0), act_type=\"relu\", mirror_attr={}, with_act=True, namepre='', args=None):\n if args is None:\n weight = mx.sym.Variable(namepre+'_weight')\n bias = mx.sym.Variable(namepre+'_bias')\n gamma = mx.sym.Variable(namepre+'_gamma')\n beta = mx.sym.Variable(namepre+'_beta')\n args = {'weight':weight, 'bias':bias}\n else:\n weight = args['weight']\n bias = args['bias']\n gamma = args['gamma']\n beta = args['beta']\n \n conv = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, weight=weight, bias=bias, name=namepre+'_conv')\n bn = mx.symbol.BatchNorm(data=conv, gamma=gamma, beta=beta, name=namepre+'_bn')\n act = bn\n if with_act:\n act = mx.symbol.Activation(data=bn, act_type=act_type, attr=mirror_attr, name=namepre+'_act')\n return act, args\n\n\ndef stem(data, namepre='', args=None):\n if args is None:\n args = {'conv1a_3_3':None, 'conv2a_3_3':None, 'conv2b_3_3':None, 'conv3b_1_1':None, 'conv4a_3_3':None}\n conv1a_3_3, args['conv1a_3_3'] = ConvFactory(data=data, num_filter=32,\n kernel=(3, 3), stride=(2, 2), namepre=namepre+'_conv1a_3_3', args=args['conv1a_3_3'])\n conv2a_3_3, args['conv2a_3_3'] = ConvFactory(conv1a_3_3, 32, (3, 3), namepre=namepre+'_conv2a_3_3', args=args['conv2a_3_3'])\n conv2b_3_3, args['conv2b_3_3'] = ConvFactory(conv2a_3_3, 64, (3, 3), pad=(1, 1), namepre=namepre+'_conv2b_3_3', args=args['conv2b_3_3'])\n maxpool3a_3_3 = mx.symbol.Pooling(\n data=conv2b_3_3, kernel=(3, 3), stride=(2, 2), pool_type='max', name=namepre+'_maxpool3a_3_3')\n conv3b_1_1, args['conv3b_1_1'] = ConvFactory(maxpool3a_3_3, 80, (1, 1), namepre=namepre+'_conv3b_1_1', args=args['conv3b_1_1'])\n conv4a_3_3, args['conv4a_3_3'] = ConvFactory(conv3b_1_1, 192, (3, 3), namepre=namepre+'_conv4a_3_3', args=args['conv4a_3_3'])\n\n return conv4a_3_3, args \n\n\ndef reductionA(conv4a_3_3, namepre='', args=None):\n if args is None:\n args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv2_0':None, 'tower_conv2_1':None, 'tower_conv2_2':None, 'tower_conv3_1':None}\n maxpool5a_3_3 = mx.symbol.Pooling(\n data=conv4a_3_3, kernel=(3, 3), stride=(2, 2), pool_type='max', name=namepre+'_maxpool5a_3_3')\n\n tower_conv, args['tower_conv'] = ConvFactory(maxpool5a_3_3, 96, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])\n tower_conv1_0, args['tower_conv1_0'] = ConvFactory(maxpool5a_3_3, 48, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])\n tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 64, (5, 5), pad=(2, 2), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])\n\n tower_conv2_0, args['tower_conv2_0'] = ConvFactory(maxpool5a_3_3, 64, (1, 1), namepre=namepre+'_tower_conv2_0', args=args['tower_conv2_0'])\n tower_conv2_1, args['tower_conv2_1'] = ConvFactory(tower_conv2_0, 96, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_1', args=args['tower_conv2_1'])\n tower_conv2_2, args['tower_conv2_2'] = ConvFactory(tower_conv2_1, 96, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_2', args=args['tower_conv2_2'])\n\n tower_pool3_0 = mx.symbol.Pooling(data=maxpool5a_3_3, kernel=(\n 3, 3), stride=(1, 1), pad=(1, 1), pool_type='avg', name=namepre+'_tower_pool3_0')\n tower_conv3_1, args['tower_conv3_1'] = ConvFactory(tower_pool3_0, 64, (1, 1), namepre=namepre+'_tower_conv3_1', args=args['tower_conv3_1'])\n tower_5b_out = mx.symbol.Concat(\n *[tower_conv, tower_conv1_1, tower_conv2_2, tower_conv3_1])\n return tower_5b_out, args \n\n\ndef reductionB(net, namepre='', args=None):\n if args is None:\n args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv1_2':None}\n tower_conv, args['tower_conv'] = ConvFactory(net, 384, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv', args=args['tower_conv'])\n tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])\n tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 256, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])\n tower_conv1_2, args['tower_conv1_2'] = ConvFactory(tower_conv1_1, 384, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv1_2', args=args['tower_conv1_2'])\n tower_pool = mx.symbol.Pooling(net, kernel=(\n 3, 3), stride=(2, 2), pool_type='max', name=namepre+'_tower_pool')\n net = mx.symbol.Concat(*[tower_conv, tower_conv1_2, tower_pool])\n\n return net, args\n\n\ndef reductionC(net, namepre='', args=None):\n if args is None:\n args = {'tower_conv':None, 'tower_conv0_1':None, 'tower_conv1':None, 'tower_conv1_1':None, 'tower_conv2':None, 'tower_conv2_1':None, 'tower_conv2_2':None}\n tower_conv, args['tower_conv'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])\n tower_conv0_1, args['tower_conv0_1'] = ConvFactory(tower_conv, 384, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv0_1', args=args['tower_conv0_1'])\n tower_conv1, args['tower_conv1'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv1', args=args['tower_conv1'])\n tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1, 288, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])\n tower_conv2, args['tower_conv2'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv2', args=args['tower_conv2'])\n tower_conv2_1, args['tower_conv2_1'] = ConvFactory(tower_conv2, 288, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_1', args=args['tower_conv2_1'])\n tower_conv2_2, args['tower_conv2_2'] = ConvFactory(tower_conv2_1, 320, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv2_2', args=args['tower_conv2_2'])\n tower_pool = mx.symbol.Pooling(net, kernel=(3, 3), stride=(2, 2), pool_type='max', name=namepre+'_tower_pool')\n net = mx.symbol.Concat(*[tower_conv0_1, tower_conv1_1, tower_conv2_2, tower_pool])\n return net, args\n\n\ndef block35(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, namepre='', args=None):\n if args is None:\n args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv2_0':None, 'tower_conv2_1':None, 'tower_conv2_2':None, 'tower_out':None}\n tower_conv, args['tower_conv'] = ConvFactory(net, 32, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])\n tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 32, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])\n tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 32, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])\n tower_conv2_0, args['tower_conv2_0'] = ConvFactory(net, 32, (1, 1), namepre=namepre+'_tower_conv2_0', args=args['tower_conv2_0'])\n tower_conv2_1, args['tower_conv2_1'] = ConvFactory(tower_conv2_0, 48, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_1', args=args['tower_conv2_1'])\n tower_conv2_2, args['tower_conv2_2'] = ConvFactory(tower_conv2_1, 64, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_2', args=args['tower_conv2_2'])\n tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_1, tower_conv2_2])\n tower_out, args['tower_out'] = ConvFactory(\n tower_mixed, input_num_channels, (1, 1), with_act=False, namepre=namepre+'_tower_out', args=args['tower_out'])\n\n net = net + scale * tower_out\n act = net\n if with_act:\n act = mx.symbol.Activation(\n data=net, act_type=act_type, attr=mirror_attr, name=namepre+'_act')\n return act, args\n\n\ndef block17(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, namepre='', args=None):\n if args is None:\n args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv1_2':None, 'tower_out':None}\n tower_conv, args['tower_conv'] = ConvFactory(net, 192, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])\n tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 129, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])\n tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 160, (1, 7), pad=(1, 2), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])\n tower_conv1_2, args['tower_conv1_2'] = ConvFactory(tower_conv1_1, 192, (7, 1), pad=(2, 1), namepre=namepre+'_tower_conv1_2', args=args['tower_conv1_2'])\n tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_2])\n tower_out, args['tower_out'] = ConvFactory(\n tower_mixed, input_num_channels, (1, 1), with_act=False, namepre=namepre+'_tower_out', args=args['tower_out'])\n net = net + scale * tower_out\n act = net\n if with_act:\n act = mx.symbol.Activation(\n data=net, act_type=act_type, attr=mirror_attr, name=namepre+'_act')\n return act, args\n\n\ndef block8(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, namepre='', args=None):\n if args is None:\n args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv1_2':None, 'tower_out':None}\n tower_conv, args['tower_conv'] = ConvFactory(net, 192, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])\n tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 192, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])\n tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 224, (1, 3), pad=(0, 1), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])\n tower_conv1_2, args['tower_conv1_2'] = ConvFactory(tower_conv1_1, 256, (3, 1), pad=(1, 0), namepre=namepre+'_tower_conv1_2', args=args['tower_conv1_2'])\n tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_2])\n tower_out, args['tower_out'] = ConvFactory(\n tower_mixed, input_num_channels, (1, 1), with_act=False, namepre=namepre+'_tower_out', args=args['tower_out'])\n net = net + scale * tower_out\n act = net\n if with_act:\n act = mx.symbol.Activation(\n data=net, act_type=act_type, attr=mirror_attr, name=namepre+'_act')\n return act, args\n\n\ndef repeat(inputs, repetitions, layer, *ltargs, **kwargs):\n outputs = inputs\n namepre = kwargs['namepre']\n args = kwargs['args']\n if args is None:\n args = {}\n for i in xrange(repetitions):\n argname='repeat_'+str(i)\n args[argname] = None\n for i in range(repetitions):\n kwargs['namepre'] = namepre+'_'+str(i)\n argname='repeat_'+str(i)\n kwargs['args'] = args[argname]\n# print ltargs\n# print kwargs\n outputs, args[argname] = layer(outputs, *ltargs, **kwargs)\n\n return outputs, args\n\n\ndef create_inception_resnet_v2(data, namepre='', args=None):\n if args is None:\n args = {'stem':None, 'reductionA':None, 'repeat_block35':None, 'reductionB':None, \n 'repeat_block17':None, 'reductionC':None, 'repeat_block8':None, \n 'final_block8':None, 'final_conv':None, 'finalfc':None}\n\n stem_net, args['stem']= stem(data, namepre=namepre+'_stem', args=args['stem'])\n\n reduceA, args['reductionA'] = reductionA(stem_net, namepre=namepre+'_reductionA', args=args['reductionA'])\n\n repeat_block35, args['repeat_block35'] = repeat(reduceA, 2, block35, scale=0.17, input_num_channels=320, namepre=namepre+'_repeat_block35', args=args['repeat_block35'])\n\n\n reduceB, args['reductionB'] = reductionB(repeat_block35, namepre=namepre+'_reductionB', args=args['reductionB'])\n\n repeat_block17, args['repeat_block17'] = repeat(reduceB, 4, block17, scale=0.1, input_num_channels=1088, namepre=namepre+'_repeat_block17', args=args['repeat_block17'])\n\n reduceC, args['reductionC'] = reductionC(repeat_block17, namepre=namepre+'_reductionC', args=args['reductionC'])\n\n repeat_block8, args['repeat_block8'] = repeat(reduceC, 2, block8, scale=0.2, input_num_channels=2080, namepre=namepre+'_repeat_block8', args=args['repeat_block8'])\n final_block8, args['final_block8'] = block8(repeat_block8, with_act=False, input_num_channels=2080, namepre=namepre+'_final_block8', args=args['final_block8'])\n\n final_conv, args['final_conv'] = ConvFactory(final_block8, 1536, (1, 1), namepre=namepre+'_final_conv', args=args['final_conv'])\n final_pool = mx.symbol.Pooling(final_conv, kernel=(8, 8), global_pool=True, pool_type='avg', name=namepre+'_final_pool')\n# final_pool = mx.symbol.Pooling(final_conv, kernel=(5, 5), stride=(1, 1), pool_type='avg', name=namepre+'_final_pool')\n final_flatten = mx.symbol.Flatten(final_pool, name=namepre+'_final_flatten')\n\n drop1 = mx.sym.Dropout(data=final_flatten, p=0.5, name=namepre+'_dropout1')\n\n if args['finalfc'] is None:\n args['finalfc'] = {}\n args['finalfc']['weight'] = mx.sym.Variable(namepre+'_fc1_weight')\n args['finalfc']['bias'] = mx.sym.Variable(namepre+'_fc1_bias')\n \n reid_fc1 = mx.sym.FullyConnected(data=drop1, num_hidden=FEAT_DIM, name=namepre+\"_fc1\", \n weight=args['finalfc']['weight'], bias=args['finalfc']['bias']) \n# reid_act = mx.sym.Activation(data=reid_fc1, act_type='tanh', name=namepre+'_fc1_relu')\n\n net = reid_fc1\n# net = final_flatten\n\n return net, args\n\ndef create_net(data, radius):\n# data = mx.sym.Variable('data')\n args_all = None\n feat_final, args_all = create_inception_resnet_v2(data, namepre='part1', args=args_all)\n feat_final = mx.sym.BatchNorm(data=feat_final, fix_gamma=False, name='feat_bn1')\n\n\n min_value =10**-36\n norm_value = radius\n # norm_value = 24\n# logging.info('norm_value:%f, min_value:%e, hardratio:%f', norm_value, min_value, hardratio)\n logging.info('norm_value:%f, min_value:%e', norm_value, min_value)\n #norm\n znorm_loss = None\n if norm_value>0:\n # proxy_Z = mx.sym.L2Normalization(proxy_Z) * norm_value\n # feat_final = mx.sym.L2Normalization(feat_final) * norm_value\n# proxy_Znorm = mx.sym.sum_axis(proxy_Z**2, axis=1)\n# proxy_Znorm = mx.sym.sqrt(proxy_Znorm) + min_value\n\n# # znorm_loss = mx.sym.abs(proxy_Znorm - 1.0)\n# # znorm_loss = mx.sym.sum(znorm_loss)\n# # znorm_loss = mx.sym.MakeLoss(znorm_loss)\n\n# proxy_Znorm = mx.sym.Reshape(proxy_Znorm, shape=(-2, 1))\n# proxy_Z = mx.sym.broadcast_div(proxy_Z, proxy_Znorm)# * norm_value\n\n feat_finalnorm = mx.sym.sum_axis(feat_final**2, axis=1)\n feat_finalnorm = mx.sym.sqrt(feat_finalnorm) + min_value\n feat_finalnorm = mx.sym.Reshape(feat_finalnorm, shape=(-2, 1))\n feat_final = mx.sym.broadcast_div(feat_final, feat_finalnorm) * norm_value\n# X = mx.nd.empty(shape=(64, 10000000), ctx=mx.cpu(0))\n return feat_final\n\nclass mixModule(object):\n def __init__(self, symbol, context, handle, data_shape, proxy_Z, K):\n self.mod = mx.mod.Module(symbol=symbol, \n data_names=(\"data\",), \n label_names=None, \n context=context)\n self.mod.bind(data_shapes=[(\"data\", data_shape)])\n self.context = context if isinstance(context, list) else [context]\n self.handle = handle\n self.W = proxy_Z\n self.N = data_shape[0]\n self.C, self.M = self.W.shape\n self.score = np.empty((self.M, self.N), np.float32)\n self.X = np.empty((self.N, self.C), np.float32)\n self.K = K\n# self.history = mx.nd.zeros(shape=(self.C, self.M), ctx=mx.cpu(0), dtype='float32')\n self.history = np.zeros((self.C, self.M), np.float32)\n self.loss = None\n def init_params(self, *args, **kwargs):\n self.mod.init_params(*args, **kwargs)\n\n def init_optimizer(self, *args, **kwargs):\n self.mod.init_optimizer(*args, **kwargs)\n \n def update(self, data_batch):\n self.mod.forward(data_batch)\n self.X = self.mod.get_outputs()[0].asnumpy()\n y_true = data_batch.label[0].asnumpy().reshape(-1,1)\n y_true = y_true.astype(np.int32)\n def stream_cal_in_GPU(): \n cublasxt.cublasXtSgemm(self.handle,\n 'C', 'C', \n self.N, self.M, self.C, np.float32(1.0),\n self.X.ctypes.data, self.C, self.W.ctypes.data, self.M, np.float32(0.0),\n self.score.ctypes.data, self.N)\n cublasxt.cublasXtSetCpuRoutine(self.handle, 0, 0, stream_cal_in_GPU())\n self.score = self.score.T\n self.score = self.score - np.max(self.score, axis=1, keepdims=True)\n self.score = np.exp(self.score)\n self.score = self.score / np.sum(self.score, axis=1, keepdims=True)\n# print self.score.shape\n y_true_score = self.score[range(self.N), y_true.reshape(-1)]\n self.score[range(self.N), y_true.reshape(-1)] = self.score.min(axis = 1)\n \n TopK_idx = np.argpartition(self.score, -self.K, axis=1)[:, -self.K:]\n self.score[range(self.N), y_true.reshape(-1)] = y_true_score\n TopK_idx = np.hstack((TopK_idx, y_true))\n \n TopK_score = self.score[np.array(range(self.N)).reshape(-1,1), TopK_idx]\n y_true_reform = np.array([self.K]*self.N).reshape(-1,1)\n \n def softmax_loss(sparse_probs, y_true):\n \"\"\"\n Computes the loss and gradient for softmax classification.\n Inputs:\n - sparse_probs: Input data, of shape (N, K) where sparse_probs[i, j] is the probability for the jth\n class for the ith input.\n - y_true: Vector of labels, of shape (N,1) where y_true[i] is the label for probs[i] and\n 0 <= y_true[i] < K\n Returns a tuple of:\n - loss: Scalar giving the loss\n - d_sparse_score: shape: (N, K), Gradient of the loss with respect to sparse_score (not sparse_probs)\n \"\"\"\n N = sparse_probs.shape[0]\n # # Numerical stability\n # shifted_sparse_score = sparse_score - np.max(sparse_score, axis=1, keepdims=True)\n\n # Z = np.sum(np.exp(shifted_sparse_score), axis=1, keepdims=True)\n # log_probs = shifted_sparse_score - np.log(Z)\n # probs = np.exp(log_probs)\n log_sparse_probs = np.log(sparse_probs)\n loss = -np.sum(log_sparse_probs[np.arange(N), y_true.reshape(-1)]) / N\n d_sparse_score = sparse_probs.copy()\n d_sparse_score[np.arange(N), y_true.reshape(-1)] -= 1\n # rescale gradient\n d_sparse_score /= N\n return loss, d_sparse_score\n \n self.loss, d_TopK_score = softmax_loss(TopK_score, y_true_reform)\n print 'loss: ', self.loss\n self.score[...] = 0\n self.score[np.array(range(self.N)).reshape(-1,1), TopK_idx] = d_TopK_score\n \n# d_score = mx.nd.array(self.score, dtype='float32')\n# csr_d_score = d_score.tostype('csr')\n csr_d_score = scipy.sparse.csr_matrix(self.score)\n self.score = self.score.T\n# feat_final = mx.nd.array(self.X, dtype='float32', ctx=mx.cpu(0))\n# proxy_Z = mx.nd.array(self.W, dtype='float32', ctx=mx.cpu(0))\n \n# d_proxy_Z = mx.ndarray.sparse.dot(feat_final.T, csr_d_score)\n# print csr_d_score.shape, self.X.shape\n d_proxy_Z = csr_d_score.T.dot(self.X).T\n# print d_proxy_Z.shape\n# d_feat_final = mx.nd.dot(csr_d_score, proxy_Z.T)\n d_feat_final = csr_d_score.dot(self.W.T)\n d_feat_final = mx.nd.array(d_feat_final, dtype='float32', ctx=mx.gpu(0))\n # backprop\n self.mod.backward([d_feat_final])\n\n # update W\n num_iter = self.mod._optimizer.num_update\n lr = self.mod._optimizer._get_lr(num_iter)\n wd = self.mod._optimizer._get_wd(num_iter)\n eps = self.mod._optimizer.epsilon\n# print 'iter: %d, lr: %e' % (num_iter, lr)\n self.history[:] += (d_proxy_Z**2)\n# proxy_Z[:] += -lr * (d_proxy_Z / (self.history + eps).sqrt() + wd * proxy_Z)\n self.W[:] += -lr * (d_proxy_Z / np.sqrt(self.history + eps) + wd * self.W)\n# self.W = proxy_Z.asnumpy()\n# self.W = proxy_Z\n # update module\n self.mod.update()\n def save_proxy_Z(self, proxy_Z_fn): \n # save proxy_Z(W) after a certain number of self.mod._optimizer.num_update\n# if num_iter%1000 == 0:\n np.save(proxy_Z_fn, self.W)\n print 'Save proxy_Z in \"%s\"' % (proxy_Z_fn)\n def get_loss(self):\n return self.loss\n" }, { "alpha_fraction": 0.5855016112327576, "alphanum_fraction": 0.6095172166824341, "avg_line_length": 28.336719512939453, "blob_id": "1d7984ff24e5535a8ce62c0abd2b3cfeb39f5cfb", "content_id": "b49e544eda75c720c496aca3482a09bf09cb10fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40432, "license_type": "no_license", "max_line_length": 131, "num_lines": 1378, "path": "/DataGenerator.py", "repo_name": "Line290/improve_partial_fc", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport cPickle\nimport os\nimport mxnet as mx\nimport time\nimport pdb\n#datafn = '/media/data1/mzhang/data/car_ReID_for_zhangming/data/data.list'\ndatafn = './listFolder/trainlist_reid/chongxun.list'\ndef get_datalist(datafn):\n datafile = open(datafn, 'r')\n datalist = datafile.readlines()\n datalen = len(datalist)\n for di in xrange(datalen):\n datalist[di] = datalist[di].replace('\\n', '')\n \n datafile.close()\n \n return datalist\n\n\ndef get_datalist2(datafn_list):\n datalist = []\n for datafn in datafn_list:\n datalist += get_datalist(datafn) \n return datalist\n\n\ndef get_proxyset(proxyfn, proxyshape):\n proxy_set = []\n if os.path.isfile(proxyfn):\n print 'loading proxy set from ', proxyfn\n proxy_set = cPickle.load(open(proxyfn, 'rb'))\n assert(proxy_set.shape==proxyshape)\n return proxy_set\n\n print 'creating proxy set to ', proxyfn\n p = np.random.rand(proxyshape[0], proxyshape[1]) - 0.5 \n p = p.astype(dtype=np.float32)\n if True:\n pn = np.sqrt(np.sum(p*p, axis=1))\n pn = np.reshape(pn, (pn.shape[0], 1))\n proxy_set = p / pn * 4.0\n else:\n proxy_set = p\n cPickle.dump(proxy_set, open(proxyfn, 'wb'));\n return proxy_set\n\n\ndef get_pairs_data_label(data_infos, label_infos, datalist, data_rndidx, batch_now):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n neednum = batchsize / 2 + 1\n if (batch_now+1)*neednum > len(datalist):\n return None\n \n data_batch = []\n for idx in data_rndidx[batch_now*neednum:(batch_now+1)*neednum]:\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['sons'] = parts[1:]\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n same_num = batchsize / 2\n diff_num = batchsize - same_num\n dataidx = 0\n datas = {}\n labels = {}\n datas['part1_data'] = np.zeros(data_infos[0][1], dtype=np.float32)\n datas['part2_data'] = np.zeros(data_infos[1][1], dtype=np.float32)\n labels['label'] = np.zeros(label_infos[0][1], dtype=np.float32)\n #ready same data\n for si in xrange(same_num):\n onecar = cars[si]\n carpath = onecar['path']\n carsons = onecar['sons']\n rndidx = np.random.permutation(len(carsons))\n tmpath = carpath+'/'+carsons[rndidx[0]]\n son0 = cv2.imread(tmpath)\n# print 0, tmpath, son0.shape, stdsize\n stdson0 = cv2.resize(son0, (stdsize[1], stdsize[0]))\n stdson0 = stdson0.astype(np.float32) / 255.0\n tmpath = carpath+'/'+carsons[rndidx[1]]\n son1 = cv2.imread(tmpath)\n# print 1, tmpath, son1.shape, stdsize\n stdson1 = cv2.resize(son1, (stdsize[1], stdsize[0]))\n stdson1 = stdson1.astype(np.float32) / 255.0\n datas['part1_data'][dataidx, 0] = stdson0[:, :, 0]\n datas['part1_data'][dataidx, 1] = stdson0[:, :, 1]\n datas['part1_data'][dataidx, 2] = stdson0[:, :, 2]\n datas['part2_data'][dataidx, 0] = stdson1[:, :, 0]\n datas['part2_data'][dataidx, 1] = stdson1[:, :, 1]\n datas['part2_data'][dataidx, 2] = stdson1[:, :, 2]\n labels['label'][dataidx] = 1\n dataidx += 1\n\n #ready diff data\n for si in xrange(diff_num):\n rndidx = np.random.permutation(len(cars))\n car0 = cars[rndidx[0]]\n car0len = len(car0['sons'])\n car1 = cars[rndidx[1]]\n car1len = len(car1['sons'])\n son0 = cv2.imread(car0['path']+'/'+car0['sons'][np.random.randint(0, car0len)])\n stdson0 = cv2.resize(son0, (stdsize[1], stdsize[0]))\n stdson0 = stdson0.astype(np.float32) / 255.0\n son1 = cv2.imread(car1['path']+'/'+car1['sons'][np.random.randint(0, car1len)])\n stdson1 = cv2.resize(son1, (stdsize[1], stdsize[0]))\n stdson1 = stdson1.astype(np.float32) / 255.0\n datas['part1_data'][dataidx, 0] = stdson0[:, :, 0]\n datas['part1_data'][dataidx, 1] = stdson0[:, :, 1]\n datas['part1_data'][dataidx, 2] = stdson0[:, :, 2]\n datas['part2_data'][dataidx, 0] = stdson1[:, :, 0]\n datas['part2_data'][dataidx, 1] = stdson1[:, :, 1]\n datas['part2_data'][dataidx, 2] = stdson1[:, :, 2]\n labels['label'][dataidx] = -1\n dataidx += 1\n\n return datas, labels\n\n\ndef get_data_label_test(data_shape, datalist, which_car\n , normalize=True):\n \"\"\"\n data_shape: (chn, h, w)\n datalist: string list\n which_car: query which car\n \"\"\"\n query_line = datalist[which_car]\n onecar = {}\n parts = query_line.split(',')\n onecar['path'] = parts[0]\n onecar['sons'] = parts[1:]\n num_sons = len(onecar['sons'])\n parts2 = onecar['path'].split('/')\n onecar['id'] = parts2[-1]\n stdsize = data_shape[1:]\n# print data_shape, stdsize\n carinfo = {}\n carinfo['id'] = onecar['id']\n carinfo['sons'] = []\n t0 = time.time()\n for si in xrange(num_sons):\n queryone = onecar['sons'][si]\n tmppath = onecar['path'] + '/' + queryone\n sonimg = cv2.imread(tmppath) \n stdson = cv2.resize(sonimg, (stdsize[1], stdsize[0]))\n stdson = stdson.astype(np.float32) / 255.0\n if normalize:\n stdson = get_normalization(stdson)\n stdson_tmp = np.zeros((3,)+stdsize, dtype=np.float32)\n stdson_tmp[0] = stdson[:, :, 0]\n stdson_tmp[1] = stdson[:, :, 1]\n stdson_tmp[2] = stdson[:, :, 2]\n soninfo = {}\n soninfo['name'] = queryone\n soninfo['data'] = stdson_tmp\n carinfo['sons'].append(soninfo)\n t1 = time.time()\n print 'get_data_label_test:', t1-t0\n \n return carinfo\n\n\ndef get_feature_label_test__(data_shape, datalist, which_car):\n \"\"\"\n data_shape: (chn, h, w)\n datalist: string list\n which_car: query which car\n \"\"\"\n query_line = datalist[which_car]\n onecar = {}\n parts = query_line.split(',')\n onecar['path'] = parts[0]\n onecar['sons'] = parts[1:]\n num_sons = len(onecar['sons'])\n parts2 = onecar['path'].split('/')\n onecar['id'] = parts2[-1]\n stdsize = data_shape[1:]\n# print data_shape, stdsize\n carinfo = {}\n carinfo['id'] = onecar['id']\n carinfo['sons'] = []\n for si in xrange(num_sons):\n queryone = onecar['sons'][si]\n tmppath = onecar['path'] + '/' + queryone\n sonfeat = cPickle.load(open(tmppath, 'rb'))\n soninfo = {}\n soninfo['name'] = queryone\n soninfo['data'] = sonfeat.reshape(data_shape)\n carinfo['sons'].append(soninfo)\n \n return carinfo\n\n\ndef get_feature_label_query_test(data_shape, datalist, which_idx):\n \"\"\"\n data_shape: (batch, chn, h, w)\n datalist: string list\n which_idx: query a batch \n \"\"\"\n batchsize = data_shape[0]\n query_line = datalist[which_idx]\n batch_info = {'paths':[], 'ids':[], 'names':[], 'data':np.zeros(data_shape, dtype=np.float32)}\n for qli in xrange(batchsize):\n parts = query_line.split(',')\n pathpre = parts[0]\n namenow = parts[1]\n pathnow = pathpre + '/' + namenow\n parts2 = pathpre.split('/')\n idnow = parts2[-1]\n featnow = cPickle.load(open(pathnow, 'rb'))\n batch_info['data'][qli] = featnow[0]\n batch_info['paths'].append(pathnow)\n batch_info['ids'].append(idnow)\n batch_info['names'].append(namenow)\n \n return batch_info\n\n\ndef get_feature_label_test(data_shape, datalist, which_batch):\n \"\"\"\n data_shape: (batch, chn, h, w)\n datalist: string list\n which_batch: query a batch \n \"\"\"\n batchsize = data_shape[0]\n query_batch = datalist[which_batch*batchsize:(which_batch+1)*batchsize]\n batch_info = {'paths':[], 'ids':[], 'names':[], 'data':np.zeros(data_shape, dtype=np.float32)}\n t0 = time.time()\n for qli, query_line in enumerate(query_batch):\n parts = query_line.split(',')\n pathpre = parts[0]\n namenow = parts[1]\n pathnow = pathpre + '/' + namenow\n parts2 = pathpre.split('/')\n idnow = parts2[-1]\n featnow = cPickle.load(open(pathnow, 'rb'))\n batch_info['data'][qli] = featnow[0]\n batch_info['paths'].append(pathnow)\n batch_info['ids'].append(idnow)\n batch_info['names'].append(namenow)\n t1 = time.time()\n print 'label_test:', t1-t0\n \n return batch_info\n\n\ndef get_pairs_data_label_rnd(data_infos, label_infos):\n datas = {}\n for dinfo in data_infos:\n# datas[dinfo[0]] = np.zeros(dinfo[1])\n datas[dinfo[0]] = np.random.rand(*dinfo[1])\n labels = {}\n for linfo in label_infos:\n# labels[linfo[0]] = np.zeros(linfo[1])\n rndlabels = np.random.binomial(1, 0.5, linfo[1])\n rndlabels[rndlabels==0] = -1\n labels[linfo[0]] = rndlabels\n# print rndlabels\n\n return datas, labels\n\n\ndef get_data_label(data_infos, label_infos, datalist, data_rndidx, batch_now, \n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[0].split('/')[-1]\n# print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n datas = {}\n labels = {}\n datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)\n labels['label'] = np.zeros(label_infos[0][1], dtype=np.float32)\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n son = cv2.imread(tmpath)\n if rndcrop:\n son = get_rnd_crop(son)\n# print 0, tmpath, son0.shape, stdsize\n stdson = cv2.resize(son, (stdsize[1], stdsize[0]))\n stdson = stdson.astype(np.float32) / 255.0\n if rndcont:\n stdson = get_rnd_contrast(stdson)\n if rndnoise:\n stdson = get_rnd_noise(stdson)\n if normalize:\n stdson = get_normalization(stdson)\n if rndrotate:\n stdson = get_rnd_rotate(stdson)\n if rndhflip:\n stdson = get_rnd_hflip(stdson)\n# print carid, stdson\n datas['data'][si, 0] = stdson[:, :, 0]\n datas['data'][si, 1] = stdson[:, :, 1]\n datas['data'][si, 2] = stdson[:, :, 2]\n labels['label'][si] = carid\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n\n return datas, labels\n\n\ndef get_data_label_proxy(data_infos, label_infos, datalist, data_rndidx, proxyset, batch_now, \n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[0].split('/')[-1]\n# print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n datas = {}\n labels = {}\n datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)\n labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)\n# labels['proxy_Z'] = np.zeros(label_infos[1][1], dtype=np.float32)\n labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n son = cv2.imread(tmpath)\n if rndcrop:\n son = get_rnd_crop(son)\n# print 0, tmpath, son0.shape, stdsize\n stdson = cv2.resize(son, (stdsize[1], stdsize[0]))\n stdson = stdson.astype(np.float32) / 255.0\n if rndcont:\n stdson = get_rnd_contrast(stdson)\n if rndnoise:\n stdson = get_rnd_noise(stdson)\n if normalize:\n stdson = get_normalization(stdson)\n if rndrotate:\n stdson = get_rnd_rotate(stdson)\n if rndhflip:\n stdson = get_rnd_hflip(stdson)\n# print carid, stdson\n datas['data'][si, 0] = stdson[:, :, 0]\n datas['data'][si, 1] = stdson[:, :, 1]\n datas['data'][si, 2] = stdson[:, :, 2]\n labels['proxy_yM'][si, carid] = 1\n# labels['proxy_Z'][:] = proxyset\n labels['proxy_ZM'][si, carid] = 0\n# print proxyset[carid], np.sum(proxyset[carid] * proxyset[carid])\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n\n datas = [mx.nd.array(datas['data'])]\n labels = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]\n\n return datas, labels\n\n\n\n\ndef get_rnd_crop(img):\n imgh, imgw = img.shape[:2]\n rndmg = np.random.randint(0, 10, 4)/100.0\n mgs = [imgh*rndmg[0], imgh*rndmg[1], imgw*rndmg[2], imgw*rndmg[3]]\n cropimg = img[mgs[0]:imgh-mgs[1], mgs[2]:imgw-mgs[3]]\n return cropimg\n\n\ndef get_rnd_contrast(img):\n rndv = np.random.randint(75, 100)/100.0\n img *= rndv\n\n return img\n\ndef get_rnd_noise(img):\n rndv = np.random.randint(1, 20) / 1000.0\n gauss = np.random.normal(0, rndv, img.shape)\n img += gauss\n img[img<0] = 0\n img[img>1.0] = 1.0\n\n return img\n\n\ndef get_rnd_rotate(img):\n imgh, imgw = img.shape[:2]\n rndv = np.random.randint(-30, 30)#*3.1415/180\n# print rndv\n rotmat = cv2.getRotationMatrix2D((imgw/2, imgh/2), rndv, 1.0)\n rotimg = cv2.warpAffine(img, rotmat, (imgw, imgh))\n\n return rotimg\n\n\ndef get_rnd_hflip(img):\n rndv = np.random.rand()\n hfimg = img\n if rndv<0.5:\n hfimg = img[:, ::-1]\n\n return hfimg\n\n\ndef get_normalization_rgb(img):\n mean = img.mean(axis=(0, 1))\n std = img.std(axis=(0, 1))\n nimg = (img-mean)/std\n\n return nimg\n\n\ndef get_normalization(img):\n mean = img.mean()\n std = img.std()\n nimg = (img-mean)/std\n\n return nimg\n\n\n\n \n\n\n#format: path,imgname\ndef get_data_label_proxy_mxnet(data_infos, label_infos, datalist, data_rndidx, batch_now, \n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[0].split('/')[-1]\n# print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n datas = {}\n labels = {}\n datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)\n labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)\n labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)\n \n imgs = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n# son = mx.image.imdecode(open(tmpath).read())\n son = cv2.imread(tmpath)\n imgs.append(son)\n\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n \n son = imgs[si] \n# son = son.asnumpy()\n# print son.shape\n if rndcrop:\n son = get_rnd_crop(son)\n# print 0, tmpath, son0.shape, stdsize\n stdson = cv2.resize(son, (stdsize[1], stdsize[0]))\n stdson = stdson.astype(np.float32) / 255.0\n if rndcont:\n stdson = get_rnd_contrast(stdson)\n if rndnoise:\n stdson = get_rnd_noise(stdson)\n if normalize:\n stdson = get_normalization(stdson)\n if rndrotate:\n stdson = get_rnd_rotate(stdson)\n if rndhflip:\n stdson = get_rnd_hflip(stdson)\n# print carid, stdson\n datas['data'][si, 0] = stdson[:, :, 0]\n datas['data'][si, 1] = stdson[:, :, 1]\n datas['data'][si, 2] = stdson[:, :, 2]\n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [mx.nd.array(datas['data'])]\n label_nd = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]\n return datas_nd, label_nd\n\n\nfrom ctypes import *\nfunc_c = CDLL('/train/execute/augmentation_threads/libaugment.so')\ndef aug_threads_c(paths, tmpshape):\n imgnum, chs, stdH, stdW = tmpshape \n imgsout = np.zeros((imgnum, stdH, stdW, chs), dtype=np.float32)\n strs = (c_char_p*imgnum)()\n strs[:] = paths\n# t0 = time.time()\n func_c.do_augment_threads(strs, imgnum, stdH, stdW,\n imgsout.ctypes.data_as(POINTER(c_float)))\n# t1 = time.time()\n# print t1-t0\n# for i in xrange(imgnum):\n# img = imgsout[i]\n# cv2.imshow('hi', img)\n# cv2.waitKey(0)\n return imgsout\n\n\ndef aug_threads_c2(paths, tmpshape, imgsout):\n imgnum, chs, stdH, stdW = tmpshape \n strs = (c_char_p*imgnum)()\n strs[:] = paths\n# t0 = time.time()\n func_c.do_augment_threads(strs, imgnum, stdH, stdW,\n imgsout.ctypes.data_as(POINTER(c_float)))\n# t1 = time.time()\n# print t1-t0\n for i in xrange(imgnum):\n img = imgsout[i]\n img = img.swapaxes(0, 1)\n img = img.swapaxes(1, 2)\n cv2.imshow('hi', img)\n cv2.waitKey(0)\n\n\ndef aug_plate_threads_c(paths, tmpshape, imgsout):\n imgnum, chs, stdH, stdW = tmpshape \n# plates = np.asarray(tmpplates)\n strs = (c_char_p*imgnum)()\n strs[:] = paths\n# t0 = time.time()\n #hu\n# print \"hahhhha\"\n func_c.do_augment_threads(strs, imgnum, stdH, stdW, imgsout.ctypes.data_as(POINTER(c_float)))\n #print \"haha\"\n# func_c.do_augment_person_threads(strs, \n# imgnum, stdH, stdW, imgsout.ctypes.data_as(POINTER(c_float)))\n# t1 = time.time()\n# print t1-t0\n if False:\n for i in xrange(imgnum):\n # print i, plates[i]\n img = imgsout[i]*255\n# img = imgsout[i]*50+100\n# img[img>255.0] = 255.0\n# img[img<0.0] = 0.0\n img = img.astype(np.uint8)\n img = img.swapaxes(0, 1)\n img = img.swapaxes(1, 2)\n print 'str(i): ', str(i)\n imgpath = '/home/xiangsun/listFolder/imgAug/' + str(i) + '.jpg'\n cv2.imwrite(imgpath, img)\n print img.shape, imgpath\n #assert(i<5)\n exit() \n \n \n# cv2.imshow('hi', img)\n# cv2.waitKey(0)\n \n pass\n\ndef get_test_threads_c(paths, tmpshape, imgsout):\n _, chs, stdH, stdW = tmpshape \n imgnum = len(paths)\n strs = (c_char_p*imgnum)()\n strs[:] = paths\n# t0 = time.time()\n func_c.do_get_test_threads(strs, imgnum, stdH, stdW, imgsout.ctypes.data_as(POINTER(c_float)))\n# t1 = time.time()\n# print t1-t0\n if False:\n for i in xrange(imgnum):\n img = imgsout[i]*255\n img = img.swapaxes(0, 1)\n img = img.swapaxes(1, 2)\n imgpath = '/home/xiangsun/listFolder/imgAug/test/' + str(i) + '.jpg'\n cv2.imwrite(imgpath, img)\n print img.shape, imgpath\n exit()\n# for i in xrange(imgnum):\n# img = imgsout[i]\n# img = img.swapaxes(0, 1)\n# img = img.swapaxes(1, 2)\n# cv2.imshow('hi', img)\n# cv2.waitKey(0)\n pass\n\n\n\n#format: path,imgname\ndef get_data_label_proxy_mxnet_threads(data_infos, datas, label_infos, labels, datalist, data_rndidx, batch_now, \n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n #onecar['id'] = parts[0].split('/')[-1]\n onecar['id'] = parts[-1]\n print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n labels['proxy_yM'][:] = 0\n labels['proxy_ZM'][:] = 1.0\n \n tmpaths = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n \n aug_data = datas['databuffer']\n aug_threads_c2(tmpaths, data_infos[0][1], aug_data)\n datas['data'][:] = aug_data\n\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n datas_nd = [datas['data']]\n label_nd = [labels['proxy_yM'], labels['proxy_ZM']]\n return datas_nd, label_nd\n\n\n\n\n#format: path,imgname,idnumber\ndef get_data_label_proxy_mxnet2(data_infos, label_infos, datalist, data_rndidx, batch_now, \n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[2]\n# print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n datas = {}\n labels = {}\n datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)\n labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)\n labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)\n \n imgs = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n# son = mx.image.imdecode(open(tmpath).read())\n son = cv2.imread(tmpath)\n imgs.append(son)\n\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n \n son = imgs[si] \n# son = son.asnumpy()\n# print son.shape\n if rndcrop:\n son = get_rnd_crop(son)\n# print 0, tmpath, son0.shape, stdsize\n stdson = cv2.resize(son, (stdsize[1], stdsize[0]))\n stdson = stdson.astype(np.float32) / 255.0\n if rndcont:\n stdson = get_rnd_contrast(stdson)\n if rndnoise:\n stdson = get_rnd_noise(stdson)\n if normalize:\n stdson = get_normalization(stdson)\n if rndrotate:\n stdson = get_rnd_rotate(stdson)\n if rndhflip:\n stdson = get_rnd_hflip(stdson)\n# print carid, stdson\n datas['data'][si, 0] = stdson[:, :, 0]\n datas['data'][si, 1] = stdson[:, :, 1]\n datas['data'][si, 2] = stdson[:, :, 2]\n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [mx.nd.array(datas['data'])]\n label_nd = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]\n return datas_nd, label_nd\n\n\n#format: path,imgname,idnumber\ndef get_data_label_proxy_mxnet2_threads(data_infos, datas, label_infos, labels, datalist, data_rndidx, batch_now, \n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[2]\n# print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n labels['proxy_yM'][:] = 0 \n labels['proxy_ZM'][:] = 1.0 \n \n tmpaths = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n \n aug_data = datas['databuffer']\n aug_threads_c2(tmpaths, data_infos[0][1], aug_data)\n datas['data'][:] = aug_data\n\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n \n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n# t2 = time.time() \n datas_nd = [datas['data']]\n label_nd = [labels['proxy_yM'], labels['proxy_ZM']]\n# print t2-t1, t1-t0\n return datas_nd, label_nd\n\n\n\n#format: path,imgname\ndef get_data_label_proxy_batch_mxnet(data_infos, label_infos, datalist, batch_now, \n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n idlist = []\n batch_info = []\n for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):\n data_batch.append(datalist[idx])\n idlist.append(idx)\n cars = []\n for idx, onedata in zip(idlist, data_batch):\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[-1] \n# print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])\n batch_info.append(oneinfo)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n datas = {}\n labels = {}\n datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)\n labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)\n labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)\n \n imgs = []\n carids = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carids.append(carid)\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n# son = mx.image.imdecode(open(tmpath).read())\n son = cv2.imread(tmpath)\n imgs.append(son)\n\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n \n son = imgs[si] \n# son = son.asnumpy()\n# print son.shape\n if rndcrop:\n son = get_rnd_crop(son)\n# print 0, tmpath, son0.shape, stdsize\n stdson = cv2.resize(son, (stdsize[1], stdsize[0]))\n stdson = stdson.astype(np.float32) / 255.0\n if rndcont:\n stdson = get_rnd_contrast(stdson)\n if rndnoise:\n stdson = get_rnd_noise(stdson)\n if normalize:\n stdson = get_normalization(stdson)\n if rndrotate:\n stdson = get_rnd_rotate(stdson)\n if rndhflip:\n stdson = get_rnd_hflip(stdson)\n# print carid, stdson\n datas['data'][si, 0] = stdson[:, :, 0]\n datas['data'][si, 1] = stdson[:, :, 1]\n datas['data'][si, 2] = stdson[:, :, 2]\n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [mx.nd.array(datas['data'])]\n label_nd = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]\n return datas_nd, label_nd, carids, batch_info\n\n\n#format: path,imgname\ndef get_data_label_proxy_batch_mxnet_threads(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum,\n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n# t0 = time.time()\n data_batch = []\n idlist = []\n batch_info = []\n for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):\n data_batch.append(datalist[idx])\n idlist.append(idx)\n cars = []\n for idx, onedata in zip(idlist, data_batch):\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[-1] \n# print onecar['id']\n onecar['son'] = parts[1]\n cars.append(onecar)\n carid = int(onecar['id'])\n oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])\n batch_info.append(oneinfo)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n labels['proxy_yM'][:] = 0\n labels['proxy_ZM'][:] = 1.0 \n \n tmpaths = []\n carids = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carids.append(carid)\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n \n# t1 = time.time()\n# aug_data = aug_threads_c(tmpaths, data_infos[0][1])\n aug_data = datas['databuffer']\n aug_threads_c2(tmpaths, data_infos[0][1], aug_data)\n# t2 = time.time()\n\n# aug_data = aug_data.swapaxes(2, 3)\n# aug_data = aug_data.swapaxes(1, 2)\n# t3 = time.time()\n datas['data'][:] = aug_data\n\n# t4 = time.time()\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n\n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n labels['proxy_ZM'][si, caridnum:] = 0\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [datas['data']]\n label_nd = [labels['proxy_yM'], labels['proxy_ZM']]\n# t5 = time.time()\n# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0\n\n return datas_nd, label_nd, carids, batch_info\n\n\ndef get_data_label_proxy_batch_plate_mxnet_threads_nsoftmax(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n# t0 = time.time()\n data_batch = []\n batch_info = []\n# rndidx_list = np.random.permutation(len(datalist))\n for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):\n# for bi in xrange(batchsize):\n# idx = rndidx_list[bi]\n data_batch.append(datalist[idx])\n cars = []\n# pdb.set_trace()\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[-1] \n# print onecar['id']\n onecar['son'] = parts[1]\n #p = parts[2].replace(' ', ',')\n #onecar['plate'] = np.asarray(eval(p), dtype=np.int32)\n cars.append(onecar)\n carid = int(onecar['id'])\n oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])\n batch_info.append(oneinfo)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n labels['proxy_yM'][:] = 0\n \n tmpaths = []\n # tmpplates = []\n carids = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carids.append(carid)\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n # tmpplates.append(onecar['plate'])\n \n# t1 = time.time()\n# aug_data = aug_threads_c(tmpaths, data_infos[0][1])\n aug_data = datas['databuffer']\n aug_plate_threads_c(tmpaths, data_infos[0][1], aug_data)\n# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)\n# t2 = time.time()\n\n# aug_data = aug_data.swapaxes(2, 3)\n# aug_data = aug_data.swapaxes(1, 2)\n# t3 = time.time()\n datas['data'][:] = aug_data\n\n# t4 = time.time()\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n\n labels['proxy_yM'][si, 0] = carid\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [datas['data']]\n label_nd = [labels['proxy_yM']]\n# t5 = time.time()\n# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0\n\n return datas_nd, label_nd, carids, batch_info\n\n\n\ndef get_data_label_proxy_batch_plate_mxnet_threads(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum,\n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n# t0 = time.time()\n data_batch = []\n batch_info = []\n# rndidx_list = np.random.permutation(len(datalist))\n for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):\n# for bi in xrange(batchsize):\n# idx = rndidx_list[bi]\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[-1] \n# print onecar['id']\n onecar['son'] = parts[1]\n #p = parts[2].replace(' ', ',')\n #onecar['plate'] = np.asarray(eval(p), dtype=np.int32)\n cars.append(onecar)\n carid = int(onecar['id'])\n oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])\n batch_info.append(oneinfo)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n labels['proxy_yM'][:] = 0\n # for loss with margin\n #labels['proxy_ZM'][:] = 1.0 \n \n tmpaths = []\n # tmpplates = []\n carids = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carids.append(carid)\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n # tmpplates.append(onecar['plate'])\n \n# t1 = time.time()\n# aug_data = aug_threads_c(tmpaths, data_infos[0][1])\n aug_data = datas['databuffer']\n aug_plate_threads_c(tmpaths, data_infos[0][1], aug_data)\n# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)\n# t2 = time.time()\n\n# aug_data = aug_data.swapaxes(2, 3)\n# aug_data = aug_data.swapaxes(1, 2)\n# t3 = time.time()\n datas['data'][:] = aug_data\n\n# t4 = time.time()\n #ready same data\n #dim2 = labels['proxy_ZM'].shape[1] # for loss with margin\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n\n labels['proxy_yM'][si, 0] = carid\n '''\n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n if caridnum < dim2:\n labels['proxy_ZM'][si, caridnum:] = 0\n '''\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [datas['data']]\n # for loss with margin\n #label_nd = [labels['proxy_yM'], labels['proxy_ZM']]\n label_nd = [labels['proxy_yM']]\n# t5 = time.time()\n# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0\n# pdb.set_trace()\n# print datas_nd\n# print label_nd\n return datas_nd, label_nd, carids, batch_info\n\n\ndef get_data_label_proxy_batch_plate_mxnet_threads2(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum,\n rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,\n rndhflip=True, normalize=True):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n# t0 = time.time()\n data_batch = []\n batch_info = []\n# rndidx_list = np.random.permutation(len(datalist))\n for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):\n# for bi in xrange(batchsize):\n# idx = rndidx_list[bi]\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[-1] \n# print onecar['id']\n onecar['son'] = parts[1]\n p = parts[2].replace(' ', ',')\n onecar['plate'] = np.asarray(eval(p), dtype=np.int32)\n cars.append(onecar)\n carid = int(onecar['id'])\n oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])\n batch_info.append(oneinfo)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n labels['proxy_yM'][:] = 0\n labels['proxy_ZM'][:] = 1.0 \n \n tmpaths = []\n tmpplates = []\n carids = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carids.append(carid)\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n tmpplates.append(onecar['plate'])\n \n# t1 = time.time()\n# aug_data = aug_threads_c(tmpaths, data_infos[0][1])\n aug_data = datas['databuffer']\n print \"******************\"\n aug_plate_threads_c(tmpaths, tmpplates, data_infos[0][1], aug_data)\n# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)\n# t2 = time.time()\n\n# aug_data = aug_data.swapaxes(2, 3)\n# aug_data = aug_data.swapaxes(1, 2)\n# t3 = time.time()\n datas['data'][:] = aug_data\n\n# t4 = time.time()\n #ready same data\n dim2 = labels['proxy_ZM'].shape[1]\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n\n labels['proxy_yM'][si, carid] = 1\n labels['proxy_ZM'][si, carid] = 0\n if caridnum < dim2:\n labels['proxy_ZM'][si, :dim2-caridnum] = 0\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [datas['data']]\n label_nd = [labels['proxy_yM'], labels['proxy_ZM']]\n# t5 = time.time()\n# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0\n print datas_nd\n print labels_nd\n return datas_nd, label_nd, carids, batch_info\n\n\n\ndef get_data_label_pair_threads(data_infos, datas, label_infos, labels, datalist, rndidx, batch_now):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n if (batch_now+1)*batchsize > len(datalist):\n return None\n \n data_batch = []\n for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):\n idx = rndidx[idx]\n data_batch.append(datalist[idx])\n cars = []\n for onedata in data_batch:\n onecar = {}\n parts = onedata.split(',')\n onecar['path'] = parts[0]\n onecar['id'] = parts[-1] \n onecar['son'] = parts[1]\n p = parts[2].replace(' ', ',')\n onecar['plate'] = np.asarray(eval(p), dtype=np.int32)\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n \n tmpaths = []\n tmpplates = []\n carids = []\n for si in xrange(batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carids.append(carid)\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n tmpplates.append(onecar['plate'])\n \n aug_data = datas['databuffer']\n aug_plate_threads_c(tmpaths, tmpplates, data_infos[0][1], aug_data)\n# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)\n datas['data'][:] = aug_data\n #ready same data\n for si in xrange(batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n labels['id'][si, 0] = carid\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [datas['data']]\n label_nd = [labels['id']]\n\n return datas_nd, label_nd\n\n\ndef get_test_data_label_pair_threads(data_infos, datas, label_infos, labels, datalist, batch_now):\n# print label_infos\n labelshape = label_infos[0][1]\n batchsize = labelshape[0]\n dlen = len(datalist)\n data_batch = []\n if (batch_now+1)*batchsize < dlen:\n for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):\n data_batch.append(datalist[idx])\n else:\n for idx in xrange(batch_now*batchsize, dlen):\n data_batch.append(datalist[idx]) \n cars = []\n for onedata in data_batch:\n onecar = {}\n #hu\n parts = onedata.split('*')\n onecar['path'] = parts[0]\n onecar['id'] = parts[-1] \n onecar['son'] = parts[1]\n onecar['type'] = 0\n if onecar['son'].find('noplate')>=0:\n onecar['type'] = 1\n# p = parts[2].replace(' ', ',')\n# onecar['plate'] = np.asarray(eval(p), dtype=np.int32)\n cars.append(onecar)\n\n stdsize = data_infos[0][1][2:]\n dataidx = 0\n \n tmpaths = []\n carids = []\n real_batchsize = len(cars)\n for si in xrange(real_batchsize):\n onecar = cars[si]\n carpath = onecar['path']\n carid = int(onecar['id'])\n carids.append(carid)\n carson = onecar['son']\n tmpath = carpath+'/'+carson\n tmpaths.append(tmpath)\n \n aug_data = datas['databuffer']\n aug_data[:] = 0\n get_test_threads_c(tmpaths, data_infos[0][1], aug_data)\n datas['data'][:] = aug_data\n labels['id'][:] = -1\n #ready same data\n for si in xrange(real_batchsize):\n onecar = cars[si]\n carid = int(onecar['id'])\n labels['id'][si, 0] = carid\n labels['id'][si, 1] = onecar['type']\n if False:\n imgsave = (stdson*255).astype(np.uint8)\n cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)\n datas_nd = [datas['data']]\n label_nd = [labels['id']]\n\n return datas_nd, label_nd, tmpaths\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6315357089042664, "alphanum_fraction": 0.6433264017105103, "avg_line_length": 35.49964141845703, "blob_id": "cd097ebbad510924228cea8a09c725c4cd670f1d", "content_id": "1cc7916fda06b240fb7b35bfe18bf62e02a614f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51142, "license_type": "no_license", "max_line_length": 232, "num_lines": 1401, "path": "/DataIter.py", "repo_name": "Line290/improve_partial_fc", "src_encoding": "UTF-8", "text": "import sys\n# sys.path.insert(0, '/home/yunfeiwu')\nimport numpy as np\nimport logging\nimport mxnet as mx \nimport DataGenerator as dg \nimport operator\nimport os\n\n# datafn = '/media/data1/mzhang/data/car_ReID_for_zhangming/data.list'\n# datafn = '/home/mingzhang/data/car_ReID_for_zhangming/data.list'\ndatafn = './listFolder/trainlist_reid/chongxun.list'\n\nclass CarReID_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, \n data_label_gen=None):\n super(CarReID_Iter, self).__init__()\n\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.data_label_gen = data_label_gen\n self.cur_batch = 0\n# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label) \n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.rndidx_list = np.random.permutation(self.datalen)\n self.num_batches = self.datalen / label_shapes[0][0]\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.rndidx_list = np.random.permutation(self.datalen)\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n self.cur_batch += 1\n datas, labels = dg.get_pairs_data_label(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch) \n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Predict_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn_list):\n super(CarReID_Predict_Iter, self).__init__()\n\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.cur_batch = 0\n self.datalist = dg.get_datalist2(datafn_list)\n self.datalen = len(self.datalist)\n self.rndidx_list = np.random.permutation(self.datalen)\n self.num_batches = self.datalen / label_shapes[0][0]\n self.datas_batch = {}\n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['id'] = mx.nd.zeros(label_shapes[0], dtype=np.int32)\n\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.rndidx_list = np.random.permutation(self.datalen)\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n self.cur_batch += 1\n datas, labels = dg.get_data_label_pair_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.rndidx_list, self.cur_batch) \n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_TestQuick_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn_list):\n super(CarReID_TestQuick_Iter, self).__init__()\n\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.cur_batch = 0\n self.datalist = dg.get_datalist2(datafn_list)\n self.datalen = len(self.datalist)\n self.num_batches = self.datalen / label_shapes[0][0]\n self.batch_size = label_shapes[0][0]\n if self.datalen%label_shapes[0][0]!=0:\n self.num_batches += 1\n self.datas_batch = {}\n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['id'] = mx.nd.zeros(label_shapes[0], dtype=np.int32)\n self.paths = None\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels, paths = dg.get_test_data_label_pair_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.cur_batch) \n self.cur_batch += 1\n self.paths = paths\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Test_Iter(mx.io.DataIter):\n def __init__(self, data_name, data_shape, datafn, normalize=True):\n super(CarReID_Test_Iter, self).__init__()\n\n self._provide_data = zip(data_name, data_shape)\n self.cur_idx = 0\n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.normalize = normalize\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_idx = 0\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n def next(self):\n if self.cur_idx < self.datalen:\n# print self._provide_data\n carinfo = dg.get_data_label_test(self._provide_data[0][1][1:], self.datalist, self.cur_idx, self.normalize) \n self.cur_idx += 1\n return carinfo \n else:\n raise StopIteration\n\n\nclass CarReID_Feat_Query_Iter(mx.io.DataIter):\n def __init__(self, data_name, data_shape, datafn):\n super(CarReID_Feat_Query_Iter, self).__init__()\n\n self._provide_data = zip(data_name, data_shape)\n self.cur_idx = 0\n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.batchsize = data_shape[0][0]\n self.batchnum = self.datalen\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_idx = 0\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n def next(self):\n if self.cur_idx < self.batchnum:\n# print self._provide_data\n carinfo = dg.get_feature_label_query_test(self._provide_data[0][1], self.datalist, self.cur_idx) \n self.cur_idx += 1\n return carinfo \n else:\n raise StopIteration\n\n\n\nclass CarReID_Feat_Iter(mx.io.DataIter):\n def __init__(self, data_name, data_shape, datafn):\n super(CarReID_Feat_Iter, self).__init__()\n\n self._provide_data = zip(data_name, data_shape)\n self.cur_idx = 0\n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.batchsize = data_shape[0][0]\n self.batchnum = self.datalen / self.batchsize\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_idx = 0\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n def next(self):\n if self.cur_idx < self.batchnum:\n# print self._provide_data\n carinfo = dg.get_feature_label_test(self._provide_data[0][1], self.datalist, self.cur_idx) \n self.cur_idx += 1\n return carinfo \n else:\n raise StopIteration\n\n\nclass CarReID_Softmax_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn):\n super(CarReID_Softmax_Iter, self).__init__()\n\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.cur_batch = 0\n# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label) \n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.rndidx_list = np.random.permutation(self.datalen)\n self.num_batches = self.datalen / label_shapes[0][0]\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.rndidx_list = np.random.permutation(self.datalen)\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels = dg.get_data_label(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch) \n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Proxy_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, proxyfn):\n super(CarReID_Proxy_Iter, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.cur_batch = 0\n# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label) \n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.rndidx_list = np.random.permutation(self.datalen)\n self.num_batches = self.datalen / label_shapes[0][0]\n self.labeldict = dict(self._provide_label)\n self.proxy_set = None#dg.get_proxyset(proxyfn, self.labeldict['proxy_Z'])\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.rndidx_list = np.random.permutation(self.datalen)\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels = dg.get_data_label_proxy(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.proxy_set, self.cur_batch) \n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Proxy2_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, bucket_key):\n super(CarReID_Proxy2_Iter, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.cur_batch = 0\n# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label) \n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.rndidx_list = np.random.permutation(self.datalen)\n self.num_batches = self.datalen / label_shapes[0][0]\n self.labeldict = dict(self._provide_label)\n self.default_bucket_key = bucket_key\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.rndidx_list = np.random.permutation(self.datalen)\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels = dg.get_data_label_proxy2(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch) \n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Proxy_Mxnet_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, bucket_key):\n super(CarReID_Proxy_Mxnet_Iter, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)\n self.cur_batch = 0\n# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label) \n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.rndidx_list = np.random.permutation(self.datalen)\n self.num_batches = self.datalen / label_shapes[0][0]\n self.labeldict = dict(self._provide_label)\n self.default_bucket_key = bucket_key\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.rndidx_list = np.random.permutation(self.datalen)\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n# datas, labels = dg.get_data_label_proxy_mxnet(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch) \n datas, labels = dg.get_data_label_proxy_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.rndidx_list, self.cur_batch) \n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Proxy_Batch_Mxnet_Iter(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, \n proxy_num, featdim, proxy_batchsize, repeat_times=4, num_proxy_batch_max=0.0):\n super(CarReID_Proxy_Batch_Mxnet_Iter, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)\n self.cur_batch = 0\n self.datalist = dg.get_datalist(datafn)\n self.datalen = len(self.datalist)\n self.labeldict = dict(self._provide_label)\n self.proxy_batchsize = proxy_batchsize\n self.rndidx_list = None \n self.num_batches = self.proxy_batchsize / label_shapes[0][0]\n self.batch_carids = []\n self.batch_infos = []\n self.num_proxy_batch = self.datalen / self.proxy_batchsize\n self.num_proxy_batch_max = num_proxy_batch_max\n self.cur_proxy_batch = 0\n self.big_epoch = 0\n self.proxy_num = proxy_num\n self.featdim = featdim\n self.proxy_Z_fn = './proxy_Z.params'\n proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5\n self.proxy_Z = proxy_Ztmp.astype(np.float32) \n if os.path.exists(self.proxy_Z_fn):\n tmpZ = mx.nd.load(self.proxy_Z_fn)\n self.proxy_Z = tmpZ[0].asnumpy()\n assert(self.proxy_num==tmpZ[0].shape[0])\n print 'load proxy_Z from', self.proxy_Z_fn\n proxy_Z_ptmp = np.random.rand(self.proxy_batchsize, self.featdim)-0.5\n self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)\n self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1\n self.caridnum = None\n self.total_proxy_batch_epoch = 0\n self.repeat_times = repeat_times\n self.do_reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n pass\n\n def proxy_updateset(self, proxy_Z_p_new):\n num = np.sum(self.proxy_Z_map>-1)\n p_Z = proxy_Z_p_new.asnumpy()\n self.proxy_Z_p[:] = p_Z\n for i in xrange(num):\n carid = self.proxy_Z_map[i]\n self.proxy_Z[carid] = p_Z[i]\n savename = self.proxy_Z_fn \n mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])\n# a = self.proxy_Z\n# a = p_Z\n print 'save proxy_Z into file', savename#, a#, a[a<0], a[a>0]\n pass\n\n def do_reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n if self.total_proxy_batch_epoch == 0 \\\n or self.cur_proxy_batch == self.num_proxy_batch \\\n or (self.num_proxy_batch_max > 0.0 \\\n and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):\n self.cur_proxy_batch = 0 \n self.big_epoch += 1\n self.rndidx_list = np.random.permutation(self.datalen)\n\n self.proxy_datalist = []\n carids = {}\n self.proxy_Z_map[:] = -1\n prndidxs = np.random.permutation(self.proxy_batchsize)\n for i in xrange(self.proxy_batchsize):\n pidx = prndidxs[i]\n pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx\n idx = self.rndidx_list[pxyi]\n onedata = self.datalist[idx] \n parts = onedata.split(',')\n path = parts[0]\n son = parts[1]\n carid = path.split('/')[-1]\n if not carids.has_key(carid):\n carids[carid] = len(carids)\n ori_id = int(carid)\n proxyid = carids[carid] \n self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]\n self.proxy_Z_map[proxyid] = ori_id\n proxy_str = '%s,%s,%s,%s'%(path, son, carid, str(proxyid))\n self.proxy_datalist.append(proxy_str)\n\n self.caridnum = len(carids)\n print 'got another proxy batch to train(%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\\\n self.caridnum, self.proxy_batchsize, self.datalen, self.cur_proxy_batch+1,\\\n self.num_proxy_batch, self.big_epoch)\n\n self.total_proxy_batch_epoch += 1\n if self.total_proxy_batch_epoch%self.repeat_times==0: \n self.cur_proxy_batch += 1\n# print self.proxy_Z_p, self.proxy_Z_p.sum()\n return self.caridnum, self.proxy_Z_p\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n\n def next(self):\n if self.cur_batch < self.num_batches:\n# datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet(self._provide_data, self._provide_label, self.proxy_datalist, self.cur_batch) \n datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.caridnum) \n self.batch_carids = carids\n self.batch_infos = infos\n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\n\n\nclass CarReID_Proxy_Mxnet_Iter2(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn_list, bucket_key):\n super(CarReID_Proxy_Mxnet_Iter2, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)\n self.cur_batch = 0\n# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label) \n self.datalist = dg.get_datalist2(datafn_list)\n self.datalen = len(self.datalist)\n self.rndidx_list = np.random.permutation(self.datalen)\n self.num_batches = self.datalen / label_shapes[0][0]\n self.labeldict = dict(self._provide_label)\n self.default_bucket_key = bucket_key\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.rndidx_list = np.random.permutation(self.datalen)\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n def next(self):\n if self.cur_batch < self.num_batches:\n# datas, labels = dg.get_data_label_proxy_mxnet2(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch) \n datas, labels = dg.get_data_label_proxy_mxnet2_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.rndidx_list, self.cur_batch) \n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Proxy_Batch_Mxnet_Iter2(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, \n proxy_num, featdim, proxy_batchsize, repeat_times=4, num_proxy_batch_max=0.0):\n super(CarReID_Proxy_Batch_Mxnet_Iter2, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)\n self.cur_batch = 0\n self.datalist = dg.get_datalist2(datafn)\n self.datalen = len(self.datalist)\n self.labeldict = dict(self._provide_label)\n self.proxy_batchsize = proxy_batchsize\n self.rndidx_list = None \n self.num_batches = self.proxy_batchsize / label_shapes[0][0]\n self.batch_carids = []\n self.batch_infos = []\n self.num_proxy_batch = self.datalen / self.proxy_batchsize\n self.num_proxy_batch_max = num_proxy_batch_max\n self.cur_proxy_batch = 0\n self.big_epoch = 0\n self.proxy_num = proxy_num\n self.featdim = featdim\n self.proxy_Z_fn = './proxy_Z.params'\n proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5\n self.proxy_Z = proxy_Ztmp.astype(np.float32) \n if os.path.exists(self.proxy_Z_fn):\n tmpZ = mx.nd.load(self.proxy_Z_fn)\n self.proxy_Z = tmpZ[0].asnumpy()\n assert(self.proxy_num==tmpZ[0].shape[0])\n print 'load proxy_Z from', self.proxy_Z_fn\n proxy_Z_ptmp = np.random.rand(self.proxy_batchsize, self.featdim)-0.5\n self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)\n self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1\n self.caridnum = None\n self.total_proxy_batch_epoch = 0\n self.repeat_times = repeat_times\n self.do_reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n pass\n\n def proxy_updateset(self, proxy_Z_p_new):\n num = np.sum(self.proxy_Z_map>-1)\n p_Z = proxy_Z_p_new.asnumpy()\n self.proxy_Z_p[:] = p_Z\n for i in xrange(num):\n carid = self.proxy_Z_map[i]\n self.proxy_Z[carid] = p_Z[i]\n savename = self.proxy_Z_fn \n mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])\n# a = self.proxy_Z\n# a = p_Z\n print 'save proxy_Z into file', savename#, a#, a[a<0], a[a>0]\n pass\n\n def do_reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n if self.total_proxy_batch_epoch == 0 \\\n or self.cur_proxy_batch == self.num_proxy_batch \\\n or (self.num_proxy_batch_max > 0.0 \\\n and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):\n self.cur_proxy_batch = 0 \n self.big_epoch += 1\n self.rndidx_list = np.random.permutation(self.datalen)\n\n self.proxy_datalist = []\n carids = {}\n self.proxy_Z_map[:] = -1\n prndidxs = np.random.permutation(self.proxy_batchsize)\n for i in xrange(self.proxy_batchsize):\n pidx = prndidxs[i]\n pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx\n idx = self.rndidx_list[pxyi]\n onedata = self.datalist[idx] \n parts = onedata.split(',')\n path = parts[0]\n son = parts[1]\n carid = parts[2]\n if not carids.has_key(carid):\n carids[carid] = len(carids)\n ori_id = int(carid)\n proxyid = carids[carid] \n self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]\n self.proxy_Z_map[proxyid] = ori_id\n proxy_str = '%s,%s,%s,%s'%(path, son, carid, str(proxyid))\n self.proxy_datalist.append(proxy_str)\n\n self.caridnum = len(carids)\n print 'got another proxy batch to train(%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\\\n self.caridnum, self.proxy_batchsize, self.datalen, self.cur_proxy_batch+1,\\\n self.num_proxy_batch, self.big_epoch)\n\n self.total_proxy_batch_epoch += 1\n if self.total_proxy_batch_epoch%self.repeat_times==0:\n self.cur_proxy_batch += 1\n# print self.proxy_Z_p, self.proxy_Z_p.sum()\n return self.caridnum, self.proxy_Z_p\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n\n def next(self):\n if self.cur_batch < self.num_batches:\n# datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet(self._provide_data, self._provide_label, self.proxy_datalist, self.cur_batch) \n datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.caridnum) \n self.batch_carids = carids\n self.batch_infos = infos\n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\nclass PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, \n proxy_num, featdim, proxy_batchsize, proxy_num_batch, repeat_times=4, num_proxy_batch_max=0.0):\n super(PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n self.cur_batch = 0\n self.datalist = dg.get_datalist2(datafn)\n self.datalen = len(self.datalist)\n self.labeldict = dict(self._provide_label)\n self.proxy_batchsize = proxy_batchsize\n self.proxy_num_batch = proxy_num_batch \n self.rndidx_list = None \n self.num_batches = None#self.proxy_batchsize / label_shapes[0][0]\n self.batch_personids = []\n self.batch_infos = []\n self.num_proxy_batch = self.datalen / self.proxy_batchsize\n self.num_proxy_batch_max = num_proxy_batch_max\n self.cur_proxy_batch = 0\n self.big_epoch = 0\n self.proxy_num = proxy_num\n self.featdim = featdim\n self.proxy_Z_fn = './proxy_Z.params'\n proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5\n self.proxy_Z = proxy_Ztmp.astype(np.float32) \n if os.path.exists(self.proxy_Z_fn):\n tmpZ = mx.nd.load(self.proxy_Z_fn)\n self.proxy_Z = tmpZ[0].asnumpy()\n print self.proxy_num, tmpZ[0].shape[0]\n assert(self.proxy_num==tmpZ[0].shape[0])\n print 'load proxy_Z from', self.proxy_Z_fn\n proxy_Z_ptmp = np.random.rand(self.proxy_num_batch, self.featdim)-0.5\n self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)\n self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1\n self.personidnum = 0\n self.total_proxy_batch_epoch = 0\n self.repeat_times = repeat_times\n self.do_reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.batch_personids = []\n self.batch_infos = []\n pass\n\n def proxy_updateset(self, proxy_Z_p_new):\n num = np.sum(self.proxy_Z_map>-1)\n p_Z = proxy_Z_p_new.asnumpy()\n self.proxy_Z_p[:] = p_Z\n for i in xrange(num):\n personid = self.proxy_Z_map[i]\n self.proxy_Z[personid] = p_Z[i]\n savename = self.proxy_Z_fn \n mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])\n# a = self.proxy_Z\n# a = p_Z\n print 'save proxy_Z into file', savename#, num, self.caridnum, p_Z[:self.caridnum].sum()#, a#, a[a<0], a[a>0]\n pass\n\n def do_reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n if self.total_proxy_batch_epoch == 0 \\\n or self.cur_proxy_batch == self.num_proxy_batch \\\n or (self.num_proxy_batch_max > 0.0 \\\n and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):\n self.cur_proxy_batch = 0 \n self.big_epoch += 1\n self.rndidx_list = np.random.permutation(self.datalen)\n print 'permutation....................'\n\n self.proxy_datalist = []\n# carids = {}\n personids = {}\n self.proxy_Z_map[:] = -1\n prndidxs = np.random.permutation(self.proxy_batchsize)\n# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()\n for i in xrange(self.proxy_batchsize):\n pidx = prndidxs[i]\n pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx\n idx = self.rndidx_list[pxyi]\n onedata = self.datalist[idx] \n \n parts = onedata.split('*')\n path = parts[0]\n son = parts[1]\n #plate = parts[2]\n personid = parts[-1]\n# print personid\n if not personids.has_key(personid):\n personids[personid] = len(personids)\n# print 'personid = ',personid\n# print 'personids = ', personids\n# print 'personids[personid]= ', len(personids)\n if len(personids)>self.proxy_num_batch:\n logging.info('arriving max number proxy_num_batch:%d[%d/%d]...', len(personids), i+1, self.proxy_batchsize)\n break\n \n# if not carids.has_key(carid):\n# carids[carid] = len(carids)\n ori_id = int(personid)\n# print 'ori_id = ', ori_id\n proxyid = personids[personid] \n# print 'proxyid = ',proxyid\n self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]\n self.proxy_Z_map[proxyid] = ori_id\n \n proxy_str = '%s,%s,%s,%s'%(path, son, personid, str(proxyid))\n self.proxy_datalist.append(proxy_str)\n# np.save('datatemp/map', personids)\n# np.save('/train/execute/map2', self.proxy_Z_map)\n realnum = i+1\n self.num_batches = len(self.proxy_datalist) / self.batch_size\n self.personidnum = len(personids)\n# print 'self.personidnum = ',len(personids)\n print 'got another proxy batch to train(%d/%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\\\n self.personidnum, self.proxy_batchsize, realnum, self.datalen, self.cur_proxy_batch+1,\\\n self.num_proxy_batch, self.big_epoch)\n\n self.total_proxy_batch_epoch += 1\n if self.total_proxy_batch_epoch%self.repeat_times==0:\n self.cur_proxy_batch += 1\n# print 'carid 1', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()\n return self.personidnum, self.proxy_Z_p\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels, personids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads_nsoftmax(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.personidnum) \n self.batch_personids = personids\n self.batch_infos = infos\n self.cur_batch += 1\n# print 'data shape : ', self._provide_data[0][1]\n# print 'label shape : ', self._provide_label[0][1]\n# datas = mx.nd.ones(shape=self._provide_data[0][1], dtype='float32', ctx = mx.gpu(0))\n# labels = mx.nd.ones(shape=self._provide_label[0][1], dtype='int32', ctx = mx.gpu(0)) \n# mx.nd.save('datatemp/data_X.params', datas)\n# mx.nd.save('datatemp/data_y.params', labels)\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\nclass PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, \n proxy_num, featdim, proxy_batchsize, proxy_num_batch, repeat_times=4, num_proxy_batch_max=0.0):\n super(PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n self.cur_batch = 0\n self.datalist = dg.get_datalist2(datafn)\n self.datalen = len(self.datalist)\n self.labeldict = dict(self._provide_label)\n self.proxy_batchsize = proxy_batchsize\n self.proxy_num_batch = proxy_num_batch \n self.rndidx_list = None \n self.num_batches = None#self.proxy_batchsize / label_shapes[0][0]\n self.batch_personids = []\n self.batch_infos = []\n self.num_proxy_batch = self.datalen / self.proxy_batchsize\n self.num_proxy_batch_max = num_proxy_batch_max\n self.cur_proxy_batch = 0\n self.big_epoch = 0\n self.proxy_num = proxy_num\n self.featdim = featdim\n self.proxy_Z_fn = '/train/execute/proxy_Z.params'\n proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5\n self.proxy_Z = proxy_Ztmp.astype(np.float32) \n if os.path.exists(self.proxy_Z_fn):\n tmpZ = mx.nd.load(self.proxy_Z_fn)\n self.proxy_Z = tmpZ[0].asnumpy()\n print self.proxy_num, tmpZ[0].shape[0]\n assert(self.proxy_num==tmpZ[0].shape[0])\n print 'load proxy_Z from', self.proxy_Z_fn\n proxy_Z_ptmp = np.random.rand(self.proxy_num_batch, self.featdim)-0.5\n self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)\n self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1\n self.personidnum = 0\n self.total_proxy_batch_epoch = 0\n self.repeat_times = repeat_times\n# self.do_reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.batch_personids = []\n self.batch_infos = []\n pass\n\n def proxy_updateset(self, proxy_Z_p_new):\n num = np.sum(self.proxy_Z_map>-1)\n p_Z = proxy_Z_p_new.asnumpy()\n self.proxy_Z_p[:] = p_Z\n for i in xrange(num):\n personid = self.proxy_Z_map[i]\n self.proxy_Z[personid] = p_Z[i]\n savename = self.proxy_Z_fn \n mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])\n# a = self.proxy_Z\n# a = p_Z\n print 'save proxy_Z into file', savename#, num, self.caridnum, p_Z[:self.caridnum].sum()#, a#, a[a<0], a[a>0]\n pass\n\n def do_reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n if self.total_proxy_batch_epoch == 0 \\\n or self.cur_proxy_batch == self.num_proxy_batch \\\n or (self.num_proxy_batch_max > 0.0 \\\n and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):\n self.cur_proxy_batch = 0 \n self.big_epoch += 1\n self.rndidx_list = np.random.permutation(self.datalen)\n print 'permutation....................'\n\n self.proxy_datalist = []\n# carids = {}\n personids = {}\n self.proxy_Z_map[:] = -1\n prndidxs = np.random.permutation(self.proxy_batchsize)\n# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()\n for i in xrange(self.proxy_batchsize):\n pidx = prndidxs[i]\n pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx\n idx = self.rndidx_list[pxyi]\n onedata = self.datalist[idx] \n \n parts = onedata.split('*')\n path = parts[0]\n son = parts[1]\n #plate = parts[2]\n personid = parts[-1]\n# print personid\n if not personids.has_key(personid):\n personids[personid] = len(personids)\n# print 'personid = ',personid\n# print 'personids = ', personids\n# print 'personids[personid]= ', len(personids)\n if len(personids)>self.proxy_num_batch:\n logging.info('arriving max number proxy_num_batch:%d[%d/%d]...', len(personids), i+1, self.proxy_batchsize)\n break\n \n# if not carids.has_key(carid):\n# carids[carid] = len(carids)\n ori_id = int(personid)\n# print 'ori_id = ', ori_id\n proxyid = personids[personid] \n# print 'proxyid = ',proxyid\n self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]\n self.proxy_Z_map[proxyid] = ori_id\n \n proxy_str = '%s,%s,%s,%s'%(path, son, personid, str(proxyid))\n self.proxy_datalist.append(proxy_str)\n# np.save('datatemp/map', personids)\n np.save('/train/execute/map2', self.proxy_Z_map)\n realnum = i+1\n self.num_batches = len(self.proxy_datalist) / self.batch_size\n self.personidnum = len(personids)\n# print 'self.personidnum = ',len(personids)\n print 'got another proxy batch to train(%d/%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\\\n self.personidnum, self.proxy_batchsize, realnum, self.datalen, self.cur_proxy_batch+1,\\\n self.num_proxy_batch, self.big_epoch)\n\n self.total_proxy_batch_epoch += 1\n if self.total_proxy_batch_epoch%self.repeat_times==0:\n self.cur_proxy_batch += 1\n# print 'carid 1', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()\n return self.personidnum, self.proxy_Z_p\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels, personids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads_nsoftmax(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.personidnum) \n self.batch_personids = personids\n self.batch_infos = infos\n self.cur_batch += 1\n# print 'data shape : ', self._provide_data[0][1]\n# print 'label shape : ', self._provide_label[0][1]\n# datas = mx.nd.ones(shape=self._provide_data[0][1], dtype='float32', ctx = mx.gpu(0))\n# labels = mx.nd.ones(shape=self._provide_label[0][1], dtype='int32', ctx = mx.gpu(0)) \n# mx.nd.save('datatemp/data_X.params', datas)\n# mx.nd.save('datatemp/data_y.params', labels)\n proxy_label = labels[0].asnumpy()\n y_label = mx.nd.array(source_array=self.proxy_Z_map[proxy_label[range(len(proxy_label))].astype(np.int32)], dtype='int32').reshape(-1,1)\n return mx.io.DataBatch(datas, [y_label])\n else:\n raise StopIteration\n\n\n\nclass PersonReID_Proxy_Batch_Plate_Mxnet_Iter2(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, \n proxy_num, featdim, proxy_batchsize, proxy_num_batch, repeat_times=4, num_proxy_batch_max=0.0):\n super(PersonReID_Proxy_Batch_Plate_Mxnet_Iter2, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n #print 'batch_size Person: ', self.batch_size\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n #print 'label_shape Person: ', label_shapes[0]\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n # for loss with margin\n #self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)\n self.cur_batch = 0\n self.datalist = dg.get_datalist2(datafn)\n self.datalen = len(self.datalist)\n self.labeldict = dict(self._provide_label)\n self.proxy_batchsize = proxy_batchsize\n self.proxy_num_batch = proxy_num_batch \n self.rndidx_list = None \n self.num_batches = None#self.proxy_batchsize / label_shapes[0][0]\n self.batch_personids = []\n self.batch_infos = []\n self.num_proxy_batch = self.datalen / self.proxy_batchsize\n self.num_proxy_batch_max = num_proxy_batch_max\n self.cur_proxy_batch = 0\n self.big_epoch = 0\n self.proxy_num = proxy_num\n self.featdim = featdim\n self.proxy_Z_fn = './proxy_Z.params'\n proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5\n self.proxy_Z = proxy_Ztmp.astype(np.float32) \n if os.path.exists(self.proxy_Z_fn):\n tmpZ = mx.nd.load(self.proxy_Z_fn)\n self.proxy_Z = tmpZ[0].asnumpy()\n print self.proxy_num, tmpZ[0].shape[0]\n assert(self.proxy_num==tmpZ[0].shape[0])\n print 'load proxy_Z from', self.proxy_Z_fn\n proxy_Z_ptmp = np.random.rand(self.proxy_num_batch, self.featdim)-0.5\n self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)\n self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1\n self.personidnum = 0\n self.total_proxy_batch_epoch = 0\n self.repeat_times = repeat_times\n self.do_reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.batch_personids = []\n self.batch_infos = []\n pass\n\n def proxy_updateset(self, proxy_Z_p_new):\n num = np.sum(self.proxy_Z_map>-1)\n p_Z = proxy_Z_p_new.asnumpy()\n self.proxy_Z_p[:] = p_Z\n for i in xrange(num):\n personid = self.proxy_Z_map[i]\n self.proxy_Z[personid] = p_Z[i]\n savename = self.proxy_Z_fn \n mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])\n# a = self.proxy_Z\n# a = p_Z\n print 'save proxy_Z into file', savename#, num, self.caridnum, p_Z[:self.caridnum].sum()#, a#, a[a<0], a[a>0]\n pass\n\n def do_reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n if self.total_proxy_batch_epoch == 0 \\\n or self.cur_proxy_batch == self.num_proxy_batch \\\n or (self.num_proxy_batch_max > 0.0 \\\n and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):\n self.cur_proxy_batch = 0 \n self.big_epoch += 1\n self.rndidx_list = np.random.permutation(self.datalen)\n print 'permutation....................'\n\n self.proxy_datalist = []\n# carids = {}\n personids = {}\n self.proxy_Z_map[:] = -1\n prndidxs = np.random.permutation(self.proxy_batchsize)\n# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()\n for i in xrange(self.proxy_batchsize):\n pidx = prndidxs[i]\n pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx\n idx = self.rndidx_list[pxyi]\n onedata = self.datalist[idx] \n \n parts = onedata.split('*')\n path = parts[0]\n son = parts[1]\n #plate = parts[2]\n personid = parts[-1]\n# print personid \n if not personids.has_key(personid):\n personids[personid] = len(personids)\n# print 'personid = ',personid\n# print 'personids = ', personids\n# print 'personids[personid]= ', len(personids) \n if len(personids)>self.proxy_num_batch:\n logging.info('arriving max number proxy_num_batch:%d[%d/%d]...', len(personids), i+1, self.proxy_batchsize)\n break\n# if not carids.has_key(carid):\n# carids[carid] = len(carids)\n ori_id = int(personid)\n# print 'ori_id = ', ori_id\n proxyid = personids[personid] \n# print 'proxyid = ',proxyid\n self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]\n self.proxy_Z_map[proxyid] = ori_id\n proxy_str = '%s,%s,%s,%s'%(path, son, personid, str(proxyid))\n self.proxy_datalist.append(proxy_str)\n realnum = i+1\n self.num_batches = len(self.proxy_datalist) / self.batch_size\n self.personidnum = len(personids)\n# print 'self.personidnum = ',len(personids)\n print 'got another proxy batch to train(%d/%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\\\n self.personidnum, self.proxy_batchsize, realnum, self.datalen, self.cur_proxy_batch+1,\\\n self.num_proxy_batch, self.big_epoch)\n\n self.total_proxy_batch_epoch += 1\n if self.total_proxy_batch_epoch%self.repeat_times==0:\n self.cur_proxy_batch += 1\n# print 'carid 1', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()\n return self.personidnum, self.proxy_Z_p\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels, personids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.personidnum) \n self.batch_personids = personids\n self.batch_infos = infos\n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\nclass CarReID_Proxy_Distribution_Batch_Plate_Mxnet_Iter2(mx.io.DataIter):\n def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, \n total_proxy_num, featdim, proxy_batchsize, repeat_times=1, num_proxy_batch_max=0.0):\n super(CarReID_Proxy_Distribution_Batch_Plate_Mxnet_Iter2, self).__init__()\n\n self.batch_size = data_shapes[0][0]\n self._provide_data = zip(data_names, data_shapes)\n self._provide_label = zip(label_names, label_shapes)\n self.datas_batch = {} \n self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)\n self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)\n self.labels_batch = {}\n self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)\n self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)\n self.cur_batch = 0\n self.datalist = dg.get_datalist2(datafn)\n self.datalen = len(self.datalist)\n self.labeldict = dict(self._provide_label)\n self.proxy_batchsize = proxy_batchsize\n self.rndidx_list = None \n self.num_batches = self.proxy_batchsize / label_shapes[0][0]\n self.batch_carids = []\n self.batch_infos = []\n self.num_proxy_batch = self.datalen / self.proxy_batchsize\n self.num_proxy_batch_max = num_proxy_batch_max\n self.cur_proxy_batch = 0\n self.big_epoch = 0\n self.proxy_num = total_proxy_num\n self.featdim = featdim\n self.proxy_Z_fn = './proxy_Z.params'\n proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5\n self.proxy_Z = proxy_Ztmp.astype(np.float32) \n if os.path.exists(self.proxy_Z_fn):\n tmpZ = mx.nd.load(self.proxy_Z_fn)\n self.proxy_Z = tmpZ[0].asnumpy()\n logging.info('proxy number:%d, Z number:%d', self.proxy_num, tmpZ[0].shape[0])\n assert(self.proxy_num==tmpZ[0].shape[0])\n logging.info('Load proxy_Z from %s', self.proxy_Z_fn)\n self.proxy_Z = mx.nd.array(self.proxy_Z)\n\n self.proxy_ori_index = np.zeros(self.proxy_batchsize, dtype=np.int32)\n self.caridnum = 0\n self.total_proxy_batch_epoch = 0\n self.repeat_times = repeat_times\n self.do_reset()\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n pass\n\n def do_reset(self):\n self.cur_batch = 0 \n self.batch_carids = []\n self.batch_infos = []\n if self.total_proxy_batch_epoch == 0 \\\n or self.cur_proxy_batch == self.num_proxy_batch \\\n or (self.num_proxy_batch_max > 0.0 \\\n and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):\n self.cur_proxy_batch = 0 \n self.big_epoch += 1\n self.rndidx_list = np.random.permutation(self.datalen)\n logging.info('permutation....................')\n\n self.proxy_datalist = []\n carids = {}\n prndidxs = np.random.permutation(self.proxy_batchsize)\n# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()\n self.proxy_ori_index[:] = range(-self.proxy_batchsize, 0)\n for i in xrange(self.proxy_batchsize):\n pidx = prndidxs[i]\n pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx\n idx = self.rndidx_list[pxyi]\n onedata = self.datalist[idx] \n parts = onedata.split(',')\n path = parts[0]\n son = parts[1]\n plate = parts[2]\n carid = parts[3]\n if not carids.has_key(carid):\n carids[carid] = len(carids)\n ori_id = int(carid)\n proxyid = carids[carid] \n self.proxy_ori_index[proxyid] = ori_id\n proxy_str = '%s,%s,%s,%s,%s'%(path, son, plate, carid, str(proxyid))\n self.proxy_datalist.append(proxy_str)\n\n self.caridnum = len(carids)\n logging.info('got another proxy batch to train(%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\\\n self.caridnum, self.proxy_batchsize, self.datalen, self.cur_proxy_batch+1,\\\n self.num_proxy_batch, self.big_epoch))\n\n self.total_proxy_batch_epoch += 1\n if self.total_proxy_batch_epoch%self.repeat_times==0:\n self.cur_proxy_batch += 1\n self.proxy_ori_index = np.sort(self.proxy_ori_index)\n pidx = range(self.proxy_ori_index.shape[0])\n pairval = zip(self.proxy_ori_index, pidx)\n pairdict = dict(pairval)\n for idx in xrange(len(self.proxy_datalist)):\n pstr = self.proxy_datalist[idx]\n parts = pstr.split(',')\n carid = int(parts[-2])\n proxyid = pairdict[carid]\n self.proxy_datalist[idx] = '%s,%s,%s,%s,%s'%(parts[0], parts[1], parts[2], parts[3], str(proxyid))\n # print self.proxy_ori_index, self.proxy_ori_index.shape\n\n return self.caridnum, self.proxy_ori_index\n\n def __next__(self):\n return self.next()\n\n @property\n def provide_data(self):\n return self._provide_data\n\n @property\n def provide_label(self):\n return self._provide_label\n\n\n def next(self):\n if self.cur_batch < self.num_batches:\n datas, labels, carids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads2(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.caridnum) \n self.batch_carids = carids\n self.batch_infos = infos\n self.cur_batch += 1\n return mx.io.DataBatch(datas, labels)\n else:\n raise StopIteration\n\n\n\nif __name__=='__main__':\n print 'testing DataIter.py...'\n data_shape = (4, 3, 200, 200)\n proxy_yM_shape = (4, 4000)\n proxy_ZM_shape = (4, 4000)\n datafn_list = ['/home/chuanruihu/list_dir/Person_train.list']\n total_proxy_num = 60000\n featdim = 128\n proxy_batch = 4000 \n # num_batches = 10\n# pair_part1_shape = (32, 3, 128, 128)\n# pair_part2_shape = (32, 3, 128, 128)\n# label_shape = (pair_part1_shape[0],)\n# data_iter = CarReID_Iter(['part1_data', 'part2_data'], [pair_part1_shape, pair_part2_shape],\n# ['label'], [label_shape], get_pairs_data_label,\n# num_batches)\n data_iter = PersonReID_Proxy_Batch_Plate_Mxnet_Iter2(['data'], [data_shape], ['proxy_yM','proxy_ZM'], [proxy_yM_shape, proxy_ZM_shape],datafn_list, total_proxy_num, featdim, proxy_batch, 1)\n for d in data_iter:\n print d.data\n print d.label\n# dks = d.data.keys()\n# lks = d.label.keys()\n# print dks[0], ':', d.data[dks[0]].asnumpy().shape, ' ', lks[0], ':', d.label[lks[0]].asnumpy().shape\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5395166277885437, "alphanum_fraction": 0.5754408836364746, "avg_line_length": 31.231578826904297, "blob_id": "82a301d9cc2cf1a49890ca1cbd9a6b1bd207c1d0", "content_id": "7ae1b1cf928b89c849a6c1c80a7a6d03bcb6b8e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3062, "license_type": "no_license", "max_line_length": 96, "num_lines": 95, "path": "/orig_list2rec_list.py", "repo_name": "Line290/improve_partial_fc", "src_encoding": "UTF-8", "text": "# from __future__ import print_function\nimport os\nimport sys\n\n# curr_path = os.path.abspath(os.path.dirname(__file__))\n# sys.path.append(os.path.join(curr_path, \"../python\"))\nimport mxnet as mx\nsys.path.insert(0, '/train/execute/distribution')\nimport random\nimport argparse\nimport cv2\nimport time\nimport traceback\n\ntry:\n import multiprocessing\nexcept ImportError:\n multiprocessing = None\n\nimport DataGenerator as dg\n\ndef write_list(path_out, image_list):\n with open(path_out, 'w') as fout:\n for i, item in enumerate(image_list):\n line = '%d\\t' % item[0]\n for j in item[2:]:\n line += '%f\\t' % j\n line += '%s\\n' % item[1]\n fout.write(line)\n \ndef make_list_new(image_list, prefix):\n# image_list = list_image(args.root, args.recursive, args.exts)\n # get image list\n # (No, path, ID or label)\n # e.g. (0, '201709011900/10.209.2.85-0-201709011900-201709012200/1/1_1_1.jpg', 0)\n# image_list = list(image_list)\n shuffle = True\n if shuffle is True:\n random.seed(100)\n random.shuffle(image_list)\n N = len(image_list)\n \n # split several blocks, the number is chunks\n# chunk_size = (N + args.chunks - 1) // args.chunks\n chunk_size = N\n# for i in range(args.chunks):\n for i in range(1):\n chunk = image_list[i * chunk_size:(i + 1) * chunk_size]\n# if 1 > 1:\n# str_chunk = '_%d' % i\n# else:\n str_chunk = ''\n sep = int(chunk_size * 1)\n# sep = int(chunk_size * args.train_ratio)\n# sep_test = int(chunk_size * args.test_ratio)\n# if args.train_ratio == 1.0:\n# prefix = '/train/trainset/list_28w_20180731'\n write_list(prefix + str_chunk + '.lst', chunk)\n# else:\n# if args.test_ratio:\n# write_list(args.prefix + str_chunk + '_test.lst', chunk[:sep_test])\n# if args.train_ratio + args.test_ratio < 1.0:\n# write_list(args.prefix + str_chunk + '_val.lst', chunk[sep_test + sep:])\n# write_list(args.prefix + str_chunk + '_train.lst', chunk[sep_test:sep_test + sep])\n\n\n\n# list_path = './listFolder/trainlist_reid/list_all_20180723.list'\n# all_lists = dg.get_datalist2([list_path])\n# print all_lists[0]\n\n# lists = []\n# for i, onelist in enumerate(all_lists):\n# path, name, img_id = onelist.split('*')\n# # print path, name, img_id\n# # break\n# path = path + '/' + name\n# newline = (i, path, int(img_id))\n# lists.append(newline)\nif __name__ == '__main__':\n \n list_path = '/train/execute/listFolder/trainlist_reid/list_clean_28w_20180803.list'\n all_lists = dg.get_datalist2([list_path])\n \n lists = []\n for i, onelist in enumerate(all_lists):\n path, name, img_id = onelist.split('*')\n # print path, name, img_id\n # break\n path = path + '/' + name\n newline = (i, path, int(img_id))\n lists.append(newline)\n \n prefix = '/train/trainset/list_clean_28w_20180803' \n make_list_new(lists, prefix)\n" } ]
7
maggiezhao1212/hello-world
https://github.com/maggiezhao1212/hello-world
8e6d26ae06023dc52801dc4c3ef1cdccb9964203
7bebd8f5302f1174b7ae3273c3136b9f6ff4ce76
81412beac6c06526b26ba85ef7ea7bd0be4160c4
refs/heads/main
2023-01-30T06:15:57.370444
2020-12-14T03:22:47
2020-12-14T03:22:47
321,218,482
0
0
null
2020-12-14T03:11:41
2020-12-14T03:22:50
2020-12-14T03:36:02
Python
[ { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 11, "blob_id": "9d6a7e40763aa333f8285b8bf9de57754f66adfe", "content_id": "cb5a40329cfaee260427bb4b5f6da13699503877", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/README.md", "repo_name": "maggiezhao1212/hello-world", "src_encoding": "UTF-8", "text": "# hello-world\ngfsdgsfdg\n" }, { "alpha_fraction": 0.7627118825912476, "alphanum_fraction": 0.7627118825912476, "avg_line_length": 28.5, "blob_id": "ff0489eb13368ae1a1bdaad92629a3f4e6866903", "content_id": "38e14dfaac5c12143888a86fba5e6c67073da3b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59, "license_type": "no_license", "max_line_length": 38, "num_lines": 2, "path": "/firstpython.py", "repo_name": "maggiezhao1212/hello-world", "src_encoding": "UTF-8", "text": "#display the output\ndisplay(\"new python file new new new\")\n" } ]
2
pb-students/PSIO-02-sampling
https://github.com/pb-students/PSIO-02-sampling
641c7944c492a98a0b27a55c880cbbb022df08c9
f9af706cff94e6855f7b65d3f86ff3bc5716f2b0
be61a077385c02bcaf4fe479eb892b6cf52b6615
refs/heads/main
2023-01-22T23:19:24.345013
2020-11-23T22:09:57
2020-11-23T22:09:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5121861100196838, "alphanum_fraction": 0.5952732563018799, "avg_line_length": 19.269662857055664, "blob_id": "3056ad54c207f8006740cb68e34b22cccd01e1be", "content_id": "279a472f058862952c746b6745be1ec08810c11f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5440, "license_type": "permissive", "max_line_length": 126, "num_lines": 267, "path": "/Lab2.py", "repo_name": "pb-students/PSIO-02-sampling", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import pi as PI\nfrom scipy import signal\nimport IPython.display as ipd\n\n\n# <b>Zadanie 2.1.a)<b>\n\n# In[103]:\n\n\ny = [0]*41\ny[0] = 1\ny[40] = 1\n\nplt.figure(figsize= (12,4), dpi= 100)\nplt.title(\"Impuls oraz impuls przesunięty o N = 40 próbek\")\nplt.xlabel(\"Wartość Próbki\")\nplt.ylabel(\"Nr Próbki\")\nplt.stem(range(41), y)\nplt.savefig(\"Zadanie_2_1\\\\a.png\")\n\n\n# <b>Zadanie 2.1.b)<b>\n\n# In[102]:\n\n\na = np.arange(0, 36.2, 0.2)\ny1 = np.cos(a)\ny2 = signal.sawtooth(a)\ny3 = signal.square(a)\n\nfig, plots = plt.subplots(3, 1, figsize= (12,8), dpi= 100)\n\nfor plot in plots:\n plot.set_yticks(np.arange(-1, 1.1, 0.5))\n plot.set_xticks(np.arange(0, 40, 4))\n plot.grid(True)\n plot.set_ylim(-1.1, 1.1)\n plot.set_xlim(a[0], a[-1])\n\nplots[0].set_title(\"Cosinus\")\nplots[0].plot(a, y1)\n\nplots[1].set_title(\"Piłokształtny\")\nplots[1].plot(a, y2)\n\nplots[2].set_title(\"Prostokątny\")\nplots[2].plot(a, y3)\n\nplt.subplots_adjust(hspace=1)\n\nplt.savefig(\"Zadanie_2_1\\\\b.png\")\n\n\n# <b>Zadanie 2.1.c)<b>\n\n# In[101]:\n\n\nx = np.arange(0, 200)\ny = np.random.normal(0, np.sqrt(0.5), 200)\n\nplt.figure(figsize=(12,8), dpi= 100)\nplt.title(\"Szum Gaussowski\")\nplt.xlabel(\"Numer Próbki\")\nplt.ylabel(\"Wartość Chwilowa\")\nplt.plot(x, y)\nplt.savefig(\"Zadanie_2_1\\\\c.png\")\n\n\n# <b>Zadanie 2.2<b>\n\n# In[115]:\n\n\ndef PlotSignal(plot, A, f, phi, fs, justReturnY=False):\n Ts = 1/fs\n x = np.arange(0, 0.003 + Ts, Ts)\n y = A * np.sin((phi + x * 2 * PI)*f)\n if justReturnY:\n return y\n plot.set_title(f\"A: {A}, f: {f/1000}kHz, phi: {phi}rad, fs: {fs/1000}kHz\")\n plot.plot(x, y)\n\nfig, plots = plt.subplots(3, 1, figsize= (12,8), dpi= 100)\n\nmaxA = 1\n\nfor plot in plots:\n plot.set_yticks(np.arange(-maxA, maxA + .1, 1))\n plot.set_xticks(np.arange(0, 0.003 + .0005, 0.0005))\n plot.grid(True)\n plot.set_ylim(-maxA - .1, maxA + .1)\n plot.set_xlim(0, 0.003)\n\nPlotSignal(plots[0], 1, 1000, 0, 80000)\nPlotSignal(plots[1], 1, 1000, 0.5, 80000)\nPlotSignal(plots[2], 1, 1000, 1, 80000)\n\nplt.subplots_adjust(hspace=1)\n\nplt.savefig(\"Zadanie_2_2\\\\phi.png\")\n\nipd.Audio(PlotSignal(plots[0], 1, 1000, 0, 80000, True), rate=44100)\n\n# <b>Zadanie 2.3<b>\n\n# In[119]:\n\n\ndef PlotSignal(plot, A, f, phi, fs, justReturnY=False):\n Ts = 1/fs\n x = np.arange(0, 0.007 + Ts, Ts)\n y = A * np.sin((phi + x * 2 * PI)*f)\n if justReturnY:\n return y\n plot.set_title(f\"A: {A}, f: {f/1000}kHz, phi: {phi}rad, fs: {fs/1000}kHz\")\n plot.plot(x, y, 'D-')\n\nfig, plots = plt.subplots(3, 1, figsize= (12,8), dpi= 100)\n\nmaxA = 1\n\nfor plot in plots:\n plot.set_yticks(np.arange(-maxA, maxA + .1, 1))\n plot.set_xticks(np.arange(0, 0.007 + .0005, 0.0005))\n plot.grid(True)\n plot.set_ylim(-maxA - .1, maxA + .1)\n plot.set_xlim(0, 0.007)\n\nPlotSignal(plots[0], 1, 1000, 0, 8000)\nPlotSignal(plots[1], 1, 1000, 0, 2000)\nPlotSignal(plots[2], 1, 1000, 0, 1100)\n\nplt.subplots_adjust(hspace=1)\n\nplt.savefig(\"Zadanie_2_3\\\\fs.png\")\n\n\n# <b>Zadanie 2.4<b>\n\n# In[81]:\n\n\nimport wave\n\nSNR = 3\n\ndata = wave.open(\"Zadanie_2_4\\\\Nagranie.wav\")\nframerate = data.getframerate()*2\nrecording = np.frombuffer(data.readframes(-1), dtype = \"int16\") /2000\n\nrecording_reversed = np.flip(recording)\n\nx = np.arange(0, recording.size/framerate, 1/framerate)\n\nnoise = np.random.normal(0, 1, recording.size)\n\n# Powinno się to zrobić za pomocą formuły na decybele i jak ktoś zechciałby to zrobić to byłoby miło gdyby zrobił pull request\nmixed = recording + noise/(5*SNR)\n\n\nfig, plots = plt.subplots(4, 1, figsize= (8,8), dpi= 100)\n\nfor plot in plots:\n plot.set_xticks(np.arange(0, x[-1], 1))\n plot.grid(True)\n plot.set_xlim(0, x[-1])\n\nplots[0].set_title(\"Mowa\")\nplots[0].set_xlabel(\"Czas [s]\")\nplots[0].plot(x, recording, color=\"orange\")\n\nplots[1].set_title(\"Mowa - odwrócona\")\nplots[1].set_xlabel(\"Czas [s]\")\nplots[1].plot(x, recording_reversed, color=\"orange\")\n\nplots[2].set_title(\"Szum\")\nplots[2].set_xlabel(\"Czas [s]\")\nplots[2].plot(x, noise, color=\"orange\")\n\nplots[3].set_title(f\"Mowa + szum, SNR: {SNR}dB\")\nplots[3].set_xlabel(\"Czas [s]\")\nplots[3].plot(x, mixed, color=\"orange\")\n\n\nplt.subplots_adjust(hspace=1)\nplt.savefig(\"Zadanie_2_4\\\\plots.png\")\nipd.Audio(mixed, rate=framerate)\n\n\n# <b>Zadanie 2.5<b>\n\n# In[27]:\n\n\nfrom math import sin\n\n\ndef generate_sound(frequency, lenght = 0.5, samplerate = 44100):\n sound = []\n i = 0\n while i < int(lenght * samplerate):\n sound.append(sin(i*2*PI*frequency/samplerate))\n i += 1\n for a in range(500):\n sound.append(sin(i*2*PI*frequency/samplerate) * (500 - a)/500)\n i += 1\n return sound\n\n#Wzięte z internetu:\nNotes = {\n ' ': 0.0,\n 'C': 261.6,\n 'D': 293.7,\n 'E': 329.6,\n 'F': 349.2,\n 'G': 392.0,\n 'A': 440.0,\n 'B': 493.9,\n}\n\ndef play_notes(notesToPlay, samplerate=44100):\n melody = []\n notesToPlay = list(notesToPlay)\n for note in notesToPlay:\n melody.extend(generate_sound(Notes.get(note[0], 0.0), note[1]))\n return melody\n\n\n\ncatSong = [\n ['G', 0.4],\n ['E', 0.4],\n ['E', 0.4],\n ['F', 0.4],\n ['D', 0.4],\n ['D', 0.4],\n ['C', 0.2],\n ['E', 0.2],\n ['G', 0.8],\n [' ', 0.4],\n ['G', 0.4],\n ['E', 0.4],\n ['E', 0.4],\n ['F', 0.4],\n ['D', 0.4],\n ['D', 0.4],\n ['C', 0.2],\n ['E', 0.2],\n ['C', 0.8],\n]\n\nmelody = play_notes(catSong)\nipd.Audio(melody, rate=44100)\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.7308781743049622, "alphanum_fraction": 0.7705382704734802, "avg_line_length": 28.41666603088379, "blob_id": "9e6bb38609ea3f92e6ffdd7bbb0b04c1554c54dd", "content_id": "c09f763c039b0aba69bc8aee01433c03361ead78", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 369, "license_type": "permissive", "max_line_length": 78, "num_lines": 12, "path": "/README.md", "repo_name": "pb-students/PSIO-02-sampling", "src_encoding": "UTF-8", "text": "# 3-Przetwarzanie-Sygnalow-i-Obrazow-02-Py\nZadanie 2gie z PSów PSiO z Sławomirem Zielińskim\n\nCez: https://cez2.wi.pb.edu.pl/moodle/mod/assign/view.php?id=25364&action=view\n\nW razie problemów proszę pisać do FreeDOOM#4231 na discordzie ^w^\n\nJuż ogarnąłem w jak w miarę sensowny sposób dzielić się kodem :>\n\nTreść zadań:\n\n![alt text](Screen.PNG?raw=true)\n" } ]
2
Guoozz/monitor
https://github.com/Guoozz/monitor
e143e4b60ed12a774a5704bcc55ddfb871905df6
c903a2d6d2f39a96824fdd90ff247cbcdebf1db5
2db9ea7fa0c3ef7e0e0caf19710ee4aeb4d9644a
refs/heads/master
2021-01-10T17:47:09.918203
2016-03-05T01:09:45
2016-03-05T01:09:45
53,145,606
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6838235259056091, "alphanum_fraction": 0.6838235259056091, "avg_line_length": 25.153846740722656, "blob_id": "d0fbdc26741684ecabf059394e9aa00070d1e554", "content_id": "a938902ee3349cce3654f980bf05808c25a3e20a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 680, "license_type": "no_license", "max_line_length": 57, "num_lines": 26, "path": "/monitor_chart/views.py", "repo_name": "Guoozz/monitor", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\n# Create your views here.\n\ndef get_warn(request):\n return HttpResponse('i am warn')\n\ndef get_flow(request):\n room = request.GET.get('room')\n return HttpResponse({'fuck':'you'})\n\ndef get_message(request):\n\n _type = request.GET.get('type',None)\n title = request.GET.get('title',None)\n content = request.GET.get('content',None)\n is_blcok = request.GET.get('isBlock',False)\n ip = request.GET.get('ip',None)\n referer = request.GET.get('referer',None)\n \n return HttpResponse('i am message')\n\ndef dashboard(request):\n \n return render(request,'monitor_chart/dashboard.html')\n" }, { "alpha_fraction": 0.7699999809265137, "alphanum_fraction": 0.7699999809265137, "avg_line_length": 19, "blob_id": "a4fa0458041fe713a5dd231b38186c5333c559d9", "content_id": "b987ad0eb7f400101ab8a16fbece5f831f525d41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100, "license_type": "no_license", "max_line_length": 36, "num_lines": 5, "path": "/monitor_chart/apps.py", "repo_name": "Guoozz/monitor", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass MonitorChartConfig(AppConfig):\n name = 'monitor_chart'\n" } ]
2
louisdang/govhack2016
https://github.com/louisdang/govhack2016
b45ef6363d14003afcae2bb415e3b1af6f1c3a00
25aeee7506fcd6c07ff71cb83360c9d13a60d3e4
bc8c9eb200cc7929c51587c85963ff24694f1ce7
refs/heads/master
2020-05-29T11:50:59.543791
2016-07-31T06:25:35
2016-07-31T06:25:35
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7494600415229797, "alphanum_fraction": 0.7494600415229797, "avg_line_length": 32.14285659790039, "blob_id": "5538e518dbbc27c659c897355875834edd554803", "content_id": "6848d5ef08f1d18f87a1acc6ee825e985946221d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "no_license", "max_line_length": 86, "num_lines": 14, "path": "/govhack16_django/mysite/mysite/urls.py", "repo_name": "louisdang/govhack2016", "src_encoding": "UTF-8", "text": "from django.conf.urls import include, url\nfrom django.contrib import admin\n\nfrom django.contrib import admin\n#from search_recipes.views import search_recipes_form, search_recipes, get_full_recipe\nfrom polls.views import search_form,search_postcode\nfrom django.conf import settings\n\nurlpatterns = [\n url(r'^polls/', include('polls.urls')),\n url(r'^admin/', admin.site.urls),\n\turl(r'^search_form/', search_form),\n\turl(r'^search_postcode/', search_postcode),\n]" }, { "alpha_fraction": 0.6664749979972839, "alphanum_fraction": 0.6710753440856934, "avg_line_length": 25.953489303588867, "blob_id": "ef069ae5caa2ed7c37bbdff3a8646eb63079046c", "content_id": "e1835ebe072d10e396e9cb6701566274b1675c03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3478, "license_type": "no_license", "max_line_length": 99, "num_lines": 129, "path": "/sides/views.py", "repo_name": "louisdang/govhack2016", "src_encoding": "UTF-8", "text": "from django.http import HttpResponseBadRequest, JsonResponse, HttpResponse, HttpResponseServerError\nfrom sides import utils\nimport json\nimport logging\nfrom django.shortcuts import render\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\nfrom django.contrib.staticfiles import finders\nimport os\nimport urllib2 # the lib that handles the url stuff\nimport json\nfrom django.http import JsonResponse\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(filename='/home/ec2-user/log')\n\ndef get_optimal_routes(request):\n\ttry:\n\t if request.method=='POST':\n\t \tdata = json.loads(request.body)\t \t\n\t log.info(request.POST)\n\n\t result = utils.get_optimal_routes(data['sources'], (data['destinations']))\n\t \treturn JsonResponse(result, safe=False)\n\t else:\n\t return HttpResponseBadRequest(\"Only accepts POST for now\")\n\texcept Exception as e:\n\t\treturn HttpResponseServerError(\"Server error: {}\".format(e))\n\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n# Create your views here.\n\ndef search_form(request):\n\t#return HttpResponse(\"search_form.\")\n\t#return render(request, 'search_form.html')\n\treturn render(request, 'index.html')\n\t\ndef get_bushfire_cat(school_code):\n\tbush_fire_risk = \"\"\n\t\n\tfinders.find('NSW-Government-Schools-by-Bushfire-Category.txt')\n\tsearched_locations = finders.searched_locations\n\t#print searched_locations\n\tfile_path = os.path.join(searched_locations[-1],'NSW-Government-Schools-by-Bushfire-Category.txt')\n\tprint file_path\n\t\n\twith open(file_path) as f:\n\t\tf.readline()\n\t\tlines = f.readlines()\n\t\t\n\t\tfor each_line in lines:\n\t\t\tcols = each_line.split(\"\\t\")\n\t\t\t\n\t\t\tdoe_school_code = cols[0].rstrip(\"\\r\\n\")\n\t\t\t\n\t\t\tif(doe_school_code == school_code):\n\t\t\t\tprint school_code\n\t\t\t\t\n\t\t\t\tbush_fire_risk = cols[2].rstrip(\"\\r\\n\")\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tbush_fire_risk = \"No_risk\"\n\t\t\t\n\t\t\tprint bush_fire_risk\n\t\t\t\n\treturn bush_fire_risk\t\t\n\t\n\ndef search_postcode(request):\n\t\n\tif 'postcode' in request.GET:\n\t\tpostcode = request.GET['postcode']\n\t\n\t\t\n\t\tjson_array = []\n\t\tfinders.find('Government-School-Locations.txt')\n\t\tsearched_locations = finders.searched_locations\n\t\t#print searched_locations\n\t\tfile_path = os.path.join(searched_locations[-1],'Government-School-Locations.txt')\n\t\tprint file_path\n\t\t\n\t\twith open(file_path) as f:\n\t\t\tfirst_line = f.readline()\n\t\t\tprint first_line\n\t\t\t\n\t\t\tfirst_line = f.readline()\n\t\t\tlines = f.readlines()\n\t\t\t\t\n\t\t\tfor each_line in lines:\n\t\t\t\tcols = each_line.split(\"\\t\")\n\t\t\t\t\t\n\t\t\t\tschool_code = cols[0].rstrip(\"\\r\\n\")\n\t\t\t\tschool_name_col = cols[2].rstrip(\"\\r\\n\")\n\t\t\t\tpostcode_col = cols[19].rstrip(\"\\r\\n\")\n\t\t\t\ttotal_enrollments = cols[10].rstrip(\"\\r\\n\")\n\t\t\t\tlat = cols[20].rstrip(\"\\r\\n\")\n\t\t\t\tlong = cols[21].rstrip(\"\\r\\n\")\n\t\t\t\t\t\n\t\t\t\tif(str(postcode) == postcode_col):\n\t\t\t\t\t\n\t\t\t\t\tbush_fire_cat = get_bushfire_cat(school_code)\n\n\t\t\t\t\tprint \"---------------------\"\n\t\t\t\t\tprint postcode_col\n\t\t\t\t\tprint school_name_col\n\t\t\t\t\tprint total_enrollments\n\t\t\t\t\tprint lat\n\t\t\t\t\tprint long\n\t\t\t\t\tprint bush_fire_cat\n\t\t\t\t\t\n\t\t\t\t\tdata = {\n\t\t\t\t\t'json_school_name' : school_name_col,\n\t\t\t\t\t'json_total_enrollments' : total_enrollments,\n\t\t\t\t\t'lat' : lat,\n\t\t\t\t\t'long' : long,\n\t\t\t\t\t'bush_fire_cat' : bush_fire_cat\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\t\tjson_school_output = json.dumps(data)\n\t\t\t\t\tjson_array.append(json_school_output)\n\t\t\n\t\t\n\t\t\n\t#return HttpResponse(\"POST CODE.\")\n\treturn JsonResponse({'json_array': json_array})\n\t#return render(request, 'search_postcode.html',{'json_array': json_array})\n\n" }, { "alpha_fraction": 0.5373256802558899, "alphanum_fraction": 0.5479901432991028, "avg_line_length": 18.672412872314453, "blob_id": "f3d209d5d96f21d39bf5bdd3cda2d4fba273d719", "content_id": "78021adff6305d5778e724ed6763d6f23b7d380d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "no_license", "max_line_length": 52, "num_lines": 58, "path": "/get_schools_of_postcode.py", "repo_name": "louisdang/govhack2016", "src_encoding": "UTF-8", "text": "# Code by : Anushi Shah\r\nimport sys\r\nimport json\r\n\r\ndef main():\r\n # my code here\r\n\t\r\n\tprint \"hello\"\r\n\tjson_array = get_schools_postcode(2000)\r\n\t\r\n\tfor each_obj in json_array:\r\n\t\tjson_str = json.loads(each_obj)\r\n\t\tprint json_str\r\n\t\r\n\r\ndef get_schools_postcode(postcode):\r\n\t\tprint \"school function\"\r\n\t\tprint postcode\r\n\t\t\r\n\t\tjson_array = []\r\n\t\t\r\n\t\twith open('Government-School-Locations.txt') as f:\r\n\t\t\tfirst_line = f.readline()\r\n\t\t\tlines = f.readlines()\r\n\t\t\t\r\n\t\t\tfor each_line in lines:\r\n\t\t\t\tcols = each_line.split(\"\\t\")\r\n\t\t\t\t\r\n\t\t\t\tschool_name_col = cols[2]\r\n\t\t\t\tpostcode_col = cols[19]\r\n\t\t\t\ttotal_enrollments = cols[10]\r\n\t\t\t\tlat = cols[20]\r\n\t\t\t\tlong = cols[21]\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\tif(str(postcode) == postcode_col):\r\n\t\t\t\t\t#print \"---------------------\"\r\n\t\t\t\t\t#print postcode_col\r\n\t\t\t\t\t#print school_name_col\r\n\t\t\t\t\t#print total_enrollments\r\n\t\t\t\t\t#print lat\r\n\t\t\t\t\t#print long\r\n\t\t\t\t\t\r\n\t\t\t\t\tdata = {\r\n\t\t\t\t\t'json_school_name' : school_name_col,\r\n\t\t\t\t\t'json_total_enrollments' : total_enrollments,\r\n\t\t\t\t\t'lat' : lat,\r\n\t\t\t\t\t'long' : long\r\n\t\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\t\tjson_school_output = json.dumps(data)\r\n\t\t\t\t\tjson_array.append(json_school_output)\r\n\t\t\t\t\t\r\n\t\t\treturn json_array\r\n\t\t\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n\t\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5686376690864563, "alphanum_fraction": 0.6144829392433167, "avg_line_length": 43.651161193847656, "blob_id": "c83ea04813c4a391afbb7238328fb43ea10f73e0", "content_id": "4ae5789178ae02d0d549a3720dd1e655ec4c57ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3839, "license_type": "no_license", "max_line_length": 482, "num_lines": 86, "path": "/sides/utils.py", "repo_name": "louisdang/govhack2016", "src_encoding": "UTF-8", "text": "import googlemaps\ngmaps = googlemaps.Client(key='AIzaSyDPvDQc0_i1cT9sMoT7vnHRUuk8vF3D1CE')\nfrom pulp import LpProblem, LpMinimize, LpInteger, LpVariable, lpSum\nimport collections\nimport logging\n\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\n\ndef convert_int(x):\n if x is None:\n return 0\n try:\n return int(float(x))\n except ValueError:\n raise\n\n\ndef get_optimal_routes(sources, destinations):\n sources = collections.OrderedDict([(x['id'], x) for x in sources])\n destinations = collections.OrderedDict([(x['id'], x) for x in destinations])\n\n sources_points = [{'lat': x['lat'], 'lng': x['lng']} for x in sources.values()]\n destinations_points = [{'lat': x['lat'], 'lng': x['lng']} for x in destinations.values()]\n\n source_ids = [str(x['id']) for x in sources.values()]\n dest_ids = [str(x['id']) for x in destinations.values()]\n\n demand = {str(x['id']): convert_int(x['num_students']) for x in sources.values()}\n supply = {str(x['id']): convert_int(x['num_students']) for x in destinations.values()}\n\n log.info(\"Calling gmaps api...\")\n distances = gmaps.distance_matrix(origins=sources_points, destinations=destinations_points, mode='walking')\n\n costs = {}\n for i, origin in enumerate(distances['rows']):\n origin_costs = {}\n for j, entry in enumerate(origin['elements']):\n origin_costs[dest_ids[j]] = entry['duration']['value']\n costs[source_ids[i]] = origin_costs\n\n prob = LpProblem(\"Evaucation Routing for Schools\",LpMinimize)\n routes = [(s,d) for s in source_ids for d in dest_ids]\n route_lookup = {'Route_{}_{}'.format(x.replace(' ','_'),y.replace(' ','_')):(x,y) for (x,y) in routes}\n route_vars = LpVariable.dicts(\"Route\",(source_ids,dest_ids),0,None,LpInteger)\n prob += lpSum([route_vars[w][b]*(costs[w][b]**2) for (w,b) in routes])\n for dest in dest_ids:\n prob += lpSum([route_vars[source][dest] for source in source_ids]) <= supply[dest], \"Students going to {} is <= {}\".format(dest, supply[dest])\n for source in source_ids:\n prob += lpSum([route_vars[source][dest] for dest in dest_ids]) == demand[source], \"Students leaving {} is {}\".format(source, demand[source])\n\n log.info(\"Optimizing routes...\")\n prob.solve()\n\n if prob.status != 1:\n raise Exception(\"Algorithm could not converge to a solution\")\n\n result = []\n for v in prob.variables():\n src, dst = route_lookup[v.name]\n value = v.value()\n result.append({'src': sources[src], 'dst': destinations[dst], 'value': int(value)})\n return result\n\nif __name__ == '__main__':\n # import csv\n # import os\n # schools = collections.OrderedDict()\n # for row in csv.DictReader(open(os.path.expanduser('~/workbook1.csv'))):\n # try:\n # schools[row['SCHOOL_NAME']] =\\\n # {'id': row['SCHOOL_NAME'],\n # 'lat': float(row['LATITUDE']),\n # 'lng': float(row['LONGITUDE']),\n # 'num_students': convert_int(row['TOTAL_ENROLMENTS']),\n # 'capacity': convert_int(row['TOTAL_ENROLMENTS'])}\n # except ValueError:\n # continue\n\n # sources = schools.values()[:3]\n # destinations = schools.values()[4:10]\n import json\n data = json.loads('{\"sources\":[{\"id\":0,\"lat\":-33.78075,\"lng\":151.168917,\"num_students\":\"723\"},{\"id\":1,\"lat\":-33.767479,\"lng\":151.18429,\"num_students\":\"769\"},{\"id\":2,\"lat\":-33.773952,\"lng\":151.172207,\"num_students\":\"56\"}],\"destinations\":[{\"id\":0,\"lat\":-33.78499712154629,\"lng\":151.17525190114975,\"num_students\":null},{\"id\":1,\"lat\":-33.77950403725315,\"lng\":151.1787709593773,\"num_students\":\"200\"},{\"id\":2,\"lat\":-33.77251232953873,\"lng\":151.18374913930893,\"num_students\":\"100\"}]}')\n sources = data['sources']\n destinations = data['destinations']\n results = get_optimal_routes(sources, destinations)" }, { "alpha_fraction": 0.49440136551856995, "alphanum_fraction": 0.5267010927200317, "avg_line_length": 20.89622688293457, "blob_id": "687b8b0d3fcee31adeb0a305cd1b5617343da3a5", "content_id": "aa2de050978947cfe8ca77619ca9361eb4cb59b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2322, "license_type": "permissive", "max_line_length": 82, "num_lines": 106, "path": "/sides/templates/js/main.js", "repo_name": "louisdang/govhack2016", "src_encoding": "UTF-8", "text": "\nvar map;\n\nvar appState = {\n isDropping: false\n}\n\nvar initMap = function () {\n map = new google.maps.Map(document.getElementById('map'), {\n center: {lat: -34.397, lng: 150.644},\n zoom: 8\n });\n}\n\nvar getSchools = function () {\n return [\n {\n school: 'Killara High School',\n capacity: 400,\n lat: -33.860427,\n long: 151.204871,\n },\n {\n school: 'Hornsby Girls' ,\n capacity: 400,\n lat: -33.860863,\n long: 151.204832,\n },\n {\n school: 'North Sydney Boys' ,\n capacity: 400,\n lat: -33.863407,\n long: 151.21408,\n },\n ]\n}\n\nvar showSchoolsOnMap = function (schools) {\n schools.forEach(function(school) {\n var marker = new google.maps.Marker({\n position: { lat: school.lat, lng: school.long },\n map: map,\n title: 'Hello World!'\n });\n })\n}\n\nvar navigateTo = function (positionString) {\n var geocoder = new google.maps.Geocoder();\n geocodeAddress(geocoder, map, positionString);\n\n}\n\nvar geocodeAddress = function (geocoder, resultsMap, positionString) {\n geocoder.geocode({'address': positionString}, function(results, status) {\n if (status === 'OK') {\n resultsMap.setCenter(results[0].geometry.location);\n resultsMap.setZoom(14);\n var marker = new google.maps.Marker({\n map: resultsMap,\n position: results[0].geometry.location\n });\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}\n\n\n$('#mainInput').submit(function (e) {\n\n e.preventDefault();\n var formValue = $('#inputContent').val();\n\n // $.ajax({\n // url: 'test-string',\n // dataType: 'json',\n // cache: false,\n // success: function(response) {\n // },\n // error: function(xhr, status, err) {\n // }\n // });\n\n // on submit draw pointers\n\n // jsonData\n\n\n var schools = getSchools();\n\n showSchoolsOnMap(schools);\n\n navigateTo(formValue + ' Australia');\n\n})\n\n$('#addSite').on('click', function(e) {\n\n appState.isDropping = appState.isDropping ? false : true;\n\n if ( appState.isDropping ) {\n\n }\n\n\n})\n" }, { "alpha_fraction": 0.7254098653793335, "alphanum_fraction": 0.7581967115402222, "avg_line_length": 13.352941513061523, "blob_id": "c3111ef1502266b19958364bd74ec05150d03011", "content_id": "7858ae8e3363b817cb9432ecb3c2919d5edb5e64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 244, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/README.md", "repo_name": "louisdang/govhack2016", "src_encoding": "UTF-8", "text": "# govhack2016\nGovHack 2016 repository for SIDES by Team Zubats\n\nRequires these libraries:\n\ndjango-cors-headers\nPuLP\ngooglemaps\n\nTo install them run:\npip install PuLP django-cors-headers googlemaps\n\nDev Team:\n- Anushi Shah\n- Jeremy Arimado\n- Louis Dang\n- Ronnie Lu\n" }, { "alpha_fraction": 0.6771888136863708, "alphanum_fraction": 0.6896962523460388, "avg_line_length": 26.064516067504883, "blob_id": "a6e035b8c8fdb771aa450c87eb1b4f2c3424951e", "content_id": "0d61350d6905219ede1dc596d3da456d7bd1a637", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1679, "license_type": "no_license", "max_line_length": 117, "num_lines": 62, "path": "/govhack16_django/mysite/polls/views.py", "repo_name": "louisdang/govhack2016", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\nfrom django.contrib.staticfiles import finders\nimport os\nimport urllib2 # the lib that handles the url stuff\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n# Create your views here.\n\ndef search_form(request):\n\t#return HttpResponse(\"search_form.\")\n\treturn render(request, 'search_form.html')\n\t\ndef search_postcode(request):\t\n\tif 'postcode' in request.GET:\n\t\tpostcode = request.GET['postcode']\n\t\n\t\tprint \"school function\"\n\t\t#print postcode\n\t\t\t\n\t\t#url_file = static('Government-School-Locations.txt')\n\t\t#print url_file\n\t\t\n\t\t#data = urllib2.urlopen('https://github.com/ronniels92372/govhack2016/blob/master/Government-School-Locations.txt')\n\t\t \n\t\tresult = finders.find('Government-School-Locations.txt')\n\t\tsearched_locations = finders.searched_locations\n\t\t#print searched_locations\n\t\tfile_path = os.path.join(searched_locations[1],'Government-School-Locations.txt')\n\t\t\n\t\twith open(file_path) as f:\n\t\t\tfirst_line = f.readline()\n\t\t\tprint first_line\n\t\t\t\n\t\t\tfirst_line = f.readline()\n\t\t\tlines = f.readlines()\n\t\t\t\t\n\t\t\tfor each_line in lines:\n\t\t\t\tcols = each_line.split(\"\\t\")\n\t\t\t\t\t\n\t\t\t\tschool_name_col = cols[2]\n\t\t\t\tpostcode_col = cols[19]\n\t\t\t\ttotal_enrollments = cols[10]\n\t\t\t\tlat = cols[20]\n\t\t\t\tlong = cols[21]\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif(str(postcode) == postcode_col):\n\t\t\t\t\tprint \"---------------------\"\n\t\t\t\t\tprint postcode_col\n\t\t\t\t\tprint school_name_col\n\t\t\t\t\tprint total_enrollments\n\t\t\t\t\tprint lat\n\t\t\t\t\tprint long\n\t\t\t\t\t\n\t\t\n\t\t\n\treturn HttpResponse(\"POST CODE.\")\n\t#return render(request, 'search_form.html')\n\n" } ]
7
muhchaudhary/MNSIT-digit-classification
https://github.com/muhchaudhary/MNSIT-digit-classification
72aa6e0cc94659be0a66214697665e4605b40c60
c69a14c83fbee2ed576f528272790bf89161b8a7
e03d476177cf87c905c61cb792202564c0b0c3f4
refs/heads/master
2023-04-24T20:19:46.503348
2021-05-16T20:29:53
2021-05-16T20:29:53
367,977,637
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5734899044036865, "alphanum_fraction": 0.6057047247886658, "avg_line_length": 30.36842155456543, "blob_id": "196749462046de534df0de715764594e79c006d0", "content_id": "be50b8d3a2b42c7b5a4238f14f9e4adbbccb0374", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2980, "license_type": "no_license", "max_line_length": 88, "num_lines": 95, "path": "/webcam_capture.py", "repo_name": "muhchaudhary/MNSIT-digit-classification", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n#from sklearn.externals import joblib\nimport joblib\nfrom skimage.feature import hog\nfrom PIL import Image\ncropping = False\n\nx_start, y_start, x_end, y_end = 0, 0, 0, 0\ncam = cv2.VideoCapture(0)\n\ncv2.namedWindow(\"test\")\n\n\ndef take_webcame_img(): \n while True:\n ret, frame = cam.read()\n if not ret:\n print(\"failed to grab frame\")\n break\n cv2.imshow(\"test\", frame)\n k = cv2.waitKey(1)\n if k%256 == 32:\n # SPACE pressed\n img_name = \"img_with_number.png\"\n cv2.imwrite(img_name, frame)\n print(\"{} written!\".format(img_name))\n break\n cam.release()\n cv2.destroyAllWindows()\n\n\ndef mouse_crop(event, x, y, flags, param):\n # grab references to the global variables\n global x_start, y_start, x_end, y_end, cropping\n # if the left mouse button was DOWN, start RECORDING\n # (x, y) coordinates and indicate that cropping is being\n if event == cv2.EVENT_LBUTTONDOWN:\n x_start, y_start, x_end, y_end = x, y, x, y\n cropping = True\n # Mouse is Moving\n elif event == cv2.EVENT_MOUSEMOVE:\n if cropping == True:\n x_end, y_end = x, y\n # if the left mouse button was released\n elif event == cv2.EVENT_LBUTTONUP:\n # record the ending (x, y) coordinates\n x_end, y_end = x, y\n cropping = False # cropping is finished\n refPoint = [(x_start, y_start), (x_end, y_end)]\n if len(refPoint) == 2: #when two points were found\n roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]\n cv2.imshow(\"Cropped\", roi)\n img_name = \"img_with_number.png\"\n cv2.imwrite(img_name, roi)\n\n\ndef crop(image):\n cv2.namedWindow(\"image\")\n cv2.setMouseCallback(\"image\", mouse_crop)\n\n while True:\n i = image.copy()\n k = cv2.waitKey(1)\n if k%256 == 27:\n print(\"latest crop selected!\")\n cv2.destroyAllWindows()\n break\n if not cropping:\n cv2.imshow(\"image\", image)\n elif cropping:\n cv2.rectangle(i, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2)\n cv2.imshow(\"image\", i)\n #cv2.waitKey(1)\n # close all open windows\n cv2.destroyAllWindows()\n\ntake_webcame_img()\nimage = cv2.imread('img_with_number.png')\noriImage = image.copy()\ncrop(image)\nimage = cv2.imread('img_with_number.png')\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nth2 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,15,2)\n(thresh, im_binary) = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\ncv2.imshow('th2',im_binary)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\npil_image=Image.fromarray(im_binary)\npil_image = pil_image.resize((28,28),resample=4)\n#thresh = 200\n#fn = lambda x : 255 if x > thresh else 0\n#pil_image = pil_image.convert('L').point(fn, mode='1')\npil_image.save('conv_img.bmp')\n" }, { "alpha_fraction": 0.8467742204666138, "alphanum_fraction": 0.8467742204666138, "avg_line_length": 61, "blob_id": "69e140a5c014f4650b961a67a223fcf748e2e7a4", "content_id": "e43b727b1d3c6b5c442acbb89a04a4947dd0ce0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 124, "license_type": "no_license", "max_line_length": 94, "num_lines": 2, "path": "/README.md", "repo_name": "muhchaudhary/MNSIT-digit-classification", "src_encoding": "UTF-8", "text": "# MNSIT-digit-classification\nA simple CNN for handwritten digit classification based on the MNSIT handwritten digit dataset\n" }, { "alpha_fraction": 0.6089109182357788, "alphanum_fraction": 0.6574257612228394, "avg_line_length": 27.08333396911621, "blob_id": "80e65b720db3591eb7407979e8541d6da11f47a8", "content_id": "9d6c5af88d0dfcd1592d5fcead9827998f02002c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1010, "license_type": "no_license", "max_line_length": 74, "num_lines": 36, "path": "/model_tester.py", "repo_name": "muhchaudhary/MNSIT-digit-classification", "src_encoding": "UTF-8", "text": "from keras.datasets import mnist\nfrom tensorflow.keras.models import load_model\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nfrom PIL import Image\n\nmodel = load_model('saved_model/my_model')\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\nimage_index = 8888\nimage =Image.open('conv_img.bmp')\nrawData = image.load()\n#print(rawData[0,0])\ndata = []\nfor y in range(28):\n row = []\n for x in range(28):\n row.append(255-rawData[x,y])\n data.append(row)\n\nfor x in range(len(data)):\n data[0][x] = 0\n data[x][0] = 0\n data[x][1] = 0\n if data[x][1] > 0 and data[x][1] <= 255:\n print(\"what the hell\")\n data[x][1] == 0\ndata = np.array(data)\nplt.imshow(data.reshape(28,28),cmap='Greys')\n#plt.imshow(x_test[image_index].reshape(28,28),cmap='Greys')\nplt.show()\n#print(data)\npred = model.predict(data.reshape(1, 28, 28, 1))\n#pred2 = model.predict(x_test[image_index].reshape(1,28,28,1))\nprint(pred.argmax())\n#print(pred2.argmax())" }, { "alpha_fraction": 0.6953125, "alphanum_fraction": 0.7369791865348816, "avg_line_length": 29.289474487304688, "blob_id": "158796e51358fd07b188a5d9db4fbb36757fb976", "content_id": "0f372b7bf199c57546c60aa2be6cf53354863a1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 81, "num_lines": 38, "path": "/main.py", "repo_name": "muhchaudhary/MNSIT-digit-classification", "src_encoding": "UTF-8", "text": "from keras.datasets import mnist\nfrom matplotlib import pyplot\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D\nimport cv2\n# load dataset\n(trainX, trainy), (testX, testy) = mnist.load_data()\n\n\n#reshaping the array to 4 dimenstional numpy array, used for Keras API\ntrainX = trainX.reshape(trainX.shape[0],28,28,1)\ntestX = testX.reshape(testX.shape[0],28,28,1)\ninp_shape = (28,28,1)\ntrainX = trainX.astype('float32')\ntestX = testX.astype('float32')\n#normalize RGB values\ntrainX /= 255\ntestX /= 255\nprint(\"trainX shape: \", trainX.shape)\n#setting up the model\nmodel = Sequential()\nmodel.add(Conv2D(28,kernel_size=(3,3),input_shape=inp_shape))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(128,activation=tf.nn.relu))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10,activation=tf.nn.softmax))\n\nmodel.compile(optimizer='adam', \n loss='sparse_categorical_crossentropy', \n metrics=['accuracy'])\n\nmodel.fit(x=trainX,y=trainy, epochs=10)\n\nmodel.save('saved_model/my_model')\n\nmodel.evaluate(testX, testy)\n\n" } ]
4
kazi-arafat/custometfeedbackapp
https://github.com/kazi-arafat/custometfeedbackapp
a3127477a3301f1e3ee1864bb3bf6b16407f496f
0ee18b6e5b4c052ff7f882d9cedab0f418ab23c2
a43e260f22460a83802fa3ae40539bcef06a9c73
refs/heads/master
2021-06-28T09:26:38.245090
2019-11-26T18:51:26
2019-11-26T18:51:26
224,463,801
0
0
null
2019-11-27T15:43:04
2019-11-27T15:43:58
2021-03-20T02:33:54
HTML
[ { "alpha_fraction": 0.6310455799102783, "alphanum_fraction": 0.6582220196723938, "avg_line_length": 35.813560485839844, "blob_id": "3e3e7461f2ac2f7ddd6e49b4668367c72e7a7683", "content_id": "3c0b26c758adc23be11606c8976ec4955f87a263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2171, "license_type": "no_license", "max_line_length": 190, "num_lines": 59, "path": "/app.py", "repo_name": "kazi-arafat/custometfeedbackapp", "src_encoding": "UTF-8", "text": "from flask import Flask,flash,render_template,request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom send_mail import send_email\n\napp = Flask(__name__)\nENV = \"prod\"\n\nif (ENV == \"dev\"):\n app.debug = True\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:abc123@localhost/CustomerFeedback'\nelse:\n app.debug = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://qhgxgzgfmalnxu:a2bc34670c77162e732c08c4404918b33e7ce9096d07be2ec3710bef10bd2541@ec2-107-20-239-47.compute-1.amazonaws.com:5432/d4603d4b6h369v'\n\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\nclass FeedbackForm(db.Model):\n __tablename__ = 'feedback'\n id = db.Column(db.Integer, primary_key=True)\n customer = db.Column(db.String(200), unique=True)\n dealer = db.Column(db.String(200))\n rating = db.Column(db.Integer)\n comments = db.Column(db.Text())\n\n def __init__(self,customer,dealer,rating,comments):\n self.customer = customer\n self.dealer = dealer\n self.rating = rating\n self.comments = comments\n\n \n\[email protected](\"/\")\ndef Index():\n return render_template(\"index.html\")\n\[email protected](\"/submit\",methods=['POST'])\ndef Submit():\n if (request.method == \"POST\"):\n customer = request.form['customer']\n dealer = request.form['dealer']\n rating = request.form['rating']\n comments = request.form['comments']\n # print (\"{0} {1} {2} {3}\".format(customer,dealer,rating,comments))\n if (customer == \"\" or dealer == \"\"):\n return render_template(\"index.html\",message=\"Please enter required fields.\")\n # Check if the customer already submitted feedback and then proceed with further steps\n if (db.session.query(FeedbackForm).filter(FeedbackForm.customer == customer).count() == 0):\n data = FeedbackForm(customer,dealer,rating,comments)\n db.session.add(data)\n db.session.commit()\n send_email(customer, dealer, rating, comments)\n return render_template(\"success.html\")\n return render_template(\"index.html\",message=\"You have already submitted feedback.\")\n\nif (__name__ == \"__main__\"):\n app.run()" }, { "alpha_fraction": 0.6213333606719971, "alphanum_fraction": 0.6386666893959045, "avg_line_length": 31.65217399597168, "blob_id": "34caaed77c64ab875e0f5bd04a44d510dc284788", "content_id": "cb7228896da5f1cf706e5bf4e6a44338bf016322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 750, "license_type": "no_license", "max_line_length": 180, "num_lines": 23, "path": "/send_mail.py", "repo_name": "kazi-arafat/custometfeedbackapp", "src_encoding": "UTF-8", "text": "import smtplib\nfrom email.mime.text import MIMEText\n\ndef send_email(customer, dealer, rating, comments):\n port = 587\n userid = \"40dc44b7a3fe59\"\n pwd = \"b7183feda5fb84\"\n host = \"smtp.mailtrap.io\"\n\n to_email = \"[email protected]\"\n from_email = \"[email protected]\"\n\n mail_body = f\"<h3>Customer Feedback</h3><hr><ul><li>Customer Name : {customer}</li><li>Dealer Name : {dealer}</li><li>Rating : {rating}</li><li>Comments : {comments}</li></ul>\"\n\n msg = MIMEText(mail_body,'html')\n msg['Subject'] = \"Customer Feedback\"\n msg['From'] = from_email\n msg['To'] = to_email\n\n # Send Email\n with smtplib.SMTP(host=host,port=port) as smtpServer:\n smtpServer.login(userid,pwd)\n smtpServer.sendmail(to_email, from_email, msg.as_string())" } ]
2
JamesTFarrington/stellar
https://github.com/JamesTFarrington/stellar
f0277a62cfd6597831af55feb74f8a33fa65c437
df2eda816013d7c34634c9a2c0c4117609be7f40
2ee115b7e9aab7ee9d7295b3a32ff7b485aaa39f
refs/heads/master
2021-01-10T20:13:12.652776
2014-08-29T20:20:55
2014-08-29T20:21:47
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5390404462814331, "alphanum_fraction": 0.5390404462814331, "avg_line_length": 19.056604385375977, "blob_id": "bd67e5fe14b77e30619b68835665a047bf06b03a", "content_id": "568169490bfb864f27f72d8056d07fc3bca8a8d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1063, "license_type": "permissive", "max_line_length": 64, "num_lines": 53, "path": "/stellar/config.py", "repo_name": "JamesTFarrington/stellar", "src_encoding": "UTF-8", "text": "import os\nimport yaml\nfrom schema import Use, Schema, SchemaError\n\n\nclass InvalidConfig(Exception):\n pass\n\n\nclass MissingConfig(Exception):\n pass\n\n\ndefault_config = {}\nschema = Schema({\n 'stellar_url': Use(str),\n 'url': Use(str),\n 'project_name': Use(str),\n 'tracked_databases': [Use(str)]\n})\n\n\ndef load_config():\n config = {}\n current_directory = os.getcwd()\n while True:\n try:\n with open(\n os.path.join(current_directory, 'stellar.yaml'),\n 'rb'\n ) as fp:\n config = yaml.safe_load(fp)\n break\n except IOError:\n pass\n current_directory = os.path.abspath(\n os.path.join(current_directory, '..')\n )\n\n if current_directory == '/':\n break\n\n if not config:\n raise MissingConfig()\n\n for k, v in default_config.items():\n if k not in config:\n config[k] = v\n\n try:\n return schema.validate(config)\n except SchemaError, e:\n raise InvalidConfig(e)\n" }, { "alpha_fraction": 0.7851239442825317, "alphanum_fraction": 0.7851239442825317, "avg_line_length": 14.125, "blob_id": "be78aa36ba435869bfcbea5a55dc998e3be054cc", "content_id": "f7a1fc6e4e85d967ffd184fd6a645b862c8af705", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "permissive", "max_line_length": 29, "num_lines": 8, "path": "/stellar/__init__.py", "repo_name": "JamesTFarrington/stellar", "src_encoding": "UTF-8", "text": "import app\nimport command\nimport config\nimport models\nimport operations\nimport exceptions\n\n__version__ = app.__version__\n" }, { "alpha_fraction": 0.5013728737831116, "alphanum_fraction": 0.5038440227508545, "avg_line_length": 26.793893814086914, "blob_id": "014142e258e6965df039793d3670717cf829c26b", "content_id": "47018f80e8818743b184d5cb9aae4f10fed65b2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3642, "license_type": "permissive", "max_line_length": 74, "num_lines": 131, "path": "/stellar/operations.py", "repo_name": "JamesTFarrington/stellar", "src_encoding": "UTF-8", "text": "import sqlalchemy_utils\n\n\nSUPPORTED_DIALECTS = (\n 'postgresql',\n 'mysql'\n)\n\nclass NotSupportedDatabase(Exception):\n pass\n\n\ndef terminate_database_connections(raw_conn, database):\n if raw_conn.engine.dialect.name == 'postgresql':\n raw_conn.execute(\n '''\n SELECT pg_terminate_backend(pg_stat_activity.pid)\n FROM pg_stat_activity\n WHERE\n pg_stat_activity.datname = '%s' AND\n pid <> pg_backend_pid();\n ''' % database\n )\n else:\n # NotYetImplemented\n pass\n\n\ndef create_database(raw_conn, database):\n return sqlalchemy_utils.functions.create_database(\n '%s%s' % (raw_conn.engine.url, database)\n )\n\n\ndef copy_database(raw_conn, from_database, to_database):\n terminate_database_connections(raw_conn, from_database)\n\n if raw_conn.engine.dialect.name == 'postgresql':\n raw_conn.execute(\n '''\n CREATE DATABASE \"%s\" WITH TEMPLATE \"%s\";\n ''' %\n (\n to_database,\n from_database\n )\n )\n elif raw_conn.engine.dialect.name == 'mysql':\n # Horribly slow implementation.\n create_database(raw_conn, to_database)\n for row in raw_conn.execute('SHOW TABLES in %s;' % from_database):\n raw_conn.execute('''\n CREATE TABLE %s.%s LIKE %s.%s\n ''' % (\n to_database,\n row[0],\n from_database,\n row[0]\n ))\n raw_conn.execute('ALTER TABLE %s.%s DISABLE KEYS' % (\n to_database,\n row[0]\n ))\n raw_conn.execute('''\n INSERT INTO %s.%s SELECT * FROM %s.%s\n ''' % (\n to_database,\n row[0],\n from_database,\n row[0]\n ))\n else:\n raise NotSupportedDatabase()\n\n\ndef database_exists(raw_conn, database):\n return sqlalchemy_utils.functions.database_exists(\n '%s%s' % (raw_conn.engine.url, database)\n )\n\n\ndef remove_database(raw_conn, database):\n terminate_database_connections(raw_conn, database)\n return sqlalchemy_utils.functions.drop_database(\n '%s%s' % (raw_conn.engine.url, database)\n )\n\n\ndef rename_database(raw_conn, from_database, to_database):\n if raw_conn.engine.dialect.name == 'postgresql':\n raw_conn.execute(\n '''\n ALTER DATABASE \"%s\" RENAME TO \"%s\"\n ''' %\n (\n from_database,\n to_database\n )\n )\n elif raw_conn.engine.dialect.name == 'mysql':\n create_database(raw_conn, to_database)\n for row in raw_conn.execute('SHOW TABLES in %s;' % from_database):\n raw_conn.execute('''\n RENAME TABLE %s.%s TO %s.%s;\n ''' % (\n from_database,\n row[0],\n to_database,\n row[0]\n ))\n remove_database(raw_conn, from_database)\n else:\n raise NotSupportedDatabase()\n\n\ndef list_of_databases(raw_conn):\n if raw_conn.engine.dialect.name == 'postgresql':\n return [\n row[0]\n for row in raw_conn.execute('''\n SELECT datname FROM pg_database\n WHERE datistemplate = false\n ''')\n ]\n elif raw_conn.engine.dialect.name == 'mysql':\n return [\n row[0]\n for row in raw_conn.execute('''SHOW DATABASES''')\n ]\n else:\n raise NotSupportedDatabase()\n\n" }, { "alpha_fraction": 0.5653255581855774, "alphanum_fraction": 0.5675201416015625, "avg_line_length": 26.34000015258789, "blob_id": "c4f741384a96ffc98d07fc3dbc9a4a18378ddb6b", "content_id": "462b54f7548a76a42ce9761dd71c9bce6c5bb1e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6835, "license_type": "permissive", "max_line_length": 79, "num_lines": 250, "path": "/stellar/command.py", "repo_name": "JamesTFarrington/stellar", "src_encoding": "UTF-8", "text": "import argparse\nimport sys\nimport os\nfrom datetime import datetime\nfrom time import sleep\n\nimport humanize\nimport click\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.exc import OperationalError\n\nfrom app import Stellar, __version__\nfrom config import InvalidConfig, MissingConfig\nfrom operations import database_exists, list_of_databases, SUPPORTED_DIALECTS\n\n\[email protected]()\ndef stellar():\n \"\"\"Fast database snapshots for development. It's like Git for databases.\"\"\"\n pass\n\[email protected]()\ndef version():\n \"\"\"Shows version number\"\"\"\n print \"Stellar %s\" % __version__\n\n\[email protected]()\ndef gc():\n \"\"\"Deletes old stellar tables that are not used anymore\"\"\"\n def after_delete(database):\n print \"Deleted table %s\" % database\n\n app = Stellar()\n app.delete_orphan_snapshots(after_delete)\n\n\[email protected]()\[email protected]('name', required=False)\ndef snapshot(name):\n \"\"\"Takes a snapshot of the database\"\"\"\n app = Stellar()\n name = name or app.default_snapshot_name\n\n if app.get_snapshot(name):\n print \"Snapshot with name %s already exists\" % name\n sys.exit(1)\n else:\n def before_copy(table_name):\n print \"Snapshotting database %s\" % table_name\n app.create_snapshot(name, before_copy=before_copy)\n\n\[email protected]()\ndef list():\n \"\"\"Returns a list of snapshots\"\"\"\n snapshots = Stellar().get_snapshots()\n\n print '\\n'.join(\n '%s: %s' % (\n s.snapshot_name,\n humanize.naturaltime(datetime.utcnow() - s.created_at)\n )\n for s in snapshots\n )\n\n\[email protected]()\[email protected]('name', required=False)\ndef restore(name):\n \"\"\"Restores the database from a snapshot\"\"\"\n app = Stellar()\n\n if not name:\n snapshot = app.get_latest_snapshot()\n if not snapshot:\n print (\n \"Couldn't find any snapshots for project %s\" %\n self.config['project_name']\n )\n sys.exit(1)\n else:\n snapshot = app.get_snapshot(name)\n if not snapshot:\n print (\n \"Couldn't find snapshot with name %s.\\n\"\n \"You can list snapshots with 'stellar list'\" % name\n )\n sys.exit(1)\n\n # Check if slaves are ready\n if not snapshot.slaves_ready:\n if app.is_copy_process_running(snapshot):\n sys.stdout.write(\n 'Waiting for background process(%s) to finish' %\n snapshot.worker_pid\n )\n sys.stdout.flush()\n while not snapshot.slaves_ready:\n sys.stdout.write('.')\n sys.stdout.flush()\n sleep(1)\n app.db.session.refresh(snapshot)\n print ''\n else:\n print 'Background process missing, doing slow restore.'\n app.inline_slave_copy(snapshot)\n\n app.restore(snapshot)\n print \"Restore complete.\"\n\n\[email protected]()\[email protected]('name')\ndef remove(name):\n \"\"\"Removes a snapshot\"\"\"\n app = Stellar()\n\n snapshot = app.get_snapshot(name)\n if not snapshot:\n print \"Couldn't find snapshot %s\" % name\n sys.exit(1)\n\n print \"Deleting snapshot %s\" % name\n app.remove_snapshot(snapshot)\n print \"Deleted\"\n\n\[email protected]()\[email protected]('old_name')\[email protected]('new_name')\ndef rename(old_name, new_name):\n \"\"\"Renames a snapshot\"\"\"\n app = Stellar()\n\n snapshot = app.get_snapshot(old_name)\n if not snapshot:\n print \"Couldn't find snapshot %s\" % old_name\n sys.exit(1)\n\n new_snapshot = app.get_snapshot(new_name)\n if new_snapshot:\n print \"Snapshot with name %s already exists\" % new_name\n sys.exit(1)\n\n app.rename_snapshot(snapshot, new_name)\n print \"Renamed snapshot %s to %s\" % (old_name, new_name)\n\n\[email protected]()\ndef init():\n \"\"\"Initializes Stellar configuration.\"\"\"\n while True:\n url = click.prompt(\n \"Please enter the url for your database.\\n\\n\"\n \"For example:\\n\"\n \"PostreSQL: postgresql://localhost:5432/\\n\"\n \"MySQL: mysql+pymysql://root@localhost/\"\n )\n if not url.endswith('/'):\n url = url + '/'\n\n engine = create_engine(url, echo=False)\n try:\n conn = engine.connect()\n except OperationalError:\n print \"Could not connect to database: %s\" % url\n print \"Make sure database process is running and try again.\"\n print\n else:\n break\n\n if engine.dialect.name not in SUPPORTED_DIALECTS:\n print \"Your engine dialect %s is not supported.\" % (\n engine.dialect.name\n )\n print \"Supported dialects: %s\" % (\n ', '.join(SUPPORTED_DIALECTS)\n )\n\n while True:\n click.echo(\"You have the following databases: %s\" % ', '.join([\n db for db in list_of_databases(conn)\n if not db.startswith('stellar_')\n ]))\n\n db_name = click.prompt(\n \"Please enter the name of the database (eg. projectdb)\"\n )\n if database_exists(conn, db_name):\n break\n else:\n print \"Could not find database %s\" % db_name\n print\n\n name = click.prompt(\n 'Please enter your project name (used internally, eg. %s)' % db_name,\n default=db_name\n )\n\n with open('stellar.yaml', 'w') as project_file:\n project_file.write(\n \"\"\"\nproject_name: '%(name)s'\ntracked_databases: ['%(db_name)s']\nurl: '%(url)s'\nstellar_url: '%(url)sstellar_data'\n \"\"\".strip() %\n {\n 'name': name,\n 'url': url,\n 'db_name': db_name\n }\n )\n\n print \"Wrote stellar.yaml\"\n print\n if engine.dialect.name == 'mysql':\n print \"Warning: MySQL support is still in beta.\"\n print \"Tip: You probably want to take a snapshot: stellar snapshot\"\n\n\ndef main():\n try:\n stellar()\n except MissingConfig:\n print \"You don't have stellar.yaml configuration yet.\"\n print \"Initialize it by running: stellar init\"\n sys.exit(1)\n except InvalidConfig, e:\n print \"Your stellar.yaml configuration is wrong: %s\" % e.message\n sys.exit(1)\n except ImportError, e:\n libraries = {\n 'psycopg2': 'PostreSQL',\n 'pymysql': 'MySQL',\n }\n for library, name in libraries.items():\n if str(e) == 'No module named %s' % library:\n print \"Python library %s is required for %s support.\" % (\n library,\n name\n )\n print \"You can install it with pip:\"\n print \"pip install %s\" % library\n sys.exit(1)\n raise\n\nif __name__ == '__main__':\n main()\n" } ]
4
elggem/joystick2dynamixel
https://github.com/elggem/joystick2dynamixel
60307aeea1f516bb9adbc263eae85b787d58d14b
0fc76dcc9d2b5caffe9e7eb47ce632298a3983fa
1d8a2b6b07e3dc3d3974b6b5cd7d1a5d650ca759
refs/heads/master
2017-12-20T04:09:42.667486
2016-12-16T04:46:06
2016-12-16T04:46:06
76,534,295
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5581043362617493, "alphanum_fraction": 0.5739853978157043, "avg_line_length": 27.941606521606445, "blob_id": "559a5d094c1d7a553c3bf378bafd568d02c3ffc8", "content_id": "5132c2bcbd0489e8a52e35dfd7a5ffd1f4f4280b", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3967, "license_type": "permissive", "max_line_length": 100, "num_lines": 137, "path": "/joystick2dynamixel.py", "repo_name": "elggem/joystick2dynamixel", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport time\nimport pygame\n\nimport logging as log\nimport numpy as np\n\nfrom retry_decorator import *\nfrom dynamixel_driver import dynamixel_io\n\nclass Joystick2Dynamixel:\n def __init__(self):\n self.dynamixelInterface = '/dev/ttyUSB0'\n\n # Dynamixel Servo IDs\n self.leftMotor = 31\n self.rightMotor = 30\n\n # Joystick Axes\n self.fwdAxis = 1\n self.lrAxis = 0\n\n # What value on Joystick before we start moving\n self.deadzone = 0.1\n # Minimum speed on dynamixels\n self.dynamixelCutoff = 5\n\n # Acceleration\n self.acceleration = 0.05\n\n # Current Velocity\n self.velocity = [0.0,0.0]\n self.dynamixelSpeed = [0,0]\n\n try:\n self.joystick = self.init_joystick()\n self.dynamixel = self.init_dynamixel()\n except Exception as e:\n log.error(e)\n sys.exit(0)\n \n\n @retry(Exception, tries = 5, timeout_secs = 0.5)\n def init_dynamixel(self):\n dynamixel = dynamixel_io.DynamixelIO(self.dynamixelInterface, 1000000)\n\n # wait for servo to connect...\n time.sleep(1.5)\n\n # see if both motors respond\n if (len(dynamixel.ping(self.leftMotor))==0 or len(dynamixel.ping(self.rightMotor))==0) :\n raise Exception('Servo not found...')\n\n return dynamixel\n\n @retry(Exception, tries = 2, timeout_secs = 1.5)\n def init_joystick(self):\n pygame.init()\n\n # Set up the joystick\n pygame.joystick.init()\n\n joystick = None\n joystick_names = []\n\n # Enumerate joysticks\n for i in range(0, pygame.joystick.get_count()):\n joystick_names.append(pygame.joystick.Joystick(i).get_name())\n\n log.info(\"connecting to \" + str(joystick_names))\n\n # By default, load the first available joystick.\n if (len(joystick_names) > 0):\n joystick = pygame.joystick.Joystick(0)\n joystick.init()\n else:\n raise Exception('Joystick not found...')\n\n return joystick\n\n\n def setSpeedLeft(self, speed):\n self.dynamixel.set_speed(self.leftMotor, speed)\n\n def setSpeedRight(self, speed):\n self.dynamixel.set_speed(self.rightMotor, speed)\n\n def calculateDifferentialDrive(self,dirX,dirY):\n if (np.abs(dirX) < self.deadzone):\n dirX = 0\n\n if (np.abs(dirY) < self.deadzone):\n dirY = 0\n\n mag = np.sqrt(np.power(dirX,2) + np.power(dirY,2))\n left = np.maximum(np.minimum(dirX - dirY,1),-1)\n right = np.maximum(np.minimum(dirX + dirY,1),-1)\n\n return [left,right]\n\n def main(self):\n while (True):\n try:\n pygame.event.pump()\n\n dirX = -self.joystick.get_axis(self.fwdAxis)\n dirY = -self.joystick.get_axis(self.lrAxis)\n\n targetVelocity = self.calculateDifferentialDrive(dirX, dirY)\n\n # calculate velocity for each motors\n for i in [0, 1]:\n self.velocity[i] += - (self.velocity[i] - targetVelocity[i]) * self.acceleration\n self.dynamixelSpeed[i] = int(np.floor(self.velocity[i] * 512))\n \n if (np.abs(self.dynamixelSpeed[i]) < self.dynamixelCutoff):\n self.dynamixelSpeed[i] = 0\n\n self.setSpeedLeft(self.dynamixelSpeed[0])\n self.setSpeedRight(-self.dynamixelSpeed[1])\n\n log.info(\"target: \" + str(targetVelocity) + \" actual: \" + str(self.dynamixelSpeed))\n time.sleep(0.1)\n except dynamixel_io.DroppedPacketError:\n log.warning(\"Dropped package to dynamixel motor...\")\n\n\nif __name__ == \"__main__\":\n sys.tracebacklimit = 0\n log.root.setLevel(log.INFO)\n log.info(\"joystick2dynamixel launching...\")\n\n app = Joystick2Dynamixel()\n app.main()\n\n\n" }, { "alpha_fraction": 0.8510638475418091, "alphanum_fraction": 0.8510638475418091, "avg_line_length": 27.399999618530273, "blob_id": "0bc457befe8a19d7eeb73aefb5d66747b4696e3e", "content_id": "6380e180c4cdbc77ffc4111ab9e96defab68434f", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 141, "license_type": "permissive", "max_line_length": 101, "num_lines": 5, "path": "/requirements.txt", "repo_name": "elggem/joystick2dynamixel", "src_encoding": "UTF-8", "text": "retry_decorator\nnumpy\npygame\ncatkin_pkg\ngit+https://github.com/arebgun/dynamixel_motor.git#egg=dynamixel-driver&subdirectory=dynamixel_driver" }, { "alpha_fraction": 0.7496423721313477, "alphanum_fraction": 0.7610872387886047, "avg_line_length": 32.33333206176758, "blob_id": "f419a28d17e5a64d774628a9755a3c241e8ea376", "content_id": "a72887e43187b23dd447be111a1bd9f115064077", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 699, "license_type": "permissive", "max_line_length": 229, "num_lines": 21, "path": "/README.md", "repo_name": "elggem/joystick2dynamixel", "src_encoding": "UTF-8", "text": "# joystick2dynamixel\n\nSimple python scripts to map joystick input to dynamixel servos for movement of robotics platform. Launch script is for internal deployment to Raspberry Pi.\n\n## Install\n\n pip install -r requirements.txt\n\n## Run\n\n python joystick2dynamixel.py\n\n## Deployment to Raspberry Pi\n\n### Daemon mode\n\nThis could be done nicely as a service but for our purposes we're just gonna put `launch.sh` in `.bashrc`. This assumes Raspberry Pi is setup for readonly mode according to [this guide](http://hallard.me/raspberry-pi-read-only/).\n\n### To pair Sony PS3 navigation controller\n\nSee [this guide](https://www.piborg.org/rpi-ps3-help) but modify code to reflect the product id `0x042f`." }, { "alpha_fraction": 0.6937500238418579, "alphanum_fraction": 0.7093750238418579, "avg_line_length": 23.69230842590332, "blob_id": "80d5d11644de875f3c3e3fae60ab9d7a3e6210d3", "content_id": "4221c80b8fc90108e317845f237650c03c39151c", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 320, "license_type": "permissive", "max_line_length": 85, "num_lines": 13, "path": "/launch.sh", "repo_name": "elggem/joystick2dynamixel", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd \"$(dirname \"$0\")\"\n\n# update from git repo\n# this assumes RO raspberry pi according to http://hallard.me/raspberry-pi-read-only/\nsudo mount -o remount,rw /\nsleep 8\ngit pull\nsudo mount -o remount,ro /\n\n# execute script indefinately\nwhile [ 1 ]; do python joystick2dynamixel.py; test $? -gt 0 && break; done" } ]
4
anba8005/nsfw-service
https://github.com/anba8005/nsfw-service
7d3a10b253a5bfd21c6a92b2429b8504287b0ec1
6cfa29ddebdeb254efe4658b8b7e871682655edf
3ea85cf1c94f7d648bb66aeb36948182b65b0e0e
refs/heads/master
2020-03-25T15:56:13.570661
2018-08-07T18:02:23
2018-08-07T18:02:23
143,907,654
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5992890000343323, "alphanum_fraction": 0.607414960861206, "avg_line_length": 31.278688430786133, "blob_id": "ede3f91be5535e6ce3421d3726246569b7c2359c", "content_id": "7d0344673fd9367e3801b25cce70b61c39db09fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1969, "license_type": "no_license", "max_line_length": 95, "num_lines": 61, "path": "/service.py", "repo_name": "anba8005/nsfw-service", "src_encoding": "UTF-8", "text": "import PIL.Image as Image\nfrom nsfw import classify\n\nimport os\nfrom flask import Flask, flash, request, redirect, url_for, render_template\nfrom werkzeug.utils import secure_filename\n\nfrom datetime import datetime\n\nUPLOAD_FOLDER = '/tmp'\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 64 * 1024 * 1024\napp.secret_key = b'_5#y2L\"F4Q8z\\n\\xec]/'\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\ndef analyze_file(filename):\n image = Image.open(filename)\n sfw, nsfw = classify(image)\n return nsfw\n\[email protected]('/', methods=['GET', 'POST'])\ndef upload_file():\n #\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit an empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n # all good in da hood :)\n filename = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(file.filename))\n file.save(filename)\n start = datetime.now()\n nsfw = analyze_file(filename)\n end = datetime.now()\n os.remove(filename)\n if nsfw >= 0.6:\n flash('NUDITY detected (NSFW >= 0.6)')\n flash(\"NSFW Probability: {}\".format(nsfw))\n flash(\"Processing time {} seconds\".format((end-start).total_seconds()))\n return redirect(request.url)\n else:\n flash('Invalid file type')\n return redirect(request.url)\n #\n return render_template('index.html')\n\nif __name__ == '__main__':\n app.run()\n" } ]
1
lhleonardo/ufla-ia-knn
https://github.com/lhleonardo/ufla-ia-knn
b1fb393f0e2f60997bea6ea5eecbd55cc25941a4
586f4d47f028b98bbb303cf724c2e6c75c53d0fe
17c6cfdda07eede4ec35515de2034d5486142b13
refs/heads/master
2022-12-07T09:59:20.013756
2020-08-29T16:05:23
2020-08-29T16:05:23
291,303,616
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.573782742023468, "alphanum_fraction": 0.5775281190872192, "avg_line_length": 27.404254913330078, "blob_id": "2f578c7c0578d9a6fc180f97b1d51ac7debe02e5", "content_id": "06c9a0ea895932962440f544de6bea25c43c2792", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 78, "num_lines": 47, "path": "/src/knn.py", "repo_name": "lhleonardo/ufla-ia-knn", "src_encoding": "UTF-8", "text": "class Instance:\n def __init__(self, params, category):\n self.params = params\n self.category = category\n\n def distance(self, another):\n result = 0\n for i in range(len(self.params)):\n result += (self.params[i] - another.params[i]) ** 2\n\n return result\n\n\nclass Knn:\n def __init__(self, data):\n self.data = data\n\n def __distance(self, unknown):\n neighbours = []\n\n for element in self.data:\n neighbours.append((element, element.distance(unknown)))\n\n return sorted(neighbours, key=lambda element: element[1])\n\n def predict(self, unkown, k):\n\n # Cria a matriz de k vizinhos mais proximos\n neighbours = self.__distance(unkown)\n\n category_count = {}\n for i in range(k):\n instance, _ = neighbours[i]\n if instance.category in category_count:\n category_count[instance.category] += 1\n else:\n category_count[instance.category] = 1\n\n possible_category = None\n\n for category in category_count.keys():\n if possible_category is None:\n possible_category = category\n elif category_count[category] > category_count[possible_category]:\n possible_category = category\n\n return possible_category\n" }, { "alpha_fraction": 0.5886396765708923, "alphanum_fraction": 0.6671490669250488, "avg_line_length": 35.355262756347656, "blob_id": "438ca81ecbae634b680956e793dae7d027c8ef80", "content_id": "e742c098b746bbbf285bbb52d9129c422810a6b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2838, "license_type": "no_license", "max_line_length": 350, "num_lines": 76, "path": "/README.md", "repo_name": "lhleonardo/ufla-ia-knn", "src_encoding": "UTF-8", "text": "# KNN - Implementação\n\n## Introdução\n\nImplementação do algoritmo KNN para classificação aplicado à técnicas de Inteligência Artificial, sob orientação do Prof. Dr. Ahmed Ali Abdalla Esmin.\n\nOs arquivos principais da execução do código estão presentes na pasta `src`, sendo definidos como:\n\n- `main.py`: contém a execução principal do programa, contendo o intervalo de valores _k_ que serão utilizados na execução e o arquivo que será usado para análise;\n- `knn.py`: contém a implementação do KNN e todas as operações necessárias para realização do processo;\n- `analytics.py`: contém todo processo de análise da corretude das predições realizadas pelo KNN, construindo a matriz de confusão e verificação de acurrácia para as predições;\n\n## Formato de apresentação\n\nPara sua execução é necessário apenas o comando:\n\n```\npython3 main.py\n```\n\nO formato de saída da aplicação é dado por:\n\n```\nNUMERO_K\nMATRIZ_CONFUSAO\n\nACURACIA_ACERTOS\nACURACIA_FALHAS\n```\n\nUma execução para o spambase é definida logo abaixo:\n\n```\nk=1\n[[265 70]\n [101 493]]\n81.59311087190528\n18.40688912809472\n\nk=3\n[[272 72]\n [ 89 471]]\n82.19026548672566\n17.809734513274336\n\nk=5\n[[293 72]\n [ 83 454]]\n82.8159645232816\n17.184035476718407\n\nk=7\n[[256 93]\n [110 471]]\n78.17204301075269\n21.827956989247312\n```\n\n## Resultados e análises\n\n### Spambase\n\nPara a base de dados spamBase foi demonstrado uma melhor acurácia para valores de k mais baixos como 1, porém essa taxa pode variar uma vez que os dados de teste e treinamento estão sendo escolhidos de forma randômica.\n\n### IrisBase\n\nPara a base de dados irisBase foi demonstrado uma melhor acurácia para valores de k mais altos como 5 e 7, porém assim como na spamBase os dados de teste e treinamento também estão sendo escolhidos de forma randômica podendo ocorrer variâncias na acurácia para determinado k.\n\nPode-se observar que o KNN é um algoritmo simples e bastante eficaz, demonstrando uma boa precisão na maioria dos casos aplicados.\n\n## Autores\n\nRepositório criado com intuito em obtenção de nota para o trabalho final de Inteligência Artificial. Turma ministrada em 2020/1.\n\n| [<img src=\"https://avatars0.githubusercontent.com/u/11544276?v=4&s=450\" width=115><br><sub>@lhleonardo</sub>](https://github.com/lhleonardo) <br><sub>Leonardo Braz</sub> | [<img src=\"https://avatars0.githubusercontent.com/u/37846911?s=460&v=4\" width=115><br><sub>@gbochikubo</sub>](https://github.com/gbochikubo) <br><sub>Guilherme Ochikubo</sub> |\n| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |\n\n" }, { "alpha_fraction": 0.6547231078147888, "alphanum_fraction": 0.6677524447441101, "avg_line_length": 19.46666717529297, "blob_id": "6e0387a39749febf51cd3c1d5a5a64150bf954d3", "content_id": "7476e1cc1f64cb3d12b6082b10cc8eaef0ed27ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/src/main.py", "repo_name": "lhleonardo/ufla-ia-knn", "src_encoding": "UTF-8", "text": "import numpy as np\n\nfrom analytics import analyze\n\nk_range = [1, 3, 5, 7]\n\nfilepath = \"spambase/spambase.data\"\n\nfor k in k_range:\n matrix, hit_accurency, fault_accurency = analyze(k, filepath)\n print(\"k=\", k)\n print(np.array(matrix))\n print(hit_accurency)\n print(fault_accurency)\n print()\n" }, { "alpha_fraction": 0.6244519948959351, "alphanum_fraction": 0.6312713027000427, "avg_line_length": 24.987340927124023, "blob_id": "5835fd932d7ec3e288a1db802d1d1a478c33ffa6", "content_id": "9d77b14d24569f9d90797470b13e69c2c8352724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2053, "license_type": "no_license", "max_line_length": 74, "num_lines": 79, "path": "/src/analytics.py", "repo_name": "lhleonardo/ufla-ia-knn", "src_encoding": "UTF-8", "text": "from knn import Instance\nfrom knn import Knn\n\nimport csv\nimport random\n\n\ndef ReadFile(filename):\n # Monta a matriz de dados\n dataset = []\n file = csv.reader(open(filename, \"r\"))\n\n categories = []\n\n for row in file:\n category = row[-1]\n if len(row) != 0:\n params = []\n for i in range(len(row)-1):\n params.append(float(row[i]))\n instance = Instance(params=params, category=category)\n dataset.append(instance)\n\n if not category in categories:\n categories.append(category)\n\n return (dataset, categories)\n\n\ndef GenerateCustomDataset(filepath, percentage=0.2):\n dataset, categories = ReadFile(filepath)\n test_data = []\n training_data = []\n # Constroi a base de dados:\n for instance in dataset:\n if random.random() < percentage:\n test_data.append(instance)\n else:\n training_data.append(instance)\n\n return (test_data, training_data, categories)\n\n\ndef __accuracy(matrix, length):\n correct_predict_count = 0\n\n for index in range(len(matrix)):\n correct_predict_count += matrix[index][index]\n\n correct_accuracy = (correct_predict_count*100) / length\n fault_accurency = 100 - correct_accuracy\n\n return (correct_accuracy, fault_accurency)\n\n\ndef analyze(k, filepath):\n test_data, training_data, categories = GenerateCustomDataset(\n filepath=filepath)\n\n predicted_data = []\n\n knn = Knn(training_data)\n\n matrix = [[0 for i in range(len(categories))]\n for i in range(len(categories))]\n\n for instance in test_data:\n result = knn.predict(instance, k)\n\n result_index = categories.index(result)\n category_index = categories.index(instance.category)\n\n matrix[result_index][category_index] += 1\n\n predicted_data.append(\n Instance(params=instance.params, category=result))\n\n correct_accuracy, fault_accurency = __accuracy(matrix, len(test_data))\n return (matrix, correct_accuracy, fault_accurency)\n" } ]
4
narlaraj/Games-Development
https://github.com/narlaraj/Games-Development
136e7a96f79f58819d5b794342e36e1390501a75
10fd5fc8cb5551dd33ddff5ad5328ca681b10889
77a73834e3ba61e4d1914e006f44bd7558e9b55e
refs/heads/master
2022-07-31T20:51:58.405561
2020-05-15T07:14:29
2020-05-15T07:14:29
264,120,174
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5538555979728699, "alphanum_fraction": 0.5764994025230408, "avg_line_length": 16.02083396911621, "blob_id": "36eec5f7852e64c3038f0213fc995a2f516e3918", "content_id": "0cfa4f730c61efcf1d71c9c0c5ea1a2d17769a58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3268, "license_type": "no_license", "max_line_length": 84, "num_lines": 192, "path": "/Test.py", "repo_name": "narlaraj/Games-Development", "src_encoding": "UTF-8", "text": "\"\"\"\ncities=['Hyderabad','Amaravathi','Trivandrum','Chennai','Mumbai','Ahmedabad']\n\n#Bad Way\nprint('Bad Way')\ni=0\nfor city in cities:\n\tprint(i,city)\n\ti+=1\n\n#Good Way\nprint('Good Way')\nfor (i,city) in enumerate(cities):\n print(i,city)\n\nx_list = [1, 2, 3]\ny_list = [5, 6, 7]\n\n# Bad Way\nprint('Bad Way')\nfor i in range(len(x_list)):\n x = x_list[i]\n y = y_list[i]\n print(x, y)\n\n# Good Way\nprint('Good Way')\nfor (x, y) in zip(x_list, y_list):\n print(x, y)\n\nx=10\ny=20\nprint(f'Before Swap x={x},y={y}')\n\n#Bad Way\ntmp=x\nx=y\ny=tmp\nprint(f'After Swap x={x},y={y}')\n\n#Good Way\n\nx,y=y,x\nprint(f'After Swap x={x},y={y}')\n\n\nages = {\n 'Kiran': 34,\n 'Kishore': 45,\n 'Hari': 34,\n 'Praveen':30\n}\n\n# Bad Way\nprint('Bad Way')\nif 'Praveen' in ages:\n age = ages['Praveen']\nelse:\n age = 'Unknown'\n\nprint(f'Praveen is {age} years old')\n\n# Good Way\nprint('Good Way')\n\nage = ages.get('Praveen','Unknown')\nprint(f'Praveen is {age} years old')\n\n\nneedle = 'd'\nhaystick = ['a', 'b', 'c','d']\nfound = False\n# Bad Way\nprint('Bad Way')\nfor item in haystick:\n if item == needle:\n print('Found')\n found = True\n break\nif not found:\n print('Not Found')\n\n# Good Way\nprint('Good Way')\nfor item in haystick:\n if item == needle:\n print('Found')\n break\nelse: # if no break statement occured\n print('Not Found')\n\n###############\nprint('Converting')\n\ntry:\n\tprint(int('1'))\nexcept:\n\tprint('Conversion failed')\nelse:\n\tprint('Conversion Successful')\nfinally:\n\tprint('Done!!!')\n\n###################\ncondition=True\n\nif condition:\n x=1\nelse:\n x=0\n\nprint(f'X={x}')\n\nprint('Better:')\nx=1 if condition else 0\nprint(f'X={x}')\n\n\nname_list=['Kiran','Kishore','Ramesh']\nage_list=[30,23,34]\nsal_list=[30000,400000,500000]\n\nfor val in zip(name_list,age_list,sal_list):\n\tprint(val)\n\n\n# Coconuts problem\nbag_content=int(input(\"Enter the number of coconuts per bag:\"))\ntot_coc=bag_content*bag_content\ntoll=bag_content\nwhile toll>=0:\n\ttot_bags=int(tot_coc//bag_content)\n\textra=tot_coc%bag_content\n\ttoll_paid=tot_bags\n\tif(extra>0):\n\t\ttoll_paid += 1\n\n\tprint(f'Toll#{toll} Total Bags : {tot_bags} Extra:{extra} Toll Paid:{toll_paid} ')\n\ttot_coc=tot_coc-(tot_bags)\n\tif(extra>0):\n\t\ttot_coc-=1\n\ttoll-=1\n\n\n\ndef find_next_priosoner(priosoners, nxtPrsnr, step, tprsn):\n cnt = step\n while cnt > 1:\n while (priosoners[nxtPrsnr] == '-'):\n nxtPrsnr += 1\n if (nxtPrsnr == tprsn):\n nxtPrsnr = 0\n cnt -= 1\n nxtPrsnr += 1\n return (nxtPrsnr)\n\n\n\n if (priosoners[nxtPrsnr] == '-'):\n nxtPrsnr += 1\n else:\n cnt -= 1\n nxtPrsnr += 1\n if nxtPrsnr == tprsn:\n nxtPrsnr = 0\n\n return (nxtPrsnr)\n\n\n\ndef who_goes_free(nop, step):\n priosoners = list(range(0, nop))\n nxtPrsnr = 0\n tprsn = nop\n while nop > 1:\n nxtPrsnr = find_next_priosoner(priosoners, nxtPrsnr, step, tprsn)\n print(f\"Round:{nop}# Kill{priosoners[nxtPrsnr]}@{nxtPrsnr}\")\n priosoners[nxtPrsnr] = '-'\n\n nop -= 1\n for item in priosoners:\n if item != '-':\n break\n print(f\"Result: {item}@{priosoners.index(item)}\")\n\n\n# who_goes_free(9,2)\n# who_goes_free(9,3)\n\"\"\"\n\nif __name__ == '__main__':\n who_goes_free(16, 3)\n" }, { "alpha_fraction": 0.7349397540092468, "alphanum_fraction": 0.7349397540092468, "avg_line_length": 19.75, "blob_id": "e20bbf40c1b27ad0280e3176c1fde9621d249313", "content_id": "a7323f2c42bba78f2f8353ec7f57080ef0d74919", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 49, "num_lines": 8, "path": "/Test1.py", "repo_name": "narlaraj/Games-Development", "src_encoding": "UTF-8", "text": "import re\nNameAge='''\nWe need to inform him with the latest information\n'''\nregex=re.compile(\"inform\")\nNameAge=regex.sub(\"Food\",NameAge)\n\nprint(f\"NameAge:{NameAge}\")\n" }, { "alpha_fraction": 0.49309664964675903, "alphanum_fraction": 0.5049309730529785, "avg_line_length": 18.753246307373047, "blob_id": "ec9eafee35ea5e5589c9c9d3a13efb32a623d331", "content_id": "6ab488d5500760ec1452038ba4893dd10cc7f837", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1521, "license_type": "no_license", "max_line_length": 56, "num_lines": 77, "path": "/hangman.py", "repo_name": "narlaraj/Games-Development", "src_encoding": "UTF-8", "text": "from random import randint\nimport linecache\n\nprocessed = []\ntext = \"\"\nguess = \"\"\n\n\n# replace_char(3,'K')s\n# --> abc K edf\n\ndef replace_char(pos, ch):\n global guess\n guess = guess[:pos] + ch + guess[pos + 1:]\n\n\ndef find_and_replace(ch):\n global text\n found = False\n for i in range(len(text)):\n if text[i] == ch:\n replace_char(i, ch)\n found = True\n return found\n\n\ndef init_word(pos):\n global text\n global guess\n\n text = linecache.getline('hangman.txt', pos)\n text = text[:-1]\n guess = '_' * len(text)\n\n\ndef guess_word():\n global text\n global guess\n cnt = 0\n while cnt < 7 and text != guess:\n print(f\"Guess : {guess}\")\n gs = input('Enter the guess character')\n rs = find_and_replace(gs)\n if rs == False:\n cnt += 1\n\n if text != guess:\n return False\n else:\n return True\n\n\ndef main():\n count = 1\n while True:\n rint = randint(0, 50 - 1)\n while rint in processed:\n rint = randint(0, 50 - 1)\n processed.append(rint)\n init_word(rint)\n res = guess_word()\n if res == True:\n print(f\"Guess : {guess}\")\n count += 1\n else:\n print(\"Sorry time up\")\n print(f\"The wor is : {text}\")\n\n if count == 5:\n print('You won 5 times, Congratulations!!!')\n break\n cont = input(\"Want to play again(y/n)?\")\n if (cont == 'n' or cont == 'N'):\n break\n\n\nmain()\n" }, { "alpha_fraction": 0.4490121901035309, "alphanum_fraction": 0.4973852336406708, "avg_line_length": 26.20948600769043, "blob_id": "6fa05d82e9c3ce9b30d229df232b8dd0ea25c75d", "content_id": "aca7e3bd19b14b13add4c03a4965bae6dc8475ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6884, "license_type": "no_license", "max_line_length": 117, "num_lines": 253, "path": "/tictactoe.py", "repo_name": "narlaraj/Games-Development", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom tkinter import messagebox\n\nwindow = Tk()\n\nwindow.title(\"Tic-tac-toe - Rajashekar Narla\")\nwindow.geometry(\"500x300\")\n\nxscr = 0\noscr = 0\ntie = 0\n\nlbl = Label(window, text=f\"Overall Result : N/A \", font=('Helvetica', '15'))\nlbl.grid(row=0, column=0)\n\nlbl1 = Label(window, text=\" Last Won: N/A\", font=('Helvetica', '10'))\nlbl1.grid(row=1, column=4)\n\nlbl2 = Label(window, text=f\" Score : X={xscr}\\n O={oscr}\\n Tie={tie}\", anchor='w',\n font=('Helvetica', '10'))\nlbl2.grid(row=2, column=4)\n\nlbl3 = Label(window, text=\"Player 1: X\", font=('Helvetica', '10'))\nlbl3.grid(row=1, column=0)\nlbl4 = Label(window, text=\"Player 2: O\", font=('Helvetica', '10'))\nlbl4.grid(row=2, column=0)\n\nturn = 1 # For first person turn.\nis_disable = False\n\n\ndef clicked1():\n global turn\n if btn1[\"text\"] == \" \": # For getting the text of a button\n if turn == 1:\n turn = 2\n btn1[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn1[\"text\"] = \"O\"\n check()\n\n\ndef clicked2():\n global turn\n if btn2[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn2[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn2[\"text\"] = \"O\"\n check()\n\n\ndef clicked3():\n global turn\n if btn3[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn3[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn3[\"text\"] = \"O\"\n check()\n\n\ndef clicked4():\n global turn\n if btn4[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn4[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn4[\"text\"] = \"O\"\n check()\n\n\ndef clicked5():\n global turn\n if btn5[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn5[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn5[\"text\"] = \"O\"\n check()\n\n\ndef clicked6():\n global turn\n if btn6[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn6[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn6[\"text\"] = \"O\"\n check()\n\n\ndef clicked7():\n global turn\n if btn7[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn7[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn7[\"text\"] = \"O\"\n check()\n\n\ndef clicked8():\n global turn\n if btn8[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn8[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn8[\"text\"] = \"O\"\n check()\n\n\ndef clicked9():\n global turn\n if btn9[\"text\"] == \" \":\n if turn == 1:\n turn = 2\n btn9[\"text\"] = \"X\"\n elif turn == 2:\n turn = 1\n btn9[\"text\"] = \"O\"\n check()\n\n\nflag = 1\n\n\ndef check():\n global flag\n global tie\n\n restart[\"state\"] = DISABLED\n b1 = btn1[\"text\"]\n b2 = btn2[\"text\"]\n b3 = btn3[\"text\"]\n b4 = btn4[\"text\"]\n b5 = btn5[\"text\"]\n b6 = btn6[\"text\"]\n b7 = btn7[\"text\"]\n b8 = btn8[\"text\"]\n b9 = btn9[\"text\"]\n flag = flag + 1\n if b1 == b2 and b1 == b3 and b1 == \"O\" or b1 == b2 and b1 == b3 and b1 == \"X\":\n win(btn1[\"text\"])\n if b4 == b5 and b4 == b6 and b4 == \"O\" or b4 == b5 and b4 == b6 and b4 == \"X\":\n win(btn4[\"text\"])\n if b7 == b8 and b7 == b9 and b7 == \"O\" or b7 == b8 and b7 == b9 and b7 == \"X\":\n win(btn7[\"text\"])\n if b1 == b4 and b1 == b7 and b1 == \"O\" or b1 == b4 and b1 == b7 and b1 == \"X\":\n win(btn1[\"text\"])\n if b2 == b5 and b2 == b8 and b2 == \"O\" or b2 == b5 and b2 == b8 and b2 == \"X\":\n win(btn2[\"text\"])\n if b3 == b6 and b3 == b9 and b3 == \"O\" or b3 == b6 and b3 == b9 and b3 == \"X\":\n win(btn3[\"text\"])\n if b1 == b5 and b1 == b9 and b1 == \"O\" or b1 == b5 and b1 == b9 and b1 == \"X\":\n win(btn1[\"text\"])\n if b7 == b5 and b7 == b3 and b7 == \"O\" or b7 == b5 and b7 == b3 and b7 == \"X\":\n win(btn7[\"text\"])\n if flag == 10:\n messagebox.showinfo(\"Tie\", \"Match Tied!!! Try again :)\")\n restart[\"state\"] = NORMAL\n tie += 1\n lbl1[\"text\"] = \" Last Result: Tie\"\n lbl2[\"text\"] = f\" Score : X={xscr}\\n O={oscr}\\n Tie={tie}\"\n\n\ndef win(player):\n global xscr\n global oscr\n global tie\n\n if player == 'X':\n xscr += 1\n else:\n oscr += 1\n if xscr > oscr:\n lbl[\"text\"] = f\"Overall Result : X WON \"\n elif oscr > xscr:\n lbl[\"text\"] = f\"Overall Result : O WON \"\n else:\n lbl[\"text\"] = f\"Overall Result : TIE \"\n\n ans = \"Game complete \" + player + \" wins \"\n lbl1[\"text\"] = \" Last Result: \" + player + \" Won\"\n lbl2[\"text\"] = f\" Score : X={xscr}\\n O={oscr}\\n Tie={tie}\"\n restart[\"state\"] = NORMAL\n messagebox.showinfo(\"Congratulations\", ans)\n\n\n# window.destroy() # is used to close the program\n\ndef restart_game():\n global turn\n global flag\n\n btn1[\"text\"] = \" \"\n btn2[\"text\"] = \" \"\n btn3[\"text\"] = \" \"\n btn4[\"text\"] = \" \"\n btn5[\"text\"] = \" \"\n btn6[\"text\"] = \" \"\n btn7[\"text\"] = \" \"\n btn8[\"text\"] = \" \"\n btn9[\"text\"] = \" \"\n turn = 1\n flag = 1\n\n\ndef exit_game():\n window.destroy()\n\n\nbtn1 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked1)\nbtn1.grid(column=1, row=1)\nbtn2 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked2)\nbtn2.grid(column=2, row=1)\nbtn3 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked3)\nbtn3.grid(column=3, row=1)\nbtn4 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked4)\nbtn4.grid(column=1, row=2)\nbtn5 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked5)\nbtn5.grid(column=2, row=2)\nbtn6 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked6)\nbtn6.grid(column=3, row=2)\nbtn7 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked7)\nbtn7.grid(column=1, row=3)\nbtn8 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked8)\nbtn8.grid(column=2, row=3)\nbtn9 = Button(window, text=\" \", bg=\"Blue\", fg=\"White\", width=3, height=1, font=('Helvetica', '20'), command=clicked9)\nbtn9.grid(column=3, row=3)\n\nrestart = Button(window, text=\"Restart\", width=6, height=1, font=('Helvetica', '10'), command=restart_game)\nrestart.grid(column=1, row=5)\n\nexit = Button(window, text=\"Exit\", width=6, height=1, font=('Helvetica', '10'), command=exit_game)\nexit.grid(column=2, row=5)\n\nwindow.mainloop()\n" } ]
4
Saftfresse/ArduinoCoffeCup
https://github.com/Saftfresse/ArduinoCoffeCup
d9ac2b6fb796ec5f3a0483688e8288e5e5d71998
45ce934e4f3df6ae001111c1a5ef08f2976850ed
6cc403c0199bba62510ccdc10efd7a5af692bcf3
refs/heads/master
2020-11-23T21:09:14.393897
2019-12-19T12:22:50
2019-12-19T12:22:50
227,821,355
0
0
null
2019-12-13T11:07:46
2019-12-19T12:22:53
2020-01-28T07:16:48
C++
[ { "alpha_fraction": 0.7933333516120911, "alphanum_fraction": 0.8133333325386047, "avg_line_length": 49, "blob_id": "0bae4ab020b26974fbf65ebfe94426563f1f398c", "content_id": "17a1421151f465ad0d8ddab676e22a183af3d577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 152, "license_type": "no_license", "max_line_length": 124, "num_lines": 3, "path": "/README.md", "repo_name": "Saftfresse/ArduinoCoffeCup", "src_encoding": "UTF-8", "text": "# Kaffeebecher Projekt\n\nFüllstandsmesser für Kaffeebecher mit HC-SR04 laufend auf einem Raspberry Pi 3b der die Daten an das SAP IoT backend sendet.\n" }, { "alpha_fraction": 0.6131474375724792, "alphanum_fraction": 0.647011935710907, "avg_line_length": 22.457944869995117, "blob_id": "49ff0677d6b2abb481e0406c9d8f1bdeadae5627", "content_id": "7f64e1e957cff1ce0d69d95506772152e5eaa476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2510, "license_type": "no_license", "max_line_length": 96, "num_lines": 107, "path": "/sketch_dec09a/sketch_dec09a.ino", "repo_name": "Saftfresse/ArduinoCoffeCup", "src_encoding": "UTF-8", "text": "#include <ESP8266WiFi.h>\n#include <ESP8266HTTPClient.h>\n\nconst char* ssid = \"SY-Digitalisierung\"; \nconst char* password = \"FullDigitality19\"; \n\nconst int trigPin =12 ; //D4\nconst int echoPin = 14; //D3\n\nconst int cupHeight = 10;\nconst int deadZone = 2;\n\nlong duration;\nint distance;\nfloat distanceF;\n\nint lastdist = 0;\nfloat lastdistF = 0;\n\nint buttonState = 0; // variable for reading the pushbutton status\n\nvoid setup() {\n Serial.begin(9600); // Start the Serial communication to send messages to the computer\n delay(10);\n Serial.println('\\n');\n\n pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output\n pinMode(echoPin, INPUT); // Sets the echoPin as an Input\n\n pinMode(16, OUTPUT);\n pinMode(5, OUTPUT);\n pinMode(4, OUTPUT);\n pinMode(0, OUTPUT);\n pinMode(2, INPUT);\n \n WiFi.mode(WIFI_OFF);\n delay(1000);\n WiFi.mode(WIFI_STA);\n \n WiFi.begin(ssid, password); // Connect to the network\n Serial.print(\"Connecting to \");\n Serial.print(ssid); Serial.println(\" ...\");\n\n int i = 0;\n while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect\n delay(1000);\n Serial.print(++i); Serial.print(' ');\n }\n\n Serial.println('\\n');\n Serial.println(\"Connection established!\"); \n Serial.print(\"IP address:\\t\");\n Serial.println(WiFi.localIP());\n}\n\nvoid loop() {\n // Clears the trigPin\n digitalWrite(trigPin, LOW);\n delayMicroseconds(2);\n \n // Sets the trigPin on HIGH state for 10 micro seconds\n digitalWrite(trigPin, HIGH);\n delayMicroseconds(10);\n digitalWrite(trigPin, LOW);\n \n // Reads the echoPin, returns the sound wave travel time in microseconds\n duration = pulseIn(echoPin, HIGH);\n \n // Calculating the distance\n distance= duration*0.034/2;\n distanceF= duration*0.034/2;\n // Prints the distance on the Serial Monitor\n if(distanceF != lastdistF){\n Serial.print(\"Distance: \");\n //Serial.println(distance);\n Serial.println(distanceF);\n lastdistF = distanceF;\n Serial.println((distanceF - deadZone) / (cupHeight - deadZone));\n }\n delay(500);\n\n\n \n buttonState = digitalRead(2);\n\n if (buttonState == HIGH) {\n // turn LED on:\n digitalWrite(0, HIGH);\n delay(50);\n digitalWrite(16, HIGH);\n delay(50);\n digitalWrite(5, HIGH);\n delay(50);\n digitalWrite(4, HIGH);\n delay(50);\n digitalWrite(0, LOW);\n delay(50);\n digitalWrite(16, LOW);\n delay(50);\n digitalWrite(5, LOW);\n delay(50);\n digitalWrite(4, LOW);\n } else {\n // turn LED off:\n digitalWrite(0, LOW);\n }\n}\n" }, { "alpha_fraction": 0.600850522518158, "alphanum_fraction": 0.64702308177948, "avg_line_length": 20.102563858032227, "blob_id": "9f51efc7da3649f0c4f2d6cdcf1750213c0e6d5b", "content_id": "41225277c68a26904d1905ea9a418103a6bcdb2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 111, "num_lines": 78, "path": "/Raspbian/sensor.py", "repo_name": "Saftfresse/ArduinoCoffeCup", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\nimport json\nimport requests\nimport statistics\n\nGPIO.setmode(GPIO.BCM)\n\nGPIO_TRIGGER = 18\nGPIO_ECHO = 24\n\nGPIO.setup(GPIO_TRIGGER, GPIO.OUT)\nGPIO.setup(GPIO_ECHO, GPIO.IN)\n\nurl = \"https://d8eee94a-276c-461a-8a65-0135cc38a058.eu10.cp.iot.sap/iot/gateway/rest/measures/device\"\n\ncupHeight = 10.3\nsensorDeadZone = 3\nlastLevel = 0.0\n\ninterrupt = 0.5\n\nlastVals = []\n\n\ndef distance():\n\tGPIO.output(GPIO_TRIGGER, True)\n\t\n\ttime.sleep(0.00001)\n\tGPIO.output(GPIO_TRIGGER, False)\n\t\n\tStartTime = time.time()\n\tStopTime = time.time()\n\t\n\twhile GPIO.input(GPIO_ECHO) == 0:\n\t\tStartTime = time.time()\n\t\n\twhile GPIO.input(GPIO_ECHO) == 1:\n\t\tStopTime = time.time()\n\t\n\tTimeElapsed = StopTime - StartTime\n\t\n\tdist = (TimeElapsed * 34300) / 2\n\t\n\treturn float(\"{0:.2f}\".format(dist))\n\nif __name__ == '__main__':\n\ttry:\n\t\twhile True:\n\t\t\tlevel = 100 - float(\"{0:.2f}\".format(((distance() - sensorDeadZone) / (cupHeight - sensorDeadZone)) * 100))\n\t\t\tif (level > 100): \n\t\t\t\tlevel = 100\n\t\t\t\tinterrupt = 2\n\t\t\telif (level < 0):\n\t\t\t\tlevel = 0\n\t\t\telse:\n\t\t\t\tinterrupt = 0.5\n\n\t\t\tif (len(lastVals) < 3):\n\t\t\t\tlastVals.append(level)\n\t\t\telse:\n\t\t\t\tlastVals.pop(0)\n\t\t\t\tlastVals.append(level)\n\t\t\tavgLevel = float(\"{0:.2f}\".format(statistics.mean(lastVals)))\n\n\t\t\tif(level != lastLevel):\n\t\t\t\t\n\t\t\t\tprint(level)\n\t\t\t\tpayload = { \"capabilityAlternateId\" : \"cap1\" , \"measures\" : [[ avgLevel ]], \"sensorAlternateId\":\"sensor1\" }\n\t\t\t\tr = requests.post(url, \n\t\t\t\t\tauth=('greinert', 'zYIDmXduZWB5ExN8unGX'), \n\t\t\t\t\tjson=payload,\n\t\t\t\t\tcert=('client.crt', 'client.key'))\n\t\t\t\tlastLevel = level\n\t\t\ttime.sleep(interrupt)\n\texcept KeyboardInterrupt:\n\t\tprint(\"Cancelling\")\n\t\tGPIO.cleanup()\n" } ]
3
msaisushma/Github-API
https://github.com/msaisushma/Github-API
bd90c5e2da6c07f839ba212beaa4eeecf5aa13a0
326491d9cb4dffd1013dae620d1ba274c414107b
27ea43edeff1da64340d6652ed9171639b5751ae
refs/heads/master
2021-01-22T07:27:20.093076
2014-06-20T12:01:03
2014-06-20T12:01:03
21,036,156
1
3
null
null
null
null
null
[ { "alpha_fraction": 0.6278586387634277, "alphanum_fraction": 0.6798336505889893, "avg_line_length": 19.04166603088379, "blob_id": "e5bcd96301392a3144af6cf19ad187f2b8cb360d", "content_id": "6f60e626e9a3c059ac5e6e5262b41024d672fcc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 57, "num_lines": 24, "path": "/pyapi.py", "repo_name": "msaisushma/Github-API", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\nAccess_token = 'b0e86264e1b3dfb6d8f93c84eda09c2e42c82017'\napi_url = \"https://api.github.com/users\"\n\n\ndef get_comments():\n\tusrname = raw_input(\"Enter the username:\")\n\turl = api_url+usrname+\"/events\"\n\treq = requests.get(url)\n\tres = req.content\n\t# print res\n\tresp = json.loads(res)\n\n\tpload = [li['payload']for li in resp]\n\tpayload = pload[3]\n\t# print payload\n\n\tfor k,v in payload.items():\n\t\tprint v['html_url']\n\nif __name__ == '__main__':\n\tget_comments()\n" } ]
1
shanexia1818/face_comparison
https://github.com/shanexia1818/face_comparison
5955b712cd7d4e528511cf52ba87a06cc231a2cd
90bed24407e252ed997e07b688ea602384e230f6
a53b66daabe2bb3f922beb133bcfb83723eeec7d
refs/heads/master
2020-08-20T05:41:53.274831
2019-09-20T07:29:24
2019-09-20T07:29:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.669741690158844, "alphanum_fraction": 0.6734317541122437, "avg_line_length": 21.58333396911621, "blob_id": "028980a3e3b271e27ce4bf84541746221ed45617", "content_id": "7c0a57aac7363ab4f11172319872d28e354de639", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 542, "license_type": "permissive", "max_line_length": 68, "num_lines": 24, "path": "/run.py", "repo_name": "shanexia1818/face_comparison", "src_encoding": "UTF-8", "text": "import os\n\nimport click\n\nfrom app import create_app\n\nconfig_name = os.environ.get('FLASK_CONFIG', 'default')\napp = create_app(config_name=config_name)\n\n\[email protected]()\[email protected]('test_names', nargs=-1)\ndef test(test_names):\n \"\"\"Run the unit tests\"\"\"\n import unittest\n if test_names:\n tests = unittest.TestLoader().loadTestsFromNames(test_names)\n else:\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n" }, { "alpha_fraction": 0.7866666913032532, "alphanum_fraction": 0.7866666913032532, "avg_line_length": 14, "blob_id": "5e8d69eaca6ce1912f44132974724b389dbdd446", "content_id": "f434a742a4a0b72104d30f0111c575ed90fcfe57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 75, "license_type": "permissive", "max_line_length": 34, "num_lines": 5, "path": "/tests/test_compare.py", "repo_name": "shanexia1818/face_comparison", "src_encoding": "UTF-8", "text": "from tests import SetupMixin\n\n\nclass CompareTestCase(SetupMixin):\n pass\n" }, { "alpha_fraction": 0.6790243983268738, "alphanum_fraction": 0.6819512248039246, "avg_line_length": 23.404762268066406, "blob_id": "fe1ca7b074b35c1d92b2931915b74c7b47ea9e05", "content_id": "45f56d812bd07d9f72b7efb9defd1f8b664a4ffe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1025, "license_type": "permissive", "max_line_length": 69, "num_lines": 42, "path": "/config.py", "repo_name": "shanexia1818/face_comparison", "src_encoding": "UTF-8", "text": "import os\n\nBASE = os.path.abspath(os.path.dirname(__file__))\n\n\nclass Config:\n APP_NAME = 'face-comparison'\n SECRET_KEY = os.environ.get('SECRET_KEY') or 'secret-key'\n PROJECT_ROOT = BASE\n\n # compare faces similarity threshold\n THRESHOLD = float(os.environ.get('THRESHOLD')) \\\n if 'THRESHOLD' in os.environ else 0.85\n # engine detector plugin name and filepath\n ENGINE_DETECTOR_PLUGIN = os.environ.get('ENGINE_DETECTOR_PLUGIN')\n ENGINE_DETECTOR_NAME = os.environ.get('ENGINE_DETECTOR_NAME')\n # engine embedder plugin name and filepath\n ENGINE_EMBEDDER_PLUGIN = os.environ.get('ENGINE_EMBEDDER_PLUGIN')\n ENGINE_EMBEDDER_NAME = os.environ.get('ENGINE_EMBEDDER_NAME')\n\n\nclass DevConfig(Config):\n DEBUG = True\n TESTING = False\n\n\nclass TestConfig(Config):\n DEBUG = True\n TESTING = True\n\n\nclass ProdConfig(Config):\n DEBUG = False\n TESTING = False\n\n\nconfig = {\n 'development': DevConfig,\n 'testing': TestConfig,\n 'production': ProdConfig,\n 'default': DevConfig\n}\n" }, { "alpha_fraction": 0.6678004264831543, "alphanum_fraction": 0.6734693646430969, "avg_line_length": 32.92307662963867, "blob_id": "3c86efb5754de7a2edc93b01e6d7633e3dbc4a60", "content_id": "23572db3560a1bf5723f639c39d4b2d8b85833d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1764, "license_type": "permissive", "max_line_length": 77, "num_lines": 52, "path": "/app/api.py", "repo_name": "shanexia1818/face_comparison", "src_encoding": "UTF-8", "text": "from face_engine import FaceError\nfrom flask import Blueprint, request, jsonify, current_app\nfrom skimage.io import imread\n\nfrom . import engine\nfrom .errors import bad_request, unsupported, unprocessable\n\napi = Blueprint('api', __name__)\n\n\ndef allowed_files(filename):\n file_type = filename.rsplit('.', 1)[1].lower()\n return '.' in filename and \\\n file_type in ['jpg', 'jpeg', 'png']\n\n\[email protected]('/faces/compare', methods=['POST'])\ndef compare_faces():\n if 'source' not in request.files:\n return bad_request('no source file')\n\n if 'target' not in request.files:\n return bad_request('no target file')\n\n source = request.files.get('source')\n if source is None or not allowed_files(source.filename):\n return unsupported(\"'source' image file type is not supported\")\n\n target = request.files.get('target')\n if target is None or not allowed_files(target.filename):\n return unsupported(\"'target' image file type is not supported\")\n\n source_image = imread(source)\n try:\n _, source_bb = engine.find_face(source_image)\n except FaceError as e:\n return unprocessable(e.args[0] + \" on 'source' image\")\n\n target_image = imread(target)\n try:\n _, target_bbs = engine.find_faces(target_image)\n except FaceError as e:\n return unprocessable(e.args[0] + \" on 'target' image\")\n\n source_embedding = engine.compute_embeddings(source_image, [source_bb])\n target_embeddings = engine.compute_embeddings(target_image, target_bbs)\n _, score = engine._predictor.compare(source_embedding, target_embeddings)\n\n answer = dict()\n answer['FaceMatches'] = float(score) > current_app.config['THRESHOLD']\n answer['Similarity'] = score * 100\n return jsonify(answer), 200\n" }, { "alpha_fraction": 0.7159090638160706, "alphanum_fraction": 0.7159090638160706, "avg_line_length": 21, "blob_id": "e6ee904146bdceae2281fbc09127c551de701043", "content_id": "88948e82fcf06002228214961c59cd73a8e79a2f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "permissive", "max_line_length": 54, "num_lines": 12, "path": "/tests/test_basics.py", "repo_name": "shanexia1818/face_comparison", "src_encoding": "UTF-8", "text": "from flask import current_app\n\nfrom tests import SetupMixin\n\n\nclass BasicTestCase(SetupMixin):\n\n def test_app_exists(self):\n self.assertFalse(current_app is None)\n\n def test_app_is_testing(self):\n self.assertTrue(current_app.config['TESTING'])\n" }, { "alpha_fraction": 0.6106060743331909, "alphanum_fraction": 0.6227272748947144, "avg_line_length": 15.948718070983887, "blob_id": "5be16f9c773b480a1fe544cbec26798c186c61f6", "content_id": "9ef357eedefaf8a18509a24887ea04ec892490ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 660, "license_type": "permissive", "max_line_length": 99, "num_lines": 39, "path": "/README.md", "repo_name": "shanexia1818/face_comparison", "src_encoding": "UTF-8", "text": "# Face comparison micro-service\n\n## Installation\n\n#### Requirements\n\n* Python 3.6+\n\n#### Clone\n\n git clone https://github.com/guesswh0/compare_faces.git\n \n#### Install dependencies\n pip3 install -r requirements.txt\n \n\n### Run\n\nExport `.env` environment variables (configure it before):\n\n export $(grep -v '^#' .env | xargs)\n \nand run flask app:\n \n flask run\n\n\n#### Deployment\n\nTo _deploy_ see flask [deployment options](https://flask.palletsprojects.com/en/1.1.x/deploying/) \n\n\n##\n **Sample Call:**\n ```\n curl -X POST [host:port]/api/faces/compare \\\n -F source=@face_image1.jpg \\\n -F target=@face_image2.jpg\n ```" }, { "alpha_fraction": 0.6438515186309814, "alphanum_fraction": 0.6438515186309814, "avg_line_length": 25.121212005615234, "blob_id": "50bc3e85a0dbcc7a9d5e42f265a00d8bb221f40f", "content_id": "c67a387f2da475f2469cf3de325836593b5d02d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "permissive", "max_line_length": 53, "num_lines": 33, "path": "/app/__init__.py", "repo_name": "shanexia1818/face_comparison", "src_encoding": "UTF-8", "text": "from face_engine import FaceEngine\nfrom flask import Flask\n\nfrom config import config\n\nengine = FaceEngine()\n\n\ndef create_app(config_name):\n app = Flask(__name__)\n app.config.from_object(config[config_name])\n\n # set FaceEngine detector model\n detector = app.config['ENGINE_DETECTOR_NAME']\n if detector:\n plugin = app.config['ENGINE_DETECTOR_PLUGIN']\n if plugin:\n engine.use_plugin(detector, plugin)\n else:\n engine.detector = detector\n # set FaceEngine embedder model\n embedder = app.config['ENGINE_EMBEDDER_NAME']\n if embedder:\n plugin = app.config['ENGINE_EMBEDDER_PLUGIN']\n if plugin:\n engine.use_plugin(embedder, plugin)\n else:\n engine.embedder = embedder\n\n from .api import api\n app.register_blueprint(api, url_prefix='/api')\n\n return app\n" } ]
7
stasSajin/dw-benchmarks
https://github.com/stasSajin/dw-benchmarks
e7c8b50fa7f933953589df5faf25b75597d9ea08
f9aeae926df3c4d37bebaf116557d7eecdadc98e
769b702c262d271d57f1e800066c28a9189508d5
refs/heads/master
2020-11-30T04:34:10.907862
2019-12-30T16:51:09
2019-12-30T16:51:09
230,303,101
0
0
null
2019-12-26T17:34:01
2019-12-26T17:34:05
2019-12-30T16:51:10
null
[ { "alpha_fraction": 0.4513089060783386, "alphanum_fraction": 0.4785340428352356, "avg_line_length": 30.83333396911621, "blob_id": "60cc763a781ccdd4668beff3da5dea14ef32207e", "content_id": "24ee0fcaaf6d2131e783d1e8d363da9be97b7a20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 955, "license_type": "no_license", "max_line_length": 110, "num_lines": 30, "path": "/queries/query20.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query20\nSELECT /*tcpds_query20*/\n i_item_id ,\n i_item_desc ,\n i_category ,\n i_class ,\n i_current_price ,\n Sum(cs_ext_sales_price) AS itemrevenue ,\n Sum(cs_ext_sales_price)*100/Sum(Sum(cs_ext_sales_price)) OVER (partition BY i_class) AS revenueratio\nFROM catalog_sales ,\n item ,\n date_dim\nWHERE cs_item_sk = i_item_sk\nAND i_category IN ('Children',\n 'Women',\n 'Electronics')\nAND cs_sold_date_sk = d_date_sk\nAND Cast(d_date AS DATE) BETWEEN Cast('2001-02-03' AS DATE) AND (\n Cast('2001-03-03' AS DATE))\nGROUP BY i_item_id ,\n i_item_desc ,\n i_category ,\n i_class ,\n i_current_price\nORDER BY i_category ,\n i_class ,\n i_item_id ,\n i_item_desc ,\n revenueratio\nLIMIT 100;\n" }, { "alpha_fraction": 0.5115044116973877, "alphanum_fraction": 0.5415928959846497, "avg_line_length": 25.904762268066406, "blob_id": "7c237379dccce556485603bc440a7f96f6957429", "content_id": "672bf4a245656b5b4c98c527882c855f5e7766dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 565, "license_type": "no_license", "max_line_length": 54, "num_lines": 21, "path": "/queries/query22.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query22\nSELECT /*tcpds_query22*/ i_product_name, \n i_brand,\n i_class,\n i_category,\n Avg(inv_quantity_on_hand) qoh\nFROM inventory,\n date_dim,\n item,\n warehouse\nWHERE inv_date_sk = d_date_sk\n AND inv_item_sk = i_item_sk\n AND inv_warehouse_sk = w_warehouse_sk\n AND d_month_seq BETWEEN 1205 AND 1205 + 11\nGROUP BY i_product_name, i_brand, i_class, i_category\nORDER BY qoh,\n i_product_name,\n i_brand,\n i_class,\n i_category\nLIMIT 100;\n" }, { "alpha_fraction": 0.44195953011512756, "alphanum_fraction": 0.4696485698223114, "avg_line_length": 30.299999237060547, "blob_id": "6f20452bfba4bb4e613b03cf299a544702158316", "content_id": "027b53c52d10acb651c16aa34774faafbd4ed5f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 939, "license_type": "no_license", "max_line_length": 110, "num_lines": 30, "path": "/queries/query12.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query12\nSELECT /*tcpds_query12*/\n i_item_id ,\n i_item_desc ,\n i_category ,\n i_class ,\n i_current_price ,\n Sum(ws_ext_sales_price) AS itemrevenue ,\n Sum(ws_ext_sales_price)*100/Sum(Sum(ws_ext_sales_price)) OVER (partition BY i_class) AS revenueratio\nFROM web_sales ,\n item ,\n date_dim\nWHERE ws_item_sk = i_item_sk\nAND i_category IN ('Home',\n 'Men',\n 'Women')\nAND ws_sold_date_sk = d_date_sk\nAND Cast(d_date AS DATE) BETWEEN Cast('2000-05-11' AS DATE) AND (\n Cast('2000-06-11' AS DATE))\nGROUP BY i_item_id ,\n i_item_desc ,\n i_category ,\n i_class ,\n i_current_price\nORDER BY i_category ,\n i_class ,\n i_item_id ,\n i_item_desc ,\n revenueratio\nLIMIT 100;\n" }, { "alpha_fraction": 0.4825327396392822, "alphanum_fraction": 0.5152838230133057, "avg_line_length": 25.941177368164062, "blob_id": "58ec3be047502369364115ff7d64d72bea95f017", "content_id": "831cb9a29bfa13d083587b2f162a460219b11a56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 458, "license_type": "no_license", "max_line_length": 59, "num_lines": 17, "path": "/queries/query55.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query55\nSELECT /*tcpds_query55*/ i_brand_id brand_id, \n i_brand brand,\n Sum(ss_ext_sales_price) ext_price\nFROM date_dim,\n store_sales,\n item\nWHERE d_date_sk = ss_sold_date_sk\n AND ss_item_sk = i_item_sk\n AND i_manager_id = 33\n AND d_moy = 12\n AND d_year = 1998\nGROUP BY i_brand,\n i_brand_id\nORDER BY ext_price DESC,\n i_brand_id\nLIMIT 100;\n" }, { "alpha_fraction": 0.6778711676597595, "alphanum_fraction": 0.6799719929695129, "avg_line_length": 34.70000076293945, "blob_id": "10c1af1374f1774e9b8b3d9a4acd4665c63fa82f", "content_id": "5a59aac1acafb84e63ef592cb21f7a47ee364fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1428, "license_type": "no_license", "max_line_length": 134, "num_lines": 40, "path": "/dw_benchmark/ddl/shared/utils.py", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "try:\n import importlib.resources as pkg_resources\nexcept ImportError:\n # Try backported to PY<37 `importlib_resources`.\n import importlib_resources as pkg_resources\nfrom dw_benchmark import templates\n\n\ndef run_warmup(model, engine) -> None:\n print(\"Running warmup by selecting * from all tables in a model\")\n warmup = pkg_resources.read_text(templates, \"warmup.sql\")\n statement = warmup.format(schema=model.schema_name)\n _ = run_query(engine, statement)\n\n\ndef read_query(sql_file_path):\n with open(sql_file_path) as file:\n query = file.read()\n return query\n\n\ndef run_query(engine, statement):\n with engine.connect() as con:\n result = con.execution_options(autocommit=True).execute(statement)\n return result\n\n\ndef create_user_with_permissions(user: str, engine, pw: str = \"Password1\"):\n try:\n run_query(engine, f\"create user if not exists {user} password '{pw}';\")\n except:\n print(f\"User {user} already exists. Skipping user creation\")\n schemas = run_query(\n engine, \"select schema_name from information_schema.schemata;\"\n ).fetchall()\n for schema in schemas:\n schema_name = schema[0]\n print(f\"Granting all permissions to schema {schema_name} to user {user}\")\n stmt = f\"grant usage on schema {schema_name} to {user}; grant all privileges on all tables in schema {schema_name} to {user};\"\n run_query(engine, stmt)\n" }, { "alpha_fraction": 0.7722457647323608, "alphanum_fraction": 0.7976694703102112, "avg_line_length": 43.9523811340332, "blob_id": "54342fb7cbfa695c3d419a6dbba57481de93ff37", "content_id": "07986725cc238e96d11217d0aa1cf9b294d96fe1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 944, "license_type": "no_license", "max_line_length": 77, "num_lines": 21, "path": "/redshift-experiments/optimized_vs_unoptimized.py", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "from dw_benchmark.ddl.shared.models import TCPDS100g, TCPDS100gUnoptimized\nfrom dw_benchmark.ddl.shared.utils import run_warmup\nfrom dw_benchmark.ddl.shared.utils import create_user_with_permissions\nfrom dw_benchmark.ddl.redshift_ddls.redshift_utils import get_redshift_engine\nfrom dw_benchmark.ddl.redshift_ddls.redshift_utils import run_copy_commands\nfrom dw_benchmark.ddl.redshift_ddls.redshift_utils import run_ddl\nfrom dw_benchmark.ddl.redshift_ddls.redshift_utils import run_analyze\nimport config\n\n\nengine = get_redshift_engine(\n host=config.host, db=config.db, user=config.user, pwd=config.pw\n)\n\nfor model in [TCPDS100g, TCPDS100gUnoptimized]:\n run_ddl(TCPDS100g, engine=engine)\n run_copy_commands(TCPDS100gUnoptimized, engine=engine, role=config.role)\n run_analyze(engine)\n run_warmup(TCPDS100gUnoptimized, engine=engine)\n run_warmup(TCPDS100g, engine=engine)\n create_user_with_permissions(\"tcpds\", engine=engine)\n" }, { "alpha_fraction": 0.48122867941856384, "alphanum_fraction": 0.5153583884239197, "avg_line_length": 31.55555534362793, "blob_id": "e081e219b063c9f422d5964763e32de914ba1ae2", "content_id": "b190e0f179cf71289536e55970e8b38e6f3d9928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 586, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/queries/query86.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query86\nSELECT /*tcpds_query86*/ Sum(ws_net_paid) AS total_sum, \n i_category,\n i_class,\n Rank()\n OVER (\n PARTITION BY i_category, i_class\n ORDER BY Sum(ws_net_paid) DESC) AS rank_within_parent\nFROM web_sales,\n date_dim d1,\n item\nWHERE d1.d_month_seq BETWEEN 1183 AND 1183 + 11\n AND d1.d_date_sk = ws_sold_date_sk\n AND i_item_sk = ws_item_sk\nGROUP BY i_category, i_class\nORDER BY i_category,\n rank_within_parent\nLIMIT 100;\n" }, { "alpha_fraction": 0.6690518856048584, "alphanum_fraction": 0.7066189646720886, "avg_line_length": 20.5, "blob_id": "ed6644c46a826c2ed6b206c97295b245d170a145", "content_id": "44f13a995ed3f91c6c7c972bf70cd090f412286c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 559, "license_type": "no_license", "max_line_length": 72, "num_lines": 26, "path": "/pyproject.toml", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"dw-benchmark\"\nversion = \"0.1.0\"\ndescription = \"Benchmark utility and reporting for Data Warehouse tools\"\nauthors = [\"Stas Sajin <[email protected]>\"]\n\n[tool.poetry.dependencies]\npython = \"^3.6\"\nsqlalchemy = \"1.3.3\"\npsycopg2-binary = \"2.8.2\"\npydantic = \"1.3\"\n\n[tool.isort]\nline_length = 88\nforce_single_line = true\natomic = true\ninclude_trailing_comma = true\nlines_after_imports = 2\nlines_between_types = 1\nmulti_line_output = 3\nuse_parentheses = true\nfilter_files = true\n\n[build-system]\nrequires = [\"poetry>=1.0\"]\nbuild-backend = \"poetry.masonry.api\"\n" }, { "alpha_fraction": 0.5202797055244446, "alphanum_fraction": 0.5412587523460388, "avg_line_length": 28.79166603088379, "blob_id": "70eb6c527968154bb4b1f6086a9ac6c6291120d6", "content_id": "6a1a541f01a529c8eb284d118cebfe3b81b083f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 715, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/queries/query26.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query26\nSELECT /*tcpds_query26*/ i_item_id, \n Avg(cs_quantity) agg1,\n Avg(cs_list_price) agg2,\n Avg(cs_coupon_amt) agg3,\n Avg(cs_sales_price) agg4\nFROM catalog_sales,\n customer_demographics,\n date_dim,\n item,\n promotion\nWHERE cs_sold_date_sk = d_date_sk\n AND cs_item_sk = i_item_sk\n AND cs_bill_cdemo_sk = cd_demo_sk\n AND cs_promo_sk = p_promo_sk\n AND cd_gender = 'F'\n AND cd_marital_status = 'W'\n AND cd_education_status = 'Secondary'\n AND ( p_channel_email = 'N'\n OR p_channel_event = 'N' )\n AND d_year = 2000\nGROUP BY i_item_id\nORDER BY i_item_id\nLIMIT 100;\n" }, { "alpha_fraction": 0.3611111044883728, "alphanum_fraction": 0.3951388895511627, "avg_line_length": 41.35293960571289, "blob_id": "c6d14a90f629c1d755b040aa1d001128c35f892e", "content_id": "462ec05880c5e13914187118ffed5c76feee39a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 167, "num_lines": 34, "path": "/queries/query40.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query40\nSELECT /*tcpds_query40*/ \n w_state ,\n i_item_id ,\n Sum(\n CASE\n WHEN (\n Cast(d_date AS DATE) < Cast ('2002-06-01' AS DATE)) THEN cs_sales_price - COALESCE(cr_refunded_cash,0)\n ELSE 0\n END) AS sales_before ,\n Sum(\n CASE\n WHEN (\n Cast(d_date AS DATE) >= Cast ('2002-06-01' AS DATE)) THEN cs_sales_price - COALESCE(cr_refunded_cash,0)\n ELSE 0\n END) AS sales_after\nFROM catalog_sales\nLEFT OUTER JOIN catalog_returns\nON (\n cs_order_number = cr_order_number\n AND cs_item_sk = cr_item_sk) ,\n warehouse ,\n item ,\n date_dim\nWHERE i_current_price BETWEEN 0.99 AND 1.49\nAND i_item_sk = cs_item_sk\nAND cs_warehouse_sk = w_warehouse_sk\nAND cs_sold_date_sk = d_date_sk\nAND Cast(d_date AS DATE) BETWEEN (Cast ('2002-05-01' AS DATE)) AND cast ('2002-07-01' AS date)\nGROUP BY w_state,\n i_item_id\nORDER BY w_state,\n i_item_id\nLIMIT 100;\n" }, { "alpha_fraction": 0.4677206873893738, "alphanum_fraction": 0.5256916880607605, "avg_line_length": 35.14285659790039, "blob_id": "054efed6525663d8a89c30fce193dc2cc8ffc2c5", "content_id": "466f65a667b04ea0bfed91ba49982a0929a00774", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 759, "license_type": "no_license", "max_line_length": 85, "num_lines": 21, "path": "/queries/query32.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query32\nSELECT /*tcpds_query32*/ \n Sum(cs_ext_discount_amt) AS excess_discount_amount\nFROM catalog_sales ,\n item ,\n date_dim\nWHERE i_manufact_id = 610\nAND i_item_sk = cs_item_sk\nAND Cast(d_date AS DATE) BETWEEN Cast('2001-03-04' AS DATE) AND (\n Cast('2001-06-03' AS DATE))\nAND d_date_sk = cs_sold_date_sk\nAND cs_ext_discount_amt >\n (\n SELECT 1.3 * avg(cs_ext_discount_amt)\n FROM catalog_sales ,\n date_dim\n WHERE cs_item_sk = i_item_sk\n AND Cast(d_date AS DATE) BETWEEN Cast('2001-03-04' AS DATE) AND (\n Cast('2001-06-03' AS DATE))\n AND d_date_sk = cs_sold_date_sk )\nLIMIT 100;\n" }, { "alpha_fraction": 0.5060449242591858, "alphanum_fraction": 0.5302245020866394, "avg_line_length": 27.950000762939453, "blob_id": "452eb66275c6dfed34ad08e897b5f3e1a4c2d726", "content_id": "30ffb8cbcb4d05035c49d8f4d0017b56d7733ec3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 579, "license_type": "no_license", "max_line_length": 50, "num_lines": 20, "path": "/queries/query52.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query52\nSELECT /*tcpds_query52*/ dt.d_year, \n item.i_brand_id brand_id,\n item.i_brand brand,\n Sum(ss_ext_sales_price) ext_price\nFROM date_dim dt,\n store_sales,\n item\nWHERE dt.d_date_sk = store_sales.ss_sold_date_sk\n AND store_sales.ss_item_sk = item.i_item_sk\n AND item.i_manager_id = 1\n AND dt.d_moy = 11\n AND dt.d_year = 1999\nGROUP BY dt.d_year,\n item.i_brand,\n item.i_brand_id\nORDER BY dt.d_year,\n ext_price DESC,\n brand_id\nLIMIT 100;\n" }, { "alpha_fraction": 0.7976190447807312, "alphanum_fraction": 0.7976190447807312, "avg_line_length": 41, "blob_id": "22dd43267e676ede97da04e19e674d67f9f438d5", "content_id": "91f5354bd0a130b2faf9eedfa9f18108ee8b1fc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 84, "license_type": "no_license", "max_line_length": 67, "num_lines": 2, "path": "/README.md", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "# dw-benchmarks\nSet of utilities, scripts, reports, and configs for Data Warehouses\n" }, { "alpha_fraction": 0.5990098714828491, "alphanum_fraction": 0.6522276997566223, "avg_line_length": 25.064516067504883, "blob_id": "d722382e0726e92e7b08ce50bb5bce27fbb1c44a", "content_id": "92b8ec2b40c0d41950c90546c354dcdbfa2b3ca9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 808, "license_type": "no_license", "max_line_length": 58, "num_lines": 31, "path": "/dw_benchmark/ddl/shared/models.py", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "from enum import Enum\n\n\nclass TCPDS100g(str, Enum):\n s3_url: str = \"s3://fivetran-benchmark/tpcds_100_dat\"\n schema_name: str = \"tcpds100g\"\n ddl: str = \"optimized.sql\"\n\n\nclass TCPDS100gUnoptimized(str, Enum):\n s3_url: str = \"s3://fivetran-benchmark/tpcds_100_dat\"\n schema_name: str = \"tcpds100g_unoptimized\"\n ddl: str = \"not_optimized.sql\"\n\n\nclass TCPDS1T(str, Enum):\n s3_url: str = \"s3://fivetran-benchmark/tpcds_1000_dat\"\n schema_name: str = \"tcpds1TB\"\n ddl: str = \"optimized.sql\"\n\n\nclass TCPDS3T(str, Enum):\n s3_url: str = \"s3://redshift-downloads/TPC-DS/3TB\"\n schema_name: str = \"tcpds3TB\"\n ddl: str = \"optimized.sql\"\n\n\nclass TCPDS10T(str, Enum):\n s3_url: str = \"s3://redshift-downloads/TPC-DS/10TB\"\n schema_name: str = \"tcpds10TB\"\n ddl: str = \"optimized.sql\"\n" }, { "alpha_fraction": 0.49147287011146545, "alphanum_fraction": 0.5627906918525696, "avg_line_length": 28.272727966308594, "blob_id": "77b3858a5b8bc82b9909fe1865678b8e52c97242", "content_id": "a4634191bf0bacd898c6d66f8c3ccea1459fd135", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 645, "license_type": "no_license", "max_line_length": 75, "num_lines": 22, "path": "/queries/query82.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "\n-- query82\nSELECT/*tcpds_query82*/ \n i_item_id ,\n i_item_desc ,\n i_current_price\nFROM item,\n inventory,\n date_dim,\n store_sales\nWHERE i_current_price BETWEEN 63 AND 63+30\nAND inv_item_sk = i_item_sk\nAND d_date_sk=inv_date_sk\nAND Cast(d_date AS DATE) BETWEEN Cast('1998-04-27' AS DATE) AND (\n Cast('1998-06-27' AS DATE))\nAND i_manufact_id IN (57,293,427,320)\nAND inv_quantity_on_hand BETWEEN 100 AND 500\nAND ss_item_sk = i_item_sk\nGROUP BY i_item_id,\n i_item_desc,\n i_current_price\nORDER BY i_item_id\nLIMIT 100;\n" }, { "alpha_fraction": 0.5112179517745972, "alphanum_fraction": 0.5865384340286255, "avg_line_length": 28.714284896850586, "blob_id": "cf696a9907e14b52c3c374d386a9176a1190c14e", "content_id": "31a9bf29426180e1e91b1865f28a9222bfccb540", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 624, "license_type": "no_license", "max_line_length": 95, "num_lines": 21, "path": "/queries/query37.sql", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "-- query37\nSELECT /*tcpds_query37*/ \n i_item_id ,\n i_item_desc ,\n i_current_price\nFROM item,\n inventory,\n date_dim,\n catalog_sales\nWHERE i_current_price BETWEEN 20 AND 20 + 30\nAND inv_item_sk = i_item_sk\nAND d_date_sk=inv_date_sk\nAND Cast(d_date AS DATE) BETWEEN Cast('1999-03-06' AS DATE) AND Cast('1999-05-06' AS DATE)\nAND i_manufact_id IN (843,815,850,840)\nAND inv_quantity_on_hand BETWEEN 100 AND 500\nAND cs_item_sk = i_item_sk\nGROUP BY i_item_id,\n i_item_desc,\n i_current_price\nORDER BY i_item_id\nLIMIT 100;\n" }, { "alpha_fraction": 0.6231092214584351, "alphanum_fraction": 0.6340336203575134, "avg_line_length": 29.126583099365234, "blob_id": "2c3c135f6651354491efa9e9dedae4179036d621", "content_id": "8cb54f42a5280ea7be55aa915c9152faf4c0f807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2380, "license_type": "no_license", "max_line_length": 121, "num_lines": 79, "path": "/dw_benchmark/ddl/redshift_ddls/redshift_utils.py", "repo_name": "stasSajin/dw-benchmarks", "src_encoding": "UTF-8", "text": "try:\n import importlib.resources as pkg_resources\nexcept ImportError:\n # Try backported to PY<37 `importlib_resources`.\n import importlib_resources as pkg_resources\nfrom dw_benchmark import templates\nfrom dw_benchmark.ddl.shared.models import TCPDS100g\nfrom dw_benchmark.ddl.shared.models import TCPDS100gUnoptimized\nfrom dw_benchmark.ddl.shared.models import TCPDS1T\nfrom dw_benchmark.ddl.shared.models import TCPDS3T\nfrom dw_benchmark.ddl.shared.models import TCPDS10T\nfrom dw_benchmark.ddl.shared.utils import run_query\nfrom sqlalchemy import create_engine\n\n\ndef get_redshift_engine(host, db, user, pwd):\n return create_engine(f\"postgresql://{user}:{pwd}@{host}:5439/{db}\")\n\n\ndef generate_ddl(model):\n print(f\"Generating DDL for {model.schema_name}\")\n ddl = pkg_resources.read_text(templates, model.ddl)\n ddl = ddl.format(schema=model.schema_name)\n return ddl\n\n\ndef run_copy_commands(model, engine, role):\n # the copy parameters depend on the source of data.\n # for fivetran data-sources\n if model in [TCPDS100g, TCPDS100gUnoptimized, TCPDS1T]:\n shared_params = (\n \"format delimiter '|' acceptinvchars compupdate on region 'us-east-1'\"\n )\n else:\n # for redshift data sources\n shared_params = \"gzip delimiter '|' compupdate on region 'us-east-1'\"\n tables = [\n \"store_sales\",\n \"catalog_sales\",\n \"web_sales\",\n \"web_returns\",\n \"store_returns\",\n \"catalog_returns\",\n \"call_center\",\n \"catalog_page\",\n \"customer_address\",\n \"customer\",\n \"customer_demographics\",\n \"date_dim\",\n \"household_demographics\",\n \"income_band\",\n \"inventory\",\n \"item\",\n \"promotion\",\n \"reason\",\n \"ship_mode\",\n \"store\",\n \"time_dim\",\n \"warehouse\",\n \"web_page\",\n \"web_site\",\n ]\n\n for table in tables:\n print(f\"Running copy for table {model.schema_name}.{table}\")\n statement = f\"copy {model.schema_name}.{table} from '{model.s3_url}/{table}/' iam_role '{role}' {shared_params};\"\n _ = run_query(engine, statement)\n\n\ndef run_ddl(model, engine) -> None:\n ddl = generate_ddl(model)\n _ = run_query(engine, ddl)\n\n\ndef run_analyze(engine) -> None:\n \"\"\"\n Compute table statistics on all the db.\n \"\"\"\n _ = run_query(engine, \"analyze;\")\n" } ]
17
wonnerky/ml
https://github.com/wonnerky/ml
75732a2ebb6167dde1f6a96bbac24162aa480f13
60798932bca8f63232327a93afaae96ee58f1230
af72fba34daddee3e13b0e23af2db65390c4dc13
refs/heads/master
2022-04-16T22:27:25.152915
2020-04-20T10:19:13
2020-04-20T10:19:13
255,813,272
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6844444274902344, "alphanum_fraction": 0.7081481218338013, "avg_line_length": 29.727272033691406, "blob_id": "a458d1d195e710fe17c5fb21208149aeb321d5fb", "content_id": "7ad0fcff9de097ed7f1353a0ad91da9ebd079a3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 675, "license_type": "no_license", "max_line_length": 60, "num_lines": 22, "path": "/filter_visualization/test.py", "repo_name": "wonnerky/ml", "src_encoding": "UTF-8", "text": "import time\nimport numpy as np\nfrom PIL import Image as pil_image\nfrom keras.preprocessing.image import save_img\nfrom keras import layers\nfrom keras.applications import vgg16\nfrom keras import backend as K\n\nif __name__ == '__main__':\n # the name of the layer we want to visualize\n # (see model definition at keras/applications/vgg16.py)\n LAYER_NAME = 'block3_conv1'\n\n # build the VGG16 network with ImageNet weights\n vgg = vgg16.VGG16(weights='imagenet', include_top=False)\n print('Model loaded.')\n vgg.summary()\n print()\n output_layer = vgg.get_layer(LAYER_NAME).output\n print(output_layer)\n print(output_layer[4,4,4,4])\n print(vgg.input)" }, { "alpha_fraction": 0.556400716304779, "alphanum_fraction": 0.58840411901474, "avg_line_length": 38.37288284301758, "blob_id": "3874e4119e3320e9b4eda03db2b580b9dff50deb", "content_id": "1c80df2ba1d150a612b6dde9d4f062918d7853ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6968, "license_type": "no_license", "max_line_length": 109, "num_lines": 177, "path": "/AE_img_conv/feature_coco.py", "repo_name": "wonnerky/ml", "src_encoding": "UTF-8", "text": "from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Flatten\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom PIL import Image\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nimport shutil\nimport os\n\ntraining_dir = 'data/val2017'\ntest_dir = 'data/val2017/test'\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntraining_set = train_datagen.flow_from_directory(training_dir,\n target_size=(200,200),\n batch_size=32,\n class_mode='input')\ntest_set = train_datagen.flow_from_directory(test_dir,\n target_size=(200,200),\n batch_size=32,\n class_mode='input')\ntraining_set.image_data_generator\ninput_img = Input(shape=(200, 200, 3))\n\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(64, (3, 3), activation='relu', padding='same')(x)\nencoded = MaxPooling2D((2, 2), padding='same')(x)\n\nx = Conv2D(64, (3, 3), activation='relu', padding='same')(encoded)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\ndecoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)\n\nautoencoder = Model(input_img, decoded)\nae_filter = Model(input_img, decoded)\n\nprint(autoencoder.summary())\n# check point\ncp_path = 'cp/coco_cp.ckpt'\ncp_dir = os.path.dirname(cp_path)\nos.makedirs(cp_dir, exist_ok=True)\n\nif os.path.isfile(cp_path):\n autoencoder.load_weights(cp_path)\n ae_filter.load_weights(cp_path)\n\ncpCallback = ModelCheckpoint(cp_path, verbose=0)\n\n# Train\nif not os.path.isfile(cp_path):\n autoencoder.compile(optimizer='adam', loss='mse')\n autoencoder.fit_generator(training_set,\n steps_per_epoch=4500/32,\n epochs=15,\n shuffle=True,\n validation_data=test_set,\n validation_steps=500/32,\n callbacks=[cpCallback]\n )\n\n\nlayer_ = [autoencoder.layers[1],autoencoder.layers[3],autoencoder.layers[5],autoencoder.layers[7],\n autoencoder.layers[9],autoencoder.layers[11]]\nlayer_outputs = [layer.output for layer in layer_]\nactivation_model = Model(inputs=autoencoder.input, outputs=layer_outputs)\n\nimg = Image.open('data/val2017/000000001584.jpg')\nimg = img.resize((200,200))\nprint(img.size)\nimg = np.asarray(img)\nimg = img / 255.\nimg = img.reshape(1,200,200,3)\nfig = plt.figure(figsize=(5,5))\nplt.imshow(img[0,:,:,:])\nplt.show()\nresult = autoencoder.predict(img)\nplt.imshow(result[0,:,:,:])\n\nactivations = activation_model.predict(img)\n\nlayer_names = []\nfor layer in layer_:\n layer_names.append(layer.name) # Names of the layers, so you can have them as part of your plot\n\nimages_per_row = 8\n\nfor layer_name, layer_activation in zip(layer_names, activations): # Displays the feature maps\n n_features = layer_activation.shape[-1] # Number of features in the feature map\n size = layer_activation.shape[1] # The feature map has shape (1, size, size, n_features).\n n_cols = n_features // images_per_row # Tiles the activation channels in this matrix\n display_grid = np.zeros((size * n_cols, images_per_row * size))\n for col in range(n_cols): # Tiles each filter into a big horizontal grid\n for row in range(images_per_row):\n channel_image = layer_activation[0, :, :, col * images_per_row + row]\n channel_image -= channel_image.mean() # Post-processes the feature to make it visually palatable\n channel_image /= (channel_image.std() + 1e-7)\n channel_image *= 64\n channel_image += 128\n channel_image = np.clip(channel_image, 0, 255).astype('uint8')\n # Displays the grid\n display_grid[col * size: (col + 1) * size, row * size: (row + 1) * size] = channel_image\n scale = 1. / size\n plt.figure(figsize=(scale * display_grid.shape[1],\n scale * display_grid.shape[0]))\n plt.title(layer_name)\n plt.grid(False)\n plt.imshow(display_grid, aspect='equal') #, cmap='viridis')\nplt.show()\n\n\n# -------------------------------------------------\n# Utility function for displaying filters as images\n# -------------------------------------------------\n\ndef deprocess_image(x):\n x -= x.mean()\n x /= (x.std() + 1e-5)\n x *= 0.1\n x += 0.5\n x = np.clip(x, 0, 1)\n # x *= 255\n # x = np.clip(x, 0, 255).astype('uint8')\n return x\n\n\n# ---------------------------------------------------------------------------------------------------\n# Utility function for generating patterns for given layer starting from empty input image and then\n# applying Stochastic Gradient Ascent for maximizing the response of particular filter in given layer\n# ---------------------------------------------------------------------------------------------------\n\ndef generate_pattern(layer_name, filter_index, size=25):\n layer_output = ae_filter.get_layer(layer_name).output\n loss = K.mean(layer_output[:, :, :, filter_index])\n grads = K.gradients(loss, ae_filter.input)[0]\n grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)\n iterate = K.function([ae_filter.input], [loss, grads])\n input_img_data = np.random.random((1, size, size, 3)) * 20 + 128.\n step = 1.\n for i in range(80):\n loss_value, grads_value = iterate([input_img_data])\n input_img_data += grads_value * step\n\n img = input_img_data[0]\n return deprocess_image(img)\n\n\n# ------------------------------------------------------------------------------------------\n# Generating convolution layer filters for intermediate layers using above utility functions\n# ------------------------------------------------------------------------------------------\n\nlayer_name = 'conv2d_4'\nsize = 200\nmargin = 5\nresults = np.zeros((4 * size + 7 * margin, 8 * size + 7 * margin, 3))\n\nfor i in range(4):\n for j in range(8):\n filter_img = generate_pattern(layer_name, i + j, size=size)\n horizontal_start = i * size + i * margin\n horizontal_end = horizontal_start + size\n vertical_start = j * size + j * margin\n vertical_end = vertical_start + size\n results[horizontal_start: horizontal_end, vertical_start: vertical_end, :] = filter_img\n\nplt.figure(figsize=(20, 20))\nplt.imshow(results, aspect='equal')\nplt.show()" }, { "alpha_fraction": 0.7423780560493469, "alphanum_fraction": 0.8064024448394775, "avg_line_length": 45.71428680419922, "blob_id": "415105c7e31be0ffa8851660b57d3bd2934075c0", "content_id": "e9efaed1c26e170a9374cdb3bf802819ce3f78d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 656, "license_type": "no_license", "max_line_length": 133, "num_lines": 14, "path": "/README.md", "repo_name": "wonnerky/ml", "src_encoding": "UTF-8", "text": "# ml\n\nmnist visualization \nhttps://towardsdatascience.com/visualizing-intermediate-activations-of-a-cnn-trained-on-the-mnist-dataset-2c34426416c8 \nhttps://github.com/jireh-father/tensorflow-cnn-visualization \nhttps://www.yceffort.kr/2019/02/21/pytorch-06-convolutional-neural-network(1)/ \n\nvgg visualization \nhttps://towardsdatascience.com/how-to-visualize-convolutional-features-in-40-lines-of-code-70b7d87b0030 \n\nfeaturemap visualization Youtube \nhttps://www.youtube.com/watch?v=RNnKtNrsrmg&feature=youtu.be \n\nhttps://www.researchgate.net/figure/Visualization-of-feature-map-From-left-to-right-Original-image-feature-maps-of-our_fig2_327995064 \n" }, { "alpha_fraction": 0.5916076898574829, "alphanum_fraction": 0.612740159034729, "avg_line_length": 37.18918991088867, "blob_id": "5a4a1aef159c152a71b876340d8963ede4732f3c", "content_id": "468dd37782a6ac4892bdd7103c6643092bca9e61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9928, "license_type": "no_license", "max_line_length": 109, "num_lines": 259, "path": "/AE_img_conv/cifar_classification.py", "repo_name": "wonnerky/ml", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import backend as K\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nbatch_size = 32\nnum_classes = 10\nepochs = 100\ndata_augmentation = True\nnum_predictions = 20\nsave_dir = os.path.join(os.getcwd(), 'saved_models')\nmodel_name = 'keras_cifar10_trained_model.h5'\n\n# The data, split between train and test sets:\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n# print('x_train shape:', x_train.shape)\n# print(x_train.shape[0], 'train samples')\n# print(x_test.shape[0], 'test samples')\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), padding='same', input_shape=x_train.shape[1:]))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes))\nmodel.add(Activation('softmax'))\n\nprint(model.summary())\n\n# initiate RMSprop optimizer\nopt = keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\n\n# check point\ncp_path = 'cp/cifar_cp.ckpt'\ncp_dir = os.path.dirname(cp_path)\nos.makedirs(cp_dir, exist_ok=True)\n\nif os.path.isfile(cp_path):\n model.load_weights(cp_path)\n\ncpCallback = ModelCheckpoint(cp_path, verbose=0)\n\n# Train\nif not os.path.isfile(cp_path):\n model.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n\n if not data_augmentation:\n print('Not using data augmentation.')\n model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=[cpCallback])\n else:\n print('Using real-time data augmentation.')\n # This will do preprocessing and realtime data augmentation:\n datagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n zca_epsilon=1e-06, # epsilon for ZCA whitening\n rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)\n # randomly shift images horizontally (fraction of total width)\n width_shift_range=0.1,\n # randomly shift images vertically (fraction of total height)\n height_shift_range=0.1,\n shear_range=0., # set range for random shear\n zoom_range=0., # set range for random zoom\n channel_shift_range=0., # set range for random channel shifts\n # set mode for filling points outside the input boundaries\n fill_mode='nearest',\n cval=0., # value used for fill_mode = \"constant\"\n horizontal_flip=True, # randomly flip images\n vertical_flip=False, # randomly flip images\n # set rescaling factor (applied before any other transformation)\n rescale=None,\n # set function that will be applied on each input\n preprocessing_function=None,\n # image data format, either \"channels_first\" or \"channels_last\"\n data_format=None,\n # fraction of images reserved for validation (strictly between 0 and 1)\n validation_split=0.0)\n\n # Compute quantities required for feature-wise normalization\n # (std, mean, and principal components if ZCA whitening is applied).\n datagen.fit(x_train)\n\n # Fit the model on the batches generated by datagen.flow().\n model.fit_generator(datagen.flow(x_train, y_train,\n batch_size=batch_size),\n epochs=epochs,\n validation_data=(x_test, y_test),\n workers=4,\n callbacks=[cpCallback])\n\n\n# Let's train the model using RMSprop\n\n\n\n#### visualization ####\nlayer_ = [model.layers[1], model.layers[3], model.layers[7],\n model.layers[9], model.layers[13], model.layers[15]]\nlayer_outputs = [layer.output for layer in layer_]\nactivation_model = Model(inputs=model.input, outputs=layer_outputs)\n\nimg = x_test[100]\nimg = img.reshape(1,32,32,3)\nfig = plt.figure(figsize=(5,5))\nplt.imshow(img[0,:,:,:])\n# plt.savefig('input.png')\nplt.show()\n\nactivations = activation_model.predict(img)\n\nlayer_names = []\nfor layer in layer_:\n layer_names.append(layer.name) # Names of the layers, so you can have them as part of your plot\n\nimages_per_row = 8\n\nfor layer_name, layer_activation in zip(layer_names, activations): # Displays the feature maps\n n_features = layer_activation.shape[-1] # Number of features in the feature map\n size = layer_activation.shape[1] # The feature map has shape (1, size, size, n_features).\n n_cols = n_features // images_per_row # Tiles the activation channels in this matrix\n display_grid = np.zeros((size * n_cols, images_per_row * size))\n for col in range(n_cols): # Tiles each filter into a big horizontal grid\n for row in range(images_per_row):\n channel_image = layer_activation[0, :, :, col * images_per_row + row]\n channel_image -= channel_image.mean() # Post-processes the feature to make it visually palatable\n channel_image /= (channel_image.std() + 1e-7)\n channel_image *= 64\n channel_image += 128\n channel_image = np.clip(channel_image, 0, 255).astype('uint8')\n # Displays the grid\n display_grid[col * size: (col + 1) * size, row * size: (row + 1) * size] = channel_image\n scale = 1. / size\n plt.figure(figsize=(scale * display_grid.shape[1],\n scale * display_grid.shape[0]))\n plt.title(layer_name)\n plt.grid(False)\n plt.imshow(display_grid, aspect='equal') #, cmap='viridis')\n img_file_name = layer_name + '.png'\n # plt.savefig(img_file_name)\nplt.show()\n\n\n# -------------------------------------------------\n# Utility function for displaying filters as images\n# -------------------------------------------------\n\ndef deprocess_image(x):\n x -= x.mean()\n x /= (x.std() + 1e-5)\n x *= 0.1\n x += 0.5\n x = np.clip(x, 0, 1)\n # x *= 255\n # x = np.clip(x, 0, 255).astype('uint8')\n return x\n\n\n# ---------------------------------------------------------------------------------------------------\n# Utility function for generating patterns for given layer starting from empty input image and then\n# applying Stochastic Gradient Ascent for maximizing the response of particular filter in given layer\n# ---------------------------------------------------------------------------------------------------\n\ndef generate_pattern(layer_name, filter_index, img, size=32):\n #layer의 output feature map 가져옴\n layer_output = model.get_layer(layer_name).output\n # feature map 각 channel의 mean\n loss = K.mean(layer_output[:, :, :, filter_index])\n # model input과 loss의 gradient\n grads = K.gradients(loss, model.input)[0]\n # print('grads : ', grads)\n grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)\n # print('grads : ', grads)\n iterate = K.function([model.input], [loss, grads])\n # 이게 뭔지 모르겟음\n input_img_data = img * 20 + 128.\n # input_img_data = np.random.random((1, size, size, 3)) * 20 + 128.\n step = 1.\n for i in range(80):\n loss_value, grads_value = iterate([input_img_data])\n input_img_data += grads_value * step\n\n img = input_img_data[0]\n return deprocess_image(img)\n\n\n# ------------------------------------------------------------------------------------------\n# Generating convolution layer filters for intermediate layers using above utility functions\n# ------------------------------------------------------------------------------------------\n\nlayer_name = 'activation_6'\nsize = 32\nmargin = 5\nresults = np.zeros((4 * size + 7 * margin, 8 * size + 7 * margin, 3))\n\nfor i in range(4):\n for j in range(8):\n # filter_img = generate_pattern(layer_name, i + j, img, size=size)\n # input img에 feature map 넣음\n filter_img = generate_pattern(layer_name, i + j, model.get_layer(layer_name).output, size=size)\n horizontal_start = i * size + i * margin\n horizontal_end = horizontal_start + size\n vertical_start = j * size + j * margin\n vertical_end = vertical_start + size\n results[horizontal_start: horizontal_end, vertical_start: vertical_end, :] = filter_img\n\nplt.figure(figsize=(20, 20))\nplt.title(layer_name)\nplt.imshow(results, aspect='equal')\nfile_name = layer_name + '_filter.png'\nplt.savefig(file_name)\nplt.show()" }, { "alpha_fraction": 0.6106392741203308, "alphanum_fraction": 0.6437192559242249, "avg_line_length": 36.60504150390625, "blob_id": "eff24af2cbff1e50b62455979ca17d5184a188ad", "content_id": "880f0a8ce89ea803f6228c3220a1c1234e5032a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4496, "license_type": "no_license", "max_line_length": 109, "num_lines": 119, "path": "/AE_img_conv/main.py", "repo_name": "wonnerky/ml", "src_encoding": "UTF-8", "text": "from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Flatten\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom tensorflow.keras.datasets import cifar10\n\n(x_train, _), (x_test, _) = cifar10.load_data()\n\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\n\ninput_img = Input(shape=(32, 32, 3))\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(64, (3, 3), activation='relu', padding='same')(x)\nencoded = MaxPooling2D((2, 2), padding='same')(x)\n\n# 이 시점에서 표현(representatoin)은 (4,4,8) 즉, 128 차원\n\nx = Conv2D(64, (3, 3), activation='relu', padding='same')(encoded)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\ndecoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)\n\nautoencoder = Model(input_img, decoded)\nprint(autoencoder.summary())\n# check point\ncp_path = 'cp/cp.ckpt'\ncp_dir = os.path.dirname(cp_path)\nos.makedirs(cp_dir, exist_ok=True)\n\nif os.path.isfile(cp_path):\n autoencoder.load_weights(cp_path)\n\ncpCallback = ModelCheckpoint(cp_path, verbose=0)\n\n# Train\nif not os.path.isfile(cp_path):\n autoencoder.compile(optimizer='adam', loss='mse')\n autoencoder.fit(x_train,x_train,\n epochs=50,\n batch_size=128,\n shuffle=True,\n validation_data=(x_test,x_test),\n callbacks=[cpCallback]\n )\n\n\nlayer_ = [autoencoder.layers[1],autoencoder.layers[3],autoencoder.layers[5]]\n# layer_ = [autoencoder.layers[1],autoencoder.layers[3],autoencoder.layers[5],autoencoder.layers[7],\n# autoencoder.layers[9],autoencoder.layers[11]]\nlayer_outputs = [layer.output for layer in layer_]\nactivation_model = Model(inputs=autoencoder.input, outputs=layer_outputs)\nprint(x_test[51].shape)\nprint(type(x_test[51]))\nimg = x_test[51].reshape(1,32,32,3)\nfig = plt.figure(figsize=(5,5))\nplt.imshow(img[0,:,:,:])\nplt.show()\nresult = autoencoder.predict(img)\nplt.imshow(result[0,:,:,:])\n\nactivations = activation_model.predict(img)\n\nlayer_names = []\nfor layer in layer_:\n layer_names.append(layer.name) # Names of the layers, so you can have them as part of your plot\n\nimages_per_row = 8\n\nfor layer_name, layer_activation in zip(layer_names, activations): # Displays the feature maps\n n_features = layer_activation.shape[-1] # Number of features in the feature map\n size = layer_activation.shape[1] # The feature map has shape (1, size, size, n_features).\n n_cols = n_features // images_per_row # Tiles the activation channels in this matrix\n display_grid = np.zeros((size * n_cols, images_per_row * size))\n for col in range(n_cols): # Tiles each filter into a big horizontal grid\n for row in range(images_per_row):\n channel_image = layer_activation[0, :, :, col * images_per_row + row]\n channel_image -= channel_image.mean() # Post-processes the feature to make it visually palatable\n channel_image /= (channel_image.std() + 1e-7)\n channel_image *= 64\n channel_image += 128\n channel_image = np.clip(channel_image, 0, 255).astype('uint8')\n # Displays the grid\n display_grid[col * size: (col + 1) * size, row * size: (row + 1) * size] = channel_image\n\n scale = 1. / size\n plt.figure(figsize=(scale * display_grid.shape[1],\n scale * display_grid.shape[0]))\n plt.title(layer_name)\n plt.grid(False)\n plt.imshow(display_grid, aspect='equal', cmap='viridis')\n # plt.imshow(display_grid, aspect='auto', cmap='viridis')\n\nplt.show()\n\n# plot the output from each block\n# for fmap in feature_maps:\n\t# plot all 64 maps in an 8x8 squares\n# print(K.int_shape(feature_maps))\n# ix = 1\n# for _ in range(2):\n# for _ in range(4):\n# # specify subplot and turn of axis\n# ax = plt.subplot(2, 4, ix)\n# plt.imshow(feature_maps[ix-1, :, :, 0])\n# # plot filter channel in grayscale\n# # plt.imshow(fmap[0, :, :, ix-1], cmap='gray')\n# ix += 1\n# # show the figure\n# plt.show()" }, { "alpha_fraction": 0.5456490516662598, "alphanum_fraction": 0.5948644876480103, "avg_line_length": 22.366666793823242, "blob_id": "dc96aa02ff001034063efc10f9096b8a7cd9492e", "content_id": "4d55fe5f93fe444578137453c8ed8dc74b05341c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1402, "license_type": "no_license", "max_line_length": 60, "num_lines": 60, "path": "/AE_mnist_conv/ae_mnist.py", "repo_name": "wonnerky/ml", "src_encoding": "UTF-8", "text": "from tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.layers import Dense, Input, Flatten, \\\n Reshape, LeakyReLU as LR, \\\n Activation, Dropout\nfrom tensorflow.keras.models import Model, Sequential\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train / 255.0\nx_test = x_test / 255.0\n# Plot image data from x_train\nplt.imshow(x_train[0], cmap=\"gray\")\nplt.show()\nLATENT_SIZE = 32\nencoder = Sequential([\n Flatten(input_shape=(28, 28)),\n Dense(512),\n LR(),\n Dropout(0.5),\n Dense(256),\n LR(),\n Dropout(0.5),\n Dense(128),\n LR(),\n Dropout(0.5),\n Dense(64),\n LR(),\n Dropout(0.5),\n Dense(LATENT_SIZE),\n LR()\n])\ndecoder = Sequential([\n Dense(64, input_shape=(LATENT_SIZE,)),\n LR(),\n Dropout(0.5),\n Dense(128),\n LR(),\n Dropout(0.5),\n Dense(256),\n LR(),\n Dropout(0.5),\n Dense(512),\n LR(),\n Dropout(0.5),\n Dense(784),\n Activation(\"sigmoid\"),\n Reshape((28, 28))\n])\nimg = Input(shape=(28, 28))\nlatent_vector = encoder(img)\noutput = decoder(latent_vector)\nmodel = Model(inputs=img, outputs=output)\nmodel.compile(\"nadam\", loss=\"binary_crossentropy\")\nmodel.fit(x_train,x_train,\n epochs=50,\n batch_size=128,\n shuffle=True,\n validation_data=(x_test,x_test),\n )\n" } ]
6
ThouCheese/eunt_domus
https://github.com/ThouCheese/eunt_domus
4140e43381bb34ef6010436b08b880a68f389c96
714957e171ceb6253067016ac4399a88afb1c3c4
259edb19df348d9d635fc869872af38f8a422a14
refs/heads/master
2021-09-09T18:24:40.935689
2018-03-18T21:43:11
2018-03-18T21:43:11
91,601,952
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6325420141220093, "alphanum_fraction": 0.6528189778327942, "avg_line_length": 34.47368240356445, "blob_id": "e3679ec1516a1afd67762d5ce285bfa6f0f943a6", "content_id": "08d9a15b1a15c2ac7d8b0ce1749105d2b7c482d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2022, "license_type": "no_license", "max_line_length": 80, "num_lines": 57, "path": "/main.py", "repo_name": "ThouCheese/eunt_domus", "src_encoding": "UTF-8", "text": "from os import system\nfrom time import sleep\nfrom datetime import datetime, timedelta\nfrom astral import Astral # dependency\nfrom phue import Bridge # dependency\n\n# dict that contains a bunch of city objects\nastral = Astral()\n# city object that can calculate sunrise and down, Amsterdam is close enough\ncity = astral['Amsterdam']\n# make sure the ip of the hue bridge is always the same\nip = '192.168.1.4'\n# weird ass codes\nscenes = {'bright': 'LUA5ONeFAb0I3sF', 'dim': 'ijw3l2w2wXn2p8n'}\n# wait time in seconds\nwait_time = 15 * 60\n\n\ndef activate_lights():\n # create new sun object every call with new datetime\n sun = city.sun(date=datetime.now(), local=True)\n # lights go dim after 23 'c clock\n if datetime.now().hour > 23 or datetime.now().hour < 6:\n Bridge(ip=ip).activate_scene(1, scenes['dim'])\n # lights go bright one hour before dusk\n elif datetime.now() > sun['dusk'].replace(tzinfo=None) - timedelta(hours=2):\n Bridge(ip=ip).activate_scene(1, scenes['bright'])\n\n\n# true if phone present\ndef phone_present(): return system(\"ping -c 1 192.168.1.2\") == 0\n\n\ndef remains_gone():\n checks = 3 # check three times, evenly spaced within wait_time\n for _ in range(wait_time // checks, wait_time, wait_time // checks):\n if phone_present():\n return False\n sleep(wait_time // checks)\n return True\n\n\nwas_present = False\nwhile True:\n sleep(1)\n # do nothing if the lights are already on\n if not Bridge(ip=ip).get_light(3, 'on'):\n if phone_present():\n # if the phone was already present, do not turn the lights on\n if was_present:\n sleep(wait_time) # that way I still able to turn them off\n else:\n was_present = True # mark the phone as present\n activate_lights() # turn on the appropriate light scheme\n # timeout after wait_time, if the phone remains gone,\n elif remains_gone():\n was_present = False # start listening for the phone again\n" } ]
1
Avron08Gm/sample_block_chain
https://github.com/Avron08Gm/sample_block_chain
8fb06efcfdb93a5a6241eed1c2349edf87d78572
213307627d226dcc58c8c730092f9e8be6a38077
ce40c88a2a3f05564d4829fabe938e48cda44f18
refs/heads/master
2020-03-23T17:57:26.255429
2018-07-22T09:30:54
2018-07-22T09:30:54
141,882,805
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7230769395828247, "alphanum_fraction": 0.7572649717330933, "avg_line_length": 57.599998474121094, "blob_id": "4b0c2b16bd2933e72507968528add08b898ea0c6", "content_id": "ac3788c7a0895608eed302c1ad4f789f2a92fac5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 585, "license_type": "no_license", "max_line_length": 176, "num_lines": 10, "path": "/README.md", "repo_name": "Avron08Gm/sample_block_chain", "src_encoding": "UTF-8", "text": "# sample_block_chain\n\nThis respository is regarding a simple working blockchain (built in Python) which can perform bogus transactions by simulating mining. It is only intended for testing purposes.\n\nTo test it, first two servers are needed to be running locally on different ports. Ex:\nAT : 'http://127.0.0.1:5000' AND 'http://127.0.0.1:5001' . (localhost).\n**AND** the webapp : 'flask_app.py' should be deployed on each of these servers.\nLater on, after setting up all these, the Python script : 'main_driver.py' should be executed.\n\nAll genuine pull requests are happily accepted :)" }, { "alpha_fraction": 0.6697102189064026, "alphanum_fraction": 0.6903533339500427, "avg_line_length": 34, "blob_id": "aec97f014153fbb207895961e7f8a1d2df8fd767", "content_id": "e8c2583a39872c160fbb5a16820323b339283560", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2519, "license_type": "no_license", "max_line_length": 190, "num_lines": 72, "path": "/main_driver.py", "repo_name": "Avron08Gm/sample_block_chain", "src_encoding": "UTF-8", "text": "# !!!!!!!\n\"\"\"\n BEFORE RUNNING THIS SCRIPT, ENSURE THAT TWO SERVERS ARE ALREADY RUNNING AT : 'http://127.0.0.1:5000' AND 'http://127.0.0.1:5001' . (localhost)\n\n\"\"\"\n# !!!!!!!\n\n# this entire code is there for testing the working of blockchain in localhost. It's not yet intended for computers running remotely.\n\n\nimport requests\nfrom block_chain import BlockChain\n\nblockchain = BlockChain()\nblockchain.create_genesis_block()\n\ndef register_node(node_addr , serv_addr):\n requests.post(serv_addr + '/register_node' , json = {\n 'node-address' : node_addr\n })\n\n print(' Node : {} has registered in the server : {}'.format(node_addr,serv_addr))\n\ndef create_transaction(serv_addr , data) :\n requests.post( serv_addr + '/create_transaction', json = {\n data # 'data' is a dictionary object\n } )\n \n print('Transaction has successfully completed for server : {}.'.format(serv_addr))\n\ndef mine_block(serv_addr):\n requests.get(serv_addr + '/mine_block').json()\n\n print('New block has been successfully mined for server: {}'.format(serv_addr))\n\ndef print_server_chain (serv_addr):\n response = requests.get(serv_addr + '/get_full_chain').json()\n\n print('Chain (in JSON format) for the server : {} is {}.'.format(serv_addr,response))\n\ndef sync_chain(serv_addr):\n response = requests.get(serv_addr + '/sync_chain').json()\n\n print('Chain in server : {} successfully synced.'.format(serv_addr))\n print('Result (in JSON) : {}'.format(response))\n\n# now let's assume that the port : '5000' is our server (presonal computer) and the port : '5001' is some node (reomte computer)\n\nserver = 'http://127.0.0.1:5000'\nnode = 'http://127.0.0.1:5001'\n\nregister_node(server,node)\n\n# real life transaction is not yet implemented\ncreate_transaction(server , {\n 'sender' : 'Us',\n 'reciever' : 'Someone',\n 'total_amount' : 99\n } )\n\n# by mining a new block for the node, its chain's length would increase by 1. \nmine_block(node)\n\nprint_server_chain(server) # server's chain\nprint_server_chain(node) # node's chain\n# if you notice the output, you would find that node's chain is having one more block. Its the block which was mined during the transaction\n\n# so inoreder to have consensus, all the chains involved in P2P nerwork must be synced. But, here, there is only need for syncing chain between 'node' and 'server' which are running locally.\nsync_chain(server)\n\n# now on printing the server's chain after syncing, we can see that it's same as that of node's.\nprint_server_chain(server)" }, { "alpha_fraction": 0.5760158896446228, "alphanum_fraction": 0.5802785158157349, "avg_line_length": 31.293577194213867, "blob_id": "67305bf4218aad227bf7fa0a7c5b812feb49e0b8", "content_id": "7a17acd286776d56b958f8a3177aff8bd052a5da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3519, "license_type": "no_license", "max_line_length": 218, "num_lines": 109, "path": "/block_chain.py", "repo_name": "Avron08Gm/sample_block_chain", "src_encoding": "UTF-8", "text": "from block import Block\n\n# class definition for the blockchain\nclass BlockChain:\n\n def __init__(self):\n \n self.chain = [] # list of the Block objects in the chain\n \n self.current_node_transactions = [] # transaction info going to be added to ledger\n\n self.nodes = set() # set of all the unique nodes\n\n # function to create the genesis block\n def create_genesis_block(self):\n \n self.create_new_block(proof_of_work=0,prev_hash=0)\n\n # function to create a new block and add it to the blockchain \n def create_new_block(self,proof_of_work,prev_hash):\n \n block=Block(\n index=len(self.chain),\n proof_of_work=proof_of_work,\n prev_hash=prev_hash,\n transactions=self.current_node_transactions)\n\n self.current_node_transactions = [] # transaction list is reset\n\n self.chain.append(block) # append new block to the blockchain\n\n return block\n\n # function to make new transaction\n def create_new_transaction(self,sender,reciever,total_amount):\n\n self.current_node_transactions.append({\n 'sender' : sender,\n 'reciever' : reciever,\n 'total_amount' : total_amount\n })\n \n # return the index of new block \n\n return self.get_last_block().index + 1\n \n # function to generate the proof of work for a new block\n @staticmethod\n def create_proof_of_work(prev_proof):\n\n # this is a very easy algorithm for finding proof of work : Find the sum of the number and previous proof of work number which is divisible by 13\n #--------------------------begin-----------------------------\n\n proof=prev_proof + 1\n \n while ( proof + prev_proof ) % 13 != 0 :\n proof += 1\n\n #---------------------------end-----------------------------\n # an easily computable algorithm is intentionally applied here, so that mining when testing dosen't waste too much time. However, a properly working cryptographic algorithm can also be used here instead too :) \n\n return proof\n \n # function to get the last Block object of the chain\n def get_last_block(self):\n \n return self.chain[-1]\n \n # function to mine a new block\n def mine_block(self,miner_addr):\n\n self.create_new_transaction(\n sender = '0-0-0',\n reciever = miner_addr,\n total_amount = 1\n )\n\n last_block = self.get_last_block()\n last_proof = last_block.proof_of_work\n last_hash = last_block.get_hash()\n\n new_proof = self.create_proof_of_work(last_proof)\n\n new_block = self.create_new_block( new_proof , last_hash )\n\n return vars(new_block) # return a dictionary object consisting all attributes as key , value pair \n\n # function to get the list of blocks in the form of dict\n def get_serialized_chain(self):\n\n return [vars(block) for block in self.chain]\n \n # function to create a new node\n def create_new_node(self,address):\n \n self.nodes.add(address)\n \n return True\n\n # function to return a copy of a Block object\n @staticmethod\n def get_block_copy(block_data):\n return Block (\n block_data['index'],\n block_data['proof_of_work'],\n block_data['prev_hash'],\n block_data['transactions'],\n timestamp = block_data['timestamp']\n )" }, { "alpha_fraction": 0.6216742396354675, "alphanum_fraction": 0.6275146007537842, "avg_line_length": 27.28440284729004, "blob_id": "c7dc3f65480d0dff5077ce9c7026fc0b8593a197", "content_id": "440a588200f255a9bbc076e46735e4ca09043949", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3082, "license_type": "no_license", "max_line_length": 109, "num_lines": 109, "path": "/flask_app.py", "repo_name": "Avron08Gm/sample_block_chain", "src_encoding": "UTF-8", "text": "from flask import Flask , jsonify , request , url_for\nfrom block_chain import BlockChain\nfrom uuid import uuid4\n\napp = Flask(__name__) \n\nblockchain = BlockChain()\n\nblockchain.create_genesis_block()\n\n# make a unique adddress for the current node\nnode_address = uuid4().hex\n\n# app to carry out the transaction process\[email protected]( '/make_transaction' , methods = ['POST'] )\ndef make_transaction():\n transaction_data = request.get_json()\n index = blockchain.create_new_transaction(**transaction_data)\n\n response = {\n 'message' : 'Transaction has been successfully done.',\n 'block_index' : index\n }\n\n return jsonify(response) , 201\n\n# app for mining \[email protected]( '/mine' , methods = ['GET'] )\ndef mine():\n block = blockchain.mine_block(node_address)\n\n response = {\n 'message' : 'New block successfully mined.',\n 'block_data' : block\n }\n\n return jsonify(response)\n\n# returning complete chain\[email protected]( '/full_chain' , methods = ['GET'] )\ndef get_full_chain():\n response = {\n 'chain' : blockchain.get_serialized_chain() \n }\n\n return jsonify(response)\n\n# registering a node\[email protected]( '/register_node' , methods = ['POST'] )\ndef register_node():\n node_data=request.get_json()\n\n blockchain.create_new_node(node_data.get('address'))\n \n response = {\n 'message' : 'Successfully created new node.',\n 'node_count' : len(blockchain.nodes),\n 'nodes' : list(blockchain.nodes)\n }\n\n return jsonify(response) , 201\n\ndef get_neighbour_chains():\n neighbour_chains = []\n\n for node_address in blockchain.nodes:\n response = request.get(node_address + url_for('get_full_chain')).json()\n chain = response['chain']\n neighbour_chains.append(chain)\n \n return neighbour_chains \n\n# Syncing the chain\[email protected]('/sync_chain' , methods = ['GET'])\ndef consensus():\n neighbour_chains=get_neighbour_chains()\n\n if not neighbour_chains : \n return jsonify({\n 'message' : 'No neighbouring chains are currently available.'\n })\n\n longest_chain = max(neighbour_chains , key = len)\n\n if len(blockchain.chain) >= longest_chain:\n response = {\n 'message' : 'No new blocks are there.',\n 'chain' : blockchain.get_serialized_chain()\n }\n else: # if our blockchain is not the longest, then it means new block(s) is/are there in some other chain\n blockchain.chain = [blockchain.get_block_copy( block_data ) for block_data in longest_chain]\n response = {\n 'message' : 'New block(s) is/are added.',\n 'chain' : blockchain.get_serialized_chain()\n }\n\n return jsonify(response)\n\n\n# for testing the working of 'flask_app.py' in case of any edits\n#-------------------------\nfrom argparse import ArgumentParser\nparser = ArgumentParser()\nparser.add_argument( '-H', '--host' ,default='127.0.0.1')\nparser.add_argument( '-p', '--port' ,default=5000, type=int)\nargs = parser.parse_args()\n\napp.run( host = args.host , debug = True , port = args.port )\n#--------------------------" }, { "alpha_fraction": 0.6060903668403625, "alphanum_fraction": 0.6090373396873474, "avg_line_length": 34.13793182373047, "blob_id": "1c012be9474cbef2fcd0e7f50b927dacd32985fe", "content_id": "793330b0ca9412844942a38cc6a537147003cefe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 117, "num_lines": 29, "path": "/block.py", "repo_name": "Avron08Gm/sample_block_chain", "src_encoding": "UTF-8", "text": "import time\nimport hashlib\n\n# class definition for each of the 'Block' object of the chain \nclass Block:\n\n def __init__(self,index,proof_of_work,prev_hash,transactions,timestamp = None):\n \n self.index = index # index of the block\n \n self.proof_of_work = proof_of_work # number generated after mining \n \n self.transactions = transactions # transaction list of the block\n \n self.prev_hash = prev_hash # hexdigest of the previous block\n \n if timestamp :\n self.timestamp = timestamp\n else : \n self.timestamp = time.time() # time when the block is being created\n \n\n # function to get the hashed value of the block\n def get_hash(self):\n\n # getting all the block information in one string \n block_id = '{}{}{}{}{}'.format(self.index,self.proof_of_work,self.prev_hash,self.transactions,self.timestamp)\n\n return hashlib.sha256(block_id.encode()).hexdigest()" } ]
5
tomxuetoy/Python_gambling
https://github.com/tomxuetoy/Python_gambling
db7361611ac00f7f8261af8253db427def99dd63
a4ddf93a304c0e20b4ce950e7b484eb17fdbd8e5
b43ae9d21c57b81d8a007e07fc5df9e1b0d7b104
refs/heads/master
2021-01-10T02:42:28.981554
2013-03-05T15:51:44
2013-03-05T15:51:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.41929134726524353, "alphanum_fraction": 0.43996062874794006, "avg_line_length": 33.440677642822266, "blob_id": "ef9615e6abf4df95abd2b600e8d69d356d04c9bd", "content_id": "1c3af7cde56da6d3267736a4c3814db63c36349c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2032, "license_type": "no_license", "max_line_length": 76, "num_lines": 59, "path": "/test01.py", "repo_name": "tomxuetoy/Python_gambling", "src_encoding": "UTF-8", "text": "# can play repeatly\n# from link: http://idongnou.com/2012/02/fristpython/\n\nimport random\n\nclass touzi:\n\n def u1(self):\n self.num = random.randint(1,4)\n if self.num == 1 or self.num == 3:\n print \"User:%s \\t Computer:%s \\n Draw!\" % (str,self.num)\n elif self.num == 2:\n print \"User:%s \\t Computer:%s \\n You lose !\" % (str,self.num)\n else :\n print \"User:%s \\t Computer:%s \\n You win !\" % (str,self.num)\n \n def u2(self):\n self.num = random.randint(1,4)\n if self.num == 2 or self.num == 4:\n print \"User:%s \\t Computer:%s \\n Draw!\" % (str,self.num)\n elif self.num == 3:\n print \"User:%s \\t Computer:%s \\n You lose !\" % (str,self.num)\n else :\n print \"User:%s \\t Computer:%s \\n You win !\" % (str,self.num)\n \n def u3(self):\n self.num = random.randint(1,4)\n if self.num == 1 or self.num == 3:\n print \"User:%s \\t Computer:%s \\n Draw!\" % (str,self.num)\n elif self.num == 4:\n print \"User:%s \\t Computer:%s \\n You lose !\" % (str,self.num)\n else :\n print \"User:%s \\t Computer:%s \\n You win !\" % (str,self.num)\n \n def u4(self):\n self.num = random.randint(1,4)\n if self.num == 2 or self.num == 4:\n print \"User:%s \\t Computer:%s \\n Draw!\" % (str,self.num)\n elif self.num == 1:\n print \"User:%s \\t Computer:%s \\n You lose !\" % (str,self.num)\n else :\n print \"User:%s \\t Computer:%s \\n You win !\" % (str,self.num)\n\n \nif __name__ == '__main__':\n p = touzi()\n while True:\n str = raw_input('you show: (1/2/3/4/q)')\n if str == '1':\n p.u1()\n elif str == '2':\n p.u2()\n elif str == '3':\n p.u3()\n elif str == '4':\n p.u4()\n else:\n print \"wrong!\"\n break\n" } ]
1
KavindaDasanayaka/NIBMHDCN018
https://github.com/KavindaDasanayaka/NIBMHDCN018
ce69dd038370f94b6deeff6cd6b09a777fc42116
112b2630caf6e504892b952426ca3377e85a2d4d
1150a8a21b23eb2b9ad28ccf1ae15ac3146b9c3b
refs/heads/master
2020-03-19T01:38:27.400471
2018-05-31T09:14:11
2018-05-31T09:14:11
135,560,349
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6152304410934448, "alphanum_fraction": 0.6292585134506226, "avg_line_length": 25.72222137451172, "blob_id": "5d202dd148c01519e0185741a54bea6db2e08d74", "content_id": "4ea79460a3251be97e9d1bfdc70b316be7cb8ffa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 59, "num_lines": 18, "path": "/bill.py.py", "repo_name": "KavindaDasanayaka/NIBMHDCN018", "src_encoding": "UTF-8", "text": "item_list=[]\r\nprice_list=[]\r\ndef tot(t):\r\n\tsum=0\r\n\tfor i in t:\r\n\t\tsum=float(i)\r\n\t\treturn sum\r\n\tno=int (raw_input(\"no of items :\"))\r\n\tfor i in range(no):\r\n\t\titem=str(raw_input(\"name of the item \"+str(i+1)+\":\"))\r\n\t\tprice=float(raw_input(\"price of the item \"+str(i+1)+\":\"))\r\n\t\titem_list.append(item)\r\n\t\tprice_list.append(price)\r\n\t\tdiscount=float(raw_input(\"\\n\\n enterthe discount :\"))\r\n\t\ttoatl=float(tot(price_list))\r\n\t\tdis=total*discount/100.0\r\n\t\tnet_price=toale-dis\r\n\t\tprint(\"net price\" ,net_price)\r\n" }, { "alpha_fraction": 0.5521582961082458, "alphanum_fraction": 0.5827338099479675, "avg_line_length": 22.173913955688477, "blob_id": "25dd7225075ec50c84c45469c7a3962679e87562", "content_id": "ba58f154710cf253990a91368616acc98d556a4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "no_license", "max_line_length": 64, "num_lines": 23, "path": "/xxd.py.py", "repo_name": "KavindaDasanayaka/NIBMHDCN018", "src_encoding": "UTF-8", "text": "import argparse\r\n#import binascii\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--file\", \"-f\", type = str, required = True)\r\nargs = parser.parse_args()\r\n\r\nline = 0\r\nread = 3\r\n\r\nfile = open(args.file, \"rb\")\r\nrawContent = file.read()\r\nstrContent = str(rawContent)\r\n\r\nfor c in range(0, int(len(strContent)/16)):\r\n text = \"{:#08x}\".format(line) + \" | \"\r\n text += \" \".join(\"{:02x}\".format(ord(x)) \\\r\n for x in strContent[read:read+16])\r\n text += \" | \" + strContent[read:read+32]\r\n line += 16\r\n read += 16\r\n\r\n print(text)\r\n" } ]
2
ratcht/typeracer-bot
https://github.com/ratcht/typeracer-bot
22f290afed7b201ab7f64d094139a2ee0b635ece
0cf381553cb31807433eb118bbf7c0ac7af75b5b
4a78f9a48fbcaa163341ae8fc519b18e678f6a6b
refs/heads/master
2023-04-19T23:05:48.968291
2021-05-09T23:02:35
2021-05-09T23:02:35
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6925698518753052, "alphanum_fraction": 0.7123380899429321, "avg_line_length": 34.75609588623047, "blob_id": "a3c3eb50407bbe39a835244ff80d2a2dac1add1e", "content_id": "83d30c0c5624279987051a54acb35132836bc20e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1467, "license_type": "no_license", "max_line_length": 175, "num_lines": 41, "path": "/main.py", "repo_name": "ratcht/typeracer-bot", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import NoSuchElementException \nimport time\n\n\nPATH = \"chromedriver.exe\"\ndriver = webdriver.Chrome(PATH)\n\ndriver.get(\"https://play.typeracer.com/\")\n\ndef check_exists_by_xpath(xpath):\n try:\n driver.find_element_by_xpath(xpath)\n except NoSuchElementException:\n return False\n return True\n\ntime.sleep(3)\nbody = driver.find_element_by_class_name(\"redesign\")\nbody.send_keys(Keys.CONTROL, Keys.ALT, \"O\")\n\ntime.sleep(5)\n\nfirsttext = driver.find_element_by_xpath(\"//*[@id='gwt-uid-20']/table/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/div/span[1]\").get_attribute('innerHTML')\nsecondtext = driver.find_element_by_xpath(\"//*[@id='gwt-uid-20']/table/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/div/span[2]\").get_attribute('innerHTML')\nthirdtext = \"\"\n\nif check_exists_by_xpath(\"//*[@id='gwt-uid-20']/table/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/div/span[3]\"):\n thirdtext = driver.find_element_by_xpath(\"//*[@id='gwt-uid-20']/table/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/div/span[3]\").get_attribute('innerHTML')\n\n\nfulltext = firsttext + secondtext + thirdtext\n\nprint(fulltext)\n\ninputfield = driver.find_element_by_class_name(\"txtInput\")\n\nfor i in fulltext:\n inputfield.send_keys(i)\n time.sleep(0.01) #change speed here, the smaller the number, the faster\n\n" } ]
1
itsvaibhav01/Gentle
https://github.com/itsvaibhav01/Gentle
32fe90a0a3c98ca918e7a84d3f8429907c204a40
c91a09f7220f312ced67b83c030466fdf859f6e2
8f3e9620ea302a05419777c2fb00b21d50a8dfbf
refs/heads/master
2021-05-21T02:31:39.915897
2020-04-06T05:34:23
2020-04-06T05:34:23
252,503,293
2
1
null
2020-04-02T16:05:51
2020-04-03T03:52:01
2020-04-03T03:56:11
Python
[ { "alpha_fraction": 0.6624265909194946, "alphanum_fraction": 0.6702544093132019, "avg_line_length": 27.36111068725586, "blob_id": "c5a04b728de64223600c760f3827d12775408d66", "content_id": "eb8e99b951e85ec9f5e17955f235e1fb5bcb0df1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1022, "license_type": "permissive", "max_line_length": 156, "num_lines": 36, "path": "/align.py", "repo_name": "itsvaibhav01/Gentle", "src_encoding": "UTF-8", "text": "from process import inbox , clip , string_to_txt, json_to_csv, outbox, check, cleaning\nimport os \nimport argparse\n\nparser = argparse.ArgumentParser(description='Align your subtitles in a movie by use of Deep learning library Align. Outputs srt')\n\nparser.add_argument('-m', type=str, help='movie file name' , required=True)\nparser.add_argument('-s', type=str, help='subtitles file name' , required=True)\nparser.add_argument('-o', type=str, help='output srt file', default = 'new subtitles.srt')\n\n\nif __name__ == \"__main__\": \n\n\targs = parser.parse_args()\n\tsrt = args.s\n\tmovie = args.m\n\tcut = \"cut.mkv\"\n\taudio = \"audio.mp3\"\n\tout = args.o\n\n\ttext , data = inbox(srt)\n\tlast = data[-1][0]\n\n\tclip(last, movie, cut, audio)\n\n\tstring_to_txt(text)\n\n\tos.system(\"curl -X POST -F 'audio=@{}' -F 'transcript=<{}' 'http://localhost:32768/transcriptions?async=false' -o {}\".format(audio, \"out.txt\", \"out.json\"))\n\n\tjson_to_csv(\"out.json\")\n\n\tdelay = check(out = \"out.csv\", data = data)\n\n\toutbox(srt, new = out, delay = delay)\n\n\tcleaning()\n\n" }, { "alpha_fraction": 0.7111356258392334, "alphanum_fraction": 0.7188533544540405, "avg_line_length": 32.592594146728516, "blob_id": "3b18915b0b8d2319a0504412a3abe2a127eb71b2", "content_id": "6bdb09de806e0196dba2161306a8ba071e38d2a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 907, "license_type": "permissive", "max_line_length": 169, "num_lines": 27, "path": "/README.md", "repo_name": "itsvaibhav01/Gentle", "src_encoding": "UTF-8", "text": "# Gentle - a movie subtitle alignment tool using deep learning application gentle\n---\n<b> http://lowerquality.com/gentle/ </b>\n\n### Fast run \n---\nThere are 3 files to process under align.py file <br>\n1. Need to give movie name after -m arg along with the extenstion like **-m movie.mkv**\n2. Need to give the subtitle file with -s arg like **-s movie_subtitle.srt** \n3. It is optional to give name of final adjusted subtitle file a name, by default it gives **new subtitles.srt**. If needed we can name it with **-o file_name_here.srt**\n---\n<i>A simple running example is like this:</i>\n\n~~~bash\npython3 align.py -m example_name.mkv -s subtitle.srt -o output.srt\n~~~\n---\n\n### Installation\n1. Get the dockercontainer of Gentle and keep it running (instructions inside gentle folder)\n2. Install all resources by installing resources.\n\n---\n\n### License & Copyright \n\nLicensed under the [MIT License](LICENSE).\n" } ]
2
abrown4123/Lambda-Mini-Bootcamp
https://github.com/abrown4123/Lambda-Mini-Bootcamp
f72daf888a464eb463409dc57c692b8ab49c9fe5
c8eb91b2211883eca0cc66559a073ce3ed5d0f9d
856292d5e1e6da36f69c9771e12e4ddea4648487
refs/heads/master
2021-01-09T05:41:48.836389
2017-03-21T22:50:07
2017-03-21T22:50:07
80,784,077
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7095088958740234, "alphanum_fraction": 0.7126436829566956, "avg_line_length": 24.157894134521484, "blob_id": "a371ebf2918b78a815d80ba6a69d0c65f9b02811", "content_id": "62fc7bb51d47f12e06fa00c4361fe5429d2ea6b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 957, "license_type": "no_license", "max_line_length": 78, "num_lines": 38, "path": "/my_blog/my_blog.py", "repo_name": "abrown4123/Lambda-Mini-Bootcamp", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\nimport sqlite3\n\napp = Flask(__name__)\n\nconnection = sqlite3.connect('database.db')\nprint('Open database successfully')\n\nconnection.execute('CREATE TABLE IF NOT EXISTS posts (title TEXT, post TEXT)')\nprint('Table created successfully')\nconnection.close()\n\n\[email protected]('/')\ndef index():\n\treturn render_template('home.html')\n\[email protected]('/new')\ndef new_post():\n\treturn render_template('new.html')\n\t\[email protected]('/addrecord', methods = ['POST'])\ndef addrecord():\n\tconnection = sqlite3.connect('database.db')\n\tcursor = connection.cursor()\n\t\n\ttry:\n\t\ttitle = request.form['title']\n\t\tpost = request.form['post']\n\t\tcursor.execute('INSERT INTO posts (title,post) VALUES (?,?)', (title,post))\n\t\tconnection.commit()\n\t\tmessage = 'Record successfully added'\n\texcept:\n\t\tconnection.rollback()\n\t\tmessage = 'error in insert operation'\n\tfinally:\n\t\treturn render_template('result.html', message = message)\n\t\tconnection.close()\n\t" }, { "alpha_fraction": 0.8041958212852478, "alphanum_fraction": 0.8041958212852478, "avg_line_length": 46.66666793823242, "blob_id": "2adcd27dceebbb2a169bea8d1e18d3ac56e1c5d4", "content_id": "01dfbd69d7238e42a51736ff7bc0d326cc69aa61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 143, "license_type": "no_license", "max_line_length": 118, "num_lines": 3, "path": "/README.md", "repo_name": "abrown4123/Lambda-Mini-Bootcamp", "src_encoding": "UTF-8", "text": "# Lambda-Mini-Bootcamp\n\nThrough Lambda's mini bootcamp, I created a server with python flask and got an introduction to databases with sqlite.\n" } ]
2
ManivaDigital-AB/Happicard
https://github.com/ManivaDigital-AB/Happicard
9cffe3195a2c9cac1b6547a20186dbe9a51fe7bc
2bca84683c439d0448a398d3c1883381d9bf2274
4b8fb0ea1c57c03b6836f149c5df8a00957cbbe6
refs/heads/main
2023-03-27T02:01:46.933827
2021-03-29T08:11:36
2021-03-29T08:11:36
352,580,309
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5770252346992493, "alphanum_fraction": 0.5799658298492432, "avg_line_length": 32.36392593383789, "blob_id": "5a9e266aa70885fe3ae82a3f5af64591bd4a5d92", "content_id": "cc0a6f9c51ad87e95910dd6fa7ecc6232d9ff1b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10542, "license_type": "no_license", "max_line_length": 105, "num_lines": 316, "path": "/backend/api/orders/views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework import permissions, status, generics, views\nfrom rest_framework.response import Response\nfrom drf_yasg.utils import swagger_auto_schema\nfrom drf_yasg import openapi\nfrom uuid import UUID\nimport requests\nimport stripe\nimport json\n\nfrom .serializers import (\n OrderSerializer,\n OrderItemSerializer,\n OrderListSerializer,\n OrderItemListSerializer,\n HappicardSerializer,\n PayoutSerializer,\n TransferSerializer,\n)\nfrom .models import (\n Order,\n OrderItem,\n)\n\nfrom backend.tasks import send_happicard_email_task, outbound_mms_task\nfrom backend.utils import Util\n\nDEFAULT_FROM_NUMBER = settings.DEFAULT_FROM_NUMBER\n\n\nclass OrderListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = OrderListSerializer\n queryset = Order.objects.all()\n\n\nclass OrderItemListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = OrderItemListSerializer\n queryset = OrderItem.objects.all()\n\n\nclass OrderItemCreateView(generics.CreateAPIView):\n \"\"\"\n Create Order Item View\n \"\"\"\n\n permission_classes = (permissions.AllowAny,)\n serializer_class = OrderItemSerializer\n\n def post(self, request):\n order = request.data\n serializer = self.serializer_class(data=order)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass StripePaymentIntentView(generics.GenericAPIView):\n \"\"\"\n Stripe Payment View\n \"\"\"\n\n permission_classes = (permissions.AllowAny,)\n serializer_class = OrderSerializer\n\n def post(self, request):\n order = request.data\n serializer = self.serializer_class(data=order)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n order = serializer.data\n\n current_order = Order.objects.get(id=order[\"id\"])\n total = current_order.get_order_total\n for item in current_order.items.all():\n print(item)\n try:\n for item in current_order.items.all():\n if item.giftcard:\n stripe.api_key = settings.STRIPE_DEV_STORE_SK\n else:\n stripe.api_key = settings.STRIPE_DEV_NGO_SK\n intent = stripe.PaymentIntent.create(\n amount=total,\n currency=\"sek\",\n payment_method_types=[\"card\"],\n receipt_email=current_order.email,\n )\n return Response(\n {\n \"client_secret\": intent.client_secret,\n \"order\": order,\n }\n )\n except stripe.error.CardError as e:\n body = e.json_body\n err = body.get(\"error\", {})\n print(\"Status is: %s\" % e.http_status)\n print(\"Type is: %s\" % err.get(\"type\"))\n print(\"Code is: %s\" % err.get(\"code\"))\n print(\"Message is %s\" % err.get(\"message\"))\n return Response({\"message\": err.get(\"message\")}, status=e.http_status)\n except stripe.error.RateLimitError as e:\n return Response({\"Error\": \"The API was not able to respond, try again.\"})\n except stripe.error.InvalidRequestError as e:\n return Response({\"Error\": \"Invalid parameters, unable to process payment.\"})\n except stripe.error.AuthenticationError as e:\n pass\n except stripe.error.APIConnectionError as e:\n return Response({\"Error\": \"Network communication failed, try again.\"})\n except stripe.error.StripeError as e:\n return Response({\"Error\": \"Internal Stripe Error, contact support.\"})\n except Exception as e:\n return Response({\"message\": \"Unable to process payment, try again.\"})\n\n\nclass HappicardSendView(generics.GenericAPIView):\n \"\"\"\n Happicard Send View\n \"\"\"\n\n permission_classes = (permissions.AllowAny,)\n serializer_class = HappicardSerializer\n\n def get(self, request, pk):\n\n order = Order.objects.get(id=pk)\n\n sender_name = order.first_name\n recipient_name = order.happicard_recipient_name\n recipient_email_choice = order.happicard_recipient_email_choice\n recipient_sms_choice = order.happicard_recipient_sms_choice\n personal_message = order.happicard_personal_message\n email_subject = f\"{sender_name} sent you a Happicard\"\n\n if order.happicard_personal_image:\n personal_image = order.happicard_personal_image\n if order.happicard_personal_video:\n personal_video = order.happicard_personal_video\n\n try:\n rebate_code = [\n item.match_price_choice_with_rebate for item in order.items.all()\n ].pop()\n except:\n return Response(\n {\"Error\": \"An item in your basket is missing a rebate code.\"}\n )\n\n try:\n redeem_website = [\n item.get_redeem_website for item in order.items.all()\n ].pop()\n except:\n return Response(\n {\n \"Error\": \"An item in your basket doesn't include a website for redeeming code.\"\n }\n )\n\n if recipient_email_choice and recipient_sms_choice:\n recipient_email = order.happicard_recipient_email\n confirmation = {\n \"to_email\": recipient_email,\n \"email_body\": personal_message,\n \"email_subject\": email_subject,\n }\n send_happicard_email_task.apply_async(\n args=[\n confirmation,\n recipient_name,\n rebate_code,\n redeem_website,\n ],\n eta=order.happicard_delivery_date,\n )\n recipient_number = order.happicard_recipient_number\n outbound_mms_task.apply_async(\n args=[\n recipient_number,\n DEFAULT_FROM_NUMBER,\n personal_message,\n recipient_name,\n sender_name,\n rebate_code,\n redeem_website,\n ],\n eta=order.happicard_delivery_date,\n )\n return Response(\n {\"Success\": \"Happicard email and SMS successfully sent.\"},\n status=status.HTTP_200_OK,\n )\n elif recipient_sms_choice and not recipient_email_choice:\n recipient_number = order.happicard_recipient_number\n outbound_mms_task.apply_async(\n args=[\n recipient_number,\n DEFAULT_FROM_NUMBER,\n personal_message,\n recipient_name,\n sender_name,\n rebate_code,\n redeem_website,\n ],\n eta=order.happicard_delivery_date,\n )\n return Response(\n {\"Success\": \"Happicard SMS successfully sent.\"},\n status=status.HTTP_200_OK,\n )\n else:\n recipient_email = order.happicard_recipient_email\n confirmation = {\n \"to_email\": recipient_email,\n \"email_body\": personal_message,\n \"email_subject\": email_subject,\n }\n send_happicard_email_task.apply_async(\n args=[\n confirmation,\n recipient_name,\n rebate_code,\n redeem_website,\n ],\n eta=order.happicard_delivery_date,\n )\n return Response(\n {\n \"Success\": f\"Happicard email will be successfully sent on {happicard_delivery_date}.\"\n },\n status=status.HTTP_200_OK,\n )\n\n\nclass StripePayoutView(generics.GenericAPIView):\n \"\"\"\n Stripe Payout View\n \"\"\"\n\n permission_classes = (permissions.AllowAny,)\n serializer_class = PayoutSerializer\n\n def post(self, request):\n\n payout = request.data\n serializer = self.serializer_class(data=payout)\n serializer.is_valid(raise_exception=True)\n payout = serializer.data\n current_order = Order.objects.get(id=payout.get(\"order_id\"))\n total = current_order.get_order_total\n\n payout_total = (4 * total) / 100.0\n\n try:\n payout = stripe.Payout.create(\n amount=int(payout_total),\n currency=\"sek\",\n destination=payout.get(\"destination\"),\n )\n except:\n return Response({\"Error\": \"Payout Could Not Be Processed\"})\n\n return Response(status=status.HTTP_200_OK, data=payout)\n\n\nclass StripeTransferView(generics.GenericAPIView):\n \"\"\"\n Stripe Transfer View\n \"\"\"\n\n permission_classes = (permissions.AllowAny,)\n serializer_class = TransferSerializer\n\n def post(self, request):\n\n transfer = request.data\n serializer = self.serializer_class(data=transfer)\n serializer.is_valid(raise_exception=True)\n transfer = serializer.data\n current_order = Order.objects.get(id=transfer.get(\"order_id\"))\n total = current_order.get_order_total\n\n payout_total = (4 * total) / 100.0\n\n try:\n payout = stripe.Transfer.create(\n amount=int(payout_total),\n currency=\"sek\",\n source=transfer.get(\"source\"),\n destination=transfer.get(\"destination\"),\n )\n except:\n return Response({\"Error\": \"Transfer Could Not Be Completed\"})\n\n return Response(status=status.HTTP_200_OK, data=payout)\n\n\nclass OrderItemDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = OrderItem.objects.all()\n serializer_class = OrderItemListSerializer\n\n\nclass OrderDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Order.objects.all()\n serializer_class = OrderListSerializer" }, { "alpha_fraction": 0.5250620245933533, "alphanum_fraction": 0.7096773982048035, "avg_line_length": 17.657407760620117, "blob_id": "bd8f4f06f9a67c924612fe47ea3df3178ba3c0f0", "content_id": "9000ba008c216f6719b630078bac2ea0fe5ac7f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2015, "license_type": "no_license", "max_line_length": 36, "num_lines": 108, "path": "/requirements.txt", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "amqp==5.0.5\nappdirs==1.4.4\nargcomplete==1.12.2\nasgiref==3.3.1\nbilliard==3.6.3.0\nblack==20.8b1\nboto3==1.16.45\nbotocore==1.19.45\ncelery==5.0.5\ncertifi==2020.11.8\ncffi==1.14.3\ncfn-flip==1.2.3\nchardet==3.0.4\nclick==7.1.2\nclick-didyoumean==0.0.3\nclick-plugins==1.1.1\nclick-repl==0.1.6\ncoreapi==2.3.3\ncoreschema==0.0.4\ncryptography==3.2.1\ndefusedxml==0.7.0rc1\nDjango==3.1.3\ndjango-admin-interface==0.14.2\ndjango-colorfield==0.3.2\ndjango-cors-headers==3.5.0\ndjango-countries==6.1.3\ndjango-environ==0.4.5\ndjango-filter==2.4.0\ndjango-flat-responsive==2.0\ndjango-flat-theme==1.1.4\ndjango-npm==1.0.0\ndjango-oauth-toolkit==1.3.3\ndjango-pipeline==2.0.5\ndjango-rest-auth==0.9.5\ndjango-rest-passwordreset==1.1.0\ndjango-storages==1.11.1\ndjangorestframework==3.12.2\ndjangorestframework-simplejwt==4.6.0\ndrf-social-oauth2==1.0.8\ndrf-yasg==1.20.0\ndurationpy==0.5\nfuture==0.18.2\ngunicorn==20.0.4\nhjson==3.0.2\nidna==2.10\ninflection==0.5.1\nitypes==1.2.0\nJinja2==2.11.2\njmespath==0.10.0\njsmin==2.2.2\nkappa==0.6.0\nkombu==5.0.2\nMarkupSafe==1.1.1\nmypy-extensions==0.4.3\nmysqlclient==2.0.2\noauthlib==3.1.0\nopenapi-codec==1.3.2\npackaging==20.4\nparameterized==0.7.4\npathspec==0.8.1\npem==20.1.0\nPillow==8.0.1\npip-tools==5.4.0\nplacebo==0.9.0\nprompt-toolkit==3.0.16\nprotobuf==3.14.0\npsycopg2-binary==2.8.6\npycparser==2.20\npycryptodome==3.9.9\nPyJWT==1.7.1\npyOpenSSL==20.0.1\npyparsing==2.4.7\npython-dateutil==2.8.1\npython-decouple==3.3\npython-dotenv==0.15.0\npython-slugify==4.0.1\npython3-openid==3.2.0\npytz==2020.4\nPyYAML==5.3.1\nqrcode==6.1\nregex==2020.11.13\nrequests==2.25.0\nrequests-oauthlib==1.3.0\nruamel.yaml==0.16.12\nruamel.yaml.clib==0.2.2\ns3transfer==0.3.3\nsegno==1.3.1\nsimplejson==3.17.2\nsix==1.15.0\nsocial-auth-app-django==4.0.0\nsocial-auth-core==3.3.3\nsqlparse==0.4.1\nstripe==2.55.0\ntext-unidecode==1.3\ntoml==0.10.2\ntqdm==4.55.0\ntroposphere==2.6.3\ntwilio==6.51.0\ntyped-ast==1.4.1\ntyping-extensions==3.7.4.3\nuritemplate==3.0.1\nurllib3==1.26.2\nvine==5.0.0\nwcwidth==0.2.5\nWerkzeug==0.16.1\nwsgi-request-logger==0.4.6\nxlrd==2.0.1\nzappa==0.52.0\n" }, { "alpha_fraction": 0.6698382496833801, "alphanum_fraction": 0.6841103434562683, "avg_line_length": 24.634145736694336, "blob_id": "dee7a3ddd0c0ca7e17c26070c3d5903bb3e6f460", "content_id": "d472bcd58229a3ba404e0e251f0133f3b3fdccba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1051, "license_type": "no_license", "max_line_length": 58, "num_lines": 41, "path": "/backend/settings/dev.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "\"\"\"Development Settings\"\"\"\n\nfrom .base import *\n\nALLOWED_HOSTS = [\"*\"]\nLOGGING[\"handlers\"][\"file\"][\"backupCount\"] = 1\n\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_ORIGIN_WHITELIST = [\n \"http://localhost:3000\",\n \"http://localhost:8000\",\n \"http://localhost:8080\",\n]\n\nWSGI_APPLICATION = \"backend.settings.wsgi.dev.application\"\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": os.path.join(BASE_DIR, \"db.sqlite3\"),\n }\n}\n\n# Email\nEMAIL_HOST_USER = config(\"EMAIL_DEV_HOST_USER\")\nEMAIL_HOST_PASSWORD = config(\"EMAIL_DEV_HOST_PASSWORD\")\nDEFAULT_FROM_EMAIL = config(\"DEFAULT_DEV_FROM_EMAIL\")\n\n# Twilio\nTWILIO_ACCOUNT_SID = config(\"TWILIO_ACCOUNT_SID\")\nTWILIO_AUTH_TOKEN = config(\"TWILIO_AUTH_TOKEN\")\nDEFAULT_FROM_NUMBER = config(\"TWILIO_NUMBER\")\n\n# Stripe\nSTRIPE_DEV_STORE_PK = config(\"STRIPE_DEV_STORE_PK\")\nSTRIPE_DEV_STORE_SK = config(\"STRIPE_DEV_STORE_SK\")\nSTRIPE_DEV_NGO_PK = config(\"STRIPE_DEV_NGO_PK\")\nSTRIPE_DEV_NGO_SK = config(\"STRIPE_DEV_NGO_SK\")\n\n# Celery\nBROKER_URL = config(\"CELERY_DEV_BROKER_URL\")\n" }, { "alpha_fraction": 0.7457627058029175, "alphanum_fraction": 0.7457627058029175, "avg_line_length": 18.66666603088379, "blob_id": "f762afdfa0d5910607a6afa4500c803b33e6352a", "content_id": "43f915655fcb9f16db0a174895fc2a1a77315efd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59, "license_type": "no_license", "max_line_length": 37, "num_lines": 3, "path": "/backend/settings/__init__.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from .base import *\n\nfrom .celery import app as celery_app\n" }, { "alpha_fraction": 0.7200374603271484, "alphanum_fraction": 0.7256554365158081, "avg_line_length": 31.393939971923828, "blob_id": "fc133fc06c4c0043bacb317f92423cbab3a9838d", "content_id": "0c23f9c8437d5fe5fdad3c8d94ba5c27ff32f9ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 82, "num_lines": 33, "path": "/backend/api/seo/views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework import permissions, status, generics\n\nfrom .serializers import SEOSerializer\nfrom .models import SEO\n\n\nclass SEOListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = SEO.objects.all()\n serializer_class = SEOSerializer\n\n\nclass SEOCreateView(generics.CreateAPIView):\n permission_classes = (permissions.AllowAny,)\n serializer_class = SEOSerializer\n\n def post(self, request):\n seo = request.data\n serializer = self.serializer_class(data=seo)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass SEODetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = SEO.objects.all()\n serializer_class = SEOSerializer" }, { "alpha_fraction": 0.6757678985595703, "alphanum_fraction": 0.6757678985595703, "avg_line_length": 24.521739959716797, "blob_id": "6da335a483f5da27d307ab9618f635d31899b908", "content_id": "62ce8a8f3a87911ce02076d386e164fc2b55922f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 586, "license_type": "no_license", "max_line_length": 45, "num_lines": 23, "path": "/backend/api/profiles/admin.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Store, NGO\n\n\nclass StoreAdmin(admin.ModelAdmin):\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(author=request.user)\n\n\nclass NGOAdmin(admin.ModelAdmin):\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(author=request.user)\n\n\nadmin.site.register(Store, StoreAdmin)\nadmin.site.register(NGO, NGOAdmin)" }, { "alpha_fraction": 0.6727400422096252, "alphanum_fraction": 0.6734408140182495, "avg_line_length": 26.461538314819336, "blob_id": "dd7edc185e253bc94ce1f8e52bf420450c2a1968", "content_id": "33366ce81df2fc79a55cd9229eaad8c2bdc86fdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 91, "num_lines": 52, "path": "/backend/settings/prod.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "\"\"\"Production Settings\"\"\"\n\nfrom .base import *\nfrom decouple import config\n\nALLOWED_HOSTS = [\"happicard.se\", \"www.happicard.se\"]\n\nWSGI_APPLICATION = \"backend.settings.wsgi.prod.application\"\n\nKLARNA_BASE_URL = \"https://api.klarna.com\"\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.postgresql_psycopg2\",\n \"NAME\": config(\"POSTGRES_NAME\"),\n \"USER\": config(\"POSTGRES_USER\"),\n \"PASSWORD\": config(\"POSTGRES_PASSWORD\"),\n \"HOST\": config(\"POSTGRES_HOSTNAME\"),\n \"PORT\": config(\"POSTGRES_PORT\"),\n }\n}\n\nEMAIL_HOST_USER = config(\"EMAIL_PROD_HOST_USER\")\nEMAIL_HOST_PASSWORD = config(\"EMAIL_PROD_HOST_PASSWORD\")\nDEFAULT_FROM_EMAIL = config(\"DEFAULT_PROD_FROM_EMAIL\")\n\nTWILIO_ACCOUNT_SID = config(\"TWILIO_ACCOUNT_SID\")\nTWILIO_AUTH_TOKEN = config(\"TWILIO_AUTH_TOKEN\")\nTWILIO_NUMBER = config(\"TWILIO_NUMBER\")\n\n# Stripe\nSTRIPE_PROD_PK = config(\"STRIPE_PROD_PK\")\nSTRIPE_PROD_SK = config(\"STRIPE_PROD_SK\")\n\n\n# Celery\nBROKER_URL = config(\"CELERY_PROD_BROKER_URL\")\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\",\n },\n {\n \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\",\n },\n {\n \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\",\n },\n {\n \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\",\n },\n]" }, { "alpha_fraction": 0.6718403697013855, "alphanum_fraction": 0.6729490160942078, "avg_line_length": 36.58333206176758, "blob_id": "454d3bf508a26e7f7cc75c7980070b4e11482ad7", "content_id": "775094609431fd69574edd42e97f051be9584e11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1808, "license_type": "no_license", "max_line_length": 144, "num_lines": 48, "path": "/backend/api/accounts/admin.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib import messages\nfrom django.utils.translation import ngettext\nfrom django.contrib.auth.models import Group\nfrom .models import User, Vendor, Customer, Subscriber\n\nfrom backend.utils import Util\n\n\nclass VendorAdmin(admin.ModelAdmin):\n list_display = (\"email\", \"company_name\", \"is_verified\")\n\n actions = [\"make_verified\"]\n\n def make_verified(self, request, queryset):\n rows_updated = queryset.update(is_verified=True)\n if rows_updated == 1:\n message_bit = \"1 vendor was\"\n else:\n message_bit = \"%s vendors were\" % rows_updated\n self.message_user(request, \"%s successfully verified.\" % message_bit)\n\n for q in queryset.all():\n curr_vendor = Vendor.objects.get(email=q)\n Group.objects.get(name=\"Partners\").user_set.add(curr_vendor)\n vendor_body = f\"Använd dessa autentiseringsuppgifter för att logga in på Happicard. Email: {curr_vendor.email} Password: välkommen-till-happicard\"\n vendor_data = {\n \"email_body\": vendor_body,\n \"to_email\": curr_vendor.email,\n \"email_subject\": \"Happicard inloggning och lösenord\",\n }\n if curr_vendor.is_staff == True and curr_vendor.is_verified == True:\n Util.send_email(vendor_data)\n\n make_verified.short_description = \"Verify vendors and send email\"\n\n\nadmin.site.register(User)\nadmin.site.register(Customer)\nadmin.site.register(Vendor, VendorAdmin)\nadmin.site.register(Subscriber)\n\nadmin.site.site_header = \"Happicard CMS\"\nadmin.site.site_title = \"Happicard CMS\"\nadmin.site.site_url = \"https://happicard.se/\"\nadmin.site.index_title = \"Hantera Happicard\"\nadmin.empty_value_display = \"**Empty**\"\n" }, { "alpha_fraction": 0.6191049814224243, "alphanum_fraction": 0.62530118227005, "avg_line_length": 29.740739822387695, "blob_id": "b06bc01d901c4de7e0040a7a2c7144d728d25acd", "content_id": "255403e08b3a17baea65fc001a5ccdeaf8d5def5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5854, "license_type": "no_license", "max_line_length": 87, "num_lines": 189, "path": "/backend/api/accounts/models.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib.auth.base_user import BaseUserManager\nfrom django.contrib.auth.models import AbstractBaseUser, PermissionsMixin\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils import timezone\nfrom django.db import models\nimport uuid\n\n\nSTORE_CHOICES = (\n (\"Mode\", \"Mode\"),\n (\"Mode kvinna\", \"Mode kvinna\"),\n (\"Mode herr\", \"Mode herr\"),\n (\"Hus & Hem\", \"Hus & Hem\"),\n (\"Livsmedel\", \"Livsmedel\"),\n (\"Mat & Dryck\", \"Mat & Dryck\"),\n (\"Musik, Böcker & Spel\", \"Musik, Böcker & Spel\"),\n (\"Semester & Resor\", \"Semester & Resor\"),\n (\"Underhållning & Upplevelser\", \"Underhållning & Upplevelser\"),\n (\"Annat\", \"Annat\"),\n)\n\n\nNGO_CHOICES = (\n (\"Anhörigstöd\", \"Anhörigstöd\"),\n (\"Barn\", \"Barn\"),\n (\"Bevarande projekt\", \"Bevarande projekt\"),\n (\"Fadderverksamhet\", \"Fadderverksamhet\"),\n (\"Familjer\", \"Familjer\"),\n (\"Flyktingar\", \"Flyktingar\"),\n (\"Förebyggande arbete\", \"Förebyggande arbete\"),\n (\"Föräldralösa barn\", \"Föräldralösa barn\"),\n (\"Hemlösa\", \"Hemlösa\"),\n (\"Hjälp till enskilda\", \"Hjälp till enskilda\"),\n (\"Jordbruk\", \"Jordbruk\"),\n (\"Jämställdhet\", \"Jämställdhet\"),\n (\"Katastrofhjälp\", \"Katastrofhjälp\"),\n (\"Kvinnor\", \"Kvinnor\"),\n (\"Mikrolån/Mikrokrediter\", \"Mikrolån/Mikrokrediter\"),\n (\"Personalutveckling\", \"Personalutveckling\"),\n (\"Rehabilitering\", \"Rehabilitering\"),\n (\"Rättshjälp\", \"Rättshjälp\"),\n (\"Second hand\", \"Second hand\"),\n (\"Sjukhus/Vårdhem/Äldreboende\", \"Sjukhus/Vårdhem/Äldreboende\"),\n (\"Skyddat boende\", \"Skyddat boende\"),\n (\"Telefonjour\", \"Telefonjour\"),\n (\"Ungdom\", \"Ungdom\"),\n (\"Utbildning - grund\", \"Utbildning - grund\"),\n (\"Utbildning - högre\", \"Utbildning - högre\"),\n (\"Utbildning - yrkes\", \"Utbildning - yrkes\"),\n (\"Vatten/Sanitets projekt\", \"Vatten/Sanitets projekt\"),\n (\"Verksamhet för sjuka\", \"Verksamhet för sjuka\"),\n (\"Volontärer\", \"Volontärer\"),\n (\"Vuxna\", \"Vuxna\"),\n (\"Äldre\", \"Äldre\"),\n (\"Annat\", \"Annat\"),\n)\n\n\nclass UserManager(BaseUserManager):\n \"\"\"\n Base User Manager\n \"\"\"\n\n def create_user(\n self,\n first_name,\n last_name,\n email,\n password=\"välkommen-till-happicard\",\n **extra_fields,\n ):\n \"\"\"\n Create user with the given email and password\n \"\"\"\n if not email:\n raise ValueError(\"The email must be set.\")\n first_name = first_name.capitalize()\n last_name = last_name.capitalize()\n\n user = self.model(\n first_name=first_name,\n last_name=last_name,\n email=self.normalize_email(email),\n **extra_fields,\n )\n user.set_password(password)\n user.save()\n return user\n\n def create_superuser(self, first_name, last_name, email, password, **extra_fields):\n \"\"\"\n Create superuser with the given email and password.\n \"\"\"\n extra_fields.setdefault(\"is_staff\", True)\n extra_fields.setdefault(\"is_superuser\", True)\n extra_fields.setdefault(\"is_active\", True)\n\n if extra_fields.get(\"is_staff\") is not True:\n raise ValueError(\"Superuser must have is_staff=True.\")\n if extra_fields.get(\"is_superuser\") is not True:\n raise ValueError(\"Superuser must have is_superuser=True.\")\n return self.create_user(first_name, last_name, email, password, **extra_fields)\n\n\nclass User(AbstractBaseUser, PermissionsMixin):\n \"\"\"\n Abstract User Model\n \"\"\"\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n username = None\n email = models.EmailField(max_length=255, unique=True, db_index=True)\n first_name = models.CharField(max_length=255, verbose_name=\"First name\")\n last_name = models.CharField(max_length=255, verbose_name=\"Last name\")\n is_active = models.BooleanField(default=True)\n is_staff = models.BooleanField(default=True)\n is_verified = models.BooleanField(default=False)\n published = models.DateTimeField(default=timezone.now)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n USERNAME_FIELD = \"email\"\n REQUIRED_FIELDS = [\"first_name\", \"last_name\", \"password\"]\n\n objects = UserManager()\n\n def __str__(self):\n return self.email\n\n def tokens(self):\n refresh = RefreshToken.for_user(self)\n return {\"refresh\": str(refresh), \"access\": str(refresh.access_token)}\n\n\nclass Vendor(User):\n \"\"\"\n Vendor Model\n \"\"\"\n\n phone_number = models.CharField(max_length=15, null=True, blank=True)\n company_name = models.CharField(max_length=255, null=True, blank=True)\n company_address = models.CharField(max_length=255, null=True, blank=True)\n company_role = models.CharField(max_length=255, null=True, blank=True)\n corporate_form = models.CharField(max_length=255, null=True, blank=True)\n company_store_category = models.CharField(\n max_length=100,\n choices=STORE_CHOICES,\n null=True,\n blank=True,\n verbose_name=_(\"Store Category\"),\n )\n company_ngo_category = models.CharField(\n max_length=100,\n choices=NGO_CHOICES,\n null=True,\n blank=True,\n verbose_name=_(\"NGO Category\"),\n )\n company_website = models.CharField(max_length=255, null=True, blank=True)\n comments = models.TextField(max_length=500, null=True, blank=True)\n\n def __str__(self):\n return self.email\n\n\nclass Customer(User):\n \"\"\"\n Customer Model\n \"\"\"\n\n pass\n\n\nclass Subscriber(models.Model):\n \"\"\"\n Email Subscriber Model\n \"\"\"\n\n email = models.EmailField(unique=True)\n\n def __str__(self):\n return self.email\n" }, { "alpha_fraction": 0.587400496006012, "alphanum_fraction": 0.5975539684295654, "avg_line_length": 62.72793960571289, "blob_id": "07d82e9000f3e12ed564ce210a3ad72ac71de2b6", "content_id": "0f14313e832a99d0d37395828c7c116e4fbe9f04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8667, "license_type": "no_license", "max_line_length": 161, "num_lines": 136, "path": "/backend/api/customizations/migrations/0001_initial.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-18 12:43\n\nimport backend.settings.storage_backends\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\nimport uuid\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='StorePage',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('main_store_banner_1', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('main_store_banner_2', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('main_store_banner_3', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('published', models.DateTimeField(default=django.utils.timezone.now)),\n ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='published', max_length=10)),\n ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Store Page',\n 'verbose_name_plural': 'Store Page',\n 'ordering': ('-published',),\n },\n ),\n migrations.CreateModel(\n name='PartnersPage',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('partners_page_title', models.CharField(max_length=50)),\n ('partners_page_img', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('partners_page_banner', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('partners_page_paragraph', models.TextField(max_length=500)),\n ('published', models.DateTimeField(default=django.utils.timezone.now)),\n ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='published', max_length=10)),\n ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Partners Page',\n 'verbose_name_plural': 'Partners Page',\n 'ordering': ('-published',),\n },\n ),\n migrations.CreateModel(\n name='NGOPage',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('main_ngo_banner_1', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('main_ngo_banner_2', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('main_ngo_banner_3', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('published', models.DateTimeField(default=django.utils.timezone.now)),\n ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='published', max_length=10)),\n ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'NGO Page',\n 'verbose_name_plural': 'NGO Page',\n 'ordering': ('-published',),\n },\n ),\n migrations.CreateModel(\n name='HomePage',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('home_page_carousel_img_1', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('home_page_carousel_img_2', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('home_page_carousel_img_3', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('home_page_giftcards_img', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('home_page_happioffers_img', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('home_page_campaigns_img', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('published', models.DateTimeField(default=django.utils.timezone.now)),\n ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='published', max_length=10)),\n ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Home Page',\n 'verbose_name_plural': 'Home Page',\n 'ordering': ('-published',),\n },\n ),\n migrations.CreateModel(\n name='Footer',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('footer_subscription_details', models.CharField(max_length=50)),\n ('published', models.DateTimeField(default=django.utils.timezone.now)),\n ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='published', max_length=10)),\n ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Footer',\n 'verbose_name_plural': 'Footer',\n 'ordering': ('-published',),\n },\n ),\n migrations.CreateModel(\n name='AboutPage',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('about_page_title', models.CharField(max_length=50)),\n ('about_page_title_img', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('about_page_paragraph_top', models.TextField(max_length=250)),\n ('about_page_paragraph_bottom', models.TextField(max_length=250)),\n ('about_page_process_main_title', models.CharField(max_length=50)),\n ('about_page_process_title_1', models.CharField(max_length=50)),\n ('about_page_process_paragraph_1', models.TextField(max_length=250)),\n ('about_page_process_title_2', models.CharField(max_length=50)),\n ('about_page_process_paragraph_2', models.TextField(max_length=250)),\n ('about_page_process_title_3', models.CharField(max_length=50)),\n ('about_page_process_paragraph_3', models.TextField(max_length=250)),\n ('contact_title', models.CharField(max_length=50)),\n ('contact_address', models.CharField(max_length=50)),\n ('contact_number', models.CharField(max_length=50)),\n ('contact_email', models.CharField(max_length=50)),\n ('published', models.DateTimeField(default=django.utils.timezone.now)),\n ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='published', max_length=10)),\n ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'About Page',\n 'verbose_name_plural': 'About Page',\n 'ordering': ('-published',),\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5204036831855774, "alphanum_fraction": 0.5274243354797363, "avg_line_length": 24.05494499206543, "blob_id": "5e44f427419ac80d29b62303815ec59edda8465d", "content_id": "65ea9e49e9bcdd01bcadbe99f9e42179fcc26f03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2279, "license_type": "no_license", "max_line_length": 58, "num_lines": 91, "path": "/backend/api/customizations/serializers.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import (\n HomePage,\n Footer,\n AboutPage,\n PartnersPage,\n StorePage,\n NGOPage,\n)\n\n\nclass HomePageSerializer(serializers.ModelSerializer):\n class Meta:\n model = HomePage\n fields = (\n \"id\",\n \"home_page_carousel_img_1\",\n \"home_page_carousel_img_2\",\n \"home_page_carousel_img_3\",\n \"home_page_giftcards_img\",\n \"home_page_happioffers_img\",\n \"home_page_campaigns_img\",\n )\n\n\nclass FooterSerializer(serializers.ModelSerializer):\n class Meta:\n model = Footer\n fields = (\n \"id\",\n \"footer_subscription_details\",\n \"social_media\",\n )\n depth = 2\n\n\nclass AboutPageSerializer(serializers.ModelSerializer):\n class Meta:\n model = AboutPage\n fields = (\n \"id\",\n \"about_page_title\",\n \"about_page_title_img\",\n \"about_page_paragraph_top\",\n \"about_page_paragraph_bottom\",\n \"about_page_process_main_title\",\n \"about_page_process_title_1\",\n \"about_page_process_paragraph_1\",\n \"about_page_process_title_2\",\n \"about_page_process_paragraph_2\",\n \"about_page_process_title_3\",\n \"about_page_process_paragraph_3\",\n \"contact_title\",\n \"contact_address\",\n \"contact_number\",\n \"contact_email\",\n )\n\n\nclass PartnersPageSerializer(serializers.ModelSerializer):\n class Meta:\n model = PartnersPage\n fields = (\n \"id\",\n \"partners_page_title\",\n \"partners_page_img\",\n \"partners_page_banner\",\n \"partners_page_paragraph\",\n )\n\n\nclass StorePageSerializer(serializers.ModelSerializer):\n class Meta:\n model = StorePage\n fields = (\n \"id\",\n \"main_store_banner_1\",\n \"main_store_banner_2\",\n \"main_store_banner_3\",\n )\n\n\nclass NGOPageSerializer(serializers.ModelSerializer):\n class Meta:\n model = NGOPage\n fields = (\n \"id\",\n \"main_ngo_banner_1\",\n \"main_ngo_banner_2\",\n \"main_ngo_banner_3\",\n )" }, { "alpha_fraction": 0.5884718298912048, "alphanum_fraction": 0.6300268173217773, "avg_line_length": 30.08333396911621, "blob_id": "8176efa338bc656af799fe471195e4d8e0eb5d8a", "content_id": "3d934117f69bcb04e84cc229fa82f4496babcfad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 746, "license_type": "no_license", "max_line_length": 133, "num_lines": 24, "path": "/backend/api/items/migrations/0005_auto_20210322_1716.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-22 16:16\n\nimport backend.settings.storage_backends\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('items', '0004_auto_20210319_1520'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='campaign',\n name='image',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CampaignStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='giftcard',\n name='image',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.GiftCardStorage(), upload_to=''),\n ),\n ]\n" }, { "alpha_fraction": 0.45979437232017517, "alphanum_fraction": 0.48220404982566833, "avg_line_length": 22.559005737304688, "blob_id": "b29d00bc45760e2d311db63ceb8f680545134b70", "content_id": "ddaf2b33f9894a58956d768ca085cde09e4058ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3793, "license_type": "no_license", "max_line_length": 78, "num_lines": 161, "path": "/frontend/src/components/Nav/RightNav.jsx", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "import React, { useState } from \"react\";\nimport styled from \"styled-components\";\nimport cartImg from \"../../assets/images/cart.PNG\";\nimport searchImg from \"../../assets/images/search.PNG\";\nimport facebookMobileImg from \"../../assets/images/facebook_mobile_01.PNG\";\nimport instagramMobileImg from \"../../assets/images/instagram_mobile_02.PNG\";\nimport linkedinMobileImg from \"../../assets/images/linkedin_mobile_01.PNG\";\n\nconst Ul = styled.ul`\n list-style: none;\n display: flex;\n flex-flow: row nowrap;\n\n li {\n padding: 18px 10px;\n }\n\n .selected {\n color: #000;\n }\n\n .unselected {\n color: #fff;\n }\n\n .onlyMobile {\n display: none;\n }\n\n @media (max-width: 768px) {\n flex-flow: column nowrap;\n background-color: #000;\n position: fixed;\n transform: ${({ open }) => (open ? \"translateX(0)\" : \"translateX(100%)\")};\n top: 0;\n right: 0;\n height: 100vh;\n width: 200px;\n padding-top: 3.5rem;\n transition: transform 0.3s ease-in-out;\n z-index: 10;\n\n li {\n color: #fff;\n padding: 8px;\n font-size: 16px;\n text-align: right;\n margin-right: 25px;\n }\n\n .selected {\n color: #dfb248;\n }\n\n .onlyMobile {\n display: block;\n }\n\n .paddingTop {\n padding-top: 30px;\n }\n }\n`;\n\nconst RightNav = ({ open }) => {\n const [selectedMenu, setSelectedMenu] = useState(\"Home\");\n const handleClick = (param) => {\n setSelectedMenu(param);\n };\n return (\n <>\n <Ul\n open={open}\n style={{ fontFamily: \"Helvetica Neue, Helvetica, sans-serif\" }}\n >\n <li\n className={selectedMenu == \"Home\" ? \"selected\" : \"unselected\"}\n onClick={() => handleClick(\"Home\")}\n >\n Home\n </li>\n <li\n className={selectedMenu == \"Stores\" ? \"selected\" : \"unselected\"}\n onClick={() => handleClick(\"Stores\")}\n >\n Stores\n </li>\n <li\n className={selectedMenu == \"NGOs\" ? \"selected\" : \"unselected\"}\n onClick={() => handleClick(\"NGOs\")}\n >\n NGOs\n </li>\n <li\n className={selectedMenu == \"Partners\" ? \"selected\" : \"unselected\"}\n onClick={() => handleClick(\"Partners\")}\n >\n Partners\n </li>\n <li\n className={selectedMenu == \"About\" ? \"selected\" : \"unselected\"}\n onClick={() => handleClick(\"About\")}\n >\n About\n </li>\n <li className=\"onlyMobile paddingTop\">Sign in/Sign up</li>\n <li className=\"onlyMobile\">\n <img\n src={facebookMobileImg}\n style={{\n width: \"25px\",\n backgroundColor: \"#fff\",\n borderRadius: \"27px\",\n marginLeft: \"10px\",\n }}\n />\n <img\n src={instagramMobileImg}\n style={{\n width: \"27px\",\n backgroundColor: \"#fff\",\n borderRadius: \"27px\",\n marginLeft: \"10px\",\n }}\n />\n <img\n src={linkedinMobileImg}\n style={{\n width: \"27px\",\n backgroundColor: \"#fff\",\n borderRadius: \"27px\",\n marginLeft: \"10px\",\n }}\n />\n </li>\n </Ul>\n <div style={{ marginLeft: \"15px\", marginLeft: \"100px\" }}>\n <img\n src={cartImg}\n style={{\n width: \"18px\",\n height: \"19px\",\n marginTop: \"18px\",\n marginRight: \"10px\",\n }}\n />\n <img\n src={searchImg}\n style={{\n width: \"18px\",\n height: \"19px\",\n marginTop: \"18px\",\n marginRight: \"3px\",\n }}\n />\n </div>\n </>\n );\n};\n\nexport default RightNav;\n" }, { "alpha_fraction": 0.6997166872024536, "alphanum_fraction": 0.6997166872024536, "avg_line_length": 24.285715103149414, "blob_id": "2302df80913f42c4d0d7afd0650d00c263b8fdf2", "content_id": "c0e01f6e66276f93077456b7cdea1d3fb1417041", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "no_license", "max_line_length": 45, "num_lines": 14, "path": "/backend/api/seo/admin.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import SEO, Keyword\n\n\nclass SEOAdmin(admin.ModelAdmin):\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(author=request.user)\n\n\nadmin.site.register(Keyword)\nadmin.site.register(SEO, SEOAdmin)" }, { "alpha_fraction": 0.35551315546035767, "alphanum_fraction": 0.3658367395401001, "avg_line_length": 36.425323486328125, "blob_id": "88e8a0b28705e728c9eca61ee429c76c02a27a69", "content_id": "78941ee06e53646f54bcdba024d8792c693b9110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 11527, "license_type": "no_license", "max_line_length": 79, "num_lines": 308, "path": "/frontend/src/components/footer/footer.js", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport logoImg from \"../../assets/images/logo-footer.PNG\";\nimport \"./footer.css\";\nimport giftBoxImg from \"../../assets/images/giftBox.PNG\";\nimport Copyright from \"../copyright/copyright\";\n\nconst Footer = () => {\n return (\n <div>\n <footer\n className=\"pt-4 my-md-5 pt-md-5 border-top\"\n style={{\n backgroundColor: \"#fbcc51\",\n fontFamily: \"Helvetica Neue, Helvetica, sans-serif;\",\n fontSize: \"12px\",\n }}\n >\n <div className=\"footerDesktop\">\n <div className=\"row\">\n <div className=\"col-12 col-md-3\" style={{ marginLeft: \"75px\" }}>\n <img\n className=\"mb-2\"\n src={logoImg}\n alt=\"\"\n width=\"100px\"\n height=\"25px\"\n style={{ marginLeft: \"6px\" }}\n />\n <input\n type=\"text\"\n class=\"form-control\"\n placeholder=\"Email\"\n style={{\n borderRadius: \"30px\",\n height: \"28px\",\n width: \"185px\",\n borderColor: \"white\",\n backgroundColor: \"rgb(251, 204, 81)\",\n borderWidth: \"3px\",\n fontSize: \"12px\",\n }}\n />\n <button\n style={{\n marginTop: \"10px\",\n borderColor: \"white\",\n borderWidth: \"thin\",\n marginTop: \"10px\",\n borderRadius: \"30px\",\n width: \"84px\",\n backgroundColor: \"#fff\",\n outline: \"none\",\n }}\n >\n subscribe\n </button>\n </div>\n <div className=\"col-6 col-md-2\">\n <h7 style={{ fontWeight: \"bold\" }}>Browse</h7>\n <ul\n className=\"list-unstyled text-small\"\n style={{ marginLeft: \"10px\", paddingTop: \"5px\" }}\n >\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Home\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n How it works\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Gift cards\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Happi offers\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Campaigns\n </a>\n </li>\n </ul>\n </div>\n <div className=\"col-6 col-md-2\">\n <h7 style={{ fontWeight: \"bold\" }}>About</h7>\n <ul\n className=\"list-unstyled text-small\"\n style={{ marginLeft: \"10px\", paddingTop: \"5px\" }}\n >\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n About\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n contact us\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Another resource\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Partner with us\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Reviews\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Sign in\n </a>\n </li>\n </ul>\n </div>\n <div className=\"col-6 col-md-2\">\n <h7\n style={{\n fontWeight: \"bold\",\n }}\n >\n Support\n </h7>\n <ul\n className=\"list-unstyled text-small\"\n style={{ marginLeft: \"10px\", paddingTop: \"5px\" }}\n >\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Help center\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Privacy policy\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n Terms & conditions\n </a>\n </li>\n <li style={{ marginBottom: \"5px\" }}>\n <a className=\"text-muted\" href=\"#\">\n FAQs\n </a>\n </li>\n </ul>\n </div>\n <div className=\"col-6 col-md-2\">\n <img\n src={giftBoxImg}\n style={{ height: \"58px\", marginTop: \"45px\" }}\n />\n </div>\n </div>{\" \"}\n </div>\n <div className=\"footerMobile\" style={{ display: \"none\" }}>\n <div className=\"row\">\n <div className=\"col-12 col-md\">\n <div className=\"accordion\" id=\"accordionExample\">\n <div className=\"accordion-item\">\n <h5 className=\"accordion-header\" id=\"headingOne\">\n <div\n className=\"accordion-button\"\n type=\"button\"\n data-bs-toggle=\"collapse\"\n data-bs-target=\"#collapseOne\"\n aria-expanded=\"true\"\n aria-controls=\"collapseOne\"\n style={{\n marginLeft: \"10px\",\n height: \" 50px\",\n paddingTop: \"10px\",\n paddingBottom: \"10px\",\n borderStyle: \"solid\",\n borderColor: \"#fff\",\n borderLeftStyle: \"none\",\n borderRightStyle: \"none\",\n borderTopStyle: \"none\",\n }}\n >\n Browse\n </div>\n </h5>\n <div\n id=\"collapseOne\"\n className=\"accordion-collapse collapse show\"\n aria-labelledby=\"headingOne\"\n data-bs-parent=\"#accordionExample\"\n >\n <div className=\"accordion-body\">\n <ul className=\"list-group\">\n <li className=\"list-group-item\">Home</li>\n <li className=\"list-group-item\">How it works</li>\n <li className=\"list-group-item\">Gift cards</li>\n <li className=\"list-group-item\">Happi offers</li>\n <li className=\"list-group-item\">Campaigns</li>\n </ul>\n </div>\n </div>\n </div>\n <div className=\"accordion-item\">\n <h5 className=\"accordion-header\" id=\"headingTwo\">\n <div\n className=\"accordion-button collapsed\"\n type=\"button\"\n data-bs-toggle=\"collapse\"\n data-bs-target=\"#collapseTwo\"\n aria-expanded=\"false\"\n aria-controls=\"collapseTwo\"\n style={{\n marginLeft: \"10px\",\n height: \" 50px\",\n paddingTop: \"10px\",\n paddingBottom: \"10px\",\n borderStyle: \"solid\",\n borderColor: \"#fff\",\n borderLeftStyle: \"none\",\n borderRightStyle: \"none\",\n borderTopStyle: \"none\",\n }}\n >\n About\n </div>\n </h5>\n <div\n id=\"collapseTwo\"\n className=\"accordion-collapse collapse\"\n aria-labelledby=\"headingTwo\"\n data-bs-parent=\"#accordionExample\"\n >\n <div className=\"accordion-body\">\n <ul className=\"list-group\">\n <li className=\"list-group-item\">About</li>\n <li className=\"list-group-item\">Contact us</li>\n <li className=\"list-group-item\">Partner With Us</li>\n <li className=\"list-group-item\">Reviews</li>\n <li className=\"list-group-item\">Sign In</li>\n </ul>\n </div>\n </div>\n </div>\n <div className=\"accordion-item\">\n <h5 className=\"accordion-header\" id=\"headingThree\">\n <div\n className=\"accordion-button collapsed\"\n type=\"button\"\n data-bs-toggle=\"collapse\"\n data-bs-target=\"#collapseThree\"\n aria-expanded=\"false\"\n aria-controls=\"collapseThree\"\n style={{\n marginLeft: \"10px\",\n height: \" 50px\",\n paddingTop: \"10px\",\n paddingBottom: \"10px\",\n borderBottomStyle: \"solid\",\n borderColor: \"#fff\",\n borderLeftStyle: \"none\",\n borderRightStyle: \"none\",\n borderTopStyle: \"none\",\n }}\n >\n Support\n </div>\n </h5>\n <div\n id=\"collapseThree\"\n className=\"accordion-collapse collapse\"\n aria-labelledby=\"headingThree\"\n data-bs-parent=\"#accordionExample\"\n >\n <div className=\"accordion-body\">\n {\" \"}\n <ul className=\"list-group\">\n <li className=\"list-group-item\">Help Center</li>\n <li className=\"list-group-item\">Privacy Policy</li>\n <li className=\"list-group-item\">Terms & Conditions</li>\n <li className=\"list-group-item\">FAQs</li>\n </ul>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <Copyright />\n </footer>\n </div>\n );\n};\n\nexport default Footer;\n" }, { "alpha_fraction": 0.5567282438278198, "alphanum_fraction": 0.5567282438278198, "avg_line_length": 20.05555534362793, "blob_id": "13bf73a9ee09f67c355e7b706b534d054b4b3541", "content_id": "109a6814ac89a2704bba1888015a4830df5fd9b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 379, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/frontend/src/components/Nav/Navbar.jsx", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport { Nav } from \"./Navbarstyles\";\nimport Burger from \"./Burger\";\nimport logoImg from \"../../assets/images/logo.PNG\";\n\nconst Navbar = () => {\n return (\n <Nav>\n {/* <div className=\"logo\">Nav Bar</div> */}\n <div>\n <img src={logoImg} className=\"logo\"></img>\n </div>\n <Burger />\n </Nav>\n );\n};\n\nexport default Navbar;\n" }, { "alpha_fraction": 0.5116882920265198, "alphanum_fraction": 0.53311687707901, "avg_line_length": 29.19607925415039, "blob_id": "ebc2579e0e2cbbd9b127e5b4548e14feb5ed770a", "content_id": "1ad8d8327c865cb64065763c5f4065c37258a194", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1540, "license_type": "no_license", "max_line_length": 116, "num_lines": 51, "path": "/backend/api/customizations/migrations/0003_auto_20210319_1559.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-19 14:59\n\nimport backend.settings.storage_backends\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customizations', '0002_auto_20210319_1538'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='SocialMedia',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('icon', models.FileField(storage=backend.settings.storage_backends.CustomStorage(), upload_to='')),\n ('link', models.CharField(max_length=20)),\n ],\n options={\n 'verbose_name': 'Social Media',\n 'verbose_name_plural': 'Social Media',\n },\n ),\n migrations.RemoveField(\n model_name='footer',\n name='facebook',\n ),\n migrations.RemoveField(\n model_name='footer',\n name='instagram',\n ),\n migrations.RemoveField(\n model_name='footer',\n name='linkedin',\n ),\n migrations.RemoveField(\n model_name='footer',\n name='twitter',\n ),\n migrations.RemoveField(\n model_name='footer',\n name='youtube',\n ),\n migrations.AddField(\n model_name='footer',\n name='social_media',\n field=models.ManyToManyField(blank=True, to='customizations.SocialMedia'),\n ),\n ]\n" }, { "alpha_fraction": 0.43061771988868713, "alphanum_fraction": 0.44136080145835876, "avg_line_length": 23.282608032226562, "blob_id": "a1f3070f4639125d295ac8bd307eaf01251c3f39", "content_id": "7d2b0605f36a6df2f8d5cecad2951e5e6347c0da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1117, "license_type": "no_license", "max_line_length": 54, "num_lines": 46, "path": "/backend/api/items/serializers.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import GiftCard, Campaign\n\n\nclass GiftCardSerializer(serializers.ModelSerializer):\n class Meta:\n model = GiftCard\n fields = (\n \"id\",\n \"title\",\n \"price_option_1\",\n \"price_option_2\",\n \"price_option_3\",\n \"rebate_code_1\",\n \"rebate_code_2\",\n \"rebate_code_3\",\n \"image\",\n \"description\",\n \"online\",\n \"in_store\",\n \"has_offer\",\n \"discount_price\",\n \"store_category\",\n \"created_at\",\n )\n\n\nclass CampaignSerializer(serializers.ModelSerializer):\n class Meta:\n model = Campaign\n fields = (\n \"id\",\n \"title\",\n \"price_option_1\",\n \"price_option_2\",\n \"price_option_3\",\n \"rebate_code_1\",\n \"rebate_code_2\",\n \"rebate_code_3\",\n \"image\",\n \"description\",\n \"online\",\n \"in_store\",\n \"ngo_category\",\n \"created_at\",\n )\n" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.6034858226776123, "avg_line_length": 23.157894134521484, "blob_id": "371a7a14a58eff4107adee5933001b6e3736f759", "content_id": "8bca218b391618ece2d905732fce2d420aa893ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 77, "num_lines": 19, "path": "/backend/api/customizations/migrations/0007_auto_20210319_1655.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-19 15:55\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customizations', '0006_auto_20210319_1649'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='socialmedia',\n name='link',\n field=models.CharField(blank=True, default=None, max_length=200),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5967283248901367, "alphanum_fraction": 0.6219772696495056, "avg_line_length": 36.47999954223633, "blob_id": "c1287415324bedbc0b1a16744b6071f196c8e7e7", "content_id": "67bfdd41c64660678f9082913ee7030ff2ef18f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2812, "license_type": "no_license", "max_line_length": 74, "num_lines": 75, "path": "/backend/api/orders/tests/test_views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\n\nfrom .models import Order\nfrom .serializers import OrderSerializer\n\nfrom django.conf import settings.DEFAULT_FROM_EMAIL as test_email\nfrom backend.tasks import send_happicard_email_task\n\nclass HappicardTestCase(TestCase):\n \"\"\"\n Happicard Unit Test\n \"\"\"\n\n def setUp(self):\n Order.objects.create(\n first_name=\"Test Sender\"\n happicard_recipient_myself=False,\n happicard_personal_message=\"This is a unit test\",\n happicard_recipient_email=test_email,\n happicard_recipient_name=\"Test Receiver\",\n happicard_recipient_number=\"+460720137236\",\n happicard_recipient_email_choice=True,\n happicard_recipient_sms_choice=False,\n )\n\n def test_happicard_delivery(self):\n order = Order.objects.get(happicard_recipient_name=\"Test Receiver\")\n sender_name = order.first_name\n recipient_name = order.happicard_recipient_name\n personal_message = order.happicard_personal_message\n email_subject = f\"{sender_name} sent you a Happicard\"\n\n rebate_code = \"Your Rebate Code Here\"\n redeem_website = \"Your Website Here\"\n\n recipient_email = order.happicard_recipient_email\n confirmation = {\n \"to_email\": order.happicard_recipient_email,\n \"email_body\": order.happicard_personal_message,\n \"email_subject\": email_subject,\n }\n resp = send_happicard_email_task.delay(\n confirmation, recipient_name, rebate_code, redeem_website\n )\n\n self.assertEqual(resp.status_code, status.HTTP_201_CREATED)\n\n\nclass StripePaymentIntentTestCase(APITestCase):\n\n def test_payment_intent(self):\n data = {\n \"items\": [\"eea58e2b-8b76-44f1-94e6-3d653a0048af\"], \n \"first_name\": \"testfirstname\", \n \"last_name\": \"testlastname\",\n \"email\": \"[email protected]\",\n \"phone_number\": \"+460720137236\",\n \"country\": \"SE\",\n \"region\": \"Uplands\",\n \"postcode\": \"75423\",\n \"town_or_city\": \"Uppsala\",\n \"street_address1\": \"testaddress1\",\n \"street_address2\": \"testaddress2\",\n \"happicard_recipient_myself\": False,\n \"happicard_recipient_name\": \"testhappicardname\",\n \"happicard_recipient_email_choice\" : True,\n \"happicard_recipient_email\" : \"[email protected]\",\n \"happicard_recipient_sms_choice\" : True,\n \"happicard_recipient_number\" : \"+460720137236\",\n \"happicard_personal_message\" : \"This is a test message.\",\n }\n resp = self.client.post(\"api/orders/create/stripe-payment/\", data)\n self.assertEqual(resp.status_code, status.HTTP_201_CREATED)\n\n" }, { "alpha_fraction": 0.7643678188323975, "alphanum_fraction": 0.7643678188323975, "avg_line_length": 25.303030014038086, "blob_id": "2f86e510ea7db5dcc61f0c013d9b38121ba366f6", "content_id": "fd6599ab1e874f07e83841fd61b6e924c22385c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 870, "license_type": "no_license", "max_line_length": 107, "num_lines": 33, "path": "/README.md", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Happicard\n\nTech Stack:\n* React (Frontend)\n* Django (Backend)\n* SQLite (Dev DB) / Postgresql (Prod DB)\n* AWS (Deployment)\n* Windows (Frontend Server)\n* Linux/NGINX/Gunicorn (Backend Server)\n* Stripe (Payment Service)\n* RabbitMQ (Message Broker)\n\nOur goal for Happicard is to integrate React.js within a Django app and consume a RESTful API with React.js\n\n## Back-End Development Workflow\nTo run Django on your local computer, you will need to run the following commands:\n```\npip install virtualenv \npython -m venv env\nsource env/bin/activate\npip install -r requirements.txt\npython manage.py makemigrations authentification orders payments profiles\npython manage.py migrate\npython manage.py runserver\n```\nFor running scheduled tasks with Celery workers:\n```\ncelery --app backend.settings.celery worker -l INFO\n```\n## Front-End Development Workflow\n```\nnpm install\n```\n\n\n" }, { "alpha_fraction": 0.5657225847244263, "alphanum_fraction": 0.5683853626251221, "avg_line_length": 26.91216278076172, "blob_id": "20ebb697a0cc8b6a1c77994ec430dd1571bc77c4", "content_id": "946fb31e88ca375d67208b646756cb1016772141", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4131, "license_type": "no_license", "max_line_length": 194, "num_lines": 148, "path": "/backend/utils.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.core.mail import EmailMessage, EmailMultiAlternatives\nfrom django.conf import settings\n\nfrom email.mime.image import MIMEImage\nfrom django.contrib.staticfiles import finders\nfrom functools import lru_cache\nimport threading\n\nimport os\nimport qrcode\nfrom django.template.loader import render_to_string\nfrom django.template import Context\nfrom PIL import Image\n\nfrom twilio.rest import Client\nfrom twilio.twiml.messaging_response import Body, Media, Message, MessagingResponse\n\ntwilio = Client(\n settings.TWILIO_ACCOUNT_SID,\n settings.TWILIO_AUTH_TOKEN,\n)\n\n\ndef happicard_mms_body(\n recipient_name,\n sender_name,\n personal_message,\n rebate_code,\n redeem_website,\n):\n body = f\"Hej {recipient_name}!\\nYou received a Happicard from {sender_name} who says '{personal_message}'\\nHere's your rebate code:\\n{rebate_code}\\nYou can redeem it here:\\n{redeem_website}\"\n return body\n\n\nclass EmailThread(threading.Thread):\n \"\"\"\n Speed up email\n \"\"\"\n\n def __init__(self, email):\n self.email = email\n threading.Thread.__init__(self)\n\n def run(self):\n self.email.send()\n\n\nclass Util:\n @staticmethod\n def send_email(data):\n html_content = render_to_string(\n \"basic_email.html\",\n {\n \"body\": data[\"email_body\"],\n },\n )\n email = EmailMultiAlternatives(\n subject=data[\"email_subject\"],\n body=data[\"email_body\"],\n to=[data[\"to_email\"]],\n )\n email.attach_alternative(\n html_content,\n \"text/html\",\n )\n EmailThread(email).start()\n\n @staticmethod\n def send_contactform(data):\n email = EmailMessage(\n subject=data[\"email_subject\"],\n body=data[\"email_body\"],\n to=[settings.DEFAULT_FROM_EMAIL],\n from_email=data[\"from_email\"],\n )\n EmailThread(email).start()\n\n @staticmethod\n def send_happicard_email(data, recipient_name, rebate_code, redeem_website):\n html_content = render_to_string(\n \"happicard.html\",\n {\n \"personal_message\": data[\"email_body\"],\n \"recipient_name\": recipient_name,\n \"rebate_code\": rebate_code,\n \"redeem_website\": redeem_website,\n },\n )\n email = EmailMultiAlternatives(\n subject=data[\"email_subject\"],\n body=data[\"email_body\"],\n to=[data[\"to_email\"]],\n )\n email.attach_alternative(\n html_content,\n \"text/html\",\n )\n EmailThread(email).start()\n\n @staticmethod\n def create_qrcode(photo, data):\n logo = Image.open(photo)\n basewidth = 150\n wpercent = basewidth / float(logo.size[0])\n hsize = int((float(logo.size[1]) * float(wpercent)))\n logo = logo.resize((basewidth, hsize), Image.ANTIALIAS)\n qr_big = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)\n qr_big.add_data(data)\n qr_big.make()\n img_qr_big = qr_big.make_image(fill_color=\"black\", back_color=\"orange\").convert(\n \"RGB\"\n )\n pos = (\n (img_qr_big.size[0] - logo.size[0]) // 2,\n (img_qr_big.size[1] - logo.size[1]) // 2,\n )\n img_qr_big.paste(logo, pos)\n img_qr_big.save(\"backend/api/orders/qr_data/order_qr.png\")\n\n @staticmethod\n def outbound_sms(to_number, from_number, message_body):\n twilio.messages.create(\n to=to_number,\n from_=from_number,\n body=message_body,\n )\n\n @staticmethod\n def outbound_mms(\n to_number,\n from_number,\n personal_message,\n recipient_name,\n sender_name,\n rebate_code,\n redeem_website,\n ):\n twilio.messages.create(\n to=to_number,\n from_=from_number,\n body=happicard_mms_body(\n recipient_name,\n sender_name,\n personal_message,\n rebate_code,\n redeem_website,\n ),\n )\n" }, { "alpha_fraction": 0.598630964756012, "alphanum_fraction": 0.6017423868179321, "avg_line_length": 25.78333282470703, "blob_id": "5f4e32d3a7fd45f81ee9c9d54008cb38a82181bd", "content_id": "ec742291f4d9486b1eef47878b251bdf71bce8c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1607, "license_type": "no_license", "max_line_length": 66, "num_lines": 60, "path": "/backend/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom django.urls import path, include\nfrom rest_framework import permissions, routers\nfrom drf_yasg.views import get_schema_view\nfrom drf_yasg import openapi\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Happicard API\",\n default_version=\"v2\",\n description=\"The transferral of data for Happicard\",\n terms_of_service=\"https://www.google.com/policies/terms/\",\n contact=openapi.Contact(email=\"[email protected]\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=False,\n permission_classes=[permissions.AllowAny],\n)\n\nurlpatterns = [\n path(\n \"\",\n schema_view.with_ui(\"swagger\", cache_timeout=0),\n name=\"schema-swagger-ui\",\n ),\n path(\n \"redoc/\",\n schema_view.with_ui(\"redoc\", cache_timeout=0),\n name=\"schema-redoc\",\n ),\n path(\n \"login/\",\n admin.site.urls,\n ),\n path(\n \"admin/password_reset/\",\n auth_views.PasswordResetView.as_view(),\n name=\"admin_password_reset\",\n ),\n path(\n \"admin/password_reset/done/\",\n auth_views.PasswordResetDoneView.as_view(),\n name=\"password_reset_done\",\n ),\n path(\n \"reset/<uidb64>/<token>/\",\n auth_views.PasswordResetConfirmView.as_view(),\n name=\"password_reset_confirm\",\n ),\n path(\n \"reset/done/\",\n auth_views.PasswordResetCompleteView.as_view(),\n name=\"password_reset_complete\",\n ),\n path(\n \"api/\",\n include(\"backend.api.urls\"),\n ),\n]\n" }, { "alpha_fraction": 0.5018642544746399, "alphanum_fraction": 0.5123042464256287, "avg_line_length": 22.946428298950195, "blob_id": "7d87cea78cadaa3c4281692f80f500d8f937a978", "content_id": "7450f149dd2f00411afbd1f116421b8ff0e743ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 75, "num_lines": 56, "path": "/frontend/src/index.js", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport Navbar from \"./components/Nav/Navbar\";\nimport LandingPageList from \"./components/LandingPageList/LandingPageList\";\nimport LandingImg from \"./assets/images/landing_carousel.PNG\";\nimport Slider from \"react-slick\";\n\nimport \"./index.css\";\nimport Footer from \"./components/footer/footer\";\nimport \"bootstrap/dist/css/bootstrap.min.css\";\n\nconst App = () => {\n const settings = {\n dots: true,\n infinite: true,\n speed: 500,\n slidesToShow: 1,\n slidesToScroll: 1,\n };\n return (\n <div className=\"App\">\n <div className=\"container\">\n <Navbar />\n <Slider {...settings}>\n {\" \"}\n <div>\n {\" \"}\n <img src={LandingImg} style={{ width: \"100%\" }}></img>\n </div>\n <div>\n {\" \"}\n <img src={LandingImg} style={{ width: \"100%\" }}></img>\n </div>\n <div>\n {\" \"}\n <img src={LandingImg} style={{ width: \"100%\" }}></img>\n </div>\n </Slider>\n <LandingPageList />\n <Footer />\n </div>\n\n {/* <div className=\"container\">\n <Navbar />\n\n <div className=\"row\">\n \n \n </div>\n \n </div> */}\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\"));\n" }, { "alpha_fraction": 0.524167537689209, "alphanum_fraction": 0.524167537689209, "avg_line_length": 21.190475463867188, "blob_id": "ac439c847fe72a714a1f8e70e22887134bea8445", "content_id": "810d4479203e905de85333f42ef3355ac82ad3fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 931, "license_type": "no_license", "max_line_length": 55, "num_lines": 42, "path": "/backend/api/profiles/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.urls import path, re_path\nfrom rest_framework_simplejwt import views as jwt_views\nfrom . import views\n\napp_name = \"profiles\"\nurlpatterns = [\n path(\n \"list/stores/\",\n views.StoreListView.as_view(),\n name=\"list-stores\",\n ),\n path(\n \"list/ngos/\",\n views.NGOListView.as_view(),\n name=\"list-ngos\",\n ),\n path(\n \"store/<uuid:pk>/\",\n views.StoreDetailView.as_view(),\n name=\"store-detail\",\n ),\n path(\n \"ngo/<uuid:pk>/\",\n views.NGODetailView.as_view(),\n name=\"ngo-detail\",\n ),\n path(\n \"create/store/\",\n views.StoreCreateView.as_view(),\n name=\"create-store\",\n ),\n path(\n \"create/ngo/\",\n views.NGOCreateView.as_view(),\n name=\"create-ngo\",\n ),\n re_path(\n \"search/(?P<title>.+)/$\",\n views.StoreSearchView.as_view(),\n name=\"search-stores\",\n ),\n]" }, { "alpha_fraction": 0.5411089658737183, "alphanum_fraction": 0.5418738126754761, "avg_line_length": 23.904762268066406, "blob_id": "b2df8674c3bc8a6af54eaefee593eb681fce1508", "content_id": "6cb9b034731685408e20590a0746c28ae85efd25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2615, "license_type": "no_license", "max_line_length": 59, "num_lines": 105, "path": "/backend/api/orders/serializers.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django_countries.serializer_fields import CountryField\nfrom rest_framework import serializers\n\nfrom .models import Order, OrderItem\nfrom backend.api.items.models import GiftCard, Campaign\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n class Meta:\n model = Order\n fields = (\n \"id\",\n \"items\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone_number\",\n \"happicard_recipient_myself\",\n \"happicard_recipient_name\",\n \"happicard_recipient_email_choice\",\n \"happicard_recipient_email\",\n \"happicard_recipient_sms_choice\",\n \"happicard_recipient_number\",\n \"happicard_personal_message\",\n \"happicard_delivery_date\",\n )\n\n\nclass OrderListSerializer(serializers.ModelSerializer):\n class Meta:\n model = Order\n fields = (\n \"id\",\n \"items\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone_number\",\n \"happicard_recipient_myself\",\n \"happicard_recipient_name\",\n \"happicard_recipient_email_choice\",\n \"happicard_recipient_email\",\n \"happicard_recipient_sms_choice\",\n \"happicard_recipient_number\",\n \"happicard_personal_message\",\n \"happicard_delivery_date\",\n )\n depth = 2\n\n\nclass OrderItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = OrderItem\n fields = (\n \"id\",\n \"ordered\",\n \"campaign\",\n \"giftcard\",\n \"price_choice\",\n \"quantity\",\n )\n\n\nclass OrderItemListSerializer(serializers.ModelSerializer):\n class Meta:\n model = OrderItem\n fields = (\n \"id\",\n \"ordered\",\n \"campaign\",\n \"giftcard\",\n \"price_choice\",\n \"quantity\",\n )\n depth = 2\n\n\nclass HappicardSerializer(serializers.ModelSerializer):\n class Meta:\n model = Order\n fields = (\"id\",)\n\n\nclass PayoutSerializer(serializers.Serializer):\n order_id = serializers.UUIDField()\n destination = serializers.CharField()\n\n class Meta:\n fields = (\n \"order_id\",\n \"destination\",\n )\n\n\nclass TransferSerializer(serializers.Serializer):\n order_id = serializers.UUIDField()\n source = serializers.CharField()\n destination = serializers.CharField()\n\n class Meta:\n fields = (\n \"order_id\",\n \"source\",\n \"destination\",\n )\n" }, { "alpha_fraction": 0.6055495142936707, "alphanum_fraction": 0.6104461550712585, "avg_line_length": 27.422679901123047, "blob_id": "88bf2ab226241041d30e8698d01d2b065a29cac1", "content_id": "1244c0f02c08c6f6add4d8bfc26a931613a4a31d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5514, "license_type": "no_license", "max_line_length": 82, "num_lines": 194, "path": "/backend/api/accounts/serializers.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom rest_framework.exceptions import AuthenticationFailed\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom rest_framework_simplejwt.exceptions import TokenError\nfrom django.contrib import auth\nfrom .models import Vendor, Customer, Subscriber\n\n\nclass NewsletterSerializer(serializers.ModelSerializer):\n class Meta:\n model = Subscriber\n fields = (\"email\",)\n\n\nclass VendorSerializer(serializers.ModelSerializer):\n class Meta:\n model = Vendor\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"password\",\n \"created_at\",\n \"updated_at\",\n )\n\n\nclass VendorListSerializer(serializers.ModelSerializer):\n class Meta:\n model = Vendor\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone_number\",\n \"company_name\",\n \"company_store_category\",\n \"company_ngo_category\",\n \"created_at\",\n \"updated_at\",\n )\n depth = 2\n\n\nclass CustomerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Customer\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"password\",\n \"created_at\",\n \"updated_at\",\n )\n\n\nclass VendorLoginSerializer(serializers.ModelSerializer):\n email = serializers.EmailField(max_length=255, min_length=3)\n password = serializers.CharField(max_length=68, min_length=6, write_only=True)\n tokens = serializers.CharField(max_length=68, min_length=6, read_only=True)\n\n class Meta:\n model = Vendor\n fields = (\"email\", \"password\", \"tokens\")\n\n def validate(self, attrs):\n email = attrs.get(\"email\", \"\")\n password = attrs.get(\"password\", \"\")\n\n user = auth.authenticate(email=email, password=password)\n if not user:\n raise AuthenticationFailed(\"Invalid credentials, try again\")\n if not user.is_active:\n raise AuthenticationFailed(\"Account disabled, contact admin\")\n if not user.is_verified:\n raise AuthenticationFailed(\"Email is not verified\")\n\n return {\"email\": user.email, \"tokens\": user.tokens}\n\n return super().validate(attrs)\n\n\nclass CustomerLoginSerializer(serializers.ModelSerializer):\n email = serializers.EmailField(max_length=255, min_length=3)\n password = serializers.CharField(max_length=68, min_length=6, write_only=True)\n tokens = serializers.CharField(max_length=68, min_length=6, read_only=True)\n\n class Meta:\n model = Customer\n fields = (\"email\", \"password\", \"tokens\")\n\n def validate(self, attrs):\n email = attrs.get(\"email\", \"\")\n password = attrs.get(\"password\", \"\")\n\n user = auth.authenticate(email=email, password=password)\n if not user:\n raise AuthenticationFailed(\"Invalid credentials, try again\")\n if not user.is_active:\n raise AuthenticationFailed(\"Account disabled, contact admin\")\n if not user.is_verified:\n raise AuthenticationFailed(\"Email is not verified\")\n\n return {\"email\": user.email, \"tokens\": user.tokens}\n\n return super().validate(attrs)\n\n\nclass VendorRegisterSerializer(serializers.ModelSerializer):\n class Meta:\n model = Vendor\n fields = (\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone_number\",\n \"company_name\",\n \"company_address\",\n \"company_role\",\n \"corporate_form\",\n \"company_ngo_category\",\n \"company_store_category\",\n \"company_website\",\n \"comments\",\n )\n\n def validate(self, attrs):\n email = attrs.get(\"email\", \"\")\n return attrs\n\n def create(self, validated_data):\n return Vendor.objects.create_user(**validated_data)\n\n\nclass CustomerRegisterSerializer(serializers.ModelSerializer):\n password = serializers.CharField(max_length=68, min_length=6, write_only=True)\n\n class Meta:\n\n model = Customer\n fields = (\"first_name\", \"last_name\", \"email\", \"password\")\n\n def validate(self, attrs):\n email = attrs.get(\"email\", \"\")\n return attrs\n\n def create(self, validated_data):\n return Customer.objects.create_user(**validated_data)\n\n\nclass VendorVerificationSerializer(serializers.ModelSerializer):\n choices = ((\"Yes\", \"Yes\"), (\"No\", \"No\"))\n decision = serializers.ChoiceField(choices=choices)\n\n class Meta:\n model = Vendor\n fields = (\"email\", \"decision\")\n\n\nclass CustomerEmailVerificationSerializer(serializers.ModelSerializer):\n token = serializers.CharField(max_length=555)\n\n class Meta:\n model = Customer\n fields = (\"token\",)\n\n\nclass UserLogoutSerializer(serializers.Serializer):\n refresh = serializers.CharField()\n\n default_error_message = {\"bad_token\": (\"Token is expired or invalid\")}\n\n def validate(self, attrs):\n self.token = attrs[\"refresh\"]\n return attrs\n\n def save(self, **kwargs):\n\n try:\n RefreshToken(self.token).blacklist()\n\n except TokenError:\n self.fail(\"bad_token\")\n\n\nclass ContactSerializer(serializers.Serializer):\n name = serializers.CharField()\n email = serializers.EmailField()\n subject = serializers.CharField()\n message = serializers.CharField()\n" }, { "alpha_fraction": 0.5424098968505859, "alphanum_fraction": 0.5424098968505859, "avg_line_length": 22.8869571685791, "blob_id": "8c79a26720dde5b662c47865069f0c6a7a4e6547", "content_id": "d23cc73bcd73caa5b2dad332a6b7d08187b7b9eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2747, "license_type": "no_license", "max_line_length": 55, "num_lines": 115, "path": "/backend/api/accounts/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom django.conf.urls import url, include\nfrom rest_framework_simplejwt import views as jwt_views\nfrom . import views\n\napp_name = \"accounts\"\nurlpatterns = [\n path(\n \"create/newsletter/\",\n views.NewsletterCreateView.as_view(),\n name=\"create-newsletter-sub\",\n ),\n path(\n \"list/customers/\",\n views.CustomerListView.as_view(),\n name=\"list-customers\",\n ),\n path(\n \"list/pending-vendors/\",\n views.PendingVendorListView.as_view(),\n name=\"list-pending-vendors\",\n ),\n path(\n \"list/vendors/\",\n views.VendorListView.as_view(),\n name=\"list-vendors\",\n ),\n path(\n \"list/subscribers/\",\n views.SubscriberListView.as_view(),\n name=\"list-subscribers\",\n ),\n path(\n \"customer/<uuid:pk>/\",\n views.CustomerDetailView.as_view(),\n name=\"customer-detail\",\n ),\n path(\n \"vendor/<uuid:pk>/\",\n views.VendorDetailView.as_view(),\n name=\"vendor-detail\",\n ),\n path(\n \"subscriber/<uuid:pk>/\",\n views.SubscriberDetailView.as_view(),\n name=\"subscriber-detail\",\n ),\n path(\n \"register/customer/\",\n views.CustomerRegistrationView.as_view(),\n name=\"vendor-register\",\n ),\n path(\n \"register/vendor/\",\n views.VendorRegistrationView.as_view(),\n name=\"vendor-register\",\n ),\n path(\n \"customer-verify/\",\n views.CustomerEmailVerificationView.as_view(),\n name=\"customer-verify\",\n ),\n path(\n \"subscribers/count/\",\n views.SubscriberCountView.as_view(),\n name=\"count-subscribers\",\n ),\n path(\n \"token/\",\n jwt_views.TokenObtainPairView.as_view(),\n name=\"token-obtain-pair\",\n ),\n path(\n \"token/refresh/\",\n jwt_views.TokenRefreshView.as_view(),\n name=\"token-refresh\",\n ),\n path(\n \"login/customer/\",\n views.CustomerLoginView.as_view(),\n name=\"login-customer\",\n ),\n path(\n \"login/vendor/\",\n views.VendorLoginView.as_view(),\n name=\"login-vendor\",\n ),\n path(\n \"logout/\",\n views.UserLogoutView.as_view(),\n name=\"logout\",\n ),\n path(\n \"password-reset/\",\n include(\n \"django_rest_passwordreset.urls\",\n namespace=\"password-reset\",\n ),\n ),\n path(\n \"contact/\",\n views.ContactFormView.as_view(),\n name=\"contact\",\n ),\n path(\n \"count/customers/\",\n views.CustomerCountView.as_view(),\n name=\"count-customers\",\n ),\n path(\n \"count/vendors/\",\n views.VendorCountView.as_view(),\n name=\"count-vendor\",\n ),\n]\n" }, { "alpha_fraction": 0.5278246402740479, "alphanum_fraction": 0.5902191996574402, "avg_line_length": 24.782608032226562, "blob_id": "85d33e835e18ca35dc28680fc82b82e3174dccf0", "content_id": "559f5d9d90fbd4dcc11dd3cb71e648efbb4e5aea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/backend/api/customizations/migrations/0012_auto_20210329_1003.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-29 08:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customizations', '0011_auto_20210329_1002'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='aboutpage',\n name='about_page_paragraph_bottom',\n field=models.TextField(max_length=750),\n ),\n migrations.AlterField(\n model_name='aboutpage',\n name='about_page_paragraph_top',\n field=models.TextField(max_length=750),\n ),\n ]\n" }, { "alpha_fraction": 0.6262776851654053, "alphanum_fraction": 0.6352360248565674, "avg_line_length": 27.361562728881836, "blob_id": "31f3c011084d00a729705748e7fcc3689a3fd028", "content_id": "57ff3b23d5d287dbe5c82d1984e8758b689ca753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8707, "license_type": "no_license", "max_line_length": 88, "num_lines": 307, "path": "/backend/api/customizations/models.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\nimport uuid\n\n\nfrom backend.settings.storage_backends import CustomStorage\n\nOPTIONS = (\n (\"draft\", \"Draft\"),\n (\"published\", \"Published\"),\n)\n\n\nclass HomePage(models.Model):\n \"\"\"\n Home Page Customization Model\n \"\"\"\n\n class HomePageObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n verbose_name = _(\"Home Page\")\n verbose_name_plural = _(\"Home Page\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n\n home_page_carousel_img_1 = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n home_page_carousel_img_2 = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n home_page_carousel_img_3 = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n\n home_page_giftcards_img = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n home_page_happioffers_img = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n home_page_campaigns_img = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"+\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n\n def __str__(self):\n return _(\"Home Page Anpassningar\")\n\n\nclass SocialMedia(models.Model):\n class Meta:\n verbose_name = _(\"Social Media\")\n verbose_name_plural = _(\"Social Media\")\n\n name = models.CharField(max_length=20)\n icon = models.FileField(storage=CustomStorage())\n link = models.CharField(max_length=200, blank=True)\n\n def __str__(self):\n return self.name\n\n\nclass Footer(models.Model):\n \"\"\"\n Footer Customization Model\n \"\"\"\n\n class FooterObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n verbose_name = _(\"Footer\")\n verbose_name_plural = _(\"Footer\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n\n footer_subscription_details = models.CharField(max_length=50)\n social_media = models.ManyToManyField(SocialMedia, blank=True)\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"+\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n\n def __str__(self):\n return \"Footer Anpassningar\"\n\n\nclass AboutPage(models.Model):\n \"\"\"\n About Page Customization Model\n \"\"\"\n\n class AboutPageObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n verbose_name = _(\"About Page\")\n verbose_name_plural = _(\"About Page\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n\n about_page_title = models.CharField(max_length=50)\n about_page_title_img = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n\n about_page_paragraph_top = models.TextField(max_length=750)\n about_page_paragraph_bottom = models.TextField(max_length=750)\n\n about_page_process_main_title = models.CharField(max_length=50)\n about_page_process_title_1 = models.CharField(max_length=50)\n about_page_process_paragraph_1 = models.TextField(max_length=250)\n about_page_process_title_2 = models.CharField(max_length=50)\n about_page_process_paragraph_2 = models.TextField(max_length=250)\n about_page_process_title_3 = models.CharField(max_length=50)\n about_page_process_paragraph_3 = models.TextField(max_length=250)\n\n contact_title = models.CharField(max_length=50)\n contact_address = models.CharField(max_length=50)\n contact_number = models.CharField(max_length=50)\n contact_email = models.CharField(max_length=50)\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"+\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n\n def __str__(self):\n return \"About Page Anpassningar\"\n\n\nclass PartnersPage(models.Model):\n \"\"\"\n Partners Page Customization Model\n \"\"\"\n\n class PartnersPageObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n verbose_name = _(\"Partners Page\")\n verbose_name_plural = _(\"Partners Page\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n\n partners_page_title = models.CharField(max_length=50)\n partners_page_img = models.FileField(storage=CustomStorage(), blank=True, null=True)\n partners_page_banner = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n partners_page_paragraph = models.TextField(max_length=750)\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"+\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n\n def __str__(self):\n return \"Partner Page Anpassningar\"\n\n\nclass StorePage(models.Model):\n \"\"\"\n Store Page Customization Model\n \"\"\"\n\n class StorePageObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n verbose_name = _(\"Store Page\")\n verbose_name_plural = _(\"Store Page\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n\n main_store_banner_1 = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n main_store_banner_2 = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n main_store_banner_3 = models.FileField(\n storage=CustomStorage(), blank=True, null=True\n )\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"+\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n\n def __str__(self):\n return \"Store Page Anpassningar\"\n\n\nclass NGOPage(models.Model):\n \"\"\"\n NGO Page Customization Model\n \"\"\"\n\n class NGOPageObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n verbose_name = _(\"NGO Page\")\n verbose_name_plural = _(\"NGO Page\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n\n main_ngo_banner_1 = models.FileField(storage=CustomStorage(), blank=True, null=True)\n main_ngo_banner_2 = models.FileField(storage=CustomStorage(), blank=True, null=True)\n main_ngo_banner_3 = models.FileField(storage=CustomStorage(), blank=True, null=True)\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"+\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n\n def __str__(self):\n return \"NGO Page Anpassningar\"\n" }, { "alpha_fraction": 0.5299760103225708, "alphanum_fraction": 0.6115108132362366, "avg_line_length": 22.16666603088379, "blob_id": "8fdd5e2c9fc6476d8a173eb5d6fc51f388bfb817", "content_id": "29516272796a75ff7d7da8e981dfcd3d1ecf62d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/backend/api/customizations/migrations/0010_auto_20210329_0952.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-29 07:52\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customizations', '0009_auto_20210322_1716'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='partnerspage',\n name='partners_page_paragraph',\n field=models.TextField(max_length=750),\n ),\n ]\n" }, { "alpha_fraction": 0.676239013671875, "alphanum_fraction": 0.6787401437759399, "avg_line_length": 33.60256576538086, "blob_id": "4603ecbc0e02fecc22f97f58b71ff87bfa5c6efb", "content_id": "8ba0aa3dd8b34f330f4ec95799eeec83bf840fbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10825, "license_type": "no_license", "max_line_length": 163, "num_lines": 312, "path": "/backend/api/accounts/views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from decouple import config\nfrom django.conf import settings\nfrom django.urls import reverse\nfrom django.core.mail import send_mail\nfrom django.shortcuts import redirect\nfrom rest_framework import permissions, status\nfrom rest_framework import generics, viewsets\nfrom rest_framework.response import Response\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom rest_framework import views\nfrom django.core.mail import send_mail\nfrom django.dispatch import receiver\nfrom django.urls import reverse\nfrom django_rest_passwordreset.signals import reset_password_token_created\nfrom drf_yasg.utils import swagger_auto_schema\nfrom drf_yasg import openapi\nimport jwt\n\nfrom .serializers import (\n NewsletterSerializer,\n VendorSerializer,\n VendorRegisterSerializer,\n VendorLoginSerializer,\n VendorListSerializer,\n CustomerSerializer,\n CustomerRegisterSerializer,\n CustomerLoginSerializer,\n UserLogoutSerializer,\n VendorVerificationSerializer,\n CustomerEmailVerificationSerializer,\n ContactSerializer,\n)\nfrom .models import User, Vendor, Customer, Subscriber\nfrom backend.utils import Util\n\n\nclass NewsletterCreateView(generics.CreateAPIView):\n serializer_class = NewsletterSerializer\n\n def post(self, request):\n sub = request.data\n serializer = self.serializer_class(data=sub)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n sub_data = serializer.data\n subscriber = Subscriber.objects.get(email=sub_data[\"email\"])\n email_body = \"Tack för att du registrerade dig för Happicards nyhetsbrev!\"\n data = {\n \"email_body\": email_body,\n \"to_email\": subscriber.email,\n \"email_subject\": \"Välkommen till Happicard!\",\n }\n Util.send_email(data)\n\n return Response({\"Success\": \"Email Delivered\"}, status=status.HTTP_201_CREATED)\n\n\nclass SubscriberListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Subscriber.objects.all()\n serializer_class = NewsletterSerializer\n\n\nclass VendorListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = VendorListSerializer\n queryset = Vendor.objects.filter(is_verified=True)\n\n\nclass PendingVendorListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Vendor.objects.filter(is_verified=False)\n serializer_class = VendorSerializer\n\n\nclass CustomerListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Customer.objects.all()\n serializer_class = CustomerSerializer\n\n\nclass VendorDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Vendor.objects.all()\n serializer_class = VendorSerializer\n\n\nclass CustomerDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Customer.objects.all()\n serializer_class = CustomerSerializer\n\n\nclass SubscriberDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Subscriber.objects.all()\n serializer_class = NewsletterSerializer\n\n\nclass VendorRegistrationView(generics.GenericAPIView):\n serializer_class = VendorRegisterSerializer\n\n def post(self, request):\n vendor = request.data\n serializer = self.serializer_class(data=vendor)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n form = serializer.data\n email = form[\"email\"]\n name = form[\"first_name\"]\n onboard_staff_body = f\"Denna leverantör väntar på verifiering med det här e-postmeddelandet: {email}. Uppdatera deras status nu på Happicard-adminpanelen!\"\n onboard_staff_data = {\n \"email_body\": onboard_staff_body,\n \"to_email\": settings.DEFAULT_FROM_EMAIL,\n \"email_subject\": \"Ombordstigningsprocess\",\n }\n Util.send_email(onboard_staff_data)\n onboard_vendor_body = f\"Tack för att du registrerade dig, {name}! Vår administration kommer snart tillbaka till dig för att uppdatera din partnerstatus.\"\n onboard_vendor_data = {\n \"email_body\": onboard_vendor_body,\n \"to_email\": email,\n \"email_subject\": \"Ombordstigningsprocess\",\n }\n Util.send_email(onboard_vendor_data)\n\n return Response(\n {\"Success\": \"Onboarding Emails Delivered\"}, status=status.HTTP_201_CREATED\n )\n\n\nclass CustomerRegistrationView(generics.GenericAPIView):\n serializer_class = CustomerRegisterSerializer\n\n def post(self, request):\n customer = request.data\n serializer = self.serializer_class(data=customer)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n customer_data = serializer.data\n customer = Customer.objects.get(email=customer_data[\"email\"])\n token = RefreshToken.for_user(customer).access_token\n current_site = get_current_site(request).domain\n relative_link = \"/api/auth/customer-verify/\"\n absurl = \"http://\" + current_site + relative_link + \"?token=\" + str(token)\n email_body = (\n \"Hej \"\n + customer.first_name\n + \"!\\n\\nAnvänd länken nedan för att bekräfta din email:\\n\"\n + absurl\n )\n data = {\n \"email_body\": email_body,\n \"to_email\": customer.email,\n \"email_subject\": \"Bekräfta din email\",\n }\n Util.send_email(data)\n\n return Response(customer_data, status=status.HTTP_201_CREATED)\n\n\nclass CustomerEmailVerificationView(views.APIView):\n serializer_class = CustomerEmailVerificationSerializer\n\n token_param_config = openapi.Parameter(\n \"token\",\n in_=openapi.IN_QUERY,\n description=\"Token\",\n type=openapi.TYPE_STRING,\n )\n\n @swagger_auto_schema(manual_parameters=[token_param_config])\n def get(self, request):\n token = request.GET.get(\"token\")\n try:\n payload = jwt.decode(token, settings.SECRET_KEY)\n user = Customer.objects.get(id=payload[\"user_id\"])\n if not user.is_verified:\n user.is_verified = True\n user.save()\n return Response(\n {\"Email\": \"Successfully Activated\"}, status=status.HTTP_200_OK\n )\n except jwt.ExpiredSignatureError as identifier:\n return Response(\n {\"Error\": \"Activation Expired\"}, status=status.HTTP_400_BAD_REQUEST\n )\n except jwt.exceptions.DecodeError as identifier:\n return Response(\n {\"Error\": \"Invalid Token\"}, status=status.HTTP_400_BAD_REQUEST\n )\n\n\nclass VendorLoginView(generics.GenericAPIView):\n serializer_class = VendorLoginSerializer\n\n def post(self, request):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass CustomerLoginView(generics.GenericAPIView):\n serializer_class = CustomerLoginSerializer\n\n def post(self, request):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass UserLogoutView(views.APIView):\n serializer_class = UserLogoutSerializer\n permission_classes = (permissions.AllowAny,)\n\n def post(self, request):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n@receiver(reset_password_token_created)\ndef password_reset_token_created(\n sender, instance, reset_password_token, *args, **kwargs\n):\n relative_link = \"/api/auth/password-reset/reset-password-confirm\"\n absurl = \"{}?token={}\".format(\n instance.request.build_absolute_uri(relative_link),\n reset_password_token.key,\n )\n email_body = (\n \"Hej!\\n\\nAnvänd länken nedan för att återställa ditt lösenord:\\n{}\".format(\n absurl\n )\n )\n data = {\n \"email_body\": email_body,\n \"to_email\": reset_password_token.user.email,\n \"email_subject\": \"Återställ lösenord för {title}\".format(title=\"Happicard\"),\n }\n Util.send_email(data)\n\n return Response({\"Email\": \"Successfully Sent\"})\n\n\nclass ContactFormView(generics.GenericAPIView):\n serializer_class = ContactSerializer\n permission_classes = (permissions.AllowAny,)\n\n def post(self, request):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n contact = serializer.data\n from_email = contact.get(\"email\")\n contact_subject = contact.get(\"subject\")\n contact_message = contact.get(\"message\")\n contact_data = {\n \"email_body\": contact_message,\n \"email_subject\": contact_subject,\n \"from_email\": from_email,\n }\n Util.send_contactform(contact_data)\n # confirm email\n confirm_data = {\n \"email_body\": \"Vi återkommer så snart som möjligt.\",\n \"to_email\": from_email,\n \"email_subject\": \"Tack för att du kontaktade oss!\",\n }\n Util.send_email(confirm_data)\n return Response({\"Contact Form\": \"Successfully Sent\"})\n\n\nclass SubscriberCountView(generics.GenericAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = NewsletterSerializer\n\n def get(self, request, format=None):\n subscriber_count = Subscriber.objects.count()\n data = {\"Subscriber Count\": subscriber_count}\n return Response(data)\n\n\nclass VendorCountView(generics.GenericAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = VendorSerializer\n\n def get(self, request, format=None):\n vendor_count = Vendor.objects.count()\n data = {\"Vendor Count\": vendor_count}\n return Response(data)\n\n\nclass CustomerCountView(generics.GenericAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = CustomerSerializer\n\n def get(self, request, format=None):\n customer_count = Customer.objects.count()\n data = {\"Customer Count\": customer_count}\n return Response(data)" }, { "alpha_fraction": 0.6083750128746033, "alphanum_fraction": 0.6189096570014954, "avg_line_length": 44.2023811340332, "blob_id": "b70ead318ede5068bafb976a897ca8ad704078a6", "content_id": "9fcad90393052f43321518904f2e42f4c4c4a9a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3797, "license_type": "no_license", "max_line_length": 131, "num_lines": 84, "path": "/backend/api/customizations/migrations/0009_auto_20210322_1716.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-22 16:16\n\nimport backend.settings.storage_backends\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customizations', '0008_auto_20210322_1624'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='homepage',\n name='home_page_campaigns_img',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='homepage',\n name='home_page_carousel_img_1',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='homepage',\n name='home_page_carousel_img_2',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='homepage',\n name='home_page_carousel_img_3',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='homepage',\n name='home_page_giftcards_img',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='homepage',\n name='home_page_happioffers_img',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='ngopage',\n name='main_ngo_banner_1',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='ngopage',\n name='main_ngo_banner_2',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='ngopage',\n name='main_ngo_banner_3',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='partnerspage',\n name='partners_page_banner',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='partnerspage',\n name='partners_page_img',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='storepage',\n name='main_store_banner_1',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='storepage',\n name='main_store_banner_2',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='storepage',\n name='main_store_banner_3',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n ]\n" }, { "alpha_fraction": 0.5078125, "alphanum_fraction": 0.5078125, "avg_line_length": 17.33333396911621, "blob_id": "321c05220b71c39983703f473487f2bce9b755bd", "content_id": "8c56493e0a25ed2bf23b002f0387c4981ae965d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 384, "license_type": "no_license", "max_line_length": 38, "num_lines": 21, "path": "/backend/api/seo/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = \"seo\"\nurlpatterns = [\n path(\n \"list/\",\n views.SEOListView.as_view(),\n name=\"list-seo\",\n ),\n path(\n \"create/\",\n views.SEOCreateView.as_view(),\n name=\"create-seo\",\n ),\n path(\n \"detail/\",\n views.SEODetailView.as_view(),\n name=\"detail-seo\",\n ),\n]" }, { "alpha_fraction": 0.5939849615097046, "alphanum_fraction": 0.652255654335022, "avg_line_length": 27, "blob_id": "1eff63cce76eb19b58a3df3e8a268871ab9f1161", "content_id": "a3dbd4a5d35496afd57fc33996c6f76e8f8a0263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 131, "num_lines": 19, "path": "/backend/api/customizations/migrations/0008_auto_20210322_1624.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-22 15:24\n\nimport backend.settings.storage_backends\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customizations', '0007_auto_20210319_1655'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='aboutpage',\n name='about_page_title_img',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.CustomStorage(), upload_to=''),\n ),\n ]\n" }, { "alpha_fraction": 0.7451573610305786, "alphanum_fraction": 0.7451573610305786, "avg_line_length": 26.098360061645508, "blob_id": "81741537acbdfc02782e8e1879ab3c4a49797a90", "content_id": "b971f17a956659a3a1e327ae052080f3316b8bab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1652, "license_type": "no_license", "max_line_length": 56, "num_lines": 61, "path": "/backend/api/customizations/views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework import permissions, status, generics\n\nfrom .serializers import (\n HomePageSerializer,\n FooterSerializer,\n AboutPageSerializer,\n PartnersPageSerializer,\n StorePageSerializer,\n NGOPageSerializer,\n)\nfrom .models import (\n HomePage,\n Footer,\n AboutPage,\n PartnersPage,\n StorePage,\n NGOPage,\n)\n\n\nclass HomePageListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = HomePage.objects.all()\n serializer_class = HomePageSerializer\n\n\nclass FooterListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Footer.objects.all()\n serializer_class = FooterSerializer\n\n\nclass AboutPageListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = AboutPage.objects.all()\n serializer_class = AboutPageSerializer\n\n\nclass PartnersPageListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = PartnersPage.objects.all()\n serializer_class = PartnersPageSerializer\n\n\nclass StorePageListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = StorePage.objects.all()\n serializer_class = StorePageSerializer\n\n\nclass NGOPageListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = NGOPage.objects.all()\n serializer_class = NGOPageSerializer" }, { "alpha_fraction": 0.5382830500602722, "alphanum_fraction": 0.5382830500602722, "avg_line_length": 18.613636016845703, "blob_id": "1af4336118dea73ad1e1844998b65e68c01fb865", "content_id": "a3d366a84ce0fd5ff0d5dbbd8e6fed1ae079b40a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 43, "num_lines": 44, "path": "/backend/api/orders/admin.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Order, OrderItem\n\n\nclass OrderAdmin(admin.ModelAdmin):\n\n readonly_fields = (\n \"id\",\n \"date\",\n )\n\n fields = (\n \"id\",\n \"user\",\n \"items\",\n \"date\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone_number\",\n \"happicard_recipient_myself\",\n \"happicard_recipient_name\",\n \"happicard_recipient_email_choice\",\n \"happicard_recipient_email\",\n \"happicard_recipient_sms_choice\",\n \"happicard_recipient_number\",\n \"happicard_personal_message\",\n \"happicard_delivery_date\",\n )\n\n list_display = (\n \"id\",\n \"user\",\n \"date\",\n \"first_name\",\n \"last_name\",\n )\n\n ordering = (\"-date\",)\n\n\nadmin.site.register(Order, OrderAdmin)\nadmin.site.register(OrderItem)" }, { "alpha_fraction": 0.4493190050125122, "alphanum_fraction": 0.46881720423698425, "avg_line_length": 27.94190788269043, "blob_id": "01780eff6863e0472df740423db8b2282a7a93a7", "content_id": "cbaa74a7a5f0e67ed24440a27775d3064bf642c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6975, "license_type": "no_license", "max_line_length": 79, "num_lines": 241, "path": "/frontend/src/components/LandingPageList/LandingPageList.js", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "import React, { useState } from \"react\";\nimport giftImg from \"../../assets/images/gift_card_01.PNG\";\nimport offersImg from \"../../assets/images/happi_offers_02.PNG\";\nimport giftCardListImg from \"../../assets/images/gift_card_list_01.PNG\";\nimport happiOffersListImg from \"../../assets/images/happi_offers_list_01.PNG\";\nimport campaignsListImg from \"../../assets/images/campaigns_image_list_01.PNG\";\nimport styled from \"styled-components\";\nimport ProductList from \"../../components/productList/productList\";\n\nconst Button = styled.button`\n /* Adapt the colors based on primary prop */\n background: white};\n color: black;\n\n font-size: 1em;\n font-weight: bold;\n font-family: Helvetica Neue, Helvetica, sans-serif;\n\n margin: 1em;\n padding: 0.25em 1em;\n border: 2px solid #DFB248;\n border-radius: 28px;\n width: 140px;\n outline: none;\n`;\n\nconst ListImg = styled.img`\n width: 350px;\n padding: 5px 5px 5px 5px;\n @media only screen and (max-width: 600px) {\n width: 200px;\n }\n`;\n\nconst LandingPageList = () => {\n const [displayGiftCards, setDisplayGiftCards] = useState(false);\n const [displayHappiOffers, setDisplayHappiOffers] = useState(false);\n const [displayCampaigns, setDisplayCampaigns] = useState(false);\n\n const clickGiftCards = () => {\n if (displayGiftCards) {\n setDisplayGiftCards(false);\n } else {\n setDisplayGiftCards(true);\n }\n setDisplayHappiOffers(false);\n setDisplayCampaigns(false);\n };\n\n const clickHappiOffers = () => {\n if (displayHappiOffers) {\n setDisplayHappiOffers(false);\n } else {\n setDisplayHappiOffers(true);\n }\n setDisplayGiftCards(false);\n setDisplayCampaigns(false);\n };\n\n const clickCampaigns = () => {\n if (displayCampaigns) {\n setDisplayCampaigns(false);\n } else {\n setDisplayCampaigns(true);\n }\n setDisplayGiftCards(false);\n setDisplayHappiOffers(false);\n };\n\n function Test(props) {\n return (\n <div className=\"row\" style={{ textAlign: \"center\" }}>\n <div className=\"col-sm-4\">\n <div className=\"card\" style={{ borderRadius: \"0.65rem\" }}>\n <div className=\"card-body\">\n <h6 className=\"card-title\" style={{ color: \"red\" }}>\n {props.name}\n </h6>\n <img\n src={props.image}\n width=\"300\"\n height=\"150\"\n style={{ borderRadius: \"0.65rem\" }}\n />\n <p\n className=\"card-text\"\n style={{\n paddingTop: \"10px\",\n fontSize: \"12px\",\n wordSpacing: \"6px\",\n letterSpacing: \"0.2px\",\n color: \"grey\",\n fontFamily: \"Helvetica Neue, Helvetica, sans-serif\",\n }}\n >\n {props.title}\n </p>\n </div>\n </div>\n </div>\n <div className=\"col-sm-4\">\n <div className=\"card\" style={{ borderRadius: \"0.65rem\" }}>\n <div className=\"card-body\">\n <h6 className=\"card-title\" style={{ color: \"red\" }}>\n {props.name}\n </h6>\n <img\n src={props.image}\n width=\"300\"\n height=\"150\"\n style={{ borderRadius: \"0.65rem\" }}\n />\n <p\n className=\"card-text\"\n style={{\n paddingTop: \"10px\",\n fontSize: \"12px\",\n wordSpacing: \"6px\",\n letterSpacing: \"0.2px\",\n color: \"grey\",\n fontFamily: \"Helvetica Neue, Helvetica, sans-serif\",\n }}\n >\n {props.title}\n </p>\n </div>\n </div>\n </div>\n <div className=\"col-sm-4\">\n <div className=\"card\" style={{ borderRadius: \"0.65rem\" }}>\n <div className=\"card-body\">\n <h6 className=\"card-title\" style={{ color: \"red\" }}>\n {props.name}\n </h6>\n <img\n src={props.image}\n width=\"300\"\n height=\"150\"\n style={{ borderRadius: \"0.65rem\" }}\n />\n <p\n className=\"card-text\"\n style={{\n paddingTop: \"10px\",\n fontSize: \"12px\",\n wordSpacing: \"6px\",\n letterSpacing: \"0.2px\",\n color: \"grey\",\n fontFamily: \"Helvetica Neue, Helvetica, sans-serif\",\n }}\n >\n {props.title}\n </p>\n </div>\n </div>\n </div>\n </div>\n );\n }\n\n return (\n <>\n <div className=\"row\" style={{ paddingTop: \"75px\" }}>\n <div className=\"col-sm\">\n <div style={{ textAlign: \"center\" }}>\n <ListImg\n src={giftImg}\n // style={{ width: \"350px\", padding: \"5px 5px 5px 5px\" }}\n />\n <Button\n onClick={clickGiftCards}\n style={{\n backgroundColor: displayGiftCards ? \"#dfb248\" : \"\",\n outline: \"none\",\n }}\n >\n Gift cards\n </Button>\n </div>\n </div>\n <div className=\"col-sm\">\n <div style={{ textAlign: \"center\" }}>\n <ListImg\n src={offersImg}\n // style={{ width: \"350px\", padding: \"5px 5px 5px 5px\" }}\n />\n <Button\n onClick={clickHappiOffers}\n style={{\n backgroundColor: displayHappiOffers ? \"#dfb248\" : \"\",\n outline: \"none\",\n }}\n >\n Happi offers\n </Button>\n </div>\n </div>\n <div className=\"col-sm\">\n <div style={{ textAlign: \"center\" }}>\n <ListImg\n src={giftImg}\n // style={{ width: \"350px\", padding: \"5px 5px 5px 5px\" }}\n />\n <Button\n onClick={clickCampaigns}\n style={{\n backgroundColor: displayCampaigns ? \"#dfb248\" : \"\",\n outline: \"none\",\n }}\n >\n Campaigns\n </Button>\n </div>\n </div>\n </div>\n {displayGiftCards && (\n <Test\n name=\"Gift card title\"\n image={giftCardListImg}\n title=\"Category:Fashion | Online \"\n />\n )}\n {displayHappiOffers && (\n <Test\n name=\"Happi offers title\"\n image={happiOffersListImg}\n title=\"Category:Fashion | Online+In-store \"\n />\n )}\n {displayCampaigns && (\n <Test\n name=\"Campaigns title\"\n image={campaignsListImg}\n title=\"Category:Non profit Organizations \"\n />\n )}\n </>\n );\n};\n\nexport default LandingPageList;\n" }, { "alpha_fraction": 0.5387523770332336, "alphanum_fraction": 0.5746691823005676, "avg_line_length": 24.190475463867188, "blob_id": "163e016279cd7cb11488e04ac7569fcc7f56999d", "content_id": "da3be308f795b97ecb5c9acde94c4aad868035c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 529, "license_type": "no_license", "max_line_length": 84, "num_lines": 21, "path": "/backend/api/seo/migrations/0002_auto_20210318_1343.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-18 12:43\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('seo', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='keyword',\n options={'verbose_name': 'Keyword', 'verbose_name_plural': 'Keywords'},\n ),\n migrations.AlterModelOptions(\n name='seo',\n options={'verbose_name': 'Metadata', 'verbose_name_plural': 'Metadata'},\n ),\n ]\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 29.5, "blob_id": "21c5ced81e24ce8a1264ac3fbb47ff69dee441d1", "content_id": "103daa1662c8e1f7688d11119d74b236cf972a0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 65, "num_lines": 8, "path": "/backend/api/items/tests/test_views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\n\nfrom .models import Item\nfrom .serializers import ItemSerializer\n\nfrom django.conf import settings.DEFAULT_FROM_EMAIL as test_email\n\n\n" }, { "alpha_fraction": 0.7572559118270874, "alphanum_fraction": 0.7572559118270874, "avg_line_length": 18.947368621826172, "blob_id": "7ebd4c82370b924e20718f39078afaa693103c77", "content_id": "cc7f36682aee6610226406c06c967287546c70f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 33, "num_lines": 19, "path": "/backend/api/customizations/admin.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import (\n HomePage,\n SocialMedia,\n Footer,\n AboutPage,\n PartnersPage,\n StorePage,\n NGOPage,\n)\n\n\nadmin.site.register(HomePage)\nadmin.site.register(SocialMedia)\nadmin.site.register(Footer)\nadmin.site.register(AboutPage)\nadmin.site.register(PartnersPage)\nadmin.site.register(StorePage)\nadmin.site.register(NGOPage)\n" }, { "alpha_fraction": 0.6104000210762024, "alphanum_fraction": 0.6255999803543091, "avg_line_length": 35.764705657958984, "blob_id": "e04c444d59077034b0ecf22a0d219767aed81f49", "content_id": "4a022af94244cbd82ce7952da6b940cdad789c62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1250, "license_type": "no_license", "max_line_length": 137, "num_lines": 34, "path": "/backend/api/profiles/migrations/0004_auto_20210322_1716.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-22 16:16\n\nimport backend.settings.storage_backends\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('profiles', '0003_profile_display_first'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ngo',\n name='banner_image',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.NGOProfileStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='ngo',\n name='header_image',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.NGOProfileStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='store',\n name='banner_image',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.StoreProfileStorage(), upload_to=''),\n ),\n migrations.AlterField(\n model_name='store',\n name='header_image',\n field=models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.StoreProfileStorage(), upload_to=''),\n ),\n ]\n" }, { "alpha_fraction": 0.545981764793396, "alphanum_fraction": 0.545981764793396, "avg_line_length": 22.6862735748291, "blob_id": "3366d3e45c07d9b44300e7be811d0c4cdd7351e3", "content_id": "29054a5e2571eac1b1b73e4dd7f209c425978484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 48, "num_lines": 51, "path": "/backend/api/orders/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = \"orders\"\nurlpatterns = [\n path(\n \"list/order/\",\n views.OrderListView.as_view(),\n name=\"list-order\",\n ),\n path(\n \"list/order-items/\",\n views.OrderItemListView.as_view(),\n name=\"list-order-items\",\n ),\n path(\n \"create/item-to-basket/\",\n views.OrderItemCreateView.as_view(),\n name=\"create-item-to-basket\",\n ),\n path(\n \"item-to-basket/<uuid:pk>\",\n views.OrderItemDetailView.as_view(),\n name=\"item-to-basket-detail\",\n ),\n path(\n \"order/<uuid:pk>\",\n views.OrderDetailView.as_view(),\n name=\"order-detail\",\n ),\n path(\n \"create/stripe-payment/\",\n views.StripePaymentIntentView.as_view(),\n name=\"stripe-payment\",\n ),\n path(\n \"send/happicard/<uuid:pk>\",\n views.HappicardSendView.as_view(),\n name=\"send-happicard\",\n ),\n path(\n \"create/stripe-payout/\",\n views.StripePayoutView.as_view(),\n name=\"stripe-payout\",\n ),\n path(\n \"create/stripe-transfer/\",\n views.StripeTransferView.as_view(),\n name=\"stripe-transfer\",\n ),\n]" }, { "alpha_fraction": 0.5006992816925049, "alphanum_fraction": 0.5006992816925049, "avg_line_length": 19.457143783569336, "blob_id": "701400cfeeee87ffe301233d717c06f173558f85", "content_id": "67267411adb3f570d7979dec7a87922a8c9190f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 715, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/backend/api/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.urls import path, include\n\napp_name = \"api\"\nurlpatterns = [\n path(\n \"accounts/\",\n include(\"backend.api.accounts.urls\"),\n name=\"accounts\",\n ),\n path(\n \"orders/\",\n include(\"backend.api.orders.urls\"),\n name=\"orders\",\n ),\n path(\n \"items/\",\n include(\"backend.api.items.urls\"),\n name=\"items\",\n ),\n path(\n \"profiles/\",\n include(\"backend.api.profiles.urls\"),\n name=\"profiles\",\n ),\n path(\n \"customizations/\",\n include(\"backend.api.customizations.urls\"),\n name=\"customizations\",\n ),\n path(\n \"seo/\",\n include(\"backend.api.seo.urls\"),\n name=\"seo\",\n ),\n]" }, { "alpha_fraction": 0.5800604224205017, "alphanum_fraction": 0.6435045599937439, "avg_line_length": 17.38888931274414, "blob_id": "358145491dbca95b8f2c6968706ce0ba13c6c8a1", "content_id": "dd41ce6ddb521e07c7cb51456b37a7abc4df5e97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 331, "license_type": "no_license", "max_line_length": 39, "num_lines": 18, "path": "/frontend/src/components/Nav/Navbarstyles.js", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "import styled from \"styled-components\";\n\nexport const Nav = styled.nav`\n width: 100%;\n height: 55px;\n padding: 0 20px;\n display: flex;\n justify-content: center;\n background-color: #dfb248;\n color: white;\n font-size: 14px;\n .logo {\n padding-top: 20px;\n width: 114px;\n height: 60px;\n padding-bottom: 5px;\n }\n`;\n" }, { "alpha_fraction": 0.6876590251922607, "alphanum_fraction": 0.7061068415641785, "avg_line_length": 24.786884307861328, "blob_id": "ef326df2ce72a97923d32b85c3f11bd10de865eb", "content_id": "88995b8161b0faf9286c85a80bd5afec35b31960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1572, "license_type": "no_license", "max_line_length": 61, "num_lines": 61, "path": "/backend/settings/storage_backends.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from storages.backends.s3boto3 import S3Boto3Storage\nfrom django.conf import settings\n\nDEV = True\n\nif DEV:\n stage = \"dev\"\nelse:\n stage = \"prod\"\n\n\nclass StaticStorage(S3Boto3Storage):\n location = \"static\"\n default_acl = \"public-read\"\n\n\nclass MediaStorage(S3Boto3Storage):\n location = \"media\"\n default_acl = \"public-read\"\n file_overwrite = False\n\n\nclass StoreProfileStorage(S3Boto3Storage):\n bucket_name = f\"happicard-stores-{stage}\"\n custom_domain = \"{}.s3.amazonaws.com\".format(bucket_name)\n location = \"profiles\"\n\n\nclass NGOProfileStorage(S3Boto3Storage):\n bucket_name = f\"happicard-ngos-{stage}\"\n custom_domain = \"{}.s3.amazonaws.com\".format(bucket_name)\n location = \"profiles\"\n\n\nclass GiftCardStorage(S3Boto3Storage):\n bucket_name = f\"happicard-stores-{stage}\"\n custom_domain = \"{}.s3.amazonaws.com\".format(bucket_name)\n location = \"giftcards\"\n\n\nclass CampaignStorage(S3Boto3Storage):\n bucket_name = f\"happicard-ngos-{stage}\"\n custom_domain = \"{}.s3.amazonaws.com\".format(bucket_name)\n location = \"campaigns\"\n\n\nclass HappicardImageStorage(S3Boto3Storage):\n bucket_name = f\"happicard-orders-{stage}\"\n custom_domain = \"{}.s3.amazonaws.com\".format(bucket_name)\n location = \"images\"\n\n\nclass HappicardVideoStorage(S3Boto3Storage):\n bucket_name = f\"happicard-orders-{stage}\"\n custom_domain = \"{}.s3.amazonaws.com\".format(bucket_name)\n location = \"videos\"\n\n\nclass CustomStorage(S3Boto3Storage):\n bucket_name = f\"happicard-promo-{stage}\"\n custom_domain = \"{}.s3.amazonaws.com\".format(bucket_name)" }, { "alpha_fraction": 0.5133587718009949, "alphanum_fraction": 0.5410305261611938, "avg_line_length": 26.578947067260742, "blob_id": "9f83548f03c6d3c4b856c021568f5373e5a73501", "content_id": "8eceb00e4ef1c1c77903ec3acdf23192ea32a7b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "no_license", "max_line_length": 61, "num_lines": 38, "path": "/backend/api/customizations/migrations/0002_auto_20210319_1538.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-19 14:38\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customizations', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='footer',\n name='facebook',\n field=models.CharField(max_length=50, null=True),\n ),\n migrations.AddField(\n model_name='footer',\n name='instagram',\n field=models.CharField(max_length=50, null=True),\n ),\n migrations.AddField(\n model_name='footer',\n name='linkedin',\n field=models.CharField(max_length=50, null=True),\n ),\n migrations.AddField(\n model_name='footer',\n name='twitter',\n field=models.CharField(max_length=50, null=True),\n ),\n migrations.AddField(\n model_name='footer',\n name='youtube',\n field=models.CharField(max_length=50, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5171339511871338, "alphanum_fraction": 0.5171339511871338, "avg_line_length": 20.46666717529297, "blob_id": "5b8bd9e26cf398e531b5492feb4943de6d1fbeec", "content_id": "6153e5ceea108d531637332bd1f548af11f99411", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 321, "license_type": "no_license", "max_line_length": 49, "num_lines": 15, "path": "/backend/api/seo/serializers.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import SEO\n\n\nclass SEOSerializer(serializers.ModelSerializer):\n class Meta:\n model = SEO\n fields = (\n \"title\",\n \"keywords\",\n \"description\",\n \"heading\",\n \"subheading\",\n \"extra\",\n )" }, { "alpha_fraction": 0.6488286852836609, "alphanum_fraction": 0.6570969223976135, "avg_line_length": 31.022058486938477, "blob_id": "92f990f1653f0c73176ed1ae58151af1f5ef00d6", "content_id": "fb6e744564b0ffc29616fac67d45f1d0f8788549", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4354, "license_type": "no_license", "max_line_length": 88, "num_lines": 136, "path": "/backend/api/orders/models.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django_countries.fields import CountryField\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.conf import settings\nfrom django.db.models import signals\nimport uuid\n\nfrom django.utils.translation import gettext_lazy as _\n\nfrom backend.api.items.models import GiftCard, Campaign\n\nfrom backend.settings.storage_backends import (\n HappicardImageStorage,\n HappicardVideoStorage,\n)\n\nfrom backend.tasks import send_happicard_email_task, outbound_mms_task\n\n\nclass OrderItem(models.Model):\n \"\"\"\n Order Item Model\n \"\"\"\n\n class Meta:\n verbose_name = _(\"Item in Basket\")\n verbose_name_plural = _(\"Items in Basket\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True\n )\n ordered = models.BooleanField(default=False)\n price_choice = models.PositiveIntegerField(default=0)\n quantity = models.IntegerField(default=1)\n giftcard = models.ForeignKey(\n GiftCard,\n on_delete=models.CASCADE,\n blank=True,\n null=True,\n )\n campaign = models.ForeignKey(\n Campaign,\n on_delete=models.CASCADE,\n blank=True,\n null=True,\n )\n\n @property\n def get_total_item_price(self):\n return self.quantity * self.item.price\n\n @property\n def match_price_choice_with_rebate(self):\n if self.giftcard:\n if self.price_choice == self.giftcard.price_option_1:\n return self.giftcard.rebate_code_1\n elif self.price_choice == self.giftcard.price_option_2:\n return self.giftcard.rebate_code_2\n else:\n return self.giftcard.rebate_code_3\n else:\n if self.price_choice == self.campaign.price_option_1:\n return self.campaign.rebate_code_1\n elif self.price_choice == self.campaign.price_option_2:\n return self.campaign.rebate_code_2\n else:\n return self.campaign.rebate_code_3\n\n @property\n def get_redeem_website(self):\n if self.giftcard:\n return self.giftcard.redeem_website\n else:\n return self.campaign.redeem_website\n\n\nclass Order(models.Model):\n \"\"\"\n Order Model\n \"\"\"\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n null=True,\n blank=True,\n )\n items = models.ManyToManyField(OrderItem, blank=True)\n status = models.CharField(max_length=56, null=False, default=\"created\")\n first_name = models.CharField(max_length=50, null=False, blank=False)\n last_name = models.CharField(max_length=50, null=False, blank=False)\n email = models.EmailField(max_length=254, null=False, blank=False)\n phone_number = models.CharField(max_length=20, null=False, blank=False)\n date = models.DateTimeField(auto_now_add=True)\n\n happicard_recipient_myself = models.BooleanField(default=True)\n happicard_recipient_name = models.CharField(max_length=50, null=True, blank=True)\n happicard_delivery_date = models.DateTimeField(\n auto_now_add=False, null=True, blank=True\n )\n happicard_recipient_email_choice = models.BooleanField(default=False)\n happicard_recipient_email = models.EmailField(max_length=254, null=True, blank=True)\n happicard_recipient_sms_choice = models.BooleanField(default=False)\n happicard_recipient_number = models.CharField(max_length=20, null=True, blank=True)\n happicard_personal_message = models.TextField(null=True, blank=True)\n happicard_personal_image = models.FileField(\n storage=HappicardImageStorage(), null=True, blank=True\n )\n happicard_personal_video = models.FileField(\n storage=HappicardVideoStorage(), null=True, blank=True\n )\n\n def __str__(self):\n return str(self.id)\n\n @property\n def get_order_total(self):\n total_amount = 0\n for item in self.items.all():\n total_amount += item.price_choice\n return total_amount * 100" }, { "alpha_fraction": 0.6297435760498047, "alphanum_fraction": 0.6441025733947754, "avg_line_length": 25.37837791442871, "blob_id": "192f0fc8035d51edf878095dba11d9be1aba4924", "content_id": "9f058573dc9681da5a93a58adb0462a1afcc3bbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 58, "num_lines": 37, "path": "/backend/api/seo/models.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils.translation import gettext_lazy as _\nimport uuid\n\n\nclass Keyword(models.Model):\n class Meta:\n verbose_name = _(\"Keyword\")\n verbose_name_plural = _(\"Keywords\")\n\n keyword = models.CharField(max_length=20)\n\n def __str__(self):\n return self.keyword\n\n\nclass SEO(models.Model):\n class Meta:\n verbose_name = _(\"Metadata\")\n verbose_name_plural = _(\"Metadata\")\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n title = models.CharField(max_length=68, blank=True)\n keywords = models.ManyToManyField(Keyword, blank=True)\n description = models.TextField(max_length=155)\n heading = models.CharField(max_length=20)\n subheading = models.CharField(max_length=20)\n extra = models.CharField(max_length=20)\n\n def __str__(self):\n return f\"Metadata with {self.title}\"" }, { "alpha_fraction": 0.7330135703086853, "alphanum_fraction": 0.7378097772598267, "avg_line_length": 32.37333297729492, "blob_id": "920026e00e140212bd95f2435e260605baf5d3b0", "content_id": "4ec52b3eb813628e0d78cbc7fd00065af55d2fa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2502, "license_type": "no_license", "max_line_length": 82, "num_lines": 75, "path": "/backend/api/items/views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom requests.auth import HTTPBasicAuth\nfrom rest_framework import permissions, status\nfrom rest_framework import generics\nfrom rest_framework.response import Response\nimport requests\n\nfrom .models import GiftCard, Campaign\nfrom .serializers import (\n GiftCardSerializer,\n CampaignSerializer,\n)\n\n\nclass GiftCardListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentification_classes = ()\n queryset = GiftCard.objects.filter(has_offer=False).all()\n serializer_class = GiftCardSerializer\n\n\nclass GiftCardOfferListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentification_classes = ()\n queryset = GiftCard.objects.filter(has_offer=True).all()\n serializer_class = GiftCardSerializer\n\n\nclass CampaignListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentification_classes = ()\n queryset = Campaign.objects.all()\n serializer_class = CampaignSerializer\n\n\nclass GiftCardCreateView(generics.CreateAPIView):\n permission_classes = (permissions.AllowAny,)\n serializer_class = GiftCardSerializer\n\n def post(self, request):\n product = request.data\n serializer = self.serializer_class(data=product)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass CampaignCreateView(generics.CreateAPIView):\n permission_classes = (permissions.AllowAny,)\n serializer_class = CampaignSerializer\n\n def post(self, request):\n product = request.data\n serializer = self.serializer_class(data=product)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass GiftCardDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = GiftCard.objects.all()\n serializer_class = GiftCardSerializer\n\n\nclass CampaignDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Campaign.objects.all()\n serializer_class = CampaignSerializer" }, { "alpha_fraction": 0.46219685673713684, "alphanum_fraction": 0.46219685673713684, "avg_line_length": 20.24242401123047, "blob_id": "6ef2ed9b229ea1a09840dba19270517a1c6deaa0", "content_id": "4860ac30570bd848e9f8b7de8d7475fd647ee1ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license_type": "no_license", "max_line_length": 51, "num_lines": 33, "path": "/backend/api/profiles/serializers.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\n\nfrom .models import Store, NGO\n\n\nclass StoreSerializer(serializers.ModelSerializer):\n class Meta:\n model = Store\n fields = (\n \"id\",\n \"title\",\n \"banner_image\",\n \"header_image\",\n \"about\",\n \"giftcards\",\n \"store_category\",\n \"created_at\",\n )\n\n\nclass NGOSerializer(serializers.ModelSerializer):\n class Meta:\n model = NGO\n fields = (\n \"id\",\n \"title\",\n \"banner_image\",\n \"header_image\",\n \"about\",\n \"campaigns\",\n \"ngo_category\",\n \"created_at\",\n )\n" }, { "alpha_fraction": 0.651334822177887, "alphanum_fraction": 0.6629140973091125, "avg_line_length": 28.065420150756836, "blob_id": "6637e8d4b4d3247557fb23271d260b0b28a3b93b", "content_id": "4ccd2bb356cb1795d5d279127ba27864435392a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3109, "license_type": "no_license", "max_line_length": 88, "num_lines": 107, "path": "/backend/api/items/models.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.conf import settings\nimport uuid\n\nfrom backend.api.accounts.models import STORE_CHOICES, NGO_CHOICES\nfrom backend.settings.storage_backends import CampaignStorage, GiftCardStorage\n\nOPTIONS = (\n (\"draft\", \"Draft\"),\n (\"published\", \"Published\"),\n)\n\n\nclass Item(models.Model):\n \"\"\"\n Abstract Item Model\n \"\"\"\n\n class ItemsObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n title = models.CharField(max_length=255, null=True, blank=True)\n\n price_option_1 = models.PositiveIntegerField(default=0)\n price_option_2 = models.PositiveIntegerField(default=0)\n price_option_3 = models.PositiveIntegerField(default=0)\n\n rebate_code_1 = models.CharField(max_length=200, unique=True, null=True, blank=True)\n rebate_code_2 = models.CharField(max_length=200, unique=True, null=True, blank=True)\n rebate_code_3 = models.CharField(max_length=200, unique=True, null=True, blank=True)\n\n description = models.TextField(\"Description\", max_length=500, blank=True)\n\n online = models.BooleanField(default=True)\n in_store = models.BooleanField(default=False)\n redeem_website = models.CharField(max_length=50, blank=True)\n\n display_first = models.BooleanField(default=False)\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"+\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return f\"{self.title} with the unique ID of {self.id}\"\n\n\nclass GiftCard(Item):\n \"\"\"\n Gift Card Model\n \"\"\"\n\n class Meta:\n verbose_name = _(\"Gift Card\")\n verbose_name_plural = _(\"Gift Cards\")\n\n image = models.FileField(storage=GiftCardStorage(), blank=True, null=True)\n has_offer = models.BooleanField(default=False)\n discount_price = models.IntegerField(default=0)\n store_category = models.CharField(\n max_length=100,\n choices=STORE_CHOICES,\n null=True,\n blank=True,\n verbose_name=_(\"Gift Card Category\"),\n )\n\n\nclass Campaign(Item):\n \"\"\"\n NGO Campaign Model\n \"\"\"\n\n class Meta:\n verbose_name = _(\"Campaign\")\n verbose_name_plural = _(\"Campaigns\")\n\n image = models.FileField(storage=CampaignStorage(), blank=True, null=True)\n ngo_category = models.CharField(\n max_length=100,\n choices=NGO_CHOICES,\n null=True,\n blank=True,\n verbose_name=_(\"Campaign Category\"),\n )" }, { "alpha_fraction": 0.5176767706871033, "alphanum_fraction": 0.5959596037864685, "avg_line_length": 21, "blob_id": "907bdffbefd7356ffd814e768e1560db5ba4032a", "content_id": "46dbcce94d6e57b33533e2024f46c48b81e24985", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/backend/api/profiles/migrations/0003_profile_display_first.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-18 12:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('profiles', '0002_auto_20210317_0824'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='profile',\n name='display_first',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.514487087726593, "alphanum_fraction": 0.5371965765953064, "avg_line_length": 32.605262756347656, "blob_id": "0bf39ccf67f918a2a611a87a3a738f023ca107de", "content_id": "cc6b3a2bb71166f6c1dafe8978e66658b9737950", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1277, "license_type": "no_license", "max_line_length": 140, "num_lines": 38, "path": "/backend/api/seo/migrations/0001_initial.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-17 10:10\n\nfrom django.db import migrations, models\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Keyword',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('keyword', models.CharField(max_length=20)),\n ],\n ),\n migrations.CreateModel(\n name='SEO',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('title', models.CharField(blank=True, max_length=68)),\n ('description', models.TextField(max_length=155)),\n ('heading', models.CharField(max_length=20)),\n ('subheading', models.CharField(max_length=20)),\n ('extra', models.CharField(max_length=20)),\n ('keywords', models.ManyToManyField(blank=True, to='seo.Keyword')),\n ],\n options={\n 'verbose_name': 'SEO',\n 'verbose_name_plural': 'SEO',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6435319781303406, "alphanum_fraction": 0.648982584476471, "avg_line_length": 25.7281551361084, "blob_id": "39091cdc7e888b4247d6a55601080a7901ffe419", "content_id": "86daa2566063e8ff6700a59fec6a370c0575fcd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2752, "license_type": "no_license", "max_line_length": 87, "num_lines": 103, "path": "/backend/api/profiles/models.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "import uuid\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\n\nfrom backend.api.items.models import GiftCard, Campaign\nfrom backend.api.accounts.models import STORE_CHOICES, NGO_CHOICES\nfrom backend.settings.storage_backends import NGOProfileStorage, StoreProfileStorage\n\n\nOPTIONS = (\n (\"draft\", \"Draft\"),\n (\"published\", \"Published\"),\n)\n\n\nclass Profile(models.Model):\n \"\"\"\n Abstract Profile Model\n \"\"\"\n\n class ProfileObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(status=\"published\")\n\n class Meta:\n ordering = (\"-published\",)\n\n id = models.UUIDField(\n default=uuid.uuid4,\n unique=True,\n db_index=True,\n editable=False,\n primary_key=True,\n )\n title = models.CharField(max_length=255, unique=True)\n about = models.TextField(\"About\", max_length=750, blank=True)\n\n display_first = models.BooleanField(default=False)\n\n published = models.DateTimeField(default=timezone.now)\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name=\"publishers\",\n null=True,\n blank=True,\n )\n status = models.CharField(max_length=10, choices=OPTIONS, default=\"published\")\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = models.Manager()\n profobjects = ProfileObjects()\n\n def __str__(self):\n return self.title\n\n\nclass Store(Profile):\n \"\"\"\n Store Model\n \"\"\"\n\n class Meta:\n verbose_name = _(\"Store\")\n verbose_name_plural = _(\"Stores\")\n\n banner_image = models.FileField(\n storage=StoreProfileStorage(), blank=True, null=True\n )\n header_image = models.FileField(\n storage=StoreProfileStorage(), blank=True, null=True\n )\n giftcards = models.ManyToManyField(GiftCard, blank=True)\n store_category = models.CharField(\n max_length=100,\n choices=STORE_CHOICES,\n null=True,\n blank=True,\n verbose_name=_(\"Store Category\"),\n )\n\n\nclass NGO(Profile):\n \"\"\"\n NGO Model\n \"\"\"\n\n class Meta:\n verbose_name = _(\"NGO\")\n verbose_name_plural = _(\"NGOs\")\n\n banner_image = models.FileField(storage=NGOProfileStorage(), blank=True, null=True)\n header_image = models.FileField(storage=NGOProfileStorage(), blank=True, null=True)\n campaigns = models.ManyToManyField(Campaign, blank=True)\n ngo_category = models.CharField(\n max_length=100,\n choices=NGO_CHOICES,\n null=True,\n blank=True,\n verbose_name=_(\"NGO Category\"),\n )" }, { "alpha_fraction": 0.618863046169281, "alphanum_fraction": 0.618863046169281, "avg_line_length": 17.428571701049805, "blob_id": "967ab76df7ee90eaf8e55a0e2990789e49f3bc4c", "content_id": "dbdaf13ec26919e1d7a9e426f481fe2239f921c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 39, "num_lines": 42, "path": "/backend/tasks.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from celery import shared_task\nfrom celery.utils.log import logger\n\nfrom .utils import Util\n\n\n@shared_task\ndef send_happicard_email_task(\n data,\n recipient_name,\n rebate_code,\n redeem_website,\n):\n logger.info(\"Sent Happicard Email\")\n return Util.send_happicard_email(\n data,\n recipient_name,\n rebate_code,\n redeem_website,\n )\n\n\n@shared_task\ndef outbound_mms_task(\n to_number,\n from_number,\n personal_message,\n recipient_name,\n sender_name,\n rebate_code,\n redeem_website,\n):\n logger.info(\"Sent Happicard MMS\")\n return Util.outbound_mms(\n to_number,\n from_number,\n personal_message,\n recipient_name,\n sender_name,\n rebate_code,\n redeem_website,\n )\n" }, { "alpha_fraction": 0.6155274510383606, "alphanum_fraction": 0.6248100996017456, "avg_line_length": 27.080568313598633, "blob_id": "5f92da1556c639f249190edd161bb063bc09acef", "content_id": "8f7ccfa239a715243fec277d7f7514abc33e87a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5925, "license_type": "no_license", "max_line_length": 75, "num_lines": 211, "path": "/backend/settings/base.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "\"\"\"Main Settings\"\"\"\n\nimport os\nimport pathlib\nfrom datetime import timedelta\nfrom decouple import config\n\nBASE_DIR = pathlib.Path(__file__).parent.parent\nPROJECT_ROOT = BASE_DIR.parent\n\nDEBUG = True\n\nSECRET_KEY = config(\"DJANGO_SECRET_KEY\")\n\nINSTALLED_APPS = [\n \"admin_interface\",\n \"colorfield\",\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n \"django_countries\",\n \"backend.api.accounts\",\n \"backend.api.orders\",\n \"backend.api.items\",\n \"backend.api.profiles\",\n \"backend.api.customizations\",\n \"backend.api.seo\",\n \"drf_yasg\",\n \"storages\",\n \"rest_framework\",\n \"rest_framework_simplejwt.token_blacklist\",\n \"django_rest_passwordreset\",\n \"rest_auth\",\n \"corsheaders\",\n]\n\nMIDDLEWARE = [\n \"corsheaders.middleware.CorsMiddleware\",\n \"django.middleware.security.SecurityMiddleware\",\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n]\n\nROOT_URLCONF = \"backend.urls\"\n\nTEMPLATE_DIR = os.path.join(BASE_DIR, \"templates\")\n\nTEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [TEMPLATE_DIR],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.contrib.messages.context_processors.messages\",\n ],\n },\n },\n]\n\nAUTH_USER_MODEL = \"accounts.User\"\n\n# Permission settings\nREST_FRAMEWORK = {\n \"DEFAULT_PERMISSION_CLASSES\": (\"rest_framework.permissions.AllowAny\",),\n \"DEFAULT_AUTHENTICATION_CLASSES\": (\n \"rest_framework_simplejwt.authentication.JWTAuthentication\",\n ),\n}\n\n# JWT settings\nSIMPLE_JWT = {\n \"ACCESS_TOKEN_LIFETIME\": timedelta(minutes=30),\n \"REFRESH_TOKEN_LIFETIME\": timedelta(days=30),\n \"ROTATE_REFRESH_TOKENS\": True,\n \"BLACKLIST_AFTER_ROTATION\": False,\n \"ALGORITHM\": \"HS256\",\n \"SIGNING_KEY\": SECRET_KEY,\n \"VERIFYING_KEY\": None,\n \"AUTH_HEADER_TYPES\": (\"JWT\",),\n \"USER_ID_FIELD\": \"id\",\n \"USER_ID_CLAIM\": \"user_id\",\n \"AUTH_TOKEN_CLASSES\": (\"rest_framework_simplejwt.tokens.AccessToken\",),\n \"TOKEN_TYPE_CLAIM\": \"token_type\",\n}\n\nLOGIN_URL = \"/login\"\nLOGIN_REDIRECT_URL = \"/\"\nLOGOUT_REDIRECT_URL = \"/login\"\n\n# Internationalization\nLANGUAGE_CODE = \"sv-eu\"\n\nTIME_ZONE = \"Europe/Stockholm\"\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Storage\nUSE_S3 = True\n\nif USE_S3:\n # AWS settings\n AWS_ACCESS_KEY_ID = config(\"AWS_ACCESS_KEY_ID\")\n AWS_SECRET_ACCESS_KEY = config(\"AWS_SECRET_ACCESS_KEY\")\n AWS_STORAGE_BUCKET_NAME = config(\"AWS_STORAGE_BUCKET_NAME\")\n AWS_S3_REGION_NAME = \"us-west-2\"\n AWS_S3_CUSTOM_DOMAIN = f\"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com\"\n AWS_S3_OBJECT_PARAMETERS = {\"CacheControl\": \"max-age=86400\"}\n # S3 static settings\n STATIC_LOCATION = \"static\"\n STATIC_URL = f\"https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/\"\n STATICFILES_STORAGE = \"backend.settings.storage_backends.StaticStorage\"\n # S3 media settings\n MEDIA_LOCATION = \"media\"\n MEDIA_URL = f\"https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/\"\n DEFAULT_FILE_STORAGE = \"backend.settings.storage_backends.MediaStorage\"\n # Other static files\n STATICFILES_DIRS = [\n os.path.join(PROJECT_ROOT, \"static\"),\n ]\nelse:\n STATIC_URL = \"/staticfiles/\"\n STATIC_ROOT = os.path.join(BASE_DIR, \"staticfiles\")\n pathlib.Path(STATIC_ROOT).mkdir(exist_ok=True, parents=True)\n MEDIA_URL = \"/mediafiles/\"\n MEDIA_ROOT = os.path.join(BASE_DIR, \"mediafiles\")\n pathlib.Path(MEDIA_ROOT).mkdir(exist_ok=True, parents=True)\n\n# Email\nEMAIL_BACKEND = \"django.core.mail.backends.smtp.EmailBackend\"\nEMAIL_USE_TLS = True\nEMAIL_HOST = config(\"EMAIL_HOST\")\nEMAIL_PORT = 587\n\n# Task Scheduling\nCELERY_TIMEZONE = \"Europe/Stockholm\"\nCELERY_TASK_TRACK_STARTED = True\nCELERY_TASK_TIME_LIMIT = 30 * 60\nCELERY_ACCEPT_CONTENT = [\"json\"]\nCELERY_TASK_SERIALIZER = \"json\"\n\n# Logging\nLOG_DIR = PROJECT_ROOT / \"log\"\nLOG_DIR.mkdir(exist_ok=True)\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"console\": {\n \"format\": \"%(levelname)-8s %(name)-12s %(module)s:%(lineno)s\\n\"\n \"%(message)s\"\n },\n \"file\": {\n \"format\": \"%(asctime)s %(levelname)-8s %(name)-12s \"\n \"%(module)s:%(lineno)s\\n%(message)s\"\n },\n },\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"console\",\n },\n \"file\": {\n \"class\": \"logging.handlers.RotatingFileHandler\",\n \"formatter\": \"file\",\n \"filename\": LOG_DIR / \"django.log\",\n \"backupCount\": 10, # keep at most 10 files\n \"maxBytes\": 5 * 1024 * 1024, # 5MB\n },\n },\n \"loggers\": {\n \"django.request\": {\n \"handlers\": [\"console\", \"file\"],\n \"level\": \"DEBUG\",\n \"propagate\": True,\n },\n },\n}\nLOGGING[\"loggers\"].update(\n {\n app: {\n \"handlers\": [\"console\", \"file\"],\n \"level\": \"DEBUG\",\n \"propagate\": True,\n }\n for app in INSTALLED_APPS\n }\n)\n\n# Different development and production settings\nif DEBUG:\n try:\n from .dev import *\n except ModuleNotFoundError:\n print(\"Dev config not found\")\nelse:\n try:\n from .prod import *\n except ModuleNotFoundError:\n print(\"Prod config not found\")\n" }, { "alpha_fraction": 0.5514315962791443, "alphanum_fraction": 0.5514315962791443, "avg_line_length": 22.024391174316406, "blob_id": "adf6c884bd3a727f529c2c0ba2c59ca7f9330af5", "content_id": "98f05e548208ac29b16d97f3affa48fca20d3223", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 943, "license_type": "no_license", "max_line_length": 46, "num_lines": 41, "path": "/backend/api/items/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = \"items\"\nurlpatterns = [\n path(\n \"list/giftcards/\",\n views.GiftCardListView.as_view(),\n name=\"list-giftcards\",\n ),\n path(\n \"list/giftcard/offers/\",\n views.GiftCardOfferListView.as_view(),\n name=\"list-giftcardoffers\",\n ),\n path(\n \"list/campaigns/\",\n views.CampaignListView.as_view(),\n name=\"list-campaigns\",\n ),\n path(\n \"create/giftcard/\",\n views.GiftCardCreateView.as_view(),\n name=\"create-giftcard\",\n ),\n path(\n \"create/campaign/\",\n views.CampaignCreateView.as_view(),\n name=\"create-campaign\",\n ),\n path(\n \"giftcard/<uuid:pk>/\",\n views.GiftCardDetailView.as_view(),\n name=\"giftcard-detail\",\n ),\n path(\n \"campaign/<uuid:pk>/\",\n views.CampaignDetailView.as_view(),\n name=\"campaign-detail\",\n ),\n]" }, { "alpha_fraction": 0.692556619644165, "alphanum_fraction": 0.692556619644165, "avg_line_length": 25.913043975830078, "blob_id": "131c021588be1e50d924e7e2c615f295913ddd86", "content_id": "514ae95763a91b8d6de3d065a39439c8b464bf66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "no_license", "max_line_length": 45, "num_lines": 23, "path": "/backend/api/items/admin.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import GiftCard, Campaign\n\n\nclass GiftCardAdmin(admin.ModelAdmin):\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(author=request.user)\n\n\nclass CampaignAdmin(admin.ModelAdmin):\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n if request.user.is_superuser:\n return qs\n return qs.filter(author=request.user)\n\n\nadmin.site.register(GiftCard, GiftCardAdmin)\nadmin.site.register(Campaign, CampaignAdmin)" }, { "alpha_fraction": 0.47790056467056274, "alphanum_fraction": 0.5635359287261963, "avg_line_length": 19.11111068725586, "blob_id": "dd18a0fdfc7e6ebc401f45a7439d67d02e3d37f7", "content_id": "83808ed90bd5011578f500b88fb2fdc003a9ee78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 362, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/backend/api/items/migrations/0004_auto_20210319_1520.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-19 14:20\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('items', '0003_auto_20210318_1343'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='item',\n old_name='premium',\n new_name='in_store',\n ),\n ]\n" }, { "alpha_fraction": 0.6103934049606323, "alphanum_fraction": 0.6224309802055359, "avg_line_length": 55.766666412353516, "blob_id": "9b2eb28e6359553e4e32bebc2c158c193ec40a34", "content_id": "d7ae2d424385ce46732862b0d9e910b676b96fc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3406, "license_type": "no_license", "max_line_length": 167, "num_lines": 60, "path": "/backend/api/orders/migrations/0001_initial.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-17 06:49\n\nimport backend.settings.storage_backends\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('items', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='OrderItem',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('ordered', models.BooleanField(default=False)),\n ('price_choice', models.PositiveIntegerField(default=0)),\n ('quantity', models.IntegerField(default=1)),\n ('campaign', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='items.campaign')),\n ('giftcard', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='items.giftcard')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Item in Basket',\n 'verbose_name_plural': 'Items in Basket',\n },\n ),\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),\n ('status', models.CharField(default='created', max_length=56)),\n ('first_name', models.CharField(max_length=50)),\n ('last_name', models.CharField(max_length=50)),\n ('email', models.EmailField(max_length=254)),\n ('phone_number', models.CharField(max_length=20)),\n ('date', models.DateTimeField(auto_now_add=True)),\n ('happicard_recipient_myself', models.BooleanField(default=True)),\n ('happicard_recipient_name', models.CharField(blank=True, max_length=50, null=True)),\n ('happicard_delivery_date', models.DateTimeField(blank=True, null=True)),\n ('happicard_recipient_email_choice', models.BooleanField(default=False)),\n ('happicard_recipient_email', models.EmailField(blank=True, max_length=254, null=True)),\n ('happicard_recipient_sms_choice', models.BooleanField(default=False)),\n ('happicard_recipient_number', models.CharField(blank=True, max_length=20, null=True)),\n ('happicard_personal_message', models.TextField(blank=True, null=True)),\n ('happicard_personal_image', models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.HappicardImageStorage(), upload_to='')),\n ('happicard_personal_video', models.FileField(blank=True, null=True, storage=backend.settings.storage_backends.HappicardVideoStorage(), upload_to='')),\n ('items', models.ManyToManyField(blank=True, to='orders.OrderItem')),\n ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5465995073318481, "alphanum_fraction": 0.5465995073318481, "avg_line_length": 21.08333396911621, "blob_id": "c6e6cf082c572598b2102d26184ce46b77d73ce4", "content_id": "e54a4e7b79289af109c68616cc1bffba5e294832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 794, "license_type": "no_license", "max_line_length": 45, "num_lines": 36, "path": "/backend/api/customizations/urls.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = \"customizations\"\nurlpatterns = [\n path(\n \"list/homepage/\",\n views.HomePageListView.as_view(),\n name=\"list-homepage\",\n ),\n path(\n \"list/footer/\",\n views.FooterListView.as_view(),\n name=\"list-footer\",\n ),\n path(\n \"list/aboutpage/\",\n views.AboutPageListView.as_view(),\n name=\"list-aboutpage\",\n ),\n path(\n \"list/partnerspage/\",\n views.PartnersPageListView.as_view(),\n name=\"list-partnerspage\",\n ),\n path(\n \"list/storepage/\",\n views.StorePageListView.as_view(),\n name=\"list-storepage\",\n ),\n path(\n \"list/ngopage/\",\n views.NGOPageListView.as_view(),\n name=\"list-ngopage\",\n ),\n]" }, { "alpha_fraction": 0.538891077041626, "alphanum_fraction": 0.5460709929466248, "avg_line_length": 35.340579986572266, "blob_id": "84c2e4f215c8a020036b19b5df6d695852dfa130", "content_id": "8cbda6d3b14bdbeb19bcca10f655beae2e31d8ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5014, "license_type": "no_license", "max_line_length": 82, "num_lines": 138, "path": "/backend/api/profiles/views.py", "repo_name": "ManivaDigital-AB/Happicard", "src_encoding": "UTF-8", "text": "from rest_framework import permissions, status, generics\nfrom rest_framework.response import Response\n\nfrom .serializers import StoreSerializer, NGOSerializer\nfrom .models import Store, NGO\n\n\nclass StoreListView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = StoreSerializer\n queryset = \"\"\n\n def get(self, request):\n queryset = [\n {\n \"id\": b.id,\n \"title\": b.title,\n \"about\": b.about,\n \"banner_image\": b.banner_image.url,\n \"header_image\": b.header_image.url,\n \"store_category\": b.store_category,\n \"created_at\": b.created_at,\n \"giftcards\": [\n {\n \"giftcard_id\": a.id,\n \"giftcard_title\": a.title,\n \"price_option_1\": a.price_option_1,\n \"price_option_2\": a.price_option_2,\n \"price_option_3\": a.price_option_3,\n \"rebate_code_1\": a.rebate_code_1,\n \"rebate_code_2\": a.rebate_code_2,\n \"rebate_code_3\": a.rebate_code_3,\n \"giftcard_image\": a.image.url,\n \"giftcard_description\": a.description,\n \"giftcard_has_offer\": a.has_offer,\n \"giftcard_discount_price\": a.discount_price,\n \"giftcard_store_category\": a.store_category,\n }\n for a in b.giftcards.all()\n ],\n }\n for b in Store.objects.prefetch_related(\"giftcards\")\n ]\n return Response(queryset)\n\n\nclass NGOListView(generics.GenericAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = NGOSerializer\n queryset = \"\"\n\n def get(self, request):\n queryset = [\n {\n \"id\": b.id,\n \"title\": b.title,\n \"about\": b.about,\n \"banner_image\": b.banner_image.url,\n \"header_image\": b.header_image.url,\n \"ngo_category\": b.ngo_category,\n \"created_at\": b.created_at,\n \"campaigns\": [\n {\n \"campaign_id\": a.id,\n \"campaign_title\": a.title,\n \"price_option_1\": a.price_option_1,\n \"price_option_2\": a.price_option_2,\n \"price_option_3\": a.price_option_3,\n \"rebate_code_1\": a.rebate_code_1,\n \"rebate_code_2\": a.rebate_code_2,\n \"rebate_code_3\": a.rebate_code_3,\n \"campaign_image\": a.image.url,\n \"campaign_description\": a.description,\n \"campaign_ngo_category\": a.ngo_category,\n }\n for a in b.campaigns.all()\n ],\n }\n for b in NGO.objects.prefetch_related(\"campaigns\")\n ]\n return Response(queryset)\n\n\nclass StoreDetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = Store.objects.all()\n serializer_class = StoreSerializer\n\n\nclass NGODetailView(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n queryset = NGO.objects.all()\n serializer_class = NGOSerializer\n\n\nclass StoreCreateView(generics.CreateAPIView):\n permission_classes = (permissions.AllowAny,)\n serializer_class = StoreSerializer\n\n def post(self, request):\n prof = request.data\n serializer = self.serializer_class(data=prof)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass NGOCreateView(generics.CreateAPIView):\n permission_classes = (permissions.AllowAny,)\n serializer_class = NGOSerializer\n\n def post(self, request):\n prof = request.data\n serializer = self.serializer_class(data=prof)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass StoreSearchView(generics.ListAPIView):\n permission_classes = (permissions.AllowAny,)\n authentication_classes = ()\n serializer_class = StoreSerializer\n\n def get_queryset(self):\n try:\n title = self.kwargs[\"title\"]\n return Store.objects.filter(title=title)\n except:\n return Response(\"Store does not exist in the database.\")" } ]
64
anderser/django-csv-admin
https://github.com/anderser/django-csv-admin
cdb1b8e1713d8f874bd2f5a073e7b68774ee85ab
575977dd07c36fd167e6c6738387f1c985d1899f
a58a505d3be1b41e2bb8b87fa736fb8e489a663c
refs/heads/master
2020-12-25T10:50:57.076548
2012-02-10T09:42:11
2012-02-10T09:42:11
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.642405092716217, "alphanum_fraction": 0.6487341523170471, "avg_line_length": 27.727272033691406, "blob_id": "00d10e6bf1d3e3c4142a989069aa65e9665eb833", "content_id": "76ca1d9bddc00c6e39f31cbf907ffc3800869713", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 71, "num_lines": 11, "path": "/setup.py", "repo_name": "anderser/django-csv-admin", "src_encoding": "UTF-8", "text": "from distutils.core import setup\n\nsetup(\n name = \"django-csv-admin\",\n version = '0.1',\n url = 'https://github.com/anderser/django-csv-admin',\n author = 'huddlej/anderser',\n author_email= '[email protected]',\n description = 'Import to Django models from CSV files using admin',\n packages = ['csv_admin']\n)\n" } ]
1
testitesti22/ha-sun2
https://github.com/testitesti22/ha-sun2
8db173750005c986dc45ed144fb72b3c772671a5
d466778d68aae71afae948efe7c811e893ddd27c
2fe960b3dbd6588b52c22729432991f40425779a
refs/heads/master
2023-04-03T23:19:20.001901
2021-04-02T21:16:04
2021-04-02T21:16:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5887289643287659, "alphanum_fraction": 0.5964385867118835, "avg_line_length": 34.31807327270508, "blob_id": "2393ccb90a822cfddcc69234a18f931618f11b45", "content_id": "70c013689922cb91077ea46119e6a8c1a5b94844", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14659, "license_type": "permissive", "max_line_length": 89, "num_lines": 415, "path": "/custom_components/sun2/sensor.py", "repo_name": "testitesti22/ha-sun2", "src_encoding": "UTF-8", "text": "\"\"\"Sun2 Sensor.\"\"\"\nfrom datetime import timedelta\nimport logging\n\nimport voluptuous as vol\n\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\nfrom homeassistant.const import (\n CONF_MONITORED_CONDITIONS, DEVICE_CLASS_TIMESTAMP)\nfrom homeassistant.core import callback\nfrom homeassistant.util import dt as dt_util\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.helpers.event import (\n async_track_time_change, async_track_point_in_time)\n\nfrom .helpers import (\n async_init_astral_loc, astral_event, nearest_second, SIG_LOC_UPDATED)\n\n_LOGGER = logging.getLogger(__name__)\n_SOLAR_DEPRESSIONS = ('astronomical', 'civil', 'nautical')\n_ELEV_RND = 0.5\n_ELEV_MAX_ERR = 0.02\n_DELTA = timedelta(minutes=5)\n_ONE_DAY = timedelta(days=1)\n\nATTR_NEXT_CHANGE = 'next_change'\n\n\nclass Sun2Sensor(Entity):\n \"\"\"Sun2 Sensor.\"\"\"\n\n def __init__(self, hass, sensor_type, icon, default_solar_depression=0):\n \"\"\"Initialize sensor.\"\"\"\n if any(sol_dep in sensor_type for sol_dep in _SOLAR_DEPRESSIONS):\n self._solar_depression, self._event = sensor_type.rsplit('_', 1)\n else:\n self._solar_depression = default_solar_depression\n self._event = sensor_type\n self._icon = icon\n self._name = sensor_type.replace('_', ' ').title()\n self._state = None\n self._yesterday = None\n self._today = None\n self._tomorrow = None\n async_init_astral_loc(hass)\n self._unsub_dispatcher = None\n self._unsub_update = None\n\n @property\n def should_poll(self):\n \"\"\"Do not poll.\"\"\"\n return False\n\n @property\n def name(self):\n \"\"\"Return the name of the entity.\"\"\"\n return self._name\n\n @property\n def state(self):\n \"\"\"Return the state of the entity.\"\"\"\n return self._state\n\n def _device_state_attributes(self):\n return {\n 'yesterday': self._yesterday,\n 'today': self._today,\n 'tomorrow': self._tomorrow,\n }\n\n @property\n def device_state_attributes(self):\n \"\"\"Return device specific state attributes.\"\"\"\n return self._device_state_attributes()\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend.\"\"\"\n return self._icon\n\n def _setup_fixed_updating(self):\n # Default behavior is to update every local midnight.\n # Override for sensor types that should update at a different time,\n # or that have a more dynamic update schedule (in which case override\n # with a method that does nothing and set up the update at the end of\n # an override of _update instead.)\n @callback\n def async_update_at_midnight(now):\n self.async_schedule_update_ha_state(True)\n self._unsub_update = async_track_time_change(\n self.hass, async_update_at_midnight, 0, 0, 0)\n\n async def async_loc_updated(self):\n \"\"\"Location updated.\"\"\"\n self.async_schedule_update_ha_state(True)\n\n async def async_added_to_hass(self):\n \"\"\"Subscribe to update signal and set up fixed updating.\"\"\"\n self._unsub_dispatcher = async_dispatcher_connect(\n self.hass, SIG_LOC_UPDATED, self.async_loc_updated)\n self._setup_fixed_updating()\n\n async def async_will_remove_from_hass(self):\n \"\"\"Disconnect from update signal and cancel fixed updating.\"\"\"\n self._unsub_dispatcher()\n if self._unsub_update:\n self._unsub_update()\n\n def _get_astral_event(self, event, date_or_dt):\n return astral_event(event, date_or_dt, self._solar_depression)\n\n def _get_data(self, date_or_dt):\n return self._get_astral_event(self._event, date_or_dt)\n\n def _update(self):\n today = dt_util.now().date()\n self._yesterday = self._get_data(today-timedelta(days=1))\n self._state = self._today = self._get_data(today)\n self._tomorrow = self._get_data(today+timedelta(days=1))\n\n async def async_update(self):\n \"\"\"Update state.\"\"\"\n self._update()\n\n\nclass Sun2PointInTimeSensor(Sun2Sensor):\n \"\"\"Sun2 Point in Time Sensor.\"\"\"\n\n def __init__(self, hass, sensor_type, icon):\n \"\"\"Initialize sensor.\"\"\"\n super().__init__(hass, sensor_type, icon, 'civil')\n\n @property\n def device_class(self):\n \"\"\"Return the class of this device.\"\"\"\n return DEVICE_CLASS_TIMESTAMP\n\n def _update(self):\n super()._update()\n if self._state != 'none':\n self._state = self._state.isoformat()\n\n\ndef _hours_to_hms(hours):\n try:\n return str(timedelta(hours=hours)).split('.')[0]\n except TypeError:\n return None\n\n\nclass Sun2PeriodOfTimeSensor(Sun2Sensor):\n \"\"\"Sun2 Period of Time Sensor.\"\"\"\n\n def __init__(self, hass, sensor_type, icon):\n \"\"\"Initialize sensor.\"\"\"\n super().__init__(hass, sensor_type, icon, 0.833)\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return 'hr'\n\n def _device_state_attributes(self):\n data = super()._device_state_attributes()\n data.update({\n 'yesterday_hms': _hours_to_hms(data['yesterday']),\n 'today_hms': _hours_to_hms(data['today']),\n 'tomorrow_hms': _hours_to_hms(data['tomorrow']),\n })\n return data\n\n def _get_data(self, date_or_dt):\n if 'daylight' in self._event:\n start = self._get_astral_event('dawn', date_or_dt)\n end = self._get_astral_event('dusk', date_or_dt)\n else:\n start = self._get_astral_event('dusk', date_or_dt)\n end = self._get_astral_event('dawn', date_or_dt+timedelta(days=1))\n if 'none' in (start, end):\n return None\n return (end - start).total_seconds()/3600\n\n def _update(self):\n super()._update()\n if self._state is not None:\n self._state = round(self._state, 3)\n\n\nclass Sun2MinMaxElevationSensor(Sun2Sensor):\n \"\"\"Sun2 Min/Max Elevation Sensor.\"\"\"\n\n def __init__(self, hass, sensor_type, icon, is_min):\n \"\"\"Initialize sensor.\"\"\"\n super().__init__(hass, sensor_type, icon)\n self._event = 'solar_midnight' if is_min else 'solar_noon'\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return '°'\n\n def _get_data(self, date_or_dt):\n event_time = self._get_astral_event(self._event, date_or_dt)\n return self._get_astral_event('solar_elevation', event_time)\n\n def _update(self):\n super()._update()\n if self._state is not None:\n self._state = round(self._state, 3)\n\n\nclass Sun2MinElevationSensor(Sun2MinMaxElevationSensor):\n \"\"\"Sun2 Min Elevation Sensor.\"\"\"\n\n def __init__(self, hass, sensor_type, icon):\n \"\"\"Initialize sensor.\"\"\"\n super().__init__(hass, sensor_type, icon, is_min=True)\n\n\nclass Sun2MaxElevationSensor(Sun2MinMaxElevationSensor):\n \"\"\"Sun2 Max Elevation Sensor.\"\"\"\n\n def __init__(self, hass, sensor_type, icon):\n \"\"\"Initialize sensor.\"\"\"\n super().__init__(hass, sensor_type, icon, is_min=False)\n\n\ndef _nearest_multiple(value, multiple):\n return int(round(value / multiple)) * multiple\n\n\ndef _calc_nxt_time(time0, elev0, time1, elev1, trg_elev):\n return nearest_second(\n time0 + (time1 - time0) * ((trg_elev - elev0) / (elev1 - elev0)))\n\n\nclass Sun2ElevationSensor(Sun2Sensor):\n \"\"\"Sun2 Elevation Sensor.\"\"\"\n\n def __init__(self, hass, sensor_type, icon):\n \"\"\"Initialize sensor.\"\"\"\n super().__init__(hass, sensor_type, icon)\n self._reset()\n\n def _reset(self):\n self._prv_sol_midn = None\n self._sol_noon = None\n self._sol_midn = None\n self._prv_time = None\n self._prv_elev = None\n self._next_change = None\n\n @property\n def device_state_attributes(self):\n \"\"\"Return device specific state attributes.\"\"\"\n return {ATTR_NEXT_CHANGE: self._next_change}\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return '°'\n\n async def async_loc_updated(self):\n \"\"\"Location updated.\"\"\"\n self._reset()\n if self._unsub_update:\n self._unsub_update()\n self._unsub_update = None\n self.async_schedule_update_ha_state(True)\n\n def _setup_fixed_updating(self):\n pass\n\n def _get_nxt_time(self, time1, elev1, trg_elev, min_time, max_time):\n if self._prv_time < min_time:\n return None\n time0 = self._prv_time\n elev0 = self._prv_elev\n nxt_elev = trg_elev + 1.5 * _ELEV_MAX_ERR\n while abs(nxt_elev - trg_elev) >= _ELEV_MAX_ERR:\n try:\n nxt_time = _calc_nxt_time(time0, elev0, time1, elev1, trg_elev)\n except ZeroDivisionError:\n return None\n if nxt_time < min_time or nxt_time > max_time:\n return None\n if nxt_time in (time0, time1):\n break\n nxt_elev = astral_event(\"solar_elevation\", nxt_time)\n if nxt_time > time1:\n time0 = time1\n elev0 = elev1\n time1 = nxt_time\n elev1 = nxt_elev\n elif elev0 < trg_elev < nxt_elev or elev0 > trg_elev > nxt_elev:\n time1 = nxt_time\n elev1 = nxt_elev\n else:\n time0 = nxt_time\n elev0 = nxt_elev\n return nxt_time\n\n def _set_nxt_time(self, cur_time):\n if self._sol_noon - _DELTA <= cur_time < self._sol_noon:\n return self._sol_noon\n elif self._sol_midn - _DELTA <= cur_time:\n return self._sol_midn\n else:\n return cur_time + _DELTA\n\n def _update(self):\n # Astral package ignores microseconds, so round to nearest second\n # before continuing.\n cur_time = nearest_second(dt_util.now())\n cur_elev = astral_event(\"solar_elevation\", cur_time)\n self._state = f'{cur_elev:0.1f}'\n _LOGGER.debug('Raw elevation = %f -> %s', cur_elev, self._state)\n\n # Find the next solar midnight AFTER the current time, and the solar noon and\n # solar midnight that precede it. This only needs to be done once a day when we\n # reach or pass the previously determined solar midnight.\n if not self._sol_midn or cur_time >= self._sol_midn:\n date = cur_time.date()\n # solar_midnight() returns the solar midnight (which is when the\n # sun reaches its lowest point) nearest to the start of today. Note\n # that it may have occurred yesterday.\n self._sol_midn = astral_event(\"solar_midnight\", date)\n while self._sol_midn <= cur_time:\n date += _ONE_DAY\n self._sol_midn = astral_event(\"solar_midnight\", date)\n self._sol_noon = astral_event(\"solar_noon\", date - _ONE_DAY)\n self._prv_sol_midn = astral_event(\"solar_midnight\", date - _ONE_DAY)\n _LOGGER.debug(\n \"Solar midnight/noon/midnight: %s/%0.2f, %s/%0.2f, %s/%0.2f\",\n self._prv_sol_midn,\n astral_event(\"solar_elevation\", self._prv_sol_midn),\n self._sol_noon,\n astral_event(\"solar_elevation\", self._sol_noon),\n self._sol_midn,\n astral_event(\"solar_elevation\", self._sol_midn),\n )\n\n if self._prv_time:\n # Extrapolate based on previous point and current point to find\n # next point.\n rnd_elev = _nearest_multiple(cur_elev, _ELEV_RND)\n if cur_time < self._sol_noon:\n nxt_time = self._get_nxt_time(\n cur_time, cur_elev,\n rnd_elev + _ELEV_RND, self._prv_sol_midn, self._sol_noon)\n else:\n nxt_time = self._get_nxt_time(\n cur_time, cur_elev,\n rnd_elev - _ELEV_RND, self._sol_noon, self._sol_midn)\n else:\n nxt_time = None\n\n if not nxt_time:\n nxt_time = self._set_nxt_time(cur_time)\n\n self._prv_time = cur_time\n self._prv_elev = cur_elev\n\n self._next_change = nxt_time\n\n @callback\n def async_update(now):\n self._unsub_update = None\n self.async_schedule_update_ha_state(True)\n\n self._unsub_update = async_track_point_in_time(self.hass, async_update, nxt_time)\n\n\n_SENSOR_TYPES = {\n # Points in time\n 'solar_midnight': (Sun2PointInTimeSensor, 'mdi:weather-night'),\n 'astronomical_dawn': (Sun2PointInTimeSensor, 'mdi:weather-sunset-up'),\n 'nautical_dawn': (Sun2PointInTimeSensor, 'mdi:weather-sunset-up'),\n 'dawn': (Sun2PointInTimeSensor, 'mdi:weather-sunset-up'),\n 'sunrise': (Sun2PointInTimeSensor, 'mdi:weather-sunset-up'),\n 'solar_noon': (Sun2PointInTimeSensor, 'mdi:weather-sunny'),\n 'sunset': (Sun2PointInTimeSensor, 'mdi:weather-sunset-down'),\n 'dusk': (Sun2PointInTimeSensor, 'mdi:weather-sunset-down'),\n 'nautical_dusk': (Sun2PointInTimeSensor, 'mdi:weather-sunset-down'),\n 'astronomical_dusk': (Sun2PointInTimeSensor, 'mdi:weather-sunset-down'),\n # Time periods\n 'daylight': (Sun2PeriodOfTimeSensor, 'mdi:weather-sunny'),\n 'civil_daylight': (Sun2PeriodOfTimeSensor, 'mdi:weather-sunny'),\n 'nautical_daylight': (Sun2PeriodOfTimeSensor, 'mdi:weather-sunny'),\n 'astronomical_daylight': (Sun2PeriodOfTimeSensor, 'mdi:weather-sunny'),\n 'night': (Sun2PeriodOfTimeSensor, 'mdi:weather-night'),\n 'civil_night': (Sun2PeriodOfTimeSensor, 'mdi:weather-night'),\n 'nautical_night': (Sun2PeriodOfTimeSensor, 'mdi:weather-night'),\n 'astronomical_night': (Sun2PeriodOfTimeSensor, 'mdi:weather-night'),\n # Min/Max elevation\n 'min_elevation': (Sun2MinElevationSensor, 'mdi:weather-night'),\n 'max_elevation': (Sun2MaxElevationSensor, 'mdi:weather-sunny'),\n # Elevation\n 'elevation': (Sun2ElevationSensor, 'mdi:weather-sunny'),\n}\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_MONITORED_CONDITIONS): vol.All(\n cv.ensure_list, [vol.In(_SENSOR_TYPES)]),\n})\n\n\nasync def async_setup_platform(\n hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up sensors.\"\"\"\n async_add_entities([_SENSOR_TYPES[event][0](hass, event,\n _SENSOR_TYPES[event][1])\n for event in config[CONF_MONITORED_CONDITIONS]], True)\n" }, { "alpha_fraction": 0.556118369102478, "alphanum_fraction": 0.5652714967727661, "avg_line_length": 34.72380828857422, "blob_id": "1ded1d3f6bf6ba18acd1a2e93ebc666fd51e35e2", "content_id": "eaec3564f8dc503b621771e6172f36fbd2d4b2ab", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11253, "license_type": "permissive", "max_line_length": 93, "num_lines": 315, "path": "/custom_components/sun2/binary_sensor.py", "repo_name": "testitesti22/ha-sun2", "src_encoding": "UTF-8", "text": "\"\"\"Sun2 Binary Sensor.\"\"\"\nfrom datetime import timedelta\nimport logging\n\nimport voluptuous as vol\n\ntry:\n from homeassistant.components.binary_sensor import BinarySensorEntity\nexcept ImportError:\n from homeassistant.components.binary_sensor import BinarySensorDevice\n BinarySensorEntity = BinarySensorDevice\nfrom homeassistant.components.binary_sensor import PLATFORM_SCHEMA\nfrom homeassistant.const import (\n CONF_ABOVE, CONF_ELEVATION, CONF_MONITORED_CONDITIONS, CONF_NAME)\nfrom homeassistant.core import callback\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\nfrom homeassistant.helpers.event import async_track_point_in_time\nfrom homeassistant.util import dt as dt_util\n\nfrom .helpers import (\n async_init_astral_loc, astral_event, nearest_second, SIG_LOC_UPDATED)\n\n_LOGGER = logging.getLogger(__name__)\n\nDEFAULT_ELEVATION_ABOVE = -0.833\nDEFAULT_ELEVATION_NAME = 'Above Horizon'\n\nABOVE_ICON = 'mdi:white-balance-sunny'\nBELOW_ICON = 'mdi:moon-waxing-crescent'\n\n_ONE_DAY = timedelta(days=1)\n_ONE_SEC = timedelta(seconds=1)\n\n_SENSOR_TYPES = [CONF_ELEVATION]\n\nATTR_NEXT_CHANGE = 'next_change'\n\n\n# elevation\n# elevation: <threshold>\n# elevation:\n# above: <threshold>\n# name: <friendly_name>\n\n\ndef _val_cfg(config):\n if isinstance(config, str):\n config = {config: {}}\n else:\n if CONF_ELEVATION in config:\n value = config[CONF_ELEVATION]\n if isinstance(value, float):\n config[CONF_ELEVATION] = {CONF_ABOVE: value}\n if CONF_ELEVATION in config:\n options = config[CONF_ELEVATION]\n for key in options:\n if key not in [CONF_ELEVATION, CONF_ABOVE, CONF_NAME]:\n raise vol.Invalid(\n f'{key} not allowed for {CONF_ELEVATION}')\n if CONF_ABOVE not in options:\n options[CONF_ABOVE] = DEFAULT_ELEVATION_ABOVE\n if CONF_NAME not in options:\n above = options[CONF_ABOVE]\n if above == DEFAULT_ELEVATION_ABOVE:\n name = DEFAULT_ELEVATION_NAME\n else:\n name = 'Above '\n if above < 0:\n name += f'minus {-above}'\n else:\n name += f'{above}'\n options[CONF_NAME] = name\n return config\n\n\n_BINARY_SENSOR_SCHEMA = vol.All(\n vol.Any(\n vol.In(_SENSOR_TYPES),\n vol.Schema({\n vol.Required(vol.In(_SENSOR_TYPES)): vol.Any(\n vol.Coerce(float),\n vol.Schema({\n vol.Optional(CONF_ABOVE): vol.Coerce(float),\n vol.Optional(CONF_NAME): cv.string,\n }),\n ),\n }),\n ),\n _val_cfg,\n)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_MONITORED_CONDITIONS): vol.All(\n cv.ensure_list, [_BINARY_SENSOR_SCHEMA]),\n})\n\n\nclass Sun2ElevationSensor(BinarySensorEntity):\n \"\"\"Sun2 Elevation Sensor.\"\"\"\n\n def __init__(self, hass, name, above):\n \"\"\"Initialize sensor.\"\"\"\n self._name = name\n self._threshold = above\n self._state = None\n self._next_change = None\n async_init_astral_loc(hass)\n self._unsub_dispatcher = None\n self._unsub_update = None\n\n @property\n def should_poll(self):\n \"\"\"Do not poll.\"\"\"\n return False\n\n @property\n def name(self):\n \"\"\"Return the name of the entity.\"\"\"\n return self._name\n\n @property\n def device_state_attributes(self):\n \"\"\"Return device specific state attributes.\"\"\"\n return {ATTR_NEXT_CHANGE: self._next_change}\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend.\"\"\"\n return ABOVE_ICON if self.is_on else BELOW_ICON\n\n @property\n def is_on(self):\n \"\"\"Return true if the binary sensor is on.\"\"\"\n return self._state\n\n async def async_loc_updated(self):\n \"\"\"Location updated.\"\"\"\n if self._unsub_update:\n self._unsub_update()\n self._unsub_update = None\n self.async_schedule_update_ha_state(True)\n\n async def async_added_to_hass(self):\n \"\"\"Subscribe to update signal.\"\"\"\n self._unsub_dispatcher = async_dispatcher_connect(\n self.hass, SIG_LOC_UPDATED, self.async_loc_updated)\n\n async def async_will_remove_from_hass(self):\n \"\"\"Disconnect from update signal.\"\"\"\n self._unsub_dispatcher()\n if self._unsub_update:\n self._unsub_update()\n\n def _find_nxt_dttm(self, t0_dttm, t0_elev, t1_dttm, t1_elev):\n # Do a binary search for time between t0 & t1 where elevation is\n # nearest threshold, but also above (or equal to) it if current\n # elevation is below it (i.e., current state is False), or below it if\n # current elevation is above (or equal to) it (i.e., current state is\n # True.)\n\n slope = 1 if t1_elev > t0_elev else -1\n\n # Find mid point and throw away fractional seconds since astral package\n # ignores microseconds.\n tn_dttm = nearest_second(t0_dttm + (t1_dttm - t0_dttm) / 2)\n tn_elev = astral_event(\"solar_elevation\", tn_dttm)\n\n while not (\n (self._state and tn_elev <= self._threshold\n or not self._state and tn_elev > self._threshold)\n and abs(tn_elev - self._threshold) <= 0.01):\n\n if (tn_elev - self._threshold) * slope > 0:\n if t1_dttm == tn_dttm:\n break\n t1_dttm = tn_dttm\n else:\n if t0_dttm == tn_dttm:\n break\n t0_dttm = tn_dttm\n tn_dttm = nearest_second(t0_dttm + (t1_dttm - t0_dttm) / 2)\n tn_elev = astral_event(\"solar_elevation\", tn_dttm)\n\n # Did we go too far?\n if self._state and tn_elev > self._threshold:\n tn_dttm -= slope * _ONE_SEC\n if astral_event(\"solar_elevation\", tn_dttm) > self._threshold:\n raise RuntimeError(\"Couldn't find next update time\")\n elif not self._state and tn_elev <= self._threshold:\n tn_dttm += slope * _ONE_SEC\n if astral_event(\"solar_elevation\", tn_dttm) <= self._threshold:\n raise RuntimeError(\"Couldn't find next update time\")\n\n return tn_dttm\n\n def _get_nxt_dttm(self, cur_dttm):\n # Find next segment of elevation curve, between a pair of solar noon &\n # solar midnight, where it crosses the threshold, but in the opposite\n # direction (i.e., where output should change state.) Note that this\n # might be today, tomorrow, days away, or never, depending on location,\n # time of year and specified threshold.\n\n # Start by finding the next five solar midnight & solar noon \"events\"\n # since current time might be anywhere from before today's solar\n # midnight (if it is this morning) to after tomorrow's solar midnight\n # (if it is this evening.)\n date = cur_dttm.date()\n evt_dttm1 = astral_event(\"solar_midnight\", date)\n evt_dttm2 = astral_event(\"solar_noon\", date)\n evt_dttm3 = astral_event(\"solar_midnight\", date + _ONE_DAY)\n evt_dttm4 = astral_event(\"solar_noon\", date + _ONE_DAY)\n evt_dttm5 = astral_event(\"solar_midnight\", date + 2 * _ONE_DAY)\n\n # See if segment we're looking for falls between any of these events.\n # If not move ahead a day and try again, but don't look more than a\n # a year ahead.\n end_date = date + 366 * _ONE_DAY\n while date < end_date:\n if cur_dttm < evt_dttm1:\n if self._state:\n t0_dttm = cur_dttm\n t1_dttm = evt_dttm1\n else:\n t0_dttm = evt_dttm1\n t1_dttm = evt_dttm2\n elif cur_dttm < evt_dttm2:\n if not self._state:\n t0_dttm = cur_dttm\n t1_dttm = evt_dttm2\n else:\n t0_dttm = evt_dttm2\n t1_dttm = evt_dttm3\n elif cur_dttm < evt_dttm3:\n if self._state:\n t0_dttm = cur_dttm\n t1_dttm = evt_dttm3\n else:\n t0_dttm = evt_dttm3\n t1_dttm = evt_dttm4\n else:\n if not self._state:\n t0_dttm = cur_dttm\n t1_dttm = evt_dttm4\n else:\n t0_dttm = evt_dttm4\n t1_dttm = evt_dttm5\n\n t0_elev = astral_event(\"solar_elevation\", t0_dttm)\n t1_elev = astral_event(\"solar_elevation\", t1_dttm)\n\n # Did we find it?\n # Note, if t1_elev > t0_elev, then we're looking for an elevation\n # ABOVE threshold. In this case we can't use this range if the\n # threshold is EQUAL to the elevation at t1, because this range\n # does NOT include any points with a higher elevation value. For\n # all other cases it's ok for the threshold to equal the elevation\n # at t0 or t1.\n if (t0_elev <= self._threshold < t1_elev\n or t1_elev <= self._threshold <= t0_elev):\n\n nxt_dttm = self._find_nxt_dttm(\n t0_dttm, t0_elev, t1_dttm, t1_elev)\n if nxt_dttm - cur_dttm > _ONE_DAY:\n _LOGGER.warning(\n 'Sun elevation will not reach %f again until %s',\n self._threshold, nxt_dttm.date())\n return nxt_dttm\n\n # Shift one day ahead.\n date += _ONE_DAY\n evt_dttm1 = evt_dttm3\n evt_dttm2 = evt_dttm4\n evt_dttm3 = evt_dttm5\n evt_dttm4 = astral_event(\"solar_noon\", date + _ONE_DAY)\n evt_dttm5 = astral_event(\"solar_midnight\", date + 2 * _ONE_DAY)\n\n # Didn't find one.\n return None\n\n async def async_update(self):\n \"\"\"Update state.\"\"\"\n cur_dttm = dt_util.now()\n cur_elev = astral_event(\"solar_elevation\", cur_dttm)\n self._state = cur_elev > self._threshold\n _LOGGER.debug(\n 'name=%s, above=%f, elevation=%f',\n self._name, self._threshold, cur_elev)\n\n nxt_dttm = self._get_nxt_dttm(cur_dttm)\n self._next_change = nxt_dttm\n\n @callback\n def async_update(now):\n self._unsub_update = None\n self.async_schedule_update_ha_state(True)\n\n if nxt_dttm:\n self._unsub_update = async_track_point_in_time(self.hass, async_update, nxt_dttm)\n else:\n _LOGGER.error(\n 'Sun elevation never reaches %f at this location',\n self._threshold)\n\n\nasync def async_setup_platform(\n hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up sensors.\"\"\"\n sensors = []\n for cfg in config[CONF_MONITORED_CONDITIONS]:\n if CONF_ELEVATION in cfg:\n options = cfg[CONF_ELEVATION]\n sensors.append(Sun2ElevationSensor(\n hass, options[CONF_NAME], options[CONF_ABOVE]))\n async_add_entities(sensors, True)\n" }, { "alpha_fraction": 0.6524865031242371, "alphanum_fraction": 0.6590772867202759, "avg_line_length": 26.816667556762695, "blob_id": "d3377c4d3a5c8743f691567eb26b5e5d57da5890", "content_id": "f3375397eef5a3f4a68d90b2e720970aa4e61cd6", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1669, "license_type": "permissive", "max_line_length": 81, "num_lines": 60, "path": "/custom_components/sun2/helpers.py", "repo_name": "testitesti22/ha-sun2", "src_encoding": "UTF-8", "text": "\"\"\"Sun2 Helpers.\"\"\"\nfrom datetime import timedelta\n\ntry:\n from astral import AstralError\nexcept ImportError:\n AstralError = TypeError\nfrom homeassistant.const import EVENT_CORE_CONFIG_UPDATE\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.dispatcher import dispatcher_send\nfrom homeassistant.helpers.sun import get_astral_location\n\nSIG_LOC_UPDATED = 'sun2_loc_updated'\n\n_LOC = None\n_ELEV = None\n_HASS = None\n\ndef _get_astral_location():\n global _LOC, _ELEV\n try:\n _LOC, _ELEV = get_astral_location(_HASS)\n except TypeError:\n _LOC = get_astral_location(_HASS)\n\n\ndef _update_location(event):\n _get_astral_location()\n dispatcher_send(_HASS, SIG_LOC_UPDATED)\n\n\n@callback\ndef async_init_astral_loc(hass):\n \"\"\"Initialize astral Location.\"\"\"\n global _HASS\n if not _LOC:\n _HASS = hass\n _get_astral_location()\n hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, _update_location)\n\n\ndef astral_event(event, date_or_dt, depression=None):\n \"\"\"Return astral event result.\"\"\"\n if depression is not None:\n _LOC.solar_depression = depression\n try:\n if _ELEV is not None:\n if event in ('solar_midnight', 'solar_noon'):\n return getattr(_LOC, event.replace('solar_', ''))(date_or_dt)\n else:\n return getattr(_LOC, event)(date_or_dt, observer_elevation=_ELEV)\n return getattr(_LOC, event)(date_or_dt)\n except AstralError:\n return 'none'\n\n\ndef nearest_second(time):\n \"\"\"Round time to nearest second.\"\"\"\n return (time.replace(microsecond=0) +\n timedelta(seconds=0 if time.microsecond < 500000 else 1))\n" } ]
3
cellcounter/cellcounter
https://github.com/cellcounter/cellcounter
7e9b8fe65845ba56f3cd6100d06836c9b9e5d2d0
a04664df7ad8bca44d0c88b89fd589419c2aca40
d14239d2f896407fc6b19d1170bef76ff4e580c3
refs/heads/master
2023-02-20T13:55:33.209410
2022-07-08T09:41:50
2022-07-08T09:41:50
5,912,723
2
3
MIT
2012-09-22T12:02:02
2022-05-29T20:10:31
2023-02-15T18:41:53
Python
[ { "alpha_fraction": 0.4168734550476074, "alphanum_fraction": 0.43176180124282837, "avg_line_length": 22.705883026123047, "blob_id": "6fee1b682b5dac84fc17d1cdd38c9131b3a4746a", "content_id": "8fd87a4821016cb73cd4ae5e4bd02d807145213f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 403, "license_type": "permissive", "max_line_length": 57, "num_lines": 17, "path": "/cellcounter/main/static/js/images.js", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "$(document).ready(function() {\n\n $('body').on(\"click\", \".modaldialog\", function() {\n\t\t\t\n var $link = $(this);\n var $dialog = $('<div></div>')\n\t\t\t.load($link.attr('href'))\n\t\t\t.dialog({\n\t\t\t\tautoOpen: false,\n\t\t\t\ttitle: $link.attr('title'),\n\t\t\t\twidth: 840,\n\t\t\t\theight: 600\n\t\t\t});\n $dialog.dialog('open');\n\t\t\treturn false;\n\t\t});\n});\n" }, { "alpha_fraction": 0.5840736031532288, "alphanum_fraction": 0.5938081741333008, "avg_line_length": 36.44820785522461, "blob_id": "3bc607318df369bb9e4a050bc461b79ea6df4972", "content_id": "ec94fb42ccdaa5bc3f993085fa6c0b7c624f8243", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18803, "license_type": "permissive", "max_line_length": 107, "num_lines": 502, "path": "/cellcounter/accounts/test_views.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from urllib.parse import urlparse\n\nfrom django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm\nfrom django.contrib.auth.models import User, AnonymousUser\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.core import mail\nfrom django.core.cache import cache\nfrom django.urls import reverse\nfrom django.test import TestCase\nfrom django.test.client import RequestFactory\nfrom django.test.utils import override_settings\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode\n\nfrom cellcounter.cc_kapi.factories import UserFactory, KeyboardFactory\nfrom .forms import EmailUserCreationForm, PasswordResetForm\nfrom .utils import read_signup_email\nfrom .views import PasswordResetConfirmView\n\n\nclass TestRegistrationView(TestCase):\n def setUp(self):\n self.request_factory = RequestFactory()\n\n def test_get(self):\n response = self.client.get(reverse(\"register\"))\n self.assertEqual(response.status_code, 200)\n self.assertIsInstance(response.context[\"form\"], EmailUserCreationForm)\n\n def test_valid(self):\n data = {\n \"username\": \"123\",\n \"email\": \"[email protected]\",\n \"password1\": \"test\",\n \"password2\": \"test\",\n \"tos\": True,\n }\n response = self.client.post(reverse(\"register\"), data=data, follow=True)\n self.assertRedirects(response, reverse(\"new_count\"))\n user = User.objects.get(username=\"123\")\n messages = list(response.context[\"messages\"])\n self.assertEqual(\n \"Successfully registered, you are now logged in! <a href='/accounts/%s/'>View your profile</a>\"\n % user.id,\n messages[0].message,\n )\n self.assertEqual(user, response.context[\"user\"])\n\n def test_invalid(self):\n data = {\n \"username\": \"123\",\n \"email\": \"[email protected]\",\n \"password1\": \"test\",\n \"password2\": \"test\",\n \"tos\": False,\n }\n response = self.client.post(reverse(\"register\"), data=data)\n self.assertEqual(response.status_code, 200)\n self.assertFormError(\n response, \"form\", \"tos\", \"You must agree our Terms of Service\"\n )\n self.assertEqual(AnonymousUser(), response.context[\"user\"])\n\n @override_settings(RATELIMIT_ENABLE=True)\n def test_ratelimit_registration(self):\n cache.clear()\n data = {\n \"username\": \"123\",\n \"email\": \"[email protected]\",\n \"password1\": \"test\",\n \"password2\": \"test\",\n \"tos\": True,\n }\n self.client.post(reverse(\"register\"), data)\n self.client.logout()\n data[\"username\"] = \"Another\"\n self.client.post(reverse(\"register\"), data, follow=True)\n self.client.logout()\n data[\"username\"] = \"Another2\"\n response = self.client.post(reverse(\"register\"), data, follow=True)\n messages = list(response.context[\"messages\"])\n self.assertEqual(1, len(messages))\n self.assertEqual(\"You have been rate limited\", messages[0].message)\n\n @override_settings(RATELIMIT_ENABLE=True)\n def test_ratelimit_invalid_form(self):\n cache.clear()\n data = {\n \"username\": \"123\",\n \"email\": \"1234\",\n \"password1\": \"test\",\n \"password2\": \"test\",\n \"tos\": True,\n }\n self.client.post(reverse(\"register\"), data)\n response = self.client.post(reverse(\"register\"), data, follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertNotIn(\"You have been rate limited\", response.content.decode(\"utf-8\"))\n\n\nclass TestPasswordChangeView(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n self.user = UserFactory()\n self.valid_data = {\n \"old_password\": \"test\",\n \"new_password1\": \"new\",\n \"new_password2\": \"new\",\n }\n self.invalid_data = {\n \"old_password\": \"test\",\n \"new_password1\": \"test\",\n \"new_password2\": \"1234\",\n }\n\n def test_logged_out_get_redirect(self):\n response = self.client.get(reverse(\"change-password\"))\n self.assertRedirects(\n response, \"%s?next=%s\" % (reverse(\"login\"), reverse(\"change-password\"))\n )\n\n def test_logged_out_post_redirect(self):\n response = self.client.post(reverse(\"change-password\"), self.valid_data)\n self.assertRedirects(\n response, \"%s?next=%s\" % (reverse(\"login\"), reverse(\"change-password\"))\n )\n\n def test_logged_in_to_form(self):\n self.client.force_login(self.user)\n response = self.client.get(reverse(\"change-password\"))\n self.assertEqual(response.status_code, 200)\n self.assertIsInstance(response.context[\"form\"], PasswordChangeForm)\n\n def test_post_valid(self):\n self.client.force_login(self.user)\n response = self.client.post(\n reverse(\"change-password\"), data=self.valid_data, follow=True\n )\n self.assertRedirects(response, reverse(\"new_count\"))\n messages = list(response.context[\"messages\"])\n self.assertEqual(\"Password changed successfully\", messages[0].message)\n\n def test_post_invalid(self):\n self.client.force_login(self.user)\n response = self.client.post(reverse(\"change-password\"), data=self.invalid_data)\n self.assertFormError(\n response, \"form\", \"new_password2\", \"The two password fields didn’t match.\"\n )\n\n\nclass TestUserDetailView(TestCase):\n def setUp(self):\n self.keyboard = KeyboardFactory()\n\n def test_get_anonymous(self):\n user2 = UserFactory()\n response = self.client.get(reverse(\"user-detail\", kwargs={\"pk\": user2.id}))\n self.assertRedirects(\n response,\n \"%s?next=%s\"\n % (reverse(\"login\"), reverse(\"user-detail\", kwargs={\"pk\": user2.id})),\n )\n\n def test_get_self(self):\n self.client.force_login(self.keyboard.user)\n response = self.client.get(\n reverse(\"user-detail\", kwargs={\"pk\": self.keyboard.user.id})\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context[\"user_detail\"], self.keyboard.user)\n self.assertEqual(len(response.context[\"keyboards\"]), 3)\n\n def test_get_someone_else(self):\n user2 = UserFactory()\n self.client.force_login(self.keyboard.user)\n response = self.client.get(reverse(\"user-detail\", kwargs={\"pk\": user2.id}))\n self.assertEqual(response.status_code, 403)\n\n\nclass TestUserDeleteView(TestCase):\n def setUp(self):\n self.user = UserFactory()\n\n def test_get_delete_anonymous(self):\n response = self.client.get(reverse(\"user-delete\", kwargs={\"pk\": self.user.id}))\n self.assertRedirects(\n response,\n \"%s?next=%s\"\n % (reverse(\"login\"), reverse(\"user-delete\", kwargs={\"pk\": self.user.id})),\n )\n\n def test_delete_anonymous(self):\n user2 = UserFactory()\n response = self.client.delete(reverse(\"user-delete\", kwargs={\"pk\": user2.id}))\n self.assertRedirects(\n response,\n \"%s?next=%s\"\n % (reverse(\"login\"), reverse(\"user-delete\", kwargs={\"pk\": user2.id})),\n )\n\n def test_get_delete_self(self):\n self.client.force_login(self.user)\n response = self.client.get(reverse(\"user-delete\", kwargs={\"pk\": self.user.id}))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, \"accounts/user_check_delete.html\")\n\n def test_delete_self(self):\n self.client.force_login(self.user)\n response = self.client.delete(\n reverse(\"user-delete\", kwargs={\"pk\": self.user.id}), follow=True\n )\n self.assertRedirects(response, reverse(\"new_count\"))\n self.assertEqual(\n \"User account deleted\", list(response.context[\"messages\"])[0].message\n )\n\n def test_get_delete_someone_else(self):\n user2 = UserFactory()\n self.client.force_login(self.user)\n response = self.client.get(reverse(\"user-delete\", kwargs={\"pk\": user2.id}))\n self.assertEqual(response.status_code, 403)\n\n def test_delete_someone_else(self):\n user2 = UserFactory()\n self.client.force_login(self.user)\n response = self.client.delete(reverse(\"user-delete\", kwargs={\"pk\": user2.id}))\n self.assertEqual(response.status_code, 403)\n\n\nclass TestUserUpdateView(TestCase):\n def setUp(self):\n self.valid_data = {\n \"first_name\": \"Jack\",\n \"last_name\": \"Example\",\n \"email\": \"[email protected]\",\n }\n self.extra_data = {\n \"first_name\": \"Joe\",\n \"last_name\": \"Example\",\n \"email\": \"[email protected]\",\n \"username\": \"invalid\",\n }\n self.invalid_data = {\n \"first_name\": \"Joe\",\n \"last_name\": \"Example\",\n \"email\": \"1234\",\n }\n\n def test_get_update_when_anonymous(self):\n user = UserFactory()\n response = self.client.get(reverse(\"user-update\", kwargs={\"pk\": user.id}))\n self.assertRedirects(\n response,\n \"%s?next=%s\"\n % (reverse(\"login\"), reverse(\"user-update\", kwargs={\"pk\": user.id})),\n )\n\n def test_post_update_when_anonymous(self):\n user = UserFactory()\n response = self.client.post(\n reverse(\"user-update\", kwargs={\"pk\": user.id}), data=self.valid_data\n )\n self.assertRedirects(\n response,\n \"%s?next=%s\"\n % (reverse(\"login\"), reverse(\"user-update\", kwargs={\"pk\": user.id})),\n )\n\n def test_update_self_valid(self):\n user = UserFactory()\n self.client.force_login(user)\n response = self.client.post(\n reverse(\"user-update\", kwargs={\"pk\": user.id}),\n data=self.valid_data,\n follow=True,\n )\n self.assertRedirects(response, reverse(\"user-detail\", kwargs={\"pk\": user.id}))\n self.assertEqual(\n \"User details updated\", list(response.context[\"messages\"])[0].message\n )\n updated_user = User.objects.get(username=user.username)\n self.assertNotEqual(updated_user.first_name, user.first_name)\n self.assertNotEqual(updated_user.last_name, user.last_name)\n self.assertNotEqual(updated_user.email, user.email)\n\n def test_update_self_extra(self):\n user = UserFactory()\n self.client.force_login(user)\n response = self.client.post(\n reverse(\"user-update\", kwargs={\"pk\": user.id}),\n data=self.extra_data,\n follow=True,\n )\n self.assertRedirects(response, reverse(\"user-detail\", kwargs={\"pk\": user.id}))\n self.assertEqual(\n \"User details updated\", list(response.context[\"messages\"])[0].message\n )\n updated_user = User.objects.get(username=user.username)\n self.assertNotEqual(updated_user.first_name, user.first_name)\n self.assertNotEqual(updated_user.last_name, user.last_name)\n self.assertNotEqual(updated_user.email, user.email)\n self.assertEqual(updated_user.username, user.username)\n\n def test_update_self_invalid(self):\n user = UserFactory()\n self.client.force_login(user)\n response = self.client.post(\n reverse(\"user-update\", kwargs={\"pk\": user.id}), data=self.invalid_data\n )\n self.assertEqual(response.status_code, 200)\n self.assertFormError(response, \"form\", \"email\", \"Enter a valid email address.\")\n\n def test_update_someone_else(self):\n user = UserFactory()\n user2 = UserFactory()\n self.client.force_login(user)\n response = self.client.post(reverse(\"user-update\", kwargs={\"pk\": user2.id}))\n self.assertEqual(response.status_code, 403)\n\n\nclass TestPasswordResetView(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n self.user = UserFactory()\n\n def test_get_form(self):\n response = self.client.get(reverse(\"password-reset\"))\n self.assertEqual(response.status_code, 200)\n self.assertIsInstance(response.context[\"form\"], PasswordResetForm)\n self.assertTemplateUsed(response, \"accounts/reset_form.html\")\n\n def test_post_valid_email(self):\n data = {\"email\": self.user.email}\n response = self.client.post(reverse(\"password-reset\"), data=data, follow=True)\n self.assertRedirects(response, reverse(\"new_count\"))\n self.assertEqual(\n \"Reset email sent\", list(response.context[\"messages\"])[0].message\n )\n self.assertEqual(1, len(mail.outbox))\n url, path = read_signup_email(mail.outbox[0])\n uidb64, token = urlparse(url).path.split(\"/\")[-3:-1]\n self.assertEqual(\n path,\n reverse(\n \"password-reset-confirm\", kwargs={\"uidb64\": uidb64, \"token\": token}\n ),\n )\n\n def test_post_invalid_email(self):\n data = {\"email\": \"[email protected]\"}\n response = self.client.post(reverse(\"password-reset\"), data=data, follow=True)\n self.assertRedirects(response, reverse(\"new_count\"))\n self.assertEqual(0, len(mail.outbox))\n\n @override_settings(RATELIMIT_ENABLE=True)\n def test_post_ratelimit(self):\n for n in range(0, 5):\n self.client.post(\n reverse(\"password-reset\"), data={\"email\": self.user.email}, follow=True\n )\n response = self.client.post(\n reverse(\"password-reset\"), data={\"email\": self.user.email}, follow=True\n )\n self.assertEqual(\n list(response.context[\"messages\"])[0].message, \"You have been rate limited\"\n )\n cache.clear()\n\n\nclass TestPasswordResetConfirmView(TestCase):\n def setUp(self):\n self.user = UserFactory()\n self.valid_uidb64 = urlsafe_base64_encode(force_bytes(self.user.pk))\n self.valid_data = {\"new_password1\": \"newpwd\", \"new_password2\": \"newpwd\"}\n self.invalid_data = {\"new_password1\": \"newpwd\", \"new_password2\": \"1234\"}\n\n def _generate_token(self, user):\n return default_token_generator.make_token(user)\n\n def test_valid_user_valid(self):\n \"\"\"valid_user() with valid uidb64\"\"\"\n self.assertEqual(\n PasswordResetConfirmView().valid_user(self.valid_uidb64), self.user\n )\n\n def test_valid_user_invalid(self):\n \"\"\"valid_user() with invalid uidb64\"\"\"\n uidb64 = urlsafe_base64_encode(force_bytes(2))\n self.assertIsNone(PasswordResetConfirmView().valid_user(uidb64))\n\n def test_valid_token_valid(self):\n \"\"\"valid_token() with valid user and token\"\"\"\n self.assertTrue(\n PasswordResetConfirmView().valid_token(\n self.user, self._generate_token(self.user)\n )\n )\n\n def test_valid_token_invalid_token(self):\n \"\"\"valid_token() with valid user and invalid token\"\"\"\n token = \"AAA-AAAAAAAAAAAAAAAAAAAA\"\n self.assertFalse(PasswordResetConfirmView().valid_token(self.user, token))\n\n def test_valid_token_invalid_both(self):\n \"\"\"valid_token() with invalid user and invalid token\"\"\"\n token = \"AAA-AAAAAAAAAAAAAAAAAAAA\"\n self.assertFalse(\n PasswordResetConfirmView().valid_token(\n None, self._generate_token(self.user)\n )\n )\n\n def test_get_invalid_token(self):\n token = \"AAA-AAAAAAAAAAAAAAAAAAAA\"\n response = self.client.get(\n reverse(\n \"password-reset-confirm\",\n kwargs={\"uidb64\": self.valid_uidb64, \"token\": token},\n )\n )\n self.assertEqual(response.status_code, 200)\n self.assertFalse(response.context[\"validlink\"])\n self.assertIn(\n \"The password reset link was invalid, possibly because it has already been used.\"\n \" Please request a new password reset.\",\n response.content.decode(\"utf-8\"),\n )\n\n def test_get_invalid_user(self):\n response = self.client.get(\n reverse(\n \"password-reset-confirm\",\n kwargs={\n \"uidb64\": urlsafe_base64_encode(force_bytes(2)),\n \"token\": self._generate_token(self.user),\n },\n )\n )\n self.assertEqual(response.status_code, 200)\n self.assertFalse(response.context[\"validlink\"])\n self.assertIn(\n \"The password reset link was invalid, possibly because it has already been used.\"\n \" Please request a new password reset.\",\n response.content.decode(\"utf-8\"),\n )\n\n def test_post_invalid_token(self):\n token = \"AAA-AAAAAAAAAAAAAAAAAAAA\"\n response = self.client.post(\n reverse(\n \"password-reset-confirm\",\n kwargs={\"uidb64\": self.valid_uidb64, \"token\": token},\n ),\n data=self.valid_data,\n )\n self.assertEqual(response.status_code, 200)\n self.assertFalse(response.context[\"validlink\"])\n self.assertIn(\n \"The password reset link was invalid, possibly because it has already been used.\"\n \" Please request a new password reset.\",\n response.content.decode(\"utf-8\"),\n )\n\n def test_get_valid(self):\n token = self._generate_token(self.user)\n response = self.client.get(\n reverse(\n \"password-reset-confirm\",\n kwargs={\"uidb64\": self.valid_uidb64, \"token\": token},\n )\n )\n self.assertEqual(response.status_code, 200)\n self.assertIsInstance(response.context[\"form\"], SetPasswordForm)\n\n def test_post_valid(self):\n token = self._generate_token(self.user)\n response = self.client.post(\n reverse(\n \"password-reset-confirm\",\n kwargs={\"uidb64\": self.valid_uidb64, \"token\": token},\n ),\n data=self.valid_data,\n follow=True,\n )\n self.assertRedirects(response, reverse(\"new_count\"))\n self.assertEqual(\n \"Password reset successfully\", list(response.context[\"messages\"])[0].message\n )\n\n def test_post_invalid(self):\n token = self._generate_token(self.user)\n response = self.client.post(\n reverse(\n \"password-reset-confirm\",\n kwargs={\"uidb64\": self.valid_uidb64, \"token\": token},\n ),\n data=self.invalid_data,\n )\n self.assertEqual(response.status_code, 200)\n self.assertFormError(\n response, \"form\", \"new_password2\", \"The two password fields didn’t match.\"\n )\n" }, { "alpha_fraction": 0.49888041615486145, "alphanum_fraction": 0.49888041615486145, "avg_line_length": 33.890625, "blob_id": "ca73f2b4a2bcb8367cb22c2cff63ab757268506e", "content_id": "6b59fbb320b92bb136607b11f59d8d719fc19140", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2233, "license_type": "permissive", "max_line_length": 88, "num_lines": 64, "path": "/cellcounter/cc_kapi/routers.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from rest_framework.routers import Route, SimpleRouter\n\nfrom .models import Keyboard\n\n\nclass KeyboardAPIRouter(SimpleRouter):\n \"\"\"\n A router for the keyboard API, which splits desktop and mobile.\n \"\"\"\n\n routes = [\n Route(\n url=r\"^{prefix}/$\",\n mapping={\"get\": \"list\"},\n name=\"{basename}-list\",\n detail=False,\n initkwargs={\"suffix\": \"List\"},\n ),\n Route(\n url=r\"^{prefix}/desktop/$\",\n mapping={\"get\": \"list\", \"post\": \"create\"},\n name=\"{basename}-desktop-list\",\n detail=False,\n initkwargs={\"suffix\": \"Desktop List\", \"device_type\": Keyboard.DESKTOP},\n ),\n Route(\n url=r\"^{prefix}/desktop/{lookup}/$\",\n mapping={\"get\": \"retrieve\", \"put\": \"update\", \"delete\": \"destroy\"},\n name=\"{basename}-desktop-detail\",\n detail=True,\n initkwargs={\"suffix\": \"Desktop Detail\", \"device_type\": Keyboard.DESKTOP},\n ),\n Route(\n url=r\"^{prefix}/desktop/{lookup}/set_default$\",\n mapping={\"put\": \"set_default\"},\n name=\"{basename}-desktop-set_default\",\n detail=True,\n initkwargs={\n \"suffix\": \"Desktop Set Default\",\n \"device_type\": Keyboard.DESKTOP,\n },\n ),\n Route(\n url=r\"^{prefix}/mobile/$\",\n mapping={\"get\": \"list\", \"post\": \"create\"},\n name=\"{basename}-mobile-list\",\n detail=False,\n initkwargs={\"suffix\": \"Mobile List\", \"device_type\": Keyboard.MOBILE},\n ),\n Route(\n url=r\"^{prefix}/mobile/{lookup}/$\",\n mapping={\"get\": \"retrieve\", \"put\": \"update\", \"delete\": \"destroy\"},\n name=\"{basename}-mobile-detail\",\n detail=True,\n initkwargs={\"suffix\": \"Mobile Detail\", \"device_type\": Keyboard.MOBILE},\n ),\n Route(\n url=r\"^{prefix}/mobile/{lookup}/set_default$\",\n mapping={\"put\": \"set_default\"},\n name=\"{basename}-mobile-set_default\",\n detail=True,\n initkwargs={\"suffix\": \"Mobile Set Default\", \"device_type\": Keyboard.MOBILE},\n ),\n ]\n" }, { "alpha_fraction": 0.6350957155227661, "alphanum_fraction": 0.6370418667793274, "avg_line_length": 29.22549057006836, "blob_id": "3afec0e3523d798157e32c28c83b0f5343cec3a5", "content_id": "98d848e7aeb44fd8da906dba509031e70ff875c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3083, "license_type": "permissive", "max_line_length": 84, "num_lines": 102, "path": "/cellcounter/cc_kapi/models.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\nfrom cellcounter.main.models import CellType\n\nfrom django.utils import timezone\n\n\nclass Keyboard(models.Model):\n \"\"\"Represents a Keyboard mapping between users and keys\"\"\"\n\n DESKTOP = 1\n MOBILE = 2\n\n DEVICE_TYPES = (\n (DESKTOP, \"desktop\"),\n (MOBILE, \"mobile\"),\n )\n\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n label = models.CharField(max_length=25)\n created = models.DateTimeField(auto_now_add=True)\n last_modified = models.DateTimeField(auto_now=True)\n device_type = models.PositiveIntegerField(choices=DEVICE_TYPES, default=DESKTOP)\n\n _is_default = False\n\n def _set_default(self):\n self._is_default = True\n\n @property\n def is_default(self):\n return self._is_default\n\n @is_default.setter\n def is_default(self, value):\n self._set_default()\n to_set = self\n if not self.user:\n to_set = None\n if self.device_type == self.DESKTOP:\n self.user.defaultkeyboards.desktop = to_set\n elif self.device_type == self.MOBILE:\n self.user.defaultkeyboards.mobile = to_set\n\n def __unicode__(self):\n if self.user is None:\n return \"Builtin Keyboard '%s'\" % (self.label)\n else:\n return \"Keyboard '%s' for user '%s'\" % (self.label, self.user.username)\n\n def _sync_keymaps(self, new_mapping_list):\n \"\"\"Expects a list of KeyMap objects\"\"\"\n current_mappings = self.mappings.all()\n new_mappings = new_mapping_list\n\n [self.mappings.remove(x) for x in current_mappings if x not in new_mappings]\n [self.mappings.add(x) for x in new_mappings if x not in current_mappings]\n\n def set_keymaps(self, new_mapping_list):\n \"\"\"new_mapping_list is a list of KeyMap objects\"\"\"\n self._sync_keymaps(new_mapping_list)\n\n def save(\n self, force_insert=False, force_update=False, using=None, update_fields=None\n ):\n\n if self.user:\n self.last_modified = timezone.now()\n\n super(Keyboard, self).save(\n force_insert=False, force_update=False, using=None, update_fields=None\n )\n\n\nclass KeyMap(models.Model):\n cellid = models.ForeignKey(CellType, on_delete=models.CASCADE)\n key = models.CharField(max_length=1)\n keyboards = models.ManyToManyField(Keyboard, related_name=\"mappings\")\n\n\nclass DefaultKeyboards(models.Model):\n \"\"\"Maps the default keyboard settings (desktop and mobile) to the user\"\"\"\n\n user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)\n desktop = models.ForeignKey(\n Keyboard,\n default=None,\n related_name=\"desktop_default\",\n null=True,\n on_delete=models.CASCADE,\n )\n mobile = models.ForeignKey(\n Keyboard,\n default=None,\n related_name=\"mobile_default\",\n null=True,\n on_delete=models.CASCADE,\n )\n\n def __str__(self): # __unicode__ on Python 2\n return \"%s default keyboard mappings\" % self.user.username\n" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 38.46154022216797, "blob_id": "7843e765bcc1f79cd9ebd3d9389f6572e3085a2e", "content_id": "0ce9a9a9df2102e67306f2d34c4d754b20c1631f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 513, "license_type": "permissive", "max_line_length": 86, "num_lines": 13, "path": "/cellcounter/statistics/middleware.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.contrib.sessions import middleware\n\n\nclass StatsSessionMiddleware(middleware.SessionMiddleware):\n def process_request(self, request):\n session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)\n request.session = self.SessionStore(session_key)\n if not session_key:\n request.session.save()\n\n def process_response(self, request, response):\n return super(StatsSessionMiddleware, self).process_response(request, response)\n" }, { "alpha_fraction": 0.6246227025985718, "alphanum_fraction": 0.625053882598877, "avg_line_length": 28.730770111083984, "blob_id": "14c41461983cdfb36516f29e202e9605d878bf8a", "content_id": "eb59893fe635d4a0bd0d54e4ba17da642e5c386f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4638, "license_type": "permissive", "max_line_length": 88, "num_lines": 156, "path": "/cellcounter/cc_kapi/serializers.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\n\nfrom .models import KeyMap, Keyboard\nfrom django.contrib.auth.models import User\n\nfrom django.urls import reverse\n\n\nclass KeyMapSerializer(serializers.ModelSerializer):\n class Meta:\n model = KeyMap\n fields = (\"cellid\", \"key\")\n\n\nclass KeyboardListItemSerializer(serializers.ModelSerializer):\n \"\"\"Serialises a list of keyboards with hrefs.\"\"\"\n\n class Meta:\n model = Keyboard\n fields = (\n \"id\",\n \"user\",\n \"label\",\n \"created\",\n \"last_modified\",\n \"is_default\",\n \"device_type\",\n \"href\",\n )\n read_only_fields = (\"href\",)\n\n id = serializers.IntegerField(required=False)\n user = serializers.CharField(source=\"user.username\") # , allow_null=True)\n device_type = serializers.SerializerMethodField()\n\n is_default = serializers.BooleanField()\n\n # XXX: This is a hack but I can't get HyperlinkedIdentityField to work, which\n # seems like it should be the right answer\n href = serializers.SerializerMethodField(\"get_api_url\")\n\n def get_api_url(self, obj):\n return reverse(\n \"keyboards-%s-detail\" % obj.get_device_type_display(), kwargs={\"pk\": obj.id}\n )\n\n def get_device_type(self, obj):\n return obj.get_device_type_display()\n\n\nclass ChoiceField(serializers.ChoiceField):\n def to_representation(self, obj):\n if obj == \"\" and self.allow_blank:\n return obj\n return self._choices[obj]\n\n def to_internal_value(self, data):\n # To support inserts with the value\n if data == \"\" and self.allow_blank:\n return \"\"\n\n for key, val in self._choices.items():\n if val == data:\n return key\n self.fail(\"invalid_choice\", input=data)\n\n\nclass KeyboardSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField(required=False)\n user = serializers.CharField(\n source=\"user.username\", allow_null=True, required=False\n )\n device_type = ChoiceField(choices=Keyboard.DEVICE_TYPES)\n mappings = KeyMapSerializer(many=True)\n\n class Meta:\n model = Keyboard\n fields = (\n \"id\",\n \"user\",\n \"label\",\n \"created\",\n \"last_modified\",\n \"device_type\",\n \"mappings\",\n )\n\n def create_from_self(self):\n return self.create(self.validated_data)\n\n def create(self, validated_data):\n mappings_data = validated_data.pop(\"mappings\")\n keyboard = Keyboard.objects.create(**validated_data)\n mapping_objects = [\n KeyMap.objects.get_or_create(cellid=mapping[\"cellid\"], key=mapping[\"key\"])[\n 0\n ]\n for mapping in mappings_data\n ]\n keyboard.set_keymaps(mapping_objects)\n return keyboard\n\n def update(self, instance, validated_data):\n mappings_data = validated_data.pop(\"mappings\")\n instance.label = validated_data.get(\"label\", instance.label)\n instance.save()\n\n mapping_objects = [\n KeyMap.objects.get_or_create(cellid=mapping[\"cellid\"], key=mapping[\"key\"])[\n 0\n ]\n for mapping in mappings_data\n ]\n instance.set_keymaps(mapping_objects)\n return instance\n\n\nclass MappingList(serializers.Serializer):\n cellid = serializers.IntegerField()\n key = serializers.CharField()\n\n\nclass BuiltinKeyboardSerializer(serializers.Serializer):\n id = serializers.CharField(required=False)\n user = serializers.CharField(required=False)\n device_type = serializers.SerializerMethodField()\n label = serializers.CharField()\n created = serializers.DateTimeField()\n last_modified = serializers.DateTimeField()\n\n mappings = MappingList(many=True)\n\n def get_device_type(self, obj):\n return obj.get_device_type_display()\n\n\nclass BuiltinKeyboardListItemSerializer(serializers.Serializer):\n id = serializers.CharField(required=False)\n user = serializers.CharField(required=False)\n device_type = serializers.SerializerMethodField()\n label = serializers.CharField()\n created = serializers.DateTimeField()\n last_modified = serializers.DateTimeField()\n\n is_default = serializers.BooleanField()\n\n href = serializers.SerializerMethodField(\"get_api_url\")\n\n def get_api_url(self, obj):\n return reverse(\n \"keyboards-%s-detail\" % obj.get_device_type_display(),\n kwargs={\"pk\": \"builtin\"},\n )\n\n def get_device_type(self, obj):\n return obj.get_device_type_display()\n" }, { "alpha_fraction": 0.41326531767845154, "alphanum_fraction": 0.49384236335754395, "avg_line_length": 41.417911529541016, "blob_id": "2044cb5fadc346634909af1fd78dea97b63c461b", "content_id": "920c878eae67ecb1061292d2242007c34421f3ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5684, "license_type": "permissive", "max_line_length": 509, "num_lines": 134, "path": "/cellcounter/cc_kapi/defaults.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom pytz import utc\n\nfrom .models import Keyboard\n\nBUILTIN_DESKTOP_KEYBOARD_MAP = {\n \"id\": \"builtin\",\n \"user\": None,\n \"label\": \"Default desktop\",\n \"created\": datetime.datetime(2013, 10, 22, 12, 15, 5, 0, tzinfo=utc),\n \"last_modified\": datetime.datetime(2013, 10, 22, 12, 15, 13, 0, tzinfo=utc),\n \"device_type\": Keyboard.DESKTOP,\n \"mappings\": [\n {\"cellid\": 1, \"key\": \"q\"},\n {\"cellid\": 2, \"key\": \"w\"},\n {\"cellid\": 3, \"key\": \"e\"},\n {\"cellid\": 4, \"key\": \"r\"},\n {\"cellid\": 5, \"key\": \"t\"},\n {\"cellid\": 8, \"key\": \"a\"},\n {\"cellid\": 9, \"key\": \"s\"},\n {\"cellid\": 11, \"key\": \"d\"},\n {\"cellid\": 10, \"key\": \"f\"},\n {\"cellid\": 13, \"key\": \"g\"},\n {\"cellid\": 7, \"key\": \"z\"},\n {\"cellid\": 6, \"key\": \"x\"},\n {\"cellid\": 12, \"key\": \"c\"},\n ],\n}\n\n\nBUILTIN_MOBILE_KEYBOARD_MAP = {\n \"id\": \"builtin\",\n \"user\": None,\n \"label\": \"Default mobile\",\n \"created\": datetime.datetime(2016, 5, 21, 12, 33, 0, 0, tzinfo=utc),\n \"last_modified\": datetime.datetime(2016, 5, 21, 12, 33, 0, 0, tzinfo=utc),\n \"device_type\": Keyboard.MOBILE,\n \"mappings\": [\n {\"cellid\": 1, \"key\": \"q\"},\n {\"cellid\": 2, \"key\": \"w\"},\n {\"cellid\": 3, \"key\": \"e\"},\n {\"cellid\": 4, \"key\": \"r\"},\n {\"cellid\": 5, \"key\": \"t\"},\n {\"cellid\": 8, \"key\": \"a\"},\n {\"cellid\": 9, \"key\": \"s\"},\n {\"cellid\": 11, \"key\": \"d\"},\n {\"cellid\": 10, \"key\": \"f\"},\n {\"cellid\": 13, \"key\": \"g\"},\n {\"cellid\": 7, \"key\": \"z\"},\n {\"cellid\": 6, \"key\": \"x\"},\n {\"cellid\": 12, \"key\": \"c\"},\n ],\n}\n\nBUILTIN_KEYBOARDS = [BUILTIN_DESKTOP_KEYBOARD_MAP, BUILTIN_MOBILE_KEYBOARD_MAP]\n\nMOCK_KEYBOARD = {\n \"mappings\": [\n {\"cellid\": 1, \"key\": \"q\"},\n {\"cellid\": 2, \"key\": \"w\"},\n {\"cellid\": 3, \"key\": \"e\"},\n {\"cellid\": 4, \"key\": \"r\"},\n {\"cellid\": 5, \"key\": \"t\"},\n {\"cellid\": 8, \"key\": \"a\"},\n {\"cellid\": 9, \"key\": \"s\"},\n {\"cellid\": 11, \"key\": \"d\"},\n {\"cellid\": 10, \"key\": \"f\"},\n {\"cellid\": 13, \"key\": \"g\"},\n {\"cellid\": 7, \"key\": \"z\"},\n {\"cellid\": 6, \"key\": \"x\"},\n {\"cellid\": 12, \"key\": \"c\"},\n ],\n \"created\": \"2013-10-22T12:15:05.118Z\",\n \"label\": \"Default\",\n \"last_modified\": \"2013-10-22T12:15:13.201Z\",\n \"user\": None,\n \"device_type\": \"desktop\",\n}\n\nMOCK_KEYBOARD2 = {\n \"mappings\": [\n {\"cellid\": 1, \"key\": \"q\"},\n {\"cellid\": 2, \"key\": \"w\"},\n {\"cellid\": 3, \"key\": \"e\"},\n {\"cellid\": 4, \"key\": \"r\"},\n {\"cellid\": 5, \"key\": \"t\"},\n {\"cellid\": 8, \"key\": \"a\"},\n {\"cellid\": 9, \"key\": \"s\"},\n {\"cellid\": 11, \"key\": \"d\"},\n {\"cellid\": 10, \"key\": \"f\"},\n {\"cellid\": 13, \"key\": \"g\"},\n {\"cellid\": 7, \"key\": \"z\"},\n {\"cellid\": 6, \"key\": \"x\"},\n {\"cellid\": 12, \"key\": \"c\"},\n ],\n \"created\": \"2013-10-22T12:15:05.118Z\",\n \"label\": \"Keyboard2\",\n \"last_modified\": \"2013-10-22T12:15:13.201Z\",\n \"user\": None,\n \"device_type\": \"desktop\",\n}\n\nBAD_KEYBOARD = {\n \"mappings\": [\n {\"cellid\": 1, \"key\": \"q\"},\n {\"cellid\": 2, \"key\": \"w\"},\n {\"cellid\": 3, \"key\": \"e\"},\n {\"cellid\": 4, \"key\": \"r\"},\n {\"cellid\": 5, \"key\": \"t\"},\n {\"cellid\": 8, \"key\": \"a\"},\n {\"cellid\": 9, \"key\": \"s\"},\n {\"cellid\": 11, \"key\": \"d\"},\n {\"cellid\": 10, \"key\": \"f\"},\n {\"cellid\": 13, \"key\": \"g\"},\n {\"cellid\": 7, \"key\": \"z\"},\n {\"cellid\": 6, \"key\": \"x\"},\n {\"cellid\": 12, \"key\": \"c\"},\n ],\n \"created\": \"2013-10-22T12:15:05.118Z\",\n \"is_default\": True,\n \"labelxxx\": \"Default\",\n \"last_modified\": \"2013-10-22T12:15:13.201Z\",\n \"userxxx\": None,\n \"device_type\": \"desktopz\",\n}\n\nBUILTIN_DESKTOP_KEYBOARD_STRING = \"\"\"{\"mappings\":[{\"cellid\":1,\"key\":\"q\"},{\"cellid\":2,\"key\":\"w\"},{\"cellid\":3,\"key\":\"e\"},{\"cellid\":4,\"key\":\"r\"},{\"cellid\":5,\"key\":\"t\"},{\"cellid\":8,\"key\":\"a\"},{\"cellid\":9,\"key\":\"s\"},{\"cellid\":11,\"key\":\"d\"},{\"cellid\":10,\"key\":\"f\"},{\"cellid\":13,\"key\":\"g\"},{\"cellid\":7,\"key\":\"z\"},{\"cellid\":6,\"key\":\"x\"},{\"cellid\":12,\"key\":\"c\"}],\"created\":\"2013-10-22T12:15:05.118Z\",\"is_default\":true,\"label\":\"Default\",\"last_modified\":\"2013-10-22T12:15:13.201Z\",\"user\":null,\"device_type\":\"desktop\"}\"\"\"\n\nBUILTIN_MOBILE_KEYBOARD_STRING = \"\"\"{\"mappings\":[{\"cellid\":1,\"key\":\"q\"},{\"cellid\":2,\"key\":\"w\"},{\"cellid\":3,\"key\":\"e\"},{\"cellid\":4,\"key\":\"r\"},{\"cellid\":5,\"key\":\"t\"},{\"cellid\":8,\"key\":\"a\"},{\"cellid\":9,\"key\":\"s\"},{\"cellid\":11,\"key\":\"d\"},{\"cellid\":10,\"key\":\"f\"},{\"cellid\":13,\"key\":\"g\"},{\"cellid\":7,\"key\":\"z\"},{\"cellid\":6,\"key\":\"x\"},{\"cellid\":12,\"key\":\"c\"}],\"created\":\"2013-10-22T12:15:05.118Z\",\"is_default\":true,\"label\":\"Default\",\"last_modified\":\"2013-10-22T12:15:13.201Z\",\"user\":null,\"device_type\":\"mobile\"}\"\"\"\n\nBUILTIN_KEYBOARD_STRING = \"\"\"[{\"id\":\"builtin\",\"user\":null,\"label\":\"Default desktop\",\"created\":\"2013-10-22T12:15:05Z\",\"last_modified\":\"2013-10-22T12:15:13Z\",\"device_type\":\"desktop\",\"is_default\":true,\"href\":\"/api/keyboards/desktop/builtin/\"},{\"id\":\"builtin\",\"user\":null,\"label\":\"Default mobile\",\"created\":\"2016-05-21T12:33:00Z\",\"last_modified\":\"2016-05-21T12:33:00Z\",\"device_type\":\"mobile\",\"is_default\":true,\"href\":\"/api/keyboards/mobile/builtin/\"}]\"\"\"\n\nBUILTIN_KEYBOARD_STRING_LOGGED_IN = \"\"\"[{\"id\":\"builtin\",\"user\":null,\"label\":\"Default desktop\",\"created\":\"2013-10-22T12:15:05Z\",\"last_modified\":\"2013-10-22T12:15:13Z\",\"device_type\":\"desktop\",\"is_default\":true,\"href\":\"/api/keyboards/desktop/builtin/\"},{\"id\":\"builtin\",\"user\":null,\"label\":\"Default mobile\",\"created\":\"2016-05-21T12:33:00Z\",\"last_modified\":\"2016-05-21T12:33:00Z\",\"device_type\":\"mobile\",\"is_default\":true,\"href\":\"/api/keyboards/mobile/builtin/\"}]\"\"\"\n" }, { "alpha_fraction": 0.5581144690513611, "alphanum_fraction": 0.5591919422149658, "avg_line_length": 38.49468231201172, "blob_id": "a1946a41b58550e8e34a402442a1bae408ffb4a0", "content_id": "4d8e7daceac74e6ab43e1e5cb1bbedf48f4c697c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7425, "license_type": "permissive", "max_line_length": 86, "num_lines": 188, "path": "/cellcounter/main/management/commands/fix_database.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nimport psycopg2\nfrom psycopg2.extras import DictCursor\n\nfrom django.core.management.base import BaseCommand\nfrom django.contrib.auth.models import User\n\nfrom cellcounter.cc_kapi.models import Keyboard, KeyMap\nfrom cellcounter.main.models import CellType, CellImage, License, CopyrightHolder\n\n\nclass Command(BaseCommand):\n help = \"Fixes broken database migration\"\n\n def handle(self, *args, **options):\n dbname = os.environ.get(\"OLD_DB_NAME\", None)\n dbuser = os.environ.get(\"OLD_DB_USER\", None)\n dbpwd = os.environ.get(\"OLD_DB_PWD\", None)\n\n if any(a is None for a in [dbname, dbuser, dbpwd]):\n sys.exit(\n \"You have not supplied sufficient data for old database connection\"\n )\n\n connect_string = \"dbname=%s user=%s password=%s host=localhost port=5432\" % (\n dbname,\n dbuser,\n dbpwd,\n )\n conn = psycopg2.connect(connect_string)\n dict_cur = conn.cursor(cursor_factory=DictCursor)\n\n # Get old users\n dict_cur.execute(\"SELECT * FROM auth_user;\")\n old_user_list = dict_cur.fetchall()\n\n for user_tuple in old_user_list:\n user_id = user_tuple[\"id\"]\n username = user_tuple[\"username\"]\n password = user_tuple[\"password\"]\n first_name = user_tuple[\"first_name\"]\n last_name = user_tuple[\"last_name\"]\n email = user_tuple[\"email\"]\n date_joined = user_tuple[\"date_joined\"]\n is_staff = user_tuple[\"is_staff\"]\n is_superuser = user_tuple[\"is_superuser\"]\n\n new_user = User.objects.create_user(\n username=username,\n email=email,\n password=password,\n first_name=first_name,\n last_name=last_name,\n )\n new_user.date_joined = date_joined\n new_user.is_staff = is_staff\n new_user.is_superuser = is_superuser\n new_user.save()\n\n dict_cur.execute(\n \"SELECT * FROM cc_kapi_keyboard WHERE user_id=%s\" % user_id\n )\n user_keyboards = dict_cur.fetchall()\n\n for keyboard_tuple in user_keyboards:\n old_keyboard_id = keyboard_tuple[\"id\"]\n old_label = keyboard_tuple[\"label\"]\n is_default = keyboard_tuple[\"is_default\"]\n created = keyboard_tuple[\"created\"]\n\n new_keyboard = Keyboard.objects.create(\n user=new_user,\n label=old_label,\n is_primary=is_primary,\n created=created,\n )\n\n # Add new maps to keyboards\n dict_cur.execute(\n \"SELECT * FROM cc_kapi_keymap_keyboards WHERE keyboard_id=%s\"\n % old_keyboard_id\n )\n old_maps_list = dict_cur.fetchall()\n\n new_maps = []\n\n for old_map_tuple in old_maps_list:\n keymap_id = old_map_tuple[\"keymap_id\"]\n dict_cur.execute(\n \"SELECT * FROM cc_kapi_keymap WHERE id=%s\" % keymap_id\n )\n old_keymap_tuple = dict_cur.fetchone()\n old_keymap_key = old_keymap_tuple[\"key\"]\n cell = CellType.objects.get(id=old_keymap_tuple[\"cellid_id\"])\n\n new_keymap = KeyMap.objects.get_or_create(\n key=old_keymap_key, cellid=cell\n )[0]\n new_maps.append(new_keymap)\n\n new_keyboard.set_keymaps(new_maps)\n\n # Save across all the CellImage related stuff\n dict_cur.execute(\"SELECT * FROM main_license\")\n old_license_list = dict_cur.fetchall()\n\n for old_license_tuple in old_license_list:\n new_license = License.objects.create(\n title=old_license_tuple[\"title\"], details=old_license_tuple[\"details\"]\n )\n\n dict_cur.execute(\"SELECT * FROM main_copyrightholder\")\n old_copyrightholder_list = dict_cur.fetchall()\n\n for old_copyrightholder_tuple in old_copyrightholder_list:\n old_id = old_copyrightholder_tuple[\"id\"]\n dict_cur.execute(\n \"SELECT * FROM main_copyrightholder_user where copyrightholder_id=%s\"\n % old_id\n )\n old_copyrightholder_user = dict_cur.fetchone()\n old_user_id = old_copyrightholder_user[\"user_id\"]\n dict_cur.execute(\"SELECT * FROM auth_user WHERE id=%s\" % old_user_id)\n old_user = dict_cur.fetchone()\n old_username = old_user[\"username\"]\n new_user = User.objects.get(username=old_username)\n new_copyrightholder = CopyrightHolder.objects.create(\n name=old_copyrightholder_tuple[\"name\"],\n link_title=old_copyrightholder_tuple[\"link_title\"],\n link_url=old_copyrightholder_tuple[\"link_url\"],\n )\n new_copyrightholder.user.add(new_user)\n\n # Migrate over CellImages\n\n dict_cur.execute(\"SELECT * FROM main_cellimage\")\n old_cellimage_list = dict_cur.fetchall()\n\n for old_cellimage_tuple in old_cellimage_list:\n old_title = old_cellimage_tuple[\"title\"]\n old_description = old_cellimage_tuple[\"description\"]\n old_file = old_cellimage_tuple[\"file\"]\n old_thumbnail = old_cellimage_tuple[\"thumbnail\"]\n old_celltype = old_cellimage_tuple[\"celltype_id\"]\n old_thumbnail_left = old_cellimage_tuple[\"thumbnail_left\"]\n old_thumbnail_top = old_cellimage_tuple[\"thumbnail_top\"]\n old_thumbnail_width = old_cellimage_tuple[\"thumbnail_width\"]\n old_uploader = old_cellimage_tuple[\"uploader_id\"]\n\n dict_cur.execute(\"SELECT * FROM auth_user WHERE id=%s\" % old_uploader)\n old_uploader_username = dict_cur.fetchone()[\"username\"]\n\n old_copyright = old_cellimage_tuple[\"copyright_id\"]\n dict_cur.execute(\n \"SELECT * FROM main_copyrightholder WHERE id=%s\" % old_copyright\n )\n old_copyrightholder_name = dict_cur.fetchone()[\"name\"]\n\n old_license = old_cellimage_tuple[\"license_id\"]\n dict_cur.execute(\"SELECT * FROM main_license WHERE id=%s\" % old_license)\n old_license_title = dict_cur.fetchone()[\"title\"]\n\n # Get modern equivalents\n cell = CellType.objects.get(id=old_celltype)\n uploader = User.objects.get(username=old_uploader_username)\n copyright = CopyrightHolder.objects.get(name=old_copyrightholder_name)\n license = License.objects.get(title=old_license_title)\n\n # Generate new CellImage instance\n new_image = CellImage(\n title=old_title,\n description=old_description,\n celltype=cell,\n thumbnail_left=old_thumbnail_left,\n thumbnail_top=old_thumbnail_top,\n thumbnail_width=old_thumbnail_width,\n uploader=uploader,\n copyright=copyright,\n license=license,\n )\n new_image.file.name = old_file\n new_image.thumbnail.name = old_thumbnail\n\n new_image.save()\n\n conn.close()\n" }, { "alpha_fraction": 0.7527472376823425, "alphanum_fraction": 0.7527472376823425, "avg_line_length": 25, "blob_id": "942771116def45b2de3e60af83b31b7c3ad02100", "content_id": "8c7dd0773aad8c7f3e105fa3b310c42f372a4641", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "permissive", "max_line_length": 82, "num_lines": 7, "path": "/cellcounter/statistics/urls.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom .views import ListCreateCountInstanceAPI\n\nurlpatterns = [\n url(\"^$\", ListCreateCountInstanceAPI.as_view(), name=\"create-count-instance\"),\n]\n" }, { "alpha_fraction": 0.5053879022598267, "alphanum_fraction": 0.5226293206214905, "avg_line_length": 24.77777862548828, "blob_id": "48cec5446b5ee253d0e903a0374222a47774ed91", "content_id": "1233fbe13c648e0b3da6a216801495b0f7f97423", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2784, "license_type": "permissive", "max_line_length": 67, "num_lines": 108, "path": "/cellcounter/main/migrations/0002_initial_data.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.db import models, migrations\n\n\nCELLTYPES_INITIAL = [\n {\n \"readable_name\": \"Neutrophils\",\n \"machine_name\": \"neutrophils\",\n \"abbr_name\": \"neut\",\n \"visualisation_colour\": \"#4f6228\",\n },\n {\n \"readable_name\": \"Metamyelocytes\",\n \"machine_name\": \"meta\",\n \"abbr_name\": \"meta\",\n \"visualisation_colour\": \"#77933c\",\n },\n {\n \"readable_name\": \"Myelocytes\",\n \"machine_name\": \"myelocytes\",\n \"abbr_name\": \"myelo\",\n \"visualisation_colour\": \"#c3d69b\",\n },\n {\n \"readable_name\": \"Promyelocytes\",\n \"machine_name\": \"promyelocytes\",\n \"abbr_name\": \"promyelo\",\n \"visualisation_colour\": \"#d7e4bd\",\n },\n {\n \"readable_name\": \"Blasts\",\n \"machine_name\": \"blasts\",\n \"abbr_name\": \"blast\",\n \"visualisation_colour\": \"#ebf1de\",\n },\n {\n \"readable_name\": \"Basophils\",\n \"machine_name\": \"basophils\",\n \"abbr_name\": \"baso\",\n \"visualisation_colour\": \"#8064a2\",\n },\n {\n \"readable_name\": \"Eosinophils\",\n \"machine_name\": \"eosinophils\",\n \"abbr_name\": \"eo\",\n \"visualisation_colour\": \"#f79546\",\n },\n {\n \"readable_name\": \"Erythroid\",\n \"machine_name\": \"erythroid\",\n \"abbr_name\": \"erythro\",\n \"visualisation_colour\": \"#ff0000\",\n },\n {\n \"readable_name\": \"Lymphocytes\",\n \"machine_name\": \"lymphocytes\",\n \"abbr_name\": \"lympho\",\n \"visualisation_colour\": \"#ffffff\",\n },\n {\n \"readable_name\": \"Monocytes\",\n \"machine_name\": \"monocytes\",\n \"abbr_name\": \"mono\",\n \"visualisation_colour\": \"#bfbfbf\",\n },\n {\n \"readable_name\": \"Plasma cells\",\n \"machine_name\": \"plasma_cells\",\n \"abbr_name\": \"plasma\",\n \"visualisation_colour\": \"#0000ff\",\n },\n {\n \"readable_name\": \"Other\",\n \"machine_name\": \"other\",\n \"abbr_name\": \"other\",\n \"visualisation_colour\": \"#f9ff00\",\n },\n {\n \"readable_name\": \"Lymphoblasts\",\n \"machine_name\": \"lymphoblasts\",\n \"abbr_name\": \"ly_blasts\",\n \"visualisation_colour\": \"#606060\",\n },\n]\n\n\ndef initial_celltypes(apps, schema_editor):\n CellType = apps.get_model(\"main\", \"CellType\")\n\n for cell_type in CELLTYPES_INITIAL:\n ct = CellType(\n readable_name=cell_type[\"readable_name\"],\n machine_name=cell_type[\"machine_name\"],\n abbr_name=cell_type[\"abbr_name\"],\n visualisation_colour=cell_type[\"visualisation_colour\"],\n ).save()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"main\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.RunPython(initial_celltypes),\n ]\n" }, { "alpha_fraction": 0.6630653142929077, "alphanum_fraction": 0.6670854091644287, "avg_line_length": 38.01960754394531, "blob_id": "5ea84903bfd6606754ff0f77c7c100a5514304c3", "content_id": "2a1d5a6eac192e07ba44c4e9b5cd56c7cf10d252", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3980, "license_type": "permissive", "max_line_length": 97, "num_lines": 102, "path": "/cellcounter/cc_kapi/test_builtin_keyboards.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "import json\n\nfrom django.test import TestCase\n\n# from .factories import KeyboardLayoutsFactory\nfrom .marshalls import KeyboardLayoutsMarshall\nfrom .factories import UserFactory, KeyboardFactory, BuiltinKeyboardFactory\nfrom .models import Keyboard\n\n\ndef DecodeDateTimeInUTC(d, fields=[\"created\", \"last_modified\"]):\n \"\"\"Utility function to convert datetime fields to UTC\"\"\"\n\n def to_utc(datetime_string):\n return datetime.fromisoformat(\n datetime_string.replace(\"Z\", \"+00:00\")\n ).astimezone(pytz.utc)\n\n for f in fields:\n if f in d:\n d[f] = to_utc(d[f])\n return d\n\n\nclass KeyboardLayoutsTestCase(TestCase):\n def setUp(self):\n self.user = UserFactory()\n self.desktop_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.DESKTOP\n )\n self.mobile_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.MOBILE\n )\n\n def test_builtin_keyboard_factory(self):\n \"\"\"Check that the builtin keyboard factory returns the same keyboards as the marshall.\"\"\"\n\n builtin_desktop_keyboard_factory = BuiltinKeyboardFactory(\n device_type=Keyboard.DESKTOP\n )\n builtin_mobile_keyboard_factory = BuiltinKeyboardFactory(\n device_type=Keyboard.MOBILE\n )\n [\n builtin_desktop_keyboard_marshall,\n builtin_mobile_keyboard_marshall,\n ] = KeyboardLayoutsMarshall().get_all(layout_types=\"builtin\")\n self.assertEqual(\n builtin_desktop_keyboard_factory.serialize(),\n builtin_desktop_keyboard_marshall.serialize(),\n )\n self.assertEqual(\n builtin_mobile_keyboard_factory.serialize(),\n builtin_mobile_keyboard_marshall.serialize(),\n )\n\n def test_builtin_keyboards_count(self):\n builtin_keyboards = KeyboardLayoutsMarshall().get_all(layout_types=\"builtin\")\n self.assertEqual(len(builtin_keyboards), 2)\n self.assertEqual(builtin_keyboards[0].layout_type(), \"builtin\")\n self.assertEqual(builtin_keyboards[1].layout_type(), \"builtin\")\n\n builtin_keyboard_desktop = KeyboardLayoutsMarshall().get_all(\n layout_types=\"builtin\", device=Keyboard.DESKTOP\n )\n self.assertEqual(len(builtin_keyboard_desktop), 1)\n self.assertEqual(builtin_keyboard_desktop[0].device(), Keyboard.DESKTOP)\n\n builtin_keyboard_mobile = KeyboardLayoutsMarshall().get_all(\n layout_types=\"builtin\", device=Keyboard.MOBILE\n )\n self.assertEqual(len(builtin_keyboard_mobile), 1)\n self.assertEqual(builtin_keyboard_mobile[0].device(), Keyboard.MOBILE)\n\n def test_default_keyboards_count(self):\n builtin_keyboards = KeyboardLayoutsMarshall().get(\n device=Keyboard.DESKTOP, layout_id=\"default\"\n )\n self.assertEqual(builtin_keyboards.layout_type(), \"builtin\")\n\n def test_builtin_keyboards_fields_match(self):\n \"\"\"Check the fields in the builtin keyboards match those in the Keyboard model.\"\"\"\n desktop_keyboard = KeyboardFactory(user=self.user, device_type=Keyboard.DESKTOP)\n builtin_desktop_keyboard = BuiltinKeyboardFactory(device_type=Keyboard.DESKTOP)\n\n self.assertEqual(\n desktop_keyboard.serialize().keys(),\n builtin_desktop_keyboard.serialize().keys(),\n )\n\n def test_user_keyboard_count(self):\n user_keyboards = KeyboardLayoutsMarshall(self.user).get_all(layout_types=\"user\")\n self.assertEqual(len(user_keyboards), 2)\n self.assertEqual(user_keyboards[0].layout_type(), \"user\")\n self.assertEqual(user_keyboards[1].layout_type(), \"user\")\n\n def test_all_keyboard_count(self):\n all_keyboards_no_user = KeyboardLayoutsMarshall().get_all()\n self.assertEqual(len(all_keyboards_no_user), 2)\n\n all_keyboards = KeyboardLayoutsMarshall(self.user).get_all()\n self.assertEqual(len(all_keyboards), 4)\n" }, { "alpha_fraction": 0.664897620677948, "alphanum_fraction": 0.6675511598587036, "avg_line_length": 31.975000381469727, "blob_id": "8ca63b228752222932697b46adbfd29cdaa33e6a", "content_id": "37655dc3ce5034699529f5682eb9d2a45cafcef6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2638, "license_type": "permissive", "max_line_length": 88, "num_lines": 80, "path": "/cellcounter/main/views.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom django.views.generic import TemplateView, ListView, DetailView\nfrom rest_framework.generics import ListAPIView\nfrom PIL import Image\n\nfrom .models import CellType, CellImage\nfrom .serializers import CellTypeSerializer\n\n\nclass CellTypesListView(ListAPIView):\n queryset = CellType.objects.all().order_by(\"id\")\n serializer_class = CellTypeSerializer\n\n\nclass NewCountTemplateView(TemplateView):\n template_name = \"main/count.html\"\n\n def get_context_data(self, **kwargs):\n context = super(NewCountTemplateView, self).get_context_data(**kwargs)\n context[\"logged_in\"] = self.request.user.is_authenticated\n context[\"cell_types\"] = CellType.objects.all().order_by(\"display_order\")\n return context\n\n\nclass CellImageListView(ListView):\n model = CellImage\n template_name = \"main/images_by_cell_type.html\"\n\n def get_queryset(self):\n return CellImage.objects.filter(\n celltype__machine_name__iexact=self.kwargs[\"cell_type\"]\n )\n\n def get_context_data(self, **kwargs):\n copyright_holders = []\n image_list = []\n context = super(CellImageListView, self).get_context_data(**kwargs)\n if context[\"object_list\"]:\n for image in self.object_list:\n if image.copyright not in copyright_holders:\n copyright_holders.append(image.copyright)\n image_list.append((copyright_holders.index(image.copyright) + 1, image))\n context.pop(\"object_list\")\n context[\"images\"] = image_list\n context[\"copyrightholders\"] = copyright_holders\n return context\n\n\nclass CellImageDetailView(DetailView):\n model = CellImage\n context_object_name = \"cellimage\"\n template_name = \"main/image_page.html\"\n pk_url_kwarg = \"cell_image_pk\"\n\n\ndef similar_images(request, cell_image_pk):\n ci = CellImage.objects.get(pk=cell_image_pk)\n return render(\n request, \"main/images_by_cell_type.html\", {\"images\": ci.similar_cells()}\n )\n\n\ndef thumbnail(request, cell_image_pk):\n ci = CellImage.objects.get(pk=cell_image_pk)\n\n image = Image.open(ci.file.file)\n thumb_image = image.crop(\n (\n ci.thumbnail_left,\n ci.thumbnail_top,\n ci.thumbnail_left + ci.thumbnail_width,\n ci.thumbnail_top + ci.thumbnail_width,\n )\n )\n thumb_image = thumb_image.resize((200, 200), Image.ANTIALIAS)\n response = HttpResponse(mimetype=\"image/png\")\n thumb_image.save(response, \"PNG\")\n return response\n" }, { "alpha_fraction": 0.671046257019043, "alphanum_fraction": 0.6773722767829895, "avg_line_length": 24.04878044128418, "blob_id": "c3f1876e1f07182fb7367cd6a2e970a30f16faab", "content_id": "12e0e8990050084d422856caa7f43a42aab77a29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 2055, "license_type": "permissive", "max_line_length": 99, "num_lines": 82, "path": "/docker/app/Dockerfile", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# syntax=docker/dockerfile:1\nFROM python:3.9.6-slim AS builder\n\n# set environment variables\nENV PYTHONDONTWRITEBYTECODE=1\nENV PYTHONUNBUFFERED=1\n\n# Create a group and user to run the app\nARG APP_USER=cellcountr\nRUN groupadd -r ${APP_USER} && useradd --no-log-init -r -g ${APP_USER} ${APP_USER}\n\n# install run dependencies\nRUN set -ex \\\n && RUN_DEPS=\" \\\n libpcre3 \\\n mime-support \\\n postgresql-client \\\n \" \\\n && seq 1 8 | xargs -I{} mkdir -p /usr/share/man/man{} \\\n && apt-get update && apt-get install -y --no-install-recommends $RUN_DEPS \\\n && rm -rf /var/lib/apt/lists/*\n\n# copy in requirements file\nCOPY requirements.txt /requirements.txt\n\n# Install build deps, then run `pip install`, then remove unneeded build deps all in a single step.\n# Correct the path to your production requirements file, if needed.\nRUN set -ex \\\n && BUILD_DEPS=\" \\\n build-essential \\\n libpcre3-dev \\\n libpq-dev \\\n libmemcached-dev \\\n zlib1g-dev \\\n \" \\\n && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \\\n && pip install --upgrade pip \\\n && pip install --no-cache-dir -r /requirements.txt\n\n# set work directory and copy project\nENV HOME=/usr/src/cellcounter\nRUN mkdir $HOME\nWORKDIR $HOME\nCOPY . $HOME\n\n\nFROM builder AS prod\n\nARG APP_USER=cellcountr\n\n# remove extraneous packages\nRUN set -ex \\\n && BUILD_DEPS=\" \\\n build-essential \\\n libpcre3-dev \\\n libpq-dev \\\n libmemcached-dev \\\n zlib1g-dev \\\n \" \\\n && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false $BUILD_DEPS \\\n && rm -rf /var/lib/apt/lists/*\n\nRUN mkdir $HOME/static\nRUN chown ${APP_USER}:${APP_USER} $HOME/static\n\n# Change to a non-root user\nUSER ${APP_USER}:${APP_USER}\n\nENTRYPOINT [\"/usr/src/cellcounter/docker/entrypoint.sh\"]\n\n\nFROM builder AS test\n\n# copy in requirements file\nCOPY test-requirements.txt /test-requirements.txt\n\nRUN set -ex \\\n && pip install --no-cache-dir -r /test-requirements.txt\n\nENV TEST=True\n\nENTRYPOINT [\"/usr/src/cellcounter/docker/test-entrypoint.sh\"]\n\n" }, { "alpha_fraction": 0.6922693252563477, "alphanum_fraction": 0.6942643523216248, "avg_line_length": 33.568965911865234, "blob_id": "fa495e6a47762d6b2707e6d943e7de4bcb30e0c6", "content_id": "8e72e706172194fb777eff001c2da00702cc5f19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2005, "license_type": "permissive", "max_line_length": 84, "num_lines": 58, "path": "/cellcounter/statistics/views.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from rest_framework import status\nfrom rest_framework.generics import ListCreateAPIView\nfrom rest_framework.permissions import BasePermission\nfrom rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.throttling import AnonRateThrottle\nfrom rest_framework_xml.renderers import XMLRenderer\n\nfrom .models import CountInstance\nfrom .serializers import CountInstanceCreateSerializer, CountInstanceModelSerializer\n\nSAFE_METHODS = [\"GET\", \"HEAD\", \"OPTIONS\"]\n\n\nclass OpenPostStaffGet(BasePermission):\n \"\"\"\n Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS\n \"\"\"\n\n def has_permission(self, request, view):\n if request.method == \"POST\" or all(\n [\n request.method in SAFE_METHODS,\n request.user.is_authenticated,\n request.user.is_staff,\n ]\n ):\n return True\n return False\n\n\nclass CountInstanceAnonThrottle(AnonRateThrottle):\n rate = \"1/minute\"\n\n\nclass ListCreateCountInstanceAPI(ListCreateAPIView):\n permission_classes = (OpenPostStaffGet,)\n serializer_class = CountInstanceModelSerializer\n queryset = CountInstance.objects.all()\n throttle_classes = (CountInstanceAnonThrottle,)\n renderer_classes = (JSONRenderer, BrowsableAPIRenderer, XMLRenderer)\n\n def create(self, request, *args, **kwargs):\n serializer = CountInstanceCreateSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n if self.request.user.is_authenticated:\n user = self.request.user\n else:\n user = None\n serializer.save(\n session_id=request.session.session_key,\n ip_address=request.META.get(\"REMOTE_ADDR\"),\n user=user,\n )\n headers = self.get_success_headers(serializer.data)\n return Response(\n serializer.data, status=status.HTTP_201_CREATED, headers=headers\n )\n" }, { "alpha_fraction": 0.6306607127189636, "alphanum_fraction": 0.6340014934539795, "avg_line_length": 35.4054069519043, "blob_id": "8c597a95ca3f9ec26204bde75bf334be38a33eef", "content_id": "c26708886a42b0a5cc6bb34d649a4bdeb49da3ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2694, "license_type": "permissive", "max_line_length": 87, "num_lines": 74, "path": "/cellcounter/accounts/forms.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.conf import settings\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.core.mail import send_mail\nfrom django.urls import reverse\nfrom django.core.validators import ValidationError\nfrom django.template import loader\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass EmailUserCreationForm(UserCreationForm):\n email = forms.EmailField(required=True, label=\"Email Address\")\n tos = forms.BooleanField(\n required=True,\n label=\"Terms and Conditions\",\n error_messages={\"required\": \"You must agree our Terms of Service\"},\n )\n\n class Meta:\n model = User\n fields = (\"username\", \"email\", \"password1\", \"password2\")\n\n\nclass PasswordResetForm(forms.Form):\n email = forms.EmailField(label=_(\"Email\"), max_length=254)\n\n def __init__(self, *args, **kwargs):\n super(PasswordResetForm, self).__init__(*args, **kwargs)\n self.valid_users = []\n\n def clean_email(self):\n email = self.cleaned_data[\"email\"]\n active_users = User.objects.filter(email__iexact=email, is_active=True)\n if not active_users:\n raise ValidationError(\"Enter a valid email address\")\n valid_users = [user for user in active_users if user.has_usable_password()]\n if not valid_users:\n raise ValidationError(\"Enter a valid email address\")\n self.valid_users = valid_users\n return email\n\n def get_context_data(self, request, user, token_generator=default_token_generator):\n context = {\n \"email\": user.email,\n \"url\": request.build_absolute_uri(\n reverse(\n \"password-reset-confirm\",\n kwargs={\n \"uidb64\": urlsafe_base64_encode(force_bytes(user.pk)),\n \"token\": token_generator.make_token(user),\n },\n )\n ),\n \"user\": user,\n }\n return context\n\n def save(\n self,\n request=None,\n email_template_name=\"accounts/reset_email.txt\",\n token_generator=default_token_generator,\n ):\n\n for user in self.valid_users:\n context = self.get_context_data(request, user, token_generator)\n subject = \"Password reset information for Cellcountr\"\n body = loader.render_to_string(email_template_name, context)\n\n send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [user.email])\n" }, { "alpha_fraction": 0.5739450454711914, "alphanum_fraction": 0.5840108394622803, "avg_line_length": 28.01685333251953, "blob_id": "d56e6036e7962f1e715255ed2b5725f78f8fd738", "content_id": "0c65fad51cdef077518c599124a4f3dfa94c6075", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5166, "license_type": "permissive", "max_line_length": 112, "num_lines": 178, "path": "/js_test/test_display.js", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "// Mocha Specification Cases\n\n// Imports\nconst assert = require('assert');\nconst { JSDOM } = require('jsdom');\n\n// Setup\nconst url = 'http://127.0.0.1:8000/';\nlet window, $;\nconst loadWebPage = (done) => {\n const handleWebPage = (dom) => {\n const waitForScripts = () => {\n window = dom.window;\n $ = dom.window.jQuery;\n $.when(window.initialised).done(function () {done();});\n };\n dom.window.onload = waitForScripts;\n };\n const options = { resources: 'usable', runScripts: 'dangerously', pretendToBeVisual: true };\n global.document = JSDOM.fromURL(url, options).then(handleWebPage);\n };\nconst closeWebPage = () => window.close();\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\nfunction trigger_keydown(key, repeat) {\n var rpt = (typeof repeat === \"undefined\") ? 1 : repeat;\n var e = $.Event('keydown');\n\n var key_code;\n if(typeof key === \"number\") {\n key_code = key;\n } else if(typeof key === \"string\") {\n key_code = key.charCodeAt(0);\n }\n\n e.key = e.which = key_code;\n for(var i=0; i<rpt; i++)\n $(window.document).trigger(e);\n}\n\nfunction get_display(selector) {\n return window.getComputedStyle($(selector)[0])['display'];\n}\n\nfunction get_display_parent(selector) {\n return window.getComputedStyle($(selector).first().parent()[0])['display'];\n}\n\nfunction delay(interval) \n{\n return it('should delay', done => \n {\n setTimeout(() => done(), interval)\n\n }).timeout(interval + 100) // The extra 100ms should guarantee the test will not fail due to exceeded timeout\n}\n\ndescribe('The web page', function () {\n\n before(function(done) {\n this.timeout(3000);\n loadWebPage(done);\n });\n\n after(closeWebPage);\n\n this.timeout(4000);\n\n it('has the correct URL -> ' + url, () => {\n const actual = { url: window.location.href };\n const expected = { url: url };\n assert.deepStrictEqual(actual, expected);\n });\n\n it('displays the keyboard', () => {\n assert.deepStrictEqual(get_display('div#counterbox'), \"block\");\n });\n\n it('triggers the keyboard to close', () => {\n $('#close_button').trigger('click');\n });\n\n //wait two seconds for the keyboard to close\n delay(1500);\n\n it('closes the keyboard and does not show stats', () => {\n\n assert.deepStrictEqual(get_display('div#counterbox'), \"none\");\n assert.deepStrictEqual(get_display('div#statistics'), \"none\");\n });\n\n it('does not count when the keyboard is closed', () => {\n trigger_keydown('d',1);\n trigger_keydown('q',5);\n\n var total = window.counter.get_total();\n\n assert.deepStrictEqual(total, 0);\n });\n\n it('triggers the keyboard to open', () => {\n $('div#openkeyboard').trigger('click');\n });\n\n delay(1500);\n\n it('shows the keyboard again', () => {\n assert.deepStrictEqual(get_display('div#counterbox'), \"block\");\n });\n\n it('counts and closes the keyboard', () => {\n trigger_keydown('d',1);\n\n var total = window.counter.get_total();\n\n assert.deepStrictEqual(total, 1);\n \n $('#close_button').trigger('click');\n });\n\n delay(1500);\n\n it('hides the keyboard and shows HTML results', () => {\n assert.deepStrictEqual(get_display('div#counterbox'), \"none\");\n assert.deepStrictEqual(get_display('div#statistics'), \"block\");\n assert.deepStrictEqual(get_display('div#statistics_html'), \"block\");\n assert.deepStrictEqual(get_display('div#statistics_text'), \"none\");\n });\n\n it('shows the text results', () => {\n $('#textview').trigger('click');\n\n assert.deepStrictEqual(get_display('div#statistics_html'), \"none\");\n assert.deepStrictEqual(get_display('div#statistics_text'), \"block\");\n });\n\n it('shows the html results again', () => {\n $('#htmlview').trigger('click');\n\n assert.deepStrictEqual(get_display('div#statistics_html'), \"block\");\n assert.deepStrictEqual(get_display('div#statistics_text'), \"none\");\n });\n\n it('shows the reset modal dialog', () => {\n $('.reset_button').trigger('click');\n\n assert.deepStrictEqual(window.counter.get_total(), 1);\n\n $('input#reset-count').trigger('click');\n\n assert.deepStrictEqual(window.counter.get_total(), 0);\n });\n\n delay(1500);\n\n it('shows the keyboard after reset', () => {\n assert.deepStrictEqual(get_display('div#counterbox'), \"block\");\n assert.deepStrictEqual(get_display('div#statistics'), \"none\");\n });\n\n it('shows the edit keyboard dialog', () => {\n assert.deepStrictEqual(get_display('div#editkeymapbox'), \"none\");\n\n $('#edit_button').trigger('click');\n\n assert.deepStrictEqual(get_display('div#editkeymapbox'), \"block\");\n });\n\n it('hides the edit keyboard dialog', () => {\n assert.deepStrictEqual(get_display_parent('div#editkeymapbox'), \"block\");\n\n $('.ui-dialog-buttonset button:contains(\"Close\")').trigger('click');\n\n assert.deepStrictEqual(get_display_parent('div#editkeymapbox'), \"none\");\n });\n \n});\n\n" }, { "alpha_fraction": 0.6036866307258606, "alphanum_fraction": 0.6082949042320251, "avg_line_length": 26.125, "blob_id": "28d418826a5528d952503fe43d71a5e4cd43cbd5", "content_id": "0f784f8bfb21cd9c76e33987aa53feed871d3620", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "permissive", "max_line_length": 70, "num_lines": 8, "path": "/cellcounter/accounts/utils.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "import re\n\n\ndef read_signup_email(email):\n url_match = re.search(r\"https?://[^/]*(/.*reset/\\S*)\", email.body)\n if url_match is None:\n return None, None\n return url_match.group(), url_match.groups()[0]\n" }, { "alpha_fraction": 0.5890766978263855, "alphanum_fraction": 0.5890766978263855, "avg_line_length": 31.0625, "blob_id": "32ce2193051bf3f1339147e0a4d551590f93181d", "content_id": "e9c7adb5ac4adc90cfec98f7e67342fd77cb11c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1538, "license_type": "permissive", "max_line_length": 111, "num_lines": 48, "path": "/cellcounter/accounts/templates/accounts/user_update.html", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "{% extends 'main/base.html' %}\n\n{% block content %}\n\n<form action=\"\" method=\"post\" class=\"form-horizontal\">\n{% csrf_token %}\n{% if form.non_field_errors %}\n <div class=\"alert alert-danger\">\n <a class=\"close\" data-dismiss=\"alert\">&times;</a>\n {% for non_field_error in form.non_field_errors %}\n {{ non_field_error }}\n {% endfor %}\n </div>\n{% endif %}\n\n<div class=\"control-group {% if form.first_name.errors %}error{% endif %}\">\n <label class=\"control-label\" for=\"id_first_name\">First Name</label>\n <div class=\"controls\">\n {{ form.first_name }}\n {% if form.first_name.errors %}<span class=\"help-inline\">{{ form.first_name.errors }}</span>{% endif %}\n </div>\n</div>\n\n<div class=\"control-group {% if form.last_name.errors %}error{% endif %}\">\n <label class=\"control-label\" for=\"id_last_name\">Last Name</label>\n <div class=\"controls\">\n {{ form.last_name }}\n {% if form.last_name.errors %}<span class=\"help-inline\">{{ form.last_name.errors }}</span>{% endif %}\n </div>\n</div>\n\n<div class=\"control-group {% if form.email.errors %}error{% endif %}\">\n <label class=\"control-label\" for=\"id_email\">Email Address</label>\n <div class=\"controls\">\n {{ form.email }}\n {% if form.email.errors %}<span class=\"help-inline\">{{ form.email.errors }}</span>{% endif %}\n </div>\n</div>\n\n<div class=\"control-group\">\n <div class=\"controls\">\n <input type=\"submit\" class=\"btn btn-success\" value=\"Update\" />\n </div>\n</div>\n\n</form>\n\n{% endblock %}" }, { "alpha_fraction": 0.5697697401046753, "alphanum_fraction": 0.5758708715438843, "avg_line_length": 34.041378021240234, "blob_id": "0dfa5b2159965da2a48db8b30910e534f1c7c928", "content_id": "74c94f665cd84fafb28fc83ca0016aa8b90560a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5081, "license_type": "permissive", "max_line_length": 91, "num_lines": 145, "path": "/cellcounter/cc_kapi/migrations/0002_v2api.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.6 on 2016-05-24 16:16\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import connection\n\nfrom ..defaults import BUILTIN_KEYBOARDS\nfrom ..models import User\nfrom ..models import Keyboard as KeyboardLatest\n\n\ndef migrate_user_default_keyboards(apps, schema_editor):\n # get all the models corresponding to the current state\n Keyboard = apps.get_model(\"cc_kapi\", \"Keyboard\")\n DefaultKeyboards = apps.get_model(\"cc_kapi\", \"DefaultKeyboards\")\n User = apps.get_model(\"auth\", \"user\")\n\n for user in User.objects.all():\n # the previous code should guarantee there is at most one primary keyboard per user\n try:\n keyboard = Keyboard.objects.get(user=user, is_primary=True)\n except ObjectDoesNotExist:\n continue\n if not hasattr(user, \"defaultkeyboards\"):\n defaultkeyboards = DefaultKeyboards.objects.create(user=user)\n else:\n defaultkeyboards = user.defaultkeyboards\n if keyboard.device_type == KeyboardLatest.DESKTOP:\n defaultkeyboards.desktop = keyboard\n elif keyboard.device_type == KeyboardLatest.MOBILE:\n defaultkeyboards.mobile = keyboard\n defaultkeyboards.save()\n\n\ndef undo_user_default_keyboards(apps, schema_editor):\n # get all the models corresponding to the current state\n Keyboard = apps.get_model(\"cc_kapi\", \"Keyboard\")\n DefaultKeyboards = apps.get_model(\"cc_kapi\", \"DefaultKeyboards\")\n User = apps.get_model(\"auth\", \"user\")\n\n for user in User.objects.all():\n if hasattr(user, \"defaultkeyboards\") and hasattr(\n user.defaultkeyboards, \"desktop\"\n ):\n default_desktop = user.defaultkeyboards.desktop\n keyboard = Keyboard.objects.get(id=default_desktop.id)\n keyboard.is_primary = True\n keyboard.save()\n\n\nclass Migration(migrations.Migration):\n def set_constraints_detect_sqlite_noop():\n # hack around sqlite not supporting the SET CONSTRAINTS SQL command\n if connection.vendor == \"sqlite\":\n return migrations.RunSQL.noop\n return \"SET CONSTRAINTS ALL IMMEDIATE\"\n\n dependencies = [\n (\"auth\", \"0007_alter_validators_add_error_messages\"),\n (\"main\", \"0002_initial_data\"),\n (\"cc_kapi\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.RunSQL(\n set_constraints_detect_sqlite_noop(), reverse_sql=migrations.RunSQL.noop\n ),\n migrations.CreateModel(\n name=\"DefaultKeyboards\",\n fields=[\n (\n \"user\",\n models.OneToOneField(\n on_delete=django.db.models.deletion.CASCADE,\n primary_key=True,\n serialize=False,\n to=settings.AUTH_USER_MODEL,\n ),\n ),\n ],\n ),\n migrations.AddField(\n model_name=\"keyboard\",\n name=\"device_type\",\n field=models.PositiveIntegerField(\n choices=[(1, b\"desktop\"), (2, b\"mobile\")], default=1\n ),\n ),\n migrations.AlterField(\n model_name=\"keyboard\",\n name=\"user\",\n field=models.ForeignKey(\n null=True,\n on_delete=django.db.models.deletion.CASCADE,\n to=settings.AUTH_USER_MODEL,\n ),\n ),\n migrations.AddField(\n model_name=\"defaultkeyboards\",\n name=\"desktop\",\n field=models.ForeignKey(\n default=None,\n null=True,\n on_delete=django.db.models.deletion.CASCADE,\n related_name=\"desktop_default\",\n to=\"cc_kapi.Keyboard\",\n ),\n ),\n migrations.AddField(\n model_name=\"defaultkeyboards\",\n name=\"mobile\",\n field=models.ForeignKey(\n default=None,\n null=True,\n on_delete=django.db.models.deletion.CASCADE,\n related_name=\"mobile_default\",\n to=\"cc_kapi.Keyboard\",\n ),\n ),\n migrations.AlterField(\n model_name=\"keyboard\",\n name=\"created\",\n field=models.DateTimeField(default=django.utils.timezone.now),\n ),\n migrations.AlterField(\n model_name=\"keyboard\",\n name=\"last_modified\",\n field=models.DateTimeField(default=django.utils.timezone.now),\n ),\n migrations.RunPython(\n migrate_user_default_keyboards,\n undo_user_default_keyboards,\n ),\n migrations.RemoveField(\n model_name=\"keyboard\",\n name=\"is_primary\",\n ),\n migrations.RunSQL(\n migrations.RunSQL.noop, reverse_sql=set_constraints_detect_sqlite_noop()\n ),\n ]\n" }, { "alpha_fraction": 0.8185840845108032, "alphanum_fraction": 0.8185840845108032, "avg_line_length": 27.25, "blob_id": "476586ad52dfab8e0e3835bd3ed7d6d1b4974f58", "content_id": "48696f48067103600a882d09820a63d510e640fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 226, "license_type": "permissive", "max_line_length": 59, "num_lines": 8, "path": "/cellcounter/cc_kapi/urls.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from .views import KeyboardViewSet\n\nfrom rest_framework import routers\nfrom .routers import KeyboardAPIRouter\n\nrouter = KeyboardAPIRouter()\nrouter.register(r\"\", KeyboardViewSet, basename=\"keyboards\")\nurlpatterns = router.urls\n" }, { "alpha_fraction": 0.5548297762870789, "alphanum_fraction": 0.5550277233123779, "avg_line_length": 28.717647552490234, "blob_id": "0ac860ba824cfc89fc589ab5d12327e180222cf9", "content_id": "4fd62355c8e0908b8c1d486eede4b9e86a6ce8a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5052, "license_type": "permissive", "max_line_length": 88, "num_lines": 170, "path": "/cellcounter/cc_kapi/marshalls.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from .models import Keyboard\nfrom .serializers import (\n KeyboardSerializer,\n KeyboardListItemSerializer,\n BuiltinKeyboardSerializer,\n BuiltinKeyboardListItemSerializer,\n)\nfrom .defaults import BUILTIN_KEYBOARDS\n\nfrom pydictobject import DictObject\n\nfrom abc import ABC, abstractmethod\n\n\nclass KeyboardLayoutsMarshall:\n def __init__(self, user=None):\n self.user = user\n self._populate_defaults()\n\n def _populate_defaults(self):\n self.default_desktop_id = \"builtin\"\n self.default_mobile_id = \"builtin\"\n if self.user and hasattr(self.user, \"defaultkeyboards\"):\n try:\n self.default_desktop_id = self.user.defaultkeyboards.desktop.id\n except AttributeError:\n pass\n try:\n self.default_mobile_id = (\n self.user.defaultkeyboards.mobile.id or \"builtin\"\n )\n except AttributeError:\n pass\n\n def get_all(self, device=\"all\", layout_types=\"all\"):\n if layout_types == \"all\":\n layout_types = [\"builtin\", \"user\"]\n else:\n layout_types = layout_types.split(\",\")\n\n keyboards = []\n\n if \"builtin\" in layout_types:\n for kb in BUILTIN_KEYBOARDS:\n keyboard = BuiltinKeyboardModel(kb)\n if device != \"all\" and device != keyboard.device():\n continue\n\n if (\n keyboard.device() == Keyboard.DESKTOP\n and self.default_desktop_id == \"builtin\"\n ):\n keyboard.set_default()\n elif (\n keyboard.device() == Keyboard.MOBILE\n and self.default_mobile_id == \"builtin\"\n ):\n keyboard.set_default()\n\n keyboards.append(keyboard)\n\n if \"user\" in layout_types:\n if device != \"all\":\n user_keyboards = UserKeyboardModel.objects.filter(\n user=self.user, device_type=device\n ).order_by(\"id\")\n else:\n user_keyboards = UserKeyboardModel.objects.filter(\n user=self.user\n ).order_by(\"id\")\n for kb in user_keyboards:\n if kb.device() == Keyboard.DESKTOP and self.default_desktop_id == kb.id:\n kb.set_default()\n elif kb.device() == Keyboard.MOBILE and self.default_mobile_id == kb.id:\n kb.set_default()\n keyboards.append(kb)\n\n return keyboards\n\n def get(self, layout_id, device):\n \"\"\"Get the keyboard layout by id for the specified device\"\"\"\n if layout_id == \"default\":\n return self.get_default(device)\n\n if layout_id == \"builtin\":\n for kb in BUILTIN_KEYBOARDS:\n keyboard = BuiltinKeyboardModel(kb)\n if keyboard.device() == device:\n return keyboard\n return None\n\n if self.user:\n try:\n keyboard = UserKeyboardModel.objects.get(\n user=self.user, id=layout_id, device_type=device\n )\n except Keyboard.DoesNotExist:\n return None\n\n return keyboard\n\n return None\n\n def get_default(self, device):\n \"\"\"Get the default keyboard layout for the specified device\"\"\"\n\n if device == Keyboard.DESKTOP:\n return self.get(self.default_desktop_id, Keyboard.DESKTOP)\n elif device == Keyboard.MOBILE:\n return self.get(self.default_mobile_id, Keyboard.MOBILE)\n\n return None\n\n\nclass KeyboardLayout:\n def serialize(self):\n raise NotImplementedError()\n\n def set_default(self):\n self._set_default()\n\n def device(self):\n return self.device_type\n\n def layout_type(self):\n raise NotImplementedError()\n\n\nclass BuiltinKeyboardModel(DictObject, KeyboardLayout):\n def __init__(self, *args, **kwargs):\n self.is_default = False\n super().__init__(*args, **kwargs)\n\n def _set_default(self):\n self.is_default = True\n\n def serializer(self):\n return \"json\"\n\n def serialize(self, many=False):\n if many:\n return BuiltinKeyboardListItemSerializer(self).data\n return BuiltinKeyboardSerializer(self).data\n if many:\n self.pop(\"mappings\")\n else:\n self.pop(\"is_default\")\n return self\n\n def layout_type(self):\n return \"builtin\"\n\n def get_device_type_display(self):\n try:\n return [x for i, x in Keyboard.DEVICE_TYPES if i == self.device_type][0]\n except IndexError:\n return None\n\n\nclass UserKeyboardModel(Keyboard, KeyboardLayout):\n def serialize(self, many=False):\n if many:\n return KeyboardListItemSerializer(self).data\n return KeyboardSerializer(self).data\n\n def layout_type(self):\n return \"user\"\n\n class Meta:\n proxy = True\n" }, { "alpha_fraction": 0.46614518761634827, "alphanum_fraction": 0.46964067220687866, "avg_line_length": 32.450531005859375, "blob_id": "0d8a0f26f9ce11d4406d411cf55ee9e91e352340", "content_id": "05ad724c825b0d9cd8a18b282ff99d59b8cdefdf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 40911, "license_type": "permissive", "max_line_length": 230, "num_lines": 1223, "path": "/cellcounter/cc_kapi/static/js/counter.js", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "/* global $:false */\n'use strict';\n\nvar abnormal = false;\nvar keyboard_active = false;\nvar img_displayed = false;\n\nvar cell_types = {};\n\nvar editing_keyboard = false;\nvar first_count = true;\nvar edit_cell_id = -1;\nvar selected_element = {};\nvar date_now = new Date(Date.now()).toISOString();\n\nvar keyboard_map = {label: \"Default\",\n is_default: true,\n created: date_now,\n last_modified: date_now,\n mappings: [] };\nvar chart, chart2;\n\nvar keyboard_platform = \"desktop\";\n\n/* Counter object */\nvar counter = (function () {\n var undo_history = [];\n var count_data = [];\n var counting_start_time;\n\n return {\n init: function () {\n /* Load cell_types object, and create and load new count_data object\n * provides error message should loading of data fail.\n * Returns a Deferred object for promise chaining. */\n return $.getJSON('/api/cell_types/', function (data) {\n cell_types = {};\n $.each(data, function (key, cell) {\n cell.box = [];\n cell_types[cell.id] = cell;\n });\n }).done(function () {\n /* Loads an empty count_data array */\n var cell_order = ['blasts', 'promyelocytes', 'myelocytes', 'meta', 'neutrophils', 'monocytes', 'basophils',\n 'eosinophils', 'lymphocytes', 'plasma_cells', 'erythroid', 'other', 'lymphoblasts'];\n\n for (var i = 0; i < cell_order.length; i++) {\n for (var cell in cell_types) {\n if (cell_types.hasOwnProperty(cell)) {\n if (cell_types[cell].machine_name === cell_order[i]) {\n count_data.push({ id: cell_types[cell].id,\n count: 0,\n abnormal: 0,\n visualisation_colour: cell_types[cell].visualisation_colour,\n readable_name: cell_types[cell].readable_name,\n machine_name: cell_types[cell].machine_name });\n }\n }\n }\n }\n }).fail(function () {\n add_alert('ERROR', 'Cellcountr failed to load cell data. Please refresh page');\n });\n },\n\n reset: function () {\n /* Reset all the count data and the undo history */\n for (var i = 0; i < count_data.length; i++) {\n count_data[i].count = 0;\n count_data[i].abnormal = 0;\n }\n undo_history = [];\n },\n\n reset_start_time: function () {\n counting_start_time = new Date();\n },\n\n get_cell_ids: function () {\n var cell_ids = [];\n for (var i = 0; i < count_data.length; i++) {\n cell_ids.push(count_data[i].id);\n }\n return cell_ids;\n },\n\n get_count_data: function () {\n /* XXX: to remove. Exposes private count_data structure - all access should be through a class method */\n return count_data;\n },\n\n increment: function (cell_type_id, abnormal) {\n var j;\n if (abnormal === true) {\n for (j = 0; j < count_data.length; j++) {\n if (count_data[j].id === cell_type_id) {\n count_data[j].abnormal++;\n }\n }\n undo_history.push({ c_id: cell_type_id, c_type: 'abnormal' });\n } else {\n for (j = 0; j < count_data.length; j++) {\n if (count_data[j].id === cell_type_id) {\n count_data[j].count++;\n }\n }\n undo_history.push({ c_id: cell_type_id, c_type: 'count' });\n }\n },\n\n undo: function () {\n var last_key = undo_history.pop();\n if (typeof last_key !== 'undefined') {\n var c_id = last_key.c_id;\n var c_type = last_key.c_type;\n\n for (var i = 0; i < count_data.length; i++) {\n if (count_data[i].id === c_id) {\n if (count_data[i][c_type] > 0) {\n count_data[i][c_type]--;\n }\n }\n }\n return c_id;\n } else {\n /* Nothing to delete */\n undo_history = [];\n }\n },\n\n get_counts: function (cell_id) {\n var count_normal;\n var count_abnormal;\n\n for (var k = 0; k < count_data.length; k++) {\n if (count_data[k].id === cell_id) {\n count_normal = count_data[k].count;\n count_abnormal = count_data[k].abnormal;\n }\n }\n return {\n normal: count_normal,\n abnormal: count_abnormal\n };\n },\n\n get_visualisation_colour: function (cell_id) {\n for (var k = 0; k < count_data.length; k++) {\n if (count_data[k].id === cell_id) {\n return count_data[k].visualisation_colour;\n }\n }\n },\n\n get_machine_name: function (cell_id) {\n for (var k = 0; k < count_data.length; k++) {\n if (count_data[k].id === cell_id) {\n return count_data[k].machine_name;\n }\n }\n },\n\n get_readable_name: function (cell_id) {\n for (var k = 0; k < count_data.length; k++) {\n if (count_data[k].id === cell_id) {\n return count_data[k].readable_name;\n }\n }\n },\n\n get_total: function () {\n // TODO: optimise by keeping a running total\n var total = 0;\n for (var i = 0; i < count_data.length; i++) {\n total += count_data[i].count;\n total += count_data[i].abnormal;\n }\n return total;\n },\n\n get_abnormal_total: function () {\n // TODO: optimise by keeping a running total\n var total = 0;\n for (var i = 0; i < count_data.length; i++) {\n total += count_data[i].abnormal;\n }\n return total;\n },\n\n get_counting_time: function () {\n return Math.round((new Date() - counting_start_time)/1000);\n }\n\n };\n})();\n\nfunction render_chart() {\n if(chart) {\n chart.render();\n }\n}\n\nfunction render_chart2() {\n if(chart2) {\n chart2.render();\n }\n}\n\nfunction init_objects () {\n chart = doughnutChart('#doughnut').data(counter.get_count_data());\n chart2 = doughnutChart('#doughnut2').data(counter.get_count_data());\n}\n\nfunction init_keyboard_label_editing () {\n $('.keyboard-label').each(function() {\n\n if($(this).data('pk') != \"builtin\") {\n\n $(this).editable({\n url: function (params) {\n var href = $(this).data('href');\n var keyboard = load_keyboard(href);\n keyboard.label = params.value;\n save_keyboard(keyboard);\n }\n });\n $(this).css(\"cursor\", \"pointer\");\n }\n });\n}\n\nfunction init_keyboard () {\n $('#save_new_name').click(function () {\n save_new_keyboard($('#keyboard-name-input').val());\n });\n\n // Re-enable keyboard when dialog is closed\n $('#keyboard_name').on('hide', function () {\n editing_keyboard = true;\n keyboard_active = true;\n });\n\n $('#select_button').on('click', function () {\n $('#select-keyboard').modal('show');\n });\n\n $('#select-keyboard').on('show', function() {\n $.getJSON(\"/api/keyboards/\" + keyboard_platform + '/', function(data) {\n $('#keyboard_list tbody > tr').remove();\n $.each(data, function (i, data) {\n $('#keyboard_list table tbody').append(\n '<tr><td>'+data.label+'</td><td><span class=\"btn btn-success load_keyboard\" title=\"Select keyboard\" data-id=\"' + data.id + '\" data-href=\"' + data.href + '\"><i class=\"icon-ok icon-white\"></i></span></td></tr>');\n });\n $('.load_keyboard').on('click', function() {\n var href = ($(this).attr('data-href'));\n set_keyboard(load_keyboard(href));\n $('#select-keyboard').modal(\"hide\");\n $(\"div#editkeymapbox\").dialog(\"close\");\n });\n });\n });\n}\n\nfunction init_other () {\n var i, j;\n\n $('#edit_button').on('click', edit_keyboard);\n\n register_resets();\n\n $('#fuzz, #close_button').click(function () {\n if (editing_keyboard) {\n return;\n }\n\n if (keyboard_active) {\n keyboard_active = false;\n\n var cell_ids = counter.get_cell_ids();\n\n for (i = 0; i < cell_ids.length; i++) {\n var counts = counter.get_counts(cell_ids[i]);\n $('#id_' + i + '-normal_count').prop('value', counts.normal);\n $('#id_' + i + '-abnormal_count').prop('value', counts.abnormal);\n }\n\n var total = counter.get_total();\n var time_counting = counter.get_counting_time();\n\n if (total > 0) {\n log_counter_stats(total, time_counting, \"close\");\n results.update();\n results.show('html');\n }\n\n $('#counterbox').slideUp('slow', function () {\n $('#fuzz').fadeOut('slow', function () {\n });\n });\n\n if (first_count === true) {\n var keyboard_selector = $('#keyboard-buttons');\n keyboard_selector.append(\"<div id='openkeyboard' class='btn btn-success btn-large'>Continue counting</div>\");\n $('#openkeyboard').on('click', open_keyboard);\n keyboard_selector.append(\"<div class='btn btn-large btn-danger reset_button restart_button' style='margin-left: 5px'>Reset counters</div>\");\n register_resets();\n first_count = false;\n }\n }\n });\n\n // Adjust height of overlay to fill screen when browser gets resized\n $(window).on('resize', function () {\n $('#fuzz').css('height', $(document).height());\n // $(\"#fuzz\").css(\"top\", $(window).top());\n\n if (keyboard_active) {\n resize_keyboard($('div#content').width());\n }\n });\n\n $(document).on('keydown', function (e) {\n var key; var code; var shift_pressed; var el; var enter = false;\n var alpha = false; var up = false; var down = false;\n\n if (keyboard_active) {\n key = String.fromCharCode(e.which).toUpperCase();\n code = e.which;\n shift_pressed = e.shiftKey;\n\n if (/[a-z]/i.test(key) && !shift_pressed) {\n alpha = true;\n }\n if (code === 188) {\n key = ','; // XXX: WTF\n }\n if (code === 173) {\n key = '-'; // XXX: WTF\n }\n if (key === ' ') {\n abnormal = true;\n return false;\n } else if (code === 13) {\n enter = true;\n } else if (code === 38) {\n up = true;\n } else if (code === 40) {\n down = true;\n }\n\n if (editing_keyboard) {\n if (enter) {\n deselect_element(selected_element);\n select_element(selected_element.next());\n return;\n } else if (down) {\n deselect_element(selected_element);\n select_element(selected_element.next());\n return false;\n } else if (up) {\n deselect_element(selected_element);\n el = selected_element.prev();\n if (!$(el).html()) {\n el = $('div#celllist').find('li').last();\n }\n select_element(el);\n return false;\n } else if (alpha) {\n if (cell_types.hasOwnProperty(edit_cell_id.toString())) {\n if ($('#multi_key').is(':checked')) {\n /* DENIES ABILITY TO MAP MULTIPLE KEYS TO THE SAME CELL TYPE\n * Iterate through all key mappings, looking for any which map to the current cell_id.\n * If found, delete them. N.B. we decrement the iterator if we've spliced to avoid\n * issues with the length of the array and correct iteration position.\n */\n for (i = 0; i < keyboard_map.mappings.length; i++) {\n if (keyboard_map.mappings[i].cellid.toString() === edit_cell_id) {\n keyboard_map.mappings.splice(i, 1);\n i--;\n }\n }\n /* Remove any previous mappings for the key we're trying to add - prevents assigning\n * two celltypes to a given key.\n */\n for (i = 0; i < keyboard_map.mappings.length; i++) {\n if (keyboard_map.mappings[i].key === key.toLowerCase()) {\n keyboard_map.mappings.splice(i, 1);\n i--;\n }\n }\n\n /* Add the new mapping for this keypress */\n keyboard_map.mappings.push({ cellid: parseInt(edit_cell_id), key: key.toLowerCase() });\n\n if ($('#auto_advance').is(':checked')) {\n deselect_element(selected_element);\n select_element(selected_element.next());\n }\n } else {\n /* We allow multiple mappings to the same cell_id , here we check if the key has been\n * previously mapped, and if so, we remove any mappings for that key.\n */\n for (i = 0; i < keyboard_map.mappings.length; i++) {\n if (keyboard_map.mappings[i].key === key.toLowerCase()) {\n keyboard_map.mappings.splice(i, 1);\n i--;\n }\n }\n\n /* Add the new mapping */\n keyboard_map.mappings.push({ cellid: parseInt(edit_cell_id), key: key.toLowerCase() });\n\n /* Now we need to check that we have indeed mapped a key. If we haven't, it means we are\n * creating a new map for a previously unmapped key, and therefore should just insert it\n * into the mappings array.\n */\n var is_mapped = false;\n for (i = 0; i < keyboard_map.mappings.length; i++) {\n if (keyboard_map.mappings[i].key === key.toLowerCase() &&\n keyboard_map.mappings[i].cellid.toString() === edit_cell_id) {\n is_mapped = true;\n }\n }\n if (is_mapped === false) {\n keyboard_map.mappings.push({ cellid: parseInt(edit_cell_id), key: key.toLowerCase() });\n }\n\n if ($('#auto_advance').is(':checked')) {\n deselect_element(selected_element);\n select_element(selected_element.next());\n }\n }\n update_keyboard();\n }\n }\n return;\n }\n\n if (shift_pressed) {\n /* We now show the image overlay to the user with the selected celltype images */\n for (i = 0; i < keyboard_map.mappings.length; i++) {\n if (keyboard_map.mappings[i].key.toUpperCase() === key) {\n var cell_id = keyboard_map.mappings[i].cellid;\n var slug = cell_types[cell_id].machine_name;\n var fullname = cell_types[cell_id].readable_name;\n\n var $dialog = $('<div></div>')\n .load('/images/celltype/' + slug + '/')\n .dialog({\n autoOpen: false,\n title: fullname,\n width: 900,\n height: 700\n });\n /* Close any open dialogues before opening */\n $('.ui-dialog-content').dialog('close');\n $dialog.dialog('open');\n /* No further need to iterate through list */\n break;\n }\n }\n } else if (img_displayed) {\n $('div#imagebox').css('display', 'none');\n img_displayed = false;\n return;\n }\n\n if (key === '1') {\n /* Show percentage view, note e.which is not working due to keypress issues */\n var total = counter.get_total();\n\n var cell_ids = counter.get_cell_ids();\n\n for (i = 0; i < cell_ids.length; i++) {\n var counts = counter.get_counts(cell_ids[i]);\n var boxes = cell_types[cell_ids[i]].box; // XXX\n for (j = 0; j < boxes.length; j++) {\n $(boxes[j]).find('span.countval').text(\n Math.floor((counts.normal + counts.abnormal) / total * 100 + 0.5) + '%');\n $(boxes[j]).find('span.abnormal').text('');\n }\n }\n }\n\n if (code === 8) {\n e.preventDefault();\n var cell_id = counter.undo();\n if (cell_id) update_key_display(cell_id);\n } else {\n for (i = 0; i < keyboard_map.mappings.length; i++) {\n if (keyboard_map.mappings[i].key.toUpperCase() === key && !(shift_pressed)) {\n var id = keyboard_map.mappings[i].cellid;\n\n // Add highlighting to keyboard\n // Remove all currently active highlights (stops a queue developing)\n for (j = 0; j < cell_types[id].box.length; j++) {\n $(cell_types[id].box[j]).stop(true, true).css('background-color', '#ffffff');\n }\n\n // Add highlight to typed key\n $(cell_types[id].box).effect('highlight', {}, 200);\n\n counter.increment(id, abnormal);\n update_key_display(id);\n\n /* No further need to iterate through list */\n break;\n }\n }\n }\n render_chart();\n }\n });\n\n $(document).on('keyup', function (e) {\n var key, code;\n if (keyboard_active) {\n code = e.which;\n key = String.fromCharCode(code).toUpperCase();\n if (code === 173) {\n key = '-';// XXX: WTF\n }\n if (key === ' ') {\n abnormal = false;\n }\n\n if (key === '1') {\n /* Exit view percentages mode */\n update_keyboard();\n }\n }\n });\n}\n\n// resolves when fully initialised\nvar initialised = new $.Deferred();\n\nfunction initialise () {\n init_keyboard_label_editing();\n init_objects();\n\n var init_fns = [function () { init_keyboard(); }, function () { init_other(); }];\n var init_array = [];\n var init_functions = [];\n\n var init_counter = counter.init();\n\n // for each member of init_fns\n // create a deferred object, set the init state to uninitialised\n\n class Container {\n constructor (fun) {\n // Store a reference to our element\n // on the page\n this.fun = fun;\n }\n\n init () {\n // Create a new Deferred.\n var dfd = new $.Deferred();\n this.dfd = dfd;\n\n // Return an immutable promise object.\n // Clients can listen for its done or fail\n // callbacks but they can't resolve it themselves\n return dfd.promise();\n }\n\n run () {\n // run the function\n this.fun();\n\n this.dfd.resolve('Initialised');\n }\n }\n\n for (var i in init_fns) {\n var init_fn = init_fns[i];\n // init_fn();\n var cnt = new Container(init_fn);\n // cnt.init();\n init_array.push(cnt.init());\n init_functions.push(cnt);\n }\n\n // join all the deferred functions\n $.when.apply($, init_array).done(function () {\n update_keyboard();\n\n open_keyboard(initialised.resolve);\n });\n\n $.when(init_counter).done(function () {\n /* Once cell_types has been populated successfully, load keyboard */\n\n results.init(counter);\n\n $.when(load_keyboard()).done(function () {\n // resolve all deferred functions\n for (var i in init_functions) {\n var init_fn = init_functions[i];\n init_fn.run();\n }\n /* for (var i in init_fns) {\n init_fns[i]();\n } */\n });\n });\n}\n\n$(document).ready(initialise);\n\nfunction resize_keyboard (width) {\n /* Does nothing */\n}\n\nfunction register_resets () {\n $('.reset_button').on('click', function () {\n $('#confirm-reset').modal('show');\n });\n $('#reset-count').on('click', function () {\n var total = counter.get_total();\n if(total==0) {\n $('#confirm-reset').modal('hide');\n return;\n }\n var time_counting = counter.get_counting_time();\n log_counter_stats(total, time_counting, \"reset\");\n reset_counters();\n $('#confirm-reset').modal('hide');\n });\n $('#cancel-reset').on('click', function () {\n $('#confirm-reset').modal('hide');\n });\n}\n\nfunction reset_counters () {\n counter.reset();\n results.hide();\n update_keyboard();\n render_chart();\n open_keyboard();\n}\n\nfunction open_keyboard (done) {\n if (typeof done !== 'function') {\n done = function () {};\n }\n\n results.hide();\n\n $('#fuzz').fadeIn({\n duration: 'slow',\n complete: function () {\n resize_keyboard($('div#content').width());\n $('#counterbox').slideDown('slow', function () {\n $('#fuzz').css('height', $(document).height());\n });\n },\n done: done\n });\n\n keyboard_active = true;\n $('#savefilebutton').css('display', 'none');\n render_chart();\n counter.reset_start_time();\n}\n\nvar results = (function () {\n var counter_object = {};\n\n var abnormal_total, me_ratio, count_total;\n\n var results_data;\n\n function calc_stats () {\n count_total = counter_object.get_total();\n\n abnormal_total = counter_object.get_abnormal_total();\n\n var cell_total, cell_percent, cell_percent_abnormal;\n var cell_percent_string, cell_percent_abnormal_string;\n\n cell_percent_string = [];\n cell_percent_abnormal_string = [];\n\n results_data = [];\n\n var erythroid, myeloid;\n var myeloid_cells = ['neutrophils', 'meta', 'myelocytes', 'promyelocytes',\n 'basophils', 'eosinophils', 'monocytes'];\n myeloid = 0;\n\n var cell_ids = counter_object.get_cell_ids();\n\n for (var i = 0; i < cell_ids.length; i++) {\n var cell_id = cell_ids[i];\n\n var counts = counter.get_counts(cell_id);\n var colour = counter.get_visualisation_colour(cell_id);\n var name = counter.get_readable_name(cell_id);\n\n cell_total = counts.normal + counts.abnormal;\n\n cell_percent = Math.round(((cell_total / count_total) * 100));\n cell_percent_abnormal = 0;\n\n if (cell_total !== 0) {\n cell_percent_abnormal = Math.round(((counts.abnormal / cell_total) * 100));\n }\n\n if (cell_total === 0) {\n cell_percent_abnormal_string = 'N/A';\n } else if (cell_percent_abnormal === 0 && counts.abnormal > 0) {\n cell_percent_abnormal_string = '<0.5%';\n } else if (cell_percent_abnormal === 100 && counts.abnormal < cell_total) {\n cell_percent_abnormal_string = '&ge;99.5%';\n } else {\n cell_percent_abnormal_string = cell_percent_abnormal.toString() + '%';\n }\n\n if (cell_percent === 0 && cell_total > 0) {\n cell_percent_string = '<0.5%';\n } else if (cell_percent === 100 && cell_total < count_total) {\n cell_percent_string = '&ge;99.5%';\n } else {\n cell_percent_string = cell_percent.toString() + '%';\n }\n\n results_data.push({\n cell_id: cell_id,\n readable_name: name,\n visualisation_colour: colour,\n count: counts.normal,\n abnormal: counts.abnormal,\n percent_string: cell_percent_string,\n percent_abnormal_string: cell_percent_abnormal_string\n });\n\n var machine_name = counter_object.get_machine_name(cell_id);\n\n /* N.B. Hacky erythroid/myeloid counting */\n if (machine_name === 'erythroid') {\n erythroid = counts.normal + counts.abnormal;\n }\n\n for (var j = 0; j < myeloid_cells.length; j++) {\n if (machine_name === myeloid_cells[j]) {\n myeloid += (counts.normal + counts.abnormal);\n }\n }\n }\n\n me_ratio = parseFloat(myeloid / erythroid).toFixed(2);\n if (me_ratio === 'Infinity') {\n me_ratio = 'Incalculable';\n }\n }\n\n function update_html () {\n var stats_div = $('div#statistics_html');\n\n for (var i = 0; i < results_data.length; i++) {\n var r = results_data[i];\n stats_div.find('td#name-' + r.cell_id).text(r.readable_name);\n stats_div.find('td#colour-' + r.cell_id).css('background-color', r.visualisation_colour);\n stats_div.find('td#percent-' + r.cell_id).text(r.percent_string);\n stats_div.find('td#percent-abnormal-' + r.cell_id).text(r.percent_abnormal_string);\n stats_div.find('td#count-' + r.cell_id).text(r.count);\n stats_div.find('td#abnormal-' + r.cell_id).text(r.abnormal);\n }\n\n stats_div.find('td#total-count').text(count_total);\n stats_div.find('td#me-ratio').text(me_ratio);\n\n if (abnormal_total === 0) {\n /* If we don't have abnormal cells, don't show the columns */\n $('.abnormal_stats').hide();\n $('.table_spacer').attr('colspan', 1);\n } else {\n $('.abnormal_stats').show();\n $('.table_spacer').attr('colspan', 3);\n }\n }\n\n function update_text () {\n var stats_div = $('div#statistics_text');\n var per = '';\n\n for (var i = 0; i < results_data.length; i++) {\n var r = results_data[i];\n per += r.readable_name + ' ' + r.percent_string;\n if (abnormal_total > 0) {\n per += ', abnormal ' + r.percent_abnormal_string + '\\n';\n } else {\n per += '\\n';\n }\n }\n\n stats_div.empty();\n\n var stats_text = '';\n stats_text = '<pre class=\"stats\"><code>';\n stats_text += 'Cells Counted: ' + count_total + '\\n';\n stats_text += 'M:E Ratio: ' + me_ratio + '\\n';\n stats_text += per;\n stats_text += '</code></pre>';\n stats_div.append(stats_text);\n }\n\n return {\n init: function (cntr) {\n counter_object = cntr;\n\n $('#htmlview').click(function () {\n results.show('html');\n });\n $('#textview').click(function () {\n results.show('text');\n });\n },\n\n show: function (fmt) {\n var format = typeof fmt !== 'undefined' ? fmt : 'html';\n\n $('div#statistics_html').hide();\n $('div#statistics_text').hide();\n if (format === 'html') {\n $('div#statistics_html').show();\n } else {\n $('div#statistics_text').show();\n }\n $('div#statistics').show();\n render_chart2();\n\n // display the chart\n $('#visualise2').css('display', 'block');\n },\n\n hide: function () {\n $('div#statistics').hide();\n $('#visualise2').css('display', 'none');\n },\n\n update: function () {\n calc_stats();\n update_html();\n update_text();\n }\n\n };\n})();\n\nfunction log_counter_stats(total, time_counting, event_type) {\n if (total > 75) {\n $.ajax({\n url: '/api/stats/',\n type: 'POST',\n data: JSON.stringify({ count_total: total }),\n contentType: 'application/json; charset=utf-8',\n async: true\n });\n }\n log_plausible_event('Counter', {props: {count: total, time: time_counting, event: event_type}});\n}\n\nfunction log_plausible_event(name, props) {\n if(window.plausible) {\n if(props)\n plausible(name, props);\n else\n plausible(name);\n }\n}\n\nfunction set_keyboard (mapping) {\n keyboard_map = mapping;\n update_keyboard();\n render_chart();\n}\n\nfunction load_keyboard(href) {\n \"use strict\";\n if (href === undefined) {\n $.getJSON(\"/api/keyboards/\" + keyboard_platform + \"/default/\", function(data) {\n keyboard_map = data;\n update_keyboard();\n render_chart();\n });\n } else {\n var keyboard = {};\n $.ajax({\n url: href,\n type: 'GET',\n dataType: 'json',\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function (data) {\n keyboard = data;\n }\n });\n return keyboard;\n }\n}\n\nfunction set_keyboard_default(keyboard_href) {\n \"use strict\";\n $.ajax({\n url: keyboard_href + 'set_default',\n type: 'PUT',\n data: '',\n contentType: \"application/json; charset=utf-8\",\n async: false\n });\n return false;\n}\n\nfunction delete_specific_keyboard(keyboard_href) {\n \"use strict\";\n $.ajax({\n url: keyboard_href,\n type: 'DELETE',\n data: '',\n contentType: 'application/json; charset=utf-8',\n async: false\n });\n}\n\nfunction update_key_display (cell_id) {\n var counts = counter.get_counts(cell_id);\n var k;\n for (k = 0; k < cell_types[cell_id].box.length; k++) {\n $(cell_types[cell_id].box[k]).find('span.abnormal').text('(' + counts.abnormal + ')');\n }\n for (k = 0; k < cell_types[cell_id].box.length; k++) {\n $(cell_types[cell_id].box[k]).find('span.countval').text(counts.normal);\n }\n}\n\nfunction update_keyboard () {\n var i, j;\n var keyboard_keys = $('#keysbox').find('div.box1');\n\n for (var cell in cell_types) {\n if (cell_types.hasOwnProperty(cell)) {\n cell_types[cell].box = [];\n }\n }\n\n for (i = 0; i < keyboard_keys.length; i++) {\n var item = $(keyboard_keys[i]);\n var key = item.attr('id');\n\n item.empty();\n item.append('<p>' + key + '</p>');\n\n for (j = 0; j < keyboard_map.mappings.length; j++) {\n if (keyboard_map.mappings[j].key === key) {\n var cell_id = keyboard_map.mappings[j].cellid;\n var cell_data = cell_types[cell_id];\n\n /* Adds keyboard key div to list of attached keys */\n cell_data.box.push(item);\n var name = cell_data.abbr_name;\n\n var counts = counter.get_counts(cell_id);\n item.append('<div class=\"name\">' + name + '</div>');\n item.append('<div class=\"count\"><span class=\"countval\">' + counts.normal + '</span> <span class=\"abnormal abnormal_count\">(' + counts.abnormal + ')</span></div>');\n\n // Attach cell visualisation_colour to key\n item.find('p').css('background-color', cell_data.visualisation_colour);\n }\n }\n }\n}\n\nfunction edit_keyboard () {\n if (editing_keyboard) {\n return;\n }\n var cell;\n var list = '<ul>';\n\n for (cell in cell_types) {\n if (cell_types.hasOwnProperty(cell)) {\n list += '<li><div class=\"element\"><div class=\"edit_colour_swatch\" id=\"swatch_' + cell + '\"></div>' + cell_types[cell].readable_name + '</div><div class=\"cellid\" style=\"display: none;\">' + cell + '</div></li>';\n }\n }\n list += '</ul>';\n\n var cell_list_div = $('div#celllist');\n\n cell_list_div.empty();\n cell_list_div.append(list);\n\n for (cell in cell_types) {\n if (cell_types.hasOwnProperty(cell)) {\n $('div#swatch_' + cell).css('background-color', cell_types[cell].visualisation_colour);\n }\n }\n\n cell_list_div.find('div.element').click(function () {\n edit_cell_id = $(this).find('div.cellid').text();\n $('div#celllist').find('li').css('background', '');\n deselect_element(selected_element);\n selected_element = $(this).parent();\n select_element($(this).parent());\n });\n\n var el = cell_list_div.find('li').first();\n select_element(el);\n\n $('#clearkeyboard').click(function () {\n clear_keyboard();\n });\n\n editing_keyboard = true;\n\n var save_text = 'Save';\n var save_keys = true;\n if (typeof notloggedin !== 'undefined') {\n save_text = 'Close';\n save_keys = false;\n }\n\n var d = $('div#editkeymapbox').dialog({\n close: function () {\n end_keyboard_edit();\n },\n open: function () {\n // remove focus from the default button\n $('.ui-dialog :button').blur();\n },\n resizable: false,\n buttons: [{ text: save_text,\n id: \"save_keyboard_map\",\n click: function () {\n if (save_keys) {\n save_keyboard();\n } else {\n end_keyboard_edit();\n }\n }\n },\n { text: 'Save as New',\n click: function () {\n if (save_keys) {\n keyboard_name_input();\n } else {\n end_keyboard_edit();\n }\n }\n },\n { text: 'Revert',\n id: \"revert_keyboard_map\",\n click: function () {\n load_keyboard();\n $('div#editkeymapbox').dialog('close');\n }\n }\n ],\n width: '368px'\n });\n\n $(d).dialog('widget')\n .position({ my: 'right top', at: 'right top', of: $('div#counterbox') });\n\n if (!save_keys) {\n $(\":button:contains('Save as New')\").remove();\n }\n}\n\nfunction select_element (el) {\n selected_element = $(el);\n\n if (!selected_element.html()) {\n selected_element = $('div#celllist').find('li').first();\n el = selected_element;\n selected_element = $(selected_element);\n }\n\n if (selected_element.html()) {\n edit_cell_id = $(el).find('div.cellid').text();\n $(el).addClass('selected');\n } else {\n edit_cell_id = -1;\n }\n}\n\nfunction deselect_element (el) {\n $(el).removeClass('selected');\n}\n\nfunction keyboard_name_input () {\n // Disable keyboard capture for edit/input\n editing_keyboard = false;\n keyboard_active = false;\n // Show us the keyboard modal\n $('#keyboard_name').modal('show');\n}\n\nfunction save_new_keyboard (keyboard_name) {\n // Takes keyboard_name from dialog and creates keyboard\n // Scraps any pre-existing keyboard_id\n delete (keyboard_map.id);\n keyboard_name = keyboard_name || 'NewKeyboard';\n keyboard_map.label = keyboard_name;\n save_keyboard();\n\n $('#keyboard_name').modal('hide');\n // This is required to override default modal hide behaviour (above)\n // as when a keyboard is successfully saved, user should return to\n // count.\n editing_keyboard = false;\n}\n\nfunction save_keyboard (keyboard) {\n if (typeof keyboard === 'undefined') {\n keyboard = keyboard_map;\n }\n\n if ('id' in keyboard) {\n $.ajax({\n url: '/api/keyboards/' + keyboard_platform + '/' + keyboard.id + '/',\n type: 'PUT',\n data: JSON.stringify(keyboard),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function () {\n add_alert('INFO', 'Keyboard saved');\n end_keyboard_edit();\n }\n });\n } else {\n $.ajax({\n url: '/api/keyboards/' + keyboard_platform + '/',\n type: 'POST',\n data: JSON.stringify(keyboard),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function () {\n add_alert('INFO', 'Keyboard saved');\n end_keyboard_edit();\n }\n });\n }\n}\n\nfunction end_keyboard_edit () {\n $('div#celllist').empty();\n\n editing_keyboard = false;\n edit_cell_id = -1;\n $('#edit_button').show();\n $('div#editkeymapbox').dialog('close');\n}\n\nfunction clear_keyboard () {\n /* Clear keyboard needs to provide the correct keyboard_map structure\n * otherwise modification of a blank keyboard fails. Also maintain\n * object ID when clearing keyboards so we save to the right place.\n * N.B. .toISOString() requires a shim for IE<= 8 */\n if ('id' in keyboard_map) {\n var id = keyboard_map.id;\n }\n if ('user' in keyboard_map) {\n var user = keyboard_map.user;\n }\n var date = new Date(Date.now()).toISOString();\n keyboard_map = { label: \"Default\",\n is_default: true,\n created: date,\n last_modified: date,\n mappings: [] };\n if (typeof id !== 'undefined') {\n keyboard_map.id = id;\n }\n if (typeof user !== 'undefined') {\n keyboard_map.user = user;\n }\n update_keyboard();\n}\n\nfunction add_alert (alert_class, message) {\n /* Adds alert messages in bootstrap style to page */\n var css_class = '';\n if (alert_class === 'ERROR') {\n css_class = 'alert-error';\n }\n var el = '<div class=\"alert ' + css_class + '\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button><strong>' + alert_class + ':</strong> ' + message + '</div>';\n $('#alerts').append(el);\n}\n\nfunction csrfSafeMethod (method) {\n // these HTTP methods do not require CSRF protection\n return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n}\n\nfunction sameOrigin (url) {\n // test that a given url is a same-origin URL\n // url could be relative or scheme relative or absolute\n var host = document.location.host; // host + port\n var protocol = document.location.protocol;\n var sr_origin = '//' + host;\n var origin = protocol + sr_origin;\n // Allow absolute or scheme relative URLs to same origin\n return (url === origin || url.slice(0, origin.length + 1) === origin + '/') ||\n (url === sr_origin || url.slice(0, sr_origin.length + 1) === sr_origin + '/') ||\n // or any other URL that isn't scheme relative or absolute i.e relative.\n !(/^(\\/\\/|http:|https:).*/.test(url));\n}\n\n$.ajaxSetup({\n beforeSend: function (xhr, settings) {\n var csrftoken = $.cookie('csrftoken');\n if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {\n // Send the token to same-origin, relative URLs only.\n // Send the token only if the method warrants CSRF protection\n // Using the CSRFToken value acquired earlier\n xhr.setRequestHeader('X-CSRFToken', csrftoken);\n }\n }\n});\n" }, { "alpha_fraction": 0.6392745971679688, "alphanum_fraction": 0.6489090323448181, "avg_line_length": 31.981307983398438, "blob_id": "e0b1ffeb822af12bf9638212a589e242c8910728", "content_id": "5d98cfe3e69763d43326dbe57466aaae78e522a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3529, "license_type": "permissive", "max_line_length": 85, "num_lines": 107, "path": "/cellcounter/main/models.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "import os\nimport mimetypes\nfrom io import StringIO\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom colorful.fields import RGBColorField\nfrom PIL import Image\n\n\nclass CellType(models.Model):\n readable_name = models.CharField(max_length=50)\n # TODO Use a slugfield\n machine_name = models.CharField(max_length=50, unique=True)\n abbr_name = models.CharField(max_length=10, unique=True)\n comment = models.TextField(blank=True)\n visualisation_colour = RGBColorField(blank=True)\n display_order = models.IntegerField(null=False, unique=True)\n\n def __unicode__(self):\n return self.readable_name\n\n\nclass CellImage(models.Model):\n title = models.CharField(max_length=100)\n description = models.TextField()\n file = models.ImageField(upload_to=\"cell_images\")\n thumbnail = models.ImageField(upload_to=\"cell_thumbnails\", null=True, blank=True)\n celltype = models.ForeignKey(CellType, on_delete=models.CASCADE)\n thumbnail_left = models.IntegerField()\n thumbnail_top = models.IntegerField()\n thumbnail_width = models.IntegerField()\n uploader = models.ForeignKey(User, on_delete=models.CASCADE)\n copyright = models.ForeignKey(\"CopyrightHolder\", on_delete=models.CASCADE)\n license = models.ForeignKey(\"License\", on_delete=models.CASCADE)\n\n def similar_cells(self):\n groups = self.similarlookinggroup_set.all()\n similar_cells = []\n for group in groups:\n for image in group.cell_image.all():\n similar_cells.append(image)\n return similar_cells\n\n def generate_thumbnail(self):\n django_type = mimetypes.guess_type(self.file.file.name)[0]\n\n if django_type == \"image/jpeg\":\n pil_type = \"jpeg\"\n file_extension = \"jpg\"\n elif django_type == \"image/png\":\n pil_type = \"png\"\n file_extension = \"png\"\n\n image = Image.open(StringIO(self.file.read()))\n thumb_image = image.crop(\n (\n self.thumbnail_left,\n self.thumbnail_top,\n self.thumbnail_left + self.thumbnail_width,\n self.thumbnail_top + self.thumbnail_width,\n )\n )\n thumb_image = thumb_image.resize((200, 200), Image.ANTIALIAS)\n temp_handle = StringIO()\n thumb_image.save(temp_handle, pil_type)\n temp_handle.seek(0)\n\n suf = SimpleUploadedFile(\n os.path.split(self.file.name)[-1],\n temp_handle.read(),\n content_type=django_type,\n )\n self.thumbnail.save(\n \"%s_thumbnail.%s\" % (os.path.splitext(suf.name)[0], file_extension), suf\n )\n\n def __unicode__(self):\n return self.title\n\n\nclass SimilarLookingGroup(models.Model):\n name = models.CharField(max_length=100)\n cell_image = models.ManyToManyField(\"CellImage\")\n\n def __unicode__(self):\n return self.name\n\n\nclass License(models.Model):\n title = models.CharField(max_length=100)\n details = models.TextField()\n\n def __unicode__(self):\n return self.title\n\n\nclass CopyrightHolder(models.Model):\n name = models.CharField(max_length=300)\n link_title = models.CharField(max_length=300, null=True, blank=True)\n link_url = models.CharField(max_length=300, null=True, blank=True)\n user = models.ManyToManyField(\n User\n ) # These users may apply this copyright to an image\n\n def __unicode__(self):\n return self.name\n" }, { "alpha_fraction": 0.5893386006355286, "alphanum_fraction": 0.5984205603599548, "avg_line_length": 35.970802307128906, "blob_id": "c403f29d3db9d618a153d706f6a830c9f6eb0078", "content_id": "eda8f58840c2cb844c303cd8d2127150f14150c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5065, "license_type": "permissive", "max_line_length": 86, "num_lines": 137, "path": "/cellcounter/accounts/test_forms.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from urllib.parse import urlparse\n\nimport re\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.core import mail\nfrom django.urls import reverse\nfrom django.test import TestCase\nfrom django.test.client import RequestFactory\nfrom django.utils.http import urlsafe_base64_decode\n\nfrom cellcounter.cc_kapi.factories import UserFactory\nfrom .forms import EmailUserCreationForm, PasswordResetForm\n\n\nclass TestEmailUserCreationForm(TestCase):\n def test_valid(self):\n data = {\n \"username\": \"joebloggs\",\n \"email\": \"[email protected]\",\n \"password1\": \"new_pwd\",\n \"password2\": \"new_pwd\",\n \"tos\": True,\n }\n form = EmailUserCreationForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_invalid(self):\n data_no_email = {\n \"username\": \"joebloggs\",\n \"email\": \"\",\n \"password1\": \"new_pwd\",\n \"password2\": \"new_pwd\",\n \"tos\": True,\n }\n data_invalid_email = {\n \"username\": \"joebloggs\",\n \"email\": \"\",\n \"password1\": \"new_pwd\",\n \"password2\": \"new_pwd\",\n \"tos\": True,\n }\n data_no_tos = {\n \"username\": \"joebloggs\",\n \"email\": \"[email protected]\",\n \"password1\": \"new_pwd\",\n \"password2\": \"new_pwd\",\n }\n data_false_tos = {\n \"username\": \"joebloggs\",\n \"email\": \"[email protected]\",\n \"password1\": \"new_pwd\",\n \"password2\": \"new_pwd\",\n \"tos\": False,\n }\n\n form = EmailUserCreationForm(data=data_no_email)\n self.assertFalse(form.is_valid())\n form = EmailUserCreationForm(data=data_invalid_email)\n self.assertFalse(form.is_valid())\n self.assertEqual(\"This field is required.\", form.errors[\"email\"][0])\n form = EmailUserCreationForm(data=data_no_tos)\n self.assertFalse(form.is_valid())\n self.assertEqual(\"You must agree our Terms of Service\", form.errors[\"tos\"][0])\n form = EmailUserCreationForm(data=data_false_tos)\n self.assertFalse(form.is_valid())\n self.assertEqual(\"You must agree our Terms of Service\", form.errors[\"tos\"][0])\n\n\nclass TestPasswordResetForm(TestCase):\n def setUp(self):\n self.user = UserFactory()\n self.request_factory = RequestFactory()\n\n def test_valid(self):\n data = {\"email\": self.user.email}\n form = PasswordResetForm(data=data)\n self.assertTrue(form.is_valid())\n\n def test_invalid(self):\n # Empty\n data = {\"email\": \"\"}\n form = PasswordResetForm(data=data)\n self.assertFalse(form.is_valid())\n self.assertEqual(\"This field is required.\", form.errors[\"email\"][0])\n\n # Invalid\n data = {\"email\": \"[email protected]\"}\n form = PasswordResetForm(data=data)\n self.assertFalse(form.is_valid())\n self.assertEqual(\"Enter a valid email address\", form.errors[\"email\"][0])\n\n # Inactive\n user = UserFactory(is_active=False)\n data = {\"email\": user.email}\n form = PasswordResetForm(data=data)\n self.assertFalse(form.is_valid())\n self.assertEqual(\"Enter a valid email address\", form.errors[\"email\"][0])\n\n # Disabled password\n user = UserFactory()\n user.set_unusable_password()\n user.save()\n data = {\"email\": user.email}\n form = PasswordResetForm(data=data)\n self.assertFalse(form.is_valid())\n self.assertEqual(\"Enter a valid email address\", form.errors[\"email\"][0])\n\n def test_save(self):\n data = {\"email\": self.user.email}\n request = self.request_factory.post(reverse(\"password-reset\"), data=data)\n form = PasswordResetForm(data=data)\n self.assertTrue(form.is_valid())\n form.save(request=request)\n self.assertEqual(len(mail.outbox), 1)\n\n def test_save_multi(self):\n user1 = UserFactory(email=\"[email protected]\")\n UserFactory(email=\"[email protected]\")\n data = {\"email\": user1.email}\n request = self.request_factory.post(reverse(\"password-reset\"), data=data)\n form = PasswordResetForm(data=data)\n self.assertTrue(form.is_valid())\n form.save(request=request)\n self.assertEqual(len(mail.outbox), 2)\n\n def test_token_generation(self):\n user = UserFactory()\n data = {\"email\": user.email}\n request = self.request_factory.post(reverse(\"password-reset\"), data=data)\n reset_form = PasswordResetForm(data=data)\n self.assertTrue(reset_form.is_valid())\n context = reset_form.get_context_data(request, user, default_token_generator)\n uidb64, token = urlparse(context[\"url\"]).path.split(\"/\")[-3:-1]\n self.assertIsNotNone(re.match(\"[0-9A-Za-z_\\-]+\", uidb64))\n self.assertIsNotNone(re.match(\"[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20}\", token))\n self.assertEqual(urlsafe_base64_decode(uidb64).decode(\"utf-8\"), str(user.id))\n self.assertTrue(default_token_generator.check_token(user, token))\n" }, { "alpha_fraction": 0.6467034220695496, "alphanum_fraction": 0.6614131927490234, "avg_line_length": 31.818965911865234, "blob_id": "e59ce915a798d3cd9da132366a67eb648e67ae0d", "content_id": "ca7f68c0ba4606e72c9459975d2cc02d80f76e16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3807, "license_type": "permissive", "max_line_length": 89, "num_lines": 116, "path": "/cellcounter/cc_kapi/test_db_migration.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.test import TransactionTestCase\nfrom django.db.migrations.executor import MigrationExecutor\nfrom django.db import connection, transaction\n\nfrom django.utils import timezone\n\nfrom django.contrib.auth.models import User\nfrom .factories import UserFactory, KeyboardFactory\nfrom .serializers import KeyboardListItemSerializer\nfrom .models import Keyboard\n\nfrom django.db import models\n\n\nclass TestMigrations(TransactionTestCase):\n\n migrate_from = None\n migrate_to = None\n\n def setUp(self):\n assert (\n self.migrate_from and self.migrate_to\n ), \"TestCase '{}' must define migrate_from and migrate_to properties\".format(\n type(self).__name__\n )\n\n connection.prepare_database()\n\n executor = MigrationExecutor(connection)\n old_apps = executor.loader.project_state(self.migrate_from).apps\n\n # Reverse to the original migration\n executor.migrate(self.migrate_from)\n\n # Setup the database in the pre-migration state\n self.setUpBeforeMigration(old_apps)\n\n # Run the migration to test\n executor.loader.build_graph()\n executor.migrate(self.migrate_to)\n\n self.apps = executor.loader.project_state(self.migrate_to).apps\n\n def setUpBeforeMigration(self, apps):\n pass\n\n\nclass DefaultsTestCase(TestMigrations):\n\n migrate_from = [(\"cc_kapi\", \"0001_initial\")]\n migrate_to = [(\"cc_kapi\", \"0002_v2api\")]\n\n def setUpBeforeMigration(self, apps):\n # create users and keyboards under the old schema\n User = apps.get_model(\"auth\", \"User\")\n\n class KeyboardFactory2(KeyboardFactory):\n class Meta:\n model = apps.get_model(\"cc_kapi\", \"Keyboard\")\n\n user = User(username=\"test\")\n user.save()\n self.user_id = user.id\n\n keyboard1 = KeyboardFactory2(user=user)\n keyboard1.is_primary = True\n keyboard1.save()\n self.keyboard1_id = keyboard1.id\n\n keyboard2 = KeyboardFactory2(user=user)\n keyboard2.save()\n self.keyboard2_id = keyboard2.id\n\n user1 = User(username=\"test2\")\n user1.save()\n self.user1_id = user1.id\n\n keyboard3 = KeyboardFactory2(user=user1)\n keyboard3.save()\n self.keyboard3_id = keyboard3.id\n\n def test_defaults_migrated(self):\n # check that there are two users\n users = User.objects.all()\n self.assertEqual(len(users), 2)\n\n user = User.objects.get(id=self.user_id)\n user1 = User.objects.get(id=self.user1_id)\n\n # check that the three keyboards in the database exist\n kb1 = Keyboard.objects.get(id=self.keyboard1_id)\n kb2 = Keyboard.objects.get(id=self.keyboard2_id)\n kb3 = Keyboard.objects.get(id=self.keyboard3_id)\n\n # check that there are two keyboards for user and that the ids match\n keyboards = user.keyboard_set.all()\n self.assertEqual(len(keyboards), 2)\n kids = [k.id for k in keyboards]\n kids.sort()\n self.assertEqual(kids, [self.keyboard1_id, self.keyboard2_id])\n\n # check that there is one keyboard for user1 and that the id matches\n keyboards1 = user1.keyboard_set.all()\n self.assertEqual(len(keyboards1), 1)\n self.assertEqual(keyboards1[0].id, self.keyboard3_id)\n\n # check that there are three keyboards in total\n keyboards_all = Keyboard.objects.all()\n self.assertEqual(len(keyboards_all), 3)\n\n # check that kb is user's default desktop keyboard and there is no mobile default\n self.assertEqual(user.defaultkeyboards.desktop.id, kb1.id)\n self.assertEqual(user.defaultkeyboards.mobile, None)\n\n # check that user1 has no default desktop or mobile keyboard\n self.assertFalse(hasattr(user1, \"defaultkeyboards\"))\n" }, { "alpha_fraction": 0.5445292592048645, "alphanum_fraction": 0.5928753018379211, "avg_line_length": 20.83333396911621, "blob_id": "e29791c70828f801f335cab42f4d9481dcf8579e", "content_id": "dc4ed76e7f0f60ebe40865b7551d713d2560b2b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "permissive", "max_line_length": 51, "num_lines": 18, "path": "/cellcounter/main/migrations/0005_unique_display_order.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.3 on 2019-07-11 15:48\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"main\", \"0004_display_order_data\"),\n ]\n\n operations = [\n migrations.AlterField(\n model_name=\"celltype\",\n name=\"display_order\",\n field=models.IntegerField(unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.4089943468570709, "alphanum_fraction": 0.41678470373153687, "avg_line_length": 26.42718505859375, "blob_id": "cee383c695439ebc952b7773fa33b92cbaa4d7af", "content_id": "3faa6c584777aee0722d9381e1f770f44dd5cf5a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2824, "license_type": "permissive", "max_line_length": 82, "num_lines": 103, "path": "/cellcounter/main/static/js/visualise.js", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "function doughnutChart(selector_id) {\n \"use strict\";\n var _chart = {};\n\n var _width = 200, _height = 200,\n _data = [],\n _svg, _bodyG, _pieG,\n _radius = 100,\n _inner_radius = 50;\n\n _chart.render = function(data) {\n if (!_svg) {\n _svg = d3.select(selector_id).append(\"svg\")\n .attr(\"height\", _height)\n .attr(\"width\", _width);\n }\n renderBody(_svg);\n };\n\n function renderBody(svg) {\n if (!_bodyG) {\n _bodyG = svg.append(\"g\")\n .attr(\"class\", \"body\");\n }\n renderDoughnut();\n }\n\n function renderDoughnut() {\n var pie = d3.layout.pie()\n .sort(null)\n .value(function (d) {\n return d.count + d.abnormal;\n });\n\n var arc = d3.svg.arc()\n .outerRadius(_radius)\n .innerRadius(_inner_radius);\n\n if (!_pieG) {\n _pieG = _bodyG.append(\"g\")\n .attr(\"class\", \"pie\")\n .attr(\"transform\", \"translate(\"\n + _radius\n + \",\"\n + _radius + \")\");\n }\n renderSlices(pie, arc);\n renderLabels(pie, arc);\n }\n\n function renderSlices(pie, arc) {\n var slices;\n\n if (pie(_data).filter(function(d) {return d.value > 0;}).length > 0 ) {\n slices = _pieG.selectAll(\"path.arc\")\n .data(pie(_data));\n\n slices.enter()\n .append(\"path\")\n .attr(\"class\", \"arc\")\n .attr(\"fill\", function (d) {\n return d.data.visualisation_colour;\n });\n\n slices.transition()\n .attrTween(\"d\", function (d) {\n var currentArc = this.__current__;\n if (!currentArc) {\n currentArc = {startAngle: 0, endAngle: 0};\n }\n var interpolate = d3.interpolate(currentArc, d);\n this.__current__ = interpolate(1);\n return function (t) {\n return arc(interpolate(t));\n };\n });\n } else {\n /* This handles the case when you have an empty (i.e. Zero'd graph) */\n slices = _pieG.selectAll(\"path.arc\")\n .data(pie(_data));\n slices.remove();\n }\n }\n\n function renderLabels() {\n\n var total = 0;\n for (var j=0; j < _data.length; j++) {\n total += (_data[j].count + _data[j].abnormal);\n }\n $(\"div.total\").text(total);\n }\n\n _chart.data = function(d) {\n if (!arguments.length) {\n return _data;\n }\n _data = d;\n return _chart;\n };\n\n return _chart;\n}" }, { "alpha_fraction": 0.4885496199131012, "alphanum_fraction": 0.694656491279602, "avg_line_length": 15.375, "blob_id": "15ba2b68cbf36f73718661a69d6e249f823abe1e", "content_id": "547a764f546ccf562bbe6e2bb9770bcbcc54f860", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 131, "license_type": "permissive", "max_line_length": 22, "num_lines": 8, "path": "/test-requirements.txt", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "WebOb==1.8.7\nWebTest==3.0.0\nbeautifulsoup4==4.11.1\ndjango-webtest==1.9.10\nfactory-boy==3.2.1\nsix==1.16.0\nwaitress==2.1.2\nblack>=22\n" }, { "alpha_fraction": 0.7072637677192688, "alphanum_fraction": 0.7078099250793457, "avg_line_length": 34.19230651855469, "blob_id": "8f8f2cb0d052e58cd18a7292d5e26089fef3b34f", "content_id": "fa6e79eade8aa370ebd55aec8cce0d6c2df0fc38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1831, "license_type": "permissive", "max_line_length": 125, "num_lines": 52, "path": "/cellcounter/cc_kapi/README.md", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# Cellcounter Keyboard API v2 \n\n# Setup\n\nAs part of the pain Cellcounter project, the below is already done, but as a note on functionality:\n\ncc_kapi is listed in the INSTALLED_APPS in settings.py:\n INSTALLED_APPS = (...\n 'cellcounter.cc_kapi',\n )\n\nIn urls.py we have a declaration to point the keyboard api related requests to the cc_kapi urls.py\n\n urlpatterns = patterns('',\n url(r'^api/keyboards', include('cellcounter.cc_kapi.urls')),\n )\n\nFinally, in deployment, we'll need to run ```collectstatic``` in order to pull the Javascript into the main static directory.\n\n python manage.py collectstatic\n\n\n# Usage\n\nAccess through api/keyboards/\n\napi/keyboards/\n GET: lists all available keyboards, including builtin and user keyboards for both desktop and mobile\n\napi/keyboards/desktop/\n GET: lists all available desktop keyboards, including builtin and user keyboards\n POST: adds a new desktop keyboard\n\napi/keyboards/desktop/<id>/\n GET: gets the desktop keyboard with identifier <id> (<id>: db_key | 'builtin' | 'default')\n PUT: updates the specified desktop keyboard\n DELETE: deletes the specified desktop keyboard\n\napi/keyboards/desktop/<id>/set_default\n PUT: sets the specified desktop keyboard as the default desktop keyboard\n\napi/keyboards/mobile/\n GET: lists all available mobile keyboards, including builtin and user keyboards\n POST: adds a new mobile keyboard\n\napi/keyboards/mobile/<id>/\n GET: gets the mobile keyboard with identifier <id> (<id>: db_key | 'builtin' | 'default')\n PUT: updates the specified mobile keyboard\n DELETE: deletes the specified mobile keyboard\n\napi/keyboards/mobile/<id>/set_default\n PUT: sets the specified mobile keyboard as the default mobile keyboard\n\n" }, { "alpha_fraction": 0.7069199681282043, "alphanum_fraction": 0.7137042284011841, "avg_line_length": 18.36842155456543, "blob_id": "764cb5a9a05523f79454d92fb67a02f1e5a2f7ec", "content_id": "5799ec15066f95fc0139299475a4115595ffc1ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 737, "license_type": "permissive", "max_line_length": 77, "num_lines": 38, "path": "/test_integration.sh", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nexport NODE_PATH=node_modules/.bin\n\n\nTMP_SERVER_LOG_FILE=$(mktemp)\n\nexport DEBUG=True\n\n# disable autoreload or Django unhelpfully changes PID\n(python3 -u manage.py runserver --noreload | tee $TMP_SERVER_LOG_FILE) &\n\nDEBUG_SERVER_PID=$!\n\nsleep 1\n\n[ -d \"/proc/${DEBUG_SERVER_PID}\" ] || (echo \"Server not running\"; exit 1)\n\nwhile ! grep -m1 'Quit the server with CONTROL-C.' < $TMP_SERVER_LOG_FILE; do\n sleep 1\ndone\n\nTESTS=\"js_test/test_counting.js\"\nTESTS=\"$TESTS js_test/test_display.js\"\nTESTS=\"$TESTS js_test/test_abnormal.js\"\nTESTS=\"$TESTS js_test/test_keyboard_editing.js\"\n\nmocha $TESTS\n\nretval=$?\n\n# kill the server process\nkill $DEBUG_SERVER_PID\n\n# delete the temporary log file\nrm $TMP_SERVER_LOG_FILE\n\nexit $retval\n\n" }, { "alpha_fraction": 0.6525423526763916, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 24.285715103149414, "blob_id": "a32afcd091898373669766f6ed9b798b9291d0f5", "content_id": "8a37e1a64c4faacdd5910279d5b1c5640c078660", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 354, "license_type": "permissive", "max_line_length": 48, "num_lines": 14, "path": "/docker/nginx/Dockerfile", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "FROM nginx:1.21-alpine\n\nRUN rm /etc/nginx/conf.d/default.conf\nCOPY nginx.conf /etc/nginx/conf.d\n\nCOPY 50x.html /srv\n\nRUN chown -R nginx:nginx /var/cache/nginx && \\\n chown -R nginx:nginx /var/log/nginx && \\\n chown -R nginx:nginx /etc/nginx/conf.d\nRUN touch /var/run/nginx.pid && \\\n chown -R nginx:nginx /var/run/nginx.pid\n\nUSER nginx\n" }, { "alpha_fraction": 0.5917408466339111, "alphanum_fraction": 0.6038442850112915, "avg_line_length": 35.527366638183594, "blob_id": "743bc0ac1ea035610311ab63a7597908cdd1e82a", "content_id": "beebe8edd7897e7e65cf9a48f0ab2f5f0e1d2eee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34701, "license_type": "permissive", "max_line_length": 188, "num_lines": 950, "path": "/cellcounter/cc_kapi/tests.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "import json\n\nfrom django_webtest import WebTest\nfrom django.test import TestCase\n\nfrom django.urls import reverse\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nfrom cellcounter.main.models import CellType\nfrom .defaults import MOCK_KEYBOARD, MOCK_KEYBOARD2, BAD_KEYBOARD\nfrom .defaults import BUILTIN_KEYBOARD_STRING, BUILTIN_KEYBOARD_STRING_LOGGED_IN\nfrom .defaults import BUILTIN_DESKTOP_KEYBOARD_MAP, BUILTIN_MOBILE_KEYBOARD_MAP\nfrom .factories import (\n UserFactory,\n KeyboardFactory,\n KeyMapFactory,\n DefaultKeyboardFactory,\n DefaultKeyboardsFactory,\n BuiltinKeyboardFactory,\n)\nfrom .models import Keyboard, DefaultKeyboards\nfrom .serializers import KeyboardSerializer, KeyboardListItemSerializer\n\nfrom io import StringIO\n\nfrom datetime import datetime\nimport pytz\n\n\ndef DecodeDateTimeInUTC(d, fields=[\"created\", \"last_modified\"]):\n \"\"\"Utility function to convert datetime fields to UTC\"\"\"\n\n def to_utc(datetime_string):\n return datetime.fromisoformat(\n datetime_string.replace(\"Z\", \"+00:00\")\n ).astimezone(pytz.utc)\n\n for f in fields:\n if f in d:\n d[f] = to_utc(d[f])\n return d\n\n\nclass KeyboardTestCase(TestCase):\n def test_unicode(self):\n keyboard = KeyboardFactory(user__username=\"alpha\", label=\"alpha\")\n self.assertEqual(keyboard.__unicode__(), \"Keyboard 'alpha' for user 'alpha'\")\n\n def test_set_keymaps(self):\n user = UserFactory()\n keyboard = KeyboardFactory(user=user)\n number_old_maps = len(keyboard.mappings.all())\n new_maps = [KeyMapFactory(cellid=CellType.objects.get(id=1))]\n keyboard.set_keymaps(new_maps)\n\n self.assertNotEqual(number_old_maps, len(keyboard.mappings.all()))\n self.assertEqual(len(new_maps), len(keyboard.mappings.all()))\n\n\nclass KeyboardsAPIListTest(WebTest):\n csrf_checks = False\n\n def setUp(self):\n self.user = UserFactory()\n self.desktop_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.DESKTOP\n )\n self.mobile_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.MOBILE\n )\n self.builtin_desktop_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.DESKTOP\n )\n self.builtin_mobile_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.MOBILE\n )\n\n self.maxDiff = None\n\n def test_get_keyboard_default_anon(self):\n response = self.app.get(reverse(\"keyboards-list\"))\n\n # decode the datetime fields in UTC for comparison (app is timezone aware)\n a = json.loads(BUILTIN_KEYBOARD_STRING, object_hook=DecodeDateTimeInUTC)\n b = json.loads(response.body.decode(\"utf-8\"), object_hook=DecodeDateTimeInUTC)\n self.assertEqual(a, b)\n\n def test_get_keyboard_default_logged_in(self):\n # create a default user with no keyboards\n self.maxDiff = None\n user = UserFactory(username=\"test\")\n response = self.app.get(reverse(\"keyboards-list\"), user=user.username)\n\n # decode the datetime fields in UTC for comparison (app is timezone aware)\n a = json.loads(\n BUILTIN_KEYBOARD_STRING_LOGGED_IN, object_hook=DecodeDateTimeInUTC\n )\n b = json.loads(response.body.decode(\"utf-8\"), object_hook=DecodeDateTimeInUTC)\n self.assertEqual(a, b)\n\n def test_get_default_notset(self):\n # use a user but don't have any default keyboard set\n response = self.app.get(reverse(\"keyboards-list\"), user=self.user.username)\n\n # XXX: the default is currently set in the view, so mirror that in the test\n self.builtin_desktop_keyboard.set_default()\n self.builtin_mobile_keyboard.set_default()\n\n keyboards = [\n self.builtin_desktop_keyboard,\n self.builtin_mobile_keyboard,\n self.desktop_keyboard,\n self.mobile_keyboard,\n ]\n serializer = []\n for kb in keyboards:\n serializer.append(kb.serialize(many=True))\n # serializer = KeyboardListItemSerializer(keyboards, many=True)\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n self.assertEqual(serializer[0][\"is_default\"], True)\n self.assertEqual(serializer[1][\"is_default\"], True)\n self.assertEqual(serializer[2][\"is_default\"], False)\n self.assertEqual(serializer[3][\"is_default\"], False)\n\n def test_get_default_set(self):\n # use a user with a default desktop and user keyboard\n if not hasattr(self.user, \"defaultkeyboards\"):\n self.user.defaultkeyboards = DefaultKeyboards.objects.create(user=self.user)\n self.user.defaultkeyboards.desktop = self.desktop_keyboard\n self.user.defaultkeyboards.mobile = self.mobile_keyboard\n self.user.defaultkeyboards.save()\n\n response = self.app.get(reverse(\"keyboards-list\"), user=self.user.username)\n\n # XXX: the default is currently set in the view, so mirror that in the test\n self.desktop_keyboard.set_default()\n self.mobile_keyboard.set_default()\n\n keyboards = [\n self.builtin_desktop_keyboard,\n self.builtin_mobile_keyboard,\n self.desktop_keyboard,\n self.mobile_keyboard,\n ]\n serializer = []\n for kb in keyboards:\n serializer.append(kb.serialize(many=True))\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n self.assertEqual(serializer[0][\"is_default\"], False)\n self.assertEqual(serializer[1][\"is_default\"], False)\n self.assertEqual(serializer[2][\"is_default\"], True)\n self.assertEqual(serializer[3][\"is_default\"], True)\n\n # test put\n def test_put_keyboard_logged_out(self):\n response = self.app.put(reverse(\"keyboards-list\"), MOCK_KEYBOARD, status=403)\n self.assertEqual(response.status_code, 403)\n\n def test_put_keyboard_list(self):\n response = self.app.put(\n reverse(\"keyboards-list\"), MOCK_KEYBOARD, user=self.user, status=405\n )\n self.assertEqual(response.status_code, 405)\n\n # test delete\n def test_delete_keyboard_logged_out(self):\n response = self.app.delete(reverse(\"keyboards-list\"), status=403)\n self.assertEqual(response.status_code, 403)\n\n def test_delete_keyboard_list(self):\n response = self.app.delete(\n reverse(\"keyboards-list\"), user=self.user, status=405\n )\n self.assertEqual(response.status_code, 405)\n\n # test post\n def test_post_keyboard_logged_out(self):\n response = self.app.post(reverse(\"keyboards-list\"), MOCK_KEYBOARD, status=403)\n self.assertEqual(response.status_code, 403)\n\n def test_post_keyboard_list(self):\n response = self.app.post(\n reverse(\"keyboards-list\"), MOCK_KEYBOARD, user=self.user, status=405\n )\n self.assertEqual(response.status_code, 405)\n\n\nclass KeyboardsAPIDesktopListTest(WebTest):\n csrf_checks = False\n\n def setUp(self):\n self.user = UserFactory()\n self.desktop_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.DESKTOP\n )\n self.mobile_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.MOBILE\n )\n self.builtin_desktop_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.DESKTOP\n )\n self.builtin_mobile_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.MOBILE\n )\n\n # test get\n def test_get_keyboard_desktop_builtin(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-list\"), user=self.user, status=200\n )\n\n # XXX: the default is currently set in the view, so mirror that in the test\n self.builtin_desktop_keyboard.set_default()\n\n keyboards = [self.builtin_desktop_keyboard, self.desktop_keyboard]\n serializer = []\n for kb in keyboards:\n serializer.append(kb.serialize(many=True))\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n def test_get_keyboard_desktop_builtin_logged_out(self):\n response = self.app.get(reverse(\"keyboards-desktop-list\"), status=200)\n\n # XXX: the default is currently set in the view, so mirror that in the test\n self.builtin_desktop_keyboard.set_default()\n\n serializer = [self.builtin_desktop_keyboard.serialize(many=True)]\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n # test put\n def test_put_keyboard_logged_out(self):\n response = self.app.put(\n reverse(\"keyboards-desktop-list\"), MOCK_KEYBOARD, status=403\n )\n self.assertEqual(response.status_code, 403)\n\n def test_put_keyboard(self):\n response = self.app.put(\n reverse(\"keyboards-desktop-list\"), MOCK_KEYBOARD, user=self.user, status=405\n )\n self.assertEqual(response.status_code, 405)\n\n # test delete\n def test_delete_keyboard_logged_out(self):\n response = self.app.delete(reverse(\"keyboards-desktop-list\"), status=403)\n self.assertEqual(response.status_code, 403)\n\n def test_delete_keyboard(self):\n response = self.app.delete(\n reverse(\"keyboards-desktop-list\"), user=self.user, status=405\n )\n self.assertEqual(response.status_code, 405)\n\n # test post\n def test_post_keyboard_logged_out(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-list\"), MOCK_KEYBOARD, status=403\n )\n self.assertEqual(response.status_code, 403)\n\n def test_post_keyboard_logged_in(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-list\"),\n json.dumps(MOCK_KEYBOARD),\n headers={\"Content-Type\": \"application/json\"},\n user=self.user.username,\n status=201,\n )\n self.assertEqual(response.status_code, 201)\n self.assertEqual(len(Keyboard.objects.filter(user=self.user)), 3)\n\n def test_post_keyboard_missing_fields(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-list\"),\n json.dumps({k: v for k, v in list(MOCK_KEYBOARD.items()) if k != \"label\"}),\n headers={\"Content-Type\": \"application/json\"},\n user=self.user.username,\n status=400,\n )\n self.assertEqual(\n response.body.decode(\"utf-8\"), '{\"label\":[\"This field is required.\"]}'\n )\n self.assertEqual(response.status_code, 400)\n\n def test_post_keyboard_missing_mappings(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-list\"),\n json.dumps(\n {k: v for k, v in list(MOCK_KEYBOARD.items()) if k != \"mappings\"}\n ),\n headers={\"Content-Type\": \"application/json\"},\n user=self.user.username,\n status=400,\n )\n self.assertEqual(\n '{\"mappings\":[\"This field is required.\"]}', response.body.decode(\"utf-8\")\n )\n self.assertEqual(response.status_code, 400)\n\n\nclass KeyboardsAPIDesktopDetailTest(WebTest):\n csrf_checks = False\n\n def setUp(self):\n self.user = UserFactory()\n self.desktop_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.DESKTOP\n )\n self.mobile_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.MOBILE\n )\n self.builtin_desktop_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.DESKTOP\n )\n self.builtin_mobile_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.MOBILE\n )\n\n ##### test get\n def test_get_keyboard_desktop_builtin(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n user=self.user,\n status=200,\n )\n serializer = self.builtin_desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n def test_get_keyboard_desktop_builtin_logged_out(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}), status=200\n )\n serializer = self.builtin_desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n def test_get_keyboard_desktop_default(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n serializer = self.builtin_desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n def test_get_keyboard_desktop_default_logged_out(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"default\"}), status=200\n )\n serializer = self.builtin_desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n def test_get_keyboard_desktop_anothers_keyboard(self):\n user = UserFactory()\n response = self.app.get(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=user.username,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n def test_get_keyboard_desktop_keyboard(self):\n response = self.app.get(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=self.user,\n status=200,\n )\n serializer = KeyboardSerializer(self.desktop_keyboard)\n self.assertEqual(JSONRenderer().render(serializer.data), response.body)\n\n def test_get_keyboard_desktop_keyboard_mobile(self):\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": self.desktop_keyboard.id}),\n user=self.user,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n def test_get_keyboard_desktop_keyboard_logged_out(self):\n response = self.app.get(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n def test_get_desktop_nonexistent_keyboard_detail(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": 99}),\n user=self.user.username,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n ##### test put\n def test_put_keyboard_desktop_logged_out(self):\n response = self.app.put(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_put_keyboard_desktop_builtin(self):\n response = self.app.put(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n user=self.user.username,\n status=400,\n )\n self.assertEqual(response.status_code, 400)\n\n def test_put_keyboard_desktop_no_data(self):\n response = self.app.put(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=self.user.username,\n status=400,\n )\n self.assertEqual(\n '{\"label\":[\"This field is required.\"],\"device_type\":[\"This field is required.\"],\"mappings\":[\"This field is required.\"]}',\n response.body.decode(\"utf-8\"),\n )\n self.assertEqual(response.status_code, 400)\n\n def test_put_keyboard_desktop_invalid_data(self):\n response = self.app.put(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n BAD_KEYBOARD,\n user=self.user.username,\n status=400,\n )\n self.assertEqual(\n '{\"label\":[\"This field is required.\"],\"device_type\":[\"\\\\\"desktopz\\\\\" is not a valid choice.\"],\"mappings\":[\"This field is required.\"]}',\n response.body.decode(\"utf-8\"),\n )\n self.assertEqual(response.status_code, 400)\n\n def test_put_keyboard_desktop_nonexistent_keyboard_logged_in(self):\n response = self.app.put(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": 99}),\n json.dumps(MOCK_KEYBOARD),\n headers={\"Content-Type\": \"application/json\"},\n user=self.user.username,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n def test_put_keyboard_desktop_no_mappings(self):\n response = self.app.put(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n json.dumps({k: v for k, v in MOCK_KEYBOARD.items() if k != \"mappings\"}),\n headers={\"Content-Type\": \"application/json\"},\n user=self.user.username,\n status=400,\n )\n self.assertEqual(\n '{\"mappings\":[\"This field is required.\"]}', response.body.decode(\"utf-8\")\n )\n self.assertEqual(response.status_code, 400)\n\n def test_put_keyboard_desktop_missing_fields(self):\n response = self.app.put(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n json.dumps({k: v for k, v in MOCK_KEYBOARD.items() if k != \"label\"}),\n headers={\"Content-Type\": \"application/json\"},\n user=self.user.username,\n status=400,\n )\n self.assertEqual(\n response.body.decode(\"utf-8\"), '{\"label\":[\"This field is required.\"]}'\n )\n self.assertEqual(response.status_code, 400)\n\n def test_put_keyboard_desktop_valid_data(self):\n # response = self.client.put(reverse('keyboards-desktop-detail', kwargs={'pk': self.desktop_keyboard.id}), MOCK_KEYBOARD2, user=self.user.username, content_type='application/json')\n response = self.app.put_json(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n MOCK_KEYBOARD2,\n user=self.user.username,\n )\n response = self.app.get(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=self.user,\n status=200,\n )\n a = json.loads(response.body.decode(\"utf-8\"))\n self.assertEqual(a[\"id\"], self.desktop_keyboard.id)\n self.assertEqual(a[\"label\"], \"Keyboard2\")\n self.assertEqual(response.status_code, 200)\n\n ##### test delete\n def test_delete_keyboard_logged_out(self):\n response = self.app.delete(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_delete_keyboard_builtin(self):\n response = self.app.delete(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n user=self.user,\n status=400,\n )\n self.assertEqual(response.status_code, 400)\n\n def test_delete_keyboard_desktop(self):\n self.assertEqual(len(Keyboard.objects.filter(user=self.user)), 2)\n response = self.app.delete(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=self.user,\n status=200,\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(Keyboard.objects.filter(user=self.user)), 1)\n with self.assertRaises(Keyboard.DoesNotExist):\n Keyboard.objects.get(id=self.desktop_keyboard.id)\n\n def test_delete_keyboard_desktop_mobile(self):\n self.assertEqual(len(Keyboard.objects.filter(user=self.user)), 2)\n response = self.app.delete(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": self.mobile_keyboard.id}),\n user=self.user,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n self.assertEqual(len(Keyboard.objects.filter(user=self.user)), 2)\n\n def test_delete_keyboard_desktop_other_user(self):\n user = UserFactory()\n self.assertEqual(len(Keyboard.objects.filter(user=self.user)), 2)\n response = self.app.delete(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": self.mobile_keyboard.id}),\n user=user,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n self.assertEqual(len(Keyboard.objects.filter(user=self.user)), 2)\n self.assertEqual(\n '{\"detail\":\"desktop keyboard with id \\''\n + str(self.mobile_keyboard.id)\n + \"' not found\\\"}\",\n response.body.decode(\"utf-8\"),\n )\n\n ##### test post\n def test_post_keyboard_desktop_logged_out(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_post_keyboard_desktop_no_post(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n user=self.user.username,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n\nclass KeyboardsAPIDesktopSetDefaultTest(WebTest):\n csrf_checks = False\n\n def setUp(self):\n self.user = UserFactory()\n self.desktop_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.DESKTOP\n )\n self.mobile_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.MOBILE\n )\n self.builtin_desktop_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.DESKTOP\n )\n self.builtin_mobile_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.MOBILE\n )\n\n ##### test get\n def test_get_keyboard_logged_out(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n def test_get_keyboard(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n user=self.user,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n ##### test post\n def test_post_keyboard_logged_out(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_post_keyboard(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n user=self.user,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n ##### test delete\n def test_delete_keyboard_logged_out(self):\n response = self.app.delete(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_delete_keyboard(self):\n response = self.app.delete(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n user=self.user,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n ##### test put\n def test_put_keyboard_desktop_logged_out(self):\n response = self.app.put(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_put_keyboard_desktop_builtin_default(self):\n response = self.app.put(\n reverse(\"keyboards-desktop-set_default\", kwargs={\"pk\": \"builtin\"}),\n user=self.user.username,\n status=200,\n )\n self.assertEqual('{\"status\":\"Default cleared\"}', response.body.decode(\"utf-8\"))\n self.assertEqual(response.status_code, 200)\n\n def test_put_keyboard_desktop_set_user_default(self):\n # retrieve the default keyboard\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the builtin keyboard\n serializer = self.builtin_desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n response = self.app.put(\n reverse(\n \"keyboards-desktop-set_default\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=self.user.username,\n status=200,\n )\n self.assertEqual(response.status_code, 200)\n\n # retrieve the new default keyboard\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the user's keyboard\n serializer = KeyboardSerializer(self.desktop_keyboard)\n self.assertEqual(JSONRenderer().render(serializer.data), response.body)\n\n def test_put_keyboard_desktop_mobile(self):\n response = self.app.put(\n reverse(\n \"keyboards-desktop-set_default\", kwargs={\"pk\": self.mobile_keyboard.id}\n ),\n MOCK_KEYBOARD,\n user=self.user.username,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n\nclass KeyboardsAPIMobileDetailTest(WebTest):\n csrf_checks = False\n\n def setUp(self):\n self.user = UserFactory()\n self.desktop_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.DESKTOP\n )\n self.mobile_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.MOBILE\n )\n self.builtin_desktop_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.DESKTOP\n )\n self.builtin_mobile_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.MOBILE\n )\n\n # test get\n def test_get_keyboard_mobile_builtin(self):\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"builtin\"}), status=200\n )\n self.assertEqual(\n JSONRenderer().render(self.builtin_mobile_keyboard.serialize()),\n response.body,\n )\n\n def test_get_keyboard_mobile_default(self):\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"default\"}), status=200\n )\n self.assertEqual(\n JSONRenderer().render(self.builtin_mobile_keyboard.serialize()),\n response.body,\n )\n\n def test_get_keyboard_mobile_default_logged_in(self):\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n self.assertEqual(\n JSONRenderer().render(self.builtin_mobile_keyboard.serialize()),\n response.body,\n )\n\n def test_get_keyboard_mobile_keyboard(self):\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": self.mobile_keyboard.id}),\n user=self.user,\n status=200,\n )\n serializer = KeyboardSerializer(self.mobile_keyboard)\n self.assertEqual(JSONRenderer().render(serializer.data), response.body)\n\n def test_get_keyboard_mobile_keyboard_desktop(self):\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": self.mobile_keyboard.id}),\n user=self.user,\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n def test_get_keyboard_mobile_keyboard_logged_out(self):\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": self.mobile_keyboard.id}),\n status=404,\n )\n self.assertEqual(response.status_code, 404)\n\n # test put\n # test delete\n\n def test_post_keyboard_desktop_logged_out(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_post_keyboard_mobile_logged_out(self):\n response = self.app.post(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_post_keyboard_desktop_no_post(self):\n response = self.app.post(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n user=self.user.username,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n def test_post_keyboard_mobile_no_post(self):\n response = self.app.post(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n user=self.user.username,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n # test post\n def test_post_keyboard_mobile_logged_out(self):\n response = self.app.post(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n status=403,\n )\n self.assertEqual(response.status_code, 403)\n\n def test_post_keyboard_mobile_no_post(self):\n response = self.app.post(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"builtin\"}),\n MOCK_KEYBOARD,\n user=self.user.username,\n status=405,\n )\n self.assertEqual(response.status_code, 405)\n\n\nclass KeyboardsAPICompositeActions(WebTest):\n csrf_checks = False\n\n def setUp(self):\n self.user = UserFactory()\n self.desktop_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.DESKTOP\n )\n self.mobile_keyboard = KeyboardFactory(\n user=self.user, device_type=Keyboard.MOBILE\n )\n self.builtin_desktop_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.DESKTOP\n )\n self.builtin_mobile_keyboard = BuiltinKeyboardFactory(\n device_type=Keyboard.MOBILE\n )\n\n def test_keyboard_desktop_mobile_set_user_default(self):\n # retrieve the default desktop keyboard\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the builtin keyboard\n serializer = self.builtin_desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n # retrieve the default mobile keyboard\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the builtin mobile keyboard\n serializer = self.builtin_mobile_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n # set the default desktop keyboard...\n response = self.app.put(\n reverse(\n \"keyboards-desktop-set_default\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=self.user.username,\n status=200,\n )\n self.assertEqual(response.status_code, 200)\n\n # ... and the mobile one\n response = self.app.put(\n reverse(\n \"keyboards-mobile-set_default\", kwargs={\"pk\": self.mobile_keyboard.id}\n ),\n user=self.user.username,\n status=200,\n )\n self.assertEqual(response.status_code, 200)\n\n # retrieve the new default desktop keyboard\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the user's keyboard\n serializer = self.desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n # retrieve the new default mobile keyboard\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the user's keyboard\n serializer = self.mobile_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n # delete the desktop keyboard\n response = self.app.delete(\n reverse(\n \"keyboards-desktop-detail\", kwargs={\"pk\": self.desktop_keyboard.id}\n ),\n user=self.user,\n status=200,\n )\n self.assertEqual(response.status_code, 200)\n\n # retrieve the new default desktop keyboard\n response = self.app.get(\n reverse(\"keyboards-desktop-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the builtin keyboard\n serializer = self.builtin_desktop_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n\n # retrieve the new default mobile keyboard\n response = self.app.get(\n reverse(\"keyboards-mobile-detail\", kwargs={\"pk\": \"default\"}),\n user=self.user,\n status=200,\n )\n # assert that it is the user's keyboard\n serializer = self.mobile_keyboard.serialize()\n self.assertEqual(JSONRenderer().render(serializer), response.body)\n" }, { "alpha_fraction": 0.6325017809867859, "alphanum_fraction": 0.63321453332901, "avg_line_length": 32.56459426879883, "blob_id": "7ef31bda2bd68f3eff6980e527f70daa4f8b5448", "content_id": "806858bedd80697669d2c847ac5938d53b9bee63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7015, "license_type": "permissive", "max_line_length": 93, "num_lines": 209, "path": "/cellcounter/cc_kapi/views.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from rest_framework import generics\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated\nfrom rest_framework.exceptions import NotFound, ParseError, NotAuthenticated\nfrom rest_framework import status\n\nfrom .models import Keyboard, DefaultKeyboards\nfrom .serializers import KeyboardSerializer, KeyboardListItemSerializer\nfrom .defaults import BUILTIN_KEYBOARDS\nfrom .defaults import BUILTIN_DESKTOP_KEYBOARD_MAP, BUILTIN_MOBILE_KEYBOARD_MAP\nfrom .marshalls import KeyboardLayoutsMarshall\n\nfrom rest_framework import viewsets\n\nfrom django.urls import reverse\n\nimport itertools\n\n\nclass KeyboardViewSet(viewsets.ViewSet):\n \"\"\"\n A ViewSet for manipulating keyboards.\n \"\"\"\n\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n _device_type = None\n\n def device_type_display(self):\n return Keyboard.DEVICE_TYPES[self._device_type - 1][1]\n\n @property\n def device_type(self):\n return self._device_type\n\n @device_type.setter\n def device_type(self, val):\n self._device_type = val\n\n def _set_user_default_keyboard(self, user, keyboard):\n \"\"\"Helper function to set the user's default keyboard.\"\"\"\n\n # update or create a default on the user's profile as appropriate\n if not hasattr(user, \"defaultkeyboards\"):\n defaultkeyboards = DefaultKeyboards.objects.create(user=user)\n else:\n defaultkeyboards = user.defaultkeyboards\n\n if self.device_type == Keyboard.DESKTOP:\n defaultkeyboards.desktop = keyboard\n elif self.device_type == Keyboard.MOBILE:\n defaultkeyboards.mobile = keyboard\n\n defaultkeyboards.save()\n\n def _clear_user_default_keyboard(self, user):\n if not hasattr(user, \"defaultkeyboards\"):\n return\n defaultkeyboards = user.defaultkeyboards\n\n if self.device_type == Keyboard.DESKTOP:\n defaultkeyboards.desktop = None\n elif self.device_type == Keyboard.MOBILE:\n defaultkeyboards.mobile = None\n\n defaultkeyboards.save()\n\n def list(self, request):\n \"\"\"List the keyboards available for the current user.\n\n Can show all keyboards for the top level API, or those restricted to\n either desktop or mobile.\n \"\"\"\n\n user = None\n if self.request.user.is_authenticated:\n user = self.request.user\n\n if self.device_type:\n keyboards = KeyboardLayoutsMarshall(user).get_all(self.device_type)\n else:\n keyboards = KeyboardLayoutsMarshall(user).get_all()\n\n keyboard_data = []\n for kb in keyboards:\n keyboard_data.append(kb.serialize(many=True))\n\n return Response(keyboard_data)\n\n def create(self, request):\n \"\"\"Create a new keyboard based on request data and set it as the default keyboard.\"\"\"\n\n if not self.request.user.is_authenticated:\n raise NotAuthenticated(\"Method only available to authenticated users\")\n user = self.request.user\n\n serializer = KeyboardSerializer(data=request.data)\n serializer.device_type = self.device_type\n serializer.is_valid(raise_exception=True)\n keyboard = serializer.save(user=user)\n\n self._set_user_default_keyboard(user, keyboard)\n\n return Response(request.data, status=status.HTTP_201_CREATED)\n\n def retrieve(self, request, pk=None):\n \"\"\"Retrieve a specific keyboard.\"\"\"\n\n user = None\n\n if self.request.user.is_authenticated:\n user = self.request.user\n\n keyboard = KeyboardLayoutsMarshall(user).get(pk, self.device_type)\n\n if not keyboard:\n raise NotFound(\n f\"{self.device_type_display()} keyboard with name '{pk}' not found\"\n )\n\n return Response(keyboard.serialize())\n\n def update(self, request, pk=None):\n \"\"\"Update a keyboard based on request data.\"\"\"\n\n if not self.request.user.is_authenticated:\n raise NotAuthenticated(\"Method only available to authenticated users\")\n user = self.request.user\n\n try:\n keyboard = Keyboard.objects.get(\n user=user, id=pk, device_type=self.device_type\n )\n except ValueError:\n raise ParseError(\"Invalid keyboard identifier\")\n except Keyboard.DoesNotExist:\n raise NotFound(\n f\"{self.device_type_display()} keyboard with id '{pk}' not found\"\n )\n\n serializer = KeyboardSerializer(keyboard, data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(request.data)\n\n def destroy(self, request, pk=None):\n \"\"\"Destroy a keyboard based on request data.\"\"\"\n\n if not self.request.user.is_authenticated:\n raise NotAuthenticated(\"Method only available to authenticated users\")\n user = self.request.user\n\n try:\n keyboard = Keyboard.objects.get(\n user=user, id=pk, device_type=self.device_type\n )\n except ValueError:\n raise ParseError(\"Invalid keyboard identifier\")\n except Keyboard.DoesNotExist:\n raise NotFound(\n f\"{self.device_type_display()} keyboard with id '{pk}' not found\"\n )\n\n # check if the keyboard we are about to delete is the default keyboard\n if hasattr(user, \"defaultkeyboards\"):\n if (\n self.device_type == Keyboard.DESKTOP\n and hasattr(user.defaultkeyboards, \"desktop\")\n and user.defaultkeyboards.desktop == keyboard\n ):\n user.defaultkeyboards.desktop = None\n elif (\n self.device_type == Keyboard.MOBILE\n and hasattr(user.defaultkeyboards, \"mobile\")\n and user.defaultkeyboards.mobile == keyboard\n ):\n user.defaultkeyboards.mobile = None\n\n user.defaultkeyboards.save()\n\n keyboard.delete()\n\n return Response(request.data)\n\n def set_default(self, request, pk=None):\n \"\"\"Set the specified keyboard as the user's default.\"\"\"\n\n if not self.request.user.is_authenticated:\n raise NotAuthenticated(\"Method only available to authenticated users\")\n user = self.request.user\n\n if pk == \"builtin\":\n self._clear_user_default_keyboard(user)\n return Response({\"status\": \"Default cleared\"})\n\n try:\n keyboard = Keyboard.objects.get(\n user=user, id=pk, device_type=self.device_type\n )\n except ValueError:\n raise ParseError(\"Invalid keyboard identifier\")\n except Keyboard.DoesNotExist:\n raise NotFound(\n f\"{self.device_type_display()} keyboard with name '{pk}' not found\"\n )\n\n self._set_user_default_keyboard(user, keyboard)\n return Response({\"status\": \"Default set\"})\n" }, { "alpha_fraction": 0.6342504620552063, "alphanum_fraction": 0.6342504620552063, "avg_line_length": 33.557376861572266, "blob_id": "51d2ec9bd53f5b26ad9c9456bbd9bf5613449e5b", "content_id": "b290c0933b0e36055e7efb0c62df19280ea0598f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2108, "license_type": "permissive", "max_line_length": 88, "num_lines": 61, "path": "/cellcounter/urls.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom django.views.generic import TemplateView\n\nfrom cellcounter.main.views import (\n NewCountTemplateView,\n CellImageListView,\n CellTypesListView,\n CellImageDetailView,\n similar_images,\n thumbnail,\n)\n\nadmin.autodiscover()\n\nurlpatterns = [\n url(r\"^$\", NewCountTemplateView.as_view(), name=\"new_count\"),\n url(\n r\"^discover/$\",\n TemplateView.as_view(template_name=\"main/discover.html\"),\n name=\"discover\",\n ),\n url(\n r\"^about/$\", TemplateView.as_view(template_name=\"main/about.html\"), name=\"about\"\n ),\n url(r\"^help/$\", TemplateView.as_view(template_name=\"main/help.html\"), name=\"help\"),\n url(\n r\"^images/celltype/(?P<cell_type>\\w+)/$\",\n CellImageListView.as_view(),\n name=\"images_by_cell_type\",\n ),\n url(\n r\"^images/similar/(?P<cell_image_pk>\\d+)/$\",\n similar_images,\n name=\"images_by_similar_cell\",\n ),\n url(r\"^images/thumbnail/(?P<cell_image_pk>\\d+)/$\", thumbnail, name=\"thumbnail\"),\n url(\n r\"^images/page/(?P<cell_image_pk>\\d+)/$\",\n CellImageDetailView.as_view(),\n name=\"page\",\n ),\n url(r\"^api/cell_types/$\", CellTypesListView.as_view(), name=\"cell_types\"),\n url(r\"^api/stats/\", include(\"cellcounter.statistics.urls\")),\n url(r\"^login/$\", LoginView.as_view(template_name=\"main/login.html\"), name=\"login\"),\n url(r\"^logout/$\", LogoutView.as_view(next_page=\"/\"), name=\"logout\"),\n url(r\"^api/keyboards/\", include(\"cellcounter.cc_kapi.urls\")),\n url(r\"^accounts/\", include(\"cellcounter.accounts.urls\")),\n url(r\"^admin/\", admin.site.urls),\n url(\n r\"^terms$\", TemplateView.as_view(template_name=\"main/terms.html\"), name=\"terms\"\n ),\n url(\n r\"^privacy$\",\n TemplateView.as_view(template_name=\"main/privacy.html\"),\n name=\"privacy\",\n ),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" }, { "alpha_fraction": 0.5382550358772278, "alphanum_fraction": 0.563758373260498, "avg_line_length": 25.60714340209961, "blob_id": "2e1b53851cbf0764af198a90ad0eed2456a900de", "content_id": "1d680d216deb652e602c1ef206b0ddb2307ca9c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "permissive", "max_line_length": 88, "num_lines": 28, "path": "/cellcounter/main/migrations/0003_add_display_order.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.3 on 2019-07-11 15:37\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"main\", \"0002_initial_data\"),\n ]\n\n operations = [\n migrations.AddField(\n model_name=\"celltype\",\n name=\"display_order\",\n field=models.IntegerField(null=True),\n ),\n migrations.AlterField(\n model_name=\"cellimage\",\n name=\"file\",\n field=models.ImageField(upload_to=\"cell_images\"),\n ),\n migrations.AlterField(\n model_name=\"cellimage\",\n name=\"thumbnail\",\n field=models.ImageField(blank=True, null=True, upload_to=\"cell_thumbnails\"),\n ),\n ]\n" }, { "alpha_fraction": 0.8144171833992004, "alphanum_fraction": 0.8144171833992004, "avg_line_length": 20.733333587646484, "blob_id": "96cfcebaf822f6aa20a329045a7434a99d13d244", "content_id": "b4b464dc10e4da2a57ba4382d52d0b3c1aae9d48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "permissive", "max_line_length": 86, "num_lines": 30, "path": "/cellcounter/main/admin.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import CellImage, CellType, SimilarLookingGroup, License, CopyrightHolder\n\n\nclass CellImageAdmin(admin.ModelAdmin):\n pass\n\n\nclass SimilarLookingGroupAdmin(admin.ModelAdmin):\n pass\n\n\nclass CellTypeAdmin(admin.ModelAdmin):\n pass\n\n\nclass LicenseAdmin(admin.ModelAdmin):\n pass\n\n\nclass CopyrightHolderAdmin(admin.ModelAdmin):\n pass\n\n\nadmin.site.register(CellImage, CellImageAdmin)\nadmin.site.register(CellType, CellTypeAdmin)\nadmin.site.register(SimilarLookingGroup, SimilarLookingGroupAdmin)\nadmin.site.register(License, LicenseAdmin)\nadmin.site.register(CopyrightHolder, CopyrightHolderAdmin)\n" }, { "alpha_fraction": 0.7532133460044861, "alphanum_fraction": 0.7583547830581665, "avg_line_length": 37.900001525878906, "blob_id": "4f62b1856c52b8481de4bef37d76335695f90f23", "content_id": "58f042b0daf8c34cc8ecd03c45e3080f305c5b8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "permissive", "max_line_length": 85, "num_lines": 10, "path": "/cellcounter/statistics/models.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass CountInstance(models.Model):\n timestamp = models.DateTimeField(auto_now_add=True)\n session_id = models.CharField(max_length=32)\n ip_address = models.GenericIPAddressField()\n user = models.ForeignKey(User, null=True, default=None, on_delete=models.CASCADE)\n count_total = models.IntegerField()\n" }, { "alpha_fraction": 0.6591951251029968, "alphanum_fraction": 0.6614875197410583, "avg_line_length": 32.69956970214844, "blob_id": "80a8c666d177b3b06dffd7b7088d7403d0c62c1a", "content_id": "2dd4f3476f93a23d6b380fbbb0d560737c2b1bc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7852, "license_type": "permissive", "max_line_length": 100, "num_lines": 233, "path": "/cellcounter/accounts/views.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from braces.views import LoginRequiredMixin\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.forms import PasswordChangeForm\nfrom django.contrib.auth.forms import SetPasswordForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.core.exceptions import PermissionDenied\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.utils.decorators import method_decorator\nfrom django.utils.http import urlsafe_base64_decode\nfrom django.utils.safestring import mark_safe\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.views.generic import FormView, UpdateView, DetailView, DeleteView\nfrom ratelimit.exceptions import Ratelimited\nfrom ratelimit.mixins import RatelimitMixin\nfrom ratelimit.utils import is_ratelimited\n\nfrom ..cc_kapi.marshalls import KeyboardLayoutsMarshall\n\nfrom .forms import EmailUserCreationForm, PasswordResetForm\n\n\nclass RateLimitedFormView(FormView):\n ratelimit_key = \"ip\"\n ratelimit_block = True\n ratelimit_rate = \"1/h\"\n ratelimit_group = None\n\n def dispatch(self, *args, **kwargs):\n ratelimited = is_ratelimited(\n request=self.request,\n group=self.ratelimit_group,\n key=self.ratelimit_key,\n rate=self.ratelimit_rate,\n increment=False,\n )\n if ratelimited and self.ratelimit_block:\n raise Ratelimited()\n return super(RateLimitedFormView, self).dispatch(*args, **kwargs)\n\n\nclass RegistrationView(RateLimitedFormView):\n template_name = \"accounts/register.html\"\n form_class = EmailUserCreationForm\n ratelimit_group = \"registration\"\n\n def form_valid(self, form):\n user = form.save()\n messages.success(\n self.request,\n mark_safe(\n \"Successfully registered, you are now logged in! <a href='%s'>View your profile</a>\"\n % reverse(\"user-detail\", kwargs={\"pk\": user.id})\n ),\n )\n user = authenticate(\n username=form.cleaned_data[\"username\"],\n password=form.cleaned_data[\"password1\"],\n )\n login(self.request, user)\n is_ratelimited(\n request=self.request,\n group=self.ratelimit_group,\n key=self.ratelimit_key,\n rate=self.ratelimit_rate,\n increment=True,\n )\n return super(RegistrationView, self).form_valid(form)\n\n def get_success_url(self):\n return reverse(\"new_count\")\n\n\nclass PasswordChangeView(LoginRequiredMixin, FormView):\n template_name = \"accounts/password_change.html\"\n form_class = PasswordChangeForm\n\n def get_form_kwargs(self):\n kwargs = super(PasswordChangeView, self).get_form_kwargs()\n kwargs[\"user\"] = self.request.user\n return kwargs\n\n def form_valid(self, form):\n form.save()\n messages.success(self.request, \"Password changed successfully\")\n return HttpResponseRedirect(reverse(\"new_count\"))\n\n\nclass UserDetailView(LoginRequiredMixin, DetailView):\n model = User\n context_object_name = \"user_detail\"\n template_name = \"accounts/user_detail.html\"\n\n def get_object(self, queryset=None):\n if self.request.user.id == int(self.kwargs[\"pk\"]):\n return super(UserDetailView, self).get_object()\n else:\n raise PermissionDenied\n\n def get_context_data(self, **kwargs):\n context = super(UserDetailView, self).get_context_data(**kwargs)\n\n keyboards = KeyboardLayoutsMarshall(self.request.user).get_all()\n\n # sort keyboards by device_type\n keyboards.sort(key=lambda e: e.device_type)\n\n # serialize the keyboards\n keyboard_data = []\n for kb in keyboards:\n keyboard_data.append(kb.serialize(many=True))\n\n context[\"keyboards\"] = keyboard_data\n\n return context\n\n\nclass UserDeleteView(LoginRequiredMixin, DeleteView):\n model = User\n context_object_name = \"user_object\"\n template_name = \"accounts/user_check_delete.html\"\n\n def get_object(self, queryset=None):\n if self.request.user.id == int(self.kwargs[\"pk\"]):\n return super(UserDeleteView, self).get_object()\n else:\n raise PermissionDenied\n\n def get_success_url(self):\n messages.success(self.request, \"User account deleted\")\n return reverse(\"new_count\")\n\n\nclass UserUpdateView(LoginRequiredMixin, UpdateView):\n model = User\n fields = [\n \"first_name\",\n \"last_name\",\n \"email\",\n ]\n template_name = \"accounts/user_update.html\"\n\n def get_object(self, queryset=None):\n if self.request.user.id == int(self.kwargs[\"pk\"]):\n return super(UserUpdateView, self).get_object()\n else:\n raise PermissionDenied\n\n def get_success_url(self):\n messages.success(self.request, \"User details updated\")\n return reverse(\"user-detail\", kwargs={\"pk\": self.kwargs[\"pk\"]})\n\n\nclass PasswordResetView(RatelimitMixin, FormView):\n template_name = \"accounts/reset_form.html\"\n form_class = PasswordResetForm\n ratelimit_rate = \"5/h\"\n ratelimit_group = \"pwdreset\"\n ratelimit_key = \"ip\"\n ratelimit_block = True\n\n def form_valid(self, form):\n form.save(request=self.request)\n messages.success(self.request, \"Reset email sent\")\n return super(PasswordResetView, self).form_valid(form)\n\n def form_invalid(self, form):\n \"\"\"Don't expose form errors to the user\"\"\"\n return HttpResponseRedirect(self.get_success_url())\n\n def get_success_url(self):\n return reverse(\"new_count\")\n\n\nclass PasswordResetConfirmView(FormView):\n template_name = \"accounts/reset_confirm.html\"\n form_class = SetPasswordForm\n\n @method_decorator(sensitive_post_parameters())\n def dispatch(self, request, *args, **kwargs):\n return super(PasswordResetConfirmView, self).dispatch(request, *args, **kwargs)\n\n @staticmethod\n def valid_user(uidb64):\n try:\n uid = urlsafe_base64_decode(uidb64)\n user = User.objects.get(pk=uid)\n except (TypeError, ValueError, OverflowError, User.DoesNotExist):\n return None\n return user\n\n @staticmethod\n def valid_token(user, token):\n if user is not None:\n return default_token_generator.check_token(user, token)\n else:\n return False\n\n def _valid_inputs(self, uidb64, token):\n self.user_object = self.valid_user(uidb64)\n return self.valid_token(self.user_object, token)\n\n def get(self, request, *args, **kwargs):\n if self._valid_inputs(self.kwargs[\"uidb64\"], self.kwargs[\"token\"]):\n form = self.get_form(self.get_form_class())\n return self.render_to_response(\n self.get_context_data(form=form, validlink=True)\n )\n else:\n return self.render_to_response(self.get_context_data(validlink=False))\n\n def post(self, request, *args, **kwargs):\n if self._valid_inputs(self.kwargs[\"uidb64\"], self.kwargs[\"token\"]):\n return super(PasswordResetConfirmView, self).post(request, *args, **kwargs)\n else:\n return self.render_to_response(self.get_context_data(validlink=False))\n\n def get_form_kwargs(self):\n kwargs = super(PasswordResetConfirmView, self).get_form_kwargs()\n kwargs[\"user\"] = self.user_object\n return kwargs\n\n def form_valid(self, form):\n form.save()\n messages.success(self.request, \"Password reset successfully\")\n return HttpResponseRedirect(reverse(\"new_count\"))\n\n\ndef rate_limited(request, exception):\n messages.error(request, \"You have been rate limited\")\n return HttpResponseRedirect(reverse(\"new_count\"))\n" }, { "alpha_fraction": 0.581589937210083, "alphanum_fraction": 0.6087865829467773, "avg_line_length": 44.52381134033203, "blob_id": "99e56124a5cdc8336233e7568c422c7878c4c9dd", "content_id": "7bde35f25b805433089a31b9ca1139b4e3f0044b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 956, "license_type": "permissive", "max_line_length": 113, "num_lines": 21, "path": "/cellcounter/accounts/urls.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom cellcounter.accounts import views\n\nurlpatterns = [\n url(\"^new/$\", views.RegistrationView.as_view(), name=\"register\"),\n url(\"^(?P<pk>[0-9]+)/$\", views.UserDetailView.as_view(), name=\"user-detail\"),\n url(\"^(?P<pk>[0-9]+)/delete/$\", views.UserDeleteView.as_view(), name=\"user-delete\"),\n url(\"^(?P<pk>[0-9]+)/edit/$\", views.UserUpdateView.as_view(), name=\"user-update\"),\n url(\"^password/reset/$\", views.PasswordResetView.as_view(), name=\"password-reset\"),\n # url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n # url('^password/reset/confirm/<uidb64>/<token>/',\n url(\n r\"^password/reset/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$\",\n views.PasswordResetConfirmView.as_view(),\n name=\"password-reset-confirm\",\n ),\n url(\n \"^password/change/$\", views.PasswordChangeView.as_view(), name=\"change-password\"\n ),\n]\n" }, { "alpha_fraction": 0.6626605987548828, "alphanum_fraction": 0.6639038324356079, "avg_line_length": 24.94623565673828, "blob_id": "2ee3ea4e17e34cee270cedcbe802b92ab81bbba1", "content_id": "0b6a65bec3bd97cd785957a40e31be99e34a2c87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2413, "license_type": "permissive", "max_line_length": 77, "num_lines": 93, "path": "/cellcounter/cc_kapi/factories.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "import string\nfrom django.contrib.auth.models import User, AnonymousUser\n\nfrom cellcounter.main.models import CellType\nfrom .models import Keyboard, KeyMap, DefaultKeyboards\nfrom .defaults import (\n BUILTIN_KEYBOARDS,\n BUILTIN_DESKTOP_KEYBOARD_MAP,\n BUILTIN_MOBILE_KEYBOARD_MAP,\n)\nfrom .marshalls import BuiltinKeyboardModel, UserKeyboardModel\n\nimport factory\n\n\nclass UserFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = User\n\n username = factory.Sequence(lambda n: \"test%s\" % n)\n first_name = factory.Sequence(lambda n: \"test%s\" % n)\n last_name = factory.Sequence(lambda n: \"test%s\" % n)\n email = factory.Sequence(lambda n: \"test%[email protected]\" % n)\n password = factory.PostGenerationMethodCall(\"set_password\", \"test\")\n\n is_staff = False\n is_active = True\n is_superuser = False\n\n\nclass DefaultKeyboardsFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = DefaultKeyboards\n\n\nclass DefaultKeyboardFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Keyboard\n strategy = factory.BUILD_STRATEGY\n\n class Params:\n mappings = None\n\n id = 0\n user = None\n\n\nclass DefaultKeyMapFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = KeyMap\n strategy = factory.BUILD_STRATEGY\n\n key = \"a\"\n\n\nclass KeyboardFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = UserKeyboardModel\n\n user = factory.SubFactory(UserFactory)\n label = \"Test\"\n\n @factory.post_generation\n def add_maps(self, create, extracted, **kwargs):\n if not create:\n return\n if not extracted:\n return\n i = 0\n for cell in CellType.objects.all():\n mapping, created = models.KeyMap.objects.get_or_create(\n cellid=cell, key=string.ascii_lowercase[i]\n )\n self.mappings.add(mapping)\n i += 1\n\n self.save()\n\n\nclass KeyMapFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = KeyMap\n\n key = \"a\"\n\n\nclass BuiltinKeyboardFactory:\n def __new__(cls, *args, **kwargs):\n device_type = kwargs.pop(\"device_type\")\n if device_type == Keyboard.DESKTOP:\n return BuiltinKeyboardModel(BUILTIN_DESKTOP_KEYBOARD_MAP)\n elif device_type == Keyboard.MOBILE:\n return BuiltinKeyboardModel(BUILTIN_MOBILE_KEYBOARD_MAP)\n" }, { "alpha_fraction": 0.6708229184150696, "alphanum_fraction": 0.6708229184150696, "avg_line_length": 29.846153259277344, "blob_id": "d3f6b854d6cbc872a57b4a353379205b11fe0201", "content_id": "a0da91dbe9fb2cc60052a8f15ad5a545efc1ac02", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 802, "license_type": "permissive", "max_line_length": 72, "num_lines": 26, "path": "/cellcounter/accounts/test_utils.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom django.test.client import RequestFactory\n\nfrom cellcounter.cc_kapi.factories import UserFactory\nfrom .forms import PasswordResetForm\nfrom .utils import read_signup_email\n\n\nclass Email:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass TestReadEmailUtil(TestCase):\n def test_matching_email(self):\n user = UserFactory()\n request = RequestFactory().post(\"/\")\n url = PasswordResetForm().get_context_data(request, user)[\"url\"]\n msg = Email(body=url)\n email_url, path = read_signup_email(msg)\n self.assertEqual(email_url, url)\n\n def test_nonmatching_email(self):\n msg = Email(body=\"\")\n email_url, path = read_signup_email(msg)\n self.assertTrue(not any([email_url, path]))\n" }, { "alpha_fraction": 0.5484662652015686, "alphanum_fraction": 0.5717791318893433, "avg_line_length": 21.027027130126953, "blob_id": "c3e0260369a303b80448d4e13a16bd14063e33c6", "content_id": "08219a33881029fedab9105e9abb8fc043146071", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "permissive", "max_line_length": 74, "num_lines": 37, "path": "/cellcounter/main/migrations/0004_display_order_data.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.3 on 2019-07-11 15:39\n\nfrom django.db import migrations\n\n\ndef set_display_order(apps, schema_editor):\n cell_order = [\n \"blasts\",\n \"promyelocytes\",\n \"myelocytes\",\n \"meta\",\n \"neutrophils\",\n \"monocytes\",\n \"basophils\",\n \"eosinophils\",\n \"lymphocytes\",\n \"plasma_cells\",\n \"erythroid\",\n \"other\",\n \"lymphoblasts\",\n ]\n\n CellType = apps.get_model(\"main\", \"CellType\")\n for cell_type in CellType.objects.all():\n cell_type.display_order = cell_order.index(cell_type.machine_name)\n cell_type.save()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"main\", \"0003_add_display_order\"),\n ]\n\n operations = [\n migrations.RunPython(set_display_order),\n ]\n" }, { "alpha_fraction": 0.6867007613182068, "alphanum_fraction": 0.6867007613182068, "avg_line_length": 34.54545593261719, "blob_id": "cff3009a482c74f3a2c2e612a8e94f6f52ef447d", "content_id": "5cce3bacebfc920645c103f432ef31a20eb43849", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 782, "license_type": "permissive", "max_line_length": 82, "num_lines": 22, "path": "/cellcounter/main/context_processors.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from django.conf import settings\n\n\ndef plausible_analytics(request):\n plausible_analytics_enabled = False\n plausible_analytics_server = \"\"\n plausible_analytics_domain_key = \"\"\n if (\n hasattr(settings, \"PLAUSIBLE_ANALYTICS_CONFIG\")\n and settings.PLAUSIBLE_ANALYTICS_CONFIG[\"enabled\"]\n ):\n plausible_analytics_enabled = True\n plausible_analytics_server = settings.PLAUSIBLE_ANALYTICS_CONFIG[\"server\"]\n plausible_analytics_domain_key = settings.PLAUSIBLE_ANALYTICS_CONFIG[\n \"domainkey\"\n ]\n\n return {\n \"PLAUSIBLE_ANALYTICS_ENABLED\": plausible_analytics_enabled,\n \"PLAUSIBLE_ANALYTICS_SERVER\": plausible_analytics_server,\n \"PLAUSIBLE_ANALYTICS_DOMAIN_KEY\": plausible_analytics_domain_key,\n }\n" }, { "alpha_fraction": 0.6638146638870239, "alphanum_fraction": 0.6759182214736938, "avg_line_length": 38.60330581665039, "blob_id": "6c66df744135fbe24d105f09b7cf7d06a2ef1321", "content_id": "ebd290884ace92524cb2686baefcac026d074f23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4792, "license_type": "permissive", "max_line_length": 83, "num_lines": 121, "path": "/cellcounter/statistics/tests.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "from importlib import import_module\n\nfrom django.conf import settings\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\nfrom django.core.cache import cache\nfrom django.test import TestCase, RequestFactory\nfrom django.shortcuts import render\n\nfrom rest_framework import status\nfrom rest_framework.test import APIRequestFactory, APITestCase, force_authenticate\n\nfrom .views import ListCreateCountInstanceAPI\nfrom .middleware import StatsSessionMiddleware\nfrom .models import CountInstance\n\nfactory = APIRequestFactory()\nview = ListCreateCountInstanceAPI.as_view()\n\n\nclass TestStatsMiddleware(TestCase):\n def setUp(self):\n self.request = RequestFactory().get(reverse(\"create-count-instance\"))\n self.request.session = {}\n self.request.COOKIES = {}\n self.mw = StatsSessionMiddleware()\n\n def test_empty_session(self):\n self.mw.process_request(self.request)\n self.assertIsNotNone(self.request.session.session_key)\n\n def test_no_key_session(self):\n self.mw.process_request(self.request)\n self.assertIsNotNone(self.request.session.session_key)\n\n def test_key_session(self):\n \"\"\"Don't create new session id when one is already set\"\"\"\n session_engine = import_module(settings.SESSION_ENGINE)\n SessionStore = session_engine.SessionStore\n session_id = SessionStore(None)\n session_id.save()\n self.request.COOKIES[\"sessionid\"] = session_id.session_key\n self.mw.process_request(self.request)\n self.assertEqual(session_id.session_key, self.request.session.session_key)\n\n\nclass TestCountInstanceAPI(APITestCase):\n def setUp(self):\n self.user = User.objects.create_user(\"basic\", \"[email protected]\", \"basic\")\n self.staff_user = User.objects.create_superuser(\n \"permitted\", \"[email protected]\", \"password\"\n )\n self.url = reverse(\"create-count-instance\")\n self.data = {\"count_total\": 100}\n cache.clear()\n\n def test_create_permissions(self):\n request = factory.post(\"/\", {\"count_total\": 100}, format=\"json\")\n StatsSessionMiddleware().process_request(request)\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n request = factory.post(\"/\", {\"count_total\": 100}, format=\"json\")\n StatsSessionMiddleware().process_request(request)\n force_authenticate(request, user=self.staff_user)\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n request = factory.post(\"/\", {\"count_total\": 100}, format=\"json\")\n StatsSessionMiddleware().process_request(request)\n force_authenticate(request, user=self.user)\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_safe_permissions(self):\n request = factory.get(\"/\")\n force_authenticate(request, user=self.staff_user)\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n request = factory.head(\"/\")\n force_authenticate(request, user=self.staff_user)\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n request = factory.options(\"/\")\n force_authenticate(request, user=self.staff_user)\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_anonymous_permissions(self):\n request = factory.get(\"/\")\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n request = factory.head(\"/\")\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n request = factory.options(\"/\")\n response = view(request)\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n def test_authenticated_get(self):\n instance = CountInstance.objects.create(\n user=self.user, session_id=\"a\", count_total=100, ip_address=\"127.0.0.1\"\n )\n request = factory.get(\"/\")\n force_authenticate(request, user=self.staff_user)\n response = view(request)\n response.render()\n self.assertEqual(response.data[0][\"session_id\"], instance.session_id)\n self.assertEqual(response.data[0][\"count_total\"], instance.count_total)\n self.assertEqual(response.data[0][\"ip_address\"], instance.ip_address)\n\n def test_ratelimit_exceeded(self):\n request = factory.post(\"/\", {\"count_total\": 100}, format=\"json\")\n StatsSessionMiddleware().process_request(request)\n for dummy in range(2):\n response = view(request)\n self.assertEqual(429, response.status_code)\n" }, { "alpha_fraction": 0.4250493049621582, "alphanum_fraction": 0.4299802780151367, "avg_line_length": 33.25675582885742, "blob_id": "9c9ba65b02d9aa1a07cf5f22305059b37ad441f1", "content_id": "c060619fcc912367411d3a384f6b0ac263f85baf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5070, "license_type": "permissive", "max_line_length": 88, "num_lines": 148, "path": "/cellcounter/main/migrations/0001_initial.py", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport colorful.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"CellImage\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\"title\", models.CharField(max_length=100)),\n (\"description\", models.TextField()),\n (\"file\", models.ImageField(upload_to=b\"cell_images\")),\n (\n \"thumbnail\",\n models.ImageField(\n null=True, upload_to=b\"cell_thumbnails\", blank=True\n ),\n ),\n (\"thumbnail_left\", models.IntegerField()),\n (\"thumbnail_top\", models.IntegerField()),\n (\"thumbnail_width\", models.IntegerField()),\n ],\n options={},\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name=\"CellType\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\"readable_name\", models.CharField(max_length=50)),\n (\"machine_name\", models.CharField(unique=True, max_length=50)),\n (\"abbr_name\", models.CharField(unique=True, max_length=10)),\n (\"comment\", models.TextField(blank=True)),\n (\"visualisation_colour\", colorful.fields.RGBColorField(blank=True)),\n ],\n options={},\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name=\"CopyrightHolder\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\"name\", models.CharField(max_length=300)),\n (\"link_title\", models.CharField(max_length=300, null=True, blank=True)),\n (\"link_url\", models.CharField(max_length=300, null=True, blank=True)),\n (\"user\", models.ManyToManyField(to=settings.AUTH_USER_MODEL)),\n ],\n options={},\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name=\"License\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\"title\", models.CharField(max_length=100)),\n (\"details\", models.TextField()),\n ],\n options={},\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name=\"SimilarLookingGroup\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\"name\", models.CharField(max_length=100)),\n (\"cell_image\", models.ManyToManyField(to=\"main.CellImage\")),\n ],\n options={},\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name=\"cellimage\",\n name=\"celltype\",\n field=models.ForeignKey(to=\"main.CellType\", on_delete=models.CASCADE),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name=\"cellimage\",\n name=\"copyright\",\n field=models.ForeignKey(\n to=\"main.CopyrightHolder\", on_delete=models.CASCADE\n ),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name=\"cellimage\",\n name=\"license\",\n field=models.ForeignKey(to=\"main.License\", on_delete=models.CASCADE),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name=\"cellimage\",\n name=\"uploader\",\n field=models.ForeignKey(\n to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n ),\n preserve_default=True,\n ),\n ]\n" }, { "alpha_fraction": 0.7258651852607727, "alphanum_fraction": 0.7317850589752197, "avg_line_length": 25.768293380737305, "blob_id": "92da7e3426f45697e02958e54f99fdb7373c5e06", "content_id": "1582a129682de6cc9471eae00b90c64a77c2f630", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2196, "license_type": "permissive", "max_line_length": 331, "num_lines": 82, "path": "/README.md", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "# CellCounter\n\n[![CircleCI](https://circleci.com/gh/cellcounter/cellcounter/tree/master.svg?style=shield)](https://circleci.com/gh/cellcounter/cellcounter/tree/master) [![Coverage Status](https://coveralls.io/repos/cellcounter/cellcounter/badge.svg?branch=master&service=github)](https://coveralls.io/github/cellcounter/cellcounter?branch=master)\n\nCellcounter Django app to count cells for haematological blood film analysis. Cellcounter is deployed at [cellcountr.com](http://www.cellcountr.com).\n\n\n## Running Locally\n\nClone the repository:\n\n git clone ...\n\nCreate a virtual environment:\n\n virtualenv -p python3 .env\n source .env/bin/activate\n pip install --upgrade pip\n pip install -r requirements.txt\n\n(if you don't have `virtualenv`, then `sudo pip install virtualenv`)\n(if you don't have `pip`, then `sudo easy_install pip`)\n\nUpdate your database:\n\n python manage.py migrate\n\nRun the Django webserver locally, setting the DEBUG environment variable:\n\n export DEBUG=True\n export ALLOWED_HOSTS=\"127.0.0.1\"\n python manage.py runserver\n\n\n## Testing\n\nTo run the test suite locally, you also need the test requirements in your virtualenv:\n\n pip install -r test-requirements.txt\n\n export TEST=True\n python manage.py test\n\nTo install npm from source for JavaScript testing:\n\n curl https://nodejs.org/dist/node-latest.tar.gz | tar xvz\n cd node-v*\n ./configure --prefix=$VIRTUAL_ENV\n make install\n\n npm ci\n \n export DEBUG=True; export ALLOWED_HOSTS=\"127.0.0.1\"\n ./test_integration\n\nTo run the test suite via docker:\n\n docker build --target test -t cellcountr/cellcountr_test:latest .\n\n docker run cellcountr/cellcountr_test:latest python manage.py test\n\n\n## Deployment\n\nTo create the docker volume to store the media files:\n\n sudo mkdir -p /var/www/mediafiles\n docker volume create --driver local --opt type=none --opt device=/var/www/mediafiles --opt o=bind media_volume\n\nTo build and run the docker image:\n\n cp env.dev.example env.dev\n edit env.dev\n docker compose build\n\n docker compose up -d\n\n docker compose exec web python manage.py migrate --no-input\n\nTo stop the docker image:\n\n docker compose down -v\n\n" }, { "alpha_fraction": 0.582524299621582, "alphanum_fraction": 0.7411003112792969, "avg_line_length": 19.600000381469727, "blob_id": "24c9f61ef11d11472d14121a67d4ea39fb9e0ff9", "content_id": "afd93d6429166b93af59ea4e28d64e607dd7251b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 309, "license_type": "permissive", "max_line_length": 30, "num_lines": 15, "path": "/requirements.txt", "repo_name": "cellcounter/cellcounter", "src_encoding": "UTF-8", "text": "Django==3.2.14\nPillow==9.0.1\ndj-database-url==0.5.0\ndjango-colorful==1.3\ndjango-braces==1.15.0\ndjangorestframework==3.11.2\ndjangorestframework-xml==2.0.0\ndjango-pylibmc==0.6.1\ndjango-ratelimit==1.0.1\npylibmc==1.6.0\npytz==2018.9\npydictobject==1.5\npsycopg2-binary==2.9.3\ndjango-compressor==4.0\ngunicorn==20.1.0\n" } ]
47
Code-Institute-Submissions/Python_Project
https://github.com/Code-Institute-Submissions/Python_Project
4652374a95d7bd72d598d0fadfef31f8cc87c58a
a4debe742293b32dadf209b78aba3522db9e5655
485fca7b7f0eab94bab629aaedb78ce01c30cad9
refs/heads/main
2023-09-03T08:51:02.309408
2021-11-06T14:27:34
2021-11-06T14:27:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7503109574317932, "alphanum_fraction": 0.7549751400947571, "avg_line_length": 50.015872955322266, "blob_id": "65b431dbe1eb4d40f1367dda2b62fc2dd3aaa153", "content_id": "1035c3f92bafb49ef54e5a66bfa815ae266c126f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3216, "license_type": "no_license", "max_line_length": 269, "num_lines": 63, "path": "/README.md", "repo_name": "Code-Institute-Submissions/Python_Project", "src_encoding": "UTF-8", "text": "# Battleship--Game\nThis battleship game is only played by one user. \nThe user wins by eliminating 5 of the computer's ships.\nThe computer will try and do the same. the computer generates a random number to try and hit one of your ships.\n\nThis is a picture of the Heroku website where you will be playing the game.\n![Heroku Game page](Game.PNG)\n# How To play\n* To start the game, the user enters their name.\n + Two boards are randomly generated. \n + The board with the user's name is the user's board, The board with Computer written at the top of the board is the computer's board. \n + You will select a row and column (the computer will do the same), row and column are numbers between 0 and 9. Row and column are used to get the coordinates. \n + Once either you or the computer hit the opponent's 5 ships, a new game will start and you will be congratulated. \n\n# Features\n* What features does my game have?\n + Random board generator that generates the player and computer ships randomly.\n + the computer ships are hidden from the user.\n \n![random generator](random-generator.PNG)\n* Inputs\n + Get's user input\n + Play against the computer\n\n![Computer and user inputs](inputs.PNG)\n* Input validation and error checking\n + You cannot enter a row or column number that's lower than 0 or that's higher than 9.\n + You cannot enter the same guess twice. \n\n![input Validations](validation.PNG)\n\n# Data Model\nI decided to use a class model to generate the player and computer board and add the other methods to those boards.\n\nThe set-up board class stores many variables but the most important are num_ships, player_name, computer_board, computer_board2, and board. They were all used to create and modify the player and computer boards. \n\nThe computer_board2 is used for displaying the computer's board to the user, the other computer_board is used as the backend where the game is actually happening. \n\n# Testing\nI have tested this project myself by:\n + Running this code in PEP8 and confirmed their was no major errors, Theirs only errors for lines being too long, i tried fixing them but couldn't do it, Theirs warnings for trailing white space too.\n + Giving the terminal invalid corordinates, giving both row and column higher than 9 numbers and letters.\n + I have tested my app in the Heroku website too.\n\n![Errors in PEP8](errors.PNG) \n## Bugs\n* Solved Bugs\n + Their was a bug in the make_guess function where the computer will go into a infinit loop whenever it picks the same number twice, i fixed this issue by creating another random number in the else statement so that the computer will always pick a different number. \n\n* Remaining bugs\n + No remaining bugs\n# Deployment\nThis project was deployed to Heroku with the help of code insitute's deployment video.\nHeroku Link - https://battleship--game.herokuapp.com/\n* steps for deployment\n + Create a new Heroku app.\n + set Key to PORT and value to 8000 in the Config Vars in settings page.\n + set the buildpacks to python and Node.js in that order in the settings page.\n + press manual deploy in the deploy page in heroku.\n# Credits\n + Mentors help and advice\n + Tutors help\n + Code Insitute deployment video.\n\n\n" }, { "alpha_fraction": 0.4979938566684723, "alphanum_fraction": 0.5119187831878662, "avg_line_length": 38.4139518737793, "blob_id": "12ddc7eba7e580f32557ab3a9ee3500c72529583", "content_id": "c80773fa01871aee6be0ee8ba65c119bd1e59831", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8474, "license_type": "no_license", "max_line_length": 110, "num_lines": 215, "path": "/run.py", "repo_name": "Code-Institute-Submissions/Python_Project", "src_encoding": "UTF-8", "text": "import random\n\n\nclass Setup_Board:\n \"\"\"\n This setup_Board class sets up all the other methods so that they can all be connected and used together.\n \"\"\"\n\n def __init__(self, num_ships, ship_hit, ship, type, guess, water,\n computer_board, board, player_name, row, column, alpabet, numbers, computer_board2):\n self.num_ships = 5\n self.ship_hit = 'X'\n self.type = type\n self.ship = 'O'\n self.guess = []\n self.water = ['-']\n self.computer_board = []\n self.board = []\n self.player_name = player_name\n self.row = 9\n self.column = 9\n self.computer_board2 = []\n\n def validate_corordinates(self, player_name, alpabet, numbers):\n \"\"\"\n Vaildates the corordinates that the Player Choose, it also updates the render_computer_board and \n the render_computer_board2() functions once the corordinates have been set. \n \"\"\"\n self.num_ships = 5\n while self.num_ships > 0:\n\n self.alpabet = None\n self.alpabet = input('Enter a Row: ')\n if self.alpabet.isdigit() and int(self.alpabet) >= 0 and int(self.alpabet) <= 9:\n self.alpabet = int(self.alpabet)\n self.numbers = None\n self.numbers = input('Enter a Column: ')\n if self.numbers.isdigit() and int(self.numbers) >= 0 and int(self.numbers) <= 9:\n self.numbers = int(self.numbers)\n if self.computer_board[self.alpabet][self.numbers] == 'O':\n print('You Hit')\n self.num_ships -= 1\n self.computer_board[self.alpabet][self.numbers] = 'X'\n self.computer_board2[self.alpabet][self.numbers] = 'X'\n self.render_computer_board2(alpabet, numbers)\n self.make_guess(player_name)\n elif self.computer_board2[self.alpabet][self.numbers] == 'X':\n print('Already picked this Corordinate, Please Pick again.')\n else:\n if self.computer_board2[self.alpabet][self.numbers] == '-':\n print('You Missed')\n self.computer_board2[self.alpabet][self.numbers] = 'X'\n self.render_computer_board2(alpabet, numbers)\n self.make_guess(player_name)\n\n else:\n print('row and colum must be between 0 and 9, they must be an int')\n else:\n print('row and colum must be between 0 and 9, they must be an int')\n\n if self.num_ships == 0:\n print('Player Has Won, starting new game')\n New_game()\n\n def populate_boards(self, computer_board, board):\n \"\"\"\n Populates the two boards, render_computer_board and reder_player_board. \n \"\"\"\n del computer_board\n del board\n\n for board in [self.computer_board, self.board]:\n counter = 1\n while counter <= 5:\n random_number_x = random.randrange(10)\n random_number_y = random.randrange(10)\n\n if board[random_number_x][random_number_y] == 'O':\n continue\n else:\n board[random_number_x][random_number_y] = 'O'\n counter += 1\n\n def make_guess(self, player_name):\n \"\"\"\n computer will auto guess Corordinates, and this will update the render_player_board() function.\n \"\"\"\n self.num_ships = 5\n computer_guess_x = random.randrange(10)\n computer_guess_y = random.randrange(10)\n while self.num_ships > 0:\n print(f'computer row: {computer_guess_x}')\n print(f'computer column: {computer_guess_y}')\n if self.board[computer_guess_x][computer_guess_y] == 'O':\n print('Computer has Hit one of your ships')\n self.board[computer_guess_x][computer_guess_y] = 'X'\n self.num_ships -= 1\n self.render_Player_board('Player', player_name)\n break\n\n elif self.board[computer_guess_x][computer_guess_y] == '-':\n print('Computer has Missed')\n self.board[computer_guess_x][computer_guess_y] = 'X'\n self.render_Player_board('Player', player_name)\n break\n\n else:\n computer_guess_x = random.randrange(10)\n computer_guess_y = random.randrange(10)\n\n if self.num_ships == 0:\n print('Computer has Won, starting new game')\n New_game()\n\n def render_Player_board(self, type, player_name):\n \"\"\"\n Creates the game board that the Computer will guess in.\n \"\"\"\n print('\\n\\n\\n')\n print(f' {self.player_name}')\n print(' 0 1 2 3 4 5 6 7 8 9')\n print(' +---------------------+')\n for self.row in range(10):\n self.board.append(self.water * 10)\n\n letters = 0\n for self.row in range(10):\n print(chr(letters + 65), end=' | ')\n for self.column in range(len(self.board[letters])):\n print(self.board[letters][self.column], end=' ')\n print('| ')\n letters += 1\n print(' +---------------------+ \\n\\n\\n')\n\n def render_computer_board(self, type):\n \"\"\"\n renders Computers Board that the user will play in.\n \"\"\"\n print(' COMPUTER ')\n print(' 0 1 2 3 4 5 6 7 8 9')\n print(' +---------------------+')\n for self.row in range(10):\n self.computer_board.append(self.water * 10)\n\n letters = 0\n for self.row in range(10):\n print(chr(letters + 65), end=' | ')\n for self.column in range(len(self.computer_board[letters])):\n print(self.computer_board[letters][self.column], end=' ')\n print('| ')\n letters += 1\n print(' +---------------------+ \\n\\n\\n')\n\n def render_computer_board2(self, alpabet, numbers):\n \"\"\"\n renders Computer Board that the user will see, their is 2 computer board, one is for the user to see\n and the other render_computer_board function is to play on. \n \"\"\"\n print(' COMPUTER ')\n print(' 0 1 2 3 4 5 6 7 8 9')\n print(' +---------------------+')\n for self.row in range(10):\n self.computer_board2.append(self.water * 10)\n\n letters = 0\n for self.row in range(10):\n print(chr(letters + 65), end=' | ')\n for self.column in range(len(self.computer_board2[letters])):\n print(self.computer_board2[letters][self.column], end=' ')\n print('| ')\n letters += 1\n print(' +---------------------+ \\n\\n\\n')\n\n\ndef New_game():\n \"\"\"\n Starts a new game and welcomes the user to the game.\n \"\"\"\n computer_board2 = []\n alpabet = None\n numbers = None\n column = 9\n row = 9\n computer_board = []\n board = []\n num_ships = 5\n ship_hit = 'X'\n ship = 'O'\n guess = []\n water = ['-']\n print('-------------------------------------------')\n print('Welcome To Battleship!! ')\n print('How to play? Try and guess where the')\n print('enemy ships are by choosing a row and a column.')\n print('Example: row: 2 comlumn: 2 \\n \\n\\n')\n print('Row and column must be between 0 and 9.')\n player_name = (input('Enter Your Name: '))\n print('-------------------------------------------\\n\\n\\n')\n setup_pb = Setup_Board(num_ships, ship_hit, ship, type, guess, water,\n computer_board, board, player_name, row, column, alpabet, numbers, computer_board2)\n print('---------------------------------------------')\n print('This is what the boards look like.')\n setup_pb.render_Player_board('Player', player_name)\n setup_pb.render_computer_board('Computer')\n print('---------------------------------------------')\n setup_pb.populate_boards(computer_board, board)\n print('---------------------------------------------')\n print('Game Starts Here')\n setup_pb.render_Player_board('Player', player_name)\n setup_pb.render_computer_board2(alpabet, numbers)\n setup_pb.make_guess(player_name)\n setup_pb.validate_corordinates(player_name, alpabet, numbers)\n\n\nNew_game()\n" } ]
2
rubenscp/CreateTrainValidTestDatasetsProject
https://github.com/rubenscp/CreateTrainValidTestDatasetsProject
ee8b20ede4657d3fe65a4dba7a804efca20d56e6
12c662853774c5289c072f4c56a2b84a140534a9
741ba44d02ab424f3611e114577784ccd7415bd9
refs/heads/main
2023-06-15T06:32:04.793523
2021-06-29T09:31:26
2021-06-29T09:31:26
336,275,017
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8504672646522522, "alphanum_fraction": 0.8504672646522522, "avg_line_length": 52.5, "blob_id": "d9db3c467a7245cca11404784bfa5117d6cf6a33", "content_id": "b15fde24492fb233cb85233d71455b48647386a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 107, "license_type": "no_license", "max_line_length": 68, "num_lines": 2, "path": "/README.md", "repo_name": "rubenscp/CreateTrainValidTestDatasetsProject", "src_encoding": "UTF-8", "text": "# CreateTrainValidTestDatasetsProject\nThis project aims to create datasets to training, validate and test.\n" }, { "alpha_fraction": 0.6627880930900574, "alphanum_fraction": 0.6704699397087097, "avg_line_length": 39.23636245727539, "blob_id": "d1dd241c0d92e80354d0268768c91c01d6716a9b", "content_id": "a8b70316b16d25a723f9254c2690d16fd9905052", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8855, "license_type": "no_license", "max_line_length": 163, "num_lines": 220, "path": "/createTrainValidTestDatasetsFullRandomized.py", "repo_name": "rubenscp/CreateTrainValidTestDatasetsProject", "src_encoding": "UTF-8", "text": "\"\"\"\nProject: Creates the the train, valid and test datasets to use in the Yolo neural network.\nAuthor: Rubens de Castro Pereira\nAdvisor: Dibio Leandro Borges\nDate: 18/01/2021\nVersion: 1.0.0\n\"\"\"\n\n# Importing needed libraries\n\nimport os\nimport pathlib\nimport shutil\nfrom random import randrange\n\n# from re import _expand\n\n# import cv2\n#\n# from Entity.BoundingBox import BoundingBox\n# from Entity.Image import Image\n# from Entity.Pixel import Pixel\n# from Entity.GroundTruthData import GroundTruthData\n# from Entity.DetectedObject import DetectedObject\n\n# ###########################################\n# Constants\n# ###########################################\nLINE_FEED = '\\n'\nCROPPED_BOUNDING_BOXES_DATABASE_PATH = 'E:/desenvolvimento/projetos/DoctoralProjects/Images-Input-Output/02. White Fly - Cropped Bounding Boxes Images by Classes/'\nTRAIN_VALID_TEST_DATASET_PATH = 'E:/desenvolvimento/projetos/DoctoralProjects/Images-Input-Output/03. White Fly - Train-Valid-Test Datasets/'\n\n\n# ###########################################\n# Application Methods\n# ###########################################\n\ndef getImageFileNameWithouExtension(fileName):\n # getting jpg position\n jpegPosition = -1\n jpegPosition = fileName.find('jpg')\n if jpegPosition == -1: jpegPosition = fileName.find('jpeg')\n if jpegPosition == -1: jpegPosition = fileName.find('JPG')\n if jpegPosition == -1: jpegPosition = fileName.find('JPEG')\n\n # getting only image name\n imageFileName = fileName[:jpegPosition - 1]\n\n # returning image file name\n return imageFileName\n\n\n# move images and annotations files\ndef moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfImages,\n specificDestinationFolder):\n # defining auxiliary variables\n imagesCounter = 0\n\n # process images\n while (imagesCounter < numberOfImages):\n # getting the files list\n filesList = os.listdir(croppedImagesClassNamePath)\n\n # getting the random position\n index = randrange(len(filesList))\n\n # getting the file name\n fileName = filesList[index]\n\n # check if file is an image or not\n if fileName.lower().find('jpg') == -1 and fileName.lower().find('jpeg') == -1:\n continue\n\n # move image file\n source = croppedImagesClassNamePath + fileName\n destination = trainValidTestDatasetsPath + specificDestinationFolder + fileName\n shutil.move(source, destination)\n\n # move annotation file\n source = croppedImagesClassNamePath + getImageFileNameWithouExtension(fileName) + '.txt'\n destination = trainValidTestDatasetsPath + specificDestinationFolder + getImageFileNameWithouExtension(\n fileName) + '.txt'\n shutil.move(source, destination)\n\n # saving processing results\n saveProcessingResults(trainValidTestDatasetsPath, fileName)\n\n # counting files moved\n imagesCounter += 1\n\n\n# process images\ndef organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages, className):\n # setting the full path name\n croppedImagesClassNamePath = croppedImagesPath + className + '/'\n\n # get the total number of images by class\n numberOfTotalImages = len(list(pathlib.Path(croppedImagesClassNamePath).glob('*.jpg')))\n images = list(pathlib.Path(croppedImagesClassNamePath).glob('*.jpg'))\n\n # calculating the number of images used in train, valid and test datasets\n numberOfTrainImages = round(numberOfTotalImages * percentageOfTrainImages / 100.0)\n numberOfValidImages = round(numberOfTotalImages * percentageOfValidImages / 100.0)\n numberOfTestImages = numberOfTotalImages - numberOfTrainImages - numberOfValidImages\n\n # moving to specific folders\n moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfTrainImages, 'train/')\n moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfValidImages, 'valid/')\n moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfTestImages, 'test/')\n\n\n# save results of processing\ndef saveProcessingResults(trainValidTestDatasetsPath, fileName):\n # creating the processing results file\n processingResultsFile = open(trainValidTestDatasetsPath + 'processingResults.txt', 'a+')\n\n # replacing characters to split string\n fileName = fileName.replace('-', '.')\n\n # getting the array of names parts\n values = fileName.split('.')\n\n # setting line to write\n line = values[0] + ' ' \\\n + values[1] + ' ' \\\n + values[3] + ' ' \\\n + values[4] + ' ' \\\n + LINE_FEED\n\n # write line\n processingResultsFile.write(line)\n\n # closing file\n processingResultsFile.close()\n\n\n# process images\ndef processImages(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages):\n # process images of the classes\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'adulta')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar1')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar2')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar3')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar4')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'exuvia')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'ovo')\n\n # defining counters\n # totalOfImages = 0\n # totalOfBoundingBoxes = 0\n # totalOfExuviaBoundingBoxesImages = 0\n # totalOfInstar1BoundingBoxesImages = 0\n # totalOfInstar2BoundingBoxesImages = 0\n # totalOfInstar3BoundingBoxesImages = 0\n # totalOfInstar4BoundingBoxesImages = 0\n # totalOfAdultaBoundingBoxesImages = 0\n # totalOfOvoBoundingBoxesImages = 0\n\n # printing statistics\n # print('')\n # print('Estatísticas do Processamento:')\n # print('------------------------------')\n # print('Total de imagens : ', totalOfImages)\n # print('Total de bounding boxes : ', totalOfBoundingBoxes)\n # print('Total de imagens de exuvia : ', totalOfExuviaBoundingBoxesImages)\n # print('Total de imagens de instar1 : ', totalOfInstar1BoundingBoxesImages)\n # print('Total de imagens de instar2 : ', totalOfInstar2BoundingBoxesImages)\n # print('Total de imagens de instar3 : ', totalOfInstar3BoundingBoxesImages)\n # print('Total de imagens de instar4 : ', totalOfInstar4BoundingBoxesImages)\n # print('Total de imagens de adultas : ', totalOfAdultaBoundingBoxesImages)\n # print('Total de imagens de ovo : ', totalOfOvoBoundingBoxesImages)\n # print('Máximo Height : ', sizeSquareImage)\n # print('Máximo Width : ', sizeSquareImage)\n # print('')\n\n\n# ###########################################\n# Main method\n# ###########################################\nif __name__ == '__main__':\n print('Cropping Annotated Bounding Boxes')\n print('---------------------------------')\n print('')\n print('Input images path - Cropped images path : ', CROPPED_BOUNDING_BOXES_DATABASE_PATH)\n print('Output images path : ', TRAIN_VALID_TEST_DATASET_PATH)\n print('')\n\n # setting the percentual of each dataset\n percentageOfTrainImages = 70\n percentageOfValidImages = 20\n percentageOfTestImages = 10\n\n # processing the annotated images\n processImages(CROPPED_BOUNDING_BOXES_DATABASE_PATH, TRAIN_VALID_TEST_DATASET_PATH,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages)\n\n # end of processing\n print('End of processing')\n" }, { "alpha_fraction": 0.6608847379684448, "alphanum_fraction": 0.667944073677063, "avg_line_length": 41.61891174316406, "blob_id": "9dc3ff6d720e58be284151dd7efdae44c0b7529d", "content_id": "f5c7e689c142a0349bf8ec4b64aa988c4ab23ad6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14874, "license_type": "no_license", "max_line_length": 158, "num_lines": 349, "path": "/createTrainValidTestDatasetsByImage.py", "repo_name": "rubenscp/CreateTrainValidTestDatasetsProject", "src_encoding": "UTF-8", "text": "\"\"\"\nProject: Creates the the train, valid and test datasets to use in the Yolo neural network.\nAuthor: Rubens de Castro Pereira\nAdvisor: Dibio Leandro Borges\nDate: 18/01/2021\nVersion: 1.0.0\n\"\"\"\n\n# Importing needed libraries\nimport os\nimport pathlib\nimport shutil\nfrom random import randrange\nimport glob\nimport fnmatch\nfrom datetime import datetime\n\n# ###########################################\n# Constants\n# ###########################################\nLINE_FEED = '\\n'\n\n\n# ###########################################\n# Application Methods\n# ###########################################\n\n\n# ###########################################\n# Methods of Level 1\n# ###########################################\n\n# process images\ndef processImages(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages):\n # creating train, valid and test directories\n createTrainValidTestDirectories(trainValidTestDatasetsPath)\n\n # process images of the classes\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'adulta')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar1')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar2')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar3')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar4')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'exuvia')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'ovo')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar1ou2')\n\n organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages,\n 'instar3ou4')\n\n # defining counters\n # totalOfImages = 0\n # totalOfBoundingBoxes = 0\n # totalOfExuviaBoundingBoxesImages = 0\n # totalOfInstar1BoundingBoxesImages = 0\n # totalOfInstar2BoundingBoxesImages = 0\n # totalOfInstar3BoundingBoxesImages = 0\n # totalOfInstar4BoundingBoxesImages = 0\n # totalOfAdultaBoundingBoxesImages = 0\n # totalOfOvoBoundingBoxesImages = 0\n\n # calculating statistics\n # get the total number of images by class\n numberOfTrainImages = len(list(pathlib.Path(trainValidTestDatasetsPath + 'train/').glob('*.jpg')))\n numberOfValidImages = len(list(pathlib.Path(trainValidTestDatasetsPath + 'valid/').glob('*.jpg')))\n numberOfTestImages = len(list(pathlib.Path(trainValidTestDatasetsPath + 'test/').glob('*.jpg')))\n totalOfImages = numberOfTrainImages + numberOfValidImages + numberOfTestImages\n\n # printing statistics\n print('')\n print('Processing Statistics by Image:')\n print('-------------------------------')\n print('Date:', datetime.now())\n print('Total of train images : ', numberOfTrainImages)\n print('Total of valid images : ', numberOfValidImages)\n print('Total of test images : ', numberOfTestImages)\n print('Total of images : ', totalOfImages)\n\n\n# ###########################################\n# Methods of Level 2\n# ###########################################\n\n# create train, valid and test directories\ndef createTrainValidTestDirectories(trainValidTestDatasetsPath):\n if not os.path.exists(trainValidTestDatasetsPath):\n os.makedirs(trainValidTestDatasetsPath)\n\n directory = trainValidTestDatasetsPath + 'train'\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n directory = trainValidTestDatasetsPath + 'valid'\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n directory = trainValidTestDatasetsPath + 'test'\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\n# organize images by classes\ndef organizeImagesByClassName(croppedImagesPath, trainValidTestDatasetsPath,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages, className):\n # setting the full path name\n croppedImagesClassNamePath = croppedImagesPath + className + '/'\n\n # get the total number of images by class\n numberOfTotalImages = len(list(pathlib.Path(croppedImagesClassNamePath).glob('*center*.jpg')))\n images = list(pathlib.Path(croppedImagesClassNamePath).glob('*center*.jpg'))\n\n # calculating the number of images used in train, valid and test datasets\n numberOfTrainImages = round(numberOfTotalImages * percentageOfTrainImages / 100.0)\n numberOfValidImages = round(numberOfTotalImages * percentageOfValidImages / 100.0)\n numberOfTestImages = numberOfTotalImages - numberOfTrainImages - numberOfValidImages\n\n # printing message in the console\n print(' ')\n print('Processing the class: ', className)\n print('Train: ', numberOfTrainImages)\n print('Valid: ', numberOfValidImages)\n print('Test: ', numberOfTestImages)\n print('Total: ', numberOfTotalImages)\n\n # moving to specific folders\n moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfTrainImages, 'train/')\n moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfValidImages, 'valid/')\n moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfTestImages, 'test/')\n\n\n# ###########################################\n# Methods of Level 3\n# ###########################################\n\n# move images and annotations files\ndef moveImageAndAnnotationFiles(croppedImagesClassNamePath, trainValidTestDatasetsPath, numberOfImages,\n specificDestinationFolder):\n # defining auxiliary variables\n imagesCounter = 0\n\n # process images\n while (imagesCounter < numberOfImages):\n # getting the files list\n # filesList2 = os.listdir(croppedImagesClassNamePath)\n # filesList3 = list(pathlib.Path(croppedImagesClassNamePath).glob('*center*.jpg'))\n # filesList4 = glob.glob(croppedImagesClassNamePath + '*center*.jpg')\n filesList = fnmatch.filter(os.listdir(croppedImagesClassNamePath), \"*center*.jpg\")\n\n # getting the random position\n index = randrange(len(filesList))\n\n # getting the file name\n fileName = filesList[index]\n\n # check if file is an image or not\n if fileName.lower().find('jpg') == -1 and fileName.lower().find('jpeg') == -1:\n continue\n\n # moving image and annotation of center position\n centerImageName = getImageFileNameWithouExtension(fileName)\n moveImageAndAnnotationFile(croppedImagesClassNamePath, centerImageName,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n # get position of string 'center.jpg'\n centerStringPosition = fileName.find('center')\n\n # moving image and annotation of another positions\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'north'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'south'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'east'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'west'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'northeast'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'northwest'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'southeast'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n imageNameOfAnotherPosition = fileName[0:centerStringPosition] + 'southwest'\n moveImageAndAnnotationFile(croppedImagesClassNamePath, imageNameOfAnotherPosition,\n trainValidTestDatasetsPath, specificDestinationFolder)\n\n # # move image file\n # source = croppedImagesClassNamePath + fileName\n # destination = trainValidTestDatasetsPath + specificDestinationFolder + fileName\n # shutil.move(source, destination)\n #\n # # move annotation file\n # source = croppedImagesClassNamePath + getImageFileNameWithouExtension(fileName) + '.txt'\n # destination = trainValidTestDatasetsPath + specificDestinationFolder + getImageFileNameWithouExtension(\n # fileName) + '.txt'\n # shutil.move(source, destination)\n\n # # saving processing results\n # saveProcessingResults(trainValidTestDatasetsPath, fileName)\n #\n # counting files moved\n imagesCounter += 1\n\n\n# ###########################################\n# Methods of Level 4\n# ###########################################\n\n\ndef moveImageAndAnnotationFile(croppedImagesClassNamePath, fileName, trainValidTestDatasetsPath,\n specificDestinationFolder):\n # defining the image name source\n source = croppedImagesClassNamePath + fileName + '.jpg'\n\n # checking if image file exists\n if not os.path.isfile(source):\n return\n\n # move image file\n destination = trainValidTestDatasetsPath + specificDestinationFolder + fileName + '.jpg'\n shutil.move(source, destination)\n\n # move annotation file\n source = croppedImagesClassNamePath + fileName + '.txt'\n destination = trainValidTestDatasetsPath + specificDestinationFolder + fileName + '.txt'\n shutil.move(source, destination)\n\n # saving processing results\n saveProcessingResults(trainValidTestDatasetsPath, specificDestinationFolder, fileName)\n\n\n# ###########################################\n# Methods of Level 5\n# ###########################################\n\n\n# get image filiename without extension name\ndef getImageFileNameWithouExtension(fileName):\n # getting jpg position\n jpegPosition = -1\n jpegPosition = fileName.find('jpg')\n if jpegPosition == -1: jpegPosition = fileName.find('jpeg')\n if jpegPosition == -1: jpegPosition = fileName.find('JPG')\n if jpegPosition == -1: jpegPosition = fileName.find('JPEG')\n\n # getting only image name\n imageFileName = fileName[:jpegPosition - 1]\n\n # returning image file name\n return imageFileName\n\n\n# save results of processing\ndef saveProcessingResults(trainValidTestDatasetsPath, specificDestinationFolder, fileName):\n # creating the processing results file\n processingResultsFile = open(trainValidTestDatasetsPath + 'processingResults.txt', 'a+')\n\n # replacing characters to split string\n fileName = fileName.replace('-', '.')\n\n # getting the array of names parts\n values = fileName.split('.')\n\n # setting line to write\n line = specificDestinationFolder + ' ' \\\n + values[0] + ' ' \\\n + values[1] + ' ' \\\n + values[3] + ' ' \\\n + values[4] + ' ' \\\n + LINE_FEED\n\n # write line\n processingResultsFile.write(line)\n\n # closing file\n processingResultsFile.close()\n\n\n# ###########################################\n# Main method\n# ###########################################\nif __name__ == '__main__':\n # INPUT_CROPPED_BOUNDING_BOXES_DATABASE_PATH = \\\n # 'E:/desenvolvimento/projetos/DoctoralProjects/CreateTrainValidTestDatasetsProjectImages/Block 30/30.2 White Fly Cropped Images by Classes/'\n # OUTPUT_TRAIN_VALID_TEST_DATASET_PATH = \\\n # 'E:/desenvolvimento/projetos/DoctoralProjects/CreateTrainValidTestDatasetsProjectImages/Block 30/30.3 White Fly Cropped Images by Train-Valid-Test/'\n\n INPUT_CROPPED_BOUNDING_BOXES_DATABASE_PATH = \\\n 'E:/desenvolvimento/projetos/DoctoralProjects/WhiteFlyExperiment/01.06 - Training - Cropped Images by Classes (128x128 pixels)/'\n OUTPUT_TRAIN_VALID_TEST_DATASET_PATH = \\\n 'E:/desenvolvimento/projetos/DoctoralProjects/WhiteFlyExperiment/01.07 - Training - Train-Valid-Test Cropped Images (128x128 pixels)/'\n\n print('Organize cropped images into train, valid and test folders')\n print('---------------------------------')\n print('')\n print('Input images path : ', INPUT_CROPPED_BOUNDING_BOXES_DATABASE_PATH)\n print('Output images path : ', OUTPUT_TRAIN_VALID_TEST_DATASET_PATH)\n print('')\n\n # setting the percentual of each dataset\n percentageOfTrainImages = 70\n percentageOfValidImages = 20\n percentageOfTestImages = 10\n\n # processing the annotated images\n processImages(INPUT_CROPPED_BOUNDING_BOXES_DATABASE_PATH, OUTPUT_TRAIN_VALID_TEST_DATASET_PATH,\n percentageOfTrainImages, percentageOfValidImages, percentageOfTestImages)\n\n # end of processing\n print()\n print('End of processing')\n" } ]
3
elidiocampeiz/ArrowFieldTraversal
https://github.com/elidiocampeiz/ArrowFieldTraversal
b0facb107cbf00d0d4ad4aa0f116a3774b0f536d
baa813cfca6379b7151994bbe7f161c527d6d430
4f68568d1097978b3539cf7f4e8cc4dfcab9c1e3
refs/heads/master
2023-02-02T18:40:50.089946
2020-12-04T19:23:47
2020-12-04T19:23:47
317,980,889
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7956204414367676, "alphanum_fraction": 0.8029196858406067, "avg_line_length": 44.66666793823242, "blob_id": "91c6895beb586a37cfd53774fd3822c2809f9684", "content_id": "fee24d2987d4d8caa319e1011e04373577022a8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 137, "license_type": "no_license", "max_line_length": 81, "num_lines": 3, "path": "/readMe.md", "repo_name": "elidiocampeiz/ArrowFieldTraversal", "src_encoding": "UTF-8", "text": "To run the project compile the GraphTraversal.py with the input and output files:\n\ne.g. python3 GraphTraversal.py rect.txt rect-soln.txt\n" }, { "alpha_fraction": 0.545918345451355, "alphanum_fraction": 0.5524781346321106, "avg_line_length": 30.204545974731445, "blob_id": "2a47b9f071e8c3a30056323cea16cac326d50821", "content_id": "17d0c53bb34180a464260589a7cb8e1c85ed6dae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1372, "license_type": "no_license", "max_line_length": 96, "num_lines": 44, "path": "/GraphTraversal.py", "repo_name": "elidiocampeiz/ArrowFieldTraversal", "src_encoding": "UTF-8", "text": "import sys\nfrom graph_utils import * \n# DFS implementation that solves the Arrow Traversal problem\ndef dfs_arrows(graph, start, goal):\n paths = {}\n paths[start] = None\n visited = set()\n visited.add(start)\n stack = []\n stack.append(start)\n while len(stack) != 0:\n node = stack.pop()\n if node == goal:\n # print('found')\n break\n for next_node in get_edges(graph, node):\n if not next_node in visited:\n # print(node, next_node, stack)\n visited.add(next_node)\n paths[next_node] = node\n stack.append(next_node)\n # visited.remove(node)\n return paths\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print(\"\\nInvalid number of arguments. Please include path of input and output files.\\n\")\n\n else:\n input_file, output_file = sys.argv[1], sys.argv[2]\n graph = get_graph(input_file)\n # print(graph)\n n, m = len(graph), len(graph[0])\n start, goal = (0,0), (n-1, m-1)\n \n paths = dfs_arrows(graph, start, goal)\n path = trace_path(graph, start, goal, paths)\n # print(paths)\n formated_path = format_path(path)\n # print(path)\n # print(formated_path)\n # test_paths(formated_path, input_file)\n write_file(output_file, formated_path)" }, { "alpha_fraction": 0.47764334082603455, "alphanum_fraction": 0.5152551531791687, "avg_line_length": 32.646018981933594, "blob_id": "dbff471c51247a20cd8bda0478d5b6fae84cd0ee", "content_id": "36c77036c0acd5580b21cf233acc9fabda436869", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3802, "license_type": "no_license", "max_line_length": 162, "num_lines": 113, "path": "/graph_utils.py", "repo_name": "elidiocampeiz/ArrowFieldTraversal", "src_encoding": "UTF-8", "text": "\ndef get_graph(filename):\n with open(filename, 'r') as fp:\n text_data = fp.readlines()\n data = [line_string.rstrip().split(' ') for line_string in text_data]\n # print(data)\n # print(data[0])# size\n graph_matrix = [] #[[None]*int(data[0][1])]*int(data[0][0])\n # print(graph_matrix)\n for c_idx, line in enumerate(data[1:]):\n row = []\n for r_idx, item in enumerate(line):\n item_data = item.split('-')\n if item_data[0]=='O':\n item_data.append(\"*\")\n \n arrow = {'type': item_data[0], 'direction': item_data[1]}\n # print(c_idx, r_idx, arrow)\n row.append( arrow)\n graph_matrix.append(row)\n # print(graph_matrix)\n for r in range(0, len(graph_matrix)):\n for c in range(0, len(graph_matrix[0])):\n node = (r, c)\n graph_matrix[r][c]['edges'] = connect_edges(graph_matrix, node)\n # graph = {}\n # {(i, j) : dict({'type': 'type', 'direction': 'dir', 'edges': set( (x,y),... ) })\n return graph_matrix\n\ndef connect_edges(graph, node):\n edges = set()\n i, j = node\n direction = graph[i][j]['direction'] \n curr_type = graph[i][j]['type']\n r, c = node\n new_node = (r, c) \n while True:\n r, c = get_next(graph, new_node, direction)\n new_node = (r, c) \n # print(r, c)\n if r == None or c == None or not (0 <= r < len(graph) and 0 <= c < len(graph[0])):\n break\n if curr_type != graph[r][c]['type']:\n edges.add(new_node)\n # print(node, edges)\n return edges\n\ndef get_next(graph, node, direction):\n i, j = node\n dir_map = {\n 'N': (i-1, j),\n 'NE': (i-1, j+1),\n 'NW': (i-1, j-1),\n 'S': (i+1, j),\n 'SE': (i+1, j+1),\n 'SW':(i+1, j-1),\n 'E' : (i, j+1),\n 'W': (i, j-1),\n '*': (None, None),\n }\n return dir_map[direction]\n\ndef get_edges(graph, node):\n i, j = node\n return graph[i][j]['edges']\n\n# funtions that reconstructs the minimum path from all explored paths\ndef trace_path(grid, start, end, paths):\n # if end is not in paths it means it can not be reached from start\n if not end in paths:\n return []\n temp = end\n path = []\n # Retrace path\n while temp != None:\n i, j = temp\n direction = grid[i][j]['direction']\n path.append( (temp, direction) )\n temp = paths[temp]\n \n \n # Reverse path and return it \n path.reverse()\n return path\n\ndef format_path(path):\n node, direction = path[0]\n formated_path = []\n for next_node, next_dir in path[1:]:\n r, c = node\n n_r, n_c = next_node\n num = max(abs(n_r - r), abs(n_c - c))\n item = ''+str(num)+direction\n formated_path.append(item)\n node, direction = next_node, next_dir\n\n return ' '.join(formated_path)\n\ndef write_file(filename, path_str):\n with open(filename, 'w+') as fp:\n fp.write(path_str)\n# def test_paths(path_str, filename):\n# solution = {\n# 'small.txt':'2S 5SE 7N 2W 1W 1SE 1NE 2E 7S 1NE 5NW 2W 3SE 2NE 2SE 3S',\n# 'rect.txt': '8S 9E 1SW 2W 7N 3SE 1SE 2N 2NW 2NW 7E 1E 1SW 5S 2E 3SW 3W 4NW 2NW 14E 1NW 2S 2NE 1N 1SW 7SW 2N 1NW 2W 7W 1SE 7N 1E 2SE 5SE 3N 4E 5E 5S 1E',\n# 'small':'2S 5SE 7N 2W 1W 1SE 1NE 2E 7S 1NE 5NW 2W 3SE 2NE 2SE 3S',\n# 'rect': '8S 9E 1SW 2W 7N 3SE 1SE 2N 2NW 2NW 7E 1E 1SW 5S 2E 3SW 3W 4NW 2NW 14E 1NW 2S 2NE 1N 1SW 7SW 2N 1NW 2W 7W 1SE 7N 1E 2SE 5SE 3N 4E 5E 5S 1E',\n \n# }\n# res = filename in solution and path_str == solution[filename]\n# if not res:\n# print('exp',solution[filename])\n# print('act', path_str)\n# return res" } ]
3
idealluna/ongoing
https://github.com/idealluna/ongoing
864070697c76388e4b02c1b35f385b2e0d470a00
a8be6facb495dbba40496dd68a5461c68382fd8a
501ddd5eea660173107eee4899093530d2b7d6ca
refs/heads/master
2020-09-20T07:57:45.401870
2016-12-30T06:24:10
2016-12-30T06:24:10
67,849,413
0
1
null
2016-09-10T03:50:39
2016-10-19T15:09:53
2016-12-30T06:24:11
C
[ { "alpha_fraction": 0.4721233546733856, "alphanum_fraction": 0.48635825514793396, "avg_line_length": 21.1842098236084, "blob_id": "a4fecd1e5e46668a8fa9f3f329f86c3d61187932", "content_id": "19bc6d8f61cbd8ba22649b8cb460d07b20746d2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 843, "license_type": "no_license", "max_line_length": 75, "num_lines": 38, "path": "/leetcode/cpp/001-twoSum/my-twosum.cc", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <vector>\n#include <unordered_map>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> m;\n vector<int> result;\n for (unsigned int i = 0; i < nums.size(); i++) {\n if (m.find(nums[i]) == m.end()) {\n m[target - nums[i]] = i;\n } else {\n result.push_back(m[nums[i]]);\n result.push_back(i);\n }\n }\n\n return result;\n\n }\n};\n\nint main(int argc, char *argv[])\n{\n Solution s;\n vector<int> v = {2, 7, 13, 4, 11, 5, -2};\n int target = 9;\n vector<int> r = s.twoSum(v, target);\n for (vector<int>::iterator iter = r.begin(); iter != r.end(); iter++) {\n cout << *iter << \"\\t\";\n }\n\n cout << endl;\n\n return 0;\n}\n" }, { "alpha_fraction": 0.4522821605205536, "alphanum_fraction": 0.4564315378665924, "avg_line_length": 16.214284896850586, "blob_id": "24f4b6415b59a9f805abdebb61faa677e3cabdd7", "content_id": "342105444be1b2aad20117dc72ee88ca03716677", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/python/setup-to-rpm/hello", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport time\n\n\ndef hello(fout):\n while True:\n fout.write(time.ctime() + \" hello\\n\")\n time.sleep(5)\n\n\nif __name__ == \"__main__\":\n f = open(\"/tmp/test\", \"w+b\")\n hello(f)\n" }, { "alpha_fraction": 0.2963365912437439, "alphanum_fraction": 0.31302139163017273, "avg_line_length": 28.967391967773438, "blob_id": "1a4f1107da1798d50045fc6fe7fdba8de39e3999", "content_id": "c89902032134e0d7c6894ecd7dd3962acc13608e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2757, "license_type": "no_license", "max_line_length": 86, "num_lines": 92, "path": "/leetcode/cpp/005-longest-palindrome/longestPalin.cc", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nclass Solution {\npublic:\n string longestPalindrome(string s) {\n if (s.empty()) return \"\";\n int v = 0, p = 0, m = 0, l = 1;\n while (p < s.length() - 1) {\n if (s[p] == s[p + 1]) {\n while ((p - v) >= 0 && (p + v + 1) < s.length()\n && s[p - v] == s[p + v + 1]) {\n v++;\n }\n if (l < 2 * v) {\n m = p - (v - 1);\n l = 2 * v;\n }\n v = 0;\n }\n if (s[p - v] == s[p + v]) {\n while ((p - v) >= 0 && (p + v) < s.length()\n && s[p - v] == s[p + v]) {\n v++;\n }\n if (l < 2 * (v - 1) + 1) {\n m = p - (v - 1);\n l = 2 * (v - 1) + 1;\n }\n v = 0;\n }\n p++;\n v = 0;\n }\n\n //cout << m << \"\\t\" << l << endl;\n return s.substr(m, l);\n }\n};\n\nstring longestPalindrome(string s) {\n if (s.empty()) return \"\";\n if (s.size() == 1) return s;\n int min_start = 0, max_len = 1;\n for (int i = 0; i < s.size();) {\n if (s.size() - i <= max_len / 2) break;\n int j = i, k = i;\n while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters.\n i = k+1;\n while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.\n int new_len = k - j + 1;\n if (new_len > max_len) { min_start = j; max_len = new_len; }\n }\n return s.substr(min_start, max_len);\n}\n\nint main()\n{\n vector<string> strs = {/*\"esabadc\",\n \"a\",\n \"aa\",\n \"aaa\",\n \"aaaa\",\n \"aaaaa\",\n \"aaaaasaaaa\",\n \"aaaaasaaaaa\",\n \"asasasasa\",\n \"asasaqwe\",\n \"qweasasa\",\n \"aaaaqwer\", */\n \"asdyyvvyfsd\",\n \"asdyyvvvvyfsd\",\n \"asdyyvvvyfsd\",\n \"asaaaaqwer\",\n \"aaqwer\",\n \"qweraaaa\"\n };\n\n Solution s;\n for (unsigned int i = 0; i < strs.size(); i++) {\n //\u001bOBfor (int j = 0; j < 1000000; j++)\n // //longestPalindrome(strs[i]);\n // s.longestPalindrome(strs[i]);\n cout << s.longestPalindrome(strs[i]) << endl;\n //cout << longestPalindrome(strs[i]) << endl;\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 8.5, "blob_id": "ffa79674290767e9403161ca52bf7d744bc90b9b", "content_id": "bfd3e27f0a0b07d5916134ec50a025f63a1f2bbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 9, "num_lines": 2, "path": "/README.md", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "# ongoing\nlearn go\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 14.600000381469727, "blob_id": "fd0b51ca7413ada23f7933433861f0ddfaa3e5ae", "content_id": "9309b880381778d888b594b72561e4e22f449ae8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 78, "license_type": "no_license", "max_line_length": 38, "num_lines": 5, "path": "/python/setup-to-rpm/Makefile", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "rpm:\n\tpython setup.py bdist_rpm\n\nspec:\n\tpython setup.py bdist_rpm --spec-only\n" }, { "alpha_fraction": 0.4096890091896057, "alphanum_fraction": 0.44736841320991516, "avg_line_length": 19.390243530273438, "blob_id": "cd04aa3410a98e9150aa312c0bbd3be918629a2f", "content_id": "f580b65a7de03a0c97ef33841fce81a48ca3ebe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 58, "num_lines": 82, "path": "/leetcode/cpp/002-add-two/addTwo.cc", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n\n#include <iostream>\n#include <vector>\nusing namespace std;\n\nstruct ListNode {\n int val;\n ListNode *next;\n ListNode(int x) : val(x), next(NULL) {}\n};\n\nclass Solution {\npublic:\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n ListNode head(0);\n ListNode *r = &head;\n int c = 0, s= 0;\n\n while (l1 != NULL || l2 != NULL) {\n s = ((l1 != NULL) ? l1->val : 0) +\n ((l2 != NULL) ? l2->val : 0) +\n c;\n r->next = new ListNode(s % 10);\n r = r->next;\n c = s / 10;\n\n if (l1 != NULL)\n l1 = l1->next;\n if (l2 != NULL)\n l2 = l2->next;\n }\n\n if (c != 0) {\n r->next = new ListNode(c);\n r = r->next;\n }\n\n return head.next;\n }\n};\n\n\nint main(int argc, char *argv[])\n{\n Solution s;\n vector<int> v1 = {2, 4, 3, 8};\n vector<int> v2 = {5, 6, 4, 9};\n\n ListNode head1(0);\n ListNode head2(0);\n ListNode *l1 = &head1, *l2 = &head2;\n\n for (unsigned int i = 0; i != v1.size(); i++) {\n l1->next = new ListNode(v1[i]);\n l1 = l1->next;\n l2->next = new ListNode(v2[i]);\n l2 = l2->next;\n }\n\n l2->next = new ListNode(9);\n l2 = l2->next;\n l2->next = new ListNode(9);\n l2 = l2->next;\n\n ListNode *r = s.addTwoNumbers(head1.next, head2.next);\n\n while (r != NULL) {\n cout << r->val << \"\\t\";\n r = r->next;\n }\n\n cout << endl;\n return 0;\n}\n" }, { "alpha_fraction": 0.582524299621582, "alphanum_fraction": 0.594660222530365, "avg_line_length": 19.600000381469727, "blob_id": "23bd53624fa654950e48e401250376d6e9583a0f", "content_id": "2a06424261ee9fed7a2cbbe1089d569b3080178a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 54, "num_lines": 20, "path": "/python/setup-to-rpm/setup.py", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport distutils.core\n\nname = 'hello'\n\ndistutils.core.setup(name=name,\n version='1.0',\n author=\"Packager Tester\",\n author_email=\"[email protected]\",\n url=\"http://test.cn\",\n description=\"hello test for setup.py to rpm\",\n long_description=\"hello test for setup.py to rpm\",\n license=\"GPLv2\",\n\n scripts=[name],\n data_files=[\n ('/usr/share/man/man1', [name + '.1.gz']),\n ],\n)\n" }, { "alpha_fraction": 0.34398889541625977, "alphanum_fraction": 0.3537178635597229, "avg_line_length": 22.590164184570312, "blob_id": "26964d2e59223305d1fa8616b5aaa4e5a5fc1b47", "content_id": "92eb2f3895bdd8a3e1d8f5916f48f8a79102b956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1439, "license_type": "no_license", "max_line_length": 95, "num_lines": 61, "path": "/leetcode/cpp/003-longest-substring/longestSubStr.cc", "repo_name": "idealluna/ongoing", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <string>\n\nusing namespace std;\n\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n unordered_map<char, int> m;\n /*\n int i = 0, b = -1, r = 0;\n while (i < s.length()) {\n if (m.count(s[i])) \n b = max(b, m[s[i]]);\n\n m[s[i]] = i;\n r = max(r, i - b);\n i++;\n }\n int i = 0, r = 0, len = 0;\n while (i < s.length()) {\n if (m.find(s[i]) == m.end()) {\n m[s[i]] = i;\n len++;\n i++;\n } else {\n r = (r > len) ? r : len;\n i = m[s[i]] + 1;\n len = 0;\n m.clear();\n }\n r = (r > len) ? r : len;\n }\n */\n int i = 0, r = 0, b = -1;\n while (i < s.length()) {\n if (m.count(s[i])) {\n b = max(b, m[s[i]]);\n }\n m[s[i]] = i;\n r = (r > i - b) ? r : i - b;\n i++;\n }\n if (r == 0)\n r = s.length();\n return r;\n }\n};\n\n\nint main(int argc, char *argv[])\n{\n Solution s;\n vector<string> strs = {\"aab\", \"abcabcbb\", \"bbbbb\", \"pwwkew\", \"abcdefgha\", \"abcdefghqwrty\"};\n for (int i = 0; i < strs.size(); i++) {\n cout << s.lengthOfLongestSubstring(strs[i]) << endl;\n }\n return 0;\n}\n" } ]
8
karaleina/lucasKanadeFlow
https://github.com/karaleina/lucasKanadeFlow
3337b17bda88498cde99e4e0edc0165d8a3bcf5d
fe81db0f22e8dc1ef6198fb9cefe8ec99e75ed0f
aca24f58fdb4fd955af92c986f6b89eaf7f9ca7d
refs/heads/master
2021-01-02T08:58:35.004912
2017-08-02T13:07:18
2017-08-02T13:07:18
99,107,563
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5887016654014587, "alphanum_fraction": 0.6139742136001587, "avg_line_length": 25.359477996826172, "blob_id": "27ceb5e3b66daa19bfc630c47955e0a376586f0f", "content_id": "6e7221227a83f605ae520711b43a4550e7e95c48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4046, "license_type": "no_license", "max_line_length": 90, "num_lines": 153, "path": "/lucasKanadeFlow.py", "repo_name": "karaleina/lucasKanadeFlow", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport os\nfrom matplotlib import pyplot as plt\nfrom sklearn import decomposition\nimport h5py\nimport math\n\nfilename = \"4_oddech_przykrywka.avi\"\nfilepath = os.path.abspath(\"C:\\\\Users\\\\ImioUser\\\\Desktop\\\\K&A\\\\pylon_spekle\\\\\" + filename)\nfilename_save = \"test.h5\"\n\ncap = cv2.VideoCapture(filepath)\n\n# params for ShiTomasi corner detection\nfeature_params = dict( maxCorners = 100,#100\n qualityLevel = 0.005,#0.3\n minDistance = 20,#7\n blockSize = 7)#7\n\n# Parameters for lucas kanade optical flow\nlk_params = dict( winSize = (15,15),\n maxLevel = 2,\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\n# Create some random colors\ncolor = np.random.randint(0,255,(100,3))\n\n# Take first frame and find corners in it\nret, old_frame = cap.read()\nold_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)\np0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)\n\nprint(\"Znaleziona liczba śledzonych punktów\"\n \" = \" + str(len(p0)))\n\n# Create a mask image for drawing purposes\nmask = np.zeros_like(old_frame)\n\n# Zmienne\nall = []\nmean_x_all_frames = []\nmean_y_all_frames = []\nangles_in_all_frames = []\nspeed_in_all_frames = []\n\n# while(cap.isOpened()):\n# ret,frame = cap.read()\n#\n# if(frame == None):\n# break\n#\n# frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n#\n# # calculate optical flow\n# p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)\n#\n# # Select good points\n# good_new = p1[st==1]\n# good_old = p0[st==1]\n#\n# # Here is the list of current changes in a and b for all piramids\n# current_a = []\n# current_b = []\n# current_c = []\n# current_d = []\n#\n# # draw the tracks\n# for i,(new,old) in enumerate(zip(good_new,good_old)):\n# a,b = new.ravel()\n# c,d = old.ravel()\n#\n# # Adding parameters to the list of current changes in a and b for all piramids\n# current_a.append(a)\n# current_b.append(b)\n# current_c.append(c)\n# current_d.append(d)\n#\n# mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)\n# frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)\n#\n# # Adding current mean to the list of all means\n# mean_x_all_frames.append(np.mean(current_a))\n# mean_y_all_frames.append(np.mean(current_b))\n# angles_in_all_frames.append(math.atan((b-d)/float(a-c)))\n# speed_in_all_frames.append(math.sqrt(math.pow((b-d), 2) + math.pow((a-c),2)))\n#\n# img = cv2.add(frame,mask)\n# cv2.imshow('frame',img)\n# k = cv2.waitKey(30) & 0xff\n# if k == 27:\n# break\n# # Now update the previous frame and previous points\n# old_gray = frame_gray.copy()\n# p0 = good_new.reshape(-1,1,2)\n#\n# cv2.destroyAllWindows()\n# cap.release()\n#\n# ##########################################################\n#\n#\n\n# # Write\n# all = np.zeros(shape=(4,len(angles_in_all_frames)))\n# all[2,:] = angles_in_all_frames\n# all[3,:] = speed_in_all_frames\n# all[0,:] = mean_x_all_frames\n# all[1,:] = mean_y_all_frames\n#\n#\n# with h5py.File(filename_save, 'w') as hf:\n# hf.create_dataset(\"all\", data=all)\n\n# Read\nwith h5py.File(filename_save, 'r') as hf:\n all = hf['all'][:]\n\nprint(all)\nprint(type(all))\n\nmean_x = all[0,:]\nmean_y = all[1,:]\nangles_in_all_frames = all[2,:]\nspeed_in_all_frames = all[3,:]\n\n\n# convert to matrix\ntrain_data = np.mat([mean_x,mean_y])\npca_components = 1\n\n# reduce both train and test data\npca = decomposition.PCA(n_components=pca_components).fit(train_data)\nX_out_pca = pca.transform(train_data)\n\nplt.subplot(2,2,1)\nplt.plot(mean_x, mean_y)\nplt.title(\"Średni ruch spekli w wejściowych współrzędnych\")\n\nplt.subplot(2,2,2)\nplt.plot(X_out_pca)\nplt.title(\"Ruch spekli po PCA\")\n\nplt.subplot(2,2,4)\nplt.plot(angles_in_all_frames)\nplt.title(\"Zmiany kąta w czasie\")\n\nplt.subplot(2,2,3)\nplt.plot(speed_in_all_frames)\nplt.title(\"Zmiany prędkości w czasie\")\n\n\nplt.show()\n\n\n\n" } ]
1
narulgo/MovieRater-backend
https://github.com/narulgo/MovieRater-backend
8ec8a514d24965450927d37573cf1b1bf7be34b1
e23162785418fa7ac53f63b8c1305841351811fb
6ef65cd548bee3d0757d41229c7c6384d2b7805c
refs/heads/master
2023-04-20T17:08:34.820866
2021-05-03T10:58:24
2021-05-03T10:58:24
338,007,745
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6270396113395691, "alphanum_fraction": 0.6783216595649719, "avg_line_length": 25.8125, "blob_id": "61ebc8bab2c36e51f7d6f2e28613ccda8c4efe31", "content_id": "b049298b10af264f32347e5923f7d4b8f745bb05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 60, "num_lines": 16, "path": "/movierater/urls.py", "repo_name": "narulgo/MovieRater-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import include\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/', include('api.urls')),\n path('auth/', obtain_auth_token),\n<<<<<<< HEAD\n path(\"api-auth/\",\n include(\"rest_framework.urls\")),\n]\n=======\n]\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\n" }, { "alpha_fraction": 0.6011635661125183, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 21.25899314880371, "blob_id": "80ab5f6a5dc2e65ed11790932685ffa3a63ae6c1", "content_id": "7596e71feb32fb4d9a4ff1e2585b7ac627c341d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3094, "license_type": "no_license", "max_line_length": 91, "num_lines": 139, "path": "/movierater/settings.py", "repo_name": "narulgo/MovieRater-backend", "src_encoding": "UTF-8", "text": "from pathlib import Path\n\n<<<<<<< HEAD\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n\nSECRET_KEY = 'django-insecure-x%gl-9wn)i^#h#(&v=r$)#blp84f6@(z_e7k7ih$3-g*$okd+c'\n=======\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\nSECRET_KEY = '6v3q1ofg6-$pcl4_v*s@wrlycyke-_jjq^c-z+#l#-!5#f_1+w'\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\n\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n<<<<<<< HEAD\n=======\n\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'rest_framework.authtoken',\n<<<<<<< HEAD\n 'rest_auth',\n 'rest_auth.registration',\n=======\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\n 'corsheaders',\n 'api',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nCORS_ORIGIN_WHITELIST = [\n \"http://localhost:8080\"\n]\n\nROOT_URLCONF = 'movierater.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'movierater.wsgi.application'\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\n\n<<<<<<< HEAD\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n )\n}\n\n\n=======\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': {\n 'rest_framework.permissions.IsAuthenticated',\n }\n}\n\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n<<<<<<< HEAD\n=======\n\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\nSTATIC_URL = '/static/'\n<<<<<<< HEAD\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n=======\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\n" }, { "alpha_fraction": 0.6561086177825928, "alphanum_fraction": 0.7556561231613159, "avg_line_length": 23.55555534362793, "blob_id": "90ee91f66abac90af2823a7ac4f73af78582e96b", "content_id": "a258781ba57fcf850983667d6931da5393a7b1b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 221, "license_type": "no_license", "max_line_length": 48, "num_lines": 9, "path": "/api/admin.py", "repo_name": "narulgo/MovieRater-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Movie, Rating\n\nadmin.site.register(Movie)\n<<<<<<< HEAD\nadmin.site.register(Rating)\n=======\nadmin.site.register(Rating)\n>>>>>>> 3afca6c2a2eb7b733f6b361c20c76d681fc4aa85\n" } ]
3
joeo/dgshell
https://github.com/joeo/dgshell
ad2d3a3007cbbfbb0b6c890efed37ffda3723f50
e78eed63d16ca2e3dd16d02ae2804de0a94b2760
81b28817833a22f88e94b63569df9a657bb0572f
refs/heads/master
2018-12-28T11:21:19.866408
2012-06-22T17:39:20
2012-06-22T17:39:20
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5050662755966187, "alphanum_fraction": 0.5159781575202942, "avg_line_length": 21.508771896362305, "blob_id": "3707c3bc54e1dc2e64cb07249a19ee028d1e40e1", "content_id": "124aaf1d5acb75a343c4aa5425abe38db26f5a0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1283, "license_type": "no_license", "max_line_length": 63, "num_lines": 57, "path": "/shellparse.py", "repo_name": "joeo/dgshell", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nclass Tokenizer:\n def __init__(self, string):\n self.string = string\n self.pos = 0\n def set(self, pos):\n self.pos = pos\n def get(self):\n s = self.string\n pos = self.pos\n l = len(s)\n while pos < l and s[pos].isspace():\n pos = pos + 1\n startpos = pos\n if pos >= l:\n return None\n start = s[pos]\n pos = pos + 1\n if start == ';':\n endpos = pos\n elif start == '\"' or start == \"'\":\n startpos = pos\n while pos < l and s[pos] != start:\n pos = pos + 1\n endpos = pos\n pos = pos + 1\n else:\n while pos < l and not s[pos].isspace() and s[pos] != ';':\n pos = pos + 1\n endpos = pos\n self.pos = pos\n return s[startpos:endpos]\n\ndef split(string):\n tokenizer = Tokenizer(string)\n result = []\n while True:\n t = tokenizer.get()\n if t is None:\n return result\n else:\n result.append(t)\n\ndef test():\n def check_tokens(string, expected):\n actual = split(string)\n if expected != actual:\n print \"FAILED: %s\" % string\n print \" expected: %s\" % expected\n print \" actual: %s\" % actual\n\n check_tokens(\" 'asdf' \"\" \\\" 1234 ' jkl;\\\" xy;z jkl\",\n [\"asdf\", \" 1234 ' jkl;\", \"xy\", \";\", \"z\", \"jkl\"])\n\nif __name__ == \"__main__\":\n test()\n" }, { "alpha_fraction": 0.6118999123573303, "alphanum_fraction": 0.6179851293563843, "avg_line_length": 21.074626922607422, "blob_id": "6aec624a7e0ea778074d2766019071fc3e1ee863", "content_id": "89921bc19302e75f8633a88128b2ace1ea66e2e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1479, "license_type": "no_license", "max_line_length": 69, "num_lines": 67, "path": "/dgshell", "repo_name": "joeo/dgshell", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# vim: set ts=2 sw=2:\n\nimport readline\nimport sys\nimport getpass\n\nimport commands\nimport database\n\ndef load_history(db):\n history = db.load_history()\n for h in history:\n readline.add_history(h)\n\ndef save_history(db):\n history = [readline.get_history_item(i)\n for i in range(1,readline.get_current_history_length()+1)]\n db.save_history(history)\n\ndef run_interpreter(db):\n try:\n load_history(db)\n\n print \"This is dgshell. Be nice to your neighbors.\"\n print \"For a list of commands type help. To exit type Control+C.\"\n print\n print \" Username: %s\" % db.username\n print\n while True:\n s = raw_input(\"> \")\n if len(s.strip()) == 0:\n continue\n try:\n cmd = commands.parse_text(s)\n cmd.run()\n except commands.Error as ex:\n print \"Error: %s\" % ex\n\n except (EOFError, KeyboardInterrupt):\n save_history(db)\n print\n\ndef main(argv):\n if len(argv) < 2:\n sys.stderr.write(\"usage: dgshell dgfile [COMMAND...]\\n\")\n return\n filename = argv[1]\n \n db = database.Db(filename)\n if db.status == db.STATUS_NEW:\n print \"Initializing.\"\n username = raw_input(\"username: \")\n password = getpass.getpass(\"password: \")\n db.init(username, password)\n\n if len(argv) == 2:\n run_interpreter(db)\n else:\n try:\n cmd = commands.parse_list(argv[2:])\n cmd.run()\n except commands.Error as ex:\n print \"Error: %s\" % ex\n\nif __name__ == \"__main__\":\n main(sys.argv)\n" }, { "alpha_fraction": 0.6112716794013977, "alphanum_fraction": 0.615606963634491, "avg_line_length": 28.43617057800293, "blob_id": "b962cfe9215929882b9128aa95656ac1bdab5266", "content_id": "380fdba5dce62257e88e803ac9d8453823850966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2768, "license_type": "no_license", "max_line_length": 94, "num_lines": 94, "path": "/database.py", "repo_name": "joeo/dgshell", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# vim: set ts=2 sw=2:\n\nimport sqlite3\n\nclass Db:\n CURRENT_DB_VERSION = 1\n\n # Everything is ready to go\n STATUS_OK = \"OK\"\n # Old version of the db. No more actions possible.\n # (Maybe some day we'll support upgrades)\n STATUS_OLD_VERSION = \"OLD_VERSION\"\n # The database is ok, but it's new. Must call init()\n STATUS_NEW = \"NEW\"\n\n def __init__(self, filename):\n self.conn = sqlite3.connect(filename)\n self.status = Db.STATUS_OK\n\n c = self.conn.cursor()\n try:\n c.execute(\"SELECT db_version, username, password FROM Info\")\n info = c.fetchall()[0]\n if info[0] != Db.CURRENT_DB_VERSION:\n self.status = Db.STATUS_OLD_VERSION\n return # bail\n self.username = info[1]\n self.password = info[2]\n except sqlite3.OperationalError:\n # Need initialization\n self.conn.execute(\"\"\"CREATE TABLE Info (\n db_version INETGER,\n username TEXT,\n password TEXT\n )\"\"\")\n self.conn.execute(\"\"\"CREATE TABLE CommandHistory (\n id INTEGER,\n command TEXT\n )\"\"\")\n self.conn.execute(\"\"\"INSERT INTO Info(db_version) VALUES(%d)\"\"\"\n % (Db.CURRENT_DB_VERSION))\n self.conn.commit()\n self.status = Db.STATUS_NEW\n finally:\n c.close()\n\n def init(self, username, password):\n if self.status != Db.STATUS_OK and self.status != Db.STATUS_NEW:\n raise Exception(\"Database is not initialized. Status: %s\" % self.status)\n c = self.conn.cursor()\n try:\n c.execute(\"UPDATE Info SET username=?, password=?\", (username, password))\n self.conn.commit()\n self.status = Db.STATUS_OK\n self.username = username\n self.password = password\n finally:\n c.close()\n\n def assert_ok(self):\n if self.status != Db.STATUS_OK:\n raise Exception(\"Database status is %s\" % self.status)\n\n def close(self):\n if self.status != Db.STATUS_OK and self.status != Db.STATUS_NEW:\n raise Exception(\"Database status is %s\" % self.status)\n self.conn.close()\n\n def save_history(self, history):\n self.assert_ok()\n self.conn.execute(\"DELETE FROM CommandHistory\")\n for i in range(0,len(history)):\n self.conn.execute(\"INSERT INTO CommandHistory(id,command) VALUES(?,?)\", (i, history[i]))\n self.conn.commit()\n\n def load_history(self):\n return [row[0] for row\n in self.conn.execute(\"SELECT command FROM CommandHistory ORDER BY id ASC\")]\n\ndef test():\n db = Db(\"test.dg\")\n print \"db.status=%s\" % db.status\n if db.status == Db.STATUS_NEW:\n db.init(\"testuser\", \"testpasswd\")\n print \"did init\"\n if db.status != Db.STATUS_OK:\n print \"bailing\"\n return\n db.save_history([\"asdf\",\"hi\",\"mom\"])\n print db.load_history()\n\nif __name__ == \"__main__\":\n test()\n\n" }, { "alpha_fraction": 0.5880823135375977, "alphanum_fraction": 0.5974225401878357, "avg_line_length": 22.755617141723633, "blob_id": "fe4b46b297da92da41ed95d6b680e1636c35881e", "content_id": "17faf0106959f3eb9ea5da38d2c00f5ab4247ba7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8458, "license_type": "no_license", "max_line_length": 99, "num_lines": 356, "path": "/commands.py", "repo_name": "joeo/dgshell", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# vim: set ts=2 sw=2:\n\nimport re\n\nimport shellparse\n\nIDENTIFIER_RE = re.compile(r\"^[A-Za-z_][A-Za-z0-9_]*$\")\n\nclass Error:\n def __init__(self, message):\n self.message = message\n def __str__(self):\n return self.message\n\n\nclass Command:\n def run(self):\n print self\n def flatten(self):\n print str(self)\n\n\nclass Help(Command):\n NAME = \"help\"\n SHORTHELP = \"Shows this help message.\"\n LONGHELP = \"\"\"\n help Show the list of commands\n help COMMAND Show the help for COMMAND\n \"\"\"\n\n def __init__(self, words):\n if len(words) == 1:\n self.command = None\n elif len(words) == 2:\n self.command = words[1]\n else:\n raise Error(\"malformed help command\")\n assert_identifier(self.command)\n\n def __str__(self):\n return \"Help command=%s\" % self.command\n\n def flatten(self):\n if self.command:\n return \"help %s\" % self.command\n else:\n return \"help\"\n\n def run(self):\n if self.command:\n cmd = choose_command(self.command)\n if cmd:\n print \" \" + cmd.SHORTHELP\n print cmd.LONGHELP\n else:\n raise Error(\"Not a command: %s\" % self.command)\n else:\n print \"Commands:\"\n maxlen = 0\n for cmd in COMMANDS:\n if len(cmd.NAME) > maxlen:\n maxlen = len(cmd.NAME)\n fmt = \" {0:<%d} {1}\" % (maxlen)\n for cmd in COMMANDS:\n print fmt.format(cmd.NAME, cmd.SHORTHELP)\n\n\nclass Print(Command):\n NAME = \"print\"\n SHORTHELP = \"Prints the value of an expression.\"\n LONGHELP = \"\"\"\n \"\"\"\n\n def __init__(self, words):\n # See if it's an expression\n self.val,index = parse_value(words[1:], None)\n\n def __str__(self):\n return \"Print %s\" % (self.val)\n\n def flatten(self):\n return \"print %s\" % (self.val.flatten())\n\n\nclass Reload(Command):\n NAME = \"reload\"\n SHORTHELP = \"Reloads the game data from the web.\"\n LONGHELP = \"\"\"\n \"\"\"\n\n def __init__(self, words):\n pass\n\n def __str__(self):\n return \"Reload\"\n\n def flatten(self):\n return \"reload\"\n\n\nclass Save(Command):\n NAME = \"save\"\n SHORTHELP = \"Creates a saved query\"\n LONGHELP = \"\"\"\n \"\"\"\n\n def __init__(self, words):\n # var\n try:\n self.var = words[1]\n except IndexError as ex:\n raise Error(\"set command malformed: missing variable name\")\n # =\n if words[2] != '=':\n raise Error(\"set command malformed: missing '='\")\n # value\n self.query,index = parse_value(words[3:], None)\n\n def __str__(self):\n return \"Save %s = %s\" % (self.var, self.query)\n\n def flatten(self):\n return \"save %s = %s\" % (self.var, self.query.flatten())\n\n\nclass Set(Command):\n NAME = \"set\"\n SHORTHELP = \"Sets a variable value.\"\n LONGHELP = \"\"\"\n \"\"\"\n\n def __init__(self, words):\n # var\n try:\n self.var = words[1]\n except IndexError as ex:\n raise Error(\"set command malformed: missing variable name\")\n # =\n if words[2] != '=':\n raise Error(\"set command malformed: missing '='\")\n # value\n self.val,index = parse_value(words[3:], None)\n\n def __str__(self):\n return \"Set %s = %s\" % (self.var, self.val)\n\n def flatten(self):\n return \"set %s = %s\" % (self.var, self.val.flatten())\n\n\nclass Show(Command):\n NAME = \"show\"\n SHORTHELP = \"Shows the command for a saved query.\"\n LONGHELP = \"\"\"\n \"\"\"\n\n def __init__(self, words):\n # var\n try:\n self.var = words[1]\n except IndexError as ex:\n raise Error(\"show command malformed: missing variable name\")\n\n def __str__(self):\n return \"Show %s\" % (self.var)\n\n def flatten(self):\n return \"show %s\" % self.var\n\n\nclass FleetExpression:\n def __init__(self, types):\n self.queries = []\n self.types = set(types)\n\n def __str__(self):\n return \"Fleets(types=%s queries=%s)\" % (self.types, self.queries)\n\n def flatten(self):\n result = \"\"\n result = result + \" \".join(self.types)\n for q in self.queries:\n if q[0] == \"within\":\n result = result + \" within %s of %s\" % (q[1], flatten_string(q[2]))\n else:\n result = result + \" %s %s\" % (q[0], flatten_string(q[1]))\n return result\n\n\nclass PlanetExpression:\n def __init__(self):\n self.queries = []\n\n def __str__(self):\n return \"Planets(queries=%s)\" % (self.queries)\n\n def flatten(self):\n result = \"planets\"\n for q in self.queries:\n if q[0] == \"within\":\n result = result + \" within %s of %s\" % (q[1], flatten_string(q[2]))\n else:\n result = result + \" %s %s\" % (q[0], flatten_string(q[1]))\n return result\n\n\n\ndef flatten_string(text):\n if IDENTIFIER_RE.match(text):\n return text\n else:\n return \"\\\"\" + text + \"\\\"\"\n\n\n# Parses out a fleet, planet or route expression. If termiator is provided,\n# parsing will stop if that word is encountered.\n# Returns a tuple of\n# 0: FleetExpression or PlanetExpression expressed in words\n# 1: The next position in words at which parsing should continue\n# Raises Error if there is an error\ndef parse_value(words, terminator):\n try:\n types,index = parse_fleet_names(words)\n if len(types) > 0:\n return parse_fleets(words, terminator)\n if words[0] == \"planets\":\n return parse_planets(words[1:], terminator)\n if len(words) == 1:\n return (words[0],1)\n raise Error(\"Expected fleets, planets or routes\")\n except IndexError as ex:\n raise Error(\"IndexError\")\n\ndef assert_identifier(text):\n if not IDENTIFIER_RE.match(text):\n raise Error(\"Expecting identifier. Found: %s\" % text)\n\nFLEET_NAMES = {\n \"arc\": \"arc\",\n \"arcs\": \"arc\",\n \"merchantman\": \"merchantmen\",\n \"merchantmen\": \"merchantmen\",\n}\n\ndef normalize_fleet_name(word):\n if FLEET_NAMES.has_key(word):\n return FLEET_NAMES[word]\n else:\n return None\n\ndef parse_fleet_names(words):\n if words[0] == \"fleets\":\n return ([\"fleets\"],1)\n index = 0\n result = []\n while index < len(words):\n name = normalize_fleet_name(words[index])\n if name:\n result.append(name)\n else:\n break\n index = index + 1\n return result,index\n\ndef parse_fleets(words, terminator):\n types,index = parse_fleet_names(words)\n fleets = FleetExpression(types)\n while index < len(words):\n if words[index] == \"within\":\n distance = words[index+1]\n if words[index+2] != \"of\":\n raise Error(\"Expected 'of'\")\n planet = words[index+3]\n fleets.queries.append((\"within\", distance, planet))\n index = index + 4\n elif words[index] == \"inside\":\n fleets.queries.append((\"inside\", words[index+1]))\n index = index + 2\n elif words[index] == \"on\":\n fleets.queries.append((\"on\", words[index+1]))\n index = index + 2\n elif words[index] == \"id\":\n fleets.queries.append((\"id\", words[index+1]))\n index = index + 2\n else:\n fleets.queries.append((\"id\", words[index]))\n index = index + 1\n return (fleets, index)\n\ndef parse_planets(words, terminator):\n index = 0\n fleets = PlanetExpression()\n while index < len(words):\n if words[index] == \"within\":\n distance = words[index+1]\n if words[index+2] != \"of\":\n raise Error(\"Expected 'of'\")\n planet = words[index+3]\n fleets.queries.append((\"within\", distance, planet))\n index = index + 4\n elif words[index] == \"inside\":\n fleets.queries.append((\"inside\", words[index+1]))\n index = index + 2\n elif words[index] == \"id\":\n fleets.queries.append((\"id\", words[index+1]))\n index = index + 2\n else:\n fleets.queries.append((\"id\", words[index]))\n index = index + 1\n return (fleets, index)\n\nCOMMANDS = (\n Help,\n Print,\n Reload,\n Save,\n Set,\n Show,\n )\n\ndef choose_command(word):\n for cmd in COMMANDS:\n if cmd.NAME == word:\n return cmd\n return None\n\ndef parse_text(text):\n return parse_list(shellparse.split(text))\n\ndef parse_list(words):\n cmd = choose_command(words[0])\n if cmd:\n return cmd(words)\n else:\n raise Error(\"Not a command: %s\" % words[0])\n\ndef test():\n def check(text):\n cmd = parse_text(text)\n print cmd\n\n check(\"reload\")\n check(\"set x = fleets inside 'routename' within 4.2 of mom on routey\")\n check(\"set x = fleets\")\n check(\"set x = arc arcs\")\n check(\"set x = arcs merchantmen inside 'routename' within 4.2 of mom on routey\")\n check(\"set x = asdf\")\n check(\"save x = arcs merchantmen inside 'routename' more within 4.2 of mom on routey 1234 'a b'\")\n check(\"save x = planets inside 'routename' more within 4.2 of mom 1234 'a b'\")\n check(\"show x\")\n check(\"help\")\n check(\"help show\")\n\nif __name__ == \"__main__\":\n test()\n\n" } ]
4
amaliyazar/compling
https://github.com/amaliyazar/compling
a05823f80f47d09b600bb81a3b1dc8a2d133f36e
372420e88f3daea4707748dabe6477eb2e6e3c22
682767ce3c910cef68ead892a2b65349ad2b42bf
refs/heads/master
2022-11-16T19:26:28.088320
2022-11-08T17:11:40
2022-11-08T17:11:40
157,390,971
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7371794581413269, "alphanum_fraction": 0.7596153616905212, "avg_line_length": 35.70588302612305, "blob_id": "a4510cdbe2635ea89ee67570d2e07a7ca5d32425", "content_id": "7a97a3555aa66254ac9bec08b14e91c5dd1193d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 676, "license_type": "no_license", "max_line_length": 75, "num_lines": 17, "path": "/Работа 15.01.18.md", "repo_name": "amaliyazar/compling", "src_encoding": "UTF-8", "text": "# [ Compling ]\n\n[Задача 1](https://github.com/amaliyazar/compling/blob/master/cycles_1.py)\n\n[Задача 2](https://github.com/amaliyazar/compling/blob/master/cycles_2.py)\n\n[Задача 3](https://github.com/amaliyazar/compling/blob/master/cycles_3.py)\n\n[Задача 4](https://github.com/amaliyazar/compling/blob/master/cycles_4.py)\n\n[Задача 5](https://github.com/amaliyazar/compling/blob/master/cycles_5.py)\n\n[Задача 6](https://github.com/amaliyazar/compling/blob/master/cycles_6.py)\n\n[Задача 7](https://github.com/amaliyazar/compling/blob/master/cycles_7.py)\n\n[Шифр Цезаря](https://github.com/amaliyazar/compling/blob/master/ceaser.py)\n" }, { "alpha_fraction": 0.6761858463287354, "alphanum_fraction": 0.6805421113967896, "avg_line_length": 24.825000762939453, "blob_id": "c96fbf378b116117d28fa5c3c719727f22bb7e6e", "content_id": "baf668122b3c2519cf064c1fdd2e4a8c0b1944b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2194, "license_type": "no_license", "max_line_length": 63, "num_lines": 80, "path": "/stopwords.py", "repo_name": "amaliyazar/compling", "src_encoding": "UTF-8", "text": "import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.tokenize import sent_tokenize\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem.snowball import SnowballStemmer \n\n\ntext=''\nfile_text=open('input1.txt', 'r', encoding=\"utf-8\")\ntext_res = open(\"output1.txt\", \"w\")\nfor line in file_text:\n\ttext+=line\n\n\npunktuation = [\".\", \",\", \";\", \"!\", \"?\", \"«\", \"»\", \"-\"]\n\ndownload_stopwords = stopwords.words('english') #стоп-слова\nstop_text = []\ntokens = word_tokenize(text)\nfor i in tokens:\n\tif i not in download_stopwords and i not in punktuation:\n\t\tstop_text.append(i)\n\n\ntokens = word_tokenize(text) #разбиение на слова\ntok_sent = sent_tokenize(text) #разбиение на предложения\n\nstemsPorter = [] #Стеммер Портера\nporter = PorterStemmer()\nfor w in tokens:\n a = w\n w = porter.stem(w)\n if w != \"\":\n stemsPorter.append(w)\n\nstems = []\nstemmer = SnowballStemmer(\"english\") #Стеммер Snowball\nfor token in tokens:\n token = stemmer.stem(token)\n if token != \"\" and token not in punktuation:\n stems.append(token)\nresult=[]\ntext_split=text.split(\" \")\nfor i in range (len(text_split)):\n result.append(text_split[i])\n if stems[i] not in punktuation:\n result.append(stems[i])\n\n\n\ntext_res.write(\"stopwords:\")\ntext_res.write(str(stop_text))\ntext_res.write(\"\\n\")\ntext_res.write(\"\\n\")\ntext_res.write (\"word_tokenize:\")\ntext_res.write(str(tokens))\ntext_res.write(\"\\n\")\ntext_res.write(\"\\n\")\ntext_res.write(\"sent_tokenize:\")\ntext_res.write(str(tok_sent))\ntext_res.write(\"\\n\")\ntext_res.write(\"\\n\")\ntext_res.write(\"stems:\")\ntext_res.write(str(stems))\ntext_res.write(\"\\n\")\ntext_res.write(\"\\n\")\ntext_res.write(\"Количество слов:\")\ntext_res.write(str(len(text_split)))\ntext_res.write(\"\\n\")\ntext_res.write(\"Количество стоп-слов:\")\ntext_res.write(str(len(stop_text)))\ntext_res.write(\"\\n\")\ntext_res.write(\"Процент стоп-слов:\")\ntext_res.write(str(100-(len(stop_text)/(len(text_split)/100))))\ntext_res.write(\"\\n\")\ntext_res.write(\"\\n\")\ntext_res.write(\"Слово, основа:\")\ntext_res.write(str(result))\ntext_res.close()\n" }, { "alpha_fraction": 0.6893576383590698, "alphanum_fraction": 0.6912751793861389, "avg_line_length": 56.88888931274414, "blob_id": "6696f00257b40e65959757a4acc70a4ba3c089b3", "content_id": "20532faffa5f6af6c7ab45fd5b26991fdea5f953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1602, "license_type": "no_license", "max_line_length": 396, "num_lines": 18, "path": "/counterr.py", "repo_name": "amaliyazar/compling", "src_encoding": "UTF-8", "text": "a=\"\"\"Проект \"Венера\" - организация под началом Жака Фреско, занимающаяся проектом, целью которого является переход к ресурсно-ориентированной экономике, общей автоматизации всех производственных процессов и внедрение достижений научного-технологического прогресса в повседневную жизнь человека. Основная задача проекта – достижение стабильной глобальной цивилизации, которая постоянно развивается. \"\"\"\n\nprint (\"Количество слов:\", len(a.split()))\n\nprint (\"Количество букв а в тексте:\", a.count(\"а\"))\nprint (\"Количество букв о в тексте:\", a.count(\"о\"))\nprint (\"Количество букв р в тексте:\", a.count(\"р\"))\nprint (\"Количество букв х в тексте:\", a.count(\"х\"))\n\npunktuation = [\".\", \",\", \";\", \"!\", \"?\", \"«\", \"»\", \"-\"]\nn=0\nfor i in range (len(a)):\n if a[i]!=\" \" and a[i] not in punktuation:\n n+=1\nprint (\"Процент вхождений буквы а в тексте:\", a.count(\"а\")/n)\nprint (\"Процент вхождений буквы о в тексте:\", a.count(\"о\")/n)\nprint (\"Процент вхождений буквы р в тексте:\", a.count(\"р\")/n)\nprint (\"Процент вхождений буквы х в тексте:\", a.count(\"х\")/n)\n\n" }, { "alpha_fraction": 0.6703600883483887, "alphanum_fraction": 0.6759002804756165, "avg_line_length": 22.29032325744629, "blob_id": "61da6ee5d288b2ef7316a92a66cc94d1abebf5ef", "content_id": "c87f9c88cc74861e717510ff5b6e82be1707c195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "no_license", "max_line_length": 50, "num_lines": 31, "path": "/7.py", "repo_name": "amaliyazar/compling", "src_encoding": "UTF-8", "text": "import pymorphy2\ntext=''\nfile_text=open('input.txt', 'r', encoding=\"utf-8\")\ntext_res = open(\"output.txt\", \"w\")\nfor line in file_text:\n\ttext+=line\ntext_split = text.split(\" \")\n\nmorph = pymorphy2.MorphAnalyzer()\n\nfor a in text_split:\n\tparse = morph.parse(a)[0]\n\tresult = parse.normalized\n\tsklon = parse.inflect({\"gent\"})\n\tlex = parse.lexeme\n\n\ttext_res.write(\"Простой разбор: \")\n\ttext_res.write(str(parse))\n\ttext_res.write(\"\\n\")\n\ttext_res.write (\"Нормализовано: \")\n\ttext_res.write(str(result))\n\ttext_res.write(\"\\n\")\n\ttext_res.write(\"Склоение в родительном:\")\n\ttext_res.write(str(sklon))\n\ttext_res.write(\"\\n\")\n\ttext_res.write(\"Лексемы:\")\n\ttext_res.write(str(lex))\n\ttext_res.write(\"\\n\")\n\ttext_res.write(\"\\n\")\n\ntext_res.close()\n" }, { "alpha_fraction": 0.7923946380615234, "alphanum_fraction": 0.7923946380615234, "avg_line_length": 59.8125, "blob_id": "0912cbeb946cd7106f4e13fa443711ec838f3e25", "content_id": "00f7c610d50ded9b9b4599804351e5978622dc56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1599, "license_type": "no_license", "max_line_length": 461, "num_lines": 16, "path": "/Gephi.md", "repo_name": "amaliyazar/compling", "src_encoding": "UTF-8", "text": "# [ Compling ]\n\n## Создание графа друзей при помощи Gephi\n\n\n![Graph](https://github.com/amaliyazar/compling/blob/master/Graph.pdf)\n### Операции, которые я провела после загрузки графа:\n* Распределение цветов вершин и ребер в зависимости от города проживания человека\n* Изменение размера вершин по критерию relation\n* Разные цвета у имен в зависимости от пола человека\n* Размер текста имени по критерию degree\n* Укладка - Fruchterman Reingold\n\n[Файл с таблицей](https://github.com/amaliyazar/compling/blob/master/Graph.xlsx)\n\nВ итоге, граф разделился на три сообщества, что в принципе довольно-таки верно. Два из этих сообществ разделились по двум городам, где люди в целом взаимосвязаны друг с другом. Но иногда бывает, что укладка графа не совсем удачна, и разделение на сообщество нечетко выражено. Также есть соврешнно отдельные люди, что тоже верно. Я не совсем поняла, что значит фильтр relation, так как количество общих друзей не совпадает с результатами, и частота общения тоже. " }, { "alpha_fraction": 0.6299212574958801, "alphanum_fraction": 0.6377952694892883, "avg_line_length": 17.14285659790039, "blob_id": "540321cc16ef8e905db2a9648aca6f154d616420", "content_id": "41a4d4a3ced365e2431991c0dfff76119c9824f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 40, "num_lines": 7, "path": "/ceaser.py", "repo_name": "amaliyazar/compling", "src_encoding": "UTF-8", "text": "arr=\"абвгдеёжзийклмнопрстуфхцчшщъыьэюяа\"\na=input()\nb=\"\"\nfor i in range (len(a)):\n x=arr.find(a[i])\n b+=arr[x+1]\nprint(b)\n" }, { "alpha_fraction": 0.7587719559669495, "alphanum_fraction": 0.761904776096344, "avg_line_length": 26.517240524291992, "blob_id": "b7036753465dac5656ee5babe5b3e01b45152ced", "content_id": "4a42d0be10657a5ffffb048a55ec0b9bdb682105", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2264, "license_type": "no_license", "max_line_length": 79, "num_lines": 58, "path": "/README.md", "repo_name": "amaliyazar/compling", "src_encoding": "UTF-8", "text": "# [ Compling ]\n\n## Программа, проводящая морфологический анализ текста\n\n[Файл с кодом](https://github.com/amaliyazar/compling/blob/master/7.py)\n\n![Code](https://github.com/amaliyazar/compling/blob/master/code.png)\n### Использованные библиотеки:\n* pymorphy2\n\n### В результате исполнения программы производится:\n* Нормализование слова (перевод в именительный падеж)\n* Склонение в родительном\n* Лексемы\n* Простой Анализ\n\n_Файл с введенным текстом **(Текст Фицджеральда: Великий Гэтсби)**:_\n[Тык](https://github.com/amaliyazar/compling/blob/master/input.txt)\n\n_Файл с выводом:_\n[Тык](https://github.com/amaliyazar/compling/blob/master/output.txt)\n\n> Потому что нужно писать на питоне.\n>\n> Что за бред?\n\n:new_moon:\n:waxing_crescent_moon:\n:first_quarter_moon:\n:waxing_gibbous_moon:\n:full_moon:\n:waning_gibbous_moon:\n:last_quarter_moon:\n:waning_crescent_moon:\n\n## NLTK: стоп-слова, токенизация, стемминг\n\n[Файл с кодом](https://github.com/amaliyazar/compling/blob/master/stopwords.py)\n\n![Code](https://github.com/amaliyazar/compling/blob/master/code1.png)\n\n### Использованные библиотеки:\n* NLTK\n\n### В результате исполнения программы производится:\n* Токенизация текста\n* Извлечение стоп-слов\n* Подсчет количества слов в тексте\n* Подсчет количества слов в тексте без стоп-слов\n* Процент стоп-слов в тексте\n* Разбиение текста на предложения\n* Стемминг (выделение основы слова)\n\n_Файл с введенным текстом **(Текст Фицджеральда: Великий Гэтсби)**:_\n[Тык](https://github.com/amaliyazar/compling/blob/master/input1.txt)\n\n_Файл с выводом:_\n[Тык](https://github.com/amaliyazar/compling/blob/master/output1.txt)\n" } ]
7
nnn112358/robotics_ros
https://github.com/nnn112358/robotics_ros
2271327d61375bc0a8241b3cd56749d9b248d5e1
6980937d80d323731939a92e4e31d608b08711eb
9e026c1d20dc673645ea41aaa4c972a5bef82626
refs/heads/master
2019-01-13T18:57:43.364660
2018-03-04T06:23:13
2018-03-04T06:23:13
95,365,371
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6761239767074585, "alphanum_fraction": 0.7036228775978088, "avg_line_length": 25.034090042114258, "blob_id": "d176d39eaf5f9209df88dd70efef82ca9e7577be", "content_id": "a2ea774619fab014356bb5718204be773aa75e31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2291, "license_type": "no_license", "max_line_length": 81, "num_lines": 88, "path": "/n_pcl_3d_to_2d/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/point_cloud_conversion.h>\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\nusing namespace std;\n\n\ndouble grid_leaf_size = 0.1f;\ndouble Removal_setMeanK = 50.0f;\ndouble Removal_setStddevMulThresh = 1.0f;\n\nros::Subscriber cloud_sub;\nros::Publisher cloud_pub;\n\n\n\nvoid cloud_cb(const sensor_msgs::PointCloud2ConstPtr &input){\n\tpcl::PointCloud<pcl::PointXYZ> cloud;\n\tpcl::PointCloud<pcl::PointXYZ> cloud_filtered;\n\tpcl::PointCloud<pcl::PointXYZ> cloud_filtered2;\n\n\tsensor_msgs::PointCloud2 output;\n\tpcl::fromROSMsg(*input, cloud);\n\n\n\tif( cloud.points.size ()==0){\n\t\tcout<<\"No_points_in clouds\"<<endl;\n\t\tusleep(1*1000*1000);\n\t\treturn;\n\t}\n\n\tfor (size_t i = 0; i < cloud.points.size (); ++i)\t{\n\t\t// cloud.points[i].x = 512 * rand () / (RAND_MAX + 1.0f);\n\t\t// cloud.points[i].y = 512 * rand () / (RAND_MAX + 1.0f);\n\t\tcloud.points[i].z = 1.0;\n\t}\n\n\tpcl::VoxelGrid<pcl::PointXYZ> vox_obj;\n\tvox_obj.setInputCloud(cloud.makeShared());\n\tvox_obj.setLeafSize(grid_leaf_size, grid_leaf_size, grid_leaf_size);\n\tvox_obj.filter(cloud_filtered);\n\n\t// Create the filtering object\n\tpcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor;\n\tsor.setInputCloud (cloud_filtered.makeShared());\n\tsor.setMeanK (Removal_setMeanK);\n\tsor.setStddevMulThresh (Removal_setStddevMulThresh);\n\tsor.filter (cloud_filtered2);\n\n\tpcl::toROSMsg(cloud_filtered2, output);\n\n\toutput.header.stamp= ros::Time::now();\n\n\t// \toutput.header.frame_id = \"point_cloud\";\n\tcloud_pub.publish(output);\n\n\tdouble wait_time=0.030;\n\tusleep(1000.0*1000.0*wait_time);\n}\n\n\nint main(int argc, char **argv){\n\n\tros::init(argc, argv, \"n_pcl_xyz2xy\");\n\tros::NodeHandle private_nh(\"~\");\n\tprivate_nh.param(\"grid_leaf_size\", grid_leaf_size, 0.05);\n\tprivate_nh.param(\"Removal_setMeanK\", Removal_setMeanK, 50.0);\n\tprivate_nh.param(\"Removal_setStddevMulThresh\", Removal_setStddevMulThresh, 1.0);\n\n\tros::NodeHandle nh;\n\n\tcloud_pub = nh.advertise<sensor_msgs::PointCloud2>(\"points_out\", 1);\n\tcloud_sub = nh.subscribe(\"points_in\", 1, cloud_cb);\n\n\tros::spin();\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5213985443115234, "alphanum_fraction": 0.564920961856842, "avg_line_length": 23.705223083496094, "blob_id": "710e4091a5e51e45329a2621a6084f180bf42746", "content_id": "defb31016ca2ef9832bcd60c70fb6439865fd1f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7315, "license_type": "no_license", "max_line_length": 139, "num_lines": 268, "path": "/n_vel_view/src/geometory.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n\r\n#include <math.h>\r\n#include<iostream>\r\n#include<string>\r\n#include<sstream> \r\n#include<fstream>\r\nusing namespace std;\r\n\r\n\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n\r\n\r\n//strをdoubleに変換する\r\ndouble str_double(string str){\t\r\n\tistringstream is; \r\n\tis.str(str); \r\n\tdouble x; \r\n\tis >> x; \r\n\treturn x;\r\n}\r\n\r\n\r\n\r\n//時間を計測する\r\ndouble get_dtime(void){\r\n\tdouble freq = 1000.0/cv::getTickFrequency();\r\n\tstatic int64 old_time = cv::getTickCount();\r\n\tint64 time = cv::getTickCount();\r\n\tdouble dt_msec=(time-old_time)*freq/50.0;\r\n\told_time=time;\r\n\treturn dt_msec;\r\n}\r\n\r\n\r\n\r\n//線分の交差判定関数\r\n//但し,a=bだと交差判定受けるので注意.\r\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y){\r\n\r\n\t// 外積:axb = ax*by - ay*bx\r\n\t// 外積と使用して交差判定を行なう\r\n\tdouble v1 = (a2_x - a1_x) * (b1_y - a1_y) - (a2_y - a1_y) * (b1_x - a1_x);\r\n\tdouble v2 = (a2_x - a1_x) * (b2_y - a1_y) - (a2_y - a1_y) * (b2_x - a1_x);\r\n\tdouble m1 = (b2_x - b1_x) * (a1_y - b1_y) - (b2_y - b1_y) * (a1_x - b1_x);\r\n\tdouble m2 = (b2_x - b1_x) * (a2_y - b1_y) - (b2_y - b1_y) * (a2_x - b1_x);\r\n\r\n\t// +-,-+だったら-値になるのでそれぞれを掛けて確認\r\n\tif((v1*v2<= 0) && (m1*m2 <= 0)){\r\n\t\treturn true; // 2つとも左右にあった\r\n\t}else{\r\n\t\t//cout<<\"checkerror\"<<endl;\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\n//\r\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y){\r\n\r\n\tdouble aa_a=(a2_y-a1_y)/(a2_x-a1_x+1/1000000.0);\r\n\tdouble aa_b=a1_y-aa_a*a1_x;\r\n\t\r\n\tdouble bb_a=(b2_y-b1_y)/(b2_x-b1_x+1/1000000.0);\r\n\tdouble bb_b=b1_y-bb_a*b1_x;\r\n\r\n\tif(a2_x!=a1_x){\r\n\t\t aa_a=(a2_y-a1_y)/(a2_x-a1_x);\r\n\t\t aa_b=a1_y-aa_a*a1_x;\r\n\t}\r\n\tif(b2_x!=b1_x){\r\n\t\t bb_a=(b2_y-b1_y)/(b2_x-b1_x);\r\n\t\t bb_b=b1_y-bb_a*b1_x;\r\n\t}\r\n\r\n\r\n\tif(aa_a!=bb_a){\r\n\t\tcro_x=-(bb_b-aa_b)/(bb_a-aa_a);\r\n\t\tcro_y=cro_x*aa_a+aa_b;\r\n\t\t//cout<<cro_x<<\"_\"<<cro_y<<endl;\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n\r\n\r\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, URG &urg_data){\r\n\r\n\t//URG_Dataの初期化\r\n\tfor(int i=0;i<urg_data.data_num;i++){\r\n\t\turg_data.x[i]=robot.x;\r\n\t\turg_data.y[i]=robot.y;\r\n\t\turg_data.leng[i]=0.0;\r\n\t}\r\n\r\n\t//URG_レーザ\r\n\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\turg_area.x[i]=(-1)*urg_area.leng[i]*sin(i*urg_data.reso+urg_data.start_rad+robot.theta)+robot.x;\r\n\t\turg_area.y[i]=urg_area.leng[i]*cos(i*urg_data.reso+urg_data.start_rad+robot.theta)+robot.y;\r\n\t}\r\n\r\n\tfor(int j=0;j<obst.n;j++){\r\n\t\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\t\tdouble a1_x=obst.x1[j];\r\n\t\t\tdouble a1_y=obst.y1[j];\r\n\t\t\tdouble a2_x=obst.x2[j];\r\n\t\t\tdouble a2_y=obst.y2[j];\r\n\t\t\tdouble b2_x=urg_area.x[i];\r\n\t\t\tdouble b2_y=urg_area.y[i];\r\n\t\t\tdouble b1_x=robot.x;\r\n\t\t\tdouble b1_y=robot.y;\r\n\t\t\t//線分の交差判定\r\n\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\r\n\r\n\t\t\t\t//\tcout<<\"交差:\"<<a1_x<<endl;\r\n\t\t\t\t//attach_flg=1;\r\n\t\t\t\tdouble ata_x=0.0;\r\n\t\t\t\tdouble ata_y=0.0;\r\n\t\t\t\t//線分の交点の算出\r\n\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){//交点のある場合\r\n\r\n\t\t\t\t\tif(urg_data.leng[i]==0){\t//データが入っていないなら\r\n\t\t\t\t\t\t//\tcout<<\"n\"<<(ata_y-robot.y)<<\"_\"<<(ata_x-robot.x)<<endl;\r\n\t\t\t\t\t\t//\tcout<<\"n\"<<((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x))<<endl;\r\n\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\telse{\t\t\t\t\t\t//データが入っていたら\r\n\t\t\t\t\t\tdouble oldleng=urg_data.leng[i];\r\n\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\tif(temp_leng<oldleng){//元より小さければ格納\r\n\t\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t//線分の交点算出はここまで\r\n\t\t\t}\r\n\t\t\t//線分の交差判定はここまで\r\n\t\t}\r\n\t}\r\n}\r\nvoid read_obstacle(string fname,OBSTACLE &obst){\r\n\tcout << \"Obstacle File reading\" << endl;\r\n\r\n\tstring filename(fname.c_str());\r\n\tstring str_line;\r\n\tifstream ifs( filename.c_str() );\r\n\r\n\tif( !ifs ) {\r\n\t\tcout << \"Error:Input data file not found\" << endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tstring obst_in[1024][4]={};\r\n\r\n\tint line=0;\r\n\tint width=0;\r\n\tgetline( ifs, str_line );\r\n\twhile( getline( ifs, str_line ) ){\r\n\t\tstring token;\r\n\t\tistringstream stream( str_line );\r\n\r\n\t\twhile( getline( stream, token, ',' ) ) {\r\n\t\t\tobst_in[line][width]=token;\r\n\t\t\t//\t\tcout << obst_in[line][width] << \",\";\r\n\t\t\twidth++;\r\n\t\t}\r\n\t\tline++;\r\n\t\twidth=0;\r\n\r\n\t\t//\tcout << endl;\r\n\t}\r\n\r\n\tobst.n=line;\r\n\tcout<<\"obst:\" <<obst.n<< endl;\r\n\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\tobst.x1[i]=str_double(obst_in[i][0]);\r\n\t\tobst.y1[i]=str_double(obst_in[i][1]);\r\n\t\tobst.x2[i]=str_double(obst_in[i][2]);\r\n\t\tobst.y2[i]=str_double(obst_in[i][3]);\r\n\t}\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\tcout << obst.x1[i] << \",\";\r\n\t\tcout << obst.x2[i] << \",\";\r\n\t\tcout << obst.y1[i] << \",\";\r\n\t\tcout << obst.y2[i] << \",\";\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\treturn;\r\n}\r\n\r\n\r\n\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta){\r\n double target_r = sqrt(target_x*target_x+target_y*target_y);\r\n \r\n if(target_y>=0){\r\n\ttheta=acos(target_x/target_r);\r\n\ttheta=theta*180.0/PI;\r\n }\r\n else if(target_y<0){\r\n\ttheta=acos(target_x/target_r);\r\n\ttheta=360.0-theta*180.0/PI;\r\n }\r\n \r\n if(theta>=90.0) theta=theta-90.0;\r\n else if(theta<90.0) theta=theta-90.0;\r\n if(theta>180.0) theta=theta-360.0;\r\n\r\n}\r\n\r\n\r\nvoid follow_velocity(double goal_x,double goal_y,double robot_theta,double &speed,double &turn){\r\n\r\n\tdouble urg_x=goal_x;\r\n\tdouble urg_y=goal_y; \r\n\tdouble urg_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble urg_rad=(-1)*atan2(urg_x,urg_y);\r\n\t//ロボット角度の正規化(+2PIに抑制)\r\n\tdouble robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\r\n\t//角度の差分\r\n\tdouble sub_rad=urg_rad-robot_theta_fmod;\r\n\r\n\t//Tanが±πの範囲のため、右回りと左回りを評価\r\n\tif(fabs(urg_rad-robot_theta_fmod)>1.0*PI){\r\n\t\tif(fabs(urg_rad-robot_theta_fmod+4.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t sub_rad=urg_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(urg_rad-robot_theta_fmod-4.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t sub_rad=urg_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(urg_rad-robot_theta_fmod+2.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t sub_rad=urg_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(urg_rad-robot_theta_fmod-2.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t sub_rad=urg_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t}\r\n\r\n\tspeed=urg_l/1.0;\r\n\tif(speed>=0.3) speed=0.3;\r\n\tif(speed<0.1) \tspeed=0.0;\r\n\r\n\tdouble turn_speed=fabs(sub_rad);\r\n//\tturn_speed = -0.0278*pow(x,5) + 0.3025*pow(x,4) - 1.1232*pow(x,3) + 1.4103*pow(x,2) + 0.4428*pow(x,1) + 0.0;\r\n\t\r\n\tif(turn_speed>=PI/3.0)\tspeed=0.0;\r\n\tif(turn_speed<=-PI/3.0)\tspeed=0.0;\r\n\t\r\n\tif(sub_rad>=0) turn=-1*turn_speed;\r\n\telse if((sub_rad<=0)) turn=1*turn_speed;\r\n\r\n\tif(turn_speed>0.1) turn_speed=0.1;\r\n\tif(turn_speed<-0.1) turn_speed=-0.1;\r\n\r\n\t//cout<<\"robo\"<<robot_theta_fmod<<\"\\t\";\r\n\t//cout<<\"atan\"<<sub_rad<<\"\\t\";\r\n\t//cout<<\"sub\"<<turn<<endl;\r\n\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.5810790061950684, "alphanum_fraction": 0.6059669256210327, "avg_line_length": 32.869110107421875, "blob_id": "a4fcf5c6aad484c24b626f7d342bfc155da9147b", "content_id": "d7fd6540b8831590644ac246753a0a9f72f45067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19491, "license_type": "no_license", "max_line_length": 127, "num_lines": 573, "path": "/n_3d_robot_sim/src/rt_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\n\n#include \"gl_main.h\"\n//#include \"read_file.h\"\n#include \"opencv_inc.h\"\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <std_msgs/Float32.h>\n\n#include <string>\n#include <limits>\nusing namespace std;\n#include <sys/time.h>\n#include <unistd.h>\n\n#include <ros/ros.h>\n#include <sensor_msgs/LaserScan.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseArray.h>\n\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_listener.h>\n\n#include <image_transport/image_transport.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <cv_bridge/cv_bridge.h>\n#include <sensor_msgs/Image.h>\n#include <std_msgs/Float32MultiArray.h>\n#include <std_msgs/Float32.h>\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <sensor_msgs/PointCloud2.h>\n\n#include <iostream>\n#include <signal.h>\n\nros::Time lrf_scantime;\nros::Time pantilt_time;\n\n//Robot制御のパラメータ\nextern struct ROBOT myrobot;\nextern struct URG urg_data;\nextern struct MOVE_OBSTACLE move_obst;\n\nextern struct ROBOT myrobot;\nextern struct URG urg_data;\nextern struct URG urg_data2;\nextern struct URG urg_data3;\nextern struct URG urg_area;\nextern struct pantilt pantable;\nstruct pantilt pantable_in;\n\n//extern struct PointCloud pt_xyz;\nextern pcl::PointCloud<pcl::PointXYZRGB> pt_xyz_out;\n\nextern struct MOVE_OBSTACLE move_obst;\nextern IplImage *camera_color;\nextern IplImage *camera_depth;\nextern IplImage *capture_video;\n\ndouble top_urg_data_num = 1080;\ndouble top_urg_deg = 270.0;\ndouble top_urg_reso = 1440.0;\ndouble top_urg_len_max = 30.0;\ndouble top_urg_len_min = 0.2;\n\ndouble classic_urg_data_num = 768;\ndouble classic_urg_deg = 240.0;\ndouble classic_urg_reso = 768.0;\ndouble classic_urg_len_max = 4.0;\ndouble classic_urg_len_min = 0.2;\n\ndouble pantilt_pan_rot_speed = 1.0;\ndouble pantilt_pan_init_deg = 1.0;\ndouble pantilt_tilt_rot_sin_amp = 1.0;\ndouble pantilt_tilt_rot_sin_speed = 1.0;\ndouble pantilt_tilt_init_deg = 1.0;\nextern double robot_z;\nextern string map_fname;\n\ndouble move_obst_num = 3;\nint odometory_tf_out_error = 0;\n\nint load_config(string fname);\n\nextern IplImage *video;\nextern IplImage *depth;\n\ndouble obstacle_z = 0;\nvoid cv_bridge_init();\n\nint view_sim_cap_flg;\nint view_camera_pcl_flg;\nint view_camera_rgb_flg;\nint view_camera_depth_flg;\n\ndouble sim_fps = 10.0;\ndouble pan_unit_scale = 1.0 / 18000.0;\n\n\nextern string robot_model_name;\n\n\nvoid vel_Callback(const geometry_msgs::Twist &vel_msg)\n{\n myrobot.v = vel_msg.linear.x;\n myrobot.w = -vel_msg.angular.z;\n}\n\nvoid panunit_Callback(const geometry_msgs::Twist &vel_msg)\n{\n pantilt_pan_rot_speed = vel_msg.linear.x * pan_unit_scale;\n}\nvoid panspeed_Callback(const std_msgs::Float32::ConstPtr &bottom_msg){\n double data_read = bottom_msg->data;\n pantilt_pan_rot_speed=(int)data_read* pan_unit_scale;\n}\n\n\n\n//時間を計測する\nstatic double get_time2(void)\n{\n double freq = 1000.0 / cv::getTickFrequency();\n static int64 old_time = cv::getTickCount();\n int64 time = cv::getTickCount();\n double dt_msec = (time - old_time) * freq;\n old_time = time;\n return dt_msec;\n}\nvoid GetRPY(const geometry_msgs::Quaternion &q,double &roll, double &pitch, double &yaw){\n tf::Quaternion btq(q.x, q.y, q.z, q.w);\n tf::Matrix3x3(btq).getRPY(roll, pitch, yaw);\n}\nvoid move_obst_Callback(const geometry_msgs::PoseArray &msg){\n\n for (int i = 0; i < move_obst_num; i++)\n {\n move_obst.x[i] += msg.poses[i].position.x;\n move_obst.y[i] += msg.poses[i].position.y;\n double roll, pitch, yaw;\n GetRPY(msg.poses[i].orientation, roll, pitch, yaw);\n move_obst.theta[i] = yaw;\n }\n}\n\nvoid mySigintHandler(int sig)\n{\n\n printf(\"shutdown catch signal %d \\n\", sig);\n ros::shutdown();\n}\n\n\nint main(int argc, char *argv[])\n{\n // string fname = \"setting.ini\";\n // string exe_name = argv[0];\n // load_config(exe_name + \"_\" + fname);\n\n cout << \"sim start\" << endl;\n usleep(10000);\n ros::init(argc, argv, \"docu_lrf_simulator\");\n ros::NodeHandle private_nh(\"~\");\n\n\n private_nh.param(\"robot_model_name\", robot_model_name, std::string(\"default_value\"));\n\n private_nh.param(\"top_urg_data_num\", top_urg_data_num, 1080.0);\n\n private_nh.param(\"top_urg_deg\", top_urg_deg, 270.0);\n private_nh.param(\"top_urg_reso\", top_urg_reso, 1440.0);\n private_nh.param(\"top_urg_len_max\", top_urg_len_max, 30.0);\n private_nh.param(\"top_urg_len_min\", top_urg_len_min, 0.2);\n\n private_nh.param(\"classic_urg_data_num\", classic_urg_data_num, 768.0);\n private_nh.param(\"classic_urg_deg\", classic_urg_deg, 240.0);\n private_nh.param(\"classic_urg_reso\", classic_urg_reso, 768.0);\n private_nh.param(\"classic_urg_len_max\", classic_urg_len_max, 10.0);\n private_nh.param(\"classic_urg_len_min\", classic_urg_len_min, 0.2);\n\n private_nh.param(\"noise_odometory_v_gain\", noise_odometory_v_gain, -0.05);\n private_nh.param(\"noise_odometory_w_gain\", noise_odometory_w_gain, 0.05);\n private_nh.param(\"noise_urg\", noise_urg, 0.010);\n private_nh.param(\"panunit_z\", robot_z, 2.50);\n\n private_nh.param(\"odometory_tf_out_error\", odometory_tf_out_error, 1);\n\n private_nh.param(\"pantilt_pan_rot_speed\", pantilt_pan_rot_speed, 1.50);\n private_nh.param(\"pantilt_pan_init_deg\", pantilt_pan_init_deg, 90.0);\n private_nh.param(\"pantilt_tilt_rot_sin_amp\", pantilt_tilt_rot_sin_amp, 0.0);\n private_nh.param(\"pantilt_tilt_rot_sin_speed\", pantilt_tilt_rot_sin_speed, 5.0);\n private_nh.param(\"pantilt_tilt_init_deg\", pantilt_tilt_init_deg, -19.0);\n\n private_nh.param(\"move_obst_num\", move_obst_num, 20.0);\n\n private_nh.param(\"obstacle_z\", obstacle_z, 3.0);\n\n private_nh.param(\"view_camera_rgb_flg\", view_camera_rgb_flg, 1);\n private_nh.param(\"view_camera_depth_flg\", view_camera_depth_flg, 0);\n private_nh.param(\"view_camera_pcl_flg\", view_camera_pcl_flg, 0);\n private_nh.param(\"view_sim_cap_flg\", view_sim_cap_flg, 0);\n private_nh.param(\"sim_fps\", sim_fps, 40.0);\n private_nh.param(\"pan_unit_scale\", pan_unit_scale, 1.0 / 18000.0);\n\n private_nh.param(\"map_fname\", map_fname, std::string(\"./obstacle.csv\"));\n\n urg_data.data_num = top_urg_data_num;\n urg_data.start_rad = -top_urg_deg / 2.0 / 360.0 * 2 * M_PI;\n urg_data.reso = top_urg_deg / top_urg_data_num / 360.0 * 2 * M_PI;\n urg_data.leng_max = top_urg_len_max;\n urg_data.leng_min = top_urg_len_min;\n\n urg_data2.data_num = classic_urg_data_num;\n urg_data2.start_rad = -classic_urg_deg / 2.0 / 360.0 * 2 * M_PI;\n urg_data2.reso = classic_urg_deg / classic_urg_data_num / 360.0 * 2 * M_PI;\n urg_data2.leng_max = classic_urg_len_max;\n urg_data2.leng_min = classic_urg_len_min;\n\n urg_data3.data_num = classic_urg_data_num;\n urg_data3.start_rad = -classic_urg_deg / 2.0 / 360.0 * 2 * M_PI;\n urg_data3.reso = classic_urg_deg / classic_urg_data_num / 360.0 * 2 * M_PI;\n urg_data3.leng_max = classic_urg_len_max;\n urg_data3.leng_min = classic_urg_len_min;\n\n urg_area.data_num = classic_urg_data_num;\n urg_area.start_rad = urg_data2.start_rad;\n urg_area.reso = urg_data2.reso;\n urg_area.leng_max = classic_urg_len_max;\n urg_area.leng_min = classic_urg_len_min;\n\n move_obst.n = move_obst_num;\n //出力のフレームレート\n // double urg1_rate = 0.005;\n // double urg2_rate = 0.1;\n // double odom_rate = 0.05;\n // double camera_rate = 0.025;\n // double pantilt_rate = 0.10;\n\n ros::NodeHandle n;\n\n ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>(\"odom_real\", 10);\n ros::Publisher odom_pub2 = n.advertise<nav_msgs::Odometry>(\"odom\", 10);\n ros::Publisher scan_pub = n.advertise<sensor_msgs::LaserScan>(\"scan\", 10);\n ros::Publisher scan_pub2 = n.advertise<sensor_msgs::LaserScan>(\"scan1\", 10);\n ros::Publisher scan_pub3 = n.advertise<sensor_msgs::LaserScan>(\"scan2\", 10);\n ros::Publisher panunit_pub = n.advertise<geometry_msgs::Pose>(\"/pantilt\", 10);\n ros::Publisher batt = n.advertise<std_msgs::Float32>(\"battery\", 100);\n ros::Publisher robot_v = n.advertise<std_msgs::Float32>(\"robot_v\", 100);\n ros::Publisher robot_w = n.advertise<std_msgs::Float32>(\"robot_w\", 100);\n \n cv_bridge_init();\n\n Graphics GL;\n cout << \"gl start\" << endl;\n\n usleep(1000 * 1000);\n\n tf::TransformBroadcaster odom_broadcaster;\n tf::TransformBroadcaster broadcaster;\n\n //画像をpublishする。\n ros::Publisher rgb_image_pub = n.advertise<sensor_msgs::Image>(\"docu_camera/rgb_image\", 5);\n ros::Publisher depth_image_pub = n.advertise<sensor_msgs::Image>(\"docu_camera/depth_image\", 5);\n ros::Publisher capture_image_pub = n.advertise<sensor_msgs::Image>(\"docu_camera/sim_capture_image\", 5);\n ros::Publisher pcl_pub = n.advertise<sensor_msgs::PointCloud2>(\"docu_camera/pcl\", 1);\n\n // const std::string panunit_topic_ = \"panunit_speed\";\n // ros::Subscriber panunit_vel = n.subscribe(panunit_topic_, 10, panunit_Callback);\n ros::Subscriber switch_sub = n.subscribe<std_msgs::Float32>(\"panunit_speed\", 10, &panspeed_Callback);\n\n\n const std::string vel_topic_ = \"cmd_vel\";\n ros::Subscriber cmd_vel = n.subscribe(vel_topic_, 10, vel_Callback);\n ros::Subscriber move_obst_cb = n.subscribe(\"move_obst\", 10, move_obst_Callback);\n\n //scan\n unsigned int num_readings = urg_data.data_num;\n double laser_frequency = 50;\n double ranges[num_readings];\n double intensities[num_readings];\n\n unsigned int num_readings2 = urg_data2.data_num;\n double laser_frequency2 = 40;\n double ranges2[num_readings2];\n double intensities2[num_readings2];\n\n ros::Time current_time, last_time;\n current_time = ros::Time::now();\n last_time = current_time;\n ros::Time mid_time;\n\n lrf_scantime = current_time;\n pantilt_time = current_time;\n\n ros::Rate r(sim_fps);\n\n cout << \"ROS start\" << endl;\n\n\n signal(SIGINT, mySigintHandler);\n\n while (n.ok()) {\n ros::spinOnce();\n r.sleep();\n\n\n std_msgs::Float32 msg_float;\n msg_float.data = 50.0f;\n batt.publish(msg_float);\n \n msg_float.data =myrobot.v;\n robot_v.publish(msg_float);\n msg_float.data = myrobot.w;\n robot_w.publish(msg_float);\n \n \n current_time = ros::Time::now();\n //compute odometry in a typical way given the velocities of the robot\n //first, we'll publish the transform over tf\n geometry_msgs::TransformStamped odom_trans;\n geometry_msgs::Quaternion odom_quat;\n odom_trans.header.stamp = current_time;\n odom_trans.header.frame_id = \"odom\";\n odom_trans.child_frame_id = \"base_footprint\";\n\n if (odometory_tf_out_error == 0){\n odom_trans.transform.translation.x = myrobot.y;\n odom_trans.transform.translation.y = -myrobot.x;\n odom_trans.transform.translation.z = 0.0;\n odom_quat = tf::createQuaternionMsgFromYaw(myrobot.theta);\n odom_trans.transform.rotation = odom_quat;\n }\n else {\n odom_trans.transform.translation.x = myrobot.y_dummy;\n odom_trans.transform.translation.y = -myrobot.x_dummy;\n odom_trans.transform.translation.z = 0.0;\n odom_quat = tf::createQuaternionMsgFromYaw(myrobot.theta_dummy);\n odom_trans.transform.rotation = odom_quat;\n }\n\n odom_broadcaster.sendTransform(odom_trans);\n\n nav_msgs::Odometry odom;\n\n odom.header.stamp = current_time;\n odom.header.frame_id = \"odom\";\n odom.child_frame_id = \"base_link\";\n odom.pose.pose.position.x = myrobot.y;\n odom.pose.pose.position.y = -myrobot.x;\n odom.pose.pose.position.z = 0.0;\n odom_quat = tf::createQuaternionMsgFromYaw(myrobot.theta);\n odom.pose.pose.orientation = odom_quat;\n\n odom.twist.twist.linear.x = myrobot.v;\n odom.twist.twist.linear.y = 0.0;\n odom.twist.twist.linear.z = 0.0;\n odom.twist.twist.angular.z = myrobot.w;\n odom_pub.publish(odom); //publish the message\n\n odom.header.stamp = current_time;\n odom.header.frame_id = \"odom\";\n odom.child_frame_id = \"base_link\";\n odom.pose.pose.position.x = myrobot.y_dummy;\n odom.pose.pose.position.y = -myrobot.x_dummy;\n odom.pose.pose.position.z = 0.0;\n odom_quat = tf::createQuaternionMsgFromYaw(myrobot.theta_dummy);\n odom.pose.pose.orientation = odom_quat;\n\n odom.twist.twist.linear.x = myrobot.v;\n odom.twist.twist.linear.y = 0.0;\n odom.twist.twist.linear.z = 0.0;\n odom.twist.twist.angular.z = myrobot.w;\n odom_pub2.publish(odom); //publish the message\n\n double roll_ = 0.0;\n double pitch_ = -pantable.tilt;\n double yaw_ = pantable.pan;\n //\ttf::Quaternion quaternion = tf::createQuaternionFromRPY(yaw_, pitch_, roll_);\n tf::Quaternion quaternion;\n quaternion.setRPY(roll_, pitch_, yaw_);\n\n geometry_msgs::Quaternion quat_Msg;\n tf::quaternionTFToMsg(quaternion, quat_Msg); //この関数はROSのライブラリ\n quat_Msg = tf::createQuaternionMsgFromYaw(yaw_);\n\n geometry_msgs::Pose pose_panunit;\n pose_panunit.position.x = 0;\n pose_panunit.position.y = 0;\n pose_panunit.position.z = 0;\n pose_panunit.orientation = quat_Msg;\n panunit_pub.publish(pose_panunit);\n\n ////////////////////////////////////////////////////\n //populate the LaserScan message\n sensor_msgs::LaserScan scan3;\n scan3.header.stamp = current_time;\n scan3.header.frame_id = \"base_scan3\";\n scan3.angle_min = urg_data3.start_rad;\n scan3.angle_max = urg_data3.start_rad + urg_data3.reso * urg_data3.data_num;\n scan3.angle_increment = urg_data3.reso;\n scan3.time_increment = (1 / laser_frequency2) / (urg_data3.data_num);\n// scan3.time_increment = 0.00;\n\n scan3.range_min = urg_data3.leng_min;\n scan3.range_max = urg_data3.leng_max;\n\n scan3.ranges.resize(num_readings2);\n scan3.intensities.resize(num_readings2);\n for (unsigned int i = 0; i < num_readings2; ++i)\n {\n\n if (urg_data2.leng[i] < 0.01)\n {\n scan3.ranges[i] = std::numeric_limits<float>::quiet_NaN();\n }\n else\n {\n scan3.ranges[i] = urg_data3.leng[i];\n }\n scan3.intensities[i] = 0.0;\n }\n\n scan_pub3.publish(scan3);\n\n ////////////////////////////////////////////////////\n\n ////////////////////////////////////////////////////\n //populate the LaserScan message\n sensor_msgs::LaserScan scan2;\n scan2.header.stamp = current_time;\n scan2.header.frame_id = \"base_scan2\";\n scan2.angle_min = urg_data2.start_rad;\n scan2.angle_max = urg_data2.start_rad + urg_data2.reso * urg_data2.data_num;\n scan2.angle_increment = urg_data2.reso;\nscan2.time_increment = (1 / laser_frequency2) / (urg_data2.data_num);\n // scan2.time_increment = 0.00;\n scan2.range_min = urg_data2.leng_min;\n scan2.range_max = urg_data2.leng_max;\n\n scan2.ranges.resize(num_readings2);\n scan2.intensities.resize(num_readings2);\n for (unsigned int i = 0; i < num_readings2; ++i)\n {\n\n if (urg_data2.leng[i] < 0.01)\n {\n scan2.ranges[i] = std::numeric_limits<float>::quiet_NaN();\n }\n else\n {\n scan2.ranges[i] = urg_data2.leng[i];\n }\n scan2.intensities[i] = 0.0;\n }\n\n scan_pub2.publish(scan2);\n\n ////////////////////////////////////////////////////\n //populate the LaserScan message\n sensor_msgs::LaserScan scan;\n scan.header.stamp = lrf_scantime;\n scan.header.frame_id = \"base_scan\";\n scan.angle_min = urg_data.start_rad;\n scan.angle_max = urg_data.start_rad + urg_data.reso * urg_data.data_num;\n scan.angle_increment = urg_data.reso;\n scan.time_increment = (1 / laser_frequency) / (urg_data.data_num);\n // scan.time_increment = 0.00;\n\n scan.range_min = urg_data.leng_min;\n scan.range_max = urg_data.leng_max;\n\n scan.ranges.resize(num_readings);\n scan.intensities.resize(num_readings);\n for (unsigned int i = 0; i < num_readings; ++i)\n {\n\n if (urg_data.leng[i] < 0.01)\n {\n scan.ranges[i] = std::numeric_limits<float>::quiet_NaN();\n }\n else\n {\n scan.ranges[i] = urg_data.leng[i];\n }\n scan.intensities[i] = 0.0;\n }\n\n scan_pub.publish(scan);\n\n broadcaster.sendTransform(\n tf::StampedTransform(\n tf::Transform(\n tf::Quaternion(0, 0, 0, 1),\n tf::Vector3(0.0, 0.0, 0.01)),\n current_time, \"base_footprint\", \"base_link\"));\n\n broadcaster.sendTransform(\n tf::StampedTransform(\n tf::Transform(\n quaternion,\n tf::Vector3(0.0, 0.0, robot_z)),\n current_time, \"base_link\", \"base_scan\"));\n //tf\n\n broadcaster.sendTransform(\n tf::StampedTransform(\n tf::Transform(\n tf::Quaternion(0, 0, 0, 1),\n tf::Vector3(0.0, 0.0, 0.1)),\n current_time, \"base_link\", \"base_scan2\"));\n\n tf::Quaternion urg_back_qt;\n urg_back_qt.setRPY(0, 0, M_PI);\n\n broadcaster.sendTransform(\n tf::StampedTransform(\n tf::Transform(\n urg_back_qt,\n tf::Vector3(0.0, 0.0, 0.1)),\n current_time, \"base_link\", \"base_scan3\"));\n\n broadcaster.sendTransform(\n tf::StampedTransform(\n tf::Transform(\n tf::Quaternion(0, 0, 0, 1),\n tf::Vector3(0.0, 0.0, robot_z)),\n pantilt_time, \"base_link\", \"camera_link\"));\n\n if (view_camera_rgb_flg != 0)\n {\n cv::Mat cvMat_rgb = cv::cvarrToMat(video);\n sensor_msgs::ImagePtr rgb_image_msg;\n rgb_image_msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", cvMat_rgb).toImageMsg();\n rgb_image_pub.publish(rgb_image_msg);\n }\n\n if (view_camera_depth_flg != 0)\n {\n\n cv::Mat cvMat_depth =cv::cvarrToMat(depth);\n sensor_msgs::ImagePtr depth_image_msg;\n depth_image_msg = cv_bridge::CvImage(std_msgs::Header(), \"mono8\", cvMat_depth).toImageMsg();\n\n depth_image_pub.publish(depth_image_msg);\n }\n\n if (view_camera_pcl_flg != 0)\n {\n sensor_msgs::PointCloud2 pcl_output;\n pcl::toROSMsg(pt_xyz_out, pcl_output);\n pcl_output.header.frame_id = \"camera_link\";\n pcl_pub.publish(pcl_output);\n }\n\n if (view_sim_cap_flg != 0)\n {\n cv::Mat Mat_capture = cv::cvarrToMat(capture_video);\n sensor_msgs::ImagePtr capture_image_msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", Mat_capture).toImageMsg();\n capture_image_pub.publish(capture_image_msg);\n }\n\n last_time = current_time;\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.7788461446762085, "alphanum_fraction": 0.807692289352417, "avg_line_length": 25, "blob_id": "70e034316fe261d205516f06a248fb40d975676b", "content_id": "b89ad4dde855ffdb8fd81eb3339a4a51b794f5a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 104, "license_type": "no_license", "max_line_length": 37, "num_lines": 4, "path": "/myproject/CMakeLists.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(myproject)\nfind_package(catkin REQUIRED)\ncatkin_package()\n" }, { "alpha_fraction": 0.5444584488868713, "alphanum_fraction": 0.5894332528114319, "avg_line_length": 25.407575607299805, "blob_id": "642301205ad35f40e39e5f93b0968f16d674baf3", "content_id": "61b78b55cc908ed725c9dcd112f5f3600c559a2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18618, "license_type": "no_license", "max_line_length": 169, "num_lines": 660, "path": "/n_3d_robot_sim/src/geometory.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\n\n/////////////////////////////////////////////////\n\n#include<stdlib.h>\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <GL/glut.h>\n#include<iostream>\n#include<string>\n#include<sstream> \n#include<fstream>\nusing namespace std;\n\n\n#include \"geometory.h\"\n//#include \"viewgui.h\"\n#include \"opencv_inc.h\"\n#include \"collision_detec_3d.h\"\n\n\n\n//unsigned int urg_data_num=510;\n//double urg_range_deg=240.0;\n//double urg_leng_max=5.0;\n//double urg_leng_min=0.2;\n\ndouble urg_range_deg=240.0;\ndouble urg_leng_max=30.0;\ndouble urg_leng_min=0.2;\n\ndouble noise_odometory_v_gain=-0.10;\ndouble noise_odometory_w_gain=M_PI*0.1;\ndouble noise_urg=0.00;\n\n\n\n\n\ndouble Uniform( void ){\n\treturn ((double)rand()+1.0)/((double)RAND_MAX+2.0);\n}\n\ndouble rand_normal( double mu, double sigma ){\n\tdouble z=sqrt( -2.0*log(Uniform()) ) * sin( 2.0*M_PI*Uniform() );\n\treturn mu + sigma*z;\n}\n\n\nvoid urg_noise( URG &urg_data){\n\n\tfor(int i=0;i<urg_data.data_num;i++){\n\t\tif(urg_data.leng[i]==urg_data.leng_max){\n\t\t\t\turg_data.leng[i]=NAN;\n\t\t}\n\t\telse{\n\t\turg_data.leng[i] = urg_data.leng[i] +urg_data.leng[i]*rand_normal(0,1.0)*noise_urg;\n\t\t}\n\t}\n\n\n}\n\n\n\n//strをdoubleに変換する\ndouble str_double(string str){\t\n\tistringstream is; \n\tis.str(str); \n\tdouble x; \n\tis >> x; \n\treturn x;\n}\n\n\n\n//時間を計測する\n/*double get_dtime(void){\n\tdouble freq = 1000.0/cv::getTickFrequency();\n\tstatic int64 old_time = cv::getTickCount();\n\tint64 time = cv::getTickCount();\n\tdouble dt_msec=(time-old_time)*freq;\n\told_time=time;\n\treturn dt_msec;\n}\n*/\n static double get_dtime()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n\tdouble n_time =tv.tv_sec + tv.tv_usec * 1e-6;\n\tstatic double o_time= n_time;\n\tdouble dt_msec=(n_time-o_time);\n\n\to_time= n_time;\n\n return dt_msec;\n}\n\n\n\n\nvoid normal_calc(double *p1, double *p2, double *p3, double *v_nl){\n double v1[3],v2[3];\n double length_nl;\n //ベクトル計算\n v1[0]=p2[0] - p1[0];\n v1[1]=p2[1] - p1[1];\n v1[2]=p2[2] - p1[2];\n v2[0]=p3[0] - p1[0];\n v2[1]=p3[1] - p1[1];\n v2[2]=p3[2] - p1[2];\n //外積\n v_nl[0] = v1[1] * v2[2] - v1[2] * v2[1];\n v_nl[1] = v1[2] * v2[0] - v1[0] * v2[2];\n v_nl[2] = v1[0] * v2[1] - v1[1] * v2[0];\n //正規化\n\n\n length_nl = sqrt(v_nl[0]*v_nl[0]+v_nl[1]*v_nl[1]+v_nl[2]*v_nl[2]);\n if(length_nl != 0){\n\tv_nl[0] = v_nl[0]/length_nl;\n\tv_nl[1] = v_nl[1]/length_nl;\n\tv_nl[2] = v_nl[2]/length_nl;\n }\n}\n\n\n//線分の交差判定関数\n//但し,a=bだと交差判定受けるので注意.\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y){\n\n\t// 外積:axb = ax*by - ay*bx\n\t// 外積と使用して交差判定を行なう\n\tdouble v1 = (a2_x - a1_x) * (b1_y - a1_y) - (a2_y - a1_y) * (b1_x - a1_x);\n\tdouble v2 = (a2_x - a1_x) * (b2_y - a1_y) - (a2_y - a1_y) * (b2_x - a1_x);\n\tdouble m1 = (b2_x - b1_x) * (a1_y - b1_y) - (b2_y - b1_y) * (a1_x - b1_x);\n\tdouble m2 = (b2_x - b1_x) * (a2_y - b1_y) - (b2_y - b1_y) * (a2_x - b1_x);\n\n\t// +-,-+だったら-値になるのでそれぞれを掛けて確認\n\tif((v1*v2<= 0) && (m1*m2 <= 0)){\n\t\treturn true; // 2つとも左右にあった\n\t}else{\n\t\t//cout<<\"checkerror\"<<endl;\n\t\treturn false;\n\t}\n}\n\n//\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y){\n\n\tdouble aa_a=(a2_y-a1_y)/(a2_x-a1_x+1/1000000.0);\n\tdouble aa_b=a1_y-aa_a*a1_x;\n\n\tdouble bb_a=(b2_y-b1_y)/(b2_x-b1_x+1/1000000.0);\n\tdouble bb_b=b1_y-bb_a*b1_x;\n\n\tif(a2_x!=a1_x){\n\t\taa_a=(a2_y-a1_y)/(a2_x-a1_x);\n\t\taa_b=a1_y-aa_a*a1_x;\n\t}\n\tif(b2_x!=b1_x){\n\t\tbb_a=(b2_y-b1_y)/(b2_x-b1_x);\n\t\tbb_b=b1_y-bb_a*b1_x;\n\t}\n\n\n\tif(aa_a!=bb_a){\n\t\tcro_x=-(bb_b-aa_b)/(bb_a-aa_a);\n\t\tcro_y=cro_x*aa_a+aa_b;\n\t\t//cout<<cro_x<<\"_\"<<cro_y<<endl;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\n//仮想距離センサ\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data){\n\n\t//URG_Dataの初期化\n\tfor(int i=0;i<urg_data.data_num;i++){\n\t\turg_data.x[i]=robot.x;\n\t\turg_data.y[i]=robot.y;\n\t\turg_data.leng[i]=0.0;\n\t}\n\n\t//URG_レーザ\n\tfor(int i=0;i<urg_area.data_num;i++){\n\t\turg_area.x[i]=(-1)*urg_area.leng[i]*sin(i*urg_data.reso+urg_data.start_rad+robot.theta)+robot.x;\n\t\turg_area.y[i]=urg_area.leng[i]*cos(i*urg_data.reso+urg_data.start_rad+robot.theta)+robot.y;\n\t}\n\n\tfor(int j=0;j<obst.n;j++){\n\t\tfor(int i=0;i<urg_area.data_num;i++){\n\t\t\tdouble a1_x=obst.x1[j];\n\t\t\tdouble a1_y=obst.y1[j];\n\t\t\tdouble a2_x=obst.x2[j];\n\t\t\tdouble a2_y=obst.y2[j];\n\t\t\tdouble b2_x=urg_area.x[i];\n\t\t\tdouble b2_y=urg_area.y[i];\n\t\t\tdouble b1_x=robot.x;\n\t\t\tdouble b1_y=robot.y;\n\t\t\t//線分の交差判定\n\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\n\n\t\t\t\t//\tcout<<\"交差:\"<<a1_x<<endl;\n\t\t\t\t//attach_flg=1;\n\t\t\t\tdouble ata_x=0.0;\n\t\t\t\tdouble ata_y=0.0;\n\t\t\t\t//線分の交点の算出\n\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){//交点のある場合\n\n\t\t\t\t\tif(urg_data.leng[i]==0){\t//データが入っていないなら\n\t\t\t\t\t\t//\tcout<<\"n\"<<(ata_y-robot.y)<<\"_\"<<(ata_x-robot.x)<<endl;\n\t\t\t\t\t\t//\tcout<<\"n\"<<((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x))<<endl;\n\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\t\t\t\t\t}\n\n\t\t\t\t\telse{\t\t\t\t\t\t//データが入っていたら\n\t\t\t\t\t\tdouble oldleng=urg_data.leng[i];\n\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\t\t\t\t\t\tif(temp_leng<oldleng){//元より小さければ格納\n\t\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t//線分の交点算出はここまで\n\t\t\t}\n\t\t\t//線分の交差判定はここまで\n\t\t}\n\t}\n\n\tfor(int j=0;j<move_obst.n;j++){\n\t\tfor(int k=0;k<move_obst.m;k++){\n\t\t\tfor(int i=0;i<urg_area.data_num;i++){\n\t\t\t\tdouble a1_x=move_obst.obst_x[j][k];\n\t\t\t\tdouble a1_y=move_obst.obst_y[j][k];\n\t\t\t\tdouble a2_x=move_obst.obst_x[j][k+1];\n\t\t\t\tdouble a2_y=move_obst.obst_y[j][k+1];\n\t\t\t\tdouble b2_x=urg_area.x[i];\n\t\t\t\tdouble b2_y=urg_area.y[i];\n\t\t\t\tdouble b1_x=robot.x;\n\t\t\t\tdouble b1_y=robot.y;\n\t\t\t\t//線分の交差判定\n\t\t\t//\tif((a1_x!=a2_x)&&(a1_y!=a2_y)){\n\t\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\n\n\t\t\t\t\t//\tcout<<\"交差:\"<<a1_x<<endl;\n\t\t\t\t\t//attach_flg=1;\n\t\t\t\t\tdouble ata_x=0.0;\n\t\t\t\t\tdouble ata_y=0.0;\n\t\t\t\t\t//線分の交点の算出\n\t\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){//交点のある場合\n\n\t\t\t\t\t\tif(urg_data.leng[i]==0){\t//データが入っていないなら\n\t\t\t\t\t\t\t//\tcout<<\"n\"<<(ata_y-robot.y)<<\"_\"<<(ata_x-robot.x)<<endl;\n\t\t\t\t\t\t\t//\tcout<<\"n\"<<((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x))<<endl;\n\t\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse{\t\t\t\t\t\t//データが入っていたら\n\t\t\t\t\t\t\tdouble oldleng=urg_data.leng[i];\n\t\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\t\t\t\t\t\t\tif(temp_leng<oldleng){//元より小さければ格納\n\t\t\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t//線分の交点算出はここまで\n\t\t\t//\t}\n\t\t\t\t//線分の交差判定はここまで\n\t\t\t}\n\t\t}\n\t}\n\n\t\n}\n//障害物情報の読み込み\nvoid read_obstacle(OBSTACLE &obst,string fname){\n\tcout << \"Obstacle File reading\" << endl;\n\n\tstring filename(fname.c_str());\n\tstring str_line;\n\tifstream ifs( filename.c_str() );\n\n\tif( !ifs ) {\n\t\tcout << \"Error:Input data file not found\" << endl;\n\t\treturn;\n\t}\n\n\tstring obst_in[4096][4]={};\n\n\tint line=0;\n\tint width=0;\n\tgetline( ifs, str_line );\n\twhile( getline( ifs, str_line ) ){\n\t\tstring token;\n\t\tistringstream stream( str_line );\n\n\t\twhile( getline( stream, token, ',' ) ) {\n\t\t\tobst_in[line][width]=token;\n\t\t\t//\t\tcout << obst_in[line][width] << \",\";\n\t\t\twidth++;\n\t\t}\n\t\tline++;\n\t\twidth=0;\n\n\t\t//\tcout << endl;\n\t}\n\n\tobst.n=line;\n\t//cout<<\"obst:\" <<obst.n<< endl;\n\n\tfor(int i=0;i<obst.n;i++){\n\t\tobst.x1[i]=str_double(obst_in[i][0]);\n\t\tobst.y1[i]=str_double(obst_in[i][1]);\n\t\tobst.x2[i]=str_double(obst_in[i][2]);\n\t\tobst.y2[i]=str_double(obst_in[i][3]);\n\t\tobst.z[i]=obstacle_z;\n\t}\n//\tfor(int i=0;i<obst.n;i++){\n//\t\tcout << obst.x1[i] << \",\";\n//\t\tcout << obst.x2[i] << \",\";\n//\t\tcout << obst.y1[i] << \",\";\n//\t\tcout << obst.y2[i] << \",\";\n//\t\tcout << endl;\n//\t}\n\n\treturn;\n}\n\n//障害物情報の読み込み\nvoid write_obstacle(OBSTACLE &obst,string fname){\n\tcout << \"Obstacle File Write\" << endl;\n\tfor(int i=0;i<obst.n;i++){\n\t\tcout << obst.x1[i] << \",\";\n\t\tcout << obst.x2[i] << \",\";\n\t\tcout << obst.y1[i] << \",\";\n\t\tcout << obst.y2[i] << \",\";\n\t\tcout << endl;\n\t}\n\n\n\tstd::ofstream writing_file;\n\twriting_file.open(fname.c_str(), std::ios::out);\n\n\tstd::cout << \"writing \" << fname << \"...\" << std::endl;\n\n\twriting_file << \"x1,y1,x2,y2\" << endl;\n\n\tfor(int i=0;i<obst.n;i++){\n\t\twriting_file << obst.x1[i] << \",\";\n\t\twriting_file << obst.y1[i] << \",\";\n\t\twriting_file << obst.x2[i] << \",\";\n\t\twriting_file << obst.y2[i] << \",\";\n\t\twriting_file << endl;\n\t}\n\treturn;\n}\n\n\n\n\n\n\n\nvoid To_goal_velocity(double _goal_x,double _goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis,double turn_limit){\n\n\tdouble goal_x=_goal_x-robot_x;\n\tdouble goal_y=_goal_y-robot_y;\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\n\tdouble goal_rad=(-1)*atan2(goal_x,goal_y);\n\t//ロボット角度の正規化(+2PIに抑制)\n\tdouble robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\n\t//角度の差分\n\tdouble sub_rad=goal_rad-robot_theta_fmod;\n\n\t//Tanが±πの範囲のため、右回りと左回りを評価\n\tif(fabs(goal_rad-robot_theta_fmod)>1.0*M_PI){\n\t\tif(fabs(goal_rad-robot_theta_fmod+4.0*M_PI)<fabs(goal_rad-robot_theta_fmod)){\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*M_PI;\n\t\t}\n\t\telse if(fabs(goal_rad-robot_theta_fmod-4.0*M_PI)<fabs(goal_rad-robot_theta_fmod)){\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*M_PI;\n\t\t}\n\t\telse if(fabs(goal_rad-robot_theta_fmod+2.0*M_PI)<fabs(goal_rad-robot_theta_fmod)){\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*M_PI;\n\t\t}\n\t\telse if(fabs(goal_rad-robot_theta_fmod-2.0*M_PI)<fabs(goal_rad-robot_theta_fmod)){\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*M_PI;\n\t\t}\n\t}\n\n\tdouble speed_gain=2.0;\n\tdouble turn_gain=speed_gain*1.0;\n\t//速度の評価関数は実機にあわせて修正すること。\n\tdouble x=goal_l;\n\t//speed = (0.0246*pow(x,4) - 0.1987*pow(x,3) + 0.169*pow(x,2) + 1.7482*pow(x,1)-1.4 );\n\t//\tspeed = (x );\n\n\tspeed=fabs(x)*speed_gain;\n\n\n\t//\tdouble turn_speed=fabs(sub_rad);\n\tdouble r=sub_rad;\n\t//\tdouble turn_speed = fabs(r);\n\tdouble turn_speed = -0.0278*pow(r,5) + 0.3025*pow(r,4) - 1.1232*pow(r,3) + 1.4103*pow(r,2) + 0.4428*pow(r,1) + 0.0;\n\n\tif(sub_rad>=0) turn=-1*turn_speed*turn_gain;\n\telse if((sub_rad<=0)) turn=1*turn_speed*turn_gain;\n\n\t//角度のかい離大きいたらその場で旋回\n\tif(turn_speed>=M_PI/2.0)\tspeed=0.0;\n\tif(turn_speed<=-M_PI/2.0)\tspeed=0.0;\n\n\n\t//最大速度の規定\n\tif(speed>2.0)\tspeed=2.0;\n\tif(goal_l<goal_reach_dis) speed=0.0;\t//到達したら停止\n\n\t//cout<<\"robo\"<<robot_theta_fmod<<\"\\t\";\n\t//cout<<\"atan\"<<sub_rad<<\"\\t\";\n\t//cout<<\"sub\"<<turn<<endl;\n\treturn ;\n}\n\n//仮想距離センサ\nvoid urg_calcurate_3d( ROBOT &robot, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data,double pan,double tilt,double robot_z){\n\t//URG urg_data;\n\n\tdouble length[3000];\n\tdouble area_x[3000];\n\tdouble area_y[3000];\n\tdouble area_z[2500];\t\n\t\n\t//URG_Dataの初期化\n\tfor(int i=0;i<urg_data.data_num;i++){\n\t\t//urg_data.x[i]=robot.x;\n\t\t//urg_data.y[i]=robot.y;\n\t\t//urg_data.leng[i]=0.0;\n\t\tlength[i]=0.0;\n\t}\n\n\t//double robot_z=2.0;\n\t//URG_レーザ\n\tfor(int i=0;i<urg_data.data_num;i++){\n\t\tlength[i]=urg_data.leng_max;\n\n\t\tdouble xx=(-1)*length[i]*sin(i*urg_data.reso+urg_data.start_rad);\n\t\tdouble yy=length[i]*cos(i*urg_data.reso+urg_data.start_rad);\n\t\tdouble zz=0.0;\n\n\t\tdouble xx_r=xx;\n\t\tdouble yy_r=yy*cos(tilt)-zz*sin(tilt);\n\t\tdouble zz_r=yy*sin(tilt)+zz*cos(tilt);\n\n\t\tarea_x[i]=xx_r*cos(pan+robot.theta)-yy_r*sin(pan+robot.theta)+robot.x;\n\t\tarea_y[i]=xx_r*sin(pan+robot.theta)+yy_r*cos(pan+robot.theta)+robot.y;\n\t\tarea_z[i]=zz_r+robot_z;\n\t}\n\n\n\t//底面との衝突判定\n\tfor(int i=0;i<urg_data.data_num;i++){\n\t\txyz line[2];\n\t\txyz tri[3];\n\t\txyz out[2];\n\n\t\t//床の3Dポリゴン\n\t\ttri[0].x=-100;tri[0].y=-100;tri[0].z=0.001;\n\t\ttri[1].x=-100;tri[1].y=+100;tri[1].z=0.001;\n\t\ttri[2].x=+100;tri[2].y=+100;tri[2].z=0.001;\n\t\tline[0].x=area_x[i];line[0].y=area_y[i];line[0].z=area_z[i];\n\t\tline[1].x=robot.x;line[1].y=robot.y;line[1].z=robot_z;\n\t\tbool flag1=collision_tri_line(tri,line,out[0]);\n\n\t\t//床の3Dポリゴン\n\t\ttri[0].x=-100;tri[0].y=-100;tri[0].z=0.001;\n\t\ttri[1].x=+100;tri[1].y=-100;tri[1].z=0.001;\n\t\ttri[2].x=+100;tri[2].y=+100;tri[2].z=0.001;\n\t\tline[0].x=area_x[i];line[0].y=area_y[i];line[0].z=area_z[i];\n\t\tline[1].x=robot.x;line[1].y=robot.y;line[1].z=robot_z;\n\t\tbool flag2=collision_tri_line(tri,line,out[1]);\n\n\t\tif(flag1||flag2){\n\t\t\tdouble dis_min=0.0;\n\t\t\tdouble dis1=sqrt((line[1].x-out[0].x)*(line[1].x-out[0].x)+(line[1].y-out[0].y)*(line[1].y-out[0].y)+(line[1].z-out[0].z)*(line[1].z-out[0].z));\n\t\t\tdouble dis2=sqrt((line[1].x-out[1].x)*(line[1].x-out[1].x)+(line[1].y-out[1].y)*(line[1].y-out[1].y)+(line[1].z-out[1].z)*(line[1].z-out[1].z));\n\t\t\tif(dis1<dis2)\tdis_min=dis1;\n\t\t\telse\t\t\tdis_min=dis2;\n\n\t\t\tif(length[i]==0){\t//データが入っていないなら\n\t\t\t\tlength[i]=dis_min;\n\t\t\t}\n\t\t\telse{\t\t\t\t\t\t//データが入っていたら\n\t\t\t\tdouble old_dis=length[i];\n\t\t\t\tif(dis_min<old_dis){//元より小さければ格納\n\t\t\t\t\tlength[i]=dis_min;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\n\n\t//壁面とのあたり判定\n\tfor(int j=0;j<obst.n;j++){\n\t\tfor(int i=0;i<urg_data.data_num;i++){\n\t\t\txyz line[2];\n\t\t\txyz tri[3];\n\t\t\txyz out[2];\n\n\t\t\t//上半分\n\t\t\ttri[0].x=obst.x1[j];tri[0].y=obst.y1[j];tri[0].z=0.0;\n\t\t\ttri[1].x=obst.x2[j];tri[1].y=obst.y2[j];tri[1].z=0.0;\n\t\t\ttri[2].x=obst.x2[j];tri[2].y=obst.y2[j];tri[2].z=obst.z[j];\n\t\t\t\n\t\t\tline[0].x=area_x[i];line[0].y=area_y[i];line[0].z=area_z[i];\n\t\t\tline[1].x=robot.x;line[1].y=robot.y;line[1].z=robot_z;\n\t\t\t\n\t\t\tbool flag1=collision_tri_line(tri,line,out[0]);\n\n\t\t\t//下半分\n\t\t\ttri[0].x=obst.x1[j];tri[0].y=obst.y1[j];tri[0].z=0.0;\n\t\t\ttri[1].x=obst.x1[j];tri[1].y=obst.y1[j];tri[1].z=obst.z[j];\n\t\t\ttri[2].x=obst.x2[j];tri[2].y=obst.y2[j];tri[2].z=obst.z[j];\n\n\t\t\tline[0].x=area_x[i];line[0].y=area_y[i];line[0].z=area_z[i];\n\t\t\tline[1].x=robot.x;line[1].y=robot.y;line[1].z=robot_z;\n\t\t\t\n\t\t\tbool flag2=collision_tri_line(tri,line,out[1]);\n\t\t\t\n\t\t\tif(flag1||flag2){\n\n\t\t\t\tdouble dis_min=0.0;\n\t\t\t\tdouble dis1=sqrt((line[1].x-out[0].x)*(line[1].x-out[0].x)+(line[1].y-out[0].y)*(line[1].y-out[0].y)+(line[1].z-out[0].z)*(line[1].z-out[0].z));\n\t\t\t\tdouble dis2=sqrt((line[1].x-out[1].x)*(line[1].x-out[1].x)+(line[1].y-out[1].y)*(line[1].y-out[1].y)+(line[1].z-out[1].z)*(line[1].z-out[1].z));\n\t\t\t\tif(dis1<dis2)\tdis_min=dis1;\n\t\t\t\telse\t\t\tdis_min=dis2;\n\n\t\t\t\tif(length[i]==0){\t//データが入っていないなら\n\t\t\t\t\tlength[i]=dis_min;\n\t\t\t\t}\n\t\t\t\telse{\t\t\t\t\t\t//データが入っていたら\n\t\t\t\t\tdouble old_dis=length[i];\n\t\t\t\t\tif(dis_min<old_dis){//元より小さければ格納\n\t\t\t\t\t\tlength[i]=dis_min;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse{\n\t\t\t\t;\n\t\t\t}\n\t\t}\n\t}\n\n\n\t//移動障害物\n\t//高さ方向は考慮しない。\n\tfor(int j=0;j<move_obst.n;j++){\n\t\tfor(int k=0;k<move_obst.m;k++){\n\t\t\tfor(int i=0;i<urg_data.data_num;i++){\n\t\t\t\tdouble a1_x=move_obst.obst_x[j][k];\n\t\t\t\tdouble a1_y=move_obst.obst_y[j][k];\n\t\t\t\tdouble a2_x=move_obst.obst_x[j][k+1];\n\t\t\t\tdouble a2_y=move_obst.obst_y[j][k+1];\n\t\t\t\tdouble b2_x=area_x[i];\n\t\t\t\tdouble b2_y=area_y[i];\n\t\t\t\tdouble b1_x=robot.x;\n\t\t\t\tdouble b1_y=robot.y;\n\t\t\t\t//線分の交差判定\n\t\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\n\t\t\t\t\tdouble ata_x=0.0;\n\t\t\t\t\tdouble ata_y=0.0;\n\t\t\t\t\t//線分の交点の算出\n\t\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){//交点のある場合\n\n\t\t\t\t\t\tif(length[i]==0){\t//データが入っていないなら\n\t\t\t\t\t\t\t//\tcout<<\"n\"<<(ata_y-robot.y)<<\"_\"<<(ata_x-robot.x)<<endl;\n\t\t\t\t\t\t\t//\tcout<<\"n\"<<((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x))<<endl;\n\t\t\t\t\t\t\tlength[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse{\t\t\t\t\t\t//データが入っていたら\n\t\t\t\t\t\t\tdouble oldleng=length[i];\n\t\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\t\t\t\t\t\t\tif(temp_leng<oldleng){//元より小さければ格納\n\t\t\t\t\t\t\t\tlength[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\t//線分の交差判定はここまで\n\n\tfor(int i=0;i<urg_data.data_num;i++){\n\t\turg_data.leng[i]=length[i];\n\t}\n}\n\nvoid robot_move(ROBOT &myrobot,double dt){\n\tdouble dtt=dt+1.0/100000.0;\t\t\t\t\t\t//0除算を回避\n\tdouble ac_v=fabs(myrobot.v-myrobot.real_v)/dtt;\n\tdouble ac_w=fabs(myrobot.w-myrobot.real_w)/dtt;\n\tif(ac_v>=myrobot.ac_trans_limit)\tac_v=myrobot.ac_trans_limit;\n\tif(ac_w>=myrobot.ac_rot_limit)\t\tac_w=myrobot.ac_rot_limit;\n\t\n\tif((myrobot.v-myrobot.real_v)>=0)\t\tmyrobot.real_v+=ac_v*dtt;\n\telse if((myrobot.v-myrobot.real_v)<0)\tmyrobot.real_v-=ac_v*dtt;\n\n\tif((myrobot.w-myrobot.real_w)>=0)\t\tmyrobot.real_w+=ac_w*dtt;\n\telse if((myrobot.w-myrobot.real_w)<0)\tmyrobot.real_w-=ac_w*dtt;\n\n\t//real_v+=real_v*rand_normal(0,1.0)*noise_odometory_v;\n\t//real_w+=real_w*rand_normal(0,1.0)*noise_odometory_w;\n\n\tmyrobot.x+=myrobot.real_v*sin(-myrobot.theta)*dt;\n\tmyrobot.y+=myrobot.real_v*cos(-myrobot.theta)*dt;\n\tmyrobot.theta-=myrobot.real_w*dt;\n\n\n\tconst double odometory_noise_liner=0.0;\n\tconst double odometory_noise_liner_sigma=1.0;\n\tconst double odometory_noise_angle=0.0;\n\tconst double odometory_noise_angle_sigma=1.0;\n\n\tmyrobot.x_dummy+=myrobot.real_v*sin(-myrobot.theta_dummy)*dt*(1+fabs(rand_normal(odometory_noise_liner,odometory_noise_liner_sigma))*noise_odometory_v_gain);\n\tmyrobot.y_dummy+=myrobot.real_v*cos(-myrobot.theta_dummy)*dt*(1+fabs(rand_normal(odometory_noise_liner,odometory_noise_liner_sigma))*noise_odometory_v_gain);\n\tmyrobot.theta_dummy-=myrobot.real_w*dt*(1+fabs(rand_normal(odometory_noise_angle,odometory_noise_angle_sigma))*noise_odometory_w_gain);\n\n}\n\n// rad角度を正規化(-pi〜PI)する\ndouble normalize_theta_rad(double theta) \n{\n\tdouble multiplier;\n\n\tif (theta >= -M_PI && theta < M_PI)\n\t\treturn theta;\n\n\tmultiplier = floor(theta / (2*M_PI));\n\ttheta = theta - multiplier*2*M_PI;\n\tif (theta >= M_PI)\n\t\ttheta -= 2*M_PI;\n\tif (theta < -M_PI)\n\t\ttheta += 2*M_PI;\n\n\treturn theta;\n} \n\n\n" }, { "alpha_fraction": 0.5651814937591553, "alphanum_fraction": 0.5701320171356201, "avg_line_length": 31.70270347595215, "blob_id": "d2cce9713d05d6cf4df96898dfbd7fccfb6d19ed", "content_id": "5e80aab5af3730c2e3ebfb2b5505e9450c8ad56e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1212, "license_type": "no_license", "max_line_length": 187, "num_lines": 37, "path": "/n_map_view/src_opencv/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#############################################################################\n# Makefile for building: ROS_module\n#############################################################################\n\nCXX = g++\nLINK = g++\nCXXFLAGS = `pkg-config --cflags roscpp std_msgs pcl_ros laser_assembler message_filters laser_geometry sensor_msgs geometry_msgs nav_msgs tf ` `pkg-config opencv --cflags opencv` -w -O2 \nINCPATH = \nLIBS = $(SUBLIBS) $(ros_libs_nocolon) `pkg-config --libs opencv` -L/usr/lib -lGL -lGLU -L/usr/X11R6/lib -lglut -lGLU -lGL -lGLEW -lXi -lXmu -lXext -lX11 `sdl-config --cflags --libs` \nros_libs = $(shell pkg-config --libs roscpp std_msgs pcl_ros laser_assembler message_filters laser_geometry sensor_msgs geometry_msgs nav_msgs cv_bridge tf)\nros_libs_nocolon = $(subst -l:,,$(ros_libs))\n\n####### Output directory\n\n####### Files\n\nHEADERS = \nSOURCES = gl_main.cpp \nOBJECTS = gl_main.o \nTARGET = robo_cart_node\n\nfirst: all\n####### Implicit rules\n\n.SUFFIXES:.cpp\n\n.cpp.o:\n\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o $@ $< \n\n\nall: Makefile $(TARGET)\n\n$(TARGET): $(UICDECLS) $(OBJECTS) $(OBJMOC) \n\t$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJMOC) $(LIBS) \n\nclean:\n\trm -f $(OBJECTS) $(TARGET)\n\n\n" }, { "alpha_fraction": 0.684297502040863, "alphanum_fraction": 0.684297502040863, "avg_line_length": 26.227272033691406, "blob_id": "d9d81d5d4dd5428ecc7b0675362cd9ce240c0198", "content_id": "2782a3e3b95bb3fcf1068b7fe943ee6005aaef21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 605, "license_type": "no_license", "max_line_length": 99, "num_lines": 22, "path": "/n_robot_sim_moveobst/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\n\nall:\n\tmake -f Makefile.docu_sim_obstmove\n#\tcp docu_sim_obstmove ../../bin\n#\tcp docu_joy_to_cmd_setting.ini ../../bin\n\nclean:\n\tmake -f Makefile.docu_sim_obstmove clean\n\t\n\t\ninstall:\n\tmkdir -p $(install_prefix)/lib/$(project)\n\tmkdir -p $(install_prefix)/share/$(project)/launch\n\techo \"<package><name>$(project)</name></package>\" > $(install_prefix)/share/$(project)/package.xml\n\ttouch $(install_prefix)/.catkin\n\tcp -a docu_sim_obstmove $(install_prefix)/lib/$(project)\n\t\nuninstall:\n\trm -f $(install_prefix)/lib/$(project)/docu_sim_obstmove\n\t\n\t\n\t\n" }, { "alpha_fraction": 0.565053403377533, "alphanum_fraction": 0.603394091129303, "avg_line_length": 18.662338256835938, "blob_id": "027523ba8b8ce7715600cb1f6931913cadc4a533", "content_id": "66234675e664a002219f9c275bf71e94c59e23e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1675, "license_type": "no_license", "max_line_length": 176, "num_lines": 77, "path": "/n_map_view/src_opencv/geometory.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n/////////////////////////////////////////////////\r\n\r\n#pragma once\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nconst double PI=3.14159265359;\r\n\r\n#define URG_DATA_MAX 1024\r\n#define PATH_POINTS_MAX 1024\r\n\r\nconst unsigned int urg_data_num=680;\r\nconst double urg_range_deg=240.0;\r\nconst double urg_leng_max=5.0;\r\nconst double urg_leng_min=0.1;\r\n\r\n\r\nstruct ROBOT{\r\n\tdouble x;\r\n\tdouble y;\r\n\tdouble theta;\r\n\tdouble v;\r\n\tdouble w;\r\n\r\n\tROBOT(){\r\n\t\tx = 0.0;\r\n\t\ty = 0.0;\r\n\t\tv = 0.0;\r\n\t\tw = 0.0;\r\n\t\ttheta = 0.0;\r\n\t}\r\n\r\n};\r\n\r\nstruct URG{\r\n\tdouble leng[URG_DATA_MAX];\r\n\tdouble x[URG_DATA_MAX];\r\n\tdouble y[URG_DATA_MAX];\r\n\tint data_num;\r\n\tdouble start_rad;\r\n\tdouble reso;\r\n\r\n\tdouble leng_max;\r\n\tdouble leng_min;\r\n\r\n\tURG(){\r\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\r\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*PI;\r\n\t\treso=2*PI/URG_DATA_MAX;\r\n\t\tleng_max=urg_leng_max;\r\n\t\tleng_min=urg_leng_min;\r\n\r\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\r\n\t\t\tx[i] = 0.0;\r\n\t\t\ty[i] = 0.0;\r\n\t\t\tleng[i] = 0.0;\r\n\t\t}\r\n\t}\r\n};\r\nstruct MOVE_PATH{\t\t//経路計画の定義\r\n\tvector<double> x;\r\n\tvector<double> y;\r\n\tunsigned int now_n;\t\t\t//現在の目標(x,y)の番号\r\n};\r\n\r\n//目的地に向かう速度指令値を算出する\r\nvoid To_goal_velocity(double goal_x,double goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis=0.2,double turn_limit=3.14);\r\n\r\n//PATHに沿う速度を出力する\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn);\r\n" }, { "alpha_fraction": 0.5185986161231995, "alphanum_fraction": 0.5554607510566711, "avg_line_length": 26.240663528442383, "blob_id": "c400bae8485d29129ff754d6f7f122f042c374e6", "content_id": "3ffaff10284cd824a0459b70e2aaddeccdc26a86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 33753, "license_type": "no_license", "max_line_length": 154, "num_lines": 1205, "path": "/n_3d_robot_sim/src/gl_win_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\n\n/////////////////////////////////////////////////\n#include <ros/ros.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <sys/time.h>\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <GL/glut.h>\n//#include <GL/glui.h>\n//#include <GL/gl.h>\n//#include <GL/glu.h>\n\n#include <cstdio>\n#include <cmath>\n//#include <GL/freeglut.h>\n\n#include \"GLMetaseq.h\"\nMQO_OBJECT mqoObj;\t// MQOモデル\n#include <iostream>\nusing namespace std;\n\n#include \"gl_main.h\"\n#include \"geometory.h\"\n#include \"opencv_inc.h\"\n#include <float.h>\n\nstring robot_model_name;\n//char robot_fname[]=\"/home/iqit/ros_bin/myproject/robot.mqo\";\n\n//Mainwindow\nint xBegin, yBegin; //mouseのXY座標\nint mButton; //mouseのClick\nfloat distance_gl, twist, elevation, azimuth; //カメラの回転行列\nfloat xOrig, yOrig, zOrig; //カメラの位置\n\n//Subwindow\nfloat distance_gl2, twist2, elevation2, azimuth2;\nfloat xOrig2 = 0.0, yOrig2 = 0.0, zOrig2 = 0.0;\nint mButton2;\nint xBegin2, yBegin2;\n\nint WinID[2]; //ウィンドウID\nint WindowNum = 0;\nint WinFlag[2];\nconst char *WindowName[] = {\"Sim_Main\", \"Camera\"};\n\n//Robot制御のパラメータ\nstruct ROBOT myrobot;\nstruct URG urg_area;\nstruct URG urg_data;\nstruct URG urg_data2;\nstruct URG urg_data3;\nstruct OBSTACLE obst;\nstruct MOVE_OBSTACLE move_obst;\nstring map_fname;\n\nextern double pantilt_pan_rot_speed;\nextern double pantilt_pan_init_deg;\nextern double pantilt_tilt_rot_speed;\nextern double pantilt_tilt_rot_sin_amp;\nextern double pantilt_tilt_rot_sin_speed;\nextern double pantilt_tilt_init_deg;\n\nextern ros::Time lrf_scantime;\nextern ros::Time pantilt_time;\n\nIplImage *capture_video_buf;\nIplImage *capture_video;\n\nint save_flg = 0;\ndouble robot_z = 0.0;\n\nstruct pantilt pantable;\nint color_no = 0;\n\nint wait_sleep(double time)\n{\n usleep(time * 1000.0);\n\n return 0;\n}\nstatic double get_dtime()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n long double n_time = tv.tv_sec + tv.tv_usec * 1e-6;\n static long double o_time = n_time;\n double dt_msec = (n_time - o_time);\n //cout<<dt_msec<<endl;\n o_time = n_time;\n return dt_msec;\n}\n\nstatic double get_time()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n long double n_time = tv.tv_sec + tv.tv_usec * 1e-6;\n return n_time;\n}\n\n\nstatic double gettimeofday_sec()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return tv.tv_sec + (double)tv.tv_usec * 1e-6;\n}\n\nint Graphics::main_3d_process(){\n double old_time=get_time();\n /*URG urg_data_buff;*/\n for(;;){\n\n double now_stock = get_time();\n double now =now_stock-old_time;\n old_time=now_stock;\n\n\n urg_calcurate_3d(myrobot, obst, move_obst, urg_data, pantable.pan, pantable.tilt, robot_z);\n urg_noise(urg_data);\n \n \n if (pantilt_tilt_init_deg == 0)\n {\n double tilt_ros_time = now_stock / pantilt_tilt_rot_sin_speed * 2 * 3.1415;\n double tilt_sin = pantilt_tilt_rot_sin_amp * sin(tilt_ros_time);\n pantable.tilt = tilt_sin;\n }\n\n pantable.pan += pantilt_pan_rot_speed * now;\n pantable.pan = fmod(pantable.pan, 2 * M_PI);\n\n pantilt_time = ros::Time::now();\n lrf_scantime = pantilt_time;\n\n wait_sleep(1);\n }\n\n}\n\n\nvoid robot_view(struct ROBOT &robot)\n{\n\n\n\n double robot_height = 2.0;\n double xx, yy, theta;\n xx = robot.x;\n yy = robot.y;\n theta = robot.theta;\n static double radius = 0.5;\n glColor3f(0, 0, 0); //Yellow\n int grid = 24.0;\n\n glLineWidth(2.0);\n //ロボットの前方を線分で表現\n glBegin(GL_LINES);\n glVertex3f_p(xx, yy, 0.0);\n glVertex3f_p(cos(theta + M_PI / 2.0) * radius + xx, sin(theta + M_PI / 2.0) * radius + yy, 0.0);\n glEnd();\n glBegin(GL_LINES);\n glVertex3f_p(xx, yy, 2.0);\n glVertex3f_p(cos(theta + M_PI / 2.0) * radius + xx, sin(theta + M_PI / 2.0) * radius + yy, robot_height);\n glEnd();\n\n glBegin(GL_LINE_LOOP);\n glVertex3f_p(xx, yy, 0.0);\n glVertex3f_p(xx, yy, 2.0);\n glEnd();\n\n //glBegin(GL_LINE_LOOP);\n //glVertex3f_p(xx-radius, yy-radius, 2.0);\n //glVertex3f_p(xx+radius, yy-radius, 2.0);\n //glVertex3f_p(xx+radius, yy+radius, 2.0);\n //glVertex3f_p(xx-radius, yy+radius, 2.0);\n //glEnd();\n\n //ロボットを円形で表現\n for (int i = 0; i < grid; i++)\n {\n double rad_1 = 2.0 * M_PI * i / grid + theta;\n double rad_2 = 2.0 * M_PI * (i + 1) / grid + theta;\n\n //底面\n glBegin(GL_LINES);\n glVertex3f_p(cos(rad_1) * radius + xx, sin(rad_1) * radius + yy, 0.0);\n glVertex3f_p(cos(rad_2) * radius + xx, sin(rad_2) * radius + yy, 0.0);\n glEnd();\n\n //天井\n // glBegin(GL_LINES);\n // glVertex3f_p(cos(rad_1) * radius + xx, sin(rad_1) * radius + yy, robot_height);\n // glVertex3f_p(cos(rad_2) * radius + xx, sin(rad_2) * radius + yy, robot_height);\n // glEnd();\n }\n\n //Dummyの位置を表示(Odometory誤差あり)\n glColor3f(1, 0, 0); //Red\n for (int i = 0; i < grid; i++)\n {\n double rad_1 = 2.0 * M_PI * i / grid + theta;\n double rad_2 = 2.0 * M_PI * (i + 1) / grid + theta;\n //底面\n glBegin(GL_LINES);\n glVertex3f_p(cos(rad_1) * radius + myrobot.x_dummy, sin(rad_1) * radius + myrobot.y_dummy, 0.0);\n glVertex3f_p(cos(rad_2) * radius + myrobot.x_dummy, sin(rad_2) * radius + myrobot.y_dummy, 0.0);\n glEnd();\n }\n\n glBegin(GL_LINES);\n glVertex3f_p(cos(myrobot.theta_dummy + M_PI / 2.0) * radius + myrobot.x_dummy, sin(myrobot.theta_dummy + M_PI / 2.0) * radius + myrobot.y_dummy, 0.0);\n glVertex3f_p(myrobot.x_dummy, myrobot.y_dummy, 0.0);\n glEnd();\n\n //for(int i = 0; i < grid; i++){\n //\tdouble rad_1= 2.0*M_PI*i/grid*4+theta;\n //\tglBegin(GL_LINES);\n //\tglVertex3f_p(cos(rad_1) * radius+xx, sin(rad_1) * radius+yy, 0.0);\n //\tglVertex3f_p(cos(rad_1) * radius+xx, sin(rad_1) * radius+yy, robot_height);\n //\tglEnd();\n //}\n\n glColor3f(1, 0, 0); //Red\n\n //xx=robot.x;\n //yy=robot.y;\n //theta=robot.theta;\n glLineWidth(1.0);\n}\n\nvoid urg_3d_view(URG &urg_data, double pan, double tilt, double robot_z)\n{\n\n// static int log_cnt = 0;\n// log_cnt++;\n// if (log_cnt > 1)\n// log_cnt = 0;\n\n for (int i = 1; i < urg_data.data_num - 1; i++)\n {\n double dis = urg_data.leng[i];\n if (dis < urg_data.leng_min)\n dis = urg_data.leng_max;\n if (isnan(urg_data.leng[i]))\n dis = urg_data.leng_max;\n\n double xx = (-1) * dis * sin(i * urg_data.reso + urg_data.start_rad);\n double yy = dis * cos(i * urg_data.reso + urg_data.start_rad);\n double zz = 0.0;\n\n double xx_r = xx;\n double yy_r = yy * cos(tilt) - zz * sin(tilt);\n double zz_r = yy * sin(tilt) + zz * cos(tilt);\n\n double xx1 = xx_r * cos(pan + myrobot.theta) - yy_r * sin(pan + myrobot.theta);\n double yy1 = xx_r * sin(pan + myrobot.theta) + yy_r * cos(pan + myrobot.theta);\n double zz1 = zz_r;\n\n double dis2 = urg_data.leng[i - 1];\n if (dis2 < urg_data.leng_min)\n dis2 = urg_data.leng_max;\n if (isnan(urg_data.leng[i - 1]))\n dis2 = urg_data.leng_max;\n\n xx = (-1) * dis2 * sin((i - 1) * urg_data.reso + urg_data.start_rad);\n yy = dis2 * cos((i - 1) * urg_data.reso + urg_data.start_rad);\n zz = 0.0;\n\n xx_r = xx;\n yy_r = yy * cos(tilt) - zz * sin(tilt);\n zz_r = yy * sin(tilt) + zz * cos(tilt);\n\n double xx2 = xx_r * cos(pan + myrobot.theta) - yy_r * sin(pan + myrobot.theta);\n double yy2 = xx_r * sin(pan + myrobot.theta) + yy_r * cos(pan + myrobot.theta);\n double zz2 = zz_r;\n\n if (i > 2)\n {\n glColor4f(0, 0, 1, 0.3);\n\n glBegin(GL_POLYGON);\n glVertex3f_p(myrobot.x, myrobot.y, robot_z);\n glVertex3f_p(myrobot.x + xx1, myrobot.y + yy1, zz1 + robot_z);\n glVertex3f_p(myrobot.x + xx2, myrobot.y + yy2, zz2 + robot_z);\n glEnd();\n }\n glColor3f(0, 1, 1); //Red\n glBegin(GL_POINTS);\n glVertex3f_p(myrobot.x + xx1, myrobot.y + yy1, zz1 + robot_z);\n glEnd();\n\n }\n}\n\n\n\nvoid scene0(){\n\n//\tglTranslated(0.0,0.0,0.0);\n\tglTranslated(myrobot.y,0, myrobot.x);\n\tglRotated(myrobot.theta*180.0/M_PI, 0.0, 1.0, 0.0);\n\tglRotated(-90.0, 1.0, 0.0, 0.0);\n\n\tglEnable( GL_LIGHTING );\t\t// 光源ON\n // mySetLight();\n float material_diffuse[4]={01.0, 0.0, 0.0, 1.0};\n\n float material_ambient[4]={0.30, .30, .30, 1.0};\n float material_specular[4]={0.30, .30, .30, 1.0};\n float material_shiness[4]={0.30, .30, .30, 1.0};\n\n// glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,material_ambient);\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_diffuse);\n// glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);\n// / glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, material_shiness);\n\n\n\tmqoCallObject( mqoObj );\n\tglDisable(GL_LIGHTING);\n\t//glTranslated(0.0, -0.10,- 0.30);\n\n}\n\n\nvoid scene1(double xx,double yy,double theta){\n\tdouble now=get_time();\n\n\tglColor3f(0,0,1);\n\tglBegin(GL_LINE_LOOP);\n\tglVertex3f_p(xx-0.5 ,yy-0.5 ,0 );\n\tglVertex3f_p(xx-0.5 ,yy+0.5 ,0 );\n\tglVertex3f_p(xx+0.5 ,yy+0.5 ,0 );\n\tglVertex3f_p(xx+0.5 ,yy-0.5 ,0 );\n\tglEnd();\n\n //glEnable(GL_LIGHTING);\n //glDisable(GL_LIGHTING);\n\n\tglPushMatrix();\n\tglTranslated(yy,0, xx);\n\tglTranslated(0.0,01.50, 0.0);\n\tglRotated(theta*180.0/M_PI+M_PI/2.0, 0.0, 1.0, 0.0);\n\tglColor3f(0,1,1);\n\t\n walkman(now,0);\n\tglTranslated(0.0,-1.0, 0.0);\n\n\tglPopMatrix();\n\n glDisable(GL_LIGHTING);\n}\n\nvoid main_draw()\n{\n double now = get_dtime(); //msec\n double now_stock = get_time();\n glEnable( GL_DEPTH_TEST );\t\t// 隠面処理の適用\n \n\n //URGセンサの検知:URGの上の表示\n for (int i = 0; i < urg_area.data_num; i++)\n urg_area.leng[i] = urg_leng_max;\n urg_calcurate(myrobot, urg_area, obst, move_obst, urg_data2);\n urg_noise(urg_data2);\n\n struct ROBOT myrobot_back;\n myrobot_back.x=myrobot.x;\n myrobot_back.y=myrobot.y;\n myrobot_back.theta=myrobot.theta+M_PI;\n\n urg_calcurate(myrobot_back, urg_area, obst, move_obst, urg_data3);\n urg_noise(urg_data3);\n\n //glMatrixMode(GL_MODELVIEW);\n\n robot_view(myrobot);\n\n // mySetLight1();\n\n obstacle_view();\n //Robotの表示\n\n move_obstacle_view();\n\n\n for (int i = 0; i < move_obst.n; i++)\n {\n double xx = (move_obst.obst_x[i][0] + move_obst.obst_x[i][2]) / 2.0;\n double yy = (move_obst.obst_y[i][0] + move_obst.obst_y[i][2]) / 2.0;\n double theta = -move_obst.obst_theta[i] + M_PI;\n color_no = i % 4;\n scene1(xx,yy,theta);\n }\n\n\n glPushMatrix();\n scene0();\n glPopMatrix();\n\n glEnable(GL_BLEND);\n\n glPushMatrix();\n\n glColor3f(0, 1, 0); //Red\n glBegin(GL_LINES);\n glVertex3f_p(0, 0, 2);\n glVertex3f_p(0, 0, 0);\n glEnd();\n glPopMatrix();\n\n glColor3f(1, 0, 0); //Red\n\n glPointSize(3.0);\n double length = 15.0;\n\n\n\n //glEnable(GL_BLEND);\n //URGの下の表示\n//////////////////////////////////////////////////\n//////////////////////////////////////////////////\n\n glColor4f(0, 0, 1, 0.3); //Red\n for (int i = 0; i < urg_data2.data_num - 1; i++)\n {\n double length = urg_data2.leng[i];\n\n if (length == 0)\n length = urg_data2.leng_max;\n if (isnan(urg_data2.leng[i]))\n length = urg_data2.leng_max;\n\n double xx1 = (-1) * length * sin(i * urg_data2.reso + urg_data2.start_rad + myrobot.theta);\n double yy1 = length * cos(i * urg_data2.reso + urg_data2.start_rad + myrobot.theta);\n double xx2 = (-1) * length * sin((i + 1) * urg_data2.reso + urg_data2.start_rad + myrobot.theta);\n double yy2 = length * cos((i + 1) * urg_data2.reso + urg_data2.start_rad + myrobot.theta);\n\n glBegin(GL_POLYGON);\n glVertex3f_p(myrobot.x, myrobot.y, 0.2);\n glVertex3f_p(myrobot.x + xx1, myrobot.y + yy1, 0.2);\n glVertex3f_p(myrobot.x + xx2, myrobot.y + yy2, 0.2);\n glEnd();\n }\n\n glColor3f(0, 1, 1); //Red\n\n glPointSize(3.0);\n for (int i = 0; i < urg_data2.data_num - 1; i++)\n {\n double length = urg_data2.leng[i] - 0.1;\n if (length >= 0.2)\n {\n double xx1 = (-1) * length * sin(i * urg_data2.reso + urg_data2.start_rad + myrobot.theta);\n double yy1 = length * cos(i * urg_data2.reso + urg_data2.start_rad + myrobot.theta);\n glBegin(GL_POINTS);\n glVertex3f_p(myrobot.x + xx1, myrobot.y + yy1, 0.2);\n glEnd();\n }\n }\n//////////////////////////////////////////////////\n//////////////////////////////////////////////////\n\n glColor4f(0, 0, 1, 0.3); //Red\n for (int i = 0; i < urg_data3.data_num - 1; i++)\n {\n double length = urg_data3.leng[i];\n\n if (length == 0)\n length = urg_data3.leng_max;\n if (isnan(urg_data3.leng[i]))\n length = urg_data3.leng_max;\n\n double xx1 = (-1) * length * sin(i * urg_data3.reso + urg_data3.start_rad + myrobot.theta+M_PI);\n double yy1 = length * cos(i * urg_data3.reso + urg_data3.start_rad + myrobot.theta+M_PI);\n double xx2 = (-1) * length * sin((i + 1) * urg_data3.reso + urg_data3.start_rad + myrobot.theta+M_PI);\n double yy2 = length * cos((i + 1) * urg_data3.reso + urg_data3.start_rad + myrobot.theta+M_PI);\n\n glBegin(GL_POLYGON);\n glVertex3f_p(myrobot.x, myrobot.y, 0.15);\n glVertex3f_p(myrobot.x + xx1, myrobot.y + yy1, 0.15);\n glVertex3f_p(myrobot.x + xx2, myrobot.y + yy2, 0.15);\n glEnd();\n }\n\n\n glColor3f(0, 1, 0); //Red\n\n glPointSize(3.0);\n for (int i = 0; i < urg_data3.data_num - 1; i++)\n {\n double length = urg_data3.leng[i] - 0.1;\n if (length >= 0.2)\n {\n double xx1 = (-1) * length * sin(i * urg_data3.reso + urg_data3.start_rad + myrobot.theta+M_PI);\n double yy1 = length * cos(i * urg_data3.reso + urg_data3.start_rad + myrobot.theta+M_PI);\n glBegin(GL_POINTS);\n glVertex3f_p(myrobot.x + xx1, myrobot.y + yy1, 0.15);\n glEnd();\n }\n }\n\n//////////////////////////////////////////////////\n//////////////////////////////////////////////////\n\n\n\n\n// urg_calcurate_3d(myrobot, obst, move_obst, urg_data, pantable.pan, pantable.tilt, robot_z);\n// urg_noise(urg_data);\n// lrf_scantime = ros::Time::now();\n\n urg_3d_view(urg_data, pantable.pan, pantable.tilt, robot_z);\n\n\n glPointSize(1.0);\n glColor4f(1, 0, 0, 1.0); //Red\n\n robot_move(myrobot, now);\n\n\n\n glDisable(GL_BLEND);\n\n // glDisable(GL_DEPTH_TEST);\n\n\n}\n\nGraphics::Graphics()\n{\n xOrig = 0.0, yOrig = 0.0, zOrig = 0.0; //始点中心\n gui_start();\n}\n\nGraphics::~Graphics()\n{\n gui_end();\n}\nextern int read_buf_flg;\n\nvoid Graphics::display()\n{\n //cout<<\"display\"<<endl;\n\n glClearColor(1, 1, 1, 1);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glPushMatrix();\n polarview();\n glEnable(GL_DEPTH_TEST);\n\n //メイン描画の関数\n main_draw();\n\n //main_draw2();\n //gl_disp_save();\n read_buf_flg = 1;\n glReadPixels(0, 0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, capture_video_buf->imageData);\n cvConvertImage(capture_video_buf, capture_video, CV_CVTIMG_FLIP + CV_CVTIMG_SWAP_RB);\n read_buf_flg = 0;\n\n glPopMatrix();\n glutSwapBuffers();\n glutPostRedisplay();\n //cout<<now<<endl;;\n wait_sleep(10.0);\n\n // waitKey(10);\n}\n\nvoid Graphics::idle(void)\n{\n\n // glutPostRedisplay();\n\n for (int loop = 0; loop < WindowNum; ++loop)\n {\n if (WinFlag[loop] > 0)\n {\n //printf(\"idle, loop=%d, WinFlag=%d\\n\", loop, WinFlag[loop]);\n glutSetWindow(WinID[loop]);\n glutPostRedisplay(); //再描画 (※display()関数を呼び出す関数 )\n }\n }\n\n wait_sleep(10);\n}\n\nvoid Graphics::myInit(char *progname)\n{\n cout<<\"myInit\"<<endl;\n float aspect = (float)WIDTH / (float)HEIGHT;\n\n cout<<\"myInit GLUT\"<<endl;\n\n glutInitWindowPosition(0, 0);\n glutInitWindowSize(WIDTH, HEIGHT);\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);\n\n cout<<\"myInit OpenCV\"<<endl;\n\n\n capture_video_buf = cvCreateImage(cvSize(WIDTH, HEIGHT), IPL_DEPTH_8U, 3);\n capture_video = cvCreateImage(cvSize(WIDTH, HEIGHT), IPL_DEPTH_8U, 3);\n cout<<\"myInit OpenCV createImage\"<<endl;\n\n //WindowMain\n WinID[WindowNum] = glutCreateWindow(WindowName[WindowNum]);\n printf(\"%d,%d\\n\", WinID[WindowNum], glutGetWindow());\n WinFlag[WindowNum] = 1;\n WindowNum = WindowNum + 1;\n glutDisplayFunc(display);\n glutReshapeFunc(reshape);\n glutIdleFunc(idle);\n\n glClearColor(1, 1, 1, 1);\n\n glutKeyboardFunc(myKbd);\n glutKeyboardUpFunc(myKbdup);\n glutSpecialFunc(mySkey);\n\n glutMouseFunc(myMouse);\n glutMotionFunc(myMotion);\n resetview();\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(45.0, aspect, 1.0, 100.0); //画角等視野の設定\n glMatrixMode(GL_MODELVIEW);\n\n glEnable(GL_LIGHTING);\n glEnable(GL_LIGHT0);\n mySetLight();\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\n if(robot_model_name!=\"default_value\")\n\tmqoObj = mqoCreateObject((char *)robot_model_name.c_str(), 0.012 );\n\n\n // Window2 //\n glutInitWindowPosition(WIDTH, 0);\n glutInitWindowSize(320, 240);\n WinID[WindowNum] = glutCreateWindow(WindowName[WindowNum]);\n printf(\"%d,%d\\n\", WinID[WindowNum], glutGetWindow());\n WinFlag[WindowNum] = 1;\n WindowNum = WindowNum + 1;\n glutDisplayFunc(display2);\n glutReshapeFunc(reshape2);\n glutIdleFunc(idle);\n\n //glutMouseFunc(myMouse2);\n //glutMotionFunc(myMotion2);\n //\tglutSpecialFunc( mySkey2 );\n mySetLight();\n\n pantable.pan = pantilt_pan_init_deg * M_PI * 2.0 / 360.0;\n pantable.tilt = pantilt_tilt_init_deg * M_PI * 2.0 / 360.0;\n\n cout<<\"myInit end:WindowNum=\"<<WindowNum<<endl;\n\n}\n\nvoid Graphics::reshape(int, int)\n{\n //glutReshapeWindow( WIDTH, HEIGHT );\n}\nint Graphics::GUImain()\n{\n //\tread_obstacle(obst);\n //read_moveobstacle(move_obst);\n int argc = 3;\n char *argv[] = {\"program\", \"-display\", \":0.0\"};\n glutInit(&argc, argv);\n\n read_obstacle(obst,map_fname);\n\n cout<<\"obst read\"<<endl;\n char *win_name = \"simulation\";\n myInit(win_name);\n cout<<\"gl init\"<<endl;\n\n\n\n glutMainLoop();\n\n return 0;\n}\n\nvoid Graphics::gui_start()\n{\n th2 = SDL_CreateThread((int (*)(void *))main_3d_process, this);\n th1 = SDL_CreateThread((int (*)(void *))GUImain, this);\n\n}\n\nvoid Graphics::gui_end()\n{\n SDL_KillThread(th1);\n SDL_KillThread(th2);\n}\n\ndouble Graphics::timer_ms()\n{\n\n double timer_ms = cv::getTickCount();\n return timer_ms;\n}\n\nvoid Graphics::myMouse(int button, int state, int x, int y)\n{\n\n double obj_x = 0, obj_y = 0, obj_z = 0;\n\n if (state == GLUT_DOWN)\n {\n switch (button)\n {\n case GLUT_LEFT_BUTTON:\n mButton = button;\n //click_pickup(x,y,obj_x,obj_y,obj_z);\n //goal_y=obj_y;\n //goal_x=obj_x;\n\n break;\n case GLUT_MIDDLE_BUTTON:\n\n break;\n case GLUT_RIGHT_BUTTON:\n\n mButton = button;\n break;\n }\n xBegin = x;\n yBegin = y;\n }\n if (state == GLUT_UP)\n {\n switch (button)\n {\n case GLUT_RIGHT_BUTTON:\n\n break;\n }\n }\n\n return;\n}\n\nvoid Graphics::myMotion(int x, int y)\n{\n\n int xDisp, yDisp;\n\n xDisp = x - xBegin;\n yDisp = y - yBegin;\n\n switch (mButton)\n {\n case GLUT_LEFT_BUTTON:\n azimuth -= (float)xDisp / 2.0;\n elevation -= (float)yDisp / 2.0;\n\n break;\n case GLUT_RIGHT_BUTTON:\n distance_gl -= (float)xDisp / 10.0;\n if (distance_gl < 0.000001)\n distance_gl = 0.000001;\n\n break;\n }\n xBegin = x;\n yBegin = y;\n\n glutPostRedisplay();\n}\n\nvoid Graphics::myKbdup(unsigned char key, int x, int y)\n{\n\n switch (key)\n {\n //case 'w':\t//ROBOTの移動指令\n //\tmyrobot.v=0.0;\n //\tbreak;\n //case 's':\t//ROBOTの移動指令\n //\tmyrobot.v=-0.0;\n //\tbreak;\n //case 'a':\t//ROBOTの移動指令\n //\tmyrobot.w=-0.0;\n //\tbreak;\n //case 'd':\t//ROBOTの移動指令\n //\tmyrobot.w=+0.0;\n //\tbreak;\n }\n}\nvoid Graphics::myKbd(unsigned char key, int x, int y)\n{\n switch (key)\n {\n case 0x1B: //終了\n //\texit(0);\n break;\n\n case 'q': //視点をリセット\n //\texit(0);;\n break;\n\n case 'z': //視点をリセット\n //\tgl_mode++;\n //myrobot.v=0;\n //myrobot.w=0;\n\n break;\n case 'x': //視点をリセット\n //gl_mode--;\n //myrobot.v=0;\n //myrobot.w=0;\n\n break;\n\n //case 'w':\t//ROBOTの移動指令\n //\tmyrobot.v=4.0;\n //\n //\tbreak;\n //case 's':\t//ROBOTの移動指令\n //\tmyrobot.v=-4.0;\n //\n //\tbreak;\n //case 'a':\t//ROBOTの移動指令\n //\tmyrobot.w=-1.0;\n //\tbreak;\n //case 'd':\t//ROBOTの移動指令\n //\tmyrobot.w=+1.0;\n //\tbreak;\n\n case 'c': //ROBOTの移動指令\n if (save_flg == 0)\n save_flg = 1;\n else if (save_flg == 1)\n save_flg = 0;\n break;\n }\n}\n\nvoid Graphics::mySkey(int key, int x, int y)\n{\n switch (key)\n {\n case GLUT_KEY_LEFT:\n xOrig -= 1;\n break;\n case GLUT_KEY_RIGHT:\n xOrig += 1;\n break;\n case GLUT_KEY_UP:\n yOrig += 1;\n break;\n case GLUT_KEY_DOWN:\n yOrig -= 1;\n break;\n case GLUT_KEY_PAGE_UP:\n zOrig += 1;\n break;\n case GLUT_KEY_PAGE_DOWN:\n zOrig -= 1;\n break;\n }\n glutPostRedisplay();\n}\n\nvoid Graphics::resetview(void)\n{\n distance_gl = 50.0;\n twist = 0.0;\n elevation = -60.0;\n azimuth = 25.0;\n}\n\nvoid Graphics::polarview(void)\n{\n //マウスで移動\n glTranslatef(0.0, 0.0, -distance_gl);\n glRotatef(-twist, 0.0, 0.0, 1.0);\n glRotatef(-elevation, 1.0, 0.0, 0.0);\n glRotatef(-azimuth, 0.0, 1.0, 0.0);\n //キーボードで移動\n glTranslatef(xOrig, zOrig, yOrig);\n}\n\nfloat Graphics::click_Depth(int x, int y)\n{ //マウスのX/Y座標からDepthを算出\n float z;\n GLint viewport[4]; //ビューポート\n //デバイス座標系とウィンドウ座標系の変換\n glGetIntegerv(GL_VIEWPORT, viewport); //現在のビューポートを代入\n glReadPixels(x, viewport[3] - y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);\n // デプスバッファの値を返す.\n return z;\n}\n\nvoid Graphics::click_pickup(int x, int y, double &ax, double &ay, double &az)\n{ //マウスのX/Y座標からX/Y/Z座標を算出\n GLdouble modelview[16];\n GLdouble projection[16];\n GLint viewport[4];\n glGetDoublev(GL_MODELVIEW_MATRIX, modelview);\n glGetDoublev(GL_PROJECTION_MATRIX, projection);\n glGetIntegerv(GL_VIEWPORT, viewport);\n GLdouble winX, winY, winZ;\n GLdouble objX = 0.0, objY = 0.0, objZ = -distance_gl + yOrig;\n\n //原点のGLUT座標系を算出\n gluProject(objX, objY, objZ, modelview, projection, viewport, &winX, &winY, &winZ);\n GLdouble objX1, objY1, objZ1;\n //gluUnProject((double)x,(double)y,0.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\n //cout<<\"near_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\n //gluUnProject((double)x,(double)y,1.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\n //cout<<\"far_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\n\n gluUnProject((double)x, (double)y, winZ, modelview, projection, viewport, &objX1, &objY1, &objZ1);\n ax = objX1 - xOrig;\n ay = -(objY1 + zOrig);\n az = objZ1 - yOrig;\n\n //cout<<\"mouse_click:\"<<\"\\t X:\"<<x<<\"\\t Y:\"<<y<<\"\\t x:\"<<ax<<\"\\t y:\"<<ay<<\"\\t z:\"<<az<<\"\"<<endl;\n\n return;\n}\nvoid draw_string(string str, int w, int h, int x0, int y0)\n{\n glColor3d(0.0, 1.0, 0.0);\n // glDisable(GL_LIGHTING);\n // 平行投影にする\n glMatrixMode(GL_PROJECTION);\n// glPushMatrix();\n glLoadIdentity();\n gluOrtho2D(0, w, h, 0);\n glMatrixMode(GL_MODELVIEW);\n//// glPushMatrix();\n glLoadIdentity();\n\n // 画面上にテキスト描画\n glRasterPos2f(x0, y0);\n int size = (int)str.size();\n for (int i = 0; i < size; ++i)\n {\n char ic = str[i];\n glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ic);\n }\n\n// glPopMatrix();\n glMatrixMode(GL_PROJECTION);\n // glPopMatrix();\n glMatrixMode(GL_MODELVIEW);\n}\n\n// 光源の設定を行う関数\nvoid mySetLight(void){\n \n GLfloat light_diffuse[] = {01.0, 01.0, 01.0, 1.0}; // 拡散反射光\n GLfloat light_specular[] = {0.9, 0.9, 0.9, 1.0}; // 鏡面反射光\n GLfloat light_ambient[] = {0.30, 0.30, 0.30, 0.9}; // 環境光\n GLfloat light_position[] = {-10.0, -10.0, -10.0, 1.0}; // 位置と種類\n\n // 光源の設定\n glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); // 拡散反射光の設定\n glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); // 鏡面反射光の設定\n glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); // 環境光の設定\n glLightfv(GL_LIGHT0, GL_POSITION, light_position); // 位置と種類の設定\n\n glShadeModel(GL_SMOOTH); // シェーディングの種類の設定\n glEnable(GL_LIGHT0); // 光源の有効化\n\n\n GLfloat light_position2[] = {10.0, 10.0, 10.0, 1.0}; // 位置と種類\n\n // 光源の設定\n glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse); // 拡散反射光の設定\n glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular); // 鏡面反射光の設定\n glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient); // 環境光の設定\n glLightfv(GL_LIGHT1, GL_POSITION, light_position2); // 位置と種類の設定\n\n glShadeModel(GL_SMOOTH); // シェーディングの種類の設定\n glEnable(GL_LIGHT1); // 光源の有効化\n\n\n}\n\n\n\nvoid Graphics::gl_disp_save()\n{\n static int skip = 0;\n skip++;\n if (save_flg == 0)\n return;\n if (skip % 2 != 0)\n return;\n char *data;\n data = new char[glutGet(GLUT_WINDOW_WIDTH) * glutGet(GLUT_WINDOW_HEIGHT) * 3];\n glReadPixels(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT),\n GL_RGB, GL_UNSIGNED_BYTE, data);\n\n IplImage *imgA;\n imgA = cvCreateImage(cvSize(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)), IPL_DEPTH_8U, 3);\n\n memcpy(imgA->imageData, data, imgA->imageSize);\n\n cvCvtColor(imgA, imgA, CV_BGR2RGB);\n cvFlip(imgA, NULL, 0);\n //\n\n static int cnt = 0;\n char fname[256];\n sprintf(fname, \"img/img_%.5d.png\", cnt);\n\n cvSaveImage(fname, imgA);\n\n cnt++;\n delete[] data;\n cvReleaseImage(&imgA);\n\n //\tsave_flg=0;\n}\n\nvoid move_obstacle_view()\n{\n\n //int t_now= timeGetTime();\t\t//msec\n double t_now = gettimeofday_sec();\n static int t_start = t_now;\n\n static long double now = 0;\n now += (t_now - t_start) / 1000.0;\n //cout<<now<<endl;\n\n double phase = 0;\n double size = 0.4;\n double offset_y = 0.0;\n for (int i = 0; i < move_obst.n; i++)\n {\n //\t\tmove_obst.obst_x[i][0]=move_obst.amp[i]*sin(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.x[i]-size;\n //\t\tmove_obst.obst_y[i][0]=move_obst.amp[i]*cos(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.y[i]-size;\n //\t\tmove_obst.obst_x[i][1]=move_obst.amp[i]*sin(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.x[i]-size;\n //\t\tmove_obst.obst_y[i][1]=move_obst.amp[i]*cos(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.y[i]+size;\n //\t\tmove_obst.obst_x[i][2]=move_obst.amp[i]*sin(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.x[i]+size;\n //\t\tmove_obst.obst_y[i][2]=move_obst.amp[i]*cos(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.y[i]+size;\n //\t\tmove_obst.obst_x[i][3]=move_obst.amp[i]*sin(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.x[i]+size;\n //\t\tmove_obst.obst_y[i][3]=move_obst.amp[i]*cos(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.y[i]-size;\n //\t\tmove_obst.obst_x[i][4]=move_obst.amp[i]*sin(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.x[i]-size;\n //\t\tmove_obst.obst_y[i][4]=move_obst.amp[i]*cos(2*M_PI*now/move_obst.freq[i]-2*M_PI/360.0*move_obst.phase[i])+ move_obst.y[i]-size;\n move_obst.obst_x[i][0] = move_obst.x[i] - size;\n move_obst.obst_x[i][1] = move_obst.x[i] - size;\n move_obst.obst_x[i][2] = move_obst.x[i] + size;\n move_obst.obst_x[i][3] = move_obst.x[i] + size;\n move_obst.obst_x[i][4] = move_obst.x[i] - size;\n\n move_obst.obst_y[i][0] = move_obst.y[i] - size + offset_y;\n move_obst.obst_y[i][1] = move_obst.y[i] + size + offset_y;\n move_obst.obst_y[i][2] = move_obst.y[i] + size + offset_y;\n move_obst.obst_y[i][3] = move_obst.y[i] - size + offset_y;\n move_obst.obst_y[i][4] = move_obst.y[i] - size + offset_y;\n\n move_obst.obst_theta[i] = 2 * M_PI * now / move_obst.freq[i] - 2 * M_PI / 360.0 * move_obst.phase[i] + M_PI;\n\n\n\n }\n //move_obst.move(now);move_obstacle_view\n\n //\tdouble size=0.5;\n glColor3f(1, 1.0, 0); //Red\n\n for (int i = 0; i < move_obst.n; i++)\n {\n glLineWidth(2.0);\n\n glBegin(GL_LINE_LOOP);\n glVertex3f_p(move_obst.obst_x[i][0], move_obst.obst_y[i][0], 0);\n glVertex3f_p(move_obst.obst_x[i][1], move_obst.obst_y[i][1], 0);\n glVertex3f_p(move_obst.obst_x[i][2], move_obst.obst_y[i][2], 0);\n glVertex3f_p(move_obst.obst_x[i][3], move_obst.obst_y[i][3], 0);\n glVertex3f_p(move_obst.obst_x[i][4], move_obst.obst_y[i][4], 0);\n glEnd();\n\n glBegin(GL_LINE_LOOP);\n glVertex3f_p(move_obst.obst_x[i][0], move_obst.obst_y[i][0], 2);\n glVertex3f_p(move_obst.obst_x[i][1], move_obst.obst_y[i][1], 2);\n glVertex3f_p(move_obst.obst_x[i][2], move_obst.obst_y[i][2], 2);\n glVertex3f_p(move_obst.obst_x[i][3], move_obst.obst_y[i][3], 2);\n glVertex3f_p(move_obst.obst_x[i][4], move_obst.obst_y[i][4], 2);\n glEnd();\n\n for (int j = 0; j < move_obst.m; j++)\n {\n glBegin(GL_LINES);\n glVertex3f_p(move_obst.obst_x[i][j], move_obst.obst_y[i][j], 0);\n glVertex3f_p(move_obst.obst_x[i][j], move_obst.obst_y[i][j], 2);\n glEnd();\n }\n\t// glPushMatrix();\n // glTranslated(move_obst.y[i],0, move_obst.x[i]);\n // glTranslated(0.0,2.0, 0.0);\n // glRotated(move_obst.obst_theta[i]*180.0/M_PI, 0.0, 1.0, 0.0);\n \n // glDisable(GL_LIGHTING);\n \n // glEnable( GL_LIGHTING );\t\t// 光源ON\n // // walkman(t_now*1.0,0);\n // glDisable(GL_LIGHTING);\n // glTranslated(-move_obst.obst_y[i][0],0, -move_obst.obst_x[i][0]);\n // glPopMatrix();\n\t \n/*\n glColor3f(1, 0.7, 0); //Red\n\n glBegin(GL_QUADS);\n glVertex3f_p(move_obst.obst_x[i][0], move_obst.obst_y[i][0], 0);\n glVertex3f_p(move_obst.obst_x[i][1], move_obst.obst_y[i][1], 0);\n glVertex3f_p(move_obst.obst_x[i][2], move_obst.obst_y[i][2], 0);\n glVertex3f_p(move_obst.obst_x[i][3], move_obst.obst_y[i][3], 0);\n glEnd();\n\n glBegin(GL_QUADS);\n glVertex3f_p(move_obst.obst_x[i][0], move_obst.obst_y[i][0], 2);\n glVertex3f_p(move_obst.obst_x[i][1], move_obst.obst_y[i][1], 2);\n glVertex3f_p(move_obst.obst_x[i][2], move_obst.obst_y[i][2], 2);\n glVertex3f_p(move_obst.obst_x[i][3], move_obst.obst_y[i][3], 2);\n glEnd();\n\n glBegin(GL_QUADS);\n for (int j = 0; j < move_obst.m; j++)\n {\n glVertex3f_p(move_obst.obst_x[i][j], move_obst.obst_y[i][j], 0);\n glVertex3f_p(move_obst.obst_x[i][j + 1], move_obst.obst_y[i][j + 1], 0);\n glVertex3f_p(move_obst.obst_x[i][j + 1], move_obst.obst_y[i][j + 1], 2);\n glVertex3f_p(move_obst.obst_x[i][j], move_obst.obst_y[i][j], 2);\n }\n glEnd();\n */\n }\n\n glLineWidth(1.0);\n}\n\nvoid obstacle_view()\n{\n glEnable(GL_LIGHTING); // 光源ON\n\n glLineWidth(3.0);\n glColor3f(0.20, 0.2, 0); //Red\n\n double p1[3];\n double p2[3];\n double p3[3];\n double n[3];\n\n float material_diffuse[4]={0.30, 0.30, 0.30, 1.0};\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_diffuse);\n\n for (int i = 0; i < obst.n; i++)\n {\n p1[0] = obst.x1[i], p1[1] = obst.x1[i], p1[2] = 0;\n p2[0] = obst.x1[i], p2[1] = obst.y1[i], p2[2] = obst.z[i];\n p3[0] = obst.x2[i], p3[1] = obst.y2[i], p3[2] = obst.z[i];\n\n normal_calc(p2, p1, p3, n);\n\n glBegin(GL_QUADS);\n glNormal3f((GLfloat)n[0], (GLfloat)n[2], (GLfloat)n[1]);\n glVertex3f_p(obst.x1[i], obst.y1[i], 0);\n glVertex3f_p(obst.x2[i], obst.y2[i], 0);\n glVertex3f_p(obst.x2[i], obst.y2[i], obst.z[i]);\n glVertex3f_p(obst.x1[i], obst.y1[i], obst.z[i]);\n\n glEnd();\n }\n glLineWidth(1.0);\n\n glDisable(GL_LIGHTING);\n\n //Gridの表示\n glColor3f(0.8, 0.8, 0.8);\n for (double x = -20.0; x <= 20.0; x += 1.0)\n {\n for (double y = -20.0; y <= 20.0; y += 1.0)\n {\n glBegin(GL_LINE_LOOP);\n glVertex3f_p(x, y, 0.0);\n glVertex3f_p(x + 1, y, 0.0);\n glVertex3f_p(x + 1, y + 1, 0.0);\n glVertex3f_p(x, y + 1, 0.0);\n glEnd();\n }\n }\n glEnable(GL_LIGHTING);\n\n}\n" }, { "alpha_fraction": 0.5960590839385986, "alphanum_fraction": 0.6004378795623779, "avg_line_length": 20.280487060546875, "blob_id": "faf60e632af71604fe3255d525bc864a09d62301", "content_id": "4099f7fcd679564625cedf9263e293239b4b35fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1981, "license_type": "no_license", "max_line_length": 87, "num_lines": 82, "path": "/n_object_tracking/src_error/read_file.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include <time.h>\r\n\r\n#include <iostream>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <iomanip>\r\n#include <cmath>\r\n#include <fstream>\r\n#include <vector>\r\n#include <sstream>\r\nusing namespace std;\r\n\r\n// 文字列 target が 文字列 pattern で始まっている場合には真、さもなくば偽を返す。\r\nint shrhstr( string target_str, string pattern_str ){\r\n\r\n\tconst char *target=target_str.c_str();\r\n\tconst char *pattern=pattern_str.c_str();\r\n\r\n\treturn target == strstr( target, pattern );\r\n\r\n}//shrhstr\r\n//String型を分割する\r\nstd::vector<std::string> split(std::string str, std::string delim) {\r\n\tstd::vector<std::string> items;\r\n\tstd::size_t dlm_idx;\r\n\tif(str.npos == (dlm_idx = str.find_first_of(delim))) {\r\n\t\titems.push_back(str.substr(0, dlm_idx));\r\n\t}\r\n\twhile(str.npos != (dlm_idx = str.find_first_of(delim))) {\r\n\t\tif(str.npos == str.find_first_not_of(delim)) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\titems.push_back(str.substr(0, dlm_idx));\r\n\t\tdlm_idx++;\r\n\t\tstr = str.erase(0, dlm_idx);\r\n\t\tif(str.npos == str.find_first_of(delim) && \"\" != str) {\r\n\t\t\titems.push_back(str);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn items;\r\n}\r\n\r\n//文字列\r\nint string_Matching(vector<string> lines,string para_name,string &params,string delim){\r\n\r\n\tparams=\"\";\r\n\tfor(int i=0;i<lines.size();i++){\r\n\t\tstring str = lines[i];\r\n\r\n\t\tif(shrhstr(str,\"//\")==true){//コメント読み飛ばし\r\n\t\t\t//cout<<\"e:\"<<str<<endl;\r\n\t\t}\r\n\t\telse{\t\t\t\t\t\t//\\t区切り\r\n\r\n\t\t\tvector<string> result = split(str, delim);\r\n\t\t\tint a=result.size();\r\n\t\t\tif(result.size()==2){\r\n\t\t\t\tif(result[0]==para_name)\t\t\tparams=result[1];\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\t\t//cout<<para_name<<\" \"<<params<<endl;\r\n\r\n\treturn 0;\r\n\r\n}\r\n\r\n//Stringからdoubleへ変換\r\ndouble StringToDouble(string in){\r\n\tistringstream is; //\r\n\tis.str(in); // isに文字列sを割り当てる\r\n\tdouble out;\r\n\tis >> out; // isからxに流す(イメージ)\r\n\treturn out;\r\n}\r\n" }, { "alpha_fraction": 0.6265305876731873, "alphanum_fraction": 0.6653061509132385, "avg_line_length": 21.96875, "blob_id": "b8b0e4c6de0d229030ca577a5210fb7bdc5a4912", "content_id": "e5d59a32685f8d101a09e882cdb27df04093282d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4410, "license_type": "no_license", "max_line_length": 173, "num_lines": 192, "path": "/orbit_pantilt_camera/src/control_orbit_pantilt.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <ros/ros.h>\n#include <std_msgs/Float32.h>\n\n\n#include <tf/transform_broadcaster.h>\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n\n\n#include <unistd.h>\n#include <iostream>\n#include <string>\n#include <sstream>\nusing namespace std;\n\ndouble pan_angle;\ndouble tilt_angle;\n\nstring IntToString(int number){\n\t stringstream ss;\n\t ss << number;\n\t return ss.str();\n}\n\nvoid pantilt_control(double pan,double tilt){\n\n\tdouble pan_limit_max=70.0;\n\tdouble pan_limit_min=-70.0;\n\tdouble tilt_limit_max=30.0;\n\tdouble tilt_limit_min=-35.0;\n\n\tdouble dpan_limit_max=70.0/2.0;\n\tdouble dpan_limit_min=-70.0/2.0;\n\tdouble dtilt_limit_max=30.0/2.0;\n\tdouble dtilt_limit_min=-30.0/2.0;\n\n\tdouble d_limit_min=10.0;\n\n\n\tstatic double pan_target=0;\n\tstatic double tilt_target=0;\n\tstatic double pan_now=0;\n\tstatic double tilt_now=0;\n\n\tstatic double d_pan=0;\n\tstatic double d_tilt=0;\n\n\tif(pan>pan_limit_max) pan=pan_limit_max;\n\telse if(pan<pan_limit_min) pan=pan_limit_min;\n\n\tif(tilt>tilt_limit_max) tilt=tilt_limit_max;\n\telse if(tilt<tilt_limit_min) tilt=tilt_limit_min;\n\n\tpan_target=pan;\n\ttilt_target=tilt;\n\n\td_pan=pan_target-pan_now;\n\td_tilt=tilt_target-tilt_now;\n\n\tif(d_pan>dpan_limit_max) d_pan=dpan_limit_max;\n\telse if(d_pan<dpan_limit_min) d_pan=dpan_limit_min;\n\n\tif(d_tilt>dtilt_limit_max) d_tilt=dtilt_limit_max;\n\telse if(d_tilt<dtilt_limit_min) d_tilt=dtilt_limit_min;\n\t\n\tif(fabs(d_pan)< d_limit_min) d_pan=0.0;\n\tif(fabs(d_tilt)< d_limit_min) d_tilt=0.0;\n\n\tif((pan!=0)&&(tilt!=0)) cout<<\"pan:\"<<d_pan<<\"_tilt:\"<<d_tilt<<\"_pan_now:\"<<pan_now<<\"_tilt_now:\"<<tilt_now<<\"_pan_target:\"<<pan_target<<\"_tilt_target:\"<<tilt_target<<endl;\n\n\tpan_now+=d_pan;\n\ttilt_now+=d_tilt;\n\n\tint sleep_pan_time=8*100*1000;\n\tint sleep_tilt_time=5*100*1000;\n\n\tint pan_degree=d_pan*64.0;\n\tint tilt_degree=d_tilt*64.0;\n\n\tstring pan_str = IntToString(pan_degree);\n\tstring tilt_str = IntToString(tilt_degree);\n\n\tstring cmd_tilt_plus=\"uvcdynctrl -d video1 -s 'Tilt (relative)' \";\n\tstring cmd_tilt_minus=\"uvcdynctrl -d video1 -s 'Tilt (relative)' -- \";\n\t\n\tstring cmd_pan_plus=\"uvcdynctrl -d video1 -s 'Pan (relative)' \";\n\tstring cmd_pan_minus=\"uvcdynctrl -d video1 -s 'Pan (relative)' -- \";\n\n\tif((d_pan>=0)&&(d_pan!=0)){\n\t\tstring cmd=cmd_pan_plus+pan_str;\n\t\tsystem(cmd.c_str());\n\t\tcout<<cmd<<endl;\n \tusleep(sleep_pan_time);\n\t}\n\telse if((d_pan<0)&&(d_pan!=0)){\n\t\tstring cmd=cmd_pan_minus+pan_str;\n\t\tsystem(cmd.c_str());\n\t\tcout<<cmd<<endl;\n \tusleep(sleep_pan_time);\n\t}\n\n\tif((d_tilt>=0)&&(d_tilt!=0)){\n\t\tstring cmd=cmd_tilt_plus+tilt_str;\n\t\tsystem(cmd.c_str());\n\t\tcout<<cmd<<endl;\n \tusleep(sleep_tilt_time);\n\t}\n\telse if((d_tilt<0)&&(d_tilt!=0)){\n\t\tstring cmd=cmd_tilt_minus+tilt_str;\n\t\tsystem(cmd.c_str());\n\t\tcout<<cmd<<endl;\n \tusleep(sleep_tilt_time);\n\t}\n\n\n}\n\nvoid panCallback(const std_msgs::Float32::ConstPtr& msg){\n //ROS_INFO(\"I heard: [%ld]\", msg->data);\n\tstd::cout<<msg->data<<std::endl;\n\tpan_angle=msg->data;\n\treturn;\n}\n\nvoid tiltCallback(const std_msgs::Float32::ConstPtr& msg){\n //ROS_INFO(\"I heard: [%ld]\", msg->data);\n\tstd::cout<<msg->data<<std::endl;\n\ttilt_angle=msg->data;\n\n\treturn;\n}\n\n\nint main(int argc, char* argv[]) {\n\n\tstring cmd1=\"uvcdynctrl -d video1 -s 'Pan Reset' 0\";\n string cmd2=\"uvcdynctrl -d video1 -s 'Tilt Reset' 0\";\n\n//\tstring cmd3=\"uvcdynctrl -d video1 -s 'Tilt (relative)' 1024\";\n// string cmd4=\"uvcdynctrl -d video1 -s 'Tilt (relative)' -- -1024\";\n\n//\tstring cmd5=\"uvcdynctrl -d video1 -s 'Pan (relative)' 2240\";\n// string cmd6=\"uvcdynctrl -d video1 -s 'Pan (relative)' -- -2240\";\n\n\tint sleep_pan_reset_time=4*1000*1000;\n\tint sleep_tilt_reset_time=3*1000*1000;\n\n//\tint sleep_pan_time=4*100*1000;\n//\tint sleep_tilt_time=3*100*1000;\n\n\tsystem(cmd1.c_str());\n\tusleep(sleep_pan_reset_time);\n\tsystem(cmd2.c_str());\n\tusleep(sleep_tilt_reset_time);\n\tsystem(cmd1.c_str());\n\tusleep(sleep_pan_reset_time);\n\n\tconst std::string ros_name = \"orbit_pantilt\";\n\tros::init(argc, argv, ros_name);\n\n\n\tros::NodeHandle n;\n\nconst std::string pan_topic = \"camera_pan_angle\";\nros::Subscriber pan_subscriber = n.subscribe (pan_topic, 10, panCallback);\n\nconst std::string tilt_topic = \"camera_tilt_angle\";\nros::Subscriber tilt_subscriber = n.subscribe (tilt_topic, 10, tiltCallback);\n\n\n//\tint sleep_time=1*1000*1000;\n\n\tros::Rate r(10.0);\n\n\twhile(n.ok()){\n\t\tros::spinOnce();\n\t\tpantilt_control(pan_angle,tilt_angle);\n\n\t\t//usleep(sleep_time);\n\n\t}\n\n\n\n\n\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6125555038452148, "alphanum_fraction": 0.6157260537147522, "avg_line_length": 34.53488540649414, "blob_id": "4865b21cb70a7937d098cd81edfb879200ad2432", "content_id": "8b4269b58a695456b499c4a97297d1a70eb14a53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1649, "license_type": "no_license", "max_line_length": 111, "num_lines": 43, "path": "/old/map_editor_simple/src/opencv_inc.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n\r\n#ifdef _WIN32\r\n\t\t#include <opencv2/opencv.hpp>\r\n\t\tusing namespace cv;\r\n\r\n\t\t// バージョン取得\r\n\t\t#define CV_VERSION_STR CVAUX_STR(CV_MAJOR_VERSION) CVAUX_STR(CV_MINOR_VERSION) CVAUX_STR(CV_SUBMINOR_VERSION)\r\n\r\n\t\t// ビルドモード\r\n\t\t#ifdef _DEBUG\r\n\t\t#define CV_EXT_STR \"d.lib\"\r\n\t\t#else\r\n\t\t#define CV_EXT_STR \".lib\"\r\n\t\t#endif\r\n\r\n\t\t// ライブラリのリンク(不要な物はコメントアウト)\r\n\t\t#pragma comment(lib, \"opencv_core\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t#pragma comment(lib, \"opencv_highgui\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_imgproc\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_calib3d\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_gpu\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_video\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_objdetect\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_features2d\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_flann\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_ffmpeg\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_ts\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_contrib\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_ml\" CV_VERSION_STR CV_EXT_STR)\r\n\t\t//#pragma comment(lib, \"opencv_legacy\" CV_VERSION_STR CV_EXT_STR)\r\n\r\n#else\r\n\t\t//Linux\r\n#include <cv.h>\r\n#include <highgui.h>\r\n#include <time.h>\r\nusing namespace cv;\r\n\r\n#endif\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6148325204849243, "alphanum_fraction": 0.630382776260376, "avg_line_length": 29.88888931274414, "blob_id": "a4b40b2d61837e2afe50b80b702c3da0a762e0ce", "content_id": "3d3fe158b2af758be485bca0aa7b5e99d257b027", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 838, "license_type": "no_license", "max_line_length": 80, "num_lines": 27, "path": "/n_3d_robot_sim/readme.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "3D LRF Simulator\n\n\n rosnode info /n_3d_robot_sim \n--------------------------------------------------------------------------------\nNode [/n_3d_robot_sim]\nPublications: \n * /scan2 [sensor_msgs/LaserScan]\n * /scan1 [sensor_msgs/LaserScan]\n * /docu_camera/pcl [sensor_msgs/PointCloud2]\n * /odom [nav_msgs/Odometry]\n * /scan [sensor_msgs/LaserScan]\n * /pantilt [geometry_msgs/Pose]\n * /battery [std_msgs/Float32]\n * /rosout [rosgraph_msgs/Log]\n * /tf [tf2_msgs/TFMessage]\n * /robot_v [std_msgs/Float32]\n * /robot_w [std_msgs/Float32]\n * /odom_real [nav_msgs/Odometry]\n * /docu_camera/sim_capture_image [sensor_msgs/Image]\n * /docu_camera/depth_image [sensor_msgs/Image]\n * /docu_camera/rgb_image [sensor_msgs/Image]\n\nSubscriptions: \n * /cmd_vel [geometry_msgs/Twist]\n * /panunit_rot [unknown type]\n * /move_obst [geometry_msgs/PoseArray]\n\n\n" }, { "alpha_fraction": 0.7209302186965942, "alphanum_fraction": 0.7286821603775024, "avg_line_length": 19.600000381469727, "blob_id": "50f0f88653718a5cd5cde8ddfcdc3fdbcdcd69aa", "content_id": "2809f320d92e573e71893f86c4c2ba2b55746342", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1032, "license_type": "no_license", "max_line_length": 102, "num_lines": 50, "path": "/n_localpathplan/CMakeLists.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(n_localpathplan)\n\n## Find catkin macros and libraries\n## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)\n## is used, also find other catkin packages\nfind_package(catkin REQUIRED COMPONENTS\n geometry_msgs\n nav_msgs\n roscpp\n rospy\n sensor_msgs\n tf\n cv_bridge\n pcl_ros \n std_msgs \n laser_assembler \n actionlib \n message_filters \n laser_geometry \n nav_msgs\n)\n\n\n\n\ncatkin_package()\n\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n ${OpenCV_INCLUDE_DIRS}\n ${OpenGL_INCLUDE_DIRS}\n)\nadd_executable(n_localpathplan_node\n src/ros_main.cpp\n src/geometory.cpp\n\n)\n\nadd_dependencies(n_localpathplan_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n## Specify libraries to link a library or executable target against\ntarget_link_libraries(n_localpathplan_node \n ${catkin_LIBRARIES}\n ${OpenCV_LIBRARIES}\n ${OpenGL_LIBRARIES}\n ${GLUT_LIBRARY}\n -lglut -lGLU -lGL -lm -lSDL -L/usr/X11R6/lib -lglut -lGLU -lGL -lXi -lXmu -lXext -lX11\n )\n\n\n" }, { "alpha_fraction": 0.5275298953056335, "alphanum_fraction": 0.5614254474639893, "avg_line_length": 23.492372512817383, "blob_id": "46f0bff3b2692ed979f8ca9c38f14b95dc222eb5", "content_id": "8513c2006cb86498e5dff9ff45a1c45619258a8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19278, "license_type": "no_license", "max_line_length": 137, "num_lines": 721, "path": "/n_localpathplan/src2/viewgui.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By\r\n/////////////////////////////////////////////////\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <time.h>\r\n#include <math.h>\r\n#include <GL/glut.h>\r\n#include <GL/gl.h>\r\n#include <GL/glu.h>\r\n\r\n#include <iostream>\r\nusing namespace std;\r\n\r\n#include \"viewgui.h\"\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n\r\n//各種OpenGL変数宣言\r\n//const int WIDTH = 900, HEIGHT = WIDTH;//ウィンドウのサイズ\r\nint xBegin, yBegin; //mouseのXY座標\r\nint mButton; //mouseのClick\r\nfloat distance_gl, twist, elevation, azimuth; //カメラの回転行列\r\nfloat xOrig, yOrig, zOrig; //カメラの位置\r\n\r\n//Robot制御のパラメータ\r\nstruct ROBOT myrobot;\r\n//struct URG urg_area;\r\nstruct URG urg_data;\r\nstruct URG urg_data2;\r\n//struct OBSTACLE obst;\r\nstruct MOVE_PATH path;\r\nstruct MOVE_PATH path_log;\r\ndouble path_x[2000][100] = {};\r\ndouble path_y[2000][100] = {};\r\ndouble path_cost[2000] = {};\r\nint path_size = 0;\r\n\r\nint gl_mode = 0; //モードを切り替える。\r\nint path_flg = 0;\r\ndouble goal_x = 0.0, goal_y = 0.0;\r\ndouble goal_theta = 0.0;\r\ndouble best_v = 0, best_w = 0;\r\n\r\ndouble target_v=0.0;\r\ndouble target_w=0.0;\r\n\r\ndouble goal_reach_dis = 0.1; //ゴールに到達したとする距離\r\ndouble turn_limit = PI / 2.0; //その角度以上で旋回\r\n\r\nvoid urg_view(ROBOT &robot, URG &urg_data);\r\n\r\nvoid path_view();\r\n\r\nint wait_sleep(int time)\r\n{\r\n usleep(time * 1000);\r\n return 0;\r\n}\r\n\r\nvoid robot_view(struct ROBOT &robot)\r\n{\r\n double xx, yy, theta;\r\n xx = robot.x;\r\n yy = robot.y;\r\n theta = robot.theta;\r\n static double radius = 0.5;\r\n glColor3f(1, 1, 0.5); //Yellow\r\n int grid = 24.0;\r\n\r\n glBegin(GL_LINES);\r\n glVertex3f(xx, yy, 0.0);\r\n glVertex3f(cos(theta + PI / 2.0) * radius + xx, sin(theta + PI / 2.0) * radius + yy, 0.0);\r\n glEnd();\r\n\r\n for (int i = 0; i < grid; i++)\r\n {\r\n double rad_1 = 2.0 * PI * i / grid + theta;\r\n double rad_2 = 2.0 * PI * (i + 1) / grid + theta;\r\n glBegin(GL_LINES);\r\n glVertex3f(cos(rad_1) * radius + xx, sin(rad_1) * radius + yy, 0.0);\r\n glVertex3f(cos(rad_2) * radius + xx, sin(rad_2) * radius + yy, 0.0);\r\n glEnd();\r\n }\r\n}\r\n\r\nvoid robot_log_view(double dt)\r\n{\r\n static double time = 0;\r\n double time_rate = 0.10; //ログのサンプルレート刻み(sec)\r\n time += dt;\r\n\r\n if (time < time_rate)\r\n {\r\n ;\r\n }\r\n\r\n else\r\n {\r\n time = 0;\r\n path_log.x[path_log.n] = myrobot.x;\r\n path_log.y[path_log.n] = myrobot.y;\r\n if (path_log.n + 1 < path_log.n_max)\r\n path_log.n++;\r\n else\r\n path_log.n = 0;\r\n }\r\n\r\n for (int i = 0; i < path_log.n_max; i++)\r\n {\r\n glColor3f(0, 1, 0.4); //\r\n\r\n glBegin(GL_POINTS);\r\n glVertex3f(path_log.x[i], path_log.y[i], 0.00);\r\n glEnd();\r\n }\r\n //cout<<\"n_max\"<<path_log.n_max<<\"_\";\r\n //cout<<\"n\"<<path_log.n<<endl;\r\n //cout<<\"time\"<<time<<endl;\r\n}\r\n\r\nvoid urg_view(ROBOT &robot, URG &urg_data, int col)\r\n{\r\n //URGのレーザーの表示\r\n if (col == 0)\r\n glColor3f(0.0, 0.0, 1.0);\r\n if (col == 1)\r\n glColor3f(0.0, 1.0, 0.0);\r\n\r\n const double length = urg_data.leng_max;\r\n glLineWidth(2.0);\r\n\r\n const int flg = 0;\r\n if (flg == 0)\r\n { //レーザ探査領域の表示\r\n for (int i = 0; i < urg_data.data_num - 1; i++)\r\n {\r\n double xx1 = (-1) * length * sin(i * urg_data.reso + urg_data.start_rad + robot.theta) + robot.x;\r\n double yy1 = length * cos(i * urg_data.reso + urg_data.start_rad + robot.theta) + robot.y;\r\n double xx2 = (-1) * length * sin((i + 1) * urg_data.reso + urg_data.start_rad + robot.theta) + robot.x;\r\n double yy2 = length * cos((i + 1) * urg_data.reso + urg_data.start_rad + robot.theta) + robot.y;\r\n glBegin(GL_LINES);\r\n glVertex3f(xx1, yy1, 0);\r\n glVertex3f(xx2, yy2, 0);\r\n glEnd();\r\n }\r\n double xx1 = (-1) * length * sin(urg_data.start_rad + robot.theta) + robot.x;\r\n double yy1 = length * cos(urg_data.start_rad + robot.theta) + robot.y;\r\n double xx2 = (-1) * length * sin((urg_data.data_num) * urg_data.reso + urg_data.start_rad + robot.theta) + robot.x;\r\n double yy2 = length * cos((urg_data.data_num) * urg_data.reso + urg_data.start_rad + robot.theta) + robot.y;\r\n glBegin(GL_LINES);\r\n glVertex3f(xx1, yy1, 0);\r\n glVertex3f(robot.x, robot.y, -0);\r\n glEnd();\r\n glBegin(GL_LINES);\r\n glVertex3f(xx2, yy2, 0);\r\n glVertex3f(robot.x, robot.y, -0);\r\n glEnd();\r\n }\r\n if (flg == 1)\r\n {\r\n for (int i = 0; i < urg_data.data_num - 1; i++)\r\n {\r\n double length = urg_data.leng[i];\r\n if (length == 0)\r\n length = urg_data.leng_max;\r\n double xx = (-1) * length * sin(i * urg_data.reso + urg_data.start_rad + robot.theta) + robot.x;\r\n double yy = length * cos(i * urg_data.reso + urg_data.start_rad + robot.theta) + robot.y;\r\n glBegin(GL_LINES);\r\n glVertex3f(xx, yy, 0);\r\n glVertex3f(robot.x, robot.y, -0);\r\n glEnd();\r\n }\r\n }\r\n glLineWidth(1.0);\r\n\r\n //レーザとOBJECTの交点の座標\r\n glPointSize(2.0);\r\n if (col == 0)\r\n glColor3f(0.0, 1.0, 1.0); //\r\n if (col == 1)\r\n glColor3f(0.0, 1.0, 0.0); //\r\n for (int i = 0; i < urg_data.data_num - 1; i++)\r\n {\r\n urg_data.x[i] = (-1) * urg_data.leng[i] * sin(i * urg_data.reso + urg_data.start_rad + robot.theta) + robot.x;\r\n urg_data.y[i] = urg_data.leng[i] * cos(i * urg_data.reso + urg_data.start_rad + robot.theta) + robot.y;\r\n glBegin(GL_POINTS);\r\n glVertex3f(urg_data.x[i], urg_data.y[i], 0.01);\r\n glEnd();\r\n }\r\n glPointSize(1.0);\r\n glLineWidth(2.0);\r\n return;\r\n}\r\n\r\nGraphics::Graphics()\r\n{\r\n xOrig = 0.0, yOrig = 0.0, zOrig = 0.0; //始点中心\r\n gui_start();\r\n}\r\n\r\nGraphics::~Graphics()\r\n{\r\n gui_end();\r\n}\r\nstatic double get_dtime()\r\n{\r\n struct timeval tv;\r\n gettimeofday(&tv, NULL);\r\n double n_time = tv.tv_sec + tv.tv_usec * 1e-6;\r\n static double o_time = n_time;\r\n double dt_msec = (n_time - o_time);\r\n o_time = n_time;\r\n\r\n return dt_msec;\r\n}\r\n\r\nvoid Graphics::main_draw()\r\n{\r\n double dt = get_dtime() / 1.0; //msec\r\n\r\n struct ROBOT myrobot2;\r\n urg_view(myrobot2, urg_data, 0); //URGの表示\r\n\r\n struct ROBOT myrobot3;\r\n myrobot3.theta = myrobot2.theta + M_PI;\r\n urg_view(myrobot3, urg_data2, 1); //URGの表示\r\n\r\n draw_string(\"dynamic_windows_approach:\");\r\n\r\n ////goalの座標を絶対位置から相対位置に変換。\r\n double _goal_x=goal_x-myrobot.x;\r\n double _goal_y=goal_y-myrobot.y;\r\n double _goal_l=sqrt(_goal_x*_goal_x+_goal_y*_goal_y);\r\n double _goal_rad=(-1)*atan2(_goal_x,_goal_y);\r\n double _robot_theta_fmod=atan2(sin(-myrobot.theta),cos(-myrobot.theta));\r\n double _sub_rad=_goal_rad-_robot_theta_fmod;\r\n\r\n double __goal_x=_goal_l*cos(_sub_rad+M_PI/2.0);\r\n double __goal_y=_goal_l*sin(_sub_rad+M_PI/2.0);\r\n\r\n glColor3f(0, 0, 1);\r\n glPointSize(10.0);\r\n glBegin(GL_POINTS);\r\n glVertex3f(__goal_x, __goal_y, 0.0);\r\n glEnd();\r\n glPointSize(1.0);\r\n\r\n glBegin(GL_LINES);\r\n glVertex3f(__goal_x, __goal_y, 0.0);\r\n glVertex3f(0, 0, 0.0);\r\n glEnd();\r\n\r\n static double vel_v=0.0;\r\n static double vel_w=0.0;\r\n\r\n //目標速度が入力されていたらそれに従う\r\n if((target_v==0.0)&&(target_w==0.0)){\r\n To_goal_velocity(goal_x, goal_y, myrobot.x, myrobot.y, -myrobot.theta, vel_v, vel_w, goal_reach_dis, turn_limit);\r\n\r\n //ゴールに到着したら、姿勢角度をあわせる。\r\n int goal_flg_near=false;\r\n goal_flg_near=To_goal_near(goal_x, goal_y, goal_theta, myrobot.x, myrobot.y, -myrobot.theta, vel_v, vel_w, goal_reach_dis);\r\n }\r\n else{\r\n vel_v=target_v;\r\n vel_w=target_w;\r\n }\r\n\r\n //DWAでの経路探索\r\n //velが早い・障害物が大きいとデットロックする\r\n dynamic_windows_approach(urg_data, path_x, path_y, path_cost, path_size, vel_v,vel_w, best_v, best_w, path_flg);\r\n myrobot.v = best_v;\r\n myrobot.w = best_w;\r\n\r\n\r\n\r\n // cout<<\"vel_v:\"<<vel_v<<endl;\r\n // cout<<\"vel_w:\"<<vel_w<<endl;\r\n // cout<<\"target_v:\"<<target_v<<endl;\r\n // cout<<\"target_w:\"<<target_w<<endl;\r\n // cout<<\"myrobot.v:\"<<myrobot.v<<endl;\r\n // cout<<\"myrobot.w:\"<<myrobot.w<<endl;\r\n\r\n\r\n //ゴールしていないのに止まってしまった場合は後ろに下がる\r\n // To_deadlock_back(goal_x, goal_y, goal_theta, myrobot.x, myrobot.y, -myrobot.theta, myrobot.v, myrobot.w, goal_reach_dis);\r\n //dynamic_windows_approach_back(urg_data2, path_x2, path_y2, path_cost2, path_size2, deadlock_v, deadlock_w, best_v, best_w, path_flg);\r\n dynamic_windows_approach_view(0, 0, 0);\r\n\r\n robot_expect_path_view(myrobot.v, myrobot.w, 0, 0, 0);\r\n\r\n // dynamic_windows_approach_view(myrobot.x, myrobot.y, myrobot.theta);\r\n // robot_expect_path_view(myrobot.v, myrobot.w, myrobot.x, myrobot.y, myrobot.theta);\r\n\r\n return;\r\n}\r\n\r\nvoid Graphics::display(){\r\n\r\n glClearColor(1, 1, 1, 1.0);\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n glEnable(GL_DEPTH_TEST);\r\n //glEnable( GL_POINT_SMOOTH );\r\n //glEnable(GL_PROGRAM_POINT_SIZE);\r\n\r\n glPushMatrix();\r\n polarview();\r\n\r\n //メイン描画の関数\r\n main_draw();\r\n\r\n glPopMatrix();\r\n glutSwapBuffers();\r\n glutPostRedisplay();\r\n\r\n usleep(10 * 1000);\r\n}\r\n\r\nvoid Graphics::idle(void)\r\n{\r\n glutPostRedisplay();\r\n usleep(10 * 1000);\r\n\r\n}\r\n\r\nvoid Graphics::myInit(char *progname){\r\n float aspect = (float)WIDTH / (float)HEIGHT;\r\n\r\n glutInitWindowPosition(0, 0);\r\n glutInitWindowSize(WIDTH, HEIGHT);\r\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);\r\n glutCreateWindow(progname);\r\n glClearColor(0, 0, 0, 1.0);\r\n\r\n glutKeyboardFunc(myKbd);\r\n glutKeyboardUpFunc(myKbdup);\r\n glutSpecialFunc(mySkey);\r\n\r\n glutMouseFunc(myMouse);\r\n glutMotionFunc(myMotion);\r\n resetview();\r\n\r\n glMatrixMode(GL_PROJECTION);\r\n glLoadIdentity();\r\n gluPerspective(45.0, aspect, 0.10, 100.0); //画角等視野の設定\r\n glMatrixMode(GL_MODELVIEW);\r\n}\r\n\r\nvoid Graphics::reshape(int, int){\r\n glutReshapeWindow(WIDTH, HEIGHT);\r\n}\r\n\r\nint Graphics::GUImain(){\r\n //\tread_obstacle(\"obstacle.csv\",obst);\r\n int argc = 3;\r\n char *argv[] = {\"program\", \"-display\", \":0.0\"};\r\n glutInit(&argc, argv);\r\n\r\n char *win_name = \"navigation\";\r\n myInit(win_name);\r\n glutDisplayFunc(display);\r\n glutReshapeFunc(reshape);\r\n\r\n glutIdleFunc(idle);\r\n glutMainLoop();\r\n\r\n return 0;\r\n}\r\n\r\nvoid Graphics::gui_start(){\r\n th1 = SDL_CreateThread((int (*)(void *))GUImain, this);\r\n}\r\n\r\nvoid Graphics::gui_end(){\r\n SDL_KillThread(th1);\r\n}\r\n\r\ndouble Graphics::timer_ms(){\r\n\r\n double timer_ms = cv::getTickCount();\r\n return timer_ms;\r\n}\r\n\r\nvoid Graphics::myMouse(int button, int state, int x, int y){\r\n\r\n double obj_x = 0, obj_y = 0, obj_z = 0;\r\n\r\n if (state == GLUT_DOWN)\r\n {\r\n switch (button)\r\n {\r\n case GLUT_LEFT_BUTTON:\r\n mButton = button;\r\n click_pickup(x, y, obj_x, obj_y, obj_z);\r\n // goal_y = obj_y;\r\n // goal_x = obj_x;\r\n\r\n path.x[path.n] = obj_x;\r\n path.y[path.n] = obj_y;\r\n path.n++;\r\n\r\n break;\r\n case GLUT_MIDDLE_BUTTON:\r\n\r\n break;\r\n case GLUT_RIGHT_BUTTON:\r\n mButton = button;\r\n\r\n if (path.n < 1)\r\n {\r\n path.now_n = 0;\r\n path.n = 0;\r\n myrobot.v = 0;\r\n myrobot.w = 0;\r\n }\r\n else\r\n {\r\n path.n--;\r\n if (path.now_n > path.n)\r\n path.now_n--;\r\n }\r\n\r\n break;\r\n }\r\n xBegin = x;\r\n yBegin = y;\r\n }\r\n if (state == GLUT_UP)\r\n {\r\n switch (button)\r\n {\r\n case GLUT_RIGHT_BUTTON:\r\n\r\n break;\r\n }\r\n }\r\n\r\n return;\r\n}\r\n\r\nvoid Graphics::myMotion(int x, int y){\r\n\r\n int xDisp, yDisp;\r\n\r\n xDisp = x - xBegin;\r\n yDisp = y - yBegin;\r\n\r\n switch (mButton)\r\n {\r\n case GLUT_LEFT_BUTTON:\r\n //azimuth -= (float) xDisp/2.0;\r\n //elevation -= (float) yDisp/2.0;\r\n xOrig += (float)xDisp / 50.0;\r\n zOrig -= (float)yDisp / 50.0;\r\n\r\n break;\r\n case GLUT_RIGHT_BUTTON:\r\n distance_gl -= (float)xDisp / 10.0;\r\n if (distance_gl < 0.000001)\r\n distance_gl = 0.000001;\r\n\r\n break;\r\n }\r\n xBegin = x;\r\n yBegin = y;\r\n\r\n glutPostRedisplay();\r\n}\r\n\r\nvoid Graphics::myKbdup(unsigned char key, int x, int y){\r\n\r\n switch (key)\r\n {\r\n\r\n case 'w': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\t\tmyrobot.v=0.0;\r\n break;\r\n case 's': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\t\tmyrobot.v=-0.0;\r\n break;\r\n case 'a': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\t\tmyrobot.w=-0.0;\r\n break;\r\n case 'd': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\t\tmyrobot.w=+0.0;\r\n break;\r\n }\r\n}\r\nvoid Graphics::myKbd(unsigned char key, int x, int y){\r\n switch (key)\r\n {\r\n case 0x1B: //終了\r\n //\texit(0);\r\n break;\r\n\r\n case 'q': //視点をリセット\r\n //\texit(0);;\r\n break;\r\n\r\n case 'z': //視点をリセット\r\n\r\n break;\r\n case 'x': //視点をリセット\r\n\r\n break;\r\n\r\n case 'w': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\t\tmyrobot.v=0.30;\r\n\r\n break;\r\n case 's': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\tmyrobot.v=-0.30;\r\n break;\r\n case 'a': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\tmyrobot.w=-0.10;\r\n break;\r\n case 'd': //ROBOTの移動指令\r\n //\tif(gl_mode==0)\tmyrobot.w=+0.10;\r\n break;\r\n }\r\n}\r\n\r\nvoid Graphics::mySkey(int key, int x, int y){\r\n switch (key)\r\n {\r\n case GLUT_KEY_LEFT:\r\n xOrig -= 0.2;\r\n break;\r\n case GLUT_KEY_RIGHT:\r\n xOrig += 0.2;\r\n break;\r\n case GLUT_KEY_UP:\r\n zOrig += 0.2;\r\n break;\r\n case GLUT_KEY_DOWN:\r\n zOrig -= 0.2;\r\n break;\r\n case GLUT_KEY_PAGE_UP:\r\n yOrig += 0.2;\r\n break;\r\n case GLUT_KEY_PAGE_DOWN:\r\n yOrig -= 0.2;\r\n break;\r\n }\r\n glutPostRedisplay();\r\n}\r\n\r\nvoid Graphics::resetview(void){\r\n distance_gl = 20.0;\r\n twist = 0.0;\r\n elevation = 0.0;\r\n azimuth = 0.0;\r\n}\r\n\r\nvoid Graphics::polarview(void){\r\n //マウスで移動\r\n glTranslatef(0.0, 0.0, -distance_gl);\r\n glRotatef(-twist, 0.0, 0.0, 1.0);\r\n glRotatef(-elevation, 1.0, 0.0, 0.0);\r\n glRotatef(-azimuth, 0.0, 1.0, 0.0);\r\n //キーボードで移動\r\n glTranslatef(xOrig, zOrig, yOrig);\r\n}\r\n\r\nfloat Graphics::click_Depth(int x, int y){ //マウスのX/Y座標からDepthを算出\r\n float z;\r\n GLint viewport[4]; //ビューポート\r\n //デバイス座標系とウィンドウ座標系の変換\r\n glGetIntegerv(GL_VIEWPORT, viewport); //現在のビューポートを代入\r\n glReadPixels(x, viewport[3] - y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);\r\n // デプスバッファの値を返す.\r\n return z;\r\n}\r\n\r\nvoid Graphics::click_pickup(int x, int y, double &ax, double &ay, double &az){ //マウスのX/Y座標からX/Y/Z座標を算出\r\n GLdouble modelview[16];\r\n GLdouble projection[16];\r\n GLint viewport[4];\r\n glGetDoublev(GL_MODELVIEW_MATRIX, modelview);\r\n glGetDoublev(GL_PROJECTION_MATRIX, projection);\r\n glGetIntegerv(GL_VIEWPORT, viewport);\r\n GLdouble winX, winY, winZ;\r\n GLdouble objX = 0.0, objY = 0.0, objZ = -distance_gl + yOrig;\r\n\r\n //原点のGLUT座標系を算出\r\n gluProject(objX, objY, objZ, modelview, projection, viewport, &winX, &winY, &winZ);\r\n GLdouble objX1, objY1, objZ1;\r\n //gluUnProject((double)x,(double)y,0.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n //cout<<\"near_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\r\n //gluUnProject((double)x,(double)y,1.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n //cout<<\"far_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\r\n\r\n gluUnProject((double)x, (double)y, winZ, modelview, projection, viewport, &objX1, &objY1, &objZ1);\r\n ax = objX1 - xOrig;\r\n ay = -(objY1 + zOrig);\r\n az = objZ1 - yOrig;\r\n\r\n cout << \"mouse_click:\"\r\n << \"\\t X:\" << x << \"\\t Y:\" << y << \"\\t x:\" << ax << \"\\t y:\" << ay << \"\\t z:\" << az << \"\" << endl;\r\n\r\n return;\r\n}\r\n\r\nvoid draw_string(string str, int w, int h, int x0, int y0){\r\n glColor3d(0.0, 0.60, 0.0);\r\n // glDisable(GL_LIGHTING);\r\n // 平行投影にする\r\n glMatrixMode(GL_PROJECTION);\r\n glPushMatrix();\r\n glLoadIdentity();\r\n gluOrtho2D(0, w, h, 0);\r\n glMatrixMode(GL_MODELVIEW);\r\n glPushMatrix();\r\n glLoadIdentity();\r\n\r\n // 画面上にテキスト描画\r\n glRasterPos2f(x0, y0);\r\n int size = (int)str.size();\r\n for (int i = 0; i < size; ++i)\r\n {\r\n char ic = str[i];\r\n glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ic);\r\n }\r\n\r\n glPopMatrix();\r\n glMatrixMode(GL_PROJECTION);\r\n glPopMatrix();\r\n glMatrixMode(GL_MODELVIEW);\r\n}\r\n\r\nvoid path_view()\r\n{\r\n\r\n glLineWidth(1.0);\r\n glColor3f(0, 1, 0); //Red\r\n if (path.n != 0)\r\n {\r\n for (int i = 0; i < path.n; i++)\r\n {\r\n glBegin(GL_LINES);\r\n glVertex3f(path.x[i], path.y[i], -0.001);\r\n glVertex3f(path.x[i - 1], path.y[i - 1], -0.001);\r\n glEnd();\r\n }\r\n }\r\n glLineWidth(1.0);\r\n\r\n double size = 0.2;\r\n glColor3f(0.5, 1, 0); //Red\r\n glBegin(GL_QUADS);\r\n glVertex3f(path.x[path.n - 1] - size, path.y[path.n - 1] - size, 0.001);\r\n glVertex3f(path.x[path.n - 1] - size, path.y[path.n - 1] + size, 0.001);\r\n glVertex3f(path.x[path.n - 1] + size, path.y[path.n - 1] + size, 0.001);\r\n glVertex3f(path.x[path.n - 1] + size, path.y[path.n - 1] - size, 0.001);\r\n glEnd();\r\n}\r\n\r\nvoid dynamic_windows_approach_view(double robot_x, double robot_y, double robot_theta){\r\n glLineWidth(1.0);\r\n //DymamicWindows_approachの軌跡を表示する\r\n glColor3f(0.3, 0.3, 0); //Y\r\n for (int j = 0; j < path_size; j++)\r\n {\r\n for (int i = 0; i < 49; i++)\r\n {\r\n glColor3f(0.3, 0.7, 1); //Green\r\n if (path_cost[j] > 100)\r\n glColor3f(1, 0, 0); //Red\r\n\r\n if ((path_x[j][i] != 0) && (path_y[j][i] != 0) && (path_x[j][i + 1] != 0) && (path_y[j][i + 1] != 0))\r\n {\r\n double xx1 = path_x[j][i] * cos(robot_theta) - path_y[j][i] * sin(robot_theta) + robot_x;\r\n double yy1 = path_x[j][i] * sin(robot_theta) + path_y[j][i] * cos(robot_theta) + robot_y;\r\n double xx2 = path_x[j][i + 1] * cos(robot_theta) - path_y[j][i + 1] * sin(robot_theta) + robot_x;\r\n double yy2 = path_x[j][i + 1] * sin(robot_theta) + path_y[j][i + 1] * cos(robot_theta) + robot_y;\r\n glBegin(GL_LINES);\r\n\r\n glVertex3f(xx1, yy1, 0);\r\n glVertex3f(xx2, yy2, 0);\r\n\r\n glEnd();\r\n }\r\n }\r\n }\r\n}\r\n//将来的な軌跡の表示\r\nvoid robot_expect_path_view(double vv, double ww, double robot_x, double robot_y, double robot_theta)\r\n{\r\n glLineWidth(3.0);\r\n glColor3f(0, 0.7, 0);\r\n //予定経路を表示\r\n double theta = 0.0;\r\n double path_x[50] = {};\r\n double path_y[50] = {};\r\n double path_theta = 0.0;\r\n double path_length = 0.0;\r\n double dt = 0.1;\r\n //\tglPointSize(5.0);\r\n\r\n for (int k = 0; k < 50 - 1; k++)\r\n {\r\n path_theta += ww * dt;\r\n path_x[k + 1] = path_x[k] - vv * sin(-path_theta) * dt;\r\n path_y[k + 1] = path_y[k] + vv * cos(-path_theta) * dt;\r\n }\r\n for (int k = 0; k < 50 - 1; k++)\r\n {\r\n double x1 = (path_x[k]) * cos(robot_theta) - (path_y[k]) * sin(robot_theta) + robot_x;\r\n double y1 = (path_x[k]) * sin(robot_theta) + (path_y[k]) * cos(robot_theta) + robot_y;\r\n double x2 = (path_x[k + 1]) * cos(robot_theta) - (path_y[k + 1]) * sin(robot_theta) + robot_x;\r\n double y2 = (path_x[k + 1]) * sin(robot_theta) + (path_y[k + 1]) * cos(robot_theta) + robot_y;\r\n\r\n glBegin(GL_LINES);\r\n glVertex3f(x1, y1, 0);\r\n glVertex3f(x2, y2, 0);\r\n glEnd();\r\n }\r\n glLineWidth(1.0);\r\n}\r\n" }, { "alpha_fraction": 0.6853055953979492, "alphanum_fraction": 0.7048114538192749, "avg_line_length": 17.634145736694336, "blob_id": "f7d44327a246c08733bb523dd3363ce7bcac13bc", "content_id": "9f6cd51b7e87787e3fe2d5f246f8d7dbea243501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 921, "license_type": "no_license", "max_line_length": 62, "num_lines": 41, "path": "/n_3d_robot_sim/src/collision_detec_3d.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string>\n#include <math.h>\n\nusing namespace std;\n\ntypedef struct xyz_st {\n\tdouble x;\n\tdouble y;\n\tdouble z;\n} xyz;\n\n//回転\nvoid Rotate3(double& x1, double& y1, double& z1, \n double alphaX,double alphaY,double alphaZ);\n//法線ベクトルの算出\nvoid normal_calc(xyz tri[], xyz &normal);\n\n//XYZ座標の外積\nxyz crossproduct_calc(xyz xyz1,xyz xyz2);\n\n//XYZ座標の内積\ndouble innerproduct_calc(xyz xyz1, xyz xyz2);\n\n//XYZ座標の引き算\nxyz sub_calc(xyz xyz1, xyz xyz2);\n\n//XYZ座標のスカラー量を求める\ndouble norm_calc(xyz xyz1);\n\n//XYZ座標の掛け算\nxyz scale_calc(xyz xyz1,double scale);\n\n//XYZ座標の足し算\nxyz add_calc(xyz xyz1,xyz xyz2);\n\n//三角形と線分のあたり判定\nbool collision_tri_line(xyz tri[],xyz line[],xyz &contact_pt);\n\n//三角形と三角形のあたり判定\nbool collision_tri_tri(\txyz in_tri[],\txyz in_tri2[]);\t\n\n\n\n\n" }, { "alpha_fraction": 0.4437984526157379, "alphanum_fraction": 0.45348837971687317, "avg_line_length": 31.866666793823242, "blob_id": "ea13e7f36a2164a970ea84ef522d529a9875baba", "content_id": "bfb2fb930ee96ab599575f6ecb0f9ae8854a5090", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 558, "license_type": "no_license", "max_line_length": 80, "num_lines": 15, "path": "/n_object_tracking_runcontrol/readme.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "##############################################\r\n#オブジェクトトラッキング走行制御Nodeの使い方。\r\n##############################################\r\n\r\nrosnode info /n_object_traking_run_control \r\n--------------------------------------------------------------------------------\r\nNode [/n_object_traking_run_control]\r\nPublications: \r\n * /rosout [rosgraph_msgs/Log]\r\n * /camera_tilt_angle [std_msgs/Float32]\r\n * /camera_pan_angle [std_msgs/Float32]\r\n * /cmd_vel2 [geometry_msgs/Twist]\r\n\r\nSubscriptions: \r\n * /target_pos [unknown type]\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6559913754463196, "alphanum_fraction": 0.6736236214637756, "avg_line_length": 25.721153259277344, "blob_id": "622a6bfa71792440aef985070da35dfd67034863", "content_id": "8dd6165f13b9f609d3f489f6b4bc65e7a1f8be52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2779, "license_type": "no_license", "max_line_length": 101, "num_lines": 104, "path": "/n_movebase_sendgoal/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <move_base_msgs/MoveBaseAction.h>\n#include <actionlib/client/simple_action_client.h>\n#include <tf/transform_broadcaster.h>\n#include <sstream>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <std_msgs/Int16.h>\n#include <actionlib_msgs/GoalID.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_listener.h>\ntf::TransformListener *tflistener;\n\ntypedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;\nros::Publisher goal_pub;\n\n\nint flag=0;\n\ndouble goal_x=0.0;\ndouble goal_y=0.0;\ndouble goal_w=0.0;\nvoid vel_Callback(const geometry_msgs::Twist::ConstPtr &vel_msg){\n flag=1;\n\n goal_x= vel_msg->linear.x;\n goal_y= vel_msg->linear.y;\n goal_w = vel_msg->linear.z;\n\n}\n\nvoid joyCallback(const std_msgs::Int16::ConstPtr &msg){\n if (msg->data == 1) {\n flag=1;\n }\n\n return;\n}\nvoid joyCallback2(const std_msgs::Int16::ConstPtr &msg){\n if (msg->data == 1){\n\tflag=2;\n\t}\n\n return;\n}\n\nint main(int argc, char **argv){\n ros::init(argc, argv, \"n_send_navigation_goals\");\n \n ros::NodeHandle nh_;\n\n ros::Publisher goal_pub = nh_.advertise<geometry_msgs::PoseStamped>(\"/move_base_simple/goal\", 1);\n \n ros::Subscriber vel_sub_= nh_.subscribe<geometry_msgs::Twist>(\"cmd_goal_pos\", 10, &vel_Callback);\n ros::Subscriber joy_subscriber = nh_.subscribe(\"button5\", 10, joyCallback);\n ros::Subscriber joy_subscriber2 = nh_.subscribe(\"button6\", 10, joyCallback2);\n\n tf::StampedTransform transform;\n tf::TransformListener listener(ros::Duration(10));\n\n ros::Rate r(10.0);\n while (nh_.ok()) {\n\n\tif(flag==1){\n\t\tROS_INFO(\"Please provide x and y of the goal!\");\n\t\tgeometry_msgs::PoseStamped msg;\n\t\tmsg.header.frame_id = \"/map\";\n\t\tmsg.pose.position.x = goal_x;\n\t\tmsg.pose.position.y = goal_y;\n\t\tmsg.pose.position.z = 0.0;\n\t\tmsg.pose.orientation.x = 0.0;\n\t\tmsg.pose.orientation.y = 0.0;\n\t\tmsg.pose.orientation.z = goal_w;\n\t\tmsg.pose.orientation.w = 1.0;\n\t\tgoal_pub.publish(msg);\n\t\tflag=0;\n\t}\n\n\tif(flag==2){\n\t\tROS_INFO(\"stop!\");\n\t\tlistener.lookupTransform(\"map\", \"base_link\",ros::Time(0), transform);\n\n\t\t// actionlib_msgs::GoalID msg;\n\t\tgeometry_msgs::PoseStamped msg;\n\t\tmsg.header.frame_id = \"/map\";\n\t\tmsg.pose.position.x = transform.getOrigin().x();\n\t\tmsg.pose.position.y = transform.getOrigin().y();\n\t\tmsg.pose.position.z = transform.getOrigin().z();\n\t\tmsg.pose.orientation.x = transform.getRotation().getX();\n\t\tmsg.pose.orientation.y = transform.getRotation().getY();\n\t\tmsg.pose.orientation.z = transform.getRotation().getZ();\n\t\tmsg.pose.orientation.w = transform.getRotation().getW();\n\t\tgoal_pub.publish(msg);\n\t\tflag=0;\n\t}\n\n\tros::spinOnce();\n\tr.sleep();\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6000784635543823, "alphanum_fraction": 0.6299058198928833, "avg_line_length": 22.423076629638672, "blob_id": "26ed3eb5b18ac2a2c5a07e0e9104f041071bd8f6", "content_id": "1f9e0d66be3652722f0e1e4a3b116bcd8da196b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2548, "license_type": "no_license", "max_line_length": 195, "num_lines": 104, "path": "/n_localpathplan/src/geometory.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n#pragma once\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n\r\nusing namespace std;\r\nconst double PI=M_PI;\r\n\r\n#define URG_DATA_MAX 2000\r\n#define OBSTACLE_MAX 2000\r\n#define DATA_SEQ 100\r\n\r\n#define MOVE_OBST_MAX_MAIN 1000\r\n\r\n#define PATH_POINTS_MAX 2000\r\nconst unsigned int urg_data_num=680;\r\nconst double urg_range_deg=240.0;\r\nconst double urg_leng_max=15.0;\r\nconst double urg_leng_min=0.1;\r\n\r\nstruct URG{\r\n\tdouble leng[URG_DATA_MAX];\r\n\tdouble x[URG_DATA_MAX];\r\n\tdouble y[URG_DATA_MAX];\r\n\tint data_num;\r\n\tdouble start_rad;\r\n\tdouble reso;\r\n\r\n\tdouble leng_max;\r\n\tdouble leng_min;\r\n\r\n\tURG(){\r\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\r\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*PI;\r\n\t\treso=2*PI/URG_DATA_MAX;\r\n\t\tleng_max=urg_leng_max;\r\n\t\tleng_min=urg_leng_min;\r\n\r\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\r\n\t\t\tx[i] = 0.0;\r\n\t\t\ty[i] = 0.0;\r\n\t\t\tleng[i] = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n};\r\n\r\nstruct OBSTACLE{\r\n\tdouble x1[OBSTACLE_MAX];\r\n\tdouble x2[OBSTACLE_MAX];\r\n\tdouble y1[OBSTACLE_MAX];\r\n\tdouble y2[OBSTACLE_MAX];\r\n\tunsigned int n;\r\n\tunsigned int n_max;\r\n\r\n\tOBSTACLE(){\r\n\t\tn_max=OBSTACLE_MAX;\r\n\r\n\t\tfor(int i=0;i<n_max;i++){\r\n\t\t\tx1[i] = 0.0;\r\n\t\t\tx2[i] = 0.0;\r\n\t\t\ty1[i] = 0.0;\r\n\t\t\ty2[i] = 0.0;\r\n\t\t}\r\n\r\n\t}\r\n};\r\n\r\n\r\n\r\n\r\nstruct MOVE_PATH{\r\n\tdouble x[PATH_POINTS_MAX];\r\n\tdouble y[PATH_POINTS_MAX];\r\n\tunsigned int n;\r\n\tunsigned int n_max;\r\n\tunsigned int now_n;\r\n\tMOVE_PATH(){\r\n\t\tn_max=PATH_POINTS_MAX;\r\n\t\tfor(int i=0;i<n_max;i++){\r\n\t\t\tx[i] = 0.0;\r\n\t\t\tx[i] = 0.0;\r\n\t\t\tn=0;\r\n\t\t\tnow_n=0;\r\n\t\t}\r\n\r\n\t}\r\n};\r\n\r\n\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta);\r\nvoid To_goal_velocity(double goal_x,double goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis=0.2,double turn_limit=3.14);\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn);\r\nvoid dynamic_windows_approach(URG urg_l,double path_x[][DATA_SEQ],double path_y[][DATA_SEQ],double path_cost[],int &path_size,double robot_v,double robot_w,double &best_v,double &best_w,int flg);\r\nvoid To_deadlock_back(double _goal_x,double _goal_y,double _goal_theta,double robot_x,double robot_y,double robot_theta,\r\n\tdouble &speed,double &turn,double goal_reach_dis);\r\nint To_goal_near(double _goal_x,double _goal_y,double _goal_theta,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis);\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6271960139274597, "alphanum_fraction": 0.6427104473114014, "avg_line_length": 25.381250381469727, "blob_id": "6b8978e841502c09a87147b7e87e821706114ab6", "content_id": "e5696fdbc28f7edab949c92c69fb7cb8a3e108ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4399, "license_type": "no_license", "max_line_length": 95, "num_lines": 160, "path": "/n_map_view/src_opencv/gl_main (コピー).cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "\r\n#include \"viewgui.h\"\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\n#include <ctime>\r\nusing namespace std;\r\n\r\n\r\n#include <sys/time.h>\r\n#include <unistd.h>\r\n#include <ros/ros.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n#include <nav_msgs/GetMap.h>\r\n#include \"opencv_inc.h\"\r\n#include <tf/transform_listener.h>\r\n\r\n#include <opencv2/opencv.hpp>\r\nusing namespace cv;\r\n\r\n\r\n//Robot制御のパラメータ\r\nextern struct URG urg_data;\r\nextern struct ROBOT myrobot;\r\nint map_width;\r\nint map_height;\r\ndouble map_resolution;\r\ndouble map_pos_x;\r\ndouble map_pos_y;\r\ndouble map_theta;\r\nchar map_data[2000*2000];\r\n\r\n\r\n\r\nvoid scanCallback (const sensor_msgs::LaserScanConstPtr & scan_msg){\r\n\tdouble range_min = scan_msg->range_min;\r\n\tdouble range_max = scan_msg->range_max;\r\n\tdouble angle_increment = scan_msg->angle_increment;\r\n\tdouble angle_min = scan_msg->angle_min ;\r\n\tdouble angle_max=scan_msg->angle_max;\r\n\r\n\r\n\tint data_num=(angle_max-angle_min)/angle_increment;\r\n\t// TODO - also copy intensity values\r\n\r\n\tfor(unsigned int i = 0; i < data_num; ++i){\r\n\t\turg_data.leng[i]=scan_msg->ranges[i];\r\n\t\tif(isnan(urg_data.leng[i]))urg_data.leng[i]=range_max;\r\n\t}\r\n\r\n\turg_data.data_num=data_num;\r\n\turg_data.start_rad=scan_msg->angle_min;\r\n\turg_data.reso=scan_msg->angle_increment;\r\n\r\n}\r\n\r\nvoid mapCallback(const nav_msgs::OccupancyGridConstPtr &map) {\r\n\tmap_width= map->info.width;\r\n\tmap_height= map->info.height;\r\n\tmap_resolution= map->info.resolution;\r\n\tmap_pos_x= map->info.origin.position.x;\r\n\tmap_pos_y= map->info.origin.position.y;\r\n\tgeometry_msgs::Quaternion orientation = map->info.origin.orientation;\r\n\ttf::Matrix3x3 mat(tf::Quaternion(orientation.x, orientation.y, orientation.z, orientation.w));\r\n\tdouble yaw, pitch, roll;\r\n\tmat.getEulerYPR(yaw, pitch, roll);\r\n\tmap_theta= yaw;\r\n\r\n\tROS_INFO(\"Received a %d X %d map @ %.3f m/pix_%f_%f_%f\",\r\n\tmap->info.width,map->info.height,map->info.resolution,\r\n\tmap->info.origin.position.x,map->info.origin.position.y,map_theta);\r\n\r\n\tfor (unsigned int y = 0; y < map->info.height; y++){\r\n\t\tfor (unsigned int x = 0; x < map->info.width; x++){\r\n\t\t\tunsigned int i = x + (map->info.height - y - 1) * map->info.width;\r\n\t\t\tmap_data[i]=map->data[i];\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tMat img_out = Mat::zeros(cv::Size(map->info.width,map->info.height), CV_8UC1);\r\n\r\n\r\n\tfor (unsigned int y = 0; y < map->info.height; y++){\r\n\t\tfor (unsigned int x = 0; x < map->info.width; x++){\r\n\t\t\tunsigned int i = x + (map->info.height - y - 1) * map->info.width;\r\n\t\t\tint intensity=205;\r\n\t\t\tif (map->data[i] >= 0 && map->data[i] <=100)\r\n\t\t\t\tintensity= round((float)(100.0-map->data[i])*2.55);\r\n\r\n \t\t\timg_out.at<unsigned char>(y, x)=intensity;\r\n\t\t}\r\n\t}\r\n\t\r\n\timwrite(\"map.png\",img_out);\r\n\r\n\t ros::shutdown();\r\n\t\r\n\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n\t//Graphics GL;\r\n\r\n\tros::init(argc, argv, \"map_viewer\");\r\n\t\r\n\t//const std::string scan_topic_ = \"scan\";\r\n\tros::NodeHandle n;\r\n\t//ros::Subscriber scan_subscriber_ = n.subscribe (scan_topic_, 10, scanCallback);\r\n\tros::Subscriber map_sub_ = n.subscribe(\"map\", 2, mapCallback);\r\n\t\r\n\t//tf::TransformListener listener(ros::Duration(10));\r\n\t//ros::Publisher cmd_vel_pub;\r\n\t//cmd_vel_pub = n.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1);\r\n\r\n\t//ros::NodeHandle private_nh(\"~\");\r\n\t//string tf_name1;\r\n\t//string tf_name2;\r\n\t//private_nh.param(\"tf_name1\",tf_name1,std::string(\"base_link\"));\r\n\t//private_nh.param(\"tf_name2\",tf_name2,std::string(\"map\"));\r\n\r\n\t//geometry_msgs::Twist base_cmd;\r\n\t//base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n\r\n\tros::Rate r(10.0);\r\n\twhile (n.ok()) {\r\n\t/*\ttf::StampedTransform trans_slam;\r\n\t\ttry{\r\n\t\t\tlistener.lookupTransform(tf_name2, tf_name1,ros::Time(0), trans_slam);\r\n\t\t\tmyrobot.y = trans_slam.getOrigin().x();\r\n\t\t\tmyrobot.x = -trans_slam.getOrigin().y();\r\n\t\t\tmyrobot.theta = tf::getYaw(trans_slam.getRotation());\r\n\t\t}catch(tf::TransformException &ex){\r\n\t\t\tROS_ERROR(\"%s\", ex.what());\r\n\t\t\tros::Duration(1.0).sleep();\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t//if(myrobot.v<0.01){\r\n\t\t//base_cmd.linear.x=myrobot.v*0.0;\r\n\t\t//base_cmd.angular.z = -myrobot.w*0.0;\r\n\t\t//}\r\n\r\n\t\t//else{\r\n\t\tbase_cmd.linear.x=myrobot.v*1.0;\r\n\t\tbase_cmd.angular.z = -myrobot.w*1.0;\r\n\t\t//}\r\n\t\tcmd_vel_pub.publish(base_cmd);\r\n\t*/\r\n\t\tros::spinOnce();\r\n\t\tr.sleep();\r\n\t}\r\n\r\n\treturn 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7834645509719849, "alphanum_fraction": 0.7834645509719849, "avg_line_length": 41.5, "blob_id": "75741e049f3eda947c5c2d79bd29b31b9d135e55", "content_id": "4101c6d5d48ae34081956c8039cc9c798ea50bfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 342, "license_type": "no_license", "max_line_length": 92, "num_lines": 6, "path": "/docu_navi_localpathplan/src/read_file.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "//TEXT読み込み・一致したら値を返す\nint string_Matching(vector<string> lines,string para_name,string &params,string delim=\"\\t\");\n\n// 文字列 target が 文字列 pattern で始まっている場合には真、さもなくば偽を返す。\nint shrhstr( string target_str, string pattern_str );\ndouble StringToDouble(string in);" }, { "alpha_fraction": 0.559440553188324, "alphanum_fraction": 0.6657342910766602, "avg_line_length": 14.880952835083008, "blob_id": "229c42dd56d9486a62a6b7297fae7dfd8a26e0c7", "content_id": "7b502bed18347d18cae82a2452fed15b3c295c94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 727, "license_type": "no_license", "max_line_length": 33, "num_lines": 42, "path": "/n_3d_robot_sim/src/docu_3D_lrf_simlator_setting.ini", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "//LRFの設定\r\ntop_urg_data_num=\t1080\r\ntop_urg_deg=\t270.0\r\ntop_urg_reso=\t1440.0\r\ntop_urg_len_max=\t30.0\r\ntop_urg_len_min=\t0.2\r\n\r\n//LPF_Fの設定\r\nclassic_urg_data_num=\t768\r\nclassic_urg_deg=\t240.0\r\nclassic_urg_reso=\t768.0\r\nclassic_urg_len_max=\t10.0\r\nclassic_urg_len_min=\t0.2\r\n\r\n\r\n\r\nnoise_odometory_v_gain=\t-0.05\r\nnoise_odometory_w_gain=\t0.05\r\nnoise_urg=\t0.010\r\nrobot_z=\t2.50\r\n\r\n\r\nodometory_tf_out_error=\t1\r\n\r\n\r\npantilt_pan_rot_speed=\t1.50\r\npantilt_pan_init_deg=\t90.0\r\npantilt_tilt_rot_sin_amp=\t0.00000\r\npantilt_tilt_rot_sin_speed=\t5.000\r\npantilt_tilt_init_deg=\t-19.0\r\n\r\n\r\nmove_obst_num=\t5\r\n\r\nobstacle_z=\t3.0\r\n\r\n\r\nview_camera_rgb_flg=\t1\r\nview_camera_depth_flg=\t0\r\nview_camera_pcl_flg=\t0\r\nview_sim_cap_flg=\t0\r\nsim_fps=\t40\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7744361162185669, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 21, "blob_id": "9b63caed4fd4f6838be06e2909f05aa76a98759f", "content_id": "c3d86b02d348cc4fa3029b13da8338029979ac4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 133, "license_type": "no_license", "max_line_length": 45, "num_lines": 6, "path": "/myproject/configuration_files/toyota_hsr_localization.lua~", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "include \"toyota_hsr.lua\"\n\nTRAJECTORY_BUILDER.pure_localization = true\nSPARSE_POSE_GRAPH.optimize_every_n_scans = 10\n\nreturn options\n\n" }, { "alpha_fraction": 0.5529736876487732, "alphanum_fraction": 0.5817052125930786, "avg_line_length": 24.774038314819336, "blob_id": "f44f0bf850e968184a53cc040c7d4ba135880edd", "content_id": "3760fbe47afac792ab8f3e7857fccef83b4c6ee4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 31388, "license_type": "no_license", "max_line_length": 192, "num_lines": 1040, "path": "/old/map_editor_simple/src/geometory.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n#include<stdlib.h>\r\n#include <math.h>\r\n#include<iostream>\r\n#include<string>\r\n#include<sstream> \r\n#include<fstream>\r\nusing namespace std;\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <cmath>\r\n\r\n#define RAD2DEG(x) ((x)*180.0/M_PI)\r\n#define DEG2RAD(x) ((x)*M_PI/180.0)\r\n\r\n\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n\r\ndouble Uniform( void ){\r\n\treturn ((double)rand()+1.0)/((double)RAND_MAX+2.0);\r\n}\r\n\r\ndouble rand_normal( double mu, double sigma ){\r\n\tdouble z=sqrt( -2.0*log(Uniform()) ) * sin( 2.0*PI*Uniform() );\r\n\treturn mu + sigma*z;\r\n}\r\n\r\n//strをdoubleに変換する\r\ndouble str_double(string str){\t\r\n\tistringstream is; \r\n\tis.str(str); \r\n\tdouble x; \r\n\tis >> x; \r\n\treturn x;\r\n}\r\n\r\n\r\n\r\n//時間を計測する\r\ndouble get_dtime(void){\r\n\tdouble freq = 1000.0/cv::getTickFrequency();\r\n\tstatic int64 old_time = cv::getTickCount();\r\n\tint64 time = cv::getTickCount();\r\n\tdouble dt_msec=(time-old_time)*freq;\r\n\told_time=time;\r\n\treturn dt_msec;\r\n}\r\n\r\n\r\n//Goal座標を相対座標に変換する\r\nvoid goal_abst_to_relative(double goal_x_abst,double goal_y_abst,double &goal_x_relate,double &goal_y_relate,double robot_x,double robot_y,double robot_theta){\r\n\tdouble xx=(goal_x_abst-robot_x);\r\n\tdouble yy=(goal_y_abst-robot_y);\r\n\r\n\tgoal_x_relate=xx*cos(-robot_theta)-yy*sin(-robot_theta);\r\n\tgoal_y_relate=xx*sin(-robot_theta)+yy*cos(-robot_theta);\r\n\r\n\treturn ;\r\n}\r\n\r\n//線分と点との距離を測定する\r\ndouble line_seg_point_distance( double px, double py,double ax, double ay, double bx, double by){\r\n\tdouble dx, dy, r2;\r\n\tdouble t, cx, cy;\r\n\tdx = bx - ax;\r\n\tdy = by - ay;\r\n\tif (dx == 0 && dy == 0)\r\n\t\treturn sqrt((px - ax) * (px - ax) + (py - ay) * (py - ay));\r\n\tr2 = dx * dx + dy * dy;\r\n\tt = (dx * (px - ax) + dy * (py - ay)) / (double)r2;\r\n\tif (t < 0)\r\n\t\treturn sqrt((px - ax) * (px - ax) + (py - ay) * (py - ay));\r\n\tif (t > 1)\r\n\t\treturn sqrt((px - bx) * (px - bx) + (py - by) * (py - by));\r\n\tcx = (1 - t) * ax + t * bx;\r\n\tcy = (1 - t) * ay + t * by;\r\n\treturn sqrt((px - cx) * (px - cx) + (py - cy) * (py - cy));\r\n}\r\n\r\n\r\n//線分の交差判定関数\r\n//但し,a=bだと交差判定受けるので注意.\r\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y){\r\n\r\n\t// 外積:axb = ax*by - ay*bx\r\n\t// 外積と使用して交差判定を行なう\r\n\tdouble v1 = (a2_x - a1_x) * (b1_y - a1_y) - (a2_y - a1_y) * (b1_x - a1_x);\r\n\tdouble v2 = (a2_x - a1_x) * (b2_y - a1_y) - (a2_y - a1_y) * (b2_x - a1_x);\r\n\tdouble m1 = (b2_x - b1_x) * (a1_y - b1_y) - (b2_y - b1_y) * (a1_x - b1_x);\r\n\tdouble m2 = (b2_x - b1_x) * (a2_y - b1_y) - (b2_y - b1_y) * (a2_x - b1_x);\r\n\r\n\t// +-,-+だったら-値になるのでそれぞれを掛けて確認\r\n\tif((v1*v2<= 0) && (m1*m2 <= 0)){\r\n\t\treturn true; // 2つとも左右にあった\r\n\t}else{\r\n\t\t//cout<<\"checkerror\"<<endl;\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\n//\r\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y){\r\n\r\n\tdouble aa_a=(a2_y-a1_y)/(a2_x-a1_x+1/1000000.0);\r\n\tdouble aa_b=a1_y-aa_a*a1_x;\r\n\r\n\tdouble bb_a=(b2_y-b1_y)/(b2_x-b1_x+1/1000000.0);\r\n\tdouble bb_b=b1_y-bb_a*b1_x;\r\n\r\n\tif(a2_x!=a1_x){\r\n\t\taa_a=(a2_y-a1_y)/(a2_x-a1_x);\r\n\t\taa_b=a1_y-aa_a*a1_x;\r\n\t}\r\n\tif(b2_x!=b1_x){\r\n\t\tbb_a=(b2_y-b1_y)/(b2_x-b1_x);\r\n\t\tbb_b=b1_y-bb_a*b1_x;\r\n\t}\r\n\r\n\r\n\tif(aa_a!=bb_a){\r\n\t\tcro_x=-(bb_b-aa_b)/(bb_a-aa_a);\r\n\t\tcro_y=cro_x*aa_a+aa_b;\r\n\t\t//cout<<cro_x<<\"_\"<<cro_y<<endl;\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n\r\n//仮想距離センサ\r\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data,bool flg=0){\r\n\r\n\tURG urg_data_buff;\r\n\r\n//センサのDelayを計測する\r\n\tdouble freq = 1000.0/cv::getTickFrequency();\r\n\tstatic int64 old_time = cv::getTickCount();\r\n\tint64 time = cv::getTickCount();\r\n\tdouble dt_msec=(time-old_time)*freq;\r\n\t//cout<<dt_msec<<endl;\r\n\tif(dt_msec<delay_urg*1000.0){\r\n\t\treturn;\r\n\t}\r\n\telse{\r\n\t\told_time=time;\r\n\t}\r\n//\r\n\r\n\t//URG_Dataの初期化\r\n\tfor(int i=0;i<urg_data_buff.data_num;i++){\r\n\t\turg_data_buff.x[i]=robot.x;\r\n\t\turg_data_buff.y[i]=robot.y;\r\n\t\turg_data_buff.leng[i]=0.0;\r\n\t}\r\n\r\n\t//URG_レーザ\r\n\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\turg_area.leng[i]=urg_data_buff.leng_max;\r\n\t\turg_area.x[i]=(-1)*urg_area.leng[i]*sin(i*urg_data_buff.reso+urg_data_buff.start_rad+robot.theta)+robot.x;\r\n\t\turg_area.y[i]=urg_area.leng[i]*cos(i*urg_data_buff.reso+urg_data_buff.start_rad+robot.theta)+robot.y;\r\n\t}\r\n\r\n\tfor(int j=0;j<obst.n;j++){\r\n\t\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\t\tdouble a1_x=obst.x1[j];\r\n\t\t\tdouble a1_y=obst.y1[j];\r\n\t\t\tdouble a2_x=obst.x2[j];\r\n\t\t\tdouble a2_y=obst.y2[j];\r\n\t\t\tdouble b2_x=urg_area.x[i];\r\n\t\t\tdouble b2_y=urg_area.y[i];\r\n\t\t\tdouble b1_x=robot.x;\r\n\t\t\tdouble b1_y=robot.y;\r\n\t\t\t//線分の交差判定\r\n\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\r\n\r\n\t\t\t\t//\tcout<<\"交差:\"<<a1_x<<endl;\r\n\t\t\t\t//attach_flg=1;\r\n\t\t\t\tdouble ata_x=0.0;\r\n\t\t\t\tdouble ata_y=0.0;\r\n\t\t\t\t//線分の交点の算出\r\n\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){//交点のある場合\r\n\r\n\t\t\t\t\tif(urg_data_buff.leng[i]==0){\t//データが入っていないなら\r\n\t\t\t\t\t\turg_data_buff.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\telse{\t\t\t\t\t\t//データが入っていたら\r\n\t\t\t\t\t\tdouble oldleng=urg_data_buff.leng[i];\r\n\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\tif(temp_leng<oldleng){//元より小さければ格納\r\n\t\t\t\t\t\t\turg_data_buff.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t//線分の交点算出はここまで\r\n\t\t\t}\r\n\t\t\t//線分の交差判定はここまで\r\n\t\t}\r\n\t}\r\n\r\n\turg_data=urg_data_buff;\r\n\r\n\tif(flg==0)return;//移動障害物を計算せずに終わり\r\n\r\n\tfor(int j=0;j<move_obst.n;j++){\r\n\t\tfor(int k=0;k<move_obst.m;k++){\r\n\t\t\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\t\t\tdouble a1_x=move_obst.obst_x[j][k];\r\n\t\t\t\tdouble a1_y=move_obst.obst_y[j][k];\r\n\t\t\t\tdouble a2_x=move_obst.obst_x[j][k+1];\r\n\t\t\t\tdouble a2_y=move_obst.obst_y[j][k+1];\r\n\t\t\t\tdouble b2_x=urg_area.x[i];\r\n\t\t\t\tdouble b2_y=urg_area.y[i];\r\n\t\t\t\tdouble b1_x=robot.x;\r\n\t\t\t\tdouble b1_y=robot.y;\r\n\t\t\t\t//線分の交差判定\r\n\t\t\t\t//\tif((a1_x!=a2_x)&&(a1_y!=a2_y)){\r\n\t\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\r\n\r\n\t\t\t\t\t//\tcout<<\"交差:\"<<a1_x<<endl;\r\n\t\t\t\t\t//attach_flg=1;\r\n\t\t\t\t\tdouble ata_x=0.0;\r\n\t\t\t\t\tdouble ata_y=0.0;\r\n\t\t\t\t\t//線分の交点の算出\r\n\t\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){//交点のある場合\r\n\r\n\t\t\t\t\t\tif(urg_data_buff.leng[i]==0){\t//データが入っていないなら\r\n\t\t\t\t\t\t\t//\tcout<<\"n\"<<(ata_y-robot.y)<<\"_\"<<(ata_x-robot.x)<<endl;\r\n\t\t\t\t\t\t\t//\tcout<<\"n\"<<((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x))<<endl;\r\n\t\t\t\t\t\t\turg_data_buff.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\telse{\t\t\t\t\t\t//データが入っていたら\r\n\t\t\t\t\t\t\tdouble oldleng=urg_data_buff.leng[i];\r\n\t\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\t\tif(temp_leng<oldleng){//元より小さければ格納\r\n\t\t\t\t\t\t\t\turg_data_buff.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t//線分の交点算出はここまで\r\n\t\t\t\t//\t}\r\n\t\t\t\t//線分の交差判定はここまで\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\turg_data=urg_data_buff;\r\n\r\n}\r\n//障害物情報の読み込み\r\nvoid read_obstacle(OBSTACLE &obst,string fname){\r\n\tcout << \"Obstacle File reading\" << endl;\r\n\r\n\tstring filename(fname.c_str());\r\n\tstring str_line;\r\n\tifstream ifs( filename.c_str() );\r\n\r\n\tif( !ifs ) {\r\n\t\tcout << \"Error:Input data file not found\" << endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tstring obst_in[1024][4]={};\r\n\r\n\tint line=0;\r\n\tint width=0;\r\n\tgetline( ifs, str_line );\r\n\twhile( getline( ifs, str_line ) ){\r\n\t\tstring token;\r\n\t\tistringstream stream( str_line );\r\n\r\n\t\twhile( getline( stream, token, ',' ) ) {\r\n\t\t\tobst_in[line][width]=token;\r\n\t\t\t//\t\tcout << obst_in[line][width] << \",\";\r\n\t\t\twidth++;\r\n\t\t}\r\n\t\tline++;\r\n\t\twidth=0;\r\n\r\n\t\t//\tcout << endl;\r\n\t}\r\n\r\n\tobst.n=line;\r\n\t//cout<<\"obst:\" <<obst.n<< endl;\r\n\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\tobst.x1[i]=str_double(obst_in[i][0]);\r\n\t\tobst.y1[i]=str_double(obst_in[i][1]);\r\n\t\tobst.x2[i]=str_double(obst_in[i][2]);\r\n\t\tobst.y2[i]=str_double(obst_in[i][3]);\r\n\t}\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\tcout << obst.x1[i] << \",\";\r\n\t\tcout << obst.x2[i] << \",\";\r\n\t\tcout << obst.y1[i] << \",\";\r\n\t\tcout << obst.y2[i] << \",\";\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\treturn;\r\n}\r\n\r\n//障害物情報の読み込み\r\nvoid write_obstacle(OBSTACLE &obst,string fname){\r\n\tcout << \"Obstacle File Write\" << endl;\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\tcout << obst.x1[i] << \",\";\r\n\t\tcout << obst.x2[i] << \",\";\r\n\t\tcout << obst.y1[i] << \",\";\r\n\t\tcout << obst.y2[i] << \",\";\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\r\n\tstd::ofstream writing_file;\r\n\twriting_file.open(fname.c_str(), std::ios::out);\r\n\r\n\tstd::cout << \"writing \" << fname << \"...\" << std::endl;\r\n\r\n\twriting_file << \"x1,y1,x2,y2\" << endl;\r\n\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\twriting_file << obst.x1[i] << \",\";\r\n\t\twriting_file << obst.y1[i] << \",\";\r\n\t\twriting_file << obst.x2[i] << \",\";\r\n\t\twriting_file << obst.y2[i] << \",\";\r\n\t\twriting_file << endl;\r\n\t}\r\n\treturn;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n//ゴールに向かうロボットへの指令速度を算出する。\r\nvoid To_goal_velocity(double _goal_x,double _goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis,double turn_limit){\r\n\r\n\tconst double speed_gain=2.0;\t\t\t\r\n\tconst double turn_gain=speed_gain*1.5;\t\t\r\n\tconst double speed_max=2.0;\r\n\tconst double turn_max=PI/2.0;\r\n\r\n\tdouble goal_x=_goal_x-robot_x;\t\t\t\t\t\t//\r\n\tdouble goal_y=_goal_y-robot_y;\t\t\t\t\t\t//\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\t//\r\n\tdouble goal_rad=(-1)*atan2(goal_x,goal_y);\r\n\t//ロボット角度の正規化(+2PIに抑制)\r\n\tdouble robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\r\n\t//角度の差分\r\n\tdouble sub_rad=goal_rad-robot_theta_fmod;\r\n\r\n\t//Tanが±πの範囲のため、右回りと左回りを評価\r\n\tif(fabs(goal_rad-robot_theta_fmod)>1.0*PI){\r\n\t\tif(fabs(goal_rad-robot_theta_fmod+4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod-4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod+2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod-2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t}\r\n\r\n\t//速度の評価関数は実機にあわせて修正すること。\r\n\tdouble x=goal_l;\r\n\t//speed = (0.0246*pow(x,4) - 0.1987*pow(x,3) + 0.169*pow(x,2) + 1.7482*pow(x,1)-1.4 );\r\n\t//speed = (x );\r\n\r\n\tspeed=fabs(x)*speed_gain;\r\n\r\n\r\n\t//\tdouble turn_speed=fabs(sub_rad);\r\n\tdouble r=sub_rad;\r\n\t//\tdouble turn_speed = fabs(r);\r\n\tdouble turn_speed = -0.0278*pow(r,5) + 0.3025*pow(r,4) - 1.1232*pow(r,3) + 1.4103*pow(r,2) + 0.4428*pow(r,1) + 0.0;\r\n\r\n\tif(sub_rad>=0) turn=-1*turn_speed*turn_gain;\r\n\telse if((sub_rad<=0)) turn=1*turn_speed*turn_gain;\r\n\r\n\t//角度のかい離大きいたらその場で旋回\r\n\tif(turn_speed>=turn_max)\tspeed=0.0;\r\n\tif(turn_speed<=-turn_max)\tspeed=0.0;\r\n\r\n\r\n\t//最大速度の規定\r\n\tif(speed>speed_max)\tspeed=2.0;\r\n\tif(goal_l<goal_reach_dis) speed=0.0;\t//到達したら停止\r\n\r\n\t//cout<<\"robo\"<<robot_theta_fmod<<\"\\t\";\r\n\t//cout<<\"atan\"<<sub_rad<<\"\\t\";\r\n\t//cout<<\"sub\"<<turn<<endl;\r\n\treturn ;\r\n}\r\n\r\n//パスに従って追従するロボットへの指令速度を算出する。\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn){\r\n\tdouble goal_limit=1.0;\t\t//ゴールと認識する距離\r\n\tdouble goal_limit_last=.20;\t\t//ゴールと認識する距離\r\n\r\n\r\n\tif(path.now_n+1==path.n) {goal_limit=goal_limit_last;}\r\n\r\n\r\n\tdouble goal_x=path.x[path.now_n]-robot_x;\r\n\tdouble goal_y=path.y[path.now_n]-robot_y;\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble goal_rad=(-1)*atan2(goal_x,goal_y);\r\n\r\n\r\n\tif(goal_l<goal_limit){ //ゴールに近い\r\n\t\tif(path.now_n+1<path.n){\r\n\t\t\tpath.now_n++;\r\n\t\t}\r\n\t\telse if(path.now_n+1==path.n) {\r\n\t\t\tspeed=0;\r\n\t\t\tturn=0;\r\n\t\t}\r\n\t}\r\n\telse{\t\t\t//ゴールから遠いのであれば経路追従\r\n\r\n\t\tTo_goal_velocity( path.x[path.now_n], path.y[path.now_n],robot_x,robot_y,robot_theta,speed,turn,goal_limit,3.14*2.0);\r\n\t}\r\n\t//cout<<\"n:\"<<path.now_n<<\"_x:\"<<path.x[path.now_n]<<\"_y:\"<<path.y[path.now_n]<<\"_\"<<path.n<<endl;\r\n\treturn;\r\n}\r\n\r\n\r\n\r\n//障害物を検知して回避する\r\nvoid dynamic_windows_approach(URG urg_data,double path_x[][50],double path_y[][50],double path_cost[],int &path_size,double robot_v,double robot_w,double &best_v,double &best_w,int check_flg){\r\n\t//URG urg_data:URGの測定データ\r\n\t//double path_x[][50]:DWAの探索するパスx座標\r\n\t//double path_y[][50]:DWAの探索するパスy座標\r\n\t//double path_cost[]:DWAの探索するパスごとのコスト\r\n\t//int &path_size:DWAの探索するパスの本数\r\n\t//double robot_v:ロボットの目標速度\r\n\t//double robot_w:ロボットの角速度\r\n\t//double &best_v:ロボットが障害物回避する速度\r\n\t//double &best_w:ロボットが障害物回避する角速度\r\n\t//int check_flg:DWAを算出できたかのFlag\r\n\r\n\r\n\tconst double robot_v_max=1.0;\t\t//最大速度\r\n\tconst double robot_v_min=0.001;\t\t//最小速度\r\n\tconst double robot_size=0.5;\t\t//ロボットの安全距離\r\n\tconst double urg_fail_min=0.01;\t\t//URGの測定異常値\r\n\tconst double dt=0.1;\t\t\t\t//予測軌跡の時間刻み\r\n\tconst double future_t=5.0;\t\t\t//何秒先まで予測するか\r\n\r\n\tint future_cnt=future_t/dt;\t\t\t//予測軌跡のは推定cycle(正し最大50cycle)\r\n\tif(future_cnt>=50) future_cnt=50;\r\n\r\n\tdouble v_range=robot_v*0.30;\t\t\t//DWAの速度範囲\r\n\tdouble w_range=1.5*PI;\t\t\t\t\t//DWAの角速度範囲\r\n\tdouble dv=fabs(robot_v-v_range)/5.0;\t//DWAの速度刻み幅\r\n\tdouble dw=2*w_range/40.0;\t\t\t\t//DWAの角速度刻み幅\r\n\r\n\tconst double v_weight=5.0;\t\t\t//速度のDWA重み項\r\n\tconst double w_weight=20.0;\t\t\t//角速度のDWA重み項\r\n\tconst double dis_weight=0.50;\t\t//障害物までの距離DWA重み項\r\n\tconst double leng_weight=0.50;\t\t//ロボットの走行距離のDWA重み項\r\n\tconst double ac_trans_limit=2.0;\t//加速度の最大値\r\n\tconst double ac_rot_limit=2.0;\t\t//角加速度の最大値\r\n\r\n\tconst double COST_MAX=99999.0;\t\t//コストの最大値(固定値)\r\n\tconst double urg_leng_max=5.0;\t\t//測域センサの最大測定距離(固定値)\r\n\r\n\r\n\t//速度のリミッタ\r\n\tbest_v=robot_v;\r\n\tbest_w=robot_w;\r\n\tif(robot_v>robot_v_max)best_v=robot_v_max;\r\n\tif(robot_v<robot_v_min)best_v=robot_v_min;\r\n\tif(best_v<0.01)\treturn;\t\t\t\t//その場で旋回時は計算しない\r\n\r\n\r\n\tfor(int i = 0;i < 1000;i++){\t\t//DWAパスの初期化\r\n\t\tfor(int j = 0;j < 50;j++){\r\n\t\t\tpath_x[i][j]=0.0;\r\n\t\t\tpath_y[i][j]=0.0;\r\n\t\t}\r\n\t}\r\n\tcheck_flg=0;\t\t\t\t\t//確認Flgの初期化\r\n\r\n\r\n\r\n\tint urg_data_point=0;\t\t\t\t\t//障害物データはいくつ入っているのか。\r\n\tconst int urg_data_point_thresh=10;\t\t//障害物データがあるかどうかの閾値\r\n\r\n\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\tif((urg_data.leng[i]<urg_data.leng_max)&&(urg_data.leng[i]>0.1))urg_data_point++;\r\n\t}\r\n\t//\tif(urg_data_point<urg_data_point_thresh)return;\t//データないなら計算しなくていい。\r\n\r\n\t//cout<<\"cal\"<<endl;\r\n\r\n\t//測域センサデータのX-Y平面変換\r\n\tdouble urg_x[1280]={};\r\n\tdouble urg_y[1280]={};\r\n\tdouble urg_l[1280]={};\r\n\r\n\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\turg_x[i]=(-1)*urg_data.leng[i]*sin(i*urg_data.reso+urg_data.start_rad);\r\n\t\turg_y[i]=urg_data.leng[i]*cos(i*urg_data.reso+urg_data.start_rad);\r\n\t\turg_l[i]=sqrt(urg_x[i]*urg_x[i]+urg_y[i]*urg_y[i]);\r\n\t}\r\n\r\n\t//回避経路の探索\r\n\tdouble path_cost_w[1000]={};\r\n\tdouble path_cost_v[1000]={};\r\n\tint cnt=0;\r\n\r\n\t//もし衝突するなら、軌跡を計算する。\r\n\tfor(double v=robot_v-v_range;v<=robot_v;v+=dv){\t\t\t\t//v;速度\t\r\n\t\tfor(double w=robot_w-w_range;w<=robot_w+w_range;w+=dw){\t\t//w;角速度\r\n\t\t\tif(v<0)v=0;\r\n\t\t\tdouble x=0;\r\n\t\t\tdouble y=0;\r\n\t\t\tdouble real_v=robot_v;\r\n\t\t\tdouble real_w=0.0;\r\n\t\t\tdouble theta=0;\r\n\t\t\tdouble length =0;\r\n\t\t\tdouble dis_min =10;\r\n\t\t\tpath_cost[cnt]=0;\r\n\t\t\tpath_cost_w[cnt]=w;\r\n\t\t\tpath_cost_v[cnt]=v;\r\n\t\t\tfor(int k = 0;k < future_cnt;k++){\r\n\t\t\t\tif(path_cost[cnt]>COST_MAX/10.0)break;\t//壁とぶつかるなら計算おわり\r\n\t\t\t\tif(theta>1*PI)break;\t\t\t//まわりすぎたら計算おわり\r\n\t\t\t\tif(theta<-1*PI)break;\t\t\t//まわりすぎたら計算おわり\r\n\r\n\t\t\t\tif(fabs(real_v-v)/dt>ac_trans_limit){//加速度のリミッタ\r\n\t\t\t\t\tif((v-real_v)>=0)\t\treal_v+=ac_trans_limit*dt;\r\n\t\t\t\t\telse if((v-real_v)<0)\treal_v-=ac_trans_limit*dt;\t\r\n\t\t\t\t}\r\n\t\t\t\tif(fabs(real_w-w)/dt>ac_rot_limit){//角加速度のリミッタ\r\n\t\t\t\t\tif((w-real_w)>=0)\t\treal_w+=ac_rot_limit*dt;\r\n\t\t\t\t\telse if((w-real_w)<0)\treal_w-=ac_rot_limit*dt;\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttheta+= real_w*dt;\t\t\t\t//v/wを積分してXY展開\r\n\t\t\t\tx+= -real_v*sin(-theta)*dt;\r\n\t\t\t\ty+= real_v*cos(-theta)*dt;\r\n\t\t\t\tlength += fabs(dt*v);\r\n\r\n\t\t\t\t//theta+= w*dt;\r\n\t\t\t\t//x+= -v*sin(-theta)*dt;\r\n\t\t\t\t//y+= v*cos(-theta)*dt;\r\n\r\n\t\t\t\tfor(int i=0;i<urg_data.data_num-1;i++){\t//障害物が近くにあれば、コストを増す\r\n\t\t\t\t\tif(urg_l[i]>urg_fail_min){\r\n\t\t\t\t\t\tdouble dist=sqrt((x-urg_x[i])*(x-urg_x[i])+(y-urg_y[i])*(y-urg_y[i]));\r\n\t\t\t\t\t\tif(dist<robot_size) {\r\n\t\t\t\t\t\t\tpath_cost[cnt]=COST_MAX;\t\t\t//大きい値を代入\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif(dis_min>dist)\tdis_min=dist;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tdouble cost=v_weight*fabs(v-robot_v)+w_weight*fabs(w-robot_w)+leng_weight*length+dis_weight*fabs(urg_data.leng_max-dis_min);\r\n\t\t\t\tif(path_cost[cnt]<cost) {\r\n\t\t\t\t\tpath_cost[cnt]=cost;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpath_x[cnt][k]=x;\r\n\t\t\t\tpath_y[cnt][k]=y;\r\n\r\n\t\t\t}\t\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t}\r\n\r\n\tpath_size=cnt;\t//パスの配列長さを保存\r\n\r\n\t//コスト最小のベストパスを算出\r\n\tdouble best_cost=COST_MAX;\r\n\tfor(int j=0;j<cnt-1;j++){\r\n\t\tif((path_cost[j]<best_cost)&&(path_cost[j]>0.0001)){\r\n\t\t\tif(path_cost[j]<COST_MAX/10.0){\r\n\t\t\t\tbest_cost=path_cost[j];\r\n\t\t\t\tbest_w=path_cost_w[j];\r\n\t\t\t\tbest_v=path_cost_v[j];\r\n\t\t\t\tcheck_flg=1;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(best_cost==COST_MAX){\r\n\t\t\tbest_v=0.0;\r\n\t\t\tbest_w=0.0;\r\n\t\t}\r\n\t}\r\n\t//cout<<\"best_\"<<best_v<<\"_\"<<best_w<<\"_\"<<best_cost<<endl;\r\n\r\n\treturn ;\r\n\r\n}\r\n\r\n//エッジを追加する関数\r\nvoid dijkstra_addEdge(int v, int u, struct Node *node,double weight){\r\n\r\n\tconst int safety=0;\r\n\tconst int hazard=1;\r\n\r\n\tif(node[u].value==hazard) weight=99999.0;\r\n\tif(node[v].value==hazard) weight=99999.0;\r\n\r\n\t//if(node[u].value==hazard) return;\r\n\t//if(node[v].value==hazard) return;\r\n\r\n\t//\tcout<<\"n::\"<<v<<\"_l:\"<<u<<\"weight\"<<weight<<endl;\r\n\t//ノードuはノードvとつながっている情報を入れる\t\r\n\tnode[ u ].to.push_back( v );\r\n\t//ノードuとノードvのエッジの重みを入れる\r\n\tnode[ u ].cost.push_back( weight*100 );\r\n\r\n\t//有向グラフならここから下の処理が不要\r\n\r\n\t//ノードvはノードuとつながっている情報を入れる\r\n\tnode[ v ].to.push_back( u );\r\n\t//ノードvとノードuのエッジの重みを入れる\r\n\tnode[ v ].cost.push_back( weight*100 );\r\n}\r\n// ダイクストラ法\r\nint dijkstra_search(int n, int start, int end, struct Node *node){\r\n\r\n\tif(start>n-1) return -1;\r\n\tif(end>n-1) return -1;\r\n\tif(start<0) return -1;\r\n\tif(end<0) return -1;\r\n\r\n\t//変数の初期化\r\n\tfor(int i=0 ; i<n ; i++){\r\n\t\tnode[i].done = false;\r\n\t\tnode[i].minCost = -1;\r\n\t}\r\n\r\n\tnode[start].minCost = 0;\t//スタートノードまでのコストは0\r\n\twhile(1){\r\n\t\tint doneNode = -1;\t//最新の確定したノード番号(-1はNULLのかわり)\r\n\t\tfor(int i=0 ; i<n ; i++){\r\n\r\n\t\t\tif( node[i].done==true ){//ノードiが確定しているときcontinue\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif( node[i].minCost < 0 ){//ノードiまでの現時点での最小コストが不明のとき\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\t//確定したノード番号が-1かノードiの現時点の最小コストが小さいとき\r\n\t\t\t//確定ノード番号を更新する\r\n\t\t\tif( doneNode<0 || node[i].minCost < node[doneNode].minCost){\r\n\t\t\t\tdoneNode = i;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(doneNode==-1) break;\t//すべてのノードが確定したら終了\r\n\r\n\t\tnode[doneNode].done = true;\t//ノードを確定させる\r\n\r\n\t\tfor(int i=0 ; i<node[doneNode].to.size() ; i++){\r\n\t\t\tint to = node[doneNode].to[i];\r\n\t\t\tint cost = node[doneNode].minCost + node[doneNode].cost[i];\r\n\r\n\t\t\t//ノードtoはまだ訪れていないノード\r\n\t\t\t//またはノードtoへより小さいコストの経路だったら\r\n\t\t\t//ノードtoの最小コストを更新\r\n\t\t\tif( node[to].minCost < 0 || cost < node[to].minCost ){\r\n\t\t\t\tnode[to].minCost = cost;\r\n\t\t\t\tnode[to].from = doneNode;\r\n\t\t\t}\r\n\t\t}\t\t\t\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid dijkstra_main( struct Node *node,int start,int end,double path_x_out[],double path_y_out[],int &path_out_num,int w_max,int h_max,double grid){\r\n\tconst int d_mat1[]={-w_max,-1,+1,w_max};\t\t\t\t//正方形を仮定するマトリックス\r\n\tconst int d_mat2[]={-w_max-1,-w_max+1,w_max-1,w_max+1};\t//正方形を仮定するマトリックス\r\n\tconst int d_mat1_num=sizeof(d_mat1)/sizeof(int);\r\n\tconst int d_mat2_num=sizeof(d_mat2)/sizeof(int);\r\n\r\n\t//cout<<\"w_grid:\"<<grid<<endl;\r\n\t//cout<<\"h_grid:\"<<grid<<endl;\r\n\t//cout<<\"w_max:\"<<w_max<<endl;\r\n\t//cout<<\"h_max:\"<<h_max<<endl;\r\n\t//cout<<\"node_min:\"<<0<<endl;\r\n\t//cout<<\"node_max:\"<<h_max*w_max-1<<endl;\r\n\r\n\t//nodeの関係を入力する\r\n\tfor(int h=0 ; h<h_max ; h++){\r\n\t\tfor(int w=0 ; w<w_max ; w++){\r\n\t\t\tint node_i=w+h*w_max;\t\t//現在位置\r\n\t\t\tfor(int m=0 ; m<d_mat1_num ; m++){\t//上下左右\r\n\t\t\t\tint node_m=node_i+d_mat1[m];\t//移動先のnode\r\n\t\t\t\tif((node_i!=node_m)&&(node_m>=0)&&(node_m<w_max*h_max)){//node_mがGrid領域内\r\n\t\t\t\t\tif(!((w==w_max-1)&&(d_mat1[m]==1)))//右端処理\r\n\t\t\t\t\t\tif(!((w==0)&&(d_mat1[m]==-1))){//左端処理\r\n\t\t\t\t\t\t\tdijkstra_addEdge( node_i , node_m , node,1.0);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor(int m=0 ; m<d_mat2_num ; m++){\t\t//斜め\r\n\t\t\t\tint node_m=node_i+d_mat2[m];\t//移動先のnode\r\n\t\t\t\tif((node_i!=node_m)&&(node_m>=0)&&(node_m<w_max*h_max)){//node_mがGrid領域内\r\n\t\t\t\t\tif(((w!=0)&&(h!=0)&&(w!=w_max-1)&&(h!=h_max-1))){//端部は斜めを計算しない。\r\n\t\t\t\t\t\tdijkstra_addEdge( node_i , node_m , node,1.414);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//ここまででグラフに関する情報(エッジ、ノード)は構造体node[]に入っている\r\n\r\n\t//\tcout << \"スタートノード&ゴールノード番号を入力:\";\r\n\r\n\t//\tint start=0;\r\n\t//\tint end=99;\r\n\t////\tcin >> start >> end;\r\n\r\n\tif(start<0)start=0;\r\n\tif(start>=w_max*h_max)start=w_max*h_max-1;\r\n\tif(end<0)end=0;\r\n\tif(end>=w_max*h_max)end=w_max*h_max-1;\r\n\r\n\t//最短経路を調べる\r\n\tvector<int> path;//最短経路の情報を保持するvector\r\n\tvector<double> path_x;//最短経路の情報を保持するvector\r\n\tvector<double> path_y;//最短経路の情報を保持するvector\r\n\r\n\r\n\t//int n=w_max*h_max;\r\n\t//ダイクストラ法で最短経路を求める\r\n\tdijkstra_search( w_max*h_max , start , end , node );\r\n\r\n\t//最短経路をゴールから順にスタートまでたどる\r\n\tfor(int i = end ; i != start ; i = node[i].from ){\r\n\t\tpath.push_back(i);\r\n\t\tpath_x.push_back(node[i].x);\r\n\t\tpath_y.push_back(node[i].y);\r\n\t}\r\n\r\n\tpath.push_back(start);\r\n\tpath_x.push_back(node[start].x);\r\n\tpath_y.push_back(node[start].y);\r\n\r\n\r\n\tpath_out_num=0;\r\n\t////最短経路の出力\r\n\t//cout << \"最短経路は\" << endl;\r\n\r\n\tdouble dx_o=100;\r\n\tdouble dy_o=100;\r\n\tpath_x_out[path_out_num]=node[start].x;\r\n\tpath_y_out[path_out_num]=node[start].y;\r\n\tpath_out_num++;\r\n\r\n\tfor(int i = path.size()-1 ; i > 0 ; i--){\r\n\t\tdouble dx=path_x[i]-path_x[i-1];\r\n\t\tdouble dy=path_y[i]-path_y[i-1];\r\n\t\tif(!((dx==dx_o)&&(dy==dy_o))){\t\t//傾き一緒なものはまとめる。\r\n\t\t\tpath_x_out[path_out_num]=path_x[i];\r\n\t\t\tpath_y_out[path_out_num]=path_y[i];\r\n\t\t\tpath_out_num++;\r\n\t\t}\r\n\t\tdx_o=dx;\r\n\t\tdy_o=dy;\r\n\t}\r\n\r\n\tpath_x_out[path_out_num]=path_x[0];\r\n\tpath_y_out[path_out_num]=path_y[0];\r\n\tpath_out_num++;\r\n\r\n\t//for(int i = path.size()-1 ; i >= 0 ; i--){\r\n\t//\tcout << path[i] << \"\\t\";\r\n\t//\tcout << path_x[i] << \"\\t\";\r\n\t//\tcout << path_y[i] << \"\\t\";\r\n\t//\tcout << endl;\r\n\t//\tpath_x_out[path_out_num]=path_x[i];\r\n\t//\tpath_y_out[path_out_num]=path_y[i];\r\n\t//\tpath_out_num++;\r\n\t//}\r\n\r\n\t////最短距離\r\n\t//cout <<\"length:\"<< node[end].minCost << endl;\r\n\t//コストが大きければ、その経路を消去\r\n\tif(node[end].minCost>99999.0) path_out_num=0;\r\n\r\n\t//int m;\r\n\t//cin >> m;\r\n\r\n}\r\n\r\n\r\nvoid global_pathplan_dijkstra(struct Node *node,double start_x,double start_y,double goal_x,double goal_y,struct MOVE_PATH &path,struct OBSTACLE &obst){\r\n\tconst int safety=0;//定数\r\n\tconst int hazard=1;//定数\r\n\r\n\tconst double x_min=0;\r\n\tconst double y_min=0;\r\n\tconst double x_max=50;\r\n\tconst double y_max=50;\r\n\tconst double grid=0.5;\r\n\tconst int w_max=(x_max-x_min)/grid;\r\n\tconst int h_max=(y_max-y_min)/grid;\r\n\tconst double y_offset=(y_max-y_min)/2.0;\r\n\tconst double x_offset=(x_max-x_min)/2.0;\r\n\tconst double hazard_dis=1.0;\r\n\r\n\t//格子地図の作成\r\n\tfor(int h=0 ; h<h_max ; h++){\r\n\t\tfor(int w=0 ; w<w_max ; w++){\r\n\t\t\tint node_i=w+h*w_max;\t\t//現在位置\r\n\t\t\tnode[node_i].w_max=w_max;\r\n\t\t\tnode[node_i].h_max=h_max;\r\n\t\t\tnode[node_i].x=(double)w*grid-x_offset;\r\n\t\t\tnode[node_i].y=-(double)h*grid+y_offset;\r\n\t\t\tnode[node_i].value=safety;\t//safetyで埋める\r\n\t\t\tfor(int i=0;i<obst.n;i++){\r\n\t\t\t\tdouble dis=line_seg_point_distance(node[node_i].x,node[node_i].y,obst.x1[i],obst.y1[i],obst.x2[i],obst.y2[i]);\r\n\t\t\t\tif(dis<hazard_dis)\tnode[node_i].value=hazard;//障害物があればhazard\r\n\r\n\t\t\t}\r\n\t\t}\t\r\n\t}\r\n\tint start_node=0;\r\n\tint end_node=0;\r\n\r\n\tdouble dis_start_min=99999.0;\t\r\n\tdouble dis_end_min=99999.0;\t\t\r\n\r\n\tfor(int i=0;i<w_max*h_max;i++){\t\r\n\t\t//スタートに近い格子点を探索\r\n\t\tdouble dis_start=(node[i].x-start_x)*(node[i].x-start_x)+(node[i].y-start_y)*(node[i].y-start_y);\r\n\t\tif(dis_start<dis_start_min)\t{\r\n\t\t\tdis_start_min=dis_start;\r\n\t\t\tstart_node=i;\r\n\t\t}\r\n\t\t//ゴールに近い格子点を探索\r\n\t\tdouble dis_end=(node[i].x-goal_x)*(node[i].x-goal_x)+(node[i].y-goal_y)*(node[i].y-goal_y);\r\n\t\tif(dis_end<dis_end_min)\t\t{\r\n\t\t\tend_node=i;\r\n\t\t\tdis_end_min=dis_end;\r\n\t\t}\r\n\t}\r\n\r\n\tdouble path_x[1000];\r\n\tdouble path_y[1000];\r\n\tint path_num=0;\r\n\r\n\tdijkstra_main(node,start_node,end_node,path_x,path_y,path_num,w_max,h_max,grid);\r\n\r\n\t//for(int i=0;i<path_num;i++){\r\n\t//\tdouble xx1=path_x[i];\r\n\t//\tdouble yy1=path_y[i];\r\n\t//\tdouble xx2=path_x[i+1];\r\n\t//\tdouble yy2=path_y[i+1];\r\n\t//}\r\n\t//\r\n\tpath.n=0;\r\n\tpath.now_n=0;\r\n\tfor(int i=0;i<path_num;i++){\r\n\t\tpath.x[path.n]=path_x[i];\r\n\t\tpath.y[path.n]=path_y[i];\r\n\t\tpath.n++;\r\n\t}\r\n}\r\n\r\nint LRF_clustring_tracking(CLUSTER clust[],double &goal_x,double &goal_y,int mouse_flag){\r\n\r\n\r\n\tconst double Threshold_tracking=2.0;\r\n\r\n\tstatic double object_x=0;\r\n\tstatic double object_y=0;\r\n\t\r\n\tif(mouse_flag==1){\r\n\t\tobject_x=goal_x; \r\n\t\tobject_y=goal_y;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tint clust_no_object=0;\r\n\tdouble distance_object_min=999.0;\r\n\tfor(int i=0;i<clust[0].clnum;i++){\r\n\t\tdouble xx=clust[i].x_ave;\r\n\t\tdouble yy=clust[i].y_ave;\r\n\t\tdouble distance_object=(xx-object_x)*(xx-object_x)+(yy-object_y)*(yy-object_y);\r\n\t\tif(distance_object<distance_object_min){\r\n\t\t\tdistance_object_min=distance_object;\r\n\t\t\tclust_no_object=i;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tif(distance_object_min<Threshold_tracking){\r\n\t\tgoal_x=clust[clust_no_object].x_ave;\r\n\t\tgoal_y=clust[clust_no_object].y_ave;\r\n\t\tobject_x=goal_x;\r\n\t\tobject_y=goal_y;\r\n\treturn 1;\r\n\t\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nvoid LRF_clustring_main(URG urg_data,CLUSTER clust[]){\r\n\t//URG urg_data URGのデータ\r\n\t//CLUSTER clust[] クラスタリングされたデータ\r\n\r\n\r\n\t//const double LRF_clustring_Threshold_percent=0.2;//クラスタリングの距離閾値[%]\r\n\t//const double LRF_clustring_Threshold_dis=0.1;//クラスタリングの距離閾値[m]\r\n\t//const int LRF_clustring_min_num=5;\r\n\r\n\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\turg_data.x[i]=(-1)*urg_data.leng[i]*sin(i*urg_data.reso+urg_data.start_rad);\r\n\t\turg_data.y[i]=urg_data.leng[i]*cos(i*urg_data.reso+urg_data.start_rad);\r\n\t}\r\n\r\n\tfor(int i=0;i<urg_data.data_num;i++){\r\n\t\tclust[i].ptnum=0;\r\n\t\tclust[i].dis=0;\r\n\t\tclust[i].flag=1;\r\n\t}\r\n \r\n int ptnum=0;\t//各クラスタ毎の点数\r\n int clnum=0;\t//クラスタの戸数\r\n \r\n\tfor(int i=0;i<urg_data.data_num;i++){//クラスタ分類\r\n\t\tif(((fabs( urg_data.leng[i+1]-urg_data.leng[i] )<urg_data.leng[i]*LRF_clustring_Threshold_percent)||\r\n\t\t\t(fabs(urg_data.leng[i+1]-urg_data.leng[i])< LRF_clustring_Threshold_dis))&&(urg_data.leng[i]>0.01)){//隣とクラスタリング\r\n\t\t\tclust[clnum].r[ptnum]=urg_data.leng[i];\r\n\t\t\tclust[clnum].x[ptnum]=urg_data.x[i];\r\n\t\t\tclust[clnum].y[ptnum]=urg_data.y[i];\r\n\t\t\tclust[clnum].ptnum=ptnum;\r\n\t\t\tptnum++;\r\n\t\t}\r\n\t\telse if(((fabs( urg_data.leng[i+2]-urg_data.leng[i] )<urg_data.leng[i]*LRF_clustring_Threshold_percent)||\r\n\t\t\t(fabs(urg_data.leng[i+2]-urg_data.leng[i] )< LRF_clustring_Threshold_dis))&&(urg_data.leng[i]>0.01)){//もうひとつ隣とクラスタリング\r\n\t\t\tclust[clnum].r[ptnum]=urg_data.leng[i];\r\n\t\t\tclust[clnum].x[ptnum]=urg_data.x[i];\r\n\t\t\tclust[clnum].y[ptnum]=urg_data.y[i];\r\n\t\t\tclust[clnum].ptnum=ptnum;\r\n\t\t\tptnum++;\r\n\t\t}\r\n\r\n\t\telse{//次のクラスタを割り振る\r\n\t\t\tif(clust[clnum].ptnum>LRF_clustring_min_num){\r\n\t\t\t\ti++;\r\n\t\t\t\tclnum++;\r\n\t\t\t\tptnum=0;\r\n\t\t\t\tclust[clnum].r[ptnum]=urg_data.leng[i];\r\n\t\t\t\tclust[clnum].x[ptnum]=urg_data.x[i];\r\n\t\t\t\tclust[clnum].y[ptnum]=urg_data.y[i];\r\n\t\t\t\tclust[clnum].ptnum=ptnum;\r\n\t\t\t\tptnum++;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\ti++;\r\n\t\t\t\tptnum=0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//クラスタ中心を求める.\r\n\tfor(int i=0;i<clnum;i++){\r\n\t\tdouble x_sum=0;\r\n\t\tdouble y_sum=0;\r\n\t\tdouble r_sum=0;\r\n\t\tint sum=0;\r\n\r\n\t\tfor(int j=0;j<clust[i].ptnum;j++){\r\n\t\t\tdouble x=clust[i].x[j];\r\n\t\t\tdouble y=clust[i].y[j];\r\n\t\t\tdouble r=clust[i].r[j];\r\n\t\t\tif(r>0.01){\r\n\t\t\t\tx_sum+=x;\r\n\t\t\t\ty_sum+=y;\r\n\t\t\t\tr_sum+=r;\r\n\t\t\t\tsum++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tclust[i].x_ave=x_sum/sum;\r\n\t\tclust[i].y_ave=y_sum/sum;\r\n\t\tclust[i].r_ave=r_sum/sum; \r\n\t\tclust[i].clnum=clnum;\r\n\t}\r\n\r\n \r\n \r\n\t//クラスタ長を求める.\r\n\tfor(int i=0;i<clnum;i++){\r\n\t\tdouble dis=0;\r\n\t\tdouble clust_dis=0;\r\n\t\tfor(int j=0;j<clust[i].ptnum;j++){\r\n\t\t\tif((fabs( clust[i].r[j+1]-clust[i].r[j] )< clust[i].r[j]*0.10)||(fabs( clust[i].r[j+1]-clust[i].r[j] )< 0.10)){\r\n\t\t\t\tdouble x0=clust[i].x[j];\r\n\t\t\t\tdouble y0=clust[i].y[j];\r\n\t\t\t\tdouble x1=clust[i].x[j+1];\r\n\t\t\t\tdouble y1=clust[i].y[j+1];\r\n\t\t\t\tdouble dis=(x1-x0)*(x1-x0)+(y1-y0)*(y1-y0);\r\n\t\t\t\tclust_dis+=dis;\r\n\t\t\t}\r\n\t\t}\r\n\t\tclust[i].dis=clust_dis;\r\n\t}\r\n\r\n\r\n //クラスタの点数が少なければ省く.\r\n\tfor(int i=0;i<clnum;i++){\r\n\t\tptnum=clust[i].ptnum;\r\n\t\tif(ptnum<3) clust[i].flag=0;\r\n\t}\r\n \r\n}\r\n// 平均mean,標準偏差stdのガウス分布の乱数を生成\r\ndouble gaussian_random(double mean, double std){\r\n const double norm = 1.0 / (RAND_MAX + 1.0);\r\n double u = 1.0 - rand() * norm; /* can't let u == 0 */\r\n double v = rand() * norm;\r\n double z = sqrt(-2.0 * log(u)) * cos(2.0 * M_PI * v);\r\n return mean + std * z;\r\n} " }, { "alpha_fraction": 0.5537076592445374, "alphanum_fraction": 0.5849056839942932, "avg_line_length": 24.221052169799805, "blob_id": "32072bf5b910a7e228e6175df6e1bf4a56a0fbbe", "content_id": "97e93702343b54c56602ffda74ae4e5c02efa1e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17601, "license_type": "no_license", "max_line_length": 198, "num_lines": 665, "path": "/docu_navi_localpathplan/src/geometory.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n#include<stdlib.h>\r\n#include <math.h>\r\n#include<iostream>\r\n#include<string>\r\n#include<sstream> \r\n#include<fstream>\r\nusing namespace std;\r\n\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n\r\ndouble moving_goal_limit=0.5;\r\ndouble target_speed_gain=0.50;\r\ndouble target_turn_gain=0.5;\r\ndouble target_speed_max=0.5;\r\ndouble circling_turn_gain=1.0;\r\ndouble circling_turn_max=0.4;\r\ndouble dwa_robot_v_max=0.30;\r\ndouble dwa_robot_v_min=0.01;\r\ndouble dwa_robot_size=0.20;\t\t\r\ndouble dwa_urg_fail_min=0.03;\t\r\ndouble dwa_dt=0.15;\t\r\ndouble dwa_v_weight=5.0;\r\ndouble dwa_w_weight=10.0;\r\ndouble dwa_dis_weight=0.10;\r\ndouble dwa_leng_weight=0.1;\r\n//double dwa_ac_trans_limit=2.0;\r\n//double dwa_ac_rot_limit=2.0;\r\n\r\ndouble Uniform( void ){\r\n\treturn ((double)rand()+1.0)/((double)RAND_MAX+2.0);\r\n}\r\n\r\ndouble rand_normal( double mu, double sigma ){\r\n\tdouble z=sqrt( -2.0*log(Uniform()) ) * sin( 2.0*PI*Uniform() );\r\n\treturn mu + sigma*z;\r\n}\r\n\r\ndouble str_double(string str){\t\r\n\tistringstream is; \r\n\tis.str(str); \r\n\tdouble x; \r\n\tis >> x; \r\n\treturn x;\r\n}\r\n\r\n\r\n static double get_dtime()\r\n{\r\n struct timeval tv;\r\n gettimeofday(&tv, NULL);\r\n\tdouble n_time =tv.tv_sec + tv.tv_usec * 1e-6;\r\n\tstatic double o_time= n_time;\r\n\tdouble dt_msec=(n_time-o_time);\r\n\r\n\to_time= n_time;\r\n\r\n return dt_msec;\r\n}\r\n\r\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y){\r\n\tdouble v1 = (a2_x - a1_x) * (b1_y - a1_y) - (a2_y - a1_y) * (b1_x - a1_x);\r\n\tdouble v2 = (a2_x - a1_x) * (b2_y - a1_y) - (a2_y - a1_y) * (b2_x - a1_x);\r\n\tdouble m1 = (b2_x - b1_x) * (a1_y - b1_y) - (b2_y - b1_y) * (a1_x - b1_x);\r\n\tdouble m2 = (b2_x - b1_x) * (a2_y - b1_y) - (b2_y - b1_y) * (a2_x - b1_x);\r\n\tif((v1*v2<= 0) && (m1*m2 <= 0)){\r\n\t\treturn true; \r\n\t}else{\r\n\t\t//cout<<\"checkerror\"<<endl;\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\n//\r\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y){\r\n\r\n\tdouble aa_a=(a2_y-a1_y)/(a2_x-a1_x+1/1000000.0);\r\n\tdouble aa_b=a1_y-aa_a*a1_x;\r\n\r\n\tdouble bb_a=(b2_y-b1_y)/(b2_x-b1_x+1/1000000.0);\r\n\tdouble bb_b=b1_y-bb_a*b1_x;\r\n\r\n\tif(a2_x!=a1_x){\r\n\t\taa_a=(a2_y-a1_y)/(a2_x-a1_x);\r\n\t\taa_b=a1_y-aa_a*a1_x;\r\n\t}\r\n\tif(b2_x!=b1_x){\r\n\t\tbb_a=(b2_y-b1_y)/(b2_x-b1_x);\r\n\t\tbb_b=b1_y-bb_a*b1_x;\r\n\t}\r\n\r\n\r\n\tif(aa_a!=bb_a){\r\n\t\tcro_x=-(bb_b-aa_b)/(bb_a-aa_a);\r\n\t\tcro_y=cro_x*aa_a+aa_b;\r\n\t\t//cout<<cro_x<<\"_\"<<cro_y<<endl;\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n\r\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data){\r\n\tfor(int i=0;i<urg_data.data_num;i++){\r\n\t\turg_data.x[i]=robot.x;\r\n\t\turg_data.y[i]=robot.y;\r\n\t\turg_data.leng[i]=0.0;\r\n\t}\r\n\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\turg_area.x[i]=(-1)*urg_area.leng[i]*sin(i*urg_data.reso+urg_data.start_rad+robot.theta)+robot.x;\r\n\t\turg_area.y[i]=urg_area.leng[i]*cos(i*urg_data.reso+urg_data.start_rad+robot.theta)+robot.y;\r\n\t}\r\n\r\n\tfor(int j=0;j<obst.n;j++){\r\n\t\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\t\tdouble a1_x=obst.x1[j];\r\n\t\t\tdouble a1_y=obst.y1[j];\r\n\t\t\tdouble a2_x=obst.x2[j];\r\n\t\t\tdouble a2_y=obst.y2[j];\r\n\t\t\tdouble b2_x=urg_area.x[i];\r\n\t\t\tdouble b2_y=urg_area.y[i];\r\n\t\t\tdouble b1_x=robot.x;\r\n\t\t\tdouble b1_y=robot.y;\r\n\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\r\n\r\n\r\n\r\n\t\t\t\tdouble ata_x=0.0;\r\n\t\t\t\tdouble ata_y=0.0;\r\n\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\r\n\t\t\t\t\tif(urg_data.leng[i]==0){\r\n\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\telse{\t\t\t\t\t\t\r\n\t\t\t\t\t\tdouble oldleng=urg_data.leng[i];\r\n\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\tif(temp_leng<oldleng){\r\n\t\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfor(int j=0;j<move_obst.n;j++){\r\n\t\tfor(int k=0;k<move_obst.m;k++){\r\n\t\t\tfor(int i=0;i<urg_area.data_num;i++){\r\n\t\t\t\tdouble a1_x=move_obst.obst_x[j][k];\r\n\t\t\t\tdouble a1_y=move_obst.obst_y[j][k];\r\n\t\t\t\tdouble a2_x=move_obst.obst_x[j][k+1];\r\n\t\t\t\tdouble a2_y=move_obst.obst_y[j][k+1];\r\n\t\t\t\tdouble b2_x=urg_area.x[i];\r\n\t\t\t\tdouble b2_y=urg_area.y[i];\r\n\t\t\t\tdouble b1_x=robot.x;\r\n\t\t\t\tdouble b1_y=robot.y;\r\n\t\t\t\tif(cross_check(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y)==true){\r\n\r\n\t\t\t\t\tdouble ata_x=0.0;\r\n\t\t\t\t\tdouble ata_y=0.0;\r\n\t\t\t\t\tif(cross_xy(a1_x,a1_y,a2_x,a2_y,b1_x,b1_y,b2_x,b2_y,ata_x,ata_y)==true){\r\n\r\n\t\t\t\t\t\tif(urg_data.leng[i]==0){\t\r\n\t\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\telse{\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tdouble oldleng=urg_data.leng[i];\r\n\t\t\t\t\t\t\tdouble temp_leng=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\t\t\t\t\t\t\tif(temp_leng<oldleng){\r\n\t\t\t\t\t\t\t\turg_data.leng[i]=sqrt((ata_y-robot.y)*(ata_y-robot.y)+(ata_x-robot.x)*(ata_x-robot.x));\r\n\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n}\r\nvoid read_obstacle(OBSTACLE &obst,string fname){\r\n\tcout << \"Obstacle File reading\" << endl;\r\n\r\n\tstring filename(fname.c_str());\r\n\tstring str_line;\r\n\tifstream ifs( filename.c_str() );\r\n\r\n\tif( !ifs ) {\r\n\t\tcout << \"Error:Input data file not found\" << endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tstring obst_in[1024][4]={};\r\n\r\n\tint line=0;\r\n\tint width=0;\r\n\tgetline( ifs, str_line );\r\n\twhile( getline( ifs, str_line ) ){\r\n\t\tstring token;\r\n\t\tistringstream stream( str_line );\r\n\r\n\t\twhile( getline( stream, token, ',' ) ) {\r\n\t\t\tobst_in[line][width]=token;\r\n\t\t\t//\t\tcout << obst_in[line][width] << \",\";\r\n\t\t\twidth++;\r\n\t\t}\r\n\t\tline++;\r\n\t\twidth=0;\r\n\r\n\t\t//\tcout << endl;\r\n\t}\r\n\r\n\tobst.n=line;\r\n\t//cout<<\"obst:\" <<obst.n<< endl;\r\n\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\tobst.x1[i]=str_double(obst_in[i][0]);\r\n\t\tobst.y1[i]=str_double(obst_in[i][1]);\r\n\t\tobst.x2[i]=str_double(obst_in[i][2]);\r\n\t\tobst.y2[i]=str_double(obst_in[i][3]);\r\n\t}\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\t//cout << obst.x1[i] << \",\";\r\n\t\t//cout << obst.x2[i] << \",\";\r\n\t\t//cout << obst.y1[i] << \",\";\r\n\t\t//cout << obst.y2[i] << \",\";\r\n\t\t//cout << endl;\r\n\t}\r\n\r\n\treturn;\r\n}\r\n\r\nvoid write_obstacle(OBSTACLE &obst,string fname){\r\n\tcout << \"Obstacle File Write\" << endl;\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\tcout << obst.x1[i] << \",\";\r\n\t\tcout << obst.x2[i] << \",\";\r\n\t\tcout << obst.y1[i] << \",\";\r\n\t\tcout << obst.y2[i] << \",\";\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\r\n\tstd::ofstream writing_file;\r\n\twriting_file.open(fname.c_str(), std::ios::out);\r\n\r\n\tstd::cout << \"writing \" << fname << \"...\" << std::endl;\r\n\r\n\twriting_file << \"x1,y1,x2,y2\" << endl;\r\n\r\n\tfor(int i=0;i<obst.n;i++){\r\n\t\twriting_file << obst.x1[i] << \",\";\r\n\t\twriting_file << obst.y1[i] << \",\";\r\n\t\twriting_file << obst.x2[i] << \",\";\r\n\t\twriting_file << obst.y2[i] << \",\";\r\n\t\twriting_file << endl;\r\n\t}\r\n\treturn;\r\n}\r\n\r\nvoid To_deadlock_back(double _goal_x,double _goal_y,double _goal_theta,double robot_x,double robot_y,double robot_theta,\r\n\t\t\t\t\tdouble &speed,double &turn,double goal_reach_dis){\r\n\r\n\tdouble goal_x=_goal_x-robot_x;\r\n\tdouble goal_y=_goal_y-robot_y;\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble goal_theta=_goal_theta;\r\n\tdouble sub_rad=goal_theta-robot_theta;\r\n\t\r\n\t//ゴールしているなら抜ける\r\n\tif(goal_l<goal_reach_dis) return;\r\n\r\n\tstatic double flg_time=0.0;\r\n\tstatic double back_time=0.0;\r\n\r\n\tconst double goal_limit=2.0;\r\n\tconst double speed_min=0.1;\r\n\tconst double turn_min=0.1;\r\n\tconst double time_limit=3.0;\r\n\r\n\tdouble back_speed_v=-0.20;\r\n\tdouble back_time_para=5.0;\r\n\t\r\n\tdouble dtime=get_dtime();\r\n\tif(back_time>0.1){\r\n\t\tspeed=back_speed_v;\r\n\t\tturn =0.30;\r\n\t\tback_time-=dtime;\r\n\t}\r\n\telse{\r\n\t\tback_time=0.0;\r\n\t}\r\n\r\n\t//ゴールより遠く、速度が0\r\n\tif((goal_l>goal_limit)&&(speed<speed_min)&&(turn<turn_min)){\r\n\t\tflg_time+=dtime;\r\n\t\tif(flg_time>time_limit){\r\n\t\tback_time=back_time_para;\r\n\t\tflg_time=0.0;\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tflg_time=0.0;\r\n\t}\r\n\r\n\r\n}\r\n\r\n\r\nint To_goal_near(double _goal_x,double _goal_y,double _goal_theta,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis){\r\n\t\r\n\tdouble goal_x=_goal_x-robot_x;\r\n\tdouble goal_y=_goal_y-robot_y;\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble goal_theta=_goal_theta;\r\n\tdouble sub_rad=goal_theta-robot_theta;\r\n\r\n\t//ゴールにまだ到着していない抜ける\r\n\tif(goal_l>goal_reach_dis*3.0) \r\n\t\treturn 0;\r\n\r\n\tif(fabs(goal_theta-robot_theta)>1.0*PI){\r\n\t\tif(fabs(goal_theta-robot_theta+4.0*PI)<fabs(goal_theta-robot_theta)){\r\n\t\t\tsub_rad=goal_theta-robot_theta+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_theta-robot_theta-4.0*PI)<fabs(goal_theta-robot_theta)){\r\n\t\t\tsub_rad=goal_theta-robot_theta-2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_theta-robot_theta+2.0*PI)<fabs(goal_theta-robot_theta)){\r\n\t\t\tsub_rad=goal_theta-robot_theta+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_theta-robot_theta-2.0*PI)<fabs(goal_theta-robot_theta)){\r\n\t\t\tsub_rad=goal_theta-robot_theta-2.0*PI;\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n//\tdouble circling_turn_gain=1.0;\r\n//\tdouble circling_turn_max=0.4;\r\n\r\n\tdouble turn_speed=fabs(sub_rad);\r\n\tif(turn_speed>circling_turn_max)turn_speed=circling_turn_max;\r\n\t\r\n\tdouble sub_rad_limit=0.1;\r\n\tif(turn_speed<sub_rad_limit) turn=0;\r\n\telse if(sub_rad>0) turn=-1*turn_speed*circling_turn_gain;\r\n\telse if((sub_rad<0)) turn=1*turn_speed*circling_turn_gain;\r\n\r\n\treturn 1;\r\n}\r\n\r\nvoid To_goal_velocity(double _goal_x,double _goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis,double turn_limit){\r\n\r\n\tdouble goal_x=_goal_x-robot_x;\r\n\tdouble goal_y=_goal_y-robot_y;\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble goal_rad=(-1)*atan2(goal_x,goal_y);\r\n\tdouble robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\r\n\tdouble sub_rad=goal_rad-robot_theta_fmod;\r\n\r\n\tconst double goal_error=5.0;\t\t\t//ゴールに近くないのに5m離れている。\r\n\tif((_goal_x==0.0)&&(_goal_y==0.0)&&(goal_l>goal_error)) {\r\n\t\tspeed=0.0;\t\r\n\t\tturn=0.0;\r\n\t\tcout<<\"To_goal_velocity _error\"<<endl;\r\n\t\treturn;\r\n\t}\r\n\r\n\tif(fabs(goal_rad-robot_theta_fmod)>1.0*PI){\r\n\t\tif(fabs(goal_rad-robot_theta_fmod+4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod-4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod+2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod-2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t}\r\n\r\n\tdouble x=goal_l;\r\n\tspeed=fabs(x)*target_speed_gain;\r\n\r\n\tdouble turn_speed=fabs(sub_rad);\r\n\tdouble r=sub_rad;\r\n\r\n\tif(turn_speed>circling_turn_max) turn_speed=circling_turn_max;\r\n\r\n\t\r\n\tif(sub_rad>=0) turn=-1*turn_speed*target_turn_gain;\r\n\telse if((sub_rad<=0)) turn=1*turn_speed*target_turn_gain;\r\n\r\n\tif(turn_speed>=turn_limit)\tspeed=0.0;\r\n\tif(turn_speed<=-turn_limit)\tspeed=0.0;\r\n\r\n\tif(speed>target_speed_max)\tspeed=target_speed_max;\r\n\tif(goal_l<goal_reach_dis) speed=0.0;\t\r\n\r\n//\tcout<<\"goal_l\"<<goal_l<<endl;\r\n//\tcout<<\"sub_rad\"<<sub_rad<<endl;\r\n//\tcout<<\"speed\"<<speed<<endl;\r\n//\tcout<<\"turn\"<<turn<<endl;\r\n\r\n\r\n\treturn ;\r\n}\r\n\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn){\r\n\r\n\tdouble goal_x=path.x[path.now_n]-robot_x;\r\n\tdouble goal_y=path.y[path.now_n]-robot_y;\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble goal_rad=(-1)*atan2(goal_x,goal_y);\r\n\r\n\t//double moving_goal_limit=0.5;\r\n\r\n\tif(goal_l<moving_goal_limit){\t\t\t\r\n\t\tif(path.now_n+1<path.n){\t\r\n\t\t\tpath.now_n++;\r\n\t\t}\r\n\t\telse if(path.now_n+1==path.n) {\r\n\t\t\tspeed=0;\r\n\t\t\tturn=0;\r\n\t\t}\r\n\t}\r\n\telse{\t\t\t\r\n\r\n\t\tTo_goal_velocity( path.x[path.now_n], path.y[path.now_n],robot_x,robot_y,robot_theta,speed,turn,moving_goal_limit,3.14*2.0);\r\n\t}\r\n\t//cout<<\"n:\"<<path.now_n<<\"_x:\"<<path.x[path.now_n]<<\"_y:\"<<path.y[path.now_n]<<\"_\"<<path.n<<endl;\r\n\treturn;\r\n}\r\n\r\n\r\n\r\nvoid dynamic_windows_approach(URG urg_data,double path_x[][DATA_SEQ],double path_y[][DATA_SEQ],double path_cost[],int &path_size,double robot_v,double robot_w,double &best_v,double &best_w,int flg){\r\n//\tconst double dwa_robot_v_max=0.30;\r\n//\tconst double dwa_robot_v_min=0.01;\r\n//\tconst double dwa_robot_size=0.20;\t\t\r\n//\tconst double dwa_urg_fail_min=0.03;\t\r\n//\tconst double dwa_dt=0.15;\r\n\r\n\tif(robot_v>dwa_robot_v_max)best_v=dwa_robot_v_max;\r\n\tif(robot_v<dwa_robot_v_min)best_v=dwa_robot_v_min;\r\n\t\t\r\n\tint future_cnt=25;\t\t\t\t\t\r\n\tfor(int i = 0;i < 1000;i++){\r\n\t\tfor(int j = 0;j < DATA_SEQ;j++){\r\n\t\t\tpath_x[i][j]=0.0;\r\n\t\t\tpath_y[i][j]=0.0;\r\n\t\t}\r\n\t}\r\n\r\n\tbest_v=robot_v;\r\n\tbest_w=robot_w;\r\n\r\n\tif(best_v<0.01)\treturn;\r\n\r\n\tflg=0;\r\n\tdouble urg_x[2000]={};\r\n\tdouble urg_y[2000]={};\r\n\tdouble urg_l[2000]={};\r\n\r\n\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\turg_x[i]=(-1)*urg_data.leng[i]*sin(i*urg_data.reso+urg_data.start_rad);\r\n\t\turg_y[i]=urg_data.leng[i]*cos(i*urg_data.reso+urg_data.start_rad);\r\n\t\turg_l[i]=sqrt(urg_x[i]*urg_x[i]+urg_y[i]*urg_y[i]);\r\n\t}\r\n\r\n\tdouble path_cost_w[2000]={};\r\n\tdouble path_cost_v[2000]={};\r\n\tint cnt=0;\r\n\r\n\tdouble v_range_s=0.1;\r\n\tdouble w_range=PI;\r\n\tdouble dv=robot_v/10.0;\r\n\tdouble dw=w_range/10.0;\r\n\r\n//\tconst double dwa_v_weight=5.0;\r\n//\tconst double dwa_w_weight=10.0;\r\n//\tconst double dwa_dis_weight=0.10;\r\n//\tconst double dwa_leng_weight=0.1;\r\n//\tconst double dwa_ac_trans_limit=2.0;\r\n//\tconst double dwa_ac_rot_limit=2.0;\r\n\tconst double dwa_dis_max=5.0;\r\n\t\r\n\t//\tglPointSize(2.0);\r\n\t\r\n\t\r\n\r\n\tdouble x=0;\r\n\tdouble y=0;\r\n\tdouble theta=0;\r\n\tint danger_flg_now=0;\r\n\tfor(int k = 0;k < future_cnt;k++){\r\n\t\ttheta+= robot_w*dwa_dt;\r\n\t\tx+= -robot_v*sin(-theta)*dwa_dt;\r\n\t\ty+= robot_v*cos(-theta)*dwa_dt;\r\n\t\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\t\tif(urg_l[i]>dwa_urg_fail_min){\r\n\t\t\t\tdouble dist=sqrt((x-urg_x[i])*(x-urg_x[i])+(y-urg_y[i])*(y-urg_y[i]));\r\n\t\t\t\tif(dist<dwa_robot_size) {\r\n\t\t\t\tdanger_flg_now=1;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\t\r\n\r\n\tif(danger_flg_now==0){\r\n\t\tbest_w=robot_v;\r\n\t\tbest_v=robot_v;\r\n\t\treturn ;\r\n\t}\t\t\t\t\r\n\t\t\t\t\r\n\t\r\n\tint w_plus_cnt=0;\t//角速度プラス側のカウンター\r\n\tint w_minus_cnt=0;\t//角速度マイナスのカウンター\r\n\t\r\n\tfor(double v=v_range_s;v<robot_v;v+=dv){\t\t\t\t\r\n\t\tfor(double w=robot_w-w_range;w<robot_w+w_range;w+=dw){\t\t\r\n\t\t\tif(v<0)v=0;\r\n\t\t\tdouble x=0;\r\n\t\t\tdouble y=0;\r\n\t\t\tdouble real_v=robot_v;\r\n\t\t\tdouble real_w=0.0;\r\n\t\t\tdouble theta=0;\r\n\t\t\tdouble length =0;\r\n\t\t\tdouble dis_min =1.0;\r\n\t\t\tpath_cost[cnt]=0;\r\n\t\t\tpath_cost_w[cnt]=w;\r\n\t\t\tpath_cost_v[cnt]=v;\r\n\t\t\tfor(int k = 0;k < future_cnt;k++){\r\n\t\t\t\tif(path_cost[cnt]>1000)break;\t\r\n\t\t\t\tif(theta>1.0*PI)break;\t\t\r\n\t\t\t\tif(theta<-1.0*PI)break;\t\t\r\n\r\n\t\t\t\t/*\r\n\t\t\t\tif(fabs(real_v-v)/dwa_dt>dwa_ac_trans_limit){\r\n\t\t\t\t\tif((v-real_v)>=0)\t\treal_v+=dwa_ac_trans_limit*dwa_dt;\r\n\t\t\t\t\telse if((v-real_v)<0)\t\treal_v-=dwa_ac_trans_limit*dwa_dt;\t\r\n\t\t\t\t}\r\n\t\t\t\tif(fabs(real_w-w)/dwa_dt>dwa_ac_rot_limit){\r\n\t\t\t\t\tif((w-real_w)>=0)\t\treal_w+=dwa_ac_rot_limit*dwa_dt;\r\n\t\t\t\t\telse if((w-real_w)<0)\t\treal_w-=dwa_ac_rot_limit*dwa_dt;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\ttheta+= real_w*dwa_dt;\t\t\t\t\r\n\t\t\t\tx+= -real_v*sin(-theta)*dwa_dt;\r\n\t\t\t\ty+= real_v*cos(-theta)*dwa_dt;\r\n\t\t\t\tlength += fabs(dwa_dt*v);\r\n\t\t\t\t*/\r\n\t\t\t\ttheta+= w*dwa_dt;\r\n\t\t\t\tx+= -v*sin(-theta)*dwa_dt;\r\n\t\t\t\ty+= v*cos(-theta)*dwa_dt;\r\n\t\t\t\tlength += fabs(dwa_dt*v);\r\n\t\t\t\t\r\n\t\t\t\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\t\t\t\tif(urg_l[i]>dwa_urg_fail_min){\r\n\t\t\t\t\t\tdouble dist=sqrt((x-urg_x[i])*(x-urg_x[i])+(y-urg_y[i])*(y-urg_y[i]));\r\n\t\t\t\t\t\tif(dist<dwa_robot_size) {\r\n\t\t\t\t\t\t\tpath_cost[cnt]=99999.0;\t\t\r\n\t\t\t\t\t\t\tif(w>0) w_plus_cnt++;\r\n\t\t\t\t\t\t\tif(w<0) w_minus_cnt++;\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif(dis_min>dist)\tdis_min=dist;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t\tif(dis_min>dwa_dis_max) dis_min=dwa_dis_max;\r\n\t\t\t\tdouble cost=dwa_v_weight*fabs(v-robot_v)+dwa_w_weight*fabs(w-robot_w)+dwa_leng_weight*length+dwa_dis_weight*(dwa_dis_max-dis_min);\r\n\t\t\t\t\r\n\t\t\t\tif(path_cost[cnt]<cost) {\r\n\t\t\t\t\tpath_cost[cnt]=cost;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpath_x[cnt][k]=x;\r\n\t\t\t\tpath_y[cnt][k]=y;\r\n\r\n\t\t\t}\t\r\n\t\t\tcnt++;\r\n\t\t}\r\n\t}\r\n\tpath_size=cnt;\r\n\tdouble best_cost=99999.0;\r\n\tcout<<\"w_minus_cnt:\"<<w_minus_cnt<<\"_\"<<\"w_plus_cnt:\"<<\"_\"<<w_plus_cnt<<endl;\r\n\tfor(int j=0;j<cnt-1;j++){\r\n\t\t//cout<<\"cost_\"<<path_cost[cnt]<<\"_\"<<best_cost;\r\n\t\tif((path_cost[j]<best_cost)&&(path_cost[j]>0.0001)){\r\n\t\t\tif(path_cost[j]<1000){\r\n\t\t\t\r\n\t\t\tif((w_plus_cnt>w_minus_cnt)&&(path_cost_w[j]<0)){\r\n\t\t\t\tbest_cost=path_cost[j];\r\n\t\t\t\tbest_w=path_cost_w[j];\r\n\t\t\t\tbest_v=path_cost_v[j];\r\n\t\t\t\tflg=1;\t\r\n\t\t\t}\r\n\t\t\tif((w_plus_cnt<w_minus_cnt)&&(path_cost_w[j]>0)){\r\n\t\t\t\tbest_cost=path_cost[j];\r\n\t\t\t\tbest_w=path_cost_w[j];\r\n\t\t\t\tbest_v=path_cost_v[j];\r\n\t\t\t\tflg=1;\t\r\n\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(best_cost==99999.0){\r\n\t\t\tbest_v=0.0;\r\n\t\t\tbest_w=0.0;\r\n\r\n\t\t}\r\n\t}\r\n\tcout<<\"best_\"<<best_v<<\"_\"<<best_w<<\"_\"<<best_cost<<endl;\r\n\r\n\treturn ;\r\n\r\n}\r\n\r\nvoid convert_odom(ROBOT &robot,ROBOT robot_buff){\r\n\r\n\tdouble robot_x_now=robot_buff.x;\r\n\tdouble robot_y_now=robot_buff.y;\r\n\tdouble robot_theta_now=robot_buff.theta;\r\n\tstatic double robot_x_old=robot_buff.x;\r\n\tstatic double robot_y_old=robot_buff.y;\r\n\tstatic double robot_theta_old=robot_buff.theta;\r\n\r\n\r\n\tdouble dx=robot_x_now-robot_x_old;\r\n\tdouble dy=robot_y_now-robot_y_old;\r\n\tdouble dtheta=(robot_theta_now-robot_theta_old);\r\n\r\n\tdouble drot1 = atan2(dy, dx) - robot_theta_old;\r\n double dtrans = sqrt(dx*dx + dy*dy);\r\n\tdouble drot2 = dtheta - drot1;\r\n\r\n\t//set the position\r\n\trobot.x+= dtrans*sin(-robot.theta);\r\n\trobot.y+= dtrans*cos(-robot.theta);\r\n\trobot.theta+= dtheta;\r\n\r\n\trobot_x_old=robot_x_now ;\r\n\trobot_y_old=robot_y_now ;\r\n\trobot_theta_old=robot_theta_now;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6284268498420715, "alphanum_fraction": 0.6442429423332214, "avg_line_length": 24.912569046020508, "blob_id": "93932959fd5b1c5fbf52b3753e4090349599db3b", "content_id": "fea7c9891218df1fe6edff24917004b59b2018af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4742, "license_type": "no_license", "max_line_length": 101, "num_lines": 183, "path": "/n_movebase_sendgoal/src/backup_sendGoals.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <move_base_msgs/MoveBaseAction.h>\n#include <actionlib/client/simple_action_client.h>\n#include <tf/transform_broadcaster.h>\n#include <sstream>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <std_msgs/Int16.h>\n#include <actionlib_msgs/GoalID.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_listener.h>\ntf::TransformListener *tflistener;\n\ntypedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;\nros::Publisher goal_pub;\n\n\nint flag=0;\nvoid vel_Callback(const geometry_msgs::Twist::ConstPtr &vel_msg)\n{\n flag=1;\n /*\n MoveBaseClient ac(\"move_base\", true);\n\n while (!ac.waitForServer(ros::Duration(5.0)))\n {\n\tROS_INFO(\"Waiting for the move_base action server\");\n }\n\n move_base_msgs::MoveBaseGoal goal;\n\n goal.target_pose.header.frame_id = \"map\";\n goal.target_pose.header.stamp = ros::Time::now();\n\n goal.target_pose.pose.position.x = 0.0;\n goal.target_pose.pose.position.y = 0.0;\n goal.target_pose.pose.orientation.w = 1.0;\n\n ROS_INFO(\"Sending goal\");\n ac.sendGoal(goal);\n\n ac.waitForResult();\n\n if (ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED)\n\tROS_INFO(\"You have arrived to the goal position\");\n else\n {\n\tROS_INFO(\"The base failed for some reason\");\n }*/\n}\n\nvoid joyCallback(const std_msgs::Int16::ConstPtr &msg)\n{\n if (msg->data == 1)\n {\n flag=1;\n/*\n\tMoveBaseClient ac(\"move_base\", true);\n\n\twhile (!ac.waitForServer(ros::Duration(5.0)))\n\t{\n\t ROS_INFO(\"Waiting for the move_base action server\");\n\t}\n\n\tmove_base_msgs::MoveBaseGoal goal;\n\n\tgoal.target_pose.header.frame_id = \"map\";\n\tgoal.target_pose.header.stamp = ros::Time::now();\n\n\tgoal.target_pose.pose.position.x = 0.0;\n\tgoal.target_pose.pose.position.y = 0.0;\n\tgoal.target_pose.pose.orientation.w = 1.0;\n\n\tROS_INFO(\"Sending goal\");\n\tac.sendGoal(goal);\n\n\tac.waitForResult();\n\n\tif (ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED)\n\t ROS_INFO(\"You have arrived to the goal position\");\n\telse\n\t{\n\t ROS_INFO(\"The base failed for some reason\");\n\t}\n }\n*/\n// geometry_msgs::PoseStamped goal_p;\n// std::string frame = \"/map\";\n// goal_p.header.frame_id = frame.c_str();\n\n// goal_p.header.stamp = ros::Time::now();\n//\tgoal_p.pose.position.x = 0.0;\n//\tgoal_p.pose.position.y = 0.0;\n // \tgoal_p.pose.position.z = 0.0;\n//\tgoal_p.pose.orientation.w = tf::createQuaternionMsgFromYaw(0.0);\n\n//\tROS_INFO(\"Sending goal\");\n // goal_pub.publish(goal_p);\n }\n\n return;\n}\nvoid joyCallback2(const std_msgs::Int16::ConstPtr &msg)\n{\n if (msg->data == 1)\n {\n\tflag=2;\n\n\t}\n\n\n\n\n return;\n}\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"docu_send_navigation_goals\");\n \n ros::NodeHandle nh_;\n\n// ros::Publisher goal_pub = nh_.advertise<geometry_msgs::PoseStamped>(\"/rwar\", 10);\n ros::Publisher goal_pub = nh_.advertise<geometry_msgs::PoseStamped>(\"/move_base_simple/goal\", 1);\n // ros::Publisher goal_pub2 = nh_.advertise<actionlib_msgs::GoalID>(\"/move_base/cancel\", 1);\n \n \n ros::Subscriber vel_sub_= nh_.subscribe<geometry_msgs::Twist>(\"cmd_goal_pos\", 10, &vel_Callback);\n ros::Subscriber joy_subscriber = nh_.subscribe(\"button5\", 10, joyCallback);\n ros::Subscriber joy_subscriber2 = nh_.subscribe(\"button6\", 10, joyCallback2);\n\n tf::StampedTransform transform;\n tf::TransformListener listener(ros::Duration(10));\n\n\n ros::Rate r(10.0);\n while (nh_.ok())\n {\n\n\t\tif(flag==1){\n\t\tROS_INFO(\"Please provide x and y of the goal!\");\n geometry_msgs::PoseStamped msg;\n msg.header.frame_id = \"/map\";\n msg.pose.position.x = 0;\n msg.pose.position.y = 0;\n msg.pose.position.z = 0.0;\n msg.pose.orientation.x = 0.0;\n msg.pose.orientation.y = 0.0;\n msg.pose.orientation.z = 0.0;\n msg.pose.orientation.w = 1.0;\n goal_pub.publish(msg);\n\t\tflag=0;\n\t\t}\n\n\t\tif(flag==2){\n\t\tROS_INFO(\"stop!\");\n\t\tlistener.lookupTransform(\"map\", \"base_link\",ros::Time(0), transform);\n\t\t\n// actionlib_msgs::GoalID msg;\n geometry_msgs::PoseStamped msg;\n msg.header.frame_id = \"/map\";\n msg.pose.position.x = transform.getOrigin().x();\n msg.pose.position.y = transform.getOrigin().y();\n msg.pose.position.z = transform.getOrigin().z();\n msg.pose.orientation.x = transform.getRotation().getX();\n msg.pose.orientation.y = transform.getRotation().getY();\n msg.pose.orientation.z = transform.getRotation().getZ();\n msg.pose.orientation.w = transform.getRotation().getW();\n goal_pub.publish(msg);\n\t\tflag=0;\n\t\t}\n\n\n\n\n\tros::spinOnce();\n\tr.sleep();\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7879580855369568, "alphanum_fraction": 0.7879580855369568, "avg_line_length": 62.33333206176758, "blob_id": "f18bdcd48811af720b0649f38de2a456e05d6e63", "content_id": "81c08211f9dbadd8951aea2b46bedf739a671e22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 382, "license_type": "no_license", "max_line_length": 242, "num_lines": 6, "path": "/n_cartographer_mapsave/README.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "https://google-cartographer-ros.readthedocs.io/en/latest/ros_api.html#services\n\nServices\nwrite_state (cartographer_ros_msgs/WriteState)\n\nWrites the current internal state to disk into filename. The file will usually end up in ~/.ros or ROS_HOME if it is set. This file can be used as input to the assets_writer_main to generate assets like probability grids, X-Rays or PLY files.\n\n\n" }, { "alpha_fraction": 0.60856693983078, "alphanum_fraction": 0.629861056804657, "avg_line_length": 25.769407272338867, "blob_id": "d261933fdca3d0e39051f5648c2c4b363fe3364d", "content_id": "acb241a394e0e49ca5b1ca3db681fb4a72059bcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12453, "license_type": "no_license", "max_line_length": 124, "num_lines": 438, "path": "/n_localpathplan/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\n#include <math.h>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <vector>\r\n#include <string>\r\n#include <limits>\r\nusing namespace std;\r\n\r\n#include <ros/ros.h>\r\n#include <actionlib_msgs/GoalStatusArray.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/transform_listener.h>\r\n#include <nav_msgs/Path.h>\r\n\r\n#include <ros/ros.h>\r\n#include <pcl/point_cloud.h>\r\n#include <pcl_conversions/pcl_conversions.h>\r\n#include <sensor_msgs/PointCloud2.h>\r\n#include <sensor_msgs/PointCloud.h>\r\n#include <sensor_msgs/point_cloud_conversion.h>\r\n#include <std_msgs/Float32.h>\r\n#include <signal.h>\r\n#include \"geometory.h\"\r\n\r\ntf::TransformListener *tflistener;\r\nros::Publisher cmd_vel_pub_;\r\nros::Publisher dwa_pub;\r\nvoid mySigintHandler(int);\r\n\r\nstruct URG urg_data;//測域センサのデータ\r\n\r\n\r\n//Robot制御のパラメータ\r\ndouble goal_x, goal_y;\r\ndouble goal_theta;\r\n\r\ndouble short_goal_dis=1.0;\r\ndouble goal_reach_dis = 0.1; \t\t//ゴールに到達したとする距離\r\ndouble turn_limit = M_PI / 2.0;\t\t//その角度以上で旋回\r\n\r\ndouble moving_goal_limit=0.5;\t\t//\r\ndouble target_speed_gain=1.0;\t\t//\r\ndouble target_turn_gain=1.0;\t\t//\r\n\r\ndouble target_speed_max=0.5;\t\t//\r\ndouble circling_turn_gain=1.0;\t\t//\r\ndouble circling_turn_max=0.4;\t\t//\r\ndouble dwa_robot_v_max=0.30;\t\t//\r\ndouble dwa_robot_v_min=0.01;\t\t//\r\n\r\ndouble dwa_robot_size=0.20;\t\t//\r\ndouble dwa_urg_fail_min=0.03;\t\t//\r\ndouble dwa_dt=0.15;\t\t\t//\r\ndouble dwa_v_weight=5.0;\t\t//\r\ndouble dwa_w_weight=10.0;\t\t//\r\ndouble dwa_dis_weight=0.10;\t\t//\r\ndouble dwa_leng_weight=0.1;\t\t//\r\ndouble dwa_ac_trans_limit=2.0;\t\t//\r\ndouble dwa_ac_rot_limit=2.0;\t\t//\r\ndouble movebase_delay_time_for_panunit=4.0;//\r\nint debug_mode;\r\n\r\ndouble path_x[2000][100] = {};\r\ndouble path_y[2000][100] = {};\r\ndouble path_cost[2000] = {};\r\nint path_size = 0;\r\n\r\ndouble target_v=0.0;\r\ndouble target_w=0.0;\r\n\r\ndouble myrobot_x;\r\ndouble myrobot_y;\r\ndouble myrobot_th;\r\n\r\ndouble myrobot_v;\r\ndouble myrobot_w;\r\n\r\ndouble danger_dis=0.5;\r\nint danger_count_thresh=300;\r\nint danger_count=0;\r\nbool danger_flg=0;\r\nros::Publisher danger_count_pub;\r\n\r\nvoid main_process(){\r\n\r\n double vel_v=0.0;\r\n double vel_w=0.0;\r\n double best_v = 0, best_w = 0;\r\n\r\n //目標速度が入力されていたらそれに従う\r\n //if((target_v==0.0)&&(target_w==0.0)){\r\n To_goal_velocity(goal_x, goal_y, myrobot_x, myrobot_y, -myrobot_th, vel_v, vel_w, goal_reach_dis, turn_limit);\r\n\r\n //ゴールに到着したら、姿勢角度をあわせる。\r\n int goal_flg_near=false;\r\n goal_flg_near=To_goal_near(goal_x, goal_y, goal_theta, myrobot_x, myrobot_y, -myrobot_th, vel_v, vel_w, goal_reach_dis);\r\n\r\n // cout<<\"goal_x:\"<<goal_x<<\"_goal_y:\"<<goal_y<<endl;\r\n\r\n //}\r\n //else{\r\n // vel_v=target_v;\r\n // vel_w=target_w;\r\n //}\r\n\r\n\r\n\r\n //myrobot_v = vel_v;\r\n //myrobot_w = vel_w;\r\n\r\n\r\n\r\n //DWAでの経路探索\r\n //velが早い・障害物が大きいとデットロックする\r\n \tint path_flg;\r\n dynamic_windows_approach(urg_data, path_x, path_y, path_cost, path_size, vel_v,vel_w, best_v, best_w, path_flg);\r\n myrobot_v = best_v;\r\n myrobot_w = best_w;\r\n\tcout<<\"myrobot_v:\"<<myrobot_v<<\"_myrobot_w:\"<<myrobot_w<<endl;\r\n /*\r\n pcl::PointCloud<pcl::PointXYZ> cloud;\r\n sensor_msgs::PointCloud2 output;\r\n cloud.width = 80*49;\r\n cloud.height = 1;\r\n cloud.points.resize(cloud.width * cloud.height);\r\n int cnt=0;\r\n for(int i=0;i<1000;i++){\r\n for(int j=0;j<100;j++){\r\n if((path_x[j][i]!=0)&&(path_y[j][i]!=0)){\r\n cloud.points[cnt].x = path_x[i][j];\r\n cloud.points[cnt].y = path_y[i][j];\r\n cloud.points[cnt].z = path_cost[i];\r\n cnt++;\r\n}\r\n}\r\n}\r\n\r\n\r\n\r\npcl::toROSMsg(cloud, output);\r\noutput.header.frame_id = \"base_link\";\r\ndwa_pub.publish(output);\r\n*/\r\n// cout<<best_v<<endl;\r\n// cout<<best_w<<endl;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\nint wait_sleep(double sec){\r\n int msen=1000.0*sec;\r\n usleep(msen * 1000);\r\n return 0;\r\n}\r\n\r\n\r\n//move_baseが動いているかどうかのflg\r\nbool move_base_robo_moving_status=0;\r\n\r\nvoid navStatusCallBack(const actionlib_msgs::GoalStatusArray::ConstPtr &status){\r\n int status_id = 0;\r\n static int old_status = 0;\r\n //status=3;goal, //status=1;moving\r\n\r\n if (!status->status_list.empty()) {\r\n actionlib_msgs::GoalStatus goalStatus = status->status_list[0];\r\n status_id = goalStatus.status;\r\n // cout<<goalStatus.text<<endl;\r\n }\r\n\r\n if(status_id==1){\r\n //もし起動開始であれば\r\n if(old_status==false){\r\n cout<<\"waiting...\"<<endl;\r\n //wait_sleep(movebase_delay_time_for_panunit);\r\n }\r\n cout<<\"run_start\"<<endl;\r\n move_base_robo_moving_status=true;\r\n }\r\n\r\n if((status_id==3)||(status_id==0)){\r\n move_base_robo_moving_status=false;\r\n }\r\n\r\n old_status=move_base_robo_moving_status;\r\n\r\n}\r\n\r\n\r\nvoid scanCallback(const sensor_msgs::LaserScanConstPtr &scan_msg){\r\n double range_min = scan_msg->range_min;\r\n double range_max = scan_msg->range_max;\r\n double angle_increment = scan_msg->angle_increment;\r\n double angle_min = scan_msg->angle_min;\r\n double angle_max = scan_msg->angle_max;\r\n int data_num = (angle_max - angle_min) / angle_increment;\r\n\r\n for (unsigned int i = 0; i < data_num; ++i){\r\n urg_data.leng[i] = scan_msg->ranges[i];\r\n if (isnan(urg_data.leng[i]))\r\n urg_data.leng[i] = 0.0;\r\n }\r\n urg_data.data_num = data_num;\r\n urg_data.start_rad = scan_msg->angle_min;\r\n urg_data.reso = scan_msg->angle_increment;\r\n urg_data.leng_max = range_max;\r\n urg_data.leng_min = range_min;\r\n danger_count=0;\r\n for(unsigned int i = 0; i < data_num; ++i){\r\n urg_data.leng[i]=scan_msg->ranges[i];\r\n if(urg_data.leng[i]<danger_dis)danger_count++;\r\n }\r\n if(danger_count>danger_count_thresh)danger_flg=1;\r\n else danger_flg=0;\r\n\r\n std_msgs::Float32 msg_float;\r\n msg_float.data = danger_count;\r\n danger_count_pub.publish(msg_float);\r\n\r\n\r\n\r\n}\r\n\r\n\r\nvoid GetRPY(const geometry_msgs::Quaternion &quat, double &theta){\r\n tf::Quaternion q(quat.x, quat.y, quat.z, quat.w);\r\n tf::Matrix3x3 m(q);\r\n double roll, pitch, yaw;\r\n m.getRPY(roll, pitch, yaw);\r\n theta = -yaw;\r\n}\r\n\r\n\r\nvoid pathCallback(const nav_msgs::PathConstPtr &path){\r\n\r\n\r\n//パスを受信\r\n if (path->poses.size() == 0) {\r\n myrobot_v = 0.0;\r\n myrobot_w = 0.0;\r\n return;\r\n }\r\n geometry_msgs::PoseStamped start_pos_map;\r\n geometry_msgs::PoseStamped start_pos_base_link;\r\n geometry_msgs::PoseStamped end_pos_map;\r\n geometry_msgs::PoseStamped end_pos_base_link;\r\n\r\n int m = (path->poses.size() - 1);\r\n int short_goal_dis_no=0;\r\n double dis=0.0;\r\n for(int i=0;i<m-1;i++){\r\n start_pos_map = path->poses[i];\r\n end_pos_map = path->poses[i+1];\r\n\r\n double sx=start_pos_map.pose.position.x;\r\n double sy=start_pos_map.pose.position.y;\r\n double ex=end_pos_map.pose.position.x;\r\n double ey=end_pos_map.pose.position.y;\r\n dis+=sqrt((ex-sx)*(ex-sx)+(ey-sy)*(ey-sy));\r\n\r\n if((short_goal_dis_no==0)&&(short_goal_dis<dis)) short_goal_dis_no=i;\r\n }\r\n\r\n if(short_goal_dis_no!=0) m=short_goal_dis_no;\r\n\r\n\r\n start_pos_map = path->poses[0];\r\n end_pos_map = path->poses[m];\r\n goal_x = -end_pos_map.pose.position.y;\r\n goal_y = end_pos_map.pose.position.x;\r\n\r\n geometry_msgs::Quaternion end_orientation = end_pos_map.pose.orientation;\r\n double theta = 0.0;\r\n GetRPY(end_orientation, theta);\r\n goal_theta = -theta;\r\n// cout<<\"goal_x:\"<<goal_x<<\"_goal_y:\"<<goal_y<<\"goal_theta:\"<<goal_theta<<endl;\r\n// cout<<\"myrobot_x:\"<<myrobot_x<<\"_myrobot_y:\"<<myrobot_y<<endl;\r\n\r\n}\r\n\r\nvoid vel_Callback(const geometry_msgs::Twist &vel_msg){\r\n target_v = vel_msg.linear.x;\r\n target_w = -vel_msg.angular.z;\r\n}\r\n\r\nvoid mySigintHandler(int sig)\r\n{\r\n geometry_msgs::Twist base_cmd;\r\n base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n cmd_vel_pub_.publish(base_cmd);\r\n\r\n printf(\"shutdown catch signal %d \\n\", sig);\r\n ros::shutdown();\r\n}\r\n\r\nint main(int argc, char *argv[]){\r\n\r\n ros::init(argc, argv, \"n_navigation_localpathplan\");\r\n\r\n ros::NodeHandle private_nh(\"~\");\r\n\r\n private_nh.param(\"short_goal_dis\", short_goal_dis, 1.0);\r\n private_nh.param(\"goal_reach_dis\", goal_reach_dis, 0.1);\r\n private_nh.param(\"turn_limit\", turn_limit, 0.70);\r\n private_nh.param(\"moving_goal_limit\", moving_goal_limit, 0.5);\r\n private_nh.param(\"target_speed_gain\", target_speed_gain, 1.0);\r\n private_nh.param(\"target_turn_gain\", target_turn_gain, 1.0);\r\n\r\n private_nh.param(\"target_speed_max\", target_speed_max, 0.5);\r\n private_nh.param(\"circling_turn_gain\", circling_turn_gain, 1.0);\r\n private_nh.param(\"circling_turn_max\", circling_turn_max, 0.4);\r\n private_nh.param(\"dwa_robot_v_max\", dwa_robot_v_max, 0.5);\r\n private_nh.param(\"dwa_robot_v_min\", dwa_robot_v_min, 0.01);\r\n\r\n private_nh.param(\"dwa_robot_size\", dwa_robot_size, 0.5);\r\n private_nh.param(\"dwa_urg_fail_min\", dwa_urg_fail_min, 0.01);\r\n private_nh.param(\"dwa_dt\", dwa_dt, 0.15);\r\n private_nh.param(\"dwa_v_weight\", dwa_v_weight, 5.0);\r\n private_nh.param(\"dwa_w_weight\", dwa_w_weight, 10.0);\r\n private_nh.param(\"dwa_dis_weight\", dwa_dis_weight, 0.1);\r\n private_nh.param(\"dwa_leng_weight\", dwa_leng_weight, 0.10);\r\n private_nh.param(\"dwa_ac_trans_limit\", dwa_ac_trans_limit, 2.0);\r\n private_nh.param(\"dwa_ac_rot_limit\", dwa_ac_rot_limit, 2.0);\r\n private_nh.param(\"movebase_delay_time_for_panunit\", movebase_delay_time_for_panunit, 0.000);\r\n private_nh.param(\"debug_mode\", debug_mode, 1);\r\n\r\n private_nh.param(\"danger_dis\",danger_dis,0.3);\r\n private_nh.param(\"danger_count_thresh\",danger_count_thresh,300);\r\n\r\n\r\n // Graphics GL;\r\n\r\n ros::NodeHandle n;\r\n //LRFの受信\r\n const std::string scan_topic_ = \"scan1\";\r\n ros::Subscriber scan_subscriber_ = n.subscribe(scan_topic_, 10, scanCallback);\r\n //Pathの受信\r\n const std::string path_topic = \"/move_base/TrajectoryPlannerROS/global_plan\";\r\n ros::Subscriber path_subscriber = n.subscribe(path_topic, 10, pathCallback);\r\n\r\n cmd_vel_pub_ = n.advertise<geometry_msgs::Twist>(\"cmd_vel_navi\", 1);\r\n\r\n const std::string vel_topic_ = \"/cmd_vel_target\";\r\n ros::Subscriber cmd_vel = n.subscribe(vel_topic_, 10, vel_Callback);\r\n dwa_pub= n.advertise<sensor_msgs::PointCloud2> (\"dwa_pub\", 1);\r\n\r\n danger_count_pub = n.advertise<std_msgs::Float32>(\"danger_count2\", 10);\r\n //ロボットの状態の受信\r\n ros::Subscriber move_base_status_sub;\r\n move_base_status_sub = n.subscribe<actionlib_msgs::GoalStatusArray>(\"/move_base/status\", 10, &navStatusCallBack);\r\n\r\n ros::Rate r(20.0);\r\n // tf::TransformListener listener;\r\n tf::TransformListener lr(ros::Duration(10));\r\n tflistener = &lr;\r\n\r\n myrobot_v = 0;\r\n myrobot_w = 0;\r\n\r\n target_v = 0.0;\r\n target_w = 0.0;\r\n goal_x = 0.0;\r\n goal_y = 0.0;\r\n\r\n signal(SIGINT, mySigintHandler);\r\n\r\n while (n.ok()){\r\n main_process();\r\n\r\n\r\n tf::StampedTransform transform;\r\n try {\r\n tflistener->waitForTransform(\"/map\", \"/base_link\", ros::Time(0), ros::Duration(1.0));\r\n\r\n tflistener->lookupTransform(\"/map\", \"/base_link\",\r\n ros::Time(0), transform);\r\n }\r\n catch (tf::TransformException ex)\r\n {\r\n ROS_ERROR(\"%s\", ex.what());\r\n ros::Duration(1.0).sleep();\r\n }\r\n\r\n geometry_msgs::Quaternion odom_quat;\r\n odom_quat.x = transform.getRotation().x();\r\n odom_quat.y = transform.getRotation().y();\r\n odom_quat.z = transform.getRotation().z();\r\n odom_quat.w = transform.getRotation().w();\r\n double theta = 0.0;\r\n GetRPY(odom_quat, theta);\r\n myrobot_x = -transform.getOrigin().y();\r\n myrobot_y = transform.getOrigin().x();\r\n myrobot_th = theta;\r\n\r\n\r\n geometry_msgs::Twist base_cmd;\r\n base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n\r\n if(move_base_robo_moving_status==true){\r\n base_cmd.linear.x = myrobot_v * target_speed_gain;\r\n base_cmd.angular.z =- myrobot_w * target_turn_gain;\r\n }\r\n\r\n/* if(debug_mode==1){\r\n base_cmd.linear.x = myrobot_v * target_speed_gain;\r\n base_cmd.angular.z = -myrobot_w * target_turn_gain;\r\n }\r\n*/\r\n if(danger_flg==1){\r\n base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n }\r\n\r\n\r\n\r\n cmd_vel_pub_.publish(base_cmd);\r\n\r\n // cout<<\"v:\"<<base_cmd.linear.x<<\"\\t w:\"<<base_cmd.angular.z <<\"\\n\";\r\n ros::spinOnce();\r\n\r\n r.sleep();\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.543749988079071, "alphanum_fraction": 0.5612499713897705, "avg_line_length": 14.666666984558105, "blob_id": "5dd063792da93bc4dfd432661d0108758281a479", "content_id": "f36e289773437b3c954c282f5c8164a065b19b7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 816, "license_type": "no_license", "max_line_length": 68, "num_lines": 48, "path": "/old/map_editor_simple/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n\r\n#include \"viewgui.h\"\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\nusing namespace std;\r\n#include <ctime>\r\n\r\n//Robot制御のパラメータ\r\n\r\n\r\n\r\n#ifdef _WIN32\r\n#include <windows.h>\r\n#pragma comment(linker, \"/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup\") \r\n#else\r\n#include <sys/time.h>\r\n#include <unistd.h>\r\n#include <ros/ros.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n\r\n\r\n#endif\r\n\r\n\r\n\r\nint main(int argc, char* argv[]) {\r\n\tGraphics GL;\r\n\r\n\r\n\tfor(;;){\r\n//\tSleep(100);\r\n\tusleep(1000*1000);\r\n\t\t\r\n\t}\r\n\treturn 0;\r\n\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6737805008888245, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 27.39130401611328, "blob_id": "5937616cc4bec41f1a884e03cd880c5e828e0745", "content_id": "33754d33c8c530422c25549c470dcc87f94f41d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 656, "license_type": "no_license", "max_line_length": 99, "num_lines": 23, "path": "/n_3d_robot_sim/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\nall:\n\tmake -f Makefile.docu_3D_lrf_simlator\n\tcp docu_3D_lrf_simlator ../../bin\n#\tcp docu_3D_lrf_simlator_setting.ini ../../bin\n\tcp obstacle.csv ../../bin\n\nclean:\n\tmake -f Makefile.docu_3D_lrf_simlator clean\n\trm -f *~\n\t\n\t\ninstall:\n\tmkdir -p $(install_prefix)/lib/$(project)\n\tmkdir -p $(install_prefix)/share/$(project)/launch\n\techo \"<package><name>$(project)</name></package>\" > $(install_prefix)/share/$(project)/package.xml\n\ttouch $(install_prefix)/.catkin\n\tcp -a docu_3D_lrf_simlator $(install_prefix)/lib/$(project)\n\nuninstall:\n\trm -f $(install_prefix)/lib/$(project)/docu_3D_lrf_simlator\n\n\n\n" }, { "alpha_fraction": 0.5495476722717285, "alphanum_fraction": 0.5811060667037964, "avg_line_length": 28.298192977905273, "blob_id": "f0fbece21286e9aa183029c0a959717bd9a199c8", "content_id": "4f0409de519ce834ece7df6d4533e7521f77723e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9902, "license_type": "no_license", "max_line_length": 165, "num_lines": 332, "path": "/n_3d_robot_sim/src/gl_win_sub.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <GL/glu.h>\n#include \"opencv_inc.h\"\n#include <iostream>\n#include <vector>\n#include <limits>\n\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/common/common.h>\n#include <pcl_ros/transforms.h>\nusing namespace std;\n\n//Subwindow\nextern int xBegin2, yBegin2;\nextern int mButton2;\nextern float distance_gl2, twist2, elevation2, azimuth2;\nextern float xOrig2, yOrig2, zOrig2;\n#include \"geometory.h\"\nextern double robot_z;\n\n//void display2();\n//void myMouse2( int button, int state, int x, int y );\n//void myMotion2( int x, int y );\n//void resetview2( void );\n//void polarview2( void );\n//void reshape2(int ,int);\n//void myMouse2( int button, int state, int x, int y );\n\nint wait_sleep(double time);\n\nvoid obstacle_view();\nvoid move_obstacle_view();\nextern struct ROBOT myrobot;\n\nchar *outputWindow = \"Output\";\nchar *outputWindow2 = \"Depth\";\nIplImage *video_buf;\nIplImage *video;\nIplImage *depth_buf;\nIplImage *depth_buf2;\nIplImage *depth_buf3;\nIplImage *depth;\n\nconst long width = 320;\nconst long out_width = 320;\nconst long height = 240;\nconst long out_height = 240;\ndouble depth_noise = 0.02;\n\ndouble camera_angleofview=120.0;\n//struct PointCloud pt_xyz;\npcl::PointCloud<pcl::PointXYZRGB> pt_xyz;\npcl::PointCloud<pcl::PointXYZRGB> pt_xyz_out;\nextern double robot_z;\nextern struct ROBOT myrobot;\n\npcl::PointCloud<pcl::PointXYZRGB> rotation_z(pcl::PointCloud<pcl::PointXYZRGB> cloud, double theta);\n\nextern void scene1(double xx,double yy,double theta);\nextern struct MOVE_OBSTACLE move_obst;\nvoid mySetLight();\n\n\nvoid cv_noise(IplImage *input, IplImage *output)\n{ //ノイズを付与する\n double p[3];\n\n for (int y = 0; y < input->height; y++)\n {\n for (int x = 0; x < input->width; x++)\n {\n for (int c = 0; c < input->nChannels; c++)\n {\n p[c] = (unsigned char)input->imageData[input->widthStep * y + x * input->nChannels + c];\n p[c] = p[c] + p[c] * rand_normal(0, 1.0) * depth_noise;\n if (p[c] < 0.0)\n p[c] = 0.0;\n if (p[c] > 255.0)\n p[c] = 255.0;\n output->imageData[output->widthStep * y + x * output->nChannels + c] = (int)p[c];\n }\n }\n }\n}\n\nvoid cv_bridge_init()\n{\n video_buf = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);\n video = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);\n depth_buf = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);\n depth_buf2 = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);\n depth_buf3 = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);\n depth = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);\n\n //cvNamedWindow(outputWindow2, CV_WINDOW_AUTOSIZE);\n}\n\nvoid polarview2(void)\n{\n\n azimuth2 = myrobot.theta / M_PI * 180.0 - 90.0 / M_PI * 180.0;\n xOrig2 = -myrobot.y;\n yOrig2 = -myrobot.x;\n zOrig2 = -robot_z;\n\n //マウスで移動\n glTranslatef(0.0, 0.0, -distance_gl2);\n glRotatef(-twist2, 0.0, 0.0, 1.0);\n glRotatef(-elevation2, 1.0, 0.0, 0.0);\n glRotatef(-azimuth2, 0.0, 1.0, 0.0);\n //キーボードで移動\n glTranslatef(xOrig2, zOrig2, yOrig2);\n\n //cout<<\"twist2:\"<<twist2<<endl;\n //cout<<\"azimuth2:\"<<azimuth2<<endl;\n //cout<<\"elevation2:\"<<elevation2<<endl;\n}\n\nvoid cv_inverse(IplImage *input, IplImage *output)\n{ //反転する\n int N = 5;\n for (int x = 0; x < input->width; x++)\n {\n for (int y = 0; y < input->height; y++)\n {\n if ((int)(input->imageData[y * input->widthStep + x * input->nChannels]) * N >= 255.0)\n {\n output->imageData[(y)*output->widthStep + (x)*output->nChannels + 2] = 0;\n output->imageData[(y)*output->widthStep + (x)*output->nChannels + 1] = 0;\n output->imageData[(y)*output->widthStep + (x)*output->nChannels] = 0;\n }\n else\n {\n output->imageData[(y)*output->widthStep + (x)*output->nChannels + 2] = 255 - (input->imageData[y * input->widthStep + x * input->nChannels + 2]) * N;\n output->imageData[(y)*output->widthStep + (x)*output->nChannels + 1] = 255 - (input->imageData[y * input->widthStep + x * input->nChannels + 1]) * N;\n output->imageData[(y)*output->widthStep + (x)*output->nChannels] = 255 - (input->imageData[y * input->widthStep + x * input->nChannels]) * N;\n }\n }\n }\n //\tcvFlip(output,output,1);\n}\n\n//http://marina.sys.wakayama-u.ac.jp/~tokoi/transparent/showdepth.c\nint gl_showdepth(void)\n{\n GLint view[4];\n GLubyte *buffer;\n /* 現在のビューポートのサイズを得る */\n\n glGetIntegerv(GL_VIEWPORT, view);\n\n buffer = (GLubyte *)malloc(view[2] * view[3]);\n\n if (buffer)\n {\n GLdouble model[16];\n GLdouble proj[16];\n GLdouble ox, oy, oz;\n /* 画面表示の完了を待つ */\n\n glFinish();\n /* デプスバッファの読み込み */\n glReadPixels(view[0], view[1], view[2], view[3],\n GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, depth_buf->imageData);\n\n cvConvertImage(depth_buf, depth_buf2, CV_CVTIMG_FLIP + CV_CVTIMG_SWAP_RB);\n cv_inverse(depth_buf2, depth_buf3);\n\n glGetDoublev(GL_MODELVIEW_MATRIX, model);\n glGetDoublev(GL_PROJECTION_MATRIX, proj);\n gluUnProject(view[0] + 0.5, view[1] + 0.5, 0.0, model, proj, view, &ox, &oy, &oz);\n glRasterPos3d(ox, oy, oz);\n free(buffer);\n\n return 1;\n }\n return 0;\n}\n\nvoid GET_WORLD_COODINATE()\n{\n GLint view[4];\n glGetIntegerv(GL_VIEWPORT, view);\n double modelview[16];\n glGetDoublev(GL_MODELVIEW_MATRIX, modelview);\n\n double projection[16];\n glGetDoublev(GL_PROJECTION_MATRIX, projection);\n\n int viewport[4];\n glGetIntegerv(GL_VIEWPORT, viewport);\n\n float z[320 * 240];\n glReadPixels(view[0], view[1], view[2], view[3], GL_DEPTH_COMPONENT, GL_FLOAT, z);\n pt_xyz.points.resize(width * height);\n\n for (int y = 0; y < height; y++)\n {\n for (int x = 0; x < width; x++)\n {\n double objX, objY, objZ;\n gluUnProject(x, height - y, z[y * width + x], modelview, projection, viewport, &objX, &objY, &objZ);\n //\t pt_xyz.point_x[y * width + x] = objX;\n //\t pt_xyz.point_y[y * width + x] = objY;\n //\t pt_xyz.point_z[y * width + x] = objZ;\n int i=y * width + x;\n pt_xyz.points[i].x = objX-myrobot.y;\n pt_xyz.points[i].y = -objZ+myrobot.x;\n pt_xyz.points[i].z = -objY+robot_z;\n\n \n\n\n pt_xyz.points[i].r = video_buf->imageData[video_buf->widthStep * y + x * video_buf->nChannels + 0];\n pt_xyz.points[i].g = video_buf->imageData[video_buf->widthStep * y + x * video_buf->nChannels + 1];\n pt_xyz.points[i].b = video_buf->imageData[video_buf->widthStep * y + x * video_buf->nChannels + 2];\n\n const double rgb_camera_limit=20.0;\n if(pt_xyz.points[i].y*pt_xyz.points[i].y+pt_xyz.points[i].x*pt_xyz.points[i].x>rgb_camera_limit*rgb_camera_limit){\n pt_xyz.points[i].x =numeric_limits<float>::quiet_NaN();\n pt_xyz.points[i].y =numeric_limits<float>::quiet_NaN();\n pt_xyz.points[i].z=numeric_limits<float>::quiet_NaN();\n }\n\n }\n }\n pt_xyz_out=rotation_z(pt_xyz,myrobot.theta);\n\n\n}\nint read_buf_flg=0;\nvoid display2()\n{\n glClearColor(1, 1, 1, 1);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glPushMatrix();\n polarview2();\n glEnable(GL_DEPTH_TEST);\n\n //メイン描画の関数\n obstacle_view();\n //Robotの表示\n //move_obstacle_view();\n mySetLight();\n for (int i = 0; i < move_obst.n; i++)\n {\n double xx = (move_obst.obst_x[i][0] + move_obst.obst_x[i][2]) / 2.0;\n double yy = (move_obst.obst_y[i][0] + move_obst.obst_y[i][2]) / 2.0;\n double theta = -move_obst.obst_theta[i] + M_PI;\n scene1(xx,yy,theta);\n }\n\n\n //read_buf_flg=1;\n if(read_buf_flg==0){\n GET_WORLD_COODINATE();\n //cout<<width<<endl;\n //cout<<height<<endl;\n glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, video_buf->imageData);\n cvConvertImage(video_buf, video, CV_CVTIMG_FLIP + CV_CVTIMG_SWAP_RB);\n gl_showdepth();\n cvCvtColor(depth_buf3, depth, CV_BGR2GRAY);\n cv_noise(depth, depth);\n }\n\n\n // imshow(outputWindow, video);\n // imshow(outputWindow2, depth);\n\n glPopMatrix();\n glutSwapBuffers();\n glutPostRedisplay();\n\n wait_sleep(10);\n \n // waitKey(10);\n}\n\n//視点のリセット\nvoid resetview2(void)\n{\n distance_gl2 = 0;\n twist2 = 0.0;\n elevation2 = 0.0;\n azimuth2 = 0.0;\n}\nvoid reshape2(int w, int h)\n{\n glutReshapeWindow(width, height);\n\n glViewport(0, 0, w, h);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(camera_angleofview, (double)w / (double)h, 0.05, 100.0);\n glMatrixMode(GL_MODELVIEW);\n}\n\n\n\npcl::PointCloud<pcl::PointXYZRGB> rotation_z(pcl::PointCloud<pcl::PointXYZRGB> cloud, double theta)\n{\n\n Eigen::Matrix4f rot_z;\n pcl::PointCloud<pcl::PointXYZRGB> cloud_out;\n double theta_z = theta ;//角度の変換\n rot_z(0,0) = cos(theta_z);\n rot_z(1,0) = -sin(theta_z);\n rot_z(2,0) = 0.0;\n rot_z(3,0) = 0.0;\n rot_z(0,1) = sin(theta_z);\n rot_z(1,1) = cos(theta_z);\n rot_z(2,1) = 0.0;\n rot_z(3,1) = 0.0;\n rot_z(0,2) = 0.0;\n rot_z(1,2) = 0.0;\n rot_z(2,2) = 1.0;\n rot_z(3,2) = 0.0;\n rot_z(0,3) = 0.0;\n rot_z(1,3) = 0.0;\n rot_z(2,3) = 0.0;\n rot_z(3,3) = 1.0;\n\n pcl::transformPointCloud( cloud, cloud_out, rot_z );\n\n return cloud_out;\n}\n\n" }, { "alpha_fraction": 0.5973597168922424, "alphanum_fraction": 0.6199905872344971, "avg_line_length": 25.848100662231445, "blob_id": "754a0091a59d06dbeae9e22d7317e3298280d506", "content_id": "47b16de29e3902c400ce9093317ead3e608696ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2133, "license_type": "no_license", "max_line_length": 125, "num_lines": 79, "path": "/check_pcl_save/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <cv_bridge/cv_bridge.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <pcl_ros/io/pcd_io.h>\n#include <sensor_msgs/image_encodings.h>\n#include <math.h>\n#include <iostream>\n#include <limits>\n#include <fstream>\n#include <cstdio>\n#include <stdio.h>\n#include <stdio.h>\n#include <stdlib.h>\nusing namespace std;\n\nint flg=0;\nclass SavePCD {\nprivate:\n ros::NodeHandle _nh;\n ros::Subscriber _sub1, _sub2;\n pcl::PointCloud<pcl::PointXYZ> input_cloud;\n int save_count;\n string outfname;\n\npublic:\n SavePCD() : save_count(0) {\n ros::NodeHandle private_nh(\"~\");\n private_nh.param(\"fname\",outfname,std::string(\"pcd_\"));\n\n //* subscribe ROS topics\n // _sub1 = _nh.subscribe (\"/camera/rgb/image_color\", 1, &SavePCD::image_cb, this);\n // ROS_INFO (\"Listening for incoming data on topic /camera/rgb/image_color ...\" );\n _sub2 = _nh.subscribe (\"/blam/blam_slam/octree_map\", 1, &SavePCD::points_cb, this);\n ROS_INFO (\"Listening for incoming data on topic /blam/blam_slam/octree_map ...\" );\n }\n ~SavePCD() {}\n\n //* get points\n void points_cb( const sensor_msgs::PointCloud2ConstPtr& cloud ){\n if ((cloud->width * cloud->height) == 0)\n return;\n pcl::fromROSMsg (*cloud, input_cloud);\n\n // std::stringstream filename2;\n // filename2 << save_count << \".pcd\";\n // pcl::io::savePCDFileBinary( filename2.str(), input_cloud );\n // std::cout << filename2.str() << \" saved.\" << std::endl;\n // save_count++;\n flg=1;\n\n\n //現在時刻取得\n char fname[500];\n time_t now = time(NULL);\n struct tm *pnow = localtime(&now);\n sprintf(fname, \"%s_%04d%02d%02d%02d%02d%02d.pcd\",outfname.c_str(), pnow->tm_year + 1900, pnow->tm_mon + 1, pnow->tm_mday,\n pnow->tm_hour, pnow->tm_min, pnow->tm_sec);\n\n\n string filename2=fname;\n pcl::io::savePCDFileBinary( filename2, input_cloud );\n std::cout << filename2 << \" saved.\" << std::endl;\n usleep( 300*1000 );\n\n }\n\n\n};\n\nint main( int argc, char** argv ){\n ros::init(argc,argv,\"save_pcd\");\n SavePCD spcd;\n while(ros::ok()) {\n if(flg==1) break;\n ros::spinOnce();\n }\n\n return 1;\n}\n" }, { "alpha_fraction": 0.745945930480957, "alphanum_fraction": 0.7621621489524841, "avg_line_length": 17.200000762939453, "blob_id": "4a2ceea102af66c694a4e13c611144b048089bc0", "content_id": "48cbd7c8ee98fc3294731922b94b9a0598b8cf42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 191, "license_type": "no_license", "max_line_length": 49, "num_lines": 10, "path": "/old/map_editor_simple/readme.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "ISO-8859-2", "text": "\n›Install\nsudo apt-get install freeglut3-dev libglew1.5-dev\nsudo apt-get install libxmu-dev libxi-dev\n\n›compile\ncd catkin_ws\ncatkin_make\n\n›Do\nrosrun docu_lrf_sim docu_lrf_sim_node\n\n\n" }, { "alpha_fraction": 0.5898054242134094, "alphanum_fraction": 0.6523556709289551, "avg_line_length": 24.698347091674805, "blob_id": "ae0a20680afc64136101314c90929bdb20882cbc", "content_id": "32ac07e3dc50513bd17fa1c6ff09bfef78da3a4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6241, "license_type": "no_license", "max_line_length": 151, "num_lines": 242, "path": "/robo_rot/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <tf/transform_listener.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\n#include <math.h>\n#include <tf/transform_broadcaster.h>\n#include <boost/asio.hpp>\n#include <std_msgs/Float32.h>\nusing namespace::boost::asio;\nusing namespace std;\nboost::mutex mtx;\n\n// Base serial settings\nconst char *PORT = \"/dev/tty_SPU01\";\nio_service io;\nserial_port port( io, PORT );\n\n\nstring init_cmd01= \"ssm,1,3\\n\";\nstring init_cmd02= \"ssc,1,0\\n\";\nstring init_cmd03= \"sva,1,36000\\n\";\nstring init_cmd04= \"saa,1,133333\\n\";\nstring init_cmd05= \"slva,1,800\\n\";\n//string init_cmd06= \"gsm,1\\n\";\n//string init_cmd07= \"gdc,1\\n\";\n//string init_cmd08= \"gsc,1\\n\";\n//string init_cmd09= \"gtv,1\\n\";\n//string init_cmd10= \"ga,1\\n\";\n//string init_cmd11= \"glv,1\\n\";\n//string init_cmd12= \"gv,1\\n\";\n\nstring init_cmd13= \"sdc,1,0\\n\";\nstring init_cmd14= \"sdm,1,1\\n\";\nstring init_cmd15= \"srm,1,1\\n\";\nstring init_cmd16= \"gp,1\\n\";\nstring init_cmd17= \"sva,1,0\\n\";\n\nstring rot_cmd00= \"sva,1,36000\\n\";\nstring rot_cmd01= \"sva,1,0\\n\";\nstring rot_cmd02= \"gp,1\\n\";\n\n\nstring end_cmd01= \"sva,1,000\\n\";\nstring end_cmd02= \"sdm,1,0\\n\";\nstring end_cmd03= \"init,1\\n\";\n\n\nint read_cnt = 0;\nchar fbuf[1024] = {0};\nboost::array<char, 256> rbuf;\n\n\n\nint panunit_read=0;\n\nint pan_speed=0.0;\nint pan_speed_old=0.0;\n\n\nvoid mySigintHandler(int sig){\n printf(\"shutdown catch signal %d \\n\", sig);\n ros::shutdown();\n}\n\nvoid read_callback(const boost::system::error_code& e, std::size_t size){\n boost::mutex::scoped_lock lk(mtx);\n\n for(unsigned int i=0;i<size;i++){\n char c = rbuf.at(i);\n fbuf[read_cnt++] = c;\n if(c == '\\n'){\n string read_str=fbuf;\n // cout<<fbuf<<endl;\n sscanf(read_str.c_str(),\"%d\",&panunit_read );\n // cout<<panunit_read<<endl;\n\n read_cnt = 0;\n }\n }\n usleep(30*1000);\n port.async_read_some( buffer(rbuf), boost::bind(&read_callback, _1, _2 ));\n}\n\n\n\nvoid write_callback(const boost::system::error_code& e, std::size_t size ){\n string wbuf=\"000\\n\";\n //std::cout << \"write :\" << size << \"byte[s]\" << std::endl;\n //cout << wbuf << endl;\n //usleep(30*1000);\n port.async_write_some( buffer(wbuf), boost::bind(&write_callback, _1, _2));\n\n}\n\nvoid panspeed_Callback(const std_msgs::Float32::ConstPtr &bottom_msg){\n double data_read = bottom_msg->data;\n pan_speed=(int)data_read;\n}\n\n\n\nint main(int argc, char **argv){\n port.set_option(serial_port_base::baud_rate(9600));\n port.set_option(serial_port_base::character_size(8));\n port.set_option(serial_port_base::flow_control(serial_port_base::flow_control::none));\n port.set_option(serial_port_base::parity(serial_port_base::parity::none));\n port.set_option(serial_port_base::stop_bits(serial_port_base::stop_bits::one));\n\n boost::thread thr_io(boost::bind(&io_service::run, &io));\n //port.async_write_some( buffer(run_cmd01), boost::bind(&write_callback, _1, _2));\n port.async_read_some( buffer(rbuf), boost::bind(&read_callback, _1, _2 ));\n\n ros::init(argc, argv, \"robot_rot\");\n ros::NodeHandle nh;\n ros::Publisher robo_rot_speed = nh.advertise<std_msgs::Float32>(\"robo_rot_setspeed\", 10);\n ros::Publisher robo_rot_readspeed = nh.advertise<std_msgs::Float32>(\"robo_rot_readspeed\", 10);\n\n ros::Subscriber switch_sub = nh.subscribe<std_msgs::Float32>(\"panunit_speed\", 10, &panspeed_Callback);\n\n double tilt_deg;\n double pan_deg;\n double robot_x;\n double robot_y;\n double robot_z;\n int init_speed;\n\n ros::NodeHandle private_nh(\"~\");\n private_nh.param(\"tilt_deg\", tilt_deg, 22.0);\n private_nh.param(\"pan_deg\", pan_deg, 120.0);\n private_nh.param(\"robot_x\", robot_x, 0.0);\n private_nh.param(\"robot_y\", robot_y, 0.0);\n private_nh.param(\"robot_z\", robot_z, 0.0);\n private_nh.param(\"init_speed\", init_speed, 0);\n pan_speed=init_speed;\n pan_speed_old=init_speed;\n\n\n boost::asio::streambuf response_buf;\n write(port, buffer(init_cmd01));\n usleep(100*1000);\n write(port, buffer(init_cmd02));\n usleep(100*1000);\n write(port, buffer(init_cmd03));\n usleep(100*1000);\n write(port, buffer(init_cmd04));\n usleep(100*1000);\n write(port, buffer(init_cmd05));\n usleep(100*1000);\n\n /*\n write(port, buffer(init_cmd06));\n write(port, buffer(init_cmd07));\n write(port, buffer(init_cmd08));\n write(port, buffer(init_cmd09));\n write(port, buffer(init_cmd10));\n write(port, buffer(init_cmd11));\n write(port, buffer(init_cmd12));\n write(port, buffer(init_cmd13));\n */\n\n write(port, buffer(init_cmd14));\n usleep(100*1000);\n write(port, buffer(init_cmd15));\n usleep(100*1000);\n write(port, buffer(init_cmd16));\n usleep(100*1000);\n write(port, buffer(init_cmd17));\n usleep(100*1000);\n\n\n char cmd[100];\n sprintf(cmd,\"sva,1,%ld\\n\",init_speed);\n string rot_cmd00= cmd;\n cout<<rot_cmd00<<endl;\n\n write(port, buffer(rot_cmd00));\n usleep(100*1000);\n ros::Rate r(30.0);\n tf::TransformBroadcaster broadcaster;\n\n signal(SIGINT, mySigintHandler);\n\n while(nh.ok()){\n\n //tf publish\n write(port, buffer(rot_cmd02));\n usleep(10*1000);\n\n double ONE_REVOLUTION = 192000.0;\n double theta = (panunit_read / ONE_REVOLUTION ) * 2.0 * M_PI *2.0;\n double theta2=tilt_deg/180.0*3.1415;\n double theta_offset=(pan_deg)/360.0*M_PI *2.0;\n\n tf::Quaternion quaternion;\n quaternion.setRPY(0.0, theta2, -(theta+theta_offset));\n ros::Time current_time;\n current_time= ros::Time::now();\n broadcaster.sendTransform(tf::StampedTransform(tf::Transform(quaternion,tf::Vector3(robot_x, 0.0, robot_z)),current_time,\"base_link\",\"base_scan\"));\n\n //tf publish\n\n //回転のスピードを変える\n if(pan_speed!=pan_speed_old){\n usleep(100*1000);\n char cmd[100];\n sprintf(cmd,\"sva,1,%ld\\n\",pan_speed);\n string rot_cmd00= cmd;\n cout<<rot_cmd00<<endl;\n write(port, buffer(rot_cmd00));\n usleep(100*1000);\n pan_speed_old=pan_speed;\n }\n\n std_msgs::Float32 msg_float;\n msg_float.data = pan_speed;\n robo_rot_speed.publish(msg_float);\n\n msg_float.data = panunit_read;\n robo_rot_readspeed.publish(msg_float);\n\n\n\n\n ros::spinOnce();\n r.sleep();\n }\n\n write(port, buffer(end_cmd01));\n usleep(100*1000);\n\n write(port, buffer(end_cmd02));\n usleep(100*1000);\n\n write(port, buffer(end_cmd03));\n usleep(100*1000);\n\n return 0;\n\n}\n" }, { "alpha_fraction": 0.6169067621231079, "alphanum_fraction": 0.6438980102539062, "avg_line_length": 25.256521224975586, "blob_id": "17cfbe5cf612a0bea4971b94b026f70eb8d559a3", "content_id": "b5671ca90835f31b13a9053cd9dd6832b30d23b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12178, "license_type": "no_license", "max_line_length": 102, "num_lines": 460, "path": "/robo_cart/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n#include <sensor_msgs/LaserScan.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/Pose.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\n\n#include <boost/asio.hpp>\n#include <boost/bind.hpp>\n#include <boost/thread.hpp>\n#include <boost/array.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\nusing namespace boost::asio;\nusing namespace boost::posix_time;\nusing namespace std;\n#include <std_msgs/Float32.h>\n\n// Base serial settings\nconst char *PORT = \"/dev/tty_robo\";\nio_service io;\nserial_port port( io, PORT );\nboost::array<char, 256> rbuf;\nstatic bool isRunning(true);\nint read_cnt = 0;\nchar fbuf[1024] = {0};\nstd::ofstream ofs;\nboost::mutex mtx;\nstring run_cmd01= \"#$00000,00000,1\\n\";\n\n\ndouble data_timestamp;\ndouble data_encL ;\ndouble data_encR;\ndouble data_vel_L;\ndouble data_vel_R;\ndouble data_vel;\ndouble data_omega ;\ndouble data_pitch_vel;\ndouble data_pitch;\ndouble data_roll_vel;\ndouble data_roll;\ndouble data_joyx;\ndouble data_joyy;\nint data_level;\nint data_am ;\ndouble data_voltL;\ndouble data_voltR;\ndouble data_IL;\ndouble data_IR;\ndouble data_Batt;\n\n\n//[vehicle\ndouble vehicle_tread = 0.470;\ndouble vehicle_radius_L = 0.125;\ndouble vehicle_radius_R = 0.125;\ndouble vehicle_enc_count = 2000.0;\nint vehicle_reverse_L = 1;\nint vehicle_reverse_R = 1;\nint vehicle_flip_LR = 1;\n\ndouble state_odom_x=0.0;\ndouble state_odom_y=0.0;\ndouble state_odom_th=0.0;\n\n//std::ofstream ofs;\n\ndouble vel_ctrl_ratio=0.1;\ndouble vel_ctrl_min=0.025;\n\ndouble vel_ctrl_L_in=0.0;\ndouble vel_ctrl_R_in=0.0;\ndouble vel_ctrl_L=0.0;\ndouble vel_ctrl_R=0.0;\n\ndouble odom_v_ratio;\ndouble odom_w_ratio;\n\n\n\nvoid send_ctrl(float vel_ctrl_L, float vel_ctrl_R){\n\tconst int AM = 1;\n\n\tchar send_cmd_char[256]; // 送信コマンド\n\tsprintf(send_cmd_char, \"#$%d %d %d\\n\",(int)(vel_ctrl_L*10000),(int)(vel_ctrl_R*10000),AM);// 送信文字列の作成\n\tstring send_cmd=send_cmd_char;\n\twrite(port, buffer(send_cmd));\n\texit(0);\n}\n\nvoid mySigintHandler(int sig){\n\tprintf(\"shutdown catch signal %d \\n\", sig);\n\n\tvel_ctrl_L=0.0;\n\tvel_ctrl_R=0.0;\n\tsend_ctrl(0.0,0.0);\n\tros::shutdown();\n}\n\n\n\nvoid odom_calc(){\n\tstatic int init_loop=true;\n\tstatic double rate_save=0.0;\n\tstatic double encL_bak=0.0;\n\tstatic double encR_bak=0.0;\n\tstatic double tx=0.0;\n\tstatic double ty=0.0;\n\tstatic double th=0.0;\n\n\tif (init_loop){\n\t\tencL_bak = data_encL;\n\t\tencR_bak = data_encR;\n\t}\n\n\n\tconst int32_t dencL = data_encL - encL_bak;\n\tconst int32_t dencR = data_encR - encR_bak;\n\tencL_bak = data_encL;\n\tencR_bak = data_encR;\n\tstatic const float delta_rad = M_PI / vehicle_enc_count;\n\tconst float dradL = dencL * delta_rad;\n\tconst float dradR = dencR * delta_rad;\n\n\tconst float vel_L = vehicle_reverse_L * dradL * vehicle_radius_L;\n\tconst float vel_R = vehicle_reverse_R * dradR * vehicle_radius_R;\n\n\tconst double rate = 2.0f * ((vel_R - vel_L) / vehicle_tread);\n\n\tif (init_loop) { rate_save = rate; init_loop = false; }\n\tconst float rot = th + (rate + rate_save) / 2.0;\n\n\tth += rate*odom_w_ratio;\n\n\tconst float velocity = (vel_R + vel_L)*odom_v_ratio;\n\ttx += velocity * cos(rot);\n\tty += velocity * sin(rot);\n\n\tstate_odom_x = tx;\n\tstate_odom_y = ty;\n\tstate_odom_th = -th;\n\n\t//cout<<dencL<<\",\"<<dencR<<endl;\n\t//cout<<vel_L<<\",\"<<vel_R<<endl;\n\t//cout<<state_odom_x<<\",\"<<state_odom_y<<\",\"<<state_odom_th<<endl;\n}\n\n\n\nvoid read_stat(string recv_cmd){\n\t// 受信文字列のパーシング\n\tunsigned int timestamp = 0;\n\tint encL = 0, encR = 0;\n\tshort velL = 0, velR = 0;\n\tshort vel = 0, omega = 0;\n\tshort pitch_vel = 0, pitch = 0;\n\tshort roll_vel = 0, roll = 0;\n\tshort joyx = 0, joyy = 0;\n\tunsigned int level = 0, am = 0;\n\tshort voltL = 0, voltR = 0;\n\tshort IL = 0, IR = 0;\n\tunsigned short Batt = 0;\n\n\tstring recv_cmd_demi;\n\tfor (int i=2; i < recv_cmd.size(); i++) {\n\t\tchar target = recv_cmd[i];\n\t\trecv_cmd_demi.push_back(target);\n\t}\n\t//cout<<recv_cmd<<endl;\n\t//cout<<recv_cmd_demi<<endl;\n\n\tsscanf(recv_cmd_demi.c_str(), // #$を飛ばす\n\t\"%X\" // T\t\t# timestamp\n\t\" %X %X\" // El Er\tmotor encoder (left/right)\n\t\" %hX %hX\" // L R\tmotor speed (left/right)\n\t\" %hX %hX\" // V W\tvelocity rotation\n\t\" %hX %hX\" // Wp Tp\tpitch[rad/s], pitch[rad]\n\t\" %hX %hX\" // Wr Tr\troll[rad/s], roll[rad]\n\t\" %hX %hX\" // Jx Jy\tjoystick (leftright/forwardbackward)\n\t\" %d\" // Lv\t\temergency switch\n\t\" %d\" // AM\t\tctrl mode\n\t\" %hX %hX\" // Vl Vr\tmotor voltage (left/right)\n\t\" %hX %hX\" // Il Ir\tmotor driver current (left/right)\n\t\" %hX\", // B\t\tbattery voltage\n\t&timestamp,\n\t&encL, &encR,\n\t&velL, &velR,\n\t&vel, &omega,\n\t&pitch_vel, &pitch,\n\t&roll_vel, &roll,\n\t&joyx, &joyy,\n\t&level,\n\t&am,\n\t&voltL, &voltR,\n\t&IL, &IR,\n\t&Batt\n);\n\n\n//cout<<recv_cmd_demi.c_str()<<endl;\n\ndouble t_secs =ros::Time::now().toSec();\nstatic double t_sec_old= t_secs;\n\nstatic int cnt=0;\nif(cnt==0){\n\t/*\tofs<<\"ROStimes\"<<\",\";\n\tofs<<\"Micon_timestamp\"<<\",\";\n\tofs<<\"encL\"<<\",\"<<\"encR\"<<\",\";\n\tofs<<\"velL\"<<\",velR\"<<\",\";\n\tofs<<\"vel\"<<\",omega\"<<\",\";\n\tofs<<\"pitch_vel\"<<\",\"<<\"pitch\"<<\",\";\n\tofs<<\"roll_vel\"<<\",\"<<\"roll\"<<\",\";\n\tofs<<\"joyx\"<<\",\"<<\"joyy\"<<\",\";\n\tofs<<\"level\"<<\",\"<<\"am\"<<\",\";\n\tofs<<\"voltL\"<<\",\"<<\"voltR\"<<\",\";\n\tofs<<\"IL\"<<\",\"<<\"IR\"<<\",\";\n\tofs<<\"Batt\"<<\",\";\n\tofs<<\"vel_ctrl_L\"<<\",\"<<\"vel_ctrl_R\"<<\",\";\n\tofs<<\"vel_ctrl_L_in\"<<\",\"<<\"vel_ctrl_R_in\"<<endl;\n\tcnt++;\n\t*/\n}\n/*\nofs<<t_secs-t_sec_old<<\",\";\nofs<<timestamp<<\",\";\nofs<<encL<<\",\"<<encR<<\",\";\nofs<<velL / 10000.0f<<\",\"<<velR / 10000.0f<<\",\";\nofs<<vel<<\",\"<<omega<<\",\";\nofs<<pitch_vel<<\",\"<<pitch<<\",\";\nofs<<roll_vel<<\",\"<<roll<<\",\";\nofs<<joyx/10000.0f<<\",\"<<joyy/10000.0f<<\",\";\nofs<<level<<\",\"<<am<<\",\";\nofs<<voltL/100.0f<<\",\"<<voltR/100.0f<<\",\";\nofs<<IL/ 100.0f<<\",\"<<IR/100.0f<<\",\";\nofs<<Batt/100.0<<\",\"<<\",\";\nofs<<vel_ctrl_L<<\",\"<<vel_ctrl_R<<\",\";\nofs<<vel_ctrl_L_in<<\",\"<<vel_ctrl_R_in<<endl;\n*/\ndata_timestamp = timestamp;\ndata_encL = encL;\ndata_encR = encR;\ndata_vel_L = static_cast<float>(velL) / 10000.0f;\ndata_vel_R = static_cast<float>(velR) / 10000.0f;\ndata_vel = vel;\ndata_omega = omega;\ndata_pitch_vel = pitch_vel;\ndata_pitch = pitch;\ndata_roll_vel = roll_vel;\ndata_roll = roll;\ndata_joyx = joyx;\ndata_joyy = joyy;\ndata_level = level;\ndata_am = am;\ndata_voltL = voltL/100.0f;\ndata_voltR = voltR/100.0f;\ndata_IL = IL/100.0f;\ndata_IR = IR/100.0f;\ndata_Batt = Batt/100.0f;\n\nt_sec_old= t_secs;\n}\n\n\n\nvoid read_callback(const boost::system::error_code& e, std::size_t size){\n\tboost::mutex::scoped_lock lk(mtx);\n\n\tfor(unsigned int i=0;i<size;i++){\n\t\tchar c = rbuf.at(i);\n\t\tfbuf[read_cnt++] = c;\n\t\tif(c == '\\n'){\n\t\t\tstring read_str=fbuf;\n\t\t\tif(read_cnt>=97){\n\t\t\t\t//cout<<read_str<<endl;\n\t\t\t\t//cout<<read_cnt<<endl;\n\t\t\t\tread_stat(read_str);\n\t\t\t}\n\t\t\tread_cnt = 0;\n\n\t\t}\n\t}\n\n\tusleep(30*1000);\n\tport.async_read_some( buffer(rbuf), boost::bind(&read_callback, _1, _2 ));\n}\n\n\n\nvoid write_callback(const boost::system::error_code& e, std::size_t size ){\n\n\t//std::cout << \"write :\" << size << \"byte[s]\" << std::endl;\n\t//cout << wbuf << endl;\n\tusleep(30*1000);\n\n\tif(fabs(vel_ctrl_L)<vel_ctrl_min) vel_ctrl_L=0.0;\n\tif(fabs(vel_ctrl_R)<vel_ctrl_min) vel_ctrl_R=0.0;\n\n\tconst int AM = 1;\n\tchar send_cmd[256];\t\t// 送信コマンド\n\tsprintf(send_cmd, \"#$%d %d %d\\n\",\n\t(int)(vel_ctrl_L*10000),\n\t(int)(vel_ctrl_R*10000),\n\tAM);// 送信文字列の作成\n\tstring wbuf=send_cmd;\n\tport.async_write_some( buffer(wbuf), boost::bind(&write_callback, _1, _2));\n\t//cout<<wbuf<<endl;\n\n}\n\nvoid vel_Callback(const geometry_msgs::Twist &vel_msg){\n\tvel_ctrl_L_in = vel_msg.linear.x-vel_msg.angular.z*vehicle_tread;\n\tvel_ctrl_R_in = vel_msg.linear.x+vel_msg.angular.z*vehicle_tread;\n}\n\n\n\nvoid GetRPY(const geometry_msgs::Quaternion &quat, double &theta){\n\ttf::Quaternion q(quat.x, quat.y, quat.z, quat.w);\n\ttf::Matrix3x3 m(q);\n\tdouble roll, pitch, yaw;\n\tm.getRPY(roll, pitch, yaw);\n\n\ttheta = yaw;\n}\n\nint main(int argc, char **argv){\n\tport.set_option(serial_port_base::baud_rate(115200));\n\tport.set_option(serial_port_base::character_size(8));\n\tport.set_option(serial_port_base::flow_control(serial_port_base::flow_control::none));\n\tport.set_option(serial_port_base::parity(serial_port_base::parity::none));\n\tport.set_option(serial_port_base::stop_bits(serial_port_base::stop_bits::one));\n\n\tboost::thread thr_io(boost::bind(&io_service::run, &io));\n\tport.async_write_some( buffer(run_cmd01), boost::bind(&write_callback, _1, _2));\n\tport.async_read_some( buffer(rbuf), boost::bind(&read_callback, _1, _2 ));\n\n\tros::init(argc, argv, \"robot_cart\");\n\tros::NodeHandle nh;\n\tstring vel_topic=\"cmd_vel\";\n\tros::Subscriber cmd_vel = nh.subscribe(vel_topic, 10, vel_Callback);\n\n\tros::Publisher robo_batt = nh.advertise<std_msgs::Float32>(\"robo_battery\", 10);\n\tros::Publisher robo_l_in = nh.advertise<std_msgs::Float32>(\"robo_vel_L_int\", 10);\n\tros::Publisher robo_r_in = nh.advertise<std_msgs::Float32>(\"robo_vel_R_in\", 10);\n\tros::Publisher robo_l_out = nh.advertise<std_msgs::Float32>(\"robo_vel_L_out\", 10);\n\tros::Publisher robo_r_out = nh.advertise<std_msgs::Float32>(\"robo_vel_R_out\", 10);\n\tros::Publisher odom_pub = nh.advertise<nav_msgs::Odometry>(\"odom\", 10);\n\tros::Publisher robo_voltL = nh.advertise<std_msgs::Float32>(\"robo_voltL\", 10);\n\tros::Publisher robo_voltR = nh.advertise<std_msgs::Float32>(\"robo_voltR\", 10);\n\tros::Publisher robo_IL = nh.advertise<std_msgs::Float32>(\"robo_IL\", 10);\n\tros::Publisher robo_IR = nh.advertise<std_msgs::Float32>(\"robo_IR\", 10);\n\tros::Publisher robo_am = nh.advertise<std_msgs::Float32>(\"robo_am\", 10);\n\n\tros::NodeHandle private_nh(\"~\");\n\tprivate_nh.param(\"odom_v_ratio\", odom_v_ratio, 1.0);\n\tprivate_nh.param(\"odom_w_ratio\", odom_w_ratio, 1.0);\n\tprivate_nh.param(\"vel_ctrl_ratio\", vel_ctrl_ratio, 0.10);\n\tstring out_file_name=\"\";\n\tprivate_nh.param(\"out_f_name\", out_file_name, std::string(\"\"));\n\n\tif(out_file_name!=\"\"){\n\t\tptime now = second_clock::local_time();\n\t\tstd::string logname = to_iso_string(now) + std::string(\".log\");\n\t\tofs.open(logname.c_str());\n\t}\n\n\n\tsignal(SIGINT, mySigintHandler);\n\n\ttf::TransformBroadcaster odom_broadcaster;\n\tros::Time current_time;\n\tcurrent_time = ros::Time::now();\n\n\n\tros::Rate r(30.0);\n\n\twhile(nh.ok()){\n\t\todom_calc();\n\n\t\tcurrent_time = ros::Time::now();\n\n\t\t//速度指令の更新\n\t\tvel_ctrl_L=vel_ctrl_ratio*vel_ctrl_L_in+(1.0-vel_ctrl_ratio)*vel_ctrl_L;\n\t\tvel_ctrl_R=vel_ctrl_ratio*vel_ctrl_R_in+(1.0-vel_ctrl_ratio)*vel_ctrl_R;\n\n\n\t\t//tf odom->base_link\n\t\tgeometry_msgs::TransformStamped odom_trans;\n\t\todom_trans.header.stamp = current_time;\n\t\todom_trans.header.frame_id = \"odom\";\n\t\todom_trans.child_frame_id = \"base_footprint\";\n\n\t\todom_trans.transform.translation.x = state_odom_x;\n\t\todom_trans.transform.translation.y = -state_odom_y;\n\t\todom_trans.transform.translation.z = 0.0;\n\t\tgeometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(state_odom_th);\n\t\todom_trans.transform.rotation = odom_quat;\n\t\todom_broadcaster.sendTransform(odom_trans);\n\n\t\tnav_msgs::Odometry odom;\n\t\todom.header.stamp = current_time;\n\t\todom.header.frame_id = \"odom\";\n\t\todom.child_frame_id = \"base_footprint\";\n\n\t\t//set the position\n\t\todom_trans.transform.translation.x = state_odom_x;\n\t\todom_trans.transform.translation.y = -state_odom_y;\n\t\todom.pose.pose.position.z = 0.0;\n\t\todom.pose.pose.orientation = odom_quat;\n\t\todom.twist.twist.linear.x = 0.0;\n\t\todom.twist.twist.linear.y = data_vel;\n\t\todom.twist.twist.angular.z = data_omega;\n\n\t\t//publish the message\n\t\todom_pub.publish(odom);\n\n\t\tstd_msgs::Float32 msg_float;\n\t\tmsg_float.data = data_Batt;\n\t\trobo_batt.publish(msg_float);\n\n\t\tmsg_float.data =vel_ctrl_L;\n\t\trobo_l_in.publish(msg_float);\n\n\t\tmsg_float.data = vel_ctrl_R;\n\t\trobo_r_in.publish(msg_float);\n\n\t\tmsg_float.data =data_vel_L;\n\t\trobo_l_out.publish(msg_float);\n\t\tmsg_float.data = data_vel_R;\n\t\trobo_r_out.publish(msg_float);\n\t\t\n\t\tmsg_float.data = data_voltL;\n\t\trobo_voltL.publish(msg_float);\n\t\tmsg_float.data = data_voltR;\n\t\trobo_voltR.publish(msg_float);\n\t\t\n\t\tmsg_float.data = data_IL;\n\t\trobo_IL.publish(msg_float);\n\t\tmsg_float.data = data_IR;\n\t\trobo_IR.publish(msg_float);\t\t\t\t\n\t\tmsg_float.data = data_am;\n\t\trobo_am.publish(msg_float);\n\n\t\tros::spinOnce();\n\t\tr.sleep();\n\t}\n\n\n\n\treturn 0;\n\n}\n" }, { "alpha_fraction": 0.5809390544891357, "alphanum_fraction": 0.6253212094306946, "avg_line_length": 18.36651611328125, "blob_id": "14e54dde131fc94965835f3917c7c245c36a6c63", "content_id": "d66c49c567d95a4022972fc76376f5b36b438e6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4639, "license_type": "no_license", "max_line_length": 139, "num_lines": 221, "path": "/n_3d_robot_sim/src/geometory.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\n\n/////////////////////////////////////////////////\n\n#pragma once\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <stdio.h>\n#include <stdlib.h>\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <stdio.h>\n#include <time.h>\n#include <sys/time.h>\nusing namespace std;\n//const double PI=3.14159265359;\n\n#define URG_DATA_MAX 2000\n#define OBSTACLE_MAX 1024\n#define MOVE_OBST_MAX_MAIN 1000\n#define PATH_POINTS_MAX 1024\nextern unsigned int urg_data_num;\nextern double urg_range_deg;\nextern double urg_leng_max;\nextern double urg_leng_min;\nextern double noise_odometory_v_gain;\nextern double noise_odometory_w_gain;\nextern double noise_urg;\n\nextern double obstacle_z;\n\n//一様分布乱数\ndouble Uniform( void );\n//正規分布乱数\ndouble rand_normal( double mu, double sigma );\n\n\nstruct pantilt{\n\tdouble pan;\n\tdouble tilt;\n\n\tpantilt(){\n\t\tpan = 0.0;\n\t\ttilt = 0.0;\n\t}\n};\n\nstruct TWIST{\t\t//Twist定義\n\tdouble v;\t\t//目標速度(m/s)\n\tdouble w;\t\t//目標角速度(rad/s)\n\tTWIST(){\n\t\tv = 0.0;\n\t\tw = 0.0;\n\t}\n};\n\nstruct ROBOT{\t\t\t\t\t\t//ロボットの定義\n\tlong double x;\t\t\t\t\t//X座標(m)\n\tlong double y;\t\t\t\t\t//Y座標(m)\n\tlong double theta;\t\t\t\t//角度(rad)\n\n\tdouble v;\t\t\t\t\t//目標速度(m/s)\n\tdouble w;\t\t\t\t\t//目標角速度(rad/s)\n\n\tdouble real_v;\t\t\t\t//実態速度(m/s)\n\tdouble real_w;\t\t\t\t//実態角速度(rad/s)\n\n\tdouble ac_trans_limit;\t\t//加速度(m/s2)\n\tdouble ac_rot_limit;\t\t//角速度(rad/s2)\n\n\tlong double x_dummy;\n\tlong double y_dummy;\n\tlong double theta_dummy;\n\n\tROBOT(){\n\t\tx = 0.0;\n\t\ty = 0.0;\n\t\tv = 0.0;\n\t\tw = 0.0;\n\t\ttheta = 0.0;\n\t\treal_v=0.0;\n\t\treal_w=0.0;\n\n\t\tac_trans_limit=5.0;\n\t\tac_rot_limit=5.0;\n\t}\n};\n\nstruct URG{\t\t\t//測域センサの定義\n\tdouble leng[URG_DATA_MAX];\t\t\n\tdouble x[URG_DATA_MAX];\t\n\tdouble y[URG_DATA_MAX];\t\n\tint data_num;\n\tdouble start_rad;\n\tdouble reso;\n\n\tdouble leng_max;\n\tdouble leng_min;\n\n\tURG(){\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*M_PI;\n\t\treso=2*M_PI/URG_DATA_MAX;\n\t\tleng_max=urg_leng_max;\n\t\tleng_min=urg_leng_min;\n\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\n\t\t\tx[i] = 0.0;\n\t\t\ty[i] = 0.0;\n\t\t\tleng[i] = 0.0;\n\t\t}\n\t}\n};\n\nstruct OBSTACLE{\t\t//障害物の定義\n\tdouble x1[OBSTACLE_MAX];\n\tdouble x2[OBSTACLE_MAX];\n\tdouble y1[OBSTACLE_MAX];\n\tdouble y2[OBSTACLE_MAX];\n\tdouble z[OBSTACLE_MAX];\n\tunsigned int n;\t\t\t\t//データ数\n\tunsigned int n_max;\t\t\t//現在の目標(x,y)の番号\n\n\tOBSTACLE(){\n\t\tn_max=OBSTACLE_MAX;\n\n\t\tfor(int i=0;i<n_max;i++){\n\t\t\tx1[i] = 0.0;\n\t\t\tx2[i] = 0.0;\n\t\t\ty1[i] = 0.0;\n\t\t\ty2[i] = 0.0;\n\t\t\tz[i] =5;\n\t\t}\n\n\t}\n};\n\nstruct MOVE_OBSTACLE{\t\t//障害物の定義\n\tdouble obst_x[100][100];\n\tdouble obst_y[100][100];\n\tdouble obst_theta[100];\n\tdouble phase[100];\n\tdouble freq[100];\n\tdouble amp[100];\n\n\tdouble x[100];\n\tdouble y[100];\n\tdouble theta[100];\n\tdouble now;\n\tdouble n;//数\n\tdouble m;//オブジェクトの辺(4辺で固定)\n\n\tdouble obst_size;\n\n\tMOVE_OBSTACLE(){\n\t\tobst_size=0.25;\n\t\tn=0;\n\t\tm=4;\n\t\tfor(int i=0;i<n;i++){\n\t\t\tx[i]=0.0;\n\t\t\ty[i]=0.0;\n\t\t\tphase[i]=0.0;\n\t\t\tamp[i]=0;\n\t\t\tfreq[i]=0;\n\t\t}\n\t\tfor(int i=0;i<n;i++){\n\t\t\tfor(int j=0;j<n;j++){\n\t\t\t\tobst_x[i][j]=0.0;\n\t\t\t\tobst_y[i][j]=0.0;\n\t\t\t}\n\t\t}\n\t\tnow=0;\n\n\t\tfor(int i=0;i<50;i++){\n\t\t\tx[i]=((double)rand() / ((double)RAND_MAX + 1)-0.5)*25.0;\n\t\t\ty[i]=((double)rand() / ((double)RAND_MAX + 1)-0.5)*25.0;\n\t\t\tamp[i]=rand()%10+5,\n\t\t\tfreq[i]=100.0;\n\t\t\tphase[i]=rand()%360;\n\t\t}\n\t}\n};\n\n\n\n\n\n\n//一様分布乱数\ndouble Uniform( void );\n//正規分布乱数\ndouble rand_normal( double mu, double sigma );\n\n//線分の交差判定関数\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y);\n\n//交点の座標を求める\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y);\n\n//URGで障害物を検知する\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data);\n\n//障害物を読み込む\nvoid read_obstacle(OBSTACLE &obst,string fname=\"obstacle.csv\");\nvoid write_obstacle(OBSTACLE &obst,string fname=\"obstacle.csv\");\n//時間を計測する\nstatic double get_dtime(void);\n\n//strをdoubleに変換する\ndouble str_double(string str);\n\n//xy座標の成す角度thetaを求める。\nvoid arc_tan2(double &target_x,double &target_y,double &theta);\n//外積\nvoid normal_calc(double *p1, double *p2, double *p3, double *v_nl);\nvoid urg_calcurate_3d( ROBOT &robot, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data,double pan,double tile,double robot_z);\nvoid urg_noise( URG &urg_data);\n\nvoid robot_move(ROBOT &myrobot,double dt);\n\n" }, { "alpha_fraction": 0.5741444826126099, "alphanum_fraction": 0.6121672987937927, "avg_line_length": 20.398351669311523, "blob_id": "80c3ad208f52f31275ca232fcbe24c1ea238a0bc", "content_id": "d7c7b4ddfd0bf650a899ecad2d078299174d1f53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9017, "license_type": "no_license", "max_line_length": 183, "num_lines": 364, "path": "/old/map_editor_simple/src/geometory.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n#pragma once\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <string>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n\r\nusing namespace std;\r\nconst double PI=3.14159265359;\r\n\r\n#define URG_DATA_MAX 1024\r\n#define OBSTACLE_MAX 1024\r\n\r\n#define MOVE_OBST_MAX_MAIN 1000\r\n\r\n#define PATH_POINTS_MAX 1024\r\nconst unsigned int urg_data_num=510;\r\nconst double urg_range_deg=180.0;\r\nconst double urg_leng_max=10.0;\r\nconst double urg_leng_min=0.01;\r\nconst double noise_odometory_v=0.010;\r\nconst double noise_odometory_w=0.010;\r\nconst double noise_urg=0.01;\r\nconst double delay_urg=0.100;\r\n\r\n\r\nconst double LRF_clustring_Threshold_percent=0.3;//クラスタリングの距離閾値[%]\r\nconst double LRF_clustring_Threshold_dis=0.2;//クラスタリングの距離閾値[m]\r\nconst int LRF_clustring_min_num=5;\t\t\t//小さいクラスタを除去\r\n\r\n#define NODE_NUM 10000//ノードの数\r\n\r\n//一様分布乱数\r\ndouble Uniform( void );\r\n//正規分布乱数\r\ndouble rand_normal( double mu, double sigma );\r\n\r\n\r\nstruct TWIST{\t\t//Twist定義\r\n\tdouble v;\t\t//目標速度(m/s)\r\n\tdouble w;\t\t//目標角速度(rad/s)\r\n\tTWIST(){\r\n\t\tv = 0.0;\r\n\t\tw = 0.0;\r\n\t}\r\n};\r\n\r\n\r\n\r\nstruct ROBOT{\t\t//ロボットの定義\r\n\tdouble x;\t\t//X座標(m)\r\n\tdouble y;\t\t//Y座標(m)\r\n\tdouble theta;\t//角度(rad)\r\n\t\r\n\r\n\t//double odom_x;\t\t//X座標(m)\r\n\t//double odom_y;\t\t//Y座標(m)\r\n\t//double odom_theta;\t//角度(rad)\r\n\r\n\r\n\tdouble v;\t\t//目標速度(m/s)\r\n\tdouble w;\t\t//目標角速度(rad/s)\r\n\r\n\tdouble real_v;\t//実態速度(m/s)\r\n\tdouble real_w;\t//実態角速度(rad/s)\r\n\r\n\tdouble ac_trans_limit;\t//加速度(m/s2)\r\n\tdouble ac_rot_limit;\t\t//角速度(rad/s2)\r\n\r\n\tROBOT(){\r\n\t\t//odom_x=0;\r\n\t\t//odom_y=0;\r\n\t\t//odom_theta=0;\r\n\r\n\t\tx = 0.0;\r\n\t\ty = 0.0;\r\n\t\tv = 0.0;\r\n\t\tw = 0.0;\r\n\t\ttheta = 0.0;\r\n\t\treal_v=0.0;\r\n\t\treal_w=0.0;\r\n\r\n\t\tac_trans_limit=5.0;\r\n\t\tac_rot_limit=5.0;\r\n\t}\r\n\r\n\tvoid kinema(double dt) {\r\n\t\tdouble dtt=dt+1.0/100000.0;//0除算を回避\r\n\t\tdouble ac_v=fabs(v-real_v)/dtt;\r\n\t\tdouble ac_w=fabs(w-real_w)/dtt;\r\n\t\tif(ac_v>=ac_trans_limit)ac_v=ac_trans_limit;\r\n\t\tif(ac_w>=ac_rot_limit)ac_w=ac_rot_limit;\r\n\t\t\r\n\t\tif((v-real_v)>=0)\t\treal_v+=ac_v*dtt;\r\n\t\telse if((v-real_v)<0)\treal_v-=ac_v*dtt;\r\n\t\t\r\n\t\tif((w-real_w)>=0)\t\treal_w+=ac_w*dtt;\r\n\t\telse if((w-real_w)<0)\treal_w-=ac_w*dtt;\r\n\r\n\t\t//cout<<\"real_v\"<<real_v<<\"_\";\r\n\t\t//cout<<\"real_w\"<<real_w<<endl;\r\n\t}\r\n\tvoid odometory(double dt){\r\n\t\tkinema(dt);\r\n\r\n\t\t//real_v+=real_v*rand_normal(0,1.0)*noise_odometory_v;\r\n\t\t//real_w+=real_w*rand_normal(0,1.0)*noise_odometory_w;\r\n\t\t\r\n\t\tx+=real_v*sin(-theta)*dt;\r\n\t\ty+=real_v*cos(-theta)*dt;\r\n\t\ttheta-=real_w*dt;\r\n\r\n\t\t//odom_x+=real_v*sin(-theta)*dt*(1+fabs(rand_normal(0,1.0))*noise_odometory_v);\r\n\t\t//odom_y+=real_v*cos(-theta)*dt*(1+fabs(rand_normal(0,1.0))*noise_odometory_v);\r\n\t\t//odom_theta-=real_w*dt*(1+fabs(rand_normal(0,1.0))*noise_odometory_w);\r\n\r\n\t\t//x+=v*sin(-theta)*dt;\r\n\t\t//y+=v*cos(-theta)*dt;\r\n\t\t//theta-=w*dt;\r\n\t\t//cout<<\"_\"<<x<<\"_\"<<y<<endl;\r\n\t}\r\n};\r\n\r\nstruct URG{\t\t\t//測域センサの定義\r\n\tdouble leng[URG_DATA_MAX];\t\t\r\n\tdouble x[URG_DATA_MAX];\t\r\n\tdouble y[URG_DATA_MAX];\t\r\n\tint data_num;\r\n\tdouble start_rad;\r\n\tdouble reso;\r\n\r\n\tdouble leng_max;\r\n\tdouble leng_min;\r\n\r\n\tURG(){\r\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\r\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*PI;\r\n\t\treso=2*PI/URG_DATA_MAX;\r\n\t\tleng_max=urg_leng_max;\r\n\t\tleng_min=urg_leng_min;\r\n\r\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\r\n\t\tx[i] = 0.0;\r\n\t\ty[i] = 0.0;\r\n\t\tleng[i] = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid noise(){\r\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\r\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*PI;\r\n\t\treso=2*PI/URG_DATA_MAX;\r\n\r\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\r\n\t\tleng[i] = leng[i] +leng[i]*rand_normal(0,1.0)*noise_urg;\r\n\t\t}\r\n\t}\r\n\r\n\r\n};\r\n\r\nstruct OBSTACLE{\t\t//障害物の定義\r\n\tdouble x1[OBSTACLE_MAX];\r\n\tdouble x2[OBSTACLE_MAX];\r\n\tdouble y1[OBSTACLE_MAX];\r\n\tdouble y2[OBSTACLE_MAX];\r\n\tunsigned int n;\t\t\t\t//データ数\r\n\tunsigned int n_max;\t\t\t//現在の目標(x,y)の番号\r\n\r\n\tOBSTACLE(){\r\n\t\tn_max=OBSTACLE_MAX;\r\n\r\n\t\tfor(int i=0;i<n_max;i++){\r\n\t\tx1[i] = 0.0;\r\n\t\tx2[i] = 0.0;\r\n\t\ty1[i] = 0.0;\r\n\t\ty2[i] = 0.0;\r\n\t\t}\r\n\t\r\n\t}\r\n};\r\n\r\nstruct MOVE_OBSTACLE{\t\t//障害物の定義\r\n\tdouble obst_x[100][100];\r\n\tdouble obst_y[100][100];\r\n\tdouble phase[100];\r\n\tdouble freq[100];\r\n\tdouble amp[100];\r\n\r\n\tdouble x[100];\r\n\tdouble y[100];\r\n\tdouble now;\r\n\tdouble n;\r\n\tdouble m;\r\n\t\r\n\tdouble obst_size;\r\n\t\r\n\tMOVE_OBSTACLE(){\r\n\t\tobst_size=0.5;\r\n\t\tn=10;\r\n\t\tm=4;\r\n\t\tfor(int i=0;i<n;i++){\r\n\t\t\tx[i]=0.0;\r\n\t\t\ty[i]=0.0;\r\n\t\t\tphase[i]=0.0;\r\n\t\t\tamp[i]=0;\r\n\t\t\tfreq[i]=0;\r\n\t\t}\r\n\t\tfor(int i=0;i<n;i++){\r\n\t\t\tfor(int j=0;j<n;j++){\r\n\t\t\t\tobst_x[i][j]=0.0;\r\n\t\t\t\tobst_y[i][j]=0.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tnow=0;\r\n\r\n\r\n\t\tfor(int i=0;i<50;i++){\r\n\t\tx[i]=rand()%10,y[i]=rand()%10;\r\n\t\tamp[i]=rand()%20+5,\r\n\t\tfreq[i]=100.0;\r\n\t\tphase[i]=rand()%360;\r\n\t\t}\r\n\r\n\t\tx[0]=2,y[0]=2,amp[0]=-010,freq[0]=10;\r\n\t\tx[1]=-2,y[1]=2,amp[1]=10,freq[1]=20;\r\n\t\tx[2]=-2,y[2]=0,amp[2]=5,freq[2]=30;\r\n\t\r\n\r\n\t}\r\n\r\n\tvoid move(double dt){\r\n\r\n\r\n\r\n\t}\r\n};\r\n\r\n\r\n\r\n\r\nstruct MOVE_PATH{\t\t//経路計画の定義\r\n\tdouble x[PATH_POINTS_MAX];\r\n\tdouble y[PATH_POINTS_MAX];\r\n\tunsigned int n;\r\n\tunsigned int n_max;\t\t\t//配列のサイズ\r\n\tunsigned int now_n;\t\t\t//現在の目標(x,y)の番号\r\n\tMOVE_PATH(){\r\n\t\tn_max=PATH_POINTS_MAX;\r\n\t\tfor(int i=0;i<n_max;i++){\r\n\t\tx[i] = 0.0;\r\n\t\tx[i] = 0.0;\r\n\t\tn=0;\r\n\t\tnow_n=0;\r\n\t\t}\r\n\t\r\n\t}\r\n};\r\n\r\nstruct Node{\r\n\tvector<int> to;\t\t//どのノードとつながっているか\r\n\tvector<double> cost;\t//エッジのコスト\r\n\r\n\tdouble x;\t\t\t//x座標\r\n\tdouble y;\t\t\t//y座標\r\n\tbool value;\t\t\t//走行可能かどうか\r\n\t//ここから下はダイクストラ法のために必要な情報\r\n\tbool done;\t\t//確定ノードかどうか\r\n\tint minCost;\t//スタートノードからのコスト\r\n\tint from;\t\t//どのノードから来たか\r\n\r\n\tint w_max;\t\t\t//幅方向のサイズ\r\n\tint h_max;\t\t\t//縦方向のサイズ\r\n\r\n\r\n};\r\n\r\n\r\ntypedef struct LRF_clustering{\r\n int flag; \r\n int flag2;\r\n int ptnum;\r\n int clnum;\r\n double dis;\r\n double r[1080];\r\n double x[1080];\r\n double y[1080];\r\n double x_ave;\r\n double y_ave;\r\n double r_ave;\r\n \r\n}CLUSTER;\r\n\r\ntypedef struct LRF_clusterTag{\r\n double r;\r\n double x;\r\n double y;\r\n double dis;\r\n int i;\r\n}TAG;\r\n\r\n\r\n\r\n\r\n\r\n//線分と点との距離\r\ndouble line_seg_point_distance( double px, double py,double ax, double ay, double bx, double by);\r\n\r\n\r\n//線分の交差判定関数\r\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y);\r\n\r\n//交点の座標を求める\r\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y);\r\n\r\n//URGで障害物を検知する\r\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data,bool);\r\n//void urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, URG &urg_data);\r\n\r\n//障害物を読み込む\r\nvoid read_obstacle(OBSTACLE &obst,string fname=\"obstacle.csv\");\r\nvoid write_obstacle(OBSTACLE &obst,string fname=\"obstacle.csv\");\r\n\r\n//時間を計測する\r\ndouble get_dtime(void);\r\n\r\n//strをdoubleに変換する\r\ndouble str_double(string str);\r\n\r\n\r\n//xy座標の成す角度thetaを求める。\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta);\r\n\r\n//目的地に向かう速度指令値を算出する\r\nvoid To_goal_velocity(double goal_x,double goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis=0.2,double turn_limit=3.14);\r\n\r\n\r\n//PATHに沿う速度を出力する\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn);\r\n\r\n//局所的経路計画:障害物を検知して回避する\r\nvoid dynamic_windows_approach(URG urg_l,double path_x[][50],double path_y[][50],double path_cost[],int &path_size,double robot_v,double robot_w,double &best_v,double &best_w,int flg);\r\n\r\n\r\n//大域経路計画:ダイクストラ法\r\nvoid dijkstra_addEdge(int v, int u, struct Node *node,double weight);//エッジを追加する関数\r\nint dijkstra_search(int n, int start, int end, struct Node *node);\t//最短経路を検索する\r\nvoid dijkstra_main( struct Node *node,int start,int end,double path_x_out[],double path_y_out[],int &path_out_num,int w_max,int h_max,double grid);\r\nvoid global_pathplan_dijkstra(struct Node *node,double start_x,double start_y,double goal_x,double goal_y,struct MOVE_PATH &path,struct OBSTACLE &obst);\r\n\r\n//Goal座標を相対座標に変換する\r\nvoid goal_abst_to_relative(double goal_x_abst,double goal_y_abst,double &goal_x_relate,double &goal_y_relate,double robot_x,double robot_y,double robot_theta);\r\n\r\n//クラスタリング\r\nvoid LRF_clustring_main(URG urg_data,CLUSTER clust[]);\r\nint LRF_clustring_tracking(CLUSTER clust[],double &goal_x,double &goal_y,int mouse_flag);\r\ndouble gaussian_random(double mean, double std);\r\n" }, { "alpha_fraction": 0.7253086566925049, "alphanum_fraction": 0.7335391044616699, "avg_line_length": 23.25, "blob_id": "011fa0857e2a0956ed6f5c8d3ee377712c455157", "content_id": "55e006f53315b96d87ebfdac286d9fa5300c9239", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 972, "license_type": "no_license", "max_line_length": 104, "num_lines": 40, "path": "/n_object_tracking/CMakeLists.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(n_object_tracking)\n\n## Find catkin macros and libraries\n## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)\n## is used, also find other catkin packages\nfind_package(catkin REQUIRED COMPONENTS\n geometry_msgs\n nav_msgs\n roscpp\n rospy\n sensor_msgs\n tf\n cv_bridge\n)\n\ncatkin_package()\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n ${OpenCV_INCLUDE_DIRS}\n ${OpenGL_INCLUDE_DIRS}\n)\nadd_executable(n_object_tracking_node\n src/ros_main.cpp\n src/geometory.cpp\n src/viewgui.cpp\n src/read_file.cpp\n)\n\nadd_dependencies(n_object_tracking_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n## Specify libraries to link a library or executable target against\ntarget_link_libraries(n_object_tracking_node \n ${catkin_LIBRARIES}\n ${OpenCV_LIBRARIES}\n ${OpenGL_LIBRARIES}\n ${GLUT_LIBRARY}\n -lglut -lGLU -lGL -lm -lSDL -L/usr/X11R6/lib -lglut -lGLU -lGL -lXi -lXmu -lXext -lX11\n )\n\n\n" }, { "alpha_fraction": 0.5064102411270142, "alphanum_fraction": 0.5288461446762085, "avg_line_length": 27.18181800842285, "blob_id": "e2cc4408a0698cd241217651b616e3ccde93e000", "content_id": "60afb22e2597b6689459da4f2bc3728be0ae7d81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 312, "license_type": "no_license", "max_line_length": 80, "num_lines": 11, "path": "/n_pcl_3d_to_2d/readme.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "$ rosnode info /n_pcl_3d_to_2d_node \n--------------------------------------------------------------------------------\nNode [/n_pcl_3d_to_2d_node]\nPublications: \n * /rosout [rosgraph_msgs/Log]\n * /assembled_xy [sensor_msgs/PointCloud2]\n\nSubscriptions: \n * /assembled_cloud2 [sensor_msgs/PointCloud2]\n\nServices: \n\n" }, { "alpha_fraction": 0.540517270565033, "alphanum_fraction": 0.5883620977401733, "avg_line_length": 17.173553466796875, "blob_id": "e1c2645ab3510d6e2ec3d3cded4ca052cceb72c4", "content_id": "0ccf48cc0d6dfe2d9d3c790d6144bd3a1ccf1e0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2544, "license_type": "no_license", "max_line_length": 139, "num_lines": 121, "path": "/n_lrf_view/src/geometory.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n#pragma once\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n\r\nusing namespace std;\r\nconst double PI=3.14159265359;\r\n\r\n#define URG_DATA_MAX 1024\r\nconst unsigned int urg_data_num=680;\r\nconst double urg_range_deg=240.0;\r\nconst double urg_leng_max=5.0;\r\nconst double urg_leng_min=0.1;\r\n\r\n\r\n\r\nstruct ROBOT{\t\t//ロボットの定義\r\n\tdouble x;\t\t//X座標\r\n\tdouble y;\t\t//Y座標\r\n\tdouble theta;\t//角度\r\n\tdouble v;\t\t//速度\r\n\tdouble w;\t\t//角速度\r\n\r\n\tROBOT(){\r\n\t\tx = 0.0;\r\n\t\ty = 0.0;\r\n\t\tv = 0.0;\r\n\t\tw = 0.0;\r\n\t\ttheta = 0.0;\r\n\t}\r\n\r\n\tvoid odometory(double dt){\r\n\t\tx+=v*sin(-theta)*dt;\r\n\t\ty+=v*cos(-theta)*dt;\r\n\t\ttheta-=w*dt;\r\n\r\n\t\t//if(theta<=(-2.0*PI)) theta+=2*PI;\r\n\t\t//if(theta>(2.0*PI)) theta-=2*PI;\r\n\t\r\n\t}\r\n};\r\n\r\nstruct URG{\t\t\t//測域センサの定義\r\n\tdouble leng[URG_DATA_MAX];\t\t\r\n\tdouble x[URG_DATA_MAX];\t\r\n\tdouble y[URG_DATA_MAX];\t\r\n\tint data_num;\r\n\tdouble start_rad;\r\n\tdouble reso;\r\n\r\n\tdouble leng_max;\r\n\tdouble leng_min;\r\n\r\n\tURG(){\r\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\r\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*PI;\r\n\t\treso=2*PI/URG_DATA_MAX;\r\n\t\tleng_max=urg_leng_max;\r\n\t\tleng_min=urg_leng_min;\r\n\r\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\r\n\t\tx[i] = 0.0;\r\n\t\ty[i] = 0.0;\r\n\t\tleng[i] = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\r\n};\r\n\r\nstruct OBSTACLE{\t\t//障害物センサの定義\r\n\tdouble x1[1024];\r\n\tdouble x2[1024];\r\n\tdouble y1[1024];\r\n\tdouble y2[1024];\r\n\tint n;\r\n\tOBSTACLE(){\r\n\t\tfor(int i=0;i<100;i++){\r\n\t\tx1[i] = 0.0;\r\n\t\tx2[i] = 0.0;\r\n\t\ty1[i] = 0.0;\r\n\t\ty2[i] = 0.0;\r\n\t\t}\r\n\t\r\n\t}\r\n};\r\n\r\n\r\n//線分の交差判定関数\r\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y);\r\n\r\n//交点の座標を求める\r\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y);\r\n\r\n//URGで障害物を検知する\r\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, URG &urg_data);\r\n\r\n//障害物を読み込む\r\nvoid read_obstacle(string ,OBSTACLE &);\r\n\r\n//時間を計測する\r\ndouble get_dtime(void);\r\n\r\n//strをdoubleに変換する\r\ndouble str_double(string str);\r\n\r\n\r\n//xy座標の成す角度thetaを求める。\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta);\r\n\r\n//目的値に向かう速度指令値を算出する\r\nvoid follow_velocity(double goal_x,double goal_y,double robot_theta,double &speed,double &turn);\r\n" }, { "alpha_fraction": 0.6796875, "alphanum_fraction": 0.6796875, "avg_line_length": 14.375, "blob_id": "98eadab2e8b3372bc37e5cab9cadef13bfc75a67", "content_id": "18cc9f4ecd8d36ded26a92a7e6dac75b0ab17feb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 128, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/check_pcl2ply/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\nall:\n\tmake -f Makefile.ros\n\nclean:\n\tmake -f Makefile.ros clean\n\t\n\n\t\n" }, { "alpha_fraction": 0.6186479330062866, "alphanum_fraction": 0.6358892917633057, "avg_line_length": 30.712230682373047, "blob_id": "c27e4ef6576aec822bf2e5faaaf844f2da06bd10", "content_id": "bd98784e9039df327e9219ae62e49310f8255e55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4408, "license_type": "no_license", "max_line_length": 153, "num_lines": 139, "path": "/n_scan_to_pcl/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <laser_assembler/AssembleScans.h>\n\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/PointCloud.h>\n#include <sensor_msgs/point_cloud_conversion.h>\n#include <sensor_msgs/LaserScan.h>\n#include <laser_geometry/laser_geometry.h>\n#include <tf/transform_listener.h>\n//PointCloud\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/filters/voxel_grid.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\nusing namespace std;\n\ndouble z_min = 0.5;\ndouble z_max = 4.0;\ndouble length_max = 10.0;\ndouble grid_leaf_size = 0.1f;\n\nvoid cloud_voxel(sensor_msgs::PointCloud2 &input){\n pcl::PointCloud<pcl::PointXYZ> cloud;\n pcl::PointCloud<pcl::PointXYZ> cloud_filtered;\n sensor_msgs::PointCloud2 output;\n pcl::fromROSMsg(input, cloud);\n\n pcl::VoxelGrid<pcl::PointXYZ> vox_obj;\n vox_obj.setInputCloud(cloud.makeShared());\n vox_obj.setLeafSize(grid_leaf_size, grid_leaf_size, grid_leaf_size);\n vox_obj.filter(cloud_filtered);\n\n pcl::toROSMsg(cloud_filtered, input);\n}\n\nvoid cloud_voxel_xy(sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output){\n pcl::PointCloud<pcl::PointXYZ> cloud;\n pcl::PointCloud<pcl::PointXYZ> cloud_filtered;\n pcl::fromROSMsg(input, cloud);\n\n pcl::VoxelGrid<pcl::PointXYZ> vox_obj;\n vox_obj.setInputCloud(cloud.makeShared());\n vox_obj.setLeafSize(grid_leaf_size, grid_leaf_size, 100.0);\n vox_obj.filter(cloud_filtered);\n\n pcl::toROSMsg(cloud_filtered, output);\n}\n\nnamespace scan_assembler{\n class ScanAssembler {\n public:\n ScanAssembler() {\n ros::NodeHandle private_nh(\"~\");\n private_nh.param(\"z_min\", z_min, 0.50);\n private_nh.param(\"z_max\", z_max, 4.00);\n private_nh.param(\"length_max\", length_max, 10.0);\n private_nh.param(\"grid_leaf_size\", grid_leaf_size, 0.10);\n\n ros::NodeHandle nh;\n\n laser_sub_ = nh.subscribe<sensor_msgs::LaserScan>(\"scan\", 10, boost::bind(&ScanAssembler::scanCb, this, _1));\n cloud_pub2_ = nh.advertise<sensor_msgs::PointCloud2>(\"pcl2_out\", 10);\n }\n\n void scanCb(const sensor_msgs::LaserScan::ConstPtr &scan_in) {\n\n double range_min = scan_in->range_min;\n double range_max = scan_in->range_max;\n double angle_increment = scan_in->angle_increment;\n double angle_min = scan_in->angle_min;\n double angle_max = scan_in->angle_max;\n int num_readings = (angle_max - angle_min) / angle_increment;\n\n if (!listener_.waitForTransform(\n scan_in->header.frame_id, \"/base_link\",\n scan_in->header.stamp + ros::Duration().fromSec(scan_in->ranges.size() * scan_in->time_increment),\n //\t\tros::Time::now(),\n ros::Duration(5.0))){\n return;\n }\n\n sensor_msgs::PointCloud cloud1;\n try {\n projector_.transformLaserScanToPointCloud(\"base_link\", *scan_in, cloud1, listener_);\n }\n catch (tf::TransformException &e) {\n std::cout << e.what();\n return;\n }\n\n //generate some fake data for our point cloud\n for (unsigned int i = 0; i < num_readings; ++i) {\n double dis = sqrt(cloud1.points[i].x * cloud1.points[i].x + cloud1.points[i].y * cloud1.points[i].y + cloud1.points[i].z * cloud1.points[i].z);\n\n if ((cloud1.points[i].z < z_min) || (cloud1.points[i].z > z_max) || (dis > length_max)) {\n float n = numeric_limits<float>::quiet_NaN();\n cloud1.points[i].x = n;\n cloud1.points[i].y = n;\n cloud1.points[i].z = n;\n }\n }\n\n sensor_msgs::convertPointCloudToPointCloud2(cloud1, cloud2);\n cloud_voxel(cloud2);\n cloud_pub2_.publish(cloud2);\n\n //\tsensor_msgs::convertPointCloudToPointCloud2(cloud1, cloud2_xy);\n cloud_voxel_xy(cloud2, cloud2_xy);\n // cloud_pub3_.publish(cloud2_xy);\n }\n\n private:\n laser_geometry::LaserProjection projector_;\n tf::TransformListener listener_;\n\n ros::Subscriber laser_sub_;\n //ros::Publisher cloud_pub1_;\n ros::Publisher cloud_pub2_;\n // ros::Publisher cloud_pub3_;\n\n sensor_msgs::PointCloud2 cloud2;\n sensor_msgs::PointCloud2 cloud2_xy;\n };\n }\n\n using namespace scan_assembler;\n int main(int argc, char **argv){\n\n ros::init(argc, argv, \"n_scan2pcl\");\n\n ScanAssembler sa;\n ros::spin();\n return 0;\n }\n" }, { "alpha_fraction": 0.3407079577445984, "alphanum_fraction": 0.36283186078071594, "avg_line_length": 11.176470756530762, "blob_id": "3fac61ce3355e2ae77cfbfd14abd589f5ba9a5a6", "content_id": "0da79ae7f074e5f5bedb3fe051e7740204ca74c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 306, "license_type": "no_license", "max_line_length": 46, "num_lines": 17, "path": "/orbit_pantilt_camera/readme.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "##############################################\r\n#pantiltcameraの使い方\t\t #\r\n##############################################\r\n\r\n1.概要\r\n Orbit AFのパンチルトヘッドを駆動します。\r\n\r\n2.依存ライブラリ\r\nuvcdynctrl\r\n\r\n3.コンパイル\r\ncd ./src\r\nmake\r\n\r\n4.実行\r\n\r\n5.使い方\r\n\r\n" }, { "alpha_fraction": 0.6483305096626282, "alphanum_fraction": 0.663463830947876, "avg_line_length": 24.85714340209961, "blob_id": "3784dd2300796c8119e59e68784fdca77ba4e6ac", "content_id": "624e744fab3587d894cf0086daae18c2094b45c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4163, "license_type": "no_license", "max_line_length": 110, "num_lines": 161, "path": "/n_sendgoal/src/sendGoals.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <move_base_msgs/MoveBaseAction.h>\n#include <actionlib/client/simple_action_client.h>\n#include <tf/transform_broadcaster.h>\n#include <sstream>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <std_msgs/Int16.h>\n#include <actionlib_msgs/GoalID.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/tf.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_listener.h>\n #include <sensor_msgs/Joy.h>\n#include <math.h>\ntf::TransformListener *tflistener;\n\ntypedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;\nros::Publisher goal_pub;\nros::Publisher joy_pub;\n\nint flag=0;\n\ndouble goal_x=0.0;\ndouble goal_y=0.0;\ndouble goal_w=0.0;\n\n\nvoid vel_Callback(const geometry_msgs::Twist::ConstPtr &vel_msg){\n flag=1;\n\n goal_x= vel_msg->linear.x;\n goal_y= vel_msg->linear.y;\n goal_w = vel_msg->angular.z;\n \n /*\n MoveBaseClient ac(\"move_base\", true);\n\n while (!ac.waitForServer(ros::Duration(5.0)))\n {\n\tROS_INFO(\"Waiting for the move_base action server\");\n }\n\n move_base_msgs::MoveBaseGoal goal;\n\n goal.target_pose.header.frame_id = \"map\";\n goal.target_pose.header.stamp = ros::Time::now();\n\n goal.target_pose.pose.position.x = goal_x;\n goal.target_pose.pose.position.y = goal_y;\n goal.target_pose.pose.orientation.x = 0.0;\n goal.target_pose.pose.orientation.y = 0.0;\n goal.target_pose.pose.orientation.z = goal_w;\n goal.target_pose.pose.orientation.w = 1.0;\n\n ROS_INFO(\"Sending goal\");\n ac.sendGoal(goal);\n\n ac.waitForResult();\n\n if (ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED)\n\tROS_INFO(\"You have arrived to the goal position\");\n else\n {\n\tROS_INFO(\"The base failed for some reason\");\n }\n \n */\n}\n\nvoid vel_Callback2(const geometry_msgs::Twist::ConstPtr &vel_msg){\n flag=2;\n\n goal_x= vel_msg->linear.x;\n goal_y= vel_msg->linear.y;\n goal_w = vel_msg->angular.z;\n \n}\n\n\nvoid joyCallback(const std_msgs::Int16::ConstPtr &msg)\n{\n if (msg->data == 1)\n {\n flag=1;\n }\n\n return;\n}\nvoid joyCallback2(const std_msgs::Int16::ConstPtr &msg)\n{\n if (msg->data == 1)\n {\n\tflag=2;\n\t}\n\n return;\n}\n\nint main(int argc, char **argv){\n\n ros::init(argc, argv, \"docu_send_navigation_goals\");\n ros::NodeHandle nh_;\n ros::Publisher goal_pub = nh_.advertise<geometry_msgs::PoseStamped>(\"/move_base_simple/goal\", 1);\n joy_pub = nh_.advertise<sensor_msgs::Joy>(\"joy2\", 1);\n\n ros::Publisher cmd_mode = nh_.advertise<std_msgs::Int16>(\"cmd_mode\", 1);\n\n ros::Subscriber vel_sub_= nh_.subscribe<geometry_msgs::Twist>(\"cmd_goal_pos\", 10, &vel_Callback);\n ros::Subscriber vel_sub_2= nh_.subscribe<geometry_msgs::Twist>(\"cmd_goal_pos_cancel\", 10, &vel_Callback2);\n \n ros::Subscriber joy_subscriber = nh_.subscribe(\"button4\", 1, joyCallback);\n ros::Subscriber joy_subscriber2 = nh_.subscribe(\"button5\", 1, joyCallback2);\n\n tf::StampedTransform transform;\n tf::TransformListener listener(ros::Duration(10));\n\n ros::Rate r(2.0);\n while (nh_.ok()){\n\n\tif(flag==1){\n\t\tROS_INFO(\"Please provide x and y of the goal!\");\n\t\tgeometry_msgs::PoseStamped msg;\n\t\tmsg.header.frame_id = \"/map\";\n\t\tmsg.pose.position.x = goal_x;\n\t\tmsg.pose.position.y = goal_y;\n\t\tmsg.pose.position.z = 0.0;\n\t\t\n\t\tgeometry_msgs::Quaternion quat= tf::createQuaternionMsgFromYaw(goal_w/180.0*M_PI);\n\t\t\n\t\tmsg.pose.orientation= quat;\n\n\t\tgoal_pub.publish(msg);\n\t\tflag=0;\n\t\t\n\t\t}\n\n\tif(flag==2){\n\t\tROS_INFO(\"stop!\");\n\t\tlistener.lookupTransform(\"map\", \"base_link\",ros::Time(0), transform);\n\n\t\t// actionlib_msgs::GoalID msg;\n\t\tgeometry_msgs::PoseStamped msg;\n\t\tmsg.header.frame_id = \"/map\";\n\t\tmsg.pose.position.x = transform.getOrigin().x();\n\t\tmsg.pose.position.y = transform.getOrigin().y();\n\t\tmsg.pose.position.z = transform.getOrigin().z();\n\t\tmsg.pose.orientation.x = transform.getRotation().getX();\n\t\tmsg.pose.orientation.y = transform.getRotation().getY();\n\t\tmsg.pose.orientation.z = transform.getRotation().getZ();\n\t\tmsg.pose.orientation.w = transform.getRotation().getW();\n\t\tgoal_pub.publish(msg);\n\t\tflag=0;\n\t}\n\n\tros::spinOnce();\n\tr.sleep();\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5785256624221802, "alphanum_fraction": 0.5945512652397156, "avg_line_length": 23.84000015258789, "blob_id": "29bbbfe3e997c32fd410be6dd516c1bf3519f9aa", "content_id": "dfabd10b1bed1b79ed3994569cf5d194405af2ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 624, "license_type": "no_license", "max_line_length": 80, "num_lines": 25, "path": "/n_robot_sim_moveobst/readme.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "$ rosnode info /n_robot_sim_moveobst_node \n--------------------------------------------------------------------------------\nNode [/n_robot_sim_moveobst_node]\nPublications: \n * /rosout [rosgraph_msgs/Log]\n * /move_obst [geometry_msgs/PoseArray]\n\nSubscriptions: None\n\nServices: \n * /n_robot_sim_moveobst_node/set_logger_level\n * /n_robot_sim_moveobst_node/get_loggers\n\n\ncontacting node http://iqit-desktop:43197/ ...\nPid: 7895\nConnections:\n * topic: /rosout\n * to: /rosout\n * direction: outbound\n * transport: TCPROS\n * topic: /move_obst\n * to: /n_3d_robot_sim\n * direction: outbound\n * transport: TCPROS\n\n\n\n" }, { "alpha_fraction": 0.3911111056804657, "alphanum_fraction": 0.42222222685813904, "avg_line_length": 13, "blob_id": "9c37d6a551fe9e0e3b97ca639212fe90e2d9b377", "content_id": "e9402e6a227d4c7518610760599df861e5fee599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 225, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/old/_memo/makeall.sh", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nmakeall(){\n echo $1\n cd $1\n make $2\n\n for FILE in `ls $1`\n do\n local FULL=$1/${FILE}\n if [ -d $FULL ]; then makeall $FULL $2\n fi\n done\n}\n\nmakeall `pwd` $1\n\n" }, { "alpha_fraction": 0.7515451312065125, "alphanum_fraction": 0.7552533745765686, "avg_line_length": 21.38888931274414, "blob_id": "d32648b07de2ab5318748110f536301fc673dbba", "content_id": "7c07f32652fab2f9188ad619d5db0700c6b9af60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 809, "license_type": "no_license", "max_line_length": 109, "num_lines": 36, "path": "/n_movebase_sendgoal_wp/CMakeLists.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(n_movebase_sendgoal_wp)\n\n## Find catkin macros and libraries\n## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)\n## is used, also find other catkin packages\nfind_package(catkin REQUIRED COMPONENTS\nroscpp \nstd_msgs \nsensor_msgs \ngeometry_msgs \nnav_msgs \ntf \nmove_base_msgs \nactionlib\n##cv_bridge\n)\n\ncatkin_package()\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n## ${OpenCV_INCLUDE_DIRS}\n ${OpenGL_INCLUDE_DIRS}\n)\nadd_executable(n_movebase_sendgoal_wp_node \n src/ros_main.cpp\n)\n\nadd_dependencies(n_movebase_sendgoal_wp_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n## Specify libraries to link a library or executable target against\ntarget_link_libraries(n_movebase_sendgoal_wp_node \n ${catkin_LIBRARIES}\n\n )\n\n\n\n" }, { "alpha_fraction": 0.6355818510055542, "alphanum_fraction": 0.6444504261016846, "avg_line_length": 26.97744369506836, "blob_id": "6f97b7631444c9cd3ec27aef88c4733bb2238ada", "content_id": "df26c6958f4e5f7f845f8d9f2f9882e2b956dd4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3721, "license_type": "no_license", "max_line_length": 99, "num_lines": 133, "path": "/n_pcl_assy_publish/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/*********************************************************************\n\n*********************************************************************/\n\n#include <cstdio>\n#include <ros/ros.h>\n\n// Services\n#include \"laser_assembler/AssembleScans.h\"\n\n// Messages\n#include \"sensor_msgs/PointCloud.h\"\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/point_cloud_conversion.h>\n\n//PointCloud\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/filters/voxel_grid.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\nusing namespace std;\n#include <ctime>\n\n\ndouble window = 0.0;\ndouble grid_leaf_size = 0.1f;\n//string frame_id = \"base_link\";\n//string frame_id = \"odom\";\n\n//double publish_rate_;\n\nvoid cloud_voxel(sensor_msgs::PointCloud2 &input){\n pcl::PointCloud<pcl::PointXYZ> cloud;\n pcl::PointCloud<pcl::PointXYZ> cloud_filtered;\n sensor_msgs::PointCloud2 output;\n pcl::fromROSMsg(input, cloud);\n\n pcl::VoxelGrid<pcl::PointXYZ> vox_obj;\n vox_obj.setInputCloud(cloud.makeShared());\n vox_obj.setLeafSize(grid_leaf_size, grid_leaf_size, grid_leaf_size);\n vox_obj.filter(cloud_filtered);\n pcl::toROSMsg(cloud_filtered, input);\n}\n\n\n/***\n* This a simple test app that requests a point cloud from the\n* point_cloud_assembler every 4 seconds, and then publishes the\n* resulting data\n*/\nnamespace laser_assembler{\n\n class PeriodicSnapshotter{\n\n public:\n PeriodicSnapshotter() {\n\n ros::NodeHandle private_nh(\"~\");\n private_nh.param(\"window\", window, 2.0);\n private_nh.param(\"grid_leaf_size\", grid_leaf_size, 0.05);\n\n // don't have a start and end time yet\n // Create a publisher for the clouds that we assemble\n // pub_ = n_.advertise<sensor_msgs::PointCloud>(\"assembled_cloud\", 1);\n pub2_ = n_.advertise<sensor_msgs::PointCloud2>(\"assembled_cloud2\", 1);\n // Create the service client for calling the assembler\n client_ = n_.serviceClient<AssembleScans>(\"assemble_scans\");\n\n // Start the timer that will trigger the processing loop (timerCallback)\n timer_ = n_.createTimer(ros::Duration(0.25, 0), &PeriodicSnapshotter::timerCallback, this);\n\n // Need to track if we've called the timerCallback at least once\n first_time_ = true;\n }\n\n void timerCallback(const ros::TimerEvent &e) {\n\n // We don't want to build a cloud the first callback, since we we\n if (first_time_) {\n first_time_ = false;\n return;\n }\n\n // Populate our service request based on our timer callback times\n AssembleScans srv;\n srv.request.begin = e.current_real - ros::Duration(window);\n srv.request.end = e.current_real;\n\n // Make the service call\n if (client_.call(srv)) {\n //ROS_INFO(\"Published Cloud with %u points\", (uint32_t)(srv.response.cloud.points.size()));\n // pub_.publish(srv.response.cloud);\n\n sensor_msgs::PointCloud2 cloud2;\n sensor_msgs::convertPointCloudToPointCloud2(srv.response.cloud, cloud2);\n cloud_voxel(cloud2);\n pub2_.publish(cloud2);\n }\n else {\n ROS_ERROR(\"Error making service call\\n\");\n }\n }\n\n private:\n ros::NodeHandle n_;\n // ros::Publisher pub_;\n ros::Publisher pub2_;\n\n ros::ServiceClient client_;\n ros::Timer timer_;\n bool first_time_;\n\n };\n}\n\nusing namespace laser_assembler;\n\nint main(int argc, char **argv){\n\n ros::init(argc, argv, \"periodic_snapshotter\");\n ros::NodeHandle n;\n ROS_INFO(\"Waiting for [build_cloud] to be advertised\");\n ros::service::waitForService(\"build_cloud\");\n ROS_INFO(\"Found build_cloud! Starting the snapshotter\");\n PeriodicSnapshotter snapshotter;\n ros::spin();\n return 0;\n}\n" }, { "alpha_fraction": 0.562001645565033, "alphanum_fraction": 0.5867329239845276, "avg_line_length": 26.27777862548828, "blob_id": "d6b38082dde064d28d2bc76330ec35bf7efad5c3", "content_id": "62672fc2cf8cd95fa636879d9e4fe905384d539a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8729, "license_type": "no_license", "max_line_length": 198, "num_lines": 306, "path": "/n_localpathplan/src/geometory.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n#include<stdlib.h>\r\n#include <math.h>\r\n#include<iostream>\r\n#include<string>\r\n#include<sstream>\r\n#include<fstream>\r\nusing namespace std;\r\n#include \"geometory.h\"\r\n\r\n#include <sys/time.h>\r\n#include <unistd.h>\r\n#include <SDL/SDL.h>\r\n#include <SDL/SDL_thread.h>\r\nextern double goal_reach_dis; //ゴールに到達したとする距離\r\nextern double turn_limit; //その角度以上で旋回\r\nextern double moving_goal_limit;\r\nextern double target_speed_gain;\r\nextern double target_turn_gain;\r\nextern double target_speed_max;\r\nextern double circling_turn_gain;\r\nextern double circling_turn_max;\r\nextern double dwa_robot_v_max;\r\nextern double dwa_robot_v_min;\r\nextern double dwa_robot_size;\r\nextern double dwa_urg_fail_min;\r\nextern double dwa_dt;\r\nextern double dwa_v_weight;\r\nextern double dwa_w_weight;\r\nextern double dwa_dis_weight;\r\nextern double dwa_leng_weight;\r\nextern double dwa_ac_trans_limit;\r\nextern double dwa_ac_rot_limit;\r\n\r\n\r\n\r\nstatic double get_dtime(){\r\n struct timeval tv;\r\n gettimeofday(&tv, NULL);\r\n double n_time =tv.tv_sec + tv.tv_usec * 1e-6;\r\n static double o_time= n_time;\r\n double dt_msec=(n_time-o_time);\r\n\r\n o_time= n_time;\r\n\r\n return dt_msec;\r\n}\r\n\r\n\r\nint To_goal_near(double _goal_x,double _goal_y,double _goal_theta,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis){\r\n\r\n double goal_x=_goal_x-robot_x;\r\n double goal_y=_goal_y-robot_y;\r\n double goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n double goal_theta=_goal_theta;\r\n double sub_rad=goal_theta-robot_theta;\r\n\r\n if(goal_l>goal_reach_dis*3.0)\r\n return 0;\r\n\r\n\r\n if(fabs(goal_theta-robot_theta)>1.0*PI){\r\n if(fabs(goal_theta-robot_theta+4.0*PI)<fabs(goal_theta-robot_theta)){\r\n sub_rad=goal_theta-robot_theta+2.0*PI;\r\n }\r\n else if(fabs(goal_theta-robot_theta-4.0*PI)<fabs(goal_theta-robot_theta)){\r\n sub_rad=goal_theta-robot_theta-2.0*PI;\r\n }\r\n else if(fabs(goal_theta-robot_theta+2.0*PI)<fabs(goal_theta-robot_theta)){\r\n sub_rad=goal_theta-robot_theta+2.0*PI;\r\n }\r\n else if(fabs(goal_theta-robot_theta-2.0*PI)<fabs(goal_theta-robot_theta)){\r\n sub_rad=goal_theta-robot_theta-2.0*PI;\r\n }\r\n }\r\n\r\n double turn_speed=fabs(sub_rad);\r\n if(sub_rad>=0) turn=-1*turn_speed;\r\n else if((sub_rad<=0)) turn=1*turn_speed;\r\n if(turn>0.4)\tturn=0.4;\r\n if(turn<-0.4)\tturn=-0.4;\r\n\r\n //if(turn_speed>circling_turn_max)turn_speed=circling_turn_max;\r\n\r\n double sub_rad_limit=0.1;\r\n if(turn_speed<sub_rad_limit) turn=0;\r\n\r\n\r\n return 1;\r\n}\r\n\r\nvoid To_goal_velocity(double _goal_x,double _goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis,double turn_limit){\r\n \r\n \r\n double goal_x=_goal_x-robot_x;\r\n double goal_y=_goal_y-robot_y;\r\n double goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n double goal_rad=(-1)*atan2(goal_x,goal_y);\r\n double robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\r\n double sub_rad=goal_rad-robot_theta_fmod;\r\n\r\n const double goal_error=5.0;\t//ゴールに近くないのに5m離れている。\r\n if((_goal_x==0.0)&&(_goal_y==0.0)&&(goal_l>goal_error)) {\r\n speed=0.0;\r\n turn=0.0;\r\n cout<<\"To_goal_velocity _error\"<<endl;\r\n return;\r\n }\r\n\r\n if(fabs(goal_rad-robot_theta_fmod)>1.0*PI){\r\n if(fabs(goal_rad-robot_theta_fmod+4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n sub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n }\r\n else if(fabs(goal_rad-robot_theta_fmod-4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n sub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n }\r\n else if(fabs(goal_rad-robot_theta_fmod+2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n sub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n }\r\n else if(fabs(goal_rad-robot_theta_fmod-2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n sub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n }\r\n }\r\n\r\n double x=goal_l;\r\n speed=fabs(x);\r\n\r\n double turn_speed=fabs(sub_rad);\r\n double r=sub_rad;\r\n\r\n\r\n\r\n if(sub_rad>=0) turn=-1*turn_speed;\r\n else if((sub_rad<=0)) turn=1*turn_speed;\r\n if(turn>0.4)\tturn=0.4;\r\n if(turn<-0.4)\tturn=-0.4;\r\n\r\n\r\n\r\n\r\n if(sub_rad>=turn_limit)\tspeed=0.0;\r\n if(sub_rad<=-turn_limit)\tspeed=0.0;\r\n\r\n if(speed>target_speed_max)\tspeed=target_speed_max;\r\n\r\n\r\n if(goal_l<goal_reach_dis) speed=0.0;\r\n\r\n\r\n\r\n\r\n \tcout<<\"goal_l\"<<goal_l<<endl;\r\n \tcout<<\"sub_rad\"<<sub_rad<<endl;\r\n \tcout<<\"speed\"<<speed<<endl;\r\n \tcout<<\"turn\"<<turn<<endl;\r\n\r\n\r\n return ;\r\n}\r\n\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn){\r\n double goal_x=path.x[path.now_n]-robot_x;\r\n double goal_y=path.y[path.now_n]-robot_y;\r\n double goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n double goal_rad=(-1)*atan2(goal_x,goal_y);\r\n //double moving_goal_limit=0.5;\r\n\r\n if(goal_l<moving_goal_limit){\r\n if(path.now_n+1<path.n){\r\n path.now_n++;\r\n }\r\n else if(path.now_n+1==path.n) {\r\n speed=0;\r\n turn=0;\r\n }\r\n }\r\n else{\r\n\r\n To_goal_velocity( path.x[path.now_n], path.y[path.now_n],robot_x,robot_y,robot_theta,speed,turn,moving_goal_limit,3.14*2.0);\r\n }\r\n //cout<<\"n:\"<<path.now_n<<\"_x:\"<<path.x[path.now_n]<<\"_y:\"<<path.y[path.now_n]<<\"_\"<<path.n<<endl;\r\n return;\r\n}\r\n\r\n\r\nvoid dynamic_windows_approach(URG urg_data,double path_x[][DATA_SEQ],double path_y[][DATA_SEQ],double path_cost[],int &path_size,double robot_v,double robot_w,double &best_v,double &best_w,int flg){\r\n\r\n cout<<\"in_v:\"<<robot_v<<\"\\t in_w:\"<<robot_w <<\"\\n\";\r\n\t\r\n if(robot_v>dwa_robot_v_max)best_v=dwa_robot_v_max;\r\n if(robot_v<dwa_robot_v_min)best_v=dwa_robot_v_min;\r\n\r\n\r\n for(int i = 0;i < 1000;i++){\r\n for(int j = 0;j < DATA_SEQ;j++){\r\n path_x[i][j]=0.0;\r\n path_y[i][j]=0.0;\r\n }\r\n }\r\n\r\n best_v=robot_v;\r\n best_w=robot_w;\r\n\r\n if(best_v<0.01)\treturn;\r\n\r\n flg=0;\r\n double urg_x[2000]={};\r\n double urg_y[2000]={};\r\n double urg_l[2000]={};\r\n\r\n\r\n for(int i=0;i<urg_data.data_num-1;i++){\r\n urg_x[i]=(-1)*urg_data.leng[i]*sin(i*urg_data.reso+urg_data.start_rad);\r\n urg_y[i]=urg_data.leng[i]*cos(i*urg_data.reso+urg_data.start_rad);\r\n urg_l[i]=sqrt(urg_x[i]*urg_x[i]+urg_y[i]*urg_y[i]);\r\n //cout<< urg_x[i]<<\",\"<< urg_y[i]<<endl;\r\n }\r\n\r\n double path_cost_w[2000]={};\r\n double path_cost_v[2000]={};\r\n int cnt=0;\r\n\r\n double v_range_s=robot_v;\r\n double w_range=1.5*PI;\r\n double dv=2*robot_v/20.0;\r\n double dw=2*w_range/80.0;\r\n\r\n\t//cout<<\"dw\"<<2*w_range/dw<<endl;\r\n\t//cout<<\"dv\"<<2*v_range_s/dv<<endl;\r\n\t\r\n int future_cnt=100;\r\n for(double v=v_range_s;v<robot_v;v+=dv){\r\n for(double w=robot_w-w_range;w<robot_w+w_range;w+=dw){\r\n if(v<0)v=0;\r\n double x=0;\r\n double y=0;\r\n double real_v=robot_v;\r\n double real_w=0.0;\r\n double theta=0;\r\n double length =0;\r\n double dis_min =1;\r\n path_cost[cnt]=0;\r\n path_cost_w[cnt]=w;\r\n path_cost_v[cnt]=v;\r\n for(int k = 0;k < future_cnt;k++){\r\n if(path_cost[cnt]>1000)break;\r\n if(theta>1*PI)break;\r\n if(theta<-1*PI)break;\r\n\r\n if(fabs(real_v-v)/dwa_dt>dwa_ac_trans_limit){\r\n if((v-real_v)>=0)\t\treal_v+=dwa_ac_trans_limit*dwa_dt;\r\n else if((v-real_v)<0)\treal_v-=dwa_ac_trans_limit*dwa_dt;\r\n }\r\n if(fabs(real_w-w)/dwa_dt>dwa_ac_rot_limit){\r\n if((w-real_w)>=0)\t\treal_w+=dwa_ac_rot_limit*dwa_dt;\r\n else if((w-real_w)<0)\treal_w-=dwa_ac_rot_limit*dwa_dt;\r\n }\r\n\r\n theta+= real_w*dwa_dt;\r\n x+= -real_v*sin(-theta)*dwa_dt;\r\n y+= real_v*cos(-theta)*dwa_dt;\r\n length += fabs(dwa_dt*v);\r\n\tcout<<\",\"<<x<<\",\"<<y<<\",\"<<theta<<\",\"<<endl;\r\n for(int i=0;i<urg_data.data_num-1;i++){\r\n if(urg_l[i]>dwa_urg_fail_min){\r\n double dist=sqrt((x-urg_x[i])*(x-urg_x[i])+(y-urg_y[i])*(y-urg_y[i]));\r\n if(dist<dwa_robot_size) {\r\n path_cost[cnt]=99999.0;\r\n }\r\n if(dis_min>dist)\tdis_min=dist;\r\n }\r\n }\r\n double cost=dwa_v_weight*fabs(v-robot_v)+dwa_w_weight*fabs(w-robot_w)+dwa_leng_weight*length+dwa_dis_weight*(5.0-dis_min);\r\n if(path_cost[cnt]<cost) {\r\n path_cost[cnt]=cost;\r\n }\r\n\r\n path_x[cnt][k]=x;\r\n path_y[cnt][k]=y;\r\n\r\n }\r\n cnt++;\r\n }\r\n }\r\n \r\n path_size=cnt;\r\n double best_cost=99999.0;\r\n for(int j=0;j<cnt-1;j++){\r\n if((path_cost[j]<best_cost)&&(path_cost[j]>0.0001)){\r\n if(path_cost[j]<1000){\r\n best_cost=path_cost[j];\r\n best_w=path_cost_w[j];\r\n best_v=path_cost_v[j];\r\n flg=1;\r\n }\r\n }\r\n else if(best_cost==99999.0){\r\n best_v=0.0;\r\n best_w=0.0;\r\n }\r\n }\r\n cout<<\"best_v:\"<<best_v<<\"_w:\"<<best_w<<\"_cost\"<<best_cost<<endl;\r\n\r\n return ;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6705653071403503, "alphanum_fraction": 0.6705653071403503, "avg_line_length": 24.350000381469727, "blob_id": "a721222f32dffa9de41e7046fb3308ac2026039e", "content_id": "0f4cea20dbe7c60d84017195d7c2731684177dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 513, "license_type": "no_license", "max_line_length": 99, "num_lines": 20, "path": "/n_robot_sim/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\nname=n_robot_sim\n\nall:\n\tmake -f Makefile.$(name)\n\nclean:\n\tmake -f Makefile.$(name) clean\n\t\n\t\ninstall:\n\tmkdir -p $(install_prefix)/lib/$(project)\n\tmkdir -p $(install_prefix)/share/$(project)/launch\n\techo \"<package><name>$(project)</name></package>\" > $(install_prefix)/share/$(project)/package.xml\n\ttouch $(install_prefix)/.catkin\n\tcp -a docu_joy_to_cmd $(install_prefix)/lib/$(project)\n\t\nuninstall:\n\trm -f $(install_prefix)/lib/$(project)/$(name)\n\t\n\t\n\t\n" }, { "alpha_fraction": 0.8000817894935608, "alphanum_fraction": 0.8082583546638489, "avg_line_length": 75.34375, "blob_id": "1e66edff972c9e50d3c25499de45a220800a730f", "content_id": "2725f94d68e27ae6e39dc401d5ea314221e754e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2446, "license_type": "no_license", "max_line_length": 338, "num_lines": 32, "path": "/inst_ros.sh", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "sudo apt-get update -y\nsudo apt-get -y install ssh inkscape checkinstall\nsudo apt-get -y install g++ cmake global exuberant-ctags doxygen git-core\nsudo apt-get -y install emacs-goodies-el windows-el ispell migemo w3m-el mew wl mhc auctex yatex ecb pymacs pyrex-mode wget-el\nsudo apt-get -y install texlive-latex-extra texlive-latex-recommended texlive-math-extra texlive-pictures texlive-publishers latex-beamer\nsudo apt-get -y install libboost-dev libboost-python-dev\nsudo apt-get -y install python-numpy python-numpy-ext python-numeric python-numeric-ext python-numarray python-numarray-ext python-imaging python-matplotlib python-scientific python-scipy python-plplot python-opencv python-rpy python-sparse python-sparse-examples python-stats python-sip4-dev python-subversion python-setuptools pychecker\nsudo apt-get -y install sbcl clisp slime hyperspec cl-asdf cl-interpol cl-kmrcl cl-cffi cl-ppcre lush\nsudo apt-get -y install cl-trivial-sockets cl-who cl-s-xml cl-hunchentoot\nsudo apt-get -y install cl-statistics cl-plplot xmaxima wxmaxima maxima-src maxima-test mascyma\nsudo apt-get -y install cl-sql onlisp-code onlisp-pdf cl-readline\nsudo apt-get -y install libcv-dev libcv1 python-magic libglew-dev libglut-dev libmagick++9-dev libcv-dev lapack3-dev libf2c2-dev uuid-dev libxmu-dev libxxf86vm-dev libgsl0-dev\nsudo apt-get -y install slapd bind9 postfix-ldap dovecot-pop3d libapache2-mod-python trac trac-ja-resource\nsudo apt-get -y install auth-client-config\nsudo apt-get -y install nautilus-open-terminal\nsudo apt-get -y install freeglut3-dev freeglut3-dbg libxmu-dev libxi-dev libglui-dev build-essential\nsudo aptitude -y install vim vim-runtime\nsudo apt-get install -y libcv-*\nsudo apt-get -y install evince ghostscript cmap-adobe-japan1 xpdf-japanese evince ghostscript cmap-adobe-japan1 xpdf-japanese\nsudo apt-get -y install vlc\nsudo apt-get -y install freeglut3-dev freeglut3-dbg libxmu-dev libxi-dev build-essential\nsudo apt-get -y install ros-indigo-roswww\nsudo apt-get -y install ros-indigo-joy\nsudo apt-get -y install ros-indigo-robot-pose-publisher \nsudo apt-get -y install ros-indigo-jsk-rviz-plugins \nsudo apt-get -y install ros-indigo-jsk-rqt-plugins \nsudo apt-get -y install ros-indigo-web-video-server\nsudo apt-get -y install ros-indigo-kobuki*\nsudo apt-get -y install ros-indigo-navigation\nsudo apt-get -y install ros-indigo-urg-node\nsudo apt-get -y install ros-indigo-hokuyo-node\nsudo apt-get -y install apache2\n\n\n\n" }, { "alpha_fraction": 0.6101602911949158, "alphanum_fraction": 0.6653083562850952, "avg_line_length": 25.577617645263672, "blob_id": "f148d49f37c78ecd62f339c91344f7032f56c8f9", "content_id": "a6dffca74387b1f48a314d127d6bfc503e604209", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7464, "license_type": "no_license", "max_line_length": 111, "num_lines": 277, "path": "/n_object_tracking_runcontrol/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Twist.h>\n#include <std_msgs/Float32.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\nusing namespace std;\n#include <ctime>\n#include <signal.h>\n\nros::Publisher Debug_pub1;\nros::Publisher Debug_pub2;\nros::Publisher cmd_vel_pub;\n\nvoid follow_velocity(double goal_x,double goal_y,double robot_theta,double &speed,double &turn);\n\nint load_config(string fname);\nvoid mySigintHandler(int);\n\ndouble now_t=0;\ndouble old_t=0;\n\ndouble speed_max=\t0.5;\ndouble speed_min=\t-0.2;\ndouble turn_max=\t0.8;\ndouble turn_min=\t-0.8;\ndouble turn_area=\t0.750;\ndouble danger_dis=\t0.3;\ndouble danger_count_thresh=\t200;\ndouble m_accelerate_mps=\t0.4;\ndouble m_accelerate_rps=\t0.4;\n\n\ndouble v_gain0=0;\ndouble v_gain1=0;\ndouble v_gain2=0;\ndouble v_gain3=0;\ndouble v_gain4=0;\ndouble v_gain5=0;\n\ndouble w_gain0=0;\ndouble w_gain1=0;\ndouble w_gain2=0;\ndouble w_gain3=0;\ndouble w_gain4=0;\ndouble w_gain5=0;\n\nvoid mySigintHandler(int sig) {\n\n\t//終了時に速度を0に実行する。\n\tgeometry_msgs::Twist twist;\n\ttwist.linear.x = 0.0;\n\ttwist.angular.z =0.0;\n\n\n\tcmd_vel_pub.publish(twist);\n\n\tprintf(\"shutdown catch signal %d \\n\", sig);\n\tros::shutdown();\n}\n\n\nvoid arc_tan2(double &target_x,double &target_y,double &dis,double &theta){\n\tdouble target_r = sqrt(target_x*target_x+target_y*target_y);\n\tif(target_r==0) target_r=0.0000001;\n\tdis=target_r;\n\n\tif(target_y>=0){\n\t\ttheta=acos(target_x/target_r);\n\t\ttheta=theta*180.0/M_PI;\n\t}\n\telse if(target_y<0){\n\t\ttheta=acos(target_x/target_r);\n\t\ttheta=360.0-theta*180.0/M_PI;\n\t}\n\n\tif(theta>=90.0) theta=theta-90.0;\n\telse if(theta<90.0) theta=theta-90.0;\n\tif(theta>180.0) theta=theta-360.0;\n\n}\n\n\n\nvoid poseCallback(const geometry_msgs::Pose::ConstPtr & msg){\n\tdouble target_x=msg->position.x;\n\tdouble target_y=msg->position.y;\n\n\n\tdouble target_dis=0;\n\tdouble target_theta=0;\n\tarc_tan2(target_x,target_y,target_dis,target_theta);\n\n\tstd_msgs::Float32 pan_msg;\n\tpan_msg.data= target_theta;\n\tDebug_pub1.publish(pan_msg);\n\n\n\tstd_msgs::Float32 tilt_msg;\n\t//\ttilt_msg.data= (1.5-target_dis)*-30-20;\n\tif(target_dis<1.5)\ttilt_msg.data=-30.0;\n\telse if((target_dis>1.5)&&(target_dis<3))\ttilt_msg.data=-20.0;\n\telse tilt_msg.data=-0;\n\t//else if(tilt_msg.data>0)tilt_msg.data=0;\n\n\tDebug_pub2.publish(tilt_msg);\n\n\t//\tcout<<pan_msg.data<<\"_\"<<tilt_msg.data<<endl;\n\n\n\tdouble myrobot_x=0.0;\n\tdouble myrobot_y=0.0;\n\tdouble myrobot_theta=0.0;\n\tdouble robot_speed=0.0;\n\tdouble robot_turn=0.0;\n\n\tfollow_velocity( target_x-myrobot_x, target_y-myrobot_y,myrobot_theta,robot_speed,robot_turn);\n\n\tif((target_x==0.0)&&(target_y==0)){\n\t\trobot_speed=0.0;\n\t\trobot_turn=0.0;\n\t}\n\n\tgeometry_msgs::Twist base_cmd;\n\tbase_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\n\tbase_cmd.linear.x=robot_speed;\n\tbase_cmd.angular.z = robot_turn;\n\n\tcmd_vel_pub.publish(base_cmd);\n\n\tcout<<\"pos y:\"<<target_y<<\"\\t pos x:\"<<target_x<<\"_\";\n\tcout<<\"vel:\"<<base_cmd.linear.x<<\"\\t omega:\"<<base_cmd.angular.z <<\"\\n\";\n\n\n}\n\nint main(int argc, char** argv){\n\n\tros::init(argc, argv, \"n_object_traking_run_control\");\n\n\tros::NodeHandle nh_;\n\tros::Subscriber pose_subscriber = nh_.subscribe (\"target_pos\", 10, poseCallback);\n\tcmd_vel_pub = nh_.advertise<geometry_msgs::Twist>(\"cmd_vel2\", 10);\n\n\tDebug_pub1= nh_.advertise<std_msgs::Float32>(\"camera_pan_angle\", 1);\n\tDebug_pub2= nh_.advertise<std_msgs::Float32>(\"camera_tilt_angle\", 1);\n\n\tros::NodeHandle private_nh(\"~\");\n\tprivate_nh.param(\"speed_max\", \t\tspeed_max,\t\t0.5);\n\tprivate_nh.param(\"speed_min\", \t\tspeed_min, \t\t-0.2);\n\n\tprivate_nh.param(\"turn_max\", \t\tturn_max,\t\t0.8);\n\tprivate_nh.param(\"turn_min\", \t\tturn_min, \t\t-0.8);\n\tprivate_nh.param(\"turn_area\", \t\tturn_area, \t\t0.75);\n\n\t//private_nh.param(\"danger_dis\", \t\tdanger_dis, \t0.3);\n\t//private_nh.param(\"danger_count_thresh\", danger_count_thresh, \t200.0);\n\n\tprivate_nh.param(\"m_accelerate_mps\", \tm_accelerate_mps, \t50.0);\n\tprivate_nh.param(\"m_accelerate_rps\", \tm_accelerate_rps, \t50.0);\n\n\tprivate_nh.param(\"v_gain0\", \tv_gain0, \t0.000);\n\tprivate_nh.param(\"v_gain1\", \tv_gain1, \t0.000);\n\tprivate_nh.param(\"v_gain2\", \tv_gain2, \t0.000);\n\tprivate_nh.param(\"v_gain3\", \tv_gain3, \t0.340);\n\tprivate_nh.param(\"v_gain4\", \tv_gain4, \t1.370);\n\tprivate_nh.param(\"v_gain5\", \tv_gain5, \t0.0);\n\n\tprivate_nh.param(\"w_gain0\", \tw_gain0, \t0.0);\n\tprivate_nh.param(\"w_gain1\", \tw_gain1, \t0.0);\n\tprivate_nh.param(\"w_gain2\", \tw_gain2, \t0.0);\n\tprivate_nh.param(\"w_gain3\", \tw_gain3, \t0.0);\n\tprivate_nh.param(\"w_gain4\", \tw_gain4, \t1.0);\n\tprivate_nh.param(\"w_gain5\", \tw_gain5, \t0.0);\n\n\tsignal(SIGINT, mySigintHandler);\n\n\tros::spin();\n\n\treturn 0;\n}\n\ndouble timer_ms() {\n\n\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\tdouble n_time = tv.tv_sec + tv.tv_usec * 1e-6;\n\treturn n_time;\n}\n\n\nvoid follow_velocity(double goal_x,double goal_y,double robot_theta,double &speed,double &turn){\n\tdouble mps_variation=0.0;\n\tdouble rps_variation=0.0;\n\tdouble urg_x=goal_x;\n\tdouble urg_y=goal_y;\n\tdouble urg_l=sqrt(goal_x*goal_x+goal_y*goal_y);\n\tdouble urg_rad=(-1)*atan2(urg_x,urg_y);\n\n\t//ロボット角度の正規化(+2PIに抑制)\n\tdouble robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\n\t//角度の差分\n\tdouble sub_rad=urg_rad-robot_theta_fmod;\n\n\tstatic long old_t;\n\tstatic double old_speed;\n\tstatic double old_turn;\n\n\t//Tanが±πの範囲のため、右回りと左回りを評価\n\tif(fabs(urg_rad-robot_theta_fmod)>1.0*M_PI){\n\t\tif(fabs(urg_rad-robot_theta_fmod+4.0*M_PI)<fabs(urg_rad-robot_theta_fmod)){\n\t\t\tsub_rad=urg_rad-robot_theta_fmod+2.0*M_PI;\n\t\t}\n\t\telse if(fabs(urg_rad-robot_theta_fmod-4.0*M_PI)<fabs(urg_rad-robot_theta_fmod)){\n\t\t\tsub_rad=urg_rad-robot_theta_fmod-2.0*M_PI;\n\t\t}\n\t\telse if(fabs(urg_rad-robot_theta_fmod+2.0*M_PI)<fabs(urg_rad-robot_theta_fmod)){\n\t\t\tsub_rad=urg_rad-robot_theta_fmod+2.0*M_PI;\n\t\t}\n\t\telse if(fabs(urg_rad-robot_theta_fmod-2.0*M_PI)<fabs(urg_rad-robot_theta_fmod)){\n\t\t\tsub_rad=urg_rad-robot_theta_fmod-2.0*M_PI;\n\t\t}\n\t}\n\tdouble x=urg_l;\n\t//speed = 0.0246*pow(x,4) - 0.1987*pow(x,3) + 0.169*pow(x,2) + 10.7482*pow(x,1) - 0.8423;\n\tspeed = +v_gain4*pow(x,4) +v_gain3*pow(x,3) +v_gain2*pow(x,2) +v_gain1*pow(x,1) +v_gain0;\n\tif(goal_y<0) speed=0.0;\n\tif(speed>=speed_max)\t\tspeed=speed_max;\n\tif(speed<speed_min)\t\tspeed=speed_min;\n\n\t//double turn_speed=fabs(sub_rad);\n\t//turn_speed = -0.0278*pow(x,5) + 0.3025*pow(x,4) - 1.1232*pow(x,3) + 1.4103*pow(x,2) + 0.4428*pow(x,1) + 0.0;\n\tx=fabs(sub_rad);\n\n\n\t//turn = -0.0278*pow(x,5) + 0.3025*pow(x,4) - 0.6232*pow(x,3) + 1.4103*pow(x,2) + 10.4428*pow(x,1) + 0.0;\n\tturn = w_gain5*pow(x,5) + w_gain4*pow(x,4) +w_gain3*pow(x,3) + w_gain2*pow(x,2) + w_gain1*pow(x,1) + w_gain0;\n\n\tif(sub_rad<0) turn=-turn;\n\telse if(sub_rad>=0) turn=turn;\n\tif(turn>=M_PI*turn_area)\tspeed=0.0;\n\tif(turn<=-M_PI*turn_area)\tspeed=0.0;\n\n\tif(turn>turn_max) turn=turn_max;\n\tif(turn<turn_min) turn=turn_min;\n\n\tnow_t=timer_ms();\n\tif((now_t!=0)&&(old_t!=0)&&((now_t-old_t)>0)){\n\n\t\tmps_variation=(now_t-old_t)/1000.0*m_accelerate_mps;\n\t\trps_variation=(now_t-old_t)/1000.0*m_accelerate_rps;\n\n\t\tif(fabs(speed-old_speed)>mps_variation){\n\t\t\tspeed=old_speed+(speed-old_speed)/fabs(speed-old_speed)*mps_variation;\n\t\t}\n\t\tif(fabs(turn-old_turn)>rps_variation){\n\t\t\tturn=old_turn+(turn-old_turn)/fabs(turn-old_turn)*rps_variation;\n\t\t}\n\t}\n\n\told_t= timer_ms();\n\told_speed=speed;\n\told_turn=turn;\n\n\t//cout<<\"robo\"<<robot_theta_fmod<<\"\\t\";\n\t//cout<<\"atan\"<<sub_rad<<\"\\t\";\n\t//cout<<\"sub\"<<turn<<endl;\n\n}\n" }, { "alpha_fraction": 0.65302973985672, "alphanum_fraction": 0.6669239401817322, "avg_line_length": 21.929203033447266, "blob_id": "b91f7e149e2daadbde7326483212b86352b2550b", "content_id": "b71de01a26a908ecaf7c994e75c807331d714843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2669, "license_type": "no_license", "max_line_length": 98, "num_lines": 113, "path": "/n_3d_robot_sim/src/gl_main.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\n\n/////////////////////////////////////////////////\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n#include <GL/glut.h>\n#include <GL/gl.h>\n#include <GL/glu.h>\n\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <sys/time.h>\n#include <unistd.h>\n#endif\n\n\n#include <SDL/SDL.h>\n#include <SDL/SDL_thread.h>\n\n#ifdef _WIN32\n#pragma comment(lib, \"SDL.lib\")\n#pragma comment(lib, \"SDLmain.lib\")\n#endif\n\n#include \"geometory.h\"\n#include \"collision_detec_3d.h\"\n\n\n\n\n//各種OpenGL変数宣言\nconst int WIDTH = 800, HEIGHT = WIDTH;//ウィンドウのサイズ\n\nvoid draw_string(string str, int w=WIDTH, int h=HEIGHT, int x0=10, int y0=10);\nvoid move_obstacle_view();\n\nvoid robot_expect_path_view(double target_v,double target_w,double x=0,double y=0,double theta=0);\nvoid robot_view(struct ROBOT &robot);\nvoid urg_view( ROBOT &robot,URG &urg_data);\nvoid obstacle_view();\nvoid path_view();\nvoid robot_log_view(double dt);\nvoid mySetLight(void);\n\nvoid cv_bridge_init();\n\n\nvoid display2();\nvoid myMouse2( int button, int state, int x, int y );\nvoid myMotion2( int x, int y );\nvoid resetview2( void );\nvoid polarview2( void );\nvoid reshape2(int ,int);\nvoid myMouse2( int button, int state, int x, int y );\nvoid reshape2(int,int);\n\nvoid main_draw();\n\nclass Graphics{\nprivate:\n\tstatic void display();\n\tstatic void myMouse( int button, int state, int x, int y );\n\tstatic void myMotion( int x, int y );\n\tstatic void resetview( void );\n\n\tstatic void idle(void);\n\tstatic void myInit(char *progname);\n\tstatic void mySkey( int key, int x, int y );\n\tstatic void myKbd( unsigned char key, int x, int y );\n\tstatic void myKbdup( unsigned char key, int x, int y );\n\tstatic void reshape(int ,int);\n\t\n\tstatic void polarview( void );\n\tstatic void* start_gui(void *);\n\tstatic int GUImain();\n\tvoid gui_start();\n\tvoid gui_end();\n\t\tdouble timer_ms();\n\n\n\tstatic int main_3d_process();\n\tSDL_Thread *th1;\n\tSDL_Thread *th2;\n//\tstatic int POINTS;\n\tfloat click_Depth(int x, int y);//マウスのX/Y座標からDepthを算出\n\tstatic void click_pickup(int x,int y,double &ax,double &ay,double &az);//マウスのX/Y座標からX/Y/Z座標を算出\n\n\t//static void urg_view_sub( URG &urg_data);\n\t//static void display2();\n\t//static void myMouse2( int button, int state, int x, int y );\n\t//static void myMotion2( int x, int y );\n\t//static void resetview2( void );\n\t//static void polarview2( void );\n\t//static void reshape2(int ,int);\n\tstatic void gl_disp_save();\n\npublic:\n Graphics();\n virtual ~Graphics();\n\n};\n\n\n\n\nstatic void glVertex3f_p(double x,double y,double z){\n\t\t\tglVertex3f(y,z,x);\n}\n\nvoid walkman(double now,double delay);\n" }, { "alpha_fraction": 0.6655573844909668, "alphanum_fraction": 0.6688851714134216, "avg_line_length": 19.724138259887695, "blob_id": "3ae5f45fbec7fddccefe2996dcb01314e6c57b84", "content_id": "e00d75ef9055474638ac68b8b864eeb340a782cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 601, "license_type": "no_license", "max_line_length": 96, "num_lines": 29, "path": "/n_cartographer_mapsave/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include \"cartographer_ros_msgs/WriteState.h\"\n#include <cstdlib>\n#include <iostream>\n#include <string>\nusing namespace std;\n\nint main(int argc, char **argv){\n\n ros::init(argc, argv, \"cartographer_client\");\n\n ros::NodeHandle n;\n ros::ServiceClient client = n.serviceClient<cartographer_ros_msgs::WriteState>(\"write_state\");\n\n cartographer_ros_msgs::WriteState srv;\n string sss=\"/home/iqit/test\";\n srv.request.filename = sss;\n \n if (client.call(srv)) {\n ROS_INFO(\"OK, map saving:\");\n }\n else\n {\n ROS_ERROR(\"Failed map saving:\");\n return 1;\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7463768124580383, "alphanum_fraction": 0.760869562625885, "avg_line_length": 11.454545021057129, "blob_id": "d3fd3b7f36989afc64b4813290bb00d81114f19e", "content_id": "11f9b4a80727ccf636d6535b57f75dc76dbf370f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 138, "license_type": "no_license", "max_line_length": 45, "num_lines": 11, "path": "/myproject/configuration_files/toyota_hsr_localization.lua", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "include \"toyota_hsr.lua\"\n\nTRAJECTORY_BUILDER.pure_localization = true\nSPARSE_POSE_GRAPH.optimize_every_n_scans = 10\n\n\n\n\n\n\nreturn options\n\n" }, { "alpha_fraction": 0.511864423751831, "alphanum_fraction": 0.5152542591094971, "avg_line_length": 25.636363983154297, "blob_id": "f2bcfe8f67d750aad0a6ecb6214bd923ee642c6c", "content_id": "a772709ff34c06fbd20aa762839de328a66fdd3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 295, "license_type": "no_license", "max_line_length": 80, "num_lines": 11, "path": "/n_scan_to_scan/readme.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "rosnode info /n_scan_to_scan_node \n--------------------------------------------------------------------------------\nNode [/n_scan_to_scan_node]\nPublications: \n * /scan_out2 [sensor_msgs/LaserScan]\n * /rosout [rosgraph_msgs/Log]\n\nSubscriptions: \n * /scan_out [sensor_msgs/LaserScan]\n\nServices: \n\n" }, { "alpha_fraction": 0.743259072303772, "alphanum_fraction": 0.7467761039733887, "avg_line_length": 22, "blob_id": "03ec508c272059134ebfadb753434040b7120f5c", "content_id": "b6ef70011ecd9aa042cf038b5b937f985723d48d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 853, "license_type": "no_license", "max_line_length": 107, "num_lines": 37, "path": "/orbit_pantilt_camera/CMakeLists.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(orbit_pantilt_camera)\n\n## Find catkin macros and libraries\n## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)\n## is used, also find other catkin packages\nfind_package(catkin REQUIRED COMPONENTS\n geometry_msgs\n nav_msgs\n roscpp\n rospy\n sensor_msgs\n tf\n cv_bridge\n)\n\ncatkin_package()\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n# ${OpenCV_INCLUDE_DIRS}\n# ${OpenGL_INCLUDE_DIRS}\n)\nadd_executable(orbit_pantilt_camera_node\n src/control_orbit_pantilt.cpp\n)\n\nadd_dependencies(orbit_pantilt_camera_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n## Specify libraries to link a library or executable target against\ntarget_link_libraries(orbit_pantilt_camera_node \n ${catkin_LIBRARIES}\n# ${OpenCV_LIBRARIES}\n# ${OpenGL_LIBRARIES}\n# ${GLUT_LIBRARY}\n\n )\n\n\n" }, { "alpha_fraction": 0.5698058009147644, "alphanum_fraction": 0.5987541079521179, "avg_line_length": 17.919708251953125, "blob_id": "388cff662aeb880760c009cef67503b50923c461", "content_id": "0047eb3718ef2129d277eff0670388bb5e4357b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2945, "license_type": "no_license", "max_line_length": 141, "num_lines": 137, "path": "/n_object_tracking/src_error/geometory.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n#pragma once\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n\r\n#ifdef _WIN32\r\n#else\r\n#include <sys/time.h>\r\n#endif\r\n\r\nusing namespace std;\r\nconst double PI=3.14159265359;\r\n\r\n#define URG_DATA_MAX 2000\r\nconst unsigned int urg_data_num=680;\r\nconst double urg_range_deg=240.0;\r\nconst double urg_leng_max=50.0;\r\nconst double urg_leng_min=0.1;\r\n\r\n\r\nstruct ROBOT{\t\t//ロボットの定義\r\n\tdouble x;\t\t//X座標\r\n\tdouble y;\t\t//Y座標\r\n\tdouble theta;\t//角度\r\n\tdouble v;\t\t//速度\r\n\tdouble w;\t\t//角速度\r\n\r\n\tROBOT(){\r\n\t\tx = 0.0;\r\n\t\ty = 0.0;\r\n\t\tv = 0.0;\r\n\t\tw = 0.0;\r\n\t\ttheta = 0.0;\r\n\t}\r\n\r\n\tvoid odometory(double dt){\r\n\t\tx+=v*sin(-theta)*dt;\r\n\t\ty+=v*cos(-theta)*dt;\r\n\t\ttheta-=w*dt;\r\n\r\n\t\t//if(theta<=(-2.0*PI)) theta+=2*PI;\r\n\t\t//if(theta>(2.0*PI)) theta-=2*PI;\r\n\t\r\n\t}\r\n};\r\n\r\nstruct URG{\t\t\t//測域センサの定義\r\n\tdouble leng[URG_DATA_MAX];\t\t\r\n\tdouble x[URG_DATA_MAX];\t\r\n\tdouble y[URG_DATA_MAX];\t\r\n\tint data_num;\r\n\tdouble start_rad;\r\n\tdouble reso;\r\n\r\n\tdouble leng_max;\r\n\tdouble leng_min;\r\n\r\n\tURG(){\r\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\r\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*PI;\r\n\t\treso=2*PI/URG_DATA_MAX;\r\n\t\tleng_max=urg_leng_max;\r\n\t\tleng_min=urg_leng_min;\r\n\r\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\r\n\t\tx[i] = 0.0;\r\n\t\ty[i] = 0.0;\r\n\t\tleng[i] = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\r\n};\r\n\r\n\r\ntypedef struct LRF_clustering{\r\n int flag; \r\n int flag2;\r\n int ptnum;\r\n int clnum;\r\n double dis;\r\n double r[URG_DATA_MAX];\r\n double x[URG_DATA_MAX];\r\n double y[URG_DATA_MAX];\r\n double x_ave;\r\n double y_ave;\r\n double r_ave;\r\n \r\n}CLUSTER;\r\n\r\ntypedef struct LRF_clusterTag{\r\n double r;\r\n double x;\r\n double y;\r\n double dis;\r\n int i;\r\n}TAG;\r\n\r\n\r\n\r\n//線分と点との距離\r\ndouble line_seg_point_distance( double px, double py,double ax, double ay, double bx, double by);\r\n\r\n\r\n////線分の交差判定関数\r\n//bool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y);\r\n//\r\n////交点の座標を求める\r\n//bool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y);\r\n\r\n//時間を計測する\r\ndouble get_dtime(void);\r\n\r\n//strをdoubleに変換する\r\ndouble str_double(string str);\r\n\r\n//xy座標の成す角度thetaを求める。\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta);\r\n\r\n//目的値に向かう速度指令値を算出する\r\nvoid follow_velocity(double goal_x,double goal_y,double robot_theta,double &speed,double &turn);\r\n\r\n//クラスタリング\r\nvoid LRF_clustring_main(URG urg_data,CLUSTER clust[]);\r\n\r\n//トラッキング\r\nint LRF_clustring_tracking(CLUSTER clust[],double &goal_x,double &goal_y,int mouse_flag,int &clust_no);\r\n" }, { "alpha_fraction": 0.7511045932769775, "alphanum_fraction": 0.7555228471755981, "avg_line_length": 21.633333206176758, "blob_id": "10186a23566ba36987e26a6eeb1b5fcd14ec9101", "content_id": "d2a555e8e1159457acd1e339b486989554ca4588", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 679, "license_type": "no_license", "max_line_length": 63, "num_lines": 30, "path": "/n_sendgoal/CMakeLists.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(n_send_goal)\n\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n move_base_msgs\n actionlib\n tf\n sensor_msgs\n)\n\ncatkin_package()\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n)\n\nadd_executable(n_send_goal_node src/sendGoals.cpp)\ntarget_link_libraries(n_send_goal_node ${catkin_LIBRARIES})\n\ninstall(TARGETS n_send_goal_node \n ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}\n)\n\nforeach(dir launch maps)\n install(DIRECTORY ${dir}/\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/${dir})\nendforeach(dir)\n" }, { "alpha_fraction": 0.7316176295280457, "alphanum_fraction": 0.7316176295280457, "avg_line_length": 27.77777862548828, "blob_id": "8ea987fbae0adc0c1e6aa3d5431b4672bb5569f1", "content_id": "d8ef5d6b8a53c194614643e3aaea739dfb2212ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 362, "license_type": "no_license", "max_line_length": 92, "num_lines": 9, "path": "/n_object_tracking/src/read_file.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "\r\n\r\n\r\n//TEXT読み込み・一致したら値を返す\r\nint string_Matching(vector<string> lines,string para_name,string &params,string delim=\"\\t\");\r\n// 文字列 target が 文字列 pattern で始まっている場合には真、さもなくば偽を返す。\r\nint shrhstr( string target_str, string pattern_str );\r\n\r\ndouble StringToDouble(string in);\r\n\r\n\r\n" }, { "alpha_fraction": 0.7068965435028076, "alphanum_fraction": 0.7068965435028076, "avg_line_length": 15.5, "blob_id": "66d0a2bca674b2af2a06a3b2d512415a15acb9d0", "content_id": "2895cc7c4c0e3dce0482e9d6b08cf188675ee473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 174, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/docu_navi_localpathplan/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\n\nall:\n\tmake -f Makefile.docu_navi_localpathplan\n\n\nclean:\n\tmake -f Makefile.docu_navi_localpathplan clean\n\t\n\t\n\n\t\n\t\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 23, "blob_id": "61543b691ef79b97ecd621601a92061430bd5433", "content_id": "b1926c31d2c3bf84f4e2f8450053e25779ed29d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/check_pcl_save/readme.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": " pcl_viewer data_out.pcd \n\n" }, { "alpha_fraction": 0.5635005235671997, "alphanum_fraction": 0.5869797468185425, "avg_line_length": 31.310344696044922, "blob_id": "03d44e917a0526737547a1f4d0ca5001a81346f8", "content_id": "7415fef61f5f838a7f07738c2faca281b6f33261", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1874, "license_type": "no_license", "max_line_length": 128, "num_lines": 58, "path": "/check_pcl2ply/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n\n// notice! fake faces!\n\nusing namespace pcl;\n\nint main( int argc, char** argv ){\n\n if( argc != 3 ){\n std::cerr << \"usage: \" << argv[0] << \" [Input PCD file] [Output PLY file]\" << std::endl;\n return 0;\n }\n\n pcl::PointCloud<pcl::PointXYZRGB> input_cloud;\n pcl::io::loadPCDFile (argv[1], input_cloud);\n\n //* count number of points\n int vnum = 0;\n for( size_t i = 0; i < input_cloud.points.size(); ++i )\n if( !isnan(input_cloud.points[ i ].x) && !isnan(input_cloud.points[ i ].y) && !isnan(input_cloud.points[ i ].z) )\n vnum++;\n\n //* fake faces\n int fnum = floor(vnum/3);\n if( vnum % 3 != 0 )\n fnum++;\n\n //* write PLY file\n FILE *fp = fopen( argv[2], \"w\" );\n fprintf(fp,\"ply\\n\");\n fprintf(fp,\"format ascii 1.0\\n\");\n fprintf(fp,\"element vertex %d\\n\", vnum);\n fprintf(fp,\"property float x\\n\");\n fprintf(fp,\"property float y\\n\");\n fprintf(fp,\"property float z\\n\");\n fprintf(fp,\"property uchar red\\n\");\n fprintf(fp,\"property uchar green\\n\");\n fprintf(fp,\"property uchar blue\\n\");\n fprintf(fp,\"element face %d\\n\", fnum);\n fprintf(fp,\"property list uchar int vertex_indices\\n\");\n fprintf(fp,\"end_header\\n\");\n for( size_t i = 0; i < input_cloud.points.size(); ++i ){\n if( isnan(input_cloud.points[ i ].x) || isnan(input_cloud.points[ i ].y) || isnan(input_cloud.points[ i ].z) )\n continue;\n int color = *reinterpret_cast<const int*>(&(input_cloud.points[i].rgb));\n int r = (0xff0000 & color) >> 16;\n int g = (0x00ff00 & color) >> 8;\n int b = 0x0000ff & color;\n fprintf(fp,\"%f %f %f %d %d %d\\n\", input_cloud.points[ i ].x, input_cloud.points[ i ].y, input_cloud.points[ i ].z, r, g, b);\n }\n for( int i = 0; i < fnum-1; ++i )\n fprintf(fp,\"3 %d %d %d\\n\", i*3, i*3+1, i*3+2);\n fprintf(fp,\"3 %d %d %d\\n\", vnum-3, vnum-2, vnum-1);\n fclose( fp );\n\n return 1;\n}\n" }, { "alpha_fraction": 0.6318749785423279, "alphanum_fraction": 0.6485416889190674, "avg_line_length": 30.16883087158203, "blob_id": "f3b8d8ba20dfdc2031750a068d755087abe29de0", "content_id": "7818471fcd1c5f4f3bdcbbf9208da5d95e01b463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4826, "license_type": "no_license", "max_line_length": 121, "num_lines": 154, "path": "/n_send_panunit/src/send_panunit_rot.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Twist.h>\n#include <std_msgs/Float32.h>\n#include <std_msgs/Int16.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include <move_base_msgs/MoveBaseAction.h>\n#include <actionlib_msgs/GoalStatusArray.h>\n#include <actionlib/client/simple_action_client.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_broadcaster.h>\n#include <sstream>\n#include <geometry_msgs/Twist.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\n#include <ctime>\n\n#include <signal.h>\nvoid mySigintHandler(int);\n\nusing namespace std;\n//ros::Publisher twist_pub;\nros::Publisher pan_unit_speed;\ndouble pan_speed;\n\n\n\nvoid switch_Callback(const std_msgs::Int16::ConstPtr &bottom_msg){\n int bottom = bottom_msg->data;\n static int bottom_old = bottom_msg->data;\n static bool switch_flg = false;\n\tstd_msgs::Float32 msg_float;\n if ((bottom_old==0)&&(bottom == 1)){\n\tif (switch_flg == true)\n\t switch_flg = false;\n\telse if (switch_flg == false)\n\t switch_flg = true;\n }\n\n if (switch_flg == true){\n msg_float.data = pan_speed;\n\t pan_unit_speed.publish(msg_float);\n }\n else{\n\tmsg_float.data = 0.0;\n pan_unit_speed.publish(msg_float);\n }\n cout<<\"switch_flg\"<<switch_flg<<\"\\t \";\n cout<<\"pan_speed\"<<msg_float.data<<endl;\n \n bottom_old = bottom_msg->data;\n usleep(100*1000);\n \n}\n\n\nvoid navStatusCallBack(const actionlib_msgs::GoalStatusArray::ConstPtr &status){\n int status_id = 0;\n //status=3;goal\n //status=1;moving\n\n\tif (!status->status_list.empty()){\n\tactionlib_msgs::GoalStatus goalStatus = status->status_list[0];\n\t status_id = goalStatus.status;\n\tcout<<goalStatus.text<<endl;\n\t}\n\n\tif(status_id==1){\n\t//geometry_msgs::Twist twist;\n\t//twist.linear.x = pan_speed;\n\t//twist_pub.publish(twist);\n\tstd_msgs::Float32 msg_float;\n\tmsg_float.data = pan_speed;\n\t pan_unit_speed.publish(msg_float);\n\t}\n\n\tif((status_id==3)||(status_id==0)){\n\t//geometry_msgs::Twist twist;\n\t//twist.linear.x = 0.0;\n\t//twist_pub.publish(twist);\n\tstd_msgs::Float32 msg_float;\n\tmsg_float.data = 0.0;\n\tpan_unit_speed.publish(msg_float);\n\t}\n\n}\n\nint main(int argc, char **argv){\n ros::init(argc, argv, \"docu_send_panunit_rot\");\n\n ros::NodeHandle private_nh(\"~\");\n\n private_nh.param(\"pan_speed\", pan_speed, 36000.0);\n\n ros::NodeHandle nh;\n ros::Subscriber switch_sub;\n\n switch_sub = nh.subscribe<std_msgs::Int16>(\"panunit_rot_button\", 10, &switch_Callback);\n // twist_pub = nh.advertise<geometry_msgs::Twist>(\"panunit_rot\", 1);\n pan_unit_speed= nh.advertise<std_msgs::Float32>(\"panunit_speed\", 10);\n\n\n //ros::Subscriber move_base_status_sub;\n //move_base_status_sub = nh.subscribe<actionlib_msgs::GoalStatusArray>(\"/move_base/status_\", 10, &navStatusCallBack);\n\n signal(SIGINT, mySigintHandler);\n ros::spin();\n\n return 0;\n}\n\n\nvoid mySigintHandler(int sig)\n{\n\n //終了時に速度を0に実行する。\n// geometry_msgs::Twist twist;\n// twist.linear.x = 0.0;\n// twist_pub.publish(twist);\n\n\t//std_msgs::Float32 msg_float;\n\t//msg_float.data = 0.0;\n\t//pan_unit_speed.publish(msg_float);\n\n\tprintf(\"shutdown catch signal %d \\n\", sig);\n\tros::shutdown();\n}\n\n//uint8 status\n//uint8 PENDING = 0 # The goal has yet to be processed by the action server\n//uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n//uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n// # and has since completed its execution (Terminal State)\n//uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n//uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n// # to some failure (Terminal State)\n//uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n// # because the goal was unattainable or invalid (Terminal State)\n//uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n// # and has not yet completed execution\n//uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n// # but the action server has not yet confirmed that the goal is canceled\n//uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n// # and was successfully cancelled (Terminal State)\n//uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n// # sent over the wire by an action server\n" }, { "alpha_fraction": 0.6622516512870789, "alphanum_fraction": 0.6622516512870789, "avg_line_length": 15.11111068725586, "blob_id": "71cd003b63cb27803727ba7f0a0424d4b030cc37", "content_id": "ebef26b6f7d181d821d6245ca420ac60f200bfea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 151, "license_type": "no_license", "max_line_length": 38, "num_lines": 9, "path": "/robo_rot/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\nname=robo_rot\n\nall:\n\tmake -f Makefile.$(name)\n\nclean:\n\tmake -f Makefile.$(name) clean\n\t\n\t\n\t\n" }, { "alpha_fraction": 0.42195257544517517, "alphanum_fraction": 0.47214561700820923, "avg_line_length": 19.551136016845703, "blob_id": "3a4083879212ffad9dc45195fc9a483ebd431896", "content_id": "b88a26fc65c7eb29e8230f572b752ba56bfa7b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3626, "license_type": "no_license", "max_line_length": 78, "num_lines": 176, "path": "/robo_rot/pan_unit/pan_unit.py", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport rospy\nimport tf\n#import tf2_ros\n\nimport serial\nimport time\nimport sys\nimport traceback\n\nimport conv_position\n\nser = serial.Serial (\n port = \"/dev/tty_SPU01\",\n # port = \"/dev/ttyUSB2\",\n # port = \"/dev/tnt1\",\n # port = \"/dev/tnt0\",\n baudrate = 9600,\n parity = serial.PARITY_NONE,\n bytesize = serial.EIGHTBITS,\n stopbits = serial.STOPBITS_ONE,\n timeout = 5,\n xonxoff = 0,\n rtscts = 0,\n dsrdtr = 0,\n writeTimeout = None,\n # interCharTimeout = None\n)\n\n\ndef control_pan_unit():\n #rosparam \n\n test_cmd = [\n 'gp,1\\n', # get position\n ]\n\n test2_cmd = [\n 'sva,1,2000\\n', \n 'saa,1,5000\\n', \n 'src,1,10\\n', \n 'grc,1\\n', \n 'gp,1\\n', \n 'ssm,1,0\\n', \n 'grc,1\\n', \n 'gp,1\\n', \n\n ]\n\n init_cmd2 = [\n 'init,1\\n',\n 'sva,1,2000\\n',\n 'saa,1,5000\\n',\n 'sdm,1,1\\n',\n 'ssm,1,3\\n',\n 'srm,1,1\\n',\n 'src,1,0',\n ]\n\n init_cmd3 = [\n 'init,1\\n',\n 'ssm,1,3\\n',\n 'ssc,1,0\\n',\n 'sva,1,36000\\n',\n 'saa,1,133333\\n',\n 'slva,1,800\\n',\n 'gsm,1\\n',\n 'gdc,1\\n',\n 'gsc,1\\n',\n 'gtv,1\\n',\n 'ga,1\\n',\n 'glv,1\\n',\n 'gv,1\\n',\n 'sdc,1,0\\n',\n 'sdm,1,1\\n',\n 'srm,1,1\\n',\n 'gp,1\\n',\n 'sva,1,0\\n',\n ]\n\n rot_cmd = {\n 'right':'sva,1,36000\\n', \n 'left':'sva,1,-36000\\n',\n }\n\n fin_cmd = [\n 'sdm,1,0\\n',\n 'init,1\\n',\n ]\n\n if(ser.isOpen() == False):\n ser.open()\n\n print \"init\"\n for x in init_cmd3:\n print('send :'+ x)\n ser.write(x)\n recv = ser.readline()\n print('recv :' + recv)\n\n print \"rotate\"\n key = 'right'\n \n ser.write(rot_cmd[key]) \n print(key + ': ' + rot_cmd[key])\n\n theta = 0\n pos = 0\n while not rospy.is_shutdown():\n \n ser.write('gp,1\\n')\n # ignore whitespace\n resp = ser.readline()\n\ttry:\n \tpos = int(resp)\n\texcept:\n\t\tcontinue\n\n\t#OFFSET_Parametor\n\ttheta2=22.0/180*3.1415\n\trobot_x=-0.25\n\trobot_y=0.0\n\trobot_z=1.5\n\ttheta_offset=-230.0/180.0*3.1415\n\n\ttheta = -conv_position.convertPosToAnguler(pos)*2.0+theta_offset\n br = tf.TransformBroadcaster()\n\n br.sendTransform((robot_x,robot_y,robot_z), \n tf.transformations.quaternion_from_euler(0,theta2,theta),\n rospy.Time.now(),\n \"base_scan\", \n \"base_link\")\n\n\n time.sleep(0.025)\n # theta = theta + 1\n \n THRESHOLD_POS = 134016000 \n # THRESHOLD_POS = 1000\n #THRESHOLD = 134208000 - ONE_REVOLUTION\n \n if ( pos > THRESHOLD_POS ):\n ser.write(rot_cmd['left'])\n elif ( pos < -THRESHOLD_POS ):\n ser.write(rot_cmd['right'])\n else:\n pass\n \nif __name__ == '__main__':\n try:\n rospy.init_node('pan_unit')\n control_pan_unit()\n\n except :\n error_type,error_value,traceback_ = sys.exc_info()\n tb_list = traceback.format_tb(traceback_)\n print(error_type)\n print(error_value)\n print(tb_list)\n\n finally : \n print \"stop program\"\n ser.write('sdm,1,0\\n')\n ret = ser.readline()\n print('fin sdm,1\\n' + ret)\n ser.write('init,1\\n')\n ret = ser.readline()\n print('fin init,1\\n' + ret)\n ser.close()\n print('fin closed serial,1\\n')\n \n\n# except KeyboardInterrupt, err:\n# except rospy.ROSInterruptException:\n# ser.close()\n \n" }, { "alpha_fraction": 0.31553396582603455, "alphanum_fraction": 0.31553396582603455, "avg_line_length": 23.75, "blob_id": "555c989453dab5b4ec3b2ffc199cb614bd7dcca0", "content_id": "24451d30f5dbc300dda6ac614e0d34214a6968c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 208, "license_type": "no_license", "max_line_length": 50, "num_lines": 8, "path": "/n_object_tracking/src_error/opencv_inc.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n#include <cv.h>\r\n#include <highgui.h>\r\n#include <time.h>\r\nusing namespace cv;\r\n" }, { "alpha_fraction": 0.7177914381027222, "alphanum_fraction": 0.7177914381027222, "avg_line_length": 14.899999618530273, "blob_id": "65874596b65bf1fc61ab728e06ae90cef5071276", "content_id": "77086cd75c430d4a32763590923f45ef35b4f354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 163, "license_type": "no_license", "max_line_length": 44, "num_lines": 10, "path": "/n_localpathplan/src2/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\n\nall:\n\tmake -f Makefile.n_navi_localpathplan\n\n\nclean:\n\tmake -f Makefile.n_navi_localpathplan clean\n\t\n\n\n" }, { "alpha_fraction": 0.7122371196746826, "alphanum_fraction": 0.7217973470687866, "avg_line_length": 21.212766647338867, "blob_id": "8b5f19de913a58ff5419b534856c6f0b9c0d1f88", "content_id": "9986bdd7e082259eb906248fe2e681e28ba6d728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 101, "num_lines": 47, "path": "/n_3d_robot_sim/CMakeLists.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(n_3d_robot_sim)\n\n## Find catkin macros and libraries\n## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)\n## is used, also find other catkin packages\nfind_package(catkin REQUIRED COMPONENTS\n geometry_msgs\n nav_msgs\n roscpp\n rospy\n sensor_msgs\n tf\n std_msgs \n geometry_msgs \n pcl_ros nav_msgs \n cv_bridge \n image_transport\n)\n\ncatkin_package()\n\ninclude_directories(\n ${catkin_INCLUDE_DIRS}\n ${OpenCV3_INCLUDE_DIRS}\n ${OpenGL_INCLUDE_DIRS}\n)\nadd_executable(n_3d_robot_sim_node \n\t src/collision_detec_3d.cpp \n\t src/gl_win_sub.cpp \n\t src/rt_main.cpp \n\t src/geometory.cpp \n\t src/gl_win_main.cpp \n\t src/read_file.cpp \n\t src/gl_human.cpp\n)\n\nadd_dependencies(n_3d_robot_sim_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})\n\n## Specify libraries to link a library or executable target against\ntarget_link_libraries(n_3d_robot_sim_node \n ${catkin_LIBRARIES}\n ${OpenCV3_LIBRARIES}\n ${OpenGL_LIBRARIES}\n ${GLUT_LIBRARY}\n -lglut -lGLU -lGL -lm -lSDL\n )\n\n\n" }, { "alpha_fraction": 0.5178571343421936, "alphanum_fraction": 0.5267857313156128, "avg_line_length": 29.363636016845703, "blob_id": "73259d7ee2c850248d53cf3f66484ae3dfacad49", "content_id": "675ad1ff696d6ef723edd435a86f56cbe4acfaee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 336, "license_type": "no_license", "max_line_length": 80, "num_lines": 11, "path": "/n_scan_to_pcl/readme.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "rosnode info /n_scan_to_pcl_node \n--------------------------------------------------------------------------------\nNode [/n_scan_to_pcl_node]\nPublications: \n * /pcl2_out [sensor_msgs/PointCloud2]\n * /rosout [rosgraph_msgs/Log]\n\nSubscriptions: \n * /tf [tf2_msgs/TFMessage]\n * /scan [sensor_msgs/LaserScan]\n * /tf_static [unknown type]\n\n\n" }, { "alpha_fraction": 0.7254902124404907, "alphanum_fraction": 0.7254902124404907, "avg_line_length": 15.88888931274414, "blob_id": "0f122029bee90cd079d89c929b917ee40963de89", "content_id": "4c426d1434ccd986072fbfeb2db56973aa2069b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 153, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/n_object_tracking/src_error/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "\nproject = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\n\nall:\n\tmake -f Makefile.n_object_tracking\n\nclean:\n\tmake -f Makefile.n_object_tracking clean\n" }, { "alpha_fraction": 0.6225228309631348, "alphanum_fraction": 0.6520918607711792, "avg_line_length": 23.933332443237305, "blob_id": "717ed7ad624ddc276e71b142c31c373e0d32f7c3", "content_id": "c45169a3cb89b5192d061c68ad5a98e7053c7d03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6618, "license_type": "no_license", "max_line_length": 111, "num_lines": 255, "path": "/n_joy2cmd/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <geometry_msgs/Twist.h>\n#include <sensor_msgs/Joy.h>\n#include <std_msgs/Int16.h>\n#include <geometry_msgs/PoseArray.h>\n#include <iostream>\n#include <vector>\n#include <std_msgs/Float32.h>\nusing namespace std;\n\n#include <signal.h>\n\nint linear_ch = 0, angular_ch = 1;\ndouble l_scale = 0.0, a_scale = 0.0;\n//int button_ch;\nint button_ch1 = 0;\nint button_ch2 = 1;\nint button_ch3 = 2;\nint button_ch4 = 3;\nint button_ch5 = 4;\nint button_ch6 = 5;\nros::Publisher twist_pub_;\n\nclass JoyStickOp{\npublic:\n JoyStickOp();\n void twist_send();\n ros::NodeHandle nh_;\n static void mySigintHandler(int);\n\nprivate:\n void joyCallback(const sensor_msgs::Joy::ConstPtr &joy);\n void navi_Callback(const geometry_msgs::Twist::ConstPtr &vel_msg);\n void tracking_Callback(const geometry_msgs::Twist::ConstPtr &vel_msg);\n void cmd_Callback(const std_msgs::Int16::ConstPtr& vel_msg);\n \n ros::Publisher button_pub1_;\n ros::Publisher button_pub2_;\n ros::Publisher button_pub3_;\n ros::Publisher button_pub4_;\n ros::Publisher button_pub5_;\n ros::Publisher button_pub6_;\n ros::Publisher Debug_pub1;\n ros::Publisher Debug_pub2;\n\n\n ros::Subscriber joy_sub_;\n ros::Subscriber vel_sub_;\n ros::Subscriber vel_sub_2;\n ros::Subscriber cmd_mode_in;\n ros::Publisher cmd_mode_out;\n \n double axis_y, axis_x;\n int button[8];\n double twist_v_navi, twist_w_navi;\n double twist_v_tracking, twist_w_tracking;\n\n double move_x, move_y;\n \n int mode_cb;\t\n};\n\nJoyStickOp::JoyStickOp(){\n ros::NodeHandle private_nh(\"~\");\n private_nh.param(\"axis_linear_ch\", linear_ch, 1);\n private_nh.param(\"axis_angular_ch\", angular_ch, 0);\n private_nh.param(\"scale_angular\", a_scale, 1.0);\n private_nh.param(\"scale_linear\", l_scale, 1.0);\n twist_v_navi = 0.0, twist_w_navi = 0.0;\n twist_v_tracking = 0.0, twist_w_tracking = 0.0;\n \n \n for (int i = 0; i < 8; i++) {\n button[i] = 0;\n }\n move_x = 0;\n move_y = 0;\n\n twist_pub_ = nh_.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1);\n button_pub1_ = nh_.advertise<std_msgs::Int16>(\"button1\", 1);\n button_pub2_ = nh_.advertise<std_msgs::Int16>(\"button2\", 1);\n button_pub3_ = nh_.advertise<std_msgs::Int16>(\"button3\", 1);\n button_pub4_ = nh_.advertise<std_msgs::Int16>(\"button4\", 1);\n button_pub5_ = nh_.advertise<std_msgs::Int16>(\"button5\", 1);\n button_pub6_ = nh_.advertise<std_msgs::Int16>(\"button6\", 1);\n\n Debug_pub1= nh_.advertise<std_msgs::Float32>(\"debug_x\", 10);\n Debug_pub2= nh_.advertise<std_msgs::Float32>(\"debug_y\", 10);\n\n joy_sub_ = nh_.subscribe<sensor_msgs::Joy>(\"joy\", 1, &JoyStickOp::joyCallback, this);\n vel_sub_ = nh_.subscribe<geometry_msgs::Twist>(\"cmd_vel_navi\", 1, &JoyStickOp::navi_Callback, this);\n vel_sub_2 = nh_.subscribe<geometry_msgs::Twist>(\"cmd_vel_tracking\", 1, &JoyStickOp::tracking_Callback, this);\n \n cmd_mode_in = nh_.subscribe<std_msgs::Int16>(\"cmd_mode\", 1, &JoyStickOp::cmd_Callback,this);\n cmd_mode_out = nh_.advertise<std_msgs::Int16>(\"cmd_mode\", 1);\n \n mode_cb=0;\n\n signal(SIGINT, mySigintHandler);\n}\n\n\nvoid JoyStickOp::cmd_Callback(const std_msgs::Int16::ConstPtr& msg){\n\tROS_INFO(\"cmd_Callback heard: [%d]\", msg->data);\n\tif(msg->data!=99) mode_cb=msg->data;\n\n\n}\n\nvoid JoyStickOp::twist_send(){\n\n//ここで条件分岐\n//button0:マニュアル操作モード\n//button1:ナビゲーションモード\n//button2:トラッキングモード\n\n\n\n static int button0_old=0;\t\n static int button1_old=0;\t\n static int button2_old=0;\t\n static int button3_old=0;\t\n \n //プラウザからの入力を初期値\n int mode=mode_cb;\n \n geometry_msgs::Twist twist;\n if (button[0] == 1){\t\t//マニュアル操作は全てに優先される\n twist.angular.z = axis_x;\n twist.linear.x = axis_y;\n }\n else if (mode == 0){\t\t//マニュアルモードでは停止\n twist.angular.z = axis_x;\n twist.linear.x = axis_y;\n }\n else if (mode == 1){\t\t//ナビゲーションモード\n twist.linear.x = twist_v_navi;\n twist.angular.z = twist_w_navi;\n }\n else if (mode == 2) {\t\t//トラッキングモード\n twist.linear.x = twist_v_tracking;\n twist.angular.z =twist_w_tracking;\n }\n else if (mode == 3) {\t\t//トラッキングモード\n twist.linear.x = twist_v_navi;;\n twist.angular.z =twist_w_navi;\n }\n else {\t\t\t//その他では停止\n twist.angular.z = 0.0;\n twist.linear.x = 0.0;\n cout<<\"else\"<<endl;\n }\n \n button0_old=button[0];\n button1_old=button[1];\n button2_old=button[2];\n button3_old=button[3];\n \n \n //速度命令をpublish\n twist_pub_.publish(twist);\n\n std_msgs::Float32 msg_float;\n msg_float.data =-move_y;\n Debug_pub1.publish(msg_float);\n\n msg_float.data =move_x;\n Debug_pub2.publish(msg_float);\n\n}\n\nvoid JoyStickOp::navi_Callback(const geometry_msgs::Twist::ConstPtr &vel_msg){\n twist_v_navi = vel_msg->linear.x;\n twist_w_navi = vel_msg->angular.z;\n\n twist_send();\n}\n\nvoid JoyStickOp::tracking_Callback(const geometry_msgs::Twist::ConstPtr &vel_msg){\n twist_v_tracking = vel_msg->linear.x;\n twist_w_tracking = vel_msg->angular.z;\n\n twist_send();\n}\n\nvoid JoyStickOp::joyCallback(const sensor_msgs::Joy::ConstPtr &joy){\n axis_x = a_scale * joy->axes[angular_ch];\n axis_y = l_scale * joy->axes[linear_ch];\n\n for (int i = 0; i < 8; i++) {\n button[i] = joy->buttons[i];\n }\n\n std_msgs::Int16 msg_int;\n msg_int.data=99;\n if(button[3]==1) \t\tmsg_int.data =3;\n else if(button[2]==1) \tmsg_int.data =2;\n else if(button[1]==1) \tmsg_int.data =1;\n else if(button[0]==1) \tmsg_int.data =0;\n cmd_mode_out.publish(msg_int);\n \n\n std_msgs::Int16 button_out;\n button_out.data = button[button_ch1];\n button_pub1_.publish(button_out);\n\n button_out.data = button[button_ch2];\n button_pub2_.publish(button_out);\n\n button_out.data = button[button_ch3];\n button_pub3_.publish(button_out);\n\n button_out.data = button[button_ch4];\n button_pub4_.publish(button_out);\n\n button_out.data = button[button_ch5];\n button_pub5_.publish(button_out);\n\n button_out.data = button[button_ch6];\n button_pub6_.publish(button_out);\n\n // std_msgs::Float32 joy_axis;\n move_x = joy->axes[2];\n move_y = joy->axes[3];\n\n twist_send();\n}\n\nvoid JoyStickOp::mySigintHandler(int sig){\n\n //終了時に速度を0に実行する。\n geometry_msgs::Twist twist;\n twist.linear.x = 0.0;\n twist.angular.z = 0.0;\n\n twist_pub_.publish(twist);\n\n printf(\"shutdown catch signal %d \\n\", sig);\n ros::shutdown();\n}\n\nint main(int argc, char **argv){\n ros::init(argc, argv, \"n_joy2cmd\");\n JoyStickOp teleop_turtle;\n\n ros::Rate r(20.0);\n\n while (teleop_turtle.nh_.ok()) {\n ros::spinOnce();\n r.sleep();\n\n teleop_turtle.twist_send();\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.5758209228515625, "alphanum_fraction": 0.6126865744590759, "avg_line_length": 20.78911590576172, "blob_id": "5de2475f50ca9e5363e2c1076f0eb2f9f4651f69", "content_id": "e988cc1c2612ad7d35c37de73cff110b353c05b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13870, "license_type": "no_license", "max_line_length": 103, "num_lines": 588, "path": "/n_map_view/src/viewgui.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n/////////////////////////////////////////////////\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <time.h>\r\n#include <math.h>\r\n#include <GL/glut.h>\r\n#include <GL/gl.h>\r\n#include <GL/glu.h>\r\n\r\n#include <iostream>\r\n#include <vector>\r\nusing namespace std;\r\n\r\n#include \"viewgui.h\"\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n\r\n//各種OpenGL変数宣言\r\nconst int WIDTH = 640, HEIGHT = WIDTH;//ウィンドウのサイズ\r\nint xBegin, yBegin;\t\t\t//mouseのXY座標\r\nint mButton;\t\t\t\t\t//mouseのClick\r\nfloat distance_gl, twist, elevation, azimuth;//カメラの回転行列\r\nfloat xOrig , yOrig, zOrig;\t\t\t\t\t//カメラの位置\r\n\r\n//Robot制御のパラメータ\r\nstruct ROBOT myrobot;\r\n//struct URG urg_area;\r\nstruct URG urg_data;\r\n//struct OBSTACLE obst;\r\nstruct MOVE_PATH move_path;\r\nint gl_mode=0;//モードを切り替える。\r\n\r\ndouble goal_x=0.0,goal_y=0.0;\r\nvector<double> goal_x_array;\r\nvector<double> goal_y_array;\r\nconst double dis_goal_thresh=0.1;\r\n\r\nextern int map_width;\r\nextern int map_height;\r\nextern double map_resolution;\r\nextern double map_pos_x;\r\nextern double map_pos_y;\r\nextern char map_data[5000*5000];\r\nextern double map_theta;\r\n\r\n\r\nint wait_sleep(int time){\r\n\tusleep(time*1000);\r\n\treturn 0;\r\n}\r\n\r\nvoid robot_view(struct ROBOT &robot){\r\n\tglLineWidth(2.0);\r\n\r\n\tdouble xx, yy, theta;\r\n\txx=robot.x;\r\n\tyy=robot.y;\r\n\ttheta=robot.theta;\r\n\tstatic double radius=0.25;\r\n\tglColor3f(0, 0, 0.0);\r\n\tint grid=24.0;\r\n\r\n\tglBegin(GL_LINES);\r\n\tglVertex3f(xx, yy, 0.010);\r\n\tglVertex3f(cos(theta+M_PI/2.0) * radius+xx, sin(theta+M_PI/2.0) * radius+yy, 0.010);\r\n\tglEnd();\r\n\r\n\tfor(int i = 0; i < grid; i++){\r\n\t\tdouble rad_1= 2.0*M_PI*i/grid+theta;\r\n\t\tdouble rad_2= 2.0*M_PI*(i+1)/grid+theta;\r\n\t\tglBegin(GL_LINES);\r\n\t\tglVertex3f(cos(rad_1) * radius+xx, sin(rad_1) * radius+yy, 0.01);\r\n\t\tglVertex3f(cos(rad_2) * radius+xx, sin(rad_2) * radius+yy, 0.01);\r\n\t\tglEnd();\r\n\t}\r\n\tglLineWidth(1.0);\r\n\r\n}\r\nvoid circle_view(double xx,double yy){\r\n\tglLineWidth(1.0);\r\n\tstatic double radius=0.15;\r\n\tglColor3f(1.0, 0, 0.0);\r\n\tint grid=24.0;\r\n\tfor(int i = 0; i < grid; i++){\r\n\t\tdouble rad_1= 2.0*M_PI*i/grid;\r\n\t\tdouble rad_2= 2.0*M_PI*(i+1)/grid;\r\n\t\tglBegin(GL_LINES);\r\n\t\tglVertex3f(cos(rad_1) * radius+xx, sin(rad_1) * radius+yy, 0.01);\r\n\t\tglVertex3f(cos(rad_2) * radius+xx, sin(rad_2) * radius+yy, 0.01);\r\n\t\tglEnd();\r\n\t}\r\n\tglLineWidth(1.0);\r\n}\r\n\r\n\r\nvoid path_view(double xx,double yy){\r\n\tglLineWidth(1.0);\r\n\tstatic double radius=0.05;\r\n\tglColor3f(1.0, 0, 0.0);\r\n\tint grid=24.0;\r\n\r\n\tfor(int i = 0; i < grid; i++){\r\n\t\tdouble rad_1= 2.0*M_PI*i/grid;\r\n\t\tdouble rad_2= 2.0*M_PI*(i+1)/grid;\r\n\t\tglBegin(GL_TRIANGLES);\r\n\t\tglVertex3f(cos(rad_1) * radius+xx, sin(rad_1) * radius+yy, 0.01);\r\n\t\tglVertex3f(cos(rad_2) * radius+xx, sin(rad_2) * radius+yy, 0.01);\r\n\t\tglVertex3f(xx, yy, 0.01);\r\n\r\n\t\tglEnd();\r\n\t}\r\n\r\n\tglLineWidth(1.0);\r\n}\r\n\r\nvoid URG_view( ROBOT &robot,URG &URG_data){\r\n\t//URGのレーザーの表示\r\n\tglColor3f(0, 0.7, 1.0);\r\n\tglLineWidth(2.0);\r\n\tconst int flg=2;\r\n\tif(flg==0){\t//レーザ探査領域の表示\r\n\t\tconst double length=URG_data.leng_max;\r\n\r\n\t\tfor(int i=0;i<URG_data.data_num;i++){\r\n\t\t\tdouble xx1=(-1)*length*sin(i*URG_data.reso+URG_data.start_rad+robot.theta)+robot.x;\r\n\t\t\tdouble yy1=length*cos(i*URG_data.reso+URG_data.start_rad+robot.theta)+robot.y;\r\n\t\t\tdouble xx2=(-1)*length*sin((i+1)*URG_data.reso+URG_data.start_rad+robot.theta)+robot.x;\r\n\t\t\tdouble yy2=length*cos((i+1)*URG_data.reso+URG_data.start_rad+robot.theta)+robot.y;\r\n\t\t\tglBegin(GL_LINES);\r\n\t\t\tglVertex3f(xx1,yy1,0 );\r\n\t\t\tglVertex3f(xx2,yy2,0 );\r\n\t\t\tglEnd();\r\n\t\t}\r\n\t\tdouble xx1=(-1)*length*sin(URG_data.start_rad+robot.theta)+robot.x;\r\n\t\tdouble yy1=length*cos(URG_data.start_rad+robot.theta)+robot.y;\r\n\t\tdouble xx2=(-1)*length*sin((URG_data.data_num)*URG_data.reso+URG_data.start_rad+robot.theta)+robot.x;\r\n\t\tdouble yy2=length*cos((URG_data.data_num)*URG_data.reso+URG_data.start_rad+robot.theta)+robot.y;\r\n\t\tglBegin(GL_LINES);\r\n\t\tglVertex3f(xx1,yy1,0 );\r\n\t\tglVertex3f(robot.x, robot.y,-0 );\r\n\t\tglEnd();\r\n\t\tglBegin(GL_LINES);\r\n\t\tglVertex3f(xx2,yy2,0 );\r\n\t\tglVertex3f(robot.x, robot.y,-0 );\r\n\t\tglEnd();\r\n\t}\r\n\tif(flg==1){\r\n\t\tfor(int i=0;i<URG_data.data_num;i++){\r\n\t\t\tdouble length=URG_data.leng[i];\r\n\t\t\tif(length==0.0)\tlength=URG_data.leng_max;\r\n\r\n\t\t\tdouble xx=(-1)*length*sin(i*URG_data.reso+URG_data.start_rad+robot.theta)+robot.x;\r\n\t\t\tdouble yy=length*cos(i*URG_data.reso+URG_data.start_rad+robot.theta)+robot.y;\r\n\r\n\t\t\tglBegin(GL_LINES);\r\n\t\t\tglVertex3f(xx,yy,0 );\r\n\t\t\tglVertex3f(robot.x, robot.y,-0 );\r\n\t\t\tglEnd();\r\n\t\t}\r\n\t}\r\n\tglLineWidth(1.0);\r\n\r\n\r\n\t//レーザとOBJECTの交点の座標\r\n\tglPointSize(2.0);\r\n\tglColor3f(0, 0.0, 1);\r\n\r\n\tfor(int i=0;i<URG_data.data_num-1;i++){\r\n\t\tURG_data.x[i]=(-1)*URG_data.leng[i]*sin(i*URG_data.reso+URG_data.start_rad+robot.theta)+robot.x;\r\n\t\tURG_data.y[i]=URG_data.leng[i]*cos(i*URG_data.reso+URG_data.start_rad+robot.theta)+robot.y;\r\n\t\tglBegin(GL_POINTS);\r\n\t\tglVertex3f(URG_data.x[i], URG_data.y[i],0.02 );\r\n\t\tglEnd();\r\n\t}\r\n\tglPointSize(1.0);\r\n\tglLineWidth(2.0);\r\n\treturn;\r\n}\r\n\r\nGraphics::Graphics(){\r\n\txOrig = 0.0, yOrig = 0.0, zOrig=0.0; //始点中心\r\n\tgui_start();\r\n\r\n}\r\n\r\nGraphics::~Graphics(){\r\n\tgui_end();\r\n}\r\n\r\nvoid Graphics::main_draw() {\r\n\t//URGのレーザーの表示\r\n\tglColor3f(0.0, 0.05, 1.0);\r\n\r\n\r\n//\tTo_goal_velocity(goal_x,goal_y,myrobot.x,myrobot.y,myrobot.theta,myrobot.v,myrobot.w,0.01);\r\n\tTo_path_velocity(move_path,myrobot.x,myrobot.y,myrobot.theta,myrobot.v,myrobot.w);\r\n\r\n\r\n\t//Gridの表示\r\n\tglColor3f(0.9,0.9,0.9);\r\n\tglLineWidth(1.0);\r\n\r\n\tdouble grid_size=1.0;\r\n\tint width=50;\r\n\tint data_num=width/grid_size;\r\n\r\n\tfor(int i=0;i<data_num*data_num;i++){\r\n\t\tdouble start_x=data_num/2.0;\r\n\t\tdouble start_y=data_num/2.0;\r\n\t\tint ix=i%data_num;\r\n\t\tint iy=i/data_num;\r\n\t\tdouble xx=ix*grid_size-start_x;\r\n\t\tdouble yy=iy*grid_size-start_y;\r\n\t\tglBegin(GL_LINE_LOOP);\r\n\t\tglVertex3f(xx,yy,-0.1);\r\n\t\tglVertex3f(xx+grid_size,yy,-0.1);\r\n\t\tglVertex3f(xx+grid_size,yy+grid_size,-0.1);\r\n\t\tglVertex3f(xx,yy+grid_size,-0.1);\r\n\t\tglEnd();\r\n\t}\r\n\r\n\tfor(int i=0;i<goal_x_array.size();i++)\r\n\t\tpath_view(goal_x_array[i],goal_y_array[i]);\r\n\r\n\tcircle_view(goal_x,goal_y);\r\n\t//circle_view(myrobot.x,myrobot.y);\r\n\r\n\trobot_view(myrobot);\r\n\r\n\tURG_view(myrobot,urg_data);\t\t\t\t//URGの表示\r\n\t//MAPの表示\r\n\tdouble map_width2=map_resolution*map_width;\r\n\tdouble map_height2=map_resolution*map_height;\r\n\r\n\tfor (unsigned int y = 0; y < map_height; y++){\r\n\t\tfor (unsigned int x = 0; x < map_width; x++){\r\n\t\t\tunsigned int i = x + (map_height - y - 1) * map_width;\r\n\t\t\tif(map_data[i]>50){\r\n\r\n\t\t\t\tdouble disp=map_data[i]/100.0;\r\n\t\t\t\tdouble map_x=x*map_resolution;\r\n\t\t\t\tdouble map_y=y*map_resolution;\r\n\t\t\t\tdouble map_x_r=map_x*sin(map_theta)+map_y*cos(map_theta);\r\n\t\t\t\tdouble map_y_r=map_x*cos(map_theta)-map_y*sin(map_theta);\r\n\r\n\t\t\t\tmap_x_r+=-map_height2-map_pos_y;\r\n\t\t\t\tmap_y_r+=+map_pos_x;\r\n\t\t\t\tglColor3f(0.0, disp,0.0);\r\n\r\n\t\t\t\tglBegin(GL_QUADS);\r\n\t\t\t\tglVertex3f(map_x_r,\t\t\t\t\t\t\t\t\tmap_y_r,\t\t\t\t\t\t\t 0);\r\n\t\t\t\tglVertex3f(map_x_r+map_resolution,\tmap_y_r,\t\t\t\t\t\t\t 0);\r\n\t\t\t\tglVertex3f(map_x_r+map_resolution,\tmap_y_r+map_resolution,0);\r\n\t\t\t\tglVertex3f(map_x_r,\t\t\t\t\t\t\t\t\tmap_y_r+map_resolution,0);\r\n\t\t\t\tglEnd();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tglPointSize(5);\r\n\r\n\t/*\r\n\tglColor3f(0.0, 0.0, 0.1);\r\n\tglBegin(GL_LINES);\r\n\tglVertex3f(-5,0,0 );\r\n\tglVertex3f(+5,0,0 );\r\n\tglEnd();\r\n\tglBegin(GL_LINES);\r\n\tglVertex3f(0,-5,0 );\r\n\tglVertex3f(0,+5,0 );\r\n\tglEnd();\r\n\t*/\r\n\r\n\r\n\treturn ;\r\n}\r\n\r\n\r\n\r\nvoid Graphics::display(){\r\n\r\n\tglClearColor(1 , 1 , 1 , 1.0);\r\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\tglEnable(GL_DEPTH_TEST);\r\n\tglPushMatrix ();\r\n\tpolarview();\r\n\r\n\t//メイン描画の関数\r\n\tmain_draw();\r\n\r\n\tglPopMatrix();\r\n\tglutSwapBuffers();\r\n\tglutPostRedisplay();\r\n\r\n\r\n\tusleep(10*1000);\r\n\r\n\r\n}\r\n\r\nvoid Graphics::idle(void)\r\n{\r\n\tglutPostRedisplay();\r\n\r\n\tusleep(10*1000);\r\n\r\n}\r\n\r\nvoid Graphics::myInit(char *progname)\r\n{\r\n\tfloat aspect = (float) WIDTH / (float) HEIGHT;\r\n\r\n\tglutInitWindowPosition(0, 0);\r\n\tglutInitWindowSize( WIDTH, HEIGHT);\r\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA| GLUT_DEPTH);\r\n\tglutCreateWindow(progname);\r\n\tglClearColor (0, 0, 0, 1.0);\r\n\r\n\r\n\tglutKeyboardFunc( myKbd );\r\n\tglutKeyboardUpFunc( myKbdup );\r\n\tglutSpecialFunc( mySkey );\r\n\r\n\tglutMouseFunc(myMouse);\r\n\tglutMotionFunc(myMotion);\r\n\tresetview();\r\n\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglLoadIdentity();\r\n\tgluPerspective(45.0, aspect, 0.010, 100.0);//画角等視野の設定\r\n\tglMatrixMode(GL_MODELVIEW);\r\n}\r\n\r\nvoid Graphics::reshape(int ,int)\r\n{\r\n\t//glutReshapeWindow( WIDTH, HEIGHT );\r\n}\r\n\r\nint Graphics::GUImain(){\r\n\tint argc= 3;\r\n\tchar *argv[] ={\"program\", \"-display\", \":0.0\"};\r\n\tglutInit ( &argc, argv );\r\n\r\n\tchar *win_name=\"URG_viewer\";\r\n\tmyInit(win_name);\r\n\tglutDisplayFunc(display);\r\n\tglutReshapeFunc(reshape);\r\n\r\n\tglutIdleFunc(idle);\r\n\tglutMainLoop();\r\n\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid Graphics::gui_start(){\r\n\tth1 = SDL_CreateThread((int (*)(void *))GUImain,this);\r\n}\r\n\r\n\r\nvoid Graphics::gui_end(){\r\n\tSDL_KillThread(th1);\r\n}\r\n\r\ndouble Graphics::timer_ms() {\r\n\r\n\tdouble timer_ms = cv::getTickCount();\r\n\treturn timer_ms;\r\n\r\n}\r\n\r\n\r\n\r\nvoid Graphics::myMouse( int button, int state, int x, int y ){\r\n\r\n\tdouble obj_x=0,obj_y=0,obj_z=0;\r\n\r\n\tif (state == GLUT_DOWN) {\r\n\t\tswitch(button) {\r\n\t\t\tcase GLUT_LEFT_BUTTON:\r\n\t\t\tmButton = button;\r\n\t\t\t//\t\tclick_pickup(x,y,obj_x,obj_y,obj_z);\r\n\t\t\t//\t\tgoal_y=obj_y;\r\n\t\t\t//\t\tgoal_x=obj_x;\r\n\t\t\tbreak;\r\n\t\t\tcase GLUT_MIDDLE_BUTTON:\r\n\r\n\t\t\tbreak;\r\n\t\t\tcase GLUT_RIGHT_BUTTON:\r\n\t\t\tmButton = button;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\txBegin = x;\r\n\t\tyBegin = y;\r\n\t}\r\n\tif (state == GLUT_UP) {\r\n\t\tswitch(button) {\r\n\t\t\tcase GLUT_RIGHT_BUTTON:\r\n\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\treturn ;\r\n}\r\n\r\n\r\nvoid Graphics::myMotion( int x, int y ){\r\n\r\n\tint xDisp, yDisp;\r\n\tdouble obj_x=0,obj_y=0,obj_z=0;\r\n\r\n\txDisp = x - xBegin;\r\n\tyDisp = y - yBegin;\r\n\r\n\tswitch (mButton) {\r\n\t\tcase GLUT_LEFT_BUTTON:\r\n\t\tclick_pickup(x,y,obj_x,obj_y,obj_z);\r\n\t\t//\t\tgoal_y=obj_y;\r\n\t\t//\t\tgoal_x=obj_x;\r\n\t\tbreak;\r\n\r\n\t\tcase GLUT_MIDDLE_BUTTON:\r\n\t\txOrig += (float) xDisp/50.0;\r\n\t\tzOrig -= (float) yDisp/50.0;\r\n\r\n\t\tbreak;\r\n\t\t//azimuth -= (float) xDisp/2.0;\r\n\t\t//elevation -= (float) yDisp/2.0;\r\n\r\n\t\tcase GLUT_RIGHT_BUTTON:\r\n\t\tdistance_gl -= (float) xDisp/10.0;\r\n\t\tif(distance_gl<0.000001)distance_gl=0.000001;\r\n\r\n\t\tbreak;\r\n\t}\r\n\txBegin = x;\r\n\tyBegin = y;\r\n\r\n\r\n\tglutPostRedisplay();\r\n}\r\n\r\n\r\nvoid Graphics::myKbdup( unsigned char key, int x, int y )\r\n{\r\n\r\n\tswitch( key ) {\r\n\r\n\t\tcase 'w':\t//ROBOTの移動指令\r\n\t\t//\tif(gl_mode==0)\t\tmyrobot.v=0.0;\r\n\t\tbreak;\r\n\t\tcase 's':\t//ROBOTの移動指令\r\n\t\t//\tif(gl_mode==0)\t\tmyrobot.v=-0.0;\r\n\t\tbreak;\r\n\t\tcase 'a':\t//ROBOTの移動指令\r\n\t\t//\tif(gl_mode==0)\t\tmyrobot.w=-0.0;\r\n\t\tbreak;\r\n\t\tcase 'd':\t//ROBOTの移動指令\r\n\t\t//\tif(gl_mode==0)\t\tmyrobot.w=+0.0;\r\n\t\tbreak;\r\n\r\n\r\n\r\n\t}\r\n\r\n}\r\nvoid Graphics::myKbd( unsigned char key, int x, int y )\r\n{\r\n\tswitch( key ) {\r\n\t\tcase 0x1B:\t//終了\r\n\t\t//\texit(0);\r\n\t\tbreak;\r\n\r\n\t}\r\n}\r\n\r\n\r\n\r\nvoid Graphics::mySkey( int key, int x, int y )\r\n{\r\n\tswitch( key ) {\r\n\t\tcase GLUT_KEY_LEFT:\r\n\t\txOrig -= 0.2;\r\n\t\tbreak;\r\n\t\tcase GLUT_KEY_RIGHT:\r\n\t\txOrig += 0.2;\r\n\t\tbreak;\r\n\t\tcase GLUT_KEY_UP:\r\n\t\tzOrig += 0.2;\r\n\t\tbreak;\r\n\t\tcase GLUT_KEY_DOWN:\r\n\t\tzOrig -= 0.2;\r\n\t\tbreak;\r\n\t\tcase GLUT_KEY_PAGE_UP:\r\n\t\tyOrig += 0.2;\r\n\t\tbreak;\r\n\t\tcase GLUT_KEY_PAGE_DOWN:\r\n\t\tyOrig -= 0.2;\r\n\t\tbreak;\r\n\r\n\t}\r\n\tglutPostRedisplay();\r\n}\r\n\r\n\r\nvoid Graphics::resetview( void )\r\n{\r\n\tdistance_gl = 20.0;\r\n\ttwist = 0.0;\r\n\televation = 0.0;\r\n\tazimuth = 0.0;\r\n}\r\n\r\n\r\n\r\nvoid Graphics::polarview( void )\r\n{\r\n\t//マウスで移動\r\n\tglTranslatef( 0.0, 0.0, -distance_gl);\r\n\tglRotatef( -twist, 0.0, 0.0, 1.0);\r\n\tglRotatef( -elevation, 1.0, 0.0, 0.0);\r\n\tglRotatef( -azimuth, 0.0, 1.0, 0.0);\r\n\t//キーボードで移動\r\n\tglTranslatef(xOrig,zOrig ,yOrig);\r\n}\r\n\r\nfloat Graphics::click_Depth(int x, int y){//マウスのX/Y座標からDepthを算出\r\n\tfloat z;\r\n\tGLint viewport[4]; //ビューポート\r\n\t//デバイス座標系とウィンドウ座標系の変換\r\n\tglGetIntegerv(GL_VIEWPORT,viewport); //現在のビューポートを代入\r\n\tglReadPixels(x,viewport[3]-y,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&z);\r\n\t// デプスバッファの値を返す.\r\n\treturn z;\r\n}\r\n\r\nvoid Graphics::click_pickup(int x,int y,double &ax,double &ay,double &az){//マウスのX/Y座標からX/Y/Z座標を算出\r\n\tGLdouble modelview[16];\r\n\tGLdouble projection[16];\r\n\tGLint viewport[4];\r\n\tglGetDoublev(GL_MODELVIEW_MATRIX,modelview);\r\n\tglGetDoublev(GL_PROJECTION_MATRIX,projection);\r\n\tglGetIntegerv(GL_VIEWPORT,viewport);\r\n\tGLdouble winX, winY, winZ;\r\n\tGLdouble objX=0.0,objY=0.0,objZ=-distance_gl+yOrig;\r\n\r\n\t//原点のGLUT座標系を算出\r\n\tgluProject(objX,objY,objZ,modelview,projection,viewport,&winX,&winY,&winZ);\r\n\tGLdouble objX1,objY1,objZ1;\r\n\t//gluUnProject((double)x,(double)y,0.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n\t//cout<<\"near_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\r\n\t//gluUnProject((double)x,(double)y,1.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n\t//cout<<\"far_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\r\n\r\n\tgluUnProject((double)x,(double)y,winZ,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n\tax=objX1-xOrig;\r\n\tay=-(objY1+zOrig);\r\n\taz=objZ1-yOrig;\r\n\r\n\t//cout<<\"mouse_click:\"<<\"\\t X:\"<<x<<\"\\t Y:\"<<y<<\"\\t x:\"<<ax<<\"\\t y:\"<<ay<<\"\\t z:\"<<az<<\"\"<<endl;\r\n\tint n=goal_x_array.size();\r\n\tif(n==0){\r\n\t\tgoal_x_array.push_back(ax);\r\n\t\tgoal_y_array.push_back(ay);\r\n\t}\r\n\telse{\r\n\t\tdouble dis_x_p=(ax-goal_x_array[n-1])*(ax-goal_x_array[n-1]);\r\n\t\tdouble dis_y_p=(ay-goal_y_array[n-1])*(ay-goal_y_array[n-1]);\r\n\r\n\t\tif(dis_x_p+dis_y_p>dis_goal_thresh*dis_goal_thresh){\r\n\t\t\tgoal_x_array.push_back(ax);\r\n\t\t\tgoal_y_array.push_back(ay);\r\n\r\n\t\t\tmove_path.x.push_back(ax);\r\n\t\t\tmove_path.y.push_back(ay);\r\n\t\t}\r\n\r\n\t//\tcout<<\"dis\"<<dis_x_p<<\"_\"<<dis_y_p<<endl;\r\n\t//\tcout<<\"aa\"<<ax<<\"_\"<<ay<<endl;\r\n\t//\tcout<<\"goal\"<<goal_x_array[n]<<\"_\"<<goal_y_array[n]<<endl;\r\n\t//\tcout<<\"nn\"<<n<<\"_\"<<n<<endl;\r\n\r\n\t}\r\n\treturn;\r\n}\r\n" }, { "alpha_fraction": 0.7144699692726135, "alphanum_fraction": 0.7632189989089966, "avg_line_length": 21.74846649169922, "blob_id": "11541bf132cf5bd68c6ca50919b011064d42c4f6", "content_id": "ad6df40d0f1adbcfcb1baeff42b1aa34ba07831a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7000, "license_type": "no_license", "max_line_length": 67, "num_lines": 163, "path": "/ai_memo.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "docu_object_tracking_160812\r\n\t済み:・ゲームPADから入力して停止させる\r\n\t済み:makeファイル作成\r\n\t済み:・LRFないと外側に円が見える。\r\n\t済み:joytstck botton2から初期位置の強制入力\r\n\t済み:速度を以前の式へ修正、バックありに。\r\n\t済み:□を見失ったときに色変える\r\n\t済み:カメラと連動\r\n\t済み:敷居値設定があまい。:実機確認\r\n\t済み:検知部と処理部をマルチスレッド化:効果なし\r\n\t済み:見失ったときに、閾値以上の時間でトラッキング停止する\r\n\t済み:・TopuRGが20DEG傾いている状態から平面変換\r\n\t11.26:見失ったときに、実時間でトラッキング停止する\r\n\t11.26:トラッキングを別スレッドか化\r\n\t11.26:RVIZで表示(maker)\r\n\t11.26:シャットダウン時に0出力\r\n\t\t\r\n\t・回転方向でODOMを考慮する\r\n\t→TFからGLobal座標でトラッキング\r\n\t・averagingして検知精度向上\r\n\t\r\n\r\nSIMLATOR\r\n\t済み:・pan_tiltの回転するしないを追加\r\n\t済み:・MAPの編集\r\n\t済み:・ODOMとDummyODomの発行\r\n\t済み:地面の判定がおかしい\r\n\t済み:gmapping/hector slamへ対応したTFの発行\r\n\t済み:・移動物体の入力\r\n\t9.18済:Simulatorが長時間で停止する→グラボのDriverをいれる。\r\n\t9.20済:Sim:画像データのpublish\r\n\t9.20済:Sim:点群データのpublish\r\n\t11.26:点群の誤差が大きい→LRFと3DSCANのタイムスタンプに不整合あり。\r\n\t11.26:点群の誤差が大きい→3DSCAN計算を別スレッッドで高速化\r\n\t11.26:PCLにRGB値を追加\r\n\t1.28移動障害物を人型\r\n\t2.25:胴体が抜けていたのを修正\r\ndocu_joy_to_cmd2\r\n\t済み:docu_object_trackingが動かないと動作しない\r\n\t済み:CPUが100%・Waitがない\r\n\t\r\nKinect\r\n\t済み:IMUで回転\r\n\r\nその他\r\n\t済み:binファイルの統一フォルダ格納\r\n\t済み:PCLのMakeが通らない。->Cmake使う\r\n\t済み:一括Make\r\n \t済み:点群(XYZ)を貯めて表示。\r\n\t済み:Octomapへの入力\r\n\t済み:Scanから天井と地下を削除してPCL発行\r\n\t済み:PCL1とPCL2の変換\r\n\t済み::KinectのRGBXYZをためて表示→RtabMap\r\n\t保留:hector slamのTF貰いながら、KinectのRGBXYZ表示。SToCK\r\n\t済み:・urg・joypad・create2を起動するスクリプト。\r\n\t済み:・Octomapの保存\r\n\t済み:・点群をためて、Gmappingへ代入\r\n\t済み:NavigationStockのゴールの入力\r\n\t済み:MultiROSURIでの他PCからの接続\r\n\t済み:URG NODEでの3個同時起動\r\n\t済み:LRFのudev固定\r\n\t済み:・上のLRFのX,y,Θ修正\r\n\t済み:プラウザでPointCloudの表示\r\n\tSkip:Ocotomapを綺麗に表示:=使いどころが。。。\r\n\t済み:OpenFrameWorksとROSを接続\r\n\t済み:点群をVOXELで削減\r\n\t9.18済:・DocuLocalPathPlanとNavigationStockを接続\r\n\t→Navi_stockのGlobalPathの座標を入力\r\n\t9.22:プラウザからゴールを指定する\r\n\t9.22:ゴール時に角度をあわせる。\r\n\t9.22:プラウザから画像を表示\r\n\t9.22:プラウザから初期値を指定する\r\n\t問題ないかも:\t・デットロックしたときに、global_pathを吐き出さない\r\n\t9.22:Slam_Kartoの動作確認\r\n\t9.30・LocalPathPlanにGoalを表示\r\n\t9.24・Simに後ろのURFの追加\r\n\t10.24:Launchで一括起動\r\n\t10.24:ウェブプラウザでPCL\r\n\t11.24:launch file化・実機確認\r\n\t11.26:障害物を回避しない->修正\r\n\t11.27:障害物とぶつかる->仮のゴールを近くにするように修正\r\n\t11.27:雲台の回転を停止する。\r\n\t11.27:自動追従機能との連携 button3で追従\r\n\t12.3:障害物の自律移動\r\n\t12.4:雲台ハードの回転を停止する仕様。\r\n\t12.18:Odomをキャリブレーションするツール作成\r\n\t12.18:cartgrapherのMAPを正しく出力するようにmap_sarverを改造\r\n\t2.25:nav2jsがローカルでも動くように改造/回転の指定可能に。\r\n\t2.26:xmlファイルに不具合ある。\r\n\t3.3:cartgrapherがSampleRate早すぎると動かないこと確認して修正。\r\n\t6.18:docu_pcl_assembledのframeを戻せるようにする。\r\n\t6.26 3D sim以外catkin 対応\r\n\t済み:blam-slam(・3D-Slam 、ethzasl_icp_mapper,ndtmaching)\r\n\t6.30 3D simもcatkin対応\r\n\t      2dsimに移動物体追加・近づいたら移動できないように修正\r\n\t7.2 データをlaunchで流して自動実行化完成。\r\n\t8.28 ロボットをRVIZで表示\r\n\t8.28 Odom精度をSLAMで評価\r\n\t8.28 object trackingが変なのは修正済、加速度設定が狂っていた。\r\n\t8.28 ボタンで切り替える 1:マニュアル、2:navigation、3:tracking、4:原点へのNavi\r\n\t9.2 WEBブラウザから操作できるように変更\r\n\t9.2 \r\n\r\n\tsimでロボットが壁を貫通しないように。\r\n\t絵をかいて、ロボットを追従させる。\r\n\t\t\r\n\t・デットロックしたときの回避\r\n\t→その場でバックする・旋回する\r\n\t・後ろのLRFで障害物回避\r\n\t・軌跡をwebで表示\r\n\t・humanoid_localization\r\n\t・ジャイロオドメトリ:並進と回転を同一化。\r\n\t・PLY読み込み・天井切る\r\n\t・壁の高さの入力\r\n\r\n\r\n9/5課題\r\ncartographerのLoaclizatinが使い物にならない。AMCLに戻す\r\n→戻したものを入れた。\r\nlibjsでプラウザで、ObstTrackの初期化が入らないことがある。\r\n→確認したがそんなことはない。ネットの問題か?\r\n無線ルータでIPが初期化される\r\n→URG側をのIPwp変更する。\r\nGoalの指定が早く入らないことがある\r\n→確認したがそんなことはない。ネットの問題か?\r\n→ちゃんとゴールを指定するコマンドを投げる?\r\n→LocalPathを削除すればよい、Mapのクリアが実行されていた。\r\n→リカバリーが入っていたoscillation_timeout: 0.0・controller_patience: 0.0\r\n回転が早すぎて追従しない\r\n→Gainを下げる\r\n→リミット値を設けた。\r\ndocu_navi_localpathplanの180degの規制になってない。\r\n→バク、修正した\r\n\r\n\r\n9/6\r\n\r\nプラウザから、ObjectTrackが入らない。\r\nプラウザから、ゴール指定がはいらない\r\n\r\n\r\n\r\n.bashrc----------------------------------\t\r\nalias cw='cd ~/catkin_ws/'\r\nalias cs='cd ~/catkin_ws/src'\r\nalias cm='cd ~/catkin_ws/ && catkin_make'\r\nalias mmm='make clean&&make'\r\n\r\nexport CUDA_HOME=/usr/local/cuda-8.0\r\n\r\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${CUDA_HOME}/lib64\r\nexport PATH=$PATH:${CUDA_HOME}/bin\r\n\r\nsource /opt/ros/indigo/setup.bash\r\n\r\nexport ROS_PACKAGE_PATH=~/ros_bin/myproject/share:$ROS_PACKAGE_PATH\r\nexport CMAKE_PREFIX_PATH=~/ros_bin/myproject:$CMAKE_PREFIX_PATH\r\n\r\nsource /home/iqit/catkin_ws/devel/setup.bash\r\nsource /home/iqit/catkin_cartographer/install_isolated/setup.bash\r\n\r\ncartgrapherのインストール手順\r\n\tcatkin_make_isolated --install --use-ninja\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.49155908823013306, "alphanum_fraction": 0.5237622261047363, "avg_line_length": 24.90458106994629, "blob_id": "9589bb81145aba7da53711b6d6f913c4bb9d348d", "content_id": "b965043460b0705662b8cb6ad12848c74509a8ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7061, "license_type": "no_license", "max_line_length": 123, "num_lines": 262, "path": "/check_tf_result/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\n#include <fstream>\r\n#include <cstdio>\r\n#include <stdio.h>\r\nusing namespace std;\r\n\r\n#include <stdio.h>\r\n#include <signal.h>\r\n#include <stdlib.h>\r\n#include <ros/ros.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <nav_msgs/Path.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n#include <tf/transform_listener.h>\r\ntf::TransformListener *tflistener;\r\n\r\nvoid GetRPY(const geometry_msgs::Quaternion &quat, double &theta){\r\n tf::Quaternion q(quat.x, quat.y, quat.z, quat.w);\r\n tf::Matrix3x3 m(q);\r\n double roll, pitch, yaw;\r\n m.getRPY(roll, pitch, yaw);\r\n //std::cout << \"Roll: \" << roll << \", Pitch: \" << pitch << \", Yaw: \" << yaw << std::endl;\r\n //theta=yaw+3.1415;\r\n theta = -yaw;\r\n}\r\n\r\n\r\ndouble sub_rad(double rad1,double rad2){\r\n double sub_rad;\r\n sub_rad=rad1-rad2;\r\n if(fabs(rad1-rad2)>1.0*M_PI){\r\n if(fabs(rad1-rad2+4.0*M_PI)<fabs(rad1-rad2)){\r\n sub_rad=rad1-rad2+2.0*M_PI;\r\n }\r\n else if(fabs(rad1-rad2-4.0*M_PI)<fabs(rad1-rad2)){\r\n sub_rad=rad1-rad2-2.0*M_PI;\r\n }\r\n else if(fabs(rad1-rad2+2.0*M_PI)<fabs(rad1-rad2)){\r\n sub_rad=rad1-rad2+2.0*M_PI;\r\n }\r\n else if(fabs(rad1-rad2-2.0*M_PI)<fabs(rad1-rad2)){\r\n sub_rad=rad1-rad2-2.0*M_PI;\r\n }\r\n }\r\n return sub_rad;\r\n\r\n}\r\n\r\nvoid mySigintHandler(int sig){\r\n printf(\"shutdown catch signal %d \\n\", sig);\r\n ros::shutdown();\r\n}\r\n\r\n\r\nint main(int argc, char *argv[]){\r\n\r\n ros::init(argc, argv, \"tf_check\");\r\n\r\n ros::NodeHandle n;\r\n tf::TransformListener listener(ros::Duration(10));\r\n\r\n\r\n ros::NodeHandle private_nh(\"~\");\r\n string tf_name1;\r\n string tf_name2;\r\n string tf_name3;\r\n string tf_name4;\r\n private_nh.param(\"tf_name1\",tf_name1,std::string(\"/base_link\"));\r\n private_nh.param(\"tf_name2\",tf_name2,std::string(\"/map\"));\r\n// private_nh.param(\"tf_name3\",tf_name3,std::string(\"/odom_true\"));\r\n private_nh.param(\"tf_name3\",tf_name3,std::string(\"/odom\"));\r\n private_nh.param(\"tf_name4\",tf_name4,std::string(\"/map\"));\r\n\r\n int end_time=0;\r\n private_nh.param(\"end_time\",end_time,200);\r\n\r\n\r\n string outfname;\r\n private_nh.param(\"fname\",outfname,std::string(\"/home/iqit/catkin_me/src/check_tf_result/data_\"));\r\n\r\n string outfname_total;\r\n private_nh.param(\"fname_total\",outfname_total,std::string(\"/home/iqit/catkin_me/src/check_tf_result/data_\"));\r\n\r\n\r\n ros::Rate r(10.0);\r\n double dis_o=0.0;\r\n double dis_m=0.0;\r\n double dis_e=0.0;\r\n\r\n double rot_o=0.0;\r\n double rot_m=0.0;\r\n double rot_e=0.0;\r\n static double x_po=0.0, y_po=0.0, yaw_po=0.0;\r\n static double x_pm=0.0, y_pm=0.0, yaw_pm=0.0;\r\n static double x_pe=0.0, y_pe=0.0, yaw_pe=0.0;\r\n\r\n double total_dis_e=0.0;\r\n double total_rot_e=0.0;\r\n\r\n //現在時刻取得\r\n char fname[200];\r\n time_t now = time(NULL);\r\n struct tm *pnow = localtime(&now);\r\n sprintf(fname, \"%s_%04d%02d%02d%02d%02d%02d.csv\",outfname.c_str(), pnow->tm_year + 1900, pnow->tm_mon + 1, pnow->tm_mday,\r\n pnow->tm_hour, pnow->tm_min, pnow->tm_sec);\r\n std::ofstream fout(fname) ;\r\n\r\n\r\n fout<< \"error\" << \",\";\r\n fout<< \"dis_error\" << \",\";\r\n fout<< \"x_error\" << \",\";\r\n fout<< \"y_error\" << \",\";\r\n fout<< \"yaw_error\" << \",\";\r\n\r\n fout<< \"slam\" << \",\";\r\n fout<< \"x_slam\" << \",\";\r\n fout<< \"y_slam\" << \",\";\r\n fout<< \"yaw_slam\"<< \",\";\r\n\r\n\r\n fout<< \"odom\" << \",\";\r\n fout<< \"x_odom\" << \",\";\r\n fout<< \"y_odom\" << \",\";\r\n fout<< \"yaw_odom\" << \",\";\r\n fout<< endl;\r\n signal(SIGINT, mySigintHandler);\r\n int cnt=0;\r\n while (n.ok()) {\r\n cnt++;\r\n if(cnt>end_time) break;\r\n\r\n double x_o=0.0, y_o=0.0, yaw_o=0.0;\r\n double x_m=0.0, y_m=0.0, yaw_m=0.0;\r\n double x_e=0.0, y_e=0.0, yaw_e=0.0;\r\n\r\n tf::StampedTransform trans_slam;\r\n tf::StampedTransform trans_true_pos;\r\n tf::StampedTransform trans_error;\r\n try {\r\n listener.lookupTransform(tf_name2, tf_name1,ros::Time(0), trans_slam);\r\n x_m = trans_slam.getOrigin().x();\r\n y_m = trans_slam.getOrigin().y();\r\n yaw_m = tf::getYaw(trans_slam.getRotation());\r\n if(x_pm!=0) dis_m+=sqrt((x_pm-x_m)*(x_pm-x_m)+(y_pm-y_m)*(y_pm-y_m));\r\n if(yaw_pm!=0) rot_m+=fabs(sub_rad(yaw_m,yaw_pm));\r\n\r\n listener.lookupTransform(tf_name4, tf_name3,ros::Time(0), trans_true_pos);\r\n x_o = trans_true_pos.getOrigin().x();\r\n y_o = trans_true_pos.getOrigin().y();\r\n yaw_o = tf::getYaw(trans_true_pos.getRotation());\r\n if(x_po!=0) dis_o+=sqrt((x_po-x_o)*(x_po-x_o)+(y_po-y_o)*(y_po-y_o));\r\n if(yaw_po!=0) rot_o+=fabs(sub_rad(yaw_o,yaw_po));\r\n\r\n // listener.lookupTransform(tf_name3, tf_name1,ros::Time(0), trans_error);\r\n // x_e = trans_error.getOrigin().x();\r\n // y_e = trans_error.getOrigin().y();\r\n // yaw_e = tf::getYaw(trans_error.getRotation());\r\n // if(x_pe!=0) dis_e+=sqrt((x_pe-x_e)*(x_pe-x_e)+(y_pe-y_e)*(y_pe-y_e));\r\n // if(yaw_pe!=0) rot_e+=fabs(sub_rad(yaw_o,yaw_po));\r\n x_e=(x_m-x_o);\r\n y_e=(y_m-y_o);\r\n yaw_e = yaw_m-yaw_o;\r\n dis_e=sqrt(x_e*x_e+y_e*y_e);\r\n\r\n total_dis_e+=dis_e;\r\n total_rot_e+=yaw_e;\r\n\r\n x_pm=x_m;\r\n x_po=x_o;\r\n x_pe=x_e;\r\n\r\n y_pm=y_m;\r\n y_po=y_o;\r\n y_pe=y_e;\r\n\r\n yaw_pm=yaw_m;\r\n yaw_po=yaw_o;\r\n yaw_pe=yaw_e;\r\n\r\n }\r\n\r\n catch (tf::TransformException &ex) {\r\n ROS_ERROR(\"%s\", ex.what());\r\n ros::Duration(1.0).sleep();\r\n continue;\r\n }\r\n cout<< \"error\" << \",\";\r\n cout<< dis_e << \",\";\r\n cout<< x_e << \",\";\r\n cout<< y_e << \",\";\r\n cout<< yaw_e/M_PI*180.0 <<endl;\r\n\r\n cout<< \"mcl\" << \",\";\r\n cout<< x_m << \",\";\r\n cout<< y_m << \",\";\r\n cout<< yaw_m/M_PI*180.0<< endl;\r\n\r\n cout<< \"odom\" << \",\";\r\n cout<< x_o << \",\";\r\n cout<< y_o << \",\";\r\n cout<< yaw_o/M_PI*180.0 << endl;\r\n\r\n cout<< endl;\r\n cout<< endl;\r\n\r\n fout<< \"error\" << \",\";\r\n fout<< dis_e << \",\";\r\n fout<< x_e << \",\";\r\n fout<< y_e << \",\";\r\n fout<< yaw_e/M_PI*180.0 << \",\";\r\n\r\n fout<< \"mcl\" << \",\";\r\n fout<< x_m << \",\";\r\n fout<< y_m << \",\";\r\n fout<< yaw_m/M_PI*180.0<< \",\";\r\n\r\n fout<< \"odom\" << \",\";\r\n fout<< x_o << \",\";\r\n fout<< y_o << \",\";\r\n fout<< yaw_o/M_PI*180.0 << \",\";\r\n fout<< endl;\r\n ros::spinOnce();\r\n r.sleep();\r\n }\r\n int ret;\r\n\r\n\r\n char fname_total[200];\r\n sprintf(fname_total, \"%s_total.csv\",outfname_total.c_str());\r\n std::ofstream fout_total(fname_total,ios_base::app) ;\r\n \r\n fout_total<< fname<< \",\";\r\n fout_total<< \"total_dis_e\" << \",\"<< total_dis_e << \",\";\r\n fout_total<< \"total_rot_e\" << \",\"<< total_rot_e /M_PI*180.0<< endl;\r\n\r\n\r\n ret = system(\"rosrun n_map_saver n_map_saver_node -f map_\");\r\n\r\n usleep(1*1000*1000);\r\n ret = system(\"rosnode kill /cartographer \");\r\n usleep(1*1000*1000);\r\n\r\n ret = system(\"rosnode kill -a\");\r\n\r\n // usleep(1*1000*1000);\r\n\r\n\r\n //exit();\r\n\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5037636160850525, "alphanum_fraction": 0.5861874222755432, "avg_line_length": 16.30293083190918, "blob_id": "26a62de115b763a8c42012015c443efb409a9fe8", "content_id": "0d1e1ba7226ea8c06afb1b966a6b2e9c8573d3ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5864, "license_type": "no_license", "max_line_length": 93, "num_lines": 307, "path": "/n_3d_robot_sim/src/collision_detec_3d.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "\n#include \"collision_detec_3d.h\"\n\n\nvoid Rotate3(double &x1, double &y1, double &z1, double alphaX,double alphaY,double alphaZ){\n\tdouble x2, y2, z2;\n\n\t//Z Axis Rotation\n\tdouble x3 = x1 * cos(alphaZ) - y1 * sin(alphaZ);\n\tdouble y3 = x1 * sin(alphaZ) + y1 * cos(alphaZ);\n\tdouble z3 = z1;\n\n\t//Y Axis Rotation\n\tdouble z4 = z3 * cos(alphaY) - x3 * sin(alphaY);\n\tdouble x4 = z3 * sin(alphaY) + x3 * cos(alphaY);\n\tdouble y4 = y3;\n\n\t//X Axis Rotation\n\ty2 = y4 * cos(alphaX) - z4 * sin(alphaX);\n\tz2 = y4 * sin(alphaX) + z4 * cos(alphaX);\n\tx2 = x4;\n\n\tx1=x2;\n\ty1=y2;\n\tz1=z2;\n\n}\n\n\n//法線ベクトルの算出\nvoid normal_calc(xyz tri[], xyz &normal){\n\tdouble p1[3],p2[3],p3[3],v_nl[3];\n\n\tp1[0]=tri[0].x;\n\tp1[1]=tri[0].y;\n\tp1[2]=tri[0].z;\n\tp2[0]=tri[1].x;\n\tp2[1]=tri[1].y;\n\tp2[2]=tri[1].z;\n\tp3[0]=tri[2].x;\n\tp3[1]=tri[2].y;\n\tp3[2]=tri[2].z;\n\n\tdouble v1[3],v2[3];\n\tdouble length_nl;\n\t//ベクトル計算\n\tv1[0]=p2[0] - p1[0];\n\tv1[1]=p2[1] - p1[1];\n\tv1[2]=p2[2] - p1[2];\n\tv2[0]=p3[0] - p1[0];\n\tv2[1]=p3[1] - p1[1];\n\tv2[2]=p3[2] - p1[2];\n\t//外積\n\tv_nl[0] = v1[1] * v2[2] - v1[2] * v2[1];\n\tv_nl[1] = v1[2] * v2[0] - v1[0] * v2[2];\n\tv_nl[2] = v1[0] * v2[1] - v1[1] * v2[0];\n\t//正規化\n\tlength_nl = sqrt(v_nl[0]*v_nl[0]+v_nl[1]*v_nl[1]+v_nl[2]*v_nl[2]);\n\tif(length_nl != 0){\n\t\tv_nl[0] = v_nl[0]/length_nl;\n\t\tv_nl[1] = v_nl[1]/length_nl;\n\t\tv_nl[2] = v_nl[2]/length_nl;\n\t}\n\n\tnormal.x=v_nl[0];\n\tnormal.y=v_nl[1];\n\tnormal.z=v_nl[2];\n\treturn;\n}\n\n\n\n//外積の算出\nxyz crossproduct_calc(xyz xyz1,xyz xyz2){\n\tdouble v1[3],v2[3],v_nl[3];\n\txyz out;\n\n\t//ベクトル計算\n\tv1[0]=xyz1.x;\n\tv1[1]=xyz1.y;\n\tv1[2]=xyz1.z;\n\tv2[0]=xyz2.x;\n\tv2[1]=xyz2.y;\n\tv2[2]=xyz2.z;\n\n\t//外積\n\tv_nl[0] = v1[1] * v2[2] - v1[2] * v2[1];\n\tv_nl[1] = v1[2] * v2[0] - v1[0] * v2[2];\n\tv_nl[2] = v1[0] * v2[1] - v1[1] * v2[0];\n\n\tout.x=v_nl[0];\n\tout.y=v_nl[1];\n\tout.z=v_nl[2];\n\treturn out;\n}\n\n\n//内積\ndouble innerproduct_calc(xyz xyz1, xyz xyz2) {\n\tint i;\n\tdouble s = 0.0;\n\n\tdouble vec1[3];\n\tdouble vec2[3];\n\n\tvec1[0]=xyz1.x;\n\tvec1[1]=xyz1.y;\n\tvec1[2]=xyz1.z;\n\n\tvec2[0]=xyz2.x;\n\tvec2[1]=xyz2.y;\n\tvec2[2]=xyz2.z;\t\n\n\tfor ( i = 0; i < 3; i++ ) {\n\t\ts += vec1[i] * vec2[i];\n\t}\n\n\treturn s;\n}\n\n//XYZ座標の引き算\n\nxyz sub_calc(xyz xyz1, xyz xyz2) {\n\txyz out;\n\tout.x=xyz1.x-xyz2.x;\n\tout.y=xyz1.y-xyz2.y;\n\tout.z=xyz1.z-xyz2.z;\n\treturn out;\n}\n\n//XYZ座標のスカラー量を求める\ndouble norm_calc(xyz xyz1){\n\tdouble vec[3];\n\tint i;\n\tdouble s = 0.0;\n\n\tvec[0]=xyz1.x;\n\tvec[1]=xyz1.y;\n\tvec[2]=xyz1.z;\n\n\tfor ( i = 0; i < 3; i++ ) {\n\t\ts += vec[i] * vec[i];\n\t}\n\n\treturn sqrt(s);\n}\n\n\n//XYZ座標の掛け算\nxyz scale_calc(xyz xyz1,double scale){\n\txyz xyz2;\n\n\txyz2.x=xyz1.x*scale;\n\txyz2.y=xyz1.y*scale;\n\txyz2.z=xyz1.z*scale;\n\n\treturn xyz2;\n}\n\n\n//XYZ座標の足し算\nxyz add_calc(xyz xyz1,xyz xyz2){\n\txyz xyz3;\n\n\txyz3.x=xyz1.x+xyz2.x;\n\txyz3.y=xyz1.y+xyz2.y;\n\txyz3.z=xyz1.z+xyz2.z;\n\n\treturn xyz3;\n}\n\n\n//三角形と線分のあたり判定\nbool collision_tri_line(xyz tri[],xyz line[],xyz &contact_pt){\n\t//あたり判定 \n\t//true→衝突\n\t//false→あたっていない\n\n\t//xyz tri[3];\n\t//xyz line[2];\n\n\txyz normal_vec;\n\tnormal_calc(tri,normal_vec);\n\n\t///三角形を含む面と線分の交差\n\t//平面上のある点から両端に引いたベクトルと法線ベクトルとの符号を調べる\n\txyz sub1,sub2;\n\tdouble h1,h2;\n\t//\n\tsub1=sub_calc(tri[0],line[0]);\n\tsub2=sub_calc(tri[0],line[1]);\n\n\th1=innerproduct_calc(sub1,normal_vec);\n\th2=innerproduct_calc(sub2,normal_vec);\n\n\t//符号を調べる\n\tint sign_h1 = (h1 > 0) - (h1 < 0);\n\tint sign_h2 = (h2 > 0) - (h2 < 0);\n\n\t//符号が一緒であれば、面と線分は交差していない\n\tif(sign_h1==sign_h2){\n\t\t//\tcout<<\"交差していない\"<<endl;\n\t\treturn false;\n\t}\n\n\t//三角形と線分の交点を求める。\n\t//i = (p1 * h2 + p2 * h1) / (h1 + h2)\n\txyz node;\n\tnode=add_calc(scale_calc(line[0],fabs(h2)),scale_calc(line[1],fabs(h1)));\n\tdouble h3=(fabs(h1)+fabs(h2));\n\tif(h3!=0)\tnode=scale_calc(node,(1/h3));\n\telse if(h3==0)\tcout<<\"error\"<<endl;\n\n\tcontact_pt=node;\n\n\t//交点から三角形頂点へのベクトル\n\t//n1n2n3とするとn1・nとn2・nとn3・nの符合が一致すること\n\txyz pp,qq,rr;\n\txyz np,nq,nr;\n\tdouble dot1,dot2,dot3;\n\tpp=sub_calc(tri[0],node);\n\tqq=sub_calc(tri[1],node);\n\trr=sub_calc(tri[2],node);\n\n\tnp=crossproduct_calc(pp,qq);\n\tnq=crossproduct_calc(qq,rr);\n\tnr=crossproduct_calc(rr,pp);\n\n\tdot1=innerproduct_calc(np,normal_vec);\n\tdot2=innerproduct_calc(nq,normal_vec);\n\tdot3=innerproduct_calc(nr,normal_vec);\n\n\n\t//符号を調べる\n\tint sign_dot1 = (dot1 > 0) - (dot1 < 0);\n\tint sign_dot2 = (dot2 > 0) - (dot2 < 0);\n\tint sign_dot3 = (dot3 > 0) - (dot3 < 0);\n\n\n\tif((sign_dot1==sign_dot2)&&(sign_dot2==sign_dot3)){\n\t\t//\tcout<<\"交差している\"<<endl;\n\t\treturn true;\n\t}\n\telse{\n\t\t//\tcout<<\"交差していない\"<<endl;\n\t\treturn false;\n\n\t}\n\n\t//cout<<\"交差していない\"<<endl;\n\treturn false;\n}\n\n//三角形と三角形のあたり判定\nbool collision_tri_tri(\txyz in_tri[],\txyz in_tri2[]){\n\n\txyz line[2];\n\txyz out[6];\n\n\tbool flag[6]={0,0,0,0,0,0};\n\txyz tri[3];\n\n\ttri[0]=in_tri[0];\n\ttri[1]=in_tri[1];\n\ttri[2]=in_tri[2];\n\n\tline[0]=in_tri2[0];\n\tline[1]=in_tri2[1];\n\tflag[0]=collision_tri_line(tri,line,out[0]);\n\n\tline[0]=in_tri2[1];\n\tline[1]=in_tri2[2];\n\tflag[1]=collision_tri_line(tri,line,out[1]);\n\n\tline[0]=in_tri2[2];\n\tline[1]=in_tri2[0];\n\tflag[2]=collision_tri_line(tri,line,out[2]);\n\n\ttri[0]=in_tri2[0];\n\ttri[1]=in_tri2[1];\n\ttri[2]=in_tri2[2];\n\n\tline[0]=in_tri[0];\n\tline[1]=in_tri[1];\n\tflag[3]=collision_tri_line(tri,line,out[3]);\n\n\tline[0]=in_tri[1];\n\tline[1]=in_tri[2];\n\tflag[4]=collision_tri_line(tri,line,out[4]);\n\n\tline[0]=in_tri[2];\n\tline[1]=in_tri[0];\n\tflag[5]=collision_tri_line(tri,line,out[5]);\n\n\n\tif(flag[0]||flag[1]||flag[2]||flag[3]||flag[4]||flag[5]){\n\t\t///cout<<\"交差している\"<<endl;\n\t\treturn true;\n\n\t}\n\telse{\n\t\t//cout<<\"交差していない\"<<endl;\n\t\treturn false;\n\n\t}\n\treturn 0;\n\n}\n\n" }, { "alpha_fraction": 0.7326202988624573, "alphanum_fraction": 0.7326202988624573, "avg_line_length": 25.714284896850586, "blob_id": "94256bca11805a62780a23f6ff3f4f076dbaf205", "content_id": "c8377933a18d8c3ac2e8d3c52944069e1b0a47a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 187, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/orbit_pantilt_camera/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "all:\n\tmake -f Makefile.control_orbit_pantilt\n\tcp control_orbit_pantilt ../../bin\n#\tcp docu_object_tracking_lrf_setting.ini ../../bin\n\nclean:\n\tmake -f Makefile.control_orbit_pantilt clean\n" }, { "alpha_fraction": 0.6211129426956177, "alphanum_fraction": 0.6252045631408691, "avg_line_length": 21.423076629638672, "blob_id": "2ad9a8e9e3dc3b506572813a5e99a0ca88f06f48", "content_id": "e2772be6cfc04baa5b4e3d5202649e104168139e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1238, "license_type": "no_license", "max_line_length": 73, "num_lines": 52, "path": "/n_vel_view/src/gl_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n\r\n#include \"viewgui.h\"\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\n#include <ctime>\r\n#include <sys/time.h>\r\n#include <unistd.h>\r\n#include <ros/ros.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\nusing namespace std;\r\n#include <signal.h>\r\n//Robot制御のパラメータ\r\n//extern struct ROBOT myrobot;\r\n//extern struct URG urg_data;\r\nextern double target_v;\r\nextern double target_w;\r\n\r\nvoid mySigintHandler(int sig){\r\n\tprintf(\"shutdown catch signal %d \\n\", sig);\r\n\tros::shutdown();\r\n}\r\n\r\n\r\nvoid vel_Callback(const geometry_msgs::Twist &vel_msg){\r\n target_v = vel_msg.linear.x;\r\n target_w = -vel_msg.angular.z;\r\n// cout<<target_v<<\",\"<<target_w<<endl;\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n\ttarget_v=0;\r\n\ttarget_w=0;\r\n\r\n\tGraphics GL;\r\n\r\n\tros::init(argc, argv, \"n_velocity_view\");\r\n\tconst std::string vel_topic_ = \"cmd_vel\";\r\n\tros::NodeHandle n;\r\n \tros::Subscriber cmd_vel = n.subscribe(vel_topic_, 10, vel_Callback);\r\n \t\tsignal(SIGINT, mySigintHandler);\r\n \t\t\r\n\tros::spin();\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.4629282057285309, "alphanum_fraction": 0.5579540133476257, "avg_line_length": 21.28272247314453, "blob_id": "1a10c49e7a89dd647502ae45af13d0a41d2dbd05", "content_id": "328360159d04674e1fc14770899d078d833c20a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4552, "license_type": "no_license", "max_line_length": 108, "num_lines": 191, "path": "/n_3d_robot_sim/src/gl_human.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <GL/glut.h>\n\n\nstatic void myBox(double x, double y, double z)\n{\n\tGLdouble hx = x * 0.50, hz = z * 0.50;\n\n\tGLdouble vertex[][3] = {\n\t\t{ -hx, -y, -hz },\n\t\t{ hx, -y, -hz },\n\t\t{ hx, 0.0, -hz },\n\t\t{ -hx, 0.0, -hz },\n\t\t{ -hx, -y, hz },\n\t\t{ hx, -y, hz },\n\t\t{ hx, 0.0, hz },\n\t\t{ -hx, 0.0, hz }\n\t};\n\n\tconst static int face[][4] = {\n\t\t{ 0, 1, 2, 3 },\n\t\t{ 1, 5, 6, 2 },\n\t\t{ 5, 4, 7, 6 },\n\t\t{ 4, 0, 3, 7 },\n\t\t{ 4, 5, 1, 0 },\n\t\t{ 3, 2, 6, 7 }\n\t};\n\n\tconst static GLdouble normal[][3] = {\n\t\t{ 0.0, 0.0,-1.0 },\n\t\t{ 1.0, 0.0, 0.0 },\n\t\t{ 0.0, 0.0, 1.0 },\n\t\t{-1.0, 0.0, 0.0 },\n\t\t{ 0.0,-1.0, 0.0 },\n\t\t{ 0.0, 1.0, 0.0 }\n\t};\n\tGLfloat mat_diffuse[4] ;\n\n\t int color_no=1;\n\n\tif(color_no==0)\t { mat_diffuse[0] = 1;mat_diffuse[1] = 1;mat_diffuse[2] = 0;mat_diffuse[3] = 1.0; };\n\tif(color_no==1)\t { mat_diffuse[0] = 0.5;mat_diffuse[1] = 0.5;mat_diffuse[2] = 0.;mat_diffuse[3] = 1.0; };\n\tif(color_no==2)\t { mat_diffuse[0] = 0;mat_diffuse[1] = 0;mat_diffuse[2] = 1;mat_diffuse[3] = 1.0; };\n\tif(color_no==3)\t { mat_diffuse[0] = 1;mat_diffuse[1] = 1;mat_diffuse[2] = 0;mat_diffuse[3] = 1.0; };\n\n\n\tint i, j;\n\n\t/* 材質を設定する */\n\tfloat diffuse[] = { 1, 1, 1, 1.0 };\n\tfloat specular[] = { 0.8, 0.8, 0.8, 1.0 };\n\tfloat ambient[] = { 0.1, 0.1, 0.1, 1.0 };\n\tfloat shininess = 60;\n\tGLfloat lightPos[] = {1 , 1 , 1 , 1};\n\n\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, specular );\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, ambient );\n\tglMaterialf( GL_FRONT_AND_BACK, GL_SHININESS, shininess );\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);\n\n\n\tglBegin(GL_QUADS);\n\tfor (j = 0; j < 6; ++j) {\n\t\tglNormal3dv(normal[j]);\n\t\tfor (i = 4; --i >= 0;) {\n\t\t\tglVertex3dv(vertex[face[j][i]]);\n\t\t}\n\t}\n\tglEnd();\n\n\tglLineWidth(1);\n\tglColor3f(0,0,0);\n\tfor (j = 0; j < 6; ++j) {\n//\t\tglNormal3dv(normal[j]);\n\t\tfor (i = 4; --i > 0;) {\n\t\t\tglBegin(GL_LINES);\n\t\t\tglVertex3dv(vertex[face[j][i]]);\n\t\t\tglVertex3dv(vertex[face[j][i-1]]);\n\t\t\tglEnd();\n\n\t\t}\n\t}\n\tglLineWidth(1);\n\tglColor3f(0,1,0);\n\n\n}\n\n\n\nvoid armleg(double girth, double length, double r1, double r2)\n{\n\tglRotated(r1, 1.0, 0.0, 0.0);\n\tmyBox(girth, length, girth);\n\tglTranslated(0.0, -0.05 - length, 0.0);\n\tglRotated(r2, 1.0, 0.0, 0.0);\n\tmyBox(girth, length, girth);\n}\n\n\n\n\nvoid walkman(double now,double delay){\n\tconst static GLfloat lightpos[] = { -10.0, 10.0,10.0, 1.0 }; /* 光源の位置 */\n\tglLightfv(GL_LIGHT0, GL_POSITION, lightpos);\n\n\tglEnable( GL_LIGHTING );\t\t//光源ON\n\tstatic double ll1 = 0.0; /* 箱男の左足の股関節の角度 */\n\tstatic double ll2 = 0.0; /* 箱男の左足の膝関節の角度 */\n\n\tstatic double rl1 = 0.0; /* 箱男の右足の股関節の角度 */\n\tstatic double rl2 = 0.0; /* 箱男の右足の膝関節の角度 */\n\n\tstatic double la1 = 0.0; /* 箱男の左腕の肩関節の角度 */\n\tstatic double la2 = 0.0; /* 箱男の左腕の肘関節の角度 */\n\n\tstatic double ra1 = 0.0; /* 箱男の右腕の肩関節の角度 */\n\tstatic double ra2 = 0.0; /* 箱男の右腕の肘関節の角度 */\n\n\tdouble dely_leg1=10;\n\n\tll1=30.0*sin(now*2*M_PI/2.0+delay)+dely_leg1;\n\trl1=30.0*sin(now*2*M_PI/2.0+2*M_PI/2.0+delay)+dely_leg1;\n\n\tdouble dely_leg2=+10.0;\n\tll2=10.0*sin(now*2*M_PI/2.0+delay)+dely_leg2;\n\trl2=10.0*sin(now*2*M_PI/2.0+2*M_PI/2.0+delay)+dely_leg2;\n\n\n\tdouble offset_arm=-0.0;\n\tla1=20.0*sin(now*2*M_PI/2.0+2*M_PI/2.0+delay)+offset_arm;\n\tra1=20.0*sin(now*2*M_PI/2.0+delay)+offset_arm;\n\n\tdouble offset_arm2=-20.0;\n\tla2=20.0*sin(now*2*M_PI/2.0+2*M_PI/2.0+delay)+offset_arm2;\n\tra2=20.0*sin(now*2*M_PI/2.0+delay)+offset_arm2;\n\n\n\t//double px = 1.0, pz = 0.0; /* 箱男の位置 */\n\t//double r = 00.0; /* 箱男の向き */\n\t//double h = 2.0; /* 箱男の高さ */\n\n\t/* 箱男の位置と方向 */\n\t//glTranslated(px, h, pz);\n\n\t/* 頭 */\n\tglPushMatrix();\n\tglTranslated(0.0, 0.5, 0.0);\n\tmyBox(0.5, 0.5, 0.5);\n\tglPopMatrix();\n\n\t/* 胴 */\n\tglPushMatrix();\n\tglTranslated(0.0, 0.0, 0.0);\n\tmyBox(0.3, 0.5, 0.2);\n\tglPopMatrix();\n\n\t/* 左足 */\n\tglPushMatrix();\n\tglTranslated(0.1, -0.65, 0.0);\n\tarmleg(0.2, 0.4, ll1, ll2);\n\tglPopMatrix();\n\n\t/* 右足 */\n\tglPushMatrix();\n\tglTranslated(-0.1, -0.65, 0.0);\n\tarmleg(0.2, 0.4, rl1, rl2);\n\tglPopMatrix();\n\n\t/* 左腕 */\n\tglPushMatrix();\n\tglTranslated(0.28, 0.0, 0.0);\n\tarmleg(0.16, 0.4, la1, la2);\n\tglPopMatrix();\n\n\t/* 右腕 */\n\tglPushMatrix();\n\tglTranslated(-0.28, 0.0, 0.0);\n\tarmleg(0.16, 0.4, ra1, ra2);\n\tglPopMatrix();\n\n\n\n\n//\tglDisable( GL_LIGHTING );\t\t// 光源ON\n}\n\n\n\n\n" }, { "alpha_fraction": 0.5805658102035522, "alphanum_fraction": 0.6322263479232788, "avg_line_length": 24.3125, "blob_id": "edf38a40c7cce8235bba98ee78b1f19481cbcc11", "content_id": "c6006d4a34c71a84184d9057fe312ebed8125726", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 813, "license_type": "no_license", "max_line_length": 44, "num_lines": 32, "path": "/robo_model/script/pictogram.py", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport rospy\nfrom jsk_rviz_plugins.msg import Pictogram\nfrom random import random\nrospy.init_node(\"pictogram_sample\")\np = rospy.Publisher(\"/pictogram\", Pictogram)\n\nr = rospy.Rate(1.0)\n\ncounter = 0\nwhile not rospy.is_shutdown():\n msg = Pictogram()\n msg.action = Pictogram.JUMP\n msg.header.frame_id = \"/map\"\n msg.header.stamp = rospy.Time.now()\n msg.pose.position.z = 0.0\n msg.pose.orientation.w = 1.0\n msg.pose.orientation.x = 0\n msg.pose.orientation.y = -1.0\n msg.pose.orientation.z = 0\n msg.mode = Pictogram.STRING_MODE\n msg.speed = 0.10\n # msg.ttl = 5.0\n msg.size = 2.0\n msg.color.r = 255.0 / 255.0\n msg.color.g = 24.0 / 255.0\n msg.color.b = 24.0 / 255.0\n msg.color.a = 1.0\n msg.character = \"Home\"\n p.publish(msg)\n r.sleep()\n \n" }, { "alpha_fraction": 0.6576782464981079, "alphanum_fraction": 0.6828153729438782, "avg_line_length": 24.44186019897461, "blob_id": "bfe02690553d1d4d7ccbd1887ae1df8a963ce831", "content_id": "3c65a0871d2f3b4185a6ff75f230e4c00c6178ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2188, "license_type": "no_license", "max_line_length": 83, "num_lines": 86, "path": "/n_scan_to_scan/src/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n#include <laser_assembler/AssembleScans.h>\n\n#include <sensor_msgs/PointCloud2.h>\n#include <sensor_msgs/PointCloud.h>\n#include <sensor_msgs/point_cloud_conversion.h>\n#include <sensor_msgs/LaserScan.h>\n#include <laser_geometry/laser_geometry.h>\n#include <tf/transform_listener.h>\n//PointCloud\n#include <pcl/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/filters/voxel_grid.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <limits>\n#include \"unistd.h\"\n\nusing namespace std;\n\n\nros::Subscriber scan_sub;\nros::Publisher scan_pub;\n\n\nvoid scanCallback (const sensor_msgs::LaserScanConstPtr & scan_msg){\n //populate the LaserScan message\n sensor_msgs::LaserScan scan3;\n\n scan3.header.stamp= ros::Time::now();// = scan_msg->header.stamp;\n scan3.header.frame_id = \"base_link\";\n scan3.angle_min = scan_msg->angle_min;\n scan3.angle_max = scan_msg->angle_max;\n scan3.angle_increment =scan_msg->angle_increment;\n scan3.range_min = scan_msg->range_min;\n scan3.scan_time = scan_msg->scan_time;\n scan3.range_max = scan_msg->range_max;\n double laser_frequency=10.0;\n\n int data_num=(scan_msg->angle_max-scan_msg->angle_min)/scan_msg->angle_increment;\n\n scan3.time_increment = (1 / laser_frequency) / (double)(data_num);\n //scan3.time_increment = 0.01;\n scan3.ranges.resize(data_num);\n scan3.intensities.resize(data_num);\n\n for (unsigned int i = 0; i <data_num; ++i)\n {\n\n scan3.ranges[i] = scan_msg->ranges[i];\n\n if (scan3.ranges[i]< scan_msg->range_min){\n scan3.ranges[i] = std::numeric_limits<float>::quiet_NaN();\n }\n\n if(scan3.ranges[i]> scan_msg->range_max) {\n scan3.ranges[i] = std::numeric_limits<float>::quiet_NaN();\n }\n //scan3.ranges[i] = 5.0;\n scan3.intensities[i] = 0.0;\n }\n\n scan_pub.publish(scan3);\n double wait_time=0.030;\n usleep(1000.0*1000.0*wait_time);\n}\n\n\nint main(int argc, char **argv){\n\n ros::init(argc, argv, \"n_scan2scan\");\n ros::NodeHandle private_nh(\"~\");\n\n ros::NodeHandle nh;\n\n scan_pub = nh.advertise<sensor_msgs::LaserScan>(\"scan_out2\", 10);\n scan_sub = nh.subscribe (\"scan_out\", 10, scanCallback);\n\n ros::spin();\n\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6518518328666687, "alphanum_fraction": 0.6592592597007751, "avg_line_length": 18.285715103149414, "blob_id": "146be5ed39f3416f0a9aa018b2e7a1ff8b7dc1ac", "content_id": "c5c95b415ccedf9d66ff4376d13aae2c59d16628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 135, "license_type": "no_license", "max_line_length": 40, "num_lines": 7, "path": "/check_tf_result/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "all:\n\tmake -f Makefile.odom_tf\n#\tcp odom_tf ../../bin\n##cp docu_scan2pcl_setting.ini ../../bin\n\nclean:\n\tmake -f Makefile.odom_tf clean\n" }, { "alpha_fraction": 0.7177419066429138, "alphanum_fraction": 0.7177419066429138, "avg_line_length": 16.714284896850586, "blob_id": "9e162d007f0bcdd4a6b40ff4c201e774ab95c34e", "content_id": "59cae4ec312c6ff9c769c525dec20a1d5f0f3228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 124, "license_type": "no_license", "max_line_length": 41, "num_lines": 7, "path": "/old/map_editor_simple/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "all:\n\tmake -f Makefile.map_editor_simple\n\tcp map_editor_simple ../../bin\n\n\nclean:\n\tmake -f Makefile.map_editor_simple clean\n" }, { "alpha_fraction": 0.5956006646156311, "alphanum_fraction": 0.6937394142150879, "avg_line_length": 24.65217399597168, "blob_id": "eb609409fe84a2ba6c6f0a15fd971d49175948d0", "content_id": "8fc9077e5337db03151378e8a46d43311e1ddf4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 591, "license_type": "no_license", "max_line_length": 52, "num_lines": 23, "path": "/orbit_pantilt_camera/orbit_pantilt.sh", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "uvcdynctrl -d video1 -s 'Pan Reset' 0\nsleep 3\nuvcdynctrl -d video1 -s 'Tilt Reset' 0\nsleep 2\nuvcdynctrl -d video1 -s 'Tilt (relative)' 1024\nuvcdynctrl -d video1 -s 'Pan (relative)' 2240\nsleep 2\n\nuvcdynctrl -d video1 -s 'Pan (relative)' -- -2240\nsleep 2\nuvcdynctrl -d video1 -s 'Tilt (relative)' -- -1024\n\n\n#uvcdynctrl -d video1 -s 'Tilt (relative)' -- -2048 \nsleep 1\nuvcdynctrl -d video1 -s 'Tilt (relative)' 1024 \nsleep 1\nuvcdynctrl -d video1 -s 'Pan (relative)' 2240 \nsleep 2\nuvcdynctrl -d video1 -s 'Pan (relative)' -- -4480\nsleep 2\nuvcdynctrl -d video1 -s 'Pan (relative)' 2240\nsleep 2\n\n" }, { "alpha_fraction": 0.6129032373428345, "alphanum_fraction": 0.774193525314331, "avg_line_length": 91, "blob_id": "6c3171a15c0977841cf2e6f029b9e6c12b095f6b", "content_id": "b69c23826d374bd4c0152c574a8eef75a7079b39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 93, "license_type": "no_license", "max_line_length": 91, "num_lines": 1, "path": "/robo_launch/old/replay.sh", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "roslaunch replay_2D.launch bag_filename:=/home/iqit/catkin_bag/2017-08-23-20-47-30_scan.bag\n\n" }, { "alpha_fraction": 0.6205947399139404, "alphanum_fraction": 0.6383488774299622, "avg_line_length": 27.3359375, "blob_id": "f1ac8b3ad4f78445c9b6a06547542c6d50482026", "content_id": "baa664a5982f0bbbcb8e5850126fc73a0aeaa480", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11367, "license_type": "no_license", "max_line_length": 114, "num_lines": 384, "path": "/docu_navi_localpathplan/src/gl_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n/////////////////////////////////////////////////\r\n\r\n#include \"viewgui.h\"\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\n\r\n#include <math.h>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <vector>\r\n#include <string>\r\n#include <limits>\r\nusing namespace std;\r\n\r\n#include <ros/ros.h>\r\n#include <actionlib_msgs/GoalStatusArray.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/transform_listener.h>\r\n#include <nav_msgs/Path.h>\r\n\r\n#include <std_msgs/Float32.h>\r\n#include <std_msgs/Int16.h>\r\nusing namespace std;\r\n#include <signal.h>\r\n\r\n//#include \"read_file.h\"\r\n\r\ntf::TransformListener *tflistener;\r\nvoid mySigintHandler(int);\r\n\r\n//Robot制御のパラメータ\r\nextern struct ROBOT myrobot;\r\nextern struct URG urg_data;\r\nextern struct URG urg_data2;\r\nstruct ROBOT myrobot_buff;\r\nextern double best_v, best_w;\r\nextern double goal_x, goal_y;\r\nextern double goal_theta;\r\n\r\nextern double goal_reach_dis; //ゴールに到達したとする距離\r\nextern double turn_limit; //その角度以上で旋回\r\nextern double moving_goal_limit;\r\nextern double target_speed_gain;\r\nextern double target_turn_gain;\r\nextern double target_speed_max;\r\nextern double circling_turn_gain;\r\nextern double circling_turn_max;\r\nextern double dwa_robot_v_max;\r\nextern double dwa_robot_v_min;\r\nextern double dwa_robot_size;\r\nextern double dwa_urg_fail_min;\r\nextern double dwa_dt;\r\nextern double dwa_v_weight;\r\nextern double dwa_w_weight;\r\nextern double dwa_dis_weight;\r\nextern double dwa_leng_weight;\r\nextern double dwa_ac_trans_limit;\r\nextern double dwa_ac_rot_limit;\r\n\r\nextern double target_v;\r\nextern double target_w;\r\n\r\ndouble danger_dis=0.5;\r\nint danger_count_thresh=300;\r\nint danger_count=0;\r\nbool danger_flg=0;\r\nros::Publisher danger_count_pub;\r\n\r\nvoid convert_odom(ROBOT &robot, ROBOT robot_buff);\r\n//int load_config(string fname);\r\nros::Publisher cmd_vel_pub;\r\n\r\n\r\nint mode=0;\r\n\r\nint wait_sleep(double sec){\r\n int msen=1000.0*sec;\r\n usleep(msen * 1000);\r\n return 0;\r\n}\r\n\r\n\r\n//move_baseが動いているかどうかのflg\r\nbool move_base_robo_moving_status=0;\r\n\r\nvoid navStatusCallBack(const actionlib_msgs::GoalStatusArray::ConstPtr &status)\r\n{\r\n int status_id = 0;\r\n static int old_status = 0;\r\n //status=3;goal, //status=1;moving\r\n\r\n if (!status->status_list.empty())\r\n {\r\n actionlib_msgs::GoalStatus goalStatus = status->status_list[0];\r\n status_id = goalStatus.status;\r\n cout<<goalStatus.text<<endl;\r\n }\r\n\r\n if(status_id==1){\r\n //もし起動開始であれば\r\n if(old_status==false){\r\n cout<<\"waiting...\"<<endl;\r\n }\r\n cout<<\"run_start\"<<endl;\r\n move_base_robo_moving_status=true;\r\n }\r\n\r\n if((status_id==3)||(status_id==0)){\r\n move_base_robo_moving_status=false;\r\n }\r\n\r\n old_status=move_base_robo_moving_status;\r\n\r\n}\r\n\r\n\r\nvoid scanCallback(const sensor_msgs::LaserScanConstPtr &scan_msg){\r\n double range_min = scan_msg->range_min;\r\n double range_max = scan_msg->range_max;\r\n double angle_increment = scan_msg->angle_increment;\r\n double angle_min = scan_msg->angle_min;\r\n double angle_max = scan_msg->angle_max;\r\n\r\n int data_num = (angle_max - angle_min) / angle_increment;\r\n // TODO - also copy intensity values\r\n\r\n for (unsigned int i = 0; i < data_num; ++i) {\r\n urg_data.leng[i] = scan_msg->ranges[i];\r\n if (isnan(urg_data.leng[i])) urg_data.leng[i] = 0.0;\r\n \r\n if(i*angle_increment+angle_min<-M_PI/2.0) {\r\n urg_data.leng[i] = 0.0;\r\n //cout<<i*angle_increment+angle_min<<endl;\r\n }\r\n if(i*angle_increment+angle_min> M_PI/2.0){\r\n urg_data.leng[i] = 0.0;\r\n } \r\n \r\n \r\n }\r\n\r\n urg_data.data_num = data_num;\r\n urg_data.start_rad = scan_msg->angle_min;\r\n urg_data.reso = scan_msg->angle_increment;\r\n urg_data.leng_max = range_max;\r\n urg_data.leng_min = range_min;\r\n \r\n danger_count=0;\r\n for(unsigned int i = 0; i < data_num; ++i){\r\n // urg_data.leng[i]=scan_msg->ranges[i];\r\n if(urg_data.leng[i]<danger_dis)danger_count++;\r\n }\r\n if(danger_count>danger_count_thresh)danger_flg=1;\r\n else danger_flg=0;\r\n\r\n std_msgs::Float32 msg_float;\r\n msg_float.data = danger_count;\r\n danger_count_pub.publish(msg_float);\r\n\r\n \r\n}\r\nvoid scanCallback2(const sensor_msgs::LaserScanConstPtr &scan_msg)\r\n{\r\n double range_min = scan_msg->range_min;\r\n double range_max = scan_msg->range_max;\r\n double angle_increment = scan_msg->angle_increment;\r\n double angle_min = scan_msg->angle_min;\r\n double angle_max = scan_msg->angle_max;\r\n\r\n int data_num = (angle_max - angle_min) / angle_increment;\r\n // TODO - also copy intensity values\r\n\r\n for (unsigned int i = 0; i < data_num; ++i){\r\n urg_data2.leng[i] = scan_msg->ranges[i];\r\n if (isnan(urg_data.leng[i]))\r\n urg_data2.leng[i] = 0.0;\r\n }\r\n\r\n urg_data2.data_num = data_num;\r\n urg_data2.start_rad = scan_msg->angle_min;\r\n urg_data2.reso = scan_msg->angle_increment;\r\n urg_data2.leng_max = range_max;\r\n urg_data2.leng_min = range_min;\r\n}\r\n\r\nvoid GetRPY(const geometry_msgs::Quaternion &quat, double &theta){\r\n tf::Quaternion q(quat.x, quat.y, quat.z, quat.w);\r\n tf::Matrix3x3 m(q);\r\n double roll, pitch, yaw;\r\n m.getRPY(roll, pitch, yaw);\r\n //std::cout << \"Roll: \" << roll << \", Pitch: \" << pitch << \", Yaw: \" << yaw << std::endl;\r\n //theta=yaw+3.1415;\r\n theta = -yaw;\r\n}\r\ndouble short_goal_dis=1.0;\r\n\r\nvoid pathCallback(const nav_msgs::PathConstPtr &path){\r\n if (path->poses.size() == 0)\r\n {\r\n myrobot.v = 0.0;\r\n myrobot.w = 0.0;\r\n return;\r\n }\r\n geometry_msgs::PoseStamped start_pos_map;\r\n geometry_msgs::PoseStamped start_pos_base_link;\r\n geometry_msgs::PoseStamped end_pos_map;\r\n geometry_msgs::PoseStamped end_pos_base_link;\r\n\r\n int m = (path->poses.size() - 1);\r\n int short_goal_dis_no=0;\r\n double dis=0.0;\r\n for(int i=0;i<m-1;i++){\r\n start_pos_map = path->poses[i];\r\n end_pos_map = path->poses[i+1];\r\n\r\n double sx=start_pos_map.pose.position.x;\r\n double sy=start_pos_map.pose.position.y;\r\n double ex=end_pos_map.pose.position.x;\r\n double ey=end_pos_map.pose.position.y;\r\n dis+=sqrt((ex-sx)*(ex-sx)+(ey-sy)*(ey-sy));\r\n\r\n if((short_goal_dis_no==0)&&(short_goal_dis<dis)) short_goal_dis_no=i;\r\n }\r\n\r\n if(short_goal_dis_no!=0) m=short_goal_dis_no;\r\n\r\n\r\n //cout<<m<<\"_\"<<dis<<endl;\r\n\r\n start_pos_map = path->poses[0];\r\n end_pos_map = path->poses[m];\r\n goal_x = -end_pos_map.pose.position.y;\r\n goal_y = end_pos_map.pose.position.x;\r\n\r\n geometry_msgs::Quaternion end_orientation = end_pos_map.pose.orientation;\r\n double theta = 0.0;\r\n GetRPY(end_orientation, theta);\r\n goal_theta = -theta;\r\n}\r\n\r\n\r\n\r\nvoid mySigintHandler(int sig){\r\n geometry_msgs::Twist base_cmd;\r\n base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n cmd_vel_pub.publish(base_cmd);\r\n\r\n printf(\"shutdown catch signal %d \\n\", sig);\r\n ros::shutdown();\r\n}\r\n\r\nint main(int argc, char *argv[]){\r\n\r\n ros::init(argc, argv, \"docu_navigation_localpathplan\");\r\n ros::NodeHandle private_nh(\"~\");\r\ndouble vel_weight=0.5;\r\n private_nh.param(\"short_goal_dis\", short_goal_dis, 1.0);\r\n private_nh.param(\"goal_reach_dis\", goal_reach_dis, 0.1);\r\n private_nh.param(\"turn_limit\", turn_limit, 0.70);\r\n private_nh.param(\"moving_goal_limit\", moving_goal_limit, 0.5);\r\n private_nh.param(\"target_speed_gain\", target_speed_gain, 1.0);\r\n private_nh.param(\"target_turn_gain\", target_turn_gain, 1.0);\r\n\r\n private_nh.param(\"target_speed_max\", target_speed_max, 0.45);\r\n private_nh.param(\"circling_turn_gain\", circling_turn_gain, 1.0);\r\n private_nh.param(\"circling_turn_max\", circling_turn_max, 0.5);\r\n private_nh.param(\"dwa_robot_v_max\", dwa_robot_v_max, 0.45);\r\n private_nh.param(\"dwa_robot_v_min\", dwa_robot_v_min, 0.01);\r\n\r\n private_nh.param(\"dwa_robot_size\", dwa_robot_size, 0.4);\r\n private_nh.param(\"dwa_urg_fail_min\", dwa_urg_fail_min, 0.05);\r\n private_nh.param(\"dwa_dt\", dwa_dt, 0.1);\r\n private_nh.param(\"dwa_v_weight\", dwa_v_weight, 5.0);\t\t\t//dwa_v_weight*fabs(v-robot_v)\r\n private_nh.param(\"dwa_w_weight\", dwa_w_weight, 10.0);\t\t\t//dwa_w_weight*fabs(w-robot_w)\r\n private_nh.param(\"dwa_dis_weight\", dwa_dis_weight, 0.1);\t\t//dwa_dis_weight*(dwa_dis_max-dis_min)\r\n private_nh.param(\"dwa_leng_weight\", dwa_leng_weight, 0.1);\t\t//dwa_leng_weight*length\r\n// private_nh.param(\"dwa_ac_trans_limit\", dwa_ac_trans_limit, 0.50);\r\n// private_nh.param(\"dwa_ac_rot_limit\", dwa_ac_rot_limit, 0.50);\r\n\r\n private_nh.param(\"danger_dis\",danger_dis,0.3);\r\n private_nh.param(\"danger_count_thresh\",danger_count_thresh,300);\r\n\r\n private_nh.param(\"vel_weight\",vel_weight,0.1);\r\n private_nh.param(\"mode\",mode,0);\r\n\r\n\r\n Graphics GL;\r\n\r\n ros::NodeHandle n;\r\n const std::string scan_topic_ = \"scan1\";\r\n ros::Subscriber scan_subscriber_ = n.subscribe(scan_topic_, 5, scanCallback);\r\n const std::string path_topic = \"/move_base/TrajectoryPlannerROS/global_plan\";\r\n ros::Subscriber path_subscriber = n.subscribe(path_topic, 10, pathCallback);\r\n\r\n cmd_vel_pub= n.advertise<geometry_msgs::Twist>(\"cmd_vel_navi\", 1);\r\n danger_count_pub = n.advertise<std_msgs::Float32>(\"danger_count2\", 1);\r\n ros::Subscriber move_base_status_sub;\r\n move_base_status_sub = n.subscribe<actionlib_msgs::GoalStatusArray>(\"/move_base/status\", 1, &navStatusCallBack);\r\n\r\n ros::Rate r(10.0);\r\n\r\n tf::TransformListener lr(ros::Duration(10));\r\n tflistener = &lr;\r\n myrobot.v = 0;\r\n myrobot.w = 0;\r\n\r\n target_v = 0.0;\r\n target_w = 0.0;\r\n goal_x = 0.0;\r\n goal_y = 0.0;\r\n\r\n\r\n signal(SIGINT, mySigintHandler);\r\n double myrobot_v_out=0.0;\r\n double myrobot_w_out=0.0;\r\n while (n.ok()) {\r\n\r\n tf::StampedTransform transform;\r\n try\r\n {\r\n tflistener->waitForTransform(\"/map\", \"/base_link\", ros::Time(0), ros::Duration(3.0));\r\n tflistener->lookupTransform(\"/map\", \"/base_link\",\r\n ros::Time(0), transform);\r\n }\r\n catch (tf::TransformException ex)\r\n {\r\n ROS_ERROR(\"%s\", ex.what());\r\n ros::Duration(1.0).sleep();\r\n }\r\n\r\n geometry_msgs::Quaternion odom_quat;\r\n odom_quat.x = transform.getRotation().x();\r\n odom_quat.y = transform.getRotation().y();\r\n odom_quat.z = transform.getRotation().z();\r\n odom_quat.w = transform.getRotation().w();\r\n double theta = 0.0;\r\n GetRPY(odom_quat, theta);\r\n myrobot.x = -transform.getOrigin().y();\r\n myrobot.y = transform.getOrigin().x();\r\n myrobot.theta = theta;\r\n\r\n\r\n geometry_msgs::Twist base_cmd;\r\n base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n \r\n myrobot_v_out =myrobot_v_out*(1.0-vel_weight)+myrobot.v*vel_weight;\r\n myrobot_w_out =myrobot_w_out*(1.0-vel_weight)+myrobot.w*vel_weight;\r\n \r\n if(fabs(myrobot_v_out)<0.01) myrobot_v_out=0.0;\r\n if(fabs(myrobot_w_out)<0.01) myrobot_w_out=0.0;\r\n\r\n\r\n if(move_base_robo_moving_status==true){\r\n base_cmd.linear.x = myrobot_v_out*target_speed_gain;\r\n base_cmd.angular.z =- myrobot_w_out*target_turn_gain;\r\n }\r\n\r\n\r\n\t // cout<<\"v:\"<<base_cmd.linear.x<<\",\";\r\n\t // cout<<\"w:\"<<base_cmd.angular.z<<\",\"<<endl;\r\n \r\n if(danger_flg==1){\r\n base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n }\r\n\r\n\r\n cmd_vel_pub.publish(base_cmd);\r\n\r\n ros::spinOnce();\r\n\r\n r.sleep();\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5644897818565369, "alphanum_fraction": 0.6032652854919434, "avg_line_length": 19.67888832092285, "blob_id": "4e75f1dfc84ad84cb1fa8abf3db3002decd842af", "content_id": "050b09e0f63f4e92a3bae188625e505192b45148", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17714, "license_type": "no_license", "max_line_length": 108, "num_lines": 791, "path": "/n_object_tracking/src/viewgui.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <time.h>\r\n#include <math.h>\r\n#include <GL/glut.h>\r\n#include <GL/gl.h>\r\n#include <GL/glu.h>\r\n\r\n#include <iostream>\r\nusing namespace std;\r\n\r\n#include \"viewgui.h\"\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n#include <std_msgs/Float32.h>\r\n//各種OpenGL変数宣言\r\nint xBegin, yBegin;\t\t\t//mouseのXY座標\r\nint mButton;\t\t\t\t//mouseのClick\r\nfloat distance_gl, twist, elevation, azimuth;//カメラの回転行列\r\nfloat xOrig , yOrig, zOrig;\t\t\t\t\t//カメラの位置\r\n\r\n//Robot制御のパラメータ\r\nstruct URG urg_data;\r\n//struct OBSTACLE obst;\r\nstatic CLUSTER clust[2500];\r\nint gl_mode=0;//モードを切り替える。\r\n\r\n//double goal_x=0.0,goal_y=0.0;\r\nint mouse_flag_sub;\r\ndouble tracking_x,tracking_y;\r\n\r\nint GL_color_flg=0;\r\ndouble GL_distance_gl=10.0;\r\n\r\ndouble lrf_ave_weight=0.03;\r\ndouble lrf_ave_thresh=0.15;\r\n\r\nextern double Threshold_tracking;\r\n\t\r\nextern int traking_init;\r\ndouble target_size;\r\n\r\nextern double lost_flg_limit;\r\nextern double lost_flg_dtime;\r\n\r\n\r\n\r\nextern double target_pos_init_x;\r\nextern double target_pos_init_y;\r\nint wait_sleep(int time){\r\n\tusleep(time*1000);\r\n\treturn 0;\r\n}\r\n\r\n\r\nGraphics::Graphics(){\r\n\txOrig = 0.0, yOrig = 0.0, zOrig=0.0; //始点中心\r\n\tgui_start();\r\n\r\n}\r\n\r\nGraphics::~Graphics(){\r\n\tgui_end();\r\n}\r\nvoid my_robot(){\r\n\tdouble grid_size=0.25;\r\n\r\n\tglColor3f(0, 0.0, 1.0);\r\n//\tglBegin(GL_LINE_LOOP);\r\n//\tglVertex3f(-grid_size/2.0,-grid_size/2.0,0.0 );\r\n//\tglVertex3f(-grid_size/2.0,grid_size/2.0,0.0 );\r\n//\tglVertex3f(grid_size/2.0,grid_size/2.0,0.0 );\r\n//\tglVertex3f(grid_size/2.0,-grid_size/2.0,0.0 );\r\n//\tglEnd();\r\n\r\n\tglLineWidth(2.0);\r\n\tdouble radius=grid_size;\r\n\tglBegin(GL_LINE_LOOP);\r\n\r\n\t\tfor(double i = 0; i < 2 * PI; i += PI / 12) //<-- Change this Value\r\n\t\t\tglVertex3f(cos(i) * radius, sin(i) * radius, 0.0);\r\n\tglEnd();\r\n\r\nglLineWidth(1.0);\r\n}\r\n\r\n\r\nvoid grid(){\r\n\t//Gridの表示\r\n\tdouble grid_size=1.0;\r\n\tglColor3f(0.75, 0.75, 0.75);\r\n\tfor(double x=-20.0;x<=20.0;x+=grid_size){\r\n\t\tfor(double y=-20.0;y<=20.0;y+=grid_size){\r\n\t\t\tglBegin(GL_LINE_LOOP);\r\n\t\t\tglVertex3f(x,y,0.0 );\r\n\t\t\tglVertex3f(x+grid_size,y,0.0 );\r\n\t\t\tglVertex3f(x+grid_size,y+grid_size,0.0 );\r\n\t\t\tglVertex3f(x,y+grid_size,0.0 );\r\n\t\t\tglEnd();\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\n\r\nint lrf_averaging(struct URG &urg_data){\r\n\tstatic double urg_ave_leng[2560]={};\r\n\t/*static double urg_pro[2560]={};*/\r\n\r\n\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\tdouble length=urg_data.leng[i];\r\n\t\tif(length<urg_data.leng_min*1.2)\tlength=0;\r\n\t\tif(length>urg_data.leng_max*0.9)\tlength=0;\r\n//\t\tif(length!=0)\r\n\t\turg_ave_leng[i]=lrf_ave_weight*length+(1.0-lrf_ave_weight)*urg_ave_leng[i];\r\n\t}\r\n\r\n\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\tdouble length=urg_ave_leng[i];\r\n\t\tif(length<urg_data.leng_min*1.1)\tlength=urg_data.leng_max;\r\n\t\tif(length>urg_data.leng_max*0.9)\tlength=urg_data.leng_max;\r\n\t//\tif(fabs(urg_data.leng[i]-urg_data.leng[i+1])>lrf_ave_thresh) length=urg_data.leng_max;\r\n\r\n\r\n//\t\tif(fabs(urg_data.leng[i]-length)>urg_data.leng[i]*lrf_ave_thresh) length=urg_data.leng_max;\r\n\t/*\turg_pro[i]=length;*/\r\n\r\n\t\turg_data.leng[i]=length;\r\n\t}\r\n\r\n\r\n\treturn 0;\r\n}\r\nstatic double get_time()\r\n{\r\n struct timeval tv;\r\n gettimeofday(&tv, NULL);\r\n long double n_time = tv.tv_sec + tv.tv_usec * 1e-6;\r\n return n_time;\r\n}\r\n\r\nvoid tracking_quad(double tracking_x,double tracking_y){\r\n\tstatic double old_x=0,old_y=0;\r\n\r\n\tglColor3f(0.0, 0.6, 0.6);\r\n\tdouble dis_err=sqrt((tracking_x-old_x)*(tracking_x-old_x)+(tracking_y-old_y)*(tracking_y-old_y));\r\n\tdouble radius=dis_err;\r\n\tglBegin(GL_LINE_LOOP);\r\n\t\tfor(double i = 0; i < 2 * PI; i += PI / 12) //<-- Change this Value\r\n\t\t\tglVertex3f(tracking_x+cos(i) * radius, tracking_y+sin(i) * radius, 0.0);\r\n\tglEnd();\r\n\r\n\tglColor3f(1.0, 0.3, 0.0);\r\n\t radius=Threshold_tracking;\r\n\tglBegin(GL_LINE_LOOP);\r\n\t\tfor(double i = 0; i < 2 * PI; i += PI / 12) //<-- Change this Value\r\n\t\t\tglVertex3f(tracking_x+cos(i) * radius, tracking_y+sin(i) * radius, 0.0);\r\n\tglEnd();\r\n\r\n\tglColor3f(0.0, 0.6, 0.0);\r\n\r\n/////////////////////////////\r\n\tdouble n_time=get_time();\r\n\tstatic double o_time=n_time;\r\n\tdouble dtime=n_time-o_time;\r\n\r\n//\tcout<<\"t:\"<<tracking_x<<\"_\"<<tracking_y<<endl;\r\n//\tcout<<\"o:\"<<old_x<<\"_\"<<old_y<<endl;\r\n//\tcout<<\"lost_flg_dtime:\"<<lost_flg_dtime<<\"_\"<<endl;\r\n//\tcout<<\"dtime:\"<<dtime<<\"_\"<<endl;\r\n\r\n\tif((tracking_x==old_x)&&(tracking_y==old_y)) {\r\n\t\tlost_flg_dtime+=dtime;\r\n//\t\tcout<<\"lost:\"<<lost_flg_dtime<<\"_\"<<endl;\r\n\t}\r\n\telse {\r\n\t\t\tlost_flg_dtime=0.0;\r\n\t}\t\r\n\to_time=n_time;\r\n\r\n\tif(lost_flg_dtime>lost_flg_limit)\tglColor3f(1.0, 0.0, 0.0);\r\n\telse \tglColor3f(0.0, 1.0, 0.0);\r\n\r\n\r\n\tglLineWidth(2.0);\r\n\tdouble quad_size=0.25;\r\n\tglBegin(GL_LINE_LOOP);\r\n\tglVertex3f(tracking_x-quad_size,tracking_y-quad_size,0 );\r\n\tglVertex3f(tracking_x+quad_size,tracking_y-quad_size,0 );\r\n\tglVertex3f(tracking_x+quad_size,tracking_y+quad_size,0 );\r\n\tglVertex3f(tracking_x-quad_size,tracking_y+quad_size,0 );\r\n\tglEnd();\r\n\tglLineWidth(1.0);\r\n\r\n\r\n/////////////////////////////\r\n\told_x=tracking_x;\r\n\told_y=tracking_y;\r\n\tlong log_num=200;\r\n\tstatic double tracking_log_x[1000]={};\r\n\tstatic double tracking_log_y[1000]={};\r\n\tstatic int tracking_log_cnt=0;\r\n\r\n\ttracking_log_x[tracking_log_cnt]=tracking_x;\r\n\ttracking_log_y[tracking_log_cnt]=tracking_y;\r\n\t\r\n\tfor(int i=0;i<log_num-1;i++){\r\n\t\tif((i!=tracking_log_cnt+1)&&(tracking_log_x[i-1]!=0)){\r\n\r\n\t\tglBegin(GL_LINES);\r\n\t\tglVertex3f(tracking_log_x[i-1],tracking_log_y[i-1],0 );\r\n\t\tglVertex3f(tracking_log_x[i],tracking_log_y[i],0 );\r\n\t\tglEnd();\r\n\t\t}\r\n\t}\r\n\r\n\ttracking_log_cnt++;\r\n\tif(tracking_log_cnt>log_num)\ttracking_log_cnt=0;\r\n\r\n\r\n\r\n\r\n\r\n}\r\n\r\n\r\nint tracking_main(){\r\n\r\n\tint clust_no=0;\r\n\t//lrf_averaging(urg_data);\r\n\tif(traking_init==1)\t{\r\n\ttracking_x=target_pos_init_x;\r\n\ttracking_y=target_pos_init_y;\r\n\tLRF_clustring_main(urg_data,clust);\r\n\tLRF_clustring_tracking( clust,tracking_x,tracking_y,true,clust_no);\r\ntraking_init=0;\r\n\t}\r\n\telse{\r\n\tLRF_clustring_main(urg_data,clust);\r\n\tLRF_clustring_tracking( clust,tracking_x,tracking_y,mouse_flag_sub,clust_no);\r\n\t}\r\n\r\n\ttarget_size=clust[clust_no].dis;\r\n\r\n}\r\n\r\nint main_process(){\r\n for(;;){\r\n\ttracking_main();\r\n\r\n wait_sleep(5);\r\n\r\n }\r\n\r\n}\r\n\r\nvoid Graphics::main_draw() {\r\n\t//URGのレーザーの表示\r\n\tglColor3f(0.0, 0.05, 1.0); \r\n\tglPointSize(3);\r\n\r\n\tdraw_string(\"object_traking:\");\r\n\r\n\r\n\ttracking_quad(tracking_x,tracking_y);\r\n\r\n\tif(GL_color_flg==1){\r\n\t\tlrf_clust_view(urg_data,clust);\r\n\t}\r\n\telse{\r\n\r\n\t\tglColor3f(1.0, 0.0, 0.0); \r\n\t\tglPointSize(3);\r\n\t\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\t\tdouble length=urg_data.leng[i];\r\n\t\t\tif((length>urg_data.leng_min)&&(length<urg_data.leng_max)){\r\n\t\t\t\tdouble xx=(-1)*length*sin(i*urg_data.reso+urg_data.start_rad);\r\n\t\t\t\tdouble yy=length*cos(i*urg_data.reso+urg_data.start_rad);\r\n\t\t\t\tglBegin(GL_POINTS);\r\n\t\t\t\tglVertex3f(xx,yy,0 );\r\n\t\t\t\tglEnd();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tgrid();\r\n\tmy_robot();\r\n wait_sleep(10);\r\n\r\n\treturn;\r\n} \r\n\r\n\r\nvoid Graphics::display(){\r\n\r\n\tglClearColor(1 , 1 , 1 , 1.0);\r\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); \r\n\tglEnable(GL_DEPTH_TEST);\r\n// glEnable( GL_POINT_SMOOTH );\r\n//\tglEnable(GL_PROGRAM_POINT_SIZE);\r\n\r\n\tglPushMatrix ();\r\n\tpolarview();\r\n\t\r\n\t//メイン描画の関数\r\n\tmain_draw();\r\n\r\n\tglPopMatrix();\r\n\tglutSwapBuffers(); \r\n\tglutPostRedisplay();\r\n\r\n\tusleep(10*1000);\r\n\r\n}\r\n\r\nvoid Graphics::idle(void)\r\n{ \r\n\tglutPostRedisplay();\r\n#ifdef _WIN32\r\n\tSleep(10);\r\n#else\r\n\tusleep(10*1000);\r\n#endif\r\n}\r\n\r\nvoid Graphics::myInit(char *progname)\r\n{\r\n\tfloat aspect = (float) WIDTH / (float) HEIGHT;\r\n\r\n\tglutInitWindowPosition(0, 0);\r\n\tglutInitWindowSize( WIDTH, HEIGHT);\r\n\tglutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA| GLUT_DEPTH);\r\n\tglutCreateWindow(progname);\r\n\tglClearColor (0, 0, 0, 1.0);\r\n\r\n\r\n\tglutKeyboardFunc( myKbd );\r\n\tglutKeyboardUpFunc( myKbdup );\r\n\tglutSpecialFunc( mySkey );\r\n\r\n\tglutMouseFunc(myMouse);\r\n\tglutMotionFunc(myMotion);\r\n\tresetview();\r\n\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglLoadIdentity();\r\n\tgluPerspective(45.0, aspect, 0.010, 50.0);//画角等視野の設定\r\n\tglMatrixMode(GL_MODELVIEW);\r\n}\r\n\r\nvoid Graphics::reshape(int ,int)\r\n{\r\n\t//glutReshapeWindow( WIDTH, HEIGHT );\r\n}\r\n\r\nint Graphics::GUImain(){ \r\n//\tread_obstacle(\"obstacle.csv\",obst);\r\n\tint argc= 3;\r\n\tchar *argv[] ={\"program\", \"-display\", \":0.0\"};\r\n\tglutInit ( &argc, argv );\r\n\r\n\tchar *win_name=\"lrf_tracking\";\r\n\tmyInit(win_name);\r\n\tglutDisplayFunc(display);\r\n\tglutReshapeFunc(reshape);\r\n\r\n\tglutIdleFunc(idle);\r\n\tglutMainLoop();\r\n\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid Graphics::gui_start(){\r\n th2 = SDL_CreateThread((int (*)(void *))main_process, this);\r\n\tth1 = SDL_CreateThread((int (*)(void *))GUImain,this);\r\n\t//usleep(1000*1000);\r\n\t//th2 = SDL_CreateThread((int (*)(void *))tracking_main,this);\r\n}\r\n\r\n\r\nvoid Graphics::gui_end(){\r\n\tSDL_KillThread(th1);\r\n//SDL_KillThread(th2);\r\n}\r\n\r\ndouble Graphics::timer_ms() {\r\n\r\n\tdouble timer_ms = cv::getTickCount();\r\n\treturn timer_ms;\r\n\r\n} \r\n\r\n\r\n\r\nvoid Graphics::myMouse( int button, int state, int x, int y ){\r\n\tmouse_flag_sub=false;\r\n\tdouble obj_x=0,obj_y=0,obj_z=0;\r\n\r\n\tif (state == GLUT_DOWN) {\r\n\t\tswitch(button) {\r\n\t\tcase GLUT_LEFT_BUTTON:\r\n\t\t\tmButton = button;\r\n\t\t\t//click_pickup(x,y,obj_x,obj_y,obj_z);\r\n\t\t\t//tracking_y=obj_y;\r\n\t\t\t//tracking_x=obj_x;\r\n\t\t\tbreak;\r\n\t\tcase GLUT_MIDDLE_BUTTON:\r\n\r\n\t\t\tbreak;\r\n\t\tcase GLUT_RIGHT_BUTTON:\r\n\t\t\tmouse_flag_sub=true; \r\n\t\t\tmButton = button;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\txBegin = x;\r\n\t\tyBegin = y;\r\n\t}\r\n\tif (state == GLUT_UP) {\r\n\t\tswitch(button) {\r\n\tcase GLUT_RIGHT_BUTTON:\r\n\t\tmouse_flag_sub=false; \r\n\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\treturn ;\r\n}\r\n\r\n\r\nvoid Graphics::myMotion( int x, int y )\r\n{\r\n\r\n\tint xDisp, yDisp;\r\n\r\n\txDisp = x - xBegin;\r\n\tyDisp = y - yBegin;\r\n\r\n\tswitch (mButton) {\r\n\tcase GLUT_LEFT_BUTTON:\r\n\t\t//azimuth -= (float) xDisp/2.0;\r\n\t\t//elevation -= (float) yDisp/2.0;\r\n\t\txOrig += (float) xDisp/20.0;\r\n\t\tzOrig -= (float) yDisp/20.0;\r\n\r\n\t\tbreak;\r\n\tcase GLUT_RIGHT_BUTTON:\r\n\t\t//distance_gl -= (float) xDisp/10.0;\r\n\t\t//if(distance_gl<0.000001)distance_gl=0.000001;\r\n\t\ttracking_x += (float) xDisp/10.0;\r\n\t\ttracking_y -= (float) yDisp/10.0;\r\n\t\tbreak;\r\n\t}\r\n\txBegin = x;\r\n\tyBegin = y;\r\n\r\n\r\n\tglutPostRedisplay();\r\n}\r\n\r\n\r\nvoid Graphics::myKbdup( unsigned char key, int x, int y )\r\n{\r\n\r\n\tswitch( key ) {\r\n\r\ncase 'w':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\t\tmyrobot.v=0.0;\r\n\tbreak;\r\ncase 's':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\t\tmyrobot.v=-0.0;\r\n\tbreak;\r\ncase 'a':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\t\tmyrobot.w=-0.0;\r\n\tbreak;\r\ncase 'd':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\t\tmyrobot.w=+0.0;\r\n\tbreak;\r\n\r\n\r\n\r\n\t}\r\n\r\n}\r\nvoid Graphics::myKbd( unsigned char key, int x, int y )\r\n{\r\n\tswitch( key ) {\r\ncase 0x1B:\t//終了\r\n//\texit(0);\r\n\tbreak;\r\n\r\ncase 'q':\t//視点をリセット\r\n//\texit(0);;\r\n\tbreak;\r\n\r\ncase 'z':\t//視点をリセット\r\n\r\n\r\n\tbreak;\r\ncase 'x':\t//視点をリセット\r\n\r\n\r\n\tbreak;\r\n\r\ncase 'w':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\t\tmyrobot.v=0.30;\r\n\r\n\tbreak;\r\ncase 's':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\tmyrobot.v=-0.30;\r\n\tbreak;\r\ncase 'a':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\tmyrobot.w=-0.10;\r\n\tbreak;\r\ncase 'd':\t//ROBOTの移動指令\r\n//\tif(gl_mode==0)\tmyrobot.w=+0.10;\r\n\tbreak;\r\n\r\n\t}\r\n}\r\n\r\n\r\n\r\nvoid Graphics::mySkey( int key, int x, int y )\r\n{\r\n\tswitch( key ) {\r\n\tcase GLUT_KEY_LEFT:\r\n\t\txOrig -= 0.2;\r\n\t\tbreak;\r\n\tcase GLUT_KEY_RIGHT:\r\n\t\txOrig += 0.2;\r\n\t\tbreak;\r\n\tcase GLUT_KEY_UP:\r\n\t\tzOrig += 0.2;\r\n\t\tbreak; \r\n\tcase GLUT_KEY_DOWN:\r\n\t\tzOrig -= 0.2;\r\n\t\tbreak;\r\n\tcase GLUT_KEY_PAGE_UP:\r\n\t\tyOrig += 0.5;\r\n\t\tbreak;\r\n\tcase GLUT_KEY_PAGE_DOWN:\r\n\t\tyOrig -= 0.5;\r\n\t\tbreak;\r\n\r\n\t}\r\n\tglutPostRedisplay();\r\n}\r\n\r\n\r\nvoid Graphics::resetview( void )\r\n{\r\n\tdistance_gl = GL_distance_gl;\r\n\ttwist = 0.0;\r\n\televation = 0.0;\r\n\tazimuth = 0.0;\r\n}\r\n\r\n\r\n\r\nvoid Graphics::polarview( void )\r\n{\r\n\t//マウスで移動\r\n\tglTranslatef( 0.0, 0.0, -distance_gl);\r\n\tglRotatef( -twist, 0.0, 0.0, 1.0);\r\n\tglRotatef( -elevation, 1.0, 0.0, 0.0);\r\n\tglRotatef( -azimuth, 0.0, 1.0, 0.0);\r\n\t//キーボードで移動\r\n\tglTranslatef(xOrig,zOrig ,yOrig);\r\n}\r\n\r\nfloat Graphics::click_Depth(int x, int y){//マウスのX/Y座標からDepthを算出\r\n\tfloat z;\r\n\tGLint viewport[4]; //ビューポート\r\n\t//デバイス座標系とウィンドウ座標系の変換\r\n\tglGetIntegerv(GL_VIEWPORT,viewport); //現在のビューポートを代入\r\n\tglReadPixels(x,viewport[3]-y,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&z);\r\n\t// デプスバッファの値を返す.\r\n\treturn z;\r\n}\r\n\r\nvoid Graphics::click_pickup(int x,int y,double &ax,double &ay,double &az){//マウスのX/Y座標からX/Y/Z座標を算出\r\n\tGLdouble modelview[16];\r\n\tGLdouble projection[16];\r\n\tGLint viewport[4];\r\n\tglGetDoublev(GL_MODELVIEW_MATRIX,modelview);\r\n\tglGetDoublev(GL_PROJECTION_MATRIX,projection);\r\n\tglGetIntegerv(GL_VIEWPORT,viewport);\r\n\tGLdouble winX, winY, winZ;\r\n\tGLdouble objX=0.0,objY=0.0,objZ=-distance_gl+yOrig;\r\n\r\n\t//原点のGLUT座標系を算出\r\n\tgluProject(objX,objY,objZ,modelview,projection,viewport,&winX,&winY,&winZ);\r\n\tGLdouble objX1,objY1,objZ1;\r\n\t//gluUnProject((double)x,(double)y,0.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n\t//cout<<\"near_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\r\n\t//gluUnProject((double)x,(double)y,1.0,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n\t//cout<<\"far_window:\"<<objX1<<\"\\t\"<<objY1<<\"\\t\"<<objZ1<<\"\\t\"<<endl;\r\n\t\r\n\tgluUnProject((double)x,(double)y,winZ,modelview,projection,viewport,&objX1,&objY1,&objZ1);\r\n\tax=objX1-xOrig;\r\n\tay=-(objY1+zOrig);\r\n\taz=objZ1-yOrig;\r\n\r\n\t//cout<<\"mouse_click:\"<<\"\\t X:\"<<x<<\"\\t Y:\"<<y<<\"\\t x:\"<<ax<<\"\\t y:\"<<ay<<\"\\t z:\"<<az<<\"\"<<endl;\r\n\r\n\treturn;\r\n}\r\n\r\n\r\nvoid draw_string(string str, int w, int h, int x0, int y0)\r\n{\r\n\tglColor3d(0.0, 0.60, 0.0);\r\n\t// glDisable(GL_LIGHTING);\r\n\t// 平行投影にする\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglPushMatrix();\r\n\tglLoadIdentity();\r\n\tgluOrtho2D(0, w, h, 0);\r\n\tglMatrixMode(GL_MODELVIEW);\r\n\tglPushMatrix();\r\n\tglLoadIdentity();\r\n\r\n\t// 画面上にテキスト描画\r\n\tglRasterPos2f(x0, y0);\r\n\tint size = (int)str.size();\r\n\tfor(int i = 0; i < size; ++i){\r\n\t//\tchar ic = str[i];\r\n\t//\tglutBitmapCharacter(GLUT_BITMAP_9_BY_15, ic);\r\n\t}\r\n\r\n\tglPopMatrix();\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglPopMatrix();\r\n\tglMatrixMode(GL_MODELVIEW);\r\n}\r\n\r\nvoid lrf_clust_view(URG &urg_data,CLUSTER clust[]){\r\n\r\n\r\n\r\n //結果の表示\r\n glPointSize(2); \r\n for(int i=0;i<clust[0].clnum;i++){\r\n\r\n\t\tif(i%8==0) glColor3f(0.5,0.5,0.50);\r\n\t\telse if(i%7==0) glColor3f(0,0.5,0.5);\r\n\t\telse if(i%6==0) glColor3f(0.5,0.6,0);\r\n\t\telse if(i%5==0) glColor3f(0,1,0);\r\n\t\telse if(i%4==0) glColor3f(0,0,1);\r\n\t\telse if(i%3==0) glColor3f(1,1,0);\r\n\t\telse if(i%2==0) glColor3f(1,0,1);\r\n\t\telse if(i%1==0) glColor3f(0,1,1);\r\n\t\t\r\n\r\n\t\tfor(int j=0;j<clust[i].ptnum;j++){\r\n\t\t\tglBegin(GL_POINTS);\r\n\t\t\tdouble x=clust[i].x[j];\r\n\t\t\tdouble y=clust[i].y[j];\r\n\t\t\tglVertex2f(x,y);\r\n\t\t\tglEnd();\r\n\t\t}\r\n\t}\r\n\r\n glPointSize(1); \r\n}\r\n\r\n\r\nvoid lrf_clust_view_for_slam(URG &urg_data,CLUSTER clust[]){//クラスタリングの可視化\r\n\r\n //クラスタ後の点群表示\r\n glPointSize(2); \r\n for(int i=0;i<clust[0].clnum;i++){\r\n\t\tif(i%8==0) glColor3f(0.5,0.5,0.50);\r\n\t\telse if(i%7==0) glColor3f(0,0.5,0.5);\r\n\t\telse if(i%6==0) glColor3f(0.5,0.6,0);\r\n\t\telse if(i%5==0) glColor3f(0,1,0);\r\n\t\telse if(i%4==0) glColor3f(0,0,1);\r\n\t\telse if(i%3==0) glColor3f(1,1,0);\r\n\t\telse if(i%2==0) glColor3f(1,0,1);\r\n\t\telse if(i%1==0) glColor3f(0,1,1);\r\n\t\tfor(int j=0;j<clust[i].ptnum;j++){\r\n\t\t\tglBegin(GL_POINTS);\r\n\t\t\tdouble x=clust[i].x[j];\r\n\t\t\tdouble y=clust[i].y[j];\r\n\t\t\tglVertex2f(x,y);\r\n\t\t\tglEnd();\r\n\t\t}\r\n\t}\r\n\r\n glPointSize(5); \r\n\r\n\tglColor3f(1,0,0);\r\n\tglBegin(GL_POINTS);\r\n\tfor(int i=0;i<clust[0].clnum;i++){\r\n\t\tdouble x=clust[i].x_ave;\r\n\t\tdouble y=clust[i].y_ave;\r\n\t\tglVertex2f(x,y);\r\n\t\tx=clust[i].x[0];\r\n\t\ty=clust[i].y[0];\r\n\t\tglVertex2f(x,y);\r\n\t\tx=clust[i].x[clust[i].ptnum];\r\n\t\ty=clust[i].y[clust[i].ptnum];\r\n\t\tglVertex2f(x,y);\r\n\t}\r\n\tglEnd();\r\n glPointSize(10); \r\n\r\n\r\n\tdouble clust_x[1000]={};\r\n\tdouble clust_y[1000]={};\r\n\r\n\tfor(int i=0;i<clust[0].clnum;i++){\r\n\t\tfor(int j=0;j<clust[i].ptnum;j++){\r\n\t\t\tclust_x[j]=clust[i].x[j];\r\n\t\t\tclust_y[j]=clust[i].y[j];\r\n\t\t}\r\n\t\tsplit_of_merge(clust_x,clust_y,clust[i].ptnum);\r\n\t}\r\n\r\n\r\n\tglPointSize(1); \r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\nvoid split_of_merge(double clust_x[],double clust_y[],int data_num){\r\n\tint split_num=0;\r\n\tstd::vector<int> split_num_mat;\r\n\tsplit_num_mat.push_back(split_num);\r\n\tsplit_num_mat.push_back(data_num-1);\r\n\r\n\r\n\tfor(int nn=1;nn<100;nn++){\r\n\t\tif(split_num_mat.size()==nn){\r\n\t\t\tfor(int mm=0;mm+1<nn;mm++)\t\t{\r\n\t\t\t\tsp_merge_cal(split_num_mat,split_num_mat[mm],split_num_mat[mm+1],clust_x,clust_y);\r\n\t\t\t//\tcout<<nn<<\"\\t\"<<mm<<endl;\r\n\t\t\t}\r\n\t\t\tstd::sort(split_num_mat.begin(), split_num_mat.end() );\r\n\t\t}\r\n\t}\r\n\r\n\tglPointSize(10); \r\n\tglColor3f(0.4,1,0);\r\n\r\n\tfor(int i=0;i<split_num_mat.size();i++){\r\n\t\tint split_num=split_num_mat[i];\r\n\r\n\t\tglBegin(GL_POINTS);\r\n\t\tdouble x=clust_x[split_num];\r\n\t\tdouble y=clust_y[split_num];\r\n\t\tglVertex2f(x,y);\r\n\t\tglEnd();\r\n\t\t//cout<<split_num_mat.size()<<\"\\t\"<<endl;\r\n\t\t//cout<<\"\\t\"<<x<<\"\\t\"<<y<<\"\\t\"<<endl;\r\n\t}\r\n\r\n\treturn;\r\n}\r\n\r\nint sp_merge_cal(std::vector<int> &split_num_mat,int start_no,int end_no,double clust_x[],double clust_y[]){\r\n\tconst double D_thresh=1.00;\r\n\t\r\n\tdouble d_max=0.0;\r\n\tint split_num=0;\r\n\tdouble start_x=clust_x[start_no];\r\n\tdouble start_y=clust_y[start_no];\r\n\tdouble end_x=clust_x[end_no-1];\r\n\tdouble end_y=clust_y[end_no-1];\r\n\r\n\tfor(int i=start_no;i<end_no;i++){\r\n\t\tdouble dd=line_seg_point_distance(clust_x[i],clust_y[i],start_x,start_y,end_x,end_y);\r\n\t\tif(dd>d_max){\r\n\t\t\td_max=dd;\r\n\t\t\tsplit_num=i;\r\n\t\t}\r\n\t}\r\n\tif((d_max<=D_thresh)||(split_num==0)) return 1;\t\t//Splitする必要なし\r\n\telse{\r\n\t\tsplit_num_mat.push_back(split_num);\r\n\t\treturn 0;\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.7381818294525146, "alphanum_fraction": 0.7418181896209717, "avg_line_length": 53.400001525878906, "blob_id": "fdf690145f826579cc3fff6948b27f45db1c987f", "content_id": "55443306f07249b9baa3f462c9471dc3f4e56d5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 275, "license_type": "no_license", "max_line_length": 96, "num_lines": 5, "path": "/robo_launch/mapsaver.sh", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "cd /home/iqit/catkin_me/src/\nrosservice call /finish_trajectory 0\nrosservice call /write_state ${HOME}/catkin_me/src/data_map/map.pbstream\nrosservice call /write_state ${HOME}/catkin_me/src/data_map/map_`date \"+%Y%m%d_%H%M%S\"`.pbstream\nrosrun n_map_saver n_map_saver_node\n\n\n\n" }, { "alpha_fraction": 0.6371681690216064, "alphanum_fraction": 0.6703540086746216, "avg_line_length": 19.522727966308594, "blob_id": "eebaef6a9bcbfca0afbd4f61dafd94f7934265a4", "content_id": "f993426de411371cb8fd3c7a9df36b67b6237c61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 80, "num_lines": 44, "path": "/n_joy2cmd/readme.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "JOYSTICK TO CMD ノード\n\nrosnode info /n_joy2cmd \n--------------------------------------------------------------------------------\nNode [/n_joy2cmd]\nPublications: \n * /button1 [std_msgs/Int16]\n * /button3 [std_msgs/Int16]\n * /button2 [std_msgs/Int16]\n * /button5 [std_msgs/Int16]\n * /button4 [std_msgs/Int16]\n * /button6 [std_msgs/Int16]\n * /cmd_vel [geometry_msgs/Twist]\n * /rosout [rosgraph_msgs/Log]\n\nSubscriptions: \n * /cmd_vel4 [unknown type]\n * /cmd_vel2 [geometry_msgs/Twist]\n * /joy [sensor_msgs/Joy]\n\nbutton5:自陣に戻る\nbutton1:joystick動作\nbutton2:LRFトラッキング\nbutton4:LRF初期化\nbutton3:\n\n事前:\n・ジョイパッド用ROSパッケージのインストール\n $ sudo apt-get install joystick jstest-gtk\n $ sudo apt-get install ros-indigo-joystick-drivers\n\n・コントローラを接続しjoystickの番号確認\n $ jstest /dev/input/js0\n\n $rosrun joy joy_node\n\n\n使い方:\n$make\n$./docu_joy_to_cmd\n\nボタン0をおしながらでJOYTSTICKでうごく(マニュアル動作)\nボタン1をおしながらでJOYTSTICKでうごく(強制停止)\n上記意外だと、上位TWISTを受信して出力\n\n" }, { "alpha_fraction": 0.6431947350502014, "alphanum_fraction": 0.6616256833076477, "avg_line_length": 23.80487823486328, "blob_id": "48b622255a00667b8ed6113174efa31590320808", "content_id": "8b1594d4ff6e513af3eb6a50fabcf7976519ef1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6432, "license_type": "no_license", "max_line_length": 107, "num_lines": 246, "path": "/n_object_tracking/src_error/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n\r\n#include \"viewgui.h\"\r\n//#include \"read_file.h\"\r\n#include <math.h>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <limits>\r\nusing namespace std;\r\n#include <ctime>\r\n\r\n//Robot制御のパラメータ\r\n//extern struct ROBOT myrobot;\r\nextern struct URG urg_data;\r\n\r\n\r\ndouble danger_dis=0.5;\r\nint danger_count_thresh=300;\r\nint danger_count=0;\r\nbool danger_flg=0;\r\n\r\n\r\n#include <sys/time.h>\r\n#include <unistd.h>\r\n#include <ros/ros.h>\r\n#include <visualization_msgs/Marker.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <geometry_msgs/Pose.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n#include <std_msgs/Int16.h>\r\n#include <signal.h>\r\n\r\n//int load_config(string);\r\n\r\nvoid mySigintHandler(int);\r\n\r\nextern double LRF_clustring_Threshold_percent;\t//クラスタリングの距離閾値[%]\r\nextern double LRF_clustring_Threshold_dis;\t\t//クラスタリングの距離閾値[m]\r\nextern double LRF_clustring_min_num;\t\t\t\t\t//小さいクラスタを除去\r\nextern double Threshold_tracking;\r\nextern int GL_color_flg;\r\nextern double GL_distance_gl;\r\n//extern double robot_speed;\r\n//extern double robot_turn;\r\n\r\nextern double tracking_x,tracking_y;\r\n//extern double m_accelerate_mps;\r\n//extern double m_accelerate_rps;\r\nextern double lrf_ave_weight;\r\nextern double lrf_ave_thresh;\r\nint traking_init=0;\r\n\r\ndouble lost_flg_limit;\r\ndouble lost_flg_dtime;\r\nstring scan_topic;\r\nros::Publisher target_pos;\r\n\r\n double target_pos_init_x;\r\n double target_pos_init_y;\r\n\r\n\r\nvoid mySigintHandler(int sig) {\r\n\tgeometry_msgs::Pose target;\r\n\r\n\ttarget.position.x=0.0;\r\n\ttarget.position.y=0.0;\r\n\r\n\ttarget_pos.publish(target);\r\n\r\n\r\n printf(\"shutdown catch signal %d \\n\", sig);\r\n ros::shutdown();\r\n}\r\n\r\n\r\nvoid scanCallback (const sensor_msgs::LaserScanConstPtr & scan_msg){\r\n\tdouble range_min = scan_msg->range_min;\r\n\tdouble range_max = scan_msg->range_max;\r\n\tdouble angle_increment = scan_msg->angle_increment;\r\n\tdouble angle_min = scan_msg->angle_min ;\r\n\tdouble angle_max=scan_msg->angle_max;\r\n\tdanger_count=0;\r\n\r\n\r\n\tint data_num=(angle_max-angle_min)/angle_increment;\r\n\t// TODO - also copy intensity values\r\n\r\n\tfor(unsigned int i = 0; i < data_num; ++i){\r\n\t\turg_data.leng[i]=scan_msg->ranges[i];\r\n\t\t//\tif(isnan(urg_data.leng[i]))urg_data.leng[i]=range_max;\r\n\t\tif(isnan(urg_data.leng[i]))\turg_data.leng[i]=0.0;\r\n\t\telse if(urg_data.leng[i]<scan_msg->range_min)\turg_data.leng[i]=0.0;\r\n\t\telse if(urg_data.leng[i]>scan_msg->range_max)\turg_data.leng[i]=0.0;\r\n\t\telse if(urg_data.leng[i]<danger_dis)danger_count++;\r\n\t}\r\n\r\n\tif(danger_count>danger_count_thresh)danger_flg=1;\r\n\telse danger_flg=0;\r\n\r\n\t//cout<<danger_count<<endl;\r\n\turg_data.data_num=data_num;\r\n\turg_data.start_rad=scan_msg->angle_min;\r\n\turg_data.reso=scan_msg->angle_increment;\r\n\r\n\turg_data.leng_max=range_max;\r\n\turg_data.leng_min=range_min;\r\n}\r\n\r\n\r\n\r\nvoid joyCallback(const std_msgs::Int16::ConstPtr& msg){\r\n //ROS_INFO(\"I heard: [%ld]\", msg->data);\r\n\t//std::cout<<msg->data<<std::endl;\r\n\ttraking_init=0;\r\n\tif(msg->data==1){\r\n\t\ttraking_init=1;\r\n\t}\r\n\treturn;\r\n}\r\n\r\nvoid target_pos_initCallback(const geometry_msgs::Pose::ConstPtr& msg){\r\n\ttarget_pos_init_x=msg->position.x;\r\n\ttarget_pos_init_y=msg->position.y;\r\n\r\n\treturn;\r\n}\r\n\r\n\r\nint main(int argc, char* argv[]) {\r\n\r\n//\tstring fname=\"setting.ini\";\r\n//\tstring exe_name=argv[0];\r\n//\tload_config(exe_name+\"_\"+fname);\r\n\tGraphics GL;\r\n\r\n\tros::init(argc, argv, \"n_object_tracking\");\r\n\tconst std::string scan_topic_ = \"scan1\";\r\n\r\n\r\n\tros::NodeHandle nh_;\r\n\r\n\tros::Subscriber scan_subscriber_ = nh_.subscribe (scan_topic_, 10, scanCallback);\r\n\tros::Subscriber joy_subscriber = nh_.subscribe(\"button2\", 10, joyCallback);\r\n\tros::Subscriber target_pos_init_subscriber = nh_.subscribe(\"target_pos_init\", 1, target_pos_initCallback);\r\n\r\n\tros::NodeHandle private_nh(\"~\");\r\n\tprivate_nh.param(\"LRF_clustring_Threshold_percent\",LRF_clustring_Threshold_percent,\t0.1);\r\n\tprivate_nh.param(\"LRF_clustring_Threshold_dis\",LRF_clustring_Threshold_dis,\t0.1);\r\n\tprivate_nh.param(\"LRF_clustring_min_num\",LRF_clustring_min_num,\t5.0);\r\n\r\n\tprivate_nh.param(\"Threshold_tracking\",\tThreshold_tracking,\t0.050);\r\n\tprivate_nh.param(\"GL_color_flg\",\t\tGL_color_flg,\t1);\r\n\tprivate_nh.param(\"GL_distance_gl\",\t\tGL_distance_gl,\t5.0);\r\n\r\n\tprivate_nh.param(\"danger_dis\",\tdanger_dis,\t0.3);\r\n\tprivate_nh.param(\"danger_count_thresh\",\tdanger_count_thresh,\t200);\r\n\r\n\tprivate_nh.param(\"lost_flg_limit_time\",\tlost_flg_limit,\t2.0);\r\n\tprivate_nh.param(\"lrf_ave_weight\",\tlrf_ave_weight,\t0.10);\r\n\tprivate_nh.param(\"lrf_ave_thresh\",\tlrf_ave_thresh,\t0.20);\r\n\r\n\ttarget_pos_init_x=0.0;\r\n\ttarget_pos_init_y=0.5;\r\n\r\n\r\n\t//ros::Publisher target_pos;\r\n\ttarget_pos = nh_.advertise<geometry_msgs::Pose>(\"/target_pos\", 10);\r\n\tgeometry_msgs::Pose target;\r\n\r\n\tros::Rate r(25.0);\r\n\ttarget.position.x=0;\r\n\ttarget.position.y=0;\r\n\ttarget.position.z=0;\r\n\r\n\r\n \tros::Publisher marker_pub = nh_.advertise<visualization_msgs::Marker>(\"target_marker\", 1);\r\n \tuint32_t shape = visualization_msgs::Marker::CUBE;\r\n\r\n \tsignal(SIGINT, mySigintHandler);\r\n\r\n\tcout<<\"n_object_tracking\"<<endl;\r\n\twhile(nh_.ok()){\r\n\t\tros::spinOnce();\r\n\r\n\t\ttarget.position.x=tracking_x;\r\n\t\ttarget.position.y=tracking_y;\r\n\r\n\t\tif(danger_flg==1){\r\n\t\ttarget.position.x=0.0;\r\n\t\ttarget.position.y=0.0;\r\n\t\t}\r\n\r\n\t\tif(lost_flg_dtime>lost_flg_limit)\t{\r\n\t\ttarget.position.x=0.0;\r\n\t\ttarget.position.y=0.0;\r\n\t\t}\r\n\r\n\t\ttarget_pos.publish(target);\r\n\r\n\r\n\t\tvisualization_msgs::Marker marker;\r\n\t\tmarker.header.frame_id = \"/base_link\";\r\n\t\tmarker.header.stamp = ros::Time::now();\r\n\t\tmarker.ns = \"basic_shapes\";\r\n\t\tmarker.id = 0;\r\n\t\tmarker.type = shape;\r\n\t\tmarker.action = visualization_msgs::Marker::ADD;\r\n\r\n\t\tmarker.pose.position.x = tracking_y;\r\n\t\tmarker.pose.position.y = -tracking_x;\r\n\t\tmarker.pose.position.z = 0.75;\r\n\t\tmarker.pose.orientation.x = 0.0;\r\n\t\tmarker.pose.orientation.y = 0.0;\r\n\t\tmarker.pose.orientation.z = 0.0;\r\n\t\tmarker.pose.orientation.w = 1.0;\r\n\r\n\t\tmarker.scale.x = 0.30;\r\n\t\tmarker.scale.y = 0.30;\r\n\t\tmarker.scale.z = 1.50;\r\n\r\n\t\tmarker.color.r = 0.0f;\r\n\t\tmarker.color.g = 1.0f;\r\n\t\tmarker.color.b = 0.0f;\r\n\t\tmarker.color.a = 1.0;\r\n \tmarker.lifetime = ros::Duration();\r\n\r\n \tmarker_pub.publish(marker);\r\n\r\n\t\tr.sleep();\r\n\t}\r\n\r\n\t//ros::spin();\r\n\r\n\r\n\treturn 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.5649999976158142, "avg_line_length": 27.14285659790039, "blob_id": "da3c837b38c0885e7fe4dc96a1e7b4f5c59fbc7e", "content_id": "4c27a029888962b5dfee757343070551d81b712b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 200, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/n_3d_robot_sim/src/opencv_inc.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <time.h>\nusing namespace cv;\n\n\n\n" }, { "alpha_fraction": 0.6367027163505554, "alphanum_fraction": 0.647519588470459, "avg_line_length": 23.29245376586914, "blob_id": "b98f6e4cc83a0dd7e9f5302270d325bb1e57b642", "content_id": "3755edc7d366fc55c5f515d52ee2e3faf246d9a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2697, "license_type": "no_license", "max_line_length": 105, "num_lines": 106, "path": "/n_lrf_view/src/gl_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n\r\n#include \"viewgui.h\"\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\n#include <ctime>\r\nusing namespace std;\r\n\r\n//Robot制御のパラメータ\r\n//extern struct ROBOT myrobot;\r\nextern struct URG urg_data;\r\n\r\n#ifdef _WIN32\r\n#include <windows.h>\r\n#pragma comment(linker, \"/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup\") \r\n#else\r\n#include <sys/time.h>\r\n#include <unistd.h>\r\n#include <ros/ros.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n\r\n\r\n\r\nvoid scanCallback (const sensor_msgs::LaserScanConstPtr & scan_msg){\r\n\tdouble range_min = scan_msg->range_min;\r\n\tdouble range_max = scan_msg->range_max;\r\n\tdouble angle_increment = scan_msg->angle_increment;\r\n\tdouble angle_min = scan_msg->angle_min ;\r\n\tdouble angle_max=scan_msg->angle_max;\r\n\r\n\r\n\tint data_num=(angle_max-angle_min)/angle_increment;\r\n // TODO - also copy intensity values\r\n\r\n\tfor(unsigned int i = 0; i < data_num; ++i){\r\n\t urg_data.leng[i]=scan_msg->ranges[i];\r\n\tif(isnan(urg_data.leng[i]))urg_data.leng[i]=range_max;\r\n\t}\r\n\r\n\turg_data.data_num=data_num;\r\n\turg_data.start_rad=scan_msg->angle_min;\r\n\turg_data.reso=scan_msg->angle_increment;\r\n\r\n}\r\n#endif\r\n\r\n\r\n\r\nint main(int argc, char* argv[]) {\r\n\tGraphics GL;\r\n\r\n#ifdef _WIN32\r\n\tLPCTSTR strShareName =(LPCTSTR)\"urg_data\";\r\n\tLPCTSTR strShareName2 =(LPCTSTR)\"myrobot\";\r\n\r\n\tHANDLE hShare = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, FILE_MAP_READ,\r\n\t\t0, sizeof(urg_data), strShareName);\r\n\r\n\t//HANDLE hShare2 = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, FILE_MAP_READ,\r\n\t//\t0, sizeof(myrobot), strShareName2);\r\n\r\n\r\n\tif(INVALID_HANDLE_VALUE == hShare){\r\n\t\tcerr<<\"Shared memory open failer\"<< endl;\r\n\t\treturn -1;\r\n\t}\r\n\t//if(INVALID_HANDLE_VALUE == hShare2){\r\n\t//\tcerr<<\"Shared memory open failer\"<< endl;\r\n\t//\treturn -1;\r\n // }\r\n\r\n\tunsigned char *shmem = (unsigned char *)MapViewOfFile(hShare, FILE_MAP_READ, 0, 0, sizeof(urg_data));\r\n\tif(shmem==NULL) cout<<\"MapViewOfFile1 error\"<<endl;\r\n\t//unsigned char *shmem2 = (unsigned char *)MapViewOfFile(hShare2, FILE_MAP_READ, 0, 0, sizeof(myrobot));\r\n\t//if(shmem2==NULL) cout<<\"MapViewOfFile2 error\"<<endl;\r\n\r\n\r\n\twhile(1){\r\n\t\tmemcpy(&urg_data,shmem,sizeof(urg_data));\r\n\t\t//memcpy(&myrobot,shmem2,sizeof(myrobot));\r\n\t\tSleep(25);\r\n\t}\r\n\r\n\r\n\r\n#else\r\n\r\n\tros::init(argc, argv, \"lrf_viewer\");\r\n\tconst std::string scan_topic_ = \"scan\";\r\n\tros::NodeHandle n;\r\n\tros::Subscriber scan_subscriber_ = n.subscribe (scan_topic_, 10, scanCallback);\r\n\r\n\tros::spin();\r\n#endif\r\n\treturn 0;\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7362637519836426, "avg_line_length": 25, "blob_id": "2941b85e48e0b190ca3c29c34ed3e8a50d25456d", "content_id": "feff4b49acf0a4f7ba96d78b68bf94d78f7a47f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 182, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/n_localpathplan/src_tf_listen_test/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "all:\n\tmake -f Makefile.docu_navi_localpathplan\n\tcp docu_navi_localpathplan ../../bin\n##cp docu_scan2pcl_setting.ini ../../bin\n\nclean:\n\tmake -f Makefile.docu_navi_localpathplan clean\n" }, { "alpha_fraction": 0.37965261936187744, "alphanum_fraction": 0.38461539149284363, "avg_line_length": 28.538461685180664, "blob_id": "5c43f70a3ead447ea4e78c8d3fd42df74d71ce70", "content_id": "2ecdcaf09ca92d64fec14e0ccb7f34089bf0b230", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 403, "license_type": "no_license", "max_line_length": 80, "num_lines": 13, "path": "/n_pcl_assy_publish/readme.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "##############################################\r\n#PCL assemble mnode\r\n##############################################\r\n\r\n\r\n$ rosnode info /n_pcl_assy_publish_node \r\n--------------------------------------------------------------------------------\r\nNode [/n_pcl_assy_publish_node]\r\nPublications: \r\n * /rosout [rosgraph_msgs/Log]\r\n * /assembled_cloud2 [sensor_msgs/PointCloud2]\r\n\r\nSubscriptions: None\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5572289228439331, "alphanum_fraction": 0.6004015803337097, "avg_line_length": 19.465517044067383, "blob_id": "2367fde718cd3048d3ee8142960f2c93726a2e8e", "content_id": "2af3f9e8712438b07399f720da3b519a2ec17ec5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4980, "license_type": "no_license", "max_line_length": 195, "num_lines": 232, "path": "/docu_navi_localpathplan/src/geometory.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n\r\n/////////////////////////////////////////////////\r\n\r\n#pragma once\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n\r\nusing namespace std;\r\nconst double PI=3.14159265359;\r\n\r\n#define URG_DATA_MAX 2000\r\n#define OBSTACLE_MAX 2000\r\n#define DATA_SEQ 100\r\n\r\n#define MOVE_OBST_MAX_MAIN 1000\r\n\r\n#define PATH_POINTS_MAX 1024\r\nconst unsigned int urg_data_num=680;\r\nconst double urg_range_deg=240.0;\r\nconst double urg_leng_max=15.0;\r\nconst double urg_leng_min=0.1;\r\n\r\n\r\nstruct TWIST{\t\r\n\tdouble v;\t\r\n\tdouble w;\t\r\n\tTWIST(){\r\n\t\tv = 0.0;\r\n\t\tw = 0.0;\r\n\t}\r\n};\r\n\r\n\r\nstruct ROBOT{\t\t\r\n\tdouble x;\t\t\r\n\tdouble y;\t\t\r\n\tdouble theta;\r\n\t\r\n\tdouble v;\t\t\r\n\tdouble w;\t\t\r\n\r\n\tdouble real_v;\r\n\tdouble real_w;\t\r\n\r\n\tdouble ac_trans_limit;\t\r\n\tdouble ac_rot_limit;\t\t\r\n\r\n\tROBOT(){\r\n\t\tx = 0.0;\r\n\t\ty = 0.0;\r\n\t\tv = 0.0;\r\n\t\tw = 0.0;\r\n\t\ttheta = 0.0;\r\n\t\treal_v=0.0;\r\n\t\treal_w=0.0;\r\n\r\n\t\tac_trans_limit=5.0;\r\n\t\tac_rot_limit=5.0;\r\n\t}\r\n\r\n\tvoid kinema(double dt) {\r\n\t\tdouble dtt=dt+1.0/100000.0;\r\n\t\tdouble ac_v=fabs(v-real_v)/dtt;\r\n\t\tdouble ac_w=fabs(w-real_w)/dtt;\r\n\t\tif(ac_v>=ac_trans_limit)ac_v=ac_trans_limit;\r\n\t\tif(ac_w>=ac_rot_limit)ac_w=ac_rot_limit;\r\n\t\t\r\n\t\tif((v-real_v)>=0)\t\treal_v+=ac_v*dtt;\r\n\t\telse if((v-real_v)<0)\treal_v-=ac_v*dtt;\r\n\t\t\r\n\t\tif((w-real_w)>=0)\t\treal_w+=ac_w*dtt;\r\n\t\telse if((w-real_w)<0)\treal_w-=ac_w*dtt;\r\n\r\n\t\tcout<<\"real_v\"<<real_v<<\"_\";\r\n\t\tcout<<\"real_w\"<<real_w<<endl;\r\n\t}\r\n\tvoid odometory(double dt){\r\n\t\tkinema(dt);\r\n\t\tx+=real_v*sin(-theta)*dt;\r\n\t\ty+=real_v*cos(-theta)*dt;\r\n\t\ttheta-=real_w*dt;\r\n\t}\r\n};\r\n\r\nstruct URG{\t\t\t\r\n\tdouble leng[URG_DATA_MAX];\t\t\r\n\tdouble x[URG_DATA_MAX];\t\r\n\tdouble y[URG_DATA_MAX];\t\r\n\tint data_num;\r\n\tdouble start_rad;\r\n\tdouble reso;\r\n\r\n\tdouble leng_max;\r\n\tdouble leng_min;\r\n\r\n\tURG(){\r\n\t\tdata_num=(int)URG_DATA_MAX*urg_range_deg/360.0;\r\n\t\tstart_rad=-data_num/2.0/URG_DATA_MAX*2*PI;\r\n\t\treso=2*PI/URG_DATA_MAX;\r\n\t\tleng_max=urg_leng_max;\r\n\t\tleng_min=urg_leng_min;\r\n\r\n\t\tfor(int i=0;i<URG_DATA_MAX;i++){\r\n\t\tx[i] = 0.0;\r\n\t\ty[i] = 0.0;\r\n\t\tleng[i] = 0.0;\r\n\t\t}\r\n\t}\r\n\r\n};\r\n\r\nstruct OBSTACLE{\r\n\tdouble x1[OBSTACLE_MAX];\r\n\tdouble x2[OBSTACLE_MAX];\r\n\tdouble y1[OBSTACLE_MAX];\r\n\tdouble y2[OBSTACLE_MAX];\r\n\tunsigned int n;\t\t\t\t\r\n\tunsigned int n_max;\t\t\t\r\n\r\n\tOBSTACLE(){\r\n\t\tn_max=OBSTACLE_MAX;\r\n\r\n\t\tfor(int i=0;i<n_max;i++){\r\n\t\tx1[i] = 0.0;\r\n\t\tx2[i] = 0.0;\r\n\t\ty1[i] = 0.0;\r\n\t\ty2[i] = 0.0;\r\n\t\t}\r\n\t\r\n\t}\r\n};\r\n\r\nstruct MOVE_OBSTACLE{\t\t\r\n\tdouble obst_x[100][100];\r\n\tdouble obst_y[100][100];\r\n\tdouble phase[100];\r\n\tdouble freq[100];\r\n\tdouble amp[100];\r\n\r\n\tdouble x[100];\r\n\tdouble y[100];\r\n\tdouble now;\r\n\tdouble n;\r\n\tdouble m;\r\n\t\r\n\tdouble obst_size;\r\n\t\r\n\tMOVE_OBSTACLE(){\r\n\t\tobst_size=0.5;\r\n\t\tn=2;\r\n\t\tm=4;\r\n\t\tfor(int i=0;i<n;i++){\r\n\t\t\tx[i]=0.0;\r\n\t\t\ty[i]=0.0;\r\n\t\t\tphase[i]=0.0;\r\n\t\t\tamp[i]=0;\r\n\t\t\tfreq[i]=0;\r\n\t\t}\r\n\t\tfor(int i=0;i<n;i++){\r\n\t\t\tfor(int j=0;j<n;j++){\r\n\t\t\t\tobst_x[i][j]=0.0;\r\n\t\t\t\tobst_y[i][j]=0.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tnow=0;\r\n\r\n\r\n\t\tx[0]=2,y[0]=2,amp[0]=10,freq[0]=10;\r\n\t\tx[1]=-2,y[1]=2,amp[1]=10,freq[1]=20;\r\n\t\tx[2]=-2,y[2]=0,amp[2]=5,freq[2]=30;\r\n\t\r\n\r\n\t}\r\n\r\n\tvoid move(double dt){\r\n\r\n\r\n\r\n\t}\r\n};\r\n\r\n\r\n\r\n\r\nstruct MOVE_PATH{\t\t\r\n\tdouble x[PATH_POINTS_MAX];\r\n\tdouble y[PATH_POINTS_MAX];\r\n\tunsigned int n;\r\n\tunsigned int n_max;\t\t\t\r\n\tunsigned int now_n;\t\t\t\r\n\tMOVE_PATH(){\r\n\t\tn_max=PATH_POINTS_MAX;\r\n\t\tfor(int i=0;i<n_max;i++){\r\n\t\tx[i] = 0.0;\r\n\t\tx[i] = 0.0;\r\n\t\tn=0;\r\n\t\tnow_n=0;\r\n\t\t}\r\n\t\r\n\t}\r\n};\r\n\r\ndouble Uniform( void );\r\ndouble rand_normal( double mu, double sigma );\r\n\r\nbool cross_xy(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y,double &cro_x,double &cro_y);\r\n\r\nbool cross_check(double a1_x,double a1_y,double a2_x,double a2_y,double b1_x,double b1_y,double b2_x,double b2_y);\r\n\r\nvoid urg_calcurate( ROBOT &robot, URG urg_area, OBSTACLE obst, MOVE_OBSTACLE move_obst, URG &urg_data);\r\n\r\nvoid read_obstacle(OBSTACLE &obst,string fname=\"obstacle.csv\");\r\nvoid write_obstacle(OBSTACLE &obst,string fname=\"obstacle.csv\");\r\nstatic double get_dtime(void);\r\n\r\ndouble str_double(string str);\r\n\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta);\r\nvoid To_goal_velocity(double goal_x,double goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis=0.2,double turn_limit=3.14);\r\n\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn);\r\nvoid dynamic_windows_approach(URG urg_l,double path_x[][DATA_SEQ],double path_y[][DATA_SEQ],double path_cost[],int &path_size,double robot_v,double robot_w,double &best_v,double &best_w,int flg);\r\nvoid convert_odom(ROBOT &robot,ROBOT robot_buff);\r\nvoid To_deadlock_back(double _goal_x,double _goal_y,double _goal_theta,double robot_x,double robot_y,double robot_theta,\r\n\t\t\t\t\tdouble &speed,double &turn,double goal_reach_dis);\r\n\r\nint To_goal_near(double _goal_x,double _goal_y,double _goal_theta,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis);\r\n" }, { "alpha_fraction": 0.50737464427948, "alphanum_fraction": 0.5221238732337952, "avg_line_length": 29.272727966308594, "blob_id": "6bff906f556498a034b640939ec7881b7dcaa7d7", "content_id": "7e21ac3f54c4602cba0d4dca874a538af61e8be7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 339, "license_type": "no_license", "max_line_length": 80, "num_lines": 11, "path": "/robo_rot/readme.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "\n\n$ rosnode info /robot_rot \n--------------------------------------------------------------------------------\nNode [/robot_rot]\nPublications: \n * /robo_rot_readspeed [std_msgs/Float32]\n * /rosout [rosgraph_msgs/Log]\n * /tf [tf2_msgs/TFMessage]\n * /robo_rot_setspeed [std_msgs/Float32]\n\nSubscriptions: \n * /panunit_speed [unknown type]\n\n\n\n\n" }, { "alpha_fraction": 0.7307268977165222, "alphanum_fraction": 0.8463656306266785, "avg_line_length": 52.382354736328125, "blob_id": "20f3bb768a09e355c528e9f322f6e9429187c97f", "content_id": "78ce4696c9bb56344554916d44d92e5af4311bc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 59, "num_lines": 34, "path": "/simtest_launch/test.bash", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n\ntimeout 600 roslaunch sim_2d_replay_cartographer_001.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_002.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_003.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_004.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_005.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_006.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_007.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_008.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_009.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_010.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_011.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_012.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_013.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_014.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_015.launch\n\ntimeout 600 roslaunch sim_2d_replay_cartographer_001.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_002.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_003.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_004.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_005.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_006.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_007.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_008.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_009.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_010.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_011.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_012.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_013.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_014.launch\ntimeout 600 roslaunch sim_2d_replay_cartographer_015.launch\n\n" }, { "alpha_fraction": 0.6857671141624451, "alphanum_fraction": 0.6950092315673828, "avg_line_length": 27.210525512695312, "blob_id": "49fecdfde9596274b3d4ced535c4960a19bd4009", "content_id": "0286b71f0020f8b89b6137f0e5ca1c26b64f037d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 541, "license_type": "no_license", "max_line_length": 99, "num_lines": 19, "path": "/n_pcl_3d_to_2d/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\nall:\n\tmake -f Makefile.docu_pclxyz2xy\n\tcp docu_pclxyz2xy ../../bin\n\nclean:\n\tmake -f Makefile.docu_pclxyz2xy clean\n\t\ninstall:\n\tmkdir -p $(install_prefix)/lib/$(project)\n\tmkdir -p $(install_prefix)/share/$(project)/launch\n\techo \"<package><name>$(project)</name></package>\" > $(install_prefix)/share/$(project)/package.xml\n\ttouch $(install_prefix)/.catkin\n\tcp -a docu_pclxyz2xy $(install_prefix)/lib/$(project)\n\t\nuninstall:\n\trm -f $(install_prefix)/lib/$(project)/docu_scan2pcl \n\t\n\t\n" }, { "alpha_fraction": 0.5854630470275879, "alphanum_fraction": 0.6236811280250549, "avg_line_length": 26.0592098236084, "blob_id": "205cdd9b76316ba8d93a8175773654811ad52afa", "content_id": "44d3e28b35e6c18111abe8f795ea1b01d80a6a91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4629, "license_type": "no_license", "max_line_length": 169, "num_lines": 152, "path": "/n_map_view/src_opencv/geometory.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n/////////////////////////////////////////////////\r\n\r\n#include <math.h>\r\n#include<iostream>\r\n#include<string>\r\n#include<sstream>\r\n#include<fstream>\r\nusing namespace std;\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n\r\ndouble str_double(string str){\r\n\tistringstream is;\r\n\tis.str(str);\r\n\tdouble x;\r\n\tis >> x;\r\n\treturn x;\r\n}\r\n\r\ndouble get_dtime(void){\r\n\tdouble freq = 1000.0/cv::getTickFrequency();\r\n\tstatic int64 old_time = cv::getTickCount();\r\n\tint64 time = cv::getTickCount();\r\n\tdouble dt_msec=(time-old_time)*freq/50.0;\r\n\told_time=time;\r\n\treturn dt_msec;\r\n}\r\n\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta){\r\n\tdouble target_r = sqrt(target_x*target_x+target_y*target_y);\r\n\r\n\tif(target_y>=0){\r\n\t\ttheta=acos(target_x/target_r);\r\n\t\ttheta=theta*180.0/PI;\r\n\t}\r\n\telse if(target_y<0){\r\n\t\ttheta=acos(target_x/target_r);\r\n\t\ttheta=360.0-theta*180.0/PI;\r\n\t}\r\n\r\n\tif(theta>=90.0) theta=theta-90.0;\r\n\telse if(theta<90.0) theta=theta-90.0;\r\n\tif(theta>180.0) theta=theta-360.0;\r\n\r\n}\r\n\r\n\r\n//ゴールに向かうロボットへの指令速度を算出する。\r\nvoid To_goal_velocity(double _goal_x,double _goal_y,double robot_x,double robot_y,double robot_theta,double &speed,double &turn,double goal_reach_dis,double turn_limit){\r\n\r\n\tconst double speed_gain=1.0;\r\n\tconst double turn_gain=speed_gain*1.0;\r\n\tconst double speed_max=2.0;\r\n\tconst double turn_max=PI/2.0;\r\n\r\n\tdouble goal_x=_goal_x-robot_x;\t\t\t\t\t\t//\r\n\tdouble goal_y=_goal_y-robot_y;\t\t\t\t\t\t//\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\t//\r\n\tdouble goal_rad=(-1)*atan2(goal_x,goal_y);\r\n\t//ロボット角度の正規化(+2PIに抑制)\r\n\tdouble robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\r\n//\tdouble robot_theta_fmod=robot_theta;\r\n\r\n\t//角度の差分\r\n\tdouble sub_rad=goal_rad-robot_theta_fmod;\r\n\r\n\t//Tanが±πの範囲のため、右回りと左回りを評価\r\n\tif(fabs(goal_rad-robot_theta_fmod)>1.0*PI){\r\n\t\tif(fabs(goal_rad-robot_theta_fmod+4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod-4.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod+2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(goal_rad-robot_theta_fmod-2.0*PI)<fabs(goal_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=goal_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t}\r\n\r\n\t//速度の評価関数は実機にあわせて修正すること。\r\n\tdouble x=goal_l;\r\n\t//speed = (0.0246*pow(x,4) - 0.1987*pow(x,3) + 0.169*pow(x,2) + 1.7482*pow(x,1)-1.4 );\r\n\t//speed = (x );\r\n\tspeed=fabs(x)*speed_gain;\r\n\r\n\r\n\t//double turn_speed=fabs(sub_rad);\r\n\tdouble r=sub_rad;\r\n\t//double turn_speed = fabs(r);\r\n\tdouble turn_speed = -0.0278*pow(r,5) + 0.3025*pow(r,4) - 1.1232*pow(r,3) + 1.4103*pow(r,2) + 0.4428*pow(r,1) + 0.0;\r\n\r\n\tif(sub_rad>=0) turn=-1*turn_speed*turn_gain;\r\n\telse if((sub_rad<=0)) turn=1*turn_speed*turn_gain;\r\n\r\n\t//角度のかい離大きいたらその場で旋回\r\n\tif(turn_speed>=turn_max)\tspeed=0.0;\r\n\tif(turn_speed<=-turn_max)\tspeed=0.0;\r\n\r\n\t//最大速度の規定\r\n\tif(speed>speed_max)\tspeed=speed_max;\r\n\tif(goal_l<goal_reach_dis) speed=0.0;\t//到達したら停止\r\n\r\n\r\n//\tcout<<\"robo:\"<<speed<<\"\\t\";\r\n//\tcout<<\"dis:\"<<goal_l<<\"\\n\";\r\n//\tcout<<\"robo:\"<<turn<<\"\\t\";\r\n//\t/cout<<\"atan;\"<<sub_rad<<\"\\t\";\r\n//\tcout<<\"robot_theta\"<<robot_theta<<endl;\r\n\r\n\treturn ;\r\n}\r\n\r\n//パスに従って追従するロボットへの指令速度を算出する。\r\nvoid To_path_velocity(MOVE_PATH &path,double robot_x,double robot_y,double robot_theta,double &speed,double &turn){\r\n\tdouble goal_limit=1.0;\t\t//ゴールと認識する距離\r\n\tdouble goal_limit_last=.10;\t\t//ゴールと認識する距離\r\n\r\n\tif(path.x.size()==0){\r\n\t\tspeed=0;\r\n\t\tturn=0;\r\n\t\treturn;\r\n\t}\r\n\r\n\tif(path.now_n+1==path.x.size()) {\r\n\t\tgoal_limit=goal_limit_last;\r\n\t}\r\n\r\n\tdouble goal_x=path.x[path.now_n]-robot_x;\r\n\tdouble goal_y=path.y[path.now_n]-robot_y;\r\n\tdouble goal_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble goal_rad=(-1)*atan2(goal_x,goal_y);\r\n\r\n\r\n\tif(goal_l<goal_limit){ //ゴールに近い\r\n\t\tif(path.now_n+1<path.x.size()){\r\n\t\t\tpath.now_n++;\r\n\t\t}\r\n\t\telse if(path.now_n+1==path.x.size()) {\r\n\t\t\tspeed=0;\r\n\t\t\tturn=0;\r\n\t\t}\r\n\t}\r\n\telse{\t\t\t//ゴールから遠いのであれば経路追従\r\n\t\tTo_goal_velocity( path.x[path.now_n], path.y[path.now_n],robot_x,robot_y,robot_theta,speed,turn,goal_limit,3.14*2.0);\r\n\t}\r\n\tcout<<\"n:\"<<path.now_n<<\"_x:\"<<path.x[path.now_n]<<\"_y:\"<<path.y[path.now_n]<<\"_\"<<path.x.size()<<endl;\r\n\treturn;\r\n}\r\n" }, { "alpha_fraction": 0.7029703259468079, "alphanum_fraction": 0.7029703259468079, "avg_line_length": 25.578947067260742, "blob_id": "38b609d341615c60bd09fca5cd262284be8c4693", "content_id": "498bda8f81bee46b7e91f25e963c09992aee4898", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 505, "license_type": "no_license", "max_line_length": 99, "num_lines": 19, "path": "/n_sendgoal/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\nall:\n\tmake -f Makefile.docu_sendgoal\n\n\ninstall:\n\tmkdir -p $(install_prefix)/lib/$(project)\n\tmkdir -p $(install_prefix)/share/$(project)/launch\n\techo \"<package><name>$(project)</name></package>\" > $(install_prefix)/share/$(project)/package.xml\n\ttouch $(install_prefix)/.catkin\n\tcp -a docu_sendgoal $(install_prefix)/lib/$(project)\n\nuninstall:\n\trm -f $(install_prefix)/lib/$(project)/docu_sendgoal \n\t\nclean:\n\tmake -f Makefile.docu_sendgoal clean\n" }, { "alpha_fraction": 0.6766467094421387, "alphanum_fraction": 0.6766467094421387, "avg_line_length": 23.549999237060547, "blob_id": "3c9ab4c9d2ad9e9d5cdc0df4c2df0c02623f15a1", "content_id": "e63c609a297cc35534bc9dd0a84ff71c4510baa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 501, "license_type": "no_license", "max_line_length": 99, "num_lines": 20, "path": "/n_map_saver/src/Makefile", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "project = myproject\ninstall_prefix ?= ~/ros_bin/$(project)\n\n\nall:\n\tmake -f Makefile.map_saver\n\nclean:\n\tmake -f Makefile.map_saver clean\n\t\n\t\ninstall:\n\tmkdir -p $(install_prefix)/lib/$(project)\n\tmkdir -p $(install_prefix)/share/$(project)/launch\n\techo \"<package><name>$(project)</name></package>\" > $(install_prefix)/share/$(project)/package.xml\n\ttouch $(install_prefix)/.catkin\n\tcp -a map_saver $(install_prefix)/lib/$(project)\n\t\nuninstall:\n\trm -f $(install_prefix)/lib/$(project)/map_saver\n\t\n\t\n\t\n\t\n\t\n" }, { "alpha_fraction": 0.5528586506843567, "alphanum_fraction": 0.5879443287849426, "avg_line_length": 23.56764793395996, "blob_id": "bab1f47bb434374a339f191041e8591d43367fb0", "content_id": "f5fb5a10cded93b728bcb6331b0eebe046363ec5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9175, "license_type": "no_license", "max_line_length": 122, "num_lines": 340, "path": "/n_object_tracking/src/geometory.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n#include <math.h>\r\n#include <time.h>\r\n#include <stdio.h>\r\n\r\n#include<iostream>\r\n#include<string>\r\n#include<sstream> \r\n#include<fstream>\r\nusing namespace std;\r\n\r\n#include \"geometory.h\"\r\n#include \"opencv_inc.h\"\r\n\r\n\r\ndouble speed_max=0.3;\r\ndouble speed_min=0.1;\r\ndouble turn_max=0.1;\r\ndouble turn_min=-0.1;\r\ndouble turn_area=0.33;\r\n\r\n double LRF_clustring_Threshold_percent=0.03;\t//クラスタリングの距離閾値[%]\r\n double LRF_clustring_Threshold_dis=0.05;\t\t//クラスタリングの距離閾値[m]\r\n double LRF_clustring_min_num=30.0;\t\t\t\t\t//小さいクラスタを除去\r\n double Threshold_tracking=0.250;\t\t\t//トラッキング距離\r\n\r\ndouble now_t=0;\r\ndouble old_t=0;\r\n \r\n double m_accelerate_mps=0.0;\r\n double m_accelerate_rps=0.0;\r\n \r\n double mps_variation=0.0;\r\n double rps_variation=0.0;\r\n\tdouble old_speed,old_turn;\r\n\t\r\n//strをdoubleに変換する\r\ndouble str_double(string str){\t\r\n\tistringstream is; \r\n\tis.str(str); \r\n\tdouble x; \r\n\tis >> x; \r\n\treturn x;\r\n}\r\n\r\n\r\n\r\n//時間を計測する\r\ndouble get_dtime(void){\r\n\tdouble freq = 1000.0/cv::getTickFrequency();\r\n\tstatic int64 old_time = cv::getTickCount();\r\n\tint64 time = cv::getTickCount();\r\n\tdouble dt_msec=(time-old_time)*freq/50.0;\r\n\told_time=time;\r\n\treturn dt_msec;\r\n}\r\n\r\nvoid arc_tan2(double &target_x,double &target_y,double &theta){\r\n\tdouble target_r = sqrt(target_x*target_x+target_y*target_y);\r\n\r\n\tif(target_y>=0){\r\n\t\ttheta=acos(target_x/target_r);\r\n\t\ttheta=theta*180.0/PI;\r\n\t}\r\n\telse if(target_y<0){\r\n\t\ttheta=acos(target_x/target_r);\r\n\t\ttheta=360.0-theta*180.0/PI;\r\n\t}\r\n\r\n\tif(theta>=90.0) theta=theta-90.0;\r\n\telse if(theta<90.0) theta=theta-90.0;\r\n\tif(theta>180.0) theta=theta-360.0;\r\n\r\n}\r\n\r\n\r\ndouble timer_ms() {\r\n\tdouble timer_ms = cv::getTickCount();\r\n\treturn timer_ms;\r\n} \r\n\r\n\r\n\r\n\r\nvoid follow_velocity(double goal_x,double goal_y,double robot_theta,double &speed,double &turn){\r\n\r\n\tdouble urg_x=goal_x;\r\n\tdouble urg_y=goal_y; \r\n\tdouble urg_l=sqrt(goal_x*goal_x+goal_y*goal_y);\r\n\tdouble urg_rad=(-1)*atan2(urg_x,urg_y);\r\n\r\n\r\n\t//ロボット角度の正規化(+2PIに抑制)\r\n\tdouble robot_theta_fmod=atan2(sin(robot_theta),cos(robot_theta));\r\n\t//角度の差分\r\n\tdouble sub_rad=urg_rad-robot_theta_fmod;\r\n\r\n\t//Tanが±πの範囲のため、右回りと左回りを評価\r\n\tif(fabs(urg_rad-robot_theta_fmod)>1.0*PI){\r\n\t\tif(fabs(urg_rad-robot_theta_fmod+4.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=urg_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(urg_rad-robot_theta_fmod-4.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=urg_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(urg_rad-robot_theta_fmod+2.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=urg_rad-robot_theta_fmod+2.0*PI;\r\n\t\t}\r\n\t\telse if(fabs(urg_rad-robot_theta_fmod-2.0*PI)<fabs(urg_rad-robot_theta_fmod)){\r\n\t\t\tsub_rad=urg_rad-robot_theta_fmod-2.0*PI;\r\n\t\t}\r\n\t}\r\n\r\n//\tspeed=urg_l;\r\n\r\n\tdouble x=urg_l;\r\n\tspeed = 0.0246*pow(x,4) - 0.1987*pow(x,3) + 0.169*pow(x,2) + 1.7482*pow(x,1) - 0.8423;\r\n\tif(goal_y<0) speed=0.0;\r\n\r\n\tif(speed>=speed_max)\tspeed=speed_max;\r\n\tif(speed<speed_min)\t\tspeed=speed_min;\r\n\r\n\t//\tdouble turn_speed=fabs(sub_rad);\r\n\t//\tturn_speed = -0.0278*pow(x,5) + 0.3025*pow(x,4) - 1.1232*pow(x,3) + 1.4103*pow(x,2) + 0.4428*pow(x,1) + 0.0;\r\n x=fabs(sub_rad);\r\n turn = -0.0278*pow(x,5) + 0.3025*pow(x,4) - 0.6232*pow(x,3) + 1.4103*pow(x,2) + 1.4428*pow(x,1) + 0.0;\r\n if(sub_rad<0) turn=-turn;\r\n else if(sub_rad>=0) turn=turn;\r\n\r\n\r\n\t//cout<<sub_rad<<\"_\"<<turn<<endl;\r\n\tif(turn>=PI*turn_area)\tspeed=0.0;\r\n\tif(turn<=-PI*turn_area)\tspeed=0.0;\r\n\r\n\r\n\tif(turn>turn_max) turn=turn_max;\r\n\tif(turn<turn_min) turn=turn_min;\r\n\r\n\tnow_t=timer_ms();\r\n\tif((now_t!=0)&&(old_t!=0)&&((now_t-old_t)>0)){\r\n\r\n\t\tmps_variation=(now_t-old_t)/1000.0*m_accelerate_mps;\r\n\t\trps_variation=(now_t-old_t)/1000.0*m_accelerate_rps;\r\n\r\n\t\tif(fabs(speed-old_speed)>mps_variation){\r\n\t\t\tspeed=old_speed+(speed-old_speed)/fabs(speed-old_speed)*mps_variation;\r\n\t\t}\r\n\t\tif(fabs(turn-old_turn)>rps_variation){\r\n\t\t\tturn=old_turn+(turn-old_turn)/fabs(turn-old_turn)*rps_variation;\r\n\t\t}\r\n\t}\r\n\r\n\told_t= timer_ms();\r\n\told_speed=speed;\r\n\told_turn=turn;\r\n\r\n\t//cout<<\"robo\"<<robot_theta_fmod<<\"\\t\";\r\n\t//cout<<\"atan\"<<sub_rad<<\"\\t\";\r\n\t//cout<<\"sub\"<<turn<<endl;\r\n\r\n}\r\n\r\nint LRF_clustring_tracking(CLUSTER clust[],double &goal_x,double &goal_y,int mouse_flag,int &clust_no){\r\n\r\n\tstatic double object_x=0;\r\n\tstatic double object_y=0;\r\n\t\r\n\tif(mouse_flag==1){\r\n\t\tobject_x=goal_x; \r\n\t\tobject_y=goal_y;\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tint clust_no_object=0;\r\n\tdouble distance_object_min=999.0;\r\n\tfor(int i=0;i<clust[0].clnum;i++){\r\n\t\tdouble xx=clust[i].x_ave;\r\n\t\tdouble yy=clust[i].y_ave;\r\n\t\tdouble distance_object=(xx-object_x)*(xx-object_x)+(yy-object_y)*(yy-object_y);\r\n\t\tif(distance_object<distance_object_min){\r\n\t\t\tdistance_object_min=distance_object;\r\n\t\t\tclust_no_object=i;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tclust_no=clust_no_object;\r\n\r\n\tif(distance_object_min<Threshold_tracking){\r\n\t\tgoal_x=clust[clust_no_object].x_ave;\r\n\t\tgoal_y=clust[clust_no_object].y_ave;\r\n\t\tobject_x=goal_x;\r\n\t\tobject_y=goal_y;\r\n\t\treturn 1;\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n\r\n\r\nvoid LRF_clustring_main(URG urg_data,CLUSTER clust[]){\r\n\t//URG urg_data URGのデータ\r\n\t//CLUSTER clust[] クラスタリングされたデータ\r\n\r\n\r\n\t//const double LRF_clustring_Threshold_percent=0.2;//クラスタリングの距離閾値[%]\r\n\t//const double LRF_clustring_Threshold_dis=0.1;//クラスタリングの距離閾値[m]\r\n\t//const int LRF_clustring_min_num=5;\r\n\r\n\tfor(int i=0;i<urg_data.data_num-1;i++){\r\n\t\turg_data.x[i]=(-1)*urg_data.leng[i]*sin(i*urg_data.reso+urg_data.start_rad);\r\n\t\turg_data.y[i]=urg_data.leng[i]*cos(i*urg_data.reso+urg_data.start_rad);\r\n\t\t}\r\n\r\n\tfor(int i=0;i<urg_data.data_num;i++){\r\n\t\tclust[i].ptnum=0;\r\n\t\tclust[i].dis=0;\r\n\t\tclust[i].flag=1;\r\n\t}\r\n\r\n\tint ptnum=0;\t//各クラスタ毎の点数\r\n\tint clnum=0;\t//クラスタの戸数\r\n\r\n\tfor(int i=0;i<urg_data.data_num;i++){//クラスタ分類\r\n\t\tif(urg_data.leng[i]!=0){\r\n\t\t\tif(((fabs( urg_data.leng[i+1]-urg_data.leng[i] )<urg_data.leng[i]*LRF_clustring_Threshold_percent)||\r\n\t\t\t\t(fabs(urg_data.leng[i+1]-urg_data.leng[i])< LRF_clustring_Threshold_dis))&&(urg_data.leng[i]>0.01)){//隣とクラスタリング\r\n\t\t\t\t\tclust[clnum].r[ptnum]=urg_data.leng[i];\r\n\t\t\t\t\tclust[clnum].x[ptnum]=urg_data.x[i];\r\n\t\t\t\t\tclust[clnum].y[ptnum]=urg_data.y[i];\r\n\t\t\t\t\tclust[clnum].ptnum=ptnum;\r\n\t\t\t\t\tptnum++;\r\n\t\t\t}\r\n\t\t\telse if(((fabs( urg_data.leng[i+2]-urg_data.leng[i] )<urg_data.leng[i]*LRF_clustring_Threshold_percent)||\r\n\t\t\t\t(fabs(urg_data.leng[i+2]-urg_data.leng[i] )< LRF_clustring_Threshold_dis))&&(urg_data.leng[i]>0.01)){//もうひとつ隣とクラスタリング\r\n\t\t\t\t\tclust[clnum].r[ptnum]=urg_data.leng[i];\r\n\t\t\t\t\tclust[clnum].x[ptnum]=urg_data.x[i];\r\n\t\t\t\t\tclust[clnum].y[ptnum]=urg_data.y[i];\r\n\t\t\t\t\tclust[clnum].ptnum=ptnum;\r\n\t\t\t\t\tptnum++;\r\n\t\t\t}\r\n\r\n\t\t\telse{//次のクラスタを割り振る\r\n\t\t\t\tif(clust[clnum].ptnum>LRF_clustring_min_num){\r\n\t\t\t\t\ti++;\r\n\t\t\t\t\tclnum++;\r\n\t\t\t\t\tptnum=0;\r\n\t\t\t\t\tclust[clnum].r[ptnum]=urg_data.leng[i];\r\n\t\t\t\t\tclust[clnum].x[ptnum]=urg_data.x[i];\r\n\t\t\t\t\tclust[clnum].y[ptnum]=urg_data.y[i];\r\n\t\t\t\t\tclust[clnum].ptnum=ptnum;\r\n\t\t\t\t\tptnum++;\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\ti++;\r\n\t\t\t\t\tptnum=0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//クラスタ中心を求める.\r\n\tfor(int i=0;i<clnum;i++){\r\n\t\tdouble x_sum=0;\r\n\t\tdouble y_sum=0;\r\n\t\tdouble r_sum=0;\r\n\t\tint sum=0;\r\n\r\n\t\tfor(int j=0;j<clust[i].ptnum;j++){\r\n\t\t\tdouble x=clust[i].x[j];\r\n\t\t\tdouble y=clust[i].y[j];\r\n\t\t\tdouble r=clust[i].r[j];\r\n\t\t\tif(r>0.01){\r\n\t\t\t\tx_sum+=x;\r\n\t\t\t\ty_sum+=y;\r\n\t\t\t\tr_sum+=r;\r\n\t\t\t\tsum++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tclust[i].x_ave=x_sum/sum;\r\n\t\tclust[i].y_ave=y_sum/sum;\r\n\t\tclust[i].r_ave=r_sum/sum; \r\n\t\tclust[i].clnum=clnum;\r\n\t}\r\n\r\n \r\n \r\n\t//クラスタ長を求める.\r\n\tfor(int i=0;i<clnum;i++){\r\n\t\tdouble dis=0;\r\n\t\tdouble clust_dis=0;\r\n\t\tfor(int j=0;j<clust[i].ptnum;j++){\r\n\t\t\tif((fabs( clust[i].r[j+1]-clust[i].r[j] )< clust[i].r[j]*0.10)||(fabs( clust[i].r[j+1]-clust[i].r[j] )< 0.10)){\r\n\t\t\t\tdouble x0=clust[i].x[j];\r\n\t\t\t\tdouble y0=clust[i].y[j];\r\n\t\t\t\tdouble x1=clust[i].x[j+1];\r\n\t\t\t\tdouble y1=clust[i].y[j+1];\r\n\t\t\t\tdouble dis=(x1-x0)*(x1-x0)+(y1-y0)*(y1-y0);\r\n\t\t\t\tclust_dis+=dis;\r\n\t\t\t}\r\n\t\t}\r\n\t\tclust[i].dis=clust_dis;\r\n\t}\r\n\r\n\r\n //クラスタの点数が少なければ省く.\r\n\tfor(int i=0;i<clnum;i++){\r\n\t\tptnum=clust[i].ptnum;\r\n\t\tif(ptnum<3) clust[i].flag=0;\r\n\t}\r\n \r\n}\r\n\r\n\r\n\r\n//線分と点との距離を測定する\r\ndouble line_seg_point_distance( double px, double py,double ax, double ay, double bx, double by){\r\n\tdouble dx, dy, r2;\r\n\tdouble t, cx, cy;\r\n\tdx = bx - ax;\r\n\tdy = by - ay;\r\n\tif (dx == 0 && dy == 0)\r\n\t\treturn sqrt((px - ax) * (px - ax) + (py - ay) * (py - ay));\r\n\tr2 = dx * dx + dy * dy;\r\n\tt = (dx * (px - ax) + dy * (py - ay)) / (double)r2;\r\n\tif (t < 0)\r\n\t\treturn sqrt((px - ax) * (px - ax) + (py - ay) * (py - ay));\r\n\tif (t > 1)\r\n\t\treturn sqrt((px - bx) * (px - bx) + (py - by) * (py - by));\r\n\tcx = (1 - t) * ax + t * bx;\r\n\tcy = (1 - t) * ay + t * by;\r\n\treturn sqrt((px - cx) * (px - cx) + (py - cy) * (py - cy));\r\n}\r\n" }, { "alpha_fraction": 0.5058823823928833, "alphanum_fraction": 0.6039215922355652, "avg_line_length": 30.75, "blob_id": "8b535778358cd50f4b7594e793b8e65cc8cc0b8a", "content_id": "061b643d1a1b641596229bb43710605e4f1336fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "no_license", "max_line_length": 65, "num_lines": 8, "path": "/robo_rot/pan_unit/conv_position.py", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\ndef convertPosToAnguler(pos):\n ONE_REVOLUTION = 192000.0\n PI = 3.141592653589793\n theta = ( pos % ONE_REVOLUTION ) / ONE_REVOLUTION * 2.0 * PI\n #print(\"pos = \" + str(pos) + \", theta = \" + str(theta));\n return theta\n\n" }, { "alpha_fraction": 0.5414829850196838, "alphanum_fraction": 0.5498998165130615, "avg_line_length": 27.880239486694336, "blob_id": "c6f8dad9a14feaa22e60a1bb6f29a40c563db616", "content_id": "206a5e053a2e44ea024f3ccbfba4fb3e930355f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4990, "license_type": "no_license", "max_line_length": 119, "num_lines": 167, "path": "/n_localpathplan/src_tf_listen_test/ros_main.cpp", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////\r\n////Create By IPF nemoto\r\n/////////////////////////////////////////////////\r\n\r\n#include <math.h>\r\n#include <iostream>\r\n#include <limits>\r\nusing namespace std;\r\n\r\n#include <ros/ros.h>\r\n#include <sensor_msgs/LaserScan.h>\r\n#include <nav_msgs/Odometry.h>\r\n#include <nav_msgs/Path.h>\r\n#include <geometry_msgs/Twist.h>\r\n#include <tf/transform_broadcaster.h>\r\n#include <tf/tf.h>\r\n#include <tf/transform_datatypes.h>\r\n#include <tf/transform_listener.h>\r\ntf::TransformListener *tflistener;\r\n/*\r\nvoid scanCallback(const sensor_msgs::LaserScanConstPtr &scan_msg)\r\n{\r\n double range_min = scan_msg->range_min;\r\n double range_max = scan_msg->range_max;\r\n double angle_increment = scan_msg->angle_increment;\r\n double angle_min = scan_msg->angle_min;\r\n double angle_max = scan_msg->angle_max;\r\n\r\n int data_num = (angle_max - angle_min) / angle_increment;\r\n // TODO - also copy intensity values\r\n\r\n for (unsigned int i = 0; i < data_num; ++i)\r\n {\r\n\turg_data.leng[i] = scan_msg->ranges[i];\r\n\tif (isnan(urg_data.leng[i]))\r\n\t urg_data.leng[i] = 0.0;\r\n }\r\n\r\n urg_data.data_num = data_num;\r\n urg_data.start_rad = scan_msg->angle_min;\r\n urg_data.reso = scan_msg->angle_increment;\r\n urg_data.leng_max = range_max;\r\n urg_data.leng_min = range_min;\r\n}*/\r\n\r\nvoid GetRPY(const geometry_msgs::Quaternion &quat, double &theta)\r\n{\r\n tf::Quaternion q(quat.x, quat.y, quat.z, quat.w);\r\n tf::Matrix3x3 m(q);\r\n double roll, pitch, yaw;\r\n m.getRPY(roll, pitch, yaw);\r\n //std::cout << \"Roll: \" << roll << \", Pitch: \" << pitch << \", Yaw: \" << yaw << std::endl;\r\n //theta=yaw+3.1415;\r\n theta = -yaw;\r\n}\r\n\r\nvoid pathCallback(const nav_msgs::PathConstPtr &path)\r\n{\r\n // geometry_msgs::PoseStamped p;\r\n //for (int i = 0; i < path->poses.size(); i++)\r\n //{\r\n // p = path->poses[i];\r\n // }\r\n\r\n geometry_msgs::PoseStamped start_pos_map;\r\n geometry_msgs::PoseStamped start_pos_base_link;\r\n geometry_msgs::PoseStamped end_pos_map;\r\n geometry_msgs::PoseStamped end_pos_base_link;\r\n\r\n int m = path->poses.size() - 1;\r\n start_pos_map = path->poses[0];\r\n end_pos_map = path->poses[m];\r\n\r\n //cout << start_pos_map.pose.position.x << \"\\t\" << start_pos_map.pose.position.y << \"\\t\" << \"_\";\r\n //cout << end_pos_map.pose.position.x << \"\\t\" << end_pos_map.pose.position.y << \"\\t\" << \"_\";\r\n /*\r\n try\r\n {\r\n tflistener->transformPose(\"/map\", path->header.stamp, start_pos_map, \"/base_scan\", start_pos_base_link);\r\n }\r\n catch (tf::TransformException ex)\r\n {\r\n ROS_ERROR(\"%s\", ex.what());\r\n ros::Duration(1.0).sleep();\r\n }\r\n\r\n try\r\n {\r\n tflistener->transformPose(\"/map\", path->header.stamp, end_pos_map, \"/base_link\", end_pos_base_link);\r\n }\r\n\r\n catch (tf::TransformException ex)\r\n {\r\n ROS_ERROR(\"%s\", ex.what());\r\n ros::Duration(1.0).sleep();\r\n }*/\r\n\r\n // cout << start_pos_base_link.pose.position.x << \"\\t\" << start_pos_base_link.pose.position.y << \"\\t\" << \"_\";\r\n // cout << end_pos_base_link.pose.position.x << \"\\t\" << end_pos_base_link.pose.position.y << \"\\t\" << \"\\n\";\r\n\r\n tf::StampedTransform transform;\r\n\r\n try\r\n {\r\n tflistener->lookupTransform(\"/map\", \"/base_link\",\r\n ros::Time(0), transform);\r\n }\r\n catch (tf::TransformException ex)\r\n {\r\n ROS_ERROR(\"%s\", ex.what());\r\n ros::Duration(1.0).sleep();\r\n }\r\n\r\n\r\n\r\n \r\n cout << \"x:\" << -transform.getOrigin().y() << \"_\";\r\n cout << \"y:\" << transform.getOrigin().x() << \"_\"\r\n << \"\\n\";\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\r\n ros::init(argc, argv, \"docu_navigation_localpathplan\");\r\n\r\n ros::NodeHandle n;\r\n // const std::string scan_topic_ = \"scan2\";\r\n // ros::Subscriber scan_subscriber_ = n.subscribe(scan_topic_, 10, scanCallback);\r\n //\r\n\r\n tf::TransformListener lr(ros::Duration(10));\r\n tflistener = &lr;\r\n\r\n const std::string path_topic = \"/move_base/TrajectoryPlannerROS/global_plan\";\r\n ros::Subscriber path_subscriber = n.subscribe(path_topic, 10, pathCallback);\r\n\r\n // const std::string odom_topic_ = \"odom\";\r\n // ros::Subscriber odom_subscriber_ = n.subscribe(odom_topic_, 10, odomCallback);\r\n\r\n ros::Publisher cmd_vel_pub_;\r\n cmd_vel_pub_ = n.advertise<geometry_msgs::Twist>(\"cmd_vel2\", 1);\r\n geometry_msgs::Twist base_cmd;\r\n\r\n ros::Rate r(10.0);\r\n\r\n while (n.ok())\r\n {\r\n ros::spinOnce();\r\n\r\n //current_time = ros::Time::now();\r\n double v_gain = 1.00;\r\n double w_gain = -1.00;\r\n\r\n base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;\r\n //\tbase_cmd.linear.x = myrobot.v * v_gain;\r\n //\tbase_cmd.angular.z = myrobot.w * w_gain;\r\n\r\n cmd_vel_pub_.publish(base_cmd);\r\n\r\n //cout<<\"x:\"<<base_cmd.linear.x<<\"\\t y:\"<<base_cmd.angular.z <<\"\\n\";\r\n\r\n r.sleep();\r\n }\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.6590909361839294, "alphanum_fraction": 0.6736363768577576, "avg_line_length": 21.148935317993164, "blob_id": "855ae88fbe7b589e35c157a5fff682e073d67efb", "content_id": "f81f0bd02c4b891d768bb143c47ca885a584da34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1316, "license_type": "no_license", "max_line_length": 114, "num_lines": 47, "path": "/n_object_tracking/readme.txt", "repo_name": "nnn112358/robotics_ros", "src_encoding": "SHIFT_JIS", "text": "##############################################\r\n#オブジェクトトラッキングNodeの使い方。\r\n##############################################\r\n\r\n\r\n\r\nNode [/n_object_traking_run_control]\r\nPublications: \r\n * /camera_pan_angle [std_msgs/Float32]\r\n * /cmd_vel2 [geometry_msgs/Twist]\r\n * /rosout [rosgraph_msgs/Log]\r\n * /camera_tilt_angle [std_msgs/Float32]\r\n\r\nSubscriptions: \r\n * /target_pos [geometry_msgs/Pose]\r\n\r\n \r\n1.概要\r\n URGからのデータをクラスタリングし追跡します\r\n。\r\n\r\n2.依存ライブラリ\r\nOpenGL/OpenCV/SDLをインストールする必要があります。\r\nsudo apt-get install build-essential\r\nsudo apt-get install freeglut3-dev libglew1.5-dev\r\nsudo apt-get install libxmu-dev libxi-dev\r\nsudo apt-get install libcv-dev libhighgui-dev libcvaux-dev python-opencv opencv-doc\r\nsudo apt-get install libsdl1.2-dev\r\n\r\n3.コンパイル\r\nmake\r\n\r\n4.実行\r\n./docu_object_tracking_lrf\r\n\r\n5.使い方\r\n\tPageUp:縮小\r\n\tPageDown:拡大\r\n\r\n右ドラック:オブジェクトの追跡\r\n左ドラック:画面の移動\r\n\r\n6.KinectでTest\r\n\r\nroslaunch freenect_launch freenect.launch\r\nrosrun image_view image_view image:=/camera/rgb/image_color\r\nrosrun depthimage_to_laserscan depthimage_to_laserscan image:=/camera/depth/image camera_info:=/camera/camera_info\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.4982364773750305, "alphanum_fraction": 0.5130348205566406, "avg_line_length": 21.21805763244629, "blob_id": "8154091e21b59bd2f54ae9498222669f8b7f09b8", "content_id": "87b54f071c56818341c5f2e3dc06e5e56ba5ca7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15990, "license_type": "no_license", "max_line_length": 92, "num_lines": 587, "path": "/n_3d_robot_sim/src/GLMetaseq.h", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "\n#ifndef __GLMETASEQ_H__\n#define __GLMETASEQ_H__\n\n/*=========================================================================================\n\n\tGLMetaseq.h\n\n\tメタセコイアで作成したモデル(*.mqo)をOpenGL上に読み込む関数をまとめたヘッダです.\n\tこのヘッダを使う上で以下の点に注意してください.\n\n \t ・扱えるテクスチャは24bitビットマップ画像\n\t ・テクスチャ画像のサイズは「一辺が2のn乗サイズ(64,128,256…)の正方形」に限る\n\t\n\tまた,最低限必要な機能しか実装していないので他にもいろいろ制約があります.\n\n\n\t再配布・改変は自由です.\n  Copyright (c) 工学ナビ, 2007-. ver.07/06/01\n\twebsite: http://www1.bbiq.jp/kougaku/\n\n=========================================================================================*/\n\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// ユーザが任意で設定\n#define MAX_MATERIAL\t1000\t\t\t// 最大マテリアル数\n#define MAX_VERTEX\t\t100000\t\t// 最大頂点数\n#define MAX_FACE\t\t100000\t\t// 最大面数\n\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// ヘッダ\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <GL/gl.h>\n#include <GL/glu.h>\n#include <GL/glut.h>\n\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// マクロ定義\n\ntypedef GLuint MQO_OBJECT;\t// MQO_OBJECTはディスプレイリストと同じ扱い\n\n#define SIZE_STR\t\t256\t// 文字列長\n#define NOUSE_TEXTURE\t0\t// テクスチャ未使用\n#define USE_TEXTURE\t\t1\t// テクスチャ使用\n#define MQO_FAILED\t\t-1\t// 処理失敗\n#define MQO_OK\t\t\t0\t// 処理成功\n\n// 最大値マクロ\n#ifndef MAX\n\t#define MAX(a, b) (((a) > (b)) ? (a) : (b))\n#endif\n\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// 構造体定義\n\n// OpenGL用色構造体\n#ifndef DEFINE_GLCOLOR\n#define DEFINE_GLCOLOR\n\ttypedef struct tag_glCOLOR{\n\t\tdouble r;\n\t\tdouble g;\n\t\tdouble b;\n\t\tdouble a;\n\t} glCOLOR;\n#endif\n\n\n// 2次元座標構造体\n#ifndef DEFINE_POINT2D\n#define DEFINE_POINT2D\n\ttypedef struct tagPOINT2D {\n\t\tdouble x;\n\t\tdouble y;\n\t} POINT2D;\n#endif\n\n\n// 3次元座標構造体\n#ifndef DEFINE_GLPOINT\n#define DEFINE_GLPOINT\n\ttypedef struct tag_glPOINT{\n\t\tdouble x;\n\t\tdouble y;\n\t\tdouble z;\n\t} glPOINT;\n#endif\n\n\n// メタセコイア面情報構造体\n#ifndef DEFINE_MQOFACE\n#define DEFINE_MQOFACE\n\ttypedef struct tagMQOFACE{\n\t\tint\t\tn;\t\t// 1つの面を構成する頂点の数(3~4)\n\t\tint\t\tm;\t\t// 面の材質番号\n\t\tint\t\tv[4];\t// 頂点番号を格納した配列\n\t\tPOINT2D uv[4];\t// UVマップ\n\t} MQOFACE;\n#endif\n\n\n// メタセコイア材質構造体\n#ifndef DEFINE_MQOMATERIAL\n#define DEFINE_MQOMATERIAL\n\ttypedef struct tagMQOMATERIAL{\n\t\tglCOLOR col;\t\t\t\t// 色\n\t\tint\t\tuseTex;\t\t\t\t// テクスチャの有無\n\t\tchar\ttexFile[SIZE_STR];\t// テクスチャファイル\n\t\tGLuint texName;\t\t\t// テクスチャ名\n\t\tGLubyte *texImage;\t\t\t// テクスチャ画像\n\t} MQOMATERIAL;\n#endif\n\n////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n/*=========================================================================\n【関数】mqoLoadTexture\n【用途】ビットマップファイルからテクスチャ画像を作成する\n【引数】\n\t\t*filename\tファイル名\n\t\t*tex_size\tテクスチャのサイズ(一辺の長さ)を返す\n\n【戻値】テクスチャ画像へのポインタ(失敗時はNULL)\n【仕様】24bitビットマップ限定\n\t\tサイズは「一辺が2のn乗の正方形」に限定\n=========================================================================*/\n/*\nGLubyte* mqoLoadTexture(char *filename,int *tex_size)\n{\n\tFILE *fp;\n\tint\ty,x,size;\n\tBITMAPFILEHEADER bmfh;\n\tBITMAPINFOHEADER bmih;\n\tGLubyte\t*pImage, *pRead;\n\n\tif ( (fp=fopen(filename,\"rb\"))==NULL ) return NULL;\n\n\t// ヘッダのロード\n\tfread(&bmfh,sizeof(BITMAPFILEHEADER),1,fp);\n\tfread(&bmih,sizeof(BITMAPINFOHEADER),1,fp);\t\n\tsize = bmih.biWidth;\n\n\t// メモリの確保\n\tpImage = (GLubyte*)malloc(sizeof(unsigned char)*size*size*4);\n\tif (pImage==NULL) return NULL;\n\n\tfor (y=0; y<size; y++){\n\t\tpRead = pImage + (size-1-y)*4*size;\n\t\tfor (x=0; x<size; x++) {\n\t\t\tfread(&pRead[2],1,1,fp);\t// B\n\t\t\tfread(&pRead[1],1,1,fp);\t// G\t\n\t\t\tfread(&pRead[0],1,1,fp);\t// R\n\t\t\tpRead[3] = 255;\t\t\t\t// A\n\t\t\tpRead+=4;\n\t\t}\n\t}\n\tfclose(fp);\n\t*tex_size = size;\n\n\treturn pImage;\n}\n\n\n*/\n/*=========================================================================\n【関数】mqoRegistTexture\n【用途】テクスチャの登録\n【引数】\n\t\t*tex_name\tテクスチャ名\n\t\t*tex_img\tテクスチャ画像へのポインタ\n\t\ttex_size\tテクスチャのサイズ(一辺の長さ)\n\n【戻値】なし\n=========================================================================*/\n\nvoid mqoRegistTexture(GLuint* tex_name,GLubyte* tex_img,int tex_size)\n{\n\tglPixelStorei(GL_UNPACK_ALIGNMENT,1);\n\tglDeleteTextures(1, tex_name);\t\t\t// 前回のテクスチャ情報を削除\n\tglGenTextures(1,tex_name);\t\t\t\t// テクスチャを生成\n\tglBindTexture(GL_TEXTURE_2D,*tex_name);\t// テクスチャの割り当て\n\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, tex_size, tex_size,\n\t\t\t\t\t0, GL_RGBA, GL_UNSIGNED_BYTE, tex_img);\n}\n\n\n\n/*=========================================================================\n【関数】mqoReleaseTexture\n【用途】テクスチャ画像の開放\n【引数】\n\t\t*pImage テクスチャ画像へのポインタ\n\n【戻値】なし\n【仕様】free()してるだけ\n=========================================================================*/\n\nvoid mqoReleaseTexture(void *pImage)\n{\n\tfree(pImage);\n}\n\n\n\n/*=========================================================================\n【関数】mqoSnormal\n【用途】法線ベクトルを求める\n【引数】\n\t\tA\t\t3次元座標上の点A\n\t\tB\t\t3次元座標上の点B\n\t\tC\t\t3次元座標上の点C\n\t\t*normal\tベクトルCAとベクトルCBの法線ベクトル(右ねじ方向)\n\n【戻値】なし\n=========================================================================*/\n\nvoid mqoSnormal(glPOINT A,glPOINT B,glPOINT C,glPOINT *normal)\n{\n\tdouble norm;\n\tglPOINT vec0,vec1;\n\n\tvec0.x = A.x-C.x; vec0.y = A.y-C.y; vec0.z = A.z - C.z;\n\tvec1.x = B.x-C.x; vec1.y = B.y-C.y; vec1.z = B.z - C.z;\n\n\tnormal->x = vec0.y * vec1.z - vec0.z * vec1.y;\n\tnormal->y = vec0.z * vec1.x - vec0.x * vec1.z;\n\tnormal->z = vec0.x * vec1.y - vec0.y * vec1.x;\n\n\t// 正規化する\n\tnorm = normal->x * normal->x + normal->y * normal->y + normal->z * normal->z;\n\tnorm = sqrt ( norm );\n\t\n\tnormal->x /= norm; normal->y /= norm; normal->z /= norm;\n}\n\n\n\n/*=========================================================================\n【関数】mqoReadMaterial\n【用途】メタセコイアファイルからマテリアル情報を読み込む\n【引数】\n\t\t*fp\t\t現在開いているファイルのファイルポインタ\n\t\tmat[]\tマテリアル情報を格納する配列\n\t\tmax_mat\tマテリアル数の上限\n\n【戻値】マテリアル情報の数\n【仕様】col属性とtex属性のみに対応\n\t\tmqoLoadFileの子関数なのでこれ単体で使うことはない\n=========================================================================*/\n\nint mqoReadMaterial(FILE *fp, MQOMATERIAL mat[],int max_mat)\n{\n\tint n_mat,i;\n\tchar buf[SIZE_STR];\n\tint len;\n\tchar *pStrEnd;\n\tchar *pStr;\n\n\t// マテリアル数を読み込む\n\tfgets(buf,SIZE_STR,fp);\n\tsscanf(buf,\"%d\",&n_mat);\n\tif ( n_mat > max_mat ) n_mat = max_mat;\t\t// 色数の上限設定\n\n\t// Materialの読み込み\n\tfor (i=0; i<n_mat; i++) {\n\n\t\tfgets(buf,SIZE_STR,fp);\t\t// 行読み込み\n\n\t\t// col\n\t\tif ( (pStr = strstr(buf,\"col\")) != NULL ) {\n\t\t\tsscanf(pStr,\"col(%lf %lf %lf %lf)\", \n\t\t\t\t &mat[i].col.r, &mat[i].col.g, &mat[i].col.b, &mat[i].col.a);\n\t\t}\n\n\t\t// tex\n\t\tif ( (pStr = strstr(buf,\"tex\")) != NULL ) {\n\t\t\tmat[i].useTex = USE_TEXTURE;\n\t\t\tpStrEnd = strstr(pStr,\"\\\")\");\n\t\t\tlen = pStrEnd - (pStr+5);\n\t\t\tstrncpy(mat[i].texFile,pStr+5,len);\n\t\t\tmat[i].texFile[len] = '\\0';\n\t\t} else {\n\t\t\tmat[i].useTex = NOUSE_TEXTURE;\n\t\t\tmat[i].texFile[0] = '\\0';\n\t\t\tmat[i].texImage = NULL;\n\t\t}\n\t}\n\n\treturn n_mat;\n}\n\n\n\n/*=========================================================================\n【関数】mqoReadVertex\n【用途】メタセコイアファイルから頂点情報を読み込む\n\n【引数】*fp\t\t\t現在オープンしているメタセコイアファイルのファイルポインタ\n\t\tV[]\t\t\t頂点を格納する配列\n\t\tmax_vertex\t頂点数の上限\n\n【戻値】頂点数\n【仕様】mqoLoadFileの子関数なのでこれ単体で使うことはない\n=========================================================================*/\n\nint mqoReadVertex(FILE *fp,glPOINT V[],int max_vertex)\n{\n\tint n_vertex,i;\n\n\tfscanf(fp,\"%d\",&n_vertex);\t\t\t\t\t\t\t// 頂点数を読み込む\n\tif (n_vertex>max_vertex) n_vertex = max_vertex;\t\t// 頂点数の上限設定\n\n\twhile (fgetc(fp)!='{');\t\t\t\t\t\t\t\t// 余分な文字を読み飛ばす\n\tfor (i=0; i<n_vertex; i++) {\n\t\tfscanf(fp,\"%lf %lf %lf\",&V[i].x,&V[i].y,&V[i].z);\n\t}\n\n\treturn n_vertex;\n}\n\n\n\n/*=========================================================================\n【関数】mqoReadFace\n【用途】メタセコイアファイルから面情報を読み込む\n\n【引数】*fp\t\t\t現在オープンしているメタセコイアファイルのファイルポインタ\n\t\tface[]\t\t面情報を格納する配列\n\t\tmax_face\t面数の上限\n\n【戻値】面数\n【仕様】mqoLoadFileの子関数なのでこれ単体で使うことはない\n=========================================================================*/\n\nint mqoReadFace(FILE *fp,MQOFACE face[],int max_face)\n{\n\tint n_face,i;\n\tchar *pStr;\n\tchar buf[SIZE_STR];\n\n\t// 面数を読み込む\n\tfgets(buf,SIZE_STR,fp);\n\tsscanf(buf,\"%d\",&n_face);\n\tif ( n_face > max_face ) n_face = max_face;\t\t// 面数の上限設定\n\t\n\tfor (i=0; i<n_face; i++) {\n\t\n\t\t// 行読み込み\n\t\tfgets(buf,SIZE_STR,fp);\n\n\t\t// 面を構成する頂点数\n\t\tsscanf(buf,\"%d\",&face[i].n);\n\n\t\t// 頂点(V)の読み込み\n\t\tif ( (pStr = strstr(buf,\"V(\")) != NULL ) {\n\t\t\tswitch (face[i].n) {\n\t\t\t\tcase 3:\n\t\t\t\t\tsscanf(pStr,\"V(%d %d %d)\",&face[i].v[0],&face[i].v[1],&face[i].v[2]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tsscanf(pStr,\"V(%d %d %d %d)\",&face[i].v[0],&face[i].v[1],&face[i].v[2],&face[i].v[3]);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\t\t\n\t\t}\n\n\t\t// マテリアル(M)の読み込み\n\t\tface[i].m = 0;\n\t\tif ( (pStr = strstr(buf,\"M(\")) != NULL ) {\n\t\t\tsscanf(pStr,\"M(%d)\",&face[i].m);\n\t\t}\n\n\t\t// UVマップ(UV)の読み込み\n\t\tif ( (pStr = strstr(buf,\"UV(\")) != NULL ) {\n\t\t\tswitch (face[i].n) {\n\t\t\t\tcase 3:\n\t\t\t\t\tsscanf(pStr,\"UV(%lf %lf %lf %lf %lf %lf)\",\n\t\t\t\t\t\t\t\t\t&face[i].uv[0].x, &face[i].uv[0].y,\n\t\t\t\t\t\t\t\t\t&face[i].uv[1].x, &face[i].uv[1].y,\n\t\t\t\t\t\t\t\t\t&face[i].uv[2].x, &face[i].uv[2].y\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tsscanf(pStr,\"UV(%lf %lf %lf %lf %lf %lf %lf %lf)\",\n\t\t\t\t\t\t\t\t\t&face[i].uv[0].x, &face[i].uv[0].y,\n\t\t\t\t\t\t\t\t\t&face[i].uv[1].x, &face[i].uv[1].y,\n\t\t\t\t\t\t\t\t\t&face[i].uv[2].x, &face[i].uv[2].y,\n\t\t\t\t\t\t\t\t\t&face[i].uv[3].x, &face[i].uv[3].y\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\t\t\n\t\t}\n\t}\n\n\treturn n_face;\n}\n\n\n\n/*=========================================================================\n【関数】mqoMakePolygon\n【用途】ポリゴンの作成\n【引数】\n\t\tF\t\t面情報\n\t\tV[]\t\t頂点配列\n\t\tM[]\t\tマテリアル配列\n\t\tscale\tスケール (1.0で等倍)\t\t\n【戻値】なし\n【仕様】この関数で1枚のポリゴンが作られる\n=========================================================================*/\n\nvoid mqoMakePolygon(MQOFACE F,glPOINT V[],MQOMATERIAL M[],double scale)\n{\n\tglPOINT normal;\t// 法線ベクトル\n\tint i;\n\n\tglColor4f(M[F.m].col.r, M[F.m].col.g, M[F.m].col.b, M[F.m].col.a);\t// 面の色\n\tmqoSnormal(V[F.v[0]],V[F.v[1]],V[F.v[2]],&normal);\t\t\t\t\t// 法線ベクトルを計算\n\n\tif (M[F.m].useTex==USE_TEXTURE) {\n\n\t\tglShadeModel(GL_FLAT);\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n\t\tglColor4f(1.0,1.0,1.0,1.0);\n\n\t\tglBindTexture(GL_TEXTURE_2D,M[F.m].texName);\n\t\t\tif (F.n==3) glBegin(GL_TRIANGLES);\n\t\t\tif (F.n==4) glBegin(GL_QUADS);\n\t\t\tfor (i=0; i<F.n; i++) {\n\t\t\t\tglTexCoord2f( F.uv[i].x, F.uv[i].y);\n\t\t\t\tglVertex3f(V[F.v[i]].x*scale, V[F.v[i]].y*scale, V[F.v[i]].z*scale);\n\t\t\t}\n\t\tglEnd();\n\n\t\tglDisable(GL_BLEND);\n\t\tglDisable(GL_TEXTURE_2D);\n\n\t} else {\n\n\t\tif (F.n==3) glBegin(GL_TRIANGLES);\n\t\tif (F.n==4) glBegin(GL_QUADS);\n\t\t\tglNormal3f(normal.x, normal.y, normal.z);\n\t\t\tfor (i=0; i<F.n; i++) {\n\t\t\t\tglTexCoord2f( F.uv[i].x, F.uv[i].y);\n\t\t\t\tglVertex3f(V[F.v[i]].x*scale, V[F.v[i]].y*scale, V[F.v[i]].z*scale);\n\t\t\t}\n\t\tglEnd();\n\t}\n\n}\n\n\n\n/*=========================================================================\n【関数】mqoLoadFile\n【用途】メタセコイアファイル(*.mqo)からモデルデータをOpenGLに読み込む\n【引数】\n\t\tfilename\tファイルのパス\n\t\tscale\t\t拡大率\n\n【戻値】成功:MQO_OK / 失敗:MQO_FAILED\n=========================================================================*/\n\nint mqoLoadFile(char *filename,double scale)\n{\n\tstatic glPOINT\t\tV[MAX_VERTEX];\t // 頂点\n\tstatic MQOMATERIAL\tM[MAX_MATERIAL]; // マテリアル\n\tstatic MQOFACE\t\tF[MAX_FACE];\t // 面\n\n\tFILE *fp;\n\tchar *pStr;\n\tchar buff[SIZE_STR];\t\t// 行バッファ\n\tchar path_dir[SIZE_STR];\t// ディレクトリのパス\n\tchar path_tex[SIZE_STR];\t// テクスチャファイルのパス\n\tint\ti, n_face, n_mat, len, tex_size;\n\n\n\t// ファイルを開く\n\tif ((fp = fopen(filename, \"r\")) == NULL) return MQO_FAILED;\n\n\t// パスの取得\n\tpStr = MAX( strrchr(filename,'\\\\'), strrchr(filename,'/') );\n\tlen = MAX((int)(pStr-filename)+1,0);\n\tstrncpy(path_dir,filename,len);\n\tpath_dir[len] = '\\0';\n\t\n\n\tglEnable(GL_DEPTH_TEST);\n\n\twhile (!feof(fp)) {\n\t\tfscanf(fp, \"%s\", buff);\n\n\t\tif (!strcmp(buff,\"Material\")) {\n\t\t\tn_mat = mqoReadMaterial(fp,M,MAX_MATERIAL);\n\n\t\t\tfor (i=0; i<n_mat; i++) {\n\t\t\t\tif (M[i].useTex == USE_TEXTURE)\t{\n\t\t\t\t//\tsprintf(path_tex,\"%s%s\",path_dir,M[i].texFile);\n\t\t\t\t//\tM[i].texImage = mqoLoadTexture(path_tex,&tex_size);\n\t\t\t\t//\tmqoRegistTexture(&(M[i].texName),M[i].texImage,tex_size);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!strcmp(buff,\"vertex\"))\t{\n\t\t\tmqoReadVertex(fp,V,MAX_VERTEX);\n\t\t}\n\n\t\tif (!strcmp(buff,\"face\")) {\n\t\t\tn_face = mqoReadFace(fp,F,MAX_FACE);\n\t\t\tfor (i=0; i<n_face; i++) {\n\t\t\t\tmqoMakePolygon(F[i],V,M,scale);\n\t\t\t}\n\t\t}\n\t}\n\tfclose(fp);\n\n\tglDisable(GL_DEPTH_TEST);\n\n\n\tfor (i=0; i<n_mat; i++) {\n\t\tmqoReleaseTexture(M[i].texImage);\n\t}\n\n\treturn MQO_OK;\n}\n\n\n\n/*=========================================================================\n【関数】mqoCreateObject\n【用途】メタセコイアファイル(*.mqo)からMQOオブジェクトを作成する\n【引数】filename\tファイルのパス\n\t\tscale\t\t拡大率\n\n【戻値】MQOオブジェクト\n【仕様】MQOオブジェクト(MQO_OBJECT)はただのディスプレイリストです.\n=========================================================================*/\n\nMQO_OBJECT mqoCreateObject(char *filename,double scale)\n{\n\tMQO_OBJECT displist;\n\n\tdisplist = glGenLists(1);\n\tglNewList(displist, GL_COMPILE_AND_EXECUTE);\n\t\tglPushMatrix();\n\t\t\tglRotatef(90.0f, 1.f, 0.f, 0.f); // ARToolKitではZ軸が上方向になるので\n\t\t\tif (mqoLoadFile(filename,scale)==MQO_FAILED) return 0; \n\t\tglPopMatrix();\n\tglEndList();\n\n\treturn displist;\n}\n\n\n\n/*=========================================================================\n【関数】mqoCallObject\n【用途】MQOオブジェクトをOpenGLの画面上に呼び出す\n【引数】\n\t\tobject\t\tMQOオブジェクト\n\n【戻値】なし\n=========================================================================*/\n\nvoid mqoCallObject(MQO_OBJECT object)\n{\n\tglCallList(object);\n}\n\n\n#endif" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 14, "blob_id": "e82da52c6d390d59cec3fe7bd3fb376ae12cf96f", "content_id": "9cd12f8701c76c3f8a7f6c6d6c91f27735070d0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17, "license_type": "no_license", "max_line_length": 14, "num_lines": 1, "path": "/README.md", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "# robotics_sim\n\n\n" }, { "alpha_fraction": 0.805084764957428, "alphanum_fraction": 0.8072034120559692, "avg_line_length": 41.818180084228516, "blob_id": "d5370524c1638016ce124a0e32088b0547817f0f", "content_id": "861189f99feb844f220b84ea3d8bba45951ba154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 472, "license_type": "no_license", "max_line_length": 53, "num_lines": 11, "path": "/other/inst_ros.sh", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "sudo apt-get install ros-indigo-roswww\nsudo apt-get install ros-indigo-joy\nsudo apt-get install ros-indigo-robot-pose-publisher \nsudo apt-get install ros-indigo-jsk-rviz-plugins \nsudo apt-get install ros-indigo-jsk-rqt-plugins \nsudo apt-get install ros-indigo-web-video-server\nsudo apt-get install ros-indigo-kobuki*\nsudo apt-get install ros-indigo-navigation\nsudo apt-get install ros-indigo-urg-node\nsudo apt-get install apache2\nsudo apt-get install ros-indigo-hector-*\n\n" }, { "alpha_fraction": 0.6897208094596863, "alphanum_fraction": 0.8229695558547974, "avg_line_length": 45.32352828979492, "blob_id": "e9e68164e9f4043fcebc373e173452bf98bc1b8b", "content_id": "9b296b9a47340b0cecd811e94e111d340e063af1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1576, "license_type": "no_license", "max_line_length": 51, "num_lines": 34, "path": "/simtest_launch2/test.bash", "repo_name": "nnn112358/robotics_ros", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n\ntimeout 600 roslaunch sim_2d_replay_base_001.launch\ntimeout 600 roslaunch sim_2d_replay_base_002.launch\ntimeout 600 roslaunch sim_2d_replay_base_003.launch\ntimeout 600 roslaunch sim_2d_replay_base_004.launch\ntimeout 600 roslaunch sim_2d_replay_base_005.launch\ntimeout 600 roslaunch sim_2d_replay_base_006.launch\ntimeout 600 roslaunch sim_2d_replay_base_007.launch\ntimeout 600 roslaunch sim_2d_replay_base_008.launch\ntimeout 600 roslaunch sim_2d_replay_base_009.launch\ntimeout 600 roslaunch sim_2d_replay_base_010.launch\ntimeout 600 roslaunch sim_2d_replay_base_011.launch\ntimeout 600 roslaunch sim_2d_replay_base_012.launch\ntimeout 600 roslaunch sim_2d_replay_base_013.launch\ntimeout 600 roslaunch sim_2d_replay_base_014.launch\ntimeout 600 roslaunch sim_2d_replay_base_015.launch\n\ntimeout 600 roslaunch sim_2d_replay_base_001.launch\ntimeout 600 roslaunch sim_2d_replay_base_002.launch\ntimeout 600 roslaunch sim_2d_replay_base_003.launch\ntimeout 600 roslaunch sim_2d_replay_base_004.launch\ntimeout 600 roslaunch sim_2d_replay_base_005.launch\ntimeout 600 roslaunch sim_2d_replay_base_006.launch\ntimeout 600 roslaunch sim_2d_replay_base_007.launch\ntimeout 600 roslaunch sim_2d_replay_base_008.launch\ntimeout 600 roslaunch sim_2d_replay_base_009.launch\ntimeout 600 roslaunch sim_2d_replay_base_010.launch\ntimeout 600 roslaunch sim_2d_replay_base_011.launch\ntimeout 600 roslaunch sim_2d_replay_base_012.launch\ntimeout 600 roslaunch sim_2d_replay_base_013.launch\ntimeout 600 roslaunch sim_2d_replay_base_014.launch\ntimeout 600 roslaunch sim_2d_replay_base_015.launch\n\n" } ]
109
TomasVPerez/ZoomNaitor
https://github.com/TomasVPerez/ZoomNaitor
550314da697b0d5fa4f1e70dc25561ff1c7f84f2
4aee1b5d9c150c5aed1bb592e55510728051283f
6a085042b213f802de391b67a7b837d0f514d210
refs/heads/main
2023-07-18T04:32:10.673895
2021-08-31T22:48:48
2021-08-31T22:48:48
347,491,824
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.64838707447052, "avg_line_length": 32.22222137451172, "blob_id": "11d3c5fa69d3dd8b2c41558fbce8714b51f4ec21", "content_id": "224d650aaf854084dd9d9366e8221f338bce2b9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1241, "license_type": "no_license", "max_line_length": 171, "num_lines": 36, "path": "/zoomNaitor.py", "repo_name": "TomasVPerez/ZoomNaitor", "src_encoding": "UTF-8", "text": "#TomasPerez\r\n#https://github.com/TomasVPerez\r\n\r\nfrom selenium import webdriver\r\nimport pyautogui, time, subprocess\r\n\r\nurlFisica = #urls de las clases de zoom. \r\n\r\nopciones = webdriver.ChromeOptions()\r\nopciones.add_experimental_option('excludeSwitches', ['enable-logging']) #Saca alertas molestas de la consola.\r\nchrome = webdriver.Chrome(options=opciones)\r\n\r\ndef iniciarClase(url):\r\n chrome.get(url)\r\n inicio = chrome.find_element_by_xpath('//*[@id=\"zoom-ui-frame\"]/div[2]/div/div[1]/div')\r\n inicio.click()\r\n time.sleep(2)\r\n pyautogui.press(\"tab\") #Se apreta el tabulador dos veces y el enter para aceptar el popup.\r\n pyautogui.press(\"tab\")\r\n pyautogui.press(\"enter\")\r\n\r\nfechaActual = time.ctime()\r\ndia = fechaActual.split(\" \")[0]\r\nhoraExacta = fechaActual.split(\" \")[3]\r\nhora = horaExacta.split(\":\")[0]\r\n\r\nwhile True:\r\n if dia == \"Mon\" and hora == \"15\" or dia == \"Tue\" and hora == \"10\" or dia == \"Fri\" and hora == \"08\": #Copiar y pegar para agregar materias. Cambiar los dias y horarios.\r\n iniciarClase(urlFisica)\r\n time.sleep(6) #Espera 6 segundos y cierra la pestaña\r\n chrome.close()\r\n break\r\n else:\r\n chrome.close()\r\n print(\"No tenes clase!\")\r\n break\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7832699418067932, "alphanum_fraction": 0.7832699418067932, "avg_line_length": 36.57143020629883, "blob_id": "57096b0aad9632f7be0f1a599653db5aa24bffae", "content_id": "88c41e7e725b7a82fcb2a999300d131af77a674f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 536, "license_type": "no_license", "max_line_length": 283, "num_lines": 14, "path": "/README.md", "repo_name": "TomasVPerez/ZoomNaitor", "src_encoding": "UTF-8", "text": "# ZoomNaitor\nAutomatizador de clases virtuales\n\n## ¿Cómo funciona?\n\nPonemos nuestros urls a nuestras clases de zoom en el código, tambien horarios y al correr el programa se fijará si tenemos clase. En caso de que sí, abre el url de la clase que nos toca y acepta el popup indicando que queremos abrir la aplicación desde la app de Zoom de nuestra pc.\n\n## Requerimientos:\n\nTener la versión de chromedriver correspondiente a tu versión de Google Chrome.\n\n### Nota: \n\nSeguramente sea mucho más simple usando el módulo schedule.\n" } ]
2
jamenne/WindingControl
https://github.com/jamenne/WindingControl
bee930ff1f4b7041f0757db0ff72deab8455a06e
946a4becc7ae8ffbd9c5dc33d7b4c230274c0af3
56ac0e3d059b68f7ce3e54996cba5b9d56508f70
refs/heads/master
2021-05-25T10:46:03.450603
2018-03-28T13:35:18
2018-03-28T13:35:18
127,144,465
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7574983835220337, "alphanum_fraction": 0.7677090167999268, "avg_line_length": 43.79999923706055, "blob_id": "6f13132f94627cabf406ef6dd1fea2ccbf08597b", "content_id": "049d7725bfc4657961a21c0d5808c56cc2d0a2a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1567, "license_type": "no_license", "max_line_length": 368, "num_lines": 35, "path": "/README.md", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "# Winding Control\n\nRepository contains files for the training and implementation of a Convolutional\nNeural Network (CNN) for the quality control of the Scintillating Fibre Mat \nwinding process. A setup containing a industry camera monitors the winding process and feed the pictures into a trained CNN for classification. If the winding pattern contains an error, the output of the camera sends a signal to the winding machine and stopps the process for correction. A GUI was developed to display the camera feed and the output of the classifier.\n\n## HOW TO RUN\nInstall required python packages: \n* Numpy\n* SciPy\n* PyQt5\n* PIL\n* matplotlib\n* keras\n\nInstall MVacquire python wrapper: \n* https://github.com/geggo/MVacquire\n\nIn Directory run the command: \n* python WindingControl.py\n* 'Run' displays a camera feed with the mvBlueFox3 using PyQt \n* 'Save' will save the displayed image to hard drive \n* 'Quit' determines the application\n* Camera setting handling available\n* Classification of incoming images working\n* 'Load' will prompt you to select a model for classification and load it\n* 'Start' will start the classification of images\n* 'Stop' will abort the classification of images\n* 'Save_Prob' will save classification probabilities to an array and after Classification is stopped or 'Save_Prob' is unchecked it will be saved to a file\n\n\n## for image processing\n* converts images from jpg to 600x800 bmp\n* remove .jpg ending and places .bmp\n* for i in *.jpg; do sips -s format bmp -s formatOptions 70 \"${i}\" -z 600 800 --out \"${i%jpg}bmp\"; done" }, { "alpha_fraction": 0.7523409724235535, "alphanum_fraction": 0.7523409724235535, "avg_line_length": 23.571428298950195, "blob_id": "b9e98bd2d62bdaacb8bfee910da8c60dd3564fde", "content_id": "8e2872910242203358ed5ce95e885142fec53fe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3097, "license_type": "no_license", "max_line_length": 58, "num_lines": 126, "path": "/CameraSettings.md", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "# Camera Settings\n## dir(dev.Setting.Base.Camera.GenICam)\n* ['AcquisitionControl',\n* 'AnalogControl',\n* 'CounterAndTimerControl',\n* 'DeviceControl',\n* 'DigitalIOControl',\n* 'FileAccessControl',\n* 'ImageFormatControl',\n* 'TransportLayerControl',\n* 'UserSetControl',\n* 'mvFrameAverageControl',\n* 'mvLogicGateControl']\n\n## dir(dev.Setting.Base.Camera.GenICam.AcquisitionControl)\n* ['AcquisitionBurstFrameCount',\n* 'AcquisitionFrameCount',\n* 'AcquisitionFrameRate',\n* 'AcquisitionMode',\n* 'ExposureAuto',\n* 'ExposureMode',\n* 'ExposureTime',\n* 'TriggerActivation',\n* 'TriggerDelay',\n* 'TriggerMode',\n* 'TriggerSelector',\n* 'TriggerSoftware@i',\n* 'TriggerSource',\n* 'mvAcquisitionFrameRateEnable',\n* 'mvAcquisitionFrameRateLimitMode',\n* 'mvAcquisitionMemoryMaxFrameCount',\n* 'mvAcquisitionMemoryMode',\n* 'mvCompressionKneepoint',\n* 'mvDefectivePixelEnable',\n* 'mvExposureAutoAOIMode',\n* 'mvExposureAutoAverageGrey',\n* 'mvExposureAutoHeight',\n* 'mvExposureAutoHighlightAOI',\n* 'mvExposureAutoLowerLimit',\n* 'mvExposureAutoOffsetX',\n* 'mvExposureAutoOffsetY',\n* 'mvExposureAutoUpperLimit',\n* 'mvExposureAutoWidth',\n* 'mvPretriggerFrameCount',\n* 'mvResultingFrameRate',\n* 'mvShutterMode']\n\n## dir(dev.Setting.Base.Camera.GenICam.AnalogControl)\n* ['BlackLevel',\n* 'BlackLevelSelector',\n* 'Gain',\n* 'GainAuto',\n* 'GainSelector',\n* 'mvGainAutoAOIMode',\n* 'mvGainAutoAverageGrey',\n* 'mvGainAutoHeight',\n* 'mvGainAutoHighlightAOI',\n* 'mvGainAutoLowerLimit',\n* 'mvGainAutoOffsetX',\n* 'mvGainAutoOffsetY',\n* 'mvGainAutoUpperLimit',\n* 'mvGainAutoWidth',\n* 'mvLinearLogarithmicMode',\n* 'mvTapBalancingMode']\n\n## dir(dev.Setting.Base.Camera.GenICam.DeviceControl)\n* ['DeviceCharacterSet',\n* 'DeviceClockFrequency',\n* 'DeviceClockSelector',\n* 'DeviceFamilyName',\n* 'DeviceFirmwareVersion',\n* 'DeviceGenCPVersionMajor',\n* 'DeviceGenCPVersionMinor',\n* 'DeviceID',\n* 'DeviceManifestEntrySelector',\n* 'DeviceManifestFileAddress',\n* 'DeviceManifestFileSize',\n* 'DeviceManifestFileType',\n* 'DeviceManifestSchemaMajorVersion',\n* 'DeviceManifestSchemaMinorVersion',\n* 'DeviceManifestXMLMajorVersion',\n* 'DeviceManifestXMLMinorVersion',\n* 'DeviceManifestXMLSubMinorVersion',\n* 'DeviceManufacturerInfo',\n* 'DeviceModelName',\n* 'DeviceReset@i',\n* 'DeviceScanType',\n* 'DeviceStreamChannelCount',\n* 'DeviceSupportedOption',\n* 'DeviceSupportedOptionSelector',\n* 'DeviceTLType',\n* 'DeviceTLVersionMajor',\n* 'DeviceTLVersionMinor',\n* 'DeviceTemperature',\n* 'DeviceTemperatureSelector',\n* 'DeviceUserID',\n* 'DeviceVendorName',\n* 'DeviceVersion',\n* 'Timestamp',\n* 'TimestampIncrement',\n* 'TimestampLatch@i',\n* 'mvDeviceClockFrequency',\n* 'mvDevicePowerMode',\n* 'mvDeviceProcessingUnit',\n* 'mvDeviceProcessingUnitSelector',\n* 'mvDeviceSensorColorMode',\n* 'mvDeviceSensorName']\n\n## dir(dev.Setting.Base.Camera.GenICam.ImageFormatControl)\n* ['BinningHorizontal',\n* 'BinningVertical',\n* 'DecimationHorizontal',\n* 'DecimationVertical',\n* 'Height',\n* 'HeightMax',\n* 'OffsetX',\n* 'OffsetY',\n* 'PixelColorFilter',\n* 'PixelFormat',\n* 'ReverseX',\n* 'ReverseY',\n* 'SensorHeight',\n* 'SensorWidth',\n* 'TestImageSelector',\n* 'Width',\n* 'WidthMax']\n\n" }, { "alpha_fraction": 0.625514030456543, "alphanum_fraction": 0.6319965124130249, "avg_line_length": 38.37523651123047, "blob_id": "d8fd7297c44cc8403eb4f8e6878e08848de58b55", "content_id": "2c6f5d012ad923f1ff2c3b45ed6277edd50f10e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20671, "license_type": "no_license", "max_line_length": 200, "num_lines": 525, "path": "/cpp-stuff/WindingControl.cpp", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "// WindingControl.cpp\n//\n// Copyright 2015 TU Dortmund, Physik, Experimentelle Physik 5\n//\n// Author: Janine Müller\n//\n//\n//\n\n#include \"WindingControl.h\"\n\n//OpenCV stuff\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n//mvIMPACT stuff\n#include <apps/Common/exampleHelper.h>\n#include <common/minmax.h>\n#include <mvIMPACT_CPP/mvIMPACT_acquire.h>\n#include <mvIMPACT_CPP/mvIMPACT_acquire_GenICam.h>\n\n\n#include <string>\n#include <iostream>\n#include <cassert>\n#include <cmath>\n#include <fstream>\n\nusing namespace std;\nusing namespace cv;\nusing namespace mvIMPACT::acquire;\nusing namespace mvIMPACT::acquire::GenICam;\n\n\n// Initializes the camera - working!\nDevice* OpenCam(DeviceManager &devMgr){\n\n\tDevice* pDev(nullptr);\n\n pDev = getDeviceFromUserInput( devMgr );\n\n if ( !pDev ) {\n cout << \"Default device not found. Maybe pick one frome the list?\" << endl;\n pDev = getDeviceFromUserInput( devMgr );\n if ( !pDev ) {\n cout << \"Unable to continue!\";\n cout << \"Press [ENTER] to end the application\" << endl;\n cin.get();\n exit(EXIT_FAILURE);\n }\n }\n\n cout << \"Initialising the device. This might take some time...\" << endl;\n try {\n pDev->open();\n }\n catch( const ImpactAcquireException& e ) {\n // this e.g. might happen if the same device is already opened in another process...\n cout << \"An error occurred while opening the device \" << pDev->serial.read() << \" (error code: \" << e.getErrorCode() << \"). Press any key to end the application...\" << endl;\n cout << \"Press [ENTER] to end the application\" << endl;\n cin.get();\n exit(EXIT_FAILURE);\n }\n\n cout << \"The device \" << pDev->serial.read() << \" has been opened.\" << endl;\n\n return pDev;\n}\n\n// Initializes the Image - working!\nMat InitializeImage(Device* pDev){\n\n Ptr<FunctionInterface> fi; // interface to get the frames from\n const int iMaxWaitTime_ms = 8000; // timeout to wait for a frame\n int requestNr(0); // handle frames by number and error codes\n int image_type(CV_8UC1); // Mat type when using mvImpact camera\n\n Request* pRequest(nullptr); // pointers to the actual frames/requests\n\n // set the pixel depth to 8 bit\n modifyPropertyValue(ImageDestination(pDev).pixelFormat, \"Mono8\");\n\n // start an interface to the device\n fi = new FunctionInterface(pDev);\n // send a request to the default request queue of the device and wait for the result.\n fi->imageRequestSingle();\n // Start the acquisition manually if this was requested(this is to prepare the driver for data capture and tell the device to start streaming data)\n if ( pDev->acquisitionStartStopBehaviour.read() == assbUser ) {\n TDMR_ERROR result = DMR_NO_ERROR;\n if ( (result = static_cast<TDMR_ERROR>(fi->acquisitionStart())) != DMR_NO_ERROR ) {\n cout << \"'FunctionInterface.acquisitionStart' returned with an unexpected result: \" << result\n << \"(\" << ImpactAcquireException::getErrorCodeAsString(result) << \")\" << endl;\n }\n }\n\n // wait for results from the default capture queue\n requestNr = fi->imageRequestWaitFor(iMaxWaitTime_ms);\n\n // get first frame so that width and height are defined\n pRequest = fi->getRequest(requestNr);\n if ( !pRequest->isOK() ) {\n cout << \"Error: \" << pRequest->requestResult.readS() << endl;\n exit(EXIT_FAILURE);\n }\n\n // get frame properties\n int cam_width = pRequest->imageWidth.read();\n int cam_height = pRequest->imageHeight.read();\n int channelcnt = pRequest->imageChannelCount.read();\n int bytesPP = pRequest->imageBytesPerPixel.read();\n\n cout << \"image width:\\t\" << cam_width << \"\\nimage height:\\t\" << cam_height << \"\\nNo channel:\\t\" << channelcnt << \"\\nbytes per pixel:\\t\" << bytesPP << endl;\n // this should no longer occur due to the fact that the pixel depth should've been set to Mono8 = 1 byte ; if this is the case exit with failure\n if (bytesPP > 1) {\n cout << \"Bytes per pixel should be 1! Please try to configure camera using wxPropView. EXIT\" << endl;\n exit(EXIT_FAILURE);\n }\n\n\n // import the frame from the request into the OpenCV container\n Mat frame = Mat(Size(cam_width, cam_height), image_type, pRequest->imageData.read());\n\n return frame;\n /*\n while(1) {\n namedWindow(\"Video Frame\", CV_WINDOW_AUTOSIZE);\n imshow(\"Video Frame\", frame);\n\n if(waitKey(0) == 27) break;\n }\n\n // close all windows\n startWindowThread(); // Must be called to destroy the windows properly\n destroyAllWindows(); // otherwise the windows will remain openend.\n */\n}\n\n// Asks for a single image - working!\nMat ImageRequestSingle(Device* pDev){ // Don't use for an continuous capture -> too slow\n\n FunctionInterface fi(pDev);\n\n // send a request to the default request queue of the device and wait for the result.\n fi.imageRequestSingle();\n manuallyStartAcquisitionIfNeeded( pDev, fi );\n\n // Define the Image Result Timeout (The maximum time allowed for the Application\n // to wait for a Result). Infinity value:-1\n const int iMaxWaitTime_ms = -1; // USB 1.1 on an embedded system needs a large timeout for the first image.\n\n // wait for results from the default capture queue.\n int requestNr = fi.imageRequestWaitFor( iMaxWaitTime_ms );\n manuallyStopAcquisitionIfNeeded( pDev, fi );\n\n // check if the image has been captured without any problems.\n if( !fi.isRequestNrValid( requestNr ) )\n {\n // If the error code is -2119(DEV_WAIT_FOR_REQUEST_FAILED), the documentation will provide\n // additional information under TDMR_ERROR in the interface reference\n cout << \"imageRequestWaitFor failed (\" << requestNr << \", \" << ImpactAcquireException::getErrorCodeAsString( requestNr ) << \")\"\n << \", timeout value too small?\" << endl;\n exit(EXIT_FAILURE);\n }\n\n const Request* pRequest = fi.getRequest( requestNr );\n if( !pRequest->isOK() )\n {\n cout << \"Error: \" << pRequest->requestResult.readS() << endl;\n // if the application wouldn't terminate at this point this buffer HAS TO be unlocked before\n // it can be used again as currently it is under control of the user. However terminating the application\n // will free the resources anyway thus the call\n // fi.imageRequestUnlock( requestNr );\n // can be omitted here.\n exit(EXIT_FAILURE);\n }\n\n cout << \"Image captured( \" << pRequest->imagePixelFormat.readS() << \" \" << pRequest->imageWidth.read() << \"x\" << pRequest->imageHeight.read() << \" )\" << endl;\n \n // import frame into OpenCV container\n Mat frame(1200,1600,CV_8U);\n frame = Mat(frame.size(), frame.type(), pRequest->imageData.read());\n\n return frame;\n}\n\n// shows the image of the camera continously - working!\nvoid ShowPictureOfCamera(Device* pDev){\n\n int CAM_HEIGHT, CAM_WIDTH;\n\n Ptr<FunctionInterface> fi; // interface to get the frames from\n const int iMaxWaitTime_ms = 8000; // timeout to wait for a frame\n int requestNr(0); // handle frames by number and error codes\n int image_type(CV_8UC1); // Mat type when using mvImpact camera\n\n Request* pRequest(nullptr), *pPreviousRequest(nullptr); // pointers to the actual frames/requests\n\n Mat whole(Size(0, 0), CV_8UC3); // container for the 'whole' video frame, CV_8UC3 means we use unsigned char types that are 8 bit long and each pixel has three of these to form the three channels\n\n // set the pixel depth to 8 bit\n modifyPropertyValue(ImageDestination(pDev).pixelFormat, \"Mono8\");\n\n // start an interface to the device\n fi = new FunctionInterface(pDev);\n // send a request to the default request queue of the device and wait for the result.\n fi->imageRequestSingle();\n // Start the acquisition manually if this was requested(this is to prepare the driver for data capture and tell the device to start streaming data)\n if ( pDev->acquisitionStartStopBehaviour.read() == assbUser ) {\n TDMR_ERROR result = DMR_NO_ERROR;\n if ( (result = static_cast<TDMR_ERROR>(fi->acquisitionStart())) != DMR_NO_ERROR ) {\n cout << \"'FunctionInterface.acquisitionStart' returned with an unexpected result: \" << result\n << \"(\" << ImpactAcquireException::getErrorCodeAsString(result) << \")\" << endl;\n }\n }\n\n // wait for results from the default capture queue\n requestNr = fi->imageRequestWaitFor(iMaxWaitTime_ms);\n\n // get first frame so that width and height are defined\n pRequest = fi->getRequest(requestNr);\n if ( !pRequest->isOK() ) {\n cout << \"Error: \" << pRequest->requestResult.readS() << endl;\n exit(EXIT_FAILURE);\n }\n\n // get frame properties\n CAM_WIDTH = pRequest->imageWidth.read();\n CAM_HEIGHT = pRequest->imageHeight.read();\n int channelcnt = pRequest->imageChannelCount.read();\n int bytesPP = pRequest->imageBytesPerPixel.read();\n\n cout << \"image width: \" << CAM_WIDTH << \" , image height: \" << CAM_HEIGHT << \" , No channel: \" << channelcnt << \" , bytes per pixel: \" << bytesPP << endl;\n // this should no longer occur due to the fact that the pixel depth should've been set to Mono8 = 1 byte ; if this is the case exit with failure\n if (bytesPP > 1) {\n cout << \"Bytes per pixel should be 1! Please try to configure camera using wxPropView. EXIT\" << endl;\n exit(EXIT_FAILURE);\n }\n\n // import the frame from the request into the OpenCV container\n whole = Mat(Size(CAM_WIDTH, CAM_HEIGHT), image_type, pRequest->imageData.read());\n\n // key pressed and time to wait at the end of the loop\n char key('a');\n int wait_ms(10);\n\n // open the main window, add a trackbar for wait_ms\n namedWindow(\"Video Frame\", CV_WINDOW_NORMAL);\n // resizeWindow(\"Video Frame\", CAM_WIDTH-305, CAM_HEIGHT);\n createTrackbar(\"waitKey duration:\", \"Video Frame\", &wait_ms, 1000, nullptr);\n\n // output format\n cout << \"Video format is h: \" << CAM_HEIGHT << \", w: \" << CAM_WIDTH << \"\\nLoop starts...\" << endl;\n\n // Create loop for continous streaming\n while (key != 27 && key != 'q'){ // end loop when 'ESC' or 'q' is pressed\n\n // show the processed frame and update the trackbars position\n imshow(\"Video Frame\", whole); // show the results in windows\n setTrackbarPos(\"waitKey duration:\", \"Video Frame\", wait_ms);\n\n key = waitKey(wait_ms); // Capture Keyboard stroke\n\n // again as before capture the next frame either from file or from device\n if ( pPreviousRequest ) pPreviousRequest->unlock();\n // this image has been displayed thus the buffer is no longer needed...\n pPreviousRequest = pRequest;\n\n fi->imageRequestSingle();\n requestNr = fi->imageRequestWaitFor(iMaxWaitTime_ms);\n\n // check if the image has been captured without any problems\n if ( !fi->isRequestNrValid(requestNr) ) {\n // If the error code is -2119(DEV_WAIT_FOR_REQUEST_FAILED), the documentation will provide\n // additional information under TDMR_ERROR in the interface reference\n cout << \"imageRequestWaitFor failed (\" << requestNr << \", \" << ImpactAcquireException::getErrorCodeAsString(requestNr) << \")\"\n << \", timeout value too small?\" << endl;\n exit(EXIT_FAILURE);\n }\n\n pRequest = fi->getRequest(requestNr);\n if ( !pRequest->isOK() ) {\n cout << \"Error: \" << pRequest->requestResult.readS() << endl;\n exit(EXIT_FAILURE);\n }\n\n // import frame into OpenCV container\n whole = Mat(Size(CAM_WIDTH, CAM_HEIGHT), image_type, pRequest->imageData.read());\n\n }\n\n cout << \"Loop ended. Releasing capture and destroying windows...\" << endl;\n\n // close all windows\n startWindowThread(); // Must be called to destroy the windows properly\n destroyAllWindows(); // otherwise the windows will remain openend.\n}\n\n// saves images as a video to file - working!\nvoid WriteVideoToFile(string outputName, Device* pDev){ \n\n int CAM_HEIGHT, CAM_WIDTH;\n\n Ptr<FunctionInterface> fi; // interface to get the frames from\n const int iMaxWaitTime_ms = 8000; // timeout to wait for a frame\n int requestNr(0); // handle frames by number and error codes\n int image_type(CV_8UC1); // Mat type when using mvImpact camera\n\n Request* pRequest(nullptr), *pPreviousRequest(nullptr); // pointers to the actual frames/requests\n\n Mat whole(Size(0, 0), CV_8UC3); // container for the 'whole' video frame, CV_8UC3 means we use unsigned char types that are 8 bit long and each pixel has three of these to form the three channels\n\n // set the pixel depth to 8 bit\n modifyPropertyValue(ImageDestination(pDev).pixelFormat, \"Mono8\");\n\n // start an interface to the device\n fi = new FunctionInterface(pDev);\n // send a request to the default request queue of the device and wait for the result.\n fi->imageRequestSingle();\n // Start the acquisition manually if this was requested(this is to prepare the driver for data capture and tell the device to start streaming data)\n if ( pDev->acquisitionStartStopBehaviour.read() == assbUser ) {\n TDMR_ERROR result = DMR_NO_ERROR;\n if ( (result = static_cast<TDMR_ERROR>(fi->acquisitionStart())) != DMR_NO_ERROR ) {\n cout << \"'FunctionInterface.acquisitionStart' returned with an unexpected result: \" << result\n << \"(\" << ImpactAcquireException::getErrorCodeAsString(result) << \")\" << endl;\n }\n }\n\n // wait for results from the default capture queue\n requestNr = fi->imageRequestWaitFor(iMaxWaitTime_ms);\n\n // get first frame so that width and height are defined\n pRequest = fi->getRequest(requestNr);\n if ( !pRequest->isOK() ) {\n cout << \"Error: \" << pRequest->requestResult.readS() << endl;\n exit(EXIT_FAILURE);\n }\n\n // get frame properties\n CAM_WIDTH = pRequest->imageWidth.read();\n CAM_HEIGHT = pRequest->imageHeight.read();\n int channelcnt = pRequest->imageChannelCount.read();\n int bytesPP = pRequest->imageBytesPerPixel.read();\n\n cout << \"image width: \" << CAM_WIDTH << \" , image height: \" << CAM_HEIGHT << \" , No channel: \" << channelcnt << \" , bytes per pixel: \" << bytesPP << endl;\n // this should no longer occur due to the fact that the pixel depth should've been set to Mono8 = 1 byte ; if this is the case exit with failure\n if (bytesPP > 1) {\n cout << \"Bytes per pixel should be 1! Please try to configure camera using wxPropView. EXIT\" << endl;\n exit(EXIT_FAILURE);\n }\n\n // import the frame from the request into the OpenCV container\n whole = Mat(Size(CAM_WIDTH, CAM_HEIGHT), image_type, pRequest->imageData.read());\n\n // it's important to set the last parameter bool isColor=false, otherwise he'll expect a colored image which doesn't exist!\n VideoWriter outputVideo(outputName,CV_FOURCC('M','J','P','G'),10, Size(CAM_WIDTH,CAM_HEIGHT),false);\n\n if (outputVideo.isOpened()) {\n cout << \"VideoWriter is opened. Writing videostream to file '\" << outputName << \"'\" << endl;\n } \n else{\n cout << \" VideoWriter couldn't be openend for file '\" << outputName << \"'. EXIT\" << endl;\n exit(EXIT_FAILURE);\n }\n\n // key pressed and time to wait at the end of the loop\n char key('a');\n int wait_ms(10);\n\n // open the main window, add a trackbar for wait_ms\n namedWindow(\"Video Frame\", CV_WINDOW_NORMAL);\n // resizeWindow(\"Video Frame\", CAM_WIDTH-305, CAM_HEIGHT);\n createTrackbar(\"waitKey duration:\", \"Video Frame\", &wait_ms, 1000, nullptr);\n\n // output format\n cout << \"Video format is h: \" << CAM_HEIGHT << \", w: \" << CAM_WIDTH << \"\\nLoop starts...\" << endl;\n\n // Create loop for continous streaming\n while (key != 27 && key != 'q'){ // end loop when 'ESC' or 'q' is pressed\n\n // show the processed frame and update the trackbars position\n imshow(\"Video Frame\", whole); // show the results in windows\n setTrackbarPos(\"waitKey duration:\", \"Video Frame\", wait_ms);\n\n // write Video to file\n outputVideo.write(whole);\n\n key = waitKey(wait_ms); // Capture Keyboard stroke\n\n // again as before capture the next frame either from file or from device\n if ( pPreviousRequest ) pPreviousRequest->unlock();\n // this image has been displayed thus the buffer is no longer needed...\n pPreviousRequest = pRequest;\n\n fi->imageRequestSingle();\n requestNr = fi->imageRequestWaitFor(iMaxWaitTime_ms);\n\n // check if the image has been captured without any problems\n if ( !fi->isRequestNrValid(requestNr) ) {\n // If the error code is -2119(DEV_WAIT_FOR_REQUEST_FAILED), the documentation will provide\n // additional information under TDMR_ERROR in the interface reference\n cout << \"imageRequestWaitFor failed (\" << requestNr << \", \" << ImpactAcquireException::getErrorCodeAsString(requestNr) << \")\"\n << \", timeout value too small?\" << endl;\n exit(EXIT_FAILURE);\n }\n\n pRequest = fi->getRequest(requestNr);\n if ( !pRequest->isOK() ) {\n cout << \"Error: \" << pRequest->requestResult.readS() << endl;\n exit(EXIT_FAILURE);\n }\n\n // import frame into OpenCV container\n whole = Mat(Size(CAM_WIDTH, CAM_HEIGHT), image_type, pRequest->imageData.read());\n\n }\n\n cout << \"Loop ended. Releasing capture and destroying windows...\" << endl;\n\n // close all windows\n startWindowThread(); // Must be called to destroy the windows properly\n destroyAllWindows(); // otherwise the windows will remain openend.\n\n}\n\n// reads a captured video from a file - working! \nvoid CaptureVideoFromFile(string VideoName){\n\n VideoCapture cap(VideoName); // open the video file for reading\n\n\n if( !cap.isOpened() ) // if not success, exit program\n {\n cout << \"Cannot open the video file\" << endl;\n exit(EXIT_FAILURE);\n }\n\n //cap.set(CV_CAP_PROP_POS_MSEC, 300); //start the video at 300ms\n\n double fps = cap.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video\n\n cout << \"Frame per seconds : \" << fps << endl;\n\n namedWindow(\"MyVideo\",CV_WINDOW_AUTOSIZE); //create a window called \"MyVideo\"\n\n while(1)\n {\n Mat frame;\n\n bool bSuccess = cap.read(frame); // read a new frame from video\n\n if (!bSuccess) //if not success, break loop\n {\n cout << \"Cannot read the frame from video file\" << endl;\n break;\n }\n\n imshow(\"MyVideo\", frame); //show the frame in \"MyVideo\" window\n\n if(waitKey(30) == 27) //wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop\n {\n cout << \"esc key is pressed by user\" << endl; \n break; \n }\n\n }\n \n\n}\n\n// sets an chosen Output to an On or Off state - working!\nvoid SetOutput( Device* pDev, int Output, bool On ){\n//-----------------------------------------------------------------------------\n// This device has 6 DigitalIOs\n// ------------------------------------------\n// IO 0: Type: Output Current state: OFF\n// IO 1: Type: Output Current state: OFF\n// IO 2: Type: Output Current state: OFF\n// IO 3: Type: Output Current state: OFF\n// IO 4: Type: Input Current state: OFF\n// IO 5: Type: Input Current state: OFF\n// ------------------------------------------\n try{\n\n DigitalIOControl dioc( pDev );\n\n //Count the number of Digital IOs\n const unsigned int IOCount = dioc.lineSelector.dictSize();\n\n const unsigned int index = static_cast<unsigned int>( Output );\n\n if( ( index >= IOCount ))\n {\n cout << \"Invalid selection\" << endl;\n exit(EXIT_FAILURE);\n }\n\n //Define the IO we are interested in\n dioc.lineSelector.write( index );\n\n //check whether selected IO is an Output or an Input\n if( dioc.lineMode.readS() == \"Output\" )\n {\n if (On)\n {\n dioc.lineInverter.write( bTrue );\n }\n\n else dioc.lineInverter.write( bFalse );\n }\n\n else{\n \n cout << \"IO \" << index << \" is a '\" << dioc.lineMode.readS() << \"'!\" << endl;\n }\n }\n\n catch( const ImpactAcquireException& e )\n {\n cout << endl;\n cout << \" An mvIMPACT Acquire Exception occurred:\" << e.getErrorCodeAsString() << endl;\n cout << endl;\n }\n\n}" }, { "alpha_fraction": 0.7303312420845032, "alphanum_fraction": 0.7412008047103882, "avg_line_length": 32.894737243652344, "blob_id": "e741aba0883a1bf15b11f7fe249b3cc83516e007", "content_id": "4621bf3f20d3bd7422cc43d82533dca772429c91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1932, "license_type": "no_license", "max_line_length": 93, "num_lines": 57, "path": "/cpp-stuff/CMakeLists.txt", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8)\n\nproject(WindingControl)\nset(PROJECT_VERSION 0.0.0.0)\nset(PROJECT_BRIEF \"\\\"No description\\\"\")\n\nset(CMAKE_CXX_FLAGS_DBG \"-O0 -ggdb\" CACHE STRING \"Debug options.\" FORCE)\nset(CMAKE_CXX_FLAGS_RELEASE \"-O3 -DNDEBUG\" CACHE STRING \"Debug options.\" FORCE)\nSET(CMAKE_CXX_FLAGS_PROFILING \"-O3 -pg\" CACHE STRING \"Debug options.\" FORCE)\n\nset(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} \"${CMAKE_SOURCE_DIR}/cmake/\")\nset(LIBRARY_OUTPUT_PATH \"${CMAKE_BINARY_DIR}/lib\")\nset(EXECUTABLE_OUTPUT_PATH \"${CMAKE_BINARY_DIR}/bin\")\n\n# BOOST, provides free peer-reviewed portable C++ source libraies\nset(Boost_USE_STATIC_LIBS OFF) \nset(Boost_USE_MULTITHREADED ON) \nset(Boost_USE_STATIC_RUNTIME OFF) \nfind_package(Boost 1.54.0 COMPONENTS system filesystem regex REQUIRED) \n\nif(Boost_FOUND)\n include_directories(${Boost_INCLUDE_DIRS}) \nendif()\n\n# mvIMPACT Acquire SDK\nfind_package( mvIMPACT REQUIRED )\nINCLUDE_DIRECTORIES( ${mvIMPACT_INCLUDE_DIRS} )\nset( LIBRARIES ${LIBRARIES} ${mvIMPACT_LIBRARIES} )\n\n# Find and include OpenCV directories\nfind_package(OpenCV REQUIRED)\nif(${OpenCV_FOUND})\n MESSAGE(STATUS \"OpenCV version: \" ${OpenCV_VERSION})\n MESSAGE(STATUS \"OpenCV libs: \" ${OpenCV_LIBS})\nendif(${OpenCV_FOUND})\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\nif(${APPLE})\n\n MESSAGE( STATUS \"Building for Mac OS X, switching on C++11 flags for Mac OS X/clang\" )\n\n SET(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11 -pedantic -Wall -Wextra\")\n\nendif(${APPLE})\n\nIF(${CMAKE_SYSTEM_NAME} MATCHES \"Linux\")\n\n MESSAGE( STATUS \"Building for Linux, switching on C++11 flags for Linux/gcc\" )\n\n SET(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++0x -pedantic -Wall -Wextra -O0 -ggdb\")\n\nENDIF(${CMAKE_SYSTEM_NAME} MATCHES \"Linux\")\n\nadd_library(WindingControl WindingControl.cpp)\n\nadd_executable(WindingControlMain WindingControlMain.cpp)\ntarget_link_libraries(WindingControlMain WindingControl ${mvIMPACT_LIBRARIES} ${OpenCV_LIBS})\n" }, { "alpha_fraction": 0.7361563444137573, "alphanum_fraction": 0.7448425889015198, "avg_line_length": 21.487804412841797, "blob_id": "0e2de48eb9a5b553f22e800c0ebc54b92ee17476", "content_id": "e42164ef664d1f3590768ca682af1215c9a3bb5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 921, "license_type": "no_license", "max_line_length": 62, "num_lines": 41, "path": "/cpp-stuff/WindingControl.h", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "// WindingControl.h\n//\n// Copyright 2015 TU Dortmund, Physik, Experimentelle Physik 5\n//\n// Author: Janine Müller\n//\n//\n//\n\n#ifndef ____WindingControl__\n#define ____WindingControl__\n\n#include <string>\n\n//OpenCV stuff\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n//mvIMPACT stuff\n#include <apps/Common/exampleHelper.h>\n#include <common/minmax.h>\n#include <mvIMPACT_CPP/mvIMPACT_acquire.h>\n\n\nusing namespace std;\nusing namespace cv;\n\nvoid CaptureVideoFromFile(string);\nvoid WriteVideoToFile(string, Device*);\nDevice* OpenCam(DeviceManager &devMgr);\nvoid ShowPictureOfCamera(Device* pDev);\nMat ImageRequestSingle(Device* pDev);\nMat InitializeImage(Device* pDev);\nvoid SaveSingleImageToFile(Device* pDev, string path);\n\n// sets an chosen Output to an On or Off state\nvoid SetOutput( Device* pDev, int Output, bool On );\n\n\n#endif /* defined(____WindingControl__) */" }, { "alpha_fraction": 0.5563660264015198, "alphanum_fraction": 0.5665782690048218, "avg_line_length": 35.900489807128906, "blob_id": "b84fde535e87acb831e1e0903d740bc38bd988be", "content_id": "ce684a1ae146ab6b33abf64943f49704eab5fc76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22634, "license_type": "no_license", "max_line_length": 170, "num_lines": 613, "path": "/WindingControl.py", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "#############################################################################################\n######### #########\n######### Created by Janine Müller #########\n######### #########\n######### #########\n######### 21.08.2017 at TU Dortmund #########\n######### #########\n######### #########\n######### #########\n######### #########\n######### 'Run' displays a camera feed with the mvBlueFox3 using PyQt #########\n######### Loads a selected images with the 'Load' button #########\n######### Saves a displayed image with the 'Save' button to hard drive #########\n######### 'Quit' determines the application #########\n######### #########\n#############################################################################################\n\n\nimport sys\nimport os\n\nfrom threading import Thread\nfrom six.moves.queue import Queue, Empty, Full\n\n# Qt stuff\nfrom PyQt5.QtWidgets import QApplication, QWidget, QCheckBox, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout, QLabel, QFileDialog, QSlider, QFrame\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport pyqtgraph as pg\n\nfrom keras.models import load_model\nimport scipy.misc #library for resizing buffer image\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport mv as mv\n\nfrom PIL import ImageQt\n\nfrom datetime import datetime\n\nfrom functools import partial\n\nimport time\n\n\n################################################## Image Aquisition ##################################################\n\n# Class to aquire images from camera\n# from https://github.com/geggo/MVacquire/\nclass AcquisitionThread(Thread):\n \n def __init__(self, device, queue):\n super(AcquisitionThread, self).__init__()\n self.dev = device\n self.queue = queue\n self.wants_abort = False\n self.running = False\n self.liveclassification = LiveClassification()\n self.classification = False\n self.save_feed = False\n self.save_img = False\n self.neg_counter = 0\n self.GPO_ON = False \n\n\n def acquire_image(self):\n #try to submit 2 new requests -> queue always full\n try:\n self.dev.image_request()\n self.dev.image_request()\n except mv.MVError as e:\n pass\n\n #get image\n image_result = None\n try:\n image_result = self.dev.get_image()\n except mv.MVTimeoutError:\n print(\"timeout\")\n except Exception as e:\n print(\"camera error: \",e)\n \n #pack image data together with metadata in a dict\n if image_result is not None:\n buf = image_result.get_buffer()\n imgdata = np.array(buf, copy = False)\n\n info=image_result.info\n timestamp = info['timeStamp_us']\n frameNr = info['frameNr']\n\n ### Classification of image\n if self.classification == True:\n neg = self.liveclassification.classify_image(imgdata)\n\n if neg == True:\n self.neg_counter += 1\n print('Count up: {:d}'.format(self.neg_counter))\n\n if neg == False:\n self.neg_counter = 0\n #print('reset counter')\n\n if self.neg_counter >= 1000000:\n # trigger stopping signal to machine\n self.switch_output()\n self.classification=False\n self.neg_counter = 0\n\n time.sleep(5)\n\n self.switch_output()\n\n\n\n ### Saving Image\n if self.save_img == True:\n self.liveclassification.save_image(imgdata, timestamp)\n self.save_img = False\n \n ## Saving Feed\n if self.save_feed == True:\n img = scipy.misc.imresize(imgdata, (75, 100))\n self.liveclassification.save_image(img, timestamp)\n\n del image_result\n return dict(img=imgdata, t=timestamp, N=frameNr)\n \n def reset(self):\n self.dev.image_request_reset()\n \n # Method representing the thread’s activity.\n # You may override this method in a subclass. - YES, we'll do it HERE -\n # The standard run() method invokes the callable object passed to the object’s constructor as the target argument, \n # if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. \n def run(self):\n self.reset()\n while not self.wants_abort:\n img = self.acquire_image()\n if img is not None:\n try:\n self.queue.put_nowait(img)\n\n #print('.',) #\n except Full:\n #print('!',)\n pass\n\n self.reset()\n print(\"acquisition thread finished\")\n\n def stop(self):\n self.wants_abort = True\n\n\n def switch_output(self):\n # ------------------------------------------\n # This device has 6 DigitalIOs\n # ------------------------------------------\n # IO 0: Type: Output Current state: OFF\n # IO 1: Type: Output Current state: OFF\n # IO 2: Type: Output Current state: OFF\n # IO 3: Type: Output Current state: OFF\n # IO 4: Type: Input Current state: OFF\n # IO 5: Type: Input Current state: OFF\n # ------------------------------------------\n # status = 1: switching GPO ON\n # status = 0: switching GPO OFF\n if self.GPO_ON == True:\n self.dev.Setting.Base.Camera.GenICam.DigitalIOControl.LineStatusAll\n self.dev.Setting.Base.Camera.GenICam.DigitalIOControl.LineInverter=0\n self.dev.Setting.Base.Camera.GenICam.DigitalIOControl.LineStatusAll\n print('Switched Output OFF')\n self.GPO_ON=False\n\n elif self.GPO_ON == False:\n self.dev.Setting.Base.Camera.GenICam.DigitalIOControl.LineStatusAll\n self.dev.Setting.Base.Camera.GenICam.DigitalIOControl.LineInverter=1\n self.dev.Setting.Base.Camera.GenICam.DigitalIOControl.LineStatusAll\n print('Switched Output ON')\n self.GPO_ON = True\n\n############################################ CLASSIFICATION / CAMERA ##########################################\nclass LiveClassification:\n def __init__(self):\n super(LiveClassification, self).__init__()\n\n self.model = load_model('/home/windingcontrol/src/WindingControl/TrainedModels/2017-09-15/165_163_163_200.h5')\n self.prob_total = []\n self.save_prob = False\n self.negative = False\n self.means = np.loadtxt('../Means.txt')\n self.stds = np.loadtxt('../StdDev.txt')\n\n self.path_dir = '/home/windingcontrol/WindingImages/' + str(datetime.now().strftime('%Y-%m-%d') + '/')\n if not os.path.exists(self.path_dir):\n os.makedirs(self.path_dir)\n print('Created path: {}'.format(self.path_dir))\n\n self.path_dir_Data = '/home/windingcontrol/src/WindingControl/Data/' + str(datetime.now().strftime('%Y-%m-%d') + '/')\n if not os.path.exists(self.path_dir_Data):\n os.makedirs(self.path_dir_Data)\n print('Created path: {}'.format(self.path_dir_Data))\n\n\n\n def classify_image(self,imgdata):\n\n #resizing image to parse through NN\n img = scipy.misc.imresize(imgdata, (75, 100)) \n # apply normalization\n img = (img-self.means)/self.stds\n #reshaping data ato parse into keras prediction\n img = np.reshape(img,[1,75,100,1]) \n #find prediction probability\n Prob = self.model.predict_proba(img, verbose=0) \n self.prob = np.squeeze(Prob)\n \n print('{:}'.format(self.prob))\n\n if self.save_prob == True:\n self.prob_total.append(self.prob)\n \n if Prob < 0.5:\n print('NEGATIVE')\n self.negative = True\n else:\n print('POSITIVE')\n self.negative = False\n\n return self.negative\n\n def save_probs_to_file(self):\n \n self.prob_total = np.array(self.prob_total)\n np.savetxt('{}WindingProb_{}.txt'.format(self.path_dir_Data, str(datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))), self.prob_total)\n print('File written!')\n self.written = True\n self.prob_total = []\n\n def save_image(self, imgdata, timestamp):\n\n scipy.misc.toimage(imgdata).save( '{}IMG_{}.jpg'.format(self.path_dir, timestamp) )\n #print('Successfully saved image to file: {:}'.format(self.path_dir) )\n\n\n def load_kerasmodel(self, fname):\n\n self.model = load_model(fname) #loading trained NN\n print('Load selected model')\n\n################################################## QT DISPLAY ##################################################\nclass App(QWidget):\n \n def __init__(self, ac_thread, parent=None):\n super(App, self).__init__(parent)\n self.title = 'Winding Control'\n self.left = 10\n self.top = 10\n self.width = 640\n self.height = 480\n self.thread = ac_thread\n self.save_im = False\n self.debugtool = None\n\n self.initGUI()\n \n def initGUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n # Image viewing region\n self.lbl = QLabel(self)\n self.lbl.setStyleSheet(\"border: 15px solid white; background-color: white; inset grey\")\n self.lbl.setFrameShape(QFrame.StyledPanel)\n self.lbl.setFrameShadow(QFrame.Sunken)\n\n # Slider for camera settings on a grid layout (4x4)\n self.exposure = self.create_slider(\"Exposure\", 10, 1e6, 58300)\n self.gain = self.create_slider(\"Gain\", 5, 18, 5)\n self.blacklevel = self.create_slider(\"Blacklevel\", -100, 100, 0)\n self.framerate = self.create_slider(\"Framerate\", 1, 20, 15)\n\n grid = QGridLayout()\n grid.addWidget(self.exposure, 0,0)\n grid.addWidget(self.gain, 0,1)\n grid.addWidget(self.blacklevel, 1,0)\n grid.addWidget(self.framerate, 1,1)\n\n # RadioButton for saving the Probabilities\n self.check_but1 = QCheckBox('Save_Prob')\n self.check_but1.setChecked(False)\n self.check_but1.stateChanged.connect(partial( self.save_probabilities, self.check_but1 ))\n\n # RadioButton for saving the video feed\n self.check_but2 = QCheckBox('Save_Feed')\n self.check_but2.setChecked(False)\n self.check_but2.stateChanged.connect(partial( self.save_feed, self.check_but2 ))\n\n # A horizontal layout to include the button on the left\n layout_button = QHBoxLayout()\n layout_button.addWidget(self.create_button(\"Load Model\", self.load_kerasmodel_but))\n layout_button.addWidget(self.create_button(\"Save Image\", self.save_image))\n layout_button.addWidget(self.create_button(\"Show\", self.run_aquisition))\n layout_button.addWidget(self.create_button(\"Start\", self.start_classification))\n layout_button.addWidget(self.create_button(\"Stop\", self.stop_classification))\n layout_button.addWidget(self.create_button(\"Debug\", self.start_debugtool))\n layout_button.addWidget(self.create_button(\"Quit\", self.quit))\n layout_button.addWidget(self.check_but1)\n layout_button.addWidget(self.check_but2)\n layout_button.addStretch()\n\n # A Vertical layout to include the button layout and then the image\n layout = QVBoxLayout()\n layout.addLayout(layout_button)\n layout.addLayout(grid)\n layout.addWidget(self.lbl)\n\n self.setLayout(layout)\n self.show()\n\n def create_slider(self, label, minV, maxV, value):\n groupBox = QGroupBox(label)\n\n slider = QSlider(Qt.Horizontal)\n slider.setMinimum(minV)\n slider.setMaximum(maxV)\n slider.setValue(value)\n slider.setTickPosition(QSlider.TicksBelow)\n slider.setTickInterval( (maxV-minV+1)/10 )\n slider.setFocusPolicy(Qt.NoFocus)\n\n slider.valueChanged.connect(partial (self.slider_val_changed, label) )\n\n vbox = QVBoxLayout()\n vbox.addWidget(slider)\n vbox.addStretch(2)\n\n #vbox.setGeometry(10, 10, 200, 30)\n groupBox.setLayout(vbox)\n\n return groupBox\n\n def create_button(self, label, func):\n\n button = QPushButton(label)\n button.clicked.connect(func)\n\n return button\n\n @pyqtSlot()\n def load_kerasmodel_but(self):\n \"\"\"\n Open a File dialog when the button is pressed\n :return:\n \"\"\"\n #Get the file location\n self.fname, _ = QFileDialog.getOpenFileName(self, 'Open')\n # Load the image from the location\n self.thread.liveclassification.load_kerasmodel(self.fname)\n\n def start_debugtool(self):\n self.debugtool = DebuggingWindow(self.thread)\n self.debugtool.show()\n\n def save_probabilities(self, b):\n if b.isChecked() == True:\n self.thread.liveclassification.save_prob = True\n print('Probabilities are being saved in array!')\n\n else:\n if self.thread.liveclassification.save_prob == True:\n self.thread.liveclassification.save_prob = False\n\n # save collected probs in File\n self.thread.liveclassification.save_probs_to_file()\n\n def save_feed(self, b):\n if b.isChecked() == True:\n self.thread.save_feed = True\n print('Images are being saved to hard disk!')\n\n else:\n if self.thread.save_feed == True:\n self.thread.save_feed = False\n\n\n def slider_val_changed(self, label):\n\n if label == \"Exposure\":\n val = self.exposure.findChild(QSlider).value()\n self.thread.dev.Setting.Base.Camera.GenICam.AcquisitionControl.ExposureTime=val\n print('Changed Exposure Time to {}'.format(val))\n\n if label == \"Gain\":\n val = self.gain.findChild(QSlider).value()\n self.thread.dev.Setting.Base.Camera.GenICam.AnalogControl.Gain=val\n print('Changed ' + label + ' to {}'.format(val))\n\n if label == \"Blacklevel\":\n val = self.blacklevel.findChild(QSlider).value()\n self.thread.dev.Setting.Base.Camera.GenICam.AnalogControl.BlackLevel=val\n print('Changed ' + label + ' to {}'.format(val))\n\n if label == \"Framerate\":\n val = self.framerate.findChild(QSlider).value()\n self.thread.dev.Setting.Base.Camera.GenICam.AcquisitionControl.mvAcquisitionFrameRateEnable=1\n #print('{:d}'.format(self.thread.dev.Setting.Base.Camera.GenICam.AcquisitionControl.mvAcquisitionFrameRateEnable))\n self.thread.dev.Setting.Base.Camera.GenICam.AcquisitionControl.AcquisitionFrameRate=val\n #print('{:.2f}'.format(self.thread.dev.Setting.Base.Camera.GenICam.AcquisitionControl.AcquisitionFrameRate))\n print('Changed ' + label + ' to {}'.format(val))\n\n def run_aquisition(self):\n # Start the thread’s activity.\n # It must be called at most once per thread object. \n # It arranges for the object’s run() method to be invoked in a separate thread of control.\n # This method will raise a RuntimeError if called more than once on the same thread object.\n self.thread.wants_abort = False\n self.thread.start()\n self.thread.running = True\n\n timer = QTimer(self)\n timer.timeout.connect(self.open)\n timer.start(20) #30 Hz\n\n def stop_aquisition(self):\n #wait until acquisition thread has stopped\n self.thread.stop()\n\n # Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates \n # – either normally or through an unhandled exception – or until the optional timeout occurs.\n # When the timeout argument is present and not None, it should be a floating point number \n # specifying a timeout for the operation in seconds (or fractions thereof). \n # As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened \n # – if the thread is still alive, the join() call timed out.\n # When the timeout argument is not present or None, the operation will block until the thread terminates.\n # A thread can be join()ed many times.\n # join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. \n # It is also an error to join() a thread before it has been started and attempts to do so raise the same exception.\n self.thread.join()\n\n def start_classification(self):\n if self.thread.liveclassification is None:\n self.thread.liveclassification = LiveClassification()\n \n if self.thread.liveclassification.model is not None:\n print('Start Classification')\n self.thread.liveclassification.prob_total = []\n self.thread.classification = True\n else:\n print('Load Model first!')\n\n\n def stop_classification(self):\n print('Stop Classification')\n self.thread.classification = False\n self.thread.plotting = False\n if self.thread.liveclassification.save_prob == True:\n # save collected probs in File\n self.thread.liveclassification.save_probs_to_file()\n\n def open(self):\n try:\n # get image\n img = self.thread.queue.get(block=True, timeout = 1)\n # convert image to pixmap to show it int GUI\n q = QPixmap.fromImage(ImageQt.ImageQt(scipy.misc.toimage(img['img'])))\n q = q.scaled(1200, 900)\n if self.thread.liveclassification.negative == True:\n self.lbl.setStyleSheet(\"border: 15px solid red\")\n\n if self.thread.liveclassification.negative == False:\n self.lbl.setStyleSheet(\"border: 15px solid green\")\n\n self.lbl.setPixmap(q)\n self.lbl.adjustSize()\n self.show()\n\n except Empty:\n print(\"got no image\")\n\n def save_image(self):\n self.thread.save_img = True\n\n def quit(self):\n if self.thread.GPO_ON == True:\n self.thread.switch_output()\n\n if self.thread.running == True:\n self.stop_aquisition()\n if self.debugtool is not None:\n self.debugtool.quit()\n self.close()\n\n\n########################## Debugging ##########################\n\nclass DebuggingWindow(QWidget):\n\n def __init__(self, ac_thread, parent=None):\n super(DebuggingWindow, self).__init__(parent)\n self.title = \"Debugging Tool\"\n self.thread = ac_thread\n self.t = QTime()\n self.timer = QTimer()\n self.x = np.arange(50)\n self.y = np.ones(50)\n self.all_y = []\n\n ## Switch to using white background and black foreground\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n\n\n self.initDebug()\n\n def initDebug(self):\n\n # A horizontal layout to include the button on the left\n layout_button = QHBoxLayout()\n #layout_button.addWidget(self.create_button(\"Plotting\", self.start_live_plotting))\n layout_button.addWidget(self.create_button(\"Quit\", self.quit))\n layout_button.addWidget(self.create_button(\"Plot\", self.plot))\n layout_button.addWidget(self.create_button(\"Stop\", self.stop_plotting))\n layout_button.addStretch()\n\n self.plotWidget1 = pg.PlotWidget()\n self.plotWidget2 = pg.PlotWidget()\n self.timer.timeout.connect(self._update)\n\n # A Vertical layout to include the button layout and then the image\n layout = QVBoxLayout()\n layout.addLayout(layout_button)\n layout.addWidget(self.plotWidget1)\n layout.addWidget(self.plotWidget2)\n\n self.setLayout(layout)\n\n self.t.start()\n\n def create_button(self, label, func):\n\n button = QPushButton(label)\n button.clicked.connect(func)\n\n return button\n\n\n @pyqtSlot()\n def stop_plotting(self):\n self.timer.stop()\n\n def plot(self):\n\n self.timer.start(200)\n self.plotWidget1.clear() \n self.plotWidget1.setYRange(-0.2, 1.2, padding=0)\n\n self.curve1 = self.plotWidget1.plot(self.x, self.y, pen=4, symbol='o') \n\n self.plotWidget2.clear()\n self.plotWidget2.setXRange(-0.2, 1.2, padding=0)\n\n ## compute standard histogram\n e1, e2 = np.histogram(self.y, bins=np.linspace(-3, 8, 40))\n\n self.curve2 = self.plotWidget2.plot(e2, e1, stepMode=True, fillLevel=0, brush=(0,0,255,150))\n\n\n def _update(self):\n if self.thread.classification == True:\n self.x = np.roll(self.x, -1)\n self.y = np.roll(self.y, -1)\n self.x[-1] = self.t.elapsed()\n self.y[-1] = self.thread.liveclassification.prob\n\n self.all_y.append(self.thread.liveclassification.prob)\n\n self.curve1.setData(x=self.x, y=self.y)\n\n ## compute standard histogram\n e1, e2 = np.histogram(self.all_y, bins=np.linspace(0, 1, 40))\n self.curve2.setData(x=e2, y=e1)\n\n\n \n def quit(self):\n self.close()\n\n\n########################## MAIN FUNCTION ##########################\n\ndef main():\n #device.Setting.Base.Camera.GenICam.DigitalIOControl.LineInverter=1 to set output ON\n\n #find and open device\n serials = mv.List(0).Devices.children\n serial = serials[0]\n device = mv.dmg.get_device(serial)\n print('Using device:', serial)\n\n queue = Queue(10)\n acquisition_thread = AcquisitionThread(device, queue)\n\n app = QApplication(sys.argv)\n ex = App(acquisition_thread)\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5418741703033447, "alphanum_fraction": 0.5491172671318054, "avg_line_length": 20.456310272216797, "blob_id": "561b06787032d358543a7a62e496702460ee02f7", "content_id": "2de023d8beddb82fb75d924de8a1d6543f164b00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2209, "license_type": "no_license", "max_line_length": 160, "num_lines": 103, "path": "/cpp-stuff/WindingControlMain.cpp", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "// WindingControlMain.cpp\n//\n// Copyright 2015 TU Dortmund, Physik, Experimentelle Physik 5\n//\n// Author: Janine Müller\n//\n//\n//\n#include \"WindingControl.h\"\n#include <iostream>\n#include \"time.h\"\n#include <sstream>\n\n//mvIMPACT stuff\n#include <apps/Common/exampleHelper.h>\n#include <common/minmax.h>\n#include <mvIMPACT_CPP/mvIMPACT_acquire.h>\n\n\nusing namespace std;\n\nint main()\n{\t\n\tstring input;\n\n\tDeviceManager devMgr;\n\n\tDevice* pDev = OpenCam(devMgr);\n\n\t// cout << \"Do you want to record a video? [y/n]\" << endl;\n\t// cin >> input;\n\n\t// if((input == \"y\") | (input == \"Yes\") | (input == \"yes\") | (input == \"Y\")){\n\n\t// \ttime_t sec = time(NULL);\n\n\t// \ttm *uhr = localtime(&sec);\n\n\t// \tstringstream path;\n\t\t\n\t\t\n\t// \tpath << \"/local/Wickel_\" << uhr->tm_year-100 << uhr->tm_mon+1 << uhr->tm_mday << \"-\" << uhr->tm_hour << uhr->tm_min << uhr->tm_sec << \".avi\";\n\n\n\n\t// \tWriteVideoToFile(path.str(), pDev);\n\n\t// }\n\n\t// if((input == \"n\") | (input == \"No\") | (input == \"no\") | (input == \"N\")){\n\n\t// \tcout << \"Do you want to take a snapshot?\" << endl;\n\t// \tcin >> input;\n\t// \tif((input == \"y\") | (input == \"Yes\") | (input == \"yes\") | (input == \"Y\")){\n\n\t// \t\tMat frame;\n\t// \t\tstringstream path;\n\n\t// \t\ttime_t sec = time(NULL);\n\n\t// \t\ttm *uhr = localtime(&sec);\t\t\n\n\t// \t\tpath << \"/home/e5a-labor/pic/Wickel_\" << uhr->tm_year-100 << uhr->tm_mon+1 << uhr->tm_mday << \"-\" << uhr->tm_hour << uhr->tm_min << uhr->tm_sec << \".png\";\n\n\t// \t\tcout << path.str() << endl;\n\n\n\t// \t\tframe = ImageRequestSingle(pDev);\n\n\t// \t\tcout << \"frame.size(): \" << frame.size() << \"mat.type(): \" << frame.type() << endl;\n\n\t// \t\t/*vector<int> compression_params;\n\t// \t\tcompression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);\n\t// \t\tcompression_params.push_back(9);*/\n\n\t// \t\ttry {\n\t// \t\t\timwrite(path.str(), frame);\n\t// \t\t\tcout << \"saved to \" << path.str() << endl;\n\t// \t\t}\n\t// \t\tcatch (runtime_error& ex) {\n\t// \t\t\tfprintf(stderr, \"Exception converting image to PNG format: %s\\n\", ex.what());\n\t// \t\t}\n\n\t// \t}\n\n\t// \telse{\n\n\t// \t\tcout << \"Camera picture will be just shown...\" << endl;\n\t// \t\tShowPictureOfCamera(pDev);\n\n\t// \t}\n\n\n\t// }\n\t\n\t// else{\n\t// \tcout << \"Camera picture will be just shown...\" << endl;\n\t// \tShowPictureOfCamera(pDev);\n\t// }\n\t\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.5323736071586609, "alphanum_fraction": 0.5404581427574158, "avg_line_length": 34.340850830078125, "blob_id": "d44bc3d3c42afd62363a2a3cf8d951c531194d86", "content_id": "de4487314aa0a20641313a3f661fb3a8f8258f2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14115, "license_type": "no_license", "max_line_length": 170, "num_lines": 399, "path": "/WoCamera_Test.py", "repo_name": "jamenne/WindingControl", "src_encoding": "UTF-8", "text": "#############################################################################################\n######### #########\n######### Created by Janine Müller #########\n######### #########\n######### #########\n######### 21.08.2017 at TU Dortmund #########\n######### #########\n######### #########\n######### #########\n######### Testing skript, without talking to camera #########\n######### #########\n######### #########\n######### #########\n######### #########\n######### #########\n#############################################################################################\n\n\nimport sys\nimport os\n\nfrom threading import Thread\nfrom six.moves.queue import Queue, Empty, Full\n\n# Qt stuff\nfrom PyQt5.QtWidgets import QApplication, QWidget, QCheckBox, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout, QLabel, QFileDialog, QSlider, QFrame\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport pyqtgraph as pg\n\nimport scipy.misc\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom PIL import ImageQt\n\nfrom datetime import datetime\n\nfrom functools import partial\n\nimport time\n\n\n################################################## Image Aquisition ##################################################\n\n# Class to aquire images from camera\n# from https://github.com/geggo/MVacquire/\nclass AcquisitionThread(Thread):\n \n def __init__(self, queue):\n super(AcquisitionThread, self).__init__()\n self.queue = queue\n self.wants_abort = False\n self.running = False\n self.classification = False\n self.negative = False\n self.save_class = False\n self.written = False\n self.ClassProb_total = []\n self.prob = 0\n self.plotting = False\n\n self.path_dir_Data = '/home/windingcontrol/src/WindingControl/Data/' + str(datetime.now().strftime('%Y-%m-%d') + '/')\n if not os.path.exists(self.path_dir_Data):\n os.makedirs(self.path_dir_Data)\n print('Created path: {}'.format(self.path_dir_Data))\n\n def acquire_image(self):\n image_result = 1\n\n ### Classification of image\n\n if self.classification == True:\n image_result = np.random.uniform(0,1)\n self.prob = image_result\n print('{:}'.format(self.prob) )\n\n if self.save_class ==True:\n self.ClassProb_total.append(self.prob)\n \n if self.prob < 0.5:\n print('NEGATIVE')\n self.negative = True\n else:\n print('POSITIVE')\n self.negative = False\n\n ### End of Classification\n\n\n return image_result\n \n # Method representing the thread’s activity.\n # You may override this method in a subclass. - YES, we'll do it HERE -\n # The standard run() method invokes the callable object passed to the object’s constructor as the target argument, \n # if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. \n def run(self):\n while not self.wants_abort:\n img = self.acquire_image()\n if img is not None:\n try:\n self.queue.put_nowait(img)\n\n #print('.',) #\n except Full:\n #print('!',)\n pass\n\n print(\"acquisition thread finished\")\n\n def stop(self):\n self.wants_abort = True\n\n\n################################################## QT DISPLAY ##################################################\nclass App(QWidget):\n \n def __init__(self, ac_thread, parent=None):\n super(App, self).__init__(parent)\n self.title = 'Winding Control'\n self.left = 10\n self.top = 10\n self.width = 640\n self.height = 480\n self.thread = ac_thread\n self.debugtool = None\n\n self.initGUI()\n \n def initGUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n # Image viewing region\n self.lbl = QLabel(self)\n self.lbl.setStyleSheet(\"border: 15px solid white; background-color: white; inset grey\")\n self.lbl.setFrameShape(QFrame.StyledPanel)\n self.lbl.setFrameShadow(QFrame.Sunken)\n\n # RadioButton for saving the Probabilities\n self.check_but1 = QCheckBox('Save_Prob')\n self.check_but1.setChecked(False)\n self.check_but1.stateChanged.connect(partial( self.save_probabilities, self.check_but1 ))\n\n # A horizontal layout to include the button on the left\n layout_button = QHBoxLayout()\n layout_button.addWidget(self.create_button(\"Run\", self.run_aquisition))\n layout_button.addWidget(self.create_button(\"Start\", self.run_classification))\n layout_button.addWidget(self.create_button(\"Stop\", self.stop_classification))\n layout_button.addWidget(self.create_button(\"Debug\", self.start_debugtool))\n layout_button.addWidget(self.create_button(\"Quit\", self.quit))\n layout_button.addWidget(self.check_but1)\n layout_button.addStretch()\n\n # A Vertical layout to include the button layout and then the image\n layout = QVBoxLayout()\n layout.addLayout(layout_button)\n layout.addWidget(self.lbl)\n\n self.setLayout(layout)\n self.show()\n\n def create_slider(self, label, minV, maxV, value):\n groupBox = QGroupBox(label)\n\n slider = QSlider(Qt.Horizontal)\n slider.setMinimum(minV)\n slider.setMaximum(maxV)\n slider.setValue(value)\n slider.setTickPosition(QSlider.TicksBelow)\n slider.setTickInterval( (maxV-minV+1)/10 )\n slider.setFocusPolicy(Qt.NoFocus)\n\n slider.valueChanged.connect(partial (self.slider_val_changed, label) )\n\n vbox = QVBoxLayout()\n vbox.addWidget(slider)\n vbox.addStretch(2)\n\n #vbox.setGeometry(10, 10, 200, 30)\n groupBox.setLayout(vbox)\n\n return groupBox\n\n def create_button(self, label, func):\n\n button = QPushButton(label)\n button.clicked.connect(func)\n\n return button\n\n\n\n @pyqtSlot()\n def save_probabilities(self, b):\n if b.isChecked() == True:\n self.thread.save_class = True\n print('Probabilties are being saved in array!')\n else:\n if self.thread.save_class == True:\n self.thread.save_class = False\n self.thread.ClassProb_total = np.array(self.thread.ClassProb_total)\n np.savetxt(self.thread.path_dir_Data + \"WindingProb_\" + str(datetime.now().strftime('%Y-%m-%d_%H-%M-%S')) + \".txt\", self.thread.ClassProb_total)\n print('File written!')\n self.thread.written = True\n self.thread.ClassProb_total = []\n self.thread.save_class = True\n\n\n # Button Actions\n def start_debugtool(self):\n self.debugtool = DebuggingWindow(self.thread)\n self.debugtool.show()\n\n\n def run_aquisition(self):\n # Start the thread’s activity.\n # It must be called at most once per thread object. \n # It arranges for the object’s run() method to be invoked in a separate thread of control.\n # This method will raise a RuntimeError if called more than once on the same thread object.\n self.thread.wants_abort = False\n self.thread.start()\n self.thread.running = True\n\n timer = QTimer(self)\n timer.timeout.connect(self.open)\n timer.start(20) #30 Hz\n\n def run_classification(self):\n print('Start Classification')\n self.thread.ClassProb_total = []\n self.thread.classification = True\n\n\n def stop_classification(self):\n print('Stop Classification')\n self.thread.classification = False\n self.thread.plotting = False\n\n if self.thread.save_class == True:\n self.thread.ClassProb_total = np.array(self.thread.ClassProb_total)\n np.savetxt(self.thread.path_dir_Data + \"WindingProb_\" + str(datetime.now().strftime('%Y-%m-%d_%H-%M-%S')) + \".txt\", self.thread.ClassProb_total)\n print('File written!')\n self.thread.written = True\n\n def open(self):\n try:\n img = self.thread.queue.get(block=True, timeout = 1)\n #rndImage = np.random.rand(600, 800, 3)\n \n #q = QPixmap.fromImage(ImageQt.ImageQt(scipy.misc.toimage(rndImage)))\n\n\n\n if self.thread.negative == True:\n self.lbl.setStyleSheet(\"border: 15px solid red\")\n\n if self.thread.negative == False:\n self.lbl.setStyleSheet(\"border: 15px solid green\")\n\n #self.lbl.setPixmap(q)\n self.lbl.adjustSize()\n self.show()\n\n except Empty:\n print(\"got no image\")\n\n def stop_aquisition(self):\n #wait until acquisition thread has stopped\n self.thread.stop()\n\n # Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates \n # – either normally or through an unhandled exception – or until the optional timeout occurs.\n # When the timeout argument is present and not None, it should be a floating point number \n # specifying a timeout for the operation in seconds (or fractions thereof). \n # As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened \n # – if the thread is still alive, the join() call timed out.\n # When the timeout argument is not present or None, the operation will block until the thread terminates.\n # A thread can be join()ed many times.\n # join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. \n # It is also an error to join() a thread before it has been started and attempts to do so raise the same exception.\n self.thread.join()\n\n def quit(self):\n if self.thread.running:\n self.stop_aquisition()\n self.close()\n\n########################## Debugging ##########################\n\nclass DebuggingWindow(QWidget):\n\n def __init__(self, ac_thread, parent=None):\n super(DebuggingWindow, self).__init__(parent)\n self.title = \"Debugging Tool\"\n self.thread = ac_thread\n self.t = QTime()\n self.timer = QTimer()\n self.x = np.arange(50)\n self.y = np.ones(50)\n self.all_y = []\n\n ## Switch to using white background and black foreground\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n\n\n self.initDebug()\n\n def initDebug(self):\n\n # A horizontal layout to include the button on the left\n layout_button = QHBoxLayout()\n #layout_button.addWidget(self.create_button(\"Plotting\", self.start_live_plotting))\n layout_button.addWidget(self.create_button(\"Quit\", self.quit))\n layout_button.addWidget(self.create_button(\"Plot\", self.plot))\n layout_button.addWidget(self.create_button(\"Stop\", self.stop_plotting))\n layout_button.addStretch()\n\n self.plotWidget1 = pg.PlotWidget()\n self.plotWidget2 = pg.PlotWidget()\n self.timer.timeout.connect(self._update)\n\n # A Vertical layout to include the button layout and then the image\n layout = QVBoxLayout()\n layout.addLayout(layout_button)\n layout.addWidget(self.plotWidget1)\n layout.addWidget(self.plotWidget2)\n\n self.setLayout(layout)\n\n self.t.start()\n\n def create_button(self, label, func):\n\n button = QPushButton(label)\n button.clicked.connect(func)\n\n return button\n\n\n @pyqtSlot()\n def stop_plotting(self):\n self.timer.stop()\n self.thread.plotting = False\n\n def plot(self):\n self.thread.plotting = True\n\n self.timer.start(200)\n self.plotWidget1.clear() \n\n self.curve1 = self.plotWidget1.plot(self.x, self.y, pen=4, symbol='o') \n\n self.plotWidget2.clear()\n ## compute standard histogram\n e1, e2 = np.histogram(self.y, bins=np.linspace(-3, 8, 40))\n\n self.curve2 = self.plotWidget2.plot(e2, e1, stepMode=True, fillLevel=0, brush=(0,0,255,150))\n\n def _update(self):\n if self.thread.plotting == True:\n self.x = np.roll(self.x, -1)\n self.y = np.roll(self.y, -1)\n self.x[-1] = self.t.elapsed()\n self.y[-1] = self.thread.prob\n\n self.all_y.append(self.thread.prob)\n\n self.curve1.setData(x=self.x, y=self.y)\n\n ## compute standard histogram\n e1, e2 = np.histogram(self.all_y, bins=np.linspace(-1, 1, 10))\n self.curve2.setData(x=e2, y=e1)\n else: \n self.timer.stop()\n\n \n\n\n def quit(self):\n self.close()\n\n########################## MAIN FUNCTION ##########################\n\ndef main():\n\n queue = Queue(10)\n acquisition_thread = AcquisitionThread(queue)\n\n app = QApplication(sys.argv)\n ex = App(acquisition_thread)\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n" } ]
8
Kmeiklejohn/numseq
https://github.com/Kmeiklejohn/numseq
14e0ba13b071d782436779976eab8f2693bc893c
33386212b5531f2576072cfb9f0bef67bfb9795d
c2aaa47bc29a6d06ab66822013badaa1ad6106e4
refs/heads/master
2020-04-10T02:02:43.887757
2018-12-06T21:16:40
2018-12-06T21:16:40
160,733,062
0
0
null
2018-12-06T21:16:10
2018-12-06T21:16:52
2018-12-19T17:45:21
Python
[ { "alpha_fraction": 0.5759162306785583, "alphanum_fraction": 0.5916230082511902, "avg_line_length": 20.33333396911621, "blob_id": "8dfc135980fe8529f5a2a1fb32b581929e1dae66", "content_id": "c57a1eb10b92a356d9562201bd8ed39dd2c57af2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/numseq/fib.py", "repo_name": "Kmeiklejohn/numseq", "src_encoding": "UTF-8", "text": "'''This file returns fibonacci's number'''\n\ndef fib(num):\n result = 0\n second = 1\n for first in range(2,num):\n result = first + second\n second = first\n return result" }, { "alpha_fraction": 0.5848101377487183, "alphanum_fraction": 0.5924050807952881, "avg_line_length": 19.36842155456543, "blob_id": "32b33a9faae5b9d751d7610710b765d3db75083b", "content_id": "9f4b5543409244dd421e4e328de0064ead369799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 78, "num_lines": 19, "path": "/numseq/geo.py", "repo_name": "Kmeiklejohn/numseq", "src_encoding": "UTF-8", "text": "\"\"\"This package returns a number depending on a cube, square, or a triangle\"\"\"\n\n\n\ndef square(num):\n \"\"\"returns a squared number\"\"\"\n sq_num = num ** 2\n return sq_num\n\ndef triangle(num):\n \"\"\"returns the area of a triangle\"\"\"\n sq_num = square(num)\n tri = sq_num / 2\n return tri\n\ndef cube(num):\n \"\"\"returns the a cubed number\"\"\"\n cubed = num ** 3\n return cubed\n\n\n \n\n" } ]
2
miguelglopes/challenge_CoEDAAI
https://github.com/miguelglopes/challenge_CoEDAAI
fe4693444138891fa28e5abfa22b737e46fbcd01
0e01cb0effa68056fbbf546ae443e76d4bd49dc5
d88e80eee9fe8dc9e33255f732c2e837ca2b6dee
refs/heads/master
2020-12-11T15:03:02.189363
2020-01-14T15:47:10
2020-01-14T15:47:10
233,876,858
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6783640384674072, "alphanum_fraction": 0.6894723773002625, "avg_line_length": 35.33945083618164, "blob_id": "789ee1ae4d064b442c330224be5879dc89961466", "content_id": "4fa4a4d92626eebdbb5d1a9a990df246b94af129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3961, "license_type": "no_license", "max_line_length": 116, "num_lines": 109, "path": "/Part1/project/SQLModel.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "from data import config # local\nfrom sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Numeric, CHAR, UniqueConstraint, create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\n\n# create sql engine\n# this doesnt connect yet to the database\nengine = create_engine(config.DBConnectString)\nBase = declarative_base()\n\n\nclass Provincia(Base):\n __tablename__ = \"Provincia\"\n __table_args__ = (UniqueConstraint(\"Name\", name=\"_nameProv_uc\"),)\n\n ID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n Name = Column(String(50), nullable=False)\n\n\nclass Margen(Base):\n __tablename__ = \"Margen\"\n\n ID = Column(CHAR(1), primary_key=True, nullable=False)\n Name = Column(String(50), nullable=False)\n\n\nclass Producto(Base):\n __tablename__ = \"Producto\"\n __table_args__ = (UniqueConstraint(\"Name\", name=\"_nameProd_uc\"),)\n\n ID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n Name = Column(String(50), nullable=False)\n\n\nclass Venta(Base):\n __tablename__ = \"Venta\"\n\n ID = Column(CHAR(1), primary_key=True, nullable=False)\n Name = Column(String(50), nullable=False)\n\n\nclass Rem(Base):\n __tablename__ = \"Rem\"\n\n ID = Column(CHAR(2), primary_key=True, nullable=False)\n Name = Column(String(50), nullable=False)\n\n\nclass Brands(Base):\n __tablename__ = \"Brands\"\n __table_args__ = (UniqueConstraint(\"Name\", name=\"_nameBrand_uc\"),)\n\n ID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n Name = Column(String(50), nullable=False)\n\n\nclass Municipio(Base):\n __tablename__ = \"Municipio\"\n __table_args__ = (UniqueConstraint(\"Name\", name=\"_nameMun_uc\"),)\n\n ID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n Name = Column(String(50), nullable=False)\n ProvinciaID = Column(Integer, ForeignKey(\"Provincia.ID\"), nullable=False)\n Provincia = relationship(\"Provincia\")\n\n\nclass Localidad(Base):\n __tablename__ = \"Localidad\"\n __table_args__ = (UniqueConstraint(\"Name\", name=\"_nameLocal_uc\"),)\n\n ID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n Name = Column(String(50), nullable=False)\n MunicipioID = Column(Integer, ForeignKey(\"Municipio.ID\"), nullable=False)\n Municipio = relationship(\"Municipio\")\n\n\nclass Station(Base):\n __tablename__ = \"Station\"\n __table_args__ = (UniqueConstraint(\"Longitud\", \"Latitud\", \"MargenID\", name=\"_PC_uc\"),)\n\n ID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n CodigoPostal = Column(CHAR(5), nullable=False)\n Direccion = Column(String(300), nullable=False)\n Longitud = Column(Numeric(20, 10), nullable=False)\n Latitud = Column(Numeric(20, 10), nullable=False)\n MargenID = Column(CHAR(1), ForeignKey(\"Margen.ID\"), nullable=False)\n Margen = relationship(\"Margen\")\n LocalidadID = Column(Integer, ForeignKey(\"Localidad.ID\"), nullable=False)\n Localidad = relationship(\"Localidad\")\n\n\nclass Price(Base):\n __tablename__ = \"Price\"\n __table_args__ = (UniqueConstraint(\"ProductoID\", \"StationID\", \"Fecha\", name=\"_PSF_uc\"),)\n ID = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n Precio = Column(Numeric(20, 10), nullable=False)\n Rotulo = Column(String(300), nullable=False)\n Fecha = Column(DateTime, nullable=False)\n ProductoID = Column(Integer, ForeignKey(\"Producto.ID\"), nullable=False)\n Producto = relationship(\"Producto\")\n StationID = Column(Integer, ForeignKey(\"Station.ID\"), nullable=False)\n Station = relationship(\"Station\")\n BrandsID = Column(Integer, ForeignKey(\"Brands.ID\"), nullable=False)\n Brands = relationship(\"Brands\")\n VentaID = Column(CHAR(1), ForeignKey(\"Venta.ID\"), nullable=False)\n Venta = relationship(\"Venta\")\n RemID = Column(CHAR(2), ForeignKey(\"Rem.ID\"), nullable=False)\n Rem = relationship(\"Rem\")\n Horario = Column(String(200), nullable=False)\n" }, { "alpha_fraction": 0.5659254789352417, "alphanum_fraction": 0.6103977560997009, "avg_line_length": 43.34722137451172, "blob_id": "bb6bee3f8c8b179ed7533b3fdc34837564d5eaed", "content_id": "21c2d8e189eaac4f454531f00f64f0bb5e267551", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3193, "license_type": "no_license", "max_line_length": 115, "num_lines": 72, "path": "/Part2/test/test_test.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "from project import test # local\nimport unittest\n\n\nclass Test_Countries(unittest.TestCase):\n\n # test question 1\n def test_import_data(self):\n c = test.import_data()\n # test some countries. If source file changes, this may fail\n dPortugal = {'Area': 92391, 'Continent': 'Europe', 'GDP': 18000.0,\n 'Literacy': 93.3, 'Phones': 399.21, 'Population': 10605870.0}\n dAfghanistan = {'Area': 647500, 'Continent': 'Asia', 'GDP': 700.0,\n 'Literacy': 36.0, 'Phones': 3.22, 'Population': 31056997.0}\n dZambia = {'Area': 752614, 'Continent': 'Africa', 'GDP': 800.0,\n 'Literacy': 80.6, 'Phones': 8.23, 'Population': 11502010.0}\n self.assertEqual(c[\"Portugal\"], dPortugal)\n self.assertEqual(c[\"Afghanistan\"], dAfghanistan)\n self.assertEqual(c[\"Zambia\"], dZambia)\n\n # test question 2\n def test_convert_population_to_int(self):\n c = test.import_data()\n cint = test.convert_population_to_int(c)[\"Afghanistan\"][\"Population\"]\n self.assertIsInstance(cint, int)\n\n # test question 3\n def test_convert_area_to_sq_km(self):\n c = test.import_data()\n areaSqMiles = round(c[\"Portugal\"][\"Area\"]*2.58999, 1)\n test.convert_area_to_sq_km(c)\n self.assertEqual(c[\"Portugal\"][\"Area\"], areaSqMiles)\n\n # test question 4\n def test_get_europe_countries(self):\n c = test.import_data()\n # test random countries. If source file changes, this may fail\n europeanCountries = ['Albania', 'Denmark', 'Estonia', 'Finland', 'Hungary',\n 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Portugal', 'Spain', 'Sweden']\n self.assertTrue(set(test.get_europe_countries(c)).issuperset(set(europeanCountries)))\n\n # test question 5\n def test_get_literacy_levels_by_continent(self):\n c = test.import_data()\n literacy = test.get_literacy_levels_by_continent(c, \"Africa\")\n # test all literacy levels. If source file changes, this may fail\n testList = [('Niger', 17.6, 'VERY_LOW'), ('Mali', 46.4, 'LOW'), ('Togo', 60.9, 'MEDIUM'),\n ('Zambia', 80.6, 'HIGH'), ('Zimbabwe', 90.7, 'VERY_HIGH')]\n self.assertTrue(set(literacy).issuperset(set(testList)))\n\n # test question 6\n def test_get_country_codes(self):\n c = test.import_data()\n countryCodes = test.get_country_codes(c)\n # test some codes. If source file changes, this may fail\n testList = [\"POR\", \"ISR\", \"AUS\", \"SPA\", \"ZIM\"] # test some\n self.assertTrue(set(countryCodes).issuperset(set(testList)))\n\n # test question 7.1\n def test_get_population_in_millions(self):\n ct = test.Country(\"MyCountry\", 10310234, \"MyContinent\")\n self.assertEqual(ct.get_population_in_millions(), round(10310234/1000000, 2))\n\n # test question 7.2\n def test_get_country_population(self):\n c = test.import_data()\n self.assertEqual(test.get_country_population(c, \"Portugal\"), round(c[\"Portugal\"][\"Population\"]/1000000, 2))\n self.assertEqual(test.get_country_population(c, \"MyCountry\"), None)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.8068965673446655, "alphanum_fraction": 0.8068965673446655, "avg_line_length": 25.363636016845703, "blob_id": "94930bfc783f62f412823736fae117b94f074bd5", "content_id": "3b2ea1b3d4746b32d2967401677aabcd7712e5ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "no_license", "max_line_length": 79, "num_lines": 11, "path": "/Part1/project/main.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "from DataExcel import ExcelFile\nimport SQLController\n\n# get excel data\ndataFile = ExcelFile()\n\n# create sql tables schema. This only needs to be run once, but it's idempotent\nSQLController.createTablesSchema()\n\n# insert excel data to SQL database.\nSQLController.insertPdTableToDB(dataFile)\n" }, { "alpha_fraction": 0.6770893931388855, "alphanum_fraction": 0.6778613924980164, "avg_line_length": 37.95488739013672, "blob_id": "c5d7d739a6dabd0bc4368daa5f9e378a1cfd5a77", "content_id": "39807835480cebf8723b47b905c162ca416fdfb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5184, "license_type": "no_license", "max_line_length": 160, "num_lines": 133, "path": "/Part1/project/SQLController.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "from data import config # local\nfrom DataExcel import ExcelFile # local, only for type hinting\nfrom pandas.core.series import Series # only for type hinting\nfrom datetime import datetime # only for type hinting\nimport SQLModel\nfrom SQLModel import Provincia, Municipio, Localidad, Margen, Producto, Venta, Station, Price, Brands, Rem\nimport logging\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy.exc import OperationalError\nfrom sqlalchemy.orm.session import Session\n\n\ndef __connectToDB():\n \"\"\"\n Test connection to the database.\n \"\"\"\n\n try:\n SQLModel.engine.connect()\n except OperationalError:\n logging.error(\"Unable to connect to the database. Check the connection string.\")\n raise\n\n\ndef createTablesSchema():\n \"\"\"\n Create database schema based on the SLQModel\n \"\"\"\n\n __connectToDB()\n SQLModel.Base.metadata.create_all(SQLModel.engine)\n logging.info(\"Tables \" + str(list(SQLModel.Base.metadata.tables.keys())) + \" successfully created in the database.\")\n\n\ndef insertPdTableToDB(dataFile: ExcelFile):\n \"\"\"\n Persists the data contained in the dataFile to the database\n\n Arguments:\n dataFile {ExcelFile} - Object containing the data to be persisted\n \"\"\"\n\n __connectToDB()\n Session = sessionmaker(bind=SQLModel.engine)\n session = Session()\n\n data = dataFile.dataFrame\n\n # convert dataframe to \"SQL friendly\"\n nonProductColumns = set(data.columns) - set(config.columns[\"productColumns\"])\n newData = data.melt(id_vars=nonProductColumns, var_name=\"Producto\", value_name=\"Precio\")\n newData = newData.dropna(subset=['Precio'])\n\n logging.info(\"Inserting data to the database. Depending on the number of rows, this may take a while...\")\n\n # insert row 1 by 1\n #newData.apply(lambda row: __addRowToSession(session, row, dataFile.date), axis=1)\n newData.apply(lambda row: __addRowToSession(session, row, dataFile.date), axis=1)\n\n # commit session\n session.commit()\n session.close()\n logging.info(\"Successfully persisted the data to the database.\")\n # TODO COUNT affected rows. Requires further investigation\n\n\ndef __addRowToSession(session: Session, row: Series, fecha: datetime):\n \"\"\" \n Add row of data to the database session to, eventually, be persisted to the database\n\n Arguments:\n session {Session} -- SQLAlchemy session\n row {Series} -- Data to be added to the session\n fecha {datetime} -- Date when the data was created\n \"\"\"\n\n # TODO\n # The best way I found in order to not get integrity errors, was to try to get the information from the database and, if there isn't create it.\n # However, this probably isn't the most efficient way to do it. For this reason, this method takes a lot of time, depending on the number of rows.\n # Requires Further investigation.\n\n try:\n provincia = session.query(Provincia).filter(Provincia.Name == row[\"Provincia\"]).one()\n except NoResultFound:\n provincia = Provincia(Name=row[\"Provincia\"])\n\n try:\n municipio = session.query(Municipio).filter(Municipio.Name == row[\"Municipio\"]).one()\n except NoResultFound:\n municipio = Municipio(Name=row[\"Municipio\"], Provincia=provincia)\n\n try:\n localidad = session.query(Localidad).filter(Localidad.Name == row[\"Localidad\"]).one()\n except NoResultFound:\n localidad = Localidad(Name=row[\"Localidad\"], Municipio=municipio)\n\n try:\n margen = session.query(Margen).filter(Margen.Name == row[\"Margen\"]).one()\n except NoResultFound:\n margen = Margen(ID=row[\"Margen\"], Name=row[\"Margen\"])\n\n try:\n station = session.query(Station).filter(Station.Longitud == row[\"Longitud\"]).filter(\n Station.Latitud == row[\"Latitud\"]).filter(Station.MargenID == row[\"Margen\"]).one()\n except NoResultFound:\n station = Station(CodigoPostal=row[\"Código postal\"], Localidad=localidad, Direccion=row[\"Dirección\"],\n Longitud=row[\"Longitud\"], Latitud=row[\"Latitud\"], Margen=margen)\n\n try:\n producto = session.query(Producto).filter(Producto.Name == row[\"Producto\"]).one()\n except NoResultFound:\n producto = Producto(Name=row[\"Producto\"])\n\n try:\n brands = session.query(Brands).filter(Brands.Name == row[\"Brands\"]).one()\n except NoResultFound:\n brands = Brands(Name=row[\"Brands\"])\n\n try:\n venta = session.query(Venta).filter(Venta.Name == row[\"Tipo venta\"]).one()\n except NoResultFound:\n venta = Venta(Name=row[\"Tipo venta\"], ID=row[\"Tipo venta\"])\n\n try:\n rem = session.query(Rem).filter(Rem.Name == row[\"Rem.\"]).one()\n except NoResultFound:\n rem = Rem(Name=row[\"Rem.\"], ID=row[\"Rem.\"])\n\n if session.query(Price).filter(Price.ProductoID == producto.ID).filter(Price.StationID == station.ID).filter(Price.Fecha == fecha).scalar() == None:\n newRow = Price(Precio=row[\"Precio\"], Rotulo=row[\"Rótulo\"], Fecha=fecha.strftime(\"%Y/%m/%d %H:%M:%S\"), Producto=producto, Station=station, Brands=brands,\n Venta=venta, Rem=rem, Horario=row[\"Horario\"])\n session.merge(newRow)\n" }, { "alpha_fraction": 0.6101800203323364, "alphanum_fraction": 0.6126629710197449, "avg_line_length": 40.30769348144531, "blob_id": "f44fe19e27865366357459e6e95f01fbd54ba01e", "content_id": "a8804bc45dbce740dd1d2e0d638f6fb0f0a2f987", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3222, "license_type": "no_license", "max_line_length": 142, "num_lines": 78, "path": "/Part1/project/DataExcel.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "from data import config # local\nimport pandas\nimport logging\nfrom datetime import datetime\nimport xlrd\n\n\nclass ExcelFile:\n \"\"\"\n Class that contains every needed information about the excel file, including its data.\n \"\"\"\n\n def __init__(self, file: str = config.dataFile[\"nameS\"], sheet: str = config.dataFile[\"sheetS\"]):\n \"\"\"\n Instantiates the class, including file, sheet, date of creation and dataframe\n\n Keyword Arguments:\n file {str} -- Excel file to be read (default: {config.dataFile[\"nameS\"]})\n sheet {str} -- Excel sheet of the excel file (default: {config.dataFile[\"sheetS\"]})\n \"\"\"\n\n self.__file = file\n self.__sheet = sheet\n self.dataFrame = None\n # to get the date\n workbook = xlrd.open_workbook(self.__file)\n worksheet = workbook.sheet_by_name(self.__sheet)\n self.date = datetime.strptime(worksheet.cell(0, 1).value, \"%d/%m/%Y %H:%M\")\n self.__setDataFrame()\n\n def __setDataFrame(self):\n \"\"\"\n Reads the excel data from the excel file. Preprocesses the information and stores it in a pandas dataframe. Creates new brands column.\n \"\"\"\n\n # get data\n self.dataFrame = pandas.read_excel(self.__file, sheet_name=self.__sheet,\n skiprows=[0, 1, 2], header=0, dtype=str)\n\n # check if we have unknown columns.\n # Replace comma by point for float columns (numbers are formatted as text)\n for column in self.dataFrame.columns:\n if column not in config.columns[\"dataTypes\"].keys():\n logging.warning(\"Column \" + column +\n \" found in data file but is not in the configuration.\")\n elif config.columns[\"dataTypes\"][column] is float:\n self.dataFrame[column] = self.dataFrame[column].replace(',', '.', regex=True)\n\n # set data types. This is mandatory, otherwise, for instance, postal codes would be read as int, and we'd lose information\n self.dataFrame = self.dataFrame.astype(config.columns[\"dataTypes\"])\n\n # generate new brands column\n self.dataFrame[config.rotulo[\"newS\"]] = self.dataFrame[config.rotulo[\"originalS\"]].apply(\n lambda row: ExcelFile.__compareBandStrings(row))\n\n logging.info(\"Loaded \" + str(self.dataFrame.shape[0]) + \" columns and \" + str(\n self.dataFrame.shape[1]) + \" rows from \" + config.dataFile[\"nameS\"] + \" into memory. New brands column successfully created.\")\n\n @staticmethod\n def __compareBandStrings(inputS: str) -> str:\n \"\"\"\n Compares a string to the list of brands in config.rotulo[\"brandsL\"]\n\n Arguments:\n inputS {string} -- Any string to compare to the list of brands \n\n Returns:\n string -- returns one of the brands in config.rotulo[\"brandsL\"] if inputS contains it\n or the string config.rotulo[\"otherS\"] otherwise.\n \"\"\"\n\n for brand in config.rotulo[\"brandsL\"]:\n if brand in inputS:\n return brand\n\n return config.rotulo[\"otherS\"]\n\n # TODO: what if it contains more than one brand? This was not taken into account.\n" }, { "alpha_fraction": 0.5594285726547241, "alphanum_fraction": 0.5708571672439575, "avg_line_length": 33.313724517822266, "blob_id": "a573a30ea27cd8660fcd2f66b0b837fdca7a324f", "content_id": "26be59b2bb2e3e4d0f8cb862029c6da1b8d6edc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1766, "license_type": "no_license", "max_line_length": 127, "num_lines": 51, "path": "/Part1/data/config.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "import logging\n\ndataFile = {\n \"nameS\": r\"Part1\\data\\preciosEESS_es.xls\",\n \"sheetS\": \"Page 1\"\n}\n\ncolumns = {\n \"dataTypes\": {\n \"Provincia\": str,\n \"Municipio\": str,\n \"Localidad\": str,\n \"Código postal\": str,\n \"Dirección\": str,\n \"Margen\": str,\n \"Longitud\": float,\n \"Latitud\": float,\n \"Precio gasolina 95\": float,\n \"Precio gasóleo A\": float,\n \"Precio gasóleo B\": float,\n \"Precio bioetanol\": float,\n \"Precio nuevo gasóleo A\": float,\n \"Precio biodiesel\": float,\n \"% éster metílico\": float,\n \"% bioalcohol\": float,\n \"Precio gasolina 98\": float,\n \"Precio gas natural comprimido\": float,\n \"Precio gas natural licuado\": float,\n \"Precio gases licuados del petróleo\": float,\n \"Rótulo\": str,\n \"Tipo venta\": str,\n \"Rem.\": str,\n \"Horario\": str\n },\n \"productColumns\": [\"Precio gasolina 95\", \"Precio gasóleo A\", \"Precio gasóleo B\", \"Precio bioetanol\", \n \"Precio nuevo gasóleo A\", \"Precio biodiesel\", \"% éster metílico\", \"% bioalcohol\",\n \"Precio gasolina 98\", \"Precio gas natural comprimido\", \"Precio gas natural licuado\",\n \"Precio gases licuados del petróleo\"]\n}\n\nrotulo = {\n \"originalS\": \"Rótulo\",\n \"newS\": \"Brands\",\n \"brandsL\": [\"ALCAMPO\", \"BALLENOIL\", \"BP\", \"CAMPSA\", \"CARREFOUR\", \"CEPSA\", \"E.LECLERC\", \"EROSKI\", \"GALP\",\n \"GAS EXPRESS\", \"PETRONOR\", \"PETROPRIX\", \"REPSOL\", \"REPOSTA\", \"SHELL\"],\n \"otherS\": \"OTHER\"\n}\n\nDBConnectString = \"mysql://admin:[email protected]:3306/stations?charset=utf8mb4\"\n\nlogging.getLogger().setLevel(logging.INFO)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 39, "blob_id": "ec363133e3e2181e880b946253529fa934227259", "content_id": "bc065ef679ada793fd7181f3fa4aed3489fd0eb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 39, "num_lines": 1, "path": "/Part2/data/config.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "jsonPath = r\"Part2\\data\\countries.json\"\n" }, { "alpha_fraction": 0.6188090443611145, "alphanum_fraction": 0.6319136619567871, "avg_line_length": 32.262821197509766, "blob_id": "fc044a1096ffd62426e403c80c231cc81e3e6040", "content_id": "1464075e5f3d467bc2f6aeacbdc034124571e776", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5189, "license_type": "no_license", "max_line_length": 131, "num_lines": 156, "path": "/Part2/project/test.py", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "import json\nfrom data import config # local\n\n\nclass Country:\n\n def __init__(self, country_name: str, population: int, continent: str):\n \"\"\"Creates a country\n\n Arguments:\n country_name {str} -- Country name\n population {int} -- Country population\n continent {str} -- Country continent\n \"\"\"\n self.country_name = country_name\n self.population = population\n self.continent = continent\n\n def get_population_in_millions(self) -> float:\n \"\"\"Returns the country population in millions, with 2 decimal digits\n\n Returns:\n float -- Country population in millions, with 2 decimal digits\n \"\"\"\n return round(float(self.population)/1000000, 2)\n\n\ndef import_data() -> dict:\n \"\"\" Read Json data from a file into a dictionary. The json file path is config.jsonPath.\n\n Returns:\n dict -- dictionary with the data contained in the config.jsonPath file. Countries dictionary\n \"\"\"\n with open(config.jsonPath) as f:\n return json.load(f)\n\n\n# ??? should it change the original dictionary? It's not clear from the question. That's what I did\n# ??? looking at the population values, it is clear that the original dictionary already had the area in sq km, not sq miles\ndef convert_population_to_int(countries: dict) -> dict:\n \"\"\"Converts each country population into int type\n\n Arguments:\n countries {dict} -- Countries dictionary\n\n Returns:\n dict -- Updated countries dictionary\n \"\"\"\n for k, v in countries.items():\n v[\"Population\"] = int(v[\"Population\"])\n return countries\n\n# ??? should it change the original dictionary? It's not clear from the question. That's what I did.\n\n\ndef convert_area_to_sq_km(countries: dict) -> dict:\n \"\"\"Converts each country area into sq km\n\n Arguments:\n countries {dict} -- Countries dictionary\n\n Returns:\n dict -- Updated countries dictionary\n \"\"\"\n for k, v in countries.items():\n v[\"Area\"] = round(float(v[\"Area\"])*2.58999, 1)\n return countries\n\n\ndef get_europe_countries(countries: dict) -> list:\n \"\"\"Gets list of all european countries names present in the countries dictionary\n\n Arguments:\n countries {dict} -- Countries dictionary\n\n Returns:\n list -- List of european countries names\n \"\"\"\n countriesL = [c for c in countries if countries[c][\"Continent\"] == \"Europe\"]\n countriesL.sort()\n return countriesL\n\n\ndef get_literacy_levels_by_continent(countries: dict, continent: str) -> list:\n \"\"\"Computes the literacy level as:\n - literacy in [0, 25[ % - VERY_LOW\n - literacy in [25, 50[ % - LOW\n - literacy in [50, 70[ % - MEDIUM\n - literacy in [70, 90[ % - HIGH\n - literacy in [90, 100] % - VERY_HIGH\n\n Arguments:\n countries {dict} -- Countries dictionary\n continent {str} -- Continent. If continent is not in the countries dictionary, an empty lsit will be returned.\n\n Raises:\n Exception: raises exception if input literacy level is unknown (higher than 100 or lower than 0)\n\n Returns:\n list -- list of tuples like [(country_1, literacy_1, literacy_level_1), ..., (country_n, literacy_n,literacy_level_n), ...]\n \"\"\"\n\n # RFE this could be done with a dictionary in the config file\n def getLiteracyLevel(literacy):\n if 0 <= v[\"Literacy\"] < 25:\n return \"VERY_LOW\"\n elif 25 <= v[\"Literacy\"] < 50:\n return \"LOW\"\n elif 50 <= v[\"Literacy\"] < 70:\n return \"MEDIUM\"\n elif 70 <= v[\"Literacy\"] < 90:\n return \"HIGH\"\n elif 90 <= v[\"Literacy\"] <= 100:\n return \"VERY_HIGH\"\n else:\n raise Exception(\"Unkown literacy level\")\n\n # ??? if continent doesnt exist, it will return an empy list. Is it the desired behavior?\n literacyL = []\n for k, v in countries.items():\n if v[\"Continent\"] == continent:\n literacyL.append((k, v[\"Literacy\"], getLiteracyLevel(v[\"Literacy\"])))\n\n return literacyL\n\n\ndef get_country_codes(countries: dict) -> list:\n \"\"\" Gets country codes from the countries dictionary. Sstrips all characters that are not letters from the country name,\n gets the first 3 characters (or as many as there are until 3) and converts them to uppercase.\n\n Arguments:\n countries {dict} -- [description]\n\n Returns:\n list -- [description]\n \"\"\"\n return list(map(lambda c: ''.join(filter(str.isalpha, c))[:3].upper(), countries.keys()))\n\n\ndef get_country_population(countries: dict, country_name: str) -> float:\n \"\"\" Gets the country population in millions, with 2 decimal digits\n\n Arguments:\n countries {dict} -- Countries dictionary\n country_name {str} -- Country name\n\n Returns:\n float -- country population in million or None, if the country doesn't exist.\n \"\"\"\n\n try:\n country = Country(country_name, countries[country_name][\"Population\"], countries[country_name][\"Continent\"])\n return country.get_population_in_millions()\n except KeyError:\n print(\"There is no information for the country \" + country_name)\n return\n" }, { "alpha_fraction": 0.6870817542076111, "alphanum_fraction": 0.6929628849029541, "avg_line_length": 76.0625, "blob_id": "48a8a5e7c9873ef3ee3db7ad2022c4b89ba76ee0", "content_id": "8bd2490843518781fa038b179269d55d996bb44f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5075, "license_type": "no_license", "max_line_length": 830, "num_lines": 64, "path": "/README.md", "repo_name": "miguelglopes/challenge_CoEDAAI", "src_encoding": "UTF-8", "text": "# CoE DAAI Python Test\n\n*Author: Miguel Gomes Lopes*\n\nThis folder contains my solutions for the CoE DAAI Python Test\n\nIt is divided between 2 sub-folders: Part1 and Part2. It also contains my configurations for VSCode, which was the editor I used for the project. You can find 2 debug configurations (launch.json in the .vscode folder), one for Part1 and another for Part2, as well as the settings.json.\n\nI used a python virtual environment to better contain the project, which can be found in the folder pythonTestVenv.\n\nAll the code respects the Python Enhancement Proposal (PEP8).\n\n## PART1\n\nThis folder contains the following structure:\n\n\n ├──.vscode # Visual Studio Code settings\n ├── Part1 # Part1\n ├── data \n ├── config.py # Configuration file\n ├── preciosEESS_es.xls # Provided data\n ├── project \n ├── DataExcel.py # Answers to P1E1\n ├── SQLModel.py # Answers to P1E2\n ├── SQLController.py # Answers to P1E2\n ├── main.py # script with the full pipeline\n ├── dashboard.pbix # powerBI file\n ├── Part2 # Part2\n ├── pythonTestVenv # Virtual Environment\n\nMy goal with this part of the project was to develop a small program that would allow the excel data to be read, processed and automatically inserted to an SQL database. I also wanted the historical data to be available, i.e., if a new file, from a different time of the day is processed, I wanted to keep the old data.\nAnalysing the data, I concluded that the best way to store this data would be with the following SQL tables structure, which guarantees data integrity, consistency and avoids redundancy:\n![alt text](Part1\\tables.png)\n\nAs can be seen, a station is described by its location (longitude, latitude, direccion, codigo postal, margen, localidade, municipio, provincia). After carefully analyzing the data, I found that an appropriate unique constraint would be (Longitude, Latitude, Margen). The table contains the actual product price data. Each is defined by a Station, a product, its price at a given time (fecha), as well as the brands, venta etc.\n\nAlthough this structure is very good in terms of integrity, consistency, redundancy and relationship, it becomes cumbersome to insert data manually, due to all the integrity constraints. Therefore I decided to use an ORM (Object-relational mapping), in this case, SQLAlchemy, to interact with the database. Although this may complexify this specific exercise, in the long term it becomes much more manageable, and, since we have a Data Model, allows to easily change the data storage engine without changing the code. Furthermore, since I had to do this project, I used it as an opportunity to learn ORM in Python, since I only had use ORM's in Java and C#.\n\nThe Model part of the ORM, that defines the classes that represent each table and the relationships between them, is coded in the SQLModel.py. The controller part, that bridges the excel data to the sql data and allows the insertion of all data, is in the SQLController.py file. In order to store the data of the excel file, including its date of creation, I decided to create a class ExcelFile. This way, multiple files can be easily inserted with 1 line of code. The file main.py has an example of the steps needed to get the data from the excel file and store it in the MySQL database. This was the file I run to populate the database stations that is then used to connect to powerBI (dashboard.pbix). Regarding the dashboard in powerBI, I don't really enjoy doing data visualization and I'm not very proud of the final result.\n\nI've included some comments in the code, as well as docstrings.\n\n## Part2\n\nThis folder has the following structure:\n\n ├──.vscode # Visual Studio Code settings\n ├── Part1 # Part1\n ├── Part2 # Part2\n ├── data \n ├── config.py # Configuration file\n ├── countries.json # Provided countries .json\n ├── project \n ├── test.py # Answers to the 8 questions\n ├── test\n ├── test.py # Unit tests\n ├── pythonTestVenv # Virtual Environment\n\nThe data folder contains the configuration file as well as the provided countries JSON file. For simplicity, the configuration file is a python file with a dictionary of immutable data. It could also be done in JSON or YAML.\n\nThe test.py file is in the project folder, and answers to the 8 questions of Part 2. I've included some comments in the code, as well as docstrings.\n\nIn order to test the methods and classes created, I've included 8 unit tests in the tes_test.py file that can easily be run to validate the results." } ]
9
Casey-S/CS1
https://github.com/Casey-S/CS1
fb10dd77622b63e0d3dd3feaf9f46edf9d912c72
98d9f176187fcbd7594045681e636d9ce4b6c1ea
143a45ffb15281e0985b4b26a20799d2c13f15e3
refs/heads/master
2021-08-24T13:20:39.681037
2017-11-21T07:54:43
2017-11-21T07:54:43
103,466,378
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6415384411811829, "alphanum_fraction": 0.6415384411811829, "avg_line_length": 31.5, "blob_id": "341c158ac78964d0b46025b6ba174c8110e39a03", "content_id": "167afa6b5b80dfe47bd463cc5c80498acc76f303", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 650, "license_type": "no_license", "max_line_length": 87, "num_lines": 20, "path": "/Gradebook/oop_classroom.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "from oop_students import Student\n\n\nclass Classroom(Student):\n # Start of classroom class.\n\n def __init__(self, class_name, teacher_name):\n # Create class with class name, teacher name, and roster array.\n self.class_name = class_name\n self.teacher_name = teacher_name\n self.roster = {}\n\n def add_student(self, student_name, ID):\n # Add student to roster array.\n # self.roster[student_name] = super(Classroom, self).__init__(student_name, ID)\n self.roster[student_name] = ID\n\n def get_student_roster(self, roster):\n # Print all currently enrolled students.\n print(self.roster)\n" }, { "alpha_fraction": 0.5959302186965942, "alphanum_fraction": 0.6017441749572754, "avg_line_length": 17.105262756347656, "blob_id": "f204572103c489e9ea9f86065a57a74f08912eda", "content_id": "3779eebbadad9f658d1f59f051dccd5ada046edf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/pythonIO/pythonIO.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "f = open('example.txt')\n\ntext = f.read()\n\nf.close()\n\n# Automatically close text file once done\nwith open('example.txt', 'w') as f:\n f.write(\"Test words\")\n\nwith open('example.txt') as f:\n text = f.read()\n print(text)\n\nwith open(\"example.txt\", 'a') as f:\n f.write('line 1 \\n')\n f.write('line 2 \\n')\n\nwith open('example.txt') as f:\n" }, { "alpha_fraction": 0.6046720743179321, "alphanum_fraction": 0.6145552396774292, "avg_line_length": 24.88372039794922, "blob_id": "1ac562287405d17c405e61861d84224b96547436", "content_id": "c0ba504b3294039f7aef444ef21b34611617ce90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1113, "license_type": "no_license", "max_line_length": 77, "num_lines": 43, "path": "/pythonIO/sales_data.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "with open('sales_data.txt') as f:\n index = 0\n for index, line in enumerate(f):\n index += 1\nprint(index)\n\n\nwith open('sales_data.txt') as f:\n feb_list = []\n for index, line in enumerate(f):\n slash_pos = line.index('/')\n if line[slash_pos - 1] is \"2\" and line[slash_pos - 2] is not \"1\":\n feb_list.append(line)\n # print(feb_list)\n # print(len(feb_list))\n\n# remove /t\n# remove /n\n# remove $\n# .split = array of strings\n# .replace = maintain string\n\nraw_data = open('sales_data.txt')\n\n\ndef clean_up(raw_data):\n cleaned_lines = []\n for line in raw_data:\n cleaned_line = line.replace('$', '')\n cleaned_line = cleaned_line.replace('\\n', '')\n cleaned_line = cleaned_line.split('\\t')\n cleaned_line[3] = float(cleaned_line[3])\n cleaned_lines.append(cleaned_line)\n return cleaned_lines\n\n\ncleaned_data = clean_up(raw_data)\ncleaned_data_phillies = cleaned_data[:9]\nphillies_sales = [i for i in cleaned_data_phillies if i[0] == 'Philadelphia']\nprint(phillies_sales)\n\ntotal_sales = sum([i[3] for i in cleaned_data])\nprint(total_sales)\n" }, { "alpha_fraction": 0.6627615094184875, "alphanum_fraction": 0.6635982990264893, "avg_line_length": 36.34375, "blob_id": "2ebfecb3e76dc66b68fa458c58462cb3e72f82d6", "content_id": "d66bba93bd9ac9745684786753a4ad2774c63754", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1195, "license_type": "no_license", "max_line_length": 79, "num_lines": 32, "path": "/Gradebook/oop_students.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "class Student(object):\n # Start of student class\n\n def __init__(self, name, ID):\n # Create student object with name and ID, create assignments dict.\n self.name = name\n self.ID = ID\n self.assignments = {}\n\n def add_assignment(self, assignment_name, score):\n # Add student assignment to assignments array with corresponding score.\n self.assignments[assignment_name] = score\n\n def remove_assignment(self, assignment_name):\n # Removes given assignment from assignment array.\n del self.assignments[assignment_name]\n\n def update_assignment(self, assignment_name, updated_score):\n # Updates assignment with an updated score.\n self.assignments[assignment_name] = updated_score\n\n def get_score(self, assignment_name):\n # Return the value of given assignment name.\n return self.assignments.get(assignment_name)\n\n def get_GPA(self, assignments):\n # Returns average score from all assignments.\n score_total = 0\n for assignment in self.assignments:\n score = self.assignments[assignment]\n score_total += score\n return score_total / len(self.assignments)\n" }, { "alpha_fraction": 0.6679151058197021, "alphanum_fraction": 0.6860174536705017, "avg_line_length": 27.60714340209961, "blob_id": "910db6f6d78341c5f593d97cac36d18c65b2c1e0", "content_id": "6eefa9dc533a5e4aecf4b79bad68a6862e36d108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1602, "license_type": "no_license", "max_line_length": 71, "num_lines": 56, "path": "/Gradebook/test_students.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "from oop_students import Student\n\n\ndef setup_student():\n # Create a new student entry.\n student = Student(\"Jeffrey Lebowski\", 42)\n return student\n\n\ndef setup_student_assignments():\n # Add assignments to new student entry.\n student = setup_student()\n student.assignments = {\"Retrieve Rug\": 0, \"Bowl\": 70, \"Abide\": 100}\n return student\n\n\ndef test_student():\n # Test student creation.\n student = setup_student()\n assert student.name == \"Jeffrey Lebowski\"\n assert student.ID == 42\n\n\ndef test_add_assignment():\n # Test adding an assignment with score to assignments dict.\n student = setup_student()\n student.add_assignment(\"Defeat Nihilists\", 20)\n assert student.assignments[\"Defeat Nihilists\"] == 20\n\n\ndef test_remove_assignment():\n # Test removing entry from assignment dict.\n student = setup_student_assignments()\n student.remove_assignment(\"Retrieve Rug\")\n assert student.assignments == {\"Bowl\": 70, \"Abide\": 100}\n\n\ndef test_update_assignment():\n # Test updating the score value in an assignment dict entry.\n student = setup_student_assignments()\n student.update_assignment(\"Bowl\", 90)\n assert student.assignments[\"Bowl\"] == 90\n\n\ndef test_get_assignment_score():\n # Test retrieving assignment dict entry value.\n student = setup_student_assignments()\n student.get_score(\"Abide\")\n assert student.get_score(\"Abide\") == 100\n\n\ndef test_get_GPA():\n # Test accuracy of GPA - (Abide + Bowl + Retrieve Rug) / 3\n student = setup_student_assignments()\n student.get_GPA(student.assignments)\n assert student.get_GPA(student.assignments) == 56\n" }, { "alpha_fraction": 0.6144161224365234, "alphanum_fraction": 0.615675151348114, "avg_line_length": 30.147058486938477, "blob_id": "7bdc39f7f2cee191de1b8bb2545b732b9b036434", "content_id": "cc31dae59c4e55f082cf702849745928de2b3c6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3177, "license_type": "no_license", "max_line_length": 112, "num_lines": 102, "path": "/oop_test.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "# Implement the Animal superclass here\nclass Animal(object):\n population = 0\n\n def __init__(self, name):\n Animal.population += 1\n self.name = name\n\n @classmethod\n def populationCount(cls):\n return population\n\n def sleep(self):\n print(\"%s sleeps for 8 hours\" % self.name)\n\n def eat(self, food):\n print(\"%s eats %s\" % (self.name, food))\n if food == self.favoriteFood:\n print(\"YUM! %s wants more %s\" % (self.name, food))\n\n\n# Implement the Tiger class here as a subclass of Animal\n# Hint: Implement the initializer method only\nclass Tiger(Animal):\n # Implement the initializer method here\n def __init__(self, name):\n super(Tiger, self).__init__(name)\n self.name = name\n self.favoriteFood = \"meat\"\n\n\n# Implement the Bear class and its initializer, sleep and eat methods here\nclass Bear(Animal):\n # Implement the initializer method here\n def __init__(self, name):\n super(Bear, self).__init__(name)\n self.name = name\n self.favoriteFood = \"fish\"\n\n # Copy your sleep function here and modify it to work as a method\n def sleep(self):\n print(\"%s hibernates for 4 months\" % self.name)\n\n\n# Implement the Unicorn class here as a subclass of Animal\n# Hint: Implement the initializer method and override the sleep method\nclass Unicorn(Animal):\n def __init__(self, name):\n super(Unicorn, self).__init__(name)\n self.name = name\n self.favoriteFood = \"marshmallows\"\n\n def sleep(self):\n print(\"%s sleeps in a cloud\" % self.name)\n\n# Implement the Giraffe class here as a subclass of Animal\n# Hint: Implement the initializer method and override the eat method\nclass Giraffe(Animal):\n def __init__(self, name):\n super(Giraffe, self).__init__(name)\n self.name = name\n self.favoriteFood = \"leaves\"\n\n def eat(self, food):\n print(\"%s eats %s\" % (self.name, food))\n if food == self.favoriteFood:\n print(\"YUM! %s wants more %s\" % (self.name, food))\n else:\n print(\"YUCK! %s spits out %s\" % (self.name, food))\n\n\n# Implement the Bee class here as a subclass of Animal\n# Hint: Implement the initializer method and override the sleep and eat methods\nclass Bee(Animal):\n def __init__(self, name):\n super(Bee, self).__init__(name)\n self.name = name\n self.favoriteFood = \"pollen\"\n\n def eat(self, food):\n print(\"%s eats %s\" % (self.name, food))\n if food == self.favoriteFood:\n print(\"YUM! %s wants more %s\" % (self.name, food))\n else:\n print(\"YUCK! %s spits out %s\" % (self.name, food))\n\n def sleep(self):\n print(\"%s never sleeps\" % self.name)\n\n\n# Implement the Zookeeper class here\nclass Zookeeper(object):\n # Implement the initializer method here\n def __init__(self, name):\n self.name = name\n\n # Implement the feedAnimals method here\n def feedAnimals(self, animals, food):\n print(\"%s is feeding %s to %i of %i total animals\" % (self.name, food, len(animals), Animal.population))\n for animal in animals:\n animal.eat(food)\n animal.sleep()\n" }, { "alpha_fraction": 0.4923076927661896, "alphanum_fraction": 0.5230769515037537, "avg_line_length": 18.846153259277344, "blob_id": "4c0b967406c28d20cd5e74f1a9959fe180414e3d", "content_id": "3f427c40a066fad723e834cf43e3821757a38bf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "no_license", "max_line_length": 53, "num_lines": 13, "path": "/fizzbuzz.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "\n\ndef fizzbuzz():\n\n user_number = input(\"Enter a number: \")\n\n if user_number % 3 == 0:\n print(\"fizz\")\n if user_number % 5 == 0:\n print(\"buzz\")\n if user_number % 3 != 0 and user_number % 5 != 0:\n print(user_number)\n\n\nfizzbuzz()\n" }, { "alpha_fraction": 0.5245956778526306, "alphanum_fraction": 0.5525606274604797, "avg_line_length": 27.815534591674805, "blob_id": "f63fcb48573ea43290b23f683fbc63b65cbdd976", "content_id": "0106c5790db3b9dacdfd5d19c2bf6d621f15bcb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2968, "license_type": "no_license", "max_line_length": 76, "num_lines": 103, "path": "/roulette.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "# Build a working roulette game. At minimum, this script should\n# Complete one round of roulette - but if you're up to the challenge,\n# feel free to build a full command line interface through which\n\nimport random\nrandom.seed(random)\n\nbank_account = 1000\n# bet_amount = 0\nbet_color = None\nbet_number = None\n\ngreen = [0, 37]\nred = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]\nblack = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35]\n\nwhile True:\n\n def take_bet():\n global bank_account\n Bet_color = raw_input(\"Enter bet color: \")\n\n if Bet_color in [\"red\", \"green\", \"black\"]:\n print(\"Color accepted\")\n # return Bet_color\n else:\n print(\"Invalid color\")\n pass\n\n bet_amount = input(\"Bet amount: \")\n bank_account = bank_account - bet_amount\n print(bank_account)\n\n return Bet_color, bet_amount\n # bet_number = number\n # bet_amount = amount\n\n def roll_ball():\n '''returns a random number between 0 and 37'''\n Number_rolled = random.randint(0, 37)\n return Number_rolled\n\n def check_results():\n '''Compares bet_color to color rolled.'''\n '''Compares bet_number to number_rolled.'''\n number_rolled = roll_ball()\n bet_color = take_bet()\n bet_amount = bet_color[1]\n\n if number_rolled in red:\n ball_color = \"red\"\n\n elif number_rolled in black:\n ball_color = \"black\"\n\n elif number_rolled in green:\n ball_color = \"green\"\n\n print(\"Ball landed on %s\" % ball_color)\n\n if bet_color[0] == ball_color:\n print(\"Color match!\")\n color_match = True\n return color_match, bet_amount\n else:\n color_match = False\n return color_match, bet_amount\n\n def payout():\n # returns total amount won or lost by user based on results of roll.\n global bank_account\n bet_net = check_results()\n if bet_net[0] is True:\n bet_amount = bet_net[1] * 2\n bank_account = bank_account + bet_amount\n print(\"You won %s\" % bet_amount)\n else:\n # bank_account = bank_account - bet_net\n print(\"You lost your wager of %s\" % bet_net[1])\n print(\"Your account balance is now %s\" % bank_account)\n\n def play_game():\n \"\"\"This is the main function for the game.\n When this function is called, one full iteration of roulette,\n including:\n Take the user's bet.\n Roll the ball.\n Determine if the user won or lost.\n Pay or deduct money from the user accordingly.\n \"\"\"\n pass\n\n payout()\n while True:\n answer = raw_input('Run again? (y/n): ')\n if answer in ('y', 'n'):\n break\n print 'Invalid input.'\n if answer == 'y':\n continue\n else:\n print 'Goodbye'\n break\n" }, { "alpha_fraction": 0.6625291109085083, "alphanum_fraction": 0.6644685864448547, "avg_line_length": 32.921051025390625, "blob_id": "63f7f906494945da38714306150862affd172fe7", "content_id": "9f7af0cfeffd456b79b4900fac919888cd8cd42b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2578, "license_type": "no_license", "max_line_length": 77, "num_lines": 76, "path": "/hangman.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "import random\n\n\ndef loadWord():\n '''\n Opens words.txt file as variable f.\n Saves read lines to variable wordsList, then removes spaces from words.\n Chooses a random word from wordsList and saves it as variable secretWord,\n then returns it.\n '''\n f = open('words.txt', 'r')\n wordsList = f.readlines()\n f.close()\n\n wordsList = wordsList[0].split(' ')\n secretWord = random.choice(wordsList)\n return secretWord\n\n\ndef getGuessedLetter(secretWord, letterArray, incorrectArray):\n '''\n secretWord: string, the random word the user is trying to guess.\n letterArray: array of underscores the length of secretWord.\n incorrectArray: array of incorrect guessed letters.\n For letters in the word that the user has not yet guessed,\n shown an _ (underscore) instead.\n '''\n userGuess = raw_input(\"Guess a letter: \")\n if userGuess == secretWord:\n print(\"WINNER\")\n exit()\n if userGuess in secretWord:\n print(\"%s is correct.\" % userGuess)\n for i, letter in enumerate(secretWord):\n if userGuess is letter:\n letterArray[i] = letter\n else:\n print(\"Incorrect, try again.\")\n incorrectArray.append(userGuess)\n\n # join all elements of letterArray into one element and print.\n letterArray = ''.join([i + \"\" for i in letterArray])\n print(letterArray)\n if letterArray == secretWord:\n print(\"WINNER\")\n exit()\n # join all elements of incorrectArray into one element and print.\n incorrectArray = ''.join([i + \" \" for i in incorrectArray])\n print(incorrectArray)\n\n\ndef hangman(secretWord):\n '''\n Starts up a game of Hangman in the command line.\n * At the start of the game, let the user know how many\n letters the secretWord contains.\n * Ask the user to guess one letter per round.\n * The user should receive feedback immediately after each guess\n about whether their guess appears in the computer's word.\n * After each round, you should also display to the user the\n partially guessed word so far, as well as letters that the\n user has not yet guessed.\n '''\n letterArray = ['_'] * len(secretWord)\n incorrectArray = []\n print(\"The word has %s letters\" % len(secretWord))\n numberOfGuesses = 10\n while numberOfGuesses > 0:\n print(\"You have %s guesses left\" % numberOfGuesses)\n getGuessedLetter(secretWord, letterArray, incorrectArray)\n numberOfGuesses = numberOfGuesses - 1\n print('The word was \"%s!\"' % secretWord)\n\n\nsecretWord = loadWord()\nhangman(secretWord)\n" }, { "alpha_fraction": 0.6620209217071533, "alphanum_fraction": 0.6794425249099731, "avg_line_length": 22.91666603088379, "blob_id": "7bb8c51413a8fc1db21dbb88bf989e4f49765b1a", "content_id": "4e3c578e1a0f69f872931930960c41c00d0d1235", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/Gradebook/test_classroom.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "from oop_classroom import Classroom\n\n\ndef setup_classroom():\n classroom = Classroom(\"CS1\", \"Yo Mamma\")\n return classroom\n\n\ndef test_add_student_to_roster():\n classroom = setup_classroom()\n classroom.add_student(\"Test Student\", 22)\n assert classroom.roster == {\"Test Student\": 22}\n" }, { "alpha_fraction": 0.6440678238868713, "alphanum_fraction": 0.7161017060279846, "avg_line_length": 32.71428680419922, "blob_id": "23c655e70699868e61f6be993cfa5fe4713c7d7e", "content_id": "649cd65e0d6668a7f2458ad46f58f958d4cf3e1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 141, "num_lines": 7, "path": "/pythonIO/nasa_api.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "import requests\n\nstart_date = '2017-10-21'\nend_date = '2017-10-22'\nnasa_response = requests.get('https://api.nasa.gov/neo/rest/v1/feed?start_date={}&end_date={}&api_key=DEMO_KEY'.format(start_date, end_date))\n\nprint(nasa_response.text)\n" }, { "alpha_fraction": 0.6444582939147949, "alphanum_fraction": 0.6457036137580872, "avg_line_length": 30.940000534057617, "blob_id": "eb55e8dac1c5b426f2652d0259b5407fc1fc4753", "content_id": "2c5e4ea3bacb971e9695149d10ff61a9739322cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1606, "license_type": "no_license", "max_line_length": 78, "num_lines": 50, "path": "/test_hangman.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "import hangman\nimport pytest\n\n'''\ndef isWordGuessed(secretWord, correctGuesses):\n\n secretWord: string, the random word the user is trying to guess.\n This is selected on line 9.\n correctGuesses: list of letters that have been guessed correctly so far.\n returns: boolean, True if all letters of secretWord are in correctGuesses;\n False otherwise\n\n if correctGuesses in secretWord:\n return True\n else:\n return False\n\n\ndef testisWordGuessed():\n x = isWordGuessed('cat', ['c', 't', 'a'])\n assert x is True\n x = isWordGuessed('cat', [])\n assert x is False\n'''\n\n\ndef test_getGuessedLetter(secretWord, correctGuesses):\n '''\n secretWord: string, the random word the user is trying to guess.\n This is selected on line 9.\n correctGuesses: list of letters that have been guessed correctly so far.\n returns: string, of letters and underscores. For letters in the word that\n the user has guessed correctly,\n the string should contain the letter at the correct position.\n For letters in the word that the user has not yet guessed,\n shown an _ (underscore) instead.\n '''\n\n output = ['_'] * len(secretWord)\n while True:\n userGuess = raw_input(\"Guess a letter: \")\n if userGuess in secretWord:\n print(\"%s is correct.\" % userGuess)\n for i, letter in enumerate(secretWord):\n if userGuess is letter:\n output[i] = letter\n else:\n print(\"Incorrect, try again.\")\n correctGuesses = ''.join([x + \"\" for x in output])\n print(correctGuesses)\n \n" }, { "alpha_fraction": 0.5248713493347168, "alphanum_fraction": 0.5471698045730591, "avg_line_length": 20.592592239379883, "blob_id": "4ad4b3764eaa9aa963a8c72ab9ccaf1240f1dcb3", "content_id": "8cf7ed27ab492d46d145115f9efafe4604f65804", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 583, "license_type": "no_license", "max_line_length": 73, "num_lines": 27, "path": "/algo.py", "repo_name": "Casey-S/CS1", "src_encoding": "UTF-8", "text": "# beginning_number = input(\"Enter beginning number: \")\n# ending_number = input(\"Enter ending number: \")\n\n\n# def is_palindrome(input_string):\n# split_str = list(input_string)\n#\n# if \"\" in split_str:\n# print(\"Space\")\n# if split_str[0] == split_str[-1] and split_str[1] == split_str[-2]:\n# print(\"palindrome!\")\n# else:\n# print(\"Not palindrome\")\n#\n#\n# is_palindrome(raw_input(\"Enter test word: \"))\n\ndef fib(n):\n if n == 1 or n == 2:\n return 1\n if n == 0:\n return 0\n else:\n return fib(n-1) + fib(n-2)\n\n\nprint(fib(10))\n" } ]
13
minhwang/slack_bot_example
https://github.com/minhwang/slack_bot_example
cc4f5801ca766ce6dfeab25dfd5c71ca21b2f284
582e3b0ff8120cf4c31e84b61330ce8d62f38af0
be9bd005fcf0ac92bf25bbd82fdb56aa1e7b8091
refs/heads/master
2020-12-24T05:48:49.966564
2016-08-23T12:35:04
2016-08-23T12:35:04
64,799,652
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3653120994567871, "alphanum_fraction": 0.36992040276527405, "avg_line_length": 26.125, "blob_id": "b8367fd05cd9721a83d14db418a3f3ae38ea91e1", "content_id": "dc7cfb4fbc8a06b751617d3b3d27be9fa5e03d9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2387, "license_type": "no_license", "max_line_length": 62, "num_lines": 88, "path": "/bot_server.py", "repo_name": "minhwang/slack_bot_example", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport web\nimport json\n\nurls = (\n '/', 'Index',\n '/hello', 'Hello',\n '/bob', 'Bob',\n '/yummy/action', 'YummyAction'\n)\n\nclass Index:\n def GET(self):\n return \"Hello, world!\"\n def POST(self):\n return \"Post\"\n\nclass Hello:\n def POST(self):\n req_data = web.input()\n a = {\n 'text': 'ttt',\n 'attachments': [\n {\n 'text': 'aaaaa',\n 'fallback': 'fallback',\n 'callback_id': 'callback_id',\n 'color': '#3AA3E3',\n 'attachment_type': 'default',\n 'actions': [\n {\n 'name': 'eeee',\n 'text': 'Eeee',\n 'type': 'button',\n 'value': 'dddd'\n }\n ]\n }\n ]\n }\n res = {'text':'Hello, {0}'.format(req_data.user_name)}\n web.header('Content-Type', 'application/json')\n return json.dumps(a)\n\nclass Bob:\n def parse_command_text(self, txt):\n s = txt.split('|')\n title = s[0].strip()\n desc = '' if len(s) == 1 else s[1].strip()\n return (title, desc)\n\n def POST(self):\n req_data = web.input()\n print(req_data.text)\n (title, desc) = self.parse_command_text(req_data.text)\n\n a = {\n 'text': title,\n 'attachments': [\n {\n 'response_type': 'in_channel',\n 'text': desc,\n 'fallback': 'fallback',\n 'callback_id': 'callback_id',\n 'color': '#3AA3E3',\n 'attachment_type': 'default',\n 'actions': [\n {\n 'name': 'Join',\n 'text': 'JOIN',\n 'type': 'button',\n 'value': 'join'\n }\n ]\n }\n ]\n }\n web.header('Content-Type', 'application/json')\n return json.dumps(a)\n\nclass YummyAction:\n def POST(self):\n pass\n\nif __name__ == \"__main__\": \n app = web.application(urls, globals())\n app.run()\n" } ]
1
taiyaeix/dotfiles
https://github.com/taiyaeix/dotfiles
3474d7f533bd81304d58740d0831036cc63fd13a
5a936b2f636ba1c9d9820632d601973fdaf898b8
e7abcf9fc70c2d01ff41b64448b9571f0b8125c3
refs/heads/master
2016-09-14T15:49:06.190697
2016-08-06T21:44:18
2016-08-06T21:44:18
43,852,036
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8151260614395142, "alphanum_fraction": 0.8151260614395142, "avg_line_length": 10.899999618530273, "blob_id": "0ff1a0317d30c3ba1e8a14d830f3264efb16f97f", "content_id": "7c04d3f781248f1fe618a97a422e559e8fd25d22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 18, "num_lines": 10, "path": "/.startup.py", "repo_name": "taiyaeix/dotfiles", "src_encoding": "UTF-8", "text": "import datetime\nimport json\nimport os\nimport pprint\nimport re\nimport urllib\nimport sys\nimport time\n\npp = pprint.pprint\n" }, { "alpha_fraction": 0.7630854249000549, "alphanum_fraction": 0.7630854249000549, "avg_line_length": 37.21052551269531, "blob_id": "fd9b2d13bdd7cbcbb192fe4c5fbd99180fe8ae73", "content_id": "7b8d2baa7dec5c03fd0d7291a5d11228f9c2ead2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 726, "license_type": "no_license", "max_line_length": 74, "num_lines": 19, "path": "/README.md", "repo_name": "taiyaeix/dotfiles", "src_encoding": "UTF-8", "text": "# dotfiles\n\nNothing special. Some vim stuff, ncmpcpp, mpd, etc.\n\n### Repo naming scheme\n\nRepos of mine that begin with the name of the language are bin (project)\nrepos, while repos that end with the extension name of the language are\nlibraries. Repos that begin with 'website' are the source of a website and\nrepos that fit neither of these are misc.\n\nEx:\n\n- python-chan-image-grabber: NOT a library, you can clone it and use it.\n- array-matcher.py: Library, you can require it in your project.\n- rust-migration-runner: NOT a library.\n- dotenv.rs: A library you can require as a dependency in your Cargo.toml.\n- website-austinhellyer.me: The website source at austinhellyer.me.\n- arch-linux-scripts: Misc scripts or projects.\n" }, { "alpha_fraction": 0.689497709274292, "alphanum_fraction": 0.6997717022895813, "avg_line_length": 24.764705657958984, "blob_id": "6e9b0cec6236386bd353df843dc0c8efebac1ac2", "content_id": "078d90b68f53fb5df4cc5e5ab61927ce6c875038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1752, "license_type": "no_license", "max_line_length": 167, "num_lines": 68, "path": "/.zshrc", "repo_name": "taiyaeix/dotfiles", "src_encoding": "UTF-8", "text": "export ZSH=~/.oh-my-zsh\n\nZSH_THEME=\"arrow\"\n\nCASE_SENSITIVE=\"false\"\n\nexport UPDATE_ZSH_DAYS=13\nDISABLE_LS_COLORS=\"true\"\nDISABLE_AUTO_TITLE=\"true\"\nENABLE_CORRECTION=\"false\"\nCOMPLETION_WAITING_DOTS=\"true\"\n\nplugins=(git ssh-agent)\n\nexport PATH=\"/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/home/sayla/.gem/ruby/2.2.0/bin:/home/sayla/.cargo/bin\"\n\n# Go PATH\nexport GOPATH=$HOME/go\nexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin\nexport PATH=$PATH:/home/sayla/.multirust/toolchains/1.9.0/cargo/bin\n\n# Gem PATH\nif which ruby > /dev/null && which gem > /dev/null; then\n export PATH=\"$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH\"\nfi\n\n# Haskell PATH\nexport PATH=$PATH:/home/sayla/.cabal/bin:/home/sayla/.cabal-sandbox/bin\n\nsource $ZSH/oh-my-zsh.sh\n\nalias rss='newsbeuter -r -C ~/.newsbeuter/config'\n\nalias pyact='source bin/activate'\nalias clr='tput reset'\nalias scr='scrot-uploader.sh http://xn--yck.xyz -s'\nalias ydl=\"youtube-dl -x --audio-format best $1\"\nalias gc='git commit -S'\n\n# Alias 'vim' to 'nvim' (NeoVim).\n# Also vi because why not.\nalias vi='nvim'\nalias vim='nvim'\n\nalias fetch='neofetch --block_range 1 14 --line_wrap on --bold off \\\n --uptime_shorthand on --gtk_shorthand on --colors 2 5 2 5 5 6 \\\n --ascii'\n\n# alias for tweather. Not included because it uses my latitude and longitude\n# coordinates. See for details:\n# https://github.com/taiyaeix/tweather\nif [[ -f ~/.config/.tweather ]]; then\n source ~/.config/.tweather\nelse\n echo \"~/.config/.tweather file not found\"\nfi\n\neval $(thefuck --alias)\n\nexport PYTHONSTARTUP=~/.startup.py\n\nexport GEM_HOME=$(ruby -e 'print Gem.user_dir')\n\n# Ensure that ssh's agent is running.\neval `ssh-agent`\nssh-add\n\ntput reset\n" } ]
3
giovannamsr/SEEDSecurityLabs
https://github.com/giovannamsr/SEEDSecurityLabs
5e1360b4c66384724a1dbdd6dc27c707483e6baa
a46da709a5967640f4cd68a9a582665cc5cd5f80
ed5227d9ab02c939e7a4bbc3eb150f276d5e5204
refs/heads/master
2023-05-14T11:17:33.426559
2021-06-10T18:24:52
2021-06-10T18:24:52
366,189,932
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8042959570884705, "alphanum_fraction": 0.8042959570884705, "avg_line_length": 103.5, "blob_id": "0a10d0a1b2c5895e37b2f2e5b004a028ed682b4e", "content_id": "36f0de29c0d0316ecf186886718b09640c40e8d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 430, "license_type": "no_license", "max_line_length": 179, "num_lines": 4, "path": "/Sniffing-and-Spoofing/README.md", "repo_name": "giovannamsr/SEEDSecurityLabs", "src_encoding": "UTF-8", "text": "# SEEDSecurityLabs\nHere you will find my resolutions and reports of some of the labs of SEEDLabs. In case you don't know what that is, you can find more information at seedsecuritylabs.org\nMost of the programs need to be in root to work.\nAqui você irá encontrar minhas soluções e relatórios de alguns dos Labs do SEEDLabs. Caso você não saiba o que é isso, você pode encontrar mais informações em seedsecuritylabs.org\n\n" }, { "alpha_fraction": 0.567460298538208, "alphanum_fraction": 0.567460298538208, "avg_line_length": 19.91666603088379, "blob_id": "532350535f42a5cc9993be574c0bf4198c669c0c", "content_id": "8c43845fa9d3743f5ca69f1a9891fbd30859e6fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 52, "num_lines": 12, "path": "/Sniffing-and-Spoofing/sniffandspoof.py", "repo_name": "giovannamsr/SEEDSecurityLabs", "src_encoding": "UTF-8", "text": "#!usr/bin/python\nfrom scapy.all import *\n\ndef print_pkt(pkt):\n if pkt.haslayer(Raw):\n print(\"------------Packet info------------\")\n print(pkt[Raw].load)\n\n#insert the filter here\nfil = 'tcp'\n\npkt = sniff(filter = fil, prn = print_pkt)\n\n" }, { "alpha_fraction": 0.521541953086853, "alphanum_fraction": 0.5827664136886597, "avg_line_length": 23.27777862548828, "blob_id": "deafef31fd48f8ba49111d76a98a54bac9f00dcf", "content_id": "76e0c988aa37bd06be30993d922fbf0a1ed371aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 71, "num_lines": 18, "path": "/TCP_IP_Attacks/tcp_rst_attack.py", "repo_name": "giovannamsr/SEEDSecurityLabs", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nfrom scapy.all import *\nimport sys\n\nIP_SRC = '10.0.2.12'\nIP_DST = '10.0.2.8'\n\ndef spoof_pkt(pkt):\n old_tcp = pkt[TCP]\n ip = IP(src = IP_SRC, dst = IP_DST)\n tcp = TCP(sport = 23, dport = old_tcp.sport,\n flags = 'R', seq = old_tcp.ack)\n new_pkt = ip/tcp\n ls(new_pkt)\n send(pkt, verbose = 0)\n\nf = 'tcp and src host 10.0.2.12 and dst host 10.0.2.8 and dst port 23' \nsniff(filter = f, prn = spoof_pkt)\n\n\n\n\n" }, { "alpha_fraction": 0.5378422141075134, "alphanum_fraction": 0.5829307436943054, "avg_line_length": 23.760000228881836, "blob_id": "7eea5e1e2a6857259cd332ceb077ee80d936e8c2", "content_id": "6d559faa7a55a8fee9378102be3e6e412347fe0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 69, "num_lines": 25, "path": "/TCP_IP_Attacks/reverse_shell.py", "repo_name": "giovannamsr/SEEDSecurityLabs", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nfrom scapy.all import *\n\nIP_SRC = '10.0.2.6' #client\nIP_DST = '10.0.2.8' #server\n\ndef spoof(pkt):\n old_ip = pkt[IP]\n old_tcp = pkt[TCP]\n\n newseq = old_tcp.seq + 5\n newack = old_tcp.ack + 1\n ip = IP(src = IP_SRC, dst = IP_DST)\n tcp = TCP(sport = old_tcp.sport, dport = 23, flags = 'A',\n seq = newseq, ack = newack)\n data = '\\n touch /tmp/spoofed_file \\n'\n pkt = ip/tcp/data\n ls(pkt)\n print(\"Sending session hijacking packet\")\n send(pkt, verbose = 0)\n quit()\n\nf = 'tcp and src host 10.0.2.6 and dst host 10.0.2.8 and dst port 23'\n\nsniff(filter = f, prn = spoof)\n\n\n" }, { "alpha_fraction": 0.5828402638435364, "alphanum_fraction": 0.5976331233978271, "avg_line_length": 24.923076629638672, "blob_id": "746fc0f03c76d4f6965af2be7631764f45fa44e6", "content_id": "51f6f4c25cfa8e41a0c0db1e2e8b5eb9cf48d09c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 48, "num_lines": 13, "path": "/Sniffing-and-Spoofing/sniffing.py", "repo_name": "giovannamsr/SEEDSecurityLabs", "src_encoding": "UTF-8", "text": "#!usr/bin/python\nfrom scapy.all import *\n\ndef print_pkt(pkt):\n print(\"------------Packet info------------\")\n print(\"Source IP: \", pkt[IP].src)\n print(\"Destination IP: \", pkt[IP].dst)\n print(\"Protocol : \",pkt[IP].proto)\n\n#insert the filter here\nfil = 'tcp and dst portrange 10-100'\n\npkt = sniff(filter = fil, prn = print_pkt)\n\n" } ]
5
piyush9910/Tambola
https://github.com/piyush9910/Tambola
0f48a10fb3dd7b651b32d6e3e437e92773ab5693
d18918a7c5282cc3235b2278a9249f1e8fbc6549
50205e152aa197f437c9d8bea58234270793b56e
refs/heads/master
2020-12-18T19:12:02.260081
2020-01-22T03:49:02
2020-01-22T03:49:02
235,493,345
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.294460654258728, "alphanum_fraction": 0.5932944416999817, "avg_line_length": 19.4375, "blob_id": "94e36f03fd33646d4bf493c6c3042ffbc32a9682", "content_id": "b037408d77567637437ec9c898919a4ca9e94e51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 686, "license_type": "no_license", "max_line_length": 280, "num_lines": 32, "path": "/Tambola Number Generator.py", "repo_name": "piyush9910/Tambola", "src_encoding": "UTF-8", "text": "import random\r\n\r\nimport time\r\n\r\n\r\n\r\nl1=[12,3,27,63,55,39,78,85,35,5,57,60,21,72,83,26,80,19,44,69,22,93,64,36,67,89,43,2,46,87,95,6,16,56,9,11,10,17,1,61,42,31,33,14,30,90,52,81,7,18,48,75,40,23,20,4,92,51,79,76,62,50,86,66,41,45,24,94,82,37,65,53,70,58,29,47,13,28,38,59,74,91,73,49,34,54,32,25,15,8,84,77,88,71,68]\r\n\r\nl2=[]\r\n\r\n\r\n\r\nwhile len(l2)!=95 :\r\n\r\n a=random.randrange(0,95)\r\n\r\n if a not in l2:\r\n\r\n l2+=[a]\r\n\r\n time.sleep(1)\r\n\r\n print(\"calling a number\",l1[a])\r\n\r\ntime.sleep(1)\r\nprint(\"calling a number 99\") \r\ntime.sleep(1)\r\nprint(\"calling a number 96\")\r\ntime.sleep(1)\r\nprint(\"calling a number 98\")\r\ntime.sleep(1)\r\nprint(\"calling a number 97\")\r\n" }, { "alpha_fraction": 0.3224341571331024, "alphanum_fraction": 0.36330607533454895, "avg_line_length": 17.087718963623047, "blob_id": "45670709021fe6828362f40f90e964486494efdc", "content_id": "579df7bd6d837e190d4e5726c27fce474aeb7e5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1101, "license_type": "no_license", "max_line_length": 154, "num_lines": 57, "path": "/Tambola Ticket.py", "repo_name": "piyush9910/Tambola", "src_encoding": "UTF-8", "text": "print(\"_____________________________________________________TAMBOLA____________________________________________________________ \")\r\n\r\nimport random\r\nimport numpy as np\r\nimport time\r\nticket=np.full(30,0)\r\nx=1\r\nticket1=ticket.reshape(3,10)\r\n\r\nfor c in range(0,10):\r\n\r\n for r in range(0,3):\r\n\r\n ticket1[r][c]=random.randrange(x,x+3)\r\n\r\n if ticket1[r][c]==100:\r\n\r\n ticket1[r][c]=99\r\n\r\n if r==1:\r\n\r\n x=x+4\r\n\r\n else:\r\n\r\n x+=3\r\n\r\nprint(ticket1)\r\n\r\n\r\n\r\nfor i in range(100):\r\n\r\n n=int(input(\"enter your called number:\"))\r\n\r\n for c in range(0,10):\r\n\r\n for r in range(0,3):\r\n\r\n if ticket1[r][c]==n:\r\n\r\n ticket1[r][c]=0\r\n\r\n print(ticket1) \r\n if ticket1[r][c]==0:\r\n time.sleep(3)\r\n print(\"yeahh!!!! BINGO \")\r\n time.sleep(10)\r\n break\r\n \r\n \r\n\r\n if ticket1[r][c]!=n:\r\n\r\n print(\"enter next number\")\r\n print(ticket1)\r\n print(\"*********************************\") \r\n" } ]
2
geraldoandradee/fatec-coding
https://github.com/geraldoandradee/fatec-coding
9a9784e6d2375fa7ae3ea3a0423db44317bba94c
4aeae7aacd8e5c3371abb2617f8b9c941bd63687
336287060408afdb489aed35d958a10cf0c9c546
refs/heads/master
2021-01-25T08:59:46.744193
2014-09-30T03:32:18
2014-09-30T03:32:18
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.620620608329773, "alphanum_fraction": 0.6396396160125732, "avg_line_length": 25.69444465637207, "blob_id": "68bbbc57bc4caf419a25941ab3378324d24b9c1e", "content_id": "70e7b054e557b0aeb91e93da0d725aa2eb374017", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1007, "license_type": "permissive", "max_line_length": 104, "num_lines": 36, "path": "/algoritmos-e-logica-da-programacao/strings/ConsoleApplication1/ConsoleApplication1/string_1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "ISO-8859-1", "text": "/*\r\n1. Ler uma string, invertê-la e mostrá-la \r\n2. Ler uma sentença e contar as vogais \r\n3. Ler uma frase e remover os espaços em branco, mostrá-la adequadamente \r\n4. Ler uma frase e verificar se ela é palíndromo \r\n5. Ler 2 palavras e verificar se a segunda é giro da primeira.\r\n*/\r\n\r\n#include <stdio.h>\r\n#include <string.h>\r\n\r\nint mmain()\r\n{\r\n\tchar name[50];\r\n\tchar nome_invertido[50]; // apenas 50 caracteres\r\n\r\n\tint total_array_string = 0, counter = 0;\r\n\tprintf(\"\\nDigite uma string:\\n\");\r\n\tscanf(\"%[^\\n]%*c\", name);\r\n\tprintf(\"Agora vamos inverter a string\");\r\n\ttotal_array_string = strlen(name)-1; // para iterar sobre a string\r\n\r\n\r\n\tfor(counter=0; name[counter]!='\\0'; counter++) { //Repete enquanto nao chegar ao final da string\r\n nome_invertido[total_array_string] = name[counter]; \r\n total_array_string--; \r\n }\r\n\r\n\tnome_invertido[strlen(name)] = '\\0';\r\n\r\n\tprintf(\"O nome invertido eh: %s\", nome_invertido);\r\n\r\n\tprintf(\"\\n\\n\");\r\n\tsystem(\"PAUSE\");\r\n\treturn 0;\r\n}\r\n\r\n" }, { "alpha_fraction": 0.6549053192138672, "alphanum_fraction": 0.6652323603630066, "avg_line_length": 28.075000762939453, "blob_id": "8aa17f440ee4503ef1343ff7ba9a8b909f637ac4", "content_id": "c0db12f85cb5950bb5fda2204ffb5c0f3abec6cd", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1164, "license_type": "permissive", "max_line_length": 120, "num_lines": 40, "path": "/algoritmos-e-logica-da-programacao/exercicio1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/* vamos pensar um pouco:\n\tpatinho: uma cabeca e dois pes\n\tcoelo: uma cabeca e quatro pes\n*/\n\nint main()\n{\n\tint numero_de_pes = 0, numero_de_cabecas = 0, quantidade_de_patos = 0, quantidade_de_coelhos = 0, resto_de_animais = 0;\n\tprintf(\"\\nEntre com o numero de cabecas:\\n\");\n\tscanf(\"%d\", &numero_de_cabecas);\n\n\tprintf(\"\\nEntre com o numero de pes:\\n\");\n\tscanf(\"%d\", &numero_de_pes);\n\n\n\t// vamos validar o numero de entrada\n\tif (numero_de_pes > 2 && numero_de_cabecas > 0)\n\t{\n\t\t// vamos validar o numero de pes fornecidas\n\t\tif (numero_de_pes >= numero_de_cabecas * 2 && numero_de_pes <= numero_de_cabecas * 4) \n\t\t{\n\t\t\tquantidade_de_coelhos = (numero_de_pes - (2* numero_de_cabecas)) / 2;\n\t\t\tquantidade_de_patos = numero_de_cabecas - quantidade_de_coelhos;\n\n\t\t\tprintf(\"A quantidade de patos é %d \\n\", quantidade_de_patos);\n\t\t\tprintf(\"A quantidade de coelhos é %d \\n\", quantidade_de_coelhos);\n\n\t\t} else {\n\t\t\tprintf(\"\\nNumero de pes e cabecas invalido. Tem algum bicho invalido (aleijado).\\n\");\n\t\t}\n\t\t// agora vamos proporcionar o numero de pes pelo numero de cabecas\n\n\t} else {\n\t\tprintf(\"\\nNumero de pes e cabecas invalido\\n\");\n\t}\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.7228915691375732, "alphanum_fraction": 0.7228915691375732, "avg_line_length": 26.83333396911621, "blob_id": "f9bc13dff2d86d0a52b7f087bc9e0ba36d2907fc", "content_id": "e9f7a537f76277436520aceccbc08ad1e48d45f4", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 166, "license_type": "permissive", "max_line_length": 44, "num_lines": 6, "path": "/estrutura-de-dados/trabalho 1/makefile", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "all: trabalho.o\n\tgcc -o target/trabalho.sh target/trabalho.o\ntrabalho.o: trabalho.c trabalho.h\n\tgcc -c trabalho.c -o target/trabalho.o\nclean:\n\trm -f *.o *.sh target/*" }, { "alpha_fraction": 0.47612157464027405, "alphanum_fraction": 0.49638205766677856, "avg_line_length": 19, "blob_id": "d6911dc832bccd3bccbde274de04b38b0e96e5a8", "content_id": "06df0f882347bb65c8a8b11cce9049a531f20437", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 698, "license_type": "permissive", "max_line_length": 97, "num_lines": 33, "path": "/programacao-micro-computadores/c/aritmetica_de_ponteiros_v2.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n\r\nint main(){\r\n\tint a[10];\r\n\tint * p;\r\n\tint i = 0;\r\n\r\n\tp = a; // inicializa o ponteiro, um array é um ponteiro que aponta para o primeiro elemento\r\n\r\n\tfor (i = 0; i < 10; i++)\r\n\t{\r\n\t\tprintf(\"p[%d] = %p\\n\", i, &p[i]);\r\n\t\t//&p[i] == &*(p + i) == p +i\r\n\t\tp[i] = 0; // *(p + i)\r\n\t}\r\n\tprintf(\"p - a = %d\\n\", p - a); // valida\r\n//\tprintf(\"p + &a[0] = %p\\n\\n\", p + &a[0]); //erro\r\n\r\n\tprintf(\"Conteudo do vetor: \\n\");\r\n\tfor (i = 0; i < 10; ++i)\r\n\t{\r\n\t\tprintf(\"%1lf, \", *(a + i));\r\n\t}\r\n\r\n\tprintf(\"\\b\\b.\\n\");\r\n\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Operações com ponteiros: soma, subtração.\r\n * Operações entre ponteiros: nao se pode somar ponteiros entre si mas pode-se subtrair entre si;\r\n */" }, { "alpha_fraction": 0.511904776096344, "alphanum_fraction": 0.5366300344467163, "avg_line_length": 22.255319595336914, "blob_id": "e05aab00af8ffe783642abfcc89db55d26c33dcb", "content_id": "ea782b870811ed98a1b41f9f263ee2c0bae47d53", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1092, "license_type": "permissive", "max_line_length": 115, "num_lines": 47, "path": "/algoritmos-e-logica-da-programacao/compra.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float vlr_compra, a_pag, parc, desc, acres;\n int op_pag, n_parc;\n \n printf(\"\\nQual o valor da compra\\n-->\");\n scanf(\"%f\", &vlr_compra);\n \n printf(\"\\nQual a opcao de pagamento\\n\\n1 - A Vista\\n2 - A Prazo\\n\\n-->\");\n scanf(\"%d\", &op_pag);\n\n if (op_pag == 1) {\n desc = vlr_compra * 10/100;\n a_pag = vlr_compra - desc;\n \n printf(\"\\nVoce ganhou um desconto de R$%.2f\\nValor a pagar %.2f\\n\\n\", desc, a_pag); \n }\n else {\n if (op_pag == 2) {\n printf(\"\\nNumero de Parcelas (2 ou 3):\\n\\n-->\");\n scanf(\"%d\", &n_parc);\n if (n_parc == 2) {\n\tparc = vlr_compra/2;\n\t\n\tprintf(\"\\nValor de cada parcela R$%.2f\\n\\n\", parc);\n }\n else {\n\tif (n_parc == 3) {\n\t acres = vlr_compra * 10/100;\n\t a_pag = vlr_compra + acres;\n\t parc = a_pag/3;\n\t \n\t printf(\"\\nValor do acrecimo R$%.2f\\nValor a Pagar R$%.2f\\nValor de cada parcela R$%.2f\\n\\n\", acres,a_pag, parc);\n\t}\n\telse {\n\t printf(\"\\nNumero de Parcelas invalido\\n\\n\"); \n\t}\n }\n }\n else {\n printf(\"\\nOpcao de pagamento invalida\\n\\n\"); \n }\n }\n \n return 0;\n}" }, { "alpha_fraction": 0.4127516746520996, "alphanum_fraction": 0.463087260723114, "avg_line_length": 15.61111068725586, "blob_id": "cede660176841e7a0738765c43d4ca4a3f3a5154", "content_id": "256ba451f7ca696f3b2a1f5ea5931bcdc667b95e", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 298, "license_type": "permissive", "max_line_length": 41, "num_lines": 18, "path": "/algoritmos-e-logica-da-programacao/exercicio3.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float v, vt;\n \n printf(\"\\nQual o valor do salario?\\n\");\n scanf(\"%f\", &v);\n \n if (v > 1000) {\n vt = v + (v * 5/100);\n printf(\"\\nO salario e: %.2f\\n\", vt);\n }\n else {\n vt = v + (v * 7/100);\n printf(\"\\nO salario e: %.2f\\n\", vt);\n }\n return 0;\n}" }, { "alpha_fraction": 0.5350961685180664, "alphanum_fraction": 0.5517628192901611, "avg_line_length": 20.60869598388672, "blob_id": "d2ecee1cabd65dad902ccf05ef721479c9893a30", "content_id": "2e3bed2c75383aaf55cbd93ffb1da1c0b843ad19", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6333, "license_type": "permissive", "max_line_length": 123, "num_lines": 276, "path": "/estrutura-de-dados/trabalho 1/trabalho1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "# include \"trabalho1.h\" // INCLUI A BIBLIOTECA ou HEADER trabalho.h A EXECUCAO DO PROGRAMA\r\n\r\n\r\nint main() {\r\n\r\n\tint * vetor_aleatorio;\r\n\tint * vetor_desc;\r\n\tint * vetor_asc;\r\n\r\n\tvetor_aleatorio = ( int * ) malloc ( T * sizeof(int));\r\n\tvetor_desc = ( int * ) malloc ( T * sizeof(int));\r\n\tvetor_asc = ( int * ) malloc ( T * sizeof(int));\r\n\r\n\tint i = 0;\r\n\tfloat contador_comparacao = 0;\r\n\tfloat contador_atribuicao = 0;\r\n\r\n\tprintf(\"Vamos testar o buble para ordenar o vetor aleatorio\\n\");\r\n\tfor (i=0;i<10;i++) {\r\n\t\tprintf(\"Gerando o vetor aleatorio...\\n\");\r\n\t\tgera(vetor_aleatorio, T);\r\n\t\tprintf(\"Vetor aleatorio gerado \\n\");\r\n\t\tprintf(\"Agora vamos ordenar o vetor aleatorio...\\n\");\r\n\t\tbubble(vetor_aleatorio, T, &contador_comparacao, &contador_atribuicao);\r\n\t}\r\n\tprintf(\"Vetor aleatorio: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\r\n//Vetor aleatorio: Contador comparacao 16777216 Contador atribuicao 67108864\r\n\r\n\ti = 0;\r\n\tcontador_comparacao = 0;\r\n\tcontador_atribuicao = 0;\r\n\tprintf(\"Vamos testar o bubble para ordenar o vetor crescente\\n\");\r\n\tfor (i=0;i<10;i++) {\r\n\t\tprintf(\"Gerando o vetor crescente...\\n\");\r\n\t\tgera_vetor_crescente(vetor_asc, T);\r\n\t\tprintf(\"Vetor crescente gerado \\n\");\r\n\t\tprintf(\"Agora vamos ordenar o vetor crescente...\\n\");\r\n\t\tbubble(vetor_asc, T, &contador_comparacao, &contador_atribuicao);\r\n\t}\r\n\tprintf(\"Vetor crescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\r\n//\tVetor crescente: Contador comparacao 16777216 Contador atribuicao 0\r\n\r\n\ti = 0;\r\n\tcontador_comparacao = 0;\r\n\tcontador_atribuicao = 0;\r\n\tprintf(\"Vamos testar o bubble para ordenar o vetor decrescente\\n\");\r\n\tfor (i=0;i<10;i++) {\r\n\t\tprintf(\"Gerando o vetor decrescente...\\n\");\r\n\t\tgera_vetor_decrescente(vetor_desc, T);\r\n\t\tprintf(\"Vetor decrescente gerado \\n\");\r\n\t\tprintf(\"Agora vamos ordenar o vetor decrescente...\\n\");\r\n\t\tbubble(vetor_desc, T, &contador_comparacao, &contador_atribuicao);\r\n\t}\r\n\tprintf(\"Vetor decrescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\r\n//Vetor decrescente: Contador comparacao 16777216 Contador atribuicao 67108864\r\n\treturn 0;\r\n}\r\n\r\nvoid gera_vetor_decrescente(int * vetor, int n) {\r\n\tint i=0;\r\n\tfor(i=0;i<n;i++) {\r\n\t\tvetor[i] = n-i;\r\n\t}\r\n}\r\n\r\nvoid gera_vetor_crescente(int * vetor, int n) {\r\n\tint i=0;\r\n\tfor(i=0;i<n;i++) {\r\n\t\tvetor[i] = i;\r\n\t}\r\n}\r\n\r\n/*\r\n * Essa funcao testa se o item já existe na matriz\r\n *\r\n * int v: matriz de vetores\r\n * int n: numero de itens\r\n * int numero_gerado: pa\r\n **/\r\nint tem_repeticao(int * v, int n, int numero_gerado) {\r\n\tint i = 0;\r\n\tfor (i=0;i<n;++i) {\r\n\t\tif (v[i] == numero_gerado) {\r\n\t\t\treturn 1; // ja existe\r\n\t\t}\r\n\t}\r\n\treturn 0; // nao tem repeticao, urru\r\n}\r\n\r\n/* FUNCAO UTILIZADA PARA GERAR UM VETOR DE N�MEROS ALEAT�RIOS */\r\nvoid gera (int *v, int n){\r\n\tint i=0;\r\n\tint numero;\r\n\twhile(i<n) {\r\n\t\tnumero = rand();\r\n\t\tif (!tem_repeticao(v, n, numero)) {\r\n\t\t\tv[i] = numero;\r\n\t\t\t++i;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA MOSTRAR O VETOR NA TELA */\r\nvoid mostra (int *v, int n, char *msg){\r\n\tint i;\r\n\tprintf ( \"\\n%s\\n\\n\", msg );\r\n\tfor ( i = 0; i < n; i++ ){\r\n\t\tprintf ( \"%d \", v[i]);\r\n\t}\r\n\tprintf (\"\\n\");\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA MOSTRAR O VETOR \"ORDENADO AO CONTR�RIO\" NA TELA */\r\nvoid mostraInvertido (int *v, int n, char *msg){\r\n\tint i = 0;\r\n\tprintf ( \"\\n%s\\n\\n\", msg );\r\n\tfor ( i = n - 1; i >= 0; i-- ){\t\t// colocado n - 1 para corre��o do \"primeiro item invertido\"\r\n\t\tprintf ( \"%d \", v[i]);\r\n\t}\r\n\t\r\n\tprintf (\"\\n\");\r\n\t\r\n}\r\n\r\n\r\n/* FUNCAO UTILIZADA PARA ORDENAR O VETOR UTILIZANDO O ALGOR�TMO \"BUBBLE SORT\" */\r\nvoid bubble (int * v, int n, float * cc, float * ca) {\r\n\tint i, j;\r\n\tfor ( i = 1; i < n; i++ ) {\r\n\t\t(*cc) = (*cc)+1;\r\n\t\tfor ( j = 0; j < n - i; j++ ) {\r\n\t\t\t(*cc) = (*cc)+1;\r\n\t\t\tif (v[j] > v[j+1]) {\r\n\t\t\t\t(*cc) = (*cc)+1;\r\n\t\t\t\ttroca (v, j);\r\n\t\t\t\t(*ca) = (*ca) + 3;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA TROCAR A POSI��O E ORDENAR O VETOR \"...\" */ // MELHORAR A DESCRI��O <<<<<<<<<<<\r\nvoid troca (int *v, int pos){\r\n\tint aux = v[pos];\r\n\tv[pos] = v[pos+1];\r\n\tv[pos+1] = aux;\r\n\t\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA TROCAR A POSI��O E ORDENAR O VETOR \"...\" */\t// MELHORAR A DESCRI��O <<<<<<<<<<<<\r\nvoid trocaProximo (int *v, int pos){\r\n\r\n\tint aux \t\t= v[pos];\r\n\t\tv[pos]\t\t= v[pos + 1];\r\n\t\tv[pos + 1]\t= aux;\r\n\t\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA TROCAR A POSI��O E ORDENAR O VETOR \"...\" */\t// MELHORAR A DESCRI��O <<<<<<<<<<<\r\nvoid trocaAnterior (int *v, int pos){\r\n\r\n\tint aux \t\t= v[pos];\r\n\t\tv[pos]\t\t= v[pos - 1];\r\n\t\tv[pos - 1]\t= aux;\r\n\t\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA TROCAR A POSI��O E ORDENAR O VETOR \"...\" */\t// MELHORAR A DESCRI��O <<<<<<<<<<<\r\nvoid trocaMinimo (int *v, int pos){\r\n\t\r\n\tint min;\r\n\tint aux \t\t= v[min];\r\n\t\tv[min]\t\t= v[pos];\r\n\t\tv[pos]\t\t= aux;\r\n\t\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA ORDENAR O VETOR UTILIZANDO O ALGOR�TMO \"BUBBLE SORT\" */\r\nvoid bubbleSort (int *v, int n){\r\n\t\r\n\tint i, j;\r\n\t\r\n\tfor ( i = 1; i < n; i++ ){\r\n\t\r\n\t\tfor ( j = 0; j < n - i; j++ ){\r\n\t\t\t\r\n\t\t\tif (v[j] > v[j+1]){\r\n\t\t\t\ttrocaProximo (v, j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA ORDENAR O VETOR UTILIZANDO O ALGOR�TMO \"INSERTION SORT\" */\r\nvoid insertionSort (int *v, int n){\r\n\r\n\tint i, j, key;\r\n\r\n\tfor ( i = 1; i < n; i++ ){\r\n\t\t\r\n\t\tkey = v[i];\r\n\r\n\t\twhile ( i > 0 && v[i -1] > key ){\r\n\t\t\t\r\n\t\t\ttrocaAnterior (v, j);\r\n\t\t\t/*\r\n\t\t\tj \t\t\t= v[i];\r\n\t\t\tv[i] \t\t= v[i -1];\r\n\t\t\tv[i -1] \t= j;\r\n\t\t\t*/\r\n\t\t\t\r\n\t\t\t--i;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA ORDENAR O VETOR UTILIZANDO O ALGOR�TMO \"SELECTION SORT\" */\r\nvoid selection (int *v, int n){\r\n\t\r\n\tint i, j, x, min, k;\r\n\t\r\n\tfor ( i = 0; i < n; i++ ){\r\n\t\r\n\t\tmin = i;\r\n\t\t\r\n\t\tfor ( j = i + 1; j < (n - i)\t; j++ ){\r\n\t\t\t\r\n\t\t\tif (v[min] > v[j]){\r\n\t\t\t\tmin = j;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttrocaMinimo (v, j);\r\n\t\t\t/*\r\n\t\t\tx \t\t= v[min];\r\n\t\t\tv[min]\t= v[j];\r\n\t\t\tv[j] \t= x;\r\n\t\t\t*/\r\n\t\t}\r\n\t}\r\n\t\r\n}\r\n\r\n\r\n/* FUN��O UTILIZADA PARA ORDENAR O VETOR UTILIZANDO O ALGOR�TMO \"BUBBLE SORT\" */\r\nint busca_binaria (int *v, int n, int x){\r\n\r\n\tint meio, ini = 0, fim = n - 1;\r\n\r\n\twhile ( ini < fim ){\r\n\t\tmeio = ( ini + fim ) / 2;\r\n\t\t\r\n\t\tif ( v[meio] == x ) {\r\n\t\t\treturn meio;\r\n\t\t}\r\n\t\t\r\n\t\tif ( x > v[meio] ){\r\n\t\t\tini = meio + 1;\r\n\t\t} \r\n\t\telse {\r\n\t\t\tfim = meio - 1;\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn -1;\r\n\t\r\n}\r\n" }, { "alpha_fraction": 0.4704875946044922, "alphanum_fraction": 0.48246365785598755, "avg_line_length": 22.39583396911621, "blob_id": "0c268724cdf91b2832eee5648cbcd66991c71937", "content_id": "48000cd2a8d8fdc45a53b62c98030973e8107919", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1171, "license_type": "permissive", "max_line_length": 125, "num_lines": 48, "path": "/algoritmos-e-logica-da-programacao/projeto2/jose_rodrigo.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "/**\r\n* Simples para qualquer numero inteiro k < n, k será 1 para k primeiros digitos na sequencia.\r\n* Os itens seguintes será a ultimo_termo de k ultimos numeros. O total de numeros deve obedecer ao total de total = k + (n-k)\r\n*/\r\n#include <stdio.h>\r\n\r\nint main() {\r\n int n, k, i, j;\r\n int ultimo_termo = 0;\r\n\r\n printf(\"Calculo do enesimo termo de Fitromacci\\n\");\r\n printf(\"Digite um inteiro k: \");\r\n scanf(\"%d\", &k);\r\n printf(\"Digite um inteiro n: \");\r\n scanf(\"%d\", &n);\r\n\r\n if (n <= k) {\r\n printf(\"\\nK nao pode ser menor do que N\\n\");\r\n return 1;\r\n }\r\n\r\n if (k <= 1) {\r\n printf(\"\\nK precisa ser maior do que 1\\n\");\r\n return 2;\r\n }\r\n\r\n int vetor[n];\r\n\r\n for (i = 0; i < k; i++) {\r\n vetor[i] = 1; // todos os primeiros 1\r\n }\r\n\r\n for (i = k; i < n; i++) {\r\n vetor[i] = 0;\r\n for (j = i - 1; j >= i - k; j--) {\r\n vetor[i] += vetor[j];\r\n }\r\n }\r\n\r\n printf(\"Segue a sequecia Fitromacci: \");\r\n for (i = 0; i < n; i++) {\r\n printf(\"%d \", vetor[i]);\r\n }\r\n\r\n printf(\"\\nO ultimo termo de Fitromacci eh: %d\", vetor[n - 1]);\r\n\r\n return 0;\r\n}" }, { "alpha_fraction": 0.5433255434036255, "alphanum_fraction": 0.5573770403862, "avg_line_length": 27.53333282470703, "blob_id": "c37b424102d0cbe916ced9f66e7deb610d6a7fff", "content_id": "488a10f40478a2a6d007965405a6e59bb5a5f022", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 430, "license_type": "permissive", "max_line_length": 78, "num_lines": 15, "path": "/estrutura-de-dados/sobre_vetores.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n// &: operador de referência ou extrator de endereço\n// *: operador derreferência \nint main () {\n\tint v[5], i;\n\tprintf(\"Endereco inicial do vetor: %p\\n\", v);\n\tfor (i=0;i<5; i++) {\n\t\tv[i] = i * 10;\n\t\tprintf(\"Posicao %d, Valor %d Endereco do vetor: %p \\n\", i, v[i], v + i);\n\t\tprintf(\"Posicao %d, Valor %d Endereco do vetor: %p \\n\", i, *(v + i), &v[i]);\n\t\t// printf(\"%d \", v[i]);\n\t} \n\tprintf(\"\\n\");\n\treturn 0;\n}" }, { "alpha_fraction": 0.5287671089172363, "alphanum_fraction": 0.5589041113853455, "avg_line_length": 23.399999618530273, "blob_id": "c6b59497786b367fdda25d0d70f886194023fab7", "content_id": "ee6f2f003db3889a54d291f65ad4d75543d86439", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 365, "license_type": "permissive", "max_line_length": 68, "num_lines": 15, "path": "/algoritmos-e-logica-da-programacao/media.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float n1, n2, media;\n printf(\"\\nColoque suas notas para o calculo da Media\\n\");\n scanf(\"%f%f\", &n1, &n2);\n media = (n1 + n2)/2;\n if ( media >= 6) {\n printf(\"\\nPARABENS voce foi aprovado com Media %.2f\\n\", media);\n }\n else {\n printf(\"\\nEstude um pouco mais, sua Media e %.2f\\n\", media);\n } \n return 0;\n}" }, { "alpha_fraction": 0.6740740537643433, "alphanum_fraction": 0.6851851940155029, "avg_line_length": 35.486488342285156, "blob_id": "abbcaf16c909aa3f7616c68e658aaf2d15027edb", "content_id": "480fd396286b0477058c6e4fc92df087fa7f4cf4", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1374, "license_type": "permissive", "max_line_length": 292, "num_lines": 37, "path": "/programacao-micro-computadores/c/trabalho/teste.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "ISO-8859-1", "text": "//teste.c\n\n/* \nPassos:\n\n1) Receber a quantidade de casos de testes;\n2) Receber os casos de testes e armazenar em um vetor (vCasoTeste);\n3) Chamar a função frequencia para cada letra do alfabeto passando um caso de teste como parâmetro e armazenando o resultado em um outro vetor (vPosicao);\n4) Chamar a função maior_frequencia para cada caso de teste passando o vPosicao como parâmetro. Essa função precisa retornar a maior frequência, então você armazena esse número em uma variável (iMaiorFrequencia);\n5) Chamar a função imprime_maior_frequencia para cada caso de teste passando o vPosicao e a varipavel iMaiorFrequencia como parâmetro. Essa função vai receber o vetor de inteiros e vai exibir todas as letras que tem o mesmo número de frequência com o mesmo valor da variável iMaiorFrequencia.\n\n*/\n#include \"frequencia.h\"\n#include <stdio.h>\n//#define T 10\n\nint main(){\n\tint i, j=0, c, f;\n\t\n\t\n\tprintf (\"\\nInforme o numero de casos de teste:\\n\"); //não terá no trabalho final\n\tscanf (\"%d\", &c);\n\tchar v[c][200];\n\tprintf (\"\\nInforme os %d casos de teste: \\n\", c);\n\tfor (i=0; i<c; i++){\n\t\tprintf(\"%d\", i);\n\t\tscanf (\"%s[^\\n]\", &v[i][j]); \n\t}\n\t\n\tprintf(\"frequencia de s e: %d\", frequencia(&v[1][j], 's'));\n\t\n\tprintf (\"\\nOs %d casos de teste informados são:\\n\", c);\n\t for (i=0; i<c; i++){\n\t \tprintf (\"%d %s\\n\", i, &v[i][j]);\n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5673469305038452, "alphanum_fraction": 0.5857142806053162, "avg_line_length": 20.326086044311523, "blob_id": "595172b476a62e54e30e9badf22c8c88f0f40807", "content_id": "4fc5f6bf1b3ecfef8355608aecfea2d4fe432a48", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 983, "license_type": "permissive", "max_line_length": 65, "num_lines": 46, "path": "/estrutura-de-dados/ordem_1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n// baixo acoplamento\n// alta coesao\n\nint busca(int *, int, int); //protótipo\nvoid desloca(int *, int, int); //protótipo\nvoid mostra(int *, int, char *); //protótipo\n\nint main () {\n\tint v[10] = {2, 4, 6, 8, 0, 0, 0, 0, 0, 0};\n\tint novo, pos_novo, ult = 3;\n\tmostra(v, ult, \"Vetor original\");\n\tprintf(\"Digite um novo elemento: \");\n\tscanf(\"%d\", &novo); // joga a referencia na variavel novo\n\tpos_novo = busca(v, ult, novo);\n\tdesloca(v, ult, pos_novo);\n\tv[pos_novo] = novo; // nova posicao pode receber o valor do item\n\tult++; // atualiza a posicao do ultimo item\n\tmostra(v, ult, \"Vetor alterado\");\n\treturn 0;\n}\n\n\nint busca(int *v, int ult, int novo){\n\tint i;\n\tfor (i=0; i<=ult && v[i] < novo;i++);\n\treturn i;\t\n}\n\n\nvoid desloca(int *v, int ult, int pos_novo) {\n\tint i;\n\tfor (i=ult+1;i>pos_novo;i--) {\n\t\tv[i] = v[i-1];\n\t}\n}\n\nvoid mostra(int * v, int ult, char * msg) {\n\tint i;\n\tprintf(\"%s\\n\", msg);\n\tfor (i=0;i<=ult;i++) {\n\t\tprintf(\"%d \", v[i]);\n\t}\n\tprintf(\"\\n\");\n}" }, { "alpha_fraction": 0.36305731534957886, "alphanum_fraction": 0.3885350227355957, "avg_line_length": 20.83333396911621, "blob_id": "d14083cf6c0d2cefd6ad4b52383565d5ad1a861c", "content_id": "61a30c9c5bafe805cfa06b25d277283afde512fd", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 794, "license_type": "permissive", "max_line_length": 47, "num_lines": 36, "path": "/algoritmos-e-logica-da-programacao/maior.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float a,b,c;\n printf (\"\\nDigite 3 valores:\\n\");\n scanf (\"%f%f%f\", &a, &b, &c);\n if (a >= b && a>=c) { //a é o primeiro\n if (b >= c) { // b é o segundo\n printf (\"\\n%.2f, %.2f, %.2f\\n\", a, b, c);\n }\n else { // c é o segundo\n printf (\"\\n%.2f, %.2f, %.2f\\n\", a, c, b);\n }\n }\n else {\n if (b >= c) { // b é o primeiro\n if (a >= c) { // a é o segundo\n\tprintf (\"\\n%.2f, %.2f, %.2f\\n\", b, a, c);\n }\n else { // c é o segundo\n\tprintf (\"\\n%.2f, %.2f, %.2f\\n\", b, c, a);\n }\n }\n else { //c é o primeiro\n if (a >= b) { //a é o segundo\n\tprintf (\"\\n%.2f, %.2f, %.2f\\n\", c, a, b);\n }\n else { //c é o segundo\n\tprintf (\"\\n%.2f, %.2f, %.2f\\n\", c, b, a);\n }\n \n }\n \n }\n return 0;\n}" }, { "alpha_fraction": 0.6069868803024292, "alphanum_fraction": 0.6266375780105591, "avg_line_length": 26.5625, "blob_id": "5fcd7c216fa63539056ebd819848283514157911", "content_id": "109fa7cc5d1907dd09da4dc75e1f8837525cbbec", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 924, "license_type": "permissive", "max_line_length": 104, "num_lines": 32, "path": "/algoritmos-e-logica-da-programacao/strings/ConsoleApplication1/ConsoleApplication1/string_2.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "ISO-8859-1", "text": "/*\r\n1. Ler uma string, invertê-la e mostrá-la \r\n2. Ler uma sentença e contar as vogais \r\n3. Ler uma frase e remover os espaços em branco, mostrá-la adequadamente \r\n4. Ler uma frase e verificar se ela é palíndromo \r\n5. Ler 2 palavras e verificar se a segunda é giro da primeira.\r\n*/\r\n\r\n#include <stdio.h>\r\n#include <string.h>\r\n\r\nint mmmain()\r\n{\r\n\tchar nome[50];\r\n\tchar vogais[5] = {'a', 'e', 'i', 'o', 'u'}; // apenas 50 caracteres\r\n\tint numero_de_vogais = 0, total_array_string = 0, counter = 0;\r\n\r\n\tprintf(\"Entre com a string: \");\r\n\tscanf(\"%[^\\n]%*c\", nome);\r\n\tprintf(\"Agora vamos contar as vogais.\");\r\n\ttotal_array_string = strlen(nome) - 1; // para iterar sobre a string\r\n\r\n\tfor(counter=0; nome[counter]!='\\0'; counter++) { //Repete enquanto nao chegar ao final da string\r\n\t\t\r\n }\r\n\r\n\tprintf(\"\\n\\nO total de vogais eh: %d\\n\\n\", numero_de_vogais);\r\n\r\n\tprintf(\"\\n\\n\");\r\n\tsystem(\"PAUSE\");\r\n\treturn 0;\r\n}\r\n\r\n" }, { "alpha_fraction": 0.5036496520042419, "alphanum_fraction": 0.525547444820404, "avg_line_length": 16.510639190673828, "blob_id": "603b18fb939369a7343ed4d3102aa8e1b62d635b", "content_id": "38b159455d852722a0a342eec632391be4c62c82", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 822, "license_type": "permissive", "max_line_length": 45, "num_lines": 47, "path": "/estrutura-de-dados/exemplo1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include<stdio.h>\n\nint busca(int *, int, int);\nvoid desloca (int *, int, int);\nvoid mostra (int *, int, char *); \n\nint main() {\n int v[10] = {2, 4, 6, 8, 0, 0, 0, 0, 0, 0};\n int novo, pos_novo, ult = 3;\n\n mostra(v, ult, \"Vetor Original\");\n printf(\"\\nDigite um novo elemento: \");\n scanf(\"%d\", &novo);\n\n pos_novo = busca(v, ult, novo);\n \n desloca(v, ult, pos_novo);\n \n v[pos_novo] = novo;\n ult++;\n\n mostra(v, ult, \"Vetor Alterado\");\n \n return 0;\n}\n\nint busca(int *v, int ult, int novo){\n int i;\n for(i=0; i<=ult && v[i]<novo; i++);\n return i; \n}\n\nvoid desloca(int *v, int ult, int pos_novo){\n int i;\n for(i=ult+1; i>pos_novo; i--){\n v[i] = v[i-1];\n }\n}\n\nvoid mostra(int *v, int ult, char *msg){\n int i;\n printf(\"\\n%s\\n\", msg);\n for(i=0; i<=ult; i++){\n printf(\"%d \", v[i]);\n }\n printf(\"\\n\");\n}" }, { "alpha_fraction": 0.7412587404251099, "alphanum_fraction": 0.7412587404251099, "avg_line_length": 22.83333396911621, "blob_id": "129b9e5ffcec91e88106ee567f10debfc91d1c71", "content_id": "563327bd7964c8a018c26e212e015f163a2c7687", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 143, "license_type": "permissive", "max_line_length": 36, "num_lines": 6, "path": "/programacao-micro-computadores/c/trabalho/makefile", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "frequencia.exe: frequencia.o\n\tgcc -o frequencia.exe frequencia.o\nmy_math.o: frequencia.c frequencia.h\n\tgcc -c frequencia.c\t\nclean:\n\trm -rf *.o\t" }, { "alpha_fraction": 0.7250859141349792, "alphanum_fraction": 0.738831639289856, "avg_line_length": 37.766666412353516, "blob_id": "eead2d40cc4273dca64a7e3a901c9ab399599214", "content_id": "8f79663148a33d4118860c226ca6bd7ef068d16c", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1191, "license_type": "permissive", "max_line_length": 64, "num_lines": 30, "path": "/programacao-micro-computadores/c/trabalho/frequencia.h", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "ISO-8859-1", "text": "/* frequencia.h */\n\n#ifndef _FREQUENCIA_H\n#define _FREQUENCIA_H\n\n#define COMPRIMENTO_MAXIMO 200 // comprimento máximo do texto\n#define LETRAS_ALFABETO 26 // número de letras do alfabeto\n\n/* recebe uma string como 1º argumento e um caractere com 2º\n* e devolve a frequência do caractere na string */\nint frequencia(char *, char);\n\n/* recebe um vetor de inteiros como 1º argumento e o tamanho\n* deste vetor como 2º argumento e devolve o maior valor\n* contido no vetor. O vetor representa a frequência de\n* cada letra do alfabeto, sendo assim, o elemento da posição\n* 0 do vetor é a frequência da letra 'a', o da posição 2 a\n* frequência da letra 'b', ..., o da posição 25 a frequência\n* a letra 'z'. */\nint maior_frequecia(int [], int);\n\n/* recebe um vetor de inteiros como 1º argumento, o tamanho\n* deste vetor como 2º argumento e a frequência da(s) letra(s)\n* que ocorre(m) mais frequentemente no texto como 3º argumento.\n* O vetor representa a frequência de cada letra do alfabeto\n* no texto e a função imprime a(s) letra(s) de maior frequência.\n* Se houver empate, imprime as letras em ordem alfabética */\nvoid imprime_mais_frequente(int [], int, int);\n\n#endif\n\n" }, { "alpha_fraction": 0.5114504098892212, "alphanum_fraction": 0.5458015203475952, "avg_line_length": 17.785715103149414, "blob_id": "24341624657eebf10cbf2aff6c57fbee828c855f", "content_id": "659b8dd723304bd5db110d018386325cd1989b86", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 262, "license_type": "permissive", "max_line_length": 51, "num_lines": 14, "path": "/algoritmos-e-logica-da-programacao/maior_numero.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n int n1, n2;\n printf(\"Escolha dois numeros\\n\");\n scanf(\"%d%d\", &n1, &n2);\n if (n1 >= n2) {\n printf(\"\\nO primeiro numero %d e maior\\n\", n1);\n }\n else {\n printf(\"\\nO segundo numero %d e maior\\n\", n2);\n }\n return 0;\n}" }, { "alpha_fraction": 0.4597594738006592, "alphanum_fraction": 0.5380820035934448, "avg_line_length": 25.37552833557129, "blob_id": "1dfb7105e00e7afea5a3115e41142ee78144a40c", "content_id": "fcab25bf3dedfc882caf6da08ed4d390007ef5d7", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6504, "license_type": "permissive", "max_line_length": 111, "num_lines": 237, "path": "/programacao-micro-computadores/c/painel.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "/* painel.c\r\n* Implementação dos protótipos das funções para a montagem do painel\r\n* José Geraldo Oliveira de Andrade Junior RA 1430481323022\r\n* Diego João Sanches RA 1430481323009\r\n* Luciano Leite Gustavo RA 1430481323023\r\n* 30/04/2014\r\n*/\r\n\r\n#include <stdio.h>\r\n#include <string.h>\r\n#include \"painel.h\"\r\n\r\n/**\r\n * Função de entrada do programa (entrypoint)\r\n * @param argc\r\n * @param argv\r\n * @return \r\n */\r\nint main(int argc, char * argv[]) {\r\n\tmonta_painel(argv[1]);\r\n\treturn 0;\r\n}\r\n\r\nvoid plot0(int posicao, int colunas, char matriz[ALTURA][colunas]) {\t\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = { 0, 0, 0, 0, 0,1,2,3,4,5, 1, 2, 3, 4, 5, 6, 6, 6, 6,6};\r\n\tint y[] = {p+1,p+2,p+3,p+4,p+5,p,p,p,p,p,p+6,p+6,p+6,p+6,p+6,p+1,p+2,p+3,p+4,p+5};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '0';\r\n\t}\r\n}\r\nvoid plot1(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0 , 0, 1, 2, 3, 4, 5, 6, 6, 6};\r\n\tint y[] = {p+2, p+3, p+3, p+3, p+3, p+3, p+3, p+3, p+2, p+4};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '1';\r\n\t}\t\r\n\r\n}\r\nvoid plot2(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0,0,0,0, 1,1, 2,3,4,5, 6,6,6,6,6,6,6};\r\n\tint y[] = {p+1,p+2,p+3,p+4,p+5, p,p+6, p+5, p+4, p+3, p+2, p,p+1,p+2,p+3,p+4,p+5,p+6};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '2';\r\n\t}\r\n}\r\nvoid plot3(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0,0,0,0,0, 1,2, 3,3,3, 4,5, 6,6,6,6,6,6};\r\n\tint y[] = {p,p+1,p+2,p+3,p+4,p+5, p+6,p+6, p+3,p+4,p+5, p+6,p+6, p,p+1,p+2,p+3,p+4,p+5,};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '2';\r\n\t}\r\n}\r\nvoid plot4(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0, 1,1, 2,2, 3,3,3,3,3,3,3, 4, 5, 6, };\r\n\tint y[] = {p+0,p+6, p+0,p+6, p+0,p+6, p+0,p+1,p+2,p+3,p+4,p+5,p+6, p+6, p+6, p+6, };\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '4';\r\n\t}\r\n}\r\nvoid plot5(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0,0,0,0,0,0, 1, 2, 3,3,3,3,3,3, 4, 5, 6,6,6,6,6,6};\r\n\tint y[] = {p+0,p+1,p+2,p+3,p+4,p+5,p+6, p+0, p+0, p+0,p+1,p+2,p+3,p+4,p+5, p+6, p+6, p+0,p+1,p+2,p+3,p+4,p+5};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '5';\r\n\t}\r\n}\r\nvoid plot6(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0,0,0,0,0, 1, 2, 3,3,3,3,3,3, 4,4, 5,5, 6,6,6,6,6};\r\n\tint y[] = {p+1,p+2,p+3,p+4,p+5,p+6, p+0, p+0, p+0,p+1,p+2,p+3,p+4,p+5, p+0,p+6, p+0,p+6, p+1,p+2,p+3,p+4,p+5};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '6';\r\n\t}\r\n}\r\nvoid plot7(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0,0,0,0,0,0, 6, 5, 4, 3, 2, 1};\r\n\tint y[] = {p+0,p+1,p+2,p+3,p+4,p+5,p+6, p+1, p+2, p+3, p+4, p+5, p+6};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '7';\r\n\t}\r\n}\r\nvoid plot8(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0,0,0,0, 1,1, 2,2, 3,3,3,3,3, 4,4, 5,5, 6,6,6,6,6};\r\n\tint y[] = {p+1,p+2,p+3,p+4,p+5, p+0,p+6, p+0,p+6, p+1,p+2,p+3,p+4,p+5, p+0,p+6, p+0,p+6, p+1,p+2,p+3,p+4,p+5};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '8';\r\n\t}\r\n}\r\nvoid plot9(int posicao, int colunas, char matriz[ALTURA][colunas]) {\r\n\tint cx=0;\r\n\tint cy=0;\r\n\tint p = posicao;\r\n\tint x[] = {0,0,0,0,0, 1,1, 2,2, 3,3,3,3,3,3, 4, 5, 6,6,6,6,6,6};\r\n\tint y[] = {p+1,p+2,p+3,p+4,p+5, p+0,p+6, p+0,p+6, p+1,p+2,p+3,p+4,p+5,p+6, p+6, p+6, p+0,p+1,p+2,p+3,p+4,p+5};\r\n\tint points = sizeof(x)/sizeof(int);\r\n\t\r\n\tfor (cx=0;cx<points;++cx) {\r\n\t\tmatriz[x[cx]][y[cx]] = '9';\r\n\t}\r\n}\r\n\r\n/**\r\n * Essa função servirá para escrever o painel na tela.\r\n * @param colunas\r\n * @param matriz\r\n * @return void\r\n */\r\nvoid imprime_painel(int colunas, char matriz[ALTURA][colunas]) {\r\n\tint linha = 0;\r\n\tint coluna = 0;\r\n\t\r\n\tfor (linha = 0; linha < ALTURA; ++linha) {\r\n\t\tfor (coluna=0; coluna<colunas; ++coluna) {\r\n\t\t\tprintf(\"%c\", matriz[linha][coluna]);\r\n\t\t}\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n}\r\n\r\n/**\r\n * Essa função recebe a cadeia de caracteres e processa-os chamando a função \r\n * correta para plotar na matriz.\r\n * \r\n * @param caractere\r\n * @return void\r\n */\r\nvoid monta_painel(char * caractere) {\r\n\t// vamos definir o máximo de colunas que a string vai gerar\r\n\tint max_columns = strlen(caractere) * (COMP_NUM + 1); \r\n\tchar matriz[ALTURA][max_columns]; \r\n\tint i = 0;\r\n\r\n\t// Vamos limpar o painel colocando espaços dentro da matriz\r\n\tlimpa_painel(max_columns, matriz);\r\n\t\r\n\tfor (i = 0; i < strlen(caractere); ++i)\r\n\t{\r\n\t\tif (caractere[i] == '0'){\r\n\t\t\tplot0(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '1'){\r\n\t\t\tplot1(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '2'){\r\n\t\t\tplot2(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '3'){\r\n\t\t\tplot3(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '4'){\r\n\t\t\tplot4(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '5'){\r\n\t\t\tplot5(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '6'){\r\n\t\t\tplot6(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '7'){\r\n\t\t\tplot7(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '8'){\r\n\t\t\tplot8(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\tif (caractere[i] == '9'){\r\n\t\t\tplot9(i * (COMP_NUM + 1), max_columns, matriz);\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t}\t\r\n\t\r\n\t// Agora vamos colocar tudo na tela\r\n\timprime_painel(max_columns, matriz);\r\n\r\n}\r\n\r\n/**\r\n * Essa função serve para limpar a matriz com os dados plotados.\r\n * \r\n * @param colunas\r\n * @param matriz\r\n */\r\nvoid limpa_painel(int colunas, char matriz [ALTURA][colunas]) {\r\n\tint linha = 0;\r\n\tint coluna = 0;\r\n\tchar espaco = ' ';\r\n\t\r\n\tfor (linha=0;linha<ALTURA;++linha){\r\n\t\tfor(coluna=0;coluna<colunas-1;++coluna) {\r\n\t\t\tmatriz[linha][coluna] = espaco;\r\n\t\t}\r\n\t}\r\n}" }, { "alpha_fraction": 0.5661691427230835, "alphanum_fraction": 0.6258706450462341, "avg_line_length": 20.404254913330078, "blob_id": "2dbc4a4377218de10bbe9fa6fb109bfd4235dadf", "content_id": "962f82d1bfe6ed433b85dca6af45efb68ee76aaa", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1007, "license_type": "permissive", "max_line_length": 67, "num_lines": 47, "path": "/estrutura-de-dados/structs.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct conta\n{\n\tint num;\n\tfloat saldo;\n};\n\nvoid mostra_conta(struct conta c, char * msg){\n\tprintf(\"%s\\n\", msg);\n\tprintf(\"Conta %d, saldo %.2f\\n\", c.num, c.saldo);\n}\n\nvoid deposito(struct conta * c, float deposito) {\n\tc->saldo = c->saldo + deposito;\n}\n\nint main() {\n\tstruct conta c1, c2;\n\tstruct conta *c3;\n\n\tc1.num = 10;\n\tc1.saldo = 100.0;\n\tc2 = c1;\n\tc2.saldo = 200.0;\n\n\t// printf(\"Conta %d, saldo %.2f\\n\", c1.num, c1.saldo);\n\t// printf(\"Conta %d, saldo %.2f\\n\", c2.num, c2.saldo);\n\n\tc3 = (struct conta *) malloc (sizeof (struct conta));\n\tc3->num = 11;\n\tc3->saldo = -50;\n\t// printf(\"Conta %d, saldo %.2f\\n\", c3->num, c3->saldo);\n\tmostra_conta(c1, \"C1\");\n\tmostra_conta(c2, \"C2\");\n\t// se usar o * conta, ele não é um struct conta, tipos diferentes\n\tmostra_conta(c1, \"C1\"); //precisa usar esse operador derreferencia\n\n\tdeposito(&c1, 1000.00);\n\tmostra_conta(c1, \"C1 Saldo atualizado\");\n\t\n\t\n\tdeposito(c3, 1000.00);\n\tmostra_conta(*c3, \"C3 Saldo atualizado\");\n\treturn 0;\n}" }, { "alpha_fraction": 0.5194274187088013, "alphanum_fraction": 0.5419222712516785, "avg_line_length": 15.896552085876465, "blob_id": "f7a56d921124b57bc465ab75dd02adc9203b62a4", "content_id": "9088c6e2c6465b7dea48d64c492d9912ddf9a715", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 491, "license_type": "permissive", "max_line_length": 102, "num_lines": 29, "path": "/algoritmos-e-logica-da-programacao/lacos/2.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "/* \n Ler inteiro n e float x, calcular x elevado a n (n nao pode ser < 0). Fazer com for, while e do-while\n*/\n\n int main()\n {\n int n = 0;\n float x = 0.00;\n float resultado = 0.00;\n\n printf(\"Vamos calcular a potencia de x elevado a n.\\n\");\n printf(\"Digite x:\\n\");\n scanf(\"%f\", &x);\n printf(\"Digite n:\\n\");\n scanf(\"%f\", &n);\n\n // vamos fazer algumas validações\n if (n==0) { // por definicao se \n printf(\"%s\\n\", );\n } else {\n\n }\n\n for (i=0;i++;i<=n) {\n \n }\n\n return 0;\n }" }, { "alpha_fraction": 0.5010183453559875, "alphanum_fraction": 0.5478615164756775, "avg_line_length": 17.22222137451172, "blob_id": "4289f5185d6a3290c8c5e0f52a9e7f5f2cdf6a69", "content_id": "96077c6e0ea37861a77f73c57ed750ea38635993", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 491, "license_type": "permissive", "max_line_length": 82, "num_lines": 27, "path": "/algoritmos-e-logica-da-programacao/exercicio2.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float v1, v2, vt, premio, p1, p2, pv1, pv2;\n \n printf(\"\\nQual o valor do premio?\\n\");\n scanf(\"%f\", &premio);\n \n printf(\"\\nQual o valor do primeiro jogador?\\n\");\n scanf(\"%f\", &v1);\n \n printf(\"\\nQual o valor do segundo jogador?\\n\");\n scanf(\"%f\", &v2);\n \n vt = v1 + v2;\n \n p1 = v1/vt;\n \n p2 = v2/vt;\n \n pv1 = premio*p1;\n pv2 = premio*p2;\n \n printf(\"\\nO premio e: %.2f para o primeiro e: %.2f para o segundo\\n\", pv1, pv2);\n \n return 0;\n}" }, { "alpha_fraction": 0.5649763941764832, "alphanum_fraction": 0.5748306512832642, "avg_line_length": 27, "blob_id": "ac65f02bbd861f0e501bfbe22b3d38b24e89dd48", "content_id": "29384cae20976de1843980baad0fdd905a584816", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4871, "license_type": "permissive", "max_line_length": 129, "num_lines": 174, "path": "/estrutura-de-dados/trabalho 1/trabalho.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include \"trabalho.h\"\n\nint main() { \n int *vetor_aleatorio;\n int *vetor_asc;\n int *vetor_desc;\n\n vetor_aleatorio = ( int * ) malloc ( T * sizeof(int));\n vetor_asc = ( int * ) malloc ( T * sizeof(int));\n vetor_desc = ( int * ) malloc ( T * sizeof(int));\n \n \n float contador_comparacao = 0;\n float contador_atribuicao = 0;\n\n int i;\n \n // for(i=0; i<10; i++){\n // printf(\"\\nGerando os vetores, %d loop Bubble...\\n\", i+1);\n \n // gera(vetor_aleatorio, T);\n // gera_vetor_crescente(vetor_asc, T);\n // gera_vetor_decrescente(vetor_desc, T);\n // bubble(vetor_aleatorio, T, &contador_comparacao, &contador_atribuicao);\n // printf(\"\\nVetor aleatorio: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n\n // contador_comparacao = 0;\n // contador_atribuicao = 0;\n\n // bubble(vetor_asc, T, &contador_comparacao, &contador_atribuicao);\n // printf(\"Vetor crescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n\n // contador_comparacao = 0;\n // contador_atribuicao = 0;\n\n // bubble(vetor_desc, T, &contador_comparacao, &contador_atribuicao);\n // printf(\"Vetor decrescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n // }\n \n // for(i=0; i<10; i++){\n // printf(\"\\nGerando os vetores, %d loop Inserction...\\n\", i+1);\n \n // gera(vetor_aleatorio, T);\n // gera_vetor_crescente(vetor_asc, T);\n // gera_vetor_decrescente(vetor_desc, T);\n // insertionSort(vetor_aleatorio, T, &contador_comparacao, &contador_atribuicao);\n // printf(\"\\nVetor aleatorio: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n\n // contador_comparacao = 0;\n // contador_atribuicao = 0;\n\n // insertionSort(vetor_asc, T, &contador_comparacao, &contador_atribuicao);\n // printf(\"Vetor crescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n\n // contador_comparacao = 0;\n // contador_atribuicao = 0;\n\n // insertionSort(vetor_desc, T, &contador_comparacao, &contador_atribuicao);\n // printf(\"Vetor decrescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n // }\n \n for(i=0; i<10; i++) {\n printf(\"\\nGerando os vetores, %d loop Selection...\\n\", i+1);\n \n gera(vetor_aleatorio, T);\n gera_vetor_crescente(vetor_asc, T);\n gera_vetor_decrescente(vetor_desc, T);\n selection(vetor_aleatorio, T, &contador_comparacao, &contador_atribuicao);\n printf(\"\\nVetor aleatorio: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n\n contador_comparacao = 0;\n contador_atribuicao = 0;\n\n selection(vetor_asc, T, &contador_comparacao, &contador_atribuicao);\n printf(\"Vetor crescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n\n contador_comparacao = 0;\n contador_atribuicao = 0;\n\n selection(vetor_desc, T, &contador_comparacao, &contador_atribuicao);\n printf(\"Vetor decrescente: Contador comparacao %.f Contador atribuicao %.f \\n\", contador_comparacao, contador_atribuicao);\n }\n return 0;\n}\n\nvoid gera_vetor_decrescente(int * vetor, int n) {\n int i;\n for(i=0;i<n;i++) {\n vetor[i] = n-i;\n }\n}\n\nvoid gera_vetor_crescente(int * vetor, int n) {\n int i=0;\n for(i=0;i<n;i++) {\n vetor[i] = i;\n }\n}\n\nvoid gera (int *v, int n){\n int i=0;\n int numero;\n \n for(i=0; i<=n;i++){\n v[i] = rand() % n;\n }\n}\n\nvoid bubble (int * v, int n, float * cc, float * ca) {\n int i, j;\n for ( i = 1; i < n; i++ , (*cc)++) {\n for ( j = 0; j < n - i; j++, (*cc)++) {\n (*cc)++;\n if (v[j] > v[j+1]) {\n troca (v, j);\n (*ca) = (*ca) + 3;\n }\n }\n }\n}\n\nvoid troca (int *v, int pos) {\n int aux = v[pos];\n v[pos] = v[pos+1];\n v[pos+1] = aux;\n}\n\nvoid trocaAnterior (int *v, int pos){\n int aux = v[pos];\n v[pos] = v[pos - 1];\n v[pos - 1] = aux;\n}\n\nvoid trocaMinimo (int *v, int min, int pos){\n int aux = v[pos];\n v[pos] = v[min];\n v[min] = aux;\n}\n\nvoid insertionSort (int * v, int n, float * cc, float * ca){\n int i, j, key;\n for ( i = 1; i < n; i++, (*cc)++, (*ca)++) {\n key = v[i];\n while ( i > 0 && v[i -1] > key ) {\n (*cc)++;\n trocaAnterior (v, i);\n --i;\n (*ca) = (*ca) + 4; \n }\n }\n}\n\nvoid selection (int *v, int n, float * cc, float * ca){ \n int i, j, x, min, k;\n for ( i = 0; i < (n-1); i++ ) {\n (*cc)++;\n min = i;\n (*ca)++;\n for ( j = i + 1; j < n; j++ ){\n (*cc)++;\n if (v[min] > v[j]){\n min = j;\n (*ca)++;\n }\n (*cc)++;\n if( min != i){\n trocaMinimo (v, min, i);\n (*ca) = (*ca) + 3;\n }\n }\n (*cc)++; //do for\n }\n (*cc)++;\n}" }, { "alpha_fraction": 0.5262854099273682, "alphanum_fraction": 0.5459272265434265, "avg_line_length": 15.027777671813965, "blob_id": "3af0686a2e7d7c32bb5f8d611b793bba9ea65541", "content_id": "bf439044036b57defa3182f3e374f55f524d0698", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1743, "license_type": "permissive", "max_line_length": 91, "num_lines": 108, "path": "/estrutura-de-dados/sort_1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "/*\n\tGeração de números aleatórios\n\tem C:\n\t\trand(): gera números entre 0 e RAND_MAX (no stdlib.h)\n\t\tsrand(semente): initica o gerador. a semente deve ser sempre diferente (usaremos o time).\n\t\ttime(0): tempo da bios em segundos\n\n\t\tstdlib.h\n\t\ttime.h\n\n\tRevisar comportamento de variáveis dinâmicas e estáticas na memória;\n\n\t===========\n\tBUBBLE SORT\n\t===========\n\n\tMatematica das iterações do bubble sort (1 + n). n/2 == (n+(n.n)) / 2\n\n\tPos comp: compiladores e análises de algoritmos\n\n\n\tEstudo de pos incrementos ou decrementos:\n\n\tint = 10;\n\n\tprintf(\"%d\", n++); // TELA: 10; RAM: 11\n\tprintf(\"%d\", ++n); // TELA: 11; RAM: 11\n\tprintf(\"%d\", n+1); // TELA: 10; RAM: 11\n\n\n*********/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define T 10\n\nvoid gera(int *, int);\nvoid mostra(int *, int, char *);\nvoid bubble(int *, int);\nvoid troca(int *, int);\n\nint main() {\n\n\tint v[T];\n\tsrand(time(0));\n\tgera(v, T);\n\tmostra(v, T, \"Vetor original\");\n\tbubble(v, T);\n\tmostra(v, T, \"Vetor Ordenado\");\n\treturn 0;\n}\n\nvoid gera(int * v, n) {\n\tint i;\n\tfor (i=0;i<n;i++) {\n\t\tv[i] = rand();\n\t}\n}\n\nvoid mostra(int * v, int n, char * msg) {\n\tint i;\n\n\tprintf(\"%s\\n\", msg);\n\n\tfor (i=0;i<n;i++) {\n\t\tprintf(\"%d \", v[i]);\n\t}\n\n\tprintf(\"\\n\");\n}\n\nvoid bubble(int * v, int n) {\n\tint i, j;\n\tfor (i=1;i<n;i++) {\n\t\tfor (j=0;j < n-i; j ++) {\n\t\t\tif (v[j] > v[j + 1]) {\n\t\t\t\ttroca(v, j);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// implementa a troca dentro o vetor v\nvoid troca(int * v, int pos) {\n\tint aux = v[pos];\n\n\tv[pos] = v[pos + 1];\n\tv[pos + 1] = aux;\n\n}\n\n\n\n\n// int main () {\n// \t//time_t tempo = time(0);\n\n// \t//printf(\"%s\\n\", );\n// \tsrand(time(0));\n// \tint n = rand();\n// \tint m = rand();\n// \tprintf(\"O valor de n %d\\n\", n);\n// \tprintf(\"O valor de m %d\\n\", m);\n\n// \treturn 0;\n// }\n" }, { "alpha_fraction": 0.6354166865348816, "alphanum_fraction": 0.6655092835426331, "avg_line_length": 38.318180084228516, "blob_id": "e1d5e4318bd9855b46ba7c5a4f14c715a457f55b", "content_id": "003cb965308dd68add4021ddd38674b9f011c200", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 864, "license_type": "permissive", "max_line_length": 155, "num_lines": 22, "path": "/algoritmos-e-logica-da-programacao/calculo_salario.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float valor_hora, salario_bruto, salario_liq, imposto;\n int numero_horas;\n printf(\"Qual o valor de sua hora de trabalho?\\n\");\n scanf(\"%f\", &valor_hora);\n printf(\"Quantas hrs voce ja trabalhou?\\n\");\n scanf(\"%d\", &numero_horas);\n salario_bruto = valor_hora * numero_horas;\n if (salario_bruto > 0 && salario_bruto < 2000) {\n imposto = salario_bruto*10/100;\n salario_liq = salario_bruto + imposto;\n printf(\"\\nSeu salario bruto e %.2f,\\nvc pagara 10%% de desconto que dara %.2f\\ne dara liquido neste mes e %.2f\\n\",salario_bruto, imposto, salario_liq);\n }\n else {\n imposto = salario_bruto*15/100;\n salario_liq = salario_bruto + imposto;\n printf(\"\\nSeu salario bruto e %.2f,\\nvc pagara 15%% de desconto que dara %.2f\\ne dara liquido neste mes e %.2f\\n\",salario_bruto, imposto, salario_liq);\n }\n return 0;\n}" }, { "alpha_fraction": 0.7004310488700867, "alphanum_fraction": 0.704741358757019, "avg_line_length": 64.28571319580078, "blob_id": "be4e188a009b059cb44dc267303d46c0526590e4", "content_id": "cec05113def2f42c8e561767c5873cdc8bcabe5e", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1392, "license_type": "permissive", "max_line_length": 118, "num_lines": 21, "path": "/estrutura-de-dados/trabalho 1/trabalho1.h", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "# include <stdio.h>\r\n# include <stdlib.h>\r\n# include <time.h>\r\n\r\n# define T 100000\t\t// CONSTANTE DEFINIDA PARA A QUANTIDADE DE ITENS GERADOS NO VETOR\r\n\r\nvoid gera (int *, int);\t\t// FUNCAO CRIADA PARA GERAR O VETOR\r\nvoid mostra (int *, int, char *);\t// FUNCAO CRIADA PARA MOSTRAR O VETOR GERADO\r\nvoid mostraInvertido (int *, int, char *);\t// FUNCAO CRIADA PARA MOSTRAR O VETOR GERADO \"ORDENADO AO CONTRARIO\"\r\nvoid bubble (int *, int, float *, float *);\t// FUNCAO CRIADA PARA ORDENAR O VETOR UTILIZANDO O ALGORITMO \"BUBBLE SORT\"\r\nvoid bubbleSort (int *, int);\t// FUNCAO CRIADA PARA ORDENAR O VETOR UTILIZANDO O ALGORITMO \"BUBBLE SORT\"\r\nvoid insertionSort (int *, int);\t// FUNCAO CRIADA PARA ORDENAR O VETOR UTILIZANDO O ALGORITMO \"INSERTION SORT\"\r\nvoid selectionSort (int *, int);\t// FUNCAO CRIADA PARA ORDENAR O VETOR UTILIZANDO O ALGORITMO \"SELECTION SORT\"\r\nvoid troca (int *, int);\t// FUNCAO CRIADA PARA TROCAR A POSICAO E ORDENAR O VETOR \"...\"\r\nvoid trocaProximo (int *, int);\t// FUNCAO CRIADA PARA TROCAR A POSICAO E ORDENAR O VETOR \"...\"\r\nvoid trocaAnterior (int *, int);\t// FUNCAO CRIADA PARA TROCAR A POSICAO E ORDENAR O VETOR \"...\"\r\nvoid trocaMinimo (int *, int);\t// FUNCAO CRIADA PARA TROCAR A POSICAO E ORDENAR O VETOR \"...\"\r\nint buscaBinaria (int *, int, int);\r\nint tem_repeticao(int *, int , int);\r\nvoid gera_vetor_crescente(int *, int);\r\nvoid gera_vetor_decrescente(int *, int);\r\n" }, { "alpha_fraction": 0.5264368057250977, "alphanum_fraction": 0.5701149702072144, "avg_line_length": 17.16666603088379, "blob_id": "ba386b68e0f84b77eb3d22152ae90266017fc94b", "content_id": "8a964bbe06a42f6ac2ce20c3352558e937772f86", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 435, "license_type": "permissive", "max_line_length": 67, "num_lines": 24, "path": "/estrutura-de-dados/ordenamento_vetor.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n// baixo acoplamento\n// alta coesao\n\nint main() {\n\tint i, j = 0;\n\tint novo = 5;\n\tint lista[10] = {2,4,6,8,10};\n\tint posicao_ultimo_item = 10;\n\n\tfor (i=0;i<=posicao_ultimo_item && lista[i] < novo;i++) { // busca\n\t\tfor (j=posicao_ultimo_item+1;j>i;j--) { // deslocamento\n\t\t\tlista[j] = lista[j-1];\n\t\t}\n\n\t}\n\n\tprintf(\"Agora vamos imprimir o vetor: \\n\");\n\tfor (i=0;i<=10;i++) {\n\t\tprintf(\"%d\\n\", lista[i]);\n\t}\n\treturn 0;\n}" }, { "alpha_fraction": 0.6294227242469788, "alphanum_fraction": 0.6536312699317932, "avg_line_length": 20.078432083129883, "blob_id": "2a23a4751abf225ac1a019b0fcebfe10e779ecb4", "content_id": "d5ee343facc7f9bf8b174dc3ce9fca3c11b2c428", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1076, "license_type": "permissive", "max_line_length": 146, "num_lines": 51, "path": "/estrutura-de-dados/structs2.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\n/*\n 1 - Construir uma funcao que recebe ums struct simples e dobra sua info por parametro\n 2 - Construir uma funcao que recebe uma struct simples e devolve outra struct (por return) cuja info é o sucessor da infor da entrada\n 3 - Construir uma funcao que recebe duas structs simples e devolve o ponteiro para uma struct (por return) cuja info é a soma da infos de entrada\n*/\n\nstruct simples {\n int info;\n struct simples * vizinho;\n};\n\nvoid mostra_conta (struct simples c, char *msg) {\n printf(\"\\n%s\\n\", msg);\n printf(\"struct: info %d\\n\", c.info);\n}\n\nvoid dobra_info(struct simples * s) {\n s->info *= 2;\n}\n\nstruct simples sucessor(struct simples s) {\n s.info++;\n return s;\n}\n\nint main() {\n struct simples s1, s2;\n s1.info = 2;\n s1.vizinho = NULL;\n\n // # 1\n mostra_conta(s1, \"S1 inicializada\");\n dobra_info(&s1);\n mostra_conta(s1, \"S1 Alterada\");\n // # 1 FIM\n\n // # 2 \n mostra_conta(s1, \"S1 antes de suceder\");\n s2 = sucessor(s1);\n mostra_conta(s2, \"S1 depois de suceder\");\n // # 2 FIM \n\n // # 3\n\n \n\n return 0;\n}" }, { "alpha_fraction": 0.640625, "alphanum_fraction": 0.640625, "avg_line_length": 15, "blob_id": "c2fa10533053c75e92881a5182b7de657a46ea57", "content_id": "a7036975adcabedb2a89e11a46d9be4c30164969", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 64, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/README.md", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "fatec-coding\n============\n\nAll coding learned in FATEC college.\n" }, { "alpha_fraction": 0.5018450021743774, "alphanum_fraction": 0.5023539662361145, "avg_line_length": 29.929134368896484, "blob_id": "3720868c38aa61287e896f40ca6296718f13e83a", "content_id": "5c8fec1152bd990b9b40979fe81c75b2cadd8c0b", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7890, "license_type": "permissive", "max_line_length": 119, "num_lines": 254, "path": "/programacao-micro-computadores/python/agenda.py", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding:utf-8 -*-\nimport os, json\n\n#especificaçao do deluqui agenda\n# uma agenda:\n# i - para incluir\n# a - alterar\n# e - excluir\n# l - limpar\n# m - mostrar\n# o - ordernar (asc ou desc)\n# s - salvar (em arquivo)\n# f - fim\n\n# Informar Nome, Data Nascimento, Telefone\n\nNOME_DO_ARQUIVO = 'agenda.bla'\nLIMITE_REGISTROS = 4\nagenda = {}\n\n\ndef check_commands():\n while True:\n print '############################################################################'\n print '########################## AGENDA VIRTUAL ##################################'\n print '######################## %s registros de %s ################################' % (\n pega_total_registros_usados(),\n LIMITE_REGISTROS)\n print 'Escolha uma das opções a seguir:'\n print '[i] para incluir'\n print '[a] para alterar'\n print '[p] para pesquisar'\n print '[e] para excluir'\n print '[l] para limpar'\n print '[m] para mostrar'\n print '[o] para ordenar'\n print '[s] para salvar'\n print '[f] para fim'\n\n tecla = raw_input('Digite uma opção: ')\n\n if tecla == 'i':\n inclui_registro()\n elif tecla == 'a':\n alterar_registro()\n elif tecla == 'e':\n remover_registro()\n elif tecla == 'l':\n limpar_registros()\n elif tecla == 'm':\n mostrar_agenda()\n elif tecla == 'o':\n ordenar_registros()\n elif tecla == 'p':\n mostrar_registro()\n elif tecla == 's':\n salvar_arquivo()\n elif tecla == 'f':\n print '########################## ATE LOGO #################################'\n exit()\n else:\n print '################ Opção inválida. Tente novamente ####################'\n\n\ndef mostrar_registro():\n sure = raw_input('Digite o id do registro: ')\n\n try:\n sure = int(sure)\n except Exception:\n print 'Isso (%s) não parece um inteiro válido' % sure\n return None\n\n if 'registros' in agenda:\n print '########################## AGENDA ######################'\n for item in agenda['registros']:\n if item['id'] == sure:\n print 'ID: %(id)s - %(nome)s - %(data_nascimento)s - %(telefone)s' % item\n else:\n print '########################## NAO EXISTEM REGISTROS ###########################'\n\n\ndef limpar_registros():\n sure = raw_input('Tem certeza? Confirmando essa opção isso apagará sua agenda completamente. [y, n]')\n if sure == 'y':\n agenda['registros'] = []\n salvar_arquivo()\n else:\n print 'Nada foi alterado.'\n\n\ndef ordenar_registros():\n\n ordem = raw_input('Qual alfabética crescente ou reversa?. [c, r]')\n\n if existe_registros():\n print '################## REGISTROS ORDENADOS #################'\n ordenar_isso = [''.join([str(registro['nome']), '-', str(registro['id'])]) for registro in agenda['registros']]\n ordenar_isso.sort()\n if ordem == 'r':\n ordenar_isso.reverse()\n\n for nome in ordenar_isso:\n id = int(nome.split('-')[1])\n item = get_item_na_agenda(id)\n print 'ID: %(id)s - %(nome)s - %(data_nascimento)s - %(telefone)s' % item\n\n\ndef get_item_na_agenda(id):\n for registro in agenda['registros']:\n if registro['id'] == id:\n return registro\n\ndef remover_registro():\n id = raw_input('Digite o id do registro: ')\n\n sure = raw_input('Tem certeza? Confirmando essa opção isso apagará esse registro da sua agenda. [y, n]')\n\n if sure != 'y':\n return None\n\n try:\n id = int(id)\n except Exception:\n print 'Isso (%s) não parece um inteiro válido' % id\n return None\n\n if 'registros' in agenda:\n\n for item in agenda['registros']:\n if item['id'] == id:\n agenda['registros'].pop(agenda['registros'].index(item))\n print 'ID: %(id)s - %(nome)s - %(data_nascimento)s - %(telefone)s' % item\n print '############## REGISTRO REMOVIDO COM SUCESSO ###################'\n else:\n print '########################## NAO EXISTEM REGISTROS ###########################'\n\n\ndef alterar_registro():\n id = raw_input('Digite o id do registro: ')\n\n try:\n id = int(id)\n except Exception:\n print 'Isso (%s) não parece um inteiro válido' % id\n return None\n\n if existe_registros():\n print '################## ALTERACAO REGISTROS #################'\n for item in agenda['registros']:\n if item['id'] == id:\n print 'ID: %(id)s - %(nome)s - %(data_nascimento)s - %(telefone)s' % item\n\n nome = raw_input('Digite o nome: ')\n data_nascimento = raw_input('Digite a data de nascimento: ')\n telefone = raw_input('Digite o telefone: ')\n\n agenda['registros'][id] = {'id': id, 'nome': nome, 'data_nascimento': data_nascimento,\n 'telefone': telefone}\n salvar_arquivo()\n\n print '############# REGISTRO ALTERADO COM SUCESSO ############'\n else:\n print '########################## NAO EXISTEM REGISTROS ###########################'\n\n\ndef mostrar_agenda():\n if existe_registros():\n print '########################## AGENDA ######################'\n for item in agenda['registros']:\n print 'ID: %(id)s - %(nome)s - %(data_nascimento)s - %(telefone)s' % item\n else:\n print '########################## NAO EXISTEM REGISTROS ###########################'\n\n\ndef inclui_registro():\n if len(agenda['registros']) >= LIMITE_REGISTROS: # not zero based\n print 'Essa agenda está cheia'\n return None\n\n print '########################## NOVO REGISTRO ##################################'\n nome = raw_input('Digite o nome: ')\n data_nascimento = raw_input('Digite a data de nascimento: ')\n telefone = raw_input('Digite o telefone: ')\n\n agenda['registros'].append({'id': len(agenda['registros']), 'nome': nome,\n 'data_nascimento': data_nascimento, 'telefone': telefone})\n salvar_arquivo()\n\n\ndef pega_total_registros_usados():\n if 'registros' in agenda:\n return len(agenda['registros'])\n else:\n return 0\n\n\ndef salvar_arquivo():\n try:\n arquivo = open(os.path.join(os.path.dirname(__file__), NOME_DO_ARQUIVO), 'w')\n arquivo.write(json.dumps(agenda))\n print 'Salvo com sucesso!'\n except Exception, e:\n raise Exception('Erro ao tentar salvar o arquivo. ')\n\n\ndef abre_arquivo():\n try:\n return open(os.path.join(os.path.dirname(__file__), NOME_DO_ARQUIVO), 'r').read()\n except Exception, e:\n raise Exception('Arquivo não existe ou sem permissão de manipulação.')\n\n\ndef abre_linha_a_linha():\n try:\n arquivo = open(os.path.join(os.path.dirname(__file__), NOME_DO_ARQUIVO), 'w')\n for linha in arquivo.readline():\n yield linha\n except Exception, e:\n raise Exception('Arquivo não existe ou sem permissão de manipulação.')\n\n\ndef carrega_dados(arquivo):\n \"\"\" Aqui vamos carregar a base de dados em memória \"\"\"\n\n if not arquivo:\n dados = json.loads('{}')\n else:\n dados = json.loads(arquivo)\n\n if 'registros' not in dados:\n dados['registros'] = []\n\n return dados\n\n\ndef carrega_linha_a_linha(linha):\n try:\n return eval(linha) # retorna um dict de um registro apenas\n except Exception, e:\n pass\n\ndef existe_registros():\n if 'registros' in agenda and len(agenda['registros']):\n return True\n else:\n return False\n\n# vamos carregar os dados\narquivo = abre_arquivo()\nagenda = carrega_dados(arquivo)\n\ncheck_commands()\n\n\n\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 26, "blob_id": "1a5653ad4b076e57b2ebdeb3197ff319ca32caf1", "content_id": "7b213473533c1c6b8ad837555d5dceb008617348", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 54, "license_type": "permissive", "max_line_length": 43, "num_lines": 2, "path": "/setup.sh", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#!/bin/sh\nsudo yum install g++ gcc build-essential -y\n" }, { "alpha_fraction": 0.5223463773727417, "alphanum_fraction": 0.5530726313591003, "avg_line_length": 21.4375, "blob_id": "b233d1e0a094b8982f65dc0e3c9f8c9ae3b024eb", "content_id": "1eed77b95e8e909a3556ea8ab55195d9cdddd449", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 358, "license_type": "permissive", "max_line_length": 74, "num_lines": 16, "path": "/algoritmos-e-logica-da-programacao/divisao1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n int n1, n2;\n float total;\n printf(\"Escolha dois numeros para serem divididos\\n\");\n scanf(\"%d%d\", &n1, &n2);\n if ( n2 != 0 ) {\n total = (float)n1/n2;\n printf(\"\\nO resultado e: %.2f\\n\\n\", total);\n }\n else {\n printf(\"\\nImpossivel dividir pois %d zero nao e um divisor\\n\\n\", n2);\n } \n return 0;\n}" }, { "alpha_fraction": 0.6920635104179382, "alphanum_fraction": 0.7079365253448486, "avg_line_length": 25.33333396911621, "blob_id": "1850b24474760fcfba1336ce0f9427cb6938455d", "content_id": "8c67d01dc5e7b36df5904d8c8f28cbbdef0a4ef4", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 323, "license_type": "permissive", "max_line_length": 73, "num_lines": 12, "path": "/algoritmos-e-logica-da-programacao/exercicios_acsii.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "/*\n\nLista com strings\n-----------------\n\n1. Ler uma string, invertê-la e mostrá-la\n2. Ler uma sentença e contar as vogais\n3. Ler uma frase e remover os espaços em branco, mostrá-la adequadamente;\n4. Ler uma frase e verificar se ela é palíndromo.\n5. Ler duas palavras e verificar se a segunda é giro da primeira;\n\n*/" }, { "alpha_fraction": 0.5745856165885925, "alphanum_fraction": 0.6132596731185913, "avg_line_length": 21.66666603088379, "blob_id": "ff2d4274b96ed267703f8c38f06ff1490b265f3d", "content_id": "b39c7294cb229e8f69647e3758dc4e87d90eec52", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 546, "license_type": "permissive", "max_line_length": 94, "num_lines": 24, "path": "/algoritmos-e-logica-da-programacao/palavras.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n\n#define N 40\n\nint main(){\n\n\tchar s1[N+1], s2[N+1];\n // observação importante \" difere de ', neste caso só funciona com aspas duplas.\n\tchar s3[] = \"Teste...\"; //uma vez inicializado dessa forma o tamanho da string nao se altera.\n\n\tprintf(\"Tamanho de S3: %d\\n\", strlen(s3));\n\tprintf(\"Digite uma frase:\\n\");\n scanf(\"%40[^\\n]\", s1);\n strcpy(s2, \"dia de sol\");\n\n printf(\"\\ns2: %s\\n\\n\", s2);\n // vamos concatenar as strings\n strcat(s1, \" \");\n strcat(s1, s2);\n printf(\"\\ns1: %s\\n\\n\", s1);\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.5244755148887634, "alphanum_fraction": 0.5692307949066162, "avg_line_length": 33.095237731933594, "blob_id": "0d3f219ee40b36548259966740dc94be24961a25", "content_id": "74448a38422d202982597cabd4c1141ef3b1fb59", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 717, "license_type": "permissive", "max_line_length": 69, "num_lines": 21, "path": "/algoritmos-e-logica-da-programacao/exercicio4.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n int numero1 = 0, numero2 = 0, numero3 = 0, numero4 = 0;\n printf(\"\\nDigite quatro numeros:\\n\");\n scanf(\"%d%d%d%d\", &numero1, &numero2, &numero3, &numero4);\n if (numero1 >= numero2 && numero1>=numero4 && numero1 >= numero3) {\n printf(\"\\nO primeiro 1 eh o maior: %d\\n\", numero1);\n } else {\n if (numero2 >= numero3 && numero2 >= numero4) {\n printf(\"\\nO segundo numero e o maior: %d\\n\", numero2);\n } else { \n if (numero3 >= numero4 && numero3 >= numero2) { //a é o segundo\n printf(\"\\nO terceiro numero e o maior: %d\\n\", numero3);\n } else { //c é o segundo\n printf(\"\\nO quarto numero e o maior: %d\\n\", numero4);\n }\n }\n }\n return 0;\n}" }, { "alpha_fraction": 0.49003320932388306, "alphanum_fraction": 0.5033222436904907, "avg_line_length": 13.48717975616455, "blob_id": "b4b38aa25838ebd4a6c4a5537c5e68f3c318e4cf", "content_id": "116330380ddd96156ed74475fcfe485487f19900", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 602, "license_type": "permissive", "max_line_length": 66, "num_lines": 39, "path": "/programacao-micro-computadores/c/string.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n\r\nint lastindexof(const char *, char);\r\n\r\n\r\nint main(){\r\n\r\n\tchar str[41], ch;\r\n\tint pos;\r\n\r\n\tprintf(\"Informe uma string: \\n\");\r\n\tscanf(\"%41[^\\n]\", str);\r\n\tprintf(\"Informe um caractere: \\n\");\r\n\tscanf(\" %c\", &ch);\r\n\r\n\tpos = lastindexof(str, ch);\r\n\r\n\tif (pos != -1) {\r\n\t\tprintf(\"Posicao da ultima de %c em \\\"%s\\\": %d\\n\", ch, str, pos);\r\n\t} else {\r\n\t\tprintf(\"%c nao ocorre em \\\"%s\\\"\\n\", ch, str);\r\n\t}\r\n}\r\n\r\n\r\nint lastindexof(const char * s, char c)\r\n{\r\n\tint i = strlen(s) - 1;\r\n\tfor(i; i >= 0; i--)\r\n\t{\r\n\t\tif (s[i] == c) {\r\n\t\t\treturn i;\r\n\t\t}\r\n\t}\r\n\r\n\treturn -1;\r\n}" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5892857313156128, "avg_line_length": 16.75, "blob_id": "802f740904d13c2dcfc0791da340e6212a9574d2", "content_id": "9f3e3ef8cb357f1dce8344b09e3e946d20342da5", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 448, "license_type": "permissive", "max_line_length": 52, "num_lines": 24, "path": "/programacao-micro-computadores/c/convert_bytes_mb.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n\r\nvoid tamanho(int, float *, float *);\r\n\r\nint main() {\r\n\tint bytes;\r\n\tfloat kbytes, mbytes;\r\n\r\n\tprintf(\"Informe o tamanho do arquivo em bytes\\n\");\r\n\tscanf(\"%d\", &bytes);\r\n\ttamanho(bytes, &kbytes, &mbytes);\r\n\tprintf(\"Tamanho do arquivo em KB: %.2f\\n\", kbytes);\r\n\tprintf(\"Tamanho do arquivo em MB: %.2f\\n\", mbytes);\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid tamanho(int b, float * kb, float * mb) {\r\n\r\n\t*kb = b / 1024.0;\r\n\t*mb = *kb / 1024;\r\n\r\n}" }, { "alpha_fraction": 0.6651982665061951, "alphanum_fraction": 0.6821900606155396, "avg_line_length": 37.775001525878906, "blob_id": "ea2de07c0bd54a0f7a32b460f1e7f82183bc8ec2", "content_id": "935beab1406e1dc4b0fb474b6711da958f7fa533", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1644, "license_type": "permissive", "max_line_length": 61, "num_lines": 40, "path": "/programacao-micro-computadores/c/painel.h", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "/* painel.h\r\n* Protótipo das funções para a montagem do painel\r\n* Ciro Cirne Trindade\r\n* 14/04/2014\r\n*/\r\n#ifndef _PAINEL_H\r\n#define _PAINEL_H\r\n#define ALTURA 7 // altura da matriz e de cada número\r\n#define COMP_NUM 7 // comprimento de cada número\r\n/* função que preenche com espaços a matriz passada \r\n* como 2º argumento. O 1º argumento da função é o\r\n* número de colunas da matriz */\r\nvoid limpa_painel(int, char [][*]);\r\n/* função que recebe um número no formato de uma string, \r\n* cria a matriz de caracteres com as dimensões adequadas\r\n* e monta o painel, utilizando as funções plot? para \r\n* plotar cada número na posição correta na matriz */\r\nvoid monta_painel(char *);\r\n/* função que plota o zero na matriz. O 1º argumento desta\r\n* função é a posição relativa do zero no número que deseja-se\r\n* plotar, o 2º argumento é o número de colunas da matriz de\r\n* caracteres utilizada para representar o painel, que é o\r\n* 3º argumento da função */\r\nvoid plot0(int, int, char [][*]);\r\n/* as demais funções são semelhantes à função plot0, só que\r\n* plotam os números indicados em seus nomes */\r\nvoid plot1(int, int, char [][*]);\r\nvoid plot2(int, int, char [][*]);\r\nvoid plot3(int, int, char [][*]);\r\nvoid plot4(int, int, char [][*]);\r\nvoid plot5(int, int, char [][*]);\r\nvoid plot6(int, int, char [][*]);\r\nvoid plot7(int, int, char [][*]);\r\nvoid plot8(int, int, char [][*]);\r\nvoid plot9(int, int, char [][*]);\r\n/* esta função imprime no vídeo a matriz passada com seu 2º \r\n* argumento. O primeiro argumento desta função é o número\r\n* de colunas da matriz */\r\nvoid imprime_painel(int, char [][*]);\r\n#endif" }, { "alpha_fraction": 0.46581196784973145, "alphanum_fraction": 0.49145299196243286, "avg_line_length": 13.666666984558105, "blob_id": "7e629eb062de2e75182b60dd7c0247fd70f7d380", "content_id": "170fc28082e582a07b0dd533723c804264fac82d", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 474, "license_type": "permissive", "max_line_length": 97, "num_lines": 30, "path": "/programacao-micro-computadores/c/aritmetica_de_ponteiros.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n\r\nint main(){\r\n\tint a[10];\r\n\tint * p;\r\n\tint i = 0;\r\n\r\n\tp = &a[0];\r\n\r\n\tfor (i = 0; i < 10; i++)\r\n\t{\r\n\t\tprintf(\"p + %d = %p\\n\", i, p+i);\r\n\t\t*(p + i) = 0;\r\n\t}\r\n\tprintf(\"Conteudo do vetor: \\n\");\r\n\r\n\tfor (i = 0; i < 10; ++i)\r\n\t{\r\n\t\tprintf(\"%d, \", a[i]);\r\n\t}\r\n\r\n\tprintf(\"\\b\\b.\\n\");\r\n\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Operações com ponteiros: soma, subtração.\r\n * Operações entre ponteiros: nao se pode somar ponteiros entre si mas pode-se subtrair entre si;\r\n */" }, { "alpha_fraction": 0.7030752897262573, "alphanum_fraction": 0.7094379663467407, "avg_line_length": 61.93333435058594, "blob_id": "019fb59e76d886f942c198fff4e86649754cf987", "content_id": "3337fe9f8d4f6c474b6d50b0efe8397679645842", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 943, "license_type": "permissive", "max_line_length": 128, "num_lines": 15, "path": "/estrutura-de-dados/trabalho 1/trabalho.h", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "# include <stdio.h>\n# include <stdlib.h>\n# include <time.h>\n\n# define T 100000\t\t// CONSTANTE DEFINIDA PARA A QUANTIDADE DE ITENS GERADOS NO VETOR\n\nvoid gera_vetor_crescente(int *, int);\nvoid gera_vetor_decrescente(int *, int);\nvoid gera (int *, int);\t\t// FUNCAO CRIADA PARA GERAR O VETOR\nvoid bubble (int *, int, float *, float *);\t// FUNCAO CRIADA PARA ORDENAR O VETOR UTILIZANDO O ALGORITMO \"BUBBLE SORT\"\nvoid troca (int *, int);\t// FUNCAO CRIADA PARA TROCAR A POSICAO E ORDENAR O VETOR \"...\"\nvoid insertionSort (int *, int, float *, float *);\t// FUNCAO CRIADA PARA ORDENAR O VETOR UTILIZANDO O ALGORITMO \"INSERTION SORT\"\nvoid selection (int *, int, float *, float *);\t// FUNCAO CRIADA PARA ORDENAR O VETOR UTILIZANDO O ALGORITMO \"SELECTION SORT\"\nvoid trocaAnterior (int *, int);\t// FUNCAO CRIADA PARA TROCAR A POSICAO E ORDENAR O VETOR \"...\"\nvoid trocaMinimo (int *, int, int);\t// FUNCAO CRIADA PARA TROCAR A POSICAO E ORDENAR O VETOR \"...\"" }, { "alpha_fraction": 0.6115108132362366, "alphanum_fraction": 0.6558753252029419, "avg_line_length": 25.09375, "blob_id": "111a7ccc5a866bc9326cf69027bd9cafdc8dd800", "content_id": "5aa3d09203f7aa2eadce40eba4bd568cd19d1dfd", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 849, "license_type": "permissive", "max_line_length": 142, "num_lines": 32, "path": "/estrutura-de-dados/vetor2.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\n/*\n\tEsse tipo de comportamento de estouro de vetor é completamente imprevisível e depende de SO, sistema operacional e outros fatores.\n\n\n\tRAM:\n\t\t* Stack: variáveis estáticas, muito concorrido e pequeno, menos espaco corrido. As variáveis maiores são alocadas como referências do head. \n\t\thttp://www.cplusplus.com/reference/cstdlib/malloc/\n\t\t* Heap: variáveis dinâmicas, possui muito mais espaço contínuo. \n\t\t* Swap:\n\n*/\n\n\n\n\nint main() {\n\t// int v[10], i;\n\t// int v[100000000000], i; // simulando o erro de declaração de vetor\n\tint *v1 = (int*) malloc(32767000000000*sizeof(int)); //, i; // simulando o erro de declaração de vetor\n\n\t// for (i=0;i<100; i++) { //estourando o vetor\n\t\t// v[i] = i*10;\n\t\t// v[i] = 5;\n\t\t// printf(\"%d \", v[i]);\n\t\t// printf(\"%d %p \\n\", v[i], v +i);\n\t// }\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.6161137223243713, "alphanum_fraction": 0.6398104429244995, "avg_line_length": 21.64285659790039, "blob_id": "8f0b048fe3b529b432c1a0cd65e97a53b1e5c432", "content_id": "dfe54b350a0a00e6d7f2906d021aa93610471a7c", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 633, "license_type": "permissive", "max_line_length": 87, "num_lines": 28, "path": "/algoritmos-e-logica-da-programacao/lacos/1_while.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "/*\n Repetir o fatorial para while e do-while\n*/\n\n#include <stdio.h>\n\nint main()\n{\n printf(\"\\nVamos fazer o fatorial de 10 utilizando o while\\n\");\n \n int valor=10; //vamos fazer o fatorial de 10\n int contador = 0;\n int resultadoFatorial = 0;\n\n while (valor>=contador) {\n if (contador>=0 && contador<=1) { // por definicao 0! e 1! = 1\n resultadoFatorial = 1;\n } else {\n resultadoFatorial = resultadoFatorial * contador;\n }\n printf(\"Vamos fazer o fatorial de %d. Parcial %d.\\n\", contador, resultadoFatorial);\n contador++;\n }\n\n printf(\"O fatorial de %d eh %d\\n\", valor, resultadoFatorial);\n\n return 0;\n}" }, { "alpha_fraction": 0.3635652959346771, "alphanum_fraction": 0.4089132249355316, "avg_line_length": 19, "blob_id": "a963c240ef230eb6c53b5433eac68468a493d553", "content_id": "de19424299e0e64db17618ddba75c765cef93948", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1289, "license_type": "permissive", "max_line_length": 74, "num_lines": 64, "path": "/algoritmos-e-logica-da-programacao/triangulo.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float a, b, c, n1, n2, n3, n4;\n printf (\"\\nDigite 3 valores:\\n\");\n scanf (\"%f%f%f\", &a, &b, &c);\n if (a <= 0 || b <= 0 || c <= 0) {\n printf(\"\\nValores invalidos para fazer o calculo\\n\");\n }\n else {\n if (a <= b && a <= c) { //a é o primeiro\n if (b <= c) { // b é o segundo\n\tprintf (\"\\n%.2f, %.2f, %.2f\\n\", a, b, c);\n\ta = n1;\n\tb = n2;\n\tc = n3;\n }\n else { // c é o segundo\n\tprintf (\"\\n%.2f, %.2f, %.2f\\n\", a, c, b);\n\ta = n1;\n\tc = n2;\n\tb = n3;\n }\n }\n else {\n if (b <= c) { // b é o primeiro\n\tif (a <= c) { // a é o segundo\n\t printf (\"\\n%.2f, %.2f, %.2f\\n\", b, a, c);\n\t b = n1;\n\t a = n2;\n\t c = n3;\n\t}\n\telse { // c é o segundo\n\t printf (\"\\n%.2f, %.2f, %.2f\\n\", b, c, a);\n\t b = n1;\n\t c = n2;\n\t a = n3;\n\t}\n }\n else { //c é o primeiro\n\tif (a <= b) { //a é o segundo\n\t printf (\"\\n%.2f, %.2f, %.2f\\n\", c, a, b);\n\t c = n1;\n\t a = n2;\n\t b = n3;\n\t}\n\telse { //c é o segundo\n\t printf (\"\\n%.2f, %.2f, %.2f\\n\", c, b, a);\n\t c = n1;\n\t b = n2;\n\t a = n3;\n\t}\t\n }\t \n }\n n4 = n1 + n2;\n if (n4 < n3) {\n printf(\"\\nOs valores formam um triangulo\\n %.2f, %.2f\", n4, n3);\n }\n else {\n printf(\"\\nOs valores não formam um triangulo\\n %.2f, %.2f\", n4, n3);\n }\n }\n return 0;\n}" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5299145579338074, "avg_line_length": 15.785714149475098, "blob_id": "5969d86673461f71f1f9554109a12ce282a1ea91", "content_id": "8c65c13e0210df24fc09d42951b83351ba0286bc", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 234, "license_type": "permissive", "max_line_length": 43, "num_lines": 14, "path": "/algoritmos-e-logica-da-programacao/tipo_numero.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n int n1;\n printf(\"\\nEscolha um numero\\n\");\n scanf(\"%d\", &n1);\n if (n1 >= 0) {\n printf(\"\\nNumero %d e positivo\\n\", n1);\n }\n else {\n printf(\"\\nNumero %d e negativo\\n\", n1);\n }\n return 0;\n}" }, { "alpha_fraction": 0.5579793453216553, "alphanum_fraction": 0.5729047060012817, "avg_line_length": 22.54054069519043, "blob_id": "fdc58607966cd83e77006e91db755952133f280f", "content_id": "49c74d28ae35de32e620b5490f7af732eb4f5c7d", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 871, "license_type": "permissive", "max_line_length": 71, "num_lines": 37, "path": "/algoritmos-e-logica-da-programacao/exercicio5.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <time.h>\n#define LIM 10\n\nint main () {\n int numero1 = 0;\n srand(time(0));\n int numero_aleatorio = rand() % LIM + 1;\n\n printf(\"%d\\n\", numero_aleatorio);\n\n printf(\"\\nEntre com um numero inteiro:\\n\");\n scanf(\"%d\", &numero1);\n\n if (numero1 == numero_aleatorio) {\n printf(\"\\nVoce acertou!\\n\");\n } else {\n if (numero1 > numero_aleatorio) {\n printf(\"\\nNumero aleatorio e menor. Tente novamente:\\n\");\n } else {\n printf(\"\\nNumero aleatorio e maior. Tente novamente:\\n\"); \n }\n\n scanf(\"%d\", &numero1);\n if (numero1 == numero_aleatorio) {\n printf(\"\\nVoce acertou!\\n\");\n } else {\n if (numero1 > numero_aleatorio) {\n printf(\"\\nNumero fornecido e maior. Tente novamente:\\n\");\n } else {\n printf(\"\\nNumero fornecido e menor. Tente novamente:\\n\"); \n }\n }\n\n } \n return 0;\n} " }, { "alpha_fraction": 0.5589414834976196, "alphanum_fraction": 0.5685645341873169, "avg_line_length": 23.920000076293945, "blob_id": "55ed414ea240eab2ba4dc4a930ac3f9978c3aa52", "content_id": "78fd501622b0414ef8f9a52359cda4143968491f", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1248, "license_type": "permissive", "max_line_length": 65, "num_lines": 50, "path": "/programacao-micro-computadores/c/trabalho/main.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "// main.c\n\n#include \"frequencia.h\"\n#include <stdio.h>\n#include <string.h>\n// #include <ctype.h>\n\n// int frequencia(char *, char);\n// int maior_frequecia(int [], int);\t\n// void imprime_mais_frequente(int [], int, int);\n\nint main(){\n \tint quantidade_de_sentencas, i;\n\n\tprintf(\"Forneca a quantidade de sentencas: \\n\");\n\tscanf(\"%d\", &quantidade_de_sentencas); \n\t// vamos declarar o vetor para armazenar as sentencas\n\tchar sentenca[COMPRIMENTO_MAXIMO];\n\n\t// agora que ja temos onde armazenar as sentencas vamos pega-las\n\tfor (i=0;i<quantidade_de_sentencas;i++) {\n\t\tprintf(\"Entre com a frase ou palavra: \");\n\t\t// fgets(sentenca, sizeof(sentenca), stdin);\n\t\tscanf(\"%[^\\n]\", sentenca);\n\t\tputs(sentenca);\n\t}\n\n // int v[LETRAS_ALFABETO];\n // int texto, i, j;\n // printf(\"Informe uma linha de texto: \");\n\t// scanf(\"%120[^\\n]\", texto);\n\t\n\t// for (i = 0; texto[i] != '\\0'; i++) {\n\t// \tfor (j = 0; j < 5; j++) {\n\t// \t\tif (tolower(texto[i]) == LETRAS_ALFABETO[j]) {\n\t// \t\t\tcont[j]++;\n\t// \t\t\tbreak;\n\t// \t\t}\n\t// \t}\n\t// }\n\t// printf(\"\\nHistograma de frequência das vogais:\\n\");\n\t// for (i = 0; i < 5; i++) {\n\t// \tprintf(\"%c: \", LETRAS_ALFABETO[i]);\n\t// \tfor (j = 1; j <= cont[i]; j++) {\n\t// \t\tcont++;\n\t// \t}\n\t// \tprintf(\" (%d)\\n\", cont[i]);\n\t// }\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.5435041785240173, "alphanum_fraction": 0.5566149950027466, "avg_line_length": 17.55813980102539, "blob_id": "f87b8cdf52739244287945c436d38b3332fdb9f3", "content_id": "393d0040903a7c764343e636f3fb1ad375727608", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 842, "license_type": "permissive", "max_line_length": 115, "num_lines": 43, "path": "/algoritmos-e-logica-da-programacao/strings/ConsoleApplication1/ConsoleApplication1/fitromatti.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "ISO-8859-1", "text": "/*\r\nSimples para qualquer numero inteiro k < n, k será 1 para k primeiros digitos na sequencia.\r\nOs itens seguintes será a soma de k ultimos numeros. O total de numeros deve obedecer ao total de total = k + (n-k)\r\n*/\r\n\r\n#include <stdio.h>\r\n\r\nint main() {\r\n\tint k = 0;\r\n\tint n = 0;\r\n\tint i = 0;\r\n\tint contador = 0;\r\n\r\n\tprintf(\"\\n\\nVamos calcular a sequencia de Fitromacci. Entre com k depois n:\\n\\n\");\r\n\tscanf(\"%d%d\", &k, &n);\r\n\t\r\n\t// agora vamos validar as entradas\r\n\r\n\tif (k >= n && k > 0) {\r\n\t\tprintf(\"K não pode ser maior ou igual a N\");\r\n\t\treturn 1;\r\n\t}\r\n\r\n\t//ok validada as entradas vamos definir a matriz \r\n\tint vetor[n];\r\n\tcontador = k;\r\n\r\n\tfor (i=0; i < n; i++) {\r\n\t\tif (contador > 0) {\r\n\t\t\tvetor[i] = 1;\r\n\t\t\tcontador--;\r\n\t\t} else {\r\n\r\n\t\t}\r\n\t}\r\n\t\r\n\r\n\r\n\t\r\n\tprintf(\"\\n\\n\");\r\n\tsystem(\"PAUSE\");\r\n\treturn 0;\r\n}" }, { "alpha_fraction": 0.417391300201416, "alphanum_fraction": 0.469565212726593, "avg_line_length": 8.666666984558105, "blob_id": "4d36ce8c3b4a10c0abf534bb520c81337327a3cb", "content_id": "9878a817efb6cb68da6e7a510bc36b770cebdbd2", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 115, "license_type": "permissive", "max_line_length": 33, "num_lines": 12, "path": "/algoritmos-e-logica-da-programacao/ascii.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main(){\n\n\tint c;\n\n\tfor (c=0; c<256;c++){\n\t\tprintf(\"\\n%3d --> %c\\n\", c, c);\n\t}\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5957854390144348, "avg_line_length": 25.149999618530273, "blob_id": "8f323b3a35e1db1e8656d2b0952f011bd71bdbc0", "content_id": "a4f1e30d6d27b77be69f3793a1abb8d45a9fbfde", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 522, "license_type": "permissive", "max_line_length": 84, "num_lines": 20, "path": "/algoritmos-e-logica-da-programacao/calculo_compra.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n float valor, valor1, valor2;\n int tipo_pag;\n printf(\"Qual o valor de sua compra?\\n\");\n scanf(\"%f\", &valor);\n printf(\"\\nSelecione o tipo de pagamento:\\n 1 - A Vista \\n 2 - A Prazo\\n\");\n scanf(\"%d\", &tipo_pag);\n if (tipo_pag == 1) {\n valor1 = valor*10/100;\n valor2 = valor-valor1;\n printf(\"\\nO valor da sua compra e %.2f com o desconto de %f\\n\", valor2, valor1);\n }\n else {\n valor1 = valor/3;\n printf(\"\\nO valor das parcelas sera %.2f\\n\", valor1);\n }\n return 0;\n}" }, { "alpha_fraction": 0.4752941131591797, "alphanum_fraction": 0.5341176390647888, "avg_line_length": 15.791666984558105, "blob_id": "b9873a7f4edbe72f4128604ffdeaa28911b34b43", "content_id": "86dfc5236d83670ca90a95785cf9a25bbd993ed3", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 425, "license_type": "permissive", "max_line_length": 53, "num_lines": 24, "path": "/programacao-micro-computadores/c/separa_data.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n\r\nvoid separa_data(int, int *, int *, int *);\r\n\r\n\r\nint main(){\r\n\r\n\tint data, dia, mes, ano;\r\n\r\n\tprintf(\"Informe uma data no formato (ddmmaaaa)\\n\");\r\n\tscanf(\"%d\", &data);\r\n\tsepara_data(data, &dia, &mes, &ano);\r\n\tprintf(\"Data: %02d/%02d/%d\\n\", dia, mes, ano);\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\nvoid separa_data(int dt, int * d, int * m, int * a) {\r\n\r\n\t*d = dt / 1000000;\r\n\t*m = (dt / 10000) % 100;\r\n\t*a = dt % 10000;\r\n}" }, { "alpha_fraction": 0.5327510833740234, "alphanum_fraction": 0.5458515286445618, "avg_line_length": 15.357142448425293, "blob_id": "a8c84f6fb580442c20b350444e9bf8ce5e3fc01b", "content_id": "f8e79f4aabd65e3bd4a7c4a92d3ceffdf64d4075", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1605, "license_type": "permissive", "max_line_length": 54, "num_lines": 98, "path": "/estrutura-de-dados/sena_1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "WINDOWS-1252", "text": "/* Geracao de numeros da megasena */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define T 6\n\nvoid gera(int *, int);\nvoid gera_sem_repeticao(int *, int);\nint tem_repeticao(int *, int , int);\nvoid mostra(int *, int, char *);\nvoid bubble(int *, int);\nvoid troca(int *, int);\nint busca(int *, int);\n\nint main() {\n\tint v[T];\n\tsrand(time(0));\n\tgera_sem_repeticao(v, T);\n\tbubble(v, T);\n\tmostra(v, T, \"Resultado: \");\n\treturn 0;\n}\n\nvoid gera(int * v, n) {\n\tint i;\n\tfor (i=0;i<n;i++) {\n\t\tv[i] = rand() % 60 + 1;\n\t}\n}\n\nvoid gera_sem_repeticao(int * v, n) {\n\tint i=0;\n\tint numero;\n\n\twhile(i<n) {\n\t\tnumero = rand() % 60 + 1;\n\t\tprintf(\"gerado numero: %d \\n\", numero);\n\n\t\tif (!tem_repeticao(v, n, numero)) {\n\t\t\tv[i] = numero;\n\t\t\t++i;\n\t\t}\n\t}\n}\n\nvoid mostra(int * v, int n, char * msg) {\n\tint i;\n\n\tprintf(\"%s \", msg);\n\n\tfor (i=0;i<n;i++) {\n\t\tprintf(\"%d \", v[i]);\n\t}\n\n\tprintf(\"\\n\");\n}\n\nvoid bubble(int * v, int n) {\n\tint i, j;\n\tfor (i=1;i<n;i++) {\n\t\tfor (j=0;j < n-i; j ++) {\n\t\t\tif (v[j] > v[j + 1]) {\n\t\t\t\ttroca(v, j);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// implementa a troca dentro o vetor v\nvoid troca(int * v, int pos) {\n\tint aux = v[pos];\n\tv[pos] = v[pos + 1];\n\tv[pos + 1] = aux;\n\n}\n\n/*\n * Essa funcao testa se o item j‡ existe na matriz\n *\n * int v: matriz de vetores\n * int n: numero de itens\n * int numero_gerado: pa\n **/\nint tem_repeticao(int * v, int n, int numero_gerado) {\n\tint i = 0;\n\tfor (i=0;i<n;++i) {\n\t\tif (v[i] == numero_gerado) {\n\t\t\tprintf(\"Ja existe %d \\n\", numero_gerado);\n\t\t\treturn 1; // ja existe\n\t\t} else {\n\t\t\tprintf(\"Nao existe %d \\n\", numero_gerado);\n\t\t}\n\t}\n\n\treturn 0; // nao tem repeticao, urru\n}\n" }, { "alpha_fraction": 0.4900398552417755, "alphanum_fraction": 0.5219123363494873, "avg_line_length": 15.800000190734863, "blob_id": "a847f06e1b0834ab34a0ae9652bc57c5f0acd4d2", "content_id": "df6a5caf8bd544e9d9f64bc31dfe0e34a46133d0", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 251, "license_type": "permissive", "max_line_length": 40, "num_lines": 15, "path": "/algoritmos-e-logica-da-programacao/tipo_numero1.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main () {\n int n1, resto;\n printf(\"\\nDigite um numero\\n\");\n scanf(\"%d\", &n1);\n resto = n1%2;\n if (resto == 0) {\n printf(\"o numero %d e par\\n\", n1);\n }\n else {\n printf(\"o numero %d e impar\\n\", n1);\n }\n return 0;\n}" }, { "alpha_fraction": 0.668639063835144, "alphanum_fraction": 0.6804733872413635, "avg_line_length": 27.33333396911621, "blob_id": "394a4956432edafe834fe086bd4a6da17da920af", "content_id": "b5efc8620beed1bc7965e438ee547a6f94fe99b6", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 169, "license_type": "permissive", "max_line_length": 56, "num_lines": 6, "path": "/estrutura-de-dados/makefile", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "all: sort.o\n\tgcc -o target/bubble.sh target/sort.o -Wno-implicit-int\nsort.o: sort_1.c\n\tgcc -c sort_1.c -o target/sort.o -Wno-implicit-int\nclean:\n\trm -f *.o *.sh target/*" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 17.66666603088379, "blob_id": "016df5bfaa49953b3d7489c1bb02094ac33b5cb7", "content_id": "e87366a9313407aa481122276356c78d323c80d7", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 112, "license_type": "permissive", "max_line_length": 27, "num_lines": 6, "path": "/programacao-micro-computadores/c/makefile", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "painel.exe: painel.o\n\tgcc -o painel.exe painel.o\npainel.o: painel.c painel.h\n\tgcc -c painel.c\nclean:\n\trm -f *.o\t" }, { "alpha_fraction": 0.5987842082977295, "alphanum_fraction": 0.6443768739700317, "avg_line_length": 15.5, "blob_id": "c1b1c78728c1dd12e81adf7c9c836bf12c2f868c", "content_id": "d22dd5f663691b30b6eba9a696c9e604824b6a5b", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 329, "license_type": "permissive", "max_line_length": 40, "num_lines": 20, "path": "/estrutura-de-dados/structs_vetor.c", "repo_name": "geraldoandradee/fatec-coding", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct simples {\n int info;\n struct simples * vizinho;\n}\n\nvoid mostra_simples();\n\nint main() {\n struct simples s1, s2;\n s1.info = 0;\n s1.vizinho = NULL;\n mostra_simples(s1, \"S1 inicializada\");\n s2.info = 10;\n s2.vizinho = &s1;\n mostra_simples(s2, \"S2 inicializada\");\n return 0;\n}" } ]
55
NashwaShokry/Bike-Share-Statistics
https://github.com/NashwaShokry/Bike-Share-Statistics
0dfe86d3505f4436fa28d85b2f2968e5859c5653
a28eb50a2ab48c2a6b72b4f75e6314cd1b5bf40b
b62e0c5f9c86012460cfdaae1a39eeac7257c7d6
refs/heads/main
2023-03-31T18:39:11.459586
2021-04-07T07:18:13
2021-04-07T07:18:13
355,446,354
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6012393832206726, "alphanum_fraction": 0.6050114631652832, "avg_line_length": 34.347618103027344, "blob_id": "b52fc59ce2bd666062df2bfae547ecef0107c6c7", "content_id": "5d967f6bbc0be4bc5354b77c42940177b933ce98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7423, "license_type": "no_license", "max_line_length": 115, "num_lines": 210, "path": "/bikeshare.py", "repo_name": "NashwaShokry/Bike-Share-Statistics", "src_encoding": "UTF-8", "text": "import time\nimport pandas as pd\nimport numpy as np\n\n# Define global variables\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\nMONTHS = ['all', 'january', 'february', 'march', 'april', 'may', 'june']\n\nDAYS = [ 'all', 'monday', 'tuesday', 'wednesday', \n 'thursday', 'friday', 'saturday', 'sunday']\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n print('-'*40)\n \n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n city = ''\n while city.lower() not in CITY_DATA:\n city = input(\"Please select a city from the following:\\n {}\\n\".format(list(CITY_DATA.keys())))\n city = city.lower()\n\n # get user input for month (all, january, february, ... , june)\n month = ''\n while month.lower() not in MONTHS:\n month = input(\"Which month do you want? Select from the following:\\n {}\\n\".format(MONTHS))\n month = month.lower()\n \n # get user input for day of week (all, monday, tuesday, ... sunday)\n day = ''\n while day.lower() not in DAYS:\n day = input(\"Which day of week do you want? Select from the following:\\n {}\\n\".format(DAYS))\n day = day.lower()\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # Print selected data\n print('Analyzing data for '+ city.title())\n if month != 'all':\n print ('Month: {}'.format(month.title()))\n if day != 'all':\n print ('Day: {}'.format(day.title()))\n print('-'*40)\n # Load data for the selected city\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday\n\n # extract hour from the Start Time column to create an hour column\n df['hour'] = df['Start Time'].dt.hour\n\n if month != 'all':\n # use the index of the MONTHS list to get the corresponding int\n month = MONTHS.index(month)\n # filter by month to create the new dataframe\n df = df[df['month']==month]\n\n if day != 'all':\n # use the index of the DAYS list to get the corresponding int\n day = DAYS.index(day)-1 #subtract one as Monday has a value 0\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day] \n\n return df\n\n\ndef time_stats(df, month, day):\n \"\"\"Displays statistics on the most frequent times of travel.\n \n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month (only if there no filter for months)\n if month == 'all':\n print(\"The most popular month is: {}\\n\".format(MONTHS[df['month'].mode()[0]].title()))\n\n # display the most common day of week (only if there is no filter for days)\n if day == 'all':\n print(\"The most frequent day is: {}\\n\".format(DAYS[df['day_of_week'].mode()[0]+1].title()))\n\n # display the most common start hour\n print(\"And the most common start hour is: {}\".format(df['hour'].mode()[0]))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n print(\"The most commonly used start station is: {}\\n\".format(df['Start Station'].mode()[0]))\n\n # display most commonly used end station\n print(\"And the most commonly used end station is: {}\\n\".format(df['End Station'].mode()[0]))\n\n # display most frequent combination of start station and end station trip\n favourite_trip = df.groupby(['Start Station','End Station']).size().idxmax()\n print(\"While the most common trip is from {} to {}\".format(favourite_trip[0], favourite_trip[1] ))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n start_time = time.time()\n print('\\nCalculating Trip Duration...\\n')\n \n # display total travel time\n print( \"Total travel time is: {}\\n\".format(\n pd.Timedelta(seconds=df['Trip Duration'].sum())))\n\n # display mean travel time\n print( \"Average trip duration is: {}\".format(\n pd.Timedelta(seconds=df['Trip Duration'].mean())))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n print('Number of trips by user types:\\n')\n print(df.groupby(['User Type']).size())\n\n # Display counts of each gender if the gender column exists\n if 'Gender' in df.columns:\n print('\\nNumber of trips by user gender:\\n')\n print(df.groupby(['Gender']).size())\n\n # Display earliest, most recent, and most common year of birth\n if 'Birth Year' in df.columns:\n print(\"\\nStatistics by user's birth year:\\n\")\n print(\"Earliest year is: {},\\n most recent year is: {}\\n and most common year: {}\".format(\n int(df['Birth Year'].min()), int(df['Birth Year'].max())\n , int(df['Birth Year'].mode()[0])))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n time_stats(df, month, day)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n \n #Show a sample of data\n while True:\n if input('\\nWould you like to view a sample of data? Enter yes or no.\\n') == 'yes':\n print(\"Showing sample of 5 data rows:\")\n print(df.drop(['month','day_of_week','hour'], axis=1).sample(5))\n else:\n break\n \n \n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n" }, { "alpha_fraction": 0.7911646366119385, "alphanum_fraction": 0.7921686768531799, "avg_line_length": 98.5999984741211, "blob_id": "cbc1986b5b36c344278d658f2bb7bcf5fccdeeff", "content_id": "9708a0f649c93fa5733f188a1a1e7c1e6162994d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 996, "license_type": "no_license", "max_line_length": 231, "num_lines": 10, "path": "/Readme.txt", "repo_name": "NashwaShokry/Bike-Share-Statistics", "src_encoding": "UTF-8", "text": "This project aims to calculate some statistics for byke share usage pattern. We have data for 3 major cities: Chicago, New York City and Washington. \nThe user can select a certain city to get its data summaries, then he can filter its data by month and/or day if he wishes. He can select \"all\" if he doesn't want to apply filters. He must enter full month/day names to filter with.\nThen the system calculates and shows statistics for the selected data, and then asks the user if he wants to view a sample of data. The system shows a sample of raw data as long as the user replies with \"yes\"\nThe system asks the user if he wants to restart, then the whole process is restarted if the user answers with \"yes\", otherwise it exits.\n\nResources:\nhttps://stackoverflow.com/questions\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html\nhttps://www.geeksforgeeks.org/python-pandas-dataframe-sample/\nhttps://pandas.pydata.org/pandas-docs/stable/user_guide/timedeltas.html\n" } ]
2
aiyush/TkinterApps
https://github.com/aiyush/TkinterApps
022bfd3d28221ac4762017a22a9684f83c39702d
513d7f8b6c9245db10c22a868869dc5bf98f5338
bbd6c4fb4ac22a37032a3a947a5dfd129802e78d
refs/heads/main
2023-02-24T23:27:13.098525
2021-01-23T08:22:55
2021-01-23T08:22:55
332,161,074
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.620546817779541, "alphanum_fraction": 0.6429163217544556, "avg_line_length": 23.723403930664062, "blob_id": "c7108ebf222f8c2ca21583cdf64e93ab72d43aac", "content_id": "99413a4998bee28e635e70a0cae096091a915112", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 169, "num_lines": 47, "path": "/resize.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\ndef res():\r\n w = str(xentry.get())\r\n h = str(yentry.get())\r\n root.geometry(w+\"x\"+h)\r\n return\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"400x400\")\r\n#root.minsize(400,400)\r\n#root.maxsize(400,400)\r\n\r\nLabel(root, text = \"Enter the resolution in which you want to resize this window\",bg = \"#87afff\", relief = RIDGE).pack(anchor = \"n\", side = TOP , ipadx = 40, ipady = 30)\r\n\r\nxf = Frame(root, borderwidth = 2)\r\nxf.pack(side = TOP, fill = X)\r\n\r\nyf = Frame(root, borderwidth = 2)\r\nyf.pack(side = TOP, fill = X)\r\n\r\nbuttn = Frame(root, borderwidth = 2)\r\nbuttn.pack(side = TOP, fill = X)\r\n# Making a label for width\r\n\r\nx = Label(xf, text = \"Enter the Width of this window\")\r\nx.pack(side = LEFT)\r\n\r\n# making an entry space for width\r\nxval = IntVar()\r\nxentry = Entry(xf, textvariable = xval, relief = RIDGE)\r\nxentry.pack(side = RIGHT)\r\n\r\n# making a label for height\r\ny = Label(yf, text = \"Enter the Height of this window\")\r\ny.pack(side = LEFT)\r\n\r\n# making an entry space for height\r\nyval = IntVar()\r\nyentry = Entry(yf, textvariable = yval)\r\nyentry.pack(side = RIGHT)\r\n\r\n# making an apply button\r\nButton(buttn, text = \"Apply\", command = res).pack(side = BOTTOM, anchor = \"s\")\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.5637880563735962, "alphanum_fraction": 0.584396481513977, "avg_line_length": 31.442623138427734, "blob_id": "7436935d78668145c3c4b95f5d7b0bf8900eca2b", "content_id": "c416d6299a4a6059bf5fc47f4edb77fd3572eb02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2038, "license_type": "no_license", "max_line_length": 281, "num_lines": 61, "path": "/tut7forms.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\ndef sub():\r\n print(\"----------------Entries Begin----------------\")\r\n print(f\"\\nname : {nameentry.get()}\")\r\n print(f\"age : {ageentry.get()}\")\r\n print(f\"email id : {emailentry.get()}\")\r\n print(f\"Button Checked : {bool(int(recieveval.get()))}\")\r\n print(\"\\n----------------Entries Complete----------------\")\r\n\r\n with open(\"gui_records.txt\", \"a\") as gr:\r\n gr.write(f\"\\n------------------------Entries Begin------------------------ \\nname : {nameentry.get()} \\nage : {ageentry.get()} \\nemail id : {emailentry.get()} \\nButton Checked : {bool({recieveval.get()})} \\n------------------------Entries Complete------------------------\")\r\n \r\n if \"@\" and \".com\" in emailentry.get():\r\n pass\r\n else:\r\n print(\"Error: Invalid email id\")\r\n return\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"300x500\")\r\nroot.maxsize(300,500)\r\nroot.minsize(300,500)\r\n\r\n#Heading\r\nLabel(root, text = \"Welcome to Tiru's forum :)\", borderwidth = 4,\r\nrelief = RIDGE).grid( row = 1, columnspan = 2, ipadx = 62, ipady = 10\r\n,sticky = N)\r\n\r\n#Form questions\r\nname = Label(root, text = \"Name\")\r\nname.grid(row = 3, column = 0, sticky = W)\r\n\r\nage = Label(root, text = \"Age\")\r\nage.grid(row = 5,column = 0, sticky = W)\r\n\r\nemail = Label(root, text = \"email id\")\r\nemail.grid(row = 7, column = 0, sticky = W)\r\n\r\n#form client input\r\n#class types\r\nnameval = StringVar()\r\nageval = IntVar()\r\nemailval = StringVar()\r\nrecieveval = IntVar()\r\n\r\n#getting the vals now\r\nnameentry = Entry(root, textvariable = nameval)\r\nnameentry.grid(row = 3, column = 1)\r\nageentry = Entry(root, textvariable = ageval)\r\nageentry.grid(row = 5, column = 1, sticky = E)\r\nemailentry = Entry(root, textvariable = emailval)\r\nemailentry.grid(row = 7, column = 1, sticky = E)\r\nrecieveentry = Checkbutton(text = \"Do you wish to recieve \\nupdates regularly?\", variable = recieveval)\r\nrecieveentry.grid(row = 9, column = 1, sticky = W)\r\n\r\n#Submitting the form\r\nButton(text = \"Submit\", command = sub, relief = RAISED).grid(row = 12, column = 1)\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.6420807242393494, "alphanum_fraction": 0.6645962595939636, "avg_line_length": 30.25, "blob_id": "ba0bd30f90140930b7c98f9efe7d9e179cbe8b43", "content_id": "a805cfd384504bace43ea8a858e108d40ea0f2fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1292, "license_type": "no_license", "max_line_length": 90, "num_lines": 40, "path": "/tut3_attributes.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"744x800\")\r\nroot.minsize(300,400)\r\nroot.maxsize(900,1080)\r\nroot.title(\"My Home automation console\")\r\n\r\n#important label options\r\n#fg = foreground\r\n#bg = background\r\n#text = add texts to the box\r\n#font = customise fonts\r\n#padx = x padding\r\n#pady = y padding\r\n#relief(border styling) = SUNKEN,RAISED,GROOVE,RIDGE, FLAT,SOLID\r\n\r\n\r\ntxt = Label(text = '''In a fast-paced, highly intense military conflict situation, \r\n\\nBrahMos, encompassing an “across the spectrum” warfare capability in all-weather, \r\n\\nday-and-night conditions, can ensure a clear, decisive outcome in the battlefield...''',\r\nfg = \"white\", bg = \"black\", padx = 50, pady = 40, font = \"Roboto 10 bold italic\",\r\nborderwidth = 5, relief = SUNKEN)\r\n\r\n#We can change the position and much more for the above pack\r\n#by using pack options\r\n#anchor = nw,sw,ne,se(directions...north east,south east...etc)\r\n#side = top,bottom,left,right\r\n#fill(for automatically adjusting the pack) = X, Y \r\n#padx\r\n#pady \r\n\r\ntxt.pack(side = TOP, anchor = \"se\", fill = X)\r\n\r\ntxt_ready = Label(text = \"-------------------- READY----------------------\",\r\nfg = \"red\", font = \"ROBOTO 12 bold\", borderwidth = 5, relief = RAISED)\r\ntxt_ready.pack(anchor = \"s\", side = BOTTOM, fill = X)\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 28.894737243652344, "blob_id": "c575aede2b3070dd793cf3f374c3a7082c4b934e", "content_id": "38e5f6fdc5aaa921bcbd661c6943da264979e7dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "no_license", "max_line_length": 61, "num_lines": 19, "path": "/tut4frames.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"300x700\")\r\n\r\nf1 = Frame(root,borderwidth = 4, bg = \"grey\", relief = RIDGE)\r\ntxt1 = Label(f1, text = \"This is the 1st frame in this gui\",\r\nbg = \"grey\", fg = \"white\", font = \"Helvetica 10 bold\")\r\nf1.pack(side = LEFT, anchor = \"w\", fill = Y)\r\ntxt1.pack(pady = 100)\r\n\r\nf2 = Frame(root, borderwidth = 4,bg = \"grey\", relief = RIDGE)\r\ntxt2 = Label(f2, text = \"This is the 2nd frame in this gui\",\r\nfg = \"white\", bg = \"grey\", font = \"Roboto 10 italic\")\r\nf2.pack(side = TOP, anchor = \"n\", fill = X)\r\ntxt2.pack(padx = 100)\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.5176817178726196, "alphanum_fraction": 0.598231852054596, "avg_line_length": 26.33333396911621, "blob_id": "1a633b1cf8884c7518062e49f6be4e79289d6513", "content_id": "812d27d10e745eead651a1941de01b7f2b43de80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 61, "num_lines": 36, "path": "/tut5buttons.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\ndef on():\r\n print(\"On\")\r\n return\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"600x300\")\r\nroot.minsize(600,300)\r\nroot.maxsize(600,300)\r\n\r\nf1 = Frame(root, bg = \"grey\", padx = 40, pady = 40, \r\nborderwidth = 5, relief = RIDGE)\r\nf1.pack(side = LEFT,fill = BOTH)\r\nb1 = Button(f1, bg = \"#3586c4\", text = \"Bulb1\", command = on)\r\nb1.pack(side = TOP)\r\n\r\nf2 = Frame(root, bg = \"grey\", padx = 40, pady = 40, \r\nborderwidth = 5, relief = RIDGE)\r\nf2.pack(side = LEFT,fill = BOTH)\r\nb2 = Button(f2, bg = \"#3586c4\", text = \"Bulb2\", command = on)\r\nb2.pack(side = BOTTOM, fill = BOTH)\r\n\r\nf3 = Frame(root, bg = \"grey\", padx = 40, pady = 40, \r\nborderwidth = 5, relief = RIDGE)\r\nf3.pack(side = LEFT,fill = BOTH)\r\nb3 = Button(f3, bg = \"#3586c4\", text = \"Bulb3\", command = on)\r\nb3.pack(side = TOP)\r\n\r\nf4 = Frame(root, bg = \"grey\", padx = 40, pady = 40, \r\nborderwidth = 5, relief = RIDGE)\r\nf4.pack(side = LEFT, fill = BOTH)\r\nb4 = Button(f4, bg = \"#3586c4\", text = \"Bulb4\", command = on)\r\nb4.pack(side = TOP)\r\nroot.mainloop()" }, { "alpha_fraction": 0.6343042254447937, "alphanum_fraction": 0.6990291476249695, "avg_line_length": 16.294116973876953, "blob_id": "6ba599ba7912d8c9152b121cd1ca384d5440a666", "content_id": "262d256d1433f4d5c9759d82cdcdeea22d2883e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/tut2.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom PIL import Image,ImageTk\r\nimport os\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"300x400\")\r\nroot.minsize(100,100)\r\nroot.maxsize(600,1400)\r\n\r\nimg = Image.open(\"background-montagne-6.jpg\")\r\nimgo = ImageTk.PhotoImage(img)\r\n\r\nimgo_label = Label(image = imgo)\r\nimgo_label.pack()\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.6357465982437134, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 22.66666603088379, "blob_id": "2b3e42ecaa9c66674a24e02942d050079f0702c9", "content_id": "aa5ad9b0af6c3f9d5c0230a0173cda6712d2d673", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "no_license", "max_line_length": 95, "num_lines": 18, "path": "/tut8event_handling.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\ndef coords(event):\r\n print(f\"The current position of the button on the screen is: x = {event.x}, y = {event.y}\")\r\n return\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"300x500\")\r\nroot.title(\"Experimenting with Event handlings\")\r\nbtn = Button(root, text = \"Khlikh\")\r\nbtn.pack(side = TOP, anchor = \"n\")\r\n\r\n#To see all the events,google it\r\nbtn.bind('<Button-1>', coords)\r\nbtn.bind('<Double-Button-1>', quit)\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.6429433226585388, "alphanum_fraction": 0.662243664264679, "avg_line_length": 23.96875, "blob_id": "8b5314e29b145a40b5a9edc2b6b613033ddcf786", "content_id": "a8bc699dbc80d57cbe3baf573b4e577f68781628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 829, "license_type": "no_license", "max_line_length": 71, "num_lines": 32, "path": "/tut6forms.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\ndef getvals():\r\n print(f\"The username is {usrvalue.get()}\")\r\n print(f\"The password is {passvalue.get()}\")\r\n return\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"300x700\")\r\n\r\nuser = Label(root, text = \"Username: \")\r\nuser.grid(row = 1, column = 3)\r\n\r\npassword = Label(root, text = \"Password: \")\r\npassword.grid(row = 3, column = 3)\r\n\r\n#Types of variables represented in tkinter are:\r\n#BooleanVar, DoubleVar, IntVar, StringVar\r\n\r\nusrvalue = StringVar()\r\nusrentry = Entry(root, relief = SUNKEN, textvariable = usrvalue) \r\nusrentry.grid(row = 1, column = 4)\r\n\r\npassvalue = StringVar()\r\npassentry = Entry(root, relief = SUNKEN, textvariable = passvalue)\r\npassentry.grid(row = 3, column = 4)\r\n\r\nbtn = Button(root, text = \"Submit\", relief = RAISED, command = getvals)\r\nbtn.grid(row = 5, column = 5)\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.7417218685150146, "alphanum_fraction": 0.7668874263763428, "avg_line_length": 26.962963104248047, "blob_id": "ffe9c25168da734d445bf8f041c90fb00a018e11", "content_id": "3540924bd258caa041b25d2f4c2a003f74a0672b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 102, "num_lines": 27, "path": "/tut1.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom PIL import Image,ImageTk\n\nroot = Tk()\n\n# sizes take arguments in this order: width x height\nroot.geometry(\"728x920\")\n\nroot.minsize(100,150)\nroot.maxsize(800,1000)\n\n#Displaying texts in the box\ntxt = Label(text = \"Hello there,I am being created for screen buttons!\")\ntxt.pack()\n\n#Displaying image in box\n#NOTE: .jpg format is not supported by Tkinter for now\n#So we use PIL module for converting the image into .png format\n#photo = PhotoImage(file =\"cocytus-overlord-crossdress-horns-demiurge-overlord-wallpaper-preview.jpg\")\n\nimage = Image.open(\"cocytus-overlord-crossdress-horns-demiurge-overlord-wallpaper-preview.jpg\")\nphoto = ImageTk.PhotoImage(image)\n\nimage_label = Label(image = photo)\nimage_label.pack()\n\nroot.mainloop() " }, { "alpha_fraction": 0.6125873923301697, "alphanum_fraction": 0.6279720067977905, "avg_line_length": 23.60714340209961, "blob_id": "d5af9be88200081240ddd1ecffb5dfb778ad9b5f", "content_id": "4164aac68bf717ba37c53ec4c943f59f00be8b4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 715, "license_type": "no_license", "max_line_length": 125, "num_lines": 28, "path": "/slider.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nimport tkinter.messagebox as tmsg\r\nimport sys\r\nimport os\r\n\r\ndef rate():\r\n a = myslider.get()\r\n if a <= 7:\r\n tmsg.showinfo(\"Ohh no!!\",\"Sorry for the bad experience.We will take this into account and improve upon our mistakes\")\r\n else:\r\n tmsg.showinfo(\"Thanks\",f\"Thanks for the {a} stars.Hope to see you soon\")\r\n\r\n \r\n with open(\"rating.txt\", \"a+\") as w:\r\n w.write(f\"The user gave a rating of {a} stars\"+\"\\n\\n\")\r\n\r\n return\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"320x300\")\r\nmyslider = Scale(root, from_=0, to_=10, orient = HORIZONTAL, tickinterval = 1)\r\nmyslider.pack()\r\n\r\nmybutton = Button(root, text = \"Rate\", command = rate)\r\nmybutton.pack()\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.6477272510528564, "alphanum_fraction": 0.689393937587738, "avg_line_length": 20.16666603088379, "blob_id": "b9e68f3a5044a72a2a342fa270d06d3b66fc2522", "content_id": "ac70b68838aff6f26a12ff10ff489caa984ddc33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 264, "license_type": "no_license", "max_line_length": 58, "num_lines": 12, "path": "/switchboard.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\n\r\nroot = Tk()\r\n\r\n# Geometry of the board\r\nroot.geometry(\"1920x1080\")\r\n\r\n# Deviding the board into sections\r\nbulbAlmirah1 = Frame(root,borderwidth = 4, relief = RIDGE)\r\nbulbAlmirah1.pack(side = TOP, anchor = \"ne\", fill = Y)\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.6691542267799377, "alphanum_fraction": 0.6878109574317932, "avg_line_length": 33.77777862548828, "blob_id": "e3c7133bc39fa3eed5ecfe9d407db4cfad96daac", "content_id": "f5b67d0c68505149d2a4af7a0f42c20b19db154f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1608, "license_type": "no_license", "max_line_length": 90, "num_lines": 45, "path": "/menu_and_submenu.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom tqdm import tqdm\r\nfrom time import *\r\n\r\ndef myfunc():\r\n print(\"Performing the opertation...Please hold.\",end = \"\\n\\n\\n\")\r\n for i in tqdm(range(50), desc = \"Loading Enviornment Variables...\"):\r\n sleep(0.001)\r\n print(\"Initialization Complete!\",end = \"\\n\\n\\n\")\r\n return\r\n\r\nroot = Tk()\r\n\r\nroot.geometry(\"500x400\")\r\n\r\n# The title of the app at top left corner\r\nroot.title(\"SwitchBoard\")\r\n\r\n# Creating a main menu bar\r\n\r\n# We create a main menu in root\r\nmainmenu = Menu(root)\r\n\r\n# Now we create a section in the main menu named \"File\"\r\nm1 = Menu(mainmenu,tearoff = 0) #Initialising file menu\r\nm1.add_command(label = \"New File\", command = myfunc) # adding options for this section\r\nm1.add_separator() # We can place it anywhere to draw a line/seperate the options\r\nm1.add_command(label = \"Save\", command = myfunc)\r\nm1.add_command(label = \"Save As\", command = myfunc)\r\nm1.add_separator()\r\nm1.add_command(label = \"Exit\", command = quit)\r\nmainmenu.add_cascade(label = \"File\",menu = m1) # giving the cascade menu a name.ie. \"File\"\r\n\r\nm2 = Menu(mainmenu,tearoff = 0) #Initialising file menu\r\nm2.add_command(label = \"Undo\", command = myfunc) # adding options for this section\r\nm2.add_separator() # We can place it anywhere to draw a line/seperate the options\r\nm2.add_command(label = \"Copy\", command = myfunc)\r\nm2.add_command(label = \"Paste\", command = myfunc)\r\nm2.add_separator()\r\nm2.add_command(label = \"Delete\", command = myfunc)\r\nmainmenu.add_cascade(label = \"Edit\",menu = m2) # giving the cascade menu a name.ie. \"File\"\r\n\r\nroot.config(menu = mainmenu)\r\n\r\nroot.mainloop()" }, { "alpha_fraction": 0.6588495373725891, "alphanum_fraction": 0.6730088591575623, "avg_line_length": 34.48387145996094, "blob_id": "5adae5e0f833267d7cf95a18c936c597c6a727aa", "content_id": "c828836078a43337e3470862be33fbd4028cff29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2260, "license_type": "no_license", "max_line_length": 126, "num_lines": 62, "path": "/message_box.py", "repo_name": "aiyush/TkinterApps", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom tqdm import tqdm\r\nfrom time import *\r\nimport tkinter.messagebox as tmsg \r\n\r\ndef myfunc():\r\n print(\"Performing the opertation...Please hold.\",end = \"\\n\\n\\n\")\r\n for i in tqdm(range(50), desc = \"Loading Enviornment Variables...\"):\r\n sleep(0.001)\r\n print(\"Initialization Complete!\",end = \"\\n\\n\\n\")\r\n return\r\n\r\ndef help():\r\n print(\"I will help you.\")\r\n a = tmsg.showinfo(\"Help\",\"To ask for help,press Yes!\")\r\n print(a)\r\n return\r\n\r\ndef rate():\r\n b = tmsg.askyesno(\"Did you enjoy the app\",\"Have you had fun using this app?\")\r\n print(b)\r\n if b == True:\r\n msg = \"Thanks for these kind words.Please rate us in the app store.\"\r\n else:\r\n msg = \"We are so sorry to hear that.Please Go to the message forum and paste your logfile.Ur queries will be resolved\"\r\n tmsg.showinfo(\"Experience\",msg)\r\nroot = Tk()\r\n\r\nroot.geometry(\"500x400\")\r\n\r\n# The title of the app at top left corner\r\nroot.title(\"SwitchBoard\")\r\n\r\n# Creating a main menu bar\r\n\r\n# We create a main menu in root\r\nmainmenu = Menu(root)\r\n\r\n# Now we create a section in the main menu named \"File\"\r\nm1 = Menu(mainmenu,tearoff = 0) #Initialising file menu\r\nm1.add_command(label = \"New File\", command = myfunc) # adding options for this section\r\nm1.add_separator() # We can place it anywhere to draw a line/seperate the options\r\nm1.add_command(label = \"Save\", command = myfunc)\r\nm1.add_command(label = \"Save As\", command = myfunc)\r\nm1.add_separator()\r\nm1.add_command(label = \"Exit\", command = quit)\r\nmainmenu.add_cascade(label = \"File\",menu = m1) # giving the cascade menu a name.ie. \"File\"\r\n\r\nm2 = Menu(mainmenu,tearoff = 0) #Initialising file menu\r\nm2.add_command(label = \"Undo\", command = myfunc) # adding options for this section\r\nm2.add_separator() # We can place it anywhere to draw a line/seperate the options\r\nm2.add_command(label = \"Copy\", command = myfunc)\r\nm2.add_command(label = \"Paste\", command = myfunc)\r\nm2.add_separator()\r\nm2.add_command(label = \"Delete\", command = myfunc)\r\nm2.add_command(label = \"Help\", command = help)\r\nm2.add_command(label = \"Rate Us!!\", command = rate)\r\nmainmenu.add_cascade(label = \"Edit\",menu = m2) # giving the cascade menu a name.ie. \"File\"\r\n\r\nroot.config(menu = mainmenu)\r\n\r\nroot.mainloop()" } ]
13
rantav/flask-sillywalk
https://github.com/rantav/flask-sillywalk
3ef528cb3c8c60149b4fd4a323a2c758fb8de6f5
cda707986981b5e26ad1a69410380abef58a8e26
0325d37a8ca214ef8c8bfa222943e6aed94f3af7
refs/heads/master
2023-06-12T20:15:34.077645
2013-10-29T20:30:50
2013-10-29T20:30:50
14,525,578
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5127792954444885, "alphanum_fraction": 0.5145319104194641, "avg_line_length": 30.122726440429688, "blob_id": "1ae85665ffec62165d56faf9bfd7b372ff068d1a", "content_id": "f374e1fb7634b1180b541b985e33d6d53241578b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6847, "license_type": "no_license", "max_line_length": 82, "num_lines": 220, "path": "/flask_sillywalk.py", "repo_name": "rantav/flask-sillywalk", "src_encoding": "UTF-8", "text": "import inspect\nimport json\nfrom collections import defaultdict\nfrom urlparse import urlparse\n\ntry:\n from flask import _app_ctx_stack as stack\nexcept ImportError:\n from flask import _request_ctx_stack as stack\n\n\n__APIVERSION__ = \"1.0\"\n__SWAGGERVERSION__ = \"1.0\"\nSUPPORTED_FORMATS = [\"json\"]\n\n\nclass SwaggerRegistryError(Exception):\n pass\n\n\nclass SwaggerApiRegistry(object):\n\n def __init__(self, app=None, baseurl=\"http://localhost/\"):\n self.baseurl = baseurl\n self.basepath = urlparse(self.baseurl).path\n self.r = defaultdict(dict)\n self.models = defaultdict(dict)\n if app is not None:\n self.app = app\n self.init_app(self.app)\n\n def init_app(self, app):\n for fmt in SUPPORTED_FORMATS:\n app.add_url_rule(\n \"{0}/resources.{1}\".format(\n self.basepath.rstrip(\"/\"),\n fmt),\n \"resources\",\n self.jsonify(self.resources))\n\n def jsonify(self, f):\n def inner_func():\n return json.dumps(f())\n return inner_func\n\n def resources(self):\n resources = {\n \"apiVersion\": __APIVERSION__,\n \"swaggerVersion\": __SWAGGERVERSION__,\n \"basePath\": self.baseurl,\n \"models\": dict(),\n \"apis\": list()}\n for resource in self.r.keys():\n resources[\"apis\"].append({\n \"path\": \"/\" + resource + \".{format}\",\n \"description\": \"\"})\n for k, v in self.models.items():\n resources[\"models\"][k] = v\n return resources\n\n def registerModel(self, c, *args, **kwargs):\n def inner_func(*args, **kwargs):\n if self.app is None:\n raise SwaggerRegistryError(\n \"You need to initialize {0} with a Flask app\".format(\n self.__class__.__name__))\n return c(*args, **kwargs)\n self.models[c.__name__] = {\n \"id\": c.__name__,\n \"properties\": dict()}\n argspec = inspect.getargspec(c.__init__)\n argspec.args.remove(\"self\")\n if argspec.defaults:\n defaults = zip(argspec.args[-len(\n argspec.defaults):], argspec.defaults)\n for arg in argspec.args[:-len(defaults)]:\n self.models[c.__name__][\"properties\"][arg] = {\"required\": True}\n for k, v in defaults:\n self.models[c.__name__][\"properties\"][k] = {\n \"required\": False,\n \"default\": v}\n return inner_func\n\n def register(\n self,\n path,\n method=\"GET\",\n parameters=[],\n errorResponses=[]):\n def inner_func(f):\n if self.app is None:\n raise SwaggerRegistryError(\n \"You need to initialize {0} with a Flask app\".format(\n self.__class__.__name__))\n\n self.app.add_url_rule(\n path,\n f.__name__,\n f,\n methods=[method])\n\n api = Api(\n method=f,\n path=path.replace(self.basepath, \"\"),\n httpMethod=method,\n params=parameters,\n errorResponses=errorResponses)\n\n if api.resource not in self.app.view_functions:\n for fmt in SUPPORTED_FORMATS:\n self.app.add_url_rule(\n \"{0}/{1}.{2}\".format(\n self.basepath.rstrip(\"/\"),\n api.resource,\n fmt),\n api.resource,\n self.show_resource(api.resource))\n\n if self.r[api.resource].get(api.path) is None:\n self.r[api.resource][api.path] = list()\n self.r[api.resource][api.path].append(api)\n\n return inner_func\n\n def show_resource(self, resource):\n def inner_func():\n return_value = {\n \"resourcePath\": resource.rstrip(\"/\"),\n \"apiVersion\": __APIVERSION__,\n \"swaggerVersion\": __SWAGGERVERSION__,\n \"basePath\": self.baseurl,\n \"apis\": list(),\n \"models\": list()\n }\n resource_map = self.r.get(resource)\n for path, apis in resource_map.items():\n api_object = {\n \"path\": path,\n \"description\": \"\",\n \"operations\": list()}\n for api in apis:\n api_object[\"operations\"].append(api.document())\n return_value[\"apis\"].append(api_object)\n return json.dumps(return_value)\n return inner_func\n\n\nclass SwaggerDocumentable(object):\n\n def document(self):\n return self.__dict__\n\n\nclass Api(SwaggerDocumentable):\n\n def __init__(\n self,\n method,\n path,\n httpMethod,\n params=None,\n errorResponses=None,\n nickname=None):\n\n self.httpMethod = httpMethod\n self.summary = method.__doc__ if method.__doc__ is not None else \"\"\n self.resource = path.lstrip(\"/\").split(\"/\")[0]\n self.path = path.replace(\"<\", \"{\").replace(\">\", \"}\")\n self.parameters = [] if params is None else params\n self.errorResponses = [] if errorResponses is None else errorResponses\n self.nickname = \"\" if nickname is None else nickname\n\n # See https://github.com/wordnik/swagger-core/wiki/API-Declaration\n def document(self):\n ret = self.__dict__.copy()\n # need to serialize these guys\n ret[\"parameters\"] = [p.document() for p in self.parameters]\n ret[\"errorResponses\"] = [e.document() for e in self.errorResponses]\n return ret\n\n def __hash__(self):\n return hash(self.path)\n\n\nclass ApiParameter(SwaggerDocumentable):\n\n def __init__(\n self,\n name,\n description,\n required,\n dataType,\n paramType,\n allowMultiple=False):\n self.name = name\n self.description = description\n self.required = required\n self.dataType = dataType\n self.paramType = paramType\n self.allowMultiple = allowMultiple\n\n def document(self):\n return self.__dict__\n\n\nclass ImplicitApiParameter(ApiParameter):\n\n def __init__(self, *args, **kwargs):\n if \"default_value\" not in kwargs:\n raise TypeError(\n \"You need to provide an implicit parameter with a default value.\")\n super(ImplicitApiParameter, self).__init__(*args, **kwargs)\n self.defaultValue = kwargs.get(\"default_value\")\n\n\nclass ApiErrorResponse(SwaggerDocumentable):\n\n def __init__(self, code, reason):\n self.reason = reason\n self.code = code\n" } ]
1
carolinebrasil/analysis-buckets-n-instances
https://github.com/carolinebrasil/analysis-buckets-n-instances
68ee4a79839cedeaff7ef4a265d63468c34bd902
a31074342dde71536b2b828c1b7ddb9e82f830ed
f79dc3a1a3b4016f55580e2f920abc56b6b43f8e
refs/heads/master
2023-04-25T02:08:28.386809
2021-05-11T17:53:55
2021-05-11T17:53:55
275,641,439
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.43396225571632385, "alphanum_fraction": 0.698113203048706, "avg_line_length": 16.66666603088379, "blob_id": "02b8270abb6e84701897131cc42122f22e4a49a6", "content_id": "1bd91ce52a996d60c489e81489c7f69b7bce358c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 53, "license_type": "no_license", "max_line_length": 19, "num_lines": 3, "path": "/requirements.txt", "repo_name": "carolinebrasil/analysis-buckets-n-instances", "src_encoding": "UTF-8", "text": "boto3==1.17.70\nbotocore==1.20.70\ntable-logger==0.3.6\n" }, { "alpha_fraction": 0.67220139503479, "alphanum_fraction": 0.6898767948150635, "avg_line_length": 41.431819915771484, "blob_id": "228b81962859531bb0b9055e6b86f65fb34ddf01", "content_id": "0b83e05a3aa6024f3d540e9f9625778e48418394", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1867, "license_type": "no_license", "max_line_length": 167, "num_lines": 44, "path": "/data-analysis-s3.py", "repo_name": "carolinebrasil/analysis-buckets-n-instances", "src_encoding": "UTF-8", "text": "import boto3 # Lib for collect information in AWS s3\nfrom table_logger import TableLogger # Lib to exhibition data in table\n\n'''\nStage to collect information for each bucket in AWS S3.\nName, date of creation, number of files, total size in KB, last modified date of the most recent file and cost.\n'''\n# Resource s3\ns3 = boto3.resource('s3') \n\n# Table to organize and show the information \ntable = TableLogger(columns='Name,Creation date,Number of files,Total size (KB),Last modified date,Price', border=True)\n\n# tax for s3 in us-east-1\ntax = 0.023 \n\nfor s3_bucket in (s3.buckets.all()):\n # Dictionary to store bucket informations \n bucketdata = dict() \n \n # Bucket name\n bucketdata['name'] = s3_bucket.name\n\n # Date of creation\n bucketdata['creation_date'] = s3_bucket.creation_date.strftime(\"%Y-%m-%d\")\n\n # Number of files \n bucketdata['number_files'] = int(sum(1 for count in s3_bucket.objects.all()))\n \n # Total bucket size with conversion Byte to KB\n bucketdata['total_size_KB'] = round(float(sum(o.size for o in s3_bucket.objects.all())) / 1024, 4)\n \n # Last modified date of most recent file \n bucketdata['last_modified'] = max(s3_bucket.objects.all(), key=lambda o: o.last_modified, default=None)\n if bucketdata['last_modified'] is None:\n bucketdata['last_modified'] = bucketdata['creation_date'].creation_date.strftime(\"%Y-%m-%d\")\n else:\n bucketdata['last_modified'] = bucketdata['last_modified'].last_modified.strftime(\"%Y-%m-%d\")\n \n # Calculate price with tax standard for us-east-1 in GB\n bucketdata['pricing'] = round(bucketdata['total_size_KB'] / 1024**2 * tax, 4)\n\n # # Show the information in table format\n table(bucketdata['name'], bucketdata['creation_date'], bucketdata['number_files'], bucketdata['total_size_KB'], bucketdata['last_modified'], bucketdata['pricing'])\n" }, { "alpha_fraction": 0.6977567672729492, "alphanum_fraction": 0.7036599516868591, "avg_line_length": 41.349998474121094, "blob_id": "e8788e4a029588408b863b78fb342b4ad4151606", "content_id": "bbdcb1338f61b9d1c4c4d1ed6bf60d3155a5b34f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 847, "license_type": "no_license", "max_line_length": 170, "num_lines": 20, "path": "/data-analysis-ec2.py", "repo_name": "carolinebrasil/analysis-buckets-n-instances", "src_encoding": "UTF-8", "text": "import boto3 # Lib to connect in AWS\nfrom table_logger import TableLogger # Lib to exhibition data in table\n\nec2 = boto3.resource('ec2')\n\n# Table to organize and show the information \ntable = TableLogger(columns='ID, Name, Key, Type, Platform, State, Private_IP', border=False)\n\nfor i in ec2.instances.all():\n instancedata = dict() \n instancedata['ID'] = i.id\n instancedata['Name'] = i.private_dns_name\n instancedata['Key'] = i.key_name\n instancedata['Type'] = i.instance_type\n instancedata['State'] = i.state['Name']\n instancedata['Private_IP'] = i.private_ip_address\n instancedata['Platform'] = i.platform\n\n # Show the information in table format\n table(instancedata['ID'], instancedata['Name'], instancedata['Key'], instancedata['Type'], instancedata['Platform'], instancedata['State'],instancedata['Private_IP'])\n" }, { "alpha_fraction": 0.3872714936733246, "alphanum_fraction": 0.47122547030448914, "avg_line_length": 38.9054069519043, "blob_id": "e64d0960e3f09bd6c9c79c5f7489e0b8c1f73246", "content_id": "7ea4b2f42812e7f966ea8530dcba246fe3eb0f51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2954, "license_type": "no_license", "max_line_length": 200, "num_lines": 74, "path": "/README.md", "repo_name": "carolinebrasil/analysis-buckets-n-instances", "src_encoding": "UTF-8", "text": "## Data analysis S3 and Ec2\nThis tool was created in Python3 to analyze informations of buckets in Amazon S3, showing about each bucket:\n - Name \n - Date of creation\n - Number of files\n - Total size (KB)\n - Last modified date\n - Price\n\n### Prerequisites \nBefore you continue, please have met the following requirements:\n\n* Create user in the IAM with permission AmazonS3FullAccess and configure the AWS credentials and region in your enviroment - see more in AWS documentation: [Configuration and credential file settings\n](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)\n```\n$ touch ~/.aws/credentials\n```\n```Credentials\n[default]\naws_access_key_id = YOUR_ACCESS_KEY_ID\naws_secret_access_key = YOUR_SECRET_ACCESS_KEY\n```\n```Config\n[default]\nregion = YOUR_PREFERRED_REGION\n```\n* Install the latest version of Python 3 and pip3\n* Windows, Linux and Mac OS supported\n\n### Install\nIn your terminal clone this repo:\n```\ngit clone https://github.com/carolinebrasil/analysis-buckets-n-instances.git\n\ncd analysis-buckets-n-instances\n```\nrun the following command:\n```\npip3 install -r requirements.txt\n```\n\n### How to use\n\n```\n$ python3 data-analysis-s3.py\n```\n\nExpected output:\n```\n+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+\n| Name | Creation date | Number of files | Total size (KB) | Last modified date | Price |\n|----------------------+----------------------+----------------------+----------------------+----------------------+----------------------|\n| challengeanalysis | 2020-06-26 | 5 | 1.662100 | 2020-06-26 | 0.000000 |\n| challengeanalysis2 | 2019-09-20 | 1 | 0.000000 | 2019-10-10 | 0.000000 |\n| firstpythonbucket | 2020-06-27 | 2 | 0.683600 | 2020-06-28 | 0.000000 |\n| secondpythonbucket | 2020-06-27 | 1 | 0.293000 | 2020-06-27 | 0.000000 |\n```\n\nor\n\n```\n$ python3 data-analysis-ec2.py\n```\n\nExpected output:\n```\n+---------------------+----------------------+----------------------+----------------------+----------------------+\n| Creation date | ID | Type | State | Private_IP |\n|---------------------+----------------------+----------------------+----------------------+----------------------|\n| 2020-07-19 18:06:32 | i-0d8fca075757d07e7 | t2.medium | running | 172.31.73.219 |\n| 2020-07-19 18:06:32 | i-0298f359163d99f24 | t2.medium | running | 172.31.73.135 |\n| 2020-07-19 18:06:32 | i-04648d0c2d5efe183 | t2.medium | running | 172.31.79.103 |\n\n```\n\n" } ]
4
kkast/cs184-final-project
https://github.com/kkast/cs184-final-project
259157f7db16ea8efced7b9e0dac5802138cdc9f
34bf69c8a6399b797ffa04da3c32a9cf2a137edb
8a8b67f4a8c7698a841c660635a0f57cabf38e36
refs/heads/master
2022-11-30T02:43:20.037079
2020-08-16T00:42:08
2020-08-16T00:42:08
286,829,979
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5759096741676331, "alphanum_fraction": 0.5922208428382874, "avg_line_length": 29.653846740722656, "blob_id": "8ae890c66aa767387e58681a088332e7b3dd70c9", "content_id": "586bfd039a64048f6b6d443f07fd540beacbf66b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1594, "license_type": "no_license", "max_line_length": 100, "num_lines": 52, "path": "/parseXml.py", "repo_name": "kkast/cs184-final-project", "src_encoding": "UTF-8", "text": "import xml.etree.ElementTree as ET\nroot = ET.parse('example.xml').getroot()\nprint (root)\nprint (root[11])\ni=0\nroot=root[11]\nel=None\nfor child in root:\n # print(type(child.attrib))\n # print(child.attrib['name'])\n # print(child.tag, child.attrib, i)\n if child.attrib['name'] == 'Q':\n el=child\n # print(child.tag, child.attrib)\n i+=1\nprint el\ncontours=[]\nfor child in el:\n if child.tag == 'contour':\n contours.append(child)\nprint (contours)\ncontours_parsed =[]\nfor c in contours:\n points =[]\n for child in c:\n points.append([float(child.attrib['x']), float(child.attrib['y']), int(child.attrib['on'])])\n # print(child.tag, child.attrib)\n # print ('end')\n contours_parsed.append(points)\nprint (contours_parsed)\ncontours_parsed_proccessed = []\nfor contour in contours_parsed:\n curr_contour = []\n for i in range(len(contour)):\n if contour[i][2] == 1:\n curr_contour.append(contour[i])\n if contour[i][2] == 0 :\n curr_contour.append(contour[i])\n if contour[(i+1)%len(contour)][2] == 0:\n x = float(contour[i][0] + contour[(i+1)%len(contour)][0]) / 2\n y = float(contour[i][1] + contour[(i+1)%len(contour)][1]) / 2\n curr_contour.append([x,y, 1])\n contours_parsed_proccessed.append(curr_contour)\n\nprint (contours_parsed_proccessed)\n\nfor contour in contours_parsed_proccessed:\n print('new contour')\n for p in contour:\n if p[2] == 0:\n print('myExample.moveTo({x}, {y})'.format(x=p[0], y=p[1]))\n print('end contour')\n" }, { "alpha_fraction": 0.6702508926391602, "alphanum_fraction": 0.6702508926391602, "avg_line_length": 16.375, "blob_id": "8c149f83af7e6b90a355ee1e2ef748ee129ad0f4", "content_id": "1ed14a165f9610bb7c8b2647fde985e5572b9459", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 48, "num_lines": 16, "path": "/main.py", "repo_name": "kkast/cs184-final-project", "src_encoding": "UTF-8", "text": "\nfrom fontTools import ttLib\n\n\ntt = ttLib.TTFont(\"FontAwesome.ttf\")\ntt.saveXML(\"FontAwesome.xml\")\n\n\n# from fontTools.ttLib import TTFont\n#\n# p = 'example.ttf'\n#\n# f = TTFont(p)\n# cmap = f.getBestCmap() # look up the encoding\n#\n# for char in sorted(cmap):\n# print(chr(char))\n" } ]
2
xufeng010203/ML
https://github.com/xufeng010203/ML
1293f941d329ecf00d48e288d9b498191a59568d
4452d29478ccd502a0fd618bafd55b3f6c74babc
40e48fea889620f57622d832b9d55e8a8d1d7abf
refs/heads/master
2023-07-08T02:42:45.416447
2021-07-25T05:28:52
2021-07-25T05:28:52
377,741,092
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5625, "avg_line_length": 15, "blob_id": "d4a47fb18ad4f04f76f04dee8435a010e52c66c1", "content_id": "bcc19eaaa0c7973217bc9f80e186e5e3fd33d659", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/first_commit.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "def fun():\n print(\"lallala\")\n" }, { "alpha_fraction": 0.39020979404449463, "alphanum_fraction": 0.4335664212703705, "avg_line_length": 15.272727012634277, "blob_id": "4cc1c2b48a540bd892b04a925b7ce641c875199e", "content_id": "a89a2155ee9203638899ffb9eb3fbb7cebb1c143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 927, "license_type": "no_license", "max_line_length": 33, "num_lines": 44, "path": "/alogorithm/10_二进制中的1的个数.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "''''''\n'''\n请实现一个函数,输入一个整数,输出该整数的二进制表示中1的个数\n例如:9表示成二进制时1001, 有2位是1, 因此输入9 输出2\n\n思路:\n 先判断二进制表示中最右边是不是1,\n 接着把输入的整数右移一位,再判断是不是1\n 这样每移动一位进行判断\n 直到整数变成0\n'''\n\n# class Solution:\n # def Number_of_1(self, n):\n # if n < 0:\n # n = n & 0xffffffff\n #\n # count = 0\n # while n:\n # if n & 1:\n # count += 1\n # n = n >> 1\n # return count\n # # print(n)\n\n\n\nclass Solution:\n def Num_of_1(self, n):\n if n < 0:\n n = n & 0xffffffff\n count = 0\n while n:\n if n & 1:\n count += 1\n n = n >> 1\n return count\n\n\n\n# s = Solution()\n# print(s.Number_of_1(9))\n\nprint(9 & 1)" }, { "alpha_fraction": 0.37637361884117126, "alphanum_fraction": 0.39217033982276917, "avg_line_length": 20.71641731262207, "blob_id": "706a3ba92c0601dc821a519ba616a04afdb09e44", "content_id": "136045dca57eb5446a1d27a982208facef24b5f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1456, "license_type": "no_license", "max_line_length": 45, "num_lines": 67, "path": "/01-反转链表.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "# # class Solution:\n# # def ReverseLinkList(self, node):\n# #\n# #\n# # if not node or node.next == None:\n# # return node\n# #\n# # pre = None\n# # while node:\n# # cur = node\n# # node = node.next\n# # cur.next = pre\n# # pre = node\n# #\n# # return pre\n# #\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n#\n# class Solution:\n# def MergeTwoLinkList(self, l1, l2):\n# if not l1 and l2:\n# return None\n# if not l1:\n# return l2\n# if not l2:\n# return l1\n#\n# head = ListNode(0)\n# cur = head\n# while l1 and l2:\n# if l1.val > l2.val:\n# head.next = l2\n# l2 = l2.next\n# else:\n# head.next = l1\n# l1 = l1.next\n# cur = cur.next\n#\n# if l1:\n# cur.next = l1\n# if l2:\n# cur.next = l2\n#\n# return cur\n\n\nclass Solution:\n def DeleteNode(self, head, node):\n if head == node:\n del node\n\n\n\n\n if node.next == None:\n while head:\n if head == node:\n head.next = None\n head = head.next\n else:\n node.val = node.next.val\n n_node = node.next\n node.next = n_node.next\n del n_node\n\n" }, { "alpha_fraction": 0.6086956262588501, "alphanum_fraction": 0.739130437374115, "avg_line_length": 12.800000190734863, "blob_id": "0eac36967d46853bbc53729f95416fd85653432d", "content_id": "e666a54c257b399b98dfe17e2e559ad1e1bd3a60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 29, "num_lines": 5, "path": "/alogorithm/12_打印1到n的最大的n位数.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "'''\n输入数字n,按顺序打印出从1到最大的n位十进制数。\n比如输入3, 打印出1,2,3,一直到最大的3位数即999\n大数问题\n'''\n" }, { "alpha_fraction": 0.26229506731033325, "alphanum_fraction": 0.3540983498096466, "avg_line_length": 13.571428298950195, "blob_id": "318184222cc8e206c27c87569937905105571796", "content_id": "412f95b23e32076d1816ad684bc1b212ea01e94f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "no_license", "max_line_length": 39, "num_lines": 21, "path": "/alogorithm/14_调整数组的顺序使奇数位于偶数前面.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "''''''\n\n\n\ndef Reorder(li):\n p1 = 0\n p2 = len(li) - 1\n\n while p1 < p2:\n if li[p1] % 2 != 0:\n p1 += 1\n elif li[p2] % 2 == 0:\n p2 -=1\n li[p1], li[p2] = li[p2], li[p1]\n\n\nif __name__ == '__main__':\n\n li = [1,2,3,4,6,5, 0, -1]\n Reorder(li)\n print(li)" }, { "alpha_fraction": 0.3416927754878998, "alphanum_fraction": 0.36050155758857727, "avg_line_length": 14.716049194335938, "blob_id": "04c2bc8526cd2d9ce6906fd13fa8a9682a02b473", "content_id": "b0aa1b169e8172854581078246373c908669955f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1426, "license_type": "no_license", "max_line_length": 47, "num_lines": 81, "path": "/alogorithm/11_实现一个函数.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "'''\n数值的整数次方\n考虑:\n输入的是整数,负数,零\n'''\n# def double_power(n):\n# \"\"\"\n# 求一个数的整数次方\n# :param n:\n# :return:\n# \"\"\"\n\nclass Solution:\n def Power(self, base, exponent):\n \"\"\"\n 实现函数的整数次方,、\n 考虑很多情况\n 先把乘方后的值算出来,\n 在根据输入的数字的正负号,进行判断\n :param base:\n :param exponent:\n :return:\n \"\"\"\n\n if base == 0:\n return False\n if exponent == 0:\n return 1\n\n res = 1.0\n for i in range(1, abs(exponent) + 1):\n res *= abs(base)\n\n\n if exponent < 0:\n if base > 0:\n return 1 / res\n else:\n return - 1 / res\n else:\n if base > 0:\n return res\n else:\n return -res\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n # if base == 0:\n # return False\n # if exponent == 0:\n # return 1\n # res = 1.0\n # for i in range(1, abs(exponent) + 1):\n # res *= abs(base)\n #\n # if exponent < 0:\n # if base > 0:\n # return 1 / res\n # else:\n # return -1 / res\n # else:\n # if base > 0:\n # return res\n # else:\n # return -res\n\n\n\n" }, { "alpha_fraction": 0.45673757791519165, "alphanum_fraction": 0.47375887632369995, "avg_line_length": 16.219512939453125, "blob_id": "f2b0c091902fb46e9bfb1243c4fcebe64a44b206", "content_id": "17a23fe8fb27ff59d4b8907979e95a6d2f74d667", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 799, "license_type": "no_license", "max_line_length": 49, "num_lines": 41, "path": "/alogorithm/01_快速排序.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "'''\n快速排序:\n 选择一个值:\n 把比这个值大的放在右侧\n 把比这个值小的放在左侧\n 递归调用\n'''\n\ndef quick_sort(arr, start, end):\n \"\"\"\n 一定要有递归终止条件\n :param arr:\n :param start:\n :param end:\n :return:\n \"\"\"\n\n if start >= end:\n return\n privot = arr[start]\n low = start\n high = end\n\n while low < high:\n while low < high and arr[high] >= privot:\n high -= 1\n arr[low] = arr[high]\n\n while low < high and arr[low] < privot:\n low += 1\n arr[high] = arr[low]\n arr[low] = privot\n\n quick_sort(arr, start, low - 1)\n quick_sort(arr, low + 1, end)\n\n\nif __name__ == '__main__':\n l = [6, 5, 4, 3, 2,1]\n quick_sort(l, 0, 5)\n print(l)" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 23.75, "blob_id": "096c5c3cabb9b6abd9ba64416313788c7278ce7e", "content_id": "6f24af2d06bf86628973f58ee953d596b6eefed8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 36, "num_lines": 4, "path": "/alogorithm/28_字符串的排列.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "# 输入一个字符串,按字典序打印出该字符串中字符的所有排列。\n# 例如输入字符串abc,\n# 则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,ba\n# c,bca,cab和cba。" }, { "alpha_fraction": 0.3584229350090027, "alphanum_fraction": 0.36200717091560364, "avg_line_length": 17.566667556762695, "blob_id": "872f95db85af08f48e45159f28702a01235640b4", "content_id": "8e930720d38573a0be7d0df032e50c4758b2921c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 41, "num_lines": 30, "path": "/alogorithm/15_链表中倒数第k个节点.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "# '''\n#\n# 输入一个链表,输出该链表中倒数第k个节点\n#\n# '''\n#\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n#\n#\n# def find_kth_o_tail(self, head, k):\n# \"\"\"\n# 查找链表中第k个节点\n# :param k:\n# :return:\n# \"\"\"\n# if not head or not k:\n# return None\n# count = 0\n# p = head\n# q = head\n# while count < k:\n# p = p.next\n# count += 1\n# while p:\n# q = q.next\n# p = p.next\n# return q.val\n\n" }, { "alpha_fraction": 0.41605839133262634, "alphanum_fraction": 0.49947863817214966, "avg_line_length": 16.10714340209961, "blob_id": "ae0e1ab06706b644f72d16c2f6dafe0be4ef814a", "content_id": "5538bd2efc83d5e243273ed5e2581c3ad5d62813", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1103, "license_type": "no_license", "max_line_length": 58, "num_lines": 56, "path": "/alogorithm/02_归并排序.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "'''\n\n归并排序\n:分治\n 84571362\n 8457 1362\n 84 57 13 62\n 8 4 5 7 1 3 6 2\n\n48 57 13 62\n4578 1236\n12345678\n'''\n\ndef merge(left, right):\n \"\"\"\n 合并两个有序数组\n :param left: arr\n :param right: arr\n :return:\n \"\"\"\n\n l, r = 0, 0\n result = []\n\n while l < len(left) and r < len(right):\n if left[l] < right[r]:\n \"\"\"\n 如果左边都比右边的小\n \"\"\"\n result.append(left[l])\n l += 1\n else:\n result.append(right[r])\n r += 1\n #如果左边的值都比右边的小,执行循环后,result就是left,然后要把右边right 和result相加\n #同理右边的值都比左边的小,\n result += left[l:]\n result += right[r:]\n return result\n\n\ndef merge_sort(li):\n if len(li) <= 1:\n return li\n #二分分解\n num = len(li) // 2\n left = merge_sort(li[:num])\n right = merge_sort(li[num:])\n return merge(left, right)\n\n\n\nalist = [54,26,93,17,77,31,44,55,20]\nsorted_alist = merge_sort(alist)\nprint(sorted_alist)\n\n" }, { "alpha_fraction": 0.3531951606273651, "alphanum_fraction": 0.38082900643348694, "avg_line_length": 20, "blob_id": "c78d5aad78c6f441792b2052652c79bee3ce52c7", "content_id": "1217648469904eeb8e1fa2385d2ed5b5317681c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1328, "license_type": "no_license", "max_line_length": 38, "num_lines": 55, "path": "/替换空格.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "\n\nclass Solution:\n def ReplaceSpace(self, ss):\n \"\"\"\n\n :param ss:\n :return:\n \"\"\"\n\n if not ss:\n return None\n\n #统计字符串中个空格\n count = 0\n for i in ss:\n if i == \" \":\n count += 1\n print(count)\n old_len = len(ss)\n new_len = old_len + count * 2\n\n #定义两个指针\n #p1指向原始字符串的末尾\n #p2指向新字符串的末尾\n p1 = old_len - 1\n p2 = new_len - 1\n\n #定义一个空字符串用来保存复制的字符产\n new_str = [' '] * new_len\n\n while p1 != p2:\n if ss[p1] != \" \":\n new_str[p2] = ss[p1]\n p1 -= 1\n p2 -= 1\n else:\n new_str[p2] = '%'\n new_str[p2 -1] = '0'\n new_str[p2- 2] = '2'\n p1 -=1\n p2 -=3\n\n #至此只有第一个空格前的字符没有复制\n for i in range(p1, -1, -1):\n new_str[i] = ss[i]\n print(new_str)\n #现在new_str是一个列表表\n #把列表转成字符串\n new_String = ''\n for i in new_str:\n\n new_String += i\n return new_String\n\ns = Solution()\nprint(s.ReplaceSpace('we are happy'))\n\n" }, { "alpha_fraction": 0.43169400095939636, "alphanum_fraction": 0.46994534134864807, "avg_line_length": 9.70588207244873, "blob_id": "8562791f0c80dcee884c471968ab112394858785", "content_id": "4ca193d834fb5a664bc62a1aa97b7f711654b471", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 37, "num_lines": 17, "path": "/alogorithm/09_斐波那契数列.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "'''\n\n递归和循环\n\n\n写一个函数,输入n,求斐波那契数列的第n项\n'''\n\n\ndef fibo(n):\n if n == 0:\n return 0\n if n == 1:\n return 1\n else:\n return fibo(n-1) + fibo(n -2)\nprint(fibo(5))\n\n" }, { "alpha_fraction": 0.34068137407302856, "alphanum_fraction": 0.41683366894721985, "avg_line_length": 16.785715103149414, "blob_id": "c91f75f4a6010fa4e7c76d762e3d0d5ecc325e70", "content_id": "589fc8596af8b638e12195dcd00b26aaec47f8b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 38, "num_lines": 28, "path": "/alogorithm/08_旋转数组的最小数字.py", "repo_name": "xufeng010203/ML", "src_encoding": "UTF-8", "text": "'''\n\n旋转数组\n前半部分时递增 后面部分是递增\n{3, 4, 5, 1, 2} 是{1, 2,3, 4, 5}的一个旋转数组\n输出 数组中最小数字 1\n利用 递增特性\n\n'''\n\ndef min1(li):\n p1 = 0\n p2 = len(li) - 1\n\n\n while p1 < p2:\n mid = (p1 + p2) // 2\n if p2 - p1 == 1:\n return li[p2]\n else:\n if li[mid] >= li[p1]:\n #当中间值大于左边的值时,说明中间值在左边\n p1 = mid\n elif li[mid] < li[p2]:\n ##当中间值小于左边的值时,说明中间值在右边\n p2 = mid\n return li[p2]\nprint(min1([8,9,1,2,3,4,5]))\n\n" } ]
13
vivekpuri95/AWS-Scripts
https://github.com/vivekpuri95/AWS-Scripts
9bdf03b34ff19559adb8cee66d38b56b76cc17a1
e71f1ab27c9a894f3b187aacfcf198da47bfbad7
f88f28050023a130efb7ff7a4876b91aaa2d0c8a
refs/heads/master
2022-04-30T10:33:49.767281
2022-03-08T04:24:28
2022-03-08T04:24:28
176,273,429
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6396462917327881, "alphanum_fraction": 0.6551215648651123, "avg_line_length": 40.121212005615234, "blob_id": "e7608658937df179b8d7f53622bb5221fb9abb48", "content_id": "353e05cdc98a7155590bd6f5b2253c614d6d03d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 132, "num_lines": 33, "path": "/FetchInstances.py", "repo_name": "vivekpuri95/AWS-Scripts", "src_encoding": "UTF-8", "text": "import boto3,datetime,filecmp,os\nfrom shutil import copyfile\nfrom shutil import move\nec2client=boto3.client('ec2')\nasclient = boto3.client('autoscaling')\ncount,servers = 3,[]\ndt = datetime.datetime.now().strftime(\"%Y-%m-%d-%H%M%S\")\nfilename = \"haproxy.cfg-\" + dt\ncopyfile(\"haproxy.tmpt\", filename)\nf = open(filename, 'a')\nresponse = asclient.describe_auto_scaling_groups(AutoScalingGroupNames=['AppASLive'])['AutoScalingGroups']\nfor instance in response:\n for id in instance['Instances']:\n if id['LifecycleState'] == \"InService\" :\n ip = ec2client.describe_instances(InstanceIds=[id['InstanceId']])['Reservations'][0]['Instances'][0]['PrivateIpAddress']\n servers.append(ip)\n f.write(\"server web\" + str(count) + \" \" + ip + \":8888 check fall 4 rise 2\\n\") # My application is running on port 8888\n count+=1\nf.close()\ndifference=filecmp.cmp('haproxy.cfg', filename)\nprint difference\nif filecmp.cmp('haproxy.cfg', filename):\n os.remove(filename)\nelse:\n command = \"/usr/sbin/haproxy -f \" + filename + \" -c\"\n confcheck = os.system(command)\n if confcheck == 0 :\n try:\n move(\"haproxy.cfg\",\"backup/haproxy.cfg-\"+dt)\n move(filename, \"haproxy.cfg\")\n os.system(\"service haproxy reload\")\n except:\n print \"Error moving haproxy.cfg to backup folder\"\n" }, { "alpha_fraction": 0.5736773014068604, "alphanum_fraction": 0.579361617565155, "avg_line_length": 39.122806549072266, "blob_id": "612e4c06b2afb8f2d41a3b00a0ce709e49e89ea0", "content_id": "6ca346d1598557357e35e30a329e240a4819b7a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2287, "license_type": "no_license", "max_line_length": 72, "num_lines": 57, "path": "/AMICreation.py", "repo_name": "vivekpuri95/AWS-Scripts", "src_encoding": "UTF-8", "text": "import boto3, datetime\nfrom datetime import date\nfrom datetime import datetime\nfrom botocore.exceptions import ClientError\n\napplication-server = {\n 'prefix': \"ApplicationServer-LiveAMI\", # Name of AMI\n 'InstanceID': \"<on-demand-instance-id>\",\n 'Region': \"<on-demand-instance-region>\",\n 'delBefore': 2 # Number of AMIs to keep\n }\nstrOfObjs = [application-server]\n\ndef createAMI(name, InstanceID,ec2):\n try:\n ec2.create_image(InstanceId=InstanceID, Name=name,NoReboot=True)\n except ClientError as e:\n print(\"Error creating AMI for \"+ name)\n print(e.response['Error']['Message'])\n return (\"Error creating AMI for \"+ name)\n else:\n print(\"creating AMI for \"+ name)\n return(name)\n\ndef lambda_handler(event, context):\n for i in strOfObjs:\n prefix = i['prefix']\n InstanceID = i['InstanceID']\n Region = i['Region']\n delBefore = i['delBefore']\n today = date.today()\n date_format = \"%Y/%m/%d\"\n today=today.strftime('%Y/%m/%d')\n a = datetime.strptime(today, date_format)\n time = datetime.now()\n name = prefix + time.strftime(\"-%Y%m%d%H%M\")\n ec2 = boto3.client('ec2', region_name = Region)\n result = createAMI(name, InstanceID, ec2)\n createList.append(result)\n images=ec2.describe_images(Owners=['self'])\n for currImage in images['Images']:\n if currImage['Name'].startswith(prefix):\n amiId=currImage['ImageId']\n creationDate=currImage['CreationDate']\n creationDate=creationDate[:10]\n creationDate=creationDate.replace(\"-\", \"/\")\n b = datetime.strptime(creationDate, date_format)\n diff = a-b\n if diff.days > delBefore:\n print(\"\\tRemoving Image:\"+currImage['Name'])\n deleteList.append(currImage['Name'])\n ec2.deregister_image(ImageId=amiId)\n blockDevices = currImage['BlockDeviceMappings']\n for currBlock in blockDevices:\n if 'SnapshotId' in currBlock['Ebs']:\n snapId = currBlock['Ebs']['SnapshotId']\n ec2.delete_snapshot(SnapshotId=snapId)\n" }, { "alpha_fraction": 0.717258870601654, "alphanum_fraction": 0.7238578796386719, "avg_line_length": 40.914894104003906, "blob_id": "2881ebdf9e4478a45074b638d4fc7da628dd8900", "content_id": "e870aac251e69dfb0a572deb7cd32780ebd0e9b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1970, "license_type": "no_license", "max_line_length": 201, "num_lines": 47, "path": "/UpdateLaunchTemplate.py", "repo_name": "vivekpuri95/AWS-Scripts", "src_encoding": "UTF-8", "text": "import boto3\nfrom datetime import date\nfrom datetime import datetime\nfrom botocore.exceptions import ClientError\n\ndef lambda_handler(event, context):\n\n prefix = \"ApplicationServer-LiveAMI\"\n Region = \"<launch-template-region>\"\n launchTemplate = '<launch-template-id>'\n ec2 = boto3.client('ec2', region_name = Region)\n \n #get AMI IDs by prefix and import time string as datetime object\n try:\n \timages=ec2.describe_images(Owners=['self'])\n except:\n \tprint \"Error getting current images\"\n \n amiList=[]\n for currImage in images['Images']:\n \tif currImage['Name'].startswith(prefix):\n \t\tamiList.append({'ImageId':currImage['ImageId'],'CreationDate':datetime.strptime(currImage['CreationDate'], '%Y-%m-%dT%H:%M:%S.000Z')}) \n \t\t\n #sort AMI Id's by date\n amiList.sort(key=lambda x: x['CreationDate'],reverse=True)\n #ami id of latest AMI\n amiID=amiList[0]['ImageId']\n \n #get Version for default launchTemplate\n try:\n \tdescribe_template_response = ec2.describe_launch_template_versions(LaunchTemplateId=launchTemplate,Filters=[{'Name':'is-default-version','Values':['true']}])\n except:\n \tprint \"Error getting default version number for template\"\n defaultVersionNumber = describe_template_response['LaunchTemplateVersions'][0]['VersionNumber']\n \n #create new templateversion with latestversion and \n try:\n \tcreate_template_response = ec2.create_launch_template_version(LaunchTemplateId=launchTemplate,VersionDescription=amiID,SourceVersion=str(defaultVersionNumber),LaunchTemplateData={'ImageId':amiID})\n except:\n \tprint \"Error creating new launch tempate\"\n newVersionNumber = create_template_response['LaunchTemplateVersion']['VersionNumber']\n \n #set new version as default\n try:\n \tmodify_template_response = ec2.modify_launch_template(LaunchTemplateId=launchTemplate,DefaultVersion=str(newVersionNumber))\n except:\n \tprint \"Error setting new version as default\"\n" }, { "alpha_fraction": 0.43001314997673035, "alphanum_fraction": 0.43791136145591736, "avg_line_length": 33.530303955078125, "blob_id": "95d4a5841cd03c8188d057ff06143fbd3fc1ae7d", "content_id": "d7cc96f821f1575b7dc85d3b653f7330ad8bd3f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2279, "license_type": "no_license", "max_line_length": 88, "num_lines": 66, "path": "/ASCPUCustomMetric.py", "repo_name": "vivekpuri95/AWS-Scripts", "src_encoding": "UTF-8", "text": "import boto3\nimport sys\nfrom datetime import datetime, timedelta\nfrom operator import itemgetter\n\ndef lambda_handler(event, context):\n now = datetime.utcnow()\n past = now - timedelta(minutes=10)\n future = now + timedelta(minutes=10)\n ec2client = boto3.client('ec2')\n cwclient = boto3.client('cloudwatch')\n custom_filter = [{\n 'Name':'tag:AppASLive', \n 'Values': ['true']}]\n instances = ec2client.describe_instances(Filters=custom_filter)\n TotalCPU = 0\n count = 0\n for instance in instances['Reservations']:\n for instanceid in instance['Instances']:\n if instanceid['State']['Name'] == \"running\" :\n try :\n results = cwclient.get_metric_statistics(\n Namespace='AWS/EC2',\n MetricName='CPUUtilization',\n Dimensions=[\n {\n 'Name': 'InstanceId',\n 'Value': instanceid['InstanceId']\n },\n ],\n StartTime=past,\n EndTime=future,\n Period=60,\n Statistics=[\n 'Average',\n ],\n Unit='Percent'\n )\n datapoints = results['Datapoints']\n last_datapoint = sorted(datapoints, key=itemgetter('Timestamp'))[-1]\n utilization = last_datapoint['Average']\n count+=1\n except:\n utilization=0\n \n TotalCPU += utilization\n try:\n AvgCPU = TotalCPU/count\n response = cwclient.put_metric_data(\n Namespace='AppASLive',\n MetricData=[\n {\n 'MetricName': 'AverageCPUUtilization',\n 'Dimensions': [\n {\n 'Name': 'CPUUtilization',\n 'Value': 'AppASLiveCPU'\n },\n ],\n 'Value': AvgCPU,\n 'Unit': 'Percent'\n },\n ]\n )\n except:\n print \"No instances found with above mentioned Tag\"\n" } ]
4
chromefan/nlp
https://github.com/chromefan/nlp
ed059e1830fd7ec25859e7c57c41c66667d2d04a
b0a2ce433b61adec89d6771883635edd78295898
c122f3146a17e70872855c5d5541472f973109e5
refs/heads/master
2021-09-06T01:46:49.387390
2018-02-01T11:43:11
2018-02-01T11:43:11
118,726,453
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6523809432983398, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 14, "blob_id": "2fd6a8ce3744160db8cd5014be97b1f786c6dffa", "content_id": "4921c2a13b7eddf82ff255eb10146c37a0a0f7dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 29, "num_lines": 14, "path": "/random.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport pylab\nmy_list=[]\nfor counter in range(10):\n my_list.append(counter*2)\nprint my_list\nprint len(my_list)\n\n#now plot the list\n\npylab.plot(my_list)\npylab.show()\n" }, { "alpha_fraction": 0.45255473256111145, "alphanum_fraction": 0.540145993232727, "avg_line_length": 22, "blob_id": "22562a79457b73d56453fbef8cc8b877678add3a", "content_id": "73c21b0f838d615daed58e237e1c50741a18d9f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 141, "license_type": "no_license", "max_line_length": 30, "num_lines": 6, "path": "/ai/nbclass.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2018/1/24 上午11:23\n# @Author : Mat\n# @Email : [email protected]\n# @File : nbclass.py\n# @Software: PyCharm" }, { "alpha_fraction": 0.28947368264198303, "alphanum_fraction": 0.5263158082962036, "avg_line_length": 11.666666984558105, "blob_id": "ddf0be1dc240a5efc574e5c57dd07ca41c12226e", "content_id": "411e973742f25b3f829ffc22ad9061f09498477a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 76, "license_type": "no_license", "max_line_length": 22, "num_lines": 6, "path": "/test.php", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "<?php\n\n $str = '2016-08-10';\n $str2 = '2017-07-10';\n\n var_dump($str>$str2);\n" }, { "alpha_fraction": 0.6350710988044739, "alphanum_fraction": 0.6682464480400085, "avg_line_length": 20.200000762939453, "blob_id": "edc45ec859452ce5dd6e27ee41b9084f95b5398b", "content_id": "41e9f9e5221cdfd3ec333849ac2d063969f8696f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/ai/word2vec.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "#encoding=utf-8\nfrom gensim.models import word2vec\n\nimport sys\n\nsentences = [['我哎', '你'], ['他们', '我爱你']]\nmodel=word2vec.Word2Vec(sentences, min_count=1)\n\nfor i in model.most_similar(u\"我你\"):\n print (i[0],i[1])" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 10, "blob_id": "4b355d4d1b7469eb109d736f51df56be9e94b847", "content_id": "9c79aac5cdeb80efb27b4b380446aa9fd3fad134", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 52, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "# nlp\n自然语言处理、机器学习练习项目\n" }, { "alpha_fraction": 0.6834532618522644, "alphanum_fraction": 0.6906474828720093, "avg_line_length": 22, "blob_id": "385578ccafd52d651833431f1dc0ca05b5a957ab", "content_id": "abb1b9dd6bf74d546fdd3408312d03102d372cfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 169, "license_type": "no_license", "max_line_length": 61, "num_lines": 6, "path": "/test.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "#!/Users/luohuanjun/Applications/anaconda/anaconda/bin/python\n# -*- coding: UTF-8 -*-\n# 导入模块\nfrom wxpy import *\n# 初始化机器人,扫码登陆\nbot = Bot()\n\n" }, { "alpha_fraction": 0.7348586916923523, "alphanum_fraction": 0.7469717264175415, "avg_line_length": 32.818180084228516, "blob_id": "d788b56296e5c040a08713406e26261b8ff8ed41", "content_id": "163b00c98ecadda6bba346113b2981045df71cee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 875, "license_type": "no_license", "max_line_length": 189, "num_lines": 22, "path": "/ai/nltk-test.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "# encoding=utf-8\n\nimport nltk\nfrom nltk.corpus import names\nimport random\n\ndef gender_features(word): #特征提取器\n return {'last_letter': word[-1]} #特征集就是最后一个字母\n\nnames = [(name,'male') for name in names.words('/Users/luohuanjun/python/nlp/ai/data/male.txt')]+[(name,'female') for name in names.words('/Users/luohuanjun/python/nlp/ai/data/female.txt')]\nrandom.shuffle(names)#将序列打乱\n\nfeatures = [(gender_features(n),g) for (n,g) in names]#返回对应的特征和标签\n\ntrain, test = features[500:],features[:500] #训练集和测试集\nclassifier = nltk.NaiveBayesClassifier.train(train) #生成分类器\n\nprint('Neo is a', classifier.classify(gender_features('Neo')))#分类\n\nprint(nltk.classify.accuracy(classifier,test)) #测试准确度\n\nclassifier.show_most_informative_features(5)#得到似然比,检测对于哪些特征有用" }, { "alpha_fraction": 0.5010183453559875, "alphanum_fraction": 0.5152749419212341, "avg_line_length": 20.34782600402832, "blob_id": "e224235a0bf9e435541b35c737122f639c2f12cf", "content_id": "5ac210206a1c317d480cab7035aeebf68c6d9c86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 69, "num_lines": 46, "path": "/mysql.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport pymysql\n\n# 连接配置信息\nconfig = {\n 'host': '127.0.0.1',\n 'port': 3306,\n 'user': 'root',\n 'password': 'Luohj@2017',\n 'db': 'cezi',\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor,\n}\n\n\n\n\n\ndef select(table):\n list = [0]\n db = pymysql.connect(**config)\n cur = db.cursor()\n # SQL 插入语句\n sql = \"SELECT * FROM \" + table\n cur.execute(sql)\n results = cur.fetchall()\n for textClass in results:\n catename = textClass['cate_name']\n catekey = textClass['cate_key']\n sql = \"SELECT * FROM text_set WHERE cate_key = '\"+catekey+\"'\"\n cur.execute(sql)\n text_sets = cur.fetchall()\n for texts in text_sets:\n words = texts['text']\n print(words)\n exit()\n db.close()\n return results\n\n\n\nif (__name__ == '__main__'):\n text_class = select('text_class')\n print(text_class)\n" }, { "alpha_fraction": 0.6161863803863525, "alphanum_fraction": 0.6266094446182251, "avg_line_length": 29.203702926635742, "blob_id": "496261f981e1ecb7bd4e9fc508b9af6caa55c769", "content_id": "3833875ef3584f442a678cdfdd7a3de7a3bd4788", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1645, "license_type": "no_license", "max_line_length": 69, "num_lines": 54, "path": "/ai/web.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2018/1/25 下午9:00\n# @Author : Mat\n# @Email : [email protected]\n# @File : web.py\n\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport json\nfrom tornado.options import define, options\n\nfrom nlp.NBclassifier import NBclassifier\nfrom words.Words import Words\n\ndefine(\"port\", default=8000, help=\"run on the given port\", type=int)\n\n\nclass IndexHandler(tornado.web.RequestHandler):\n def data_received(self, chunk):\n pass\n\n def get(self):\n text = self.get_argument('text', '')\n cut_word = self.get_argument('cut_word', 0)\n word = Words()\n word_str = word.cut_words(text)\n\n if int(cut_word) == 1:\n result = {'msg': 'ok', 'data': word_str}\n result = json.dumps(result, ensure_ascii=False)\n self.write(result)\n return\n\n clf_path = \"./datasets/trainModel/clf.m\"\n vec_path = \"./datasets/trainModel/vec.m\"\n # 创建NB分类器\n nbclassifier = NBclassifier(clf_path, vec_path)\n data_list = [word_str]\n predictList = nbclassifier.predict(data_list)\n predictList = list(predictList)\n predict_class = \"\".join(predictList)\n result = {'msg': 'ok', 'data': predict_class}\n result = json.dumps(result, ensure_ascii=False)\n self.write(result)\n\n\nif __name__ == \"__main__\":\n tornado.options.parse_command_line()\n app = tornado.web.Application(handlers=[(r\"/nlp\", IndexHandler)])\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n" }, { "alpha_fraction": 0.4957575798034668, "alphanum_fraction": 0.4981818199157715, "avg_line_length": 24.75, "blob_id": "4053160f8ff02e131a3c423d479ea2b28329d10e", "content_id": "f8d7ae65ea76695f73a9540c2eb95e86e79aae60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "no_license", "max_line_length": 60, "num_lines": 32, "path": "/ai/words/Words.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "# encoding=utf-8\nimport jieba\n\n\nclass Words:\n dictPath = ''\n\n def __init__(self):\n self.dictPath = './data/'\n\n def cut_words(self, text):\n jieba.load_userdict(self.dictPath + \"userdict.txt\")\n stopwords_file = self.dictPath + \"stop_words.txt\"\n stop_f = open(stopwords_file, \"r\", encoding='utf-8')\n stop_words = list()\n for line in stop_f.readlines():\n line = line.strip()\n if not len(line):\n continue\n stop_words.append(line)\n stop_f.close()\n\n seg_list = jieba.cut(text, cut_all=False) # 默认是精确模式\n\n outstr = ''\n for word in seg_list:\n if word not in stop_words:\n if word != '\\t':\n outstr += word\n outstr += \" \"\n\n return outstr\n\n" }, { "alpha_fraction": 0.5901012420654297, "alphanum_fraction": 0.5950506329536438, "avg_line_length": 30.524822235107422, "blob_id": "cbf26716ccdfff8b731424eda495768481c49cdc", "content_id": "31bc18e57f315f29c2385f0049c2faa6b1468d3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4851, "license_type": "no_license", "max_line_length": 110, "num_lines": 141, "path": "/ai/sknbtest.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "#!/Users/luohuanjun/Applications/anaconda/anaconda/bin/python\n# encoding=utf-8\n'''\nCreated on 2016年6月25日\n\n@author: lenovo\n'''\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport os\nimport re\nimport random\nimport jieba\nimport joblib\nimport json\nfrom tokenize import Ignore\n\n\nclass NBclassifier:\n def __init__(self, clf_path=None, vec_path=None):\n \"\"\"\n 创建对象时完成的初始化工作,判断分类器与vector路径是否为空,\n 若为空则创建新的分类器与vector,否则直接加载已经持久化的分类器与vector。\n \"\"\"\n if clf_path is None or vec_path is None:\n self.clf = MultinomialNB()\n self.vec = TfidfVectorizer()\n else:\n self.clf = joblib.load(clf_path)\n self.vec = joblib.load(vec_path)\n\n # 保存模型\n def save_model(self, clf_path=\"./datasets/trainModel/clf.m\", vec_path=\"./datasets/trainModel/vec.m\"):\n joblib.dump(self.clf, clf_path)\n joblib.dump(self.vec, vec_path)\n\n # 从文件夹中加载文本\n def load_texts(self, textPath):\n dirList = os.listdir(textPath)\n dataList = []\n labelList = []\n for dir in dirList:\n fileList = os.listdir(textPath + '/' + dir)\n for filename in fileList:\n line = open(textPath + u'/' + dir + u'/' + filename, encoding='utf-8', errors='ignore').read()\n line = re.sub(u'\\t|\\n', u'', line)\n if line != u'':\n dataList.append(line)\n labelList.append(dir)\n # print(filename)\n dataList = self.jieba_split(dataList)\n return dataList, labelList\n\n # 载入数据集\n @staticmethod\n def load_data(dataPath):\n dataList = []\n labelList = []\n for line in open(dataPath, encoding='utf-8').readlines():\n lineArray = line.split('||')\n if (len(lineArray) == 2):\n labelList.append(lineArray[0])\n dataList.append(lineArray[1])\n print('长度是{0}'.format(len(dataList)))\n return dataList, labelList\n\n # 随机生成训练样本与测试样本\n @staticmethod\n def generate_sample(dataList, labelList, trainPath, testPath):\n # 取30%作为测试集\n RATE = 0.3\n listLen = len(dataList)\n testLen = int(RATE * listLen)\n\n trainDir = open(trainPath, 'w', encoding='utf-8')\n testDir = open(testPath, 'w', encoding='utf-8')\n indexList = random.sample([i for i in range(listLen)], listLen)\n\n for item in indexList[:testLen]:\n testDir.write(labelList[item] + '||' + dataList[item])\n testDir.write('\\n')\n testDir.flush()\n for item in indexList[testLen:]:\n trainDir.write(labelList[item] + '||' + dataList[item])\n trainDir.write('\\n')\n trainDir.flush()\n\n # ds\n # 结巴分词\n\n @staticmethod\n def jieba_split(data):\n result = []\n # 首先利用结巴分词\n for content in data:\n line = ' '.join(jieba.cut(content))\n result.append(line)\n return result\n\n # 训练数据\n def train(self, dataList, labelList):\n # 训练模型首先需要将分好词的文本进行向量化,这里使用的TFIDF进行向量化\n self.clf.fit(self.vec.fit_transform(dataList), labelList)\n self.save_model()\n\n # 预测数据\n def predict(self, dataList, labelList):\n\n data = self.vec.transform(dataList)\n predictList = self.clf.predict(data)\n return predictList\n\n # 计算准确率\n @staticmethod\n def cal_accuracy(labelList, predictList):\n rightCount = 0\n if len(labelList) == len(predictList):\n for i in range(len(labelList)):\n if labelList[i] == predictList[i]:\n rightCount += 1\n print('准确率为:%s' % (rightCount / float(len(labelList))))\n\n\nif __name__ == '__main__':\n # 创建NB分类器\n nbclassifier = NBclassifier()\n # 数据集地址及生成的训练集与测试集地址\n # dataPath = u'./datasets/docsets'\n trainPath = u'./datasets/trainsets/trainData.txt'\n testPath = u'./datasets/testsets/testData.txt'\n # dataList, labelList = nbclassifier.load_texts(dataPath)\n # nbclassifier.generate_sample(dataList, labelList, trainPath, testPath)\n\n # 载入训练集与测试集\n dataList, labelList = nbclassifier.load_data(trainPath)\n testData, testLabel = nbclassifier.load_data(testPath)\n # 训练并预测分类正确性\n\n nbclassifier.train(dataList, labelList)\n predictList = nbclassifier.predict(testData, testLabel)\n nbclassifier.cal_accuracy(predictList, testLabel)\n" }, { "alpha_fraction": 0.5401069521903992, "alphanum_fraction": 0.5523300170898438, "avg_line_length": 22.799999237060547, "blob_id": "77a41f38c219bdbde760bf647d2217c1caa305cd", "content_id": "34aceea7c1de18b4d199cd9534ebaff62a5f85da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 74, "num_lines": 55, "path": "/ai/traindata.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\n\n\nimport pymysql\nfrom words.Words import Words\n\n# 连接配置信息\nconfig = {\n 'host': '127.0.0.1',\n 'port': 3306,\n 'user': 'root',\n 'password': 'Luohj@2017',\n 'db': 'cezi',\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor,\n}\n\n\n# 生成训练样本\n\ndef generate_sample(train_path):\n train_dir = open(train_path, 'w', encoding='utf-8')\n word = Words()\n db = pymysql.connect(**config)\n cur = db.cursor()\n # SQL 插入语句\n sql = \"SELECT * FROM text_class\"\n cur.execute(sql)\n results = cur.fetchall()\n for textClass in results:\n cate_name = textClass['cate_name']\n cate_key = textClass['cate_key']\n sql = \"SELECT * FROM text_set WHERE cate_key = '\" + cate_key + \"'\"\n cur.execute(sql)\n text_sets = cur.fetchall()\n words_str = ''\n num = 0\n for texts in text_sets:\n text = texts['text']\n words_str += \" \" + word.cut_words(text)\n num += 1\n\n train_dir.write(cate_name + '||' + words_str)\n train_dir.write('\\n')\n train_dir.flush()\n print(cate_name, num)\n\n db.close()\n return results\n\n\nif __name__ == '__main__':\n trainPath = u'./datasets/trainsets/trainData.txt'\n text_class = generate_sample(trainPath)\n print(text_class)\n" }, { "alpha_fraction": 0.7017543911933899, "alphanum_fraction": 0.7067669034004211, "avg_line_length": 23.9375, "blob_id": "b8d1803d78e686f8ca56ca77629d1ea7b1c523fd", "content_id": "af72c0c8d834ab43d6e31bde63f6f981fc190151", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/npl.py", "repo_name": "chromefan/nlp", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- encoding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals\nimport json\nimport requests\n\n\nSENTIMENT_URL = 'http://api.bosonnlp.com/sentiment/analysis'\n# 注意:在测试时请更换为您的API Token\nheaders = {'X-Token': 'YOUR_API_TOKEN'}\n\ns = ['他是个傻逼', '美好的世界']\ndata = json.dumps(s)\nresp = requests.post(SENTIMENT_URL, headers=headers, data=data.encode('utf-8'))\n\nprint(resp.text)\n" } ]
13
QuantumOverture/CommunityConnect
https://github.com/QuantumOverture/CommunityConnect
a7e8403c4624e81e12d2d524b7af0b8231423a47
52d2461ddb23eaf4798833944672460ab8ace6f2
47bf9b57a246b4f09e94127f40b51c9211c8d9d8
refs/heads/main
2023-06-05T01:41:38.426258
2021-06-26T08:11:30
2021-06-26T08:11:30
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6630105972290039, "alphanum_fraction": 0.6777609586715698, "avg_line_length": 36.911766052246094, "blob_id": "7cbc07695fac25e4eeee67b2175ba424cd501da5", "content_id": "4a2e89437b53facd399d9239ce62dfd78d1da505", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2644, "license_type": "no_license", "max_line_length": 85, "num_lines": 68, "path": "/server.py", "repo_name": "QuantumOverture/CommunityConnect", "src_encoding": "UTF-8", "text": "from flask import Flask,redirect,render_template\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom werkzeug.security import generate_password_hash, check_password_hash\r\n\r\napp = Flask(__name__)\r\n\r\napp.config ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///MainData.sqlite3'\r\n\r\nSQLALCHEMY_BINDS = {\r\n 'ImamData': 'sqlite:///ImamData.sqlite3',\r\n 'Annoucements': 'sqlite:///Annoucements.sqlite3',\r\n 'QuestionDatabase': 'sqlite///Questions.sqlite3'\r\n}\r\n\r\ndatabase = SQLAlchemy(app)\r\nclass MainImamData(database.Model):\r\n __bind_key__ = 'ImamData'\r\n DataID = database.Column(database.Integer, primary_key = True)\r\n UserName = database.Column(database.String(100))\r\n Password = database.Column(database.String(100))\r\n MasjidLocation = database.Column(database.String(100))\r\n \r\n def __init__(self, Username, Password, MasjidLocation):\r\n self.UserName = Username\r\n self.Password = generate_password_hash(Password)\r\n self.MasjidLocation = MasjidLocation\r\n\r\nclass Annoucements(database.Model):\r\n __bind_key__ = 'Annoucements'\r\n DataID = database.Column(database.Integer, primary_key = True)\r\n ImamOwnership = database.Column(database.String(100))\r\n AnnouncementText = database.Column(database.String(500))\r\n InactiveOrActive = database.Column(database.Boolean)\r\n \r\n def __init__(self, ImamOwnership, AnnouncementText):\r\n self.ImamOwnership = ImamOwnership\r\n self.AnnouncementText = AnnouncementText\r\n self.InactiveOrActive = True # True -> active False -> inactive\r\n\r\nclass QuestionDatabase(database.Model):\r\n __bind_key__ = 'QuestionDatabase'\r\n DataID = database.Column(database.Integer, primary_key = True)\r\n QuestionText = database.Column(database.String(200))\r\n SenderNumber = database.Column(database.String(100))\r\n ImamUsername = database.Column(database.String(100))\r\n AnsweredOrUnAnswered = database.Column(database.Boolean)\r\n def __init__(self, QuestionText,SenderNumber, ImamUsername):\r\n self.QuestionText = QuestionText\r\n self.SenderNumber = SenderNumber # In this format: \"+1 4078763333\"\r\n self.ImamUsername = ImamUsername\r\n self.AnsweredOrUnAnswered = False # False -> Unanswered True -> Answered\r\n \r\n \r\[email protected]('/')\r\ndef LoginLandingPage(): # Kabir\r\n return render_template() # Returning the html file we got from the front end team\r\n \r\[email protected]('/ImamWebView')\r\ndef ImamWebView():\r\n pass # Kabir\r\n\r\[email protected]('/Whatsappenpoint')\r\ndef Whatsappenpoint():\r\n pass # Ismail\r\n \r\nif __name__ == '__main__':\r\n database.create_all()\r\n application.run()" }, { "alpha_fraction": 0.51631760597229, "alphanum_fraction": 0.5387238264083862, "avg_line_length": 41.98952865600586, "blob_id": "d1155794ae0220692f401e3f0613e0957864590f", "content_id": "1dbf6884aa5be22e23a05906bee119ad23d3b6c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8212, "license_type": "no_license", "max_line_length": 140, "num_lines": 191, "path": "/server(ismail).py", "repo_name": "QuantumOverture/CommunityConnect", "src_encoding": "UTF-8", "text": "from flask import Flask,redirect,render_template,request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\n# Whatsapp libraries\nimport os\nfrom twilio.rest import Client\n\n\napp = Flask(__name__)\n\napp.config ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///MainData.sqlite3'\n\napp.config['SQLALCHEMY_BINDS'] = {\n 'ImamData': 'sqlite:///ImamData.sqlite3',\n 'Annoucements':'sqlite:///Annoucements.sqlite3',\n 'QuestionDatabase': 'sqlite:///Questions.sqlite3'\n}\n\ndatabase = SQLAlchemy(app)\nclass MainImamData(database.Model):\n __bind_key__ = 'ImamData'\n DataID = database.Column(database.Integer, primary_key = True)\n UserName = database.Column(database.String(100))\n Password = database.Column(database.String(100))\n MasjidLocation = database.Column(database.String(100))\n \n def __init__(self, Username, Password, MasjidLocation):\n self.UserName = Username\n self.Password = generate_password_hash(Password)\n self.MasjidLocation = MasjidLocation\n\nclass Annoucements(database.Model):\n __bind_key__ = 'Annoucements'\n DataID = database.Column(database.Integer, primary_key = True)\n ImamOwnership = database.Column(database.String(100))\n AnnouncementText = database.Column(database.String(500))\n InactiveOrActive = database.Column(database.Boolean)\n \n def __init__(self, ImamOwnership, AnnouncementText):\n self.ImamOwnership = ImamOwnership\n self.AnnouncementText = AnnouncementText\n self.InactiveOrActive = True # True -> active False -> inactive\n\nclass QuestionDatabase(database.Model):\n __bind_key__ = 'QuestionDatabase'\n DataID = database.Column(database.Integer, primary_key = True)\n QuestionText = database.Column(database.String(200))\n SenderNumber = database.Column(database.String(100))\n ImamUsername = database.Column(database.String(100))\n AnsweredOrUnAnswered = database.Column(database.Boolean)\n ImamAnswer = database.Column(database.String(500))\n def __init__(self, QuestionText,SenderNumber, ImamUsername):\n self.QuestionText = QuestionText\n self.SenderNumber = SenderNumber # In this format: \"+14078763333\"\n self.ImamUsername = ImamUsername\n self.AnsweredOrUnAnswered = False # False -> Unanswered True -> Answered\n self.ImamAnswer = \"\"\n \n \[email protected]('/')\ndef LoginLandingPage(): # Kabir\n return render_template() # Returning the html file we got from the front end team\n \[email protected]('/ImamWebView')\ndef ImamWebView():\n pass # Kabir\n\n\n\n\[email protected]('/Whatsappenpoint',methods=[\"GET\",\"POST\"])\ndef Whatsappenpoint():\n \n # Creditentials for API\n account_sid = os.environ['TWILIO_ACCOUNT_SID']\n auth_token = os.environ['TWILIO_AUTH_TOKEN']\n client = Client(account_sid, auth_token)\n\n if request.method == \"POST\":\n UserMessage = request.form\n Body = UserMessage.get('Body').split(\" \")\n print(Body)\n UserNumber = UserMessage.get('From')[UserMessage.get('From').index(\":\")+1:]\n print(UserNumber)\n if Body[0] == \"list\":\n MainData = MainImamData.query.filter_by(MasjidLocation = \" \".join(Body[1:])).all()\n if len(MainData) == 0:\n message = client.messages.create(\n body=\"No masjids in this area :( \",\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n \n ListData = \"\"\n ItemList = 1\n for Item in MainData:\n ListData += \"{}. ImamUserName:{} MasjidLocation:{}\".format(ItemList,Item.UserName,Item.MasjidLocation)\n ItemList += 1\n print(ListData) \n message = client.messages.create(\n body=ListData,\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n elif Body[0] == \"announcements\":\n MainData = MainImamData.query.filter_by(MasjidLocation = \" \".join(Body[1:-1])).all()\n if len(MainData) == 0:\n message = client.messages.create(\n body=\"No masjids in this area :( \",\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n ResultData = \"\"\n for Item in Annoucements.query.filter_by(ImamOwnership = MainData[int(Body[-1])-1].UserName).all():\n ResultData += Item.AnnouncementText+\"\\n\"\n if ResultData == \"\":\n message = client.messages.create(\n body=\"No annoucements for this Imam\",\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n else:\n message = client.messages.create(\n body=ResultData,\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n elif Body[0] == \"ask\":\n ListNumIndex = 0\n for item in Body:\n if item.isnumeric():\n break\n ListNumIndex += 1\n print(ListNumIndex)\n MainData = MainImamData.query.filter_by(MasjidLocation = \" \".join(Body[1:ListNumIndex])).all()\n if len(MainData) == 0:\n message = client.messages.create(\n body=\"No masjids in this area :( \",\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n \n database.session.add(QuestionDatabase(\" \".join(Body[ListNumIndex+1:]),UserNumber, MainData[int(Body[ListNumIndex])-1].UserName))\n database.session.commit()\n print(QuestionDatabase.query.all())\n elif Body[0] == \"inbox\":\n AllQuestions = QuestionDatabase.query.all()\n MainData = MainImamData.query.filter_by(MasjidLocation = \" \".join(Body[1:-1])).all()\n if len(MainData) == 0:\n message = client.messages.create(\n body=\"No masjids in this area :( \",\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n \n ResultData = \"\"\n for item in AllQuestions:\n if item.SenderNumber == UserNumber and item.ImamUsername == MainData[int(Body[-1]) -1].UserName:\n ResultData += \"Question:{} Answer:{} \\n\".format(item.QuestionText,item.ImamAnswer)\n \n if ResultData == \"\":\n message = client.messages.create(\n body=\"Inbox empty\",\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n else:\n message = client.messages.create(\n body=ResultData,\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n else:\n message = client.messages.create(\n body=\"Invalid command[valid commands: list,ask,inbox,announcements]\",\n from_='whatsapp:+14155238886',\n to='whatsapp:{}'.format(UserNumber)\n )\n return \"Failure - POST\"\n\n return \"Success - POST\"\n else:\n database.session.add(MainImamData(\"Dr.Ali\",\"securepassword\",\"San Jose\"))\n database.session.add(Annoucements(\"Dr.Ali\",\"Zuhr is at 1:30 Today.\"))\n database.session.commit()\n return \"Success - GET\"\n\nif __name__ == '__main__':\n database.create_all()\n app.run(port=8080)\n\n" } ]
2
Elliot-Ruiz96/CursoPython
https://github.com/Elliot-Ruiz96/CursoPython
1a7e8d74441863e114249f35848c351dc5a5244a
0d49075f8053170a18608ef41d65d5a8e3beca2f
cfce9c5bf867ede1605fc5bd5375bcb7d3ed52f6
refs/heads/main
2023-03-14T12:05:02.672663
2021-03-11T00:28:32
2021-03-11T00:28:32
337,456,639
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5327402353286743, "alphanum_fraction": 0.5580071210861206, "avg_line_length": 27.67346954345703, "blob_id": "d9801b09ee451801ba33fc647d50d0c3017a8845", "content_id": "5e4c8d4da90369b386f34d93b1becdce707b389a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2811, "license_type": "no_license", "max_line_length": 97, "num_lines": 98, "path": "/Proyecto/clienteAsist.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "from PySide6 import QtWidgets\nfrom estudiante import Estudiante\nimport sys\nimport socket\nimport pickle\n\nhost = '3.16.226.150'\nport = 9997\n\n\nclass Menu(QtWidgets.QWidget):\n\n def __init__(self, parent=None):\n super(Menu, self).__init__(parent)\n\n nameLabel1 = QtWidgets.QLabel(\"Nombre:\")\n self.nameLine = QtWidgets.QLineEdit()\n nameLabel2 = QtWidgets.QLabel(\"Correo:\")\n self.mailLine = QtWidgets.QLineEdit()\n nameLabel3 = QtWidgets.QLabel(\"Contraseña:\")\n self.passLine = QtWidgets.QLineEdit()\n\n self.submitButton = QtWidgets.QPushButton(\"&Buscar y enviar\")\n self.submitButton.setToolTip(\"Cargar archivo .zip\")\n\n self.submitButton.clicked.connect(self.submitAlumno)\n\n buttonLayout1 = QtWidgets.QVBoxLayout()\n buttonLayout1.addWidget(self.submitButton)\n\n mainLayout = QtWidgets.QGridLayout()\n mainLayout.addWidget(nameLabel1, 0, 0)\n mainLayout.addWidget(self.nameLine, 0, 1)\n mainLayout.addWidget(nameLabel2, 1, 0)\n mainLayout.addWidget(self.mailLine, 1, 1)\n mainLayout.addWidget(nameLabel3, 2, 0)\n mainLayout.addWidget(self.passLine, 2, 1)\n mainLayout.addLayout(buttonLayout1, 1, 2)\n\n self.setLayout(mainLayout)\n self.setWindowTitle(\"Proyecto\")\n\n def submitAlumno(self):\n\n s = socket.socket()\n # Port = 9997 proyecto final, 9998 pruebas\n s.connect((host, port))\n\n estudiante = Estudiante(self.nameLine.text(), self.mailLine.text(), self.passLine.text())\n estudiante_seriado = pickle.dumps(estudiante)\n\n s.send(estudiante_seriado)\n res = s.recv(1024)\n print(f'Respuesta: \\n\\t{res.decode()}')\n\n s.send(b'INI')\n res = s.recv(1024)\n print(f'Respuesta: \\n\\t{res.decode()}')\n\n fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self,\n \"Open ZIP file\",\n '',\n \"Zip file (*.zip);;All Files (*)\")\n if not fileName:\n return\n\n fileName2 = open(fileName, 'rb')\n\n fileName_seriado = pickle.dumps(fileName2.read())\n\n i = True\n j = 0\n\n while i:\n chunk = fileName_seriado[j: j + 1024]\n\n if not chunk:\n i = False\n continue\n\n s.send(chunk)\n res = s.recv(1024)\n print(f'Respuesta: \\n\\t{res.decode()}')\n j += 1024\n\n s.send(b'FIN')\n res = s.recv(1024)\n print(f'Respuesta: \\n\\t{res.decode()}')\n\n s.close()\n\n\nif __name__ == '__main__':\n\n app = QtWidgets.QApplication(sys.argv)\n Menu = Menu()\n Menu.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.5388007164001465, "alphanum_fraction": 0.5692239999771118, "avg_line_length": 35.58064651489258, "blob_id": "f1130e7a4764fd775b66b73b3aee4c21dc529fd4", "content_id": "2ece7983b2c4183e2e77b2b8663732eb4512b65b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2268, "license_type": "no_license", "max_line_length": 91, "num_lines": 62, "path": "/Pack/Tarea2_Modulo.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import re\n\n\ndef validacion(correo, telefono, curp, rfc):\n\n # Variable para validacion de correo\n # [PV] # La validacion es muy debil, ingresar solo @. lo marca como valida\n # patron sencillo '[a-z.]+@([a-z.]+){1,2}[a-z]{2-3}'\n valida_correo = re.search(\"@\", correo) # Busca el arroba\n valida_correo_dominio = re.split(\"@\", correo) # Divide en dos grupos el correo\n\n # Variable para validacion de telefono\n # [PV] Busca que haya 10 numeros pero no valida la forma\n # [PV] ej. '\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}'\n valida_telefono = re.findall(\"\\d\", telefono) # Verifica que sean solo numeros\n\n # Variable para validacion de curp\n # [PV] Si se escriben puros numeros se toma com valido\n # ej. valido [A-Z]{4}[0-9]{6}[H|M][A-Z]{5}[A-Z0-9]{2}\n valida_curp = re.search(\"\\S\", curp) # Busca que no haya espacios\n\n # Variable para validacion de rfc\n # [PV] Si se escriben puros numeros se toma com valido\n # ej. valido [A-Z]{4}[0-9]{6}[A-Z0-9]{3}\n valida_rfc = re.search(\"\\S\", rfc) # Busca que no haya espacios\n\n if valida_correo:\n if re.search(\"[.]\", valida_correo_dominio[1]): # Busca el punto en el dominio\n print(f'Correo {correo} valido.')\n else:\n print(f'Correo {correo} no valido.')\n else:\n print(f'Correo {correo} no valido.')\n\n if len(valida_telefono) == 10: # Valida que sean 10 numeros\n print(f'Numero {telefono} valido.')\n else:\n print(f'Numero {telefono} no valido.')\n\n if len(curp) == 18: # Valida que sean 18 caracteres\n if valida_curp:\n print(f'CURP {curp} valida.')\n else:\n print(f'CURP {curp} no valida.')\n else:\n print(f'CURP {curp} no valida.')\n\n if len(rfc) == 13: # Valida que sean 18 caracteres\n if valida_rfc:\n print(f'RFC {rfc} valida.')\n else:\n print(f'CURP {curp} no valida.')\n else:\n print(f'RFC {rfc} no valida.')\n\n# [email protected]\n# 4775531264\n# RUSE960823HGTZNL03\n# RUSE9608231H0\n\n# Para validar de una manera mas precisa el rfc y el curp\n# se debe validar los diferentes grupos de datos para su construccion\n" }, { "alpha_fraction": 0.576765775680542, "alphanum_fraction": 0.5923791527748108, "avg_line_length": 35.10344696044922, "blob_id": "11880e2aef7aa58d6e2479eba9ca2d5810608189", "content_id": "39cb29fd90316c90b4b26c47fc05fd9dea121978", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5381, "license_type": "no_license", "max_line_length": 111, "num_lines": 145, "path": "/Tarea5/main.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import sys\r\nfrom PySide6 import QtWidgets, QtCore\r\nfrom PySide6.QtWidgets import QLineEdit\r\nfrom PySide6.QtWidgets import *\r\nfrom mongoengine import *\r\n\r\nconnect('IECA', host='Localhost', port=27017)\r\n\r\n\r\nclass estudiantes(Document):\r\n Nombre_estudiante = StringField(required=True, max_length=200)\r\n Correo_estudiantil = StringField(required=True)\r\n Contrasenia = StringField(required=True)\r\n Materias = StringField(required=True)\r\n\r\n\r\n# def escritura(student):\r\n# def lectura():\r\n# def modificacion():\r\n\r\n\r\nclass Menu(QtWidgets.QWidget):\r\n\r\n class Estudiantes:\r\n nombre = \"\"\r\n correo = \"\"\r\n contrasenia = \"\"\r\n materias = \"\"\r\n\r\n def __init__(self, nombre, correo, contrasenia, materias):\r\n self.nombre = nombre\r\n self.correo = correo\r\n self.contrasenia = contrasenia\r\n self.materias = materias\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.setWindowTitle(\"Tarea 5\")\r\n self.layout = QtWidgets.QVBoxLayout(self)\r\n # Se usara el mismo objeto para dedicar menos memoria\r\n self.t1 = QtWidgets.QLabel(\"TAREA 5\", alignment=QtCore.Qt.AlignCenter)\r\n self.layout.addWidget(self.t1)\r\n self.B1 = QtWidgets.QPushButton(\"1. Ingresar estudiante\")\r\n self.layout.addWidget(self.B1)\r\n self.B2 = QtWidgets.QPushButton(\"2. Modificar estudiantes\")\r\n self.layout.addWidget(self.B2)\r\n self.B3 = QtWidgets.QPushButton(\"3. Mostrar Estudiantes\")\r\n self.layout.addWidget(self.B3)\r\n self.B4 = QtWidgets.QPushButton(\"4. Salir\")\r\n self.layout.addWidget(self.B4)\r\n self.B1.clicked.connect(self.escritura)\r\n self.B2.clicked.connect(self.modificacion)\r\n self.B3.clicked.connect(self.lectura)\r\n self.B4.clicked.connect(quit)\r\n self.layout = QtWidgets.QVBoxLayout(self)\r\n\r\n def escritura(self):\r\n self.t1 = QtWidgets.QLabel(\"Ingresa nombre del estudiante: \")\r\n self.layout.addWidget(self.t1)\r\n self.e1 = QLineEdit()\r\n self.layout.addWidget(self.e1)\r\n self.t1 = QtWidgets.QLabel(\"Ingresa correo del estudiante: \")\r\n self.layout.addWidget(self.t1)\r\n self.e2 = QLineEdit()\r\n self.layout.addWidget(self.e2)\r\n self.t1 = QtWidgets.QLabel(\"Ingresa contrasenia del estudiante: \")\r\n self.layout.addWidget(self.t1)\r\n self.e3 = QLineEdit()\r\n self.layout.addWidget(self.e3)\r\n self.t1 = QtWidgets.QLabel(\"Ingresa materias del estudiante: \")\r\n self.layout.addWidget(self.t1)\r\n self.e4 = QLineEdit()\r\n self.layout.addWidget(self.e4)\r\n comp_nom = self.e1\r\n comp_cor = self.e2\r\n comp_con = self.e3\r\n comp_mat = self.e4\r\n aceptado = True\r\n repetido = None\r\n for datos in estudiantes.objects:\r\n comp_nom != datos.Nombre_estudiante\r\n comp_cor != datos.Correo_estudiantil\r\n comp_con != datos.Contrasenia\r\n comp_mat != datos.Materias\r\n if comp_nom and comp_cor and comp_con and comp_mat:\r\n aceptado = True\r\n repetido = False\r\n else:\r\n print(\"Estudiante ya ingresado\")\r\n repetido = True\r\n input(\"Presione enter para continuar\")\r\n\r\n if aceptado:\r\n datos = estudiantes(\r\n Nombre_estudiante=comp_nom,\r\n Correo_estudiantil=comp_cor,\r\n Contrasenia=comp_con,\r\n Materias=comp_mat)\r\n\r\n if repetido is True:\r\n pass\r\n else:\r\n datos.save()\r\n\r\n def modificacion(self):\r\n p = estudiantes.objects(Nombre_estudiante=\"Cesar\")\r\n estudiantes.objects(Nombre_estudiante=p[0].Nombre_estudiante).update_one(set__Nombre_estudiante=\"Hola\")\r\n estudiantes.objects(Materias=p[0].Materias).update_one(set__Materias=\"Adios\")\r\n print(p[0].Contraseña)\r\n p[0].save()\r\n\r\n def lectura(self):\r\n i = 1\r\n for Datos in estudiantes.objects:\r\n self.t1 = QtWidgets.QLabel(f\"Estudiante {i}\")\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(estudiantes.Nombre_estudiante.name)\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(Datos.Nombre_estudiante)\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(estudiantes.Correo_estudiantil.name)\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(Datos.Correo_estudiantil)\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(estudiantes.Contrasenia.name)\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(Datos.Contrasenia)\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(estudiantes.Materias.name)\r\n self.layout.addWidget(self.t1)\r\n self.t1 = QtWidgets.QLabel(Datos.Materias)\r\n self.layout.addWidget(self.t1)\r\n i += 1\r\n\r\n if i == 1:\r\n self.t1 = QtWidgets.QLabel(\"Base de datos vacias.\")\r\n self.layout.addWidget(self.t1)\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QtWidgets.QApplication([])\r\n widget = Menu()\r\n widget.resize(600, 450)\r\n widget.show()\r\n sys.exit(app.exec_())\r\n" }, { "alpha_fraction": 0.6197636723518372, "alphanum_fraction": 0.626423180103302, "avg_line_length": 32.014183044433594, "blob_id": "e9578a555690ae298e495dc50ead185f669c518a", "content_id": "2f9de87290317067ad0dfa98fa1da7b6339b7822", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4658, "license_type": "no_license", "max_line_length": 113, "num_lines": 141, "path": "/Tarea4.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "from mongoengine import *\n\nconnect('IECA', host='Localhost', port=27017)\n# Pagina mas especifica de mongo engine https://www.tutorialspoint.com/mongoengine/mongoengine_atomic_updates.htm\n\n\nclass estudiantes(Document):\n Nombre_estudiante = StringField(required=True, max_length=200)\n Correo_estudiantil = StringField(required=True)\n Contrasenia = StringField(required=True)\n Materias = StringField(required=True)\n\n# class estudiantesCopia(Document):\n# Nombre_estudiante = StringField(required=True,max_length=200)\n# Correo_estudiantil = StringField(required=True)\n# Contraseña = StringField(required=True)\n# Materias = StringField(required=True)\n\n\nclass Estudiantes:\n nombre = \"\"\n correo = \"\"\n contrasenia = \"\"\n materias = \"\"\n\n def __init__(self, nombre, correo, contrasenia, materias):\n self.nombre = nombre\n self.correo = correo\n self.contrasenia = contrasenia\n self.materias = materias\n\n# def base_Datos:\n\n\ndef escritura(student):\n aceptado = True\n repetido = None\n for datos in estudiantes.objects:\n comp_nom = student.nombre != datos.Nombre_estudiante\n comp_cor = student.correo != datos.Correo_estudiantil\n comp_con = student.contrasenia != datos.Contrasenia\n comp_mat = student.materias != datos.Materias\n if comp_nom and comp_cor and comp_con and comp_mat:\n aceptado = True\n repetido = False\n else:\n print(\"Estudiante ya ingresado\")\n repetido = True\n input(\"Presione enter para continuar\")\n\n if aceptado:\n datos = estudiantes(\n Nombre_estudiante=student.nombre,\n Correo_estudiantil=student.correo,\n Contrasenia=student.contrasenia,\n Materias=student.materias)\n\n if repetido is True:\n pass\n else:\n datos.save()\n\n\ndef lectura():\n i = 1\n for Datos in estudiantes.objects:\n print(f\"\\t****Estudiante{i}****\")\n print(f\"\\t{estudiantes.Nombre_estudiante.name}:{Datos.Nombre_estudiante}\")\n print(f\"\\t{estudiantes.Correo_estudiantil.name}:{Datos.Correo_estudiantil}\")\n print(f\"\\t{estudiantes.Contrasenia.name}:{Datos.Contrasenia}\")\n print(f\"\\t{estudiantes.Materias.name}:{Datos.Materias}\")\n print(\"\")\n i += 1\n\n if i == 1:\n print(\"Base de datos esta vacia\")\n\n\ndef eliminacion():\n # [PV] Se debe eliminar solo un usuario\n estudiantes.objects.delete()\n print(\"La base de datos fue vaciada\")\n print(\"\")\n\n\ndef modificacion():\n\n # [PV] para modificar primero se debe obtener un objeto, realizar las modificaciones despues guardar de nuevo\n # User = input(\"Ingresa nombre de usuario a modificar: \")\n # User_nuev = input(\"Ingresa el nuevo nombre el usuario\");\n # estudiantes.objects(Nombre_estudiante = User).update_one(set__Nombre_estudiante = User_nuev)\n # estudiantes.objects(Nombre_estudiante=\"Elliot\").delete()\n # Nombre = input(\"Nuevo nombre usuario: \")\n # Correo = input(\"Nuevo Correo: \")\n # Contra = input(\"Nueva contraseña: \")\n # Materias = input(\"Nuevas Materias: \")\n # Modify= estudiantes.objects(Nombre_estudiante=Nombre,\n # Correo_estudiantil=Correo,\n # Contraseña=Contra,\n # Materias=Materias)\n # Eliminar[0].delete()\n\n # Eliminar[0].deleted()\n p = estudiantes.objects(Nombre_estudiante=\"Elliot\")\n estudiantes.objects(Nombre_estudiante=p[0].Nombre_estudiante).update_one(set__Nombre_estudiante=\"Hola\")\n estudiantes.objects(Materias=p[0].Materias).update_one(set__Materias=\"Adios\")\n print(p[0].Contrasenia)\n p[0].save()\n\n\ndef menu():\n ciclo = True\n\n while ciclo:\n print(\"\\n\\t\\t\\tTAREA 4\\n\")\n print(\"Bienvenido al menu de opciones.\\n\")\n print(\"1. Ingresar estudiante.\")\n print(\"2. Modificar estudiante.\")\n print(\"3. Mostrar estudiantes.\")\n print(\"4. Eliminar estudiantes.\")\n print(\"5. Salir\")\n opcion = input(\"Seleciona un opcion: \")\n if opcion == \"1\":\n print(\"\")\n nombre = input(\"Ingresa nombre del estudiante: \")\n correo = input(\"Ingresa correo del estudiante: \")\n contrasenia = input(\"Ingresa contrasenia del estudiante: \")\n materias = input(\"Ingresa materias del estudiante: \")\n escritura(Estudiantes(nombre, correo, contrasenia, materias))\n if opcion == \"2\":\n modificacion()\n if opcion == \"3\":\n lectura()\n if opcion == \"4\":\n eliminacion()\n if opcion == \"5\":\n ciclo = False\n\n\nif __name__ == '__main__':\n menu()\n" }, { "alpha_fraction": 0.5325779318809509, "alphanum_fraction": 0.5495750904083252, "avg_line_length": 21.0625, "blob_id": "7e88aaf68f9a034ef4d64a5e5132251691dd120c", "content_id": "3b12d2ea73cc8d94848c98d06fe710c457e00f81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "no_license", "max_line_length": 76, "num_lines": 16, "path": "/Pack/Funciones.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "# Un modulo es un archivo con funciones\n\ndef funcion( nombre = 'Elliot', apellido = 'Ruiz', lista=['a','b','c','d']):\n print('Hello', nombre, apellido)\n print(f'lista: {lista}')\n lista[1] = 14\n return lista\n\n\nif __name__ == '__main__':\n lista = [ 1 , 2 , 3]\n\n l = funcion(lista=lista.copy())\n\n print(f'main: {lista}')\n print(l)\n" }, { "alpha_fraction": 0.5776892304420471, "alphanum_fraction": 0.5936254858970642, "avg_line_length": 17.629629135131836, "blob_id": "fdea5997512d3f58fc5fa2eafc73b092feca401f", "content_id": "d38953b6aae25138b5fc497febb47893bb60a736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "no_license", "max_line_length": 114, "num_lines": 27, "path": "/ciclos.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "continuar = True\ncontador = 0\n\nwhile continuar:\n contador +=1\n print(f'{contador}')\n\n print('¿Deseas continuar?')\n print('s = Si')\n print('Cualquier caracter = Si')\n respuesta = input()\n\n if respuesta == 's':\n continue\n else:\n continuar = False\n\nfor i in range(1 , 10 , 2):\n\n print(f'Numero: {i + 1}')\n\n# La letra 'f' antes del texto indica que hay una variable dentro del print y se escribe dentro de los parentesis,\n\n if i == 4:\n break\n\nprint('FIN')" }, { "alpha_fraction": 0.6704980731010437, "alphanum_fraction": 0.7049808502197266, "avg_line_length": 17.64285659790039, "blob_id": "3d9346798f54f7270cf7d53e2d794afc7e543265", "content_id": "3250da6a511ecb2c89c40b3f10303ba639cb040d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 55, "num_lines": 14, "path": "/clientUDP.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import socket\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nip = 'localhost'\npuerto = 12345\n\nmsg = 'Hello world!'.encode()\n\nsock.sendto(msg, (ip, puerto))\n\ninfo, direccion = sock.recvfrom(1024)\n\nprint(f\"Recibido: {info.decode()} desde {direccion}\")\n" }, { "alpha_fraction": 0.7732240557670593, "alphanum_fraction": 0.7786885499954224, "avg_line_length": 21.875, "blob_id": "60bbb3e470fa2d5facf931d3f8a58a88f9c08442", "content_id": "6a1302ee3e2ee3263b988ee321da3d7e7addc270", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/ejemplo/gui.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "from PySide2.QtWidgets import QApplication\nfrom PySide2.QtWidgets import QMainWindow\nimport sys\nfrom main import Ejemplo\n\n# Windows -> desinger.exe\n\n# Inicializacon de gui\napp = QApplication(sys.argv)\n# Inicializacion de ventana principal\nwindow = QMainWindow()\n# window = Ejemplo()\n# Muestra la ventana creada\nwindow.show()\n# Ejecucion de gui\nsys.exit(app.exec_())\n" }, { "alpha_fraction": 0.6544342637062073, "alphanum_fraction": 0.6819571852684021, "avg_line_length": 18.235294342041016, "blob_id": "66ec063bdd21a818838fc5d4539d88288b2e24b3", "content_id": "6e1fe5a17a50a70c917f2f649e2bb493eee68c19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 56, "num_lines": 17, "path": "/serverUDP.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import socket\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nip = 'localhost'\npuerto = 12345\n\nsock.bind((ip, puerto))\n\nwhile True:\n print(\"Esperando paquetes...\")\n\n info, direccion = sock.recvfrom(1024)\n\n print(f\"Mensaje: {info.decode()} desde {direccion}\")\n\n sock.sendto('Recibido'.encode(), direccion)\n" }, { "alpha_fraction": 0.572519063949585, "alphanum_fraction": 0.5763359069824219, "avg_line_length": 15.903225898742676, "blob_id": "af841a96c4b219a51f7086d507e0ada35c3b2b3e", "content_id": "06d1fe4da2b45fada81ab889ae525de45d6bbe8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 524, "license_type": "no_license", "max_line_length": 60, "num_lines": 31, "path": "/Herencia.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "class Vehiculo:\n\n __llantas = 4\n __personas = 2\n __lucesencendidas = False\n\n def acelera(self):\n pass\n\n def enciendeluces(self):\n self.__lucesencendidas = True\n\n def apagarluces(self):\n self.__lucesencendidas = False\n\n def cuantasllantas(self):\n pass\n\n\nclass Motocicleta(Vehiculo):\n\n def __init__(self):\n self.enciendeluces()\n print(f'Luces encendidas: {self.lucesencendidas()}')\n pass\n\n\nif __name__ == '__main__':\n\n m = Motocicleta()\n print(m)\n" }, { "alpha_fraction": 0.5060241222381592, "alphanum_fraction": 0.5180723071098328, "avg_line_length": 15.600000381469727, "blob_id": "3717cbd5f9ff52819e0fd73e9d14c67a96e8f215", "content_id": "dd23b135dca5fc4ca6b92828bbabc9e424a8387e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 33, "num_lines": 10, "path": "/Expresiones.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import re\n\ndef suma (a,b):\n patron = '[0-9]*$'\n\n ra = re.match(patron,str(a))\n rb = re.match(patron, str(b))\n\n if ra and rb:\n return int(a)+int(b)\n" }, { "alpha_fraction": 0.662420392036438, "alphanum_fraction": 0.6772823929786682, "avg_line_length": 18.625, "blob_id": "8c126ae7bcdaa0a7f9842dd63cd1eb91e9a672c0", "content_id": "27ef2a14b6b99a2d79f2404bdb479ab7e018eed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 55, "num_lines": 24, "path": "/serverTCP.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import socket\n\n# Difereniciar cliente y host\nserver_sock = socket.socket()\nhost = socket.gethostname()\n\nprint(server_sock)\nprint(host)\n\nport = 9999\n\nserver_sock.bind((host, port))\n\nprint('Esperando conexiones')\nserver_sock.listen(1)\n\nwhile True:\n client_sock, addr = server_sock.accept()\n print(addr)\n\n print(f'Cliente conectado de la direccion: {addr}')\n msg = 'Hola' + addr[0] + ':' + str(addr[1])\n client_sock.send(msg.encode())\n client_sock.close()\n" }, { "alpha_fraction": 0.6033857464790344, "alphanum_fraction": 0.6118500828742981, "avg_line_length": 21.351350784301758, "blob_id": "0072877b1331a0b36b9b30c6abd6f74a61b3f952", "content_id": "0951a4b584f131b554b455a1fc0ae93d49e79ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 827, "license_type": "no_license", "max_line_length": 68, "num_lines": 37, "path": "/ejemplo/main.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "# This Python file uses the following encoding: utf-8\nimport sys\nimport os\n\n\nfrom PySide2.QtWidgets import QApplication, QWidget\nfrom PySide2.QtCore import QFile\nfrom PySide2.QtUiTools import QUiLoader\n\n\nclass Ejemplo(QWidget):\n def __init__(self):\n super(Ejemplo, self).__init__()\n self.load_ui()\n\n #self.pushButton.clicked.connect(slot1)\n\n def load_ui(self):\n loader = QUiLoader()\n path = os.path.join(os.path.dirname(__file__), \"ejemplo.ui\")\n ui_file = QFile(path)\n ui_file.open(QFile.ReadOnly)\n loader.load(ui_file, self)\n ui_file.close()\n\n def slot1(self):\n print('Boton presionado!')\n\n def fun1 (self):\n pass\n\n\nif __name__ == \"__main__\":\n app = QApplication([])\n widget = Ejemplo()\n widget.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.5814307332038879, "alphanum_fraction": 0.6176559925079346, "avg_line_length": 27.565217971801758, "blob_id": "3fd5436db6737d16821e5e55f4a5ebc529462487", "content_id": "688b476976a521df58ff40966cac5c6f196fbbd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3285, "license_type": "no_license", "max_line_length": 93, "num_lines": 115, "path": "/Pack/StudentIO.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import pickle\n\n\nclass Estudiante:\n\n def __init__(self, nombre, carrera, correo, num_control, promedio):\n self.nombre = nombre\n self.carrera = carrera\n self.correo = correo\n self.num_control = num_control\n self.promedio = promedio\n\n def setnombre(self):\n nombre = input()\n self.nombre = nombre\n\n def getnombre(self):\n return self.nombre\n\n def setcarrera(self):\n carrera = input()\n self.carrera = carrera\n\n def getcarrera(self):\n return self.carrera\n\n def setcorreo(self):\n correo = input()\n self.correo = correo\n\n def getcorreo(self):\n return self.correo\n\n def setnum_control(self):\n num_control = input()\n self.num_control = num_control\n\n def getnum_control(self):\n return self.num_control\n\n def setpromedio(self):\n promedio = input()\n self.promedio = promedio\n\n def getpromedio(self):\n return self.promedio\n\n\n# e = Estudiante(nombre, carrera, correo, num_control, promedio)\ne = Estudiante(\"Elliot\", \"MECATRONICA\", \"[email protected]\", \"16240056\", \"82.47\")\ne1 = Estudiante(\"DIEGO\", \"ACTUARIA\", \"[email protected]\", \"16240057\", \"83.47\")\ne2 = Estudiante(\"RENE\", \"SISTEMAS\", \"[email protected]\", \"16240058\", \"84.47\")\ne3 = Estudiante(\"SERGIO\", \"GESTION\", \"[email protected]\", \"16240059\", \"85.47\")\ne4 = Estudiante(\"KARLA\", \"ADMINISTRACION\", \"[email protected]\", \"16240060\", \"86.47\")\n\n\ndef agregar():\n # [PV] Solo se cambia el priemr objeto\n print(\"Ingresa tu nombre completo: \")\n e.setnombre()\n print(\"Ingresa tu carrera: \")\n e.setcarrera()\n print(\"Ingresa tu correo: \")\n e.setcorreo()\n print(\"Ingresa tu numero de control: \")\n e.setnum_control()\n print(\"Ingresa tu promedio: \")\n e.setpromedio()\n\n\ndef lectura():\n # [PV] Se puede usar un loop para mostrarlos todos\n print(\"Nombre:\")\n print(e.getnombre())\n print('Carrera:')\n print(e.getcarrera())\n print('Correo:')\n print(e.getcorreo())\n print('Numero de control:')\n print(e.getnum_control())\n print('Promedio:')\n print(e.getpromedio())\n\n\ndef actualizar():\n # [PV] Siempre se edita el primer objeto\n print(\"Ingresa tu nombre completo: \")\n e.setnombre()\n print(\"Ingresa tu carrera: \")\n e.setcarrera()\n print(\"Ingresa tu correo: \")\n e.setcorreo()\n print(\"Ingresa tu numero de control: \")\n e.setnum_control()\n print(\"Ingresa tu promedio: \")\n e.setpromedio()\n\n\ndef pickle1():\n ej_dict = {1: e.nombre, 2: e.carrera, 3: e.correo, 4: e.num_control, 5: e.promedio}\n ej_dict1 = {1: e1.nombre, 2: e1.carrera, 3: e1.correo, 4: e1.num_control, 5: e1.promedio}\n ej_dict2 = {1: e2.nombre, 2: e2.carrera, 3: e2.correo, 4: e2.num_control, 5: e2.promedio}\n ej_dict3 = {1: e3.nombre, 2: e3.carrera, 3: e3.correo, 4: e3.num_control, 5: e3.promedio}\n ej_dict4 = {1: e4.nombre, 2: e4.carrera, 3: e4.correo, 4: e4.num_control, 5: e4.promedio}\n pickle_out = open(\"dict.db\", \"wb\")\n pickle.dump(ej_dict, pickle_out)\n pickle.dump(ej_dict1, pickle_out)\n pickle.dump(ej_dict2, pickle_out)\n pickle.dump(ej_dict3, pickle_out)\n pickle.dump(ej_dict4, pickle_out)\n pickle_out.close()\n pickle_in = open(\"dict.db\", \"rb\")\n example_dict = pickle.load(pickle_in)\n print(example_dict)\n print(example_dict[2])\n" }, { "alpha_fraction": 0.5990400314331055, "alphanum_fraction": 0.6040970087051392, "avg_line_length": 35.80126190185547, "blob_id": "b646b82f76962d53f10c41cd997a017c4271f889", "content_id": "ef344a11a5ef0b8abd6401a5473bd335fa3188d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11675, "license_type": "no_license", "max_line_length": 120, "num_lines": 317, "path": "/Tarea5/main2_1.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "\nfrom PySide6 import QtCore, QtWidgets\n# from PySide6 import QtCore, QtWidgets\nfrom PySide2 import QtCore, QtWidgets\nfrom mongoengine import *\nimport sys\n\nconnect('IECA', host='Localhost', port=27017)\n\n\nclass estudiantes(Document):\n Nombre_estudiante = StringField(required=True, max_length=200)\n Correo_estudiantil = StringField(required=True)\n Contrasenia = StringField(required=True)\n Materias = StringField(required=True)\n\n\nclass Estudiantes:\n nombre = \"\"\n correo = \"\"\n contrasenia = \"\"\n materias = \"\"\n\n def __init__(self, nombre, correo, contrasenia, materias):\n self.nombre = nombre\n self.correo = correo\n self.contrasenia = contrasenia\n self.materias = materias\n\n\n# Clase padre para el menu\nclass Menu(QtWidgets.QWidget):\n ModoNavegar, ModoIngresar, ModoEditar = range(3)\n\n # Funcion para declarar e inicializar los widgets\n def __init__(self, parent=None):\n super(Menu, self).__init__(parent)\n\n self.database = estudiantes()\n self.oldName = ''\n self.oldMail = ''\n self.oldPass = ''\n self.oldSubj = ''\n self.ModoActual = self.ModoNavegar\n\n nameLabel1 = QtWidgets.QLabel(\"Nombre:\")\n self.nameLine = QtWidgets.QLineEdit()\n self.nameLine.setReadOnly(True)\n\n nameLabel2 = QtWidgets.QLabel(\"Correo:\")\n self.mailLine = QtWidgets.QLineEdit()\n self.mailLine.setReadOnly(True)\n\n nameLabel3 = QtWidgets.QLabel(\"Contraseña:\")\n self.passLine = QtWidgets.QLineEdit()\n self.passLine.setReadOnly(True)\n\n nameLabel4 = QtWidgets.QLabel(\"Materia:\")\n self.subjLine = QtWidgets.QLineEdit()\n self.subjLine.setReadOnly(True)\n\n # Botones para funcion de menu\n self.addButton = QtWidgets.QPushButton(\"&Ingresa\")\n self.editButton = QtWidgets.QPushButton(\"&Modifica\")\n self.editButton.setEnabled(False)\n self.removeButton = QtWidgets.QPushButton(\"&Elimina\")\n self.removeButton.setEnabled(False)\n self.submitButton = QtWidgets.QPushButton(\"&Confirma\")\n self.submitButton.hide()\n self.cancelButton = QtWidgets.QPushButton(\"&Cancela\")\n self.cancelButton.hide()\n\n # Botones para mostrar\n self.nextButton = QtWidgets.QPushButton(\"&Siguiente\")\n self.nextButton.setEnabled(False)\n self.previousButton = QtWidgets.QPushButton(\"&Anterior\")\n self.previousButton.setEnabled(False)\n\n # Definir la conecion a funciones\n self.addButton.clicked.connect(self.addAlumno)\n self.editButton.clicked.connect(self.editAlumno)\n self.removeButton.clicked.connect(self.removeAlumno)\n self.submitButton.clicked.connect(self.submitAlumno)\n self.cancelButton.clicked.connect(self.cancelAlumno)\n self.nextButton.clicked.connect(self.nextAlumno)\n self.previousButton.clicked.connect(self.previousAlumno)\n\n # Layout de funciones principales\n buttonLayout1 = QtWidgets.QVBoxLayout()\n buttonLayout1.addWidget(self.addButton)\n buttonLayout1.addWidget(self.editButton)\n buttonLayout1.addWidget(self.removeButton)\n buttonLayout1.addWidget(self.cancelButton)\n buttonLayout1.addWidget(self.submitButton)\n buttonLayout1.addStretch()\n\n # Layout de funciones mostrar\n buttonLayout2 = QtWidgets.QHBoxLayout()\n buttonLayout2.addWidget(self.nextButton)\n buttonLayout2.addWidget(self.previousButton)\n\n # Layout principal con coordenadas\n mainLayout = QtWidgets.QGridLayout()\n mainLayout.addWidget(nameLabel1, 0, 0)\n mainLayout.addWidget(self.nameLine, 0, 1)\n mainLayout.addWidget(nameLabel2, 1, 0)\n mainLayout.addWidget(self.mailLine, 1, 1)\n mainLayout.addWidget(nameLabel3, 2, 0)\n mainLayout.addWidget(self.passLine, 2, 1)\n mainLayout.addWidget(nameLabel4, 3, 0)\n mainLayout.addWidget(self.subjLine, 3, 1)\n mainLayout.addLayout(buttonLayout1, 1, 2)\n mainLayout.addLayout(buttonLayout2, 4, 1)\n\n self.setLayout(mainLayout)\n self.setWindowTitle(\"Tarea 5\")\n\n def addAlumno(self):\n self.oldName = self.nameLine.text()\n self.oldMail = self.mailLine.text()\n self.oldPass = self.passLine.text()\n self.oldSubj = self.subjLine.text()\n\n self.nameLine.clear()\n self.mailLine.clear()\n self.passLine.clear()\n self.subjLine.clear()\n\n self.updateGUI(self.ModoIngresar)\n\n def editAlumno(self):\n self.oldName = self.nameLine.text()\n self.oldMail = self.mailLine.text()\n self.oldPass = self.passLine.text()\n self.oldSubj = self.subjLine.text()\n\n self.updateGUI(self.ModoEditar)\n\n def removeAlumno(self):\n nombre = self.nameLine.text()\n\n # [PV] No se interactua con la BD\n\n if nombre in self.database:\n boton = QtWidgets.QMessageBox.question(self, \"Confirmar\", \"Estas seguro de quitar a \\\"%s\\\"?\" % nombre,\n QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)\n if boton == QtWidgets.QMessageBox.Yes:\n self.previous()\n del self.database[nombre]\n\n QtWidgets.QMessageBox.information(self, \"Operacion exitosa\", \"\\\"%s\\\" ha sido eliminado\" % nombre)\n\n self.updateGUI(self.ModoNavegar)\n\n def submitAlumno(self):\n nombre = self.nameLine.text()\n correo = self.mailLine.text()\n contra = self.passLine.text()\n materi = self.subjLine.text()\n\n if nombre == \"\" or correo == \"\" or contra == \"\" or materi == \"\":\n QtWidgets.QMessageBox.information(self, \"Campo Vacio\", \"Por favor ingrese todos lo campos.\")\n return\n\n if self.ModoActual == self.ModoIngresar:\n if nombre not in self.database:\n estudiantes(\n Nombre_estudiante=nombre,\n Correo_estudiantil=correo,\n Contrasenia=contra,\n Materias=materi)\n QtWidgets.QMessageBox.information(self, \"Operacion exitosa\", \"\\%s\\\" ha sido añadido.\" % nombre)\n\n\n # [PV] No se guarda a la BD\n else:\n QtWidgets.QMessageBox.information(self, \"Operacion fallida\", \"\\%s\\\" ya ha sido añadido antes.\" % nombre)\n return\n\n elif self.ModoActual == self.ModoEditar:\n if self.oldName != nombre:\n if nombre not in self.database:\n QtWidgets.QMessageBox.information(self, \"Operacion exitosa\", \"\\\"%s\\\" ha sido añadido.\"\n % self.oldName)\n\n # [PV] No se interactua con la BD\n del self.database[self.oldName]\n self.database[nombre] = correo\n self.database[nombre] = contra\n self.database[nombre] = materi\n else:\n QtWidgets.QMessageBox.information(self, \"Operacion fallida\", \"\\%s\\\" ya ha sido añadido antes.\"\n % nombre)\n return\n elif self.oldMail != correo:\n QtWidgets.QMessageBox.information(self, \"Operacion exitosa\", \"\\\"%s\\\" ha sido añadido.\" % nombre)\n self.database[nombre] = correo\n self.database[nombre] = contra\n self.database[nombre] = materi\n elif self.oldPass != contra:\n QtWidgets.QMessageBox.information(self, \"Operacion exitosa\", \"\\\"%s\\\" ha sido añadido.\" % nombre)\n self.database[nombre] = correo\n self.database[nombre] = contra\n self.database[nombre] = materi\n elif self.oldSubj != materi:\n QtWidgets.QMessageBox.information(self, \"Operacion exitosa\", \"\\\"%s\\\" ha sido añadido.\" % nombre)\n self.database[nombre] = correo\n self.database[nombre] = contra\n self.database[nombre] = materi\n\n self.updateGUI(self.ModoNavegar)\n\n def cancelAlumno(self):\n self.nameLine.setText(self.oldName)\n self.mailLine.setText(self.oldMail)\n self.passLine.setText(self.oldPass)\n self.subjLine.setText(self.oldSubj)\n self.updateGUI(self.ModoNavegar)\n\n def nextAlumno(self):\n nombre = self.nameLine.text()\n it = iter(self.database)\n\n try:\n while True:\n this_name, _ = it.next()\n\n if this_name == nombre:\n next_nombre, next_correo, next_contra, next_materi = it.next()\n break\n except StopIteration:\n next_nombre, next_correo, next_contra, next_materi = iter(self.database).next()\n\n self.nameLine.setText(next_nombre)\n self.mailLine.setText(next_correo)\n self.passLine.setText(next_contra)\n self.subjLine.setText(next_materi)\n\n def previousAlumno(self):\n nombre = self.nameLine.text()\n\n prev_nombre = prev_correo = prev_contra = prev_materi = None\n for this_name, this_correo, this_contra, this_materi in self.database:\n if this_name == nombre:\n break\n\n prev_nombre = this_name\n prev_correo = this_correo\n prev_contra = this_contra\n prev_materi = this_materi\n else:\n self.nameLine.clear()\n self.mailLine.clear()\n self.passLine.clear()\n self.subjLine.clear()\n return\n\n if prev_nombre is None:\n for prev_nombre, prev_correo, prev_contra, prev_materi in self.database:\n pass\n\n self.nameLine.setText(prev_nombre)\n self.mailLine.setText(prev_correo)\n self.passLine.setText(prev_contra)\n self.subjLine.setText(prev_materi)\n\n def updateGUI(self, modo):\n self.ModoActual = modo\n\n if self.ModoActual in (self.ModoIngresar, self.ModoEditar):\n self.nameLine.setReadOnly(False)\n self.nameLine.setFocus(QtCore.Qt.OtherFocusReason)\n self.mailLine.setReadOnly(False)\n self.passLine.setReadOnly(False)\n self.subjLine.setReadOnly(False)\n\n self.addButton.setEnabled(False)\n self.editButton.setEnabled(False)\n self.removeButton.setEnabled(False)\n\n self.nextButton.setEnabled(False)\n self.previousButton.setEnabled(False)\n\n self.submitButton.show()\n self.cancelButton.show()\n\n elif self.ModoActual == self.ModoNavegar:\n if not self.database:\n self.nameLine.clear()\n self.mailLine.clear()\n self.passLine.clear()\n self.subjLine.clear()\n\n self.nameLine.setReadOnly(True)\n self.mailLine.setReadOnly(True)\n self.passLine.setReadOnly(True)\n self.subjLine.setReadOnly(True)\n self.addButton.setEnabled(True)\n\n number = len(self.database)\n self.editButton.setEnabled(number >= 1)\n self.removeButton.setEnabled(number >= 1)\n self.findButton.setEnabled(number > 2)\n # [PV] El boton findButton no existe en otro lugar del programa\n # self.findButton.setEnabled(number > 2)\n self.nextButton.setEnabled(number > 1)\n self.previousButton.setEnabled(number > 1)\n\n self.submitButton.hide()\n self.cancelButton.hide()\n\n\nif __name__ == '__main__':\n\n app = QtWidgets.QApplication(sys.argv)\n Menu = Menu()\n Menu.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.6662561297416687, "alphanum_fraction": 0.6847290396690369, "avg_line_length": 23.606060028076172, "blob_id": "1c652f4b55ee70970c5ca004d72ca7a6b3309dd0", "content_id": "6096aeb84fa358a3d69dcec89433ec55258cbe64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 812, "license_type": "no_license", "max_line_length": 55, "num_lines": 33, "path": "/Diccionario.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "# https://devcode.la/tutoriales/diccionarios-en-python/\n\ndiccionario = {}\ndiccionario2 = dict()\n\nprint(f'Diccionario: {diccionario}')\n\nprint(f'Tipo: {type(diccionario)}')\n\ndiccionario[1] = 'uno'\ndiccionario[3.4] = 'tres punto cuatro'\ndiccionario['uno'] = 'uno'\ndiccionario[False] = 'Falso'\n\nprint(f'diccionario[1]: {diccionario[1]}')\nprint(f'diccionario[3.4]: {diccionario[3.4]}')\nprint(f'diccionario[\"uno\"]: {diccionario[\"uno\"]}')\nprint(f'diccionario[False]: {diccionario[False]}')\n\nprint(f'Diccionario: {diccionario}')\n\ndiccionario2 = {1 : 'uno' , 2.0 : 'dos punto cero'}\nprint(diccionario2)\n\nprint('\\n\\n')\nprint(diccionario.items())\nprint(diccionario.keys())\nprint(diccionario.values())\n\nfor key in diccionario.keys():\n print(f'Key: {key}')\n print(f'Valor: {diccionario[key]}')\n print(f'key: {key}')\n" }, { "alpha_fraction": 0.5875152945518494, "alphanum_fraction": 0.6022031903266907, "avg_line_length": 19.94871711730957, "blob_id": "833cfc090a0048ed5fd2f527f7bb2f3e12c6afff", "content_id": "444f6cce8f8a1352315c15a29dbc2c178e8bc103", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 817, "license_type": "no_license", "max_line_length": 76, "num_lines": 39, "path": "/Herencia_Division.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "class Division:\n divisor = 0\n dividendo = 0\n resultado = 0\n residuo = 0\n\n def __init__(self, dividendo, divisor):\n self.divisor = divisor\n self.dividendo = dividendo\n\n def dividir(self):\n pass\n\n\nclass Divisonentera(Division):\n def __init__(self, dividendo, divisor):\n super().__init__(dividendo, divisor)\n\n def dividir(self):\n\n return self.dividendo // self.divisor, self.dividendo % self.divisor\n\n\nclass Divisondecimal(Division):\n def __init__(self, dividendo, divisor):\n super().__init__(dividendo, divisor)\n\n def dividir(self):\n return self.dividendo / self.divisor\n\n\nif __name__ == '__main__':\n de = Divisonentera(15, 3)\n res = de.dividir()\n print(res)\n\n dd = Divisondecimal(16, 3)\n res2 = dd.dividir()\n print(res2)\n" }, { "alpha_fraction": 0.6798780560493469, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 20.866666793823242, "blob_id": "de57284679be85de63c1ad02e4a539ece266522d", "content_id": "c104b67d0ec7bb70bf5efe066a68cb3715951c5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 54, "num_lines": 15, "path": "/Tarea1.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "from Pack.Tarea1_Modulo import funcion\nimport random\n\n\ndef main():\n funcion(s_user, s_pc)\n\n\nprint('Bienvenido al juego de piedra, papel o tijera')\nprint('Escribe tu eleccion: ')\ns_user = input()\ns_pc = random.choice(['piedra', 'papel', 'tijera'])\nprint('Eleccion de usuario: ', s_user)\nprint('Eleccion de PC: ', s_pc)\nmain()\n" }, { "alpha_fraction": 0.5606407523155212, "alphanum_fraction": 0.6018306612968445, "avg_line_length": 15.185185432434082, "blob_id": "017b58d5cada34e0a41d0c1fed39f15cf753bd59", "content_id": "733c9106653bb7132b5bf4750946a10fa67f8d48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 57, "num_lines": 27, "path": "/clienteAsistencia.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import socket\nimport pickle\nfrom estudiante import Estudiante\n\n\ndef main():\n s = socket.socket()\n\n host = '3.16.226.150'\n port = 9999\n\n s.connect((host, port))\n\n estudiante = Estudiante(\"Elliot Ruiz Sanchez\", \"[email protected]\", \"IECA8\")\n\n estudiante_seriado = pickle.dumps(estudiante)\n\n s.send(estudiante_seriado)\n\n res = s.recv(1024)\n print(f'Respuesta: \\n\\t{res.decode()}')\n\n s.close()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6393442749977112, "alphanum_fraction": 0.6475409865379333, "avg_line_length": 12.666666984558105, "blob_id": "f1614f71c56b7121756ef391e25dc391b9e2e555", "content_id": "d58e697fd9f37c0ffa30896427beae8482bb2010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/Pickle.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import pickle\n\nfile = open('data.dat', 'wb')\n\nanimals = ['python', 'monkey', 'camel']\n\npickle.dump(animals, file, 2)\n\npass" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.675000011920929, "avg_line_length": 11.1304349899292, "blob_id": "e52b4eb4ed1889c08bd85a431b76e6875210f6da", "content_id": "b4f7e3031affa129f961957a7bbcd66720eb1030", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 78, "num_lines": 23, "path": "/server.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import pickle\n\ns = 'Hola mundo'\n\nprint(s)\nprint(type(s))\n\nse = s.encode()\n\nprint(se)\nprint(type(se))\n\nsp = pickle.dumps(s)\n\nprint(sp)\nprint(type(sp))\n\nss2 = pickle.loads(se)\n\nprint(ss2)\nprint(type(ss2))\n\n# No imprime debido a que encuenra una h primero en lugar de la direccion \\x80\n\n" }, { "alpha_fraction": 0.4193103313446045, "alphanum_fraction": 0.4193103313446045, "avg_line_length": 24.89285659790039, "blob_id": "28dd8521203676027c04ea6cb7b998750416369f", "content_id": "63947babb6a1cacc9eb6ce4fb7b0318db53a42b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "no_license", "max_line_length": 53, "num_lines": 28, "path": "/Pack/Tarea1_Modulo.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "# import random\n# s_user = input()\n# s_pc = random.choice(['piedra', 'papel', 'tijera'])\n# s_user = 'piedra', s_pc = 'tijera'\n\n\ndef funcion(s_user, s_pc):\n\n if s_user != s_pc:\n if s_user == 'piedra':\n if s_pc == 'papel':\n print('Perdiste!')\n else:\n print('Ganaste!')\n elif s_user == 'papel':\n if s_pc == 'tijera':\n print('Perdiste!')\n else:\n print('Ganaste!')\n elif s_user == 'tijera':\n if s_pc == 'piedra':\n print('Perdiste!')\n else:\n print('Ganaste!')\n else:\n print('Seleccion no valida!')\n else:\n print('Empate!')\n" }, { "alpha_fraction": 0.5372093319892883, "alphanum_fraction": 0.5418604612350464, "avg_line_length": 20.5, "blob_id": "1a411aecabf67effd4558ec74a4a49cc62e80fc5", "content_id": "1e79971246a3726d1f26afaf24015f4be79f1eb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/POO.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "class Persona:\n nombre = ''\n correo = ''\n\n def __init__(self):\n self.edad = 24\n self.nombre = 'Elliot'\n self.correo = '[email protected]'\n\n def saludar(self, nombre):\n print('Hola', nombre)\n print(self.nombre, '\\n', self.correo, '\\n', self.edad)\n\n\n# name por que es una variable especifica y main para ejecutarse\nif __name__ == '__main__':\n\n p = Persona()\n p.saludar('ERS')\n print(p)\n" }, { "alpha_fraction": 0.6272878646850586, "alphanum_fraction": 0.662229597568512, "avg_line_length": 29.049999237060547, "blob_id": "7fde95f5a24c379d51e96f499a1abe479d037715", "content_id": "0243f9b875069756871631b12d072530a3aec649", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 84, "num_lines": 20, "path": "/Tupla.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "#En las tuplas no puede cambiar ni un solo valor despues de declararlas al principio\n#Si se usa tupla[-1] (un negativo en el indice) busca de fin a inicio\n#Los indices empiezan desde 0\n# https://recursospython.com/guias-y-manuales/listas-y-tuplas/\n\ntupla = 'Hola' , 2 , 3.4 , False , [ 1 , 'test' ] , 2 , 2\ntupla2 = tuple()\n\nprint(f'Tupla: {tupla[0]}')\nprint(f'Tupla: {tupla[1]}')\nprint(f'Tupla: {tupla[2]}')\nprint(f'Tupla: {tupla[3]}')\nprint(f'Tupla: {tupla[4][1]}')\nprint(f'Tupla(-1): {tupla[-1]}')\nprint(f'Tupla2: {tupla2}')\n\nprint(type(tupla2))\n\nconteo = tupla.count(2)\nprint('Conteo: ' , conteo)\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.665517270565033, "avg_line_length": 14.263157844543457, "blob_id": "cf314791dd645d8a60db6efa1dfc83c65938b024", "content_id": "b7db43d946417df77902f6b4519a202757586ea0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "no_license", "max_line_length": 40, "num_lines": 19, "path": "/Regex.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import re\n\ntexto = 'Buenas tardes a todos y todas'\n\npatron = 'B.*t.*a'\npatron2 = 'd[aeo]s'\n\ncoincidencia = re.match(patron, texto)\n\ncoincidencia2 = re.search(patron, texto)\n\nencontrar = re.findall(patron2, texto)\n\nlista = ['unos', 'dos', 'tres']\n\nfor item in lista:\n m = re.search\n\npass\n" }, { "alpha_fraction": 0.7768924236297607, "alphanum_fraction": 0.7808765172958374, "avg_line_length": 24.200000762939453, "blob_id": "b9c95fad2732c42181a02ae568854a1159936d16", "content_id": "6c7d2453f527baa3118d97daee4eef198042a851", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 50, "num_lines": 10, "path": "/PruebasQT/Hello World.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import sys\n# Importando la clase apropiada\nfrom PySide6.QtWidgets import QApplication, QLabel\n\n# Crear instancia QApp\napp = QApplication(sys.argv)\n# Es posible pasar cualquier argumento a QApp Obj\nlabel = QLabel(\"Hello World\")\nlabel.show()\napp.exec_()" }, { "alpha_fraction": 0.5442020893096924, "alphanum_fraction": 0.5568312406539917, "avg_line_length": 27.09677505493164, "blob_id": "a9361b9158151cbd26aa7622f209bb63f15f42a1", "content_id": "943d1bb29478685cba3d875aa94211ca37d5d66a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 871, "license_type": "no_license", "max_line_length": 58, "num_lines": 31, "path": "/Tarea3.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "from Pack.StudentIO import agregar\nfrom Pack.StudentIO import lectura\nfrom Pack.StudentIO import actualizar\nfrom Pack.StudentIO import pickle1\n\n\ndef menu():\n while True:\n print(\"Bienvenido a la tarea 3.\")\n print(\"1. Agregar nuevo alumno.\")\n print(\"2. Lectura de alumno.\")\n print(\"3. Actualizar alumno.\")\n print(\"4. Salir del programa\")\n print(\"Ingrese su eleccion: \")\n choice = input()\n if choice == '1':\n # [PV] Ver comentarios el archivo StudentIO.py\n agregar()\n elif choice == '2':\n # [PV] Ver comentarios el archivo StudentIO.py\n lectura()\n pickle1()\n elif choice == '3':\n # [PV] Ver comentarios el archivo StudentIO.py\n actualizar()\n elif choice == '4':\n print(\"Adios!\")\n break\n\n\nmenu()\n" }, { "alpha_fraction": 0.6857143044471741, "alphanum_fraction": 0.699999988079071, "avg_line_length": 19.58823585510254, "blob_id": "1c76e7b8bf0466a4622beb83852f5783bb366430", "content_id": "25bacf0e5c718362fe9509aa525086ed47f3c228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 350, "license_type": "no_license", "max_line_length": 80, "num_lines": 17, "path": "/Lista.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "#En las listas se pueden cambiar los valores despues de declararlas al principio\n#Si se usa lista[-1] (un negativo en el indice) busca de fin a inicio\n#Los indices empiezan desde 0\n\nlista = [ ]\nlista2 = [ ]\n\nprint(f'Lista: {lista}')\nprint(f'Lista 2: {lista2}')\n\nprint(type(lista))\n\n# Agregar elementos\n# append()\n# insert()\n\n# Eliminar elementos\n" }, { "alpha_fraction": 0.6257668733596802, "alphanum_fraction": 0.6748466491699219, "avg_line_length": 10.642857551574707, "blob_id": "01257f9ad1af957599151e79f7d05e400cd249ba", "content_id": "841c1c38c2c1b1521af4533ec702f045107fddc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 32, "num_lines": 14, "path": "/clientTCP.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "import socket\n\ns = socket.socket()\nhost = socket.gethostname()\n\nport = 9999\n\ns.connect((host, port))\n\nmsg_recv = s.recv(1024).decode()\n\nprint(msg_recv)\n\ns.close()\n" }, { "alpha_fraction": 0.6747404932975769, "alphanum_fraction": 0.6782007217407227, "avg_line_length": 16, "blob_id": "0cf363e499a12d2b5c4bee64c858bd0bb2122a2d", "content_id": "fe1ffbba49228fe246942f3860768c151cf46352", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 289, "license_type": "no_license", "max_line_length": 41, "num_lines": 17, "path": "/Tarea2.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "from Pack.Tarea2_Modulo import validacion\n\n\ndef main():\n validacion(correo, numero, curp, rfc)\n\n\nprint(\"Ingresa tu email: \")\ncorreo = input()\nprint(\"Ingresa tu numero celular: \")\nnumero = input()\nprint(\"Ingresa tu CURP: \")\ncurp = input()\nprint(\"Ingresa tu RCF: \")\nrfc = input()\n\nmain()\n" }, { "alpha_fraction": 0.44999998807907104, "alphanum_fraction": 0.5166666507720947, "avg_line_length": 9.909090995788574, "blob_id": "9c392a39d92504d7f7eb5f3665c1f176cd207606", "content_id": "9e27f8ce3e03961f2b5ceb0a33d667067606834e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 19, "num_lines": 11, "path": "/condicionales.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "\nverdadero = 3 < 5\nfalso = 5 > 3\n\nif falso:\n print('Buenas')\n\nelif 4 > 6:\n print('4 > 6')\n\nelse:\n print('Ciao')" }, { "alpha_fraction": 0.561904788017273, "alphanum_fraction": 0.5746031999588013, "avg_line_length": 19.54347801208496, "blob_id": "e623c5d0de919626b3cf76d44d35e1639d18ade8", "content_id": "38707671c1f6b6dae420c67fd7a7d7015c002f72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 38, "num_lines": 46, "path": "/Pack/Tarea3_Clase.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "class Estudiante:\n\n def __init__(self):\n self.nombre = \"Elliot Ruiz\"\n self.carrera = \"Mecatronica\"\n self.correo = \"[email protected]\"\n self.num_control = \"16240056\"\n self.promedio = \"82.47\"\n\n def setnombre(self):\n nombre = input()\n self.nombre = nombre\n\n def getnombre(self):\n return self.nombre\n\n def setcarrera(self):\n carrera = input()\n self.carrera = carrera\n\n def getcarrera(self):\n return self.carrera\n\n def setcorreo(self):\n correo = input()\n self.correo = correo\n\n def getcorreo(self):\n return self.correo\n\n def setnum_control(self):\n num_control = input()\n self.num_control = num_control\n\n def getnum_control(self):\n return self.num_control\n\n def setpromedio(self):\n promedio = input()\n self.promedio = promedio\n\n def getpromedio(self):\n return self.promedio\n\n\ne = Estudiante()\n" }, { "alpha_fraction": 0.6208053827285767, "alphanum_fraction": 0.6409395933151245, "avg_line_length": 18.866666793823242, "blob_id": "d70c3e4e3d4028cff96515e2b1dfedef34d1d49f", "content_id": "96d9bc501c777bd87ee5662e80b55bd57eeac48c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 298, "license_type": "no_license", "max_line_length": 119, "num_lines": 15, "path": "/Archivo.py", "repo_name": "Elliot-Ruiz96/CursoPython", "src_encoding": "UTF-8", "text": "f = open(\"./DarthPlagueis.txt\", 'w+') # f: <_io.TextIOWrapper name='./DarthPlagueis.txt' mode='a+' encoding='cp1252'>\n\ng = open(\"./Pruebas.txt\", 'w+')\n\nret = f.read()\nreadable = f.readable()\nwritable = f.writable()\n\nret2 = g.write('Hola mundo\\n')\ng.seek(0)\n\nprint(readable)\nprint(writable)\n\npass\n" } ]
33
parklam/exchange_log_handler
https://github.com/parklam/exchange_log_handler
127fdfee5db15decea81ab71034339f5fa6622ec
a3684825c97117867d63cf477b1f1bc4fd56485f
de53b961ea73ed87030d6143baa01ff3bcb8fabc
refs/heads/master
2023-07-20T05:02:15.121181
2023-07-14T06:07:51
2023-07-14T06:07:51
230,171,674
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.550605833530426, "alphanum_fraction": 0.5523877143859863, "avg_line_length": 33.219512939453125, "blob_id": "2e3ec6a717f759f45d1743e661aa901a53832faf", "content_id": "16131ce1ec9e763ee7c59f048b333c0e85ae61dd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2806, "license_type": "permissive", "max_line_length": 81, "num_lines": 82, "path": "/exchange_log_handler/__init__.py", "repo_name": "parklam/exchange_log_handler", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# coding: utf-8\n'''\nAuthor: Park Lam <[email protected]>\n'''\n\nimport json\nimport re\nfrom exchangelib import DELEGATE, Account, Credentials, Configuration, Mailbox, \\\n Message\nfrom logging import Handler\n\nclass ExchangeHandler(Handler):\n \"\"\"\n A handler class which send logging records as email via ExChange server.\n \"\"\"\n def __init__(self, credentials, toaddrs, fromaddr=None, \\\n subject=None, access_type=DELEGATE, \\\n ews_url='https://outlook.office365.com/ews/exchange.asmx'):\n \"\"\"\n Initialize the handler\n \"\"\"\n Handler.__init__(self)\n if isinstance(credentials, (list, tuple)):\n self._username, self._password = credentials\n self._credentials = Credentials(username=self._username, \\\n password=self._password)\n elif isinstance(credentials, Credentials):\n self._credentials = credentials\n else:\n raise TypeError('Invalid credentials Type')\n\n self._config = Configuration(service_endpoint=ews_url, \\\n credentials=self._credentials)\n if fromaddr:\n self._fromaddr = fromaddr\n else:\n self._fromaddr = self._credentials.username\n if isinstance(toaddrs, str):\n self._toaddrs = [ i.strip() for i in toaddrs.replace(';', ',') \\\n .strip(',').split(',') ]\n elif isinstance(toaddrs, (list, tuple)):\n self._toaddrs = toaddrs\n for toaddr in toaddrs:\n assert re.match(r\"^\\S+@\\S+\\.\\S+$\", toaddr, re.M|re.I), \\\n 'invalid_email'\n self._subject = subject\n self._access_type = access_type\n\n def get_account(self):\n return Account(primary_smtp_address=self._fromaddr, \\\n config=self._config, autodiscover=False, \\\n access_type=self._access_type)\n\n def get_subject(self, record):\n if callable(self._subject):\n return self._subject(record)\n elif isinstance(self._subject, str):\n return self._subject\n return self._subject or 'No subject'\n\n def get_content(self, record):\n return self.format(record)\n\n def emit(self, record):\n \"\"\"\n Emit a record.\n \"\"\"\n try:\n acct = self.get_account()\n subject = self.get_subject(record)\n cont = self.get_content(record)\n msg = Message(\n account=acct,\n folder=acct.sent,\n subject=subject,\n body=cont,\n to_recipients=[ Mailbox(email_address=addr) \\\n for addr in self._toaddrs ])\n msg.send_and_save()\n except Exception:\n self.handleError(record)\n" }, { "alpha_fraction": 0.45652174949645996, "alphanum_fraction": 0.6739130616188049, "avg_line_length": 14.333333015441895, "blob_id": "8b42001987db19c13e4cc9bf3045420b9d708c22", "content_id": "356a9cbe6a517b5b0dfcbdfc0808cd5a4c84c064", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 46, "license_type": "permissive", "max_line_length": 18, "num_lines": 3, "path": "/requirements.txt", "repo_name": "parklam/exchange_log_handler", "src_encoding": "UTF-8", "text": "wheel>=0.31.0\ntwine==3.1.1\nexchangelib==2.1.1\n" }, { "alpha_fraction": 0.5015105605125427, "alphanum_fraction": 0.5037764310836792, "avg_line_length": 27.17021369934082, "blob_id": "474e86eecbae0c7e61d091c38b4c0954527ac484", "content_id": "8c3c6bd7cf42aba24472a85e64bc0832240f8797", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1324, "license_type": "permissive", "max_line_length": 112, "num_lines": 47, "path": "/README.md", "repo_name": "parklam/exchange_log_handler", "src_encoding": "UTF-8", "text": "# exchange_log_handler\nLog handler to send log via exchange\n\n## Dependencies\nThis library used [ecederstrand/exchangelib](https://github.com/ecederstrand/exchangelib) to send exchange mail.\n\n## How to install:\n`\npip install exchange-log-handler\n`\n## Usage:\n```\nif __name__ == '__main__':\n import logging\n import logging.config\n logging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'stream': 'ext://sys.stdout',\n },\n 'email': {\n 'level': 'ERROR',\n 'class': 'exchange_log_handler.ExchangeHandler',\n 'credentials': ('email_address', 'email_password'),\n 'subject': lambda r: '{0}-{1}'.format(r.levelname, r.name),\n 'toaddrs': 'recipient_email_address',\n },\n },\n 'loggers': {\n '': {\n 'handlers': [ 'console', 'email' ],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n },\n })\n\n logger = logging.getLogger(__name__)\n try:\n raise ValueError('This is a test exception.')\n except Exception as e:\n logger.exception(e)\n```\n" } ]
3
zirconium-n/OFE
https://github.com/zirconium-n/OFE
d768edffe59d9d08d03e2a90a7e77ea5fdf87dee
5262f9e17b402df38f08f1a2b70ef50d1e427369
327103b4ef3b34a4ebe74c8e1f1c8f7ebc45b846
refs/heads/master
2020-11-25T11:45:21.221252
2019-12-17T18:15:23
2019-12-17T18:15:23
228,640,192
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.43775099515914917, "alphanum_fraction": 0.6064257025718689, "avg_line_length": 70.28571319580078, "blob_id": "2a7d6f86e944bb2a64c1f10356a985d4d6cfe51b", "content_id": "e5550d44bc0996b5f93d777f8b3a7689c8e1d738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 127, "num_lines": 7, "path": "/OFE/OFE_Panels.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "Panel_Name = ['Void', 'Neutral', 'Check', 'Encounter', 'Draw', 'Bonus', 'Drop', 'Warp', 'Draw_2', 'Bonus_2', 'Drop_2', 'Deck', \n\t'Encounter_2', 'Move', 'Move_2', 'WarpMove', 'WarpMove_2', 'Snow', 'Ice', 'Heal', 'Heal_2','Boss','Damage','Damage_2']\nPanel_Int = [0,1,2,3,4,5,6,7,8,9,10,18,20,21,22,23,24,25,26,27,28,31,32,33]\nButton_Brush_Int = [0,2,5,9,6,10,3,20,4,8,21,22,23,24,7,25,1,18,26,27,28,31,32,33]\n\nassert(len(Panel_Name) == len(Panel_Int))\nassert(len(Panel_Name) == len(Button_Brush_Int))" }, { "alpha_fraction": 0.6075401902198792, "alphanum_fraction": 0.6180469989776611, "avg_line_length": 24.296875, "blob_id": "5f5e056a35aff6c4a2a7192b92bcb005703133fd", "content_id": "381e69fe058466cb04879363a1c1f0a0cf656175", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1748, "license_type": "no_license", "max_line_length": 87, "num_lines": 64, "path": "/OFE/OFE_Graphics.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "import os\nfrom PIL import Image\n\nclass OFE_Graphics:\n\tdef __init__(self, zoom_list, path):\n\t\t\n\t\t#初始化\n\t\tself.zoom_list = zoom_list\n\t\t#将path目录下所有文件(不包含其下级目录),若能打开,全部存入。\n\t\tprint('[Loading images...]')\n\t\tself.img_o_dict = {}\n\t\tbad_img = []\n\t\tfor file_name in os.listdir(path):\n\t\t\ttry:\n\t\t\t\timg = Image.open(path + '/' + file_name)\n\t\t\texcept:\n\t\t\t\tbad_img.append(file_name)\n\t\t\telse:\n\t\t\t\tdot_pos = file_name.index('.')\n\t\t\t\tname = file_name[:dot_pos]\n\t\t\t\tself.img_o_dict[name] = img\n\t\t#汇报加载结果\n\t\timg_count = len(self.img_o_dict)\n\t\tprint(img_count, 'images have been loaded.')\n\t\tfor file_name in bad_img:\n\t\t\tprint('Warning: ' + file_name + ' is not a image')\n\t\t\t\n\t\t#将不同zoom level的图生成出来\n\t\tprint('[Creating zooming images...]')\n\t\tself.img_zoom_dict = self.Img_Zoom(self.img_o_dict, zoom_list)\n\t\t\n\t\t#汇报生成的zoom总计\n\t\tprint(zoom_list, 'zoom levels have been created')\n\t\t\n\tdef get_image(self, name, zoom = 1.0):\n\t\ttry:\n\t\t\timg = self.img_zoom_dict[name][zoom]\n\t\texcept:\n\t\t\tif not name in self.img_zoom_dict:\n\t\t\t\tprint('Error: ', name, ' is not in graphics')\n\t\t\tif not zoom in self.zoom_list:\n\t\t\t\tprint('Error: ', zoom, ' is not in zoom_list')\n\t\telse:\n\t\t\treturn img\n\t\t\n\tdef Img_Zoom(self, img_o_dict, zoom_list):\n\t\tnew_dict = {}\n\t\tPX = 128\n\t\tfor name in img_o_dict:\n\t\t\tnew_dict[name] = {}\n\t\t\timg = img_o_dict[name]\n\t\t\tfor zoom in zoom_list:\n\t\t\t\tpx = int(PX * zoom)\n\t\t\t\timg_new = img.resize((px,px), Image.BICUBIC)\n\t\t\t\tnew_dict[name][zoom] = img_new\n\t\t\t\t\n\t\treturn new_dict\n\t\t\t\n\t\t\n\t\t\n\t\t\nif __name__ == '__main__':\n\tgraphics = OFE_Graphics([0.5, 0.75], r'D:\\OneDrive\\个人\\100oj\\橙汁地图编辑器\\OFE正式v1.0\\panels')\n\tgraphics.get_image('Panel_Bonus', 0.5)" }, { "alpha_fraction": 0.597846269607544, "alphanum_fraction": 0.6092824935913086, "avg_line_length": 23.32839012145996, "blob_id": "125176e783077265af2000e50e12cc6e562e386e", "content_id": "7ed2e23e4531e4d5700354e43d3819740a3d174e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36676, "license_type": "no_license", "max_line_length": 117, "num_lines": 1416, "path": "/OFE/OFE_Canvas.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "#OFE_Canvas\nimport sys, os\nimport copy\nfrom PyQt5 import QtGui, QtWidgets, QtCore\nfrom PIL import Image\nfrom PIL.ImageQt import ImageQt\n\nfrom OFE.OFE_Field import OFE_Field\nfrom OFE.OFE_Image import OFE_Image\nfrom OFE import Panel_Int, Panel_Name, Button_Brush_Int\n#根目录\npath0 = os.path.dirname(__file__)\n\n\n#按照list[y][x]制作新Img\ndef New_Px(DATA):\n\t\n\ttype = \"RGBA\"\n\tif len(DATA[0][0]) == 3:\n\t\ttype = \"RGB\"\n\t\t\n\tY = len(DATA)\n\tX = len(DATA[0])\n\t\n\tImg = Image.new(\"RGBA\", (X,Y),(0,0,0,0))\n\t\n\tPUT_DATA = []\n\t\n\tfor raw in DATA:\n\t\tPUT_DATA += raw\n\t\t\n\tImg.putdata(PUT_DATA)\n\t\n\treturn Img\n#图片格式转换\ndef PIXMAP(img):\n\tImgQt = ImageQt(img)\n\tpixmap = QtGui.QPixmap.fromImage(ImgQt)\n\treturn pixmap\n\t\n#Zoom List\nZoom_List = [0.5]\n\t\n\t\n#画板本体\nclass Canvas(QtWidgets.QLabel):\n\tdef __init__(self, field, PARAMETER, statue, App = None, file_name = 'Title', file_path = '', parent = None):\n\t\tsuper(Canvas,self).__init__(parent)\n\t\tself.init(field, PARAMETER, statue, App, file_name, file_path)\n\t\t\n\tdef init(self, field, PARAMETER, statue, App = None, file_name = 'Title', file_path = ''):\n\t\t\n\t\t#初始化\n\t\tself.setMouseTracking(True)\n\t\tself.file_name = file_name\n\t\tself.file_path = file_path\n\n\t\t\n\t\t#从PARAMETER中提取\n\t\tself.Graphics = PARAMETER['Graphics']\n\t\tself.file = {'Field':field, 'History':[], 'Pos':1, 'Change':0}\n\t\tself.Selected = {'Type': 'None', 'Pos_Start':(0,0), 'Pos_End':(0,0), 'Copy_Index': 0, \n\t\t\t\t'Trans_Field': None, 'Trans_Pos': (0,0), 'Trans_Img': None, 'Trans_Dis': (0,0), 'Duplicate_Index': 0}\n\t\tif self.Is_Field():\n\t\t\tself.file['History'].append(copy.deepcopy(field))\n\t\t\tself.file['Pos'] = 1\n\t\tself.PARAMETER = PARAMETER\n\t\tself.statue = statue\n\t\tself.App = App\n\t\t\n\t\t#初始化\n\t\tself.Field_Img = None\n\t\tself.Paint_Command = {'All':None}\n\t\tself.Save_Index = 0\n\t\t\n\t\t#鼠标格子位置\n\t\tself.X = 0\n\t\tself.Y = 0\n\t\tself.X_old = 0\n\t\tself.Y_old = 0\n\t\t\n\t\t#初始画定大小\n\t\tself.Img_Draw({'All':None})\n\t\n\t#是否是地图文件\n\tdef Is_Field(self):\n\t\tif self.file['Field'].data:\n\t\t\treturn True\n\t\telse:\n\t\t\tFalse\n\t\t\t\n\t#返回本地图\n\tdef Field(self):\n\t\treturn self.file['Field']\n\t\n\t##鼠标\n\t#设置移动上下限\n\tdef Set_XY(self, pos):\n\t\tMin = 0\n\t\tSize = self.file['Field'].size()\n\t\tMaxX = Size[0] - 1\n\t\tMaxY = Size[1] - 1\n\t\t\n\t\treturn max(0, min(pos[0], MaxX)), max(0, min(pos[1], MaxY))\n\t\t\n\t\t\n\t\t\n\t#返回是否在格点上发生移动\n\tdef Is_Move(self):\n\t\tif self.X != self.X_old or self.Y != self.Y_old:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\t\t\n\t#位置作差\n\tdef Pos_Minus(self, pos1, pos2):\n\t\tposnew = (pos1[0]-pos2[0], pos1[1]-pos2[1])\n\t\treturn posnew\n\t\t\n\t#位置作和\n\tdef Pos_Add(self, pos1, pos2):\n\t\tposnew = (pos1[0]+pos2[0], pos1[1]+pos2[1])\n\t\treturn posnew\n\t\t\t\n\t#返回是否处在Transform区域中以及偏差距离\n\tdef Distance(self):\n\t\tx1 = self.Selected['Trans_Pos'][0]\n\t\ty1 = self.Selected['Trans_Pos'][1]\n\t\t\n\t\tsize_area = self.Selected['Trans_Field'].size()\n\t\t\n\t\tx2 = x1 + size_area[0]\n\t\ty2 = y1 + size_area[1]\n\t\t\n\t\tif self.X in range(x1, x2) and self.Y in range(y1, y2):\n\t\t\tx_dis = self.X - x1\n\t\t\ty_dis = self.Y - y1\n\t\t\treturn (x_dis, y_dis)\n\t\telse:\n\t\t\treturn None\n\t\t\t\n\t\n\t\n\t#鼠标点击\n\tdef mousePressEvent(self, event):\n\t\tpanel_count = len(Panel_Int)\n\t\tbutton_count = 6\n\t\ttransform_count = 6\n\n\t\tcommand = {}\n\t\tif self.file['Field'].data:\n\t\t\t#鼠标位置\n\t\t\tpos = event.pos()\n\t\t\tx = pos.x()\n\t\t\ty = pos.y()\n\t\t\t\n\t\t\tPX = 128\n\t\t\tzoom = self.PARAMETER['Img_parameter']['Zoom']\n\t\t\tpx = int(PX * zoom)\n\t\t\t\n\t\t\tself.X, self.Y = self.Set_XY((int(x / px), int(y / px)))\n\t\t\tPOS = (self.X, self.Y)\n\t\t\n\t\tif event.button() == QtCore.Qt.RightButton:\n\t\t\t#右键按下指令\n\t\t\tprint(event.pos())\n\t\t\tif self.file['Field'].data:\n\t\t\t\tButton_id = self.PARAMETER['Command']['Button']\n\t\t\t\t#Brush删除模式\n\t\t\t\tif Button_id >= 0 and Button_id < panel_count:\n\t\t\t\t\tpanel_id = 0\n\t\t\t\t\tischange = self.Point_Panel(panel_id)\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\t\t\t\n\t\t\t\t#删除箭头\n\t\t\t\tif Button_id >= panel_count + 1 and Button_id <= panel_count + 3:\n\t\t\t\t\tischange = self.Point_Arrow(arrow_command = [-1,-1,-1,-1])\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\n\t\telif event.button() == QtCore.Qt.LeftButton:\n\t\t\t#左键按下指令\n\t\t\tif self.file['Field'].data:\n\t\t\t\tButton_id = self.PARAMETER['Command']['Button']\n\t\t\t\t#Brush模式\n\t\t\t\tif Button_id >= 0 and Button_id < panel_count:\n\t\t\t\t\tB_command = self.PARAMETER['Command']['Button']\n\t\t\t\t\tpanel_id = Button_Brush_Int[B_command]\n\t\t\t\t\tischange = self.Point_Panel(panel_id)\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\t\t\t\n\t\t\t\t#删除箭头\n\t\t\t\tif Button_id == panel_count + 1 :\n\t\t\t\t\tischange = self.Point_Arrow(arrow_command = [-1,-1,-1,-1])\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\t\t\t\n\t\t\t\t#选择模式\n\t\t\t\tif Button_id == panel_count:\n\t\t\t\t\tif self.Selected['Type'] == 'None' or self.Selected['Type'] == 'Selected':\n\t\t\t\t\t\t#取消Copy IndexError\n\t\t\t\t\t\tself.Selected['Copy_Index'] = 0\n\t\t\t\t\t\tself.Selected['Type'] = 'Selecting'\n\t\t\t\t\t\tself.Selected['Pos_Start'] = POS\n\t\t\t\t\t\tself.Selected['Pos_End'] = POS\n\t\t\t\t\t\tcommand['Cursor'] = None\n\t\t\t\t\t\t\n\t\t\t\t#变换模式\n\t\t\t\tif Button_id == panel_count:\n\t\t\t\t\tif self.Selected['Type'] == 'Transform':\n\t\t\t\t\t\tdis = self.Distance()\n\t\t\t\t\t\tif dis:\n\t\t\t\t\t\t\tself.Selected['Type'] = 'Transforming'\n\t\t\t\t\t\t\tself.Selected['Trans_Dis'] = dis\n\t\t\t\t\t\n\t\tif command != {}:\n\t\t\tself.A_Paint(command)\n\t\t\t\n\t#鼠标移动\n\t\n\tdef mouseMoveEvent(self, event):\n\t\t\n\t\tif self.file['Field'].data:\n\t\t\t#将当前位置记录\n\t\t\tself.X_old = self.X\n\t\t\tself.Y_old = self.Y\n\t\t\n\t\tcommand = {}\n\t\tif self.file['Field'].data:\n\t\t\t#鼠标位置\n\t\t\tpos = event.pos()\n\t\t\tx = pos.x()\n\t\t\ty = pos.y()\n\t\t\t\n\t\t\tPX = 128\n\t\t\tzoom = self.PARAMETER['Img_parameter']['Zoom']\n\t\t\tpx = int(PX * zoom)\n\t\t\t\n\t\t\tself.X, self.Y = self.Set_XY((int(x / px), int(y / px)))\n\t\t\tPOS = (self.X, self.Y)\n\t\t\t\n\t\t\t#状态条改变\n\t\t\ttext = ''\n\t\t\ttext += 'size = ('+str(self.file['Field'].size()[0])+', '+str(self.file['Field'].size()[1])+')'\n\t\t\ttext += ' | '\n\t\t\ttext += 'pos = ('+str(self.X)+', '+str(self.Y)+')'\n\t\t\t\n\t\t\tself.statue.showMessage(text)\n\t\t\t\n\t\t\t#刷新光标\n\t\t\tif self.Is_Move():\n\t\t\t\tcommand['Cursor'] = None\n\t\t\t\n\t\t\t\n\t\tif event.buttons() == QtCore.Qt.RightButton:\n\t\t\t#右键移动指令\n\t\t\tprint(event.pos())\n\t\t\tif self.file['Field'].data:\n\t\t\t\tButton_id = self.PARAMETER['Command']['Button']\n\t\t\t\t#Brush删除模式\n\t\t\t\tif Button_id >= 0 and Button_id < len(Button_Brush_Int):\n\t\t\t\t\tpanel_id = 0\n\t\t\t\t\tischange = self.Point_Panel(panel_id)\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\t\t\t\n\t\t\t\t#删除箭头\n\t\t\t\tif Button_id >= len(Button_Brush_Int) + 1 and Button_id <= len(Button_Brush_Int) + 3:\n\t\t\t\t\tischange = self.Point_Arrow(arrow_command = [-1,-1,-1,-1])\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\t\t\n\t\telif event.buttons() == QtCore.Qt.LeftButton:\n\t\t\t#左键按下指令\n\t\t\tif self.file['Field'].data:\n\t\t\t\tButton_id = self.PARAMETER['Command']['Button']\n\t\t\t\t#Brush模式\n\t\t\t\tif Button_id >= 0 and Button_id < len(Button_Brush_Int):\n\t\t\t\t\tB_command = self.PARAMETER['Command']['Button']\n\t\t\t\t\tpanel_id = Button_Brush_Int[B_command]\n\t\t\t\t\tischange = self.Point_Panel(panel_id)\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t#删除箭头\n\t\t\t\tif Button_id == len(Button_Brush_Int) + 1:\n\t\t\t\t\tischange = self.Point_Arrow(arrow_command = [-1,-1,-1,-1])\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tcommand['Point'] = POS\n\t\t\t\t\t\t\n\t\t\t\t#Line箭头\n\t\t\t\tif Button_id == len(Button_Brush_Int) + 2:\n\t\t\t\t\tPOS_old = (self.X_old, self.Y_old)\n\t\t\t\t\t#两个格子中有任意虚空格无效\n\t\t\t\t\tif not (self.file['Field'].Point_IsVoid(POS) or self.file['Field'].Point_IsVoid(POS_old)):\n\t\t\t\t\t\tArrow_Name = ['Left', 'Up', 'Right', 'Down']\n\t\t\t\t\t\tarrow_command = [0,0,0,0]\n\t\t\t\t\t\tarrow_add = ''\n\t\t\t\t\t\tif self.X - self.X_old == -1:\n\t\t\t\t\t\t\tarrow_add = 'Left'\n\t\t\t\t\t\telif self.X - self.X_old == 1:\n\t\t\t\t\t\t\tarrow_add = 'Right'\n\t\t\t\t\t\telif self.Y - self.Y_old == -1:\n\t\t\t\t\t\t\tarrow_add = 'Up'\n\t\t\t\t\t\telif self.Y - self.Y_old == 1:\n\t\t\t\t\t\t\tarrow_add = 'Down'\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif arrow_add != '':\n\t\t\t\t\t\t\tarrow_command[Arrow_Name.index(arrow_add)] = 1\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tischange = self.Point_Arrow(arrow_command, old = True)\n\t\t\t\t\t\tif ischange:\n\t\t\t\t\t\t\tcommand['Point'] = POS_old\n\t\t\t\t\t\t\n\t\t\t\t#Line删除箭头\n\t\t\t\tif Button_id == len(Button_Brush_Int) + 3:\n\t\t\t\t\tArrow_Name = ['Left', 'Up', 'Right', 'Down']\n\t\t\t\t\tarrow_command = [0,0,0,0]\n\t\t\t\t\tarrow_add = ''\n\t\t\t\t\tif self.X - self.X_old == -1:\n\t\t\t\t\t\tarrow_add = 'Left'\n\t\t\t\t\telif self.X - self.X_old == 1:\n\t\t\t\t\t\tarrow_add = 'Right'\n\t\t\t\t\telif self.Y - self.Y_old == -1:\n\t\t\t\t\t\tarrow_add = 'Up'\n\t\t\t\t\telif self.Y - self.Y_old == 1:\n\t\t\t\t\t\tarrow_add = 'Down'\n\t\t\t\t\t\t\n\t\t\t\t\tif arrow_add != '':\n\t\t\t\t\t\tarrow_command[Arrow_Name.index(arrow_add)] = -1\n\t\t\t\t\t\t\n\t\t\t\t\tischange = self.Point_Arrow(arrow_command, old = True)\n\t\t\t\t\tif ischange:\n\t\t\t\t\t\tPOS_old = (self.X_old, self.Y_old)\n\t\t\t\t\t\tcommand['Point'] = POS_old\n\t\t\t\t\t\t\n\t\t\t\t#选择模式\n\t\t\t\tif Button_id == len(Button_Brush_Int):\n\t\t\t\t\tif self.Selected['Type'] == 'Selecting':\n\t\t\t\t\t\tself.Selected['Pos_End'] = POS\n\t\t\t\t\t\t\n\t\t\t\tif Button_id == len(Button_Brush_Int):\n\t\t\t\t\tif self.Selected['Type'] == 'Transforming':\n\t\t\t\t\t\tself.Selected['Trans_Pos'] = self.Pos_Minus(POS, self.Selected['Trans_Dis'])\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\tif command != {}:\n\t\t\tself.A_Paint(command)\n\t\t\t\t\n\t#鼠标释放\n\tdef mouseReleaseEvent(self, Event):\n\t\t#记录\n\t\tif self.file['Field'].data:\n\t\t\tself.Record()\n\t\t#结束选择\n\t\tif self.Selected['Type'] == 'Selecting':\n\t\t\tself.Selected_Start()\n\t\t#结束move\n\t\tif self.Selected['Type'] == 'Transforming':\n\t\t\tself.Selected['Type'] = 'Transform'\n\t\t\t\n\t\tself.A_Paint({'Cursor':None})\n\t\n\t#按钮指令变化\n\tdef Button_Click(self, id):\n\t\t#在非选择模式,更换按钮\n\t\tif self.Selected['Type'] == 'None':\n\t\t\tif id >= 0 and id < len(Button_Brush_Int) + 4:\n\t\t\t\t#更换按钮\n\t\t\t\tself.PARAMETER['Command']['Button'] = id\n\t\t#在选择模式下,不更换按钮,执行fill指令\n\t\tif self.Selected['Type'] == 'Selected':\n\t\t\tischange = False\n\t\t\t#fill panel\n\t\t\tif id >= 0 and id < len(Button_Brush_Int):\n\t\t\t\tpanel_id = Button_Brush_Int[id]\n\t\t\t\tischange = self.Fill(panel_id)\n\t\t\t#fill 删除箭头\n\t\t\tif id == len(Button_Brush_Int) + 1:\n\t\t\t\t#删除箭头使用特殊id = 101\n\t\t\t\tischange = self.Fill(101)\n\t\t\t#取消选择\n\t\t\tif id == len(Button_Brush_Int) + 5:\n\t\t\t\tself.Selected_Cancel()\n\t\t\t\t\n\t\t\tif ischange:\n\t\t\t\t\n\t\t\t\t#储存\n\t\t\t\tself.Record()\n\t\t\t\t\n\t\t\t\t#对图像的改变\n\t\t\t\tPos1 = self.Selected['Pos_Start']\n\t\t\t\tPos2 = self.Selected['Pos_End']\n\t\t\t\tRec = [Pos1, Pos2]\n\t\t\t\tcommand = {'Rec':Rec}\n\t\t\t\tself.A_Paint(command)\n\t\t\t\t\n\t\t#Transform模式\n\t\t\n\t\tif self.Selected['Type'] == 'Transform':\n\t\t\t#确认变换\n\t\t\tif id == len(Button_Brush_Int) + 10:\n\t\t\t\tself.Transform_Ok()\n\t\t\t#取消变换\n\t\t\tif id == len(Button_Brush_Int) + 11:\n\t\t\t\tself.Transform_Cancel()\n\t\t\t\t\n\t\t\t#自由变换\n\t\t\tif id >= len(Button_Brush_Int) + 6 and id < len(Button_Brush_Int) + 10:\n\t\t\t\tlist = ['clockwise', 'anticlockwise', 'vertical', 'horizonal']\n\t\t\t\tsign = list[id - len(Button_Brush_Int) - 6]\n\t\t\t\tself.Free(sign)\n\n\t'''储存'''\n\tdef Save(self, path):\n\t\tif self.Is_Field() and path != '':\n\t\t\tfile_full = path\n\t\t\tfile_name = QtCore.QFileInfo(file_full).fileName()\n\t\t\t\n\t\t\t#储存文件\n\t\t\tself.file['Field'].Save(file_full)\n\t\t\t\n\t\t\t#更改配置\n\t\t\tself.file_name = file_name\n\t\t\tself.file_path = file_full\n\t\t\tself.Save_Index = len(self.file['History']) - self.file['Pos']\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#菜单栏更新\n\t\t\ta_command['Menu'] = None\n\t\t\t#储存标签变更\n\t\t\ta_command['Tab'] = None\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\t\n\t\t\n\t'''选择'''\n\tdef Selected_Start(self):\n\t\tself.Selected['Type'] = 'Selected'\n\t\tdef RePos(pos1, pos2):\n\t\t\tx1 = pos1[0]\n\t\t\tx2 = pos2[0]\n\t\t\ty1 = pos1[1]\n\t\t\ty2 = pos2[1]\n\t\t\tposmin = (min(x1,x2), min(y1,y2))\n\t\t\tposmax = (max(x1,x2), max(y1,y2))\n\t\t\treturn posmin, posmax\n\t\t\t\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tself.Selected['Pos_Start'], self.Selected['Pos_End'] = RePos(Pos1, Pos2)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\t#按钮图标变更\n\t\ta_command['Button'] = {'Icon':{}}\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\t\n\t\t\n\tdef Selected_Cancel(self):\n\t\t#设置\n\t\tself.Selected['Type'] = 'None'\n\t\tself.Selected['Type'] = 'None'\n\t\tself.Selected['Pos_Start'] = (0,0)\n\t\tself.Selected['Pos_End'] = (0,0)\n\t\t#更换按钮\n\t\tself.PARAMETER['Command']['Button'] = len(Button_Brush_Int)\n\t\t#光标更新\n\t\tcommand = {'Cursor':None}\n\t\tself.A_Paint(command)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\t#按钮图标变更\n\t\ta_command['Button'] = {'Icon':{}}\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t\t\n\t'''编辑'''\n\t#单点格子变化\n\tdef Point_Panel(self, panel_id):\n\t\tpos = (self.X, self.Y)\n\t\tischange = self.file['Field'].Point_Panel(pos, panel_id)\n\t\tif ischange:\n\t\t\tself.file['Change'] = 1\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#状态变更\n\t\t\ta_command['Status'] = {}\n\t\t\tif panel_id:\n\t\t\t\ta_command['Status']['Last_Action'] = 'Brush ' + Panel_Name[Panel_Int.index(panel_id)]\n\t\t\telse:\n\t\t\t\ta_command['Status']['Last_Action'] = 'Delete Panels'\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\t\t\n\t\treturn ischange\n\t\t\n\t#单点箭头变化\n\tdef Point_Arrow(self, arrow_command = [0,0,0,0], old = False):\n\t\tpos = (self.X, self.Y)\n\t\tif old:\n\t\t\tpos = (self.X_old, self.Y_old)\n\t\tischange = self.file['Field'].Point_Arrow(pos, arrow_command, self.PARAMETER['Img_parameter']['BackTrack'])\n\t\tif ischange:\n\t\t\tself.file['Change'] = 1\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#状态变更\n\t\t\ta_command['Status'] = {}\n\t\t\tif -1 in arrow_command:\n\t\t\t\ta_command['Status']['Last_Action'] = 'Delete Arrows'\n\t\t\telif 1 in arrow_command:\n\t\t\t\ta_command['Status']['Last_Action'] = 'Draw Arrows'\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\t\n\t\treturn ischange\n\t\t\n\t#填充\n\tdef Fill(self, panel_id):\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tRec = [Pos1, Pos2]\n\t\tischange = self.file['Field'].Fill(Rec, panel_id, self.PARAMETER['Img_parameter']['BackTrack'])\n\t\t\n\t\tif ischange:\n\t\t\tself.file['Change'] = 1\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#状态变更\n\t\t\ta_command['Status'] = {}\n\t\t\tif panel_id == 0:\n\t\t\t\ta_command['Status']['Last_Action'] = 'Delete Panels'\n\t\t\telif panel_id == 101:\n\t\t\t\ta_command['Status']['Last_Action'] = 'Delete Arrows'\n\t\t\telse:\n\t\t\t\ta_command['Status']['Last_Action'] = 'Fill ' + Panel_Name[Panel_Int.index(panel_id)]\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\n\t\treturn ischange\n\t\t\n\t#剪切\n\tdef Cut(self):\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tRec = [Pos1, Pos2]\n\t\t\n\t\tdata_new = self.file['Field'].Cut(Rec)\n\t\tfile_new = OFE_Field('create', data_new)\n\t\t\n\t\tself.PARAMETER['Clipboard'] = file_new\n\t\t\n\t\t#储存\n\t\tif file_new.has_value():\n\t\t\tself.file['Change'] = 1\n\t\t\tself.Record()\n\t\t#图像改变\n\t\tself.Selected['Copy_Index'] = 1\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tRec = [Pos1, Pos2]\n\t\tcommand = {'Rec':Rec}\n\t\tself.A_Paint(command)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\ta_command['Status']['Last_Action'] = 'Cut'\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t\t\n\t#复制\n\tdef Copy(self):\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tRec = [Pos1, Pos2]\n\t\t\n\t\tdata_new = self.file['Field'].Copy(Rec)\n\t\tfile_new = OFE_Field('create', data_new)\n\t\t\n\t\tself.PARAMETER['Clipboard'] = file_new\n\t\t\n\t\t#图像改变\n\t\tself.Selected['Copy_Index'] = 1\n\t\tcommand = {'Cursor':None}\n\t\tself.A_Paint(command)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\ta_command['Status']['Last_Action'] = 'Copy'\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t#粘贴\n\tdef Paste(self):\n\t\tPos = self.Selected['Pos_Start']\n\t\tsection = self.PARAMETER['Clipboard']\n\t\t\n\t\tself.file['Field'].Paste(Pos, section.data)\n\t\t\n\t\t#新光标\n\t\tx_new = min(Pos[0] + section.size()[0], self.file['Field'].size()[0]) - 1\n\t\ty_new = min(Pos[1] + section.size()[1], self.file['Field'].size()[1]) - 1\n\t\tself.Selected['Pos_End'] = (x_new, y_new)\n\t\t\n\t\t#储存\n\t\tself.file['Change'] = 1\n\t\tself.Record()\n\t\t##图像改变\n\t\tself.Selected['Copy_Index'] = 0\n\t\tcommand = {'All':None}\n\t\tself.A_Paint(command)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\ta_command['Status']['Last_Action'] = 'Paste'\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t#变换\n\tdef Transform(self):\n\t\tself.Selected['Type'] = 'Transform'\n\t\tself.Selected['Type'] = 'Transform'\n\t\t\n\t\t#区域剪切,写入Trans_Field\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tRec = [Pos1, Pos2]\n\t\t\n\t\tdata_new = self.file['Field'].Cut(Rec)\n\t\tfile_new = OFE_Field('create', data_new)\n\t\tself.Selected['Trans_Field'] = file_new\n\t\t\n\t\t#初始化此图片\n\t\timg_area = OFE_Image(self.Selected['Trans_Field'], self.Graphics, self.PARAMETER['Img_parameter']).Main()\n\t\tself.Selected['Trans_Img'] = img_area\n\t\t\n\t\t#初始位置设定\n\t\tself.Selected['Trans_Pos'] = self.Selected['Pos_Start']\n\t\t\n\t\t##图像改变\n\t\tcommand = {'All':None}\n\t\tself.A_Paint(command)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\t#按钮图标变更\n\t\ta_command['Button'] = {'Icon':{}}\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\n\t#Duplicate\n\tdef Duplicate(self):\n\t\tself.Selected['Type'] = 'Transform'\n\t\tself.Selected['Type'] = 'Transform'\n\t\t\n\t\t#区域剪切,写入Trans_Field\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tRec = [Pos1, Pos2]\n\t\t\n\t\tdata_new = self.file['Field'].Copy(Rec)\n\t\tfile_new = OFE_Field('create', data_new)\n\t\tself.Selected['Trans_Field'] = file_new\n\t\t\n\t\t#初始化此图片\n\t\timg_area = OFE_Image(self.Selected['Trans_Field'], self.Graphics, self.PARAMETER['Img_parameter']).Main()\n\t\tself.Selected['Trans_Img'] = img_area\n\t\t\n\t\t#初始位置设定\n\t\tself.Selected['Trans_Pos'] = self.Selected['Pos_Start']\n\t\t\n\t\t#状态临时记录\n\t\tself.Selected['Duplicate_Index'] = 1\n\t\t##图像改变\n\t\tcommand = {'All':None}\n\t\tself.A_Paint(command)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\t#按钮图标变更\n\t\ta_command['Button'] = {'Icon':{}}\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t#Free\n\tdef Free(self, sign):\n\t\tself.Selected['Trans_Field'].Free(sign)\n\t\t\n\t\t#重画此图片\n\t\timg_area = OFE_Image(self.Selected['Trans_Field'], self.Graphics, self.PARAMETER['Img_parameter']).Main()\n\t\tself.Selected['Trans_Img'] = img_area\n\t\t\n\t\t##图像改变\n\t\tcommand = {'Cursor':None}\n\t\tself.A_Paint(command)\n\t\t\n\t#确认变换\n\tdef Transform_Ok(self):\n\t\t#新地图\n\t\tself.file['Field'].Paste(self.Selected['Trans_Pos'], self.Selected['Trans_Field'].data)\n\t\n\t\t#参数变化\n\t\tself.Selected['Type'] = 'Selected'\n\t\tself.Selected['Pos_Start'] = self.Set_XY(self.Selected['Trans_Pos'])\n\t\tpos_add = self.Pos_Add(self.Selected['Trans_Pos'], self.Selected['Trans_Field'].size())\n\t\tpos_end = self.Set_XY((pos_add[0]-1, pos_add[1]-1))\n\t\tself.Selected['Pos_End'] = pos_end\n\t\tself.Selected['Trans_Field'] = None\n\t\tself.Selected['Trans_Img'] = None\n\t\t\n\t\t#状态变更\n\t\tself.Selected['Duplicate_Index'] = 0\n\t\t\n\t\t#储存\n\t\tself.file['Change'] = 1\n\t\tself.Record()\n\t\t#图像改变\n\t\tPos1 = self.Selected['Pos_Start']\n\t\tPos2 = self.Selected['Pos_End']\n\t\tRec = [Pos1, Pos2]\n\t\tcommand = {'Rec':Rec}\n\t\tself.A_Paint(command)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\tif self.Selected['Duplicate_Index']:\n\t\t\ta_command['Status']['Last_Action'] = 'Duplicate'\n\t\telse:\n\t\t\ta_command['Status']['Last_Action'] = 'Transform'\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#按钮图标变更\n\t\ta_command['Button'] = {'Icon': {}}\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t\t\n\t#取消变换\n\tdef Transform_Cancel(self):\n\t\t#初始化\n\t\tself.Selected['Type'] = 'Selected'\n\t\tself.Selected['Trans_Field'] = None\n\t\tself.Selected['Trans_Img'] = None\n\t\t\n\t\t#读取历史\n\t\tfield = self.file['History'][-1]\n\t\tself.file['Field'] = copy.deepcopy(field)\n\t\t\n\t\t#重画\n\t\tself.A_Paint({'All':None})\n\t\t#状态临时记录\n\t\tself.Selected['Duplicate_Index'] = 0\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#按钮图标变更\n\t\ta_command['Button'] = {'Icon': {}}\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\t\n\t'''记录'''\n\t\n\tdef Need_Save(self):\n\t\tif not self.Is_Field():\n\t\t\treturn False\n\t\tif self.Save_Index == len(self.file['History']) - self.file['Pos']:\n\t\t\treturn False\n\t\treturn True\n\t\n\t#记录\n\tdef Record(self):\n\t\tif self.file['Change']:\n\t\t\tself.file['Change'] = 0\n\t\t\t#删除未来史\n\t\t\tpos = self.file['Pos']\n\t\t\tif pos > 1:\n\t\t\t\tself.file['History'] = self.file['History'][:-pos+1]\n\t\t\t\tself.file['Pos'] = 1\n\t\t\t#写入历史\n\t\t\tself.file['History'].append(copy.deepcopy(self.file['Field']))\n\t\t\t#储存标签变更\n\t\t\tif len(self.file['History']) - self.file['Pos'] <= self.Save_Index:\n\t\t\t\tself.Save_Index = -1\n\t\t\t\t\n\t\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#状态变更\n\t\t\ta_command['Status'] = {}\n\t\t\t#菜单栏更新\n\t\t\ta_command['Menu'] = None\n\t\t\t#储存标签变更\n\t\t\ta_command['Tab'] = None\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\t\n\t\t\t\n\t#撤销\n\tdef Undo(self):\n\t\thistory_len = len(self.file['History'])\n\t\tif history_len > self.file['Pos']:\n\t\t\tself.file['Pos'] += 1\n\t\t\tpos = self.file['Pos']\n\t\t\tfield = self.file['History'][-pos]\n\t\t\tself.file['Field'] = copy.deepcopy(field)\n\t\t\t\n\t\t\t#重画\n\t\t\tself.A_Paint({'All':None})\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#状态变更\n\t\t\ta_command['Status'] = {}\n\t\t\ta_command['Status']['Last_Action'] = 'Undo'\n\t\t\t#菜单栏更新\n\t\t\ta_command['Menu'] = None\n\t\t\t#储存标签变更\n\t\t\ta_command['Tab'] = None\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\t\n\t#重做\n\tdef Redo(self):\n\t\tif self.file['Pos'] > 1:\n\t\t\tself.file['Pos'] -= 1\n\t\t\tpos = self.file['Pos']\n\t\t\tfield = self.file['History'][-pos]\n\t\t\tself.file['Field'] = copy.deepcopy(field)\n\t\t\t\n\t\t\t#重画\n\t\t\tself.A_Paint({'All':None})\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#状态变更\n\t\t\ta_command['Status'] = {}\n\t\t\ta_command['Status']['Last_Action'] = 'Redo'\n\t\t\t#菜单栏更新\n\t\t\ta_command['Menu'] = None\n\t\t\t#储存标签变更\n\t\t\ta_command['Tab'] = None\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\t\n\t\t\t\n\t'''绘制'''\n\t\t\t\n\t#绘制总函数\n\tdef A_Paint(self, command = {}):\n\t\tself.Paint_Command = command\n\t\tself.repaint()\n\t\tself.Paint_Command = {}\n\t\t\t\n\t#画笔事件\n\tdef paintEvent(self, event):\n\t\t\n\t\t#初始化\n\t\tcommand = self.Paint_Command\n\t\tpaint = QtGui.QPainter()\n\t\tpaint.begin(self)\n\t\t\n\t\t#画地图本体\n\t\tPX = 128\n\t\tzoom = self.PARAMETER['Img_parameter']['Zoom']\n\t\tpx = int(PX * zoom)\n\t\t\n\t\timg = self.Img_Draw(command)\n\t\t\n\t\t#画Transform\n\t\tself.Transform_Draw(img, command)\n\t\t\n\t\t#背景\n\t\tImg_Back = Image.new(\"RGBA\", img.size, self.PARAMETER['Img_parameter']['Background'])\n\t\tImg_Back.paste(img, (0,0), img.split()[3])\n\t\t#填充画布\n\t\tpaint.drawPixmap(self.rect(), PIXMAP(Img_Back))\n\t\t\n\t\t#画线\n\t\t\n\t\tdef DrawRec(px, Pen_Size, pos, posend = None):\n\t\t\tShrink = int(Pen_Size/2)\n\t\t\tif posend == None:\n\t\t\t\tx1 = pos[0]*px + Shrink\n\t\t\t\tx2 = pos[0]*px + px - Shrink\n\t\t\t\ty1 = pos[1]*px + Shrink\n\t\t\t\ty2 = pos[1]*px + px - Shrink\n\t\t\telse:\n\t\t\t\tdef RePos(pos1, pos2):\n\t\t\t\t\tx1 = pos1[0]\n\t\t\t\t\tx2 = pos2[0]\n\t\t\t\t\ty1 = pos1[1]\n\t\t\t\t\ty2 = pos2[1]\n\t\t\t\t\tposmin = (min(x1,x2), min(y1,y2))\n\t\t\t\t\tposmax = (max(x1,x2), max(y1,y2))\n\t\t\t\t\treturn posmin, posmax\n\t\t\t\tpos1, pos2 = RePos(pos, posend)\n\t\t\t\tx1 = pos1[0]*px + Shrink\n\t\t\t\tx2 = pos2[0]*px + px - Shrink\n\t\t\t\ty1 = pos1[1]*px + Shrink\n\t\t\t\ty2 = pos2[1]*px + px - Shrink\n\t\t\t\t\n\t\t\tpaint.drawLine(x1, y1, x1, y2)\n\t\t\tpaint.drawLine(x1, y1, x2, y1)\n\t\t\tpaint.drawLine(x2, y2, x1, y2)\n\t\t\tpaint.drawLine(x2, y2, x2, y1)\n\t\t\n\t\t\n\t\t\n\t\t#画线开始\n\t\tif self.Is_Field():\n\t\t\t#在选择事项出现时绘制选择方框\n\t\t\tif self.Selected['Type'] == 'Selecting' or self.Selected['Type'] == 'Selected':\n\t\t\t\tPen_Size = 2\n\t\t\t\tif self.Selected['Copy_Index']:\n\t\t\t\t\tpen = QtGui.QPen(QtCore.Qt.blue, Pen_Size, QtCore.Qt.SolidLine)\n\t\t\t\telse:\n\t\t\t\t\tpen = QtGui.QPen(QtCore.Qt.green, Pen_Size, QtCore.Qt.SolidLine)\n\t\t\t\tpaint.setPen(pen)\n\t\t\t\tDrawRec(px, Pen_Size, self.Selected['Pos_Start'], self.Selected['Pos_End'])\n\t\t\t#在变换事项出现时绘制黄色方框\n\t\t\tif self.Selected['Type'] == 'Transform' or self.Selected['Type'] == 'Transforming':\n\t\t\t\tPen_Size = 2\n\t\t\t\tpen = QtGui.QPen(QtCore.Qt.yellow, Pen_Size, QtCore.Qt.SolidLine)\n\t\t\t\tsize = self.Selected['Trans_Field'].size()\n\t\t\t\tpos_start = self.Selected['Trans_Pos']\n\t\t\t\tpos_end = (pos_start[0]+size[0]-1, pos_start[1]+size[1]-1)\n\t\t\t\tpaint.setPen(pen)\n\t\t\t\tDrawRec(px, Pen_Size, pos_start, pos_end)\n\t\t\t#只要不在选择进行中就绘制光标\n\t\t\tif self.Selected['Type'] == 'None' or self.Selected['Type'] == 'Selected' or self.Selected['Type'] == 'Transform':\n\t\t\t\tPen_Size = 2\n\t\t\t\tpen = QtGui.QPen(QtCore.Qt.red, Pen_Size, QtCore.Qt.SolidLine)\n\t\t\t\tpaint.setPen(pen)\n\t\t\t\tDrawRec(px, Pen_Size, (self.X, self.Y))\n\t\t\t\t\n\t\tpaint.end()\n\t\t\n\t\t\n\tdef Transform_Draw(self, img, command = {}):\n\t\t#在Transform出现时让背景变暗,并绘制被选择的区域\n\t\tif self.Selected['Type'] == 'Transform' or self.Selected['Type'] == 'Transforming':\n\t\t\tPX = 128\n\t\t\tzoom = self.PARAMETER['Img_parameter']['Zoom']\n\t\t\tpx = int(PX * zoom)\n\t\t\t#根据指令重画Transform\n\t\t\tif 'Transform_Redraw' in command:\n\t\t\t\timg_area = OFE_Image(self.Selected['Trans_Field'], self.Graphics, self.PARAMETER['Img_parameter']).Main()\n\t\t\t\tself.Selected['Trans_Img'] = img_area\n\t\t\t\n\t\t\tmask = Image.new(\"RGBA\", img.size,(0,0,0,128))\n\t\t\timg.paste(mask, (0,0), mask.split()[3])\n\t\t\t\n\t\t\timg_area = self.Selected['Trans_Img']\n\t\t\tpos = self.Selected['Trans_Pos']\n\t\t\timg.paste(img_area, (pos[0]*px, pos[1]*px), img_area.split()[3])\n\t\t\t\n\t\t\t\n\t# 生成Img的总函数\n\tdef Img_Draw(self, command = {}):\n\t\tif not self.Is_Field():\n\t\t\timg = self.Init_Draw()\n\t\telse:\n\t\t\timg = None\n\t\t\t#重画整张图\n\t\t\tif 'All' in command:\n\t\t\t\timg = self.Main_Draw()\n\t\t\t\t\n\t\t\t#重画一个格子\n\t\t\tif 'Point' in command:\n\t\t\t\tPoint_Pos = command['Point']\n\t\t\t\timg = self.Point_Draw(Point_Pos)\n\t\t\t\t\n\t\t\t#重画一个矩形区域\n\t\t\tif 'Rec' in command:\n\t\t\t\tRec = command['Rec']\n\t\t\t\timg = self.Rec_Draw(Rec)\n\t\t\t\t\n\t\t\t#画图完毕,保存地图到self\n\t\t\tif img:\n\t\t\t\tself.Field_Img = img\n\t\t\t\n\t\t\timg = self.Field_Img\n\t\t\t\n\t\t#全部绘制完成,固定窗口大小,返回图片\n\t\tself.setFixedSize(img.size[0],img.size[1])\n\t\treturn copy.deepcopy(img)\n\t\t\t\n\t\n\t# main画\n\tdef Main_Draw(self):\n\t\t#画地图本体\n\t\timg = OFE_Image(self.file['Field'], self.Graphics, self.PARAMETER['Img_parameter']).Main()\n\t\treturn img\n\t\t\n\t#单格画\n\tdef Point_Draw(self, pos):\n\t\t#从现有图片改变单个格子\n\t\timg = OFE_Image(self.file['Field'], self.Graphics, self.PARAMETER['Img_parameter']).Point(self.Field_Img, pos)\n\t\treturn img\n\t\t\n\t#矩形画\n\tdef Rec_Draw(self, rec):\n\t\t#从现有图片改变一个区域(暂时全画)\n\t\timg = OFE_Image(self.file['Field'], self.Graphics, self.PARAMETER['Img_parameter']).Main()\n\t\treturn img\n\t\t\n\t# Logo画\n\tdef Init_Draw(self):\n\t\timg = Image.open(path0 + '/'+ 'title_logo.png')\n\t\tzoom = self.PARAMETER['Img_parameter']['Zoom'] * 3\n\t\tnewsize = (int(img.size[0]*zoom), int(img.size[1]*zoom))\n\t\timg = img.resize(newsize, Image.BICUBIC)\n\t\timg_main = Image.new(\"RGBA\", img.size,self.PARAMETER['Img_parameter']['Background'])\n\t\timg_main.paste(img,(0,0),img.split()[3])\n\t\treturn img_main\n\t\n\t###状态变化###\n\t#菜单变化\n\tdef Menu_Change(self):\n\t\n\t\t#储存\n\t\tif self.Is_Field() and self.Selected['Type'] != 'Transform':\n\t\t\tself.PARAMETER['Menu_able']['Save_As'] = 0\n\t\t\tif self.Need_Save():\n\t\t\t\tself.PARAMETER['Menu_able']['Save'] = 0\n\t\t\telse:\n\t\t\t\tself.PARAMETER['Menu_able']['Save'] = 1\n\t\telse:\n\t\t\tself.PARAMETER['Menu_able']['Save_As'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Save'] = 1\n\t\t\n\t\t#撤销\n\t\tif len(self.file['History']) == self.file['Pos'] or len(self.file['History']) == 0:\n\t\t\tself.PARAMETER['Menu_able']['Undo'] = 1\n\t\telse:\n\t\t\tself.PARAMETER['Menu_able']['Undo'] = 0\n\t\t\t\n\t\t#重做\n\t\tif self.file['Pos'] <= 1:\n\t\t\tself.PARAMETER['Menu_able']['Redo'] = 1\n\t\telse:\n\t\t\tself.PARAMETER['Menu_able']['Redo'] = 0\n\t\t\t\n\t\t\t\n\t\t#剪切复制粘贴变换\n\t\tif self.Selected['Type'] == 'Selected':\n\t\t\tself.PARAMETER['Menu_able']['Cut'] = 0\n\t\t\tself.PARAMETER['Menu_able']['Copy'] = 0\n\t\t\tself.PARAMETER['Menu_able']['Transform'] = 0\n\t\t\tself.PARAMETER['Menu_able']['Duplicate'] = 0\n\t\t\tif self.PARAMETER['Clipboard']:\n\t\t\t\tself.PARAMETER['Menu_able']['Paste'] = 0\n\t\t\telse:\n\t\t\t\tself.PARAMETER['Menu_able']['Paste'] = 1\n\t\telse:\n\t\t\tself.PARAMETER['Menu_able']['Cut'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Copy'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Paste'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Transform'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Duplicate'] = 1\n\t\t\t\n\t\t#变换时全部禁用\n\t\tif self.Selected['Type'] == 'Transform':\n\t\t\tself.PARAMETER['Menu_able']['Undo'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Redo'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Cut'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Copy'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Paste'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Transform'] = 1\n\t\t\tself.PARAMETER['Menu_able']['Duplicate'] = 1\n\t\t\t\n\t\t\n\t#A状态变化\n\tdef A_Status(self, command = {}):\n\t\t#History数目\n\t\tcommand['History_Len'] = len(self.file['History'])\n\t\tcommand['History_Pos'] = self.file['Pos']\n\t\t#选择范围\n\t\tif self.Selected['Type'] == 'Selected':\n\t\t\tpos_start = self.Selected['Pos_Start']\n\t\t\tpos_end = self.Selected['Pos_End']\n\t\t\tcommand['Selected'] = [pos_start, pos_end]\n\t\telif self.Selected['Type'] == 'None':\n\t\t\tcommand['Selected'] = []\n\t\t\n\t\treturn command\n\t\t\n\t#A按钮图标更新\n\tdef A_Button(self, command = {}):\n\t\t#总状态\n\t\tcommand['Type'] = self.Selected['Type']\n\t\treturn command\n\n#画板框架\nclass Canvas_Frame(QtWidgets.QWidget):\n\tdef __init__(self, field, PARAMETER, App = None, file_name = 'Title', file_path = '', parent = None):\n\t\tsuper(Canvas_Frame,self).__init__(parent)\n\t\tself.init(field, PARAMETER, App, file_name, file_path)\n\t\t\n\tdef init(self, field, PARAMETER, App = None, file_name = 'Title', file_path = ''):\n\t\t\t\t\n\t\t# Label 原代码\n\t\t\n\t\t#状态条\n\t\tself.statue = QtWidgets.QStatusBar(self)\n\t\tself.statue.showMessage(\"\")\n\t\t\n\t\t#画板\n\t\tself.canvas = Canvas(field, PARAMETER, self.statue, App, file_name, file_path)\n\t\t\n\t\t#滚动条\n\t\tscroll = QtWidgets.QScrollArea()\n\t\tscroll.setWidget(self.canvas)\n\t\tscroll.setAutoFillBackground(True) \n\t\tscroll.setWidgetResizable(True)\n\t\t\n\t\t#打包\n\t\tvbox = QtWidgets.QVBoxLayout() \n\t\tvbox.addWidget(scroll) \n\t\tvbox.addWidget(self.statue)\n\t\tself.setLayout(vbox)\n\t\t\n\tdef Is_Field(self):\n\t\treturn self.canvas.Is_Field()\n\t\t\n\tdef Field(self):\n\t\treturn self.canvas.Field()\n\t\t\n\tdef file_name(self):\n\t\treturn self.canvas.file_name\n\t\t\n\tdef file_path(self):\n\t\treturn self.canvas.file_path\n\t\t\n\tdef Need_Save(self):\n\t\treturn self.canvas.Need_Save()\n\t\t\n\tdef Menu_Change(self):\n\t\tself.canvas.Menu_Change()\n\t\t\n\tdef A_Status(self, command = {}):\n\t\tself.canvas.A_Status(command)\n\t\t\n\tdef Button_Click(self ,id):\n\t\tself.canvas.Button_Click(id)\n\t\t\n\tdef A_Button(self, command = {}):\n\t\tself.canvas.A_Button(command)\n\t\t\n\tdef Save(self, path):\n\t\tself.canvas.Save(path)\n\t\t\n\tdef Undo(self):\n\t\tself.canvas.Undo()\n\t\t\n\tdef Redo(self):\n\t\tself.canvas.Redo()\n\t\t\n\tdef Cut(self):\n\t\tself.canvas.Cut()\n\t\t\n\tdef Copy(self):\n\t\tself.canvas.Copy()\n\t\t\n\tdef Paste(self):\n\t\tself.canvas.Paste()\n\t\t\n\tdef Transform(self):\n\t\tself.canvas.Transform()\t\t\n\t\t\n\tdef Duplicate(self):\n\t\tself.canvas.Duplicate()\n\t\t\n\t\t\n\tdef width(self):\n\t\treturn self.canvas.width()\n\t\t\n\tdef height(self):\n\t\treturn self.canvas.height()\n\n#画板Tab\n\t\t\nclass Canvas_Tab(QtWidgets.QTabWidget):\n\t\n\tTabEmitApp = QtCore.pyqtSignal()\n\t\n\tdef __init__(self, PARAMETER, App = None, parent = None):\n\t\tsuper(Canvas_Tab,self).__init__(parent)\n\t\tself.init(PARAMETER, App)\n\t\n\tdef init(self, PARAMETER, App = None):\n\t\n\t\t#初始化\n\t\tself.PARAMETER = PARAMETER\n\t\tself.App = App\n\t\t\n\t\t#初始画板\n\t\tself.Canvas_List = []\n\t\tself.Insert_Canvas()\n\t\t\n\t\t#检测Tab发生变化\n\t\tself.currentChanged.connect(self.OnChange)\n\t\t\n\t\t#更新Tab文本\n\t\tself.TabEmitApp.connect(self.Tab_Refresh)\n\t\t\n\t\t\n\tdef Insert_Canvas(self, field = None, file_name = 'Title', file_path = ''):\n\t\tif field:\n\t\t\tself.PARAMETER['Menu_able']['Close'] = 0\n\t\telse:\n\t\t\tfield = OFE_Field()\n\t\t\t\n\t\t#新画板\n\t\tcanvas_new = Canvas_Frame(field, self.PARAMETER, self.App, file_name, file_path)\n\t\t\n\t\t#第一个非地图去掉\n\t\tif self.Canvas_List != []:\n\t\t\tif not self.Canvas_List[0].Is_Field():\n\t\t\t\tself.removeTab(0)\n\t\t\t\tself.Canvas_List = []\n\t\t\t\t\n\t\t#创建新Tab\n\t\tid = self.count()\n\t\tself.Canvas_List.append(canvas_new)\n\t\tself.insertTab(id, canvas_new, file_name)\n\t\t\n\t\t#将新窗口对准\n\t\tself.setCurrentIndex(id)\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#储存标签变更\n\t\ta_command['Tab'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t\t\n\tdef Remove_Canvas(self):\n\t\tif self.Canvas_List == []:\n\t\t\treturn\n\t\tif not self.Canvas_List[0].Is_Field():\n\t\t\treturn\n\t\t\t\n\t\tcurrent_id = self.currentIndex()\n\t\tfile_name = self.Canvas_List[current_id].file_name()\n\t\tself.Canvas_List.pop(current_id)\n\t\tself.removeTab(current_id)\n\t\t\n\t\tif self.Canvas_List == []:\n\t\t\tself.Insert_Canvas()\n\t\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#菜单栏更新\n\t\ta_command['Menu'] = None\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\t\treturn file_name\n\t\t\n\tdef Is_Field(self):\n\t\tcurrent_id = self.currentIndex()\n\t\treturn self.Canvas_List[current_id].Is_Field()\n\t\t\n\tdef Field(self):\n\t\tcurrent_id = self.currentIndex()\n\t\treturn self.Canvas_List[current_id].Field()\n\t\t\n\tdef file_name(self):\n\t\tcurrent_id = self.currentIndex()\n\t\treturn self.Canvas_List[current_id].file_name()\n\t\t\n\tdef file_path(self):\n\t\tcurrent_id = self.currentIndex()\n\t\treturn self.Canvas_List[current_id].file_path()\n\t\t\n\tdef Need_Save(self):\n\t\tcurrent_id = self.currentIndex()\n\t\treturn self.Canvas_List[current_id].Need_Save()\n\t\t\n\tdef Save(self, path):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Save(path)\n\t\t\t\n\tdef Undo(self):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Undo()\n\t\t\n\tdef Redo(self):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Redo()\n\t\t\n\tdef Cut(self):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Cut()\n\t\t\n\tdef Copy(self):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Copy()\n\t\t\n\tdef Paste(self):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Paste()\n\t\t\n\tdef Transform(self):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Transform()\n\t\t\n\tdef Duplicate(self):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Duplicate()\n\t\t\n\tdef width(self):\n\t\tcurrent_id = self.currentIndex()\n\t\treturn self.Canvas_List[current_id].width()\n\t\t\n\tdef height(self):\n\t\tcurrent_id = self.currentIndex()\n\t\treturn self.Canvas_List[current_id].height()\n\t\t\n\tdef A_Paint(self, command):\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].canvas.A_Paint(command)\n\t\t\n\tdef Menu_Change(self):\n\t\tif self.Canvas_List != []:\n\t\t\tif not self.Canvas_List[0].Is_Field():\n\t\t\t\t#关闭菜单变动\n\t\t\t\tself.PARAMETER['Menu_able']['Close'] = 1\n\t\t\t\t\n\t\t#调用下级\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Menu_Change()\n\t\t\n\tdef A_Status(self, command = {}):\n\t\t#调用下级\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].A_Status(command)\n\t\t\n\tdef Button_Click(self, id):\n\t\t#调用下级\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].Button_Click(id)\n\t\t\n\tdef A_Button(self, command = {}):\n\t\t#调用下级\n\t\tcurrent_id = self.currentIndex()\n\t\tself.Canvas_List[current_id].A_Button(command)\n\t\t\n\t#改变Tab文本\n\tdef Tab_Refresh(self):\n\t\tcurrent_id = self.currentIndex()\n\t\ttext = self.Canvas_List[current_id].file_name()\n\t\tif self.Canvas_List[current_id].Need_Save():\n\t\t\ttext += '*'\n\t\tself.setTabText(current_id, text)\n\t\t\n\t#Tab切换时\n\tdef OnChange(self, Event):\n\t\t#改变文件index\n\t\tif Event >= 0:\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#状态变更\n\t\t\ta_command['Status'] = {}\n\t\t\t#按钮图标变更\n\t\t\ta_command['Button'] = {'Icon':{}}\n\t\t\t#菜单栏更新\n\t\t\ta_command['Menu'] = None\n\t\t\t#A_Command信号发射\n\t\t\tself.App['Command'].emit(a_command)\n\t\t\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 41.85714340209961, "blob_id": "ab5026821001c999bfcfa72144b045ffb787c18f", "content_id": "c86e0bc8b409bbc40e8bf624532fd6b515a3dca5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 300, "license_type": "no_license", "max_line_length": 63, "num_lines": 7, "path": "/OFE/__init__.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "\nfrom .OFE_Panels import Panel_Int, Panel_Name, Button_Brush_Int\nfrom .OFE_Field import OFE_Field\nfrom .OFE_Buttoms import ButtonWindow\nfrom .OFE_Status import StatusWindow\nfrom .OFE_Canvas import Canvas_Tab\nfrom .OFE_Files import OFE_Upload, OFE_New, OFE_Files\nfrom .OFE_Graphics import OFE_Graphics" }, { "alpha_fraction": 0.5490196347236633, "alphanum_fraction": 0.5661764740943909, "avg_line_length": 24.5625, "blob_id": "6b4782d43a1eb80073dca771457d6c113e1ac1b9", "content_id": "951e16b939ed7991c81e9a00355587768fe43a7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/setup.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "from setuptools import setup\n \nsetup(name='OrangeFieldEditor',\n version='0.1.4',\n description='100% Orange Field Editor',\n url='https://github.com/zirconium-n/OFE',\n author='lhw & sgk',\n license='MIT',\n packages=['OFE'],\n install_requires=[\n 'PyQt5',\n 'pillow'\n ],\n scripts=['bin/OFE.bat'],\n zip_safe=False,\n include_package_data=True)" }, { "alpha_fraction": 0.5077085494995117, "alphanum_fraction": 0.5719112753868103, "avg_line_length": 21.555023193359375, "blob_id": "4b3a1494e71cd2a900f646b93e2818a3e3485628", "content_id": "33b3d01240ea560a4a976e5147de901840211708", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4857, "license_type": "no_license", "max_line_length": 80, "num_lines": 209, "path": "/OFE/OFE_Image.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "#OFE_Image\nfrom PIL import Image\nimport sys, os\nfrom OFE import Panel_Int, Panel_Name\n\nimport time\n\n#根目录\npath0 = os.path.dirname(__file__)\n\n##初始加载图片\n# 图片映射表\n\n\n\nPanel_Dict = {}\nfor i, id in enumerate(Panel_Int):\n\tPanel_Dict[id] = Panel_Name[i]\n\nArrow_Name = ['Left', 'Up', 'Right', 'Down']\n\t\t\n\nclass OFE_Image():\n\tdef __init__(self, field, Graphics = None, Img_parameter = None):\n\t\tself.field = field\n\t\tself.Graphics = Graphics\n\t\tself.Img_parameter = Img_parameter\n\t\t\n\tdef PX_Image(self):\n\t\n\t\t#按照list[y][x]制作新Img\n\t\tdef New_Px(DATA):\n\t\t\t\n\t\t\ttype = \"RGBA\"\n\t\t\tif len(DATA[0][0]) == 3:\n\t\t\t\ttype = \"RGB\"\n\t\t\t\t\n\t\t\tY = len(DATA)\n\t\t\tX = len(DATA[0])\n\t\t\t\n\t\t\tImg = Image.new(\"RGBA\", (X,Y),(0,0,0,0))\n\t\t\t\n\t\t\tPUT_DATA = []\n\t\t\t\n\t\t\tfor raw in DATA:\n\t\t\t\tPUT_DATA += raw\n\t\t\t\t\n\t\t\tImg.putdata(PUT_DATA)\n\t\t\t\n\t\t\treturn Img\n\t\t\n\t\t#颜色列表\n\t\tCOLOR = {}\n\t\tCOLOR['Neutral'] = (214,214,214,256)\n\t\tCOLOR['Encounter'] = (255,115,109,256)\n\t\tCOLOR['Encounter_2'] = (255,115,109,256)\n\t\tCOLOR['Draw'] =(104,255,138,256)\n\t\tCOLOR['Draw_2'] = (0,246,88,256)\n\t\tCOLOR['Bonus'] = (254,222,110,256)\n\t\tCOLOR['Bonus_2'] = (253,186,31,256)\n\t\tCOLOR['Drop'] = (109,164,255,256)\n\t\tCOLOR['Drop_2'] = (0,96,246,256)\n\t\tCOLOR['Warp'] = (198,61,255,256)\n\t\tCOLOR['WarpMove'] = (198,61,255,256)\n\t\tCOLOR['WarpMove_2'] = (198,61,255,256)\n\t\tCOLOR['Move'] = (73,206,180,256)\n\t\tCOLOR['Move_2'] = (73,206,180,256)\n\t\tCOLOR['PLAYER1'] = (254,198,149,256)\n\t\tCOLOR['PLAYER2'] = (187,223,255,256)\n\t\tCOLOR['PLAYER3'] = (181,255,178,256)\n\t\tCOLOR['PLAYER4'] = (254,242,156,256)\n\t\t\n\t\tpx = 2\n\t\t\n\t\tDATA = []\n\t\tsize = self.field.size()\n\t\t#预填充\n\t\tfor y in range(px*size[1]):\n\t\t\tDATA.append([])\n\t\t\tfor x in range(px*size[0]):\n\t\t\t\tDATA[y].append((0,0,0,0))\n\t\t\n\t\t#填充\n\t\tfor y in range(size[1]):\n\t\t\tfor x in range(size[0]):\n\t\t\t\tpanel_id = self.field.data[y][x][0]\n\t\t\t\tpanel_name = Panel_Name[Panel_Int.index(panel_id)]\n\t\t\t\tif panel_name in COLOR:\n\t\t\t\t\tfor j in range(px):\n\t\t\t\t\t\tfor i in range(px):\n\t\t\t\t\t\t\tDATA[y*px+j][x*px+i] = COLOR[panel_name]\n\t\t\t\telif panel_name == 'Check':\n\t\t\t\t\tDATA[y*px+0][x*px+0] = COLOR['PLAYER1']\n\t\t\t\t\tDATA[y*px+1][x*px+0] = COLOR['PLAYER2']\n\t\t\t\t\tDATA[y*px+0][x*px+1] = COLOR['PLAYER3']\n\t\t\t\t\tDATA[y*px+1][x*px+1] = COLOR['PLAYER4']\n\t\t\t\t\t\n\t\timg = New_Px(DATA)\n\t\treturn img\n\t\t\n\tdef Main(self):\n\t\t\n\t\tImg = self.Panels()\n\t\tif self.Img_parameter['Show_arrows'] == 1:\n\t\t\tArrow = self.Arrows()\n\t\t\tImg.paste(Arrow,(0,0),Arrow.split()[3])\n\t\treturn Img\n\t\t\n\tdef Point(self, Img, pos):\n\t\n\t\tzoom = self.Img_parameter['Zoom']\n\t\t\n\t\tPX = 128\n\t\tpx = int(PX * zoom)\n\t\t\n\t\tsize = self.field.size()\n\t\tsize_img = map(lambda x: x * px, size)\n\t\t\n\t\tx = pos[0]\n\t\ty = pos[1]\n\t\t\n\t\t#画单个格子\n\t\tImg_this = Image.new(\"RGBA\", (px, px), self.Img_parameter['Background'])\n\t\tpanel_id = self.field.data[y][x][0]\n\t\tif panel_id:\n\t\t\tImg_Panel = self.Graphics.get_image('Panel_' + Panel_Dict[panel_id], zoom)\n\t\t\tImg_this.paste(Img_Panel, (0,0), Img_Panel.split()[3])\n\t\t\n\t\tif self.Img_parameter['Show_arrows'] == 1:\n\t\t\t#需要画的箭头\n\t\t\t#是否反向\n\t\t\tbacktrack = self.Img_parameter['BackTrack']\n\t\t\tif backtrack:\n\t\t\t\tCONST = 16\n\t\t\telse:\n\t\t\t\tCONST = 1\n\t\t\t\n\t\t\tArrows = []\n\t\t\tfor i in range(4):\n\t\t\t\tif int(self.field.data[y][x][1] / (2**i) / CONST) % 2:\n\t\t\t\t\tArrows.append(i)\n\t\t\t\t\t\n\t\t\tfor arrow_num in Arrows:\n\t\t\t\tImg_Arrow = self.Graphics.get_image('Arrow_' + Arrow_Name[arrow_num], zoom)\n\t\t\t\tImg_this.paste(Img_Arrow, (0,0) ,Img_Arrow.split()[3])\n\t\t\t\t\n\t\tImg.paste(Img_this, (px*x,px*y))\n\t\treturn Img\n\t\t\n\t\t\n\tdef Panels(self):\n\t\t\n\t\tzoom = self.Img_parameter['Zoom']\n\t\t\n\t\tPX = 128\n\t\tpx = int(PX * zoom)\n\t\t\n\t\tsize = self.field.size()\n\t\tsize_img = map(lambda x: x * px, size)\n\t\t\n\t\t#作图\n\t\tImg = Image.new(\"RGBA\", tuple(size_img), (0,0,0,0))\n\t\tfor y in range(size[1]):\n\t\t\tfor x in range(size[0]):\n\t\t\t\tpanel_id = self.field.data[y][x][0]\n\t\t\t\tif panel_id != 0 :\n\t\t\t\t\tImg_Panel = self.Graphics.get_image('Panel_' + Panel_Dict[panel_id], zoom)\n\t\t\t\t\tImg.paste(Img_Panel,(px*x,px*y),Img_Panel.split()[3])\n\t\treturn Img\n\t\t\n\tdef Arrows(self):\n\t\t\n\t\tzoom = self.Img_parameter['Zoom']\n\t\t\n\t\tPX = 128\n\t\tpx = int(PX * zoom)\n\t\t\n\t\tsize = self.field.size()\n\t\tsize_img = map(lambda x: x * px, size)\n\t\t\n\t\t#作图\n\t\tImg = Image.new(\"RGBA\", tuple(size_img), (0,0,0,0))\n\t\t\n\t\t#偏移关系\n\t\t# shift = 18\n\t\t# x_shift = [-shift, 0, shift, 0]\n\t\t# y_shift = [0, -shift, 0, shift]\n\t\t\n\t\t#是否反向\n\t\tbacktrack = self.Img_parameter['BackTrack']\n\t\t\n\t\tif backtrack:\n\t\t\tCONST = 16\n\t\telse:\n\t\t\tCONST = 1\n\t\t\n\t\tfor y in range(size[1]):\n\t\t\tfor x in range(size[0]):\n\t\t\t\t#需要画的箭头\n\t\t\t\tArrows = []\n\t\t\t\tfor i in range(4):\n\t\t\t\t\tif int(self.field.data[y][x][1] / (2**i) / CONST) % 2:\n\t\t\t\t\t\tArrows.append(i)\n\t\t\t\t\t\t\n\t\t\t\tfor arrow_num in Arrows:\n\t\t\t\t\tImg_Arrow = self.Graphics.get_image('Arrow_' + Arrow_Name[arrow_num], zoom)\n\t\t\t\t\tImg.paste(Img_Arrow,(px*x,px*y),Img_Arrow.split()[3])\n\t\t\n\t\treturn Img\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n" }, { "alpha_fraction": 0.6084815859794617, "alphanum_fraction": 0.6411415934562683, "avg_line_length": 29.063444137573242, "blob_id": "2bf86e70978d914bfcfd117e95c9dd3f6bf2fc9a", "content_id": "9f028da07d9ff50266f95268a7b1064b27df5a2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10433, "license_type": "no_license", "max_line_length": 138, "num_lines": 331, "path": "/OFE/OFE_Buttoms.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "#OFE_Buttoms\nimport sys, os\nfrom PIL import Image\nfrom PIL.ImageQt import ImageQt\nfrom PyQt5 import QtGui, QtWidgets, QtCore\nfrom OFE import Panel_Int, Panel_Name\n\n#根目录\npath0 = os.path.dirname(os.path.realpath(sys.argv[0]))\n#图片格式转换\ndef ICON(img):\n\tImgQt = ImageQt(img)\n\tpixmap = QtGui.QPixmap.fromImage(ImgQt)\n\ticon = QtGui.QIcon(pixmap)\n\treturn icon\n\nclass ButtonWindow(QtWidgets.QWidget):\n\tButtonApp = QtCore.pyqtSignal(int)\n\tdef __init__(self, PARAMETER, App = None, parent = None):\n\t\tQtWidgets.QWidget.__init__(self, parent)\n\t\t\n\t\t#初始化\n\t\tself.PARAMETER = PARAMETER\n\t\tself.App = App\n\t\tgraphics = PARAMETER['Graphics']\n\t\tprint(PARAMETER)\n\t\t###设置按钮(新)\n\t\t\n\t\t#按钮窗口layout\n\t\tlayout_main = QtWidgets.QVBoxLayout()\n\t\t#按钮图标\n\t\tself.Button_icon = {}\n\t\t#总QButtonGroup\n\t\tself.ButtonGroup = QtWidgets.QButtonGroup()\n\t\tself.ButtonGroup.buttonClicked.connect(self.Button_Click)\n\t\t#设置窗口\n\t\tself.ButtonWidget = []\n\t\t#PX\n\t\tzoom = self.PARAMETER['Img_parameter']['Button_Zoom']\n\t\tPX = 128\n\t\tpx = int(PX * zoom)\n\t\t#创建各个窗口和按钮\n\t\t'''\n\t\tfor i, type_ in enumerate(self.PARAMETER['Button']['Type']):\n\t\t\tself.ButtonWidget.append(QtWidgets.QWidget())\n\t\t\tgrid = QtWidgets.QGridLayout()\n\t\t\tfor j, name in enumerate(self.PARAMETER['Button']['Specific'][i]):\n\t\t\t\tid = 100 * i + j\n\t\t\t\tself.Button_icon[id] = []\n\t\t\t\t\n\t\t\t\t#按钮图标加载:0 不处理,1 按下, 2 低光, 3 无图\n\t\t\t\timg_o = graphics.get_image(type_ + '_' + name)\n\t\t\t\timg0 = Image.new(\"RGBA\", (PX,PX),(0,0,0,256))\n\t\t\t\timg0.paste(img_o, (0,0), img_o.split()[3])\n\t\t\t\tself.Button_icon[id].append(img0)\n\t\t\t\timg1 = Image.new(\"RGBA\", (PX,PX),(256,256,256,256))\n\t\t\t\timg1.paste(img_o, (2,2), img_o.split()[3])\n\t\t\t\tself.Button_icon[id].append(img1)\n\t\t\t\tmask = Image.new(\"RGBA\", (PX,PX),(0,0,0,64))\n\t\t\t\timg2 = Image.new(\"RGBA\", (PX,PX),(256,256,256,256))\n\t\t\t\timg2.paste(img_o, (0,0), img_o.split()[3])\n\t\t\t\timg2.paste(mask, (0,0), mask.split()[3])\n\t\t\t\tself.Button_icon[id].append(img2)\n\t\t\t\timg3 = Image.new(\"RGBA\", (PX,PX),(0,0,0,0))\n\t\t\t\tself.Button_icon[id].append(img3)\n\t\t\t\t\n\t\t\t\t#创建按钮\n\t\t\t\tbutton = QtWidgets.QPushButton()\n\t\t\t\tbutton.setFixedWidth(px)\n\t\t\t\tbutton.setFixedHeight(px)\n\t\t\t\tbutton.setIcon(ICON(self.Button_icon[id][2])) #默认低光\n\t\t\t\tbutton.setIconSize(QtCore.QSize(px,px))\n\t\t\t\t\n\t\t\t\t#绑定group\n\t\t\t\tself.ButtonGroup.addButton(button, id)\n\t\t\t\t\n\t\t\t\t#grid位置\n\t\t\t\ty = j/6\n\t\t\t\tx = j%6\n\t\t\t\tgrid.addWidget(button, y, x)\n\t\t\t\t\n\t\t\tgrid.setHorizontalSpacing(0)\n\t\t\tgrid.setVerticalSpacing(0)\n\t\t\tself.ButtonWidget[i].setLayout(grid)\n\t\t\tlayout_main.addWidget(self.ButtonWidget[i])\n\t\t\t\n\t\tself.setLayout(layout_main)\n\t\t'''\n\t\t\n\t\t#设置按钮(旧)\n\t\t\t\t\n\t\t#设置刷子类按钮\n\t\tButton_Brush_Int = [0,2,5,9,6,\n\t\t\t\t\t\t\t10,3,20,4,8,\n\t\t\t\t\t\t\t21,22,23,24,7,\n\t\t\t\t\t\t\t25,1,18,26,27\n\t\t\t\t\t\t\t,28,31,32,33]\n\t\t#鼠标类映射表\n\t\tMouse_Name = ['Mouse', 'ArrowDelete', 'ArrowLine', 'ArrowLineDelete', 'OK', 'Cancel']\n\t\t#变换类映射表\n\t\tTransform_Name = ['Clock_test', 'AntiClock_test', 'Vertical_test', 'Horizonal_test', 'OK', 'Cancel']\n\t\t\t\n\t\t#按钮多种图片\n\t\t\n\t\t\n\t\t#普通\n\t\tself.Button_0 = []\n\t\t#按下\n\t\tself.Button_1 = []\n\t\t#低光\n\t\tself.Button_2 = []\n\t\t#无\n\t\tself.Button_3 = []\n\t\tpanel_count = len(Panel_Int)\n\t\tbutton_count = 6\n\t\ttransform_count = 6\n\t\tfor id in range(panel_count + button_count + transform_count):\n\t\t\tif id < panel_count:\n\t\t\t\timg_o = graphics.get_image('Panel_' + Panel_Name[Panel_Int.index(Button_Brush_Int[id])]) \n\t\t\t\t#Image.open(path0 + r'\\panels\\Panel_' + Panel_Name[Panel_Int.index(Button_Brush_Int[id])] + '.png')\n\t\t\t\timg0 = Image.new(\"RGBA\", (PX,PX),(0,0,0,256))\n\t\t\t\timg0.paste(img_o, (0,0), img_o.split()[3])\n\t\t\t\tself.Button_0.append(img0)\n\t\t\t\timg1 = Image.new(\"RGBA\", (PX,PX),(256,256,256,256))\n\t\t\t\timg1.paste(img_o, (2,2), img_o.split()[3])\n\t\t\t\tself.Button_1.append(img1)\n\t\t\t\tmask = Image.new(\"RGBA\", (PX,PX),(0,0,0,64))\n\t\t\t\timg2 = Image.new(\"RGBA\", (PX,PX),(256,256,256,256))\n\t\t\t\timg2.paste(img_o, (0,0), img_o.split()[3])\n\t\t\t\timg2.paste(mask, (0,0), mask.split()[3])\n\t\t\t\tself.Button_2.append(img2)\n\t\t\t\timg3 = Image.new(\"RGBA\", (PX,PX),(0,0,0,0))\n\t\t\t\tself.Button_3.append(img3)\n\t\t\telif id < panel_count + button_count:\n\t\t\t\tid -= panel_count\n\t\t\t\timg_o = graphics.get_image('Button_' + Mouse_Name[id]) #Image.open(path0 + r'\\panels\\Button_' + Mouse_Name[id] + '.png')\n\t\t\t\tprint(Mouse_Name[id], id)\n\t\t\t\timg0 = Image.new(\"RGBA\", (PX,PX),(0,0,0,256))\n\t\t\t\timg0.paste(img_o, (0,0), img_o.split()[3])\n\t\t\t\tself.Button_0.append(img0)\n\t\t\t\timg1 = Image.new(\"RGBA\", (PX,PX),(256,256,256,256))\n\t\t\t\timg1.paste(img_o, (2,2), img_o.split()[3])\n\t\t\t\tself.Button_1.append(img1)\n\t\t\t\tmask = Image.new(\"RGBA\", (PX,PX),(0,0,0,64))\n\t\t\t\timg2 = Image.new(\"RGBA\", (PX,PX),(256,256,256,256))\n\t\t\t\timg2.paste(img_o, (0,0), img_o.split()[3])\n\t\t\t\timg2.paste(mask, (0,0), mask.split()[3])\n\t\t\t\tself.Button_2.append(img2)\n\t\t\t\timg3 = Image.new(\"RGBA\", (PX,PX),(0,0,0,0))\n\t\t\t\tself.Button_3.append(img3)\n\t\t\telif id < panel_count + button_count + transform_count:\n\t\t\t\tid -= panel_count + button_count\n\t\t\t\timg_o = graphics.get_image('Transform_' + Transform_Name[id]) #Image.open(path0 + r'\\panels\\Transform_' + Transform_Name[id] + '.png')\n\t\t\t\tprint(Transform_Name[id], id)\n\t\t\t\timg0 = Image.new(\"RGBA\", (PX,PX),(0,0,0,256))\n\t\t\t\timg0.paste(img_o, (0,0), img_o.split()[3])\n\t\t\t\tself.Button_0.append(img0)\n\t\t\t\n\t\t#按钮List\n\t\tself.Button_List = []\n\t\tbutton_grid_all = QtWidgets.QVBoxLayout()\n\t\t#刷子类\n\t\tbrush_grid = QtWidgets.QGridLayout()\n\n\t\tdef wrapper(ind):\n\t\t\tdef q():\n\t\t\t\tself.Button_Click(ind)\n\t\t\treturn q\t\t\n\t\tfor id in range(panel_count):\n\t\t\tself.Button_List.append(QtWidgets.QPushButton())\n\t\t\tself.Button_List[id].setFixedWidth(px)\n\t\t\tself.Button_List[id].setFixedHeight(px)\n\t\t\tself.Button_List[id].setIcon(ICON(self.Button_2[id]))\n\t\t\tself.Button_List[id].setIconSize(QtCore.QSize(px,px))\n\t\t\tself.Button_List[id].setStatusTip('Draw ' + Panel_Name[Panel_Int.index(Button_Brush_Int[id])] + ' Panel')\t\n\t\t\tself.Button_List[id].clicked.connect(wrapper(id))\n\t\t\n\t\tbrush_grid.setHorizontalSpacing(0)\n\t\tbrush_grid.setVerticalSpacing(0)\n\t\t\n\t\t#设置鼠标类按钮\n\t\t#鼠标工具#强删箭头工具#画箭头工具#擦除箭头工具#确认#取消\n\t\tmouse_grid = QtWidgets.QGridLayout()\n\t\tprint(\"INIT\", len(self.Button_List), panel_count)\n\n\t\tfor id in range(6):\n\t\t\tbuttonid = panel_count + id\n\n\t\t\tself.Button_List.append(QtWidgets.QPushButton())\n\t\t\tself.Button_List[buttonid].setFixedWidth(px)\n\t\t\tself.Button_List[buttonid].setFixedHeight(px)\n\t\t\tself.Button_List[buttonid].setIcon(ICON(self.Button_2[buttonid]))\n\t\t\tself.Button_List[buttonid].setIconSize(QtCore.QSize(px,px))\n\t\t\tself.Button_List[buttonid].setStatusTip(Mouse_Name[id])\n\t\t\tself.Button_List[buttonid].clicked.connect(wrapper(buttonid))\n\n\n\t\t\n\t\t#设置变换类按钮\n\t\ttransform_grid = QtWidgets.QGridLayout()\n\t\tCONST = panel_count + button_count\n\t\t\n\t\tfor id in range(6):\n\t\t\tbuttonid = CONST + id\n\t\t\tself.Button_List.append(QtWidgets.QPushButton())\n\t\t\tself.Button_List[buttonid].setFixedWidth(px)\n\t\t\tself.Button_List[buttonid].setFixedHeight(px)\n\t\t\tself.Button_List[buttonid].setIcon(ICON(self.Button_0[buttonid]))\n\t\t\tself.Button_List[buttonid].setIconSize(QtCore.QSize(px,px))\n\t\t\tself.Button_List[buttonid].setStatusTip(Mouse_Name[id])\n\t\t\tself.Button_List[buttonid].clicked.connect(wrapper(buttonid))\n\n\n\t\tfor id in range(CONST + transform_count):\n\t\t\ty, x = id // 6, id % 6\n\t\t\tif (id < panel_count):\n\t\t\t\tbrush_grid.addWidget(self.Button_List[id], y, x)\n\t\t\telif (id < CONST):\n\t\t\t\tmouse_grid.addWidget(self.Button_List[id], 0, id - panel_count)\n\t\t\telse:\n\t\t\t\ttransform_grid.addWidget(self.Button_List[id], 0, id - CONST)\n\t\t\n\t\tbutton_grid_all.addLayout(brush_grid)\n\t\tbutton_grid_all.addLayout(mouse_grid)\n\t\tbutton_grid_all.addLayout(transform_grid)\n\t\t#设置整体框架\n\t\t\n\t\tself.setLayout(button_grid_all)\n\t\t\n\t\t#初始化按钮图标\n\t\tself.Button_Icon_Change()\n\t\t\n\t\t#快捷键\n\t\tself.Button_List[0].setShortcut('Delete')\n\t\tself.Button_List[panel_count + 10].setShortcut('Return')\n\t\tself.Button_List[panel_count + 5].setShortcut('Esc')\n\t\tself.Button_List[panel_count + 11].setShortcut('Esc')\n\t\n\t\t\n\t\t#测试\n\t\t\n\tdef Button_Click(self, id):\n\t\t\n\t\t#print\n\t\tprint(id)\n\t\t\n\t\t#旧按钮标记\n\t\tid_old = self.PARAMETER['Command']['Button']\n\t\t\n\t\t#按钮按下发射信号\n\t\tself.App['Button'].emit(id)\n\t\t\n\t\tid_new = self.PARAMETER['Command']['Button']\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#状态变更\n\t\ta_command['Status'] = {}\n\t\t#按钮图标变更\n\t\ta_command['Button'] = {'Icon':{}}\n\t\t#A_Command信号发射\n\t\tself.App['Command'].emit(a_command)\n\t\t\n\tdef A_Button(self, command):\n\t\tif 'Zoom' in command:\n\t\t\tself.Button_Zoom_Change()\n\t\tif 'Icon' in command:\n\t\t\tself.Button_Icon_Change(command['Icon'])\n\t\t\n\tdef Button_Icon_Change(self, command = {'Type': 'None'}):\n\t\t#设置图标\n\t\t#选择按钮样式初始化\n\t\tmagic = len(Panel_Int)\n\t\tdef Selected_Button_Icon():\n\t\t\tlist = []\n\t\t\tfor i in range(magic + 6):\n\t\t\t\tlist.append(0)\n\t\t\tlist[magic] = 1\n\t\t\tlist[magic + 2] = 3\n\t\t\tlist[magic + 3] = 3\n\t\t\treturn list\n\t\tdef Init_Button_Icon():\n\t\t\tlist = []\n\t\t\tfor i in range(magic + 6):\n\t\t\t\tlist.append(2)\n\t\t\tlist[magic + 4] = 3\n\t\t\tlist[magic + 5] = 3\n\t\t\treturn list\n\t\t\n\t\tbutton_icon = []\n\t\t#处于选定状态下\n\t\tif command['Type'] == 'Selected':\n\t\t\tbutton_icon = Selected_Button_Icon()\n\t\t#处于一般状态下\n\t\telif command['Type'] == 'None':\n\t\t\tbutton_icon = Init_Button_Icon()\n\t\t\tbutton_id = self.PARAMETER['Command']['Button']\n\t\t\tbutton_icon[button_id] = 1\n\t\t\n\t\t#更换图标\n\t\tfor i, type in enumerate(button_icon):\n\t\t\tif type == 0:\n\t\t\t\tself.Button_List[i].setIcon(ICON(self.Button_0[i]))\n\t\t\tif type == 1:\n\t\t\t\tself.Button_List[i].setIcon(ICON(self.Button_1[i]))\n\t\t\tif type == 2:\n\t\t\t\tself.Button_List[i].setIcon(ICON(self.Button_2[i]))\n\t\t\tif type == 3:\n\t\t\t\tself.Button_List[i].setIcon(ICON(self.Button_3[i]))\n\t\t\t\t\n\t\t#Transform按钮在Transform形态下显示\n\t\tif command['Type'] == 'Transform':\n\t\t\tfor i in range(magic + 6):\n\t\t\t\tself.Button_List[i].hide()\n\t\t\tfor i in range(magic + 6, magic + 12):\n\t\t\t\tself.Button_List[i].show()\n\t\telse:\n\t\t\tfor i in range(magic + 6):\n\t\t\t\tself.Button_List[i].show()\n\t\t\tfor i in range(magic + 6, magic + 12):\n\t\t\t\tself.Button_List[i].hide()\n\t\t\t\t\n\t#更换按钮大小\n\tdef Button_Zoom_Change(self):\n\t\tPX = 128\n\t\tButton_Zoom = self.PARAMETER['Img_parameter']['Button_Zoom']\n\t\tpx = int(PX * Button_Zoom)\n\t\tfor button in self.Button_List:\n\t\t\tbutton.setFixedWidth(px)\n\t\t\tbutton.setFixedHeight(px)\n\t\t\tbutton.setIconSize(QtCore.QSize(px,px))\n" }, { "alpha_fraction": 0.636807918548584, "alphanum_fraction": 0.6451032161712646, "avg_line_length": 25.09395980834961, "blob_id": "ab7f31ab78201b5f6272f95277d17132ad506453", "content_id": "7ad5e204737ea5aecc0fcba82192e0ca62b3769f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16403, "license_type": "no_license", "max_line_length": 151, "num_lines": 596, "path": "/OFE/OFE_Files.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "import sys, os\nimport zipfile\nfrom PIL import Image\nfrom PIL.ImageQt import ImageQt\nfrom PyQt5 import QtWidgets, QtCore, QtGui\n\nfrom OFE.OFE_Field import OFE_Field\nfrom OFE.OFE_Image import OFE_Image\n\nimport tempfile\nimport shutil\n\n#移除pak中的指定文件\ndef remove_from_zip(zipfname, *filenames):\n\ttempdir = tempfile.mkdtemp()\n\ttry:\n\t\ttempname = os.path.join(tempdir, 'new.zip')\n\t\twith zipfile.ZipFile(zipfname, 'r') as zipread:\n\t\t\twith zipfile.ZipFile(tempname, 'w') as zipwrite:\n\t\t\t\tfor item in zipread.infolist():\n\t\t\t\t\tif item.filename not in filenames:\n\t\t\t\t\t\tdata = zipread.read(item.filename)\n\t\t\t\t\t\tzipwrite.writestr(item, data)\n\t\tshutil.move(tempname, zipfname)\n\tfinally:\n\t\tshutil.rmtree(tempdir)\n\n#根目录\npath0 = os.path.dirname(__file__)\n\nclass OFE_Upload(QtWidgets.QDialog):\n\tdef __init__(self, game_path, field, parent = None):\n\t\tsuper(OFE_Upload, self).__init__()\n\t\t\n\t\tself.game_path = game_path\n\t\tself.field_now = field\n\t\t#初始化\n\t\tself.setWindowTitle(\"Upload Manager\")\n\t\tself.setGeometry(600, 100, 900, 600)\n\t\t#本地地图列表\n\t\tself.Local_Field_Dict = self.Open_Fields(path = path0 + '/'+ 'fields.pak')\n\t\t#游戏地图列表\n\t\tself.Game_Field_Dict = self.Open_Fields(path = game_path)\n\t\t\n\t\tdef ICON(img):\n\t\t\tImgQt = ImageQt(img)\n\t\t\tpixmap = QtGui.QPixmap.fromImage(ImgQt)\n\t\t\ticon = QtGui.QIcon(pixmap)\n\t\t\treturn icon\n\t\t\n\t\t#主框架\n\t\tlayout_main = QtWidgets.QVBoxLayout()\n\t\t\n\t\t\n\t\t#从本地文件中获得排序的文件名列表\n\t\tself.Name_List = []\n\t\tfor name in self.Local_Field_Dict:\n\t\t\tself.Name_List.append(name)\n\t\t\t\n\t\tself.Name_List.sort()\n\t\t\n\t\t#grid的layout\n\t\tgrid_layout = QtWidgets.QGridLayout()\n\t\t#各种组\n\t\tself.label_img_list = []\n\t\tself.label_size_list = []\n\t\tself.label_state_list = []\n\t\tself.reset_group = QtWidgets.QButtonGroup()\n\t\tself.reset_group.buttonClicked.connect(self.Reset)\n\t\tself.upload_group = QtWidgets.QButtonGroup()\n\t\tself.upload_group.buttonClicked.connect(self.Upload)\n\t\t# upload_group = QtWidgets.QButtonGroup()\n\t\t#开始做Grid。当前图标、本地文件名、当前大小、状态\n\t\tfor i, name in enumerate(self.Name_List):\n\t\t\t#是否存在该文件\n\t\t\tExist = 0\n\t\t\tif name in self.Game_Field_Dict:\n\t\t\t\tExist = 1\n\t\t\t\t\n\t\t\t#0本地文件名\n\t\t\tlabel_name = QtWidgets.QLabel(name)\n\t\t\tgrid_layout.addWidget(label_name, i, 0)\n\t\t\t\t\n\t\t\t#1应该的大小\n\t\t\tsize_o = self.Local_Field_Dict[name].size()\n\t\t\tlabel_size_o = QtWidgets.QLabel(str(size_o[0])+'x'+str(size_o[1]))\n\t\t\tgrid_layout.addWidget(label_size_o, i, 1)\n\t\t\t\t\n\t\t\t#2图标\n\t\t\tif Exist:\n\t\t\t\timg = OFE_Image(self.Game_Field_Dict[name]).PX_Image()\n\t\t\telse:\n\t\t\t\timg = Image.open(path0 + '/'+ 'panels/Panel_Void.png')\n\t\t\t\t\n\t\t\tSIZE = (32,32)\n\t\t\timg = img.resize(SIZE, Image.BICUBIC)\n\t\t\t\n\t\t\tdef PIXMAP(img):\n\t\t\t\tImgQt = ImageQt(img)\n\t\t\t\tpixmap = QtGui.QPixmap.fromImage(ImgQt)\n\t\t\t\treturn pixmap\n\t\t\t\n\t\t\tlabel_img = QtWidgets.QLabel()\n\t\t\tlabel_img.setPixmap(PIXMAP(img))\n\t\t\tlabel_img.setFixedSize(SIZE[0],SIZE[1])\n\t\t\tgrid_layout.addWidget(label_img, i, 2)\n\t\t\t\n\t\t\tself.label_img_list.append(label_img)\n\t\t\t\n\t\t\t#3当前的大小\n\t\t\tif Exist:\n\t\t\t\tsize = self.Game_Field_Dict[name].size()\n\t\t\telse:\n\t\t\t\tsize = (0, 0)\n\t\t\tif size == size_o:\n\t\t\t\tlabel_size = QtWidgets.QLabel(\"<font color='green'>\" + str(size[0])+'x'+str(size[1]) + \"</font>\")\n\t\t\telse:\n\t\t\t\tlabel_size = QtWidgets.QLabel(\"<font color='red'>\" + str(size[0])+'x'+str(size[1]) + \"</font>\")\n\t\t\tgrid_layout.addWidget(label_size, i, 3)\n\t\t\t\n\t\t\tself.label_size_list.append(label_size)\n\t\t\t\n\t\t\t#4状态\n\t\t\tif Exist:\n\t\t\t\tif self.Game_Field_Dict[name].data == self.Local_Field_Dict[name].data:\n\t\t\t\t\ttext = 'Original'\n\t\t\t\telse:\n\t\t\t\t\ttext = 'Custom'\n\t\t\telse:\n\t\t\t\ttext = 'Lost'\n\t\t\t\t\n\t\t\tlabel_state = QtWidgets.QLabel()\n\t\t\tif text == 'Original':\n\t\t\t\tlabel_state.setText(\"<font color='green'>Original</font>\")\n\t\t\tif text == 'Custom':\n\t\t\t\tlabel_state.setText(\"<font color='blue'>Custom</font>\")\n\t\t\tif text == 'Lost':\n\t\t\t\tlabel_state.setText(\"<font color='red'>Lost</font>\")\n\t\t\tgrid_layout.addWidget(label_state, i, 4)\n\t\t\t\n\t\t\tself.label_state_list.append(label_state)\n\t\t\t\n\t\t\t#5 Reset按钮\n\t\t\treset_button = QtWidgets.QPushButton('Reset')\n\t\t\tself.reset_group.addButton(reset_button, i)\n\t\t\tgrid_layout.addWidget(reset_button, i, 5)\n\t\t\t\n\t\t\t#6 Upload按钮\n\t\t\tupload_button = QtWidgets.QPushButton('Upload')\n\t\t\tself.upload_group.addButton(upload_button, i)\n\t\t\tgrid_layout.addWidget(upload_button, i, 6)\n\t\t\t\n\t\t\t\n\t\t#滚动条\n\t\tscroll_widget = QtWidgets.QWidget()\n\t\tscroll_widget.setLayout(grid_layout)\n\t\tscroll = QtWidgets.QScrollArea()\n\t\tscroll.setWidget(scroll_widget)\n\t\tscroll.setAutoFillBackground(True) \n\t\tscroll.setWidgetResizable(True)\n\t\t\n\t\tlayout_main.addWidget(scroll)\n\t\t\t\n\t\t#总布局\n\t\tself.setLayout(layout_main)\n\t\t#重置窗口大小\n\t\twidth = self.sizeHint().width() + 20\n\t\theight = self.sizeHint().height() + 200\n\t\tself.resize(QtCore.QSize(width, height))\n\t\t\n\tdef Upload(self, button):\n\t\t#当前按钮id和对应的文件名\n\t\tid = self.upload_group.id(button)\n\t\tname = self.Name_List[id]\n\t\t####将本地文件替换到游戏文件\n\t\tif self.field_now:\n\t\t\tif self.field_now.data:\n\t\t\t\t##生成一个临时文件\n\t\t\t\t#临时目录\n\t\t\t\tpath_temporary = path0 + '/'+ 'temporary'\n\t\t\t\tfile_temporary = open(path_temporary, 'wb')\n\t\t\t\tfile_temporary.write(self.field_now.get_bin())\n\t\t\t\tfile_temporary.close()\n\t\t\t\t\n\t\t\t\t#写入\n\t\t\t\tremove_from_zip(self.game_path, name)\n\t\t\t\twith zipfile.ZipFile(self.game_path, 'a') as pak_file:\n\t\t\t\t\tpak_file.write(path_temporary, arcname=name)\n\t\t\n\t\t#更新\n\t\tself.Update()\n\t\t\n\tdef Reset(self, button):\n\t\t#当前按钮id和对应的文件名\n\t\tid = self.reset_group.id(button)\n\t\tname = self.Name_List[id]\n\t\t####将本地文件替换到游戏文件\n\t\t##生成一个临时文件\n\t\t#临时目录\n\t\tpath_temporary = path0 + '/'+ 'temporary'\n\t\tfile_temporary = open(path_temporary, 'wb')\n\t\tfile_temporary.write(self.Local_Field_Dict[name].get_bin())\n\t\tfile_temporary.close()\n\t\t\n\t\t#写入\n\t\tremove_from_zip(self.game_path, name)\n\t\twith zipfile.ZipFile(self.game_path, 'a') as pak_file:\n\t\t\tpak_file.write(path_temporary, arcname=name)\n\t\t\n\t\t#更新\n\t\tself.Update()\n\t\t\n\tdef Update(self):\n\t\t\n\t\t#看文件个数\n\t\twith zipfile.ZipFile(self.game_path) as pak_file:\n\t\t\tname_list_o = pak_file.namelist()\n\t\tcount = 0\n\t\tfor name in name_list_o:\n\t\t\tif name[-4:] == '.fld':\n\t\t\t\tcount += 1\n\t\t\t\t\n\t\tprint(count)\n\t\t\n\t\t#游戏地图列表重新加载\n\t\tself.Game_Field_Dict = self.Open_Fields(path = self.game_path)\n\t\tfor i, name in enumerate(self.Name_List):\n\t\t\t#是否存在该文件\n\t\t\tExist = 0\n\t\t\tif name in self.Game_Field_Dict:\n\t\t\t\tExist = 1\n\t\t\t\t\n\t\t\t#2图标\n\t\t\tif Exist:\n\t\t\t\timg = OFE_Image(self.Game_Field_Dict[name]).PX_Image()\n\t\t\telse:\n\t\t\t\timg = Image.open(path0 + '/'+ 'panels/Panel_Void.png')\n\t\t\t\t\n\t\t\tSIZE = (32,32)\n\t\t\timg = img.resize(SIZE, Image.BICUBIC)\n\t\t\t\n\t\t\tdef PIXMAP(img):\n\t\t\t\tImgQt = ImageQt(img)\n\t\t\t\tpixmap = QtGui.QPixmap.fromImage(ImgQt)\n\t\t\t\treturn pixmap\n\t\t\t\n\t\t\tself.label_img_list[i].setPixmap(PIXMAP(img))\n\t\t\t\n\t\t\t#3当前的大小\n\t\t\tsize_o = self.Local_Field_Dict[name].size()\n\t\t\tif Exist:\n\t\t\t\tsize = self.Game_Field_Dict[name].size()\n\t\t\telse:\n\t\t\t\tsize = (0, 0)\n\t\t\tif size == size_o:\n\t\t\t\tself.label_size_list[i].setText(\"<font color='green'>\" + str(size[0])+'x'+str(size[1]) + \"</font>\")\n\t\t\telse:\n\t\t\t\tself.label_size_list[i].setText(\"<font color='red'>\" + str(size[0])+'x'+str(size[1]) + \"</font>\")\n\t\t\t\n\t\t\t#4状态\n\t\t\tif Exist:\n\t\t\t\tif self.Game_Field_Dict[name].data == self.Local_Field_Dict[name].data:\n\t\t\t\t\ttext = 'Original'\n\t\t\t\telse:\n\t\t\t\t\ttext = 'Custom'\n\t\t\telse:\n\t\t\t\ttext = 'Lost'\n\t\t\t\t\n\t\t\tif text == 'Original':\n\t\t\t\tself.label_state_list[i].setText(\"<font color='green'>Original</font>\")\n\t\t\tif text == 'Custom':\n\t\t\t\tself.label_state_list[i].setText(\"<font color='blue'>Custom</font>\")\n\t\t\tif text == 'Lost':\n\t\t\t\tself.label_state_list[i].setText(\"<font color='red'>Lost</font>\")\n\t\t\n\tdef Upload_Main(app, game_path = '', field = None, parent = None):\n\t\n\t\t#检查本地文件是否正常\n\t\tpath = path0 + '/'+ 'fields.pak'\n\t\tpath = QtCore.QFileInfo(path).absoluteFilePath()\n\t\ttry:\n\t\t\tpak_file = zipfile.ZipFile(path)\n\t\texcept:\n\t\t\tQtWidgets.QMessageBox.critical(app, 'Error','Can not find fields.pak in '+path0, QtWidgets.QMessageBox.Ok)\n\t\t\treturn\n\t\telse:\n\t\t\t#检查游戏文件目录是否匹配\n\t\t\tdef Get_Game_Pak(app, game_path):\n\t\t\t\t\n\t\t\t\tgame_path = QtCore.QFileInfo(game_path).absoluteFilePath()\n\t\t\t\t#检查名称准确\n\t\t\t\tfile_name = QtCore.QFileInfo(game_path).fileName()\n\t\t\t\tif file_name == 'fields.pak':\n\t\t\t\t\tName_Error = False\n\t\t\t\telse:\n\t\t\t\t\tName_Error = True\n\t\t\t\t\t\n\t\t\t\t#检查是否是合法的压缩文件\n\t\t\t\ttry:\n\t\t\t\t\tgame_zip = zipfile.ZipFile(game_path)\n\t\t\t\texcept:\n\t\t\t\t\tPak_Error = True\n\t\t\t\telse:\n\t\t\t\t\tPak_Error = False\n\t\t\t\t\t\n\t\t\t\t#检查路径是否是本地的路径\n\t\t\t\tif path == game_path:\n\t\t\t\t\tPath_Error = True\n\t\t\t\telse:\n\t\t\t\t\tPath_Error = False\n\t\t\t\t\t\n\t\t\t\t#如果出错,则重新选择路径\n\t\t\t\tif Name_Error or Path_Error or Pak_Error:\n\t\t\t\t\toptions = QtWidgets.QFileDialog.Options()\n\t\t\t\t\tgame_path, _ = QtWidgets.QFileDialog.getOpenFileName(app,\"Open the fields.pak in game data\", path0 ,\"Pak (*.pak);;All Files (*)\", options=options)\n\t\t\t\t\t\n\t\t\t\t\t#再次\n\t\t\t\t\t#检查名称准确\n\t\t\t\t\tfile_name = QtCore.QFileInfo(game_path).fileName()\n\t\t\t\t\tif file_name == 'fields.pak':\n\t\t\t\t\t\tName_Error = False\n\t\t\t\t\telse:\n\t\t\t\t\t\tName_Error = True\n\t\t\t\t\t\t\n\t\t\t\t\t#检查是否是合法的压缩文件\n\t\t\t\t\ttry:\n\t\t\t\t\t\tgame_zip = zipfile.ZipFile(game_path)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tPak_Error = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tPak_Error = False\n\t\t\t\t\t\t\n\t\t\t\t\t#检查路径是否是本地的路径\n\t\t\t\t\tif path == game_path:\n\t\t\t\t\t\tPath_Error = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tPath_Error = False\n\t\t\t\t\t\n\t\t\t\t#通过/否决\n\t\t\t\tif Name_Error or Path_Error or Pak_Error:\n\t\t\t\t\tif Name_Error:\n\t\t\t\t\t\tQtWidgets.QMessageBox.critical(app, 'Error','You must find pak with name fields.pak', QtWidgets.QMessageBox.Ok)\n\t\t\t\t\telif Pak_Error:\n\t\t\t\t\t\tQtWidgets.QMessageBox.critical(app, 'Error','Not a pak file', QtWidgets.QMessageBox.Ok)\n\t\t\t\t\telif Path_Error:\n\t\t\t\t\t\tQtWidgets.QMessageBox.critical(app, 'Error','You must find fields.pak in game data', QtWidgets.QMessageBox.Ok)\n\t\t\t\telse:\n\t\t\t\t\treturn game_path\n\t\t\t\n\t\t\t#真实游戏地图目录,如有问题则返回\n\t\t\tgame_path = Get_Game_Pak(app, game_path)\n\t\t\tif not game_path:\n\t\t\t\treturn\n\t\t\t\n\t\t\t#对话框开始\n\t\t\tdialog = OFE_Upload(game_path, field, parent)\n\t\t\tresult = dialog.exec_()\n\t\t\t\n\t\t\tpak_file.close()\n\t\t\treturn game_path\n\t\t\n\t#从本地的pak中获得地图dict\n\tdef Open_Fields(self, path):\n\t\twith zipfile.ZipFile(path) as pak_file:\n\t\t\t#文件列表\n\t\t\tname_list_o = pak_file.namelist()\n\t\t\tname_fld = []\n\t\t\tfor name in name_list_o:\n\t\t\t\tif name[-4:] == '.fld':\n\t\t\t\t\tname_fld.append(name)\n\t\t\t\t\t\n\t\t\tfield_dict = {}\n\t\t\tfor name in name_fld:\n\t\t\t\tfld_bin = pak_file.read(name)\n\t\t\t\tfield = OFE_Field('bin', fld_bin)\n\t\t\t\tfield_dict[name] = field\n\t\t\t\n\t\treturn field_dict\n\nclass OFE_New(QtWidgets.QDialog):\n\tdef __init__(self, parent = None):\n\t\tsuper(OFE_New, self).__init__()\n\t\t\n\t\t#初始化\n\t\tself.setWindowTitle(\"New\")\n\t\t# self.setGeometry(300, 100, 400, 600)\n\t\t\n\t\t#地图文件列表\n\t\tself.Field_Dict = self.Open_Fields()\n\t\t\n\t\t#主框架\n\t\tlayout_main = QtWidgets.QVBoxLayout()\n\t\t\n\t\t#Title\n\t\ttitle_label = QtWidgets.QLabel('Select a field size:')\n\t\tlayout_main.addWidget(title_label)\n\t\t\n\t\t#Radio按钮layout\n\t\tradio_layout = QtWidgets.QGridLayout()\n\t\tself.radio_group = QtWidgets.QButtonGroup()\n\t\t\n\t\tself.size_list = []\n\t\tfor i, name in enumerate(self.Field_Dict):\n\t\t\tfield = self.Field_Dict[name]\n\t\t\tsize = field.size()\n\t\t\t\n\t\t\tif not size in self.size_list:\n\t\t\t\tself.size_list.append(size)\n\t\t\n\t\tself.size_list.sort()\n\t\t\n\t\tfor i, size in enumerate(self.size_list):\n\t\t\tradio = QtWidgets.QRadioButton(str(size[0])+'x'+str(size[1]))\n\t\t\tself.radio_group.addButton(radio, i)\n\t\t\tradio_layout.addWidget(radio, i, 0)\n\t\t\n\t\tlayout_main.addLayout(radio_layout)\n\t\t\n\t\t#确认取消按钮\n\t\tok_cancel = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, QtCore.Qt.Horizontal, self)\n\t\tok_cancel.accepted.connect(self.accept)\n\t\tok_cancel.rejected.connect(self.reject)\n\t\tlayout_main.addWidget(ok_cancel)\n\t\t\n\t\t#总布局\n\t\tself.setLayout(layout_main)\n\t\t\n\tdef Get_Size(app, parent = None):\n\t\tpath = path0 + '/'+ 'fields.pak'\n\t\ttry:\n\t\t\tpak_file = zipfile.ZipFile(path)\n\t\texcept:\n\t\t\tQtWidgets.QMessageBox.critical(app, 'Error','Can not find fields.pak in '+path0, QtWidgets.QMessageBox.Ok)\n\t\t\treturn\n\t\telse:\n\t\t\tdialog = OFE_New(parent)\n\t\t\tresult = dialog.exec_()\n\t\t\tif result:\n\t\t\t\tid = dialog.radio_group.checkedId()\n\t\t\t\tif id >= 0:\n\t\t\t\t\tsize = dialog.size_list[id]\n\t\t\t\t\treturn size\n\t\t\t\telse:\n\t\t\t\t\treturn\n\t\t\telse:\n\t\t\t\treturn \n\t\t\n\tdef Open_Fields(self):\n\t\tpath = path0 + '/'+ 'fields.pak'\n\t\twith zipfile.ZipFile(path) as pak_file:\n\t\t\n\t\t\t#文件列表\n\t\t\tname_list_o = pak_file.namelist()\n\t\t\tname_fld = []\n\t\t\tfor name in name_list_o:\n\t\t\t\tif name[-4:] == '.fld':\n\t\t\t\t\tname_fld.append(name)\n\t\t\t\t\t\n\t\t\tfield_dict = {}\n\t\t\tfor name in name_fld:\n\t\t\t\tfld_bin = pak_file.read(name)\n\t\t\t\tfield = OFE_Field('bin', fld_bin)\n\t\t\t\tfield_dict[name] = field\n\t\t\t\n\t\t\n\t\treturn field_dict\n\nclass OFE_Files(QtWidgets.QDialog):\n\tdef __init__(self, parent = None):\n\t\tsuper(OFE_Files, self).__init__()\n\t\t\n\t\t#初始化\n\t\tself.setWindowTitle(\"Open Official Field\")\n\t\tself.setGeometry(300, 100, 350, 600)\n\t\t\n\t\t#地图文件列表\n\t\tself.Field_Dict = self.Open_Fields()\n\t\tif self.Field_Dict:\n\t\t\n\t\t\tdef ICON(img):\n\t\t\t\tImgQt = ImageQt(img)\n\t\t\t\tpixmap = QtGui.QPixmap.fromImage(ImgQt)\n\t\t\t\ticon = QtGui.QIcon(pixmap)\n\t\t\t\treturn icon\n\t\t\t\n\t\t\t#主框架\n\t\t\tlayout_main = QtWidgets.QVBoxLayout()\n\t\t\t\n\t\t\t#Title\n\t\t\ttitle_label = QtWidgets.QLabel('Select a official field:')\n\t\t\tlayout_main.addWidget(title_label)\n\t\t\t\n\t\t\t#Radio按钮layout\n\t\t\tradio_layout = QtWidgets.QGridLayout()\n\t\t\tself.radio_group = QtWidgets.QButtonGroup()\n\t\t\t\n\t\t\tself.Name_List = []\n\t\t\tfor name in self.Field_Dict:\n\t\t\t\tself.Name_List.append(name)\n\t\t\t\t\n\t\t\tself.Name_List.sort()\n\t\t\t\n\t\t\tfor i, name in enumerate(self.Name_List):\n\t\t\t\t#图片\n\t\t\t\tSIZE = (32, 32)\n\t\t\t\timg = OFE_Image(self.Field_Dict[name]).PX_Image()\n\t\t\t\tdef PIXMAP(img):\n\t\t\t\t\tImgQt = ImageQt(img)\n\t\t\t\t\tpixmap = QtGui.QPixmap.fromImage(ImgQt)\n\t\t\t\t\treturn pixmap\n\t\t\t\tlabel_img = QtWidgets.QLabel()\n\t\t\t\tlabel_img.setPixmap(PIXMAP(img))\n\t\t\t\tlabel_img.setFixedSize(SIZE[0],SIZE[1])\n\t\t\t\tradio_layout.addWidget(label_img, i, 1)\n\t\t\t\t\n\t\t\t\t#radio,名字\n\t\t\t\tradio = QtWidgets.QRadioButton(name)\n\t\t\t\tself.radio_group.addButton(radio, i)\n\t\t\t\tradio_layout.addWidget(radio, i, 0)\n\t\t\t\t\n\t\t\t\t#大小\n\t\t\t\tsize = self.Field_Dict[name].size()\n\t\t\t\tlabel = QtWidgets.QLabel(str(size[0])+'x'+str(size[1]))\n\t\t\t\tradio_layout.addWidget(label, i, 2)\n\t\t\t\n\t\t\t#滚动条\n\t\t\tscroll_widget = QtWidgets.QWidget()\n\t\t\tscroll_widget.setLayout(radio_layout)\n\t\t\tscroll = QtWidgets.QScrollArea()\n\t\t\tscroll.setWidget(scroll_widget)\n\t\t\tscroll.setAutoFillBackground(True) \n\t\t\tscroll.setWidgetResizable(True)\n\t\t\t\n\t\t\tlayout_main.addWidget(scroll)\n\t\t\t\n\t\t\t#确认取消按钮\n\t\t\tok_cancel = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, QtCore.Qt.Horizontal, self)\n\t\t\tok_cancel.accepted.connect(self.accept)\n\t\t\tok_cancel.rejected.connect(self.reject)\n\t\t\tlayout_main.addWidget(ok_cancel)\n\t\t\t\n\t\t\t#总布局\n\t\t\tself.setLayout(layout_main)\n\t\t\t\n\t\t\t#重置窗口大小\n\t\t\twidth = self.sizeHint().width() + 20\n\t\t\theight = self.sizeHint().height() + 200\n\t\t\tself.resize(QtCore.QSize(width, height))\n\t\t\t\n\t\t\n\tdef Get_Field(app, parent = None):\n\t\t\n\t\tpath = path0 + '/'+ 'fields.pak'\n\t\ttry:\n\t\t\tpak_file = zipfile.ZipFile(path)\n\t\texcept:\n\t\t\tQtWidgets.QMessageBox.critical(app, 'Error','Can not find fields.pak in '+path0, QtWidgets.QMessageBox.Ok)\n\t\t\treturn\n\t\telse:\n\t\t\n\t\t\tdialog = OFE_Files(parent)\n\t\t\tresult = dialog.exec_()\n\t\t\tif result:\n\t\t\t\tid = dialog.radio_group.checkedId()\n\t\t\t\tif id >= 0:\n\t\t\t\t\tname = dialog.Name_List[id]\n\t\t\t\t\tfield = dialog.Field_Dict[name]\n\t\t\t\t\treturn field, name\n\t\t\t\telse:\n\t\t\t\t\treturn\n\t\t\telse:\n\t\t\t\treturn \n\t\t\n\tdef Open_Fields(self):\n\t\tpath = path0 + '/'+ 'fields.pak'\n\t\tpak_file = zipfile.ZipFile(path)\n\t\t#文件列表\n\t\tname_list_o = pak_file.namelist()\n\t\tname_fld = []\n\t\tfor name in name_list_o:\n\t\t\tif name[-4:] == '.fld':\n\t\t\t\tname_fld.append(name)\n\t\t\t\t\n\t\tfield_dict = {}\n\t\tfor name in name_fld:\n\t\t\tfld_bin = pak_file.read(name)\n\t\t\tfield = OFE_Field('bin', fld_bin)\n\t\t\tfield_dict[name] = field\n\t\t\t\n\t\treturn field_dict\n\nif __name__ == '__main__':\n\tapp = QtWidgets.QApplication(sys.argv)\n\tfield = OFE_Files.Get_Field(app)\n\tprint(field)\n\tsys.exit(app.exec_())" }, { "alpha_fraction": 0.5192743539810181, "alphanum_fraction": 0.5470820069313049, "avg_line_length": 20.90813636779785, "blob_id": "ad27a8576054ab22f0c92814e01e1d3c4d1bdee5", "content_id": "93237b7744769139532f50440437f7bcca7e9c42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8431, "license_type": "no_license", "max_line_length": 88, "num_lines": 381, "path": "/OFE/OFE_Field.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "#OFE_Field\n\nimport struct\nimport math\n\nclass OFE_Field:\n\tdef __init__(self, order = None, parameter = None):\n\t\tself.data = None\n\t\t\n\t\t#新建\n\t\tif order == 'new':\n\t\t\tX, Y = parameter\n\t\t\tself.data = []\n\t\t\tfor j in range(Y):\n\t\t\t\tself.data.append([])\n\t\t\t\tfor i in range(X):\n\t\t\t\t\tself.data[j].append([0,0])\n\t\t\n\t\t#从文件读取\n\t\tif order == 'open':\n\t\t\tfile = open(parameter, 'rb')\n\t\t\ttext = file.read()\n\t\t\tfile.close()\n\t\t\tint_num = len(text)/4\n\t\t\tint_list = struct.unpack('%di'%int_num, text)\n\t\t\t\n\t\t\tfield_o = list(int_list)\n\t\t\t\n\t\t\t#地图尺寸\n\t\t\tnum = int(len(field_o)/2)\n\t\t\tsize = int(math.sqrt(num))\n\t\t\tif size*size == num:\n\t\t\t\tx = size\n\t\t\t\ty = size\n\t\t\telse:\n\t\t\t\twhile num % size != 0:\n\t\t\t\t\tsize -= 1\n\t\t\t\ty = size\n\t\t\t\tx = int(num/size)\n\t\t\t\n\t\t\tself.data = []\n\t\t\tfor i in range(y):\n\t\t\t\tself.data.append([])\n\t\t\t\tfor j in range(x):\n\t\t\t\t\tself.data[i].append([field_o[2*(i*x+j)], field_o[2*(i*x+j)+1]])\n\t\t\t\t\t\n\t\t#从二进制导入\n\t\tif order == 'bin':\n\t\t\ttext = parameter\n\t\t\tint_num = len(text)/4\n\t\t\tint_list = struct.unpack('%di'%int_num, text)\n\t\t\t\n\t\t\tfield_o = list(int_list)\n\t\t\t\n\t\t\t#地图尺寸\n\t\t\tnum = int(len(field_o)/2)\n\t\t\tsize = int(math.sqrt(num))\n\t\t\tif size*size == num:\n\t\t\t\tx = size\n\t\t\t\ty = size\n\t\t\telse:\n\t\t\t\twhile num % size != 0:\n\t\t\t\t\tsize -= 1\n\t\t\t\ty = size\n\t\t\t\tx = int(num/size)\n\t\t\t\n\t\t\tself.data = []\n\t\t\tfor i in range(y):\n\t\t\t\tself.data.append([])\n\t\t\t\tfor j in range(x):\n\t\t\t\t\tself.data[i].append([field_o[2*(i*x+j)], field_o[2*(i*x+j)+1]])\n\t\t\t\t\t\n\t\t#从数据生成\n\t\tif order == 'create':\n\t\t\tself.data = parameter\n\t\t\t\n\tdef get_bin(self):\n\t\tint_list = []\n\t\tX, Y = self.size()\n\t\t\n\t\tfor y in range(Y):\n\t\t\tfor x in range(X):\n\t\t\t\tint_list.append(self.data[y][x][0])\n\t\t\t\tint_list.append(self.data[y][x][1])\n\t\t\t\t\n\t\tnum = len(int_list)\n\t\ttext = struct.pack('%di'%num, *int_list)\n\t\treturn text\n\t\t\t\n\tdef Save(self, path = ''):\n\t\tif path != '' and self.data:\n\t\t\ttext = self.get_bin()\n\t\t\t\n\t\t\tfile = open(path, 'wb')\n\t\t\tfile.write(text)\n\t\t\tfile.close()\n\t\t\t\n\tdef size(self):\n\t\tif self.data:\n\t\t\tx = len(self.data[0])\n\t\t\ty = len(self.data)\n\t\t\treturn (x, y)\n\t\t\t\n\tdef has_value(self):\n\t\tsize = self.size()\n\t\tX = size[0]\n\t\tY = size[1]\n\t\t\n\t\tfor y in range(Y):\n\t\t\tfor x in range(X):\n\t\t\t\tif self.data[y][x][0] != 0:\n\t\t\t\t\treturn True\n\t\t\n\t\treturn False\n\t\t\t\n\tdef Get_Section(self, rec):\n\t\tpos1 = rec[0]\n\t\tpos2 = rec[1]\n\t\tx1 = pos1[0]\n\t\ty1 = pos1[1]\n\t\tx2 = pos2[0]\n\t\ty2 = pos2[1]\n\t\t\n\t\tdata_new = []\n\t\tfor y in range(y1, y2+1):\n\t\t\tj = y - y1\n\t\t\tdata_new.append([])\n\t\t\tfor x in range(x1, x2+1):\n\t\t\t\ti = x - x1\n\t\t\t\tdata_new[j].append([])\n\t\t\t\t\n\t\t\t\tdata_new[j][i].append(self.data[y][x][0])\n\t\t\t\tdata_new[j][i].append(self.data[y][x][1])\n\t\t\t\t\n\t\treturn data_new\n\t\t\n\tdef Cut(self, rec):\n\t\tdata_new = self.Get_Section(rec)\n\t\tself.Fill(rec, 0)\n\t\treturn data_new\n\t\t\n\tdef Copy(self, rec):\n\t\tdata_new = self.Get_Section(rec)\n\t\treturn data_new\n\t\t\n\tdef Paste(self, pos, data_new):\n\t\tx1 = pos[0]\n\t\ty1 = pos[1]\n\t\tI = len(data_new[0])\n\t\tJ = len(data_new)\n\t\tX = self.size()[0]\n\t\tY = self.size()[1]\n\t\t\n\t\tfor j in range(J):\n\t\t\ty = j + y1\n\t\t\tfor i in range(I):\n\t\t\t\tx = i + x1\n\t\t\t\tif y < Y and x < X and y >= 0 and x >= 0:\n\t\t\t\t\tself.data[y][x][0] = data_new[j][i][0]\n\t\t\t\t\tself.data[y][x][1] = data_new[j][i][1]\n\t\t\t\t\t\n\tdef Arrow_Transform(self, arrow_num, type = ''):\n\t\tdef horizonal(num):\n\t\t\tchar = [0, 0, 0, 0]\n\t\t\tfor i in range(4):\n\t\t\t\tkey_num = 2**(2*i)\n\t\t\t\tvalue = num & key_num\n\t\t\t\tif value:\n\t\t\t\t\tchar[i] = 1\n\t\t\t\t\t\n\t\t\tnum_new = num\n\t\t\tfor i in range(4):\n\t\t\t\toffset = 0\n\t\t\t\tif i%2:\n\t\t\t\t\toffset = -2\n\t\t\t\telse:\n\t\t\t\t\toffset = 2\n\t\t\t\tif char[i]:\n\t\t\t\t\tkey_num = 2**(2*i + offset)\n\t\t\t\t\tnum_new = num_new | key_num\n\t\t\t\telse:\n\t\t\t\t\tkey_num = 2**8 - 2**(2*i + offset) - 1\n\t\t\t\t\tnum_new = num_new & key_num\n\t\t\treturn num_new\n\t\tdef vertical(num):\n\t\t\tchar = [0, 0, 0, 0]\n\t\t\tfor i in range(4):\n\t\t\t\tkey_num = 2**(2*i + 1)\n\t\t\t\tvalue = num & key_num\n\t\t\t\tif value:\n\t\t\t\t\tchar[i] = 1\n\t\t\t\t\t\n\t\t\tnum_new = num\n\t\t\tfor i in range(4):\n\t\t\t\toffset = 0\n\t\t\t\tif i%2:\n\t\t\t\t\toffset = -2\n\t\t\t\telse:\n\t\t\t\t\toffset = 2\n\t\t\t\tif char[i]:\n\t\t\t\t\tkey_num = 2**(2*i + 1 + offset)\n\t\t\t\t\tnum_new = num_new | key_num\n\t\t\t\telse:\n\t\t\t\t\tkey_num = 2**8 - 2**(2*i + 1 + offset) - 1\n\t\t\t\t\tnum_new = num_new & key_num\n\t\t\treturn num_new\n\t\tdef cycle(num, command = 'clock'):\n\t\t\tnum_new = 0\n\t\t\tif command == 'clock':\n\t\t\t\tstorage = int(num / 8)\n\t\t\t\tnum_new = num << 1\n\t\t\t\tnum_new %= 16\n\t\t\t\tnum_new += storage\n\t\t\t\treturn num_new\n\t\t\telif command == 'anticlock':\n\t\t\t\tstorage = num % 2\n\t\t\t\tnum_new = num >> 1\n\t\t\t\tnum_new += storage * 8\n\t\t\t\treturn num_new\n\t\tdef clockwise(num):\n\t\t\tnum1 = num % 16\n\t\t\tnum2 = num - num1\n\t\t\tnum1_new = cycle(num1, 'clock')\n\t\t\tnum2_new = cycle(num2, 'clock')\n\t\t\tnum_new = num2_new * 16 + num1_new\n\t\t\treturn num_new\n\t\tdef anticlockwise(num):\n\t\t\tnum1 = num % 16\n\t\t\tnum2 = num - num1\n\t\t\tnum1_new = cycle(num1, 'anticlock')\n\t\t\tnum2_new = cycle(num2, 'anticlock')\n\t\t\tnum_new = num2_new * 16 + num1_new\n\t\t\treturn num_new\n\t\t\t\n\t\tif type == 'horizonal':\n\t\t\treturn horizonal(arrow_num)\n\t\telif type == 'vertical':\n\t\t\treturn vertical(arrow_num)\n\t\telif type == 'clockwise':\n\t\t\treturn clockwise(arrow_num)\n\t\telif type == 'anticlockwise':\n\t\t\treturn anticlockwise(arrow_num)\n\t\t\t\n\t\t\t\t\t\n\tdef Horizonal(self):\n\t\tX, Y = self.size()\n\t\tdata_new = []\n\t\tfor y in range(Y):\n\t\t\tdata_new.append([])\n\t\t\tfor x in range(X):\n\t\t\t\tdata_new[y].append([])\n\t\t\t\tdata_new[y][x].append(self.data[y][X-x-1][0])\n\t\t\t\tdata_new[y][x].append(self.Arrow_Transform(self.data[y][X-x-1][1], 'horizonal'))\n\t\tself.data = data_new\n\t\t\n\tdef Vertical(self):\n\t\tX, Y = self.size()\n\t\tdata_new = []\n\t\tfor y in range(Y):\n\t\t\tdata_new.append([])\n\t\t\tfor x in range(X):\n\t\t\t\tdata_new[y].append([])\n\t\t\t\tdata_new[y][x].append(self.data[Y-y-1][x][0])\n\t\t\t\tdata_new[y][x].append(self.Arrow_Transform(self.data[Y-y-1][x][1], 'vertical'))\n\t\tself.data = data_new\n\t\t\n\tdef Clockwise(self):\n\t\tX, Y = self.size()\n\t\tX_new = Y\n\t\tY_new = X\n\t\tdata_new = []\n\t\tfor y in range(Y_new):\n\t\t\tdata_new.append([])\n\t\t\tfor x in range(X_new):\n\t\t\t\tdata_new[y].append([])\n\t\t\t\tdata_new[y][x].append(self.data[Y-x-1][y][0])\n\t\t\t\tdata_new[y][x].append(self.Arrow_Transform(self.data[Y-x-1][y][1], 'clockwise'))\n\t\tself.data = data_new\n\t\t\n\tdef AntiClockwise(self):\n\t\tX, Y = self.size()\n\t\tX_new = Y\n\t\tY_new = X\n\t\tdata_new = []\n\t\tfor y in range(Y_new):\n\t\t\tdata_new.append([])\n\t\t\tfor x in range(X_new):\n\t\t\t\tdata_new[y].append([])\n\t\t\t\tdata_new[y][x].append(self.data[x][X-y-1][0])\n\t\t\t\tdata_new[y][x].append(self.Arrow_Transform(self.data[x][X-y-1][1], 'anticlockwise'))\n\t\tself.data = data_new\n\t\t\n\tdef Free(self, command):\n\t\tif command == 'clockwise':\n\t\t\tself.Clockwise()\n\t\telif command == 'anticlockwise':\n\t\t\tself.AntiClockwise()\n\t\telif command == 'vertical':\n\t\t\tself.Vertical()\n\t\telif command == 'horizonal':\n\t\t\tself.Horizonal()\n\t\t\t\n\tdef Point_IsVoid(self, pos):\n\t\tx = pos[0]\n\t\ty = pos[1]\n\t\told_panel = self.data[y][x][0]\n\t\t\n\t\tif old_panel == 0 or old_panel == 18:\n\t\t\treturn True\n\t\treturn False\n\t\t\t\n\tdef Point_Panel(self, pos, panel_id, setting = 'Default'):\n\t\t\n\t\tx = pos[0]\n\t\ty = pos[1]\n\t\told_panel = self.data[y][x][0]\n\t\told_arrow = self.data[y][x][1]\n\t\t\n\t\tself.data[y][x][0] = panel_id\n\t\tif setting == 'Default':\n\t\t\tif panel_id == 0 or panel_id == 18:\n\t\t\t\tself.data[y][x][1] = 0\n\t\t\n\t\tif old_panel != self.data[y][x][0] or old_arrow != self.data[y][x][1]:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\t\t\n\tdef Point_Arrow(self, pos, arrow_command = [0,0,0,0], BackTrack = 0):\n\t\t\n\t\tx = pos[0]\n\t\ty = pos[1]\n\t\told_arrow = self.data[y][x][1]\n\t\t\n\t\tnew_arrow = old_arrow\n\t\t\n\t\tdef If_Arrow(arrow, index):\n\t\t\treturn int(arrow / (2**index)) % 2\n\t\t\t\n\t\tdef Change_Arrow(arrow, index, command):\n\t\t\tnew_arrow = arrow\n\t\t\tif command == 1 and not If_Arrow(arrow, index):\n\t\t\t\tnew_arrow += 2**index\n\t\t\telif command == -1 and If_Arrow(arrow, index):\n\t\t\t\tnew_arrow -= 2**index\n\t\t\t\t\n\t\t\treturn new_arrow\n\t\t\n\t\tBack_Index = 0\n\t\tif BackTrack:\n\t\t\tBack_Index = 4\n\t\t\t\n\t\tfor i in range(4):\n\t\t\tindex = i + Back_Index\n\t\t\tnew_arrow = Change_Arrow(new_arrow, index, arrow_command[i])\n\t\t\t\n\t\tself.data[y][x][1] = new_arrow\n\t\t\n\t\tif old_arrow != new_arrow:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\t\t\n\tdef Fill(self, rec, panel_id, BackTrack = 0):\n\t\tpos1 = rec[0]\n\t\tpos2 = rec[1]\n\t\tx1 = pos1[0]\n\t\ty1 = pos1[1]\n\t\tx2 = pos2[0]\n\t\ty2 = pos2[1]\n\t\t\n\t\tfor y in range(y1, y2+1):\n\t\t\tfor x in range(x1, x2+1):\n\t\t\t\tif panel_id < 100:\n\t\t\t\t\tself.data[y][x][0] = panel_id\n\t\t\t\tif panel_id == 0 or panel_id == 18:\n\t\t\t\t\tself.data[y][x][1] = 0\n\t\t\t\tif panel_id == 101:\n\t\t\t\t\tself.Point_Arrow((x,y), [-1,-1,-1,-1], BackTrack)\n\t\t\t\n\t\treturn True\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n" }, { "alpha_fraction": 0.5590164065361023, "alphanum_fraction": 0.5692622661590576, "avg_line_length": 23.785715103149414, "blob_id": "f845d92bfe69c354e931061f2e440d619f9b02af", "content_id": "9f514c0655591cae17525992ed3dc8b3f108787f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2466, "license_type": "no_license", "max_line_length": 157, "num_lines": 98, "path": "/OFE/OFE_Status.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "from PyQt5 import QtGui, QtWidgets, QtCore\n\nclass StatusWindow(QtWidgets.QWidget):\n\tdef __init__(self, parent = None):\n\t\tQtWidgets.QWidget.__init__(self, parent)\n\t\t\n\t\t#初始化\n\t\tself.Status = {}\n\t\t#初始参数\n\t\tself.Status['History_Len'] = 0\n\t\tself.Status['History_Pos'] = 1\n\t\tself.Status['Last_Action'] = 'None'\n\t\tself.Status['Selected'] = []\n\t\tself.Status['Button'] = 18\n\t\tself.Status['BackTrack'] = 0\n\t\t\n\t\tself.Status['Test'] = ''\n\t\t\n\t\t#主框架\n\t\tlayout_main = QtWidgets.QVBoxLayout()\n\t\t\n\t\t#主文本\n\t\tself.label_main = QtWidgets.QLabel(self)\n\t\tself.label_main.setText('test') \n\t\t\n\t\tlayout_main.addWidget(self.label_main)\n\t\tself.setLayout(layout_main)\n\t\t\n\tdef A_Status(self, command):\n\t\t\n\t\tfor key in command:\n\t\t\tself.Status[key] = command[key]\n\t\t\t\n\t\tself.Text_Refresh()\n\t\t\n\tdef Status_Refresh(self):\n\t\tself.Text_Refresh()\n\t\t\n\tdef Text_Refresh(self):\n\t\n\t\ttext = ''\n\t\t# text += '--------Status--------' + '\\n'\n\t\t###Command\n\t\ttext += '----Command----' + '\\n'\n\t\t#last action\n\t\ttext += 'Last Action : '\n\t\tlast_action = self.Status['Last_Action']\n\t\ttext += last_action\n\t\ttext += '\\n'\n\t\t#Selected\n\t\ttext += 'Selected : '\n\t\tselected = self.Status['Selected']\n\t\tif selected == []:\n\t\t\ttext += 'None'\n\t\telse:\n\t\t\tx = selected[1][0] - selected[0][0] +1\n\t\t\ty = selected[1][1] - selected[0][1] +1\n\t\t\ttext += str(x) + ' x ' + str(y)\n\t\t\ttext += '; '\n\t\t\ttext += str(selected[0]) + '-' + str(selected[1])\n\t\ttext += '\\n'\n\t\t#button\n\t\ttext += 'Button : '\n\t\tbutton_id = self.Status['Button']\n\t\tButton_Name = ['Void', 'Check', 'Bonus', 'Bonus_2', 'Drop', 'Drop_2', 'Encounter', 'Encounter_2', 'Draw', 'Draw_2', \n\t\t\t\t'Move', 'Move_2', 'WarpMove', 'WarpMove_2', 'Warp', 'Snow', 'Neutral', 'Deck'] + ['Mouse', 'ArrowDelete', 'ArrowLine', 'ArrowLineDelete', 'OK', 'Cancel']\n\t\ttext += Button_Name[button_id]\n\t\ttext += '\\n'\n\t\t\n\t\t###View\n\t\ttext += '----View----' + '\\n'\n\t\t#backtrack\n\t\ttext += 'BackTrack : '\n\t\tbacktrack = self.Status['BackTrack']\n\t\tif backtrack:\n\t\t\ttext += 'On'\n\t\telse:\n\t\t\ttext += 'Off'\n\t\ttext += '\\n'\n\t\t\n\t\t###Parameter\n\t\ttext += '----Parameter----' + '\\n'\n\t\t#history\n\t\ttext += 'History : '\n\t\thistory_now = self.Status['History_Len']-self.Status['History_Pos']\n\t\thistory_abs = self.Status['History_Len'] - 1\n\t\ttext += str(history_now)\n\t\tif history_now != history_abs:\n\t\t\ttext += '('+str(history_abs)+')'\n\t\ttext += '\\n'\n\t\t\n\t\t###Test\n\t\ttext += '----Test----' + '\\n'\n\t\ttest = self.Status['Test']\n\t\ttext += test\n\t\ttext += '\\n'\n\t\t\n\t\tself.label_main.setText(text)\n\t\t\n\t\t\n\t\t\n\t\t" }, { "alpha_fraction": 0.654018223285675, "alphanum_fraction": 0.6621570587158203, "avg_line_length": 29.36661148071289, "blob_id": "2e69d53ad7b02e3f869b42ce3a7b753cafd6acc3", "content_id": "9398f086cdab1af76df994e92e4242f158cccbcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19565, "license_type": "no_license", "max_line_length": 153, "num_lines": 611, "path": "/OFE/OFE_main.py", "repo_name": "zirconium-n/OFE", "src_encoding": "UTF-8", "text": "import sys, os\nimport re, struct\nfrom PyQt5 import QtGui, QtWidgets, QtCore\nfrom PIL import Image\nfrom PIL.ImageQt import ImageQt\n\nfrom OFE.OFE_Field import OFE_Field\nfrom OFE import ButtonWindow\nfrom OFE import StatusWindow\nfrom OFE import Canvas_Tab\nfrom OFE import OFE_Upload, OFE_New, OFE_Files\nfrom OFE.OFE_Graphics import OFE_Graphics\n\n#根目录\npath0 = os.path.dirname(__file__)\n\t\t\n#版本号\nVERSION = ' v0.3'\n\nclass OFE_MainWindow(QtWidgets.QMainWindow):\n\t\n\t#命令处理信号,当需要处理命令并因此改变界面等信息时,发射给OFE_MainWindow::A_Command,参数为字典,装着需要执行的命令。\n\tCommandEmitApp = QtCore.pyqtSignal(dict)\n\t#按钮按下信号,当按钮被按下时,从ButtonWindow::Button_Click发射,参数为按钮id\n\tButtonEmitApp = QtCore.pyqtSignal(int)\n\t\n\tdef __init__(self):\n\t\tsuper(OFE_MainWindow, self).__init__()\n\t\tself.initUI() #界面绘制交给InitUi方法\n\t\t\n\tdef initUI(self):\n\t\n\t\t#标题和图标\n\t\tself.setWindowTitle(\"100oj Fields Editor\" + VERSION) \n\t\tself.setWindowIcon(QtGui.QIcon(path0 + '/'+ 'panels/Panel_Check.png')) \n\t\t\n\t\t##加载全局参数\n\t\tself.PARAMETER = self.Init_PARAMETER()\n\t\t\n\t\t#窗口位置(来自全局参数)\n\t\twindow_pos = self.PARAMETER['Img_parameter']['Window_Pos']\n\t\tself.setGeometry(window_pos[0], window_pos[1], 1000, 600)\n\t\t\n\t\t##控件布局\n\t\tmain_ground = QtWidgets.QWidget(self)\n\t\tself.setCentralWidget(main_ground)\n\t\tself.layout_main = QtWidgets.QHBoxLayout(main_ground)\n\t\tlayout_sub = QtWidgets.QVBoxLayout()\n\t\t\n\t\t#画板区\n\t\tself.canvaswindow = Canvas_Tab(self.PARAMETER, App = {'Command':self.CommandEmitApp}) \n\t\t\n\t\t#侧边栏\n\t\tself.statuswindow = StatusWindow()\n\t\tverticalSpacer = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n\t\tself.buttonwindow = ButtonWindow(self.PARAMETER, App = {'Command':self.CommandEmitApp, 'Button':self.ButtonEmitApp})\n\t\t\n\t\tlayout_sub.addWidget(self.statuswindow)\n\t\tlayout_sub.addItem(verticalSpacer)\n\t\tlayout_sub.addWidget(self.buttonwindow)\n\t\tlayout_sub.addItem(verticalSpacer)\n\t\t\n\t\tself.layout_main.addWidget(self.canvaswindow)\n\t\tself.layout_main.addLayout(layout_sub)\n\t\t\n\t\tmain_ground.setLayout(self.layout_main)\n\t\t\n\t\t##菜单栏\n\t\t\n\t\tself.Set_Menu()\n\t\t\n\t\t###总Command连接###\n\t\tself.CommandEmitApp.connect(self.A_Command)\n\t\t\n\t\t#按钮按下信号\n\t\tself.ButtonEmitApp.connect(self.Button_Click)\n\t\t\n\t\t#主更新\n\t\tself.A_Command({'Menu': None, 'Status': {}, 'Resize': None})\n\t\t\n\t#设置菜单栏\n\tdef Set_Menu(self):\n\t\tmenubar = self.menuBar()\n\t\tself.Menu_All = {}\n\t\t\n\t\tdef set_menu(name, connect, shortcut = '', StatusTip = '', checkable=False):\n\t\t\tmenu = QtWidgets.QAction(name,self,checkable = checkable)\n\t\t\tmenu.setShortcut(shortcut)\n\t\t\tmenu.setStatusTip(StatusTip)\n\t\t\tmenu.triggered.connect(connect)\n\t\t\t\n\t\t\treturn menu\n\t\t\n\t\t##文件\n\t\tfile = menubar.addMenu(\"File\")\n\t\t#新建\n\t\tnew_menu = set_menu('New...', self.New, 'Ctrl+N', 'Open a new field')\n\t\tfile.addAction(new_menu)\n\t\tself.Menu_All['New'] = new_menu\n\t\t#打开\n\t\topen_menu = set_menu('Open...', self.Open, 'Ctrl+O', 'Open an existing field')\n\t\tfile.addAction(open_menu)\n\t\tself.Menu_All['Open'] = open_menu\n\t\t#打开\n\t\topen_official_menu = set_menu('Open Official', self.Open_Official, 'Open an official field')\n\t\tfile.addAction(open_official_menu)\n\t\tself.Menu_All['Open_Official'] = open_official_menu\n\t\t#关闭\n\t\tclose_menu = set_menu('Close', self.Close, 'Ctrl+W', 'Close the current field')\n\t\tfile.addAction(close_menu)\n\t\tself.Menu_All['Close'] = close_menu\n\t\t#--\n\t\tfile.addSeparator()\n\t\t#保存\n\t\tsave_menu = set_menu('Save Field', self.Save, 'Ctrl+S', 'Save the field in its current field name')\n\t\tfile.addAction(save_menu)\n\t\tself.Menu_All['Save'] = save_menu\n\t\t#另存为\n\t\tsave_as_menu = set_menu('Save Field As...', self.Save_As, 'Save the field with a new name')\n\t\tfile.addAction(save_as_menu)\n\t\tself.Menu_All['Save_As'] = save_as_menu\n\t\t#--\n\t\tfile.addSeparator()\n\t\t#上传\n\t\tupload_menu = set_menu('Upload', self.Upload, 'Ctrl+U', 'Upload the field to the game')\n\t\tfile.addAction(upload_menu)\n\t\tself.Menu_All['Upload'] = upload_menu\n\t\t#--\n\t\tfile.addSeparator()\n\t\t#退出\n\t\texit_menu = set_menu('Exit', QtWidgets.qApp.quit, \"Alt+F4\", \"Exit\")\n\t\tfile.addAction(exit_menu)\n\t\tself.Menu_All['Exit'] = exit_menu\n\t\t\n\t\t##编辑\n\t\tedit = menubar.addMenu(\"Edit\")\n\t\t#撤销\n\t\tundo_menu = set_menu('Undo', self.Undo, 'Ctrl+Z', 'Undo the last action')\n\t\tedit.addAction(undo_menu)\n\t\tself.Menu_All['Undo'] = undo_menu\n\t\t#重做\n\t\tredo_menu = set_menu('Redo', self.Redo, 'Ctrl+Y', 'Redo the last action')\n\t\tedit.addAction(redo_menu)\n\t\tself.Menu_All['Redo'] = redo_menu\n\t\t#--\n\t\tedit.addSeparator()\n\t\t#剪切\n\t\tcut_menu = set_menu('Cut', self.Cut, 'Ctrl+X', 'Cut the section and put it on the Clipboard')\n\t\tedit.addAction(cut_menu)\n\t\tself.Menu_All['Cut'] = cut_menu\n\t\t#复制\n\t\tcopy_menu = set_menu('Copy', self.Copy, 'Ctrl+C', 'Copy the section and put it on the Clipboard')\n\t\tedit.addAction(copy_menu)\n\t\tself.Menu_All['Copy'] = copy_menu\n\t\t#粘贴\n\t\tpaste_menu = set_menu('Paste', self.Paste, 'Ctrl+V', 'Insert Clipboard contents')\n\t\tedit.addAction(paste_menu)\n\t\tself.Menu_All['Paste'] = paste_menu\n\t\t#--\n\t\tedit.addSeparator()\n\t\t#变换\n\t\ttransform_menu = set_menu('Transform', self.Transform, 'Ctrl+T', 'Transform the section')\n\t\tedit.addAction(transform_menu)\n\t\tself.Menu_All['Transform'] = transform_menu\n\t\t#duplicate\n\t\tduplicate_menu = set_menu('Duplicate', self.Duplicate, 'Ctrl+D', 'Duplicate and transform the section')\n\t\tedit.addAction(duplicate_menu)\n\t\tself.Menu_All['Duplicate'] = duplicate_menu\n\t\t\n\t\t##视图\n\t\tview = menubar.addMenu(\"View\")\n\t\t#改变背景颜色\n\t\tbackground_menu = set_menu('Background color', self.Background, StatusTip = 'Set background color')\n\t\tview.addAction(background_menu)\n\t\tself.Menu_All['Background'] = background_menu\n\t\t#--\n\t\tview.addSeparator()\n\t\t#界面缩放大小\n\t\tzoom_level_menu = view.addMenu(\"Zoom Level\")\n\t\tzoom_level_menu.setStatusTip('Change Zoom Level')\n\t\tself.zoom_group = QtWidgets.QActionGroup(self, exclusive=True)\n\t\t\n\t\tfor zoom in self.PARAMETER['Img_parameter']['Zoom_List']:\n\t\t\taction = self.zoom_group.addAction(QtWidgets.QAction(str(zoom), self, checkable=True))\n\t\t\taction.triggered.connect(self.Zoom_Level)\n\t\t\tzoom_level_menu.addAction(action)\n\t\t\t\n\t\t\tif zoom == self.PARAMETER['Img_parameter']['Zoom']:\n\t\t\t\taction.setChecked(True)\n\t\t#按钮缩放大小\n\t\tbutton_zoom_level_menu = view.addMenu(\"Button Zoom Level\")\n\t\tbutton_zoom_level_menu.setStatusTip('Change Buttons Zoom Level')\n\t\tself.button_zoom_group = QtWidgets.QActionGroup(self, exclusive=True)\n\t\t\n\t\tfor zoom in self.PARAMETER['Img_parameter']['Zoom_List']:\n\t\t\taction = self.button_zoom_group.addAction(QtWidgets.QAction(str(zoom), self, checkable=True))\n\t\t\taction.triggered.connect(self.Button_Zoom_Level)\n\t\t\tbutton_zoom_level_menu.addAction(action)\n\t\t\t\n\t\t\tif zoom == self.PARAMETER['Img_parameter']['Button_Zoom']:\n\t\t\t\taction.setChecked(True)\n\t\t#--\n\t\tview.addSeparator()\n\t\t#BackTrack\n\t\tbacktrack_menu = set_menu('BackTrack', self.BackTrack, StatusTip = 'Switch BackTrack', checkable = True)\n\t\tview.addAction(backtrack_menu)\n\t\tself.Menu_All['BackTrack'] = backtrack_menu\n\t\t\n\t\t\n\t#初始化参数\n\tdef Init_PARAMETER(self):\n\t\tparameter = {}\n\t\t#读取参数文件\n\t\ttry:\n\t\t\tfile_para = open(path0 + '/'+ 'user.dat', 'r')\n\t\texcept:\n\t\t\ttext_para = ''\n\t\telse:\n\t\t\ttext_para = file_para.read()\n\t\t\tprint(text_para)\n\t\t\tfile_para.close()\n\t\t\n\t\t#在文本中寻找对应参数\n\t\tdef find_parameter(text, name, default):\n\t\t\ttry:\n\t\t\t\ttext1 = re.search(name + '=.+', text).group()\n\t\t\texcept:\n\t\t\t\tvalue = default\n\t\t\telse:\n\t\t\t\tpos = text1.find('=')\n\t\t\t\tvalue = text1[pos+1:]\n\t\t\t\tif type(default) == type(0.75):\n\t\t\t\t\tvalue = float(value)\n\t\t\t\telif type(default) == type(1):\n\t\t\t\t\tvalue = int(value)\n\t\t\t\telif type(default) == type((1,2,3)):\n\t\t\t\t\tp = re.compile(',')\n\t\t\t\t\tvalue = tuple(map(int, (p.split(value[1:-1]))))\n\t\t\t\telif type(default) == type('path'):\n\t\t\t\t\tvalue = str(value)\n\t\t\treturn value\n\t\t\n\t\t#文件参数\n\t\tparameter['Clipboard'] = None\n\t\tparameter['Path_Save'] = find_parameter(text_para, 'Path_Save', path0)\n\t\tparameter['Path_Game'] = find_parameter(text_para, 'Path_Game', path0)\n\t\t#视图参数\n\t\tparameter['Img_parameter'] = {}\n\t\tparameter['Img_parameter']['Window_Pos'] = find_parameter(text_para, 'Window_Pos', (600, 60))\n\t\tparameter['Img_parameter']['Zoom_List'] = (0.25, 0.375, 0.5, 0.625, 0.75, 1.0)\n\t\tparameter['Img_parameter']['Zoom'] = find_parameter(text_para, 'Zoom', 0.5)\n\t\tparameter['Img_parameter']['Background'] = find_parameter(text_para, 'Background', (52,52,52,256))\n\t\tparameter['Img_parameter']['Show_arrows'] = find_parameter(text_para, 'Show_arrows', 1)\n\t\tparameter['Img_parameter']['Button_Zoom'] = find_parameter(text_para, 'Button_Zoom', 0.5)\n\t\tparameter['Img_parameter']['BackTrack'] = 0\n\t\tparameter['Img_parameter']['Frame'] = find_parameter(text_para, 'Frame', 1)\n\t\t#菜单可用参数\n\t\tparameter['Menu_able'] = {}\n\t\tparameter['Menu_able']['Close'] = 1\n\t\tparameter['Menu_able']['Save'] = 1\n\t\tparameter['Menu_able']['Save_As'] = 1\n\t\tparameter['Menu_able']['Undo'] = 1\n\t\tparameter['Menu_able']['Redo'] = 1\n\t\tparameter['Menu_able']['Cut'] = 1\n\t\tparameter['Menu_able']['Copy'] = 1\n\t\tparameter['Menu_able']['Paste'] = 1\n\t\tparameter['Menu_able']['Transform'] = 1\n\t\tparameter['Menu_able']['Duplicate'] = 1\n\t\t#涉及命令逻辑的相关参数\n\t\tparameter['Command'] = {}\n\t\t#当前按下的按钮\n\t\tparameter['Command']['Button'] = 18\n\t\t\n\t\t#加载图片素材\n\t\tzoom_list = parameter['Img_parameter']['Zoom_List'] = (0.25, 0.375, 0.5, 0.625, 0.75, 1.0)\n\t\tparameter['Graphics'] = OFE_Graphics(zoom_list, path0 + '/'+ 'panels')\n\t\t\n\t\t#设置按钮Id\n\t\tparameter['Button'] = {}\n\t\tparameter['Button']['Type'] = ['Panel', 'Mouse', 'Transform']\n\t\tparameter['Button']['Specific'] = [['Void', 'Check', 'Bonus', 'Bonus_2', 'Drop', 'Drop_2', 'Encounter', 'Encounter_2', \n\t\t\t\t'Draw', 'Draw_2', 'Move', 'Move_2', 'WarpMove', 'WarpMove_2', 'Warp', 'Snow', 'Neutral', 'Deck'],\n\t\t\t\t['Mouse', 'ArrowDelete', 'ArrowLine', 'ArrowLineDelete', 'OK', 'Cancel'],\n\t\t\t\t['Clock_test', 'AntiClock_test', 'Vertical_test', 'Horizonal_test', 'OK', 'Cancel']]\n\t\tparameter['Button']['Id'] = {}\n\t\tparameter['Button']['Name'] = {}\n\t\tfor i, type_ in enumerate(parameter['Button']['Type']):\n\t\t\tfor j, specific in enumerate(parameter['Button']['Specific'][i]):\n\t\t\t\tid = 100*i + j\n\t\t\t\tparameter['Button']['Id'][id] = specific\n\t\t\t\tparameter['Button']['Name'][specific] = id\n\t\t\t\t\n\t\tprint(parameter['Button']['Id'])\n\t\tprint(parameter['Button']['Name'])\n\t\t\n\t\treturn parameter\n\t\t\n\t#重关闭事件\n\tdef closeEvent(self, event):\n\t\t#写入参数文件\n\t\tfile_para = open(path0 + '/'+ 'user.dat', 'w')\n\t\ttext = ''\n\t\t\n\t\tdef write_parameter(text, name, value):\n\t\t\ttext += name + '=' + str(value) + '\\n'\n\t\t\treturn text\n\t\t\n\t\ttext = write_parameter(text, 'Path_Save', self.PARAMETER['Path_Save'])\n\t\ttext = write_parameter(text, 'Path_Game', self.PARAMETER['Path_Game'])\n\t\ttext = write_parameter(text, 'Window_Pos', self.PARAMETER['Img_parameter']['Window_Pos'])\n\t\ttext = write_parameter(text, 'Zoom', self.PARAMETER['Img_parameter']['Zoom'])\n\t\ttext = write_parameter(text, 'Background', self.PARAMETER['Img_parameter']['Background'])\n\t\ttext = write_parameter(text, 'Show_arrows', self.PARAMETER['Img_parameter']['Show_arrows'])\n\t\ttext = write_parameter(text, 'Button_Zoom', self.PARAMETER['Img_parameter']['Button_Zoom'])\n\t\ttext = write_parameter(text, 'Frame', self.PARAMETER['Img_parameter']['Frame'])\n\t\t\n\t\tfile_para.write(text)\n\t\tfile_para.close()\n\t\t\n\t#重写移动事件\n\tdef moveEvent(self, event):\n\t\tpos = (event.pos().x(), event.pos().y())\n\t\tself.PARAMETER['Img_parameter']['Window_Pos'] = pos\n\t\t\n\t###总Command函数###\n\tdef A_Command(self, command):\n\t\t\n\t\t#Paint,在画板上重绘,command['Paint'] = {}\n\t\tif 'Paint' in command:\n\t\t\tself.canvaswindow.A_Paint(command['Paint'])\n\t\t#Button,改变按钮形貌,command['Button'] = {}\n\t\tif 'Button' in command:\n\t\t\t#先调用下级,从而给command['Button']['Icon']赋值 = {'Type': str}\n\t\t\tif 'Icon' in command['Button']:\n\t\t\t\tself.canvaswindow.A_Button(command['Button']['Icon'])\n\t\t\tself.buttonwindow.A_Button(command['Button'])\n\t\t#Resize\n\t\tif 'Resize' in command:\n\t\t\tself.Resize()\n\t\t#Menu\n\t\tif 'Menu' in command:\n\t\t\tself.Menu_Refresh()\n\t\t#Status\n\t\tif 'Status' in command:\n\t\t\t#先调用下级,从而给command['Status']赋值 = {...}\n\t\t\tself.canvaswindow.A_Status(command['Status'])\n\t\t\tself.statuswindow.A_Status(command['Status'])\n\t\t#Tab\n\t\tif 'Tab' in command:\n\t\t\tself.canvaswindow.Tab_Refresh()\n\t\t\t\n\t#尺寸调整\n\tdef Resize(self):\n\t\t#屏幕大小\n\t\tscreen = QtWidgets.QDesktopWidget().screenGeometry()\n\t\tMaxWidth = screen.width()-200\n\t\tMaxHeight = screen.height()-100\n\t\t#推荐窗口尺寸,来自画板\n\t\tcommandwidth = self.canvaswindow.width() + 86 \n\t\tcommandheight = self.canvaswindow.height() + 150 \n\t\t#来自按钮\n\t\tPX = 128\n\t\tbutton_zoom = self.PARAMETER['Img_parameter']['Button_Zoom']\n\t\tpx = int(PX * button_zoom)\n\t\tcommandwidth += 6 * px\n\t\tself.resize(min(commandwidth, MaxWidth), min(commandheight,MaxHeight))\n\t\t\t\n\tdef Menu_Refresh(self):\n\t\t#调用下级\n\t\tself.canvaswindow.Menu_Change()\n\t\n\t\t#菜单栏管理\n\t\tfor key in self.PARAMETER['Menu_able']:\n\t\t\tif self.PARAMETER['Menu_able'][key]:\n\t\t\t\tself.Menu_All[key].setEnabled(False)\n\t\t\telse:\n\t\t\t\tself.Menu_All[key].setEnabled(True)\n\t\t#标题管理\n\t\tid = self.canvaswindow.currentIndex()\n\t\tif id >= 0:\n\t\t\tif self.canvaswindow.Canvas_List[id].Is_Field():\n\t\t\t\ttext = \"100oj Fields Editor\" + VERSION\n\t\t\t\tfile_full = self.canvaswindow.Canvas_List[id].file_path()\n\t\t\t\tif file_full != '':\n\t\t\t\t\ttext += \" - \" + file_full\n\t\t\t\tself.setWindowTitle(text)\n\t\t\telse:\n\t\t\t\tself.setWindowTitle(\"100oj Fields Editor\" + VERSION)\n\t\telse:\n\t\t\tself.setWindowTitle(\"100oj Fields Editor\" + VERSION)\n\t\t\t\n\t#更新状态\n\t\t\n\tdef Button_Click(self, id):\n\t\tprint(\"Main Button Click\", id)\n\t\tself.canvaswindow.Button_Click(id)\n\t\t\n\tdef New(self):\n\t\tSize = OFE_New.Get_Size(self)\n\t\tif Size:\n\t\t\t\n\t\t\t#新建并存入画板\n\t\t\tfield = OFE_Field('new', Size)\n\t\t\tself.canvaswindow.Insert_Canvas(field, 'Untitled')\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#Last Action\n\t\t\ta_command['Status'] = {}\n\t\t\ta_command['Status']['Last_Action'] = '[New]'\n\t\t\t#A_Command信号发射\n\t\t\tself.CommandEmitApp.emit(a_command)\n\t\t\t\n\t\t\n\tdef Open(self):\n\t\toptions = QtWidgets.QFileDialog.Options()\n\t\tfile_full, _ = QtWidgets.QFileDialog.getOpenFileName(self,\"Open a field\", self.PARAMETER['Path_Save'],\"Fields (*.fld);;All Files (*)\", options=options)\n\t\tif file_full:\n\t\t\tfile_name = QtCore.QFileInfo(file_full).fileName()\n\t\t\tfile_path = QtCore.QFileInfo(file_full).absolutePath()\n\t\t\t#重设默认路径\n\t\t\tself.PARAMETER['Path_Save'] = file_path\n\t\t\t#打开文件至画板\n\t\t\tfield = OFE_Field('open', file_full)\n\t\t\tself.canvaswindow.Insert_Canvas(field, file_name, file_full)\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#尺寸调整\n\t\t\ta_command['Resize'] = None\n\t\t\t#菜单调整\n\t\t\ta_command['Menu'] = None\n\t\t\t#Last Action\n\t\t\ta_command['Status'] = {}\n\t\t\ta_command['Status']['Last_Action'] = '[Open] ' + file_name\n\t\t\t#A_Command信号发射\n\t\t\tself.CommandEmitApp.emit(a_command)\n\t\t\t\n\tdef Open_Official(self):\n\t\tField_and_Name = OFE_Files.Get_Field(self)\n\t\tif Field_and_Name:\n\t\t\tfield = Field_and_Name[0]\n\t\t\tname = Field_and_Name[1]\n\t\t\t\n\t\t\tself.canvaswindow.Insert_Canvas(field, name)\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#尺寸调整\n\t\t\ta_command['Resize'] = None\n\t\t\t#菜单调整\n\t\t\ta_command['Menu'] = None\n\t\t\t#Last Action\n\t\t\ta_command['Status'] = {}\n\t\t\ta_command['Status']['Last_Action'] = '[Open] ' + name\n\t\t\t#A_Command信号发射\n\t\t\tself.CommandEmitApp.emit(a_command)\n\t\t\t\n\t\t\t\n\tdef Close(self):\n\t\tfile_name = self.canvaswindow.Remove_Canvas()\n\t\t\n\t\tif file_name:\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#尺寸调整\n\t\t\ta_command['Resize'] = None\n\t\t\t#菜单调整\n\t\t\ta_command['Menu'] = None\n\t\t\t#Last Action\n\t\t\ta_command['Status'] = {}\n\t\t\ta_command['Status']['Last_Action'] = '[Close] '+file_name\n\t\t\t#A_Command信号发射\n\t\t\tself.CommandEmitApp.emit(a_command)\n\t\telse:\n\t\t\tprint('Error: Can not close.')\n\t\t\n\tdef Save(self):\n\t\tneed_save = self.canvaswindow.Need_Save()\n\t\tif need_save:\n\t\t\tfile_path = self.canvaswindow.file_path()\n\t\t\tif file_path == '':\n\t\t\t\tself.Save_As()\n\t\t\telse:\n\t\t\t\tfile_full = file_path\n\t\t\t\t#初始化\n\t\t\t\tfile_name = QtCore.QFileInfo(file_full).fileName()\n\t\t\t\tfile_path = QtCore.QFileInfo(file_full).absolutePath()\n\t\t\t\t#重设默认路径\n\t\t\t\tself.PARAMETER['Path_Save'] = file_path\n\t\t\t\t#储存成文件\n\t\t\t\tself.canvaswindow.Save(file_full)\n\t\t\t\t\n\t\t\t\t#A_Command\n\t\t\t\ta_command = {}\n\t\t\t\t#Last Action\n\t\t\t\ta_command['Status'] = {}\n\t\t\t\ta_command['Status']['Last_Action'] = '[Save] ' + file_name\n\t\t\t\t#A_Command信号发射\n\t\t\t\tself.CommandEmitApp.emit(a_command)\n\t\t\n\tdef Save_As(self):\n\t\toptions = QtWidgets.QFileDialog.Options()\n\t\tfile_full, _ = QtWidgets.QFileDialog.getSaveFileName(self,\"Save Field\", self.PARAMETER['Path_Save'],\"Fields (*.fld);;All Files (*)\", options=options)\n\t\tif file_full:\n\t\t\t#初始化\n\t\t\tfile_name = QtCore.QFileInfo(file_full).fileName()\n\t\t\tfile_path = QtCore.QFileInfo(file_full).absolutePath()\n\t\t\t#重设默认路径\n\t\t\tself.PARAMETER['Path_Save'] = file_path\n\t\t\t#储存成文件\n\t\t\tself.canvaswindow.Save(file_full)\n\t\t\t\n\t\t\t#A_Command\n\t\t\ta_command = {}\n\t\t\t#Last Action\n\t\t\ta_command['Status'] = {}\n\t\t\ta_command['Status']['Last_Action'] = '[Save] ' + file_name\n\t\t\t#A_Command信号发射\n\t\t\tself.CommandEmitApp.emit(a_command)\n\t\t\n\tdef Upload(self):\n\t\t#获取当前field\n\t\tid = self.canvaswindow.currentIndex()\n\t\tif id >= 0:\n\t\t\tfield_now = self.canvaswindow.Field()\n\t\t\t\t\n\t\t#打开dialog,返回game文件的新路径\n\t\tpath_new = OFE_Upload.Upload_Main(self, self.PARAMETER['Path_Game'], field_now)\n\t\tif path_new:\n\t\t\tself.PARAMETER['Path_Game'] = path_new\n\t\t\n\tdef Undo(self):\n\t\tself.canvaswindow.Undo()\n\t\t\n\tdef Redo(self):\n\t\tself.canvaswindow.Redo()\n\t\t\n\tdef Cut(self):\n\t\tself.canvaswindow.Cut()\n\t\t\n\tdef Copy(self):\n\t\tself.canvaswindow.Copy()\n\t\t\n\tdef Paste(self):\n\t\tself.canvaswindow.Paste()\n\t\t\n\tdef Transform(self):\n\t\tself.canvaswindow.Transform()\n\t\t\n\tdef Duplicate(self):\n\t\tself.canvaswindow.Duplicate()\n\t\t\n\tdef Background(self):\n\t\tcol = QtWidgets.QColorDialog.getColor()\n\t\tif col.isValid(): \n\t\t\tself.PARAMETER['Img_parameter']['Background'] = (col.red(), col.green(), col.blue(), 256)\n\t\t\t\n\tdef Zoom_Level(self):\n\t\taction_this = self.zoom_group.checkedAction()\n\t\tzoom = float(action_this.text())\n\t\t\n\t\tself.PARAMETER['Img_parameter']['Zoom'] = zoom\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#图像刷新,transform刷新\n\t\ta_command['Paint'] = {'All':None, 'Transform_Redraw': None}\n\t\t#画布大小\n\t\ta_command['Resize'] = None\n\t\t#A_Command信号发射\n\t\tself.CommandEmitApp.emit(a_command)\n\t\t\n\tdef Button_Zoom_Level(self):\n\t\taction_this = self.button_zoom_group.checkedAction()\n\t\tzoom = float(action_this.text())\n\t\t\n\t\tself.PARAMETER['Img_parameter']['Button_Zoom'] = zoom\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#按钮大小重设\n\t\ta_command['Button'] = {'Zoom': None}\n\t\t#画布大小\n\t\ta_command['Resize'] = None\n\t\t#A_Command信号发射\n\t\tself.CommandEmitApp.emit(a_command)\n\t\t\t\n\tdef BackTrack(self, state):\n\t\tif state:\n\t\t\tself.PARAMETER['Img_parameter']['BackTrack'] = 1\n\t\telse:\n\t\t\tself.PARAMETER['Img_parameter']['BackTrack'] = 0\n\t\t\n\t\t#A_Command\n\t\ta_command = {}\n\t\t#图像刷新,transform刷新\n\t\ta_command['Paint'] = {'All':None, 'Transform_Redraw': None}\n\t\t#画布大小\n\t\ta_command['Resize'] = None\n\t\t#A_Command信号发射\n\t\tself.CommandEmitApp.emit(a_command)\n\t\t\ndef run():\n\tapp = QtWidgets.QApplication(sys.argv)\n\tex = OFE_MainWindow()\n\tex.show()\n\tsys.exit(app.exec_()) \n\nif __name__ == '__main__':\n\trun()" } ]
11
coleifer/walrus
https://github.com/coleifer/walrus
8a0c363d0bcfe9eaf78c9911c5b61f5b2b47c817
d3907e190024a04a0c356e376765b8570aca2e02
1f62d0c90d46fe2f43102fc77eb43f6e4e9f24e3
refs/heads/master
2023-08-28T10:22:16.394863
2023-08-17T12:34:12
2023-08-17T12:34:12
28,473,847
1,182
110
MIT
2014-12-25T06:54:09
2022-11-24T18:18:00
2022-11-27T13:44:02
Python
[ { "alpha_fraction": 0.6260433793067932, "alphanum_fraction": 0.6510851383209229, "avg_line_length": 25.04347801208496, "blob_id": "fe95e595dbc67f8ddf6d97374799925ecff82f8b", "content_id": "b398e61fb440fa42da1bbce87520565df11724ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 599, "license_type": "permissive", "max_line_length": 57, "num_lines": 23, "path": "/walrus/scripts/rate_limit.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal limit_count = tonumber(ARGV[1])\nlocal limit_time = tonumber(ARGV[2])\nlocal current_time = tonumber(ARGV[3])\n\nlocal rc = redis.call('LLEN', key)\n\nlocal is_limited = 0\nlocal oldest = 0\n\nif rc < limit_count then\n redis.call('LPUSH', key, current_time)\nelse\n oldest = tonumber(redis.call('LINDEX', key, -1)) or 0\n if (current_time - oldest) < limit_time then\n is_limited = 1\n else\n redis.call('LPUSH', key, current_time)\n end\n redis.call('LTRIM', key, 0, limit_count - 1)\n redis.call('PEXPIRE', key, limit_count * 2000)\nend\nreturn is_limited\n" }, { "alpha_fraction": 0.6389001607894897, "alphanum_fraction": 0.644182562828064, "avg_line_length": 36.668365478515625, "blob_id": "8ced91cb9d7eb5afe59de216305c3df47faffa36", "content_id": "2d3fa77ebc1d05f54f313f20a7d8236bb78a6be9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7383, "license_type": "permissive", "max_line_length": 78, "num_lines": 196, "path": "/walrus/streams.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import datetime\nimport operator\nimport time\n\nfrom walrus.containers import ConsumerGroup\nfrom walrus.containers import ConsumerGroupStream\nfrom walrus.utils import basestring_type\nfrom walrus.utils import decode\nfrom walrus.utils import decode_dict\nfrom walrus.utils import make_python_attr\n\n\ndef id_to_datetime(ts):\n tsm, seq = ts.split(b'-', 1)\n return datetime.datetime.fromtimestamp(int(tsm) / 1000.), int(seq)\n\ndef datetime_to_id(dt, seq=0):\n tsm = time.mktime(dt.timetuple()) * 1000\n return '%s-%s' % (int(tsm + (dt.microsecond / 1000)), seq)\n\n\nclass Message(object):\n \"\"\"\n A message stored in a Redis stream.\n\n When reading messages from a :py:class:`TimeSeries`, the usual 2-tuple of\n (message id, data) is unpacked into a :py:class:`Message` instance. The\n message instance provides convenient access to the message timestamp as a\n datetime. Additionally, the message data is UTF8-decoded for convenience.\n \"\"\"\n __slots__ = ('stream', 'timestamp', 'sequence', 'data', 'message_id')\n\n def __init__(self, stream, message_id, data):\n self.stream = decode(stream)\n self.message_id = decode(message_id)\n self.data = decode_dict(data)\n self.timestamp, self.sequence = id_to_datetime(message_id)\n\n def __repr__(self):\n return '<Message %s %s: %s>' % (self.stream, self.message_id,\n self.data)\n\n\ndef normalize_id(message_id):\n if isinstance(message_id, basestring_type):\n return message_id\n elif isinstance(message_id, datetime.datetime):\n return datetime_to_id(message_id)\n elif isinstance(message_id, tuple):\n return datetime_to_id(*message_id)\n elif isinstance(message_id, Message):\n return message_id.message_id\n return message_id\n\n\ndef normalize_ids(id_list):\n return [normalize_id(id) for id in id_list]\n\n\ndef xread_to_messages(resp):\n if resp is None: return\n accum = []\n for stream, messages in resp:\n accum.extend(xrange_to_messages(stream, messages))\n # If multiple streams are present, sort them by timestamp.\n if len(resp) > 1:\n accum.sort(key=operator.attrgetter('message_id'))\n return accum\n\n\ndef xrange_to_messages(stream, resp):\n return [Message(stream, message_id, data) for message_id, data in resp]\n\n\nclass TimeSeriesStream(ConsumerGroupStream):\n \"\"\"\n Helper for working with an individual stream within the context of a\n :py:class:`TimeSeries` consumer group. This object is exposed as an\n attribute on a :py:class:`TimeSeries` object using the stream key for the\n attribute name.\n\n This class should not be created directly. It will automatically be added\n to the ``TimeSeries`` object.\n\n For example::\n\n ts = db.time_series('events', ['stream-1', 'stream-2'])\n ts.stream_1 # TimeSeriesStream for \"stream-1\"\n ts.stream_2 # TimeSeriesStream for \"stream-2\"\n\n This class implements the same methods as :py:class:`ConsumerGroupStream`,\n with the following differences in behavior:\n\n * Anywhere an ID (or list of IDs) is accepted, this class will also accept\n a datetime, a 2-tuple of (datetime, sequence), a :py:class:`Message`, in\n addition to a regular bytestring ID.\n * Instead of returning a list of (message id, data) 2-tuples, this class\n returns a list of :py:class:`Message` objects.\n * Data is automatically UTF8 decoded when being read for convenience.\n \"\"\"\n __slots__ = ('database', 'group', 'key', '_consumer')\n\n def ack(self, *id_list):\n return super(TimeSeriesStream, self).ack(*normalize_ids(id_list))\n\n def add(self, data, id='*', maxlen=None, approximate=True):\n db_id = super(TimeSeriesStream, self).add(data, normalize_id(id),\n maxlen, approximate)\n return id_to_datetime(db_id)\n\n def claim(self, *id_list, **kwargs):\n resp = super(TimeSeriesStream, self).claim(*normalize_ids(id_list),\n **kwargs)\n return xrange_to_messages(self.key, resp)\n\n def delete(self, *id_list):\n return super(TimeSeriesStream, self).delete(*normalize_ids(id_list))\n\n def get(self, id):\n id = normalize_id(id)\n messages = self.range(id, id, 1)\n if messages:\n return messages[0]\n\n def range(self, start='-', stop='+', count=None):\n resp = super(TimeSeriesStream, self).range(\n normalize_id(start),\n normalize_id(stop),\n count)\n return xrange_to_messages(self.key, resp)\n\n def pending(self, start='-', stop='+', count=1000, consumer=None,\n idle=None):\n start = normalize_id(start)\n stop = normalize_id(stop)\n resp = self.database.xpending_range(self.key, self.group, min=start,\n max=stop, count=count,\n consumername=consumer, idle=idle)\n return [(id_to_datetime(msg['message_id']), decode(msg['consumer']),\n msg['time_since_delivered'], msg['times_delivered'])\n for msg in resp]\n\n def read(self, count=None, block=None):\n resp = super(TimeSeriesStream, self).read(count, block)\n if resp is not None:\n return xrange_to_messages(self.key, resp)\n\n def set_id(self, id='$'):\n return super(TimeSeriesStream, self).set_id(normalize_id(id))\n\n\nclass TimeSeries(ConsumerGroup):\n \"\"\"\n :py:class:`TimeSeries` is a consumer-group that provides a higher level of\n abstraction, reading and writing message ids as datetimes, and returning\n messages using a convenient, lightweight :py:class:`Message` class.\n\n Rather than creating this class directly, use the\n :py:meth:`Database.time_series` method.\n\n Each registered stream within the group is exposed as a special attribute\n that provides stream-specific APIs within the context of the group. For\n more information see :py:class:`TimeSeriesStream`.\n\n Example::\n\n ts = db.time_series('groupname', ['stream-1', 'stream-2'])\n ts.stream_1 # TimeSeriesStream for \"stream-1\"\n ts.stream_2 # TimeSeriesStream for \"stream-2\"\n\n :param Database database: Redis client\n :param group: name of consumer group\n :param keys: stream identifier(s) to monitor. May be a single stream\n key, a list of stream keys, or a key-to-minimum id mapping. The\n minimum id for each stream should be considered an exclusive\n lower-bound. The '$' value can also be used to only read values\n added *after* our command started blocking.\n :param consumer: name for consumer within group\n :returns: a :py:class:`TimeSeries` instance\n \"\"\"\n stream_key_class = TimeSeriesStream\n\n def read(self, count=None, block=None):\n \"\"\"\n Read unseen messages from all streams in the consumer group. Wrapper\n for :py:class:`Database.xreadgroup` method.\n\n :param int count: limit number of messages returned\n :param int block: milliseconds to block, 0 for indefinitely.\n :returns: a list of :py:class:`Message` objects\n \"\"\"\n resp = super(TimeSeries, self).read(count, block)\n return xread_to_messages(resp)\n\n def set_id(self, id='$'):\n return super(TimeSeries, self).set_id(normalize_id(id))\n" }, { "alpha_fraction": 0.5280894637107849, "alphanum_fraction": 0.5456700325012207, "avg_line_length": 33.25168991088867, "blob_id": "5611b1e2914a4ebee5083be88389d2dc59c37db8", "content_id": "fb586bb7b4269fc22b60c88f4c1edba221f3de9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25312, "license_type": "permissive", "max_line_length": 78, "num_lines": 739, "path": "/walrus/tests/models.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom walrus import *\nfrom walrus.query import OP_AND\nfrom walrus.query import OP_OR\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass BaseModel(Model):\n __database__ = db\n __namespace__ = 'test'\n\n\nclass User(BaseModel):\n username = TextField(primary_key=True)\n\n\nclass Note(BaseModel):\n user = TextField(index=True)\n text = TextField()\n timestamp = DateTimeField(default=datetime.datetime.now, index=True)\n tags = JSONField()\n\n\nclass Message(BaseModel):\n content = TextField(fts=True)\n status = IntegerField(default=1, index=True)\n\n\nclass FTSOptions(BaseModel):\n content = TextField(fts=True, stemmer=True)\n metaphone = TextField(fts=True, stemmer=True, metaphone=True)\n\n\nclass Stat(BaseModel):\n key = AutoIncrementField()\n stat_type = ByteField(index=True)\n value = IntegerField(index=True)\n\n\nclass DefaultOption(BaseModel):\n default_empty = JSONField()\n txt = TextField(default='')\n num = IntegerField(default=0)\n\n\nclass TestModels(WalrusTestCase):\n def create_objects(self):\n for i in range(3):\n u = User.create(username='u%s' % (i + 1))\n for j in range(3):\n Note.create(\n user=u.username,\n text='n%s-%s' % (i + 1, j + 1),\n tags=['t%s' % (k + 1) for k in range(j)])\n\n def test_textfield_whitespace(self):\n h = User.create(username='huey cat')\n z = User.create(username='zaizee cat')\n h_db = User.load('huey cat')\n self.assertEqual(h_db.username, 'huey cat')\n z_db = User.load('zaizee cat')\n self.assertEqual(z_db.username, 'zaizee cat')\n\n query = User.query(User.username == 'huey cat')\n self.assertEqual([u.username for u in query], ['huey cat'])\n self.assertRaises(KeyError, User.load, 'mickey dog')\n\n def test_store_none(self):\n class Simple(BaseModel):\n text = TextField()\n number = IntegerField()\n normalized = FloatField()\n\n s = Simple.create(text=None, number=None, normalized=None)\n s_db = Simple.load(s._id)\n self.assertEqual(s_db.text, '')\n self.assertEqual(s_db.number, 0)\n self.assertEqual(s_db.normalized, 0.)\n\n def test_create(self):\n self.create_objects()\n self.assertEqual(\n sorted(user.username for user in User.all()),\n ['u1', 'u2', 'u3'])\n\n notes = Note.query(Note.user == 'u1')\n self.assertEqual(\n sorted(note.text for note in notes),\n ['n1-1', 'n1-2', 'n1-3'])\n\n notes = sorted(\n Note.query(Note.user == 'u2'),\n key = lambda note: note._id)\n note = notes[2]\n self.assertEqual(note.tags, ['t1', 't2'])\n\n def test_exceptions(self):\n self.assertRaises(KeyError, User.load, 'charlie')\n User.create(username='charlie')\n user = User.load('charlie')\n self.assertEqual(user.username, 'charlie')\n\n def test_query(self):\n self.create_objects()\n notes = Note.query(Note.user == 'u2')\n self.assertEqual(\n sorted(note.text for note in notes),\n ['n2-1', 'n2-2', 'n2-3'])\n\n user = User.get(User.username == 'u3')\n self.assertEqual(user._data, {'username': 'u3'})\n\n self.assertRaises(ValueError, User.get, User.username == 'ux')\n\n def test_query_with_update(self):\n stat = Stat.create(stat_type='s1', value=1)\n vq = list(Stat.query(Stat.value == 1))\n self.assertEqual(len(vq), 1)\n stat_db = vq[0]\n self.assertEqual(stat_db.stat_type, b's1')\n self.assertEqual(stat_db.value, 1)\n\n stat.value = 2\n stat.save()\n\n def assertCount(expr, count):\n self.assertEqual(len(list(Stat.query(expr))), count)\n\n assertCount(Stat.value == 1, 0)\n assertCount(Stat.value == 2, 1)\n assertCount(Stat.stat_type == 's1', 1)\n\n stat.stat_type = 's2'\n stat.save()\n\n assertCount(Stat.value == 1, 0)\n assertCount(Stat.value == 2, 1)\n assertCount(Stat.stat_type == 's1', 0)\n assertCount(Stat.stat_type == 's2', 1)\n\n def test_sorting(self):\n self.create_objects()\n all_notes = [\n 'n1-1', 'n1-2', 'n1-3', 'n2-1', 'n2-2', 'n2-3', 'n3-1', 'n3-2',\n 'n3-3']\n\n notes = Note.query(order_by=Note.text)\n self.assertEqual([note.text for note in notes], all_notes)\n\n notes = Note.query(order_by=Note.text.desc())\n self.assertEqual(\n [note.text for note in notes],\n all_notes[::-1])\n\n notes = Note.query(Note.user == 'u2', Note.text)\n self.assertEqual(\n [note.text for note in notes],\n ['n2-1', 'n2-2', 'n2-3'])\n\n notes = Note.query(Note.user == 'u2', Note.text.desc())\n self.assertEqual(\n [note.text for note in notes],\n ['n2-3', 'n2-2', 'n2-1'])\n\n def test_complex_query(self):\n usernames = ['charlie', 'huey', 'mickey', 'zaizee']\n for username in usernames:\n User.create(username=username)\n\n def assertUsers(expr, expected):\n users = User.query(expr)\n self.assertEqual(\n sorted(user.username for user in users),\n sorted(expected))\n\n assertUsers(User.username == 'charlie', ['charlie'])\n assertUsers(User.username != 'huey', ['charlie', 'mickey', 'zaizee'])\n assertUsers(\n ((User.username == 'charlie') | (User.username == 'mickey')),\n ['charlie', 'mickey'])\n assertUsers(\n (User.username == 'charlie') | (User.username != 'mickey'),\n ['charlie', 'huey', 'zaizee'])\n expr = (\n ((User.username != 'huey') & (User.username != 'zaizee')) |\n (User.username == 'charlie'))\n assertUsers(expr, ['charlie', 'mickey'])\n\n def test_scalar_query(self):\n data = [\n ('t1', 1),\n ('t1', 2),\n ('t1', 3),\n ('t2', 10),\n ('t2', 11),\n ('t2', 12),\n ('t3', 0),\n ]\n for stat_type, value in data:\n Stat.create(stat_type=stat_type, value=value)\n\n stat_objects = sorted(\n (stat for stat in Stat.all()),\n key=lambda stat: stat.key)\n self.assertEqual([stat._data for stat in stat_objects], [\n {'key': 1, 'stat_type': b't1', 'value': 1},\n {'key': 2, 'stat_type': b't1', 'value': 2},\n {'key': 3, 'stat_type': b't1', 'value': 3},\n {'key': 4, 'stat_type': b't2', 'value': 10},\n {'key': 5, 'stat_type': b't2', 'value': 11},\n {'key': 6, 'stat_type': b't2', 'value': 12},\n {'key': 7, 'stat_type': b't3', 'value': 0},\n ])\n\n def assertStats(expr, expected):\n stats = Stat.query(expr)\n self.assertEqual(\n sorted(stat.key for stat in stats),\n sorted(expected))\n\n assertStats(Stat.value <= 3, [1, 2, 3, 7])\n assertStats(Stat.value >= 10, [4, 5, 6])\n assertStats(Stat.value < 3, [1, 2, 7])\n assertStats(Stat.value > 10, [5, 6])\n\n assertStats(Stat.value == 3, [3])\n assertStats(Stat.value >= 13, [])\n assertStats(\n (Stat.value <= 2) | (Stat.key >= 7),\n [1, 2, 7])\n assertStats(\n ((Stat.value <= 2) & (Stat.key >= 7)) | (Stat.value >= 11),\n [5, 6, 7])\n assertStats(\n ((Stat.value <= 2) | (Stat.key >= 7)) & (Stat.stat_type == 't1'),\n [1, 2])\n\n assertStats(Stat.value.between(2, 11), [2, 3, 4, 5])\n assertStats(Stat.value.between(4, 12), [4, 5, 6])\n\n def test_full_text_search(self):\n phrases = [\n ('A faith is a necessity to a man. Woe to him who believes in '\n 'nothing.'),\n ('All who call on God in true faith, earnestly from the heart, '\n 'will certainly be heard, and will receive what they have asked '\n 'and desired.'),\n ('Be faithful in small things because it is in them that your '\n 'strength lies.'),\n ('Faith consists in believing when it is beyond the power of '\n 'reason to believe.'),\n ('Faith has to do with things that are not seen and hope with '\n 'things that are not at hand.')]\n\n for idx, message in enumerate(phrases):\n Message.create(content=message, status=1 + (idx % 2))\n\n def assertMatches(query, indexes):\n results = [message.content for message in query]\n self.assertEqual(results, [phrases[i] for i in indexes])\n\n def assertSearch(search, indexes):\n assertMatches(\n Message.query(Message.content.match(search)),\n indexes)\n\n assertSearch('faith', [1, 4, 3, 2, 0])\n assertSearch('faith man', [0])\n assertSearch('things', [2, 4])\n assertSearch('blah', [])\n\n query = Message.query(\n Message.content.match('faith') & (Message.status == 1))\n assertMatches(query, [4, 2, 0])\n\n def test_full_text_combined(self):\n phrases = [\n 'little bunny foo foo', # 0, s=1\n 'a little green owl', # 1, s=2\n 'the owl was named foo', # 2, s=1\n 'he had a nicotine patch on his wing', # 3, s=2\n 'he was trying to quit smoking', # 4, s=1\n 'the owl was little and green and sweet', # 5, s=2\n 'he dropped presents on my porch', # 6, s=1\n ]\n index_to_phrase = {}\n for idx, message in enumerate(phrases):\n msg = Message.create(content=message, status=1 + (idx % 2))\n index_to_phrase[idx] = message\n\n def assertSearch(search, indexes):\n self.assertEqual(\n sorted(message.content for message in query),\n sorted(index_to_phrase[idx] for idx in indexes))\n\n query = Message.query(Message.content.match('little owl'))\n assertSearch(query, [1, 5, 2]) # \"little\" is ignored (stop word).\n\n query = Message.query(\n Message.content.match('little owl') &\n Message.content.match('foo'))\n assertSearch(query, [2])\n\n query = Message.query(\n (Message.content.match('owl') & (Message.status == 1)) |\n (Message.content.match('foo') & (Message.status == 2)))\n assertSearch(query, [2])\n\n query = Message.query(\n (Message.content.match('green') & (Message.status == 2)) |\n (Message.status == 1))\n assertSearch(query, [0, 2, 4, 6, 1, 5])\n\n query = Message.query(\n ((Message.status == 2) & Message.content.match('green')) |\n (Message.status == 1))\n assertSearch(query, [0, 2, 4, 6, 1, 5])\n\n def test_full_text_options(self):\n phrases = [\n 'building web applications with python and flask',\n 'modern web development with python',\n 'unit testing with python',\n 'writing better tests for your application',\n 'applications for the web',\n ]\n\n for phrase in phrases:\n FTSOptions.create(content=phrase, metaphone=phrase)\n\n def assertMatches(search, indexes, use_metaphone=False):\n if use_metaphone:\n field = FTSOptions.metaphone\n else:\n field = FTSOptions.content\n query = FTSOptions.query(field.match(search))\n results = [message.content for message in query]\n self.assertEqual(results, [phrases[i] for i in indexes])\n\n assertMatches('web application', [0, 4])\n assertMatches('web application', [0, 4], True)\n\n assertMatches('python', [0, 1, 2])\n assertMatches('python', [0, 1, 2], True)\n\n assertMatches('testing', [3, 2])\n assertMatches('testing', [3, 2], True)\n\n # Test behavior of the metaphone algorithm.\n assertMatches('python flasck', [0], True)\n assertMatches('pithon devellepment', [], False)\n assertMatches('pithon devellepment', [1], True)\n assertMatches('younit tessts', [2], True)\n\n def test_fts_query_parser(self):\n messages = [\n 'foo green',\n 'bar green',\n 'baz blue',\n 'nug blue',\n 'nize yellow',\n 'huey greener',\n 'mickey greens',\n 'zaizee',\n ]\n for message in messages:\n Message.create(content=message)\n\n def assertMatches(query, expected, default_conjunction=OP_AND):\n expression = Message.content.search(query, default_conjunction)\n messages = Message.query(expression, order_by=Message.content)\n results = [msg.content for msg in messages]\n self.assertEqual(results, expected)\n\n assertMatches('foo', ['foo green'])\n assertMatches('foo OR baz', ['baz blue', 'foo green'])\n assertMatches('green OR blue', [\n 'bar green',\n 'baz blue',\n 'foo green',\n 'mickey greens',\n 'nug blue',\n ])\n assertMatches('green AND (bar OR mickey OR nize)', [\n 'bar green',\n 'mickey greens',\n ])\n assertMatches('zaizee OR (blue AND nug) OR (green AND bar)', [\n 'bar green',\n 'nug blue',\n 'zaizee',\n ])\n assertMatches('(blue AND (baz OR (nug OR huey OR mickey))', [\n 'baz blue',\n 'nug blue',\n ])\n assertMatches(\n '(blue OR foo) AND (green OR (huey OR (baz AND mickey)))',\n ['foo green'])\n\n assertMatches('(green AND nug) OR (blue AND bar)', [])\n assertMatches('nuglet', [])\n assertMatches('foobar', [])\n assertMatches('', sorted(messages))\n\n def test_load(self):\n User.create(username='charlie')\n u = User.load('charlie')\n self.assertEqual(u._data, {'username': 'charlie'})\n\n def test_save_delete(self):\n charlie = User.create(username='charlie')\n huey = User.create(username='huey')\n note = Note.create(user='huey', text='n1')\n note.text = 'n1-edited'\n note.save()\n\n self.assertEqual(\n sorted(user.username for user in User.all()),\n ['charlie', 'huey'])\n\n notes = Note.all()\n self.assertEqual([note.text for note in notes], ['n1-edited'])\n\n charlie.delete()\n self.assertEqual([user.username for user in User.all()], ['huey'])\n\n def test_delete_indexes(self):\n self.assertEqual(set(db.keys()), set())\n\n Message.create(content='charlie message', status=1)\n Message.create(content='huey message', status=2)\n keys = set(db.keys())\n\n charlie = Message.load(1)\n charlie.delete()\n huey_keys = set(db.keys())\n\n diff = keys - huey_keys\n\n def make_key(*args):\n return Message._query.make_key(*args).encode('utf-8')\n\n self.assertEqual(diff, set([\n make_key('_id', 'absolute', 1),\n make_key('content', 'absolute', 'charlie message'),\n make_key('content', 'fts', 'charli'),\n make_key('id', 1),\n make_key('status', 'absolute', 1),\n ]))\n\n # Ensure we cannot query for Charlie, but that we can query for Huey.\n expressions = [\n (Message.status == 1),\n (Message.status != 2),\n (Message._id == 1),\n (Message._id != 2),\n (Message.content == 'charlie message'),\n (Message.content != 'huey message'),\n (Message.content.match('charlie')),\n ]\n for expression in expressions:\n self.assertRaises(ValueError, Message.get, expression)\n\n expressions = [\n (Message.status == 2),\n (Message.status > 1),\n (Message._id == 2),\n (Message._id != 1),\n (Message.content == 'huey message'),\n (Message.content != 'charlie'),\n (Message.content.match('huey')),\n (Message.content.match('message')),\n ]\n for expression in expressions:\n obj = Message.get(expression)\n self.assertEqual(obj._data, {\n '_id': 2,\n 'content': 'huey message',\n 'status': 2,\n })\n\n after_filter_keys = set(db.keys())\n symm_diff = huey_keys ^ after_filter_keys\n self.assertTrue(all(key.startswith(b'temp') for key in symm_diff))\n\n huey = Message.load(2)\n huey.delete()\n\n final_keys = set(key for key in db.keys()\n if not key.startswith(b'temp'))\n self.assertEqual(final_keys, set([make_key('_id', '_sequence')]))\n\n def test_get_regression(self):\n Message.create(content='huey', status=1)\n Message.create(content='charlie', status=2)\n\n def assertMessage(msg, data):\n self.assertEqual(msg._data, data)\n\n huey = {'_id': 1, 'content': 'huey', 'status': 1}\n charlie = {'_id': 2, 'content': 'charlie', 'status': 2}\n assertMessage(Message.load(1), huey)\n assertMessage(Message.load(2), charlie)\n\n for i in range(3):\n assertMessage(Message.get(Message._id == 1), huey)\n assertMessage(Message.get(Message._id == 2), charlie)\n\n assertMessage(Message.get(Message.status == 1), huey)\n assertMessage(Message.get(Message.status == 2), charlie)\n assertMessage(Message.get(Message.status != 1), charlie)\n assertMessage(Message.get(Message.status != 2), huey)\n\n messages = list(Message.query(Message.status == 1))\n self.assertEqual(len(messages), 1)\n assertMessage(messages[0], huey)\n messages = list(Message.query(Message.status != 1))\n self.assertEqual(len(messages), 1)\n assertMessage(messages[0], charlie)\n\n def test_index_separator(self):\n class CustomSeparator(BaseModel):\n index_separator = '$'\n name = TextField(primary_key=True)\n data = IntegerField(index=True)\n\n CustomSeparator.create(name='huey.zai', data=3)\n CustomSeparator.create(name='michael.nuggie', data=5)\n\n keys = sorted(db.keys())\n self.assertEqual(keys, [\n # namespace | model : $-delimited indexed data\n b'test|customseparator:all',\n b'test|customseparator:data$absolute$3',\n b'test|customseparator:data$absolute$5',\n b'test|customseparator:data$continuous',\n b'test|customseparator:id$huey.zai',\n b'test|customseparator:id$michael.nuggie',\n b'test|customseparator:name$absolute$huey.zai',\n b'test|customseparator:name$absolute$michael.nuggie'])\n\n huey = CustomSeparator.get(CustomSeparator.data < 5)\n self.assertEqual(huey.name, 'huey.zai')\n\n mickey = CustomSeparator.load('michael.nuggie')\n self.assertEqual(mickey.data, 5)\n\n def test_incr(self):\n for i in range(3):\n Stat.create(stat_type='test', value=i)\n\n s1 = Stat.get(Stat.value == 1)\n res = s1.incr(Stat.value, 5)\n self.assertEqual(res, 6)\n self.assertEqual(s1.value, 6)\n\n self.assertRaises(ValueError, Stat.get, Stat.value == 1)\n s6 = Stat.get(Stat.value == 6)\n self.assertEqual(s1.key, s6.key)\n\n def test_count(self):\n self.assertEqual(User.count(), 0)\n\n for username in ['charlie', 'leslie', 'connor']:\n User.create(username=username)\n\n self.assertEqual(User.count(), 3)\n\n def test_query_delete(self):\n for i in range(5):\n u = User.create(username='u%s' % (i + 1))\n\n User.query_delete((User.username == 'u1') | (User.username == 'u4'))\n usernames = [user.username for user in User.all()]\n self.assertEqual(sorted(usernames), ['u2', 'u3', 'u5'])\n\n User.query_delete()\n self.assertEqual([user for user in User.all()], [])\n\n def test_container_field_persistence(self):\n class HashModel(BaseModel):\n data = HashField()\n name = TextField()\n\n hm1 = HashModel.create(name='hm1')\n hm1.data.update(k1='v1', k2='v2')\n\n hm2 = HashModel.create(name='hm2')\n hm2.data.update(k3='v3', k4='v4')\n\n hm1.name = 'hm1-e'\n hm1.save()\n\n hm1_db = HashModel.load(hm1._id)\n self.assertEqual(hm1_db.name, 'hm1-e')\n self.assertEqual(hm1.data.as_dict(), {b'k1': b'v1', b'k2': b'v2'})\n\n def test_delete_container_fields(self):\n class HashModel(BaseModel):\n data = HashField()\n name = TextField()\n\n hm1 = HashModel.create(name='hm1')\n hm1.data.update(k1='v1', k2='v2')\n\n hm2 = HashModel.create(name='hm2')\n hm2.data.update(k3='v3', k4='v4')\n\n hm1.delete()\n self.assertEqual(hm1.data.as_dict(), {})\n self.assertEqual(hm2.data.as_dict(), {b'k3': b'v3', b'k4': b'v4'})\n\n def test_default_is_an_empty_dict(self):\n instance = DefaultOption()\n self.assertTrue(instance.default_empty is None)\n self.assertEqual(instance.num, 0)\n self.assertEqual(instance.txt, '')\n\n def test_json_storage(self):\n class APIResponse(BaseModel):\n data = JSONField()\n\n ar = APIResponse(data={'k1': 'v1', 'k2': 'v2'})\n ar.save()\n\n ar_db = APIResponse.load(ar._id)\n self.assertEqual(ar_db.data, {'k1': 'v1', 'k2': 'v2'})\n\n def test_pickled_storage(self):\n class PythonData(BaseModel):\n data = PickledField()\n\n pd = PythonData(data={'k1': ['v1', None, 'v3']})\n pd.save()\n\n pd_db = PythonData.load(pd._id)\n self.assertEqual(pd_db.data, {'k1': ['v1', None, 'v3']})\n\n pd2 = PythonData.create(data=None)\n pd2_db = PythonData.load(pd2._id)\n self.assertTrue(pd2_db.data is None)\n\n def test_boolean_field(self):\n class Account(BaseModel):\n name = TextField(primary_key=True)\n active = BooleanField()\n admin = BooleanField(default=False)\n\n charlie = Account(name='charlie', active=True, admin=True)\n huey = Account(name='huey', active=False)\n charlie.save()\n huey.save()\n\n charlie_db = Account.get(Account.name == 'charlie')\n self.assertTrue(charlie_db.active)\n self.assertTrue(charlie_db.admin)\n\n huey_db = Account.get(Account.name == 'huey')\n self.assertFalse(huey_db.active)\n self.assertFalse(huey_db.admin)\n\n huey_db.active = True\n huey_db.admin = True\n huey_db.save()\n\n huey_db2 = Account.get(Account.name == 'huey')\n self.assertTrue(huey_db2.active)\n self.assertTrue(huey_db2.admin)\n\n def test_query_boolean(self):\n class BT(BaseModel):\n key = TextField(primary_key=True)\n flag = BooleanField(default=False, index=True)\n\n for i in range(4):\n BT.create(key='k%s' % i, flag=True if i % 2 else False)\n\n query = BT.query(BT.flag == True)\n self.assertEqual(sorted([bt.key for bt in query]), ['k1', 'k3'])\n query = BT.query(BT.flag == False)\n self.assertEqual(sorted([bt.key for bt in query]), ['k0', 'k2'])\n\n def test_uuid(self):\n class Beacon(BaseModel):\n name = TextField(primary_key=True)\n data = UUIDField()\n\n b1 = Beacon.create(name='alpha', data=uuid.uuid4())\n b2 = Beacon.create(name='bravo', data=uuid.uuid4())\n b3 = Beacon.create(name='charlie')\n b3_db = Beacon.load('charlie')\n b2_db = Beacon.load('bravo')\n b1_db = Beacon.load('alpha')\n self.assertEqual(b1.data, b1_db.data)\n self.assertEqual(b2.data, b2_db.data)\n self.assertTrue(b3.data is None)\n\n def _test_date_field(self, field_class, dt_func):\n class Event(BaseModel):\n timestamp = field_class(index=True)\n value = TextField()\n\n events = [\n Event.create(timestamp=dt_func(i), value='e%s' % i)\n for i in range(1, 11)]\n\n e_db = Event.get(Event._id == events[-1]._id)\n self.assertEqual(e_db.timestamp, dt_func(10))\n self.assertEqual(e_db.value, 'e10')\n\n events = Event.query(\n (Event.timestamp >= dt_func(3)) &\n (Event.timestamp < dt_func(7)), Event.timestamp)\n ts2value = [(e.timestamp, e.value) for e in events]\n self.assertEqual(ts2value, [\n (dt_func(3), 'e3'),\n (dt_func(4), 'e4'),\n (dt_func(5), 'e5'),\n (dt_func(6), 'e6')])\n\n e = Event.create(value='ex')\n e_db = Event.load(e._id)\n self.assertTrue(e_db.timestamp is None)\n self.assertEqual(e_db.value, 'ex')\n\n def test_datetime_field(self):\n dt = lambda day: datetime.datetime(2018, 1, day, 3, 13, 37)\n self._test_date_field(DateTimeField, dt)\n\n def test_date_field(self):\n dt = lambda day: datetime.date(2018, 1, day)\n self._test_date_field(DateField, dt)\n\n\nif __name__ == '__main__':\n import unittest; unittest.main()\n" }, { "alpha_fraction": 0.553554356098175, "alphanum_fraction": 0.5661460161209106, "avg_line_length": 29.906404495239258, "blob_id": "582f36c1f7bf779bc2e1a10dfae4c023807d41db", "content_id": "0e4d9e5d0d283e9d813ba821274c564fb137a6e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6274, "license_type": "permissive", "max_line_length": 73, "num_lines": 203, "path": "/walrus/tusks/vedisdb.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import sys\nimport unittest\n\nfrom vedis import Vedis\n\nfrom walrus import *\n\n\nclass VedisList(List):\n def extend(self, value):\n return self.database.lmpush(self.key, value)\n\n def pop(self):\n return self.database.lpop(self.key)\n\n\nclass WalrusVedis(Vedis, Database):\n def __init__(self, filename=':mem:'):\n self._filename = filename\n Vedis.__init__(self, filename)\n\n def __repr__(self):\n if self._filename in (':memory:', ':mem:'):\n db_file = 'in-memory database'\n else:\n db_file = self._filename\n return '<WalrusVedis: %s>' % db_file\n\n def execute_command(self, *args, **options):\n raise ValueError('\"%s\" is not supported by Vedis.' % args[0])\n\n def parse_response(self, *args, **kwargs):\n raise RuntimeError('Error, parse_response should not be called.')\n\n def command(self, command_name):\n return self.register(command_name)\n\n # Compatibility with method names from redis-py.\n def getset(self, key, value):\n return self.get_set(key, value)\n\n def incrby(self, name, amount=1):\n return self.incr_by(name, amount)\n\n def decrby(self, name, amount=1):\n return self.decr_by(name, amount)\n\n # Compatibility with method signatures.\n def mset(self, **data):\n return super(WalrusVedis, self).mset(data)\n\n def mget(self, *keys):\n return super(WalrusVedis, self).mget(list(keys))\n\n def __getitem__(self, key):\n try:\n return super(WalrusVedis, self).__getitem__(key)\n except KeyError:\n pass\n\n def sadd(self, key, *items):\n return super(WalrusVedis, self).smadd(key, list(items))\n\n # Override the container types since Vedis provides its own using the\n # same method-names as Walrus, and we want the Walrus containers.\n def Hash(self, key):\n return Hash(self, key)\n\n def Set(self, key):\n return Set(self, key)\n\n def List(self, key):\n return VedisList(self, key)\n\n def not_supported(name):\n def decorator(self, *args, **kwargs):\n raise ValueError('%s is not supported by Vedis.' % name)\n return decorator\n\n ZSet = not_supported('ZSet')\n Array = not_supported('Array')\n HyperLogLog = not_supported('HyperLogLog')\n pipeline = not_supported('pipeline')\n lock = not_supported('lock')\n pubsub = not_supported('pubsub')\n\n\nclass TestWalrusVedis(unittest.TestCase):\n def setUp(self):\n self.db = WalrusVedis()\n\n def test_basic(self):\n self.db['foo'] = 'bar'\n self.assertEqual(self.db['foo'], b'bar')\n self.assertTrue('foo' in self.db)\n self.assertFalse('xx' in self.db)\n self.assertIsNone(self.db['xx'])\n\n self.db.mset(k1='v1', k2='v2', k3='v3')\n results = self.db.mget('k1', 'k2', 'k3', 'kx')\n self.assertEqual(list(results), [b'v1', b'v2', b'v3', None])\n\n self.db.append('foo', 'baz')\n self.assertEqual(self.db.get('foo'), b'barbaz')\n\n self.db.incr_by('counter', 1)\n self.assertEqual(self.db.incr_by('counter', 5), 6)\n self.assertEqual(self.db.decr_by('counter', 2), 4)\n\n self.assertEqual(self.db.strlen('foo'), 6)\n self.assertEqual(self.db.getset('foo', 'nug'), b'barbaz')\n self.assertEqual(self.db['foo'], b'nug')\n\n self.assertFalse(self.db.setnx('foo', 'xxx'))\n self.assertTrue(self.db.setnx('bar', 'yyy'))\n self.assertEqual(self.db['bar'], b'yyy')\n\n del self.db['foo']\n self.assertFalse('foo' in self.db)\n\n def test_hash(self):\n h = self.db.Hash('hash_obj')\n h['k1'] = 'v1'\n h.update({'k2': 'v2', 'k3': 'v3'})\n self.assertEqual(h.as_dict(), {\n b'k1': b'v1',\n b'k2': b'v2',\n b'k3': b'v3'})\n\n self.assertEqual(h['k2'], b'v2')\n self.assertIsNone(h['kx'])\n self.assertTrue('k2' in h)\n self.assertEqual(len(h), 3)\n\n del h['k2']\n del h['kxx']\n self.assertEqual(sorted(h.keys()), [b'k1', b'k3'])\n self.assertEqual(sorted(h.values()), [b'v1', b'v3'])\n\n def test_list(self):\n l = self.db.List('list_obj')\n l.prepend('charlie')\n l.extend(['mickey', 'huey', 'zaizee'])\n self.assertEqual(l[0], b'charlie')\n self.assertEqual(l[-1], b'zaizee')\n self.assertEqual(len(l), 4)\n self.assertEqual(l.pop(), b'charlie')\n\n def test_set(self):\n s = self.db.Set('set_obj')\n s.add('charlie')\n s.add('charlie', 'huey', 'mickey')\n self.assertEqual(len(s), 3)\n self.assertTrue('huey' in s)\n self.assertFalse('xx' in s)\n del s['huey']\n self.assertFalse('huey' in s)\n self.assertEqual(s.members(), set([b'charlie', b'mickey']))\n\n s1 = self.db.Set('s1')\n s2 = self.db.Set('s2')\n s1.add(*map(str, range(5)))\n s2.add(*map(str, range(3, 7)))\n self.assertEqual(s1 - s2, set([b'0', b'1', b'2']))\n self.assertEqual(s2 - s1, set([b'5', b'6']))\n self.assertEqual(s1 & s2, set([b'3', b'4']))\n\n def test_unsupported(self):\n def assertUnsupported(cmd, *args):\n method = getattr(self.db, cmd)\n self.assertRaises(ValueError, method, *args)\n\n # Just check a handful of methods.\n assertUnsupported('zadd', 'zs', {'foo': 1})\n assertUnsupported('ZSet', 'zs')\n assertUnsupported('rpush', 'l_obj', 'val')\n assertUnsupported('rpop', 'l_obj')\n assertUnsupported('ltrim', 'l_obj', 0, 1)\n assertUnsupported('lrem', 'l_obj', 3, 1)\n\n def test_custom_commands(self):\n @self.db.command('KTITLE')\n def _ktitle_impl(context, key):\n value = context[key]\n if value:\n context[key] = value.title()\n return True\n return False\n\n self.db['n1'] = 'charlie'\n self.db['n2'] = 'huey'\n self.assertTrue(_ktitle_impl('n1'))\n self.assertEqual(self.db['n1'], b'Charlie')\n\n self.assertTrue(self.db.execute('KTITLE n2'))\n self.assertEqual(self.db['n2'], b'Huey')\n\n self.assertFalse(self.db.execute('KTITLE nx'))\n self.assertIsNone(self.db['nx'])\n\n\nif __name__ == '__main__':\n unittest.main(argv=sys.argv)\n" }, { "alpha_fraction": 0.6710383892059326, "alphanum_fraction": 0.6747236251831055, "avg_line_length": 33.68421173095703, "blob_id": "7acfeb9c24d5ffaf5e29f9fa01f7a10e8785fb07", "content_id": "80d50450524d4b93b6689068388bb57560e0e043", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9226, "license_type": "permissive", "max_line_length": 79, "num_lines": 266, "path": "/examples/twitter/app.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import datetime\nimport operator\n\nfrom flask import abort\nfrom flask import flash\nfrom flask import Flask\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import session\nfrom flask import url_for\nfrom functools import wraps\nfrom hashlib import md5\nfrom walrus import *\n\n# Configure our app's settings.\nDEBUG = True\nSECRET_KEY = 'hin6bab8ge25*r=x&amp;+5$0kn=-#log$pt^#@vrqjld!^2ci@g*b'\n\n# Create a flask application - this `app` object will be used to handle\n# inbound requests, routing them to the proper 'view' functions, etc.\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n# Create a walrus database instance - our models will use this database to\n# persist information.\ndatabase = Database()\n\n# Model definitions - the standard \"pattern\" is to define a base model class\n# that specifies which database to use. Then, any subclasses will automatically\n# use the correct storage.\nclass BaseModel(Model):\n __database__ = database\n __namespace__ = 'twitter'\n\n# Model classes specify fields declaratively, like django.\nclass User(BaseModel):\n username = TextField(primary_key=True)\n password = TextField(index=True)\n email = TextField()\n\n followers = ZSetField()\n following = ZSetField()\n\n def get_followers(self):\n # Because all users are added to the `followers` sorted-set with the\n # same score, when retrieved they will be sorted by key (username).\n return [User.load(username) for username in self.followers]\n\n def get_following(self):\n # Because all users are added to the `following` sorted-set with the\n # same score, when retrieved they will be sorted by key (username).\n return [User.load(username) for username in self.following]\n\n def is_following(self, user):\n # We can use Pythonic operators when working with Walrus containers.\n return user.username in self.following\n\n def gravatar_url(self, size=80):\n return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \\\n (md5(self.email.strip().lower().encode('utf-8')).hexdigest(), size)\n\n\n# Simple model with a one-to-many relationship: one user has 0..n messages.\n# A user is associated with a message via the `username` field.\nclass Message(BaseModel):\n username = TextField(index=True)\n content = TextField()\n timestamp = DateTimeField(default=datetime.datetime.now)\n\n def get_user(self):\n return User.load(self.username)\n\n\n# Flask provides a `session` object, which allows us to store information\n# across requests (stored by default in a secure cookie). This function allows\n# us to mark a user as being logged-in by setting some values in the session:\ndef auth_user(user):\n session['logged_in'] = True\n session['username'] = user.username\n flash('You are logged in as %s' % (user.username))\n\n# Get the currently logged-in user, or return `None`.\ndef get_current_user():\n if session.get('logged_in'):\n try:\n return User.load(session['username'])\n except KeyError:\n session.pop('logged_in')\n\n# View decorator which indicates that the requesting user must be authenticated\n# before they can access the wrapped view. The decorator checks the session to\n# see if they're logged in, and if not redirects them to the login view.\ndef login_required(f):\n @wraps(f)\n def inner(*args, **kwargs):\n if not session.get('logged_in'):\n return redirect(url_for('login'))\n return f(*args, **kwargs)\n return inner\n\n# Retrieve an object by primary key. If the object does not exist, return a\n# 404 not found.\ndef get_object_or_404(model, pk):\n try:\n return model.load(pk)\n except ValueError:\n abort(404)\n\n# Custom template filter: Flask allows you to define these functions and then\n# they are accessible in the template. This one returns a boolean whether the\n# given user is following another user.\[email protected]_filter('is_following')\ndef is_following(from_user, to_user):\n return from_user.is_following(to_user)\n\n# Views: these are the actual mappings of url to view function.\[email protected]('/')\ndef homepage():\n # Depending on whether the requesting user is logged in or not, show them\n # either the public timeline or their own private timeline.\n if session.get('logged_in'):\n return private_timeline()\n else:\n return public_timeline()\n\[email protected]('/private/')\ndef private_timeline():\n # The private timeline is a bit interesting as it shows how to create a\n # query dynamically. We are taking all the users the current user follows\n # and basically performing a big set union on message objects. Matching\n # messages are then sorted newest to oldest.\n user = get_current_user()\n if user.following:\n query = reduce(operator.or_, [\n Message.username == username\n for username, _ in user.following\n ])\n messages = Message.query(query, order_by=Message.timestamp.desc())\n else:\n messages = []\n return render_template('private_messages.html', message_list=messages)\n\[email protected]('/public/')\ndef public_timeline():\n # Display all messages, newest to oldest.\n messages = Message.query(order_by=Message.timestamp.desc())\n return render_template('public_messages.html', message_list=messages)\n\[email protected]('/join/', methods=['GET', 'POST'])\ndef join():\n if request.method == 'POST' and request.form['username']:\n username = request.form['username']\n try:\n User.load(username)\n except KeyError:\n user = User.create(\n username=username,\n password=md5(request.form['password']).hexdigest(),\n email=request.form['email'])\n auth_user(user)\n return redirect(url_for('homepage'))\n else:\n flash('That username is already taken')\n\n return render_template('join.html')\n\[email protected]('/login/', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST' and request.form['username']:\n try:\n user = User.get(\n (User.username == request.form['username']) &\n (User.password == md5(request.form['password']).hexdigest()))\n except ValueError:\n flash('The password entered is incorrect')\n else:\n auth_user(user)\n return redirect(url_for('homepage'))\n\n return render_template('login.html')\n\[email protected]('/logout/')\ndef logout():\n session.pop('logged_in', None)\n flash('You were logged out')\n return redirect(url_for('homepage'))\n\[email protected]('/following/')\n@login_required\ndef following():\n # Get the list of user objects the current user is following.\n user = get_current_user()\n return render_template('user_following', user_list=user.get_following())\n\[email protected]('/followers/')\n@login_required\ndef followers():\n # Get the list of user objects the current user is followed by.\n user = get_current_user()\n return render_template('user_following', user_list=user.get_followers())\n\[email protected]('/users/')\ndef user_list():\n # Display all users ordered by their username.\n users = User.query(order_by=User.username)\n return render_template('user_list.html', user_list=users)\n\[email protected]('/users/<username>/')\ndef user_detail(username):\n # Using the \"get_object_or_404\" shortcut here to get a user with a valid\n # username or short-circuit and display a 404 if no user exists in the db.\n user = get_object_or_404(User, username)\n\n # Get all the users messages ordered newest-first.\n messages = Message.query(\n Message.username == user.username,\n order_by=Message.timestamp.desc())\n return render_template(\n 'user_detail.html',\n message_list=messages,\n user=user)\n\[email protected]('/users/<username>/follow/', methods=['POST'])\n@login_required\ndef user_follow(username):\n current_user = get_current_user()\n user = get_object_or_404(User, username)\n current_user.following.add(user.username, 0)\n user.followers.add(current_user.username, 0)\n\n flash('You are following %s' % user.username)\n return redirect(url_for('user_detail', username=user.username))\n\[email protected]('/users/<username>/unfollow/', methods=['POST'])\n@login_required\ndef user_unfollow(username):\n current_user = get_current_user()\n user = get_object_or_404(User, username)\n current_user.following.remove(user.username)\n user.followers.remove(current_user.username)\n\n flash('You are no longer following %s' % user.username)\n return redirect(url_for('user_detail', username=user.username))\n\[email protected]('/create/', methods=['GET', 'POST'])\n@login_required\ndef create():\n # Create a new message.\n user = get_current_user()\n if request.method == 'POST' and request.form['content']:\n message = Message.create(\n username=user.username,\n content=request.form['content'])\n flash('Your message has been created')\n return redirect(url_for('user_detail', username=user.username))\n\n return render_template('create.html')\n\[email protected]_processor\ndef _inject_user():\n return {'current_user': get_current_user()}\n\n# allow running from the command line\nif __name__ == '__main__':\n app.run()\n" }, { "alpha_fraction": 0.5124133825302124, "alphanum_fraction": 0.5619407892227173, "avg_line_length": 25.807432174682617, "blob_id": "f3ceb2d6e1b8e36c541b5d0e48549362e9bd476b", "content_id": "813b027330623ac8c41d094fa3fa2f8e0fdef465", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 7935, "license_type": "permissive", "max_line_length": 372, "num_lines": 296, "path": "/docs/containers.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _containers:\n\n.. py:module:: walrus\n\nContainers\n==========\n\nAt the most basic level, Redis acts like an in-memory Python dictionary:\n\n.. code-block:: pycon\n\n >>> db['walrus'] = 'tusk'\n >>> print(db['walrus'])\n tusk\n\n >>> db['not-here']\n Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/home/charles/pypath/redis/client.py\", line 817, in __getitem__\n raise KeyError(name)\n KeyError: 'not-here'\n\n >>> db.get('not-here') is None\n True\n\nRedis also supports several primitive data-types:\n\n* :py:class:`Hash`: dictionary\n* :py:class:`List`: linked list\n* :py:class:`Set`\n* :py:class:`ZSet`: a sorted set\n* :py:class:`HyperLogLog`: probabilistic data-structure for cardinality estimation.\n* :py:class:`Array`: like a Python list (custom data type implemented on top of ``Hash`` using lua scripts).\n* :py:class:`BitField`: a bitmap that supports random access.\n* :py:class:`BloomFilter`: probabilistic data-structure for testing set membership.\n* For stream types (:py:class:`Stream`: and :py:class:`ConsumerGroup`) see\n the :ref:`streams` documentation.\n\nLet's see how to use these types.\n\nHashes\n------\n\nThe :py:class:`Hash` acts like a Python ``dict``.\n\n.. code-block:: pycon\n\n >>> h = db.Hash('charlie')\n >>> h.update(name='Charlie', favorite_cat='Huey')\n <Hash \"charlie\": {'name': 'Charlie', 'favorite_cat': 'Huey'}>\n\nWe can use common Python interfaces like iteration, len, contains, etc.\n\n.. code-block:: pycon\n\n >>> print(h['name'])\n Charlie\n\n >>> for key, value in h:\n ... print(key, '=>', value)\n name => Charlie\n favorite_cat => Huey\n\n >>> del h['favorite_cat']\n >>> h['age'] = 31\n >>> print(h)\n <Hash \"charlie\": {'age': '31', 'name': 'Charlie'}>\n\n >>> 'name' in h\n True\n >>> len(h)\n 2\n\nLists\n-----\n\nThe :py:class:`List` acts like a Python ``list``.\n\n.. code-block:: pycon\n\n >>> l = db.List('names')\n >>> l.extend(['charlie', 'huey', 'mickey', 'zaizee'])\n 4L\n >>> print(l[:2])\n ['charlie', 'huey']\n >>> print(l[-2:])\n ['mickey', 'zaizee']\n >>> l.pop()\n 'zaizee'\n >>> l.prepend('scout')\n 4L\n >>> len(l)\n 4\n\nSets\n----\n\nThe :py:class:`Set` acts like a Python ``set``.\n\n.. code-block:: python\n\n >>> s1 = db.Set('s1')\n >>> s2 = db.Set('s2')\n >>> s1.add(*range(5))\n 5\n >>> s2.add(*range(3, 8))\n 5\n\n >>> s1 | s2\n {'0', '1', '2', '3', '4', '5', '6', '7'}\n >>> s1 & s2\n {'3', '4'}\n >>> s1 - s2\n {'0', '1', '2'}\n\n >>> s1 -= s2\n >>> s1.members()\n {'0', '1', '2'}\n\n >>> len(s1)\n 3\n\nSorted Sets (ZSet)\n------------------\n\nThe :py:class:`ZSet` acts a bit like a sorted dictionary, where the values are the scores used for sorting the keys.\n\n.. code-block:: pycon\n\n >>> z1 = db.ZSet('z1')\n >>> z1.add({'charlie': 31, 'huey': 3, 'mickey': 6, 'zaizee': 2.5})\n 4\n >>> z1['huey'] = 3.5\n\nSorted sets provide a number of complex slicing and indexing options when retrieving values. You can slice by key or rank, and optionally include scores in the return value.\n\n.. code-block:: pycon\n\n >>> z1[:'mickey'] # Who is younger than Mickey?\n ['zaizee', 'huey']\n\n >>> z1[-2:] # Who are the two oldest people?\n ['mickey', 'charlie']\n\n >>> z1[-2:, True] # Who are the two oldest, and what are their ages?\n [('mickey', 6.0), ('charlie', 31.0)]\n\nThere are quite a few methods for working with sorted sets, so if you're curious then check out the :py:class:`ZSet` API documentation.\n\nHyperLogLog\n-----------\n\nThe :py:class:`HyperLogLog` provides an estimation of the number of distinct elements in a collection.\n\n.. code-block:: python\n\n >>> hl = db.HyperLogLog('hl')\n >>> hl.add(*range(100))\n >>> len(hl)\n 100\n >>> hl.add(*range(1, 100, 2))\n >>> hl.add(*range(1, 100, 3))\n >>> len(hl)\n 102\n\nArrays\n------\n\nThe :py:class:`Array` type is implemented using `lua scripts <https://github.com/andymccurdy/redis-py#lua-scripting>`_. Unlike :py:class:`List` which is implemented as a linked-list, the ``Array`` is built on top of a Redis hash and has better run-times for certain operations (indexing, for instance). Like :py:class:`List`, :py:class:`Array` acts like a Python ``list``.\n\n.. code-block:: pycon\n\n >>> a = db.Array('arr')\n >>> a.extend(['foo', 'bar', 'baz', 'nugget'])\n >>> a[-1] = 'nize'\n >>> list(a)\n ['foo', 'bar', 'baz', 'nize']\n >>> a.pop(2)\n 'baz'\n\nBitField\n--------\n\nThe :py:class:`BitField` type acts as a bitmap that supports random access\nread, write and increment operations. Operations use a format string (e.g. \"u8\"\nfor unsigned 8bit integer 0-255, \"i4\" for signed integer -8-7).\n\n.. code-block:: pycon\n\n >>> bf = db.bit_field('bf')\n >>> resp = (bf\n ... .set('u8', 8, 255)\n ... .get('u8', 0) # 00000000\n ... .get('u4', 8) # 1111\n ... .get('u4', 12) # 1111\n ... .get('u4', 13) # 111? -> 1110\n ... .execute())\n ...\n [0, 0, 15, 15, 14]\n\n >>> resp = (bf\n ... .set('u8', 4, 1) # 00ff -> 001f (returns old val, 0x0f).\n ... .get('u16', 0) # 001f (00011111)\n ... .set('u16', 0, 0)) # 001f -> 0000\n ...\n >>> for item in resp: # bitfield responses are iterable!\n ... print(item)\n ...\n 15\n 31\n 31\n\n >>> resp = (bf\n ... .incrby('u8', 8, 254) # 0000 0000 1111 1110\n ... .get('u16', 0)\n ... .incrby('u8', 8, 2, 'FAIL') # increment 254 -> 256? overflow!\n ... .incrby('u8', 8, 1) # increment 254 -> 255. success!\n ... .incrby('u8', 8, 1) # 255->256? overflow, will fail.\n ... .get('u16', 0))\n ...\n >>> resp.execute()\n [254, 254, None, 255, None, 255]\n\n:py:class:`BitField` also supports slice notation, using bit-offsets. The\nreturn values are always unsigned integers:\n\n.. code-block:: pycon\n\n >>> bf.set('u8', 0, 166).execute() # 10100110\n 166\n\n >>> bf[:8] # Read first 8 bits as unsigned byte.\n 166\n\n >>> bf[:4] # 1010\n 10\n >>> bf[4:8] # 0110\n 6\n >>> bf[2:6] # 1001\n 9\n >>> bf[6:10] # 10?? -> 1000\n 8\n >>> bf[8:16] # ???????? -> 00000000\n 0\n\n >>> bf[:8] = 89 # 01011001\n >>> bf[:8]\n 89\n\n >>> bf[:8] = 255 # 1111 1111\n >>> bf[:4] # 1111\n 15\n >>> del bf[2:6] # 1111 1111 -> 1100 0011\n >>> bf[:8] # 1100 0011\n 195\n\nBloomFilter\n-----------\n\nA :py:class:`BloomFilter` is a probabilistic data-structure used for answering\nthe question: \"is X a member of set S?\" The bloom-filter may return a false\npositive, but it is impossible to receive a false negative (in other words, if\nthe bloom-filter contains a value, it will never erroneously report that it\ndoes *not* contain such a value). The accuracy of the bloom-filter and the\nlikelihood of a false positive can be reduced by increasing the size of the\nbloom-filter buffer. The default size is 64KB (or 524,288 bits).\n\n.. code-block:: pycon\n\n >>> bf = db.bloom_filter('bf') # Create a bloom-filter, stored in key \"bf\".\n\n >>> data = ('foo', 'bar', 'baz', 'nugget', 'this is a test', 'testing')\n >>> for item in data:\n ... bf.add(item) # Add the above items to the bloom-filter.\n ...\n\n >>> for item in data:\n ... assert item in bf # Verify that all items are present.\n ...\n\n >>> for item in data:\n ... assert item.upper() not in bf # FOO, BAR, etc, are *not* present.\n ... assert item.title() not in bf # Foo, Bar, etc, are *not* present.\n ...\n\n:py:class:`BloomFilter` implements only two methods:\n\n* :py:meth:`~BloomFilter.add` - to add an item to the bloom-filter.\n* :py:meth:`~BloomFilter.contains` - test whether an item exists in the filter.\n\n.. note::\n Items cannot be removed from a bloom-filter.\n\n.. warning::\n Once a :py:class:`BloomFilter` has been created and items have been added,\n you must not modify the size of the buffer.\n" }, { "alpha_fraction": 0.5837757587432861, "alphanum_fraction": 0.5869477987289429, "avg_line_length": 33.14937210083008, "blob_id": "8055bf71b447339ec6b02a5d7bf233c0e2a289dd", "content_id": "b49dd3cf9193175ccccd17942a8b846c68ec5ad1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59898, "license_type": "permissive", "max_line_length": 87, "num_lines": 1754, "path": "/walrus/containers.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import hashlib\nimport operator\nimport struct\ntry:\n from functools import reduce\nexcept ImportError:\n pass\nfrom functools import wraps\ntry:\n from redis.exceptions import ResponseError\nexcept ImportError:\n ResponseError = Exception\n\nfrom walrus.utils import basestring_type\nfrom walrus.utils import decode as _decode\nfrom walrus.utils import decode_dict\nfrom walrus.utils import encode\nfrom walrus.utils import exception_message\nfrom walrus.utils import make_python_attr\nfrom walrus.utils import safe_decode_list\n\n\ndef chainable_method(fn):\n @wraps(fn)\n def inner(self, *args, **kwargs):\n fn(self, *args, **kwargs)\n return self\n return inner\n\n\nclass Sortable(object):\n def sort(self, pattern=None, limit=None, offset=None, get_pattern=None,\n ordering=None, alpha=True, store=None):\n if limit or offset:\n offset = offset or 0\n return self.database.sort(\n self.key,\n start=offset,\n num=limit,\n by=pattern,\n get=get_pattern,\n desc=ordering in ('DESC', 'desc'),\n alpha=alpha,\n store=store)\n\n\nclass Container(object):\n \"\"\"\n Base-class for rich Redis object wrappers.\n \"\"\"\n def __init__(self, database, key):\n self.database = database\n self.key = key\n\n def expire(self, ttl=None):\n \"\"\"\n Expire the given key in the given number of seconds.\n If ``ttl`` is ``None``, then any expiry will be cleared\n and key will be persisted.\n \"\"\"\n if ttl is not None:\n self.database.expire(self.key, ttl)\n else:\n self.database.persist(self.key)\n\n def pexpire(self, ttl=None):\n \"\"\"\n Expire the given key in the given number of milliseconds.\n If ``ttl`` is ``None``, then any expiry will be cleared\n and key will be persisted.\n \"\"\"\n if ttl is not None:\n self.database.pexpire(self.key, ttl)\n else:\n self.database.persist(self.key)\n\n def dump(self):\n \"\"\"\n Dump the contents of the given key using Redis' native\n serialization format.\n \"\"\"\n return self.database.dump(self.key)\n\n @chainable_method\n def clear(self):\n \"\"\"\n Clear the contents of the container by deleting the key.\n \"\"\"\n self.database.delete(self.key)\n\n\nclass Hash(Container):\n \"\"\"\n Redis Hash object wrapper. Supports a dictionary-like interface\n with some modifications.\n\n See `Hash commands <http://redis.io/commands#hash>`_ for more info.\n \"\"\"\n def __repr__(self):\n l = len(self)\n if l > 5:\n # Get a few keys.\n data = self.database.hscan(self.key, count=5)\n else:\n data = self.as_dict()\n return '<Hash \"%s\": %s>' % (self.key, data)\n\n def __getitem__(self, item):\n \"\"\"\n Retrieve the value at the given key. To retrieve multiple\n values at once, you can specify multiple keys as a tuple or\n list:\n\n .. code-block:: python\n\n hsh = db.Hash('my-hash')\n first, last = hsh['first_name', 'last_name']\n \"\"\"\n if isinstance(item, (list, tuple)):\n return self.database.hmget(self.key, item)\n else:\n return self.database.hget(self.key, item)\n\n def get(self, key, fallback=None):\n val = self.database.hget(self.key, key)\n return val if val is not None else fallback\n\n def __setitem__(self, key, value):\n \"\"\"Set the value of the given key.\"\"\"\n return self.database.hset(self.key, key, value)\n\n def __delitem__(self, key):\n \"\"\"Delete the key from the hash.\"\"\"\n return self.database.hdel(self.key, key)\n\n def __contains__(self, key):\n \"\"\"\n Return a boolean valud indicating whether the given key\n exists.\n \"\"\"\n return self.database.hexists(self.key, key)\n\n def __len__(self):\n \"\"\"Return the number of keys in the hash.\"\"\"\n return self.database.hlen(self.key)\n\n def _scan(self, *args, **kwargs):\n return self.database.hscan_iter(self.key, *args, **kwargs)\n\n def __iter__(self):\n \"\"\"Iterate over the items in the hash.\"\"\"\n return iter(self._scan())\n\n def search(self, pattern, count=None):\n \"\"\"\n Search the keys of the given hash using the specified pattern.\n\n :param str pattern: Pattern used to match keys.\n :param int count: Limit number of results returned.\n :returns: An iterator yielding matching key/value pairs.\n \"\"\"\n return self._scan(match=pattern, count=count)\n\n def keys(self):\n \"\"\"Return the keys of the hash.\"\"\"\n return self.database.hkeys(self.key)\n\n def values(self):\n \"\"\"Return the values stored in the hash.\"\"\"\n return self.database.hvals(self.key)\n\n def items(self, lazy=False):\n \"\"\"\n Like Python's ``dict.items()`` but supports an optional\n parameter ``lazy`` which will return a generator rather than\n a list.\n \"\"\"\n if lazy:\n return self._scan()\n else:\n return list(self)\n\n def setnx(self, key, value):\n \"\"\"\n Set ``key`` to ``value`` if ``key`` does not exist.\n\n :returns: True if successfully set or False if the key already existed.\n \"\"\"\n return bool(self.database.hsetnx(self.key, key, value))\n\n @chainable_method\n def update(self, __data=None, **kwargs):\n \"\"\"\n Update the hash using the given dictionary or key/value pairs.\n \"\"\"\n if __data is None:\n __data = kwargs\n else:\n __data.update(kwargs)\n return self.database.hset(self.key, mapping=__data)\n\n def incr(self, key, incr_by=1):\n \"\"\"Increment the key by the given amount.\"\"\"\n return self.database.hincrby(self.key, key, incr_by)\n\n def incr_float(self, key, incr_by=1.):\n \"\"\"Increment the key by the given amount.\"\"\"\n return self.database.hincrbyfloat(self.key, key, incr_by)\n\n def as_dict(self, decode=False):\n \"\"\"\n Return a dictionary containing all the key/value pairs in the\n hash.\n \"\"\"\n res = self.database.hgetall(self.key)\n return decode_dict(res) if decode else res\n\n @classmethod\n def from_dict(cls, database, key, data, clear=False):\n \"\"\"\n Create and populate a Hash object from a data dictionary.\n \"\"\"\n hsh = cls(database, key)\n if clear:\n hsh.clear()\n hsh.update(data)\n return hsh\n\n\nclass List(Sortable, Container):\n \"\"\"\n Redis List object wrapper. Supports a list-like interface.\n\n See `List commands <http://redis.io/commands#list>`_ for more info.\n \"\"\"\n def __repr__(self):\n l = len(self)\n n_items = min(l, 10)\n items = safe_decode_list(self[:n_items])\n return '<List \"%s\": %s%s>' % (\n self.key,\n ', '.join(items),\n n_items < l and '...' or '')\n\n def __getitem__(self, item):\n \"\"\"\n Retrieve an item from the list by index. In addition to\n integer indexes, you can also pass a ``slice``.\n \"\"\"\n if isinstance(item, slice):\n start = item.start or 0\n stop = item.stop\n if not stop:\n stop = -1\n else:\n stop -= 1\n return self.database.lrange(self.key, start, stop)\n return self.database.lindex(self.key, item)\n\n def __setitem__(self, idx, value):\n \"\"\"Set the value of the given index.\"\"\"\n return self.database.lset(self.key, idx, value)\n\n def __delitem__(self, item):\n \"\"\"\n By default Redis treats deletes as delete by value, as\n opposed to delete by index. If an integer is passed into the\n function, it will be treated as an index, otherwise it will\n be treated as a value.\n\n If a slice is passed, then the list will be trimmed so that it *ONLY*\n contains the range specified by the slice start and stop. Note that\n this differs from the default behavior of Python's `list` type.\n \"\"\"\n if isinstance(item, slice):\n start = item.start or 0\n stop = item.stop or -1\n if stop > 0:\n stop -= 1\n return self.database.ltrim(self.key, start, stop)\n elif isinstance(item, int):\n item = self[item]\n if item is None:\n return\n return self.database.lrem(self.key, 1, item)\n\n def __len__(self):\n \"\"\"Return the length of the list.\"\"\"\n return self.database.llen(self.key)\n\n def __iter__(self):\n \"\"\"Iterate over the items in the list.\"\"\"\n return iter(self.database.lrange(self.key, 0, -1))\n\n def append(self, value):\n \"\"\"Add the given value to the end of the list.\"\"\"\n return self.database.rpush(self.key, value)\n\n def prepend(self, value):\n \"\"\"Add the given value to the beginning of the list.\"\"\"\n return self.database.lpush(self.key, value)\n\n def extend(self, value):\n \"\"\"Extend the list by the given value.\"\"\"\n return self.database.rpush(self.key, *value)\n\n def insert(self, value, pivot, where):\n return self.database.linsert(self.key, where, pivot, value)\n\n def insert_before(self, value, key):\n \"\"\"\n Insert the given value into the list before the index\n containing ``key``.\n \"\"\"\n self.insert(value, key, 'before')\n\n def insert_after(self, value, key):\n \"\"\"\n Insert the given value into the list after the index\n containing ``key``.\n \"\"\"\n self.insert(value, key, 'after')\n\n def popleft(self):\n \"\"\"Remove the first item from the list.\"\"\"\n return self.database.lpop(self.key)\n\n def popright(self):\n \"\"\"Remove the last item from the list.\"\"\"\n return self.database.rpop(self.key)\n pop = popright\n\n def bpopleft(self, timeout=0):\n \"\"\"\n Remove the first item from the list, blocking until an item becomes\n available or timeout is reached (0 for no timeout, default).\n \"\"\"\n ret = self.database.blpop(self.key, timeout)\n if ret is not None:\n return ret[1]\n\n def bpopright(self, timeout=0):\n \"\"\"\n Remove the last item from the list, blocking until an item becomes\n available or timeout is reached (0 for no timeout, default).\n \"\"\"\n ret = self.database.brpop(self.key, timeout)\n if ret is not None:\n return ret[1]\n\n def move_tail(self, key):\n return self.database.rpoplpush(self.key, key)\n\n def bmove_tail(self, key, timeout=0):\n return self.database.brpoplpush(self.key, key, timeout)\n\n def as_list(self, decode=False):\n \"\"\"\n Return a list containing all the items in the list.\n \"\"\"\n items = self.database.lrange(self.key, 0, -1)\n return [_decode(item) for item in items] if decode else items\n\n @classmethod\n def from_list(cls, database, key, data, clear=False):\n \"\"\"\n Create and populate a List object from a data list.\n \"\"\"\n lst = cls(database, key)\n if clear:\n lst.clear()\n lst.extend(data)\n return lst\n\n\nclass Set(Sortable, Container):\n \"\"\"\n Redis Set object wrapper. Supports a set-like interface.\n\n See `Set commands <http://redis.io/commands#set>`_ for more info.\n \"\"\"\n def __repr__(self):\n return '<Set \"%s\": %s items>' % (self.key, len(self))\n\n def add(self, *items):\n \"\"\"Add the given items to the set.\"\"\"\n return self.database.sadd(self.key, *items)\n\n def __delitem__(self, item):\n \"\"\"Remove the given item from the set.\"\"\"\n return self.remove(item)\n\n def remove(self, *items):\n \"\"\"Remove the given item(s) from the set.\"\"\"\n return self.database.srem(self.key, *items)\n\n def pop(self):\n \"\"\"Remove an element from the set.\"\"\"\n return self.database.spop(self.key)\n\n def _first_or_any(self):\n return self.random()\n\n def __contains__(self, item):\n \"\"\"\n Return a boolean value indicating whether the given item is\n a member of the set.\n \"\"\"\n return self.database.sismember(self.key, item)\n\n def __len__(self):\n \"\"\"Return the number of items in the set.\"\"\"\n return self.database.scard(self.key)\n\n def _scan(self, *args, **kwargs):\n return self.database.sscan_iter(self.key, *args, **kwargs)\n\n def __iter__(self):\n \"\"\"Return an iterable that yields the items of the set.\"\"\"\n return iter(self._scan())\n\n def search(self, pattern, count=None):\n \"\"\"\n Search the values of the given set using the specified pattern.\n\n :param str pattern: Pattern used to match keys.\n :param int count: Limit number of results returned.\n :returns: An iterator yielding matching values.\n \"\"\"\n return self._scan(match=pattern, count=count)\n\n def members(self):\n \"\"\"Return a ``set()`` containing the members of the set.\"\"\"\n return self.database.smembers(self.key)\n\n def random(self, n=None):\n \"\"\"Return a random member of the given set.\"\"\"\n return self.database.srandmember(self.key, n)\n\n def __sub__(self, other):\n \"\"\"\n Return the set difference of the current set and the left-\n hand :py:class:`Set` object.\n \"\"\"\n return self.database.sdiff(self.key, other.key)\n\n def __or__(self, other):\n \"\"\"\n Return the set union of the current set and the left-hand\n :py:class:`Set` object.\n \"\"\"\n return self.database.sunion(self.key, other.key)\n\n def __and__(self, other):\n \"\"\"\n Return the set intersection of the current set and the left-\n hand :py:class:`Set` object.\n \"\"\"\n return self.database.sinter(self.key, other.key)\n\n @chainable_method\n def __isub__(self, other):\n self.diffstore(self.key, other)\n\n @chainable_method\n def __ior__(self, other):\n self.unionstore(self.key, other)\n\n @chainable_method\n def __iand__(self, other):\n self.interstore(self.key, other)\n\n def diffstore(self, dest, *others):\n \"\"\"\n Store the set difference of the current set and one or more\n others in a new key.\n\n :param dest: the name of the key to store set difference\n :param others: One or more :py:class:`Set` instances\n :returns: A :py:class:`Set` referencing ``dest``.\n \"\"\"\n keys = [self.key]\n keys.extend([other.key for other in others])\n self.database.sdiffstore(dest, keys)\n return self.database.Set(dest)\n\n def interstore(self, dest, *others):\n \"\"\"\n Store the intersection of the current set and one or more\n others in a new key.\n\n :param dest: the name of the key to store intersection\n :param others: One or more :py:class:`Set` instances\n :returns: A :py:class:`Set` referencing ``dest``.\n \"\"\"\n keys = [self.key]\n keys.extend([other.key for other in others])\n self.database.sinterstore(dest, keys)\n return self.database.Set(dest)\n\n def unionstore(self, dest, *others):\n \"\"\"\n Store the union of the current set and one or more\n others in a new key.\n\n :param dest: the name of the key to store union\n :param others: One or more :py:class:`Set` instances\n :returns: A :py:class:`Set` referencing ``dest``.\n \"\"\"\n keys = [self.key]\n keys.extend([other.key for other in others])\n self.database.sunionstore(dest, keys)\n return self.database.Set(dest)\n\n def as_set(self, decode=False):\n \"\"\"\n Return a Python set containing all the items in the collection.\n \"\"\"\n items = self.database.smembers(self.key)\n return set(_decode(item) for item in items) if decode else items\n\n @classmethod\n def from_set(cls, database, key, data, clear=False):\n \"\"\"\n Create and populate a Set object from a data set.\n \"\"\"\n s = cls(database, key)\n if clear:\n s.clear()\n s.add(*data)\n return s\n\n\nclass ZSet(Sortable, Container):\n \"\"\"\n Redis ZSet object wrapper. Acts like a set and a dictionary.\n\n See `Sorted set commands <http://redis.io/commands#sorted_set>`_\n for more info.\n \"\"\"\n def __repr__(self):\n l = len(self)\n n_items = min(l, 5)\n items = safe_decode_list(self[:n_items, False])\n return '<ZSet \"%s\": %s%s>' % (\n self.key,\n ', '.join(items),\n n_items < l and '...' or '')\n\n def add(self, _mapping=None, **kwargs):\n \"\"\"\n Add the given item/score pairs to the ZSet. Arguments are\n specified as a dictionary of item: score, or as keyword arguments.\n \"\"\"\n if _mapping is not None:\n _mapping.update(kwargs)\n mapping = _mapping\n else:\n mapping = _mapping\n return self.database.zadd(self.key, mapping)\n\n def _convert_slice(self, s):\n def _slice_to_indexes(s):\n start = s.start\n stop = s.stop\n if isinstance(start, int) or isinstance(stop, int):\n return start, stop\n if start:\n start = self.database.zrank(self.key, start)\n if start is None:\n raise KeyError(s.start)\n if stop:\n stop = self.database.zrank(self.key, stop)\n if stop is None:\n raise KeyError(s.stop)\n return start, stop\n start, stop = _slice_to_indexes(s)\n start = start or 0\n if not stop:\n stop = -1\n else:\n stop -= 1\n return start, stop\n\n def __getitem__(self, item):\n \"\"\"\n Retrieve the given values from the sorted set. Accepts a\n variety of parameters for the input:\n\n .. code-block:: python\n\n zs = db.ZSet('my-zset')\n\n # Return the first 10 elements with their scores.\n zs[:10, True]\n\n # Return the first 10 elements without scores.\n zs[:10]\n zs[:10, False]\n\n # Return the range of values between 'k1' and 'k10' along\n # with their scores.\n zs['k1':'k10', True]\n\n # Return the range of items preceding and including 'k5'\n # without scores.\n zs[:'k5', False]\n \"\"\"\n if isinstance(item, tuple) and len(item) == 2:\n item, withscores = item\n else:\n withscores = False\n\n if isinstance(item, slice):\n start, stop = self._convert_slice(item)\n else:\n start = stop = item\n\n return self.database.zrange(\n self.key,\n start,\n stop,\n withscores=withscores)\n\n def __setitem__(self, item, score):\n \"\"\"Add item to the set with the given score.\"\"\"\n return self.database.zadd(self.key, {item: score})\n\n def __delitem__(self, item):\n \"\"\"\n Delete the given item(s) from the set. Like\n :py:meth:`~ZSet.__getitem__`, this method supports a wide\n variety of indexing and slicing options.\n \"\"\"\n if isinstance(item, slice):\n start, stop = self._convert_slice(item)\n return self.database.zremrangebyrank(self.key, start, stop)\n else:\n return self.remove(item)\n\n def remove(self, *items):\n \"\"\"Remove the given items from the ZSet.\"\"\"\n return self.database.zrem(self.key, *items)\n\n def __contains__(self, item):\n \"\"\"\n Return a boolean indicating whether the given item is in the\n sorted set.\n \"\"\"\n return not (self.rank(item) is None)\n\n def __len__(self):\n \"\"\"Return the number of items in the sorted set.\"\"\"\n return self.database.zcard(self.key)\n\n def _scan(self, *args, **kwargs):\n return self.database.zscan_iter(self.key, *args, **kwargs)\n\n def __iter__(self):\n \"\"\"\n Return an iterator that will yield (item, score) tuples.\n \"\"\"\n return iter(self._scan())\n\n def iterator(self, with_scores=False, reverse=False):\n if with_scores and not reverse:\n return self.search(None)\n return self.range(\n 0,\n -1,\n with_scores=with_scores,\n reverse=reverse)\n\n def search(self, pattern, count=None):\n \"\"\"\n Search the set, returning items that match the given search\n pattern.\n\n :param str pattern: Search pattern using wildcards.\n :param int count: Limit result set size.\n :returns: Iterator that yields matching item/score tuples.\n \"\"\"\n return self._scan(match=pattern, count=count)\n\n def score(self, item):\n \"\"\"Return the score of the given item.\"\"\"\n return self.database.zscore(self.key, item)\n\n def rank(self, item, reverse=False):\n \"\"\"Return the rank of the given item.\"\"\"\n fn = reverse and self.database.zrevrank or self.database.zrank\n return fn(self.key, item)\n\n def count(self, low, high=None):\n \"\"\"\n Return the number of items between the given bounds.\n \"\"\"\n if high is None:\n high = low\n return self.database.zcount(self.key, low, high)\n\n def lex_count(self, low, high):\n \"\"\"\n Count the number of members in a sorted set between a given\n lexicographical range.\n \"\"\"\n return self.database.zlexcount(self.key, low, high)\n\n def range(self, low, high, with_scores=False, desc=False, reverse=False):\n \"\"\"\n Return a range of items between ``low`` and ``high``. By\n default scores will not be included, but this can be controlled\n via the ``with_scores`` parameter.\n\n :param low: Lower bound.\n :param high: Upper bound.\n :param bool with_scores: Whether the range should include the\n scores along with the items.\n :param bool desc: Whether to sort the results descendingly.\n :param bool reverse: Whether to select the range in reverse.\n \"\"\"\n if reverse:\n return self.database.zrevrange(self.key, low, high, with_scores)\n else:\n return self.database.zrange(self.key, low, high, desc, with_scores)\n\n def range_by_score(self, low, high, start=None, num=None,\n with_scores=False, reverse=False):\n if reverse:\n fn = self.database.zrevrangebyscore\n low, high = high, low\n else:\n fn = self.database.zrangebyscore\n return fn(self.key, low, high, start, num, with_scores)\n\n def range_by_lex(self, low, high, start=None, num=None, reverse=False):\n \"\"\"\n Return a range of members in a sorted set, by lexicographical range.\n \"\"\"\n if reverse:\n fn = self.database.zrevrangebylex\n low, high = high, low\n else:\n fn = self.database.zrangebylex\n return fn(self.key, low, high, start, num)\n\n def remove_by_rank(self, low, high=None):\n \"\"\"\n Remove elements from the ZSet by their rank (relative position).\n\n :param low: Lower bound.\n :param high: Upper bound.\n \"\"\"\n if high is None:\n high = low\n return self.database.zremrangebyrank(self.key, low, high)\n\n def remove_by_score(self, low, high=None):\n \"\"\"\n Remove elements from the ZSet by their score.\n\n :param low: Lower bound.\n :param high: Upper bound.\n \"\"\"\n if high is None:\n high = low\n return self.database.zremrangebyscore(self.key, low, high)\n\n def remove_by_lex(self, low, high):\n return self.database.zremrangebylex(self.key, low, high)\n\n def incr(self, key, incr_by=1.):\n \"\"\"\n Increment the score of an item in the ZSet.\n\n :param key: Item to increment.\n :param incr_by: Amount to increment item's score.\n \"\"\"\n return self.database.zincrby(self.key, incr_by, key)\n\n def _first_or_any(self):\n item = self[0]\n if item:\n return item[0]\n\n @chainable_method\n def __ior__(self, other):\n self.unionstore(self.key, other)\n return self\n\n @chainable_method\n def __iand__(self, other):\n self.interstore(self.key, other)\n return self\n\n def interstore(self, dest, *others, **kwargs):\n \"\"\"\n Store the intersection of the current zset and one or more\n others in a new key.\n\n :param dest: the name of the key to store intersection\n :param others: One or more :py:class:`ZSet` instances\n :returns: A :py:class:`ZSet` referencing ``dest``.\n \"\"\"\n keys = [self.key]\n keys.extend([other.key for other in others])\n self.database.zinterstore(dest, keys, **kwargs)\n return self.database.ZSet(dest)\n\n def unionstore(self, dest, *others, **kwargs):\n \"\"\"\n Store the union of the current set and one or more\n others in a new key.\n\n :param dest: the name of the key to store union\n :param others: One or more :py:class:`ZSet` instances\n :returns: A :py:class:`ZSet` referencing ``dest``.\n \"\"\"\n keys = [self.key]\n keys.extend([other.key for other in others])\n self.database.zunionstore(dest, keys, **kwargs)\n return self.database.ZSet(dest)\n\n def popmin(self, count=1):\n \"\"\"\n Atomically remove the lowest-scoring item(s) in the set.\n\n :returns: a list of item, score tuples or ``None`` if the set is empty.\n \"\"\"\n return self.database.zpopmin(self.key, count)\n\n def popmax(self, count=1):\n \"\"\"\n Atomically remove the highest-scoring item(s) in the set.\n\n :returns: a list of item, score tuples or ``None`` if the set is empty.\n \"\"\"\n return self.database.zpopmax(self.key, count)\n\n def bpopmin(self, timeout=0):\n \"\"\"\n Atomically remove the lowest-scoring item from the set, blocking until\n an item becomes available or timeout is reached (0 for no timeout,\n default).\n\n Returns a 2-tuple of (item, score).\n \"\"\"\n res = self.database.bzpopmin(self.key, timeout)\n if res is not None:\n return (res[1], res[2])\n\n def bpopmax(self, timeout=0):\n \"\"\"\n Atomically remove the highest-scoring item from the set, blocking until\n an item becomes available or timeout is reached (0 for no timeout,\n default).\n\n Returns a 2-tuple of (item, score).\n \"\"\"\n res = self.database.bzpopmax(self.key, timeout)\n if res is not None:\n return (res[1], res[2])\n\n def popmin_compat(self, count=1):\n \"\"\"\n Atomically remove the lowest-scoring item(s) in the set. Compatible\n with Redis versions < 5.0.\n\n :returns: a list of item, score tuples or ``None`` if the set is empty.\n \"\"\"\n pipe = self.database.pipeline()\n r1, r2 = (pipe\n .zrange(self.key, 0, count - 1, withscores=True)\n .zremrangebyrank(self.key, 0, count - 1)\n .execute())\n return r1\n\n def popmax_compat(self, count=1):\n \"\"\"\n Atomically remove the highest-scoring item(s) in the set. Compatible\n with Redis versions < 5.0.\n\n :returns: a list of item, score tuples or ``None`` if the set is empty.\n \"\"\"\n pipe = self.database.pipeline()\n r1, r2 = (pipe\n .zrange(self.key, 0 - count, -1, withscores=True)\n .zremrangebyrank(self.key, 0 - count, -1)\n .execute())\n return r1[::-1]\n\n def as_items(self, decode=False):\n \"\"\"\n Return a list of 2-tuples consisting of key/score.\n \"\"\"\n items = self.database.zrange(self.key, 0, -1, withscores=True)\n if decode:\n items = [(_decode(k), score) for k, score in items]\n return items\n\n @classmethod\n def from_dict(cls, database, key, data, clear=False):\n \"\"\"\n Create and populate a ZSet object from a data dictionary.\n \"\"\"\n zset = cls(database, key)\n if clear:\n zset.clear()\n zset.add(data)\n return zset\n\n\nclass HyperLogLog(Container):\n \"\"\"\n Redis HyperLogLog object wrapper.\n\n See `HyperLogLog commands <http://redis.io/commands#hyperloglog>`_\n for more info.\n \"\"\"\n def add(self, *items):\n \"\"\"\n Add the given items to the HyperLogLog.\n \"\"\"\n return self.database.pfadd(self.key, *items)\n\n def __len__(self):\n return self.database.pfcount(self.key)\n\n def __ior__(self, other):\n if not isinstance(other, (list, tuple)):\n other = [other]\n return self.merge(self.key, *other)\n\n def merge(self, dest, *others):\n \"\"\"\n Merge one or more :py:class:`HyperLogLog` instances.\n\n :param dest: Key to store merged result.\n :param others: One or more ``HyperLogLog`` instances.\n \"\"\"\n items = [self.key]\n items.extend([other.key for other in others])\n self.database.pfmerge(dest, *items)\n return HyperLogLog(self.database, dest)\n\n\nclass Array(Container):\n \"\"\"\n Custom container that emulates an array (as opposed to the\n linked-list implementation of :py:class:`List`). This gives:\n\n * O(1) append, get, len, pop last, set\n * O(n) remove from middle\n\n :py:class:`Array` is built on top of the hash data type and\n is implemented using lua scripts.\n \"\"\"\n def __getitem__(self, idx):\n \"\"\"Get the value stored in the given index.\"\"\"\n return self.database.run_script(\n 'array_get',\n keys=[self.key],\n args=[idx])\n\n def __setitem__(self, idx, value):\n \"\"\"Set the value at the given index.\"\"\"\n return self.database.run_script(\n 'array_set',\n keys=[self.key],\n args=[idx, value])\n\n def __delitem__(self, idx):\n \"\"\"Delete the given index.\"\"\"\n return self.pop(idx)\n\n def __len__(self):\n \"\"\"Return the number of items in the array.\"\"\"\n return self.database.hlen(self.key)\n\n def append(self, value):\n \"\"\"Append a new value to the end of the array.\"\"\"\n self.database.run_script(\n 'array_append',\n keys=[self.key],\n args=[value])\n\n def extend(self, values):\n \"\"\"Extend the array, appending the given values.\"\"\"\n self.database.run_script(\n 'array_extend',\n keys=[self.key],\n args=values)\n\n def pop(self, idx=None):\n \"\"\"\n Remove an item from the array. By default this will be the\n last item by index, but any index can be specified.\n \"\"\"\n if idx is not None:\n return self.database.run_script(\n 'array_remove',\n keys=[self.key],\n args=[idx])\n else:\n return self.database.run_script(\n 'array_pop',\n keys=[self.key],\n args=[])\n\n def __contains__(self, item):\n \"\"\"\n Return a boolean indicating whether the given item is stored\n in the array. O(n).\n \"\"\"\n item = encode(item)\n for value in self:\n if value == item:\n return True\n return False\n\n def __iter__(self):\n \"\"\"Return an iterable that yields array items.\"\"\"\n return iter(\n item[1] for item in sorted(self.database.hscan_iter(self.key)))\n\n def as_list(self, decode=False):\n \"\"\"\n Return a list of items in the array.\n \"\"\"\n return [_decode(i) for i in self] if decode else list(self)\n\n @classmethod\n def from_list(cls, database, key, data, clear=False):\n \"\"\"\n Create and populate an Array object from a data dictionary.\n \"\"\"\n arr = cls(database, key)\n if clear:\n arr.clear()\n arr.extend(data)\n return arr\n\n\ndef _normalize_stream_keys(keys, default_id='0-0'):\n if isinstance(keys, basestring_type):\n return {keys: default_id}\n elif isinstance(keys, (list, tuple)):\n return dict([(key, default_id) for key in keys])\n elif isinstance(keys, dict):\n return keys\n else:\n raise ValueError('keys must be either a stream key, a list of '\n 'stream keys, or a dictionary mapping key to '\n 'minimum message id.')\n\n\nclass Stream(Container):\n \"\"\"\n Redis stream container.\n \"\"\"\n def add(self, data, id='*', maxlen=None, approximate=True):\n \"\"\"\n Add data to a stream.\n\n :param dict data: data to add to stream\n :param id: identifier for message ('*' to automatically append)\n :param maxlen: maximum length for stream\n :param approximate: allow stream max length to be approximate\n :returns: the added message id.\n \"\"\"\n return self.database.xadd(self.key, data, id, maxlen, approximate)\n\n def __getitem__(self, item):\n \"\"\"\n Read a range of values from a stream.\n\n The index must be a message id or a slice. An empty slice will result\n in reading all values from the stream. Message ids provided as lower or\n upper bounds are inclusive.\n\n To specify a maximum number of messages, use the \"step\" parameter of\n the slice.\n \"\"\"\n if isinstance(item, slice):\n return self.range(item.start or '-', item.stop or '+', item.step)\n return self.get(item)\n\n def get(self, docid):\n \"\"\"\n Get a message by id.\n\n :param docid: the message id to retrieve.\n :returns: a 2-tuple of (message id, data) or None if not found.\n \"\"\"\n items = self[docid:docid:1]\n if items:\n return items[0]\n\n def range(self, start='-', stop='+', count=None):\n \"\"\"\n Read a range of values from a stream.\n\n :param start: start key of range (inclusive) or '-' for oldest message\n :param stop: stop key of range (inclusive) or '+' for newest message\n :param count: limit number of messages returned\n \"\"\"\n return self.database.xrange(self.key, start, stop, count)\n\n def revrange(self, start='+', stop='-', count=None):\n \"\"\"\n Read a range of values from a stream in reverse.\n\n :param start: start key of range (inclusive) or '+' for newest message\n :param stop: stop key of range (inclusive) or '-' for oldest message\n :param count: limit number of messages returned\n \"\"\"\n return self.database.xrevrange(self.key, start, stop, count)\n\n def __iter__(self):\n return iter(self[:])\n\n def __delitem__(self, item):\n \"\"\"\n Delete one or more messages by id. The index can be either a single\n message id or a list/tuple of multiple ids.\n \"\"\"\n if not isinstance(item, (list, tuple)):\n item = (item,)\n self.delete(*item)\n\n def delete(self, *id_list):\n \"\"\"\n Delete one or more message by id. The index can be either a single\n message id or a list/tuple of multiple ids.\n \"\"\"\n return self.database.xdel(self.key, *id_list)\n\n def length(self):\n \"\"\"\n Return the length of a stream.\n \"\"\"\n return self.database.xlen(self.key)\n __len__ = length\n\n def read(self, count=None, block=None, last_id=None):\n \"\"\"\n Monitor stream for new data.\n\n :param int count: limit number of messages returned\n :param int block: milliseconds to block, 0 for indefinitely\n :param last_id: Last id read (an exclusive lower-bound). If the '$'\n value is given, we will only read values added *after* our command\n started blocking.\n :returns: a list of (message id, data) 2-tuples.\n \"\"\"\n if last_id is None: last_id = '0-0'\n resp = self.database.xread({self.key: _decode(last_id)}, count, block)\n\n # resp is a 2-tuple of stream name -> message list.\n return resp[0][1] if resp else []\n\n def info(self):\n \"\"\"\n Retrieve information about the stream. Wraps call to\n :py:meth:`~Database.xinfo_stream`.\n\n :returns: a dictionary containing stream metadata\n \"\"\"\n return self.database.xinfo_stream(self.key)\n\n def groups_info(self):\n \"\"\"\n Retrieve information about consumer groups for the stream. Wraps call\n to :py:meth:`~Database.xinfo_groups`.\n\n :returns: a dictionary containing consumer group metadata\n \"\"\"\n return self.database.xinfo_groups(self.key)\n\n def consumers_info(self, group):\n \"\"\"\n Retrieve information about consumers within the given consumer group\n operating on the stream. Calls :py:meth:`~Database.xinfo_consumers`.\n\n :param group: consumer group name\n :returns: a dictionary containing consumer metadata\n \"\"\"\n return self.database.xinfo_consumers(self.key, group)\n\n def set_id(self, id):\n \"\"\"\n Set the maximum message id for the stream.\n\n :param id: id of last-read message\n \"\"\"\n return self.database.xsetid(self.key, id)\n\n def trim(self, count=None, approximate=True, minid=None, limit=None):\n \"\"\"\n Trim the stream to the given \"count\" of messages, discarding the oldest\n messages first.\n\n :param count: maximum size of stream (maxlen)\n :param approximate: allow size to be approximate\n :param minid: evicts entries with IDs lower than the given min id.\n :param limit: maximum number of entries to evict.\n \"\"\"\n return self.database.xtrim(self.key, maxlen=count,\n approximate=approximate, minid=minid,\n limit=limit)\n\n\nclass ConsumerGroupStream(Stream):\n \"\"\"\n Helper for working with an individual stream within the context of a\n consumer group. This object is exposed as an attribute on a\n :py:class:`ConsumerGroup` object using the stream key for the attribute\n name.\n\n This class should not be created directly. It will automatically be added\n to the ``ConsumerGroup`` object.\n\n For example::\n\n cg = db.consumer_group('groupname', ['stream-1', 'stream-2'])\n cg.stream_1 # ConsumerGroupStream for \"stream-1\"\n cg.stream_2 # ConsumerGroupStream for \"stream-2\"\n \"\"\"\n __slots__ = ('database', 'group', 'key', '_consumer')\n\n def __init__(self, database, group, key, consumer):\n self.database = database\n self.group = group\n self.key = key\n self._consumer = consumer\n\n def consumers_info(self):\n \"\"\"\n Retrieve information about consumers within the given consumer group\n operating on the stream. Calls :py:meth:`~Database.xinfo_consumers`.\n\n :returns: a list of dictionaries containing consumer metadata\n \"\"\"\n return self.database.xinfo_consumers(self.key, self.group)\n\n def ack(self, *id_list):\n \"\"\"\n Acknowledge that the message(s) were been processed by the consumer\n associated with the parent :py:class:`ConsumerGroup`.\n\n :param id_list: one or more message ids to acknowledge\n :returns: number of messages marked acknowledged\n \"\"\"\n return self.database.xack(self.key, self.group, *id_list)\n\n def claim(self, *id_list, **kwargs):\n \"\"\"\n Claim pending - but unacknowledged - messages for this stream within\n the context of the parent :py:class:`ConsumerGroup`.\n\n :param id_list: one or more message ids to acknowledge\n :param min_idle_time: minimum idle time in milliseconds (keyword-arg).\n :returns: list of (message id, data) 2-tuples of messages that were\n successfully claimed\n \"\"\"\n min_idle_time = kwargs.pop('min_idle_time', None) or 0\n if kwargs: raise ValueError('incorrect arguments for claim()')\n return self.database.xclaim(self.key, self.group, self._consumer,\n min_idle_time, id_list)\n\n def pending(self, start='-', stop='+', count=1000, consumer=None,\n idle=None):\n \"\"\"\n List pending messages within the consumer group for this stream.\n\n :param start: start id (or '-' for oldest pending)\n :param stop: stop id (or '+' for newest pending)\n :param count: limit number of messages returned\n :param consumer: restrict message list to the given consumer\n :param int idle: filter by idle-time in milliseconds (6.2)\n :returns: A list containing status for each pending message. Each\n pending message returns [id, consumer, idle time, deliveries].\n \"\"\"\n return self.database.xpending_range(self.key, self.group, min=start,\n max=stop, count=count,\n consumername=consumer, idle=idle)\n\n def autoclaim(self, consumer, min_idle_time, start_id=0, count=None, justid=False):\n \"\"\"\n Transfer ownership of pending stream entries that match the specified\n criteria. Similar to calling XPENDING and XCLAIM, but provides a more\n straightforward way to deal with message delivery failures.\n\n :param consumer: name of consumer that claims the message.\n :param min_idle_time: in milliseconds\n :param start_id: start id\n :param count: optional, upper limit of entries to claim. Default 100.\n :param justid: return just IDs of messages claimed.\n :returns: [next start id, [messages that were claimed]\n \"\"\"\n return self.database.xautoclaim(self.key, self.group, consumer,\n min_idle_time, start_id, count, justid)\n\n def read(self, count=None, block=None, last_id=None):\n \"\"\"\n Monitor the stream for new messages within the context of the parent\n :py:class:`ConsumerGroup`.\n\n :param int count: limit number of messages returned\n :param int block: milliseconds to block, 0 for indefinitely.\n :param str last_id: optional last ID, by default uses the special\n token \">\", which reads the oldest unread message.\n :returns: a list of (message id, data) 2-tuples.\n \"\"\"\n key = {self.key: '>' if last_id is None else last_id}\n resp = self.database.xreadgroup(self.group, self._consumer, key, count,\n block)\n return resp[0][1] if resp else []\n\n def set_id(self, id='$'):\n \"\"\"\n Set the last-read message id for the stream within the context of the\n parent :py:class:`ConsumerGroup`. By default this will be the special\n \"$\" identifier, meaning all messages are marked as having been read.\n\n :param id: id of last-read message (or \"$\").\n \"\"\"\n return self.database.xgroup_setid(self.key, self.group, id)\n\n def delete_consumer(self, consumer=None):\n \"\"\"\n Remove a specific consumer from a consumer group.\n\n :consumer: name of consumer to delete. If not provided, will be the\n default consumer for this stream.\n :returns: number of pending messages that the consumer had before\n being deleted.\n \"\"\"\n if consumer is None: consumer = self._consumer\n return self.database.xgroup_delconsumer(self.key, self.group, consumer)\n\n\nclass ConsumerGroup(object):\n \"\"\"\n Helper for working with Redis Streams consumer groups functionality. Each\n stream associated with the consumer group is exposed as a special attribute\n of the ``ConsumerGroup`` object, exposing stream-specific functionality\n within the context of the group.\n\n Rather than creating this class directly, use the\n :py:meth:`Database.consumer_group` method.\n\n Each registered stream within the group is exposed as a special attribute\n that provides stream-specific APIs within the context of the group. For\n more information see :py:class:`ConsumerGroupStream`.\n\n The streams managed by a consumer group must exist before the consumer\n group can be created. By default, calling :py:meth:`ConsumerGroup.create`\n will automatically create stream keys for any that do not exist.\n\n Example::\n\n cg = db.consumer_group('groupname', ['stream-1', 'stream-2'])\n cg.create() # Create consumer group.\n cg.stream_1 # ConsumerGroupStream for \"stream-1\"\n cg.stream_2 # ConsumerGroupStream for \"stream-2\"\n # or, alternatively:\n cg.streams['stream-1']\n\n :param Database database: Redis client\n :param name: consumer group name\n :param keys: stream identifier(s) to monitor. May be a single stream\n key, a list of stream keys, or a key-to-minimum id mapping. The\n minimum id for each stream should be considered an exclusive\n lower-bound. The '$' value can also be used to only read values\n added *after* our command started blocking.\n :param consumer: name for consumer\n \"\"\"\n stream_key_class = ConsumerGroupStream\n\n def __init__(self, database, name, keys, consumer=None):\n self.database = database\n self.name = name\n self.keys = _normalize_stream_keys(keys)\n self._read_keys = _normalize_stream_keys(list(self.keys), '>')\n self._consumer = consumer or (self.name + '.c1')\n self.streams = {} # Dict of key->ConsumerGroupStream.\n\n # Add attributes for each stream exposed as part of the group.\n for key in self.keys:\n attr = make_python_attr(key)\n stream = self.stream_key_class(database, name, key, self._consumer)\n setattr(self, attr, stream)\n self.streams[key] = stream\n\n def consumer(self, name):\n \"\"\"\n Create a new consumer for the :py:class:`ConsumerGroup`.\n\n :param name: name of consumer\n :returns: a :py:class:`ConsumerGroup` using the given consumer name.\n \"\"\"\n return type(self)(self.database, self.name, self.keys, name)\n\n def create(self, ensure_keys_exist=True, mkstream=False):\n \"\"\"\n Create the consumer group and register it with the group's stream keys.\n\n :param ensure_keys_exist: Ensure that the streams exist before creating\n the consumer group. Streams that do not exist will be created.\n :param mkstream: Use the \"MKSTREAM\" option to ensure stream exists (may\n require unstable version of Redis).\n \"\"\"\n if ensure_keys_exist:\n for key in self.keys:\n if not self.database.exists(key):\n msg_id = self.database.xadd(key, {'': ''}, id=b'0-1')\n self.database.xdel(key, msg_id)\n elif self.database.type(key) != b'stream':\n raise ValueError('Consumer group key \"%s\" exists and is '\n 'not a stream. To prevent data-loss '\n 'this key will not be deleted.' % key)\n\n resp = {}\n\n # Mapping of key -> last-read message ID.\n for key, value in self.keys.items():\n try:\n resp[key] = self.database.xgroup_create(key, self.name, value,\n mkstream)\n except ResponseError as exc:\n if exception_message(exc).startswith('BUSYGROUP'):\n resp[key] = False\n else:\n raise\n return resp\n\n def reset(self):\n \"\"\"\n Reset the consumer group, clearing the last-read status for each\n stream so it will read from the beginning of each stream.\n \"\"\"\n return self.set_id('0-0')\n\n def destroy(self):\n \"\"\"\n Destroy the consumer group.\n \"\"\"\n resp = {}\n for key in self.keys:\n resp[key] = self.database.xgroup_destroy(key, self.name)\n return resp\n\n def read(self, count=None, block=None, consumer=None):\n \"\"\"\n Read unseen messages from all streams in the consumer group. Wrapper\n for :py:class:`Database.xreadgroup` method.\n\n :param int count: limit number of messages returned\n :param int block: milliseconds to block, 0 for indefinitely.\n :param consumer: consumer name\n :returns: a list of (stream key, messages) tuples, where messages is\n a list of (message id, data) 2-tuples.\n \"\"\"\n if consumer is None: consumer = self._consumer\n return self.database.xreadgroup(self.name, consumer, self._read_keys,\n count, block)\n\n def set_id(self, id='$'):\n \"\"\"\n Set the last-read message id for each stream in the consumer group. By\n default, this will be the special \"$\" identifier, meaning all messages\n are marked as having been read.\n\n :param id: id of last-read message (or \"$\").\n \"\"\"\n accum = {}\n for key in self.keys:\n accum[key] = self.database.xgroup_setid(key, self.name, id)\n return accum\n\n def stream_info(self):\n \"\"\"\n Retrieve information for each stream managed by the consumer group.\n Calls :py:meth:`~Database.xinfo_stream` for each stream.\n\n :returns: a dictionary mapping stream key to a dictionary of metadata\n \"\"\"\n accum = {}\n for key in self.keys:\n accum[key] = self.database.xinfo_stream(key)\n return accum\n\n\nclass BitFieldOperation(object):\n \"\"\"\n Command builder for BITFIELD commands.\n \"\"\"\n def __init__(self, database, key):\n self.database = database\n self.key = key\n self.operations = []\n self._last_overflow = None # Default is \"WRAP\".\n\n def incrby(self, fmt, offset, increment, overflow=None):\n \"\"\"\n Increment a bitfield by a given amount.\n\n :param fmt: format-string for the bitfield being updated, e.g. u8 for\n an unsigned 8-bit integer.\n :param int offset: offset (in number of bits).\n :param int increment: value to increment the bitfield by.\n :param str overflow: overflow algorithm. Defaults to WRAP, but other\n acceptable values are SAT and FAIL. See the Redis docs for\n descriptions of these algorithms.\n :returns: a :py:class:`BitFieldOperation` instance.\n \"\"\"\n if overflow is not None and overflow != self._last_overflow:\n self._last_overflow = overflow\n self.operations.append(('OVERFLOW', overflow))\n\n self.operations.append(('INCRBY', fmt, offset, increment))\n return self\n\n def get(self, fmt, offset):\n \"\"\"\n Get the value of a given bitfield.\n\n :param fmt: format-string for the bitfield being read, e.g. u8 for an\n unsigned 8-bit integer.\n :param int offset: offset (in number of bits).\n :returns: a :py:class:`BitFieldOperation` instance.\n \"\"\"\n self.operations.append(('GET', fmt, offset))\n return self\n\n def set(self, fmt, offset, value):\n \"\"\"\n Set the value of a given bitfield.\n\n :param fmt: format-string for the bitfield being read, e.g. u8 for an\n unsigned 8-bit integer.\n :param int offset: offset (in number of bits).\n :param int value: value to set at the given position.\n :returns: a :py:class:`BitFieldOperation` instance.\n \"\"\"\n self.operations.append(('SET', fmt, offset, value))\n return self\n\n @property\n def command(self):\n return reduce(operator.add, self.operations, ('BITFIELD', self.key))\n\n def execute(self):\n \"\"\"\n Execute the operation(s) in a single BITFIELD command. The return value\n is a list of values corresponding to each operation.\n \"\"\"\n return self.database.execute_command(*self.command)\n\n def __iter__(self):\n \"\"\"\n Implicit execution and iteration of the return values for a sequence of\n operations.\n \"\"\"\n return iter(self.execute())\n\n\nclass BitField(Container):\n \"\"\"\n Wrapper that provides a convenient API for constructing and executing Redis\n BITFIELD commands. The BITFIELD command can pack multiple operations into a\n single logical command, so the :py:class:`BitField` supports a method-\n chaining API that allows multiple operations to be performed atomically.\n\n Rather than instantiating this class directly, you should use the\n :py:meth:`Database.bit_field` method to obtain a :py:class:`BitField`.\n \"\"\"\n def incrby(self, fmt, offset, increment, overflow=None):\n \"\"\"\n Increment a bitfield by a given amount.\n\n :param fmt: format-string for the bitfield being updated, e.g. u8 for\n an unsigned 8-bit integer.\n :param int offset: offset (in number of bits).\n :param int increment: value to increment the bitfield by.\n :param str overflow: overflow algorithm. Defaults to WRAP, but other\n acceptable values are SAT and FAIL. See the Redis docs for\n descriptions of these algorithms.\n :returns: a :py:class:`BitFieldOperation` instance.\n \"\"\"\n bfo = BitFieldOperation(self.database, self.key)\n return bfo.incrby(fmt, offset, increment, overflow)\n\n def get(self, fmt, offset):\n \"\"\"\n Get the value of a given bitfield.\n\n :param fmt: format-string for the bitfield being read, e.g. u8 for an\n unsigned 8-bit integer.\n :param int offset: offset (in number of bits).\n :returns: a :py:class:`BitFieldOperation` instance.\n \"\"\"\n bfo = BitFieldOperation(self.database, self.key)\n return bfo.get(fmt, offset)\n\n def set(self, fmt, offset, value):\n \"\"\"\n Set the value of a given bitfield.\n\n :param fmt: format-string for the bitfield being read, e.g. u8 for an\n unsigned 8-bit integer.\n :param int offset: offset (in number of bits).\n :param int value: value to set at the given position.\n :returns: a :py:class:`BitFieldOperation` instance.\n \"\"\"\n bfo = BitFieldOperation(self.database, self.key)\n return bfo.set(fmt, offset, value)\n\n def _validate_slice(self, item):\n if not isinstance(item, slice):\n raise ValueError('Must use a slice.')\n if item.stop is None or item.stop < 0:\n raise ValueError('slice must have a non-negative upper-bound')\n start = item.start or 0\n if start > item.stop:\n raise ValueError('start of slice cannot exceed stop')\n return start, item.stop\n\n def __getitem__(self, item):\n \"\"\"\n Short-hand for getting a range of bits in a bitfield. Note that the\n item **must** be a slice specifying the start and end of the range of\n bits to read.\n \"\"\"\n start, stop = self._validate_slice(item)\n return self.get('u%s' % (stop - start), start).execute()[0]\n\n def __setitem__(self, item, value):\n \"\"\"\n Short-hand for setting a range of bits in a bitfield. Note that the\n item **must** be a slice specifying the start and end of the range of\n bits to read. If the value representation exceeds the number of bits\n implied by the slice range, a ``ValueError`` is raised.\n \"\"\"\n start, stop = self._validate_slice(item)\n nbits = stop - start\n if value >= (1 << nbits):\n raise ValueError('value exceeds width specified by slice')\n self.set('u%s' % nbits, start, value).execute()\n\n def __delitem__(self, item):\n \"\"\"\n Clear a range of bits in a bitfield. Note that the item **must** be a\n slice specifying the start and end of the range of bits to clear.\n \"\"\"\n start, stop = self._validate_slice(item)\n self.set('u%s' % (stop - start), start, 0).execute()\n\n def get_raw(self):\n \"\"\"\n Return the raw bytestring that comprises the bitfield. Equivalent to a\n normal GET command.\n \"\"\"\n return self.database.get(self.key)\n\n def set_raw(self, value):\n \"\"\"\n Set the raw bytestring that comprises the bitfield. Equivalent to a\n normal SET command.\n \"\"\"\n return self.database.set(self.key, value)\n\n def bit_count(self, start=None, end=None):\n \"\"\"\n Count the set bits in a string. Note that the `start` and `end`\n parameters are offsets in **bytes**.\n \"\"\"\n return self.database.bitcount(self.key, start, end)\n\n def get_bit(self, offset):\n \"\"\"\n Get the bit value at the given offset (in bits).\n\n :param int offset: bit offset\n :returns: value at bit offset, 1 or 0\n \"\"\"\n return self.database.getbit(self.key, offset)\n\n def set_bit(self, offset, value):\n \"\"\"\n Set the bit value at the given offset (in bits).\n\n :param int offset: bit offset\n :param int value: new value for bit, 1 or 0\n :returns: previous value at bit offset, 1 or 0\n \"\"\"\n return self.database.setbit(self.key, offset, value)\n\n\nclass BloomFilter(Container):\n \"\"\"\n Bloom-filters are probabilistic data-structures that are used to answer the\n question: \"is X a member of set S?\" It is possible to receive a false\n positive, but impossible to receive a false negative (in other words, if\n the bloom filter contains a value, it will never erroneously report that it\n does *not* contain such a value). The accuracy of the bloom-filter and the\n likelihood of a false positive can be reduced by increasing the size of the\n bloomfilter. The default size is 64KB (or 524,288 bits).\n\n Rather than instantiate this class directly, use\n :py:meth:`Database.bloom_filter`.\n \"\"\"\n def __init__(self, database, key, size=64 * 1024):\n super(BloomFilter, self).__init__(database, key)\n self.size = size\n self.bits = self.size * 8\n self._bf = BitField(self.database, self.key)\n\n def _get_seeds(self, data):\n # Hash the data into a 16-byte digest, then break that up into 4 4-byte\n # (32-bit) unsigned integers. We use the modulo operator to normalize\n # these 32-bit ints to bit-indices.\n seeds = struct.unpack('>IIII', hashlib.md5(encode(data)).digest())\n return [seed % self.bits for seed in seeds]\n\n def add(self, data):\n \"\"\"\n Add an item to the bloomfilter.\n\n :param bytes data: a bytestring representing the item to add.\n \"\"\"\n bfo = BitFieldOperation(self.database, self.key)\n for bit_index in self._get_seeds(data):\n bfo.set('u1', bit_index, 1)\n bfo.execute()\n\n def contains(self, data):\n \"\"\"\n Check if an item has been added to the bloomfilter.\n\n :param bytes data: a bytestring representing the item to check.\n :returns: a boolean indicating whether or not the item is present in\n the bloomfilter. False-positives are possible, but a negative\n return value is definitive.\n \"\"\"\n bfo = BitFieldOperation(self.database, self.key)\n for bit_index in self._get_seeds(data):\n bfo.get('u1', bit_index)\n return all(bfo.execute())\n __contains__ = contains\n\n def __len__(self):\n return self.size\n" }, { "alpha_fraction": 0.7030967473983765, "alphanum_fraction": 0.7086451649665833, "avg_line_length": 36.80487823486328, "blob_id": "4bb91af61b60ae823a506cbff0b0bfddb890e270", "content_id": "5599de602c11945734658bb6cb47dc5ac1ce127d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 7750, "license_type": "permissive", "max_line_length": 418, "num_lines": 205, "path": "/docs/alt-backends.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _alt-backends:\n\nAlternative Backends (\"tusks\")\n==============================\n\nIn addition to `Redis <http://redis.io>`_, I've been experimenting with adding support for alternative *redis-like* backends. These alternative backends are referred to as *tusks*, and currently Walrus supports the following:\n\n* `RLite <https://github.com/seppo0010/rlite>`_, a self-contained and serverless Redis-compatible database engine. Use ``rlite`` if you want all the features of Redis, without the separate server process..\n* `Vedis <http://vedis.symisc.net/index.html>`_, an embeddable data-store written in C with over 70 commands similar in concept to Redis. Vedis is built on a fast key/value store and supports writing custom commands in Python. Use ``vedis`` if you are OK working with a smaller subset of commands out-of-the-box or are interested in writing your own commands.\n* `ledisdb <https://ledisdb.io/>`_, Redis-like database written in Golang. Supports almost all the Redis commands. Requires `ledis-py <https://github.com/holys/ledis-py>`_.\n\nrlite\n-----\n\n`rlite <https://github.com/seppo0010/rlite>`_ is an embedded Redis-compatible database.\n\nAccording to the project's README,\n\n rlite is to Redis what SQLite is to Postgres.\n\nThe project's features are:\n\n* **Supports virtually every Redis command**.\n* Self-contained embedded data-store.\n* Serverless / zero-configuration.\n* Transactions.\n* Databases can be in-memory or stored in a single file on-disk.\n\nUse-cases for ``rlite``:\n\n* **Mobile** environments, where it is not practical to run a database server.\n* **Development** or **testing** environments. Database fixtures can be distributed as a simple binary file.\n* **Slave of Redis** for additional durability.\n* Application file format, alternative to a proprietary format or SQLite.\n\nPython bindings\n^^^^^^^^^^^^^^^\n\n`rlite-py <https://github.com/seppo0010/rlite-py>`_ allows ``rlite`` to be embedded in your Python apps. To install ``rlite-py``, you can use ``pip``:\n\n.. code-block:: console\n\n $ pip install hirlite\n\nUsing with Walrus\n^^^^^^^^^^^^^^^^^\n\nTo use ``rlite`` instead of Redis in your ``walrus`` application, simply use the ``WalrusLite`` in place of the usual :py:class:`Walrus` object:\n\n.. code-block:: python\n\n from walrus.tusks.rlite import WalrusLite\n\n walrus = WalrusLite('/path/to/database.db')\n\n``WalrusLite`` can also be used as an in-memory database by omitting a path to a database file when instantiating, or by passing the special string ``':memory:'``:\n\n.. code-block:: python\n\n from walrus.tusks.rlite import WalrusLite\n\n walrus_mem_db = WalrusLite(':memory:')\n\nVedis\n-----\n\n`Vedis <http://vedis.symisc.net/>`_ is an embedded Redis-like database with over 70 commands. ``Vedis``, like ``rlite``, does not have a separate server process. And like ``rlite``, ``Vedis`` supports both file-backed databases and transient in-memory databases.\n\nAccording to the project's README,\n\n Vedis is a self-contained C library without dependency. It requires very minimal support from external libraries or from the operating system. This makes it well suited for use in embedded devices that lack the support infrastructure of a desktop computer. This also makes Vedis appropriate for use within applications that need to run without modification on a wide variety of computers of varying configurations.\n\nThe project's features are:\n\n* Serverless / zero-configuration.\n* Transactional (ACID) datastore.\n* Databases can be in-memory or stored in a single file on-disk.\n* Over 70 commands covering many Redis features.\n* Cross-platform file format.\n* Includes fast low-level key/value store.\n* Thread-safe and fully re-entrant.\n* Support for Terabyte-sized databases.\n* `Python bindings <https://vedis-python.readthedocs.io/en/latest/>`_ allow you to `write your own Vedis commands in Python <https://vedis-python.readthedocs.io/en/latest/custom_commands.html>`_.\n\nUse-cases for ``Vedis``:\n\n* **Mobile** environments, where it is not practical to run a database server.\n* **Development** or **testing** environments. Database fixtures can be distributed as a simple binary file.\n* Application file format, alternative to a proprietary format or SQLite.\n* Extremely large databases that do not fit in RAM.\n* Embedded platforms with limited resources.\n\n.. note::\n Unlike ``rlite``, which supports virtually all the Redis commands, ``Vedis`` supports a more limited subset. Notably lacking are sorted-set operations and many of the list operations. Hashes, Sets and key/value operations are very well supported, though.\n\n.. warning::\n The authors of Vedis have indicated that they are not actively working on new features for Vedis right now.\n\nPython bindings\n^^^^^^^^^^^^^^^\n\n`vedis-python <https://github.com/coleifer/vedis-python>`_ allows ``Vedis`` to be embedded in your Python apps. To install ``vedis-python``, you can use ``pip``:\n\n.. code-block:: console\n\n $ pip install vedis\n\nUsing with Walrus\n^^^^^^^^^^^^^^^^^\n\nTo use ``Vedis`` instead of Redis in your ``walrus`` application, simply use the ``WalrusVedis`` in place of the usual :py:class:`Walrus` object:\n\n.. code-block:: python\n\n from walrus.tusks.vedisdb import WalrusVedis\n\n walrus = WalrusVedis('/path/to/database.db')\n\n``WalrusVedis`` can also be used as an in-memory database by omitting a path to a database file when instantiating, or by passing the special string ``':memory:'``:\n\n.. code-block:: python\n\n from walrus.tusks.vedisdb import WalrusVedis\n\n walrus_mem_db = WalrusVedis(':memory:')\n\nWriting a custom command\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nOne of the neat features of ``Vedis`` is the ease with which you can write your own commands. Here are a couple examples:\n\n.. code-block:: python\n\n from walrus.tusks.vedisdb import WalrusVedis\n\n db = WalrusVedis() # Create an in-memory database.\n\n @db.command('SUNION') # Vedis supports SDIFF and SINTER, but not SUNION.\n def sunion(context, key1, key2):\n return list(db.smembers(key1) | db.smembers(key2))\n\n @db.command('KTITLE') # Access the low-level key/value store via the context.\n def ktitle(context, source, dest_key):\n source_val = context[source]\n if source_val:\n context[dest_key] = source_val.title()\n return True\n return False\n\nWe can use these commands like so:\n\n.. code-block:: pycon\n\n >>> s1 = db.Set('s1')\n >>> s1.add(*range(3))\n 3\n >>> s2.add(*range(1, 5))\n 4\n >>> db.SUNION('s1', 's2')\n ['1', '0', '3', '2', '4']\n\n >>> db['user.1.username'] = 'charles'\n >>> db.KTITLE('user.1.username', 'user.1.display_name')\n 1\n >>> print(db['user.1.display_name'])\n Charles\n\nLedis\n-----\n\n`ledis <https://ledisdb.io/>`_ is a Redis-like database written in Golang.\n\nThe project's features are:\n\n* **Supports virtually every Redis command**.\n* Supports multiple backends, including LevelDB, RocksDB, LMDB, BoltDB and in-memory databases.\n* Data storage is not limited by RAM, since the databases are disk-based.\n* Transactions.\n* Supports the Redis protocol for communication, so most Redis clients work with Ledis.\n* Written in golang, easy to deploy.\n\nUse-cases for ``ledisdb``:\n\n* Store data-sets that exceed RAM.\n* Use with LevelDB, RocksDB, etc.\n\nPython bindings\n^^^^^^^^^^^^^^^\n\n`ledis-py <https://github.com/holys/ledis-py>`_ allows you to connect to ``ledisdb``. To install ``ledis-py``, you can use ``pip``:\n\n.. code-block:: console\n\n $ pip install ledis\n\nUsing with Walrus\n^^^^^^^^^^^^^^^^^\n\nTo use ``ledisdb`` instead of Redis in your ``walrus`` application, simply use the ``WalrusLedis`` in place of the usual :py:class:`Walrus` object:\n\n.. code-block:: python\n\n from walrus.tusks.ledisdb import WalrusLedis\n\n walrus = WalrusLedis()\n" }, { "alpha_fraction": 0.5897142887115479, "alphanum_fraction": 0.5954285860061646, "avg_line_length": 32.01886749267578, "blob_id": "f077c25ba806b4ab445104ff8b694fe9ec73b71b", "content_id": "aebb0fce6eba6dbd305ab8aef52b13ee3672458f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1750, "license_type": "permissive", "max_line_length": 79, "num_lines": 53, "path": "/runtests.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport optparse\nimport os\nimport sys\nimport unittest\n\ndef runtests(verbose=False, failfast=False, names=None):\n if names:\n suite = unittest.TestLoader().loadTestsFromNames(names, tests)\n else:\n suite = unittest.TestLoader().loadTestsFromModule(tests)\n runner = unittest.TextTestRunner(verbosity=2 if verbose else 1,\n failfast=failfast)\n return runner.run(suite)\n\nif __name__ == '__main__':\n try:\n from redis import Redis\n except ImportError:\n raise RuntimeError('redis-py must be installed.')\n else:\n try:\n Redis().info()\n except:\n raise RuntimeError('redis server does not appear to be running')\n\n parser = optparse.OptionParser()\n parser.add_option('-v', '--verbose', action='store_true', default=False,\n dest='verbose', help='Verbose output.')\n parser.add_option('-f', '--failfast', action='store_true', default=False,\n help='Stop on first failure or error.')\n parser.add_option('-s', '--stream', action='store_true', dest='stream',\n help='Run stream command tests (default if server>=5.0)')\n parser.add_option('-z', '--zpop', action='store_true', dest='zpop',\n help='Run ZPOP* tests (default if server>=5.0)')\n options, args = parser.parse_args()\n if options.stream:\n os.environ['TEST_STREAM'] = '1'\n if options.zpop:\n os.environ['TEST_ZPOP'] = '1'\n\n from walrus import tests\n\n result = runtests(\n verbose=options.verbose,\n failfast=options.failfast,\n names=args)\n\n if result.failures:\n sys.exit(1)\n elif result.errors:\n sys.exit(2)\n" }, { "alpha_fraction": 0.6414141654968262, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 23.75, "blob_id": "d893d8da0844b834c9c5a41fb79b469749e6f442", "content_id": "e0cffe9162e4f630be4037e6e26b6f1185b3bc48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 198, "license_type": "permissive", "max_line_length": 45, "num_lines": 8, "path": "/walrus/scripts/lock_acquire.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal lock_id = ARGV[1]\nlocal ttl = tonumber(ARGV[2])\nlocal ret = redis.call('setnx', key, lock_id)\nif ret == 1 and ttl > 0 then\n redis.call('pexpire', key, ttl)\nend\nreturn ret\n" }, { "alpha_fraction": 0.5618416666984558, "alphanum_fraction": 0.5668688416481018, "avg_line_length": 35.430233001708984, "blob_id": "a29d771897fbeb4272c682ddb3c64338c61bb817", "content_id": "9732b845b92e57cd31eaef3f406576d6379a8d3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12532, "license_type": "permissive", "max_line_length": 78, "num_lines": 344, "path": "/walrus/autocomplete.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import json\nimport re\n\nfrom walrus.utils import decode\nfrom walrus.utils import encode\nfrom walrus.utils import load_stopwords\nfrom walrus.utils import PY3\n\n\nclass Autocomplete(object):\n \"\"\"\n Autocompletion for ascii-encoded string data. Titles are stored,\n along with any corollary data in Redis. Substrings of the title\n are stored in sorted sets using a unique scoring algorithm. The\n scoring algorithm aims to return results in a sensible order,\n by looking at the entire title and the position of the matched\n substring within the title.\n\n Additionally, the autocomplete object supports boosting search\n results by object ID or object type.\n \"\"\"\n def __init__(self, database, namespace='walrus', cache_timeout=600,\n stopwords_file='stopwords.txt', use_json=True):\n \"\"\"\n :param database: A :py:class:`Database` instance.\n :param namespace: Namespace to prefix keys used to store\n metadata.\n :param cache_timeout: Complex searches using boosts will be\n cached. Specify the amount of time these results are\n cached for.\n :param stopwords_file: Filename containing newline-separated\n stopwords. Set to `None` to disable stopwords filtering.\n :param bool use_json: Whether object data should be\n serialized as JSON.\n \"\"\"\n self.database = database\n self.namespace = namespace\n self._cache_timeout = cache_timeout\n self._stopwords_file = stopwords_file\n self._use_json = use_json\n self._load_stopwords()\n\n self._data = self.database.Hash('%s:d' % self.namespace)\n self._title_data = self.database.Hash('%s:t' % self.namespace)\n self._boosts = self.database.Hash('%s:b' % self.namespace)\n\n self._max_title = 10\n self._offset = self.score_token('z' * self._max_title) + 1\n\n def _load_stopwords(self):\n if self._stopwords_file:\n stopwords = load_stopwords(self._stopwords_file)\n self._stopwords = set(stopwords.splitlines())\n else:\n self._stopwords = set()\n\n def tokenize_title(self, phrase, stopwords=True):\n if isinstance(phrase, bytes):\n phrase = decode(phrase)\n phrase = re.sub('[^a-z0-9_\\-\\s]', '', phrase.lower())\n if stopwords and self._stopwords:\n return [w for w in phrase.split() if w not in self._stopwords]\n else:\n return phrase.split()\n\n def score_token(self, token):\n l = len(token)\n a = ord('a') - 2\n score = 0\n\n for i in range(self._max_title):\n if i < l:\n c = ord(token[i]) - a\n if c < 2 or c > 27:\n c = 1\n else:\n c = 1\n score += c * (27 ** (self._max_title - i - 1))\n\n return score\n\n def substrings(self, w):\n for i in range(1, len(w)):\n yield w[:i]\n yield w\n\n def object_key(self, obj_id, obj_type):\n return '%s\\x01%s' % (obj_id, obj_type or '')\n\n def word_key(self, word):\n return '%s:s:%s' % (self.namespace, word)\n\n def store(self, obj_id, title=None, data=None, obj_type=None):\n \"\"\"\n Store data in the autocomplete index.\n\n :param obj_id: Either a unique identifier for the object\n being indexed or the word/phrase to be indexed.\n :param title: The word or phrase to be indexed. If not\n provided, the ``obj_id`` will be used as the title.\n :param data: Arbitrary data to index, which will be\n returned when searching for results. If not provided,\n this value will default to the title being indexed.\n :param obj_type: Optional object type. Since results can be\n boosted by type, you might find it useful to specify this\n when storing multiple types of objects.\n\n You have the option of storing several types of data as\n defined by the parameters. At the minimum, you can specify\n an ``obj_id``, which will be the word or phrase you wish to\n index. Alternatively, if for instance you were indexing blog\n posts, you might specify all parameters.\n \"\"\"\n if title is None:\n title = obj_id\n if data is None:\n data = title\n obj_type = obj_type or ''\n\n if self._use_json:\n data = json.dumps(data)\n\n combined_id = self.object_key(obj_id, obj_type)\n\n if self.exists(obj_id, obj_type):\n stored_title = self._title_data[combined_id]\n if stored_title == title:\n self._data[combined_id] = data\n return\n else:\n self.remove(obj_id, obj_type)\n\n self._data[combined_id] = data\n self._title_data[combined_id] = title\n\n clean_title = ' '.join(self.tokenize_title(title))\n title_score = self.score_token(clean_title)\n\n for idx, word in enumerate(self.tokenize_title(title)):\n word_score = self.score_token(word)\n position_score = word_score + (self._offset * idx)\n key_score = position_score + title_score\n for substring in self.substrings(word):\n self.database.zadd(self.word_key(substring),\n {combined_id: key_score})\n\n return True\n\n def remove(self, obj_id, obj_type=None):\n \"\"\"\n Remove an object identified by the given ``obj_id`` (and\n optionally ``obj_type``) from the search index.\n\n :param obj_id: The object's unique identifier.\n :param obj_type: The object's type.\n \"\"\"\n if not self.exists(obj_id, obj_type):\n raise KeyError('Object not found.')\n\n combined_id = self.object_key(obj_id, obj_type)\n title = self._title_data[combined_id]\n\n for word in self.tokenize_title(title):\n for substring in self.substrings(word):\n key = self.word_key(substring)\n if not self.database.zrange(key, 1, 2):\n self.database.delete(key)\n else:\n self.database.zrem(key, combined_id)\n\n del self._data[combined_id]\n del self._title_data[combined_id]\n del self._boosts[combined_id]\n\n def exists(self, obj_id, obj_type=None):\n \"\"\"\n Return whether the given object exists in the search index.\n\n :param obj_id: The object's unique identifier.\n :param obj_type: The object's type.\n \"\"\"\n return self.object_key(obj_id, obj_type) in self._data\n\n def boost_object(self, obj_id=None, obj_type=None, multiplier=1.1,\n relative=True):\n \"\"\"\n Boost search results for the given object or type by the\n amount specified. When the ``multiplier`` is greater than\n 1, the results will percolate to the top. Values between\n 0 and 1 will percolate results to the bottom.\n\n Either an ``obj_id`` or ``obj_type`` (or both) must be\n specified.\n\n :param obj_id: An object's unique identifier (optional).\n :param obj_type: The object's type (optional).\n :param multiplier: A positive floating-point number.\n :param relative: If ``True``, then any pre-existing saved\n boost will be updated using the given multiplier.\n\n Examples:\n\n .. code-block:: python\n\n # Make all objects of type=photos percolate to top.\n ac.boost_object(obj_type='photo', multiplier=2.0)\n\n # Boost a particularly popular blog entry.\n ac.boost_object(\n popular_entry.id,\n 'entry',\n multipler=5.0,\n relative=False)\n \"\"\"\n combined_id = self.object_key(obj_id or '', obj_type or '')\n if relative:\n current = float(self._boosts[combined_id] or 1.0)\n self._boosts[combined_id] = current * multiplier\n else:\n self._boosts[combined_id] = multiplier\n\n def _load_objects(self, obj_id_zset, limit, chunk_size=1000):\n ct = i = 0\n while True:\n id_chunk = obj_id_zset[i:i + chunk_size]\n if not id_chunk:\n return\n\n i += chunk_size\n for raw_data in self._data[id_chunk]:\n if not raw_data:\n continue\n if self._use_json:\n yield json.loads(decode(raw_data))\n else:\n yield raw_data\n ct += 1\n if limit and ct == limit:\n return\n\n def _load_saved_boosts(self):\n boosts = {}\n for combined_id, score in self._boosts:\n obj_id, obj_type = combined_id.split(encode('\\x01'), 1)\n score = float(score)\n if obj_id and obj_type:\n boosts[combined_id] = score\n elif obj_id:\n boosts[obj_id] = score\n elif obj_type:\n boosts[obj_type] = score\n return boosts\n\n def search(self, phrase, limit=None, boosts=None, chunk_size=1000):\n \"\"\"\n Perform a search for the given phrase. Objects whose title\n matches the search will be returned. The values returned\n will be whatever you specified as the ``data`` parameter\n when you called :py:meth:`~Autocomplete.store`.\n\n :param phrase: One or more words or substrings.\n :param int limit: Limit size of the result set.\n :param dict boosts: A mapping of object id/object type to\n floating point multipliers.\n :returns: A list containing the object data for objects\n matching the search phrase.\n \"\"\"\n cleaned = self.tokenize_title(phrase, stopwords=False)\n\n # Remove stopwords except for the last token, which may be a partially\n # typed string that just happens to match a stopword.\n last_token = len(cleaned) - 1\n cleaned = [c for i, c in enumerate(cleaned)\n if (c not in self._stopwords) or (i == last_token)]\n\n if not cleaned:\n return\n\n all_boosts = self._load_saved_boosts()\n if PY3 and boosts:\n for key in boosts:\n all_boosts[encode(key)] = boosts[key]\n elif boosts:\n all_boosts.update(boosts)\n\n if len(cleaned) == 1 and not all_boosts:\n result_key = self.word_key(cleaned[0])\n else:\n result_key = self.get_cache_key(cleaned, all_boosts)\n if result_key not in self.database:\n self.database.zinterstore(\n result_key,\n list(map(self.word_key, cleaned)))\n self.database.expire(result_key, self._cache_timeout)\n\n results = self.database.ZSet(result_key)\n if all_boosts:\n for raw_id, score in results[0:0, True]:\n orig_score = score\n for identifier in raw_id.split(encode('\\x01'), 1):\n if identifier and identifier in all_boosts:\n score *= 1 / all_boosts[identifier]\n\n if orig_score != score:\n results[raw_id] = score\n\n for result in self._load_objects(results, limit, chunk_size):\n yield result\n\n def get_cache_key(self, phrases, boosts):\n if boosts:\n boost_key = '|'.join(sorted(\n '%s:%s' % (k, v) for k, v in boosts.items()))\n else:\n boost_key = ''\n phrase_key = '|'.join(phrases)\n return '%s:c:%s:%s' % (self.namespace, phrase_key, boost_key)\n\n def list_data(self):\n \"\"\"\n Return all the data stored in the autocomplete index. If the data was\n stored as serialized JSON, then it will be de-serialized before being\n returned.\n\n :rtype: list\n \"\"\"\n fn = (lambda v: json.loads(decode(v))) if self._use_json else decode\n return map(fn, self._data.values())\n\n def list_titles(self):\n \"\"\"\n Return the titles of all objects stored in the autocomplete index.\n\n :rtype: list\n \"\"\"\n return map(decode, self._title_data.values())\n\n def flush(self, batch_size=1000):\n \"\"\"\n Delete all autocomplete indexes and metadata.\n \"\"\"\n keys = self.database.keys(self.namespace + ':*')\n for i in range(0, len(keys), batch_size):\n self.database.delete(*keys[i:i + batch_size])\n" }, { "alpha_fraction": 0.518540620803833, "alphanum_fraction": 0.5704065561294556, "avg_line_length": 39.912193298339844, "blob_id": "035507480bf7eea1806ded49c68ef710c5a548d6", "content_id": "70b02154d9b4213fc6d3aeb29c41d836a4e073c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8387, "license_type": "permissive", "max_line_length": 79, "num_lines": 205, "path": "/walrus/tests/streams.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import datetime\nimport unittest\n\nfrom walrus.streams import TimeSeries\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\nfrom walrus.tests.base import stream_test\n\n\nclass TestTimeSeries(WalrusTestCase):\n def setUp(self):\n super(TestTimeSeries, self).setUp()\n for key in ('sa', 'sb', 'sc'):\n db.delete('key')\n\n self.ts = TimeSeries(db, 'cgabc', {'sa': '0', 'sb': '0', 'sc': '0'},\n consumer='ts1')\n\n def _create_test_data(self):\n start = datetime.datetime(2018, 1, 1)\n id_list = []\n keys = ('sa', 'sb', 'sc')\n for i in range(0, 10):\n tskey = getattr(self.ts, keys[i % 3])\n ts = start + datetime.timedelta(days=i)\n id_list.append(tskey.add({'k': '%s-%s' % (keys[i % 3], i)}, id=ts))\n return id_list\n\n def assertMessages(self, results, expected_ids):\n rdata = [(r.stream, r.timestamp, r.data) for r in results]\n streams = ('sa', 'sb', 'sc')\n edata = [(streams[i % 3], datetime.datetime(2018, 1, i + 1),\n {'k': '%s-%s' % (streams[i % 3], i)}) for i in expected_ids]\n self.assertEqual(rdata, edata)\n\n @stream_test\n def test_timeseries_ranges(self):\n docids = self._create_test_data()\n\n self.ts.create()\n self.assertMessages(self.ts.sa.range(), [0, 3, 6, 9])\n self.assertMessages(self.ts.sb.range(), [1, 4, 7])\n self.assertMessages(self.ts.sc.range(), [2, 5, 8])\n self.assertMessages(self.ts.sc.range(count=2), [2, 5])\n\n self.assertMessages(self.ts.sa[:docids[4]], [0, 3])\n self.assertMessages(self.ts.sb[:docids[4]], [1, 4])\n self.assertMessages(self.ts.sa[docids[4]:], [6, 9])\n self.assertMessages(self.ts.sb[docids[4]:], [4, 7])\n\n self.assertMessages([self.ts.sa.get(docids[6])], [6])\n self.assertMessages([self.ts.sa.get(docids[9])], [9])\n self.assertMessages([self.ts.sc.get(docids[5])], [5])\n self.assertTrue(self.ts.sa.get(docids[5]) is None)\n self.assertTrue(self.ts.sb.get(docids[5]) is None)\n\n # Trim sa down to 2 items.\n self.assertEqual(self.ts.sa.trim(2, False), 2)\n self.assertMessages(self.ts.sa.range(), [6, 9])\n self.assertMessages(self.ts.sa.range(count=1), [6])\n self.assertMessages(self.ts.streams['sa'].range(count=1), [6])\n\n @stream_test\n def test_timeseries_read(self):\n self._create_test_data()\n self.ts.create()\n self.assertMessages(self.ts.read(count=1), [0, 1, 2])\n self.assertMessages(self.ts.read(count=1), [3, 4, 5])\n self.assertMessages(self.ts.read(count=2), [6, 7, 8, 9])\n self.assertEqual(self.ts.read(), [])\n\n # Trim the 0-th item off of sa and reset all streams.\n self.ts.sa.trim(3, False)\n self.ts.reset()\n self.assertMessages(self.ts.read(), list(range(1, 10)))\n\n # Trim the first two items from sc (2 and 5), then set the date so\n # we've read the first item from each queue. Next read will be 4.\n self.ts.sc.trim(1, False)\n self.ts.sb.delete(datetime.datetime(2018, 1, 8)) # Delete item 7.\n self.ts.set_id(datetime.datetime(2018, 1, 4))\n self.assertMessages(self.ts.read(), [4, 6, 8, 9])\n\n @stream_test\n def test_adding(self):\n self._create_test_data()\n self.ts.create()\n resp = self.ts.set_id()\n self.assertEqual(resp, {'sa': True, 'sb': True, 'sc': True})\n\n # We can add another record to the max ts if we increment the seq.\n r = self.ts.sa.add({'k': 'sa-10'}, (datetime.datetime(2018, 1, 10), 1))\n self.assertEqual(r, (datetime.datetime(2018, 1, 10), 1))\n\n r = self.ts.sb.add({'k': 'sb-11'}, (datetime.datetime(2018, 1, 10), 2))\n self.assertEqual(r, (datetime.datetime(2018, 1, 10), 2))\n\n self.assertEqual(len(self.ts.sa), 5)\n self.assertEqual(len(self.ts.sb), 4)\n self.assertEqual(len(self.ts.sc), 3)\n\n # Read the newly-added records.\n r10, r11 = self.ts.read()\n self.assertEqual(r10.timestamp, datetime.datetime(2018, 1, 10))\n self.assertEqual(r10.sequence, 1)\n self.assertEqual(r10.stream, 'sa')\n self.assertEqual(r10.data, {'k': 'sa-10'})\n self.assertEqual(r11.timestamp, datetime.datetime(2018, 1, 10))\n self.assertEqual(r11.sequence, 2)\n self.assertEqual(r11.stream, 'sb')\n self.assertEqual(r11.data, {'k': 'sb-11'})\n\n @stream_test\n def test_timeseries_stream_read(self):\n self._create_test_data()\n self.ts.create()\n\n # Read two from sa, one from sc, then read 2x from all. Messages that\n # were read will not be re-read.\n self.assertMessages(self.ts.sa.read(count=2), [0, 3])\n self.assertMessages(self.ts.sc.read(count=1), [2])\n self.assertMessages(self.ts.read(count=2), [1, 4, 5, 6, 8, 9])\n self.assertMessages(self.ts.read(count=1), [7])\n for s in (self.ts.sa, self.ts.sb, self.ts.sc):\n self.assertEqual(s.read(), [])\n\n # Re-set the ID of stream b. Other streams are unaffected, so we just\n # re-read items from stream b.\n self.ts.sb.set_id(datetime.datetime(2018, 1, 4))\n self.assertMessages(self.ts.read(), [4, 7])\n\n # Re-set the ID of stream a and trim.\n self.ts.sa.set_id('0')\n self.ts.sa.trim(2, False)\n self.assertMessages(self.ts.read(), [6, 9])\n\n @stream_test\n def test_ack_claim_pending(self):\n self._create_test_data()\n self.ts.create()\n ts1 = self.ts\n ts2 = ts1.consumer('ts2')\n\n # Read items 0, 1, 3, and 4.\n self.assertMessages(ts1.sa.read(1), [0])\n self.assertMessages(ts2.sb.read(2), [1, 4])\n self.assertMessages(ts2.sa.read(1), [3])\n\n def assertPending(resp, expected):\n clean = [(r[0][0], r[1], r[3]) for r in resp]\n self.assertEqual(clean, expected)\n\n # Check pending status. sa was read by ts1 first, then ts2.\n assertPending(ts1.sa.pending(), [\n (datetime.datetime(2018, 1, 1), 'ts1', 1),\n (datetime.datetime(2018, 1, 4), 'ts2', 1)])\n assertPending(ts1.sa.pending(consumer='ts1'), [\n (datetime.datetime(2018, 1, 1), 'ts1', 1)])\n assertPending(ts1.sa.pending(consumer='ts2'), [\n (datetime.datetime(2018, 1, 4), 'ts2', 1)])\n\n # sb was read by ts2 only.\n assertPending(ts1.sb.pending(), [\n (datetime.datetime(2018, 1, 2), 'ts2', 1),\n (datetime.datetime(2018, 1, 5), 'ts2', 1)])\n\n # Acknowledge receipt. Although we read the Jan 4th item from \"sa\"\n # using ts2, we can still acknowledge it from ts1.\n self.assertEqual(ts1.sa.ack(datetime.datetime(2018, 1, 4)), 1)\n self.assertEqual(ts2.sb.ack(datetime.datetime(2018, 1, 2),\n datetime.datetime(2018, 1, 5)), 2)\n\n # Verify pending removed.\n assertPending(ts1.sa.pending(), [\n (datetime.datetime(2018, 1, 1), 'ts1', 1)])\n assertPending(ts2.sb.pending(), [])\n\n # Claim the first message for consumer ts2.\n resp = ts2.sa.claim(datetime.datetime(2018, 1, 1))\n self.assertMessages(resp, [0])\n\n # Pending is now marked for ts2, ack'd, and removed.\n assertPending(ts1.sa.pending(), [\n (datetime.datetime(2018, 1, 1), 'ts2', 2)])\n self.assertEqual(ts2.sa.ack(datetime.datetime(2018, 1, 1)), 1)\n assertPending(ts2.sa.pending(), [])\n\n # Read the rest from consumer ts2 and verify pending.\n self.assertMessages(ts2.read(), [2, 5, 6, 7, 8, 9])\n assertPending(ts2.sa.pending(), [\n (datetime.datetime(2018, 1, 7), 'ts2', 1),\n (datetime.datetime(2018, 1, 10), 'ts2', 1)])\n assertPending(ts2.sb.pending(), [\n (datetime.datetime(2018, 1, 8), 'ts2', 1)])\n assertPending(ts2.sc.pending(), [\n (datetime.datetime(2018, 1, 3), 'ts2', 1),\n (datetime.datetime(2018, 1, 6), 'ts2', 1),\n (datetime.datetime(2018, 1, 9), 'ts2', 1)])\n\n # Claim the records in sc for ts1.\n resp = ts1.sc.claim(\n datetime.datetime(2018, 1, 3),\n datetime.datetime(2018, 1, 6),\n datetime.datetime(2018, 1, 9))\n self.assertMessages(resp, [2, 5, 8])\n" }, { "alpha_fraction": 0.6215064525604248, "alphanum_fraction": 0.6220177412033081, "avg_line_length": 35.67499923706055, "blob_id": "2c8ae71535eb81c218a1bc1db55cf1b589595655", "content_id": "5a2873752fde2cec631f036f87f1a8b78503187e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5868, "license_type": "permissive", "max_line_length": 79, "num_lines": 160, "path": "/walrus/fts.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from walrus.query import Executor\nfrom walrus.query import OP_MATCH\nfrom walrus.query import parse\nfrom walrus.utils import decode\nfrom walrus.utils import decode_dict\nfrom walrus.search import Tokenizer\n\n\nclass Index(object):\n \"\"\"\n Full-text search index.\n\n Store documents, along with arbitrary metadata, and perform full-text\n search on the document content. Supports porter-stemming, stopword\n filtering, basic result ranking, and (optionally) double-metaphone for\n phonetic search.\n \"\"\"\n def __init__(self, db, name, **tokenizer_settings):\n \"\"\"\n :param Database db: a walrus database object.\n :param str name: name for the search index.\n :param bool stemmer: use porter stemmer (default True).\n :param bool metaphone: use double metaphone (default False).\n :param str stopwords_file: defaults to walrus stopwords.txt.\n :param int min_word_length: specify minimum word length.\n\n Create a search index for storing and searching documents.\n \"\"\"\n self.db = db\n self.name = name\n self.tokenizer = Tokenizer(**tokenizer_settings)\n self.members = self.db.Set('fts.%s' % self.name)\n\n def get_key(self, word):\n return self.db.ZSet('fts.%s.%s' % (self.name, word))\n\n def _get_hash(self, document_id):\n return self.db.Hash('doc.%s.%s' % (self.name, decode(document_id)))\n\n def get_document(self, document_id):\n \"\"\"\n :param document_id: Document unique identifier.\n :returns: a dictionary containing the document content and\n any associated metadata.\n \"\"\"\n key = 'doc.%s.%s' % (self.name, decode(document_id))\n return decode_dict(self.db.hgetall(key))\n\n def add(self, key, content, __metadata=None, **metadata):\n \"\"\"\n :param key: Document unique identifier.\n :param str content: Content to store and index for search.\n :param metadata: Arbitrary key/value pairs to store for document.\n\n Add a document to the search index.\n \"\"\"\n if __metadata is None:\n __metadata = metadata\n elif metadata:\n __metadata.update(metadata)\n\n if not isinstance(key, str):\n key = str(key)\n\n self.members.add(key)\n document_hash = self._get_hash(key)\n document_hash.update(__metadata, content=content)\n\n for word, score in self.tokenizer.tokenize(content).items():\n word_key = self.get_key(word)\n word_key[key] = -score\n\n def remove(self, key, preserve_data=False):\n \"\"\"\n :param key: Document unique identifier.\n\n Remove the document from the search index.\n \"\"\"\n if not isinstance(key, str):\n key = str(key)\n\n if self.members.remove(key) != 1:\n raise KeyError('Document with key \"%s\" not found.' % key)\n document_hash = self._get_hash(key)\n content = decode(document_hash['content'])\n if not preserve_data:\n document_hash.clear()\n\n for word in self.tokenizer.tokenize(content):\n word_key = self.get_key(word)\n del word_key[key]\n if len(word_key) == 0:\n word_key.clear()\n\n def update(self, key, content, __metadata=None, **metadata):\n \"\"\"\n :param key: Document unique identifier.\n :param str content: Content to store and index for search.\n :param metadata: Arbitrary key/value pairs to store for document.\n\n Update the given document. Existing metadata will be preserved and,\n optionally, updated with the provided metadata.\n \"\"\"\n self.remove(key, preserve_data=True)\n self.add(key, content, __metadata, **metadata)\n\n def replace(self, key, content, __metadata=None, **metadata):\n \"\"\"\n :param key: Document unique identifier.\n :param str content: Content to store and index for search.\n :param metadata: Arbitrary key/value pairs to store for document.\n\n Update the given document. Existing metadata will not be removed and\n replaced with the provided metadata.\n \"\"\"\n self.remove(key)\n self.add(key, content, __metadata, **metadata)\n\n def get_index(self, op):\n assert op == OP_MATCH\n return self\n\n def db_value(self, value):\n return value\n\n def _search(self, query):\n expression = parse(query, self)\n if expression is None:\n return [(member, 0) for member in self.members]\n executor = Executor(self.db)\n return executor.execute(expression)\n\n def search(self, query):\n \"\"\"\n :param str query: Search query. May contain boolean/set operations\n and parentheses.\n :returns: a list of document hashes corresponding to matching\n documents.\n\n Search the index. The return value is a list of dictionaries\n corresponding to the documents that matched. These dictionaries contain\n a ``content`` key with the original indexed content, along with any\n additional metadata that was specified.\n \"\"\"\n return [self.get_document(key) for key, _ in self._search(query)]\n\n def search_items(self, query):\n \"\"\"\n :param str query: Search query. May contain boolean/set operations\n and parentheses.\n :returns: a list of (key, document hashes) tuples corresponding to\n matching documents.\n\n Search the index. The return value is a list of (key, document dict)\n corresponding to the documents that matched. These dictionaries contain\n a ``content`` key with the original indexed content, along with any\n additional metadata that was specified.\n \"\"\"\n return [(decode(key), self.get_document(key))\n for key, _ in self._search(query)]\n" }, { "alpha_fraction": 0.7156862616539001, "alphanum_fraction": 0.7392156720161438, "avg_line_length": 29, "blob_id": "446cc1ce95c057fcca99ee89d1d4b3ca04fe0a99", "content_id": "06f1c56e73d86f7100ccac403c026dc91f809e33", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 510, "license_type": "permissive", "max_line_length": 153, "num_lines": 17, "path": "/docs/contributing.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _contributing:\n\nContributing\n============\n\nI'd love help making walrus a better, more useful library so if you have any questions, comments or suggestions please feel free to open a GitHub ticket:\n\nhttps://github.com/coleifer/walrus/issues/new\n\nFound a bug?\n------------\n\n.. image:: http://media.charlesleifer.com/blog/photos/p1420743625.21.png\n\nIf you think you've found a bug in walrus, please create a GitHub ticket and include any traceback if applicable.\n\nhttps://github.com/coleifer/walrus/issues/new\n" }, { "alpha_fraction": 0.4247320890426636, "alphanum_fraction": 0.42609286308288574, "avg_line_length": 30.778377532958984, "blob_id": "6284a3319a405531836c740370d4d38a573b97cf", "content_id": "6b07a4e4459bb328ec907241fa06fe2e531f86ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5879, "license_type": "permissive", "max_line_length": 71, "num_lines": 185, "path": "/walrus/tests/graph.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass TestGraph(WalrusTestCase):\n def setUp(self):\n super(TestGraph, self).setUp()\n # Limit to 5 events per second.\n self.g = db.graph('test-graph')\n\n def create_graph_data(self):\n data = (\n ('charlie', 'likes', 'huey'),\n ('charlie', 'likes', 'mickey'),\n ('charlie', 'likes', 'zaizee'),\n ('charlie', 'is', 'human'),\n ('connor', 'likes', 'huey'),\n ('connor', 'likes', 'mickey'),\n ('huey', 'eats', 'catfood'),\n ('huey', 'is', 'cat'),\n ('mickey', 'eats', 'anything'),\n ('mickey', 'is', 'dog'),\n ('zaizee', 'eats', 'catfood'),\n ('zaizee', 'is', 'cat'),\n )\n self.g.store_many(data)\n\n def create_friends(self):\n data = (\n ('charlie', 'friend', 'huey'),\n ('huey', 'friend', 'charlie'),\n ('huey', 'friend', 'mickey'),\n ('zaizee', 'friend', 'charlie'),\n ('zaizee', 'friend', 'mickey'),\n ('mickey', 'friend', 'nuggie'),\n )\n for item in data:\n self.g.store(*item)\n\n def test_search_extended(self):\n self.create_graph_data()\n X = self.g.v.x\n Y = self.g.v.y\n Z = self.g.v.z\n result = self.g.search(\n (X, 'likes', Y),\n (Y, 'is', 'cat'),\n (Z, 'likes', Y))\n self.assertEqual(result['x'], set(['charlie', 'connor']))\n self.assertEqual(result['y'], set(['huey', 'zaizee']))\n self.assertEqual(result['z'], set(['charlie', 'connor']))\n\n self.g.store_many((\n ('charlie', 'likes', 'connor'),\n ('connor', 'likes', 'charlie'),\n ('connor', 'is', 'baby'),\n ('connor', 'is', 'human'),\n ('nash', 'is', 'baby'),\n ('nash', 'is', 'human'),\n ('connor', 'lives', 'ks'),\n ('nash', 'lives', 'nv'),\n ('charlie', 'lives', 'ks')))\n\n result = self.g.search(\n ('charlie', 'likes', X),\n (X, 'is', 'baby'),\n (X, 'lives', 'ks'))\n self.assertEqual(result, {'x': set(['connor'])})\n\n result = self.g.search(\n (X, 'is', 'baby'),\n (X, 'likes', Y),\n (Y, 'lives', 'ks'))\n self.assertEqual(result, {\n 'x': set(['connor']),\n 'y': set(['charlie']),\n })\n\n def assertTriples(self, result, expected):\n result = list(result)\n self.assertEqual(len(result), len(expected))\n for i1, i2 in zip(result, expected):\n self.assertEqual(\n (i1['s'], i1['p'], i1['o']), i2)\n\n def test_query(self):\n self.create_graph_data()\n res = self.g.query()\n self.assertTriples(res, (\n ('charlie', 'is', 'human'),\n ('charlie', 'likes', 'huey'),\n ('charlie', 'likes', 'mickey'),\n ('charlie', 'likes', 'zaizee'),\n ('connor', 'likes', 'huey'),\n ('connor', 'likes', 'mickey'),\n ('huey', 'eats', 'catfood'),\n ('huey', 'is', 'cat'),\n ('mickey', 'eats', 'anything'),\n ('mickey', 'is', 'dog'),\n ('zaizee', 'eats', 'catfood'),\n ('zaizee', 'is', 'cat'),\n ))\n\n res = self.g.query('charlie', 'likes')\n self.assertTriples(res, (\n ('charlie', 'likes', 'huey'),\n ('charlie', 'likes', 'mickey'),\n ('charlie', 'likes', 'zaizee'),\n ))\n\n res = self.g.query(p='is', o='cat')\n self.assertTriples(res, (\n ('huey', 'is', 'cat'),\n ('zaizee', 'is', 'cat'),\n ))\n\n res = self.g.query(s='huey')\n self.assertTriples(res, (\n ('huey', 'eats', 'catfood'),\n ('huey', 'is', 'cat'),\n ))\n\n res = self.g.query(o='huey')\n self.assertTriples(res, (\n ('charlie', 'likes', 'huey'),\n ('connor', 'likes', 'huey'),\n ))\n\n res = self.g.query(s='does-not-exist')\n self.assertTriples(res, [])\n\n res = self.g.query(s='huey', p='is', o='x')\n self.assertTriples(res, [])\n\n def test_search(self):\n self.create_graph_data()\n X = self.g.v('x')\n result = self.g.search(\n {'s': 'charlie', 'p': 'likes', 'o': X},\n {'s': X, 'p': 'eats', 'o': 'catfood'},\n {'s': X, 'p': 'is', 'o': 'cat'})\n self.assertEqual(result, {'x': set(['huey', 'zaizee'])})\n\n def test_search_simple(self):\n self.create_friends()\n X = self.g.v('x')\n result = self.g.search({'s': X, 'p': 'friend', 'o': 'charlie'})\n self.assertEqual(result, {'x': set(['huey', 'zaizee'])})\n\n def test_search_2var(self):\n self.create_friends()\n X = self.g.v('x')\n Y = self.g.v('y')\n\n result = self.g.search(\n {'s': X, 'p': 'friend', 'o': 'charlie'},\n {'s': Y, 'p': 'friend', 'o': X})\n self.assertEqual(result, {\n 'x': set(['huey']),\n 'y': set(['charlie']),\n })\n\n result = self.g.search(\n ('charlie', 'friend', X),\n (X, 'friend', Y),\n (Y, 'friend', 'nuggie'))\n self.assertEqual(result, {\n 'x': set(['huey']),\n 'y': set(['mickey']),\n })\n\n result = self.g.search(\n ('huey', 'friend', X),\n (X, 'friend', Y))\n self.assertEqual(result['y'], set(['huey', 'nuggie']))\n\n def test_search_mutual(self):\n self.create_friends()\n X = self.g.v('x')\n Y = self.g.v('y')\n\n result = self.g.search(\n {'s': X, 'p': 'friend', 'o': Y},\n {'s': Y, 'p': 'friend', 'o': X})\n self.assertEqual(result['y'], set(['charlie', 'huey']))\n" }, { "alpha_fraction": 0.6748299598693848, "alphanum_fraction": 0.6748299598693848, "avg_line_length": 19.41666603088379, "blob_id": "8df90d865813832a75d64d597511d555e57fe7a1", "content_id": "97f86307ee5dd3952c3c4b4adec899b638775b80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 735, "license_type": "permissive", "max_line_length": 90, "num_lines": 36, "path": "/docs/installation.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _installation:\n\nInstalling and Testing\n======================\n\nMost users will want to simply install the latest version, hosted on PyPI:\n\n.. code-block:: console\n\n pip install walrus\n\n\nInstalling with git\n-------------------\n\nThe project is hosted at https://github.com/coleifer/walrus and can be installed\nusing git:\n\n.. code-block:: console\n\n git clone https://github.com/coleifer/walrus.git\n cd walrus\n python setup.py install\n\n.. note::\n On some systems you may need to use ``sudo python setup.py install`` to\n install walrus system-wide.\n\nRunning tests\n-------------\n\nYou can test your installation by running the test suite. Requires a running Redis server.\n\n.. code-block:: console\n\n python runtests.py\n" }, { "alpha_fraction": 0.5269056558609009, "alphanum_fraction": 0.5406030416488647, "avg_line_length": 33.9161491394043, "blob_id": "b4bcd9c01468e6076db5d745fea26630c31c4523", "content_id": "27ac2a5cb8604bf58ff62e101bb9f33fc2c7d3ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11243, "license_type": "permissive", "max_line_length": 79, "num_lines": 322, "path": "/walrus/tests/autocomplete.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import random\n\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass TestAutocomplete(WalrusTestCase):\n test_data = (\n (1, 'testing python'),\n (2, 'testing python code'),\n (3, 'web testing python code'),\n (4, 'unit tests with python'))\n\n def setUp(self):\n super(TestAutocomplete, self).setUp()\n self.ac = db.autocomplete()\n\n def store_test_data(self, id_to_store=None):\n for obj_id, title in self.test_data:\n if id_to_store is None or obj_id == id_to_store:\n self.ac.store(obj_id, title, {\n 'obj_id': obj_id,\n 'title': title,\n 'value': obj_id % 2 == 0 and 'even' or 'odd'})\n\n def sort_results(self, results):\n return sorted(results, key=lambda item: item['obj_id'])\n\n def assertResults(self, results, expected):\n self.assertEqual([result['obj_id'] for result in results], expected)\n\n def test_search(self):\n self.store_test_data()\n\n results = self.ac.search('testing python')\n self.assertList(results, [\n {'obj_id': 1, 'title': 'testing python', 'value': 'odd'},\n {'obj_id': 2, 'title': 'testing python code', 'value': 'even'},\n {'obj_id': 3, 'title': 'web testing python code', 'value': 'odd'},\n ])\n\n results = self.ac.search('test')\n self.assertResults(results, [1, 2, 4, 3])\n\n results = self.ac.search('uni')\n self.assertResults(results, [4])\n\n self.assertList(self.ac.search(''), [])\n self.assertList(self.ac.search('missing'), [])\n self.assertList(self.ac.search('with'), [])\n\n def test_boosting(self):\n letters = ('alpha', 'beta', 'gamma', 'delta')\n n = len(letters)\n test_data = []\n for i in range(n * 3):\n obj_id = i + 1\n obj_type = 't%d' % ((i / n) + 1)\n title = 'test %s' % letters[i % n]\n self.ac.store(\n obj_id,\n title,\n {'obj_id': obj_id, 'title': title},\n obj_type)\n\n def assertBoosts(query, boosts, expected):\n results = self.ac.search(query, boosts=boosts)\n self.assertResults(results, expected)\n\n assertBoosts('alp', None, [1, 5, 9])\n assertBoosts('alp', {'t2': 1.1}, [5, 1, 9])\n assertBoosts('test', {'t3': 1.5, 't2': 1.1}, [\n 9, 10, 12, 11, 5, 6, 8, 7, 1, 2, 4, 3])\n assertBoosts('alp', {'t1': 0.5}, [5, 9, 1])\n assertBoosts('alp', {'t1': 1.5, 't3': 1.6}, [9, 1, 5])\n assertBoosts('alp', {'t3': 1.5, '5': 1.6}, [5, 9, 1])\n\n def test_stored_boosts(self):\n id_to_type = {\n 'aaa': 1,\n 'aab': 2,\n 'aac': 3,\n 'aaab': 4,\n 'bbbb': 4}\n for obj_id, obj_type in id_to_type.items():\n self.ac.store(obj_id, obj_type=obj_type)\n\n self.assertList(self.ac.search('aa'), ['aaa', 'aaab', 'aab', 'aac'])\n\n self.ac.boost_object(obj_type=2, multiplier=2)\n self.assertList(self.ac.search('aa'), ['aab', 'aaa', 'aaab', 'aac'])\n\n self.ac.boost_object('aac', multiplier=3)\n self.assertList(self.ac.search('aa'), ['aac', 'aab', 'aaa', 'aaab'])\n\n results = self.ac.search('aa', boosts={'aac': 1.5})\n self.assertList(results, ['aab', 'aac', 'aaa', 'aaab'])\n\n def test_limit(self):\n self.store_test_data()\n results = self.ac.search('testing', limit=1)\n self.assertResults(results, [1])\n\n results = self.ac.search('testing', limit=2)\n self.assertResults(results, [1, 2])\n\n def test_search_empty(self):\n self.assertList(self.ac.search(''), [])\n\n def test_chunked(self):\n for i in range(25):\n self.ac.store('foo %s' % (chr(i + ord('a')) * 2))\n\n ge = self.ac.search('foo', limit=21, chunk_size=5)\n results = list(ge)\n self.assertEqual(len(results), 21)\n self.assertEqual(results[0], 'foo aa')\n self.assertEqual(results[-1], 'foo uu')\n\n def test_scoring_proximity_to_front(self):\n self.ac.store('aa bb cc')\n self.ac.store('tt cc')\n\n self.assertList(self.ac.search('cc'), ['tt cc', 'aa bb cc'])\n\n self.ac.store('aa b cc')\n self.assertList(self.ac.search('cc'), ['tt cc', 'aa b cc', 'aa bb cc'])\n\n def test_simple(self):\n for _, title in self.test_data:\n self.ac.store(title)\n\n self.assertList(self.ac.search('testing'), [\n 'testing python',\n 'testing python code',\n 'web testing python code'])\n self.assertList(self.ac.search('code'), [\n 'testing python code',\n 'web testing python code'])\n\n self.ac.store('z python code')\n self.assertList(self.ac.search('cod'), [\n 'testing python code',\n 'z python code',\n 'web testing python code'])\n\n def test_sorting(self):\n strings = []\n for i in range(26):\n strings.append('aaaa%s' % chr(i + ord('a')))\n if i > 0:\n strings.append('aaa%sa' % chr(i + ord('a')))\n\n random.shuffle(strings)\n for s in strings:\n self.ac.store(s)\n\n self.assertList(self.ac.search('aaa'), sorted(strings))\n self.assertList(self.ac.search('aaa', limit=30), sorted(strings)[:30])\n\n def test_removing_objects(self):\n self.store_test_data()\n self.ac.remove(1)\n\n self.assertResults(self.ac.search('testing'), [2, 3])\n\n # Restore item 1 and remove item 2.\n self.store_test_data(1)\n self.ac.remove(2)\n\n self.assertResults(self.ac.search('testing'), [1, 3])\n\n # Item with obj_id=2 has already been removed.\n with self.assertRaises(KeyError):\n self.ac.remove(2)\n\n def test_tokenize_title(self):\n self.assertEqual(\n self.ac.tokenize_title('abc def ghi'),\n ['abc', 'def', 'ghi'])\n\n # Stop-words are removed automatically.\n self.assertEqual(self.ac.tokenize_title('a A tHe an a'), [])\n\n # Empty string yields an empty list.\n self.assertEqual(self.ac.tokenize_title(''), [])\n\n # Stop-words, punctuation, capitalization, etc.\n self.assertEqual(self.ac.tokenize_title(\n 'The Best of times, the blurst of times'),\n ['times', 'blurst', 'times'])\n\n def test_exists(self):\n self.assertFalse(self.ac.exists('test'))\n self.ac.store('test')\n self.assertTrue(self.ac.exists('test'))\n\n def test_key_leaks(self):\n initial_key_count = len(db.keys())\n\n # Store a single item.\n self.store_test_data(1)\n\n # See how many keys we have in the db - check again in a bit.\n key_len = len(db.keys())\n\n # Store a second item.\n self.store_test_data(2)\n key_len2 = len(db.keys())\n\n self.assertTrue(key_len != key_len2)\n self.ac.remove(2)\n\n # Back to the original amount of keys we had after one item.\n self.assertEqual(len(db.keys()), key_len)\n\n # Remove the first item, back to original count at start.\n self.ac.remove(1)\n self.assertEqual(len(db.keys()), initial_key_count)\n\n def test_updating(self):\n # store(obj_id, title=None, data=None, obj_type=None).\n self.ac.store('id1', 'title baze', 'd1', 't1')\n self.ac.store('id2', 'title nugget', 'd2', 't2')\n self.ac.store('id3', 'title foo', 'd3', 't3')\n\n self.assertList(self.ac.search('tit'), ['d1', 'd3', 'd2'])\n\n # Overwrite the data for id1.\n self.ac.store('id1', 'title foo', 'D1', 't1')\n self.assertList(self.ac.search('tit'), ['D1', 'd3', 'd2'])\n\n # Overwrite the data with a new title, will remove the title one refs.\n self.ac.store('id1', 'Herple', 'done', 't1')\n self.assertList(self.ac.search('tit'), ['d3', 'd2'])\n self.assertList(self.ac.search('herp'), ['done'])\n\n # Overwrite again, capitalizing the data and changing the title.\n self.ac.store('id1', 'title baze', 'Done', 't1')\n self.assertList(self.ac.search('tit'), ['Done', 'd3', 'd2'])\n\n # Verify that we clean up any crap when updating.\n self.assertList(self.ac.search('herp'), [])\n\n def test_word_position_ordering(self):\n self.ac.store('aaaa bbbb')\n self.ac.store('bbbb cccc')\n self.ac.store('bbbb aaaa')\n self.ac.store('aaaa bbbb')\n\n results = self.ac.search('bb')\n self.assertList(results, ['bbbb aaaa', 'bbbb cccc', 'aaaa bbbb'])\n self.assertList(self.ac.search('aa'), ['aaaa bbbb', 'bbbb aaaa'])\n\n self.ac.store('aabb bbbb')\n self.assertList(self.ac.search('bb'), [\n 'bbbb aaaa',\n 'bbbb cccc',\n 'aaaa bbbb',\n 'aabb bbbb'])\n self.assertList(self.ac.search('aa'), [\n 'aaaa bbbb',\n 'aabb bbbb',\n 'bbbb aaaa'])\n\n # Verify issue 9 is fixed.\n self.ac.store('foo one')\n self.ac.store('bar foo one')\n self.assertList(self.ac.search('foo'), ['foo one', 'bar foo one'])\n\n def test_return_all_results(self):\n phrases = ('aa bb', 'aa cc', 'bb aa cc', 'bb cc', 'cc aa bb')\n for phrase in phrases:\n self.ac.store(phrase)\n\n self.assertList(sorted(self.ac.list_data()), list(phrases))\n self.assertEqual(sorted(self.ac.list_titles()), list(phrases))\n\n def test_multiword_phrases(self):\n self.ac.store('p1', 'alpha beta gamma delta')\n self.ac.store('p2', 'beta delta zeta')\n self.ac.store('p3', 'gamma zeta iota')\n\n self.assertList(self.ac.search('ga del'), ['alpha beta gamma delta'])\n self.assertList(self.ac.search('be de'), [\n 'beta delta zeta',\n 'alpha beta gamma delta'])\n self.assertList(self.ac.search('de be'), [\n 'beta delta zeta',\n 'alpha beta gamma delta'])\n self.assertList(self.ac.search('bet delt'), [\n 'beta delta zeta',\n 'alpha beta gamma delta'])\n self.assertList(self.ac.search('delt bet'), [\n 'beta delta zeta',\n 'alpha beta gamma delta'])\n\n self.assertList(self.ac.search('delt bet alpha'),\n ['alpha beta gamma delta'])\n\n def test_multiword_stopword_handling(self):\n self.ac.store('p1', 'alpha beta delta')\n self.ac.store('p2', 'alpha delta gamma')\n self.ac.store('p3', 'beta gamma')\n\n self.assertList(self.ac.search('a'), [\n 'alpha beta delta',\n 'alpha delta gamma'])\n self.assertList(self.ac.search('be'), [\n 'beta gamma',\n 'alpha beta delta'])\n # Here since \"a\" is a stopword and is not the last token, we strip it.\n self.assertList(self.ac.search('a be'), [\n 'beta gamma',\n 'alpha beta delta'])\n # a & be are stripped, since they are stopwords and not last token.\n self.assertList(self.ac.search('a be de'), [\n 'alpha delta gamma',\n 'alpha beta delta'])\n\n self.assertList(self.ac.search('al bet de'), [\n 'alpha beta delta'])\n" }, { "alpha_fraction": 0.5305954217910767, "alphanum_fraction": 0.5407481789588928, "avg_line_length": 27.846965789794922, "blob_id": "6e141dcb8ff54fc5bb22c6cd5b13fedabefabfff", "content_id": "c28512473e8e060948130bb4f68b3e3254b8469b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10933, "license_type": "permissive", "max_line_length": 79, "num_lines": 379, "path": "/walrus/tusks/ledisdb.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import sys\nimport unittest\n\nfrom ledis import Ledis\nfrom ledis.client import Token\n\nfrom walrus import *\nfrom walrus.containers import chainable_method\nfrom walrus.tusks.helpers import TestHelper\n\n\nclass Scannable(object):\n def _scan(self, cmd, match=None, count=None, ordering=None, limit=None):\n parts = [self.key, '']\n if match:\n parts.extend([Token('MATCH'), match])\n if count:\n parts.extend([Token('COUNT'), count])\n if ordering:\n parts.append(Token(ordering.upper()))\n return self._execute_scan(self.database, cmd, parts, limit)\n\n def _execute_scan(self, database, cmd, parts, limit=None):\n idx = 0\n while True:\n cursor, rows = database.execute_command(cmd, *parts)\n for row in rows:\n idx += 1\n if limit and idx > limit:\n cursor = None\n break\n yield row\n if cursor:\n parts[1] = cursor\n else:\n break\n\n\nclass Sortable(object):\n def _sort(self, cmd, pattern=None, limit=None, offset=None,\n get_pattern=None, ordering=None, alpha=True, store=None):\n parts = [self.key]\n def add_kw(kw, param):\n if param is not None:\n parts.extend([Token(kw), param])\n add_kw('BY', pattern)\n if limit or offset:\n offset = offset or 0\n limit = limit or 'Inf'\n parts.extend([Token('LIMIT'), offset, limit])\n add_kw('GET', get_pattern)\n if ordering:\n parts.append(Token(ordering))\n if alpha:\n parts.append(Token('ALPHA'))\n add_kw('STORE', store)\n return self.database.execute_command(cmd, *parts)\n\n\nclass LedisHash(Scannable, Hash):\n @chainable_method\n def clear(self):\n self.database.hclear(self.key)\n\n @chainable_method\n def expire(self, ttl=None):\n if ttl is not None:\n self.database.hexpire(self.key, ttl)\n else:\n self.database.hpersist(self.key)\n\n def __iter__(self):\n return self._scan('XHSCAN')\n\n def scan(self, match=None, count=None, ordering=None, limit=None):\n if limit is not None:\n limit *= 2 # Hashes yield 2 values.\n return self._scan('XHSCAN', match, count, ordering, limit)\n\n\nclass LedisList(Sortable, List):\n @chainable_method\n def clear(self):\n self.database.lclear(self.key)\n\n def __setitem__(self, idx, value):\n raise TypeError('Ledis does not support setting values by index.')\n\n @chainable_method\n def expire(self, ttl=None):\n if ttl is not None:\n self.database.lexpire(self.key, ttl)\n else:\n self.database.lpersist(self.key)\n\n def sort(self, *args, **kwargs):\n return self._sort('XLSORT', *args, **kwargs)\n\n\nclass LedisSet(Scannable, Sortable, Set):\n @chainable_method\n def clear(self):\n self.database.sclear(self.key)\n\n @chainable_method\n def expire(self, ttl=None):\n if ttl is not None:\n self.database.sexpire(self.key, ttl)\n else:\n self.database.spersist(self.key)\n\n def __iter__(self):\n return self._scan('XSSCAN')\n\n def scan(self, match=None, count=None, ordering=None, limit=None):\n return self._scan('XSSCAN', match, count, ordering, limit)\n\n def sort(self, *args, **kwargs):\n return self._sort('XSSORT', *args, **kwargs)\n\n\nclass LedisZSet(Scannable, Sortable, ZSet):\n @chainable_method\n def clear(self):\n self.database.zclear(self.key)\n\n @chainable_method\n def expire(self, ttl=None):\n if ttl is not None:\n self.database.zexpire(self.key, ttl)\n else:\n self.database.zpersist(self.key)\n\n def __iter__(self):\n return self._scan('XZSCAN')\n\n def scan(self, match=None, count=None, ordering=None, limit=None):\n if limit:\n limit *= 2\n return self._scan('XZSCAN', match, count, ordering, limit)\n\n def sort(self, *args, **kwargs):\n return self._sort('XZSORT', *args, **kwargs)\n\n\nclass LedisBitSet(Container):\n def clear(self):\n self.database.delete(self.key)\n\n def __getitem__(self, idx):\n return self.database.execute_command('GETBIT', self.key, idx)\n\n def __setitem__(self, idx, value):\n return self.database.execute_command('SETBIT', self.key, idx, value)\n\n def pos(self, bit, start=None, end=None):\n pieces = ['BITPOS', self.key, bit]\n if start or end:\n pieces.append(start or 0)\n if end:\n pieces.append(end)\n return self.database.execute_command(*pieces)\n\n def __iand__(self, other):\n self.database.execute_command(\n 'BITOP',\n 'AND',\n self.key,\n self.key,\n other.key)\n return self\n\n def __ior__(self, other):\n self.database.execute_command(\n 'BITOP',\n 'OR',\n self.key,\n self.key,\n other.key)\n return self\n\n def __ixor__(self, other):\n self.database.execute_command(\n 'BITOP',\n 'XOR',\n self.key,\n self.key,\n other.key)\n return self\n\n def __str__(self):\n return self.database[self.key]\n\n __unicode__ = __str__\n\n\nclass WalrusLedis(Ledis, Scannable, Walrus):\n def __init__(self, *args, **kwargs):\n super(WalrusLedis, self).__init__(*args, **kwargs)\n\n def __setitem__(self, key, value):\n self.set(key, value)\n\n def setex(self, name, value, time):\n return super(WalrusLedis, self).setex(name, time, value)\n\n def zadd(self, key, *args, **kwargs):\n if not isinstance(args[0], (int, float)):\n reordered = []\n for idx in range(0, len(args), 2):\n reordered.append(args[idx + 1])\n reordered.append(args[idx])\n else:\n reordered = args\n return super(WalrusLedis, self).zadd(key, *reordered, **kwargs)\n\n def hash_exists(self, key):\n return self.execute_command('HKEYEXISTS', key)\n\n def __iter__(self):\n return self.scan()\n\n def scan(self, *args, **kwargs):\n return self._scan('XSCAN', *args, **kwargs)\n\n def _scan(self, cmd, match=None, count=None, ordering=None, limit=None):\n parts = ['KV', '']\n if match:\n parts.extend([Token('MATCH'), match])\n if count:\n parts.extend([Token('COUNT'), count])\n if ordering:\n parts.append(Token(ordering.upper()))\n return self._execute_scan(self, cmd, parts, limit)\n\n def update(self, values):\n return self.mset(values)\n\n def BitSet(self, key):\n return LedisBitSet(self, key)\n\n def Hash(self, key):\n return LedisHash(self, key)\n\n def List(self, key):\n return LedisList(self, key)\n\n def Set(self, key):\n return LedisSet(self, key)\n\n def ZSet(self, key):\n return LedisZSet(self, key)\n\n\nclass TestWalrusLedis(TestHelper, unittest.TestCase):\n def setUp(self):\n self.db = WalrusLedis()\n self.db.flushall()\n\n def test_scan(self):\n values = {\n 'k1': 'v1',\n 'k2': 'v2',\n 'k3': 'v3',\n 'charlie': 31,\n 'mickey': 7,\n 'huey': 5}\n self.db.update(values)\n results = self.db.scan()\n expected = ['charlie', 'huey', 'k1', 'k2', 'k3', 'mickey']\n self.assertEqual(list(results), expected)\n self.assertEqual([item for item in self.db], expected)\n\n def test_hash_iter(self):\n h = self.db.Hash('h_obj')\n h.clear()\n h.update({'k1': 'v1', 'k2': 'v2', 'k3': 'v3'})\n\n items = [item for item in h]\n self.assertEqual(items, ['k1', 'v1', 'k2', 'v2', 'k3', 'v3'])\n items = [item for item in h.scan(limit=2)]\n self.assertEqual(items, ['k1', 'v1', 'k2', 'v2'])\n\n def test_no_setitem_list(self):\n l = self.db.List('l_obj').clear()\n l.append('foo')\n self.assertRaises(TypeError, lambda: l.__setitem__(0, 'xx'))\n\n def test_set_iter(self):\n s = self.db.Set('s_obj').clear()\n s.add('charlie', 'huey', 'mickey')\n\n items = [item for item in s]\n self.assertEqual(sorted(items), ['charlie', 'huey', 'mickey'])\n items = [item for item in s.scan(limit=2, ordering='DESC')]\n self.assertEqual(items, ['mickey', 'huey'])\n\n def test_zset_iter(self):\n zs = self.db.ZSet('z_obj').clear()\n zs.add('zaizee', 3, 'mickey', 6, 'charlie', 31, 'huey', 3, 'nuggie', 0)\n\n items = [item for item in zs]\n self.assertEqual(items, [\n 'charlie', '31',\n 'huey', '3',\n 'mickey', '6',\n 'nuggie', '0',\n 'zaizee', '3',\n ])\n\n items = [item for item in zs.scan(limit=3, ordering='DESC')]\n self.assertEqual(items, [\n 'zaizee', '3',\n 'nuggie', '0',\n 'mickey', '6',\n ])\n\n def test_bit_set(self):\n b = self.db.BitSet('bitset_obj')\n b.clear()\n b[0] = 1\n b[1] = 1\n b[2] = 0\n b[3] = 1\n self.assertEqual(self.db[b.key], '\\xd0')\n\n b[4] = 1\n self.assertEqual(self.db[b.key], '\\xd8')\n self.assertEqual(b[0], 1)\n self.assertEqual(b[2], 0)\n\n self.db['b1'] = 'foobar'\n self.db['b2'] = 'abcdef'\n b = self.db.BitSet('b1')\n b2 = self.db.BitSet('b2')\n b &= b2\n self.assertEqual(self.db[b.key], '`bc`ab')\n self.assertEqual(str(b), '`bc`ab')\n\n self.db['b1'] = '\\x00\\xff\\xf0'\n self.assertEqual(b.pos(1, 0), 8)\n self.assertEqual(b.pos(1, 2), 16)\n\n self.db['b1'] = '\\x00\\x00\\x00'\n self.assertEqual(b.pos(1), -1)\n\n def test_sorting(self):\n items = ['charlie', 'zaizee', 'mickey', 'huey']\n sorted_items = sorted(items)\n\n l = self.db.List('l_obj').clear()\n l.extend(items)\n results = l.sort()\n self.assertEqual(results, sorted_items)\n\n dest = self.db.List('l_dest')\n l.sort(ordering='DESC', limit=3, store=dest.key)\n results = list(dest)\n self.assertEqual(results, ['zaizee', 'mickey', 'huey'])\n\n s = self.db.Set('s_obj').clear()\n s.add(*items)\n results = s.sort()\n self.assertEqual(results, sorted_items)\n\n results = s.sort(ordering='DESC', limit=3)\n self.assertEqual(results, ['zaizee', 'mickey', 'huey'])\n\n z = self.db.ZSet('z_obj').clear()\n z.add('charlie', 10, 'zaizee', 10, 'mickey', 3, 'huey', 4)\n results = z.sort()\n self.assertEqual(results, sorted_items)\n\n results = z.sort(ordering='DESC', limit=3)\n self.assertEqual(results, ['zaizee', 'mickey', 'huey'])\n\n\nif __name__ == '__main__':\n unittest.main(argv=sys.argv)\n" }, { "alpha_fraction": 0.5370887517929077, "alphanum_fraction": 0.5409770607948303, "avg_line_length": 30.54088020324707, "blob_id": "19f649bcbf1b73d37aa12df27585b3536418bf91", "content_id": "9ab968ed5d69a3a837b00f517727dd7f9044fd9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10030, "license_type": "permissive", "max_line_length": 79, "num_lines": 318, "path": "/walrus/cache.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from functools import wraps\nimport hashlib\nimport pickle\nimport sys\nimport threading\nimport time\ntry:\n from Queue import Queue # Python 2\nexcept ImportError:\n from queue import Queue # Python 3\n\nfrom walrus.utils import decode\nfrom walrus.utils import encode\nfrom walrus.utils import PY3\n\nif PY3:\n imap = map\nelse:\n from itertools import imap\n\n\n\nclass Cache(object):\n \"\"\"\n Cache implementation with simple ``get``/``set`` operations,\n and a decorator.\n \"\"\"\n def __init__(self, database, name='cache', default_timeout=None,\n debug=False):\n \"\"\"\n :param database: :py:class:`Database` instance.\n :param name: Namespace for this cache.\n :param int default_timeout: Default cache timeout.\n :param debug: Disable cache for debugging purposes. Cache will no-op.\n \"\"\"\n self.database = database\n self.name = name\n self.prefix_len = len(self.name) + 1\n self.default_timeout = default_timeout\n self.debug = debug\n self.metrics = {'hits': 0, 'misses': 0, 'writes': 0}\n\n def make_key(self, s):\n return ':'.join((self.name, s))\n\n def unmake_key(self, k):\n return k[self.prefix_len:]\n\n def get(self, key, default=None):\n \"\"\"\n Retreive a value from the cache. In the event the value\n does not exist, return the ``default``.\n \"\"\"\n key = self.make_key(key)\n\n if self.debug:\n return default\n\n try:\n value = self.database[key]\n except KeyError:\n self.metrics['misses'] += 1\n return default\n else:\n self.metrics['hits'] += 1\n return pickle.loads(value)\n\n def set(self, key, value, timeout=None):\n \"\"\"\n Cache the given ``value`` in the specified ``key``. If no\n timeout is specified, the default timeout will be used.\n \"\"\"\n key = self.make_key(key)\n if timeout is None:\n timeout = self.default_timeout\n\n if self.debug:\n return True\n\n pickled_value = pickle.dumps(value)\n self.metrics['writes'] += 1\n if timeout:\n return self.database.setex(key, int(timeout), pickled_value)\n else:\n return self.database.set(key, pickled_value)\n\n def delete(self, key):\n \"\"\"Remove the given key from the cache.\"\"\"\n if self.debug: return 0\n return self.database.delete(self.make_key(key))\n\n def get_many(self, keys):\n \"\"\"\n Retrieve multiple values from the cache. Missing keys are not included\n in the result dictionary.\n\n :param list keys: list of keys to fetch.\n :returns: dictionary mapping keys to cached values.\n \"\"\"\n accum = {}\n if self.debug: return accum\n\n prefixed = [self.make_key(key) for key in keys]\n for key, value in zip(keys, self.database.mget(prefixed)):\n if value is not None:\n accum[key] = pickle.loads(value)\n self.metrics['hits'] += 1\n else:\n self.metrics['misses'] += 1\n return accum\n\n def set_many(self, __data=None, timeout=None, **kwargs):\n \"\"\"\n Set multiple key/value pairs in one operation.\n\n :param dict __data: provide data as dictionary of key/value pairs.\n :param timeout: optional timeout for data.\n :param kwargs: alternatively, provide data as keyword arguments.\n :returns: True on success.\n \"\"\"\n if self.debug:\n return True\n\n timeout = timeout if timeout is not None else self.default_timeout\n if __data is not None:\n kwargs.update(__data)\n\n accum = {}\n for key, value in kwargs.items():\n accum[self.make_key(key)] = pickle.dumps(value)\n\n pipeline = self.database.pipeline()\n pipeline.mset(accum)\n if timeout:\n for key in accum:\n pipeline.expire(key, timeout)\n\n self.metrics['writes'] += len(accum)\n return pipeline.execute()[0]\n\n def delete_many(self, keys):\n \"\"\"\n Delete multiple keys from the cache in one operation.\n\n :param list keys: keys to delete.\n :returns: number of keys removed.\n \"\"\"\n if self.debug: return\n prefixed = [self.make_key(key) for key in keys]\n return self.database.delete(*prefixed)\n\n def keys(self):\n \"\"\"\n Return all keys for cached values.\n \"\"\"\n return imap(decode, self.database.keys(self.make_key('') + '*'))\n\n def flush(self):\n \"\"\"Remove all cached objects from the database.\"\"\"\n keys = list(self.keys())\n if keys:\n return self.database.delete(*keys)\n\n def incr(self, key, delta=1):\n return self.database.incr(self.make_key(key), delta)\n\n def _key_fn(a, k):\n return hashlib.md5(pickle.dumps((a, k))).hexdigest()\n\n def cached(self, key_fn=_key_fn, timeout=None, metrics=False):\n \"\"\"\n Decorator that will transparently cache calls to the\n wrapped function. By default, the cache key will be made\n up of the arguments passed in (like memoize), but you can\n override this by specifying a custom ``key_fn``.\n\n :param key_fn: Function used to generate a key from the\n given args and kwargs.\n :param timeout: Time to cache return values.\n :param metrics: Keep stats on cache utilization and timing.\n :returns: Return the result of the decorated function\n call with the given args and kwargs.\n\n Usage::\n\n cache = Cache(my_database)\n\n @cache.cached(timeout=60)\n def add_numbers(a, b):\n return a + b\n\n print add_numbers(3, 4) # Function is called.\n print add_numbers(3, 4) # Not called, value is cached.\n\n add_numbers.bust(3, 4) # Clear cache for (3, 4).\n print add_numbers(3, 4) # Function is called.\n\n The decorated function also gains a new attribute named\n ``bust`` which will clear the cache for the given args.\n \"\"\"\n def decorator(fn):\n def make_key(args, kwargs):\n return '%s:%s' % (fn.__name__, key_fn(args, kwargs))\n\n def bust(*args, **kwargs):\n return self.delete(make_key(args, kwargs))\n\n _metrics = {\n 'hits': 0,\n 'misses': 0,\n 'avg_hit_time': 0,\n 'avg_miss_time': 0}\n\n @wraps(fn)\n def inner(*args, **kwargs):\n start = time.time()\n is_cache_hit = True\n key = make_key(args, kwargs)\n res = self.get(key, sentinel)\n if res is sentinel:\n res = fn(*args, **kwargs)\n self.set(key, res, timeout)\n is_cache_hit = False\n\n if metrics:\n dur = time.time() - start\n if is_cache_hit:\n _metrics['hits'] += 1\n _metrics['avg_hit_time'] += (dur / _metrics['hits'])\n else:\n _metrics['misses'] += 1\n _metrics['avg_miss_time'] += (dur / _metrics['misses'])\n\n return res\n\n inner.bust = bust\n inner.make_key = make_key\n if metrics:\n inner.metrics = _metrics\n return inner\n return decorator\n\n def cached_property(self, key_fn=_key_fn, timeout=None):\n \"\"\"\n Decorator that will transparently cache calls to the wrapped\n method. The method will be exposed as a property.\n\n Usage::\n\n cache = Cache(my_database)\n\n class Clock(object):\n @cache.cached_property()\n def now(self):\n return datetime.datetime.now()\n\n clock = Clock()\n print clock.now\n \"\"\"\n this = self\n\n class _cached_property(object):\n def __init__(self, fn):\n self._fn = this.cached(key_fn, timeout)(fn)\n\n def __get__(self, instance, instance_type=None):\n if instance is None:\n return self\n return self._fn(instance)\n\n def __delete__(self, obj):\n self._fn.bust(obj)\n\n def __set__(self, instance, value):\n raise ValueError('Cannot set value of a cached property.')\n\n def decorator(fn):\n return _cached_property(fn)\n\n return decorator\n\n def cache_async(self, key_fn=_key_fn, timeout=3600):\n \"\"\"\n Decorator that will execute the cached function in a separate\n thread. The function will immediately return, returning a\n callable to the user. This callable can be used to check for\n a return value.\n\n For details, see the :ref:`cache-async` section of the docs.\n\n :param key_fn: Function used to generate cache key.\n :param int timeout: Cache timeout in seconds.\n :returns: A new function which can be called to retrieve the\n return value of the decorated function.\n \"\"\"\n def decorator(fn):\n wrapped = self.cached(key_fn, timeout)(fn)\n\n @wraps(fn)\n def inner(*args, **kwargs):\n q = Queue()\n def _sub_fn():\n q.put(wrapped(*args, **kwargs))\n def _get_value(block=True, timeout=None):\n if not hasattr(_get_value, '_return_value'):\n result = q.get(block=block, timeout=timeout)\n _get_value._return_value = result\n return _get_value._return_value\n\n thread = threading.Thread(target=_sub_fn)\n thread.start()\n return _get_value\n return inner\n return decorator\n\n\nclass sentinel(object):\n pass\n" }, { "alpha_fraction": 0.6557376980781555, "alphanum_fraction": 0.6721311211585999, "avg_line_length": 29.5, "blob_id": "70ef2e51c70ec547882df7db5ff41483295f3712", "content_id": "30b989e8d797f9d265a1e8d9f6a9eafadccd13b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 122, "license_type": "permissive", "max_line_length": 39, "num_lines": 4, "path": "/walrus/scripts/array_append.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal value = ARGV[1]\nlocal max_idx = redis.call('HLEN', key)\nredis.call('HSET', key, max_idx, value)\n" }, { "alpha_fraction": 0.5813953280448914, "alphanum_fraction": 0.5862913131713867, "avg_line_length": 19.424999237060547, "blob_id": "20251dae572a82712c9161ec6f5ecb4d3ea2e926", "content_id": "cf3a8d1cb2da7c2a41f4d538000089045d0c7548", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1634, "license_type": "permissive", "max_line_length": 75, "num_lines": 80, "path": "/walrus/utils.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import os\nimport re\nimport sys\n\n\nPY3 = sys.version_info[0] == 3\n\nif PY3:\n unicode_type = str\n basestring_type = (str, bytes)\n def exception_message(exc):\n return exc.args[0]\nelse:\n unicode_type = unicode\n basestring_type = basestring\n def exception_message(exc):\n return exc.message\n\n\ndef encode(s):\n return s.encode('utf-8') if isinstance(s, unicode_type) else s\n\n\ndef decode(s):\n return s.decode('utf-8') if isinstance(s, bytes) else s\n\n\ndef decode_dict(d):\n accum = {}\n for key in d:\n accum[decode(key)] = decode(d[key])\n return accum\n\n\ndef safe_decode_list(l):\n return [i.decode('raw_unicode_escape') if isinstance(i, bytes) else i\n for i in l]\n\n\ndef decode_dict_keys(d):\n accum = {}\n for key in d:\n accum[decode(key)] = d[key]\n return accum\n\n\ndef make_python_attr(s):\n if isinstance(s, bytes):\n s = decode(s)\n s = re.sub('[^\\w]+', '_', s)\n if not s:\n raise ValueError('cannot construct python identifer from \"%s\"' % s)\n if s[0].isdigit():\n s = '_' + s\n return s.lower()\n\n\nclass memoize(dict):\n def __init__(self, fn):\n self._fn = fn\n\n def __call__(self, *args):\n return self[args]\n\n def __missing__(self, key):\n result = self[key] = self._fn(*key)\n return result\n\n\n@memoize\ndef load_stopwords(stopwords_file):\n path, filename = os.path.split(stopwords_file)\n if not path:\n path = os.path.dirname(__file__)\n filename = os.path.join(path, filename)\n if not os.path.exists(filename):\n return\n\n with open(filename) as fh:\n return fh.read()\n" }, { "alpha_fraction": 0.6453006267547607, "alphanum_fraction": 0.6943286061286926, "avg_line_length": 37.20921325683594, "blob_id": "8f167c59344cf5362067db6737add37325bbadcc", "content_id": "c49fe79ecd68b2f9806b974b93338c33f74793b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 19907, "license_type": "permissive", "max_line_length": 141, "num_lines": 521, "path": "/docs/streams.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _streams:\n\n.. py:module:: walrus\n\nStreams\n=======\n\n`Redis streams <https://redis.io/topics/streams-intro>`_ is a new data-type\navailable in Redis 5.0 which provides a persistent, append-only log. Redis\nstreams are a complex topic, so I strongly recommend reading `the streams\nintroduction <https://redis.io/topics/streams-intro>`_.\n\nI like to think of streams as having two modes of operation:\n\n* standalone-mode: streams act much like every other data-structure\n* consumer-groups: streams become stateful, with state such as \"which messages\n were read?\", \"who read what?\", etc are tracked within Redis.\n\n:py:class:`Stream` objects in walrus can be used standalone or within the\ncontext of a :py:class:`ConsumerGroup`.\n\nStandalone streams\n------------------\n\nIn standalone mode, streams behave much like every other data-structure in\nRedis. By this, I mean that they act as a dumb container: you append items, you\nread them, you delete them -- everything happens explicitly. Streams support\nthe following operations:\n\n* Add a new item (``XADD``) - :py:meth:`Stream.add`\n* Read a range of items (``XRANGE``) - :py:meth:`Stream.range`\n* Read new messages, optionally blocking (``XREAD``) - :py:meth:`Stream.read`\n* Delete one or more items (``XDEL``) - :py:meth:`Stream.delete`\n* Get the length of the stream (``XLEN``) - :py:meth:`Stream.length`\n* Trim the length to a given size (``XTRIM``) - :py:meth:`Stream.trim`\n* Set the maximum allowable ID (``XSETID``) - :py:meth:`Stream.set_id`\n\nTo get started with streams, we'll create a :py:class:`Database` instance and\nuse it to instantiate a :py:class:`Stream`:\n\n.. code-block:: python\n\n from walrus import Database # A subclass of the redis-py Redis client.\n\n db = Database()\n stream = db.Stream('stream-a') # Create a new stream instance.\n\nWhen adding data to a stream, Redis can automatically provide you with a unique\ntimestamp-based identifier, which is almost always what you want. When a new\nmessage is added, the message id is returned:\n\n.. code-block:: python\n\n msgid = stream.add({'message': 'hello streams'})\n print(msgid)\n\n # Prints something like:\n # b'1539008591844-0'\n\nMessage ids generated by Redis consist of a millisecond timestamp along with a\nsequence number (for ordering messages that arrived on the same millisecond).\nLet's :py:meth:`~Stream.add` a couple more items:\n\n.. code-block:: python\n\n msgid2 = stream.add({'message': 'message 2'})\n msgid3 = stream.add({'message': 'message 3'})\n\nRanges of records can be read using either the :py:meth:`~Stream.range` method,\nor using Python's slice notation. The message ids provided as the range\nendpoints are inclusive when using the range API:\n\n.. code-block:: python\n\n # Get messages 2 and newer:\n messages = stream[msgid2:]\n\n # messages contains:\n [(b'1539008914283-0', {b'message': b'message 2'}),\n (b'1539008918230-0', {b'message': b'message 3'})]\n\n # We can use the \"step\" parameter to limit the number of records returned.\n messages = stream[msgid::2]\n\n # messages contains the first two messages:\n [(b'1539008903588-0', {b'message': b'hello, stream'}),\n (b'1539008914283-0', {b'message': b'message 2'})]\n\n # Get all messages in stream:\n messages = list(stream)\n [(b'1539008903588-0', {b'message': b'hello, stream'}),\n (b'1539008914283-0', {b'message': b'message 2'}),\n (b'1539008918230-0', {b'message': b'message 3'})]\n\nThe size of streams can be managed by deleting messages by id, or by \"trimming\"\nthe stream, which removes the oldest messages. The desired size is specified\nwhen issuing a :py:meth:`~Stream.trim` operation, though, due to the internal\nimplementation of the stream data-structures, the size is considered\napproximate by default.\n\n.. code-block:: python\n\n # Adding and deleting a message:\n msgid4 = stream.add({'message': 'delete me'})\n del stream[msgid4]\n\n # How many items are in the stream?\n print(len(stream)) # Prints 3.\n\nTo see how trimming works, let's create another stream and fill it with 1000\nitems, then request it to be trimmed to 10 items:\n\n.. code-block:: python\n\n # Add 1000 items to \"stream-2\".\n stream2 = db.Stream('stream-2')\n for i in range(1000):\n stream2.add({'data': 'message-%s' % i})\n\n # Trim stream-2 to (approximately) 10 most-recent messages.\n nremoved = stream2.trim(10)\n print(nremoved)\n # 909\n print(len(stream2))\n # 91\n\n # To trim to an exact number, specify `approximate=False`:\n stream2.trim(10, approximate=False) # Returns 81.\n print(len(stream2))\n # 10\n\nThe previous examples show how to :py:meth:`~Stream.add`, read a\n:py:meth:`~Stream.range` of messages, :py:meth:`~Stream.delete` messages, and\nmanage the size using the :py:meth:`~Stream.trim` method. When processing a\ncontinuous stream of events, though, it may be desirable to **block** until\nmessages are added. For this we can use the :py:meth:`~Stream.read` API, which\nsupports blocking until messages become available.\n\n.. code-block:: python\n\n # By default, calling `stream.read()` returns all messages in the stream:\n stream.read()\n\n # Returns:\n [(b'1539008903588-0', {b'message': b'hello, stream'}),\n (b'1539008914283-0', {b'message': b'message 2'}),\n (b'1539008918230-0', {b'message': b'message 3'})]\n\nWe can pass a message id to :py:meth:`~Stream.read`, and unlike the slicing\noperations, this id is considered the \"last-read message\" and acts as an\n**exclusive** lower-bound:\n\n.. code-block:: python\n\n # Read any messages newer than msgid2.\n stream.read(last_id=msgid2)\n\n # Returns:\n [(b'1539008918230-0', {b'message': b'message 3'})]\n\n # This returns None since there are no messages newer than msgid3.\n stream.read(last_id=msgid3)\n\nWe can make :py:meth:`~Stream.read` blocking by specifying a special id,\n``\"$\"``, and a ``block`` in milliseconds. To block forever, you can use\n``block=0``.\n\n.. code-block:: python\n\n # This will block for 2 seconds, after which an empty list is returned\n # (provided no messages are added while waiting).\n stream.read(block=2000, last_id='$')\n\nWhile its possible to build consumers using these APIs, the client is still\nresponsible for keeping track of the last-read message ID and coming up with\nsemantics for retrying failed messages, etc. In the next section, we'll see how\nconsumer groups can greatly simplify building a stream processing pipeline.\n\nConsumer groups\n---------------\n\nIn consumer-group mode, streams retain the behaviors of standalone mode, adding\nfunctionality which makes them *stateful*. What state is tracked?\n\n* Read any unseen messages (``XREAD``) - :py:meth:`ConsumerGroupStream.read`\n* List messages that were read, but not acknowledged (``XPENDING``) - :py:meth:`ConsumerGroupStream.pending`\n* Acknowledge one or more pending messages (``XACK``) - :py:meth:`ConsumerGroupStream.ack`\n* Claim one or more pending messages for re-processing (``XCLAIM``) - :py:meth:`ConsumerGroupStream.claim`\n\n:py:class:`ConsumerGroup` objects provide the building-blocks for robust\nmessage processing pipelines or task queues. Ordinarily this type of stuff\nwould be implemented by the client -- having it in Redis means that we have a\nsingle, unified interface (rather than implementation-specific, with all the\nbugs that likely entails). Furthermore, consumer group state is tracked by the\nRDB and replicated.\n\n.. code-block:: python\n\n # Consumer groups require that a stream exist before the group can be\n # created, so we have to add an empty message.\n stream_keys = ['stream-a', 'stream-b', 'stream-c']\n for stream in stream_keys:\n db.xadd(stream, {'data': ''})\n\n # Create a consumer-group for streams a, b, and c. We will mark all\n # messages as having been processed, so only messages added after the\n # creation of the consumer-group will be read.\n cg = db.consumer_group('cg-abc', stream_keys)\n cg.create() # Create the consumer group.\n cg.set_id('$')\n\nTo read from all the streams in a consumer group, we can use the\n:py:meth:`ConsumerGroupStream.read` method. Since we marked all messages as\nread and have not added anything new since creating the consumer group, the\nreturn value is an empty list:\n\n.. code-block:: python\n\n resp = cg.read()\n\n # Returns an empty list:\n []\n\nFor convenience, walrus exposes the individual streams within a consumer group\nas attributes on the :py:class:`ConsumerGroup` instance. Let's add some\nmessages to streams *a*, *b*, and *c*:\n\n.. code-block:: python\n\n cg.stream_a.add({'message': 'new a'})\n cg.stream_b.add({'message': 'new for b'})\n for i in range(10):\n cg.stream_c.add({'message': 'c-%s' % i})\n\nNow let's try reading from the consumer group again. We'll pass ``count=1`` so\nthat we read no more than one message from each stream in the group:\n\n.. code-block:: python\n\n # Read up to one message from each stream in the group.\n cg.read(count=1)\n\n # Returns:\n [('stream-a', [(b'1539023088125-0', {b'message': b'new a'})]),\n ('stream-b', [(b'1539023088125-0', {b'message': b'new for b'})]),\n ('stream-c', [(b'1539023088126-0', {b'message': b'c-0'})])]\n\nWe've now read all the unread messages from streams *a* and *b*, but stream *c*\nstill has messages. Calling ``read()`` again will give us the next unread\nmessage from stream *c*:\n\n.. code-block:: python\n\n # Read up to 1 message from each stream in the group. Since\n # we already read everything in streams a and b, we will only\n # get the next unread message in stream c.\n cg.read(count=1)\n\n # Returns:\n [('stream-c', [(b'1539023088126-1', {b'message': b'c-1'})])]\n\nWhen using consumer groups, messages that are read need to be **acknowledged**.\nLet's look at the **pending** (read but unacknowledged) messages from\nstream *a* using the :py:meth:`~ConsumerGroupStream.pending` method, which\nreturns a list of metadata about each unacknowledged message:\n\n.. code-block:: python\n\n # We read one message from stream a, so we should see one pending message.\n cg.stream_a.pending()\n\n # Returns a list of:\n # [message id, consumer name, message age, delivery count]\n [[b'1539023088125-0', b'cg-abc.c1', 22238, 1]]\n\nTo acknowledge receipt of a message and remove it from the pending list, use\nthe :py:meth:`~ConsumerGroupStream.ack` method on the consumer group stream:\n\n.. code-block:: python\n\n # View the pending message list for stream a.\n pending_list = cg.stream_a.pending()\n msg_id = pending_list[0]['message_id']\n\n # Acknowledge the message.\n cg.stream_a.ack(msg_id)\n\n # Returns number of pending messages successfully acknowledged:\n 1\n\nConsumer groups have the concept of individual **consumers**. These might be\nworkers in a process pool, for example. Note that the\n:py:meth:`~ConsumerGroupStream.pending` method returned the consumer name as\n``\"cg-abc.c1\"``. Walrus uses the consumer group name + ``\".c1\"`` as the name\nfor the default consumer name. To create another consumer within a given group,\nwe can use the :py:meth:`~ConsumerGroupStream.consumer` method:\n\n.. code-block:: python\n\n # Create a second consumer within the consumer group.\n cg2 = cg.consumer('cg-abc.c2')\n\nCreating a new consumer within a consumer group does not affect the state of\nthe group itself. Calling :py:meth:`~ConsumerGroupStream.read` using our new\nconsumer will pick up from the last-read message, as you would expect:\n\n.. code-block:: python\n\n # Read from our consumer group using the new consumer. Recall\n # that we read all the messages from streams a and b, and the\n # first two messages in stream c.\n cg2.read(count=1)\n\n # Returns:\n [('stream-c', [(b'1539023088126-2', {b'message': b'c-2'})])]\n\nIf we look at the pending message status for stream *c*, we will see that the\nfirst and second messages were read by the consumer *\"cg-abc.c1\"* and the third\nmessage was read by our new consumer, *\"cg-abc.c2\"*:\n\n.. code-block:: python\n\n # What messages have been read, but were not acknowledged, from stream c?\n cg.stream_c.pending()\n\n # Returns list of [message id, consumer, message age, delivery count]:\n [{'message_id': b'1539023088126-0', 'consumer': b'cg-abc.c1',\n 'time_since_delivered': 51329, 'times_delivered': 1}],\n {'message_id': b'1539023088126-1', 'consumer': b'cg-abc.c1',\n 'time_since_delivered': 43772, 'times_delivered': 1},\n {'message_id': b'1539023088126-2', 'consumer': b'cg-abc.c2',\n 'time_since_delivered': 5966, 'times_delivered': 1}]\n\nConsumers can :py:meth:`~ConsumerGroupStream.claim` pending messages, which\ntransfers ownership of the message and returns a list of (message id, data)\ntuples to the caller:\n\n.. code-block:: python\n\n # Unpack the pending messages into a couple variables.\n mc1, mc2, mc3 = cg.stream_c.pending()\n\n # Claim the first message for consumer 2:\n cg2.stream_c.claim(mc1['message_id'])\n\n # Returns a list of (message id, data) tuples for the claimed messages:\n [(b'1539023088126-0', {b'message': b'c-0'})]\n\nRe-inspecting the pending messages for stream *c*, we can see that the consumer\nfor the first message has changed and the message age has been reset:\n\n.. code-block:: python\n\n # What messages are pending in stream c?\n cg.stream_c.pending()\n\n # Returns:\n [{'message_id': b'1539023088126-0', 'consumer': b'cg-abc.c2',\n 'time_since_delivered': 2168, 'times_delivered': 1},\n {'message_id': b'1539023088126-1', 'consumer': b'cg-abc.c1',\n 'time_since_delivered': 47141, 'times_delivered': 1},\n {'message_id': b'1539023088126-2', 'consumer': b'cg-abc.c2',\n 'time_since_delivered': 9335, 'times_delivered': 1}]\n\nThe individual streams within the consumer group support a number of\nuseful APIs:\n\n* ``consumer_group.stream.ack(*id_list)`` - acknowledge one or more messages\n read from the given stream.\n* ``consumer_group.stream.add(data, id='*', maxlen=None, approximate=True)`` -\n add a new message to the stream. The ``maxlen`` parameter can be used to keep\n the stream from growing without bounds. If given, the ``approximate`` flag\n indicates whether the stream maxlen should be approximate or exact.\n* ``consumer_group.stream.claim(*id_list)`` - claim one or more\n pending messages.\n* ``consumer_group.stream.delete(*id_list)`` - delete one or more messages\n by ID.\n* ``consumer_group.stream.pending(start='-', stop='+', count=1000)`` - get the\n list of unacknowledged messages in the stream. The ``start`` and ``stop``\n parameters can be message ids, while the ``count`` parameter can be used to\n limit the number of results returned.\n* ``consumer_group.stream.read(count=None, block=None)`` - monitor the\n stream for new messages within the context of the consumer group. This\n method can be made to block by specifying a ``block`` (or ``0`` to block\n forever).\n* ``consumer_group.stream.set_id(id='$')`` - set the id of the last-read\n message for the consumer group. Use the special id ``\"$\"`` to indicate all\n messages have been read, or ``\"0-0\"`` to mark all messages as unread.\n* ``consumer_group.stream.trim(count, approximate=True)`` - trim the stream to\n the given size.\n\nTimeSeries\n----------\n\nRedis automatically uses the millisecond timestamp plus a sequence number to\nuniquely identify messages added to a stream. This makes streams a natural fit\nfor time-series data. To simplify working with streams as time-series in\nPython, you can use the special :py:class:`TimeSeries` helper class, which acts\njust like the :py:class:`ConsumerGroup` from the previous section with the\nexception that it can translate between Python ``datetime`` objects and message\nids automatically.\n\nTo get started, we'll create a :py:class:`TimeSeries` instance, specifying the\nstream keys, just like we did with :py:class:`ConsumerGroup`:\n\n.. code-block:: python\n\n # Create a time-series consumer group named \"demo-ts\" for the\n # streams s1 and s2.\n ts = db.time_series('demo-ts', ['s1', 's2'])\n\n # Add dummy data and create the consumer group.\n db.xadd('s1', {'': ''}, id='0-1')\n db.xadd('s2', {'': ''}, id='0-1')\n ts.create()\n ts.set_id('$') # Do not read the dummy items.\n\nLet's add some messages to the time-series, one for each day between January\n1st and 10th, 2018:\n\n.. code-block:: python\n\n from datetime import datetime, timedelta\n\n date = datetime(2018, 1, 1)\n for i in range(10):\n ts.s1.add({'message': 's1-%s' % date}, id=date)\n date += timedelta(days=1)\n\nWe can read messages from the stream using the familiar slicing API. For\nexample, to read 3 messages starting at January 2nd, 2018:\n\n.. code-block:: python\n\n ts.s1[datetime(2018, 1, 2)::3]\n\n # Returns messages for Jan 2nd - 4th:\n [<Message s1 1514872800000-0: {'message': 's1-2018-01-02 00:00:00'}>,\n <Message s1 1514959200000-0: {'message': 's1-2018-01-03 00:00:00'}>,\n <Message s1 1515045600000-0: {'message': 's1-2018-01-04 00:00:00'}>]\n\nNote that the values returned are :py:class:`Message` objects. Message objects\nprovide some convenience functions, such as extracting timestamp and sequence\nvalues from stream message ids:\n\n.. code-block:: python\n\n for message in ts.s1[datetime(2018, 1, 1)::3]:\n print(message.stream, message.timestamp, message.sequence, message.data)\n\n # Prints:\n s1 2018-01-01 00:00:00 0 {'message': 's1-2018-01-01 00:00:00'}\n s1 2018-01-02 00:00:00 0 {'message': 's1-2018-01-02 00:00:00'}\n s1 2018-01-03 00:00:00 0 {'message': 's1-2018-01-03 00:00:00'}\n\nLet's add some messages to stream \"s2\" as well:\n\n.. code-block:: python\n\n date = datetime(2018, 1, 1)\n for i in range(5):\n ts.s2.add({'message': 's2-%s' % date}, id=date)\n date += timedelta(days=1)\n\nOne difference between :py:class:`TimeSeries` and :py:class:`ConsumerGroup` is\nwhat happens when reading from multiple streams. ConsumerGroup returns a\ndictionary keyed by stream, along with a corresponding list of messages read\nfrom each stream. TimeSeries, however, returns a flat list of Message objects:\n\n.. code-block:: python\n\n # Read up to 2 messages from each stream (s1 and s2):\n messages = ts.read(count=2)\n\n # \"messages\" is a list of messages from both streams:\n [<Message s1 1514786400000-0: {'message': 's1-2018-01-01 00:00:00'}>,\n <Message s2 1514786400000-0: {'message': 's2-2018-01-01 00:00:00'}>,\n <Message s1 1514872800000-0: {'message': 's1-2018-01-02 00:00:00'}>,\n <Message s2 1514872800000-0: {'message': 's2-2018-01-02 00:00:00'}>]\n\nWhen inspecting pending messages within a :py:class:`TimeSeries` the message\nids are unpacked into (datetime, seq) 2-tuples:\n\n.. code-block:: python\n\n ts.s1.pending()\n\n # Returns:\n [((datetime.datetime(2018, 1, 1, 0, 0), 0), 'events-ts.c', 1578, 1),\n ((datetime.datetime(2018, 1, 2, 0, 0), 0), 'events-ts.c', 1578, 1)]\n\n # Acknowledge the pending messages:\n for msgts_seq, _, _, _ in ts.s1.pending():\n ts.s1.ack(msgts_seq)\n\nWe can set the last-read message id using a datetime:\n\n.. code-block:: python\n\n ts.s1.set_id(datetime(2018, 1, 1))\n\n # Next read will be 2018-01-02, ...\n ts.s1.read(count=2)\n\n # Returns:\n [<Message s1 1514872800000-0: {'message': 's1-2018-01-02 00:00:00'}>,\n <Message s1 1514959200000-0: {'message': 's1-2018-01-03 00:00:00'}>]\n\nAs with :py:class:`ConsumerGroup`, the :py:class:`TimeSeries` helper provides\nstream-specific APIs for claiming unacknowledged messages, creating additional\nconsumers, etc.\n\nLearning more\n-------------\n\nFor more information, the following links may be helpful:\n\n* `Redis streams introduction <https://redis.io/topics/streams-intro>`_.\n* `Example multi-process task queue using walrus and streams <http://charlesleifer.com/blog/multi-process-task-queue-using-redis-streams/>`_.\n* API docs for :py:class:`Stream`, :py:class:`ConsumerGroup`,\n :py:class:`ConsumerGroupStream` and :py:class:`TimeSeries`.\n" }, { "alpha_fraction": 0.5835694074630737, "alphanum_fraction": 0.5873465538024902, "avg_line_length": 28.41666603088379, "blob_id": "2c289574d7e613f2ea20742e32040553e97ff77f", "content_id": "3427c3e32b87dd434110f92653a56aec9be2ada9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1059, "license_type": "permissive", "max_line_length": 71, "num_lines": 36, "path": "/examples/stocks.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import urllib2\nfrom walrus import Database\n\ndb = Database()\nautocomplete = db.autocomplete(namespace='stocks')\n\ndef load_data():\n url = 'http://media.charlesleifer.com/blog/downloads/misc/NYSE.txt'\n contents = urllib2.urlopen(url).read()\n for row in contents.splitlines()[1:]:\n ticker, company = row.split('\\t')\n autocomplete.store(\n ticker,\n company,\n {'ticker': ticker, 'company': company})\n\ndef search(p, **kwargs):\n return autocomplete.search(p, **kwargs)\n\nif __name__ == '__main__':\n autocomplete.flush()\n print 'Loading data (may take a few seconds...)'\n load_data()\n\n print 'Search stock data by typing a partial phrase.'\n print 'Examples: \"uni sta\", \"micro\", \"food\", \"auto\"'\n print 'Type \"q\" at any time to quit'\n\n while 1:\n cmd = raw_input('? ')\n if cmd == 'q':\n break\n results = search(cmd)\n print 'Found %s matches' % len(results)\n for result in results:\n print '%s: %s' % (result['ticker'], result['company'])\n" }, { "alpha_fraction": 0.699341356754303, "alphanum_fraction": 0.7032158374786377, "avg_line_length": 29.36470603942871, "blob_id": "f66da28f165bbc494d83794f3eda9b29fe3d492a", "content_id": "711600e3b958e6ff087f925aa88558f6fbf08b52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2581, "license_type": "permissive", "max_line_length": 79, "num_lines": 85, "path": "/docs/full-text-search.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _full-text-search:\n\nFull-text Search\n================\n\nWalrus comes with a standalone full-text search index that supports:\n\n* Storing documents along with arbitrary metadata.\n* Complex search using boolean/set operations and parentheses.\n* Stop-word removal.\n* Porter-stemming.\n* Optional double-metaphone for phonetic search.\n\nTo create a full-text index, use:\n\n* :py:meth:`Database.Index`\n* :py:class:`Index`\n\nExample:\n\n.. code-block:: python\n\n from walrus import Database\n\n db = Database()\n search_index = db.Index('app-search')\n\n # Phonetic search.\n phonetic_index = db.Index('phonetic-search', metaphone=True)\n\nStoring data\n------------\n\nUse the :py:meth:`Index.add` method to add documents to the search index:\n\n.. code-block:: python\n\n # Specify the document's unique ID and the content to be indexed.\n search_index.add('doc-1', 'this is the content of document 1')\n\n # Besides the document ID and content, we can also store metadata, which is\n # not searchable, but is returned along with the document content when a\n # search is performed.\n search_index.add('doc-2', 'another document', title='Another', status='1')\n\nTo update a document, use either the :py:meth:`Index.update` or\n:py:meth:`Index.replace` methods. The former will update existing metadata\nwhile the latter clears any pre-existing metadata before saving.\n\n.. code-block:: python\n\n # Update doc-1's content and metadata.\n search_index.update('doc-1', 'this is the new content', title='Doc 1')\n\n # Overwrite doc-2...the \"status\" metadata value set earlier will be lost.\n search_index.replace('doc-2', 'another document', title='Another doc')\n\nTo remove a document use :py:meth:`Index.remove`:\n\n.. code-block:: python\n\n search_index.remove('doc-1') # Removed from index and removed metadata.\n\nSearching\n---------\n\nUse the :py:meth:`Index.search` method to perform searches. The search query\ncan include set operations (e.g. *AND*, *OR*) and use parentheses to indicate\noperation precedence.\n\n.. code-block:: python\n\n for document in search_index.search('python AND flask'):\n # Print the \"title\" that was stored as metadata. The \"content\" field\n # contains the original content of the document as it was indexed.\n print(document['title'], document['content'])\n\nPhonetic search, using ``metaphone``, is tolerant of typos:\n\n.. code-block:: python\n\n for document in phonetic_index.search('flasck AND pythonn'):\n print(document['title'], document['content'])\n\nFor more information, see the :py:class:`Index` API documentation.\n" }, { "alpha_fraction": 0.6336405277252197, "alphanum_fraction": 0.6497696042060852, "avg_line_length": 20.700000762939453, "blob_id": "12196652602fb54dc9b6392948d2656b9bcad800", "content_id": "31aa715733466860a3d43ba232dc01e0ffb53e48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 434, "license_type": "permissive", "max_line_length": 42, "num_lines": 20, "path": "/walrus/scripts/array_remove.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal idx = tonumber(ARGV[1])\nlocal arr_len = redis.call('HLEN', key)\nif idx < 0 then\n idx = arr_len + idx\nend\nif idx < 0 or idx >= arr_len then\n return nil\nend\nlocal value = redis.call('HGET', key, idx)\nlocal tmpval\nwhile idx < arr_len do\n tmpval = redis.call('HGET', key, idx+1)\n if tmpval then\n redis.call('HSET', key, idx, tmpval)\n end\n idx = idx + 1\nend\nredis.call('HDEL', key, idx - 1)\nreturn value\n" }, { "alpha_fraction": 0.55154949426651, "alphanum_fraction": 0.5519546270370483, "avg_line_length": 28.386905670166016, "blob_id": "1deed704927b04bf8778ae5f719e9f36d63ca4b7", "content_id": "206655db03fed3c69a3effcac82f5f836edc108f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9874, "license_type": "permissive", "max_line_length": 79, "num_lines": 336, "path": "/walrus/query.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import re\nfrom collections import deque\n\nfrom walrus.containers import Set\nfrom walrus.containers import ZSet\n\n\nOP_AND = 'and'\nOP_OR = 'or'\nOP_EQ = '=='\nOP_NE = '!='\nOP_LT = '<'\nOP_LTE = '<='\nOP_GT = '>'\nOP_GTE = '>='\nOP_BETWEEN = 'between'\nOP_MATCH = 'match'\n\nABSOLUTE = set([OP_EQ, OP_NE])\nCONTINUOUS = set([OP_LT, OP_LTE, OP_GT, OP_GTE, OP_BETWEEN])\nFTS = set([OP_MATCH])\n\n\nclass Lexer(object):\n def __init__(self, query, default_conjunction='AND'):\n self.query = query\n self.default_conjunction = default_conjunction\n\n def yield_symbol(symbol_type):\n def callback(scanner, token):\n return (symbol_type, token)\n return callback\n\n def yield_string(scanner, token):\n return ('STRING', token[1:-1].lower())\n\n def yield_simple_string(scanner, token):\n return ('STRING', token.lower())\n\n self.scanner = re.Scanner([\n (r'\"[^\\n\"\\\\]*(?:\\\\.[^\\n\"\\\\]*)*\"', yield_string),\n (r\"'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'\", yield_string),\n (r'\\bAND\\b', yield_symbol('AND')),\n (r'\\bOR\\b', yield_symbol('OR')),\n (r'[@_\\-\\w]+', yield_simple_string),\n (r'&', yield_symbol('AND')),\n (r'\\|', yield_symbol('OR')),\n (r'\\(', yield_symbol('LPAREN')),\n (r'\\)', yield_symbol('RPAREN')),\n (r'\\s+', None),\n ], re.U)\n\n def lex(self):\n symbols, _ = self.scanner.scan(self.query)\n last = None\n for (symbol, sval) in symbols:\n if symbol == 'STRING' and last == 'STRING':\n # Handle default conjunctions.\n yield self.default_conjunction, None\n yield symbol, sval\n last = symbol\n\n\nclass BaseSymbol(object):\n \"\"\"Base-class for a symbol in the AST.\"\"\"\n __slots__ = []\n\n def code(self):\n raise NotImplementedError\n\n\nclass Symbol(BaseSymbol):\n \"\"\"An interior node of the AST, with left and optionally right children.\"\"\"\n __slots__ = ['left', 'right']\n\n def __init__(self, left, right):\n self.left = left\n self.right = right\n\n\nclass Leaf(BaseSymbol):\n \"\"\"Leaf node of the AST, with a value.\"\"\"\n __slots__ = ['value']\n\n def __init__(self, value):\n self.value = value\n\n def code(self):\n return lambda f, s: Expression(f, OP_MATCH, self.value)\n\n\nclass And(Symbol):\n def code(self):\n return lambda f, s: Expression(\n self.left.code()(f, s),\n OP_AND,\n self.right.code()(f, s))\n\n\nclass Or(Symbol):\n def code(self):\n return lambda f, s: Expression(\n self.left.code()(f, s),\n OP_OR,\n self.right.code()(f, s))\n\n\nclass Parser(object):\n def __init__(self, lexer):\n self.lexer = lexer\n self.symbol_stream = lexer.lex()\n self.root = None\n self.current = None\n self.finished = False\n\n def get_symbol(self):\n try:\n self.current, self.sval = next(self.symbol_stream)\n except StopIteration:\n self.finished = True\n return self.current\n\n def parse(self):\n self._expression()\n if not self.finished:\n raise ValueError('Malformed expression: %s.' % self.lexer.query)\n return self.root\n\n def _expression(self):\n self._term()\n while (self.current == 'OR'):\n left = self.root\n self._term()\n self.root = Or(left, self.root)\n\n def _term(self):\n self._factor()\n while (self.current == 'AND'):\n left = self.root\n self._factor()\n self.root = And(left, self.root)\n\n def _factor(self):\n symbol = self.get_symbol()\n if symbol == 'STRING':\n self.root = Leaf(self.sval)\n self.get_symbol()\n elif symbol == 'LPAREN':\n self._expression()\n self.get_symbol()\n else:\n raise ValueError('Malformed expression: %s.' % self.lexer.query)\n\n\ndef parse(s, field, default_conjunction='AND'):\n if not s.strip():\n return None\n lexer = Lexer(s, default_conjunction=default_conjunction)\n parser = Parser(lexer)\n ast = parser.parse()\n return ast.code()(field, s)\n\n\nclass Node(object):\n def __init__(self):\n self._ordering = None\n\n def desc(self):\n return Desc(self)\n\n def between(self, low, high):\n return Expression(self, OP_BETWEEN, (low, high))\n\n def match(self, term):\n return Expression(self, OP_MATCH, term)\n\n def search(self, search_query, default_conjunction=OP_AND):\n return parse(search_query, self, default_conjunction)\n\n def _e(op, inv=False):\n def inner(self, rhs):\n if inv:\n return Expression(rhs, op, self)\n return Expression(self, op, rhs)\n return inner\n __and__ = _e(OP_AND)\n __or__ = _e(OP_OR)\n __rand__ = _e(OP_AND, inv=True)\n __ror__ = _e(OP_OR, inv=True)\n __eq__ = _e(OP_EQ)\n __ne__ = _e(OP_NE)\n __lt__ = _e(OP_LT)\n __le__ = _e(OP_LTE)\n __gt__ = _e(OP_GT)\n __ge__ = _e(OP_GTE)\n\n\nclass Desc(Node):\n def __init__(self, node):\n self.node = node\n\n\nclass Expression(Node):\n def __init__(self, lhs, op, rhs):\n self.lhs = lhs\n self.op = op\n self.rhs = rhs\n\n def __repr__(self):\n return '(%s %s %s)' % (self.lhs, self.op, self.rhs)\n\n\nclass Executor(object):\n \"\"\"\n Given an arbitrarily complex expression, recursively execute\n it and return the resulting set (or sorted set). The set will\n correspond to the primary hash keys of matching objects.\n\n The executor works *only on fields with secondary indexes* or\n the global \"all\" index created for all models.\n \"\"\"\n def __init__(self, database, temp_key_expire=15):\n self.database = database\n self.temp_key_expire = temp_key_expire\n self._mapping = {\n OP_OR: self.execute_or,\n OP_AND: self.execute_and,\n OP_EQ: self.execute_eq,\n OP_NE: self.execute_ne,\n OP_GT: self.execute_gt,\n OP_GTE: self.execute_gte,\n OP_LT: self.execute_lt,\n OP_LTE: self.execute_lte,\n OP_BETWEEN: self.execute_between,\n OP_MATCH: self.execute_match,\n }\n\n def execute(self, expression):\n op = expression.op\n return self._mapping[op](expression.lhs, expression.rhs)\n\n def execute_eq(self, lhs, rhs):\n index = lhs.get_index(OP_EQ)\n return index.get_key(lhs.db_value(rhs))\n\n def execute_ne(self, lhs, rhs):\n all_set = lhs.model_class._query.all_index()\n index = lhs.get_index(OP_NE)\n exclude_set = index.get_key(lhs.db_value(rhs))\n tmp_set = all_set.diffstore(self.database.get_temp_key(), exclude_set)\n tmp_set.expire(self.temp_key_expire)\n return tmp_set\n\n def _zset_score_filter(self, zset, low, high):\n tmp_set = self.database.Set(self.database.get_temp_key())\n self.database.run_script(\n 'zset_score_filter',\n keys=[zset.key, tmp_set.key],\n args=[low, high])\n tmp_set.expire(self.temp_key_expire)\n return tmp_set\n\n def execute_between(self, lhs, rhs):\n index = lhs.get_index(OP_BETWEEN)\n low, high = map(lhs.db_value, rhs)\n zset = index.get_key(None) # No value necessary.\n return self._zset_score_filter(zset, low, high)\n\n def execute_lte(self, lhs, rhs):\n index = lhs.get_index(OP_LTE)\n db_value = lhs.db_value(rhs)\n zset = index.get_key(db_value)\n return self._zset_score_filter(zset, float('-inf'), db_value)\n\n def execute_gte(self, lhs, rhs):\n index = lhs.get_index(OP_GTE)\n db_value = lhs.db_value(rhs)\n zset = index.get_key(db_value)\n return self._zset_score_filter(zset, db_value, float('inf'))\n\n def execute_lt(self, lhs, rhs):\n index = lhs.get_index(OP_LTE)\n db_value = lhs.db_value(rhs)\n zset = index.get_key(db_value)\n return self._zset_score_filter(zset, float('-inf'), '(%s' % db_value)\n\n def execute_gt(self, lhs, rhs):\n index = lhs.get_index(OP_GTE)\n db_value = lhs.db_value(rhs)\n zset = index.get_key(db_value)\n return self._zset_score_filter(zset, '(%s' % db_value, float('inf'))\n\n def execute_match(self, lhs, rhs):\n index = lhs.get_index(OP_MATCH)\n db_value = lhs.db_value(rhs)\n words = index.tokenizer.tokenize(db_value)\n index_keys = []\n for word in words:\n index_keys.append(index.get_key(word).key)\n\n results = self.database.ZSet(self.database.get_temp_key())\n if index_keys:\n self.database.zinterstore(results.key, index_keys)\n results.expire(self.temp_key_expire)\n\n return results\n\n def _combine_sets(self, lhs, rhs, operation):\n if not isinstance(lhs, (Set, ZSet)):\n lhs = self.execute(lhs)\n if not isinstance(rhs, (Set, ZSet)):\n rhs = self.execute(rhs)\n\n source, dest = lhs, rhs\n if type(lhs) != type(rhs):\n # We'll perform the operation using the ZSet, as you can't call\n # SINTERSTORE or SUNIONSTORE with a ZSet.\n if isinstance(rhs, ZSet):\n source, dest = rhs, lhs\n\n if operation == 'AND':\n method = source.interstore\n elif operation == 'OR':\n method = source.unionstore\n else:\n raise ValueError('Unrecognized operation: \"%s\".' % operation)\n\n tmp_set = method(self.database.get_temp_key(), dest)\n tmp_set.expire(self.temp_key_expire)\n return tmp_set\n\n def execute_or(self, lhs, rhs):\n return self._combine_sets(lhs, rhs, 'OR')\n\n def execute_and(self, lhs, rhs):\n return self._combine_sets(lhs, rhs, 'AND')\n" }, { "alpha_fraction": 0.5091658234596252, "alphanum_fraction": 0.5350291132926941, "avg_line_length": 31.428571701049805, "blob_id": "4dd48dcf7d824d533337e313a3573ff4f46c2425", "content_id": "aa22e52e0a4caacb6f735bb115177bacb5d7b8b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7037, "license_type": "permissive", "max_line_length": 79, "num_lines": 217, "path": "/walrus/tusks/helpers.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom walrus import *\n\n\nclass TestHelper(object):\n def test_simple_string_ops(self):\n self.assertTrue(self.db.set('name', 'charlie'))\n self.assertEqual(self.db.get('name'), 'charlie')\n self.assertIsNone(self.db.get('not-exist'))\n\n self.assertFalse(self.db.setnx('name', 'huey'))\n self.db.setnx('friend', 'zaizee')\n self.assertEqual(self.db['name'], 'charlie')\n self.assertEqual(self.db['friend'], 'zaizee')\n\n self.assertTrue(self.db.mset({'k1': 'v1', 'k2': 'v2'}))\n res = self.db.mget('k1', 'k2')\n self.assertEqual(res, ['v1', 'v2'])\n\n self.db.append('k1', 'xx')\n self.assertEqual(self.db['k1'], 'v1xx')\n\n del self.db['counter']\n self.assertEqual(self.db.incr('counter'), 1)\n self.assertEqual(self.db.incr('counter', 5), 6)\n self.assertEqual(self.db.decr('counter', 2), 4)\n\n self.assertEqual(self.db.getrange('name', 3, 5), 'rli')\n self.assertEqual(self.db.getset('k2', 'baze'), 'v2')\n self.assertEqual(self.db['k2'], 'baze')\n self.assertEqual(self.db.strlen('name'), 7)\n\n self.db['data'] = '\\x07'\n self.assertEqual(self.db.bitcount('data'), 3)\n\n del self.db['name']\n self.assertIsNone(self.db.get('name'))\n self.assertRaises(KeyError, lambda: self.db['name'])\n\n self.assertFalse('name' in self.db)\n self.assertTrue('k1' in self.db)\n\n def test_simple_hash(self):\n h = self.db.Hash('hash_obj')\n h.clear()\n\n h['k1'] = 'v1'\n h.update({'k2': 'v2', 'k3': 'v3'})\n self.assertEqual(h.as_dict(), {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'})\n\n self.assertEqual(h['k2'], 'v2')\n self.assertIsNone(h['k4'])\n self.assertTrue('k2' in h)\n self.assertFalse('k4' in h)\n\n del h['k2']\n del h['k4']\n self.assertEqual(sorted(h.keys()), ['k1', 'k3'])\n self.assertEqual(sorted(h.values()), ['v1', 'v3'])\n self.assertEqual(len(h), 2)\n\n self.assertEqual(h['k1', 'k2', 'k3'], ['v1', None, 'v3'])\n\n self.assertEqual(h.incr('counter'), 1)\n self.assertEqual(h.incr('counter', 3), 4)\n\n def test_simple_list(self):\n l = self.db.List('list_obj')\n l.clear()\n\n l.append('charlie')\n l.extend(['mickey', 'huey', 'zaizee'])\n self.assertEqual(l[1], 'mickey')\n self.assertEqual(l[-1], 'zaizee')\n\n self.assertEqual(l[:], ['charlie', 'mickey', 'huey', 'zaizee'])\n self.assertEqual(l[1:-1], ['mickey', 'huey'])\n self.assertEqual(l[2:], ['huey', 'zaizee'])\n self.assertEqual(len(l), 4)\n\n l.prepend('nuggie')\n l.popright()\n l.popright()\n self.assertEqual([item for item in l], ['nuggie', 'charlie', 'mickey'])\n\n self.assertEqual(l.popleft(), 'nuggie')\n self.assertEqual(l.popright(), 'mickey')\n\n l.clear()\n self.assertEqual(list(l), [])\n self.assertIsNone(l.popleft())\n\n def test_simple_set(self):\n s = self.db.Set('set_obj')\n s.clear()\n\n self.assertTrue(s.add('charlie'))\n self.assertFalse(s.add('charlie'))\n s.add('huey', 'mickey')\n self.assertEqual(len(s), 3)\n self.assertTrue('huey' in s)\n self.assertFalse('xx' in s)\n self.assertEqual(s.members(), set(['charlie', 'huey', 'mickey']))\n\n del s['huey']\n del s['xx']\n self.assertEqual(s.members(), set(['charlie', 'mickey']))\n\n n1 = self.db.Set('n1')\n n2 = self.db.Set('n2')\n n1.add(*range(5))\n n2.add(*range(3, 7))\n\n self.assertEqual(n1 - n2, set(['0', '1', '2']))\n self.assertEqual(n2 - n1, set(['5', '6']))\n self.assertEqual(n1 | n2, set(map(str, range(7))))\n self.assertEqual(n1 & n2, set(['3', '4']))\n\n n1.diffstore('ndiff', n2)\n ndiff = self.db.Set('ndiff')\n self.assertEqual(ndiff.members(), set(['0', '1', '2']))\n\n n1.interstore('ninter', n2)\n ninter = self.db.Set('ninter')\n self.assertEqual(ninter.members(), set(['3', '4']))\n\n def test_zset(self):\n zs = self.db.ZSet('zset_obj')\n zs.clear()\n\n zs.add('charlie', 31, 'huey', 3, 'mickey', 6, 'zaizee', 3, 'nuggie', 0)\n self.assertEqual(zs[1], ['huey'])\n self.assertEqual(zs[1, True], [('huey', 3)])\n\n self.assertEqual(\n zs[:],\n ['nuggie', 'huey', 'zaizee', 'mickey', 'charlie'])\n self.assertEqual(zs[:2], ['nuggie', 'huey'])\n self.assertEqual(zs[1:3, True], [('huey', 3), ('zaizee', 3)])\n self.assertEqual(zs['huey':'charlie'], ['huey', 'zaizee', 'mickey'])\n\n self.assertEqual(len(zs), 5)\n self.assertTrue('charlie' in zs)\n self.assertFalse('xx' in zs)\n\n self.assertEqual(zs.score('charlie'), 31.)\n self.assertIsNone(zs.score('xx'))\n\n self.assertEqual(zs.rank('mickey'), 3)\n self.assertIsNone(zs.rank('xx'))\n\n self.assertEqual(zs.count(0, 5), 3)\n self.assertEqual(zs.count(6, 31), 2)\n self.assertEqual(zs.count(6, 30), 1)\n\n zs.incr('mickey')\n self.assertEqual(zs.score('mickey'), 7.)\n\n self.assertEqual(zs.range_by_score(0, 5), ['nuggie', 'huey', 'zaizee'])\n\n zs.remove('nuggie')\n self.assertEqual(zs[:2], ['huey', 'zaizee'])\n\n del zs['mickey']\n self.assertEqual(zs[:], ['huey', 'zaizee', 'charlie'])\n self.assertEqual(len(zs), 3)\n\n zs.remove_by_score(2, 4)\n self.assertEqual(zs[:], ['charlie'])\n\n zs.add('huey', 4, 'zaizee', 3, 'beanie', 8)\n zs.remove_by_rank(2)\n self.assertEqual(zs[:], ['zaizee', 'huey', 'charlie'])\n\n self.assertRaises(KeyError, lambda: zs['xx':])\n\n z1 = self.db.ZSet('z1')\n z2 = self.db.ZSet('z2')\n z1.add(1, 1, 2, 2, 3, 3)\n z2.add(3, 3, 4, 4, 5, 5)\n z3 = z1.unionstore('z3', z2)\n self.assertEqual(z3[:], ['1', '2', '4', '5', '3'])\n\n z3 = z1.interstore('z3', z2)\n self.assertEqual(z3[:], ['3'])\n\n def test_models(self):\n class User(Model):\n __database__ = self.db\n username = TextField(primary_key=True)\n value = IntegerField(index=True)\n\n for i, username in enumerate(('charlie', 'huey', 'zaizee', 'mickey')):\n User.create(username=username, value=i)\n\n charlie = User.load('charlie')\n self.assertEqual(charlie.username, 'charlie')\n self.assertEqual(charlie.value, 0)\n\n query = User.query(\n (User.username == 'charlie') |\n (User.username == 'huey'))\n users = [user.username for user in query]\n self.assertEqual(sorted(users), ['charlie', 'huey'])\n\n def test_cache(self):\n cache = self.db.cache(name='test-cache')\n\n @cache.cached(timeout=10)\n def now(seed=None):\n return datetime.datetime.now()\n\n dt1 = now()\n self.assertEqual(now(), dt1)\n self.assertNotEqual(now(1), dt1)\n self.assertEqual(now(1), now(1))\n" }, { "alpha_fraction": 0.5753317475318909, "alphanum_fraction": 0.5862607359886169, "avg_line_length": 27.46666717529297, "blob_id": "75cf171f314b97f96d729661e524226eeecb64cd", "content_id": "15bdc3b35ed605512d1512dab797165f096dbc64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1281, "license_type": "permissive", "max_line_length": 54, "num_lines": 45, "path": "/setup.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import os\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\ncur_dir = os.path.dirname(__file__)\nreadme = os.path.join(cur_dir, 'README.md')\nif os.path.exists(readme):\n with open(readme) as fh:\n long_description = fh.read()\nelse:\n long_description = ''\n\nsetup(\n name='walrus',\n version=__import__('walrus').__version__,\n description='walrus',\n long_description=long_description,\n author='Charles Leifer',\n author_email='[email protected]',\n url='http://github.com/coleifer/walrus/',\n install_requires=['redis>=3.0.0'],\n packages=find_packages(),\n package_data={\n 'walrus': [\n 'scripts/*',\n 'stopwords.txt',\n ],\n },\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n test_suite='walrus.tests',\n)\n" }, { "alpha_fraction": 0.4949870705604553, "alphanum_fraction": 0.4949870705604553, "avg_line_length": 14.93814468383789, "blob_id": "554f06afa6306d19edc2586fa5cbccfcfdc4f72a", "content_id": "9a5fbf1cc78e065e745da9833f389110f34794c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6184, "license_type": "permissive", "max_line_length": 131, "num_lines": 388, "path": "/docs/api.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _api:\n\nAPI Documentation\n=================\n\n.. py:module:: walrus\n\n.. autoclass:: Database(Redis)\n :members:\n __init__,\n run_script,\n get_temp_key,\n __iter__,\n search,\n get_key,\n cache,\n counter,\n graph,\n lock,\n rate_limit,\n rate_limit_lua,\n Index,\n List,\n Hash,\n Set,\n ZSet,\n HyperLogLog,\n Array,\n Stream,\n consumer_group,\n time_series,\n bit_field,\n bloom_filter,\n cas,\n xsetid,\n listener,\n stream_log\n\nContainer types\n---------------\n\n.. autoclass:: Container\n :members:\n\n\n.. autoclass:: Hash(Container)\n :members:\n __getitem__,\n __setitem__,\n __delitem__,\n __contains__,\n __len__,\n __iter__,\n search,\n keys,\n values,\n items,\n update,\n incr,\n as_dict\n\n.. autoclass:: List(Container)\n :members:\n __getitem__,\n __setitem__,\n __delitem__,\n __len__,\n __iter__,\n append,\n prepend,\n extend,\n insert_before,\n insert_after,\n popleft,\n popright,\n as_list\n\n.. autoclass:: Set(Container)\n :members:\n add,\n __delitem__,\n remove,\n pop,\n __contains__,\n __len__,\n __iter__,\n search,\n members,\n random,\n __sub__,\n __or__,\n __and__,\n diffstore,\n interstore,\n unionstore,\n as_set\n\n.. autoclass:: ZSet(Container)\n :members:\n add,\n __getitem__,\n __setitem__,\n __delitem__,\n remove,\n __contains__,\n __len__,\n __iter__,\n search,\n score,\n rank,\n count,\n lex_count,\n range,\n range_by_score,\n range_by_lex,\n remove_by_rank,\n remove_by_score,\n remove_by_lex,\n incr,\n interstore,\n unionstore,\n popmin,\n popmax,\n bpopmin,\n bpopmax,\n popmin_compat,\n popmax_compat,\n as_items\n\n.. autoclass:: HyperLogLog(Container)\n :members:\n add,\n __len__,\n merge\n\n.. autoclass:: Array(Container)\n :members:\n __getitem__,\n __setitem__,\n __delitem__,\n __len__,\n append,\n extend,\n pop,\n __contains__,\n __iter__,\n as_list\n\n.. autoclass:: Stream(Container)\n :members:\n __getitem__,\n __delitem__,\n __len__,\n add,\n get,\n range,\n read,\n delete,\n trim,\n info,\n groups_info,\n consumers_info,\n set_id,\n __iter__\n\n.. autoclass:: ConsumerGroup\n :members:\n consumer,\n create,\n destroy,\n reset,\n set_id,\n read,\n stream_info\n\n.. autoclass:: walrus.containers.ConsumerGroupStream(Stream)\n :members:\n consumers_info,\n ack,\n claim,\n pending,\n autoclaim,\n read,\n set_id\n\n.. autoclass:: BitField(Container)\n :members:\n incrby,\n get,\n set,\n __getitem__,\n __setitem__,\n __delitem__,\n get_raw,\n set_raw,\n bit_count,\n get_bit,\n set_bit\n\n.. autoclass:: walrus.containers.BitFieldOperation\n :members:\n incrby,\n get,\n set,\n execute,\n __iter__\n\n.. autoclass:: BloomFilter(Container)\n :members:\n add,\n contains,\n __contains__\n\nHigh-level APIs\n---------------\n\n.. autoclass:: Autocomplete\n :members:\n __init__,\n store,\n search,\n exists,\n boost_object,\n remove,\n list_data,\n list_titles,\n flush\n\n.. autoclass:: Cache\n :members:\n __init__,\n get,\n set,\n delete,\n get_many,\n set_many,\n delete_many,\n keys,\n flush,\n incr,\n cached,\n cached_property,\n cache_async\n\n.. autoclass:: Counter\n :members:\n __init__,\n incr,\n decr,\n value\n\n.. autoclass:: Index\n :members:\n __init__,\n get_document,\n add,\n remove,\n update,\n replace,\n search,\n search_items\n\n.. autoclass:: Graph\n :members:\n __init__,\n store,\n store_many,\n delete,\n query,\n search,\n v\n\n.. autoclass:: Lock\n :members:\n __init__,\n acquire,\n release,\n clear\n\n.. autoclass:: Model\n :members:\n __database__,\n __namespace__,\n index_separator,\n __init__,\n incr,\n to_hash,\n create,\n all,\n query,\n query_delete,\n get,\n load,\n delete,\n save,\n count\n\n.. autoclass:: RateLimit\n :members:\n __init__,\n limit,\n rate_limited\n\n.. autoclass:: RateLimitLua(RateLimit)\n :members:\n limit\n\n.. autoclass:: TimeSeries(ConsumerGroup)\n :members:\n consumer,\n create,\n destroy,\n reset,\n read,\n set_id\n\nField types\n-----------\n\n.. autoclass:: Field\n :members:\n __init__,\n get_indexes\n\n.. autoclass:: TextField\n :members:\n\n .. py:method:: search(query[, default_conjunction='and'])\n\n :param str query: Search query.\n :param str default_conjunction: Either ``'and'`` or ``'or'``.\n\n Create an expression corresponding to the given search query. Search queries can contain conjunctions (``AND`` and ``OR``).\n\n Example:\n\n .. code-block:: python\n\n class Message(Model):\n database = my_db\n content = TextField(fts=True)\n\n expression = Message.content.search('python AND (redis OR walrus)')\n messages = Message.query(expression)\n for message in messages:\n print(message.content)\n\n.. autoclass:: IntegerField\n :members:\n\n.. autoclass:: AutoIncrementField(IntegerField)\n :members:\n\n.. autoclass:: FloatField\n :members:\n\n.. autoclass:: ByteField\n :members:\n\n.. autoclass:: BooleanField\n :members:\n\n.. autoclass:: UUIDField\n :members:\n\n.. autoclass:: DateTimeField\n :members:\n\n.. autoclass:: DateField\n :members:\n\n.. autoclass:: JSONField\n :members:\n\nContainer Field Types\n^^^^^^^^^^^^^^^^^^^^^\n\n.. autoclass:: HashField\n :members:\n\n.. autoclass:: ListField\n :members:\n\n.. autoclass:: SetField\n :members:\n\n.. autoclass:: ZSetField\n :members:\n" }, { "alpha_fraction": 0.5920526385307312, "alphanum_fraction": 0.5938588380813599, "avg_line_length": 31.98297882080078, "blob_id": "80bd4109fae5795619399fc5c8733f83740403a0", "content_id": "f534ad5ed9c7e2eaa1158eb680cbd0b602f1b7c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15502, "license_type": "permissive", "max_line_length": 79, "num_lines": 470, "path": "/walrus/database.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from functools import wraps\nimport glob\nimport os\nimport sys\nimport threading\nimport uuid\n\ntry:\n from redis import Redis\n from redis.exceptions import ConnectionError\n from redis.exceptions import TimeoutError\nexcept ImportError:\n Redis = object\n ConnectionError = TimeoutError = Exception\n\nfrom walrus.autocomplete import Autocomplete\nfrom walrus.cache import Cache\nfrom walrus.containers import Array\nfrom walrus.containers import BitField\nfrom walrus.containers import BloomFilter\nfrom walrus.containers import ConsumerGroup\nfrom walrus.containers import Hash\nfrom walrus.containers import HyperLogLog\nfrom walrus.containers import List\nfrom walrus.containers import Set\nfrom walrus.containers import Stream\nfrom walrus.containers import ZSet\nfrom walrus.counter import Counter\nfrom walrus.fts import Index\nfrom walrus.graph import Graph\nfrom walrus.lock import Lock\nfrom walrus.rate_limit import RateLimit\nfrom walrus.rate_limit import RateLimitLua\nfrom walrus.streams import TimeSeries\n\n\nclass TransactionLocal(threading.local):\n def __init__(self, **kwargs):\n super(TransactionLocal, self).__init__(**kwargs)\n self.pipes = []\n\n @property\n def pipe(self):\n if len(self.pipes):\n return self.pipes[-1]\n\n def commit(self):\n pipe = self.pipes.pop()\n return pipe.execute()\n\n def abort(self):\n pipe = self.pipes.pop()\n pipe.reset()\n\n\nclass Database(Redis):\n \"\"\"\n Redis-py client with some extras.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n :param args: Arbitrary positional arguments to pass to the\n base ``Redis`` instance.\n :param kwargs: Arbitrary keyword arguments to pass to the\n base ``Redis`` instance.\n :param str script_dir: Path to directory containing walrus\n scripts. Use \"script_dir=False\" to disable loading any scripts.\n \"\"\"\n script_dir = kwargs.pop('script_dir', None)\n super(Database, self).__init__(*args, **kwargs)\n self.__mapping = {\n b'list': self.List,\n b'set': self.Set,\n b'zset': self.ZSet,\n b'hash': self.Hash}\n self._transaction_local = TransactionLocal()\n self._transaction_lock = threading.RLock()\n if script_dir is not False:\n self.init_scripts(script_dir=script_dir)\n\n def __bool__(self):\n return True # Avoid falling back to __len__().\n\n def xsetid(self, name, id):\n \"\"\"\n Set the last ID of the given stream.\n\n :param name: stream identifier\n :param id: new value for last ID\n \"\"\"\n return self.execute_command('XSETID', name, id) == b'OK'\n\n def xpending_summary(self, key, group):\n \"\"\"\n Pending message summary report.\n\n :param key: stream identifier\n :param group: consumer group name\n :returns: dictionary of information about pending messages\n \"\"\"\n return self.xpending(key, group)\n\n def get_transaction(self):\n with self._transaction_lock:\n local = self._transaction_local\n local.pipes.append(self.pipeline())\n return local.pipe\n\n def commit_transaction(self):\n \"\"\"\n Commit the currently active transaction (Pipeline). If no\n transaction is active in the current thread, an exception\n will be raised.\n\n :returns: The return value of executing the Pipeline.\n :raises: ``ValueError`` if no transaction is active.\n \"\"\"\n with self._transaction_lock:\n local = self._transaction_local\n if not local.pipes:\n raise ValueError('No transaction is currently active.')\n return local.commit()\n\n def clear_transaction(self):\n \"\"\"\n Clear the currently active transaction (if exists). If the\n transaction stack is not empty, then a new pipeline will\n be initialized.\n\n :returns: No return value.\n :raises: ``ValueError`` if no transaction is active.\n \"\"\"\n with self._transaction_lock:\n local = self._transaction_local\n if not local.pipes:\n raise ValueError('No transaction is currently active.')\n local.abort()\n\n def atomic(self):\n return _Atomic(self)\n\n def init_scripts(self, script_dir=None):\n self._scripts = {}\n if not script_dir:\n script_dir = os.path.join(os.path.dirname(__file__), 'scripts')\n for filename in glob.glob(os.path.join(script_dir, '*.lua')):\n with open(filename, 'r') as fh:\n script_obj = self.register_script(fh.read())\n script_name = os.path.splitext(os.path.basename(filename))[0]\n self._scripts[script_name] = script_obj\n\n def run_script(self, script_name, keys=None, args=None):\n \"\"\"\n Execute a walrus script with the given arguments.\n\n :param script_name: The base name of the script to execute.\n :param list keys: Keys referenced by the script.\n :param list args: Arguments passed in to the script.\n :returns: Return value of script.\n\n .. note:: Redis scripts require two parameters, ``keys``\n and ``args``, which are referenced in lua as ``KEYS``\n and ``ARGV``.\n \"\"\"\n return self._scripts[script_name](keys, args)\n\n def get_temp_key(self):\n \"\"\"\n Generate a temporary random key using UUID4.\n \"\"\"\n return 'temp.%s' % uuid.uuid4()\n\n def __iter__(self):\n \"\"\"\n Iterate over the keys of the selected database.\n \"\"\"\n return iter(self.scan_iter())\n\n def __len__(self):\n return self.dbsize()\n\n def search(self, pattern):\n \"\"\"\n Search the keyspace of the selected database using the\n given search pattern.\n\n :param str pattern: Search pattern using wildcards.\n :returns: Iterator that yields matching keys.\n \"\"\"\n return self.scan_iter(pattern)\n\n def get_key(self, key):\n \"\"\"\n Return a rich object for the given key. For instance, if\n a hash key is requested, then a :py:class:`Hash` will be\n returned.\n\n Note: only works for Hash, List, Set and ZSet.\n\n :param str key: Key to retrieve.\n :returns: A hash, set, list, zset or array.\n \"\"\"\n return self.__mapping.get(self.type(key), self.__getitem__)(key)\n\n def hash_exists(self, key):\n return self.exists(key)\n\n def autocomplete(self, namespace='autocomplete', **kwargs):\n return Autocomplete(self, namespace, **kwargs)\n\n def cache(self, name='cache', default_timeout=3600):\n \"\"\"\n Create a :py:class:`Cache` instance.\n\n :param str name: The name used to prefix keys used to\n store cached data.\n :param int default_timeout: The default key expiry.\n :returns: A :py:class:`Cache` instance.\n \"\"\"\n return Cache(self, name=name, default_timeout=default_timeout)\n\n def counter(self, name):\n \"\"\"\n Create a :py:class:`Counter` instance.\n\n :param str name: The name used to store the counter's value.\n :returns: A :py:class:`Counter` instance.\n \"\"\"\n return Counter(self, name=name)\n\n def graph(self, name, *args, **kwargs):\n \"\"\"\n Creates a :py:class:`Graph` instance.\n\n :param str name: The namespace for the graph metadata.\n :returns: a :py:class:`Graph` instance.\n \"\"\"\n return Graph(self, name, *args, **kwargs)\n\n def lock(self, name, ttl=None, lock_id=None):\n \"\"\"\n Create a named :py:class:`Lock` instance. The lock implements\n an API similar to the standard library's ``threading.Lock``,\n and can also be used as a context manager or decorator.\n\n :param str name: The name of the lock.\n :param int ttl: The time-to-live for the lock in milliseconds\n (optional). If the ttl is ``None`` then the lock will not\n expire.\n :param str lock_id: Optional identifier for the lock instance.\n \"\"\"\n return Lock(self, name, ttl, lock_id)\n\n def rate_limit(self, name, limit=5, per=60, debug=False):\n \"\"\"\n Rate limit implementation. Allows up to `limit` of events every `per`\n seconds.\n\n See :ref:`rate-limit` for more information.\n \"\"\"\n return RateLimit(self, name, limit, per, debug)\n\n def rate_limit_lua(self, name, limit=5, per=60, debug=False):\n \"\"\"\n Rate limit implementation. Allows up to `limit` of events every `per`\n seconds. Uses a Lua script for atomicity.\n\n See :ref:`rate-limit` for more information.\n \"\"\"\n return RateLimitLua(self, name, limit, per, debug)\n\n def Index(self, name, **options):\n \"\"\"\n Create a :py:class:`Index` full-text search index with the given\n name and options.\n \"\"\"\n return Index(self, name, **options)\n\n def List(self, key):\n \"\"\"\n Create a :py:class:`List` instance wrapping the given key.\n \"\"\"\n return List(self, key)\n\n def Hash(self, key):\n \"\"\"\n Create a :py:class:`Hash` instance wrapping the given key.\n \"\"\"\n return Hash(self, key)\n\n def Set(self, key):\n \"\"\"\n Create a :py:class:`Set` instance wrapping the given key.\n \"\"\"\n return Set(self, key)\n\n def ZSet(self, key):\n \"\"\"\n Create a :py:class:`ZSet` instance wrapping the given key.\n \"\"\"\n return ZSet(self, key)\n\n def HyperLogLog(self, key):\n \"\"\"\n Create a :py:class:`HyperLogLog` instance wrapping the given\n key.\n \"\"\"\n return HyperLogLog(self, key)\n\n def Array(self, key):\n \"\"\"\n Create a :py:class:`Array` instance wrapping the given key.\n \"\"\"\n return Array(self, key)\n\n def Stream(self, key):\n \"\"\"\n Create a :py:class:`Stream` instance wrapping the given key.\n \"\"\"\n return Stream(self, key)\n\n def consumer_group(self, group, keys, consumer=None):\n \"\"\"\n Create a named :py:class:`ConsumerGroup` instance for the given key(s).\n\n :param group: name of consumer group\n :param keys: stream identifier(s) to monitor. May be a single stream\n key, a list of stream keys, or a key-to-minimum id mapping. The\n minimum id for each stream should be considered an exclusive\n lower-bound. The '$' value can also be used to only read values\n added *after* our command started blocking.\n :param consumer: name for consumer within group\n :returns: a :py:class:`ConsumerGroup` instance\n \"\"\"\n return ConsumerGroup(self, group, keys, consumer=consumer)\n\n def time_series(self, group, keys, consumer=None):\n \"\"\"\n Create a named :py:class:`TimeSeries` consumer-group for the\n given key(s). TimeSeries objects are almost identical to\n :py:class:`ConsumerGroup` except they offer a higher level of\n abstraction and read/write message ids as datetimes.\n\n :param group: name of consumer group\n :param keys: stream identifier(s) to monitor. May be a single stream\n key, a list of stream keys, or a key-to-minimum id mapping. The\n minimum id for each stream should be considered an exclusive\n lower-bound. The '$' value can also be used to only read values\n added *after* our command started blocking.\n :param consumer: name for consumer within group\n :returns: a :py:class:`TimeSeries` instance\n \"\"\"\n return TimeSeries(self, group, keys, consumer=consumer)\n\n def bit_field(self, key):\n \"\"\"\n Container for working with the Redis BITFIELD command.\n\n :returns: a :py:class:`BitField` instance.\n \"\"\"\n return BitField(self, key)\n\n def bloom_filter(self, key, size=64 * 1024):\n \"\"\"\n Create a :py:class:`BloomFilter` container type.\n\n Bloom-filters are probabilistic data-structures that are used to answer\n the question: \"is X a member of set S?\" It is possible to receive a\n false positive, but impossible to receive a false negative (in other\n words, if the bloom filter contains a value, it will never erroneously\n report that it does *not* contain such a value). The accuracy of the\n bloom-filter and the likelihood of a false positive can be reduced by\n increasing the size of the bloomfilter. The default size is 64KB (or\n 524,288 bits).\n \"\"\"\n return BloomFilter(self, key, size)\n\n def cas(self, key, value, new_value):\n \"\"\"\n Perform an atomic compare-and-set on the value in \"key\", using a prefix\n match on the provided value.\n \"\"\"\n return self.run_script('cas', keys=[key], args=[value, new_value])\n\n def listener(self, channels=None, patterns=None, is_async=False):\n \"\"\"\n Decorator for wrapping functions used to listen for Redis\n pub-sub messages.\n\n The listener will listen until the decorated function\n raises a ``StopIteration`` exception.\n\n :param list channels: Channels to listen on.\n :param list patterns: Patterns to match.\n :param bool is_async: Whether to start the listener in a\n separate thread.\n \"\"\"\n def decorator(fn):\n _channels = channels or []\n _patterns = patterns or []\n\n @wraps(fn)\n def inner():\n pubsub = self.pubsub()\n\n def listen():\n for channel in _channels:\n pubsub.subscribe(channel)\n for pattern in _patterns:\n pubsub.psubscribe(pattern)\n\n for data_dict in pubsub.listen():\n try:\n ret = fn(**data_dict)\n except StopIteration:\n pubsub.close()\n break\n\n if is_async:\n worker = threading.Thread(target=listen)\n worker.start()\n return worker\n else:\n listen()\n\n return inner\n return decorator\n\n def stream_log(self, callback, connection_id='monitor'):\n \"\"\"\n Stream Redis activity one line at a time to the given\n callback.\n\n :param callback: A function that accepts a single argument,\n the Redis command.\n \"\"\"\n conn = self.connection_pool.get_connection(connection_id, None)\n conn.send_command('monitor')\n while callback(conn.read_response()):\n pass\n\n\nclass _Atomic(object):\n def __init__(self, db):\n self.db = db\n\n @property\n def pipe(self):\n return self.db._transaction_local.pipe\n\n def __enter__(self):\n self.db.get_transaction()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type:\n self.clear(False)\n else:\n self.commit(False)\n\n def commit(self, begin_new=True):\n ret = self.db.commit_transaction()\n if begin_new:\n self.db.get_transaction()\n return ret\n\n def clear(self, begin_new=True):\n self.db.clear_transaction()\n if begin_new:\n self.db.get_transaction()\n" }, { "alpha_fraction": 0.5221261382102966, "alphanum_fraction": 0.5231434106826782, "avg_line_length": 31.362140655517578, "blob_id": "88656b9da44d8f7867667b1512b31c3feefc431b", "content_id": "b2f78e73085c056f5adfa7b57682e6d9bf17f63f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7864, "license_type": "permissive", "max_line_length": 91, "num_lines": 243, "path": "/walrus/graph.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "# Hexastore.\nimport itertools\nimport json\n\nfrom walrus.utils import decode\n\n\nclass _VariableGenerator(object):\n def __getattr__(self, name):\n return Variable(name)\n\n def __call__(self, name):\n return Variable(name)\n\n\nclass Graph(object):\n \"\"\"\n Simple hexastore built using Redis ZSets. The basic idea is that we have\n a collection of relationships of the form subject-predicate-object. For\n example:\n\n * charlie -- friends -- huey\n * charlie -- lives -- Kansas\n * huey -- lives -- Kansas\n\n We might wish to ask questions of our data-store like \"which of charlie's\n friends live in Kansas?\" To do this we will store every permutation of\n the S-P-O triples, then we can do efficient queries using the parts of\n the relationship we know:\n\n * query the \"object\" portion of the \"charlie -- friends\" subject\n and predicate.\n * for each object returned, turn it into the subject of a second query\n whose predicate is \"lives\" and whose object is \"Kansas\"\n\n So we would return the subjects that satisfy the following expression::\n\n (\"charlie -- friends\") -- lives -- Kansas.\n\n To accomplish this in Python we could write:\n\n .. code-block:: python\n\n db = Database()\n graph = db.graph('people')\n\n # Store my friends.\n graph.store_many(\n ('charlie', 'friends', 'huey'),\n ('charlie', 'friends', 'zaizee'),\n ('charlie', 'friends', 'nuggie'))\n\n # Store where people live.\n graph.store_many(\n ('huey', 'lives', 'Kansas'),\n ('zaizee', 'lives', 'Missouri'),\n ('nuggie', 'lives', 'Kansas'),\n ('mickey', 'lives', 'Kansas'))\n\n # Perform our search. We will use a variable (X) to indicate the\n # value we're interested in.\n X = graph.v.X # Create a variable placeholder.\n\n # In the first clause we indicate we are searching for my friends.\n # In the second clause, we only want those friends who also live in\n # Kansas.\n results = graph.search(\n {'s': 'charlie', 'p': 'friends', 'o': X},\n {'s': X, 'p': 'lives', 'o': 'Kansas'})\n print results\n\n # Prints: {'X': {'huey', 'nuggie'}}\n\n See: http://redis.io/topics/indexes#representing-and-querying-graphs-using-an-hexastore\n \"\"\"\n def __init__(self, walrus, namespace):\n self.walrus = walrus\n self.namespace = namespace\n self.v = _VariableGenerator()\n self._z = self.walrus.ZSet(self.namespace)\n\n def store(self, s, p, o):\n \"\"\"\n Store a subject-predicate-object triple in the database.\n \"\"\"\n with self.walrus.atomic():\n for key in self.keys_for_values(s, p, o):\n self._z[key] = 0\n\n def store_many(self, items):\n \"\"\"\n Store multiple subject-predicate-object triples in the database.\n\n :param items: A list of (subj, pred, obj) 3-tuples.\n \"\"\"\n with self.walrus.atomic():\n for item in items:\n self.store(*item)\n\n def delete(self, s, p, o):\n \"\"\"Remove the given subj-pred-obj triple from the database.\"\"\"\n with self.walrus.atomic():\n for key in self.keys_for_values(s, p, o):\n del self._z[key]\n\n def keys_for_values(self, s, p, o):\n parts = [\n ('spo', s, p, o),\n ('pos', p, o, s),\n ('osp', o, s, p)]\n for part in parts:\n yield '::'.join(part)\n\n def keys_for_query(self, s=None, p=None, o=None):\n parts = []\n key = lambda parts: '::'.join(parts)\n\n if s and p and o:\n parts.extend(('spo', s, p, o))\n return key(parts), None\n elif s and p:\n parts.extend(('spo', s, p))\n elif s and o:\n parts.extend(('osp', s, o))\n elif p and o:\n parts.extend(('pos', p, o))\n elif s:\n parts.extend(('spo', s))\n elif p:\n parts.extend(('pos', p))\n elif o:\n parts.extend(('osp', o))\n else:\n parts.extend(('spo',))\n return key(parts + ['']), key(parts + ['\\xff'])\n\n def query(self, s=None, p=None, o=None):\n \"\"\"\n Return all triples that satisfy the given expression. You may specify\n all or none of the fields (s, p, and o). For instance, if I wanted\n to query for all the people who live in Kansas, I might write:\n\n .. code-block:: python\n\n for triple in graph.query(p='lives', o='Kansas'):\n print triple['s'], 'lives in Kansas!'\n \"\"\"\n start, end = self.keys_for_query(s, p, o)\n if end is None:\n if start in self._z:\n yield {'s': s, 'p': p, 'o': o}\n else:\n for key in self._z.range_by_lex('[' + start, '[' + end):\n keys, p1, p2, p3 = decode(key).split('::')\n yield dict(zip(keys, (p1, p2, p3)))\n\n def v(self, name):\n \"\"\"\n Create a named variable, used to construct multi-clause queries with\n the :py:meth:`Graph.search` method.\n \"\"\"\n return Variable(name)\n\n def search(self, *conditions):\n \"\"\"\n Given a set of conditions, return all values that satisfy the\n conditions for a given set of variables.\n\n For example, suppose I wanted to find all of my friends who live in\n Kansas:\n\n .. code-block:: python\n\n X = graph.v.X\n results = graph.search(\n {'s': 'charlie', 'p': 'friends', 'o': X},\n {'s': X, 'p': 'lives', 'o': 'Kansas'})\n\n The return value consists of a dictionary keyed by variable, whose\n values are ``set`` objects containing the values that satisfy the\n query clauses, e.g.:\n\n .. code-block:: python\n\n print results\n\n # Result has one key, for our \"X\" variable. The value is the set\n # of my friends that live in Kansas.\n # {'X': {'huey', 'nuggie'}}\n\n # We can assume the following triples exist:\n # ('charlie', 'friends', 'huey')\n # ('charlie', 'friends', 'nuggie')\n # ('huey', 'lives', 'Kansas')\n # ('nuggie', 'lives', 'Kansas')\n \"\"\"\n results = {}\n\n for condition in conditions:\n if isinstance(condition, tuple):\n query = dict(zip('spo', condition))\n else:\n query = condition.copy()\n materialized = {}\n targets = []\n\n for part in ('s', 'p', 'o'):\n if isinstance(query[part], Variable):\n variable = query.pop(part)\n materialized[part] = set()\n targets.append((variable, part))\n\n # Potentially rather than popping all the variables, we could use\n # the result values from a previous condition and do O(results)\n # loops looking for a single variable.\n for result in self.query(**query):\n ok = True\n for var, part in targets:\n if var in results and result[part] not in results[var]:\n ok = False\n break\n\n if ok:\n for var, part in targets:\n materialized[part].add(result[part])\n\n for var, part in targets:\n if var in results:\n results[var] &= materialized[part]\n else:\n results[var] = materialized[part]\n\n return dict((var.name, vals) for (var, vals) in results.items())\n\n\nclass Variable(object):\n __slots__ = ['name']\n\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return '<Variable: %s>' % (self.name)\n" }, { "alpha_fraction": 0.5330904722213745, "alphanum_fraction": 0.5364298820495605, "avg_line_length": 30.371429443359375, "blob_id": "7a528c34ef49b2887579e417c62bee0862227d77", "content_id": "f565cc1ec1045fa79d732dc9534176421f4cb82b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3294, "license_type": "permissive", "max_line_length": 73, "num_lines": 105, "path": "/walrus/search/__init__.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import re\n\nfrom walrus.search.metaphone import dm as double_metaphone\nfrom walrus.search.porter import PorterStemmer\nfrom walrus.utils import decode\nfrom walrus.utils import load_stopwords\n\n\nclass Tokenizer(object):\n def __init__(self, stemmer=True, metaphone=False,\n stopwords_file='stopwords.txt', min_word_length=None):\n self._use_stemmer = stemmer\n self._use_metaphone = metaphone\n self._min_word_length = min_word_length\n self._symbols_re = re.compile(\n '[\\.,;:\"\\'\\\\/!@#\\$%\\?\\*\\(\\)\\-=+\\[\\]\\{\\}_]')\n\n self._stopwords = self._load_stopwords(stopwords_file)\n\n def _load_stopwords(self, filename):\n stopwords = load_stopwords(filename)\n if stopwords:\n return set(stopwords.splitlines())\n\n def split_phrase(self, phrase):\n \"\"\"Split the document or search query into tokens.\"\"\"\n return self._symbols_re.sub(' ', phrase).split()\n\n def stem(self, words):\n \"\"\"\n Use the porter stemmer to generate consistent forms of\n words, e.g.::\n\n from walrus.search.utils import PorterStemmer\n stemmer = PorterStemmer()\n for word in ['faith', 'faiths', 'faithful']:\n print s.stem(word, 0, len(word) - 1)\n\n # Prints:\n # faith\n # faith\n # faith\n \"\"\"\n stemmer = PorterStemmer()\n _stem = stemmer.stem\n for word in words:\n yield _stem(word, 0, len(word) - 1)\n\n def metaphone(self, words):\n \"\"\"\n Apply the double metaphone algorithm to the given words.\n Using metaphone allows the search index to tolerate\n misspellings and small typos.\n\n Example::\n\n >>> from walrus.search.metaphone import dm as metaphone\n >>> print metaphone('walrus')\n ('ALRS', 'FLRS')\n\n >>> print metaphone('python')\n ('P0N', 'PTN')\n\n >>> print metaphone('pithonn')\n ('P0N', 'PTN')\n \"\"\"\n for word in words:\n r = 0\n for w in double_metaphone(word):\n if w:\n w = w.strip()\n if w:\n r += 1\n yield w\n if not r:\n yield word\n\n def tokenize(self, value):\n \"\"\"\n Split the incoming value into tokens and process each token,\n optionally stemming or running metaphone.\n\n :returns: A ``dict`` mapping token to score. The score is\n based on the relative frequency of the word in the\n document.\n \"\"\"\n words = self.split_phrase(decode(value).lower())\n if self._stopwords:\n words = [w for w in words if w not in self._stopwords]\n if self._min_word_length:\n words = [w for w in words if len(w) >= self._min_word_length]\n\n fraction = 1. / (len(words) + 1) # Prevent division by zero.\n\n # Apply optional transformations.\n if self._use_stemmer:\n words = self.stem(words)\n if self._use_metaphone:\n words = self.metaphone(words)\n\n scores = {}\n for word in words:\n scores.setdefault(word, 0)\n scores[word] += fraction\n return scores\n" }, { "alpha_fraction": 0.5484163165092468, "alphanum_fraction": 0.5511312484741211, "avg_line_length": 26.625, "blob_id": "c7225f8684d250fb51553de3747e16559bd9358b", "content_id": "7b580e90b2d888331e53f65611ee6b5377c4900b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1105, "license_type": "permissive", "max_line_length": 69, "num_lines": 40, "path": "/walrus/counter.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "class Counter(object):\n \"\"\"\n Simple counter.\n \"\"\"\n def __init__(self, database, name):\n \"\"\"\n :param database: A walrus ``Database`` instance.\n :param str name: The name for the counter.\n \"\"\"\n self.database = database\n self.name = name\n self.key = 'counter:%s' % self.name\n if self.key not in self.database:\n self.database[self.key] = 0\n\n def decr(self, decr_by=1):\n return self.database.decr(self.key, decr_by)\n\n def incr(self, incr_by=1):\n return self.database.incr(self.key, incr_by)\n\n def value(self):\n return int(self.database[self.key])\n\n def _op(self, method, other):\n if isinstance(other, Counter):\n other = other.value()\n if not isinstance(other, int):\n raise TypeError('Cannot add %s, not an integer.' % other)\n method(other)\n return self\n\n def __iadd__(self, other):\n return self._op(self.incr, other)\n\n def __isub__(self, other):\n return self._op(self.decr, other)\n\n __add__ = __iadd__\n __sub__ = __isub__\n" }, { "alpha_fraction": 0.674124538898468, "alphanum_fraction": 0.6838521361351013, "avg_line_length": 37.074073791503906, "blob_id": "75d82af99caea54d49793b6eecacb966a2c5a0c0", "content_id": "eb9f8da654bf33b09e381c302177e74cd037802e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1028, "license_type": "permissive", "max_line_length": 307, "num_lines": 27, "path": "/docs/getting-started.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _getting-started:\n\n.. py:module:: walrus\n\nGetting Started\n===============\n\nThe purpose of `walrus <https://github.com/coleifer/walrus>`_ is to make working with Redis in Python a little easier by wrapping rich objects in Pythonic containers.\n\nLet's see how this works by using ``walrus`` in the Python interactive shell. Make sure you have `redis <http://redis.io>`_ installed and running locally.\n\nIntroducing walrus\n------------------\n\nTo begin using walrus, we'll start by importing it and creating a :py:class:`Database` instance. The ``Database`` object is a thin wrapper over the `redis-py <https://redis-py.readthedocs.io/>`_ ``Redis`` class, so any methods available on ``Redis`` will also be available on the walrus ``Database`` object.\n\n.. code-block:: pycon\n\n >>> from walrus import *\n >>> db = Database(host='localhost', port=6379, db=0)\n\nIf you like fun names, you can also use ``Walrus`` instead:\n\n.. code-block:: pycon\n\n >>> from walrus import *\n >>> db = Walrus(host='localhost', port=6379, db=0)\n" }, { "alpha_fraction": 0.6002498865127563, "alphanum_fraction": 0.6101329326629639, "avg_line_length": 35.987396240234375, "blob_id": "a4c872093189c3700aa029b6ec0e0f2ec76dea55", "content_id": "a6dfd6556976481b34b66a357b0b84cc655f4d4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8803, "license_type": "permissive", "max_line_length": 80, "num_lines": 238, "path": "/examples/work_queue.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "\"\"\"\nSimple multi-process task queue using Redis Streams.\n\nhttp://charlesleifer.com/blog/multi-process-task-queue-using-redis-streams/\n\"\"\"\nfrom collections import namedtuple\nfrom functools import wraps\nimport datetime\nimport multiprocessing\nimport pickle\nimport time\n\n# At the time of writing, the standard redis-py client does not implement\n# stream/consumer-group commands. We'll use \"walrus\", which extends the client\n# from redis-py to provide stream support and high-level, Pythonic containers.\n# More info: https://github.com/coleifer/walrus\nfrom walrus import Walrus\n\n\n# Lightweight wrapper for storing exceptions that occurred executing a task.\nTaskError = namedtuple('TaskError', ('error',))\n\n\nclass TaskQueue(object):\n def __init__(self, client, stream_key='tasks'):\n self.client = client # our Redis client.\n self.stream_key = stream_key\n\n # We'll also create a consumer group (whose name is derived from the\n # stream key). Consumer groups are needed to provide message delivery\n # tracking and to ensure that our messages are distributed among the\n # worker processes.\n self.name = stream_key + '-cg'\n self.consumer_group = self.client.consumer_group(self.name, stream_key)\n self.result_key = stream_key + '.results' # Store results in a Hash.\n\n # Obtain a reference to the stream within the context of the\n # consumer group.\n self.stream = getattr(self.consumer_group, stream_key)\n self.signal = multiprocessing.Event() # Used to signal shutdown.\n self.signal.set() # Indicate the server is not running.\n\n # Create the stream and consumer group (if they do not exist).\n self.consumer_group.create()\n self._running = False\n self._tasks = {} # Lookup table for mapping function name -> impl.\n\n def task(self, fn):\n self._tasks[fn.__name__] = fn # Store function in lookup table.\n\n @wraps(fn)\n def inner(*args, **kwargs):\n # When the decorated function is called, a message is added to the\n # stream and a wrapper class is returned, which provides access to\n # the task result.\n message = self.serialize_message(fn, args, kwargs)\n\n # Our message format is very simple -- just a \"task\" key and a blob\n # of pickled data. You could extend this to provide additional\n # data, such as the source of the event, etc, etc.\n task_id = self.stream.add({'task': message})\n return TaskResultWrapper(self, task_id)\n return inner\n\n def deserialize_message(self, message):\n task_name, args, kwargs = pickle.loads(message)\n if task_name not in self._tasks:\n raise Exception('task \"%s\" not registered with queue.')\n return self._tasks[task_name], args, kwargs\n\n def serialize_message(self, task, args=None, kwargs=None):\n return pickle.dumps((task.__name__, args, kwargs))\n\n def store_result(self, task_id, result):\n # API for storing the return value from a task. This is called by the\n # workers after the execution of a task.\n if result is not None:\n self.client.hset(self.result_key, task_id, pickle.dumps(result))\n\n def get_result(self, task_id):\n # Obtain the return value of a finished task. This API is used by the\n # TaskResultWrapper class. We'll use a pipeline to ensure that reading\n # and popping the result is an atomic operation.\n pipe = self.client.pipeline()\n pipe.hexists(self.result_key, task_id)\n pipe.hget(self.result_key, task_id)\n pipe.hdel(self.result_key, task_id)\n exists, val, n = pipe.execute()\n return pickle.loads(val) if exists else None\n\n def run(self, nworkers=1):\n if not self.signal.is_set():\n raise Exception('workers are already running')\n\n # Start a pool of worker processes.\n self._pool = []\n self.signal.clear()\n for i in range(nworkers):\n worker = TaskWorker(self)\n worker_t = multiprocessing.Process(target=worker.run)\n worker_t.start()\n self._pool.append(worker_t)\n\n def shutdown(self):\n if self.signal.is_set():\n raise Exception('workers are not running')\n\n # Send the \"shutdown\" signal and wait for the worker processes\n # to exit.\n self.signal.set()\n for worker_t in self._pool:\n worker_t.join()\n\n\nclass TaskWorker(object):\n _worker_idx = 0\n\n def __init__(self, queue):\n self.queue = queue\n self.consumer_group = queue.consumer_group\n\n # Assign each worker processes a unique name.\n TaskWorker._worker_idx += 1\n worker_name = 'worker-%s' % TaskWorker._worker_idx\n self.worker_name = worker_name\n\n def run(self):\n while not self.queue.signal.is_set():\n # Read up to one message, blocking for up to 1sec, and identifying\n # ourselves using our \"worker name\".\n resp = self.consumer_group.read(1, 1000, self.worker_name)\n if resp is not None:\n # Resp is structured as:\n # {stream_key: [(message id, data), ...]}\n for stream_key, message_list in resp:\n task_id, data = message_list[0]\n self.execute(task_id.decode('utf-8'), data[b'task'])\n\n def execute(self, task_id, message):\n # Deserialize the task message, which consists of the task name, args\n # and kwargs. The task function is then looked-up by name and called\n # using the given arguments.\n task, args, kwargs = self.queue.deserialize_message(message)\n try:\n ret = task(*(args or ()), **(kwargs or {}))\n except Exception as exc:\n # On failure, we'll store a special \"TaskError\" as the result. This\n # will signal to the user that the task failed with an exception.\n self.queue.store_result(task_id, TaskError(str(exc)))\n else:\n # Store the result and acknowledge (ACK) the message.\n self.queue.store_result(task_id, ret)\n self.queue.stream.ack(task_id)\n\n\nclass TaskResultWrapper(object):\n def __init__(self, queue, task_id):\n self.queue = queue\n self.task_id = task_id\n self._result = None\n\n def __call__(self, block=True, timeout=None):\n if self._result is None:\n # Get the result from the result-store, optionally blocking until\n # the result becomes available.\n if not block:\n result = self.queue.get_result(self.task_id)\n else:\n start = time.time()\n while timeout is None or (start + timeout) > time.time():\n result = self.queue.get_result(self.task_id)\n if result is None:\n time.sleep(0.1)\n else:\n break\n\n if result is not None:\n self._result = result\n\n if self._result is not None and isinstance(self._result, TaskError):\n raise Exception('task failed: %s' % self._result.error)\n\n return self._result\n\n\nif __name__ == '__main__':\n db = Walrus() # roughly equivalent to db = Redis().\n queue = TaskQueue(db)\n\n @queue.task\n def sleep(n):\n print('going to sleep for %s seconds' % n)\n time.sleep(n)\n print('woke up after %s seconds' % n)\n\n @queue.task\n def fib(n):\n a, b = 0, 1\n for _ in range(n):\n a, b = b, a + b\n return b\n\n # Start the queue with four worker processes.\n queue.run(4)\n\n # Send four \"sleep\" tasks.\n sleep(2)\n sleep(3)\n sleep(4)\n sleep(5)\n\n # Send four tasks to compute large fibonacci numbers. We will then print the\n # last 6 digits of each computed number (showing how result storage works):\n v100k = fib(100000)\n v200k = fib(200000)\n v300k = fib(300000)\n v400k = fib(400000)\n\n # Calling the result wrapper will block until its value becomes available:\n print('100kth fib number starts ends with: %s' % str(v100k())[-6:])\n print('200kth fib number starts ends with: %s' % str(v200k())[-6:])\n print('300kth fib number starts ends with: %s' % str(v300k())[-6:])\n print('400kth fib number starts ends with: %s' % str(v400k())[-6:])\n\n # We can shutdown and restart the consumer.\n queue.shutdown()\n print('all workers have stopped.')\n\n queue.run(4)\n print('workers are running again.')\n\n # Enqueue another \"sleep\" task.\n sleep(2)\n\n # Calling shutdown now will block until the above sleep task\n # has finished, after which all workers will stop.\n queue.shutdown()\n print('done!')\n" }, { "alpha_fraction": 0.6574394702911377, "alphanum_fraction": 0.6747404932975769, "avg_line_length": 23.08333396911621, "blob_id": "a40edace4ab12ab8926998b7ae581d1c132ad9c7", "content_id": "89a22a2373611ea854ccd46241c14372405198aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 289, "license_type": "permissive", "max_line_length": 63, "num_lines": 12, "path": "/walrus/scripts/zset_score_filter.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "-- Filter.\nlocal zset_key = KEYS[1]\nlocal dest_key = KEYS[2]\nlocal low = ARGV[1]\nlocal high = ARGV[2]\nlocal values = redis.call('ZRANGEBYSCORE', zset_key, low, high)\nif # values > 0 then\n for i, value in ipairs(values) do\n redis.call('SADD', dest_key, value)\n end\nend\nreturn # values\n" }, { "alpha_fraction": 0.5434473156929016, "alphanum_fraction": 0.56695157289505, "avg_line_length": 27.363636016845703, "blob_id": "0790403a2e348caa490d339fc0a403853df154ea", "content_id": "76c96efdd95a252289b136860d2c56df3b51c8bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2808, "license_type": "permissive", "max_line_length": 66, "num_lines": 99, "path": "/walrus/tests/cache.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\ncache = db.cache(name='test.cache')\n\n\[email protected](timeout=60)\ndef now(seed=None):\n return datetime.datetime.now()\n\n\nclass Clock(object):\n @cache.cached_property()\n def now(self):\n return datetime.datetime.now()\n\n\nclass TestCache(WalrusTestCase):\n def test_cache_apis(self):\n # Nonexistant key returns None.\n self.assertTrue(cache.get('foo') is None)\n\n # Set key, value and expiration in seconds.\n self.assertEqual(cache.set('foo', 'bar', 60), True)\n self.assertEqual(cache.get('foo'), 'bar')\n\n self.assertEqual(cache.delete('foo'), 1)\n self.assertTrue(cache.get('foo') is None)\n self.assertEqual(cache.delete('foo'), 0)\n\n def test_cache_bulk_apis(self):\n self.assertEqual(cache.get_many(['k1', 'k2']), {})\n\n data = {'k1': 'v1', 'k2': 'v2'}\n self.assertEqual(cache.set_many(data, 60), True)\n self.assertEqual(cache.get_many(['k1', 'kx', 'k2']), data)\n self.assertEqual(cache.delete_many(['k1', 'kx', 'k2']), 2)\n self.assertEqual(cache.get_many(['k1', 'k2']), {})\n self.assertEqual(cache.delete_many(['k1', 'kx', 'k2']), 0)\n\n def test_cache_decorator(self):\n n0 = now() # Each should have its own cache-key.\n n1 = now(1)\n n2 = now(2)\n\n self.assertTrue(n0 != n1 != n2)\n self.assertEqual(now(), n0)\n self.assertEqual(now(1), n1)\n self.assertEqual(now(2), n2)\n\n now.bust(1)\n self.assertNotEqual(now(1), n1)\n self.assertEqual(now(1), now(1))\n\n def test_cached_property(self):\n c = Clock()\n n1 = c.now\n n2 = c.now\n self.assertEqual(n1, n2)\n\n del c.now # Property deleter busts the cache.\n n3 = c.now\n self.assertTrue(n1 != n3)\n self.assertEqual(c.now, n3)\n\n def test_cached_return_none(self):\n S = {'count': 0}\n @cache.cached()\n def returns_none(arg):\n S['count'] += 1\n\n def assertMisses(arg, n):\n returns_none(arg)\n self.assertEqual(S['count'], n)\n for i in range(3):\n assertMisses('foo', 1)\n assertMisses('bar', 2)\n assertMisses('foo', 2)\n\n def test_cached_async(self):\n @cache.cache_async()\n def double_value(value):\n return value * 2\n\n res = double_value(3)\n self.assertEqual(res(), 6)\n self.assertEqual(res(), 6)\n\n self.assertEqual(double_value(3)(), 6)\n self.assertEqual(double_value(4)(), 8)\n\n def test_flush_empty_cache(self):\n cache.set('foo', 'bar', 10)\n self.assertList(cache.keys(), ['test.cache:foo'])\n cache.flush()\n self.assertList(cache.keys(), [])\n" }, { "alpha_fraction": 0.61658775806427, "alphanum_fraction": 0.6715453863143921, "avg_line_length": 35.10880661010742, "blob_id": "4a3e5962540ae0e350b03ac90d9a35126bab54f9", "content_id": "7ee93deedb0f35d16fd8581be54eae066a74ffa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6969, "license_type": "permissive", "max_line_length": 485, "num_lines": 193, "path": "/docs/cache.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _cache:\n\n.. py:module:: walrus\n\nCache\n=====\n\nWalrus provides a simple :py:class:`Cache` implementation that makes use of Redis' key expiration feature. The cache can be used to set or retrieve values, and also provides a decorator (:py:meth:`Cache.cached`) for wrapping function or methods.\n\nBasic usage\n-----------\n\nYou can :py:meth:`~Cache.get`, :py:meth:`~Cache.set` and :py:meth:`~Cache.delete` objects directly from the cache.\n\n.. code-block:: pycon\n\n >>> from walrus import *\n >>> db = Database()\n >>> cache = db.cache()\n\n >>> cache.set('foo', 'bar', 10) # Set foo=bar, expiring in 10s.\n >>> cache.get('foo')\n 'bar'\n\n >>> time.sleep(10)\n >>> cache.get('foo') is None\n True\n\n >>> cache.set_many({'k1': 'v1', 'k2': 'v2'}, 300)\n True\n >>> cache.get_many(['k1', 'kx', 'k2'])\n {'k1': 'v1', 'k2': 'v2'}\n >>> cache.delete_many(['k1', 'kx', 'k2'])\n 2\n\nSimple Decorator\n----------------\n\nThe :py:meth:`Cache.cached` decorator will *memoize* the return values from the wrapped function for the given arguments. One way to visualize this is by creating a function that returns the current time and wrap it with the decorator. The decorated function will run the first time it is called and the return value is stored in the cache. Subsequent calls will not execute the function, but will instead return the cached value from the previous call, until the cached value expires.\n\n.. code-block:: pycon\n\n >>> @cache.cached(timeout=10)\n ... def get_time():\n ... return datetime.datetime.now()\n\n >>> print(get_time()) # First call, return value cached.\n 2015-01-07 18:26:42.730638\n\n >>> print(get_time()) # Hits the cache.\n 2015-01-07 18:26:42.730638\n\n >>> time.sleep(10) # Wait for cache to expire then call again.\n >>> print(get_time())\n 2015-01-07 18:26:53.529011\n\nIf a decorated function accepts arguments, then values will be cached based on the arguments specified. In the example below we'll pass a garbage argument to the ``get_time`` function to show how the cache varies for different arguments:\n\n.. code-block:: pycon\n\n >>> @cache.cached(timeout=60)\n ... def get_time(seed=None):\n ... return datetime.datetime.now()\n\n >>> print(get_time())\n 2015-01-07 18:30:53.831977\n\n >>> print(get_time())\n 2015-01-07 18:30:53.831977\n\n >>> print(get_time('foo'))\n 2015-01-07 18:30:56.614064\n\n >>> print(get_time('foo'))\n 2015-01-07 18:30:56.614064\n\n >>> print(get_time('bar'))\n 2015-01-07 18:31:01.497050\n\n >>> print(get_time('foo'))\n 2015-01-07 18:30:56.614064\n\nTo clear the cache, you can call the special ``bust()`` method on the decorated function:\n\n.. code-block:: pycon\n\n >>> get_time.bust('foo')\n >>> print(get_time('foo'))\n 2015-01-07 18:31:15.326435\n\nCached Property\n---------------\n\nPython supports dynamic instance attributes through the ``property`` decorator. A property looks like a normal instance attribute, but it's value is calculated at run-time. Walrus comes with a special decorator designed for implementing *cached properties*. Here is how you might use :py:meth:`~Cache.cached_property`:\n\n.. code-block:: pycon\n\n >>> class Clock(object):\n ... @cache.cached_property()\n ... def now(self):\n ... return datetime.datetime.now()\n\n >>> print(clock.now)\n 2015-01-12 21:10:34.335755\n\n >>> print(clock.now)\n 2015-01-12 21:10:34.335755\n\n.. _cache-async:\n\nCache Asynchronously\n--------------------\n\nIf you have a function that runs slowly and would like to be able to perform other operations while waiting for the return value, you might try the *asynchronous cache decorator*, :py:meth:`~Cache.cache_async`.\n\nThe :py:meth:`~Cache.cache_async` decorator will run the decorated function in a separate thread. The function therefore will return immediately, even though your code may be processing in the background. Calls to the decorated function will return a method on a synchronized queue object. When the value is calculated (or returned from the cache), it will be placed in the queue and you can retrieve it.\n\nLet's see how this works. We'll add a call to ``time.sleep`` in the decorated function to simulate a function that takes a while to run, and we'll also print a message indicating that we're inside the function body.\n\n.. code-block:: pycon\n\n >>> import time\n >>> @cache.cache_async()\n ... def get_now(seed=None):\n ... print('About to sleep for 5 seconds.')\n ... time.sleep(5)\n ... return datetime.datetime.now()\n\nThe first time we call our function we will see the message indicating our function is sleeping, but the function will return immediately! The return value can be used to get the *actual* return value of the decorated function:\n\n.. code-block:: pycon\n\n >>> result = get_now()\n About to sleep for 5 seconds.\n >>> result\n <function _get_value at 0x7fe3a4685de8>\n\nIf we attempt to check the result immediately, there will be no value because the function is still sleeping. In this case a queue ``Empty`` exception is raised:\n\n.. code-block:: pycon\n\n >>> result(block=False)\n Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.7/Queue.py\", line 165, in get\n raise Empty\n Queue.Empty\n\nWe can force our code to block until the result is ready, though:\n\n.. code-block:: pycon\n\n >>> print(result(block=True))\n 2015-01-12 21:28:25.266448\n\nNow that the result has been calculated and cached, a subsequent call to ``get_now()`` will not execute the function body. We can tell because the function does not print *About to sleep for 5 seconds*.\n\n.. code-block:: pycon\n\n >>> result = get_now()\n >>> print(result())\n 2015-01-12 21:28:25.266448\n\nThe result function can be called any number of times. It will always return the same value:\n\n.. code-block:: pycon\n\n >>> print(result())\n 2015-01-12 21:28:25.266448\n\nAnother trick is passing a timeout to the result function. Let's see what happens when we call ``get_now()`` using a different seed, then specify a timeout to block for the return value. Since we hard-coded a delay of 5 seconds, let's see what happens when we specify a timeout of 4 seconds:\n\n.. code-block:: pycon\n\n >>> print(get_now('foo')(timeout=4))\n About to sleep for 5 seconds.\n Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/home/charles/pypath/walrus/cache.py\", line 160, in _get_value\n result = q.get(block=block, timeout=timeout)\n File \"/usr/lib/python2.7/Queue.py\", line 176, in get\n raise Empty\n Queue.Empty\n\nNow let's try with a timeout of 6 seconds (being sure to use a different seed so we trigger the 5 second delay):\n\n.. code-block:: pycon\n\n >>> print(get_now('bar')(timeout=6))\n About to sleep for 5 seconds.\n 2015-01-12 21:46:49.060883\n\nSince the function returns a value within the given timeout, the value is returned.\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 23.75, "blob_id": "2e087d7494df1c3fef19d06159ca5b8ee9d5b758", "content_id": "ad718788c3d5c4453f1d2aad49441f69bbbb0e9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 198, "license_type": "permissive", "max_line_length": 47, "num_lines": 8, "path": "/walrus/scripts/array_pop.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal last_idx = redis.call('HLEN', key) - 1\nif last_idx < 0 then\n return nil\nend\nlocal value = redis.call('HGET', key, last_idx)\nredis.call('HDEL', key, last_idx)\nreturn value\n" }, { "alpha_fraction": 0.6392694115638733, "alphanum_fraction": 0.6575342416763306, "avg_line_length": 20.899999618530273, "blob_id": "05655435fe7a855ec43d132fb38444aa3cff5907", "content_id": "5a92e9c7296f63a4542e7e6e1f5858194e6f31f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 219, "license_type": "permissive", "max_line_length": 39, "num_lines": 10, "path": "/walrus/scripts/array_get.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal idx = tonumber(ARGV[1])\nlocal arr_len = redis.call('HLEN', key)\nif idx < 0 then\n idx = arr_len + idx\nend\nif idx < 0 or idx >= arr_len then\n return nil\nend\nreturn redis.call('HGET', key, idx)\n" }, { "alpha_fraction": 0.624758243560791, "alphanum_fraction": 0.6389425992965698, "avg_line_length": 26.210525512695312, "blob_id": "38144eba3028bc2c06529b98318dc7c72c24048f", "content_id": "f21109bb47e9e9206650590f439f841be7c1b0b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1551, "license_type": "permissive", "max_line_length": 78, "num_lines": 57, "path": "/walrus/tests/base.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import os\nimport unittest\nfrom distutils.version import StrictVersion\n\nfrom walrus import Database\n\n\nHOST = os.environ.get('WALRUS_REDIS_HOST') or '127.0.0.1'\nPORT = os.environ.get('WALRUS_REDIS_PORT') or 6379\n\ndb = Database(host=HOST, port=PORT, db=15)\n\n\nREDIS_VERSION = None\n\n\ndef requires_version(min_version):\n def decorator(fn):\n global REDIS_VERSION\n if REDIS_VERSION is None:\n REDIS_VERSION = db.info()['redis_version']\n too_old = StrictVersion(REDIS_VERSION) < StrictVersion(min_version)\n return unittest.skipIf(too_old,\n 'redis too old, requires %s' % min_version)(fn)\n return decorator\n\n\ndef stream_test(fn):\n test_stream = os.environ.get('TEST_STREAM')\n if not test_stream:\n return requires_version('4.9.101')(fn)\n else:\n return unittest.skipIf(not test_stream, 'skipping stream tests')(fn)\n\n\ndef zpop_test(fn):\n test_zpop = os.environ.get('TEST_ZPOP')\n if not test_zpop:\n return requires_version('4.9.101')(fn)\n else:\n return unittest.skipIf(not test_zpop, 'skipping zpop* tests')(fn)\n\n\nclass WalrusTestCase(unittest.TestCase):\n def setUp(self):\n db.flushdb()\n db._transaction_local.pipes = []\n\n def tearDown(self):\n db.flushdb()\n db._transaction_local.pipes = []\n\n def assertList(self, values, expected):\n values = list(values)\n self.assertEqual(len(values), len(expected))\n for value, item in zip(values, expected):\n self.assertEqual(value, item)\n" }, { "alpha_fraction": 0.5700165033340454, "alphanum_fraction": 0.5775947570800781, "avg_line_length": 30.947368621826172, "blob_id": "b49daa4029e0f098d2495852d96f24536e97ba26", "content_id": "164dd3a0d16957b28fbae7320cdb57a73c470362", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3035, "license_type": "permissive", "max_line_length": 79, "num_lines": 95, "path": "/walrus/tusks/rlite.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import fnmatch\nimport sys\nimport unittest\n\nfrom hirlite.hirlite import Rlite\n\nfrom walrus import *\nfrom walrus.tusks.helpers import TestHelper\n\n\nclass WalrusLite(Walrus):\n _invalid_callbacks = ('SET', 'MSET', 'LSET')\n\n def __init__(self, filename=':memory:', encoding='utf-8'):\n self._filename = filename\n self._encoding = encoding\n self._db = Rlite(path=filename, encoding=encoding)\n self.response_callbacks = self.__class__.RESPONSE_CALLBACKS.copy()\n for callback in self._invalid_callbacks:\n del self.response_callbacks[callback]\n\n def execute_command(self, *args, **options):\n command_name = args[0]\n result = self._db.command(*args)\n return self.parse_response(result, command_name, **options)\n\n def parse_response(self, result, command_name, **options):\n try:\n return self.response_callbacks[command_name.upper()](\n result, **options)\n except KeyError:\n return result\n\n def __repr__(self):\n if self._filename == ':memory:':\n db_file = 'in-memory database'\n else:\n db_file = self._filename\n return '<WalrusLite: %s>' % db_file\n\n def _filtered_scan(self, results, match=None, count=None):\n if match is not None:\n results = fnmatch.filter(results, match)\n if count:\n results = results[:count]\n return results\n\n def hscan_iter(self, key, match=None, count=None):\n return self._filtered_scan(self.hgetall(key), match, count)\n\n def sscan_iter(self, key, match=None, count=None):\n return self._filtered_scan(self.smembers(key), match, count)\n\n def zscan_iter(self, key, match=None, count=None):\n return self._filtered_scan(self.zrange(key, 0, -1), match, count)\n\n\nclass TestWalrusLite(TestHelper, unittest.TestCase):\n def setUp(self):\n self.db = WalrusLite()\n\n def test_list_set_delete_item(self):\n l = self.db.List('list_obj')\n l.clear()\n l.extend(['i1', 'i2', 'i3', 'i4'])\n l[-1] = 'ix'\n l[1] = 'iy'\n self.assertEqual(list(l), ['i1', 'iy', 'i3', 'ix'])\n\n l.prepend('nuggie')\n for idx in [-1, 2, 9]:\n del l[idx]\n self.assertEqual([item for item in l], ['nuggie', 'i1', 'i3'])\n\n def test_set_random_and_pop(self):\n s = self.db.Set('s_obj')\n s.add('charlie', 'mickey')\n self.assertTrue(s.random() in ['charlie', 'mickey'])\n self.assertTrue(s.pop() in ['charlie', 'mickey'])\n\n def test_zset_iter(self):\n zs = self.db.ZSet('z_obj').clear()\n zs.add('zaizee', 3, 'mickey', 6, 'charlie', 31, 'huey', 3, 'nuggie', 0)\n\n items = [item for item in zs]\n self.assertEqual(\n items,\n ['nuggie', 'huey', 'zaizee', 'mickey', 'charlie'])\n\n self.assertEqual(zs.search('*ie'), ['nuggie', 'charlie'])\n self.assertEqual(zs.search('*u*'), ['nuggie', 'huey'])\n\n\nif __name__ == '__main__':\n unittest.main(argv=sys.argv)\n" }, { "alpha_fraction": 0.6244344115257263, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 21.100000381469727, "blob_id": "5e031d4837e5e819612cb2f720fe75f2c63253a6", "content_id": "93118335f8a635d33da2a238b25770727c76f1a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 221, "license_type": "permissive", "max_line_length": 39, "num_lines": 10, "path": "/walrus/scripts/array_set.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal idx = tonumber(ARGV[1])\nlocal arr_len = redis.call('HLEN', key)\nif idx < 0 then\n idx = arr_len + idx\nend\nif idx < 0 or idx >= arr_len then\n return nil\nend\nredis.call('HSET', key, idx, ARGV[2])\n" }, { "alpha_fraction": 0.5841081738471985, "alphanum_fraction": 0.589180052280426, "avg_line_length": 29.33333396911621, "blob_id": "608f33364ba7d907a82ecceacec96c229f3b15c2", "content_id": "6ea4e3c99dee033dfc9293199881a10ecb16a2c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2366, "license_type": "permissive", "max_line_length": 72, "num_lines": 78, "path": "/walrus/tests/lock.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import threading\n\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass TestLock(WalrusTestCase):\n def test_lock(self):\n lock_a = db.lock('lock-a')\n lock_b = db.lock('lock-b')\n self.assertTrue(lock_a.acquire())\n self.assertTrue(lock_b.acquire())\n\n lock_a2 = db.lock('lock-a')\n self.assertFalse(lock_a2.acquire(block=False))\n self.assertFalse(lock_a2.release())\n self.assertNotEqual(lock_a._lock_id, lock_a2._lock_id)\n\n self.assertFalse(lock_a.acquire(block=False))\n self.assertFalse(lock_b.acquire(block=False))\n\n t_waiting = threading.Event()\n t_acquired = threading.Event()\n t_acknowledged = threading.Event()\n\n def wait_for_lock():\n lock_a = db.lock('lock-a')\n t_waiting.set()\n lock_a.acquire()\n t_acquired.set()\n t_acknowledged.wait()\n lock_a.release()\n\n waiter_t = threading.Thread(target=wait_for_lock)\n waiter_t.start()\n t_waiting.wait() # Wait until the thread is up and running.\n\n lock_a.release()\n t_acquired.wait()\n self.assertFalse(lock_a.acquire(block=False))\n t_acknowledged.set()\n waiter_t.join()\n self.assertTrue(lock_a.acquire(block=False))\n lock_a.release()\n\n def test_lock_ctx_mgr(self):\n lock_a = db.lock('lock-a')\n lock_a2 = db.lock('lock-a')\n with lock_a:\n self.assertFalse(lock_a2.acquire(block=False))\n self.assertTrue(lock_a2.acquire(block=False))\n\n def test_lock_decorator(self):\n lock = db.lock('lock-a')\n\n @lock\n def locked():\n lock2 = db.lock('lock-a')\n self.assertFalse(lock2.acquire(block=False))\n\n locked()\n\n @lock\n def raise_exception():\n raise ValueError()\n\n self.assertRaises(ValueError, raise_exception)\n\n # In the event of an exception, the lock will still be released.\n self.assertTrue(lock.acquire(block=False))\n\n def test_lock_cleanup(self):\n self.assertEqual(len(db), 0)\n lock = db.lock('lock-a')\n self.assertTrue(lock.acquire())\n self.assertTrue(lock.release())\n self.assertEqual(len(db), 1) # We have the lock event key.\n self.assertEqual(db.lpop(lock.event), b'1')\n" }, { "alpha_fraction": 0.3363584876060486, "alphanum_fraction": 0.3539937138557434, "avg_line_length": 40.81015396118164, "blob_id": "e6b7ec3d4f7f9fe8e9a07a8c480479120f59abdd", "content_id": "a6522a72f9978258ef755c2c4de953df1765fe8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19394, "license_type": "permissive", "max_line_length": 106, "num_lines": 453, "path": "/walrus/search/metaphone.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "#!python\r\n#coding= utf-8\r\n#This script implements the Double Metaphone algorithm (c) 1998, 1999 by\r\n#Lawrence Philips\r\n#it was translated to Python from the C source written by Kevin Atkinson\r\n#(http://aspell.net/metaphone/)\r\n#By Andrew Collins - January 12, 2007 who claims no rights to this work\r\n#http://www.atomodo.com/code/double-metaphone\r\n#Tested with Pyhon 2.4.3\r\n#Updated Feb 14, 2007 - Found a typo in the 'gh' section\r\n#Updated Dec 17, 2007 - Bugs fixed in 'S', 'Z', and 'J' sections.\r\n#Thanks Chris Leong!\r\n#Updated June 25, 2010 - several bugs fixed thanks to Nils Johnsson for a\r\n# spectacular bug squashing effort. There were many cases where this\r\n# function wouldn't give the same output\r\n# as the original C source that were fixed by his careful attention and\r\n# excellent communication.\r\n# The script was also updated to use utf-8 rather than latin-1.\r\nimport sys\r\ntry:\r\n NNNN = unicode('N')\r\n decode = lambda x: x.decode('utf-8', 'ignore')\r\nexcept:\r\n NNNN = 'N'\r\n decode = lambda x: x\r\n\r\nCCCC = 'Ç'\r\nVOWELS = frozenset((decode(x) for x in ('A', 'E', 'I', 'O', 'U', 'Y')))\r\nGNKN = frozenset((decode(x) for x in ('GN', 'KN', 'PN', 'WR', 'PS')))\r\n\r\n\r\ndef dm(st) :\r\n \"\"\"dm(string) -> (string, string or None)\r\n returns the double metaphone codes for given string - always a tuple\r\n there are no checks done on the input string, but it should be a single\r\n word or name.\"\"\"\r\n st = decode(st)\r\n # st is short for string. I usually prefer descriptive over short,\r\n # but this var is used a lot!\r\n st = st.upper()\r\n is_slavo_germanic = (st.find('W') > -1 or st.find('K') > -1 or\r\n st.find('CZ') > -1 or st.find('WITZ') > -1)\r\n length = len(st)\r\n first = 2\r\n # so we can index beyond the beginning and end of the input string\r\n st = ('-') * first + st + (' ' * 5)\r\n last = first + length -1\r\n pos = first # pos is short for position\r\n pri = sec = '' # primary and secondary metaphone codes\r\n #skip these silent letters when at start of word\r\n if st[first:first+2] in GNKN:\r\n pos += 1\r\n # Initial 'X' is pronounced 'Z' e.g. 'Xavier'\r\n if st[first] == 'X' :\r\n pri = sec = 'S' #'Z' maps to 'S'\r\n pos += 1\r\n # main loop through chars in st\r\n while pos <= last :\r\n #print str(pos) + '\\t' + st[pos]\r\n ch = st[pos] # ch is short for character\r\n # nxt (short for next characters in metaphone code) is set to a\r\n # tuple of the next characters in\r\n # the primary and secondary codes and how many characters to move\r\n # forward in the string.\r\n # the secondary code letter is given only when it is different than\r\n # the primary.\r\n # This is just a trick to make the code easier to write and read.\r\n #\r\n # default action is to add nothing and move to next char\r\n nxt = (None, 1)\r\n if ch in VOWELS :\r\n nxt = (None, 1)\r\n if pos == first : # all init VOWELS now map to 'A'\r\n nxt = ('A', 1)\r\n elif ch == 'B' :\r\n #\"-mb\", e.g\", \"dumb\", already skipped over... see 'M' below\r\n if st[pos+1] == 'B' :\r\n nxt = ('P', 2)\r\n else :\r\n nxt = ('P', 1)\r\n elif ch == 'C' :\r\n # various germanic\r\n if (pos > (first + 1) and st[pos-2] not in VOWELS and\r\n st[pos-1:pos+2] == 'ACH' and\r\n (st[pos+2] not in ['I', 'E'] or\r\n st[pos-2:pos+4] in ['BACHER', 'MACHER'])):\r\n nxt = ('K', 2)\r\n # special case 'CAESAR'\r\n elif pos == first and st[first:first+6] == 'CAESAR' :\r\n nxt = ('S', 2)\r\n elif st[pos:pos+4] == 'CHIA' : #italian 'chianti'\r\n nxt = ('K', 2)\r\n elif st[pos:pos+2] == 'CH' :\r\n # find 'michael'\r\n if pos > first and st[pos:pos+4] == 'CHAE' :\r\n nxt = ('K', 'X', 2)\r\n elif pos == first and (st[pos+1:pos+6] in ['HARAC', 'HARIS'] or \\\r\n st[pos+1:pos+4] in [\"HOR\", \"HYM\", \"HIA\", \"HEM\"]) and st[first:first+5] != 'CHORE' :\r\n nxt = ('K', 2)\r\n #germanic, greek, or otherwise 'ch' for 'kh' sound\r\n elif st[first:first+4] in ['VAN ', 'VON '] or st[first:first+3] == 'SCH' \\\r\n or st[pos-2:pos+4] in [\"ORCHES\", \"ARCHIT\", \"ORCHID\"] \\\r\n or st[pos+2] in ['T', 'S'] \\\r\n or ((st[pos-1] in [\"A\", \"O\", \"U\", \"E\"] or pos == first) \\\r\n and st[pos+2] in [\"L\", \"R\", \"N\", \"M\", \"B\", \"H\", \"F\", \"V\", \"W\", \" \"]) :\r\n nxt = ('K', 1)\r\n else :\r\n if pos > first :\r\n if st[first:first+2] == 'MC' :\r\n nxt = ('K', 2)\r\n else :\r\n nxt = ('X', 'K', 2)\r\n else :\r\n nxt = ('X', 2)\r\n #e.g, 'czerny'\r\n elif st[pos:pos+2] == 'CZ' and st[pos-2:pos+2] != 'WICZ' :\r\n nxt = ('S', 'X', 2)\r\n #e.g., 'focaccia'\r\n elif st[pos+1:pos+4] == 'CIA' :\r\n nxt = ('X', 3)\r\n #double 'C', but not if e.g. 'McClellan'\r\n elif st[pos:pos+2] == 'CC' and not (pos == (first +1) and st[first] == 'M') :\r\n #'bellocchio' but not 'bacchus'\r\n if st[pos+2] in [\"I\", \"E\", \"H\"] and st[pos+2:pos+4] != 'HU' :\r\n #'accident', 'accede' 'succeed'\r\n if (pos == (first +1) and st[first] == 'A') or \\\r\n st[pos-1:pos+4] in ['UCCEE', 'UCCES'] :\r\n nxt = ('KS', 3)\r\n #'bacci', 'bertucci', other italian\r\n else:\r\n nxt = ('X', 3)\r\n else :\r\n nxt = ('K', 2)\r\n elif st[pos:pos+2] in [\"CK\", \"CG\", \"CQ\"] :\r\n nxt = ('K', 'K', 2)\r\n elif st[pos:pos+2] in [\"CI\", \"CE\", \"CY\"] :\r\n #italian vs. english\r\n if st[pos:pos+3] in [\"CIO\", \"CIE\", \"CIA\"] :\r\n nxt = ('S', 'X', 2)\r\n else :\r\n nxt = ('S', 2)\r\n else :\r\n #name sent in 'mac caffrey', 'mac gregor\r\n if st[pos+1:pos+3] in [\" C\", \" Q\", \" G\"] :\r\n nxt = ('K', 3)\r\n else :\r\n if st[pos+1] in [\"C\", \"K\", \"Q\"] and st[pos+1:pos+3] not in [\"CE\", \"CI\"] :\r\n nxt = ('K', 2)\r\n else : # default for 'C'\r\n nxt = ('K', 1)\r\n #elif ch == CCCC:\r\n #\tnxt = ('S', 1)\r\n elif ch == 'D' :\r\n if st[pos:pos+2] == 'DG' :\r\n if st[pos+2] in ['I', 'E', 'Y'] : #e.g. 'edge'\r\n nxt = ('J', 3)\r\n else :\r\n nxt = ('TK', 2)\r\n elif st[pos:pos+2] in ['DT', 'DD'] :\r\n nxt = ('T', 2)\r\n else :\r\n nxt = ('T', 1)\r\n elif ch == 'F' :\r\n if st[pos+1] == 'F' :\r\n nxt = ('F', 2)\r\n else :\r\n nxt = ('F', 1)\r\n elif ch == 'G' :\r\n if st[pos+1] == 'H' :\r\n if pos > first and st[pos-1] not in VOWELS :\r\n nxt = ('K', 2)\r\n elif pos < (first + 3) :\r\n if pos == first : #'ghislane', ghiradelli\r\n if st[pos+2] == 'I' :\r\n nxt = ('J', 2)\r\n else :\r\n nxt = ('K', 2)\r\n #Parker's rule (with some further refinements) - e.g., 'hugh'\r\n elif (pos > (first + 1) and st[pos-2] in ['B', 'H', 'D'] ) \\\r\n or (pos > (first + 2) and st[pos-3] in ['B', 'H', 'D'] ) \\\r\n or (pos > (first + 3) and st[pos-4] in ['B', 'H'] ) :\r\n nxt = (None, 2)\r\n else :\r\n # e.g., 'laugh', 'McLaughlin', 'cough', 'gough', 'rough', 'tough'\r\n if pos > (first + 2) and st[pos-1] == 'U' \\\r\n and st[pos-3] in [\"C\", \"G\", \"L\", \"R\", \"T\"] :\r\n nxt = ('F', 2)\r\n else :\r\n if pos > first and st[pos-1] != 'I' :\r\n nxt = ('K', 2)\r\n elif st[pos+1] == 'N' :\r\n if pos == (first +1) and st[first] in VOWELS and not is_slavo_germanic :\r\n nxt = ('KN', 'N', 2)\r\n else :\r\n # not e.g. 'cagney'\r\n if st[pos+2:pos+4] != 'EY' and st[pos+1] != 'Y' and not is_slavo_germanic :\r\n nxt = ('N', 'KN', 2)\r\n else :\r\n nxt = ('KN', 2)\r\n # 'tagliaro'\r\n elif st[pos+1:pos+3] == 'LI' and not is_slavo_germanic :\r\n nxt = ('KL', 'L', 2)\r\n # -ges-,-gep-,-gel-, -gie- at beginning\r\n elif pos == first and (st[pos+1] == 'Y' \\\r\n or st[pos+1:pos+3] in [\"ES\", \"EP\", \"EB\", \"EL\", \"EY\", \"IB\", \"IL\", \"IN\", \"IE\", \"EI\", \"ER\"]) :\r\n nxt = ('K', 'J', 2)\r\n # -ger-, -gy-\r\n elif (st[pos+1:pos+2] == 'ER' or st[pos+1] == 'Y') \\\r\n and st[first:first+6] not in [\"DANGER\", \"RANGER\", \"MANGER\"] \\\r\n and st[pos-1] not in ['E', 'I'] and st[pos-1:pos+2] not in ['RGY', 'OGY'] :\r\n nxt = ('K', 'J', 2)\r\n # italian e.g, 'biaggi'\r\n elif st[pos+1] in ['E', 'I', 'Y'] or st[pos-1:pos+3] in [\"AGGI\", \"OGGI\"] :\r\n # obvious germanic\r\n if st[first:first+4] in ['VON ', 'VAN '] or st[first:first+3] == 'SCH' \\\r\n or st[pos+1:pos+3] == 'ET' :\r\n nxt = ('K', 2)\r\n else :\r\n # always soft if french ending\r\n if st[pos+1:pos+5] == 'IER ' :\r\n nxt = ('J', 2)\r\n else :\r\n nxt = ('J', 'K', 2)\r\n elif st[pos+1] == 'G' :\r\n nxt = ('K', 2)\r\n else :\r\n nxt = ('K', 1)\r\n elif ch == 'H' :\r\n # only keep if first & before vowel or btw. 2 VOWELS\r\n if (pos == first or st[pos-1] in VOWELS) and st[pos+1] in VOWELS :\r\n nxt = ('H', 2)\r\n else : # (also takes care of 'HH')\r\n nxt = (None, 1)\r\n elif ch == 'J' :\r\n # obvious spanish, 'jose', 'san jacinto'\r\n if st[pos:pos+4] == 'JOSE' or st[first:first+4] == 'SAN ' :\r\n if (pos == first and st[pos+4] == ' ') or st[first:first+4] == 'SAN ' :\r\n nxt = ('H',)\r\n else :\r\n nxt = ('J', 'H')\r\n elif pos == first and st[pos:pos+4] != 'JOSE' :\r\n nxt = ('J', 'A') # Yankelovich/Jankelowicz\r\n else :\r\n # spanish pron. of e.g. 'bajador'\r\n if st[pos-1] in VOWELS and not is_slavo_germanic \\\r\n and st[pos+1] in ['A', 'O'] :\r\n nxt = ('J', 'H')\r\n else :\r\n if pos == last :\r\n nxt = ('J', ' ')\r\n else :\r\n if st[pos+1] not in [\"L\", \"T\", \"K\", \"S\", \"N\", \"M\", \"B\", \"Z\"] \\\r\n and st[pos-1] not in [\"S\", \"K\", \"L\"] :\r\n nxt = ('J',)\r\n else :\r\n nxt = (None, )\r\n if st[pos+1] == 'J' :\r\n nxt = nxt + (2,)\r\n else :\r\n nxt = nxt + (1,)\r\n elif ch == 'K' :\r\n if st[pos+1] == 'K' :\r\n nxt = ('K', 2)\r\n else :\r\n nxt = ('K', 1)\r\n elif ch == 'L' :\r\n if st[pos+1] == 'L' :\r\n # spanish e.g. 'cabrillo', 'gallegos'\r\n if (pos == (last - 2) and st[pos-1:pos+3] in [\"ILLO\", \"ILLA\", \"ALLE\"]) \\\r\n or ((st[last-1:last+1] in [\"AS\", \"OS\"] or st[last] in [\"A\", \"O\"]) \\\r\n and st[pos-1:pos+3] == 'ALLE') :\r\n nxt = ('L', '', 2)\r\n else :\r\n nxt = ('L', 2)\r\n else :\r\n nxt = ('L', 1)\r\n elif ch == 'M' :\r\n if st[pos+1:pos+4] == 'UMB' \\\r\n and (pos + 1 == last or st[pos+2:pos+4] == 'ER') \\\r\n or st[pos+1] == 'M' :\r\n nxt = ('M', 2)\r\n else :\r\n nxt = ('M', 1)\r\n elif ch == 'N' :\r\n if st[pos+1] == 'N' :\r\n nxt = ('N', 2)\r\n else :\r\n nxt = ('N', 1)\r\n elif ch == NNNN:\r\n nxt = ('N', 1)\r\n elif ch == 'P' :\r\n if st[pos+1] == 'H' :\r\n nxt = ('F', 2)\r\n elif st[pos+1] in ['P', 'B'] : # also account for \"campbell\", \"raspberry\"\r\n nxt = ('P', 2)\r\n else :\r\n nxt = ('P', 1)\r\n elif ch == 'Q' :\r\n if st[pos+1] == 'Q' :\r\n nxt = ('K', 2)\r\n else :\r\n nxt = ('K', 1)\r\n elif ch == 'R' :\r\n # french e.g. 'rogier', but exclude 'hochmeier'\r\n if pos == last and not is_slavo_germanic \\\r\n and st[pos-2:pos] == 'IE' and st[pos-4:pos-2] not in ['ME', 'MA'] :\r\n nxt = ('', 'R')\r\n else :\r\n nxt = ('R',)\r\n if st[pos+1] == 'R' :\r\n nxt = nxt + (2,)\r\n else :\r\n nxt = nxt + (1,)\r\n elif ch == 'S' :\r\n # special cases 'island', 'isle', 'carlisle', 'carlysle'\r\n if st[pos-1:pos+2] in ['ISL', 'YSL'] :\r\n nxt = (None, 1)\r\n # special case 'sugar-'\r\n elif pos == first and st[first:first+5] == 'SUGAR' :\r\n nxt =('X', 'S', 1)\r\n elif st[pos:pos+2] == 'SH' :\r\n # germanic\r\n if st[pos+1:pos+5] in [\"HEIM\", \"HOEK\", \"HOLM\", \"HOLZ\"] :\r\n nxt = ('S', 2)\r\n else :\r\n nxt = ('X', 2)\r\n # italian & armenian\r\n elif st[pos:pos+3] in [\"SIO\", \"SIA\"] or st[pos:pos+4] == 'SIAN' :\r\n if not is_slavo_germanic :\r\n nxt = ('S', 'X', 3)\r\n else :\r\n nxt = ('S', 3)\r\n # german & anglicisations, e.g. 'smith' match 'schmidt', 'snider'\r\n # match 'schneider'\r\n # also, -sz- in slavic language altho in hungarian it is\r\n # pronounced 's'\r\n elif (pos == first and st[pos+1] in [\"M\", \"N\", \"L\", \"W\"]) or st[pos+1] == 'Z' :\r\n nxt = ('S', 'X')\r\n if st[pos+1] == 'Z' :\r\n nxt = nxt + (2,)\r\n else :\r\n nxt = nxt + (1,)\r\n elif st[pos:pos+2] == 'SC' :\r\n # Schlesinger's rule\r\n if st[pos+2] == 'H' :\r\n # dutch origin, e.g. 'school', 'schooner'\r\n if st[pos+3:pos+5] in [\"OO\", \"ER\", \"EN\", \"UY\", \"ED\", \"EM\"] :\r\n # 'schermerhorn', 'schenker'\r\n if st[pos+3:pos+5] in ['ER', 'EN'] :\r\n nxt = ('X', 'SK', 3)\r\n else :\r\n nxt = ('SK', 3)\r\n else :\r\n if pos == first and st[first+3] not in VOWELS and st[first+3] != 'W' :\r\n nxt = ('X', 'S', 3)\r\n else :\r\n nxt = ('X', 3)\r\n elif st[pos+2] in ['I', 'E', 'Y'] :\r\n nxt = ('S', 3)\r\n else :\r\n nxt = ('SK', 3)\r\n # french e.g. 'resnais', 'artois'\r\n elif pos == last and st[pos-2:pos] in ['AI', 'OI'] :\r\n nxt = ('', 'S', 1)\r\n else :\r\n nxt = ('S',)\r\n if st[pos+1] in ['S', 'Z'] :\r\n nxt = nxt + (2,)\r\n else :\r\n nxt = nxt + (1,)\r\n elif ch == 'T' :\r\n if st[pos:pos+4] == 'TION' :\r\n nxt = ('X', 3)\r\n elif st[pos:pos+3] in ['TIA', 'TCH'] :\r\n nxt = ('X', 3)\r\n elif st[pos:pos+2] == 'TH' or st[pos:pos+3] == 'TTH' :\r\n # special case 'thomas', 'thames' or germanic\r\n if st[pos+2:pos+4] in ['OM', 'AM'] or st[first:first+4] in ['VON ', 'VAN '] \\\r\n or st[first:first+3] == 'SCH' :\r\n nxt = ('T', 2)\r\n else :\r\n nxt = ('0', 'T', 2)\r\n elif st[pos+1] in ['T', 'D'] :\r\n nxt = ('T', 2)\r\n else :\r\n nxt = ('T', 1)\r\n elif ch == 'V' :\r\n if st[pos+1] == 'V' :\r\n nxt = ('F', 2)\r\n else :\r\n nxt = ('F', 1)\r\n elif ch == 'W' :\r\n # can also be in middle of word\r\n if st[pos:pos+2] == 'WR' :\r\n nxt = ('R', 2)\r\n elif pos == first and (st[pos+1] in VOWELS or st[pos:pos+2] == 'WH') :\r\n # Wasserman should match Vasserman\r\n if st[pos+1] in VOWELS :\r\n nxt = ('A', 'F', 1)\r\n else :\r\n nxt = ('A', 1)\r\n # Arnow should match Arnoff\r\n elif (pos == last and st[pos-1] in VOWELS) \\\r\n or st[pos-1:pos+5] in [\"EWSKI\", \"EWSKY\", \"OWSKI\", \"OWSKY\"] \\\r\n or st[first:first+3] == 'SCH' :\r\n nxt = ('', 'F', 1)\r\n # polish e.g. 'filipowicz'\r\n elif st[pos:pos+4] in [\"WICZ\", \"WITZ\"] :\r\n nxt = ('TS', 'FX', 4)\r\n else : # default is to skip it\r\n nxt = (None, 1)\r\n elif ch == 'X' :\r\n # french e.g. breaux\r\n nxt = (None,)\r\n if not(pos == last and (st[pos-3:pos] in [\"IAU\", \"EAU\"] \\\r\n or st[pos-2:pos] in ['AU', 'OU'])):\r\n nxt = ('KS',)\r\n if st[pos+1] in ['C', 'X'] :\r\n nxt = nxt + (2,)\r\n else :\r\n nxt = nxt + (1,)\r\n elif ch == 'Z' :\r\n # chinese pinyin e.g. 'zhao'\r\n if st[pos+1] == 'H' :\r\n nxt = ('J',)\r\n elif st[pos+1:pos+3] in [\"ZO\", \"ZI\", \"ZA\"] \\\r\n or (is_slavo_germanic and pos > first and st[pos-1] != 'T') :\r\n nxt = ('S', 'TS')\r\n else :\r\n nxt = ('S',)\r\n if st[pos+1] == 'Z' :\r\n nxt = nxt + (2,)\r\n else :\r\n nxt = nxt + (1,)\r\n # ----------------------------------\r\n # --- end checking letters------\r\n # ----------------------------------\r\n #print str(nxt)\r\n if len(nxt) == 2 :\r\n if nxt[0] :\r\n pri += nxt[0]\r\n sec += nxt[0]\r\n pos += nxt[1]\r\n elif len(nxt) == 3 :\r\n if nxt[0] :\r\n pri += nxt[0]\r\n if nxt[1] :\r\n sec += nxt[1]\r\n pos += nxt[2]\r\n if pri == sec :\r\n return (pri, None)\r\n else :\r\n return (pri, sec)\r\n" }, { "alpha_fraction": 0.4895980954170227, "alphanum_fraction": 0.529051661491394, "avg_line_length": 35.00204086303711, "blob_id": "15f335b29a1349d21dd4326b4ccc1a5d1dc1b667", "content_id": "273d9daa14cbcbfe91473f146a48457f717261e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 35282, "license_type": "permissive", "max_line_length": 79, "num_lines": 980, "path": "/walrus/tests/containers.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom walrus.containers import *\nfrom walrus.containers import _normalize_stream_keys\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\nfrom walrus.tests.base import stream_test\nfrom walrus.tests.base import zpop_test\nfrom walrus.utils import decode\nfrom walrus.utils import decode_dict\nfrom walrus.utils import encode\n\n\nclass TestHash(WalrusTestCase):\n def setUp(self):\n super(TestHash, self).setUp()\n self.hsh = db.Hash('my-hash')\n\n def test_item_api(self):\n self.hsh['k1'] = 'v1'\n self.assertEqual(self.hsh['k1'], b'v1')\n self.assertTrue(self.hsh['kx'] is None)\n\n self.hsh['k2'] = 'v2'\n self.hsh['k3'] = 'v3'\n self.assertEqual(self.hsh.as_dict(), {\n b'k1': b'v1',\n b'k2': b'v2',\n b'k3': b'v3'})\n\n del self.hsh['k2']\n self.assertEqual(self.hsh.as_dict(), {b'k1': b'v1', b'k3': b'v3'})\n\n def test_dict_apis(self):\n self.hsh.update({'k1': 'v1', 'k2': 'v2'})\n self.hsh.update(k3='v3', k4='v4')\n self.assertEqual(sorted(self.hsh.items()), [\n (b'k1', b'v1'),\n (b'k2', b'v2'),\n (b'k3', b'v3'),\n (b'k4', b'v4')])\n self.assertEqual(sorted(self.hsh.keys()), [b'k1', b'k2', b'k3', b'k4'])\n self.assertEqual(sorted(self.hsh.values()),\n [b'v1', b'v2', b'v3', b'v4'])\n\n self.assertEqual(len(self.hsh), 4)\n self.assertTrue('k1' in self.hsh)\n self.assertFalse('kx' in self.hsh)\n\n def test_search_iter(self):\n self.hsh.update(foo='v1', bar='v2', baz='v3')\n self.assertEqual(sorted(self.hsh), [\n (b'bar', b'v2'),\n (b'baz', b'v3'),\n (b'foo', b'v1')])\n self.assertEqual(sorted(self.hsh.search('b*')), [\n (b'bar', b'v2'),\n (b'baz', b'v3')])\n\n def test_as_dict(self):\n self.hsh.update(k1='v1', k2='v2')\n self.assertEqual(self.hsh.as_dict(True), {'k1': 'v1', 'k2': 'v2'})\n self.assertEqual(db.Hash('test').as_dict(), {})\n\n def test_from_dict(self):\n data = dict(zip('abcdefghij', 'klmnopqrst'))\n hsh = Hash.from_dict(db, 'test', data)\n self.assertEqual(hsh.as_dict(True), data)\n\n def test_setnx(self):\n key, value = \"key_setnx\", \"value_setnx\"\n self.assertTrue(self.hsh.setnx(key, value))\n self.assertFalse(self.hsh.setnx(key, value))\n\n\nclass TestSet(WalrusTestCase):\n def setUp(self):\n super(TestSet, self).setUp()\n self.set = db.Set('my-set')\n\n def test_basic_apis(self):\n self.set.add('i1', 'i2', 'i3', 'i2', 'i1')\n self.assertEqual(sorted(self.set), [b'i1', b'i2', b'i3'])\n\n self.set.remove('i2')\n self.assertEqual(sorted(self.set), [b'i1', b'i3'])\n\n self.set.remove('ix')\n self.assertEqual(sorted(self.set), [b'i1', b'i3'])\n\n # Test __contains__\n self.assertTrue('i1' in self.set)\n self.assertFalse('ix' in self.set)\n\n # Test __iter__.\n self.assertEqual(sorted(self.set), [b'i1', b'i3'])\n\n del self.set['i3']\n self.assertEqual(sorted(self.set), [b'i1'])\n\n def test_combining(self):\n self.set2 = db.Set('my-set2')\n self.set.add(1, 2, 3, 4)\n self.set2.add(3, 4, 5, 6)\n\n self.assertEqual(\n self.set | self.set2,\n set([b'1', b'2', b'3', b'4', b'5', b'6']))\n self.assertEqual(self.set & self.set2, set([b'3', b'4']))\n self.assertEqual(self.set - self.set2, set([b'1', b'2']))\n self.assertEqual(self.set2 - self.set, set([b'5', b'6']))\n\n def test_combine_store(self):\n self.set2 = db.Set('my-set2')\n self.set.add(1, 2, 3, 4)\n self.set2.add(3, 4, 5, 6)\n\n s3 = self.set.unionstore('my-set3', self.set2)\n self.assertEqual(s3.members(),\n set([b'1', b'2', b'3', b'4', b'5', b'6']))\n\n s3 = self.set.interstore('my-set3', self.set2)\n self.assertEqual(s3.members(), set([b'3', b'4']))\n\n s3 = self.set.diffstore('my-set3', self.set2)\n self.assertEqual(s3.members(), set([b'1', b'2']))\n\n self.set |= self.set2\n self.assertEqual(sorted(self.set),\n [b'1', b'2', b'3', b'4', b'5', b'6'])\n\n s4 = db.Set('my-set4')\n s4.add('1', '3')\n s3 &= s4\n self.assertEqual(s3.members(), set([b'1']))\n\n def test_search(self):\n self.set.add('foo', 'bar', 'baz', 'nug')\n self.assertEqual(sorted(self.set.search('b*')), [b'bar', b'baz'])\n\n def test_sort(self):\n values = ['charlie', 'zaizee', 'mickey', 'huey']\n self.set.add(*values)\n self.assertEqual(self.set.sort(),\n [b'charlie', b'huey', b'mickey', b'zaizee'])\n\n self.set.sort(ordering='DESC', limit=3, store='s_dest')\n self.assertList(db.List('s_dest'), [b'zaizee', b'mickey', b'huey'])\n\n def test_as_set(self):\n self.set.add('foo', 'bar', 'baz')\n self.assertEqual(self.set.as_set(True), set(('foo', 'bar', 'baz')))\n self.assertEqual(db.Set('test').as_set(), set())\n\n def test_from_set(self):\n data = set('abcdefghij')\n s = Set.from_set(db, 'test', data)\n self.assertEqual(s.as_set(True), data)\n\n\nclass TestZSet(WalrusTestCase):\n def setUp(self):\n super(TestZSet, self).setUp()\n self.zs = db.ZSet('my-zset')\n\n def assertZSet(self, expected):\n self.assertEqual(list(self.zs), expected)\n\n def test_basic_apis(self):\n self.zs.add({'i1': 1, 'i2': 2})\n self.assertZSet([(b'i1', 1), (b'i2', 2)])\n\n self.zs.add({'i0': 0})\n self.zs.add({'i3': 3})\n self.assertZSet([(b'i0', 0), (b'i1', 1), (b'i2', 2), (b'i3', 3)])\n\n self.zs.remove('i1')\n self.zs.remove_by_score(3)\n self.zs.add({'i2': -2})\n self.zs.add({'i9': 9})\n self.assertZSet([(b'i2', -2.), (b'i0', 0.), (b'i9', 9.)])\n\n # __len__\n self.assertEqual(len(self.zs), 3)\n\n # __contains__\n self.assertTrue('i0' in self.zs)\n self.assertFalse('i1' in self.zs)\n\n self.assertEqual(self.zs.score('i2'), -2)\n self.assertEqual(self.zs.score('ix'), None)\n\n self.assertEqual(self.zs.rank('i0'), 1)\n self.assertEqual(self.zs.rank('i1'), None)\n\n self.assertEqual(self.zs.count(0, 10), 2)\n self.assertEqual(self.zs.count(-3, 11), 3)\n\n self.zs.incr('i2')\n self.zs.incr('i0', -2)\n self.assertZSet([(b'i0', -2.), (b'i2', -1.), (b'i9', 9.)])\n\n self.assertEqual(self.zs.range_by_score(0, 9), [b'i9'])\n self.assertEqual(self.zs.range_by_score(-3, 0), [b'i0', b'i2'])\n\n self.assertEqual(self.zs.popmin_compat(), [(b'i0', -2.)])\n self.assertEqual(len(self.zs), 2)\n self.assertEqual(self.zs.popmax_compat(3),\n [(b'i9', 9.), (b'i2', -1.)])\n self.assertEqual(self.zs.popmin_compat(), [])\n self.assertEqual(self.zs.popmax_compat(), [])\n self.assertEqual(len(self.zs), 0)\n\n @zpop_test\n def test_popmin_popmax(self):\n for i in range(10):\n self.zs.add({'i%s' % i: i})\n\n # a list of item/score tuples is returned.\n self.assertEqual(self.zs.popmin(2), [(b'i0', 0.), (b'i1', 1.)])\n self.assertEqual(self.zs.popmax(2), [(b'i9', 9.), (b'i8', 8.)])\n\n # when called with no args, a list is still returned.\n self.assertEqual(self.zs.popmin(), [(b'i2', 2.)])\n self.assertEqual(self.zs.popmax(), [(b'i7', 7.)])\n\n # blocking pop returns single item.\n self.assertEqual(self.zs.bpopmin(), (b'i3', 3.))\n self.assertEqual(self.zs.bpopmax(), (b'i6', 6.))\n\n # blocking-pop with timeout.\n self.assertEqual(self.zs.bpopmin(2), (b'i4', 4.))\n self.assertEqual(self.zs.bpopmax(2), (b'i5', 5.))\n\n # empty list is returned when zset is empty.\n self.assertEqual(self.zs.popmin(), [])\n self.assertEqual(self.zs.popmax(), [])\n\n def test_item_apis(self):\n self.zs['i1'] = 1\n self.zs['i0'] = 0\n self.zs['i3'] = 3\n self.zs['i2'] = 2\n\n self.assertEqual(self.zs[0, False], [b'i0'])\n self.assertEqual(self.zs[0, True], [(b'i0', 0)])\n self.assertEqual(self.zs[2, False], [b'i2'])\n self.assertEqual(self.zs[2, True], [(b'i2', 2)])\n self.assertEqual(self.zs[-1, True], [(b'i3', 3)])\n self.assertEqual(self.zs[9, True], [])\n\n self.assertEqual(self.zs[0], [b'i0'])\n self.assertEqual(self.zs[2], [b'i2'])\n self.assertEqual(self.zs[9], [])\n\n del self.zs['i1']\n del self.zs['i3']\n self.zs['i2'] = -2\n self.zs['i9'] = 9\n self.assertZSet([(b'i2', -2.), (b'i0', 0.), (b'i9', 9.)])\n\n def test_slicing(self):\n self.zs.add({'i1': 1, 'i2': 2, 'i3': 3, 'i0': 0})\n self.assertEqual(self.zs[:1, True], [(b'i0', 0)])\n self.assertEqual(self.zs[1:3, False], [b'i1', b'i2'])\n self.assertEqual(self.zs[1:-1, True], [(b'i1', 1), (b'i2', 2)])\n\n self.assertEqual(self.zs['i1':, False], [b'i1', b'i2', b'i3'])\n self.assertEqual(self.zs[:'i2', False], [b'i0', b'i1'])\n self.assertEqual(\n self.zs['i0':'i3', True],\n [(b'i0', 0), (b'i1', 1), (b'i2', 2)])\n self.assertRaises(KeyError, self.zs.__getitem__, (slice('i9'), False))\n self.assertEqual(self.zs[99:, False], [])\n\n del self.zs[:'i2']\n self.assertZSet([(b'i2', 2.), (b'i3', 3.)])\n del self.zs[1:]\n self.assertZSet([(b'i2', 2.)])\n\n def test_combine_store(self):\n zs2 = db.ZSet('my-zset2')\n self.zs.add({1: 1, 2: 2, 3: 3})\n zs2.add({3: 3, 4: 4, 5: 5})\n\n zs3 = self.zs.unionstore('my-zset3', zs2)\n self.assertEqual(\n list(zs3),\n [(b'1', 1.), (b'2', 2.), (b'4', 4.), (b'5', 5.), (b'3', 6.)])\n\n zs3 = self.zs.interstore('my-zset3', zs2)\n self.assertEqual(list(zs3), [(b'3', 6.)])\n\n self.zs |= zs2\n self.assertZSet([\n (b'1', 1.), (b'2', 2.), (b'4', 4.), (b'5', 5.), (b'3', 6.)])\n\n zs3 &= zs2\n self.assertEqual(list(zs3), [(b'3', 9.)])\n\n def test_search(self):\n self.zs.add({'foo': 1, 'bar': 2, 'baz': 1, 'nug': 3})\n self.assertEqual(\n list(self.zs.search('b*')),\n [(b'baz', 1.), (b'bar', 2.)])\n\n def test_sort(self):\n values = ['charlie', 3, 'zaizee', 2, 'mickey', 6, 'huey', 3]\n self.zs.add(dict(zip(values[::2], values[1::2])))\n self.assertEqual(\n self.zs.sort(),\n [b'charlie', b'huey', b'mickey', b'zaizee'])\n\n self.zs.sort(ordering='DESC', limit=3, store='z_dest')\n res = db.List('z_dest')\n self.assertEqual(list(res), [b'zaizee', b'mickey', b'huey'])\n\n def test_as_items(self):\n self.zs.add({'foo': 3, 'bar': 1, 'baz': 2})\n self.assertEqual(self.zs.as_items(True),\n [('bar', 1.), ('baz', 2.), ('foo', 3.)])\n self.assertEqual(db.ZSet('test').as_items(), [])\n\n def test_from_dict(self):\n data = dict(zip('abcdefghij', [float(i) for i in range(10)]))\n zs = ZSet.from_dict(db, 'test', data)\n self.assertEqual(zs.as_items(True), sorted(data.items()))\n\n\nclass TestList(WalrusTestCase):\n def setUp(self):\n super(TestList, self).setUp()\n self.lst = db.List('my-list')\n\n def test_basic_apis(self):\n self.lst.append('i1')\n self.lst.extend(['i2', 'i3'])\n self.lst.prepend('ix')\n self.assertList(self.lst, [b'ix', b'i1', b'i2', b'i3'])\n\n self.lst.insert('iy', 'i2', 'before')\n self.lst.insert('iz', 'i2', 'after')\n self.assertList(self.lst, [b'ix', b'i1', b'iy', b'i2', b'iz', b'i3'])\n\n self.assertEqual(self.lst.pop(), b'i3')\n self.assertEqual(self.lst.popleft(), b'ix')\n self.assertEqual(len(self.lst), 4)\n\n def test_item_apis(self):\n self.lst.append('i0')\n self.assertEqual(self.lst[0], b'i0')\n\n self.lst.extend(['i1', 'i2'])\n del self.lst['i1']\n self.assertList(self.lst, [b'i0', b'i2'])\n\n self.lst[1] = 'i2x'\n self.assertList(self.lst, [b'i0', b'i2x'])\n\n del self.lst[0]\n self.assertList(self.lst, [b'i2x'])\n\n del self.lst[99]\n self.assertList(self.lst, [b'i2x'])\n\n del self.lst['ixxx']\n self.assertList(self.lst, [b'i2x'])\n\n def test_slicing(self):\n self.lst.extend(['i1', 'i2', 'i3', 'i4'])\n self.assertEqual(self.lst[:1], [b'i1'])\n self.assertEqual(self.lst[:2], [b'i1', b'i2'])\n self.assertEqual(self.lst[:-1], [b'i1', b'i2', b'i3'])\n self.assertEqual(self.lst[1:2], [b'i2'])\n self.assertEqual(self.lst[1:], [b'i2', b'i3', b'i4'])\n\n l = db.List('l1')\n l.extend(range(10))\n\n # LTRIM, preserve the 1st to last (removes the 0th element).\n del l[1:-1]\n self.assertEqual([int(decode(i)) for i in l],\n [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n # Trim the list so that it contains only the values within the\n # specified range.\n del l[:3]\n self.assertEqual([int(decode(i)) for i in l], [1, 2, 3])\n\n def test_sort(self):\n values = ['charlie', 'zaizee', 'mickey', 'huey']\n self.lst.extend(values)\n self.assertEqual(self.lst.sort(),\n [b'charlie', b'huey', b'mickey', b'zaizee'])\n\n self.lst.sort(ordering='DESC', limit=3, store='l_dest')\n self.assertList(db.List('l_dest'), [b'zaizee', b'mickey', b'huey'])\n\n def test_as_list(self):\n self.lst.extend(['foo', 'bar'])\n self.assertEqual(self.lst.as_list(True), ['foo', 'bar'])\n self.assertEqual(db.List('test').as_list(), [])\n\n def test_from_list(self):\n data = list('abcdefghij')\n lst = List.from_list(db, 'test', data)\n self.assertEqual(lst.as_list(True), data)\n\n\nclass TestArray(WalrusTestCase):\n def setUp(self):\n super(TestArray, self).setUp()\n self.arr = db.Array('my-arr')\n\n def test_basic_apis(self):\n self.arr.append('i1')\n self.arr.append('i2')\n self.arr.append('i3')\n self.arr.append('i4')\n self.assertEqual(len(self.arr), 4)\n\n # Indexing works. Invalid indices return None.\n self.assertEqual(self.arr[0], b'i1')\n self.assertEqual(self.arr[3], b'i4')\n self.assertTrue(self.arr[4] is None)\n\n # Negative indexing works and includes bounds-checking.\n self.assertEqual(self.arr[-1], b'i4')\n self.assertEqual(self.arr[-4], b'i1')\n self.assertTrue(self.arr[-5] is None)\n\n self.assertEqual(self.arr.pop(1), b'i2')\n self.assertList(self.arr, [b'i1', b'i3', b'i4'])\n\n self.assertEqual(self.arr.pop(), b'i4')\n self.assertList(self.arr, [b'i1', b'i3'])\n\n self.arr[-1] = 'iy'\n self.arr[0] = 'ix'\n self.assertList(self.arr, [b'ix', b'iy'])\n\n self.assertTrue('iy' in self.arr)\n self.assertFalse('i1' in self.arr)\n\n self.arr.extend(['foo', 'bar', 'baz'])\n self.assertList(self.arr, [b'ix', b'iy', b'foo', b'bar', b'baz'])\n\n def test_as_list(self):\n self.arr.extend(['foo', 'bar'])\n self.assertEqual(self.arr.as_list(True), ['foo', 'bar'])\n self.assertEqual(db.Array('test').as_list(), [])\n\n def test_from_list(self):\n data = list('abcdefghij')\n arr = Array.from_list(db, 'test', data)\n self.assertEqual(arr.as_list(True), data)\n\n\nclass TestStream(WalrusTestCase):\n def setUp(self):\n super(TestStream, self).setUp()\n db.delete('my-stream')\n db.delete('sa')\n db.delete('sb')\n\n def _create_test_data(self):\n return (db.xadd('sa', {'k': 'a1'}, b'1'),\n db.xadd('sb', {'k': 'b1'}, b'2'),\n db.xadd('sa', {'k': 'a2'}, b'3'),\n db.xadd('sb', {'k': 'b2'}, b'4'),\n db.xadd('sb', {'k': 'b3'}, b'5'))\n\n @stream_test\n def test_stream_group_info(self):\n sa = db.Stream('sa')\n ra1 = sa.add({'k': 'a1'})\n ra2 = sa.add({'k': 'a2'})\n ra3 = sa.add({'k': 'a3'})\n\n sb = db.Stream('sb')\n rb1 = sb.add({'k': 'b1'})\n\n sa_info = sa.info()\n self.assertEqual(sa_info['groups'], 0)\n self.assertEqual(sa_info['length'], 3)\n self.assertEqual(sa_info['first-entry'][0], ra1)\n self.assertEqual(sa_info['last-entry'][0], ra3)\n\n sb_info = sb.info()\n self.assertEqual(sb_info['groups'], 0)\n self.assertEqual(sb_info['length'], 1)\n self.assertEqual(sb_info['first-entry'][0], rb1)\n self.assertEqual(sb_info['last-entry'][0], rb1)\n\n self.assertEqual(sa.groups_info(), [])\n self.assertEqual(sb.groups_info(), [])\n\n # Create consumer groups.\n cga = db.consumer_group('cga', ['sa'])\n cga.create()\n cgab = db.consumer_group('cgab', ['sa', 'sb'])\n cgab.create()\n\n self.assertEqual(sa.info()['groups'], 2)\n self.assertEqual(sb.info()['groups'], 1)\n\n sa_groups = sa.groups_info()\n self.assertEqual(len(sa_groups), 2)\n self.assertEqual(sorted(g['name'] for g in sa_groups),\n [b'cga', b'cgab'])\n\n sb_groups = sb.groups_info()\n self.assertEqual(len(sb_groups), 1)\n self.assertEqual(sb_groups[0]['name'], b'cgab')\n\n # Verify we can get stream info from the consumer group.\n stream_info = cgab.stream_info()\n self.assertEqual(sorted(stream_info), ['sa', 'sb'])\n\n # Destroy consumer group?\n cgab.destroy()\n self.assertEqual(len(sa.groups_info()), 1)\n self.assertEqual(len(sb.groups_info()), 0)\n\n @stream_test\n def test_consumer_group_create(self):\n cg = db.consumer_group('cg', ['sa'])\n self.assertEqual(cg.create(), {'sa': True})\n\n # Creating the consumer group again will report that it was not created\n # for the given key(s).\n self.assertEqual(cg.create(), {'sa': False})\n\n # We can register the consumer group with another key.\n cg = db.consumer_group('cg', ['sa', 'sb'])\n self.assertEqual(cg.create(), {'sa': False, 'sb': True})\n\n @stream_test\n def test_consumer_group_stream_creation(self):\n cg = db.consumer_group('cg1', ['stream-a', 'stream-b'])\n self.assertFalse(db.exists('stream-a'))\n self.assertFalse(db.exists('stream-b'))\n\n cg.create()\n\n # The streams were created (by adding and then deleting a message).\n self.assertTrue(db.exists('stream-a'))\n self.assertTrue(db.exists('stream-b'))\n\n # The streams that were automatically created will not have any data.\n self.assertEqual(db.xlen('stream-a'), 0)\n self.assertEqual(db.xlen('stream-b'), 0)\n\n # If a stream already exists that's OK.\n db.xadd('stream-c', {'data': 'dummy'}, id=b'1')\n cg = db.consumer_group('cg2', ['stream-c', 'stream-d'])\n self.assertTrue(db.exists('stream-c'))\n self.assertEqual(db.type('stream-c'), b'stream')\n self.assertFalse(db.exists('stream-d'))\n\n cg.create()\n self.assertTrue(db.exists('stream-d'))\n self.assertEqual(db.type('stream-c'), b'stream')\n self.assertEqual(db.type('stream-d'), b'stream')\n self.assertEqual(db.xlen('stream-c'), 1)\n self.assertEqual(db.xlen('stream-d'), 0)\n\n # If a stream key already exists and is a different type, fail.\n db.lpush('l1', 'item-1')\n db.hset('h1', 'key', 'data')\n db.sadd('s1', 'item-1')\n db.set('k1', 'v1')\n db.zadd('z1', {'item-1': 1.0})\n for key in ('l1', 'h1', 's1', 'k1', 'z1'):\n cg = db.consumer_group('cg-%s' % key, keys=[key])\n self.assertRaises(ValueError, cg.create)\n\n @stream_test\n def test_consumer_group_streams(self):\n ra1, rb1, ra2, rb2, rb3 = self._create_test_data()\n cg = db.consumer_group('g1', ['sa', 'sb'])\n\n self.assertEqual(cg.sa[ra1], (ra1, {b'k': b'a1'}))\n self.assertEqual(cg.sb[rb3], (rb3, {b'k': b'b3'}))\n\n def assertMessages(resp, expected):\n self.assertEqual([mid for mid, _ in resp], expected)\n\n assertMessages(cg.sa[ra1:], [ra1, ra2])\n assertMessages(cg.sa[:ra1], [ra1])\n assertMessages(cg.sa[ra2:], [ra2])\n assertMessages(cg.sa[:ra2], [ra1, ra2])\n assertMessages(cg.sa[rb3:], [])\n assertMessages(cg.sa[:b'0-1'], [])\n assertMessages(list(cg.sa), [ra1, ra2])\n\n assertMessages(cg.sb[rb1:], [rb1, rb2, rb3])\n assertMessages(cg.sb[rb1::2], [rb1, rb2])\n assertMessages(cg.sb[:rb1], [rb1])\n assertMessages(cg.sb[rb3:], [rb3])\n assertMessages(cg.sb[:rb3], [rb1, rb2, rb3])\n assertMessages(list(cg.sb), [rb1, rb2, rb3])\n\n self.assertEqual(len(cg.sa), 2)\n self.assertEqual(len(cg.sb), 3)\n\n del cg.sa[ra1]\n del cg.sb[rb1, rb3]\n self.assertEqual(len(cg.sa), 1)\n self.assertEqual(len(cg.sb), 1)\n assertMessages(list(cg.sa), [ra2])\n assertMessages(list(cg.sb), [rb2])\n\n @stream_test\n def test_consumer_group_container(self):\n ra1, rb1, ra2, rb2, rb3 = self._create_test_data()\n cg1 = db.consumer_group('g1', {'sa': '1', 'sb': '0'})\n cg2 = db.consumer_group('g2', {'sb': '2'})\n\n self.assertEqual(cg1.create(), {'sa': True, 'sb': True})\n self.assertEqual(cg2.create(), {'sb': True})\n\n self.assertEqual(dict(cg1.read(count=2)), {\n b'sa': [(ra2, {b'k': b'a2'})],\n b'sb': [(rb1, {b'k': b'b1'}), (rb2, {b'k': b'b2'})]})\n self.assertEqual(cg1.sa.read(), [])\n self.assertEqual(cg1.sb.read(), [(rb3, {b'k': b'b3'})])\n\n self.assertEqual(cg1.sa.ack(ra2), 1)\n self.assertEqual(cg1.sb.ack(rb1, rb3), 2)\n p1, = cg1.sb.pending()\n self.assertEqual(p1['message_id'], rb2)\n self.assertEqual(p1['consumer'], b'g1.c1')\n\n self.assertEqual(cg2.read(count=1), [\n [b'sb', [(rb2, {b'k': b'b2'})]]])\n self.assertEqual(cg2.sb.read(), [(rb3, {b'k': b'b3'})])\n\n self.assertEqual(cg1.destroy(), {'sa': 1, 'sb': 1})\n self.assertEqual(cg2.destroy(), {'sb': 1})\n\n @stream_test\n def test_consumer_group_consumers(self):\n ra1, rb1, ra2, rb2, rb3 = self._create_test_data()\n cg11 = db.consumer_group('g1', {'sa': '0', 'sb': '0'}, consumer='cg11')\n cg11.create()\n cg12 = cg11.consumer('cg12')\n\n self.assertEqual(dict(cg11.read(count=1)), {\n b'sa': [(ra1, {b'k': b'a1'})],\n b'sb': [(rb1, {b'k': b'b1'})]})\n\n self.assertEqual(dict(cg12.read(count=1, block=1)), {\n b'sa': [(ra2, {b'k': b'a2'})],\n b'sb': [(rb2, {b'k': b'b2'})]})\n\n pa1, pa2 = cg11.sa.pending()\n self.assertEqual(pa1['message_id'], ra1)\n self.assertEqual(pa1['consumer'], b'cg11')\n self.assertEqual(pa2['message_id'], ra2)\n self.assertEqual(pa2['consumer'], b'cg12')\n\n pb1, pb2 = cg11.sb.pending()\n self.assertEqual(pb1['message_id'], rb1)\n self.assertEqual(pb1['consumer'], b'cg11')\n self.assertEqual(pb2['message_id'], rb2)\n self.assertEqual(pb2['consumer'], b'cg12')\n\n @stream_test\n def test_read_api(self):\n sa = db.Stream('a')\n sb = db.Stream('b')\n sc = db.Stream('c')\n streams = [sa, sb, sc]\n docids = []\n for i in range(20):\n stream = streams[i % 3]\n docids.append(stream.add({'k': 'v%s' % i}, id=i + 1))\n\n def assertData(ret, idxs, is_multi=False):\n if is_multi:\n ret = dict(ret)\n accum = {}\n for idx in idxs:\n sname = encode('abc'[idx % 3])\n accum.setdefault(sname, [])\n accum[sname].append((\n docids[idx], {b'k': encode('v%s' % idx)}))\n else:\n accum = []\n for idx in idxs:\n accum.append((docids[idx], {b'k': encode('v%s' % idx)}))\n self.assertEqual(ret, accum)\n\n assertData(sa.read(), [0, 3, 6, 9, 12, 15, 18])\n assertData(sc.read(), [2, 5, 8, 11, 14, 17])\n\n # We can specify a maximum number of records via \"count\".\n assertData(sa.read(3), [0, 3, 6])\n assertData(sb.read(2), [1, 4])\n assertData(sc.read(4), [2, 5, 8, 11])\n\n # We get the same values we read earlier.\n assertData(sa.read(2), [0, 3])\n\n # We can pass a minimum ID and will get newer data -- even if the ID\n # does not exist in the stream. We can also pass an exact ID and unlike\n # the range function, it is not inclusive.\n assertData(sa.read(2, last_id=docids[3]), [6, 9])\n assertData(sa.read(2, last_id=docids[4]), [6, 9])\n\n # If the last ID exceeds the highest ID (indicating no data), None is\n # returned. This is the same whether or not \"count\" is specified.\n self.assertEqual(sa.read(last_id=docids[18]), [])\n self.assertEqual(sa.read(2, last_id=docids[18]), [])\n\n # The count is a maximum, so up-to 2 items are return -- but since only\n # one item in the stream exceeds the given ID, we only get one result.\n assertData(sa.read(2, last_id=docids[17]), [18])\n\n # If a timeout is set and any stream can return a value, then that\n # value is returned immediately.\n assertData(sa.read(2, block=1, last_id=docids[17]), [18])\n assertData(sb.read(2, block=1, last_id=docids[18]), [19])\n\n # If no items are available and we timed-out, None is returned.\n self.assertEqual(sc.read(block=1, last_id=docids[19]), [])\n self.assertEqual(sc.read(2, block=1, last_id=docids[19]), [])\n\n # When multiple keys are given, up-to \"count\" items per stream\n # are returned.\n normalized = _normalize_stream_keys(['a', 'b', 'c'])\n res = db.xread(normalized, count=2)\n assertData(res, [0, 1, 2, 3, 4, 5], True)\n\n # Specify max-ids for each stream. The max value in \"c\" is 17, so\n # nothing will be returned for \"c\".\n uids = [decode(docid) for docid in docids]\n res = db.xread({'a': uids[15], 'b': uids[16], 'c': uids[17]},\n count=3)\n assertData(res, [18, 19], True)\n\n # Now we limit ourselves to being able to pull only a single item from\n # stream \"c\".\n res = db.xread({'a': uids[18], 'b': uids[19], 'c': uids[16]})\n assertData(res, [17], True)\n\n # None is returned when no results are present and timeout is None or\n # if we reach the timeout.\n res = db.xread({'a': uids[18], 'b': uids[19], 'c': uids[17]})\n self.assertEqual(res, [])\n\n res = db.xread({'a': uids[18], 'b': uids[19], 'c': uids[17]},\n count=1, block=1)\n self.assertEqual(res, [])\n\n @stream_test\n def test_set_id_stream(self):\n stream = db.Stream('my-stream')\n stream.add({'k': 'v1'}, id='3')\n self.assertTrue(stream.set_id('5'))\n self.assertRaises(Exception, stream.add, {'k': 'v2'}, id='4')\n stream.add({'k': 'v3'}, id='6')\n self.assertEqual(stream.read(), [\n (b'3-0', {b'k': b'v1'}),\n (b'6-0', {b'k': b'v3'})])\n\n @stream_test\n def test_basic_apis(self):\n stream = db.Stream('my-stream')\n\n # Item ids will be 1-0, 11-0, ...91-0.\n item_ids = [stream.add({'k': 'v%s' % i}, id='%s1' % i)\n for i in range(10)]\n self.assertEqual(len(stream), 10)\n\n # Redis automatically adds the sequence number.\n self.assertEqual(item_ids[:3], [b'1-0', b'11-0', b'21-0'])\n self.assertEqual(item_ids[7:], [b'71-0', b'81-0', b'91-0'])\n\n def assertData(items, expected):\n self.assertEqual(items, [(item_ids[e], {b'k': encode('v%s' % e)})\n for e in expected])\n\n # The sequence number is optional if it's zero.\n assertData(stream[:'1'], [0])\n assertData(stream[:'1-0'], [0])\n assertData(stream['91':], [9])\n assertData(stream['91-0':], [9])\n assertData(stream['91-1':], [])\n\n # We can slice up to a value. If the sequence number is omitted it will\n # be treated as zero.\n assertData(stream[:'31'], [0, 1, 2, 3])\n assertData(stream[:'31-0'], [0, 1, 2, 3])\n assertData(stream[:'31-1'], [0, 1, 2, 3])\n\n # We can slice up from a value as well.\n assertData(stream['71':], [7, 8, 9])\n assertData(stream['71-0':], [7, 8, 9])\n assertData(stream['71-1':], [8, 9])\n\n # We can also slice between values.\n assertData(stream['21':'41'], [2, 3, 4])\n assertData(stream['21-0':'41'], [2, 3, 4])\n assertData(stream['21':'41-0'], [2, 3, 4])\n assertData(stream['21-1':'41'], [3, 4])\n assertData(stream['21-1':'41-1'], [3, 4])\n\n # The \"step\" parameter, the third part of the slice, indicates count.\n assertData(stream['41'::3], [4, 5, 6])\n assertData(stream[:'41':3], [0, 1, 2])\n assertData(stream['81'::3], [8, 9])\n\n # Test using in-between values. The endpoints of the slice are\n # inclusive.\n assertData(stream[:'5'], [0])\n assertData(stream[:'5-1'], [0])\n assertData(stream[:'25'], [0, 1, 2])\n assertData(stream[:'25-1'], [0, 1, 2])\n assertData(stream['25':'55'], [3, 4, 5])\n assertData(stream['55':'92'], [6, 7, 8, 9])\n assertData(stream['91':'92'], [9])\n\n # If we go above or below, it returns an empty list.\n assertData(stream['92':], [])\n assertData(stream[:'0'], [])\n\n # We can also provide a count when indexing in-between.\n assertData(stream['25':'55':2], [3, 4])\n assertData(stream['55':'92':1], [6])\n\n # Use \"del\" to remove items by ID. The sequence number will be treated\n # as zero if not provided.\n del stream['21', '41-0', '61']\n del stream['51-1'] # Has no effect since we only have 51-0.\n assertData(stream['5':'65'], [1, 3, 5])\n self.assertEqual(len(stream), 7)\n\n del stream['21'] # Can delete non-existent items.\n\n # Cannot add lower than maximum ID.\n self.assertRaises(Exception, stream.add, {'k': 'v2'}, id='90-1')\n self.assertRaises(Exception, stream.add, {'k': 'v2'}, id='91-0')\n\n # Adding a \"1\" to the sequence works:\n new_id = stream.add({'k': 'v10'}, id='91-1')\n self.assertEqual(new_id, b'91-1')\n\n # Length reflects the latest addition.\n self.assertEqual(len(stream), 8)\n\n # Range starting at 91-0 yields 91-0 and 91-1.\n data = stream['91-0':]\n self.assertEqual(len(data), 2)\n self.assertEqual([obj_id for obj_id, _ in data], [b'91-0', b'91-1'])\n\n # Remove the two 91-x items.\n del stream['91', '91-1']\n\n # Sanity check that the data was really remove.\n self.assertEqual(len(stream), 6)\n assertData(stream['61':], [7, 8])\n\n # Can we add an item with an id lower than 91? We've deleted it so the\n # last value is 81, but this still doesn't work (?).\n for docid in ('90', '91', '91-1'):\n self.assertRaises(Exception, stream.add, {'k': 'v9'}, id='90')\n\n new_id = stream.add({'k': 'v9'}, id='91-2')\n self.assertEqual(new_id, b'91-2')\n self.assertEqual(stream['91':], [(b'91-2', {b'k': b'v9'})])\n del stream['91-2']\n\n nremoved = stream.trim(4, approximate=False)\n self.assertEqual(nremoved, 2)\n assertData(stream[:], [3, 5, 7, 8])\n\n # Trimming again returns 0, no items removed.\n self.assertEqual(stream.trim(4, approximate=False), 0)\n\n # Verify we can iterate over the stream.\n assertData(list(stream), [3, 5, 7, 8])\n\n # Verify we can get items by id.\n d5 = stream.get('51-0')\n self.assertEqual(d5, (b'51-0', {b'k': b'v5'}))\n\n # Nonexistant values return None.\n self.assertTrue(stream.get('61-0') is None)\n\n\nclass TestBitField(WalrusTestCase):\n def setUp(self):\n super(TestBitField, self).setUp()\n self.bf = db.bit_field('bf')\n\n def test_simple_operations(self):\n resp = (self.bf\n .set('u8', 8, 255)\n .get('u8', 0)\n .get('u4', 8) # 1111\n .get('u4', 12) # 1111\n .get('u4', 13) # 1110\n .execute())\n self.assertEqual(resp, [0, 0, 15, 15, 14])\n\n resp = (self.bf\n .set('u8', 4, 1) # 00ff -> 001f (returns old val, 0x0f)\n .get('u16', 0) # 001f (00011111)\n .set('u16', 0, 0)) # 001f -> 0000\n self.assertEqual(list(resp), [15, 31, 31])\n\n resp = (self.bf\n .incrby('u8', 8, 254)\n .get('u16', 0))\n self.assertEqual(list(resp), [254, 254])\n\n # Verify overflow protection works:\n resp = (self.bf\n .incrby('u8', 8, 2, 'FAIL')\n .incrby('u8', 8, 1)\n .incrby('u8', 8, 1) # Still \"FAIL\".\n .get('u16', 0))\n self.assertEqual(list(resp), [None, 255, None, 255])\n\n self.assertEqual(self.bf.get_raw(), b'\\x00\\xff')\n\n def test_slicing(self):\n resp = self.bf.set('u8', 0, 166).execute() # 10100110\n\n self.assertEqual(self.bf[:8], 166)\n self.assertEqual(self.bf[:4], 10) # 1010\n self.assertEqual(self.bf[4:8], 6) # 0110\n self.assertEqual(self.bf[2:6], 9) # 1001\n self.assertEqual(self.bf[6:10], 8) # 10?? -> 1000\n self.assertEqual(self.bf[8:16], 0) # Undefined, defaults to zero.\n\n self.assertRaises(ValueError, lambda: self.bf[1])\n self.assertRaises(ValueError, lambda: self.bf[1:])\n self.assertRaises(ValueError, lambda: self.bf[4:1])\n\n self.bf[:8] = 89 # 01011001\n self.assertEqual(self.bf[:8], 89)\n def overflow():\n self.bf[:8] = 256\n self.assertRaises(ValueError, overflow)\n self.bf[:8] = 255\n self.assertEqual(self.bf[:8], 255)\n\n del self.bf[2:6]\n self.assertEqual(self.bf[:8], 195) # 11000011\n\n\nclass TestBloomFilter(WalrusTestCase):\n def setUp(self):\n super(TestBloomFilter, self).setUp()\n self.bf = db.bloom_filter('bf')\n\n def test_bloom_filter(self):\n data = ('foo', 'bar', 'baz', 'nugget', 'this is a test', 'testing',\n 'alpha', 'beta', 'delta', 'gamma')\n\n # Verify that the bloom-filter does not contain any of our items.\n for item in data:\n self.assertFalse(item in self.bf)\n\n # Add all the items to the bloom filter.\n for item in data:\n self.bf.add(item)\n\n # Verify that all of our items are now present.\n for item in data:\n self.assertTrue(item in self.bf)\n\n # Making some small modifications we can verify that all these other\n # items are not present, however.\n for item in data:\n self.assertFalse(item.upper() in self.bf)\n self.assertFalse(item.title() in self.bf)\n" }, { "alpha_fraction": 0.5865978002548218, "alphanum_fraction": 0.5874643325805664, "avg_line_length": 30.653715133666992, "blob_id": "bb73a44bf271932777a3c9f1d914163e19f3cad0", "content_id": "3aa5f386d26126d5e0dec956bcca9feb686fb563", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27697, "license_type": "permissive", "max_line_length": 79, "num_lines": 875, "path": "/walrus/models.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from copy import deepcopy\nimport datetime\nimport json\nimport pickle\nimport re\nimport sys\nimport time\nimport uuid\nfrom warnings import warn\n\nfrom walrus.containers import Array\nfrom walrus.containers import Hash\nfrom walrus.containers import HyperLogLog\nfrom walrus.containers import List\nfrom walrus.containers import Set\nfrom walrus.containers import ZSet\nfrom walrus.query import ABSOLUTE\nfrom walrus.query import CONTINUOUS\nfrom walrus.query import Desc\nfrom walrus.query import Executor\nfrom walrus.query import FTS\nfrom walrus.query import Node\nfrom walrus.search import Tokenizer\nfrom walrus.utils import basestring_type\nfrom walrus.utils import decode\nfrom walrus.utils import decode_dict_keys\nfrom walrus.utils import encode\nfrom walrus.utils import PY3\nfrom walrus.utils import unicode_type\n\n\nclass Field(Node):\n \"\"\"\n Named attribute on a model that will hold a value of the given\n type. Fields are declared as attributes on a model class.\n\n Example::\n\n walrus_db = Database()\n\n class User(Model):\n __database__ = walrus_db\n __namespace__ = 'my-app'\n\n # Use the user's email address as the primary key.\n # All primary key fields will also get a secondary\n # index, so there's no need to specify index=True.\n email = TextField(primary_key=True)\n\n # Store the user's interests in a free-form text\n # field. Also create a secondary full-text search\n # index on this field.\n interests = TextField(\n fts=True,\n stemmer=True,\n min_word_length=3)\n\n class Note(Model):\n __database__ = walrus_app\n __namespace__ = 'my-app'\n\n # A note is associated with a user. We will create a\n # secondary index on this field so we can efficiently\n # retrieve all notes created by a specific user.\n user_email = TextField(index=True)\n\n # Store the note content in a searchable text field. Use\n # the double-metaphone algorithm to index the content.\n content = TextField(\n fts=True,\n stemmer=True,\n metaphone=True)\n\n # Store the timestamp the note was created automatically.\n # Note that we do not call `now()`, but rather pass the\n # function itself.\n timestamp = DateTimeField(default=datetime.datetime.now)\n \"\"\"\n _coerce = None\n\n def __init__(self, index=False, primary_key=False, default=None):\n \"\"\"\n :param bool index: Use this field as an index. Indexed\n fields will support :py:meth:`Model.get` lookups.\n :param bool primary_key: Use this field as the primary key.\n \"\"\"\n self._index = index or primary_key\n self._primary_key = primary_key\n self._default = default\n\n def _generate_key(self):\n raise NotImplementedError\n\n def db_value(self, value):\n if self._coerce:\n return self._coerce(value)\n return value\n\n def python_value(self, value):\n if self._coerce:\n return self._coerce(value)\n return value\n\n def add_to_class(self, model_class, name):\n self.model_class = model_class\n self.name = name\n setattr(model_class, name, self)\n\n def __get__(self, instance, instance_type=None):\n if instance is not None:\n return instance._data.get(self.name)\n return self\n\n def __set__(self, instance, value):\n instance._data[self.name] = value\n\n def get_index(self, op):\n indexes = self.get_indexes()\n for index in indexes:\n if op in index.operations:\n return index\n\n raise ValueError('Operation %s is not supported by an index.' % op)\n\n def get_indexes(self):\n \"\"\"\n Return a list of secondary indexes to create for the\n field. For instance, a TextField might have a full-text\n search index, whereas an IntegerField would have a scalar\n index that supported range queries.\n \"\"\"\n return [AbsoluteIndex(self)]\n\n\nclass _ScalarField(Field):\n def get_indexes(self):\n return [AbsoluteIndex(self), ContinuousIndex(self)]\n\n\nclass IntegerField(_ScalarField):\n \"\"\"Store integer values.\"\"\"\n _coerce = int\n\n def db_value(self, value):\n return 0 if value is None else int(value)\n\n\nclass AutoIncrementField(IntegerField):\n \"\"\"Auto-incrementing primary key field.\"\"\"\n def __init__(self, *args, **kwargs):\n kwargs['primary_key'] = True\n return super(AutoIncrementField, self).__init__(*args, **kwargs)\n\n def _generate_key(self):\n query_helper = self.model_class._query\n key = query_helper.make_key(self.name, '_sequence')\n return self.model_class.__database__.incr(key)\n\n\nclass FloatField(_ScalarField):\n \"\"\"Store floating point values.\"\"\"\n _coerce = float\n\n def db_value(self, value):\n return 0. if value is None else float(value)\n\n\nclass ByteField(Field):\n \"\"\"Store arbitrary bytes.\"\"\"\n def db_value(self, value):\n if isinstance(value, unicode_type):\n value = value.encode('utf-8')\n elif value is None:\n value = b''\n return value\n\n\nclass TextField(Field):\n \"\"\"\n Store unicode strings, encoded as UTF-8. :py:class:`TextField`\n also supports full-text search through the optional ``fts``\n parameter.\n\n .. note:: If full-text search is enabled for the field, then\n the ``index`` argument is implied.\n\n :param bool fts: Enable simple full-text search.\n :param bool stemmer: Use porter stemmer to process words.\n :param bool metaphone: Use the double metaphone algorithm to\n process words.\n :param str stopwords_file: File containing stopwords, one per\n line. If not specified, the default stopwords will be used.\n :param int min_word_length: Minimum length (inclusive) of word\n to be included in search index.\n \"\"\"\n def __init__(self, fts=False, stemmer=True, metaphone=False,\n stopwords_file=None, min_word_length=None, *args, **kwargs):\n super(TextField, self).__init__(*args, **kwargs)\n self._fts = fts\n self._stemmer = stemmer\n self._metaphone = metaphone\n self._stopwords_file = stopwords_file\n self._min_word_length = min_word_length\n self._index = self._index or self._fts\n\n def db_value(self, value):\n return b'' if value is None else encode(value)\n\n def python_value(self, value):\n return decode(value)\n\n def get_indexes(self):\n indexes = super(TextField, self).get_indexes()\n if self._fts:\n indexes.append(FullTextIndex(\n self,\n self._stemmer,\n self._metaphone,\n self._stopwords_file,\n self._min_word_length))\n return indexes\n\n\nclass BooleanField(Field):\n \"\"\"Store boolean values.\"\"\"\n def db_value(self, value):\n return '1' if value else '0'\n\n def python_value(self, value):\n return decode(value) == '1'\n\n\nclass UUIDField(Field):\n \"\"\"Store unique IDs. Can be used as primary key.\"\"\"\n def __init__(self, **kwargs):\n kwargs['index'] = True\n super(UUIDField, self).__init__(**kwargs)\n\n def db_value(self, value):\n return encode(value.hex if value is not None else '')\n\n def python_value(self, value):\n return uuid.UUID(decode(value)) if value else None\n\n def _generate_key(self):\n return uuid.uuid4()\n\n\nclass DateTimeField(_ScalarField):\n \"\"\"Store Python datetime objects.\"\"\"\n def db_value(self, value):\n if value is None:\n return 0.\n\n timestamp = time.mktime(value.timetuple())\n micro = value.microsecond * (10 ** -6)\n return timestamp + micro\n\n def python_value(self, value):\n if not value:\n return None\n elif isinstance(value, (basestring_type, int, float)):\n return datetime.datetime.fromtimestamp(float(value))\n else:\n return value\n\n\nclass DateField(DateTimeField):\n \"\"\"Store Python date objects.\"\"\"\n def db_value(self, value):\n if value is None:\n return 0.\n return time.mktime(value.timetuple())\n\n def python_value(self, value):\n if not value:\n return None\n elif isinstance(value, (basestring_type, int, float)):\n return datetime.datetime.fromtimestamp(float(value)).date()\n else:\n return value\n\n\nclass JSONField(Field):\n \"\"\"Store arbitrary JSON data.\"\"\"\n def db_value(self, value):\n return encode(json.dumps(value))\n\n def python_value(self, value):\n return json.loads(decode(value))\n\n\nclass PickledField(Field):\n \"\"\"Store arbitrary Python objects.\"\"\"\n def db_value(self, value):\n return pickle.dumps(value, pickle.HIGHEST_PROTOCOL)\n\n def python_value(self, value):\n return pickle.loads(value)\n\n\nclass _ContainerField(Field):\n container_class = None\n\n def __init__(self, *args, **kwargs):\n super(_ContainerField, self).__init__(*args, **kwargs)\n if self._primary_key:\n raise ValueError('Container fields cannot be primary keys.')\n if self._index:\n raise ValueError('Container fields cannot be indexed.')\n\n def _get_container(self, instance):\n return self.container_class(\n self.model_class.__database__,\n self.__key__(instance))\n\n def __key__(self, instance):\n return self.model_class._query.make_key(\n 'container',\n self.name,\n instance.get_hash_id())\n\n def __get__(self, instance, instance_type=None):\n if instance is not None:\n if not instance.get_id():\n raise ValueError('Model must have a primary key before '\n 'container attributes can be accessed.')\n return self._get_container(instance)\n return self\n\n def __set__(self, instance, instance_type=None):\n raise ValueError('Cannot set the value of a container field.')\n\n def _delete(self, instance):\n self._get_container(instance).clear()\n\n\nclass HashField(_ContainerField):\n \"\"\"Store values in a Redis hash.\"\"\"\n container_class = Hash\n\n\nclass ListField(_ContainerField):\n \"\"\"Store values in a Redis list.\"\"\"\n container_class = List\n\n\nclass SetField(_ContainerField):\n \"\"\"Store values in a Redis set.\"\"\"\n container_class = Set\n\n\nclass ZSetField(_ContainerField):\n \"\"\"Store values in a Redis sorted set.\"\"\"\n container_class = ZSet\n\n\nclass Query(object):\n def __init__(self, model_class):\n self.model_class = model_class\n\n @property\n def _base_key(self):\n model_name = self.model_class.__name__.lower()\n if self.model_class.__namespace__:\n return '%s|%s:' % (self.model_class.__namespace__, model_name)\n return '%s:' % model_name\n\n def make_key(self, *parts):\n \"\"\"Generate a namespaced key for the given path.\"\"\"\n separator = getattr(self.model_class, 'index_separator', '.')\n parts = map(decode, parts)\n return '%s%s' % (self._base_key, separator.join(map(str, parts)))\n\n def get_primary_hash_key(self, primary_key):\n pk_field = self.model_class._fields[self.model_class._primary_key]\n return self.make_key('id', pk_field.db_value(primary_key))\n\n def all_index(self):\n return self.model_class.__database__.Set(self.make_key('all'))\n\n\nclass BaseIndex(object):\n operations = None\n\n def __init__(self, field):\n self.field = field\n self.__database__ = self.field.model_class.__database__\n self.query_helper = self.field.model_class._query\n\n def field_value(self, instance):\n return self.field.db_value(getattr(instance, self.field.name))\n\n def get_key(self, value):\n raise NotImplementedError\n\n def store_instance(self, key, instance, value):\n raise NotImplementedError\n\n def delete_instance(self, key, instance, value):\n raise NotImplementedError\n\n def save(self, instance):\n value = self.field_value(instance)\n key = self.get_key(value)\n self.store_instance(key, instance, value)\n\n def remove(self, instance):\n value = self.field_value(instance)\n key = self.get_key(value)\n self.delete_instance(key, instance, value)\n\n\nclass AbsoluteIndex(BaseIndex):\n operations = ABSOLUTE\n\n def get_key(self, value):\n key = self.query_helper.make_key(\n self.field.name,\n 'absolute',\n value)\n return self.__database__.Set(key)\n\n def store_instance(self, key, instance, value):\n key.add(instance.get_hash_id())\n\n def delete_instance(self, key, instance, value):\n key.remove(instance.get_hash_id())\n if len(key) == 0:\n key.clear()\n\n\nclass ContinuousIndex(BaseIndex):\n operations = CONTINUOUS\n\n def get_key(self, value):\n key = self.query_helper.make_key(\n self.field.name,\n 'continuous')\n return self.__database__.ZSet(key)\n\n def store_instance(self, key, instance, value):\n key[instance.get_hash_id()] = value\n\n def delete_instance(self, key, instance, value):\n del key[instance.get_hash_id()]\n if len(key) == 0:\n key.clear()\n\n\nclass FullTextIndex(BaseIndex):\n operations = FTS\n\n def __init__(self, field, stemmer=True, metaphone=False,\n stopwords_file=None, min_word_length=None):\n super(FullTextIndex, self).__init__(field)\n self.tokenizer = Tokenizer(\n stemmer=stemmer,\n metaphone=metaphone,\n stopwords_file=stopwords_file or 'stopwords.txt',\n min_word_length=min_word_length)\n\n def get_key(self, value):\n key = self.query_helper.make_key(\n self.field.name,\n 'fts',\n value)\n return self.__database__.ZSet(key)\n\n def store_instance(self, key, instance, value):\n hash_id = instance.get_hash_id()\n for word, score in self.tokenizer.tokenize(value).items():\n key = self.get_key(word)\n key[hash_id] = -score\n\n def delete_instance(self, key, instance, value):\n hash_id = instance.get_hash_id()\n for word in self.tokenizer.tokenize(value):\n key = self.get_key(word)\n del key[hash_id]\n if len(key) == 0:\n key.clear()\n\n\nclass BaseModel(type):\n def __new__(cls, name, bases, attrs):\n if not bases:\n return super(BaseModel, cls).__new__(cls, name, bases, attrs)\n\n if 'database' in attrs:\n warn('\"database\" has been deprecated in favor of \"__database__\" '\n 'for Walrus models.', DeprecationWarning)\n attrs['__database__'] = attrs.pop('database')\n if 'namespace' in attrs:\n warn('\"namespace\" has been deprecated in favor of \"__namespace__\" '\n 'for Walrus models.', DeprecationWarning)\n attrs['__namespace__'] = attrs.pop('namespace')\n\n # Declarative base juju.\n ignore = set()\n primary_key = None\n\n for key, value in attrs.items():\n if isinstance(value, Field) and value._primary_key:\n primary_key = (key, value)\n\n for base in bases:\n for key, value in base.__dict__.items():\n if key in attrs:\n continue\n if isinstance(value, Field):\n if value._primary_key and primary_key:\n ignore.add(key)\n else:\n if value._primary_key:\n primary_key = (key, value)\n attrs[key] = deepcopy(value)\n\n if not primary_key:\n attrs['_id'] = AutoIncrementField()\n primary_key = ('_id', attrs['_id'])\n\n model_class = super(BaseModel, cls).__new__(cls, name, bases, attrs)\n model_class._data = None\n\n defaults = {}\n fields = {}\n indexes = []\n for key, value in model_class.__dict__.items():\n if isinstance(value, Field) and key not in ignore:\n value.add_to_class(model_class, key)\n if value._index:\n indexes.append(value)\n fields[key] = value\n if value._default is not None:\n defaults[key] = value._default\n\n model_class._defaults = defaults\n model_class._fields = fields\n model_class._indexes = indexes\n model_class._primary_key = primary_key[0]\n model_class._query = Query(model_class)\n return model_class\n\n\ndef _with_metaclass(meta, base=object):\n return meta(\"NewBase\", (base,), {'__database__': None,\n '__namespace__': None})\n\n\nclass Model(_with_metaclass(BaseModel)):\n \"\"\"\n A collection of fields to be stored in the database. Walrus\n stores model instance data in hashes keyed by a combination of\n model name and primary key value. Instance attributes are\n automatically converted to values suitable for storage in Redis\n (i.e., datetime becomes timestamp), and vice-versa.\n\n Additionally, model fields can be ``indexed``, which allows\n filtering. There are three types of indexes:\n\n * Absolute\n * Scalar\n * Full-text search\n\n Absolute indexes are used for values like strings or UUIDs and\n support only equality and inequality checks.\n\n Scalar indexes are for numeric values as well as datetimes,\n and support equality, inequality, and greater or less-than.\n\n The final type of index, FullText, can only be used with the\n :py:class:`TextField`. FullText indexes allow search using\n the ``match()`` method. For more info, see :ref:`fts`.\n \"\"\"\n #: **Required**: the :py:class:`Database` instance to use to\n #: persist model data.\n __database__ = None\n\n #: **Optional**: namespace to use for model data.\n __namespace__ = None\n\n #: **Required**: character to use as a delimiter for indexes, default \".\"\n index_separator = '.'\n\n def __init__(self, *args, **kwargs):\n self._data = {}\n self._load_default_dict()\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n def __repr__(self):\n return '<%s: %s>' % (type(self).__name__, self.get_id())\n\n def _load_default_dict(self):\n for field_name, default in self._defaults.items():\n if callable(default):\n default = default()\n setattr(self, field_name, default)\n\n def incr(self, field, incr_by=1):\n \"\"\"\n Increment the value stored in the given field by the specified\n amount. Any indexes will be updated at the time ``incr()`` is\n called.\n\n :param Field field: A field instance.\n :param incr_by: An ``int`` or ``float``.\n\n Example:\n\n .. code-block:: python\n\n # Retrieve a page counter object for the given URL.\n page_count = PageCounter.get(PageCounter.url == url)\n\n # Update the hit count, persisting to the database and\n # updating secondary indexes in one go.\n page_count.incr(PageCounter.hits)\n \"\"\"\n model_hash = self.to_hash()\n\n # Remove the value from the index.\n for index in field.get_indexes():\n index.remove(self)\n\n if isinstance(incr_by, int):\n new_val = model_hash.incr(field.name, incr_by)\n else:\n new_val = model_hash.incr_float(field.name, incr_by)\n setattr(self, field.name, new_val)\n\n # Re-index the new value.\n for index in field.get_indexes():\n index.save(self)\n\n return new_val\n\n def get_id(self):\n \"\"\"\n Return the primary key for the model instance. If the\n model is unsaved, then this value will be ``None``.\n \"\"\"\n try:\n return getattr(self, self._primary_key)\n except KeyError:\n return None\n\n def get_hash_id(self):\n return self._query.get_primary_hash_key(self.get_id())\n\n def _get_data_dict(self):\n data = {}\n for name, field in self._fields.items():\n if name in self._data:\n data[name] = field.db_value(self._data[name])\n return data\n\n def to_hash(self):\n \"\"\"\n Return a :py:class:`Hash` instance corresponding to the\n raw model data.\n \"\"\"\n return self.__database__.Hash(self.get_hash_id())\n\n @classmethod\n def create(cls, **kwargs):\n \"\"\"\n Create a new model instance and save it to the database.\n Values are passed in as keyword arguments.\n\n Example::\n\n user = User.create(first_name='Charlie', last_name='Leifer')\n \"\"\"\n instance = cls(**kwargs)\n instance.save(_is_create=True)\n return instance\n\n @classmethod\n def all(cls):\n \"\"\"\n Return an iterator that successively yields saved model\n instances. Models are saved in an unordered :py:class:`Set`,\n so the iterator will return them in arbitrary order.\n\n Example::\n\n for note in Note.all():\n print note.content\n\n To return models in sorted order, see :py:meth:`Model.query`.\n Example returning all records, sorted newest to oldest::\n\n for note in Note.query(order_by=Note.timestamp.desc()):\n print note.timestamp, note.content\n \"\"\"\n for result in cls._query.all_index():\n yield cls.load(result, convert_key=False)\n\n @classmethod\n def query(cls, expression=None, order_by=None):\n \"\"\"\n Return model instances matching the given expression (if\n specified). Additionally, matching instances can be returned\n sorted by field value.\n\n Example::\n\n # Get administrators sorted by username.\n admin_users = User.query(\n (User.admin == True),\n order_by=User.username)\n\n # List blog entries newest to oldest.\n entries = Entry.query(order_by=Entry.timestamp.desc())\n\n # Perform a complex filter.\n values = StatData.query(\n (StatData.timestamp < datetime.date.today()) &\n ((StatData.type == 'pv') | (StatData.type == 'cv')))\n\n :param expression: A boolean expression to filter by.\n :param order_by: A field whose value should be used to\n sort returned instances.\n \"\"\"\n if expression is not None:\n executor = Executor(cls.__database__)\n result = executor.execute(expression)\n else:\n result = cls._query.all_index()\n\n if order_by is not None:\n desc = False\n if isinstance(order_by, Desc):\n desc = True\n order_by = order_by.node\n\n alpha = not isinstance(order_by, _ScalarField)\n result = cls.__database__.sort(\n result.key,\n by='*->%s' % order_by.name,\n alpha=alpha,\n desc=desc)\n elif isinstance(result, ZSet):\n result = result.iterator(reverse=True)\n\n for hash_id in result:\n yield cls.load(hash_id, convert_key=False)\n\n @classmethod\n def query_delete(cls, expression=None):\n \"\"\"\n Delete model instances matching the given expression (if\n specified). If no expression is provided, then all model instances\n will be deleted.\n\n :param expression: A boolean expression to filter by.\n \"\"\"\n if expression is not None:\n executor = Executor(cls.__database__)\n result = executor.execute(expression)\n else:\n result = cls._query.all_index()\n\n for hash_id in result:\n cls.load(hash_id, convert_key=False).delete()\n\n @classmethod\n def get(cls, expression):\n \"\"\"\n Retrieve the model instance matching the given expression.\n If the number of matching results is not equal to one, then\n a ``ValueError`` will be raised.\n\n :param expression: A boolean expression to filter by.\n :returns: The matching :py:class:`Model` instance.\n :raises: ``ValueError`` if result set size is not 1.\n \"\"\"\n executor = Executor(cls.__database__)\n result = executor.execute(expression)\n if len(result) != 1:\n raise ValueError('Got %s results, expected 1.' % len(result))\n return cls.load(result._first_or_any(), convert_key=False)\n\n @classmethod\n def load(cls, primary_key, convert_key=True):\n \"\"\"\n Retrieve a model instance by primary key.\n\n :param primary_key: The primary key of the model instance.\n :returns: Corresponding :py:class:`Model` instance.\n :raises: ``KeyError`` if object with given primary key does\n not exist.\n \"\"\"\n if convert_key:\n primary_key = cls._query.get_primary_hash_key(primary_key)\n if not cls.__database__.hash_exists(primary_key):\n raise KeyError('Object not found.')\n raw_data = cls.__database__.hgetall(primary_key)\n if PY3:\n raw_data = decode_dict_keys(raw_data)\n data = {}\n for name, field in cls._fields.items():\n if isinstance(field, _ContainerField):\n continue\n elif name in raw_data:\n data[name] = field.python_value(raw_data[name])\n else:\n data[name] = None\n\n return cls(**data)\n\n @classmethod\n def count(cls):\n \"\"\"\n Return the number of objects in the given collection.\n \"\"\"\n return len(cls._query.all_index())\n\n def delete(self, for_update=False):\n \"\"\"\n Delete the given model instance.\n \"\"\"\n hash_key = self.get_hash_id()\n try:\n original_instance = self.load(hash_key, convert_key=False)\n except KeyError:\n return\n\n # Remove from the `all` index.\n all_index = self._query.all_index()\n all_index.remove(hash_key)\n\n # Remove from the secondary indexes.\n for field in self._indexes:\n for index in field.get_indexes():\n index.remove(original_instance)\n\n if not for_update:\n for field in self._fields.values():\n if isinstance(field, _ContainerField):\n field._delete(self)\n\n # Remove the object itself.\n self.__database__.delete(hash_key)\n\n def save(self, _is_create=False):\n \"\"\"\n Save the given model instance. If the model does not have\n a primary key value, Walrus will call the primary key field's\n ``generate_key()`` method to attempt to generate a suitable\n value.\n \"\"\"\n pk_field = self._fields[self._primary_key]\n if not self._data.get(self._primary_key):\n setattr(self, self._primary_key, pk_field._generate_key())\n require_delete = False\n else:\n require_delete = not _is_create\n\n if require_delete:\n self.delete(for_update=True)\n\n data = self._get_data_dict()\n hash_obj = self.to_hash()\n hash_obj.clear()\n hash_obj.update(data)\n\n all_index = self._query.all_index()\n all_index.add(self.get_hash_id())\n\n for field in self._indexes:\n for index in field.get_indexes():\n index.save(self)\n" }, { "alpha_fraction": 0.6741213798522949, "alphanum_fraction": 0.7028753757476807, "avg_line_length": 33.77777862548828, "blob_id": "f7d92c7ca476a588cb06d6d8883b3762f9ceffde", "content_id": "d8c2e084138b43b2c5bd3d222d8603bba62b5e1c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 313, "license_type": "permissive", "max_line_length": 74, "num_lines": 9, "path": "/walrus/scripts/cas.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "-- Simple compare-and-swap using a prefixed match for the compare portion.\n-- This makes it possible to do some basic fencing/etc.\nlocal value_length = string.len(ARGV[1])\nif redis.call('GETRANGE', KEYS[1], 0, value_length - 1) == ARGV[1] then\n redis.call('SET', KEYS[1], ARGV[2])\n return 1\nelse\n return 0\nend\n" }, { "alpha_fraction": 0.715871274471283, "alphanum_fraction": 0.7230854630470276, "avg_line_length": 25.101449966430664, "blob_id": "178d3a50cd302116df9e83526a2611609d2622f2", "content_id": "50789b796498b9a47a6a5aa4fece25c2dd3fca85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1802, "license_type": "permissive", "max_line_length": 108, "num_lines": 69, "path": "/docs/index.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. walrus documentation master file, created by\n sphinx-quickstart on Sun Jan 4 00:39:19 2015.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nwalrus\n======\n\n.. image:: http://media.charlesleifer.com/blog/photos/walrus-logo-0.png\n\n.. py:module:: walrus\n\nLightweight Python utilities for working with `Redis <http://redis.io>`_.\n\nThe purpose of `walrus <https://github.com/coleifer/walrus>`_ is to make\nworking with Redis in Python a little easier. Rather than ask you to learn a\nnew library, walrus subclasses and extends the popular ``redis-py`` client,\nallowing it to be used as a drop-in replacement. In addition to all the\nfeatures in ``redis-py``, walrus adds support for some newer commands,\nincluding full support for streams and consumer groups.\n\nwalrus consists of:\n\n* pythonic container classes for the Redis data-types.\n* support for stream APIs, plus regular and blocking ``zpop`` variants.\n* autocomplete\n* bloom filter\n* cache\n* full-text search\n* graph store\n* rate limiting\n* locks\n* **experimental** active-record models (secondary indexes, full-text search, composable query filters, etc)\n* more? more!\n\nMy hope is that walrus saves you time developing your application by providing\nuseful Redis-specific components. If you have an idea for a new feature, please\ndon't hesitate to `tell me about it <https://github.com/coleifer/walrus/issues/new>`_.\n\nTable of contents\n-----------------\n\nContents:\n\n.. toctree::\n :maxdepth: 2\n :glob:\n\n installation\n getting-started\n containers\n autocomplete\n cache\n full-text-search\n graph\n rate-limit\n streams\n models\n api\n alt-backends\n contributing\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\n" }, { "alpha_fraction": 0.6138613820075989, "alphanum_fraction": 0.6294201016426086, "avg_line_length": 32.66666793823242, "blob_id": "63f6bc415d8c8f7255c74bc5e495dbd66c8592cd", "content_id": "b7ffa4a3b783185690230f90dda8086177f1b9a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "permissive", "max_line_length": 46, "num_lines": 21, "path": "/walrus/tests/counter.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass TestCounter(WalrusTestCase):\n def test_counter(self):\n counter_a = db.counter('counter-a')\n counter_b = db.counter('counter-b')\n\n self.assertEqual(counter_a.value(), 0)\n self.assertEqual(counter_a.incr(), 1)\n self.assertEqual(counter_a.incr(3), 4)\n self.assertEqual(counter_a.value(), 4)\n\n self.assertEqual(counter_b.value(), 0)\n counter_b += 3\n self.assertEqual(counter_b.value(), 3)\n counter_b = counter_b + counter_a\n self.assertEqual(counter_b.value(), 7)\n counter_b = counter_b - 5\n self.assertEqual(counter_b.value(), 2)\n" }, { "alpha_fraction": 0.6860588788986206, "alphanum_fraction": 0.7126640677452087, "avg_line_length": 45.983333587646484, "blob_id": "e50102112874862a1d8961ac262845c44dbb9ec8", "content_id": "98e3a33ec549480b0cef3d801943cfb4c8ee5fb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2819, "license_type": "permissive", "max_line_length": 343, "num_lines": 60, "path": "/docs/rate-limit.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _rate-limit:\n\n.. py:module:: walrus\n\nRate Limit\n==========\n\nWalrus provides a simple :py:class:`RateLimit` implementation that makes use of Redis' :py:class:`List` object to store a series of event timestamps.\n\nAs the rate-limiter logs events, it maintains a fixed-size list of timestamps. When the list of timestamps is at max capacity, Walrus will look at the difference between the oldest timestamp and the present time to determine if a new event can be logged.\n\nExample with a rate limiter that allows 2 events every 10 seconds.\n\n* Log event from IP 192.168.1.2\n* List for key ``192.168.1.2`` now contains ``['14:42:27.04521']`` (these are actually unix timestamps, but are shown as times for readability).\n* Five seconds later log another event from the same IP.\n* List for ``192.168.1.2`` now contains ``['14:42:32.08293', '14:42:27.04521']``\n* Two seconds later attempt another event from the same IP. Since the list is \"at capacity\", and the time difference between the oldest event and the newest is less than 10 seconds, the event will not be logged and the event will be rate-limited.\n\nBasic usage\n-----------\n\nYou can :py:meth:`~RateLimit.limit` to log an event and check whether it should be rate-limited:\n\n.. code-block:: pycon\n\n >>> from walrus import *\n >>> db = Database()\n >>> rate_limit = db.rate_limit('mylimit', limit=2, per=60) # 2 events per minute.\n\n >>> rate_limit.limit('user-1')\n False\n >>> rate_limit.limit('user-1')\n False\n >>> rate_limit.limit('user-1') # Slow down, user-1!\n True\n\n >>> rate_limit.limit('user-2') # User 2 has not performed any events yet.\n False\n\nDecorator\n---------\n\nThe :py:meth:`RateLimit.rate_limited` decorator can be used to restrict calls to a function or method. The decorator accepts a ``key_function`` parameter which instructs it how to uniquely identify the source of the function call. For example, on a web-site, you might want the key function to be derived from the requesting user's IP address.\n\n.. code-block:: python\n\n rate_limit = walrus.rate_limit('login-limiter', limit=3, per=60)\n\n @app.route('/login/', methods=['GET', 'POST'])\n @rate_limit.rate_limited(lambda: request.remote_addr)\n def login():\n # Accept user login, etc.\n pass\n\n.. note::\n\n The :py:meth:`~RateLimit.rate_limited` decorator will raise a ``RateLimitException`` when an attempt to call the decorated function would exceed the allowed number of events. In your application you can catch these and perform the appropriate action.\n\nIf no key function is supplied, then Walrus will simply take the hash of all the arguments the function was called with and treat that as the key. Except for very simple functions, this is probably not what you want, so take care to ensure your ``key_function`` works as you expect.\n" }, { "alpha_fraction": 0.6795296669006348, "alphanum_fraction": 0.6801326274871826, "avg_line_length": 39.950618743896484, "blob_id": "7623d73304ea452c78e5dd2bb8fe867a258bad85", "content_id": "5ec553a9a2027bf89d1382ffe35bc259afebc4f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3317, "license_type": "permissive", "max_line_length": 361, "num_lines": 81, "path": "/docs/graph.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _graph:\n\n.. py:module:: walrus\n\nGraph\n=====\n\nThe walrus ``graph`` module provides a lightweight `hexastore <http://redis.io/topics/indexes#representing-and-querying-graphs-using-an-hexastore>`_ implementation. The :py:class:`Graph` class uses Redis :py:class:`ZSet` objects to store collections of ``subject - predicate - object`` triples. These relationships can then be queried in a very flexible manner.\n\n.. note:: The hexastore logic is expecting UTF-8 encoded values. If you are using Python 2.X unicode text, you are responsible for encoding prior to storing/querying with those values.\n\nFor example, we might store things like:\n\n* charlie -- friends -- huey\n* charlie -- lives -- Kansas\n* huey -- lives -- Kansas\n\nWe might wish to ask questions of our data-store like \"which of charlie's friends live in Kansas?\" To do this, we will store every permutation of the S-P-O triples, then we can efficiently query using the parts of the relationship we know beforehand.\n\n* query the \"object\" portion of the \"charlie -- friends\" subject/predicate.\n* for each object returned, turn it into the subject of a second query whose predicate is \"lives\" and whose object is \"Kansas\".\n\nSo we would return the subjects that satisfy the following expression::\n\n (\"charlie -- friends\") -- lives -- Kansas\n\nLet's go through this simple example to illustrate how the :py:class:`Graph` class works.\n\n.. code-block:: python\n\n from walrus import Database\n\n # Begin by instantiating a `Graph` object.\n db = Database()\n graph = db.graph('people')\n\n # Store my friends.\n # \"charlie\" is subject, \"friends\" is predicate, \"huey\" is object.\n graph.store('charlie', 'friends', 'huey')\n\n # Can also store multiple relationships at once.\n graph.store_many((\n ('charlie', 'friends', 'zaizee'),\n ('charlie', 'friends', 'nuggie')))\n\n # Store where people live.\n graph.store_many((\n ('huey', 'lives', 'Kansas'),\n ('zaizee', 'lives', 'Missouri'),\n ('nuggie', 'lives', 'Kansas'),\n ('mickey', 'lives', 'Kansas')))\n\n # We are now ready to search. We'll use a variable (X) to indicate\n # the value we're interested in.\n X = graph.v.X # Create a variable placeholder.\n\n # In the first clause we indicate we are searching for my friends.\n # In the second clause, we only want those friends who also live\n # in Kansas.\n results = graph.search(\n {'s': 'charlie', 'p': 'friends', 'o': X},\n {'s': X, 'p': 'lives', 'o': 'Kansas'})\n\n print(results)\n\n # Prints: {'X': {'huey', 'nuggie'}}\n\nIn the above example, the result value is a dictionary of variable values that satisfy the search expressions. The :py:meth:`~Graph.search` method is quite powerful!\n\nAn even simpler example\n^^^^^^^^^^^^^^^^^^^^^^^\n\nLet's say we wish only to retrieve a list of Charlie's friends. In this case we do not need to use a variable. We can use the simpler :py:meth:`~Graph.query` method. This method optionally takes a subject, predicate and/or object and, using the provided data, returns all objects that \"match\" the given pieces.\n\nSo to find Charlie's friends, we would write:\n\n.. code-block:: python\n\n query = graph.query(s='charlie', p='friends')\n for result in query:\n print(result['o']) # Print the object for the corresponding S/P.\n" }, { "alpha_fraction": 0.7643051743507385, "alphanum_fraction": 0.7643051743507385, "avg_line_length": 22.677419662475586, "blob_id": "f3be733d69458f95e0b2f2cf1979030ae332adbe", "content_id": "ec9f7c71459c6cb065b07c1ee8354dc064f72cfe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "permissive", "max_line_length": 52, "num_lines": 31, "path": "/walrus/tests/__init__.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import sys\nimport unittest\n\nfrom walrus.tests.autocomplete import *\nfrom walrus.tests.cache import *\nfrom walrus.tests.containers import *\nfrom walrus.tests.counter import *\nfrom walrus.tests.database import *\nfrom walrus.tests.fts import *\nfrom walrus.tests.graph import *\nfrom walrus.tests.lock import *\nfrom walrus.tests.models import *\nfrom walrus.tests.rate_limit import *\nfrom walrus.tests.streams import *\n\ntry:\n from walrus.tusks.ledisdb import TestWalrusLedis\nexcept ImportError:\n pass\ntry:\n from walrus.tusks.rlite import TestWalrusLite\nexcept ImportError:\n pass\ntry:\n from walrus.tusks.vedisdb import TestWalrusVedis\nexcept ImportError:\n pass\n\n\nif __name__ == '__main__':\n unittest.main(argv=sys.argv)\n" }, { "alpha_fraction": 0.4752790927886963, "alphanum_fraction": 0.5061137676239014, "avg_line_length": 29.09600067138672, "blob_id": "a8f75b5ec31d66e50ddfdfff00168a7124e020b4", "content_id": "ca96ba69e2aed7261797cfce85103bcbef7e09d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3762, "license_type": "permissive", "max_line_length": 69, "num_lines": 125, "path": "/walrus/tests/database.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from walrus.containers import *\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass TestWalrus(WalrusTestCase):\n def test_get_key(self):\n h = db.Hash('h1')\n h['hk1'] = 'v1'\n\n l = db.List('l1')\n l.append('i1')\n\n s = db.Set('s1')\n s.add('k1')\n\n zs = db.ZSet('z1')\n zs.add({'i1': 1., 'i2': 2.})\n\n h_db = db.get_key('h1')\n self.assertTrue(isinstance(h_db, Hash))\n self.assertEqual(h_db['hk1'], b'v1')\n\n l_db = db.get_key('l1')\n self.assertTrue(isinstance(l_db, List))\n self.assertEqual(l_db[0], b'i1')\n\n s_db = db.get_key('s1')\n self.assertTrue(isinstance(s_db, Set))\n self.assertEqual(s_db.members(), set((b'k1',)))\n\n z_db = db.get_key('z1')\n self.assertTrue(isinstance(z_db, ZSet))\n self.assertEqual(z_db.score('i1'), 1.)\n\n def test_atomic(self):\n def assertDepth(depth):\n self.assertEqual(len(db._transaction_local.pipes), depth)\n\n assertDepth(0)\n with db.atomic() as p1:\n assertDepth(1)\n with db.atomic() as p2:\n assertDepth(2)\n with db.atomic() as p3:\n assertDepth(3)\n p3.pipe.set('k3', 'v3')\n\n assertDepth(2)\n self.assertEqual(db['k3'], b'v3')\n\n p2.pipe.set('k2', 'v2')\n\n assertDepth(1)\n self.assertEqual(db['k3'], b'v3')\n self.assertEqual(db['k2'], b'v2')\n p1.pipe.set('k1', 'v1')\n\n assertDepth(0)\n self.assertEqual(db['k1'], b'v1')\n self.assertEqual(db['k2'], b'v2')\n self.assertEqual(db['k3'], b'v3')\n\n def test_atomic_exception(self):\n def do_atomic(k, v, exc=False):\n with db.atomic() as a:\n a.pipe.set(k, v)\n if exc:\n raise TypeError('foo')\n\n do_atomic('k', 'v')\n self.assertEqual(db['k'], b'v')\n\n self.assertRaises(TypeError, do_atomic, 'k2', 'v2', True)\n self.assertRaises(KeyError, lambda: db['k2'])\n self.assertEqual(db._transaction_local.pipe, None)\n\n # Try nested failure.\n with db.atomic() as outer:\n outer.pipe.set('k2', 'v2')\n self.assertRaises(TypeError, do_atomic, 'k3', 'v3', True)\n\n # Only this will be set.\n outer.pipe.set('k4', 'v4')\n\n self.assertTrue(db._transaction_local.pipe is None)\n self.assertEqual(db['k2'], b'v2')\n self.assertRaises(KeyError, lambda: db['k3'])\n self.assertEqual(db['k4'], b'v4')\n\n def test_clear_transaction(self):\n with db.atomic() as a1:\n a1.pipe.set('k1', 'v1')\n with db.atomic() as a2:\n a2.pipe.set('k2', 'v2')\n a2.clear()\n\n self.assertEqual(db['k1'], b'v1')\n self.assertRaises(KeyError, lambda: db['k2'])\n\n with db.atomic() as a1:\n a1.pipe.set('k3', 'v3')\n with db.atomic() as a2:\n self.assertRaises(KeyError, lambda: db['k3'])\n\n a2.pipe.set('k4', 'v4')\n a2.clear()\n\n a1.pipe.set('k5', 'v5')\n\n self.assertEqual(db['k3'], b'v3')\n self.assertRaises(KeyError, lambda: db['k4'])\n self.assertEqual(db['k5'], b'v5')\n\n self.assertTrue(db._transaction_local.pipe is None)\n\n def test_cas(self):\n db['k1'] = 'v1'\n self.assertTrue(db.cas('k1', 'v1', 'v1-x'))\n self.assertFalse(db.cas('k1', 'v1-z', 'v1-y'))\n\n self.assertEqual(db['k1'], b'v1-x')\n self.assertTrue(db.cas('k1', 'v1-', 'v2'))\n self.assertFalse(db.cas('k1', 'v1', 'v3'))\n self.assertEqual(db['k1'], b'v2')\n" }, { "alpha_fraction": 0.5821699500083923, "alphanum_fraction": 0.5843742489814758, "avg_line_length": 35.13274383544922, "blob_id": "c824fdcd49b4d082c637b0c3958376258ae8b448", "content_id": "b3aa28544b4b7cb39b6cbb88b920cf0a723da98e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4083, "license_type": "permissive", "max_line_length": 82, "num_lines": 113, "path": "/walrus/rate_limit.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import hashlib\nimport pickle\nimport time\nfrom functools import wraps\n\n\nclass RateLimitException(Exception):\n pass\n\n\nclass RateLimit(object):\n \"\"\"\n Rate limit implementation. Allows up to \"limit\" number of events every per\n the given number of seconds.\n \"\"\"\n def __init__(self, database, name, limit=5, per=60, debug=False):\n \"\"\"\n :param database: :py:class:`Database` instance.\n :param name: Namespace for this cache.\n :param int limit: Number of events allowed during a given time period.\n :param int per: Time period the ``limit`` applies to, in seconds.\n :param debug: Disable rate-limit for debugging purposes. All events\n will appear to be allowed and valid.\n \"\"\"\n self.database = database\n self.name = name\n self._limit = limit\n self._per = per\n self._debug = debug\n\n def limit(self, key):\n \"\"\"\n Function to log an event with the given key. If the ``key`` has not\n exceeded their allotted events, then the function returns ``False`` to\n indicate that no limit is being imposed.\n\n If the ``key`` has exceeded the number of events, then the function\n returns ``True`` indicating rate-limiting should occur.\n\n :param str key: A key identifying the source of the event.\n :returns: Boolean indicating whether the event should be rate-limited\n or not.\n \"\"\"\n if self._debug:\n return False\n\n counter = self.database.List(self.name + ':' + key)\n n = len(counter)\n is_limited = False\n if n < self._limit:\n counter.prepend(str(time.time()))\n else:\n oldest = counter[-1]\n if (oldest is not None) and (time.time() - float(oldest) < self._per):\n is_limited = True\n else:\n counter.prepend(str(time.time()))\n del counter[:self._limit]\n counter.pexpire(int(self._per * 2000))\n return is_limited\n\n def rate_limited(self, key_function=None):\n \"\"\"\n Function or method decorator that will prevent calls to the decorated\n function when the number of events has been exceeded for the given\n time period.\n\n It is probably important that you take care to choose an appropriate\n key function. For instance, if rate-limiting a web-page you might use\n the requesting user's IP as the key.\n\n If the number of allowed events has been exceeded, a\n ``RateLimitException`` will be raised.\n\n :param key_function: Function that accepts the params of the decorated\n function and returns a string key. If not provided, a hash of the\n args and kwargs will be used.\n :returns: If the call is not rate-limited, then the return value will\n be that of the decorated function.\n :raises: ``RateLimitException``.\n \"\"\"\n if key_function is None:\n def key_function(*args, **kwargs):\n data = pickle.dumps((args, sorted(kwargs.items())))\n return hashlib.md5(data).hexdigest()\n\n def decorator(fn):\n @wraps(fn)\n def inner(*args, **kwargs):\n key = key_function(*args, **kwargs)\n if self.limit(key):\n raise RateLimitException(\n 'Call to %s exceeded %s events in %s seconds.' % (\n fn.__name__, self._limit, self._per))\n return fn(*args, **kwargs)\n return inner\n return decorator\n\n\nclass RateLimitLua(RateLimit):\n \"\"\"\n Rate limit implementation. Allows up to \"limit\" number of events every per\n the given number of seconds. Uses a Lua script to ensure atomicity.\n \"\"\"\n def limit(self, key):\n if self._debug:\n return False\n\n key = self.name + ':' + key\n return bool(self.database.run_script(\n 'rate_limit',\n keys=[key],\n args=[self._limit, self._per, time.time()]))\n" }, { "alpha_fraction": 0.7611202597618103, "alphanum_fraction": 0.7667216062545776, "avg_line_length": 63.574466705322266, "blob_id": "3cfb1d222f905bac2bc8efb3dc564e4bcd6d4934", "content_id": "360cccfc64453be3b4d0ccf1a6e717cab9cc656c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3035, "license_type": "permissive", "max_line_length": 329, "num_lines": 47, "path": "/README.md", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "## Walrus\n\n![](http://media.charlesleifer.com/blog/photos/walrus-logo-0.png)\n\nLightweight Python utilities for working with [Redis](http://redis.io).\n\nThe purpose of [walrus](https://github.com/coleifer/walrus) is to make working\nwith Redis in Python a little easier. Rather than ask you to learn a new\nlibrary, walrus subclasses and extends the popular `redis-py` client, allowing\nit to be used as a drop-in replacement. In addition to all the features in\n`redis-py`, walrus adds support for some newer commands, including full support\nfor streams and consumer groups.\n\nwalrus consists of:\n\n* Pythonic container classes for the Redis data-types:\n * [Hash](https://walrus.readthedocs.io/en/latest/containers.html#hashes)\n * [List](https://walrus.readthedocs.io/en/latest/containers.html#lists)\n * [Set](https://walrus.readthedocs.io/en/latest/containers.html#sets)\n * [Sorted Set](https://walrus.readthedocs.io/en/latest/containers.html#sorted-sets-zset)\n * [HyperLogLog](https://walrus.readthedocs.io/en/latest/containers.html#hyperloglog)\n * [Array](https://walrus.readthedocs.io/en/latest/containers.html#arrays) (custom type)\n * [BitField](https://walrus.readthedocs.io/en/latest/containers.html#bitfield)\n * [BloomFilter](https://walrus.readthedocs.io/en/latest/containers.html#bloomfilter)\n * [**Streams**](https://walrus.readthedocs.io/en/latest/streams.html)\n* [Autocomplete](https://walrus.readthedocs.io/en/latest/autocomplete.html)\n* [Cache](https://walrus.readthedocs.io/en/latest/cache.html) implementation that exposes several decorators for caching function and method calls.\n* [Full-text search](https://walrus.readthedocs.io/en/latest/full-text-search.html) supporting set operations.\n* [Graph store](https://walrus.readthedocs.io/en/latest/graph.html)\n* [Rate-limiting](https://walrus.readthedocs.io/en/latest/rate-limit.html)\n* [Locking](https://walrus.readthedocs.io/en/latest/api.html#walrus.Lock)\n* **Experimental** active-record style [Models](https://walrus.readthedocs.io/en/latest/models.html) that support persisting structured information and performing complex queries using secondary indexes.\n* More? [More!](https://walrus.readthedocs.io)\n\n### Models\n\nPersistent structures implemented on top of Hashes. Supports secondary indexes to allow filtering on equality, inequality, ranges, less/greater-than, and a basic full-text search index. The full-text search features a boolean search query parser, porter stemmer, stop-word filtering, and optional double-metaphone implementation.\n\n### Found a bug?\n\n![](http://media.charlesleifer.com/blog/photos/p1420743625.21.png)\n\nPlease open a [github issue](https://github.com/coleifer/walrus/issues/new) and I will try my best to fix it!\n\n### Alternative Backends\n\nWalrus also can integrate with the Redis-like databases [rlite](https://github.com/seppo0010/rlite), [ledis](http://ledisdb.io/), and [vedis](http://vedis.symisc.net). Check the [documentation](https://walrus.readthedocs.io/en/latest/alt-backends.html) for more details.\n" }, { "alpha_fraction": 0.5842068195343018, "alphanum_fraction": 0.6020265817642212, "avg_line_length": 28.204082489013672, "blob_id": "8ecf578f492dd0112feace0d12703813a0ccd957", "content_id": "e2aa5106a9f4ffeeafda636345a55436c15a0e3a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2862, "license_type": "permissive", "max_line_length": 78, "num_lines": 98, "path": "/walrus/tests/rate_limit.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "import time\n\nfrom walrus.rate_limit import RateLimitException\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass TestRateLimit(WalrusTestCase):\n def setUp(self):\n super(TestRateLimit, self).setUp()\n # Limit to 5 events per second.\n self.rl = self.get_rate_limit('test-rl', 5, 1)\n\n def get_rate_limit(self, key, limit, per):\n return db.rate_limit(key, limit, per)\n\n def test_rate_limit(self):\n for i in range(5):\n self.assertFalse(self.rl.limit('k1'))\n\n for i in range(3):\n self.assertTrue(self.rl.limit('k1'))\n\n self.assertFalse(self.rl.limit('k2'))\n\n def test_rate_limit_rollover(self):\n rl = self.get_rate_limit('test-rl2', 3, 100)\n container = db.List('test-rl2:k1')\n\n now = time.time()\n past = now - 101\n\n # Simulate two events.\n container.extend([now, now])\n\n # Third event goes through OK.\n self.assertFalse(rl.limit('k1'))\n\n # Fourth event is rate-limited.\n self.assertTrue(rl.limit('k1'))\n\n # There are three timestamps in the container.\n self.assertEqual(len(container), 3)\n\n # Hand modify the oldest timestamp to appear as if it happened over\n # 100 seconds ago.\n container[-1] = past\n\n # We can again perform an action.\n self.assertFalse(rl.limit('k1'))\n\n # We once again have 3 items all within the last 100 seconds, so we\n # are rate-limited.\n self.assertTrue(rl.limit('k1'))\n\n # There are only 3 items in the container.\n self.assertEqual(len(container), 3)\n\n # The oldest item is the 2nd we added at the beginning of the test.\n self.assertEqual(float(container[-1]), now)\n\n # Remove an item and make the 2nd timestamp (oldest) in the past. This\n # gives us 2 actions.\n container.popright()\n container[-1] = past\n\n self.assertFalse(rl.limit('k1'))\n self.assertFalse(rl.limit('k1'))\n self.assertTrue(rl.limit('k1'))\n\n def test_decorator(self):\n rl = self.get_rate_limit('test-rl2', 3, 100)\n container = db.List('test-rl2:fake-key')\n\n def key_fn(*args, **kwargs):\n return 'fake-key'\n\n @rl.rate_limited(key_function=key_fn)\n def do_test():\n return 'OK'\n\n now = time.time()\n container.extend([now, now])\n\n self.assertEqual(do_test(), 'OK')\n self.assertRaises(RateLimitException, do_test)\n\n container.popright()\n container[-1] = now - 101\n\n self.assertEqual(do_test(), 'OK')\n self.assertEqual(do_test(), 'OK')\n self.assertRaises(RateLimitException, do_test)\n\n\nclass TestRateLimitLua(TestRateLimit):\n def get_rate_limit(self, key, limit, per):\n return db.rate_limit_lua(key, limit, per)\n" }, { "alpha_fraction": 0.6011049747467041, "alphanum_fraction": 0.6035358905792236, "avg_line_length": 32.51852035522461, "blob_id": "dc47e0c0b42f10d294ad83f546464e083bcfad86", "content_id": "047c02501a0d17bc3a9dbe256520db0e4e572607", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4525, "license_type": "permissive", "max_line_length": 72, "num_lines": 135, "path": "/walrus/lock.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "from functools import wraps\nimport os\n\n\nclass Lock(object):\n \"\"\"\n Lock implementation. Can also be used as a context-manager or\n decorator.\n\n Unlike the redis-py lock implementation, this Lock does not\n use a spin-loop when blocking to acquire the lock. Instead,\n it performs a blocking pop on a list. When a lock is released,\n a value is pushed into this list, signalling that the lock is\n available.\n\n .. warning::\n The event list for each lock persists\n indefinitely unless removed using :py:meth:`Lock.clear` or\n otherwise manually in the Redis database. For this reason,\n be cautious when creating locks dynamically, or your\n keyspace might grow in an unbounded way.\n\n The lock uses Lua scripts to ensure the atomicity of its\n operations.\n\n You can set a TTL on a lock to reduce the potential for deadlocks\n in the event of a crash. If a lock is not released before it\n exceeds its TTL, and threads that are blocked waiting for the\n lock could potentially re-acquire it.\n\n .. note:: TTL is specified in **milliseconds**.\n\n Locks can be used as context managers or as decorators:\n\n .. code-block:: python\n\n lock = db.lock('my-lock')\n\n with lock:\n perform_some_calculations()\n\n @lock\n def another_function():\n # The lock will be acquired when this function is\n # called, and released when the function returns.\n do_some_more_calculations()\n \"\"\"\n def __init__(self, database, name, ttl=None, lock_id=None):\n \"\"\"\n :param database: A walrus ``Database`` instance.\n :param str name: The name for the lock.\n :param int ttl: The time-to-live for the lock in milliseconds.\n :param str lock_id: Unique identifier for the lock instance.\n \"\"\"\n self.database = database\n self.name = name\n self.ttl = ttl or 0\n self._lock_id = lock_id or os.urandom(32)\n\n @property\n def key(self):\n return 'lock:%s' % (self.name)\n\n @property\n def event(self):\n return 'lock.event:%s' % (self.name)\n\n def acquire(self, block=True):\n \"\"\"\n Acquire the lock. The lock will be held until it is released\n by calling :py:meth:`Lock.release`. If the lock was\n initialized with a ``ttl``, then the lock will be released\n automatically after the given number of milliseconds.\n\n By default this method will block until the lock becomes\n free (either by being released or expiring). The blocking is\n accomplished by performing a blocking left-pop on a list, as\n opposed to a spin-loop.\n\n If you specify ``block=False``, then the method will return\n ``False`` if the lock could not be acquired.\n\n :param bool block: Whether to block while waiting to acquire\n the lock.\n :returns: Returns ``True`` if the lock was acquired.\n \"\"\"\n event_wait = self.ttl // 1000 if self.ttl else 1\n\n while True:\n acquired = self.database.run_script(\n 'lock_acquire',\n keys=[self.key],\n args=[self._lock_id, self.ttl])\n if acquired == 1 or not block:\n return acquired == 1\n\n # Perform a blocking pop on the event key. When a lock\n # is released, a value is pushed into the list, which\n # signals listeners that the lock is available.\n self.database.blpop(self.event, event_wait)\n\n def release(self):\n \"\"\"\n Release the lock.\n\n :returns: Returns ``True`` if the lock was released.\n \"\"\"\n unlocked = self.database.run_script(\n 'lock_release',\n keys=[self.key, self.event],\n args=[self._lock_id])\n return unlocked != 0\n\n def clear(self):\n \"\"\"\n Clear the lock, allowing it to be acquired. Do not use this\n method except to recover from a deadlock. Otherwise you should\n use :py:meth:`Lock.release`.\n \"\"\"\n self.database.delete(self.key)\n self.database.delete(self.event)\n\n def __enter__(self):\n self.acquire()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if not self.release():\n raise RuntimeError('Error releasing lock \"%s\".' % self.name)\n\n def __call__(self, fn):\n @wraps(fn)\n def inner(*args, **kwargs):\n with self:\n return fn(*args, **kwargs)\n return inner\n" }, { "alpha_fraction": 0.5272125601768494, "alphanum_fraction": 0.5308519601821899, "avg_line_length": 35.4156608581543, "blob_id": "12673aabab9fd50d2c6a041f6b6d319002b8d311", "content_id": "aa7cedad9589485651c392f4afa3b372885f5f0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6144, "license_type": "permissive", "max_line_length": 78, "num_lines": 166, "path": "/walrus/tests/fts.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "#coding:utf-8\nfrom walrus.tests.base import WalrusTestCase\nfrom walrus.tests.base import db\n\n\nclass TestSearchIndex(WalrusTestCase):\n def test_search_index(self):\n phrases = [\n ('A faith is a necessity to a man. Woe to him who believes in '\n 'nothing.'),\n ('All who call on God in true faith, earnestly from the heart, '\n 'will certainly be heard, and will receive what they have asked '\n 'and desired.'),\n ('Be faithful in small things because it is in them that your '\n 'strength lies.'),\n ('Faith consists in believing when it is beyond the power of '\n 'reason to believe.'),\n ('Faith has to do with things that are not seen and hope with '\n 'things that are not at hand.')]\n\n index = db.Index('test-index')\n\n for idx, message in enumerate(phrases):\n index.add('doc-%s' % idx, message)\n\n def assertDocs(query, indexes):\n results = [doc['content'] for doc in index.search(query)]\n self.assertEqual(results, [phrases[i] for i in indexes])\n\n assertDocs('faith', [0, 2, 3, 4, 1])\n assertDocs('faith man', [0])\n assertDocs('things', [4, 2])\n assertDocs('blah', [])\n\n def test_add_remove_update(self):\n data = [\n ('huey cat', {'type': 'cat', 'color': 'white'}),\n ('zaizee cat cat', {'type': 'cat', 'color': 'gray'}),\n ('mickey dog', {'type': 'dog', 'color': 'black'}),\n ('beanie cat', {'type': 'cat', 'color': 'gray'}),\n ]\n\n idx = db.Index('test-index')\n for i, (content, metadata) in enumerate(data):\n idx.add(str(i), content, **metadata)\n\n huey, = idx.search('huey')\n self.assertEqual(huey, {\n 'content': 'huey cat',\n 'type': 'cat',\n 'color': 'white'})\n\n self.assertEqual([d['content'] for d in idx.search('cat')],\n ['zaizee cat cat', 'huey cat', 'beanie cat'])\n\n idx.remove('3') # Poor beanie :(\n zaizee, huey = idx.search('cat')\n self.assertEqual(zaizee['content'], 'zaizee cat cat')\n self.assertEqual(huey['content'], 'huey cat')\n\n self.assertRaises(KeyError, idx.remove, '3')\n\n idx.update('1', 'zaizee cat', {'type': 'kitten'})\n idx.replace('0', 'huey baby cat', {'type': 'kitten'})\n\n zaizee, huey = idx.search('cat')\n self.assertEqual(zaizee['content'], 'zaizee cat')\n self.assertEqual(zaizee['type'], 'kitten')\n self.assertEqual(zaizee['color'], 'gray')\n\n self.assertEqual(huey['content'], 'huey baby cat')\n self.assertEqual(huey['type'], 'kitten')\n self.assertTrue('color' not in huey)\n\n zaizee, huey = idx.search_items('cat')\n self.assertEqual(zaizee[0], '1')\n self.assertEqual(zaizee[1]['content'], 'zaizee cat')\n self.assertEqual(huey[0], '0')\n self.assertEqual(huey[1]['content'], 'huey baby cat')\n\n def test_search_phonetic(self):\n data = (\n ('pf', 'python and flask'),\n ('lcp', 'learning cython programming'),\n ('lwd', 'learning web development with flask'),\n ('pwd', 'python web development'))\n data_dict = dict(data)\n idx = db.Index('test-index', metaphone=True)\n for key, content in data:\n idx.add(key, content)\n\n def assertResults(query, keys):\n result = idx.search(query)\n self.assertEqual([doc['content'] for doc in result],\n [data_dict[key] for key in keys])\n\n assertResults('flasck', ['pf', 'lwd'])\n assertResults('pythonn', ['pf', 'pwd'])\n assertResults('sithon', ['lcp'])\n assertResults('webb development', ['pwd', 'lwd'])\n\n assertResults('sithon OR (flasck AND pythonn)', ['pf', 'lcp'])\n assertResults('garbage', [])\n\n def test_search_parser(self):\n messages = [\n 'foo green',\n 'bar green',\n 'baz blue',\n 'nug blue',\n 'nize yellow',\n 'huey greener',\n 'mickey greens',\n 'zaizee',\n ]\n index = db.Index('testing')\n\n for idx, message in enumerate(messages):\n index.add(str(idx), message)\n\n def assertMatches(query, expected):\n results = [doc['content'] for doc in index.search(query)]\n self.assertEqual(results, expected)\n\n assertMatches('foo', ['foo green'])\n assertMatches('foo OR baz', ['foo green', 'baz blue'])\n assertMatches('green OR blue', [\n 'foo green',\n 'bar green',\n 'baz blue',\n 'nug blue',\n 'mickey greens',\n ])\n\n assertMatches('green AND (bar OR mickey OR nize)', [\n 'bar green',\n 'mickey greens',\n ])\n assertMatches('zaizee OR (blue AND nug) OR (green AND bar)', [\n 'bar green',\n 'nug blue',\n 'zaizee',\n ])\n assertMatches('(blue AND (baz OR (nug OR huey OR mickey))', [\n 'baz blue',\n 'nug blue',\n ])\n assertMatches(\n '(blue OR foo) AND (green OR (huey OR (baz AND mickey)))',\n ['foo green'])\n\n assertMatches('(green AND nug) OR (blue AND bar)', [])\n assertMatches('nuglet', [])\n assertMatches('foobar', [])\n assertMatches('foo\"bar green', ['foo green'])\n\n results = [doc['content'] for doc in index.search('')]\n self.assertEqual(sorted(results), sorted(messages))\n\n def test_unicode_handling(self):\n index = db.Index('testing', stemmer=False)\n index.add('1', u'сколько лет этому безумному моржу', {'val': 'age'})\n index.add('2', u'во сколько морж ложится спать', val='sleep')\n index.add('3', u'Вы знаете какие-нибудь хорошие истории с моржами',\n val='stories')\n self.assertEqual([r['val'] for r in index.search(u'морж')], ['sleep'])\n" }, { "alpha_fraction": 0.7163329720497131, "alphanum_fraction": 0.7412012815475464, "avg_line_length": 39.905174255371094, "blob_id": "07bf7e6b398d20fff68cae8c6f05f931d88bf6c8", "content_id": "80ec2c0b7b7f02488adfaf99019bd116c916950c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4745, "license_type": "permissive", "max_line_length": 161, "num_lines": 116, "path": "/CHANGELOG.md", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "## Changelog\n\nThis document describes changes to the APIs.\n\n### master\n\n[View changes](https://github.com/coleifer/walrus/compare/0.9.2...HEAD)\n\n### 0.9.2\n\n* Upstream decided to play around with XPENDING again.\n\n[View changes](https://github.com/coleifer/walrus/compare/0.9.1...0.9.2)\n\n### 0.9.1\n\n* Add support for `minid` and `limit` parameters on `Stream.trim()`, #169\n* Cache decorators now cache calls that return `None`, #171\n\n[View changes](https://github.com/coleifer/walrus/compare/0.9.0...0.9.1)\n\n### 0.9.0\n\n* **Backwards incompatible change:** redis-py changed the signature of the\n `xpending_range` function. This is resolved in walrus 0.9.0.\n* Add support for `autoclaim()` to the `ConsumerGroupStream` class.\n* Minor changes to the stop-word handling in `autocomplete` module.\n\n[View changes](https://github.com/coleifer/walrus/compare/0.8.2...0.9.0)\n\n### 0.8.2\n\n* Use `HSET` instead of `HMSET`.\n* Add a `search_items()` method to the full-text index which returns a 2-tuple\n of `(key, doc)`.\n* Add a timeout parameter to `bmove_tail` and `brpoplpush` wrappers.\n* Allow disabling lua script-loading for faster initialization (for\n applications that do not intend to utilize these features).\n\n[View changes](https://github.com/coleifer/walrus/compare/0.8.1...0.8.2)\n\n### 0.8.1\n\n* Fix missing parameter in error message, #105.\n* Remove redundant call to `delete()` when using Model `create()` API.\n* Fix TTL units and lock event wait timeout handling.\n* Adds `Hash.setnx()` method to the hash container.\n* Do not double-decode strings when user has enabled decode_responses, #121.\n* Fix mapping of types in `get_key()` method to return the proper container\n type, #120.\n\n[View all changes](https://github.com/coleifer/walrus/compare/0.8.0...0.8.1)\n\n### 0.8.0\n\n* Adds efficient bulk get, set and delete methods to the `Cache` class.\n* Fixes `repr` issues with some of the container types.\n* Fixed an inefficiency in the implementation of the `Graph` storage that\n cuts the amount of memory needed in half.\n* Fixed issues with unicode handling in the full-text search implementation.\n\n[View all changes](https://github.com/coleifer/walrus/compare/0.7.0...0.8.0)\n\n### 0.7.0\n\nDepends on [redis-py](https://github.com/andymccurdy/redis-py) 3.0 or newer.\nThere are a number of backwards-incompatible changes in redis-py. Because\nwalrus provides high-level abstractions for the Redis data-types/commands, your\nwalrus code should work with little or no modifications. Refer to the [list of changes](https://github.com/andymccurdy/redis-py#upgrading-from-redis-py-2x-to-30)\nfor more information.\n\n[redis-py](https://github.com/andymccurdy/redis-py) added support for stream\ncommands as well as zpop/bzpop. As a result, walrus no longer contains separate\nimplementations for these commands. For the majority of cases the low-level\nmethod signatures and return values are unchanged, notably, the `XREADGROUP`\nreturn value is slightly different. The `timeout` parameter, where it was\naccepted, has been renamed to `block` for greater compatibility with redis-py.\n\nPrior to 0.7.0, you would read from a consumer-group (which might contain one\nor more streams) and receive a `dict` keyed by the stream, whose value was a\nlist of `(message_id, data)` 2-tuples. Going forward, the return value will be\na list of `[stream_name, [(message_id, data), ...]]`. To retain the\nfunctionality of walrus prior-to 0.7.0, just wrap the return value in a call to\nthe `dict` constructor: `ret = dict(consumer_group.read(count=1))`.\n\n* Added [BloomFilter](https://walrus.readthedocs.io/en/latest/api.html#walrus.Database.bloom_filter)\n container type, which supports `add()` and `contains()`.\n* Added a high-level [BitField](https://walrus.readthedocs.io/en/latest/api.html#walrus.BitField)\n container type.\n\n[View all changes](https://github.com/coleifer/walrus/compare/0.6.4...0.7.0)\n\n### 0.6.0\n\n* Stream support added, including consumer groups.\n* Support for `zpopmin`, `zpopmax`, and the blocking `bzpopmin`, `bzpopmax`\n* Added APIs to container classes for converting to-and-from native data-types.\n* Added atomic compare-and-set method to database.\n\n### 0.5.2\n\n* Fixed incompatibilities with Python 3.7.\n* Fixed incorrect result scoring in full-text search model.\n\n### 0.5.1\n\n* Added standalone [full-text search](https://walrus.readthedocs.io/en/latest/full-text-search.html).\n* Refactored various internal classes that support the new standalone full-text\n search index.\n\n### 0.5.0\n\n* The `models` API uses a backwards-incompatible serialization approach. This\n means that data stored using 0.4.1 cannot be read back using 0.5.0.\n* `Field()` no longer supports `pickled` or `as_json` parameters. Instead, use\n the `PickledField` and `JSONField`.\n" }, { "alpha_fraction": 0.6309962868690491, "alphanum_fraction": 0.6568265557289124, "avg_line_length": 26.100000381469727, "blob_id": "758ee2fc57c84a93a25cd712f592a1b4898d6c03", "content_id": "de506234d8bd9003561b637ec46d26be78bc893d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 271, "license_type": "permissive", "max_line_length": 70, "num_lines": 10, "path": "/walrus/scripts/lock_release.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal event_key = KEYS[2]\nlocal lock_id = ARGV[1]\nif redis.call(\"get\", key) == lock_id then\n redis.call(\"lpush\", event_key, 1)\n redis.call(\"ltrim\", event_key, 0, 0) -- Trim all but the first item.\n return redis.call(\"del\", key)\nelse\n return 0\nend\n" }, { "alpha_fraction": 0.571890115737915, "alphanum_fraction": 0.5745826363563538, "avg_line_length": 25.154930114746094, "blob_id": "27db9f6bd747d62a82db4051a5496573e80b9f7b", "content_id": "ab4e9d05b606badb29d406453ab95bd9f190dc6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1857, "license_type": "permissive", "max_line_length": 72, "num_lines": 71, "path": "/examples/diary.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom collections import OrderedDict\nimport datetime\nimport sys\n\nfrom walrus import *\n\ndatabase = Database(host='localhost', port=6379, db=0)\n\nclass Entry(Model):\n __database__ = database\n __namespace__ = 'diary'\n\n content = TextField(fts=True)\n timestamp = DateTimeField(default=datetime.datetime.now, index=True)\n\n\ndef menu_loop():\n choice = None\n while choice != 'q':\n for key, value in menu.items():\n print('%s) %s' % (key, value.__doc__))\n choice = raw_input('Action: ').lower().strip()\n if choice in menu:\n menu[choice]()\n\ndef add_entry():\n \"\"\"Add entry\"\"\"\n print('Enter your entry. Press ctrl+d when finished.')\n data = sys.stdin.read().strip()\n if data and raw_input('Save entry? [Yn] ') != 'n':\n Entry.create(content=data)\n print('Saved successfully.')\n\ndef view_entries(search_query=None):\n \"\"\"View previous entries\"\"\"\n if search_query:\n expr = Entry.content.search(search_query)\n else:\n expr = None\n\n query = Entry.query(expr, order_by=Entry.timestamp.desc())\n for entry in query:\n timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p')\n print(timestamp)\n print('=' * len(timestamp))\n print(entry.content)\n print('n) next entry')\n print('d) delete entry')\n print('q) return to main menu')\n choice = raw_input('Choice? (Ndq) ').lower().strip()\n if choice == 'q':\n break\n elif choice == 'd':\n entry.delete()\n print('Entry deleted successfully.')\n break\n\ndef search_entries():\n \"\"\"Search entries\"\"\"\n view_entries(raw_input('Search query: '))\n\nmenu = OrderedDict([\n ('a', add_entry),\n ('v', view_entries),\n ('s', search_entries),\n])\n\nif __name__ == '__main__':\n menu_loop()\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6402116417884827, "avg_line_length": 22.625, "blob_id": "3b0c414af40fb7b77eeae558ef804d5ca844899d", "content_id": "3718b3d5494c0d1e8ac47df8e4bd51b3de4f7109", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 189, "license_type": "permissive", "max_line_length": 54, "num_lines": 8, "path": "/walrus/scripts/array_extend.lua", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "local key = KEYS[1]\nlocal nargs = #ARGV\nlocal offset = redis.call('HLEN', key)\nlocal idx = 0\nwhile idx < nargs do\n redis.call('HSET', key, idx + offset, ARGV[idx + 1])\n idx = idx + 1\nend\n" }, { "alpha_fraction": 0.6270926594734192, "alphanum_fraction": 0.645803689956665, "avg_line_length": 30.5137939453125, "blob_id": "e0f5bb9ce8becbc3b262d2b4064c4530b0e8aaa7", "content_id": "9b1ce7bca27a7d185ab06164d9fa00df8be2290d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 9139, "license_type": "permissive", "max_line_length": 302, "num_lines": 290, "path": "/docs/models.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _models:\n\n.. py:module:: walrus\n\nModels\n======\n\n.. warning::\n Walrus models should **not** be considered production-grade code and I\n strongly advise against anyone actually using it for anything other than\n experimenting or for inspiration/learning.\n\n My advice: just use hashes for your structured data. If you need ad-hoc\n queries, then use a relational database.\n\nWalrus provides a lightweight :py:class:`Model` class for storing structured data and executing queries using secondary indexes.\n\n.. code-block:: pycon\n\n >>> from walrus import *\n >>> db = Database()\n\nLet's create a simple data model to store some users.\n\n.. code-block:: pycon\n\n >>> class User(Model):\n ... __database__ = db\n ... name = TextField(primary_key=True)\n ... dob = DateField(index=True)\n\n.. note::\n As of 0.4.0, the ``Model.database`` attribute has been renamed to\n ``Model.__database__``. Similarly, ``Model.namespace`` is now\n ``Model.__namespace__``.\n\nCreating, Updating and Deleting\n-------------------------------\n\nTo add objects to a collection, you can use :py:meth:`Model.create`:\n\n.. code-block:: pycon\n\n >>> User.create(name='Charlie', dob=datetime.date(1983, 1, 1))\n <User: Charlie>\n\n >>> names_dobs = [\n ... ('Huey', datetime.date(2011, 6, 1)),\n ... ('Zaizee', datetime.date(2012, 5, 1)),\n ... ('Mickey', datetime.date(2007, 8, 1)),\n\n >>> for name, dob in names_dobs:\n ... User.create(name=name, dob=dob)\n\nWe can retrieve objects by primary key (name in this case). Objects can be modified or deleted after they have been created.\n\n.. code-block:: pycon\n\n >>> zaizee = User.load('Zaizee') # Get object by primary key.\n >>> zaizee.name\n 'Zaizee'\n >>> zaizee.dob\n datetime.date(2012, 5, 1)\n\n >>> zaizee.dob = datetime.date(2012, 4, 1)\n >>> zaizee.save()\n\n >>> nobody = User.create(name='nobody', dob=datetime.date(1990, 1, 1))\n >>> nobody.delete()\n\nRetrieving all records in a collection\n--------------------------------------\n\nWe can retrieve all objects in the collection by calling :py:meth:`Model.all`, which returns an iterator that successively yields model instances:\n\n.. code-block:: pycon\n\n >>> for user in User.all():\n ... print(user.name)\n Huey\n Zaizee\n Charlie\n Mickey\n\n.. note:: The objects from :py:meth:`~Model.all` are returned in an undefined order. This is because the index containing all primary keys is implemented as an unordered :py:class:`Set`.\n\nSorting records\n---------------\n\nTo get the objects in order, we can use :py:meth:`Model.query`:\n\n.. code-block:: pycon\n\n >>> for user in User.query(order_by=User.name):\n ... print(user.name)\n Charlie\n Huey\n Mickey\n Zaizee\n\n >>> for user in User.query(order_by=User.dob.desc()):\n ... print(user.dob)\n 2012-04-01\n 2011-06-01\n 2007-08-01\n 1983-01-01\n\nFiltering records\n-----------------\n\nWalrus supports basic filtering. The filtering options available vary by field type, so that :py:class:`TextField`, :py:class:`UUIDField` and similar non-scalar types support only equality and inequality tests. Scalar values, on the other hand, like integers, floats or dates, support range operations.\n\n.. warning:: You must specify ``index=True`` to be able to use a field for filtering.\n\nLet's see how this works by filtering on name and dob. The :py:meth:`~Model.query` method returns zero or more objects, while the :py:meth:`~Model.get` method requires that there be exactly one result:\n\n.. code-block:: pycon\n\n >>> for user in User.query(User.dob <= datetime.date(2009, 1, 1)):\n ... print(user.dob)\n 2007-08-01\n 1983-01-01\n\n >>> charlie = User.get(User.name == 'Charlie')\n >>> User.get(User.name = 'missing')\n Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/home/charles/pypath/walrus.py\", line 1662, in get\n raise ValueError('Got %s results, expected 1.' % len(result))\n ValueError: Got 0 results, expected 1.\n\nWe can combine multiple filters using bitwise *and* and *or*:\n\n.. code-block:: pycon\n\n >>> low = datetime.date(2006, 1, 1)\n >>> high = datetime.date(2012, 1, 1)\n >>> query = User.query(\n ... (User.dob >= low) &\n ... (User.dob <= high))\n\n >>> for user in query:\n ... print(user.dob)\n\n 2011-06-01\n 2007-08-01\n\n >>> query = User.query(User.dob.between(low, high)) # Equivalent to above.\n >>> for user in query:\n ... print(user.dob)\n\n 2011-06-01\n 2007-08-01\n\n >>> query = User.query(\n ... (User.dob <= low) |\n ... (User.dob >= high))\n\n >>> for user in query:\n ... print(user.dob)\n 2012-04-01\n 1983-01-01\n\nYou can combine filters with ordering:\n\n.. code-block:: pycon\n\n >>> expr = (User.name == 'Charlie') | (User.name == 'Zaizee')\n >>> for user in User.query(expr, order_by=User.name):\n ... print(user.name)\n Charlie\n Zaizee\n\n >>> for user in User.query(User.name != 'Charlie', order_by=User.name.desc()):\n ... print(user.name)\n Zaizee\n Mickey\n Huey\n\n.. _container-fields:\n\nContainer Fields\n----------------\n\nUp until now the fields we've used have been simple key/value pairs that are stored directly in the hash of model data. In this section we'll look at a group of special fields that correspond to Redis container types.\n\nLet's create a model for storing personal notes. The notes will have a text field for the content and a timestamp, and as an interesting flourish we'll add a :py:class:`SetField` to store a collection of tags.\n\n.. code-block:: python\n\n class Note(Model):\n __database__ = db\n text = TextField()\n timestamp = DateTimeField(\n default=datetime.datetime.now,\n index=True)\n tags = SetField()\n\n.. note:: Container fields cannot be used as a secondary index, nor can they be used as the primary key for a model. Finally, they do not accept a default value.\n\n.. warning:: Due to the implementation, it is necessary that the model instance have a primary key value before you can access the container field. This is because the key identifying the container field needs to be associated with the instance, and the way we do that is with the primary key.\n\nHere is how we might use the new note model:\n\n.. code-block:: pycon\n\n >>> note = Note.create(content='my first note')\n >>> note.tags\n <Set \"note:container.tags.note:id.3\": 0 items>\n >>> note.tags.add('testing', 'walrus')\n\n >>> Note.load(note._id).tags\n <Set \"note:container.tags.note:id.3\": 0 items>\n\nIn addition to :py:class:`SetField`, there is also :py:class:`HashField`, :py:class:`ListField`, :py:class:`ZSetField`.\n\n\n.. _fts:\n\nFull-text search\n----------------\n\nI've added a really (really) simple full-text search index type. Here is how to use it:\n\n.. code-block:: pycon\n\n >>> class Note(Model):\n ... __database__ = db\n ... content = TextField(fts=True) # Note the \"fts=True\".\n\nWhen a field contains an full-text index, then the index will be populated when new objects are added to the database:\n\n.. code-block:: pycon\n\n >>> Note.create(content='this is a test of walrus FTS.')\n >>> Note.create(content='favorite food is walrus-mix.')\n >>> Note.create(content='do not forget to take the walrus for a walk.')\n\nUse :py:meth:`TextField.search` to create a search expression, which is then passed to the :py:meth:`Model.query` method:\n\n.. code-block:: pycon\n\n >>> for note in Note.query(Note.content.search('walrus')):\n ... print(note.content)\n do not forget to take the walrus for a walk.\n this is a test of walrus FTS.\n favorite food is walrus-mix.\n\n >>> for note in Note.query(Note.content.search('walk walrus')):\n ... print(note.content)\n do not forget to take the walrus for a walk.\n\n >>> for note in Note.query(Note.content.search('walrus mix')):\n ... print(note.content)\n favorite food is walrus-mix.\n\nWe can also specify complex queries using ``AND`` and ``OR`` conjunctions:\n\n.. code-block:: pycon\n\n >>> for note in Note.query(Note.content.search('walrus AND (mix OR fts)')):\n ... print(note.content)\n this is a test of walrus FTS.\n favorite food is walrus-mix.\n\n >>> query = '(test OR food OR walk) AND walrus AND (favorite OR forget)'\n >>> for note in Note.query(Note.content.search(query)):\n ... print(note.content)\n do not forget to take the walrus for a walk.\n favorite food is walrus-mix.\n\nFeatures\n^^^^^^^^\n\n* Automatic removal of stop-words\n* Porter stemmer on by default\n* Optional double-metaphone implementation\n* Default conjunction is *AND*, but there is also support for *OR*.\n\nLimitations\n^^^^^^^^^^^\n\n* Partial strings are not matched.\n* Very naive scoring function.\n* Quoted multi-word matches do not work.\n\nNeed more power?\n----------------\n\nwalrus' querying capabilities are extremely basic. If you want more sophisticated querying, check out `StdNet <https://github.com/lsbardel/python-stdnet>`_. StdNet makes extensive use of Lua scripts to provide some really neat querying/filtering options.\n" }, { "alpha_fraction": 0.6420461535453796, "alphanum_fraction": 0.6445559859275818, "avg_line_length": 29.988889694213867, "blob_id": "0c28488aa630110db2dda6a33451222d995ed4e6", "content_id": "1b32aad0973d5c62513787d3b7b5e72ae154bf43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 8367, "license_type": "permissive", "max_line_length": 390, "num_lines": 270, "path": "/docs/autocomplete.rst", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": ".. _autocomplete:\n\n.. py:module:: walrus\n\nAutocomplete\n============\n\nProvide suggestions based on partial string search. Walrus' autocomplete library is based on the implementation from `redis-completion <https://github.com/coleifer/redis-completion>`_.\n\n.. note:: The walrus implementation of autocomplete relies on the ``HSCAN`` command and therefore requires Redis >= 2.8.0.\n\nOverview\n--------\n\nThe :py:class:`Autocomplete` engine works by storing substrings and mapping them to user-defined data.\n\nFeatures\n\n* Perform searches using partial words or phrases.\n* Store rich metadata along with substrings.\n* Boosting.\n\nSimple example\n--------------\n\nWalrus :py:class:`Autocomplete` can be used to index words and phrases, and then make suggestions based on user searches.\n\nTo begin, call :py:meth:`Database.autocomplete` to create an instance of the autocomplete index.\n\n.. code-block:: pycon\n\n >>> database = Database()\n >>> ac = database.autocomplete()\n\nPhrases can be stored by calling :py:meth:`Autocomplete.store`:\n\n.. code-block:: pycon\n\n >>> phrases = [\n ... 'the walrus and the carpenter',\n ... 'walrus tusks',\n ... 'the eye of the walrus']\n\n >>> for phrase in phrases:\n ... ac.store(phrase)\n\nTo search for results, use :py:meth:`Autocomplete.search`.\n\n.. code-block:: pycon\n\n >>> ac.search('wal')\n ['the walrus and the carpenter',\n 'walrus tusks',\n 'the eye of the walrus']\n\n >>> ac.search('wal car')\n ['the walrus and the carpenter']\n\nTo boost a result, we can specify one or more *boosts* when searching:\n\n.. code-block:: pycon\n\n >>> ac.search('wal', boosts={'walrus tusks': 2})\n ['walrus tusks',\n 'the walrus and the carpenter',\n 'the eye of the walrus']\n\nTo remove a phrase from the index, use :py:meth:`Autocomplete.remove`:\n\n.. code-block:: pycon\n\n >>> ac.remove('walrus tusks')\n\nWe can also check for the existence of a phrase in the index using :py:meth:`Autocomplete.exists`:\n\n.. code-block:: pycon\n\n >>> ac.exists('the walrus and the carpenter')\n True\n\n >>> ac.exists('walrus tusks')\n False\n\nComplete example\n----------------\n\nWhile walrus can work with just simple words and phrases, the :py:class:`Autocomplete` index was really developed to be able to provide meaningful typeahead suggestions for sites containing rich content. To this end, the autocomplete search allows you to store arbitrary metadata in the index, which will then be returned when a search is performed.\n\n.. code-block:: pycon\n\n >>> database = Database()\n >>> ac = database.autocomplete()\n\nSuppose we have a blog site and wish to add search for the entries. We'll use the blog entry's title for the search, and return, along with title, a thumbnail image and a link to the entry's detail page. That way when we display results we have all the information we need to display a nice-looking link:\n\n.. code-block:: pycon\n\n >>> for blog_entry in Entry.select():\n ... metadata = {\n ... 'image': blog_entry.get_primary_thumbnail(),\n ... 'title': blog_entry.title,\n ... 'url': url_for('entry_detail', entry_id=blog_entry.id)}\n ...\n ... ac.store(\n ... obj_id=blog_entry.id,\n ... title=blog_entry.title,\n ... data=metadata,\n ... obj_type='entry')\n\nWhen we search we receive the metadata that was stored in the index:\n\n.. code-block:: pycon\n\n >>> ac.search('walrus')\n [{'image': '/images/walrus-logo.jpg',\n 'title': 'Walrus: Lightweight Python utilities for working with Redis',\n 'url': '/blog/walrus-lightweight-python-utilities-for-working-with-redis/'},\n {'image': '/images/walrus-tusk.jpg',\n 'title': 'Building Autocomplete with Walrus',\n 'url': '/blog/building-autocomplete-with-redis/'}]\n\nWhenever an entry is created or updated, we will want to update the index. By keying off the entry's primary key and object type (*'entry'*), walrus will handle this correctly:\n\n.. code-block:: python\n\n def save_entry(entry):\n entry.save_to_db() # Save entry to relational database, etc.\n\n ac.store(\n obj_id=entry.id,\n title=entry.title,\n data={\n 'image': entry.get_primary_thumbnail(),\n 'title': entry.title,\n 'url': url_for('entry_detail', entry_id=entry.id)},\n obj_type='entry')\n\nSuppose we have a very popular blog entry that is frequently searched for. We can *boost* that entry's score by calling :py:meth:`~Autocomplete.boost_object`:\n\n.. code-block:: pycon\n\n >>> popular_entry = Entry.get(Entry.title == 'Some popular entry')\n >>> ac.boost_object(\n ... obj_id=popular_entry.id,\n ... obj_type='entry',\n ... multiplier=2.0)\n\nTo perform boosts on a one-off basis while searching, we can specify a dictionary mapping object IDs or types to a particular multiplier:\n\n.. code-block:: pycon\n\n >>> ac.search(\n ... 'some phrase',\n ... boosts={popular_entry.id: 2.0, unpopular_entry.id, 0.5})\n ...\n [ list of matching entry's metadata ]\n\nTo remove an entry from the index, we just need to specify the object's id and type:\n\n.. code-block:: python\n\n def delete_entry(entry):\n entry.delete_from_db() # Remove from relational database, etc.\n\n ac.remove(\n obj_id=entry.id,\n obj_type='entry')\n\nWe can also check whether an entry exists in the index:\n\n.. code-block:: pycon\n\n >>> entry = Entry.get(Entry.title == 'Building Autocomplete with Walrus')\n >>> ac.exists(entry.id, 'entry')\n True\n\nScoring\n-------\n\nWalrus implements a scoring algorithm that considers the words and also their position relative to the entire phrase. Let's look at some simple searches. We'll index the following strings:\n\n* ``\"aa bb\"``\n* ``\"aa cc\"``\n* ``\"bb cc\"``\n* ``\"bb aa cc\"``\n* ``\"cc aa bb\"``\n\n.. code-block:: pycon\n\n >>> phrases = ['aa bb', 'aa cc', 'bb cc', 'bb aa cc', 'cc aa bb']\n >>> for phrase in phrases:\n ... ac.store(phrase)\n\nNote how when we search for *aa* that the results with *aa* towards the front of the string score higher:\n\n.. code-block:: pycon\n\n >>> ac.search('aa')\n ['aa bb',\n 'aa cc',\n 'bb aa cc',\n 'cc aa bb']\n\nThis is even more clear when we search for *bb* and *cc*:\n\n.. code-block:: pycon\n\n >>> ac.search('bb')\n ['bb aa cc',\n 'bb cc',\n 'aa bb',\n 'cc aa bb']\n\n >>> ac.search('cc')\n ['cc aa bb',\n 'aa cc',\n 'bb cc',\n 'bb aa cc']\n\nAs you can see, results are scored by the proximity of the match to the front of the string, then alphabetically.\n\nBoosting\n^^^^^^^^\n\nTo modify the score of certain words or phrases, we can apply *boosts* when searching. Boosts consist of a dictionary mapping identifiers to multipliers. Multipliers greater than 1 will move results to the top, while multipliers between 0 and 1 will push results to the bottom.\n\nIn this example, we'll take the 3rd result, *bb cc* and bring it to the top:\n\n.. code-block:: pycon\n\n >>> ac.search('cc', boosts={'bb cc': 2})\n ['bb cc',\n 'cc aa bb',\n 'aa cc',\n 'bb aa cc']\n\nIn this example, we'll take the best result, *cc aa bb*, and push it back a spot:\n\n.. code-block:: pycon\n\n >>> ac.search('cc', boosts={'cc aa bb': .75})\n ['aa cc',\n 'cc aa bb',\n 'bb cc',\n 'bb aa cc']\n\nPersisting boosts\n^^^^^^^^^^^^^^^^^\n\nWhile boosts can be specified on a one-off basis while searching, we can also permanently store boosts that will be applied to *all* searches. To store a boost for a particular object or object type, call the :py:meth:`~Autocomplete.boost_object` method:\n\n.. code-block:: pycon\n\n >>> ac.boost_object(obj_id='bb cc', multiplier=2.0)\n >>> ac.boost_object(obj_id='cc aa bb', multiplier=.75)\n\nNow we can search and our boosts will automatically be in effect:\n\n.. code-block:: pycon\n\n >>> ac.search('cc')\n ['bb cc',\n 'aa cc',\n 'cc aa bb',\n 'bb aa cc']\n\nZRANGEBYLEX\n-----------\n\nBecause I wanted to implement a slightly more complex scoring algorithm, I chose not to use the ``ZRANGEBYLEX`` command while implementing autocomplete. For very simple use-cases, though, ``ZRANGEBYLEX`` will certainly offer better performance. Depending on your application's needs, you may be able to get by just storing your words in a sorted set and calling ``ZRANGEBYLEX`` on that set.\n" }, { "alpha_fraction": 0.5608108043670654, "alphanum_fraction": 0.5641891956329346, "avg_line_length": 28.600000381469727, "blob_id": "97c72cb59cfee623a6d18c3116798066fbbf2545", "content_id": "faf965575744a35695370cde654673b757e404ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1480, "license_type": "permissive", "max_line_length": 52, "num_lines": 50, "path": "/walrus/__init__.py", "repo_name": "coleifer/walrus", "src_encoding": "UTF-8", "text": "\"\"\"\nLightweight Python utilities for working with Redis.\n\"\"\"\n\n__author__ = 'Charles Leifer'\n__license__ = 'MIT'\n__version__ = '0.9.3'\n\n# ___\n# .-9 9 `\\\n# =(:(::)= ;\n# |||| \\\n# |||| `-.\n# ,\\|\\| `,\n# / \\\n# ; `'---.,\n# | `\\\n# ; / |\n# \\ | /\n# jgs ) \\ __,.--\\ /\n# .-' \\,..._\\ \\` .-' .-'\n# `-=`` `: | /-/-/`\n# `.__/\n\nfrom walrus.autocomplete import Autocomplete\nfrom walrus.cache import Cache\nfrom walrus.containers import Array\nfrom walrus.containers import BitField\nfrom walrus.containers import BloomFilter\nfrom walrus.containers import ConsumerGroup\nfrom walrus.containers import Container\nfrom walrus.containers import Hash\nfrom walrus.containers import HyperLogLog\nfrom walrus.containers import List\nfrom walrus.containers import Set\nfrom walrus.containers import Stream\nfrom walrus.containers import ZSet\nfrom walrus.counter import Counter\nfrom walrus.database import Database\nfrom walrus.fts import Index\nfrom walrus.graph import Graph\nfrom walrus.lock import Lock\nfrom walrus.models import *\nfrom walrus.rate_limit import RateLimit\nfrom walrus.rate_limit import RateLimitException\nfrom walrus.streams import Message\nfrom walrus.streams import TimeSeries\n\n# Friendly alias.\nWalrus = Database\n" } ]
66
yhs2/sparkWiki
https://github.com/yhs2/sparkWiki
1ee93920361abc667f7bd7dd4e0878aa74b4e013
be62beb0d48430162a6bc9b1c54901dfb5abdff6
e9e01462c61c5fb6e9f80da7258be0fb1e31706f
refs/heads/master
2023-08-16T17:09:39.863919
2021-09-23T22:46:22
2021-09-23T22:46:22
409,761,816
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.630859375, "alphanum_fraction": 0.6748046875, "avg_line_length": 25.28205108642578, "blob_id": "2fd1a6728843f167e439e3c2562c86e7d6d8914e", "content_id": "21e59b6d56f2e087373cd43ad908fd4fc9d515fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 114, "num_lines": 39, "path": "/wikipedia_popular.py", "repo_name": "yhs2/sparkWiki", "src_encoding": "UTF-8", "text": "from pyspark import SparkConf, SparkContext\nimport sys\nimport string\n\n\ninputs = sys.argv[1]\noutput = sys.argv[2]\n\nconf = SparkConf().setAppName('word count improved')\nsc = SparkContext(conf=conf)\nassert sys.version_info >= (3, 5) # make sure we have Python 3.5+\nassert sc.version >= '2.3' # make sure we have Spark 2.3+\n#20160801-020000 en AaagHiAag 1 8979\ndef words_once(line):\n\n record = line.split()\n\n record_tuple_value = (record[0], record[1], record[2], int(record[3]), record[4])\n\n return record_tuple_value\n\n\ndef get_key(kv):\n return kv[0]\n\n\ndef tab_separated(kv):\n return \"%s\\t%s\" % (kv[0], kv[1])\n\n\ntext = sc.textFile(inputs)\nrecords = text.map(words_once)\nfiltered_records = records.filter(lambda n: n[1] == \"en\").\\\n filter(lambda n: n[2] != \"Main_Page\" and not n[2].startswith(\"Special:\"))\n\nwordcount = filtered_records.map(lambda n: (n[0], (n[3], n[2]))).reduceByKey(lambda x, y: x if x[0] > y[0] else y)\n\noutdata = wordcount.sortBy(get_key).map(tab_separated)\noutdata.saveAsTextFile(output)" } ]
1
Tarooqh/myblog
https://github.com/Tarooqh/myblog
cd5f515ab202f80682dfc82ba31d9b4603c0a15e
b02539b3367ab88a8d90b57c315681266ad20d5e
5d13b2970684cd68f6007a1dd3cb26f123b8786a
refs/heads/master
2021-07-01T01:12:27.331415
2017-09-21T19:23:36
2017-09-21T19:23:36
103,056,421
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6033112406730652, "alphanum_fraction": 0.6072847843170166, "avg_line_length": 22.936508178710938, "blob_id": "0ace0e13e694e513c8f6ef9be9d7c97bc354c145", "content_id": "9e0880eb1144203dd40f2e1b263a791f8b3c9df1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1510, "license_type": "no_license", "max_line_length": 88, "num_lines": 63, "path": "/myblog/posts/admin.py", "repo_name": "Tarooqh/myblog", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import posts\n# Register your models here.\n\n\n\nclass postsAdmin(admin.ModelAdmin):\n class meta:\n model = posts\n\n # actions\n\n def make_published(self, request, posts):\n posts.update(status='p')\n\n if rows_updated == 1:\n message_bit = \"1 story was\"\n\n else:\n message_bit = \"%s stories were\" % rows_updated\n self.message_user(request, \"%s successfully marked as published.\" % message_bit)\n\n def make_draft(self, request, posts):\n posts.update(status='d')\n\n if rows_updated == 1:\n message_bit = \"1 story was\"\n\n else:\n message_bit = \"%s stories were\" % rows_updated\n self.message_user(request, \"%s successfully marked as draft.\" % message_bit)\n\n\n def make_withdrawn(self, request, posts):\n posts.update(status='w')\n\n if rows_updated == 1:\n message_bit = \"1 story was\"\n\n else:\n message_bit = \"%s stories were\" % rows_updated\n self.message_user(request, \"%s successfully marked as withdrawn.\" % message_bit)\n\n actions = [make_published, make_draft, make_withdrawn]\n # list based options\n\n\n\n list_display = [\"title\", \"timestamp\", \"updated\",\"status\"]\n list_display_links = ['title','updated']\n list_filter = ['updated', 'timestamp']\n\n#search based options\n\n search_fields = ('title', 'content')\n\n#ordering\n ordering = ['title', 'updated']\n\n\n\n\nadmin.site.register(posts, postsAdmin)\n\n\n" }, { "alpha_fraction": 0.6491862535476685, "alphanum_fraction": 0.6600361466407776, "avg_line_length": 29.93600082397461, "blob_id": "a9e8667dd94cb8c7127bf4f0cf0e5dd21ff6301e", "content_id": "74a96777b3c564e47e25ad8327c5f2ec499ed1e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3871, "license_type": "no_license", "max_line_length": 102, "num_lines": 125, "path": "/myblog/posts/views.py", "repo_name": "Tarooqh/myblog", "src_encoding": "UTF-8", "text": "try:\n from urllib import quote_plus #python 2\nexcept:\n pass\n\ntry:\n from urllib.parse import quote_plus #python 3\nexcept:\n pass\n\nfrom django.contrib import messages\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render, get_object_or_404, get_list_or_404, redirect\nfrom .forms import PostForm\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nfrom django.utils import timezone\n\nfrom .models import posts\n\n\n# Create your views here.\nqueryset = posts.objects.all()\n\n\ndef posts_create(request):\n if not request.user.is_staff or not request.user.is_superuser:\n raise Http404\n\n # if not request.user.is_authenticated:\n # raise Http404\n form = PostForm(request.POST or None, request.FILES or None)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.user=request.user\n instance.save()\n messages.success(request, \"Content added successfully\")\n return HttpResponseRedirect(instance.get_absolute_url())\n else:\n messages.error(request, \"Content not added\")\n context = {\n \"form\":form,\n }\n\n return render(request, \"create.html\", context)\n\n\ndef posts_retrieve(request, id=None):\n instance = get_object_or_404(posts, id = id)\n if instance.draft or instance.publish > timezone.now().date():\n if not request.user.is_staff or not request.user.is_superuser:\n raise Http404\n\n share_string = quote_plus(instance.content)\n context = {\n \"objectlist\":queryset,\n 'title':'detail',\n \"instance\": instance,\n \"share_string\":share_string\n }\n return render(request, \"detail.html\", context)\n\n\ndef posts_update(request, id=None):\n if not request.user.is_staff or not request.user.is_superuser:\n raise Http404\n\n instance = get_object_or_404(posts, id=id)\n form = PostForm(request.POST or None, instance = instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n messages.success(request, \"<a href='#'> Content updated successfully\", extra_tags=\"html_safe\")\n return HttpResponseRedirect(instance.get_absolute_url())\n else:\n messages.error(request, \"Content not updated successfully\")\n\n context = {\n \"objectlist\": queryset,\n 'title': 'detail',\n \"instance\": instance,\n \"form\":form,\n }\n return render(request, \"create.html\", context)\n\n\ndef posts_delete(request, id = None):\n if not request.user.is_staff or not request.user.is_superuser:\n raise Http404\n instance = get_object_or_404(posts, id=id)\n instance.delete()\n messages.success(request, \"Content deleted successfully\")\n return redirect(\"posts:default\")\n\n\ndef posts_lists(request):\n queryset_list = posts.objects.active()#.order_by(\"-timestamp\")\n query = request.GET.get(\"q\")\n if query:\n queryset_list = queryset_list.filter(\n Q(title__icontains=query) |\n Q(content__icontains=query)|\n Q(user__first_name__icontains=query) |\n Q(user__last_name__icontains=query)\n ).distinct()\n paginator = Paginator(queryset_list, 5) # Show 5 contacts per page\n page_request_var = 'page'\n page = request.GET.get(page_request_var)\n try:\n queryset = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n queryset = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n queryset = paginator.page(paginator.num_pages)\n\n\n context = {\n 'title':'list',\n \"objectlist\": queryset,\n \"page_request_var\": page_request_var,\n }\n return render(request,\"index.html\",context)\n\n\n\n\n" } ]
2
Silan1509/NumPad_Launcher
https://github.com/Silan1509/NumPad_Launcher
7356332fb790886c00a8b0f7645c4962764037d4
b8977607e2cdba50307f88f64129e5f7af856571
04cbbd01b55fa46308e892f70adc0278ae4ccdad
refs/heads/main
2023-05-23T01:36:52.520876
2021-06-09T10:37:47
2021-06-09T10:37:47
375,307,561
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48638758063316345, "alphanum_fraction": 0.5229800939559937, "avg_line_length": 33.72774887084961, "blob_id": "dc733c2a8c8b7e34dd21c207ef4e68e85db7701b", "content_id": "1eed1624a82e1ad620c2406c2d75daa87fc5e6b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6832, "license_type": "no_license", "max_line_length": 247, "num_lines": 191, "path": "/main.py", "repo_name": "Silan1509/NumPad_Launcher", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom TkinterDnD2 import *\r\nimport os\r\nfrom functools import partial\r\nfrom pynput.keyboard import Key, Listener\r\nimport time\r\nimport tkinter.messagebox\r\n\r\n\r\nif __name__ == '__main__':\r\n code = []\r\n name = []\r\n boxes = []\r\n codes = []\r\n path = []\r\n pressed_numbers = [10]*4\r\n x = 0\r\n t1 = time.time()\r\n\r\n\r\n def on_enter(e, button):\r\n e['background'] = '#282c2e'\r\n\r\n\r\n def on_leave(e, button):\r\n e['background'] = '#212526'\r\n\r\n def drop(index, boxes_i,event):\r\n\r\n if len(path) == index:\r\n path.append(event.data.replace(\"{\", \"\").replace(\"}\", \"\"))\r\n\r\n else:\r\n path[index] = event.data.replace(\"{\", \"\").replace(\"}\", \"\")\r\n\r\n print(event.data.replace(\"{\", \"\").replace(\"}\", \"\"))\r\n sch_name = path[index].split(\"/\")[-1].split(\".\")[0]\r\n boxes_i.delete(0, 20)\r\n boxes_i.insert(0, sch_name) #insert formated argument\r\n\r\n def create_new_row(boxes, codes):\r\n i = len(codes)\r\n print(i)\r\n codes.append(Entry(root, font=(\"Times\", 20), bg=\"#212526\", fg=\"white\", bd=0))\r\n codes[i].place(x=10, y=30 + 50 * i, height=40, width=60)\r\n\r\n boxes.append(Entry(root, font=(\"Courier\", 20), bg=\"#212526\", fg=\"white\", bd=0))\r\n boxes[i].place(x=85, y=30 + 50 * i, height=40, width=180)\r\n boxes[i].drop_target_register(DND_FILES)\r\n boxes[i].dnd_bind('<<Drop>>', partial(drop, i, boxes[i]))\r\n add_button.place(x=Window_width/10*6, y=i*50+80)\r\n save_button.place(x=Window_width/6, y=i*50+80)\r\n root.geometry(str(Window_width)+\"x\"+str(50*i+130))\r\n\r\n def save(codes, names):\r\n new_names = []\r\n new_path = []\r\n with open(\"data.txt\", \"w\") as f:\r\n for index, _ in enumerate(codes):\r\n try:\r\n new_names.append(names[index].get().replace(\" \", \"_\"))\r\n new_path.append(path[index].replace(\" \", \"_\"))\r\n except Exception:\r\n pass\r\n if len(codes[index].get()) > 4:\r\n tkinter.messagebox.showinfo(\"Warning\", \"Please use 4 or less digits in your code\")\r\n f.write(codes[index].get()+\" \"+new_names[index]+\" \"+new_path[index]+\"\\n\")\r\n pass\r\n\r\n\r\n def on_press(key):\r\n global t1\r\n try:\r\n if 96 <= key.vk <= 105:\r\n t2 = time.time()\r\n print(key.vk-96)\r\n if t2-t1 > 3:\r\n for index, _ in enumerate(pressed_numbers):\r\n\r\n pressed_numbers[index] = 10\r\n find_code(key.vk - 96)\r\n\r\n else:\r\n find_code(key.vk-96)\r\n t1 = t2\r\n except Exception:\r\n pass\r\n\r\n def on_release(key):\r\n if key == Key.esc:\r\n # Stop listener\r\n return False\r\n\r\n def find_code(pressed):\r\n global pressed_numbers\r\n for index, _ in enumerate(pressed_numbers):\r\n try:\r\n pressed_numbers[-index-1] = pressed_numbers[-index-2]\r\n except Exception:\r\n pressed_numbers[0] = pressed\r\n pressed_numbers1 = list(pressed_numbers[::-1])\r\n full = []\r\n for index, new in enumerate(codes):\r\n full.append(new.get())\r\n ready_codes = full\r\n for ind, full_code in enumerate(ready_codes):\r\n list_of_splitted_codes = list(full_code)\r\n try:\r\n if int(list_of_splitted_codes[0]) == pressed_numbers1[0] and int(list_of_splitted_codes[1]) == pressed_numbers1[1] and int(list_of_splitted_codes[2]) == pressed_numbers1[2] and int(list_of_splitted_codes[3]) == pressed_numbers1[3]:\r\n print('Launch app: ', path[ind])\r\n os.startfile(path[ind])\r\n pressed_numbers = [10 for _ in pressed_numbers]\r\n except:\r\n pass\r\n\r\n\r\n #reading the file\r\n if os.path.isfile(\"data.txt\"):\r\n with open(\"data.txt\") as f:\r\n for e, line in enumerate(f.readlines()):\r\n\r\n code.append(line.split()[0])\r\n try:\r\n name.append(line.split()[1].replace(\"_\", \" \"))\r\n except:\r\n name.append(line.split()[1])\r\n try:\r\n path.append(line.split()[2].replace(\"_\", \" \"))\r\n except:\r\n path.append(line.split()[2])\r\n else:\r\n with open(\"data.txt\", \"w+\") as f:\r\n pass\r\n\r\n root = TkinterDnD.Tk()\r\n var = StringVar()\r\n root.title('Fast pick')\r\n Window_width = 270\r\n Window_high = 45 * len(code) + 120\r\n root.geometry(str(Window_width)+\"x\"+str(Window_high))\r\n root.configure(background='#363636')\r\n\r\n # codes boxes\r\n for i, entry in enumerate(code):\r\n codes.append(Entry(root, font=(\"Times\", 20), bg=\"#212526\", fg=\"white\", bd=0))\r\n codes[i].insert(0, code[i])\r\n codes[i].place(x=10, y=30 + 50*i, height=40, width=60)\r\n\r\n # file paths drop places\r\n for i, box in enumerate(name):\r\n boxes.append(Entry(root, font=(\"Courier\", 20), bg=\"#212526\", fg=\"white\", bd=0))\r\n boxes[i].place(x=85, y=30+50*i, height=40, width=180)\r\n boxes[i].drop_target_register(DND_FILES)\r\n boxes[i].dnd_bind('<<Drop>>', partial(drop, i, boxes[i]))\r\n boxes[i].insert(0, name[i])\r\n\r\n #add button\r\n pixelVirtual = PhotoImage(width=1, height=1)\r\n add_button = Button(\r\n root, command=partial(create_new_row, boxes, codes), image=pixelVirtual,\r\n compound=\"c\", text=\"+\", font=(\"Times\", 30), height=40, width=40, bg=\"#212526\", fg=\"white\", bd=0, activebackground='#1b1e1f')\r\n\r\n add_button.place(x=Window_width/10*6, y=len(name)*50+30)\r\n add_button.bind(\"<Enter>\", partial(on_enter, add_button))\r\n add_button.bind(\"<Leave>\", partial(on_leave, add_button))\r\n\r\n\r\n\r\n #save button\r\n save_button = Button(root, command=partial(save, codes, boxes), image=pixelVirtual,\r\n compound=\"c\", text=\"save\", font=(\"Times\", 16), height=40, width=40, bg=\"#212526\", fg=\"white\", bd=0, activebackground='#1b1e1f')\r\n save_button.place(x=Window_width / 6, y=len(name) * 50 + 30)\r\n\r\n save_button.bind(\"<Enter>\", partial(on_enter, save_button))\r\n save_button.bind(\"<Leave>\", partial(on_leave, save_button))\r\n\r\n #Top labels\r\n code_label = Label(root, font=(\"Courier\", 15), bg=\"#212526\", fg=\"white\", bd=0, text=\"Code\")\r\n code_label.place(x=15, y=5)\r\n\r\n path_label = Label(root, font=(\"Courier\", 15), bg=\"#212526\", fg=\"white\", bd=0, text=\"Drop file\")\r\n path_label.place(x=120, y=5)\r\n\r\n # Collect events until released\r\n listener = Listener(on_press=on_press, on_release=on_release)\r\n\r\n listener.start()\r\n\r\n root.mainloop()\r\n\r\n listener.stop()\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.8083623647689819, "alphanum_fraction": 0.8083623647689819, "avg_line_length": 46.83333206176758, "blob_id": "38dca87ca58e1a7b41299e380353dabdad602078", "content_id": "364996c79dbdf452b52c08f2e1e6494af9fc6fb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 287, "license_type": "no_license", "max_line_length": 86, "num_lines": 6, "path": "/README.md", "repo_name": "Silan1509/NumPad_Launcher", "src_encoding": "UTF-8", "text": "# NumPad_Launcher\nApplication that allows you to drag and drop file and bind it to a four numpad numbers\n\nAt first launch the data file will be created\nThe data file contains code\\application name\\application path\nIf you want to delete shortcut just delete the line with it in data file\n" } ]
2
pktiny/pytest
https://github.com/pktiny/pytest
d2900252eb8ba8938c9484d983a929abf3fbb0a0
c9bf1a4f8091c3f9922527fa3699c744f27b3474
5cfee061656c519529d5961a8b00366442235f5e
refs/heads/master
2021-01-11T05:28:17.231035
2016-10-24T15:25:38
2016-10-24T15:25:38
71,802,063
0
0
null
2016-10-24T15:17:23
2016-10-24T13:57:03
2016-10-24T13:57:02
null
[ { "alpha_fraction": 0.5348837375640869, "alphanum_fraction": 0.5382059812545776, "avg_line_length": 14.8421049118042, "blob_id": "5df4680183e23fd9bf45168ca9157ad816c773d0", "content_id": "5df62e4546ca7579b9f9c8a639fe85179267c1c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "no_license", "max_line_length": 38, "num_lines": 19, "path": "/scrapy_tutorial/scrapy_tutorial/spiders/zhihu.py", "repo_name": "pktiny/pytest", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass ZhihuSpider(scrapy.CrawlSpider):\n name = \"zhihu\"\n allowed_domains = [\"zhihu.com\"]\n start_urls = (\n 'http://www.zhihu.com/',\n )\n rules = (\n\n )\n\n def start_request(self):\n pass\n\n def parse(self, response):\n pass\n" }, { "alpha_fraction": 0.764976978302002, "alphanum_fraction": 0.7695852518081665, "avg_line_length": 26.25, "blob_id": "11f9b065e3bc0b5555865b18b254aa33524615f7", "content_id": "e68dd37ce360c5f0831091d223592420f1dc7c22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "no_license", "max_line_length": 89, "num_lines": 8, "path": "/scrapy_tutorial/crawler.py", "repo_name": "pktiny/pytest", "src_encoding": "UTF-8", "text": "import scrapy.cmdline\n\n# quotos\n#scrapy.cmdline.execute(\"scrapy crawl quotes-xpath -o output/quotes-xpath3.json\".split())\n\n\n# zhihu\nscrapy.cmdline.execute(\"scrapy crawl zhihu-login -o output/zhihu-login.json\".split())" } ]
2
aryan1602/predictor
https://github.com/aryan1602/predictor
1c6a3e9116be2cc5a95ee9791ce1998996389ab0
0220147b0c3d858ca6c4947e551af6854c6f88d1
b161046e9f77da248015d8e816ddb3c913979806
refs/heads/master
2023-05-09T02:46:46.998324
2021-05-29T12:48:59
2021-05-29T12:48:59
371,973,548
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6553784608840942, "alphanum_fraction": 0.6772908568382263, "avg_line_length": 30.0625, "blob_id": "5aecc4e07372f20091acb5f2637004dd76a45fb2", "content_id": "78586cc8f68d2b2326a3ac2877b3bd1bc4309674", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "no_license", "max_line_length": 112, "num_lines": 16, "path": "/Predictor V1/tests.py", "repo_name": "aryan1602/predictor", "src_encoding": "UTF-8", "text": "import joblib\nimport pandas as pd\nwith open('reg.joblib', 'rb') as f:\n reg = joblib.load(f)\nwith open('lin.joblib', 'rb') as f:\n lin = joblib.load(f)\nwith open('onc.joblib', 'rb') as f:\n onc = joblib.load(f)\n\n\n\npred1 = reg.predict(onc.transform([['Narendra Modi Stadium',1,'Punjab Kings','Royal Challengers Bangalore',1]]))\npred2 = lin.predict(onc.transform([['Narendra Modi Stadium',1,'Punjab Kings','Royal Challengers Bangalore',1]]))\nprint(pred1)\nprint(pred2)\nprint((pred1 + pred2)/2)\n \n" }, { "alpha_fraction": 0.6327160596847534, "alphanum_fraction": 0.6759259104728699, "avg_line_length": 16.105262756347656, "blob_id": "fa3346bc6b56f7057e04fb2db16f17eacf841803", "content_id": "5bfcf913f5aa4d082f4232fe058de725b09acd08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 71, "num_lines": 19, "path": "/Predictor V1/main-test.py", "repo_name": "aryan1602/predictor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 24 16:54:29 2021\n\n@author: Aryan\n\"\"\"\n\n### Imports ###\n# add imports - classes and defs\nimport sys\nfrom predictor import predictRuns\n\n\n\"\"\"\nsys.argv[1] is the input test file name given as command line arguments\n\n\"\"\"\nruns = predictRuns('test.csv')\nprint(\"Predicted Runs: \", runs)" }, { "alpha_fraction": 0.6662606596946716, "alphanum_fraction": 0.6906211972236633, "avg_line_length": 25.483871459960938, "blob_id": "739592d9ab771736bb1b593b12c6faa9ed0839e8", "content_id": "e48e160b457dd843f161543bad1f86d5232038cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1642, "license_type": "no_license", "max_line_length": 111, "num_lines": 62, "path": "/Predictor V1/processing.py", "repo_name": "aryan1602/predictor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 19 18:27:16 2021\n\n@author: Aryan\n\"\"\"\n\ndef custom_accuracy(y_test,y_pred,thresold):\n right = 0\n l = len(y_pred)\n for i in range(0,l):\n if(abs(y_pred[i]-y_test[i]) <= thresold):\n right += 1\n return ((right/l)*100)\n\ncurrent_teams = ['Kolkata Knight Riders', 'Chennai Super Kings', 'Rajasthan Royals',\n 'Mumbai Indians', 'Punjab Kings',\n 'Royal Challengers Bangalore', 'Delhi Capitals',\n 'Sunrisers Hyderabad']\n\n\n\nimport pandas as pd\ndataset = pd.read_csv('main.csv')\ndataset = dataset[(dataset['batting_team'].isin(current_teams)) &(dataset['bowling_team'].isin(current_teams))]\n\n\nx = dataset.iloc[:,[0,1,2,3,5]].values\ny = dataset.iloc[:,4].values\n\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)\n\nfrom sklearn.preprocessing import OneHotEncoder\nonc = OneHotEncoder()\n\nx_train = onc.fit_transform(x_train)\nx_test = onc.transform(x_test)\n\n\nfrom sklearn.ensemble import RandomForestRegressor\nreg = RandomForestRegressor(n_estimators=100,max_features=None)\nreg.fit(x_train,y_train)\n\ny_pred = reg.predict(x_test)\nscore = reg.score(x_test,y_test)*100\nprint(\"R square value:\" , score)\nprint(\"Custom accuracy:\" , custom_accuracy(y_test,y_pred,20))\nfrom sklearn.linear_model import LinearRegression\nlin = LinearRegression()\nlin.fit(x_train,y_train)\n\ny_pred = lin.predict(x_test)\nscore = lin.score(x_test,y_test)*100\nprint(\"R square value:\" , score)\n\n\nimport joblib\njoblib.dump(reg, 'reg.joblib')\njoblib.dump(onc, 'onc.joblib')\njoblib.dump(lin,'lin.joblib')\n" }, { "alpha_fraction": 0.5364161729812622, "alphanum_fraction": 0.5491329431533813, "avg_line_length": 23, "blob_id": "e63e9872fdb87098a7255a35ed61c0d351a8b44d", "content_id": "88e22bc29ec664ac51ea311df7f0ea1f1e70b165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 865, "license_type": "no_license", "max_line_length": 132, "num_lines": 36, "path": "/Predictor V1/predictor.py", "repo_name": "aryan1602/predictor", "src_encoding": "UTF-8", "text": "### Custom definitions and classes if any ###\n\ndef predictRuns(testInput):\n import joblib\n import pandas as pd\n \n with open('reg.joblib', 'rb') as f:\n reg = joblib.load(f)\n with open('lin.joblib', 'rb') as f:\n lin = joblib.load(f)\n with open('onc.joblib', 'rb') as f:\n onc = joblib.load(f)\n \n i = pd.read_csv(testInput)\n \n \n \n z = i[\"batsmen\"].values\n \n wickets = -1;\n z = str(z)\n for j in z:\n if j == ',':\n wickets += 1;\n \n input_list = [[i['venue'].values[0] ,i['innings'].values[0], i['batting_team'].values[0], i['bowling_team'].values[0], wickets]]\n\n pred1 = reg.predict(onc.transform(input_list))\n pred2 = lin.predict(onc.transform(input_list))\n prediction = (pred1 + pred2)/2\n \n\n prediction = round(int(prediction))\n\n \n return prediction\n\n" } ]
4
Izardo/datarepresentation2021
https://github.com/Izardo/datarepresentation2021
2a75e643fc71aaf4063ebf518e6af2fad2dc8753
487faceda0628e3e9ab6cd9ef3231442eebd3c53
c6c10b69d9d060436a9b3a3fb9f2fa428aeb2187
refs/heads/main
2023-08-24T23:49:51.900616
2021-10-11T10:50:49
2021-10-11T10:50:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6747787594795227, "alphanum_fraction": 0.6814159154891968, "avg_line_length": 28.933332443237305, "blob_id": "cd26efcc9c265afe34bfe203d562f0248762c505", "content_id": "1bf77cb9fe7de3f8a4558187198752bc79937218", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 80, "num_lines": 15, "path": "/code/Week03-consuming XML/lecture-webscrap.py", "repo_name": "Izardo/datarepresentation2021", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://www.property.ie/property-for-sale/mayo/'\npage = requests.get(url)\n#print(page)\nsoup =BeautifulSoup(page.content, 'html.parser')\n#print(soup.prettify())\n\nlistings = soup.find_all(\"div\", class_=\"search_result\")\n#print(listings[0])\nfor listing in listings:\n pricediv = listing.find(\"div\", class_=\"sresult_description\").find(\"h3\").text\n print(pricediv)\n print(\"------------------\")\n\n\n\n" }, { "alpha_fraction": 0.6891385912895203, "alphanum_fraction": 0.6953807473182678, "avg_line_length": 28.66666603088379, "blob_id": "53da450e5d45c9b6a7845da5d6603c795127b83c", "content_id": "f280240df9db782d28df5d58b0d851ba8f1d45a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 801, "license_type": "no_license", "max_line_length": 86, "num_lines": 27, "path": "/code/Week03-consuming XML/PY06-property.py", "repo_name": "Izardo/datarepresentation2021", "src_encoding": "UTF-8", "text": "import requests\nimport csv\nfrom bs4 import BeautifulSoup\nurl = \"https://www.property.ie/property-for-sale/mayo/\"\npage = requests.get(url)\n\nsoup = BeautifulSoup(page.content, 'html.parser')\nprint(soup.prettify())\n\n\nproperty_file = open('week03property.csv', mode='w')\nproperty_writer = csv.writer(property_file, delimiter='\\t',\n quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\nlistings = soup.findAll(\"div\", class_=\"search_result\")\n\nfor listing in listings:\n print(listing)\n entryList = []\n\n address = listing.find(class_=\"sresult_address\").find(\"h2\").find(\"a\").text.strip()\n entryList.append(address)\n price = listing.find(class_=\"sresult_description\").find(\"h3\").text.strip()\n entryList.append(price)\n\n property_writer.writerow(entryList)\nproperty_file.close()\n" } ]
2
mashilu/hello-django
https://github.com/mashilu/hello-django
628db17447aff9d64285ca592f067d98cfb38de8
8a93b5fac5ac3f761450de72b2acd8f1a85d40f6
9fbcfff5f1f6054338d4594f33a23f9805757642
refs/heads/master
2020-03-18T13:54:12.836095
2018-07-20T09:08:54
2018-07-20T09:08:54
134,816,539
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6172839403152466, "alphanum_fraction": 0.6172839403152466, "avg_line_length": 24.959999084472656, "blob_id": "a694f0f5ed84077b502fba27300c0420e0973782", "content_id": "95f4afc687222ef1bf4edf0cd9f30d8b375ef2a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 748, "license_type": "no_license", "max_line_length": 90, "num_lines": 25, "path": "/learning_logs/urls.py", "repo_name": "mashilu/hello-django", "src_encoding": "UTF-8", "text": "\"\"\"\n定义learning_logs的URL模式\n\"\"\"\nfrom django.conf.urls import url\nfrom learning_logs import views\n\nurlpatterns = [\n # 主页\n url(r'^$', views.index, name='index'),\n\n # 显示所有主题\n url(r'^show_topics/$', views.show_topics, name='show_topics'),\n\n # 显示单个主题及其所有的条目\n url(r'^show_topic/(?P<topic_id>\\d+)/$', views.show_topic, name='show_topic'),\n\n # 添加新主题\n url(r'^add_new_topic/$', views.add_new_topic, name='add_new_topic'),\n\n # 在特定的主题中添加新条目\n url(r'^add_new_entry/(?P<topic_id>\\d+)/$', views.add_new_entry, name='add_new_entry'),\n\n # 编辑条目entry的页面\n url(r'^edit_entry/(?P<entry_id>\\d+)/$', views.edit_entry, name='edit_entry'),\n]" }, { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 14.5, "blob_id": "64b3ce5898c6bea42f185c62faad0809a22717aa", "content_id": "9a836415655c9450bcc496b52e7a5e4fa8123126", "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": "mashilu/hello-django", "src_encoding": "UTF-8", "text": "# hello-django\nlearning django\n" } ]
2
chyzwar/learning-fields
https://github.com/chyzwar/learning-fields
072e79e3bb0c26163ad2258059e1e2b936d4b8dd
98e4c588380496e94df7c51d91136036d3d410da
6f82f50491caceae3d30dc8dd2090ffcc2ec3f36
refs/heads/master
2021-07-10T00:40:51.917238
2019-03-18T23:19:40
2019-03-18T23:19:40
29,887,612
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4988946318626404, "alphanum_fraction": 0.5232129693031311, "avg_line_length": 24.129629135131836, "blob_id": "162d6fef1f76dcc10109146acfffe6712e9fe8fa", "content_id": "a7f43c2f2ded05f1e723e1276614a851288c8dee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 68, "num_lines": 54, "path": "/CSharp/code-examples/sys-programming/buffer3.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Author: [email protected]\nusing System;\n\nclass MyClass {\n public unsafe void Tester() {\n int[] iArray = new int[10];\n int[] jArray = new int[10];\n Console.WriteLine(\"Initialising iArray with i^2 for i = 0..9\");\n for (int count=0; count < 10; count++){\n iArray[count] = count*count;\n }\n fixed (int *fromPtr = iArray) {\n fixed (int *toPtr = jArray) {\n Console.WriteLine(\"iArray = {0}\", showArr(fromPtr, 10));\n Console.WriteLine(\"jArray = {0}\", showArr(toPtr, 10));\n memcpy(fromPtr, toPtr, 10);\n Console.WriteLine(\"After copying:\");\n Console.WriteLine(\"jArray = {0}\", showArr(toPtr, 10));\n Display(toPtr,10);\n Console.WriteLine(\"4-th element of jArray = {0}\", *(toPtr+4));\n }}\n }\n\n public unsafe static void memcpy (int *p1, int *p2, int n) {\n int *p = p1;\n int *q = p2;\n for (int i = 0; i<n; i++) {\n *q++ = *p++;\n }\n }\n public unsafe static string showArr(int *p, int n) {\n string s = \"\";\n int *q = p;\n for (int i = 0; i<n; q++, i++) {\n if (s!=\"\") {\n s += ',';\n }\n s += (*q).ToString();\n }\n return s;\n }\n public unsafe void Display(int *pt, int n) {\n for (int i=0; i < n;i++) {\n Console.WriteLine(*(pt+i));\n }\n }\n}\n\nclass MyClient {\n public static void Main() {\n MyClass mc = new MyClass();\n mc.Tester();\n }\n}\n" }, { "alpha_fraction": 0.5853658318519592, "alphanum_fraction": 0.5995935201644897, "avg_line_length": 27.941177368164062, "blob_id": "e3232230f9af3cbe11a66e88487c2d1ade36968b", "content_id": "5d50931fb5c10c79ec0091d6c37a70395a28f74b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 492, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/Python/IndustrialProgramming/classes/class2 (1).py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nclass D:\n pass # empty class object\n\n\ndef method(self): # just a function\n print (D.classVar) # not-yet existing attribute\n print (D.__dict__['classVar']) # same effect\n print (self.classVar) # ditto\n\nd = D() # create an instance\nD.method = method # add new class attributes\nD.classVar = 42\nprint(\"Testing adding of methods to class; expect value '42' printed 3 times.\")\nd.method() # prints 42 (thrice)\n" }, { "alpha_fraction": 0.6246668100357056, "alphanum_fraction": 0.6348437070846558, "avg_line_length": 22.42011833190918, "blob_id": "aa4ece732b8f249c3e4204cf0f6d0a6ab07e98c5", "content_id": "86da229faa28a6199f285410b4a9dd15c3061715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4127, "license_type": "no_license", "max_line_length": 137, "num_lines": 169, "path": "/Java/F21SF Soft E Fundation/Assignment 2/src/Golfer.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import java.util.Arrays;\r\n\r\n\r\n/**The Golfer class is a subclass of competitor which contains about infomation about Golfer.\r\n * \r\n * @author Kamontorn Khamrun H00144659\r\n *\r\n */\r\npublic class Golfer extends Competitor\r\n{\r\n\tprivate String competitorLevel;\r\n\tprivate int competitorAge;\r\n\tprivate String competitorCountry;\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t/**Constructor\r\n\t * @param cNumber competitor number\r\n\t * @param cName competitor number\r\n\t * @param cScores array of scores\r\n\t * @param cLevel competitor level\r\n\t * @param cAge competitor age\r\n\t * @param cCountry competitor country\r\n\t */\r\n\tpublic Golfer(int cNumber, Name cName, int[] cScores, String cLevel, int cAge, String cCountry){\r\n\t\tsuper(cNumber,cName,cScores);\r\n\t\r\n\t\tcompetitorLevel = cLevel;\r\n\t\tcompetitorAge = cAge;\r\n\t\tcompetitorCountry = cCountry;\r\n\t\t\r\n\t\t\r\n\t}\r\n\t\r\n\t\r\n\t/**This method is to return a competitor level.\r\n\t * @return competitor level\r\n\t */\r\n\tpublic String getCompetitorLevel()\r\n\t{\r\n\t\t//returns the capitalized in the first char \r\n\t\treturn Character.toUpperCase(competitorLevel.charAt(0)) + competitorLevel.substring(1);\r\n\t}\r\n\r\n\t\r\n\t/**This method is to return a competitor age.\r\n\t * @return competitor age\r\n\t */\r\n\tpublic int getCompetitorAge()\r\n\t{\r\n\t\treturn competitorAge;\r\n\t}\r\n\r\n\t/**This method is to return a competitor country.\r\n\t * @return competitor country\r\n\t */\r\n\tpublic String getCompetitorCountry()\r\n\t{\r\n\treturn competitorCountry;\r\n\t}\r\n\t\r\n\t\r\n\t/**This method is to return all scores in String format e.g. 3 4 1 3 4\r\n\t * @return score\r\n\t */\r\n\tpublic String getAllScore(){\r\n\t\t//create a format of array score to display e.g. 3 4 1 3 4\r\n\t\t\t\tString score =\"\";\r\n\t\t\t\tfor(int index=0; index < listOfScores.length ; index++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(index != listOfScores.length-1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tscore += listOfScores[index]+\" \";\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tscore += listOfScores[index];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn score;\r\n\t\t\t\t\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\t/**This method is to return an array of competitor scores\r\n\t * @return an array of competitor scores\r\n\t */\r\n\tpublic int[] getScore() {\r\n\t\treturn listOfScores;\r\n\t}\r\n\t\r\n\t\r\n\t/** This method overrides from a superclass to calculate and return\r\n\t * an overall score by average of top n scores where n is the level number Rookie (n=1), Amateur (n=2), Pro (n=3)\r\n\t * @return overallscore\r\n\t */\r\n\t\r\n\tpublic double getOverallScore() {\r\n\t\t\r\n\t\tdouble overallScore = 0;\r\n\t\tint level =0;\r\n\t\tint total = 0;\r\n\t\tint[] sortedScores = new int[5];\r\n\t\t\r\n\t\t\r\n\t\tfor(int index=0; index < listOfScores.length ; index++)\r\n\t\t{\r\n\t\t\t//Copy listOfScores to sortedScores\r\n\t\t\tsortedScores[index] = listOfScores[index];\r\n\t\t}\r\n\t\t\r\n\t\tArrays.sort(sortedScores); //sort all scores into ascending order\r\n\t\tif (competitorLevel.equals(\"rookie\"))\r\n\t\t{\r\n\t\t\tlevel = 1;\r\n\t\t}\r\n\t\telse if (competitorLevel.equals(\"amateur\"))\r\n\t\t{\r\n\t\t\tlevel = 2;\r\n\t\t}\r\n\t\telse if (competitorLevel.equals(\"pro\"))\r\n\t\t{\r\n\t\t\tlevel = 3;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\tfor(int scoreIndex = sortedScores.length - 1 ; scoreIndex >= sortedScores.length - level ; scoreIndex--)\r\n\t\t{\r\n\t\t\t//adding top n scores where n is the level number\r\n\t\t\t//starting of the last index (the highest score) then index-1 continue n loops, n = level.\r\n\t\t\ttotal += sortedScores[scoreIndex];\r\n\t\t\t\r\n\t\t}\r\n\t\t//compute an overall score\r\n\t\toverallScore = (double)total/level;\r\n\t\t\r\n\t\treturn overallScore;\r\n\t}\r\n\t\r\n\t\r\n\t/** This method overrides from the superclass to return a String of full competitor details\r\n\t * @return full details\r\n\t */\r\n\tpublic String getFullDetails() {\r\n\t\t//create a format of array scores to display e.g. 3,4,1,3,4\r\n\t\tString Score =\"\";\r\n\t\tfor(int index=0; index < listOfScores.length ; index++)\r\n\t\t{\r\n\t\t\tif(index != listOfScores.length-1)\r\n\t\t\t{\r\n\t\t\t\tScore += listOfScores[index]+\",\";\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tScore += listOfScores[index];\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\treturn \"Full details for \" + getId() + \":\\r\\nCompetitor number \" + getId() + \", name \" + getName() + \".\\n\"\r\n\t\t\t\t+ competitorName.getShortName() + \" is a \" + this.getCompetitorLevel() + \" aged \" + competitorAge\r\n\t\t\t\t+ \" from \" + competitorCountry + \" and received these scores : \"+ Score+ \" which has an overall score of \" + getOverallScore() + \".\";\r\n\t}\r\n\t\r\n\r\n}\r\n" }, { "alpha_fraction": 0.46414074301719666, "alphanum_fraction": 0.484438419342041, "avg_line_length": 15.043478012084961, "blob_id": "be00a84a4080a153e34bad34dcedce69316d04f7", "content_id": "0b73212ff7817eed19a2b91ab05227999c739be7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 42, "num_lines": 46, "path": "/Python/Excercises/fibonaci.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\ndef fib_iter(n):\n a, b = 1, 1\n for i in range(n - 1):\n a, b = b, a + b\n return a\n\nprint(fib_iter(5))\n\n\ndef fib_rec(n):\n if n == 1 or n == 2:\n return 1\n return fib_rec(n - 1) + fib_rec(n - 2)\n\nprint(fib_rec(3))\n\n\ndef memoize(fn, arg):\n memo = {}\n if arg not in memo:\n memo[arg] = fn(arg)\n return memo[arg]\n\nprint(memoize(fib_iter, 5))\n\n\nclass Memoize:\n\n def __init__(self, fn):\n self.fn = fn\n self.memo = {}\n\n def __call__(self, arg):\n if arg not in self.memo:\n self.memo[arg] = self.fn(arg)\n return self.memo[arg]\n\n\n@Memoize\ndef fib_mem(n):\n a, b = 1, 1\n for i in range(n - 1):\n a, b = b, a + b\n return a\n\nprint(fib_mem(5))\n" }, { "alpha_fraction": 0.5368421077728271, "alphanum_fraction": 0.5473684072494507, "avg_line_length": 18, "blob_id": "f2a42fe41504dca5c21af5fcfa0a7bc5f109ebba", "content_id": "bc8c225e60ce1cc74e4739824741d3a9c7607b7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 380, "license_type": "no_license", "max_line_length": 54, "num_lines": 20, "path": "/Python/Excercises/factorials.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from functools import wraps\n\n\ndef memo(f):\n \"\"\"Memoizing decorator for dynamic programming.\"\"\"\n @wraps(f)\n def func(*args):\n if args not in func.cache:\n func.cache[args] = f(*args)\n return func.cache[args]\n func.cache = {}\n return func\n\n\n@memo\ndef fact(n):\n if n == 0 or n == 1:\n return 1\n else:\n return n * fact(n - 1)\n" }, { "alpha_fraction": 0.5705289840698242, "alphanum_fraction": 0.5869017839431763, "avg_line_length": 21.05555534362793, "blob_id": "9a0acde1d0d94de9aa3d8bafd02e420844df4cf6", "content_id": "221b5e85e53853ef5b3c37ead8c1f64f36cd5022", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 794, "license_type": "no_license", "max_line_length": 63, "num_lines": 36, "path": "/Python/CodingTests/Dynamic Programming/subarrat.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# import sys\n\n# input_all = []\n\n# for line in sys.stdin:\n# input_all.append([int(x) for x in line.split()])\n\n\ninput_all = [[6], [-1, -2, -3, -4, -5, -6]]\n\nlist_arrays = input_all[1::2]\n\n\ndef maximum_subarray(list_arrays):\n for array in list_arrays:\n tu = max_subarray_conti(array), max_subarray_non(array)\n print(str(tu).strip('(').strip(')').replace(',', ''))\n\n\ndef max_subarray_conti(array):\n max_ending_here = max_so_far = array[0]\n for x in array[1:]:\n max_ending_here = max(x, max_ending_here + x)\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n\n\ndef max_subarray_non(array):\n sums = sum([x for x in array if x > 0])\n if sums is 0:\n return max(array)\n else:\n return sums\n\n\nmaximum_subarray(list_arrays)\n" }, { "alpha_fraction": 0.5098039507865906, "alphanum_fraction": 0.5392156839370728, "avg_line_length": 11.75, "blob_id": "62ffcd13655f22e9bb7056f086c8aa9a538cc481", "content_id": "e4930b744022899819645d6a9fb08857cba0b2ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 52, "num_lines": 8, "path": "/Interviews/skyscanner/task_1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# n = int(input())\n\nn = 2\n\nsum_of_power = sum([x * x for x in range(1, n + 1)])\n\n\nprint(sum_of_power)\n" }, { "alpha_fraction": 0.5492683053016663, "alphanum_fraction": 0.5492683053016663, "avg_line_length": 22.837209701538086, "blob_id": "f12f18a26859bef91a93d576aaf2a2e0443d68cf", "content_id": "a161c0c359169719b2bf25c22ff41b051c3f707d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 57, "num_lines": 43, "path": "/CSharp/coursework/MarcinK mpk31/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/controllers/HomePageController.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing WebBrowser_OuterSpace.models;\n\nnamespace WebBrowser_OuterSpace.controllers\n{\n /// <summary>\n /// Controller for HomePage Settings\n /// </summary>\n public class HomePageController\n {\n\n /// <summary>\n /// Read up a config on application load\n /// </summary>\n public void setUpHomePageConfig()\n {\n HomePageConfig hpc = HomePageConfig.Instance;\n hpc.readConfig();\n }\n\n /// <summary>\n /// Get Currently Selected home page\n /// </summary>\n /// <returns></returns>\n public String getHomePageURL(){\n\n HomePageConfig hpc = HomePageConfig.Instance;\n return hpc.homePageURL;\n }\n\n\n\n /// <summary>\n /// Save new home page address\n /// </summary>\n /// <param name=\"url\"></param>\n public void setHomePage(string url)\n {\n HomePageConfig hpc = HomePageConfig.Instance;\n hpc.writeHomeConfig(url);\n }\n }\n}\n" }, { "alpha_fraction": 0.558849573135376, "alphanum_fraction": 0.5615044236183167, "avg_line_length": 23.83516502380371, "blob_id": "04d305da7bbd27916d7b211d5a2226ffc7d7948b", "content_id": "bb8557b8b9ca8b965bd465a9cfb608789607e78d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2260, "license_type": "no_license", "max_line_length": 77, "num_lines": 91, "path": "/Java/F21AS Advanced Software Engineering/Week 1 Excepions/src/Staff.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "//a simple class to contain and manage Staff details\n//(id, name, hours)\npublic class Staff implements Comparable<Staff>\n{\n\tprivate String id;\n private String name;\n private int hoursWorked;\n\n /**\n * Set up the contact details. All details are trimmed to remove\n * trailing white space.\n * @param name The name.\n * @param hoursWorked The hours worked\n */\n public Staff(String id, String name, int hoursWorked)\n { \n \t//id and name MUSt be provided\n if( name.trim().length() ==0|| id.trim().length()== 0) \n {\n throw new IllegalStateException(\n \"Cannot have blank id or name\");\n }\n this.id =id.trim();\n this.name = name.trim();\n this.hoursWorked = hoursWorked;\n }\n \n /**\n * @return The id.\n */ \n public String getId() {\n \treturn id;\n }\n \n /**\n * @return The name.\n */\n public String getName()\n {\n return name;\n }\n\n /**\n * @return The hours Worked\n */\n public int getHoursWorked()\n {\n return hoursWorked;\n }\n\n \n /**\n * Test for content equality between two objects.\n * @param other The object to compare to this one.\n * @return true if the argument object has same id\n */\n public boolean equals(Object other)\n {\n if(other instanceof Staff) {\n Staff otherStaff = (Staff) other;\n return id.equals(otherStaff.getId());\n }\n else {\n return false;\n }\n }\n\n /**\n * Compare this Staff object against another, for the purpose\n * of sorting. The fields are compared by id.\n * @param otherDetails The details to be compared against.\n * @return a negative integer if this id comes before the parameter's id,\n * zero if they are equal and a positive integer if this\n * comes after the other.\n */\n\n public int compareTo(Staff otherDetails)\n {\n return id.compareTo(otherDetails.getId());\n } \n\n /**\n * @return A string containing all details.\n */\n public String toString()\n {\n return String.format(\"%-5s\", id ) + String.format(\"%-20s\", name) +\n String.format(\"%5d\", hoursWorked );\n }\n\n}\n" }, { "alpha_fraction": 0.5187320113182068, "alphanum_fraction": 0.5194524526596069, "avg_line_length": 27.61855697631836, "blob_id": "72b0c0191ab40043193aaf410bc2ced5e0af3244", "content_id": "696f52e9e895120a3d51f99b2d7746fece978d0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2778, "license_type": "no_license", "max_line_length": 103, "num_lines": 97, "path": "/CSharp/coursework/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/models/WebDocumentsCache.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Linq;\nusing System.Collections;\n\nnamespace WebBrowser_OuterSpace.models\n{ \n /// <summary>\n /// Singleton class dealing with browsing and getting a webpages\n /// </summary>\n class WebDocumentsCache\n {\n private static WebDocumentsCache instance;\n private ArrayList cachedTabs = new ArrayList();\n\n /// <summary>\n /// Constructor used only in Program.cs\n /// </summary>\n private WebDocumentsCache()\n {\n\n }\n \n /// <summary>\n /// Function that return referecnce to this singleton\n /// </summary>\n public static WebDocumentsCache Instance\n {\n get\n {\n if (instance == null)\n {\n instance = new WebDocumentsCache();\n }\n return instance;\n }\n }\n\n /// <summary>\n /// Get web document, depends on tabID it will create a new intsance of tab or use existing one\n /// </summary>\n /// <param name=\"url\"></param>\n /// <param name=\"tabID\"></param>\n /// <returns></returns>\n public String[] getWebDocument(String url, int tabID)\n {\n if(cachedTabs.Capacity >= tabID+1)\n {\n WebDocumenTab cachedDocument = (WebDocumenTab)cachedTabs[tabID];\n return cachedDocument.makeRequest(url);\n\n }else{\n WebDocumenTab newDocument = createNewTab(url);\n return newDocument.makeRequest(url);\n }\n\n }\n\n /// <summary>\n /// Get content of given Browser Tab\n /// </summary>\n /// <param name=\"tabID\"></param>\n /// <param name=\"homeURL\"></param>\n /// <returns></returns>\n public String[] getTabDocument(int tabID, String homeURL)\n {\n if (cachedTabs.Count >= tabID + 2)\n {\n WebDocumenTab cachedDocument = (WebDocumenTab)cachedTabs[tabID];\n return cachedDocument.retrieveDocument();\n\n }\n else\n { \n WebDocumenTab newDocument = createNewTab(homeURL);\n newDocument.makeRequest(homeURL).ToList().Add(homeURL);\n return newDocument.retrieveDocument();\n }\n }\n \n /// <summary>\n /// Create new Browsertab and to ArrayList for later retrieval\n /// </summary>\n /// <param name=\"url\"></param>\n /// <returns></returns>\n public WebDocumenTab createNewTab(String url)\n {\n WebDocumenTab newTab = new WebDocumenTab(url);\n cachedTabs.Add(newTab);\n newTab.runFetchThread();\n return newTab;\n\n }\n\n\n\n }\n}\n" }, { "alpha_fraction": 0.5775966048240662, "alphanum_fraction": 0.5932971239089966, "avg_line_length": 27.06779670715332, "blob_id": "51540c50d7073a27cdbe04d296669a446c87e0fe", "content_id": "46af6401102185b580576d11f7aa17f71e921555", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3312, "license_type": "no_license", "max_line_length": 124, "num_lines": 118, "path": "/CSharp/code-examples/parallel/goldbach_par.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/* Goldbach conjecture:\n Every even integer greater than 2 can be expressed as the sum of two primes.\n Usage: goldbach <int>\n\n Setup: \n ~/OPT/x86_64-unknown-linux/bin/dmcs --version\n Mono C# compiler version 2.10.2.0\n\n Compile: ~/OPT/x86_64-unknown-linux/bin/dmcs -optimize+ -out:goldbach_par.exe goldbach_par.cs\n Run: time ~/OPT/x86_64-unknown-linux/bin/mono goldbach_par.exe 65536\n\n ----------------------------------------------------------------------------- */\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic; // for List<T>\n\n// for parallelism:\nusing System.Collections.Concurrent; // partitioner\nusing System.Threading.Tasks; // parallel patterns\n\nclass Primes : IEnumerable {\n private static List<int> all_primes;\n private int ctr = 0;\n\n // enumerator\n public IEnumerator<int> GetEnumerator() {\n foreach (int n in all_primes) {\n yield return n;\n }\n }\n // required to fulfill IEnumerable\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator(){\n throw new NotImplementedException();\n }\n\n // Build a list of all primes\n public Primes(int m) {\n bool is_prime;\n all_primes = new List<int>();\n all_primes.Add(2); ctr++;\n for (int n = 3; n<m; n+=2) {\n is_prime = true;\n foreach (int p in all_primes) {\n\tif (n % p == 0) {\n\t is_prime = false;\n\t break;\n\t}\n }\n if (is_prime) { all_primes.Add(n); ctr++; }\n }\n }\n}\n\npublic class Goldbach {\n\n public static void Main (string []args) {\n if (args.Length < 1) { // expect 1 args: x\n System.Console.WriteLine(\"Usage: goldbach <int>\");\n } else if (args.Length == 2) {\n int p = Convert.ToInt32(args[0]);\n int x = Convert.ToInt32(args[1]);\n System.Console.WriteLine(\"Parallel Goldbach conjecture up to {0} is {1} on {2} processors\", x, p, goldbach_par(x,p));\n } else {\n int x = Convert.ToInt32(args[0]);\n System.Console.WriteLine(\"Goldbach conjecture up to {0} is {1}\", x, goldbach_naive(x));\n }\n }\n\n public static bool goldbach_naive (int m) {\n Primes primes = new Primes(m);\n bool found = false;\n\n for (int n = 4; n<m; n+=2) {\n found = false;\n foreach (int p in primes) { \n\tforeach (int q in primes) { \n\t if (n == p+q) {\n\t found = true;\n\t }\n\t}\n\tif (found) break;\n }\n if (!found) break;\n }\n// if (!found) \n// System.Console.WriteLine(\"False: no Goldbach pair found for {0}\", m); \n return found;\n }\n\n public static bool goldbach_par (int m, int proc) {\n // initialise list of primes eagerly\n Primes primes = new Primes(m);\n Object foundLock = new Object();\n bool globalFound = false;\n\n /* Parallel version, using only k tasks */\n var options = new ParallelOptions() { MaxDegreeOfParallelism = proc};\n\n // for (int n = 4; n<m; n+=2) {\n Parallel.For(4, m, options, (n, loopState) => {\n bool found = false; // thread-local\n foreach (int p in primes) { \n\tforeach (int q in primes) { \n\t if (n == p+q) {\n\t found = true;\n\t }\n\t}\n\tif (found) { lock (foundLock) { globalFound = true; } ; loopState.Break(); }\n }\n if (!found) loopState.Break();\n n++; n++; \n });\n// if (!found) \n// System.Console.WriteLine(\"False: no Goldbach pair found for {0}\", m); \n return globalFound;\n }\n}\n" }, { "alpha_fraction": 0.5894736647605896, "alphanum_fraction": 0.6070175170898438, "avg_line_length": 16.8125, "blob_id": "6bb0c131abaf74ac71f1fb605cc499e79d48c42a", "content_id": "e81cac132b0de05af07c5a449459afab427877db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 40, "num_lines": 16, "path": "/Python/IndustrialProgramming/advanced/vector1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nclass Vector(object):\n # constructor\n\n def __init__(self, coord):\n self.coord = coord\n # turns the object into string\n\n def __str__(self):\n return str(self.coord)\n\nv1 = Vector([1, 2, 3])\n# performs conversion to string as above\nprint (v1)\n" }, { "alpha_fraction": 0.5477386713027954, "alphanum_fraction": 0.5628140568733215, "avg_line_length": 14.583333015441895, "blob_id": "f335fa0bc08b985583160564772ddd0e42bd5aac", "content_id": "144158e05367977bfd4e9e023371a349bd30460f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 398, "license_type": "no_license", "max_line_length": 49, "num_lines": 24, "path": "/Java/F21AS Advanced Software Engineering/Week 2 Multi-Threading/src/ThreadsExtendThread.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\r\npublic class ThreadsExtendThread extends Thread {\r\n\tint id;\r\n\r\n\tpublic ThreadsExtendThread(int i) { id = i; }\r\n\r\n\tpublic void run()\r\n\t{ \r\n\t\tint i = 0;\r\n\t\twhile (true)\r\n\t\t{\r\n\t\t\tSystem.out.print(id); \r\n\t\t\ti++;\r\n\t\t\tif (i>100)\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\t\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\tpublic static void main(String args[]) {\r\n\t\t\tnew ThreadsExtendThread(1).start();\r\n\t\t\tnew ThreadsExtendThread(2).start();\r\n\t\t}\r\n\t}" }, { "alpha_fraction": 0.5978552103042603, "alphanum_fraction": 0.6112600564956665, "avg_line_length": 11.064516067504883, "blob_id": "3051da92f36dbd6f77ff1bd655ad2046072f659b", "content_id": "2683eb51069988f1f10068ad5f968fcc01ded108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 373, "license_type": "no_license", "max_line_length": 41, "num_lines": 31, "path": "/CSharp/exercises/shapes-inheritance.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "namespace shapes;\n\n\n\n\nabstract class Shape\n{\n\n public abstract double area();\n\n}\n\nclass Square : Shape\n{\n public static int no = 0;\n public static double area = 0;\n public static double sideLenght = 10;\n\n public double area()\n {\n area = sideLenght * sideLenght;\n return area;\n }\n\n}\n\nclass Circle : Shape\n{\n public static int no = 0;\n\n}" }, { "alpha_fraction": 0.6967213153839111, "alphanum_fraction": 0.7131147384643555, "avg_line_length": 12.55555534362793, "blob_id": "6141b4462bcd685f79777ae0cd265b69b6e3c58f", "content_id": "0866b853805c3dc33c6b212b8d552c573829e7f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 27, "num_lines": 9, "path": "/Interviews/jp_morgan/stack/test2.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from src.stack import Stack\n\nstack = Stack()\nstack.push(1)\nstack.push(5)\nprint(str(stack))\n\nstack.pop()\nprint(str(stack))\n" }, { "alpha_fraction": 0.6574434041976929, "alphanum_fraction": 0.6663617491722107, "avg_line_length": 39.49074172973633, "blob_id": "22bdd37e531d02c9d9a1726e1e98c5be1760b711", "content_id": "0ff04409edd3c1e9e818eff9055b7a458e38bc23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4373, "license_type": "no_license", "max_line_length": 173, "num_lines": 108, "path": "/CSharp/code-examples/objects/person.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Example demonstrating class hierarchies and inheritance\n// From Lecture 3: C# Basics\n// -----------------------------------------------------------------------------\n\nusing System;\n\n// The base class: generic information on a person\nclass Person{\n // data fields for Person; uses a mixture of access modifiers for demonstration\n public string fName;\n private string lName;\n private string address;\n\n public Person(string fName, string lName, string address){\n this.fName = fName;\n this.lName = lName;\n this.address = address;\n }\n\n // explicit, public access methods to the data fields\n public string GetfName(){return fName;}\n public string GetlName(){return lName;}\n public string GetAddress(){return address;}\n\n public override string ToString() {\n return String.Format(\"Name: {0} {1}\\tAddress: {2}\", this.fName, this.lName, this.address);\n }\n}\n\n// Student is a sub-class of Person, and inherits its data-fields and methods\nclass Student: Person{\n // data fields for Student\n private string matricNo;\n private string degree;\n\t\n public Student(string fName, string lName, string address, string matricNo, string degree): base(fName, lName, address) {\n this.matricNo = matricNo;\n this.degree = degree;\n }\n \n // explicit, public access methods to the data fields\n public string GetMatricNo(){return matricNo;}\n public string GetDegree(){return degree;}\n\n // override ToString as an example of serialisation\n public override string ToString() {\n string base_str = base.ToString();\n string this_str = String.Format(\"MatricNo: {0}\\tDegree: {1}\", this.matricNo, this.degree);\n return base_str+\"\\n\"+this_str;\n }\n // A different way to implement ToString; it is less generic, \n // because it relies on knowledge of the field in all parent classes\n public string ToString0() {\n return String.Format(\"Name: {0} {1}\\tAddress: {2}\\nMatricNo: {3}\\tDegree: {4}\", \n\t\t\t this.GetfName(), this.GetlName(), this.GetAddress(), this.matricNo, this.degree);\n }\n\n}\n\n// Lecturer is another sub-class of Person, and inherits its data-fields and methods\nclass Lecturer: Person{\n // data fields for Lecturer\n private string officeNo;\n \n public Lecturer(string fName, string lName, string address, string officeNo): base(fName, lName, address) {\n this.officeNo = officeNo;\n }\n // explicit, public access methods to the data fields\n public string GetOfficeNo(){return officeNo;}\n // override ToString as an example of serialisation\n public override string ToString() {\n string base_str = base.ToString();\n string this_str = String.Format(\"OfficeNo: {0}\", this.officeNo);\n return base_str+\"\\n\"+this_str;\n }\n}\n\nclass Test{\n public static void Main(){\n Person p = new Person(\"John\", \"Smith\", \"Edinburgh\");\n Student s = new Student(\"Brian\", \"Hillman\", \"London\", \"99124678\", \"CS\");\n Lecturer l = new Lecturer(\"Hans-Wolfgang\", \"Loidl\", \"Edinburgh\", \"G48\");\n Console.WriteLine(\"\\nInstantiating a person p, student s and lecturer l\");\n Console.WriteLine(\"Person p: {0} \", p.ToString());\n Console.WriteLine(\"Student s: {0} \", s.ToString());\n Console.WriteLine(\"Lecturer l: {0} \", l.ToString());\n Console.WriteLine(\"\\nBasic tests, showing values after instantiating basic objects:\");\n Console.WriteLine(\"Student matric no: {0} \", s.GetMatricNo());\n Console.WriteLine(\"Student address: {0} \", s.GetAddress());\n Console.WriteLine(\"Person address: {0} \", p.GetAddress());\n Console.WriteLine(\"Lecturer address: {0} \", l.GetAddress());\n Console.WriteLine(\"Lecturer office: {0} \", l.GetOfficeNo());\n // ---\n \n Console.WriteLine(\"\\nNow, copying the object and updating first name, demonstrating reference semantics in objects, ie. the update of first name in q affects p, too\");\n Person q = p;\n Console.WriteLine(\"Person p: {0} \", p.ToString());\n Console.WriteLine(\"Person q: {0} \", q.ToString());\n q.fName = \"Will\";\n Console.WriteLine(\"Person p: {0} \", p.ToString());\n Console.WriteLine(\"Person q: {0} \", q.ToString());\n\n Console.WriteLine(\"\\nHere we use the overriden ToString() method, implemented as a generic serialisation method:\");\n Console.WriteLine(\"Student: {0} \", s.ToString0());\n Console.WriteLine(\"Student: {0} \", s.ToString());\n Console.WriteLine(\"Lecturer: {0} \", l.ToString());\n }\n}\n" }, { "alpha_fraction": 0.4564315378665924, "alphanum_fraction": 0.46473029255867004, "avg_line_length": 25.55555534362793, "blob_id": "3dc94b178a137dd85c0f54311ff2b99b0237394e", "content_id": "60b79760202838220c76ca6e1017768b73a890fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 45, "num_lines": 9, "path": "/Python/Excercises/list_of_words.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\ndef list_of_words(file_name):\n words = {}\n\n for line in read(file_name):\n for word in line.split():\n if word in words:\n words[word] = words[word] + 1\n else:\n words[word] = 1\n" }, { "alpha_fraction": 0.5204219818115234, "alphanum_fraction": 0.5266432166099548, "avg_line_length": 20.358381271362305, "blob_id": "292b1e621e9de8d7032cc2b8ceee00434a323bf8", "content_id": "a7558d68d890d3755639d30ae32e2a16baf8685b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3697, "license_type": "no_license", "max_line_length": 89, "num_lines": 173, "path": "/Interviews/pebble/battleships/src/app/services/GameService.ts", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/// <reference path='../../typings/_custom.d.ts' />\n\nimport {provide, Injectable} from 'angular2/angular2';\n\nconst ammo = 35;\nconst dimensions = { x: 10, y: 10 };\nconst initialFleet = [\n { type: 'Destroyer', count: 2, size: 5 },\n { type: 'BattleShip', count: 1, size: 4 }]\n\n\ntype Area = { isHit: boolean, hasShip: boolean };\ntype Point = { x: number; y: number };\ntype Ship = { type: string, size: number, coords: Array<Point> };\n\n@Injectable()\nexport class GameService {\n\n grid: Area[][];\n fleet: Ship[];\n plays: Point[];\n ammo: number;\n hasWon: boolean;\n\n constructor() {\n this.grid = this.initGrid(\n dimensions.x,\n dimensions.y\n );\n\n this.fleet = this.initFleet(\n initialFleet\n );\n this.ammo = ammo;\n this.hasWon = true;\n }\n\n private initFleet(initialFleet: any): Ship[] {\n var fleet = [];\n\n initialFleet.forEach(\n formation => {\n this.positionShips(formation).forEach(\n ship => {\n fleet.push(ship);\n }\n );\n }\n );\n return fleet;\n }\n\n private positionShips(formation: any): Ship[] {\n var formationShips = [];\n\n for (var i = 0; i < formation.count; ++i) {\n formationShips.push(\n this.createShip(\n formation.type, formation.size)\n );\n }\n\n return formationShips;\n }\n\n private createShip(type: string, size: number): Ship {\n var ship = {\n type: type,\n size: size,\n coords: []\n };\n\n ship.coords = this.insertShip(size);\n\n ship.coords.forEach(\n point => {\n this.grid[point.x][point.y].hasShip = true;\n }\n );\n return ship;\n }\n\n private insertShip(size: number): Point[] {\n var x = this.randomNumber(0, dimensions.x - 1);\n var y = this.randomNumber(0, dimensions.y - 1);\n\n if (!this.hasShip(x, y)) {\n if (x + size < dimensions.x) {\n return this.attemptInsert(x, y, size, 'x');\n }\n else if (y + size < dimensions.y) {\n return this.attemptInsert(x, y, size, 'y');\n }\n }\n\n return this.insertShip(size);\n }\n\n private attemptInsert(x: number, y: number, size: number, direction: string): Point[] {\n var coords = [];\n var canPosition = true;\n\n coords.push({ x: x, y: y });\n\n for (var i = 1; i < size; ++i) {\n if (direction === 'x') {\n if (this.hasShip(x + i, y)) {\n canPosition = false;\n } else {\n coords.push({ x: x + i, y: y });\n }\n } else {\n if (this.hasShip(x, y + i)) {\n canPosition = false;\n } else {\n coords.push({ x: x, y: y + i });\n }\n }\n }\n\n if (canPosition) {\n return coords;\n } else {\n return this.insertShip(size);\n }\n }\n\n\n private hasShip(x: number, y: number): boolean {\n return this.grid[x][y].hasShip || false;\n }\n\n private randomNumber(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min + 1) + min);\n }\n\n private initGrid(x: number, y: number): Area[][] {\n var matrix = [];\n for (var i: number = 0; i < x; i++) {\n matrix[i] = [];\n for (var j: number = 0; j < y; j++) {\n matrix[i][j] = { isHit: false, hasShip: false };\n }\n }\n return matrix;\n }\n\n static create(): GameService {\n return new GameService();\n }\n\n\n play(coord: Point) {\n this.ammo -= 1;\n this.grid[coord.x][coord.y].isHit = true;\n\n if (this.ammo === 0) {\n this.grid.forEach(\n row => {\n row.forEach(area => {\n if (area.hasShip && !area.isHit)\n this.hasWon = false;\n }\n );\n }\n );\n }\n }\n}\n\nexport var GAMESERVICE_BINDINGS = [\n provide(GameService, { useClass: GameService })\n];\n\n\n" }, { "alpha_fraction": 0.6540403962135315, "alphanum_fraction": 0.6553030014038086, "avg_line_length": 23, "blob_id": "452e07419d4eccbc8d2e17872d1cf54adda6631c", "content_id": "9ed458417f680dd5d26718d5820e751d458f99ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 792, "license_type": "no_license", "max_line_length": 74, "num_lines": 33, "path": "/Angular/seed-testdrive/models/User.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "//User Models\nvar mongoose = require('mongoose');\nvar Schema = mongoose.Schema;\nvar bcrypt = require('bcrypt');\n\nvar UserSchema = new Schema({\n id: String,\n password: String,\n email: String,\n firstName: String,\n lastName: String,\n authority: {\n role: String,\n name: String,\n }\n});\n\nUserSchema.methods.generateHash = function(password) {\n return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);\n};\n\nUserSchema.methods.isValidPassword = function(password) {\n return bcrypt.compareSync(password, this.password);\n};\n\nUserSchema.statics.findByEmailOrQuery = function(email, query, callback) {\n this.findOne({\n $or: [{\n email: email\n }, query]\n }, callback);\n};\nmodule.exports = mothership.model('User', UserSchema);\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6695652008056641, "avg_line_length": 19.5625, "blob_id": "fc59757499d75417af310345c4cc38977bb43fa5", "content_id": "3f7f6b32d65c32a75e30bcf5436424b1df5b7e0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 345, "license_type": "no_license", "max_line_length": 68, "num_lines": 16, "path": "/Java/F21AS Advanced Software Engineering/Week 6 Observer Pattern/src/Counter.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import javax.swing.JOptionPane;\r\npublic class Counter implements Observer{\r\n\tprivate int counter ;\r\n\t\r\n\tpublic Counter (Subject subject) {\r\n\t\tcounter = 0;\r\n\t\tsubject.registerObserver(this);\r\n\t}\r\n\t\r\n\tpublic void update () {\r\n\t\tcounter++;\r\n\t\tJOptionPane.showMessageDialog(null, \"The clock has been changed \" \r\n\t\t\t\t+ counter + \" times\");\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.7163865566253662, "alphanum_fraction": 0.7184873819351196, "avg_line_length": 23.7297306060791, "blob_id": "4d3a5188388714ed3f891a15e1b3c63f90cc6d8c", "content_id": "b873f57e616d67f91bd1b476ecf6520e7437cdf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 952, "license_type": "no_license", "max_line_length": 60, "num_lines": 37, "path": "/Java/F21AS Advanced Software Engineering/Week 6 MVC/src/controllers/ClockController.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package controllers;\r\nimport java.awt.event.ActionEvent;\r\nimport java.awt.event.ActionListener;\r\nimport java.awt.event.WindowAdapter;\r\nimport java.awt.event.WindowEvent;\r\n\r\nimport model.Clock;\r\nimport views.ClockGUI;\r\n\r\n//Handles interaction with users\r\n//calls view and model as needed\r\n\r\npublic class ClockController {\r\n\r\n\tprivate ClockGUI view; //GUI to allow user to set the time\r\n\r\n\tprivate Clock clock; //clockmodel stores the time\r\n\t\r\n\tpublic ClockController(ClockGUI view, Clock clock) {\r\n\t\tthis.clock = clock;\r\n\t\tthis.view = view;\r\n\t\t//specify the listener for the view\r\n\t\tview.addSetListener(new SetListener());\r\n\t}\r\n\t\r\n\t//inner class SetListener responds when user sets the time\r\n\tpublic class SetListener implements ActionListener\r\n\t{\r\n\t\tpublic void actionPerformed (ActionEvent e)\r\n\t\t{\r\n\t\t\tint hour = Integer.parseInt(view.getHours());\r\n\t\t\tint min = Integer.parseInt(view.getMins());\r\n\t\t\tclock.setTime24(hour, min);\r\n\t\t}\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5306630730628967, "alphanum_fraction": 0.5389037728309631, "avg_line_length": 29.514619827270508, "blob_id": "309a5bb0b375358b609e6b78a8769742563f6987", "content_id": "e51f3a8ac8de6462da6848525c0af0f664b42e63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5218, "license_type": "no_license", "max_line_length": 98, "num_lines": 171, "path": "/Python/IndustrialProgramming/extra/ho_sort.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Higher order sorting in Python\n\nimport sys\nimport random\nimport os\nimport fractions\n#import json\n\n# -----------------------------------------------------------------------------\n# constants\n\nnames = [\"Jack\", \"Thomas\", \"Joshua\", \"Oliver\", \"Harry\",\n \"James\", \"William\", \"Samuel\", \"Daniel\", \"Charlie\"]\n\n# -----------------------------------------------------------------------------\n# functions\n\n\ndef gcd(x, y):\n \"\"\"Compute the greatest common divisor, using Euclid's algorithm (top level function)\"\"\"\n assert(x >= 0 and y >= 0) # sanity check on the input\n if (x < y):\n res = gcd_rec(y, x) # uses recursive version in this case\n else:\n res = gcd_rec(x, y) # uses recursive version in this case\n return res\n\n\ndef gcd_rec(x, y):\n \"\"\"Compute the greatest common divisor, using Euclid's algorithm (recursive version)\"\"\"\n assert(x >= 0 and y >= 0 and x >=\n y) # NB: x>=y to save that test in the recursive calls\n if (y < 1):\n res = x\n # base case\n else:\n res = gcd_rec(y, x % y) # recursion case\n return res\n\n\ndef mkList(n, m=65535):\n \"\"\"Generate a list of <n> random elements bounded by <m>.\"\"\"\n list = []\n for i in range(n):\n no = random.randint(0, m)\n list.append(no)\n\n return list\n\n\ndef mkFavNums(n, names, m=65535):\n \"\"\"For each person in <names> generate a list of <n> favourite numbers each bounded by <m>.\"\"\"\n dict = {}\n for nam in names:\n list = []\n for i in range(n):\n no = random.randint(0, m)\n list.append(no)\n dict[nam] = list\n return dict\n\n\ndef countMatches(x, dict):\n \"\"\"How often does n appear as a favourite number?\"\"\"\n n = 0\n for k in dict.keys():\n if x in dict[k]:\n n += 1\n return n\n\n\ndef mostFavNum(dict):\n \"\"\"Return the most favourite number.\"\"\"\n # we use sets to collect the numbers\n xs = set([])\n # iterate over the dictionary entries\n for k in dict.keys():\n xs = xs | set(dict[k])\n # decorate each number with the matches, and use this as 1st arg in the\n # tuple\n xs_dec = [(countMatches(x, dict), x) for x in xs]\n # sort the list by first component in the tuple (no of matches)\n xs_dec.sort()\n # return xs_dec[-10:-1] # return largest 10 values, if you prefer (for\n # testing)\n n, x = xs_dec[-1] # largest elem\n return x # return it's value\n\n\ndef mostFavNumGen(dict, decorator):\n \"\"\"Return the most favourite number, using a decorator function argument.\"\"\"\n # we use sets to collect the numbers\n xs = set([])\n # iterate over the dictionary entries\n for k in dict.keys():\n xs = xs | set(dict[k])\n # decorate each number with the matches, and use this as 1st arg in the\n # tuple\n xs_dec = [(decorator(x, dict), x) for x in xs]\n # sort the list by first component in the tuple (no of matches)\n xs_dec.sort()\n # return xs_dec[-10:-1] # return largest 10 values, if you prefer (for\n # testing)\n n, x = xs_dec[-1] # largest elem\n return x # return it's value\n\n\ndef my_cmp(x, y):\n \"\"\"Custom comparison operator to return inverse of the default order.\"\"\"\n return (-1) * (x - y)\n\n\ndef gcd_cmp(x, y):\n \"\"\"Weird comparison that computes the gcd of two numbers.\"\"\"\n z = gcd(x, y)\n if z == 1:\n return 1\n else:\n return -1\n\n# -----------------------------------------------------------------------------\n# main\n\nif (len(sys.argv) != 2): # expect 0 args:\n print(\"Usage: \", argv[0], \" <n> ... sort a list of <n> random numbers\")\nelse:\n n = int(sys.argv[1]) # read from command-line\n\n # -------------------------------------------------------\n # I. generic sorting of integer values\n # -------------------------------------------------------\n # Generate input\n print (\"Generating a random list ...\")\n xs = mkList(n)\n print (xs)\n print (\"Sorting list using default < ...\")\n ys = list(xs) # this clones the input\n ys.sort()\n print (ys)\n # zs = xs\n # print (\"Input ...\")\n # print (zs)\n print (\n \"Doing a custom sort, here descending rather than ascending order ...\")\n zs = list(xs)\n zs.sort(cmp=my_cmp) # specify a function to use for comparison\n print (zs)\n print (\"Doing a custom sort, here in gcd order ...\")\n zs = list(xs)\n zs.sort(cmp=gcd_cmp) # specify a function to use for comparison\n print (zs)\n\n # -------------------------------------------------------\n # II. towards the CW\n # -------------------------------------------------------\n # Generate input\n print (\"Generating a favourite numbers ...\")\n favs = mkFavNums(n, names, 13)\n print (favs)\n print (\n \"Computing most favourite number (the one with most occurrences) ...\")\n print(mostFavNum(favs))\n\n print (\"Now using higher-order functions to do the sorting ...\")\n print (\n \"We declare, that the most favourite number should be the largest number ...\")\n print(mostFavNumGen(favs, (lambda x, y: x)))\n print (\n \"We declare, that the most favourite number should be the one with most matches ...\")\n print(mostFavNumGen(favs, countMatches))\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.5375000238418579, "avg_line_length": 11.684210777282715, "blob_id": "a7d302dc7f15b7f863c6a6cd0b8a47f5699e860b", "content_id": "7509a298475eaa486f5aa973ca22d0605f79cbc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 240, "license_type": "no_license", "max_line_length": 55, "num_lines": 19, "path": "/C/Learn-byExamples/hello_world.c", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main()\n{\n char string[] = \"Hello World\";\n\n printf(\"%s\\n\", string);\n\n\n\n int a;\n\n printf(\"Enter an integer\\n\");\n scanf(\"%d\", &a);\n\n printf(\"Integer that you have entered is %d\\n\", a);\n\n return 0;\n}" }, { "alpha_fraction": 0.5693923234939575, "alphanum_fraction": 0.5693923234939575, "avg_line_length": 27.978260040283203, "blob_id": "34c87173f70398d736a48f6c97f970c4e5945408", "content_id": "3d5009ebb218328e0154b7194ac0b457ed167f0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 72, "num_lines": 46, "path": "/Interviews/jp_morgan/call_billing/src/client/new_client.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from client import Client\n\n\nclass NewClient(Client):\n\n \"\"\"NewClient class inherit from Client\"\"\"\n\n def __init__(self, client_id, call_plan, client_type):\n super(NewClient, self).__init__(client_id, call_plan)\n self.__client_type = client_type\n\n def call_cost(self, call):\n \"\"\"Calculate total cost of call\"\"\"\n try:\n cost = self.per_minute(call.call_type) * call.call_duration\n\n if call.is_international:\n rate = self.call_plan.plan_tariffs['international_rate']\n cost = cost * rate\n\n return cost\n\n except KeyError, e:\n print 'I got a KeyError - reason \"%s\"' % str(e)\n\n def per_minute(self, call_type):\n \"\"\"Calculate base cost per minute,\n NewClient have use tariff for regular call as late call\"\"\"\n try:\n if call_type is \"regular_call\":\n per_minute = self.call_plan.plan_tariffs['late_call']\n else:\n per_minute = self.call_plan.plan_tariffs[call_type]\n\n return per_minute\n\n except KeyError, e:\n print 'I got a KeyError - reason \"%s\"' % str(e)\n\n @property\n def client_type(self):\n return self.__client_type\n\n @client_type.setter\n def call_type(self, value):\n self.__client_type = value\n" }, { "alpha_fraction": 0.6103895902633667, "alphanum_fraction": 0.6103895902633667, "avg_line_length": 24.53333282470703, "blob_id": "fce83f6a2caef2e90bf78455ea37fc6ad71bd042", "content_id": "99525479421f4c06b147f8a89815636a191eb413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/Interviews/jp_morgan/call_billing/src/call/call_plan.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\nclass CallPlan(object):\n\n \"\"\"Call plan class, use dictionary for tariff \"\"\"\n\n def __init__(self, call_plan_id, tariffs):\n self.__call_plan_id = call_plan_id\n self.__plan_tariffs = tariffs\n\n @property\n def plan_tariffs(self):\n return self.__plan_tariffs\n\n @plan_tariffs.setter\n def plan_tariffs(self, value):\n self.__plan_tariffs = value\n" }, { "alpha_fraction": 0.719298243522644, "alphanum_fraction": 0.719298243522644, "avg_line_length": 13.25, "blob_id": "4f8f91d0412c427a4832d3f0d484d5df607adc27", "content_id": "9bb8e13327a10b5cd2a6232728cfe0392bb3ba29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 57, "license_type": "no_license", "max_line_length": 27, "num_lines": 4, "path": "/Interviews/jp_morgan/stack/test1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from src.stack import Stack\n\nstack = Stack()\nstack.pop()\n" }, { "alpha_fraction": 0.6154598593711853, "alphanum_fraction": 0.6272015571594238, "avg_line_length": 29.058822631835938, "blob_id": "21504ebbdaa0410cbc919224ac8fc0b000779b16", "content_id": "c592314502965cae728ad4dd197bc660a5359fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4089, "license_type": "no_license", "max_line_length": 103, "num_lines": 136, "path": "/CSharp/code-examples/parallel/ParPipeline.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "ISO-8859-9", "text": "/* \nFrom: \nParallel Programming with Microsoft® .NET\nDesign Patterns for Decomposition and Coordination on Multicore Architectures\nBy Colin Campbell, Ralph Johnson, Ade Miller, Stephen Toub\nPublisher: Microsoft Press\nReleased: August 2010 \nOn-line: http://msdn.microsoft.com/en-us/library/ff963547.aspx\n\nChapter on Pipelines\n\nSimplified example from the book.\n*/\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Concurrent;\nusing System.Threading.Tasks;\n\nclass Pipeline<T> where T:IComparable {\n\n public delegate T IncDelegate (T x);\n\n private static void mkSequence(List<T> seq, T m, T n, IncDelegate inc) {\n if (m.CompareTo(n)>0) { // m>n\n return;\n } else {\n T m1 = inc(m);\n seq.Add(m);\n mkSequence(seq, m1, n, inc);\n return;\n }\n }\n\n public delegate T ProducerDelegate(T x, T y);\n\n public static void Producer(BlockingCollection<T> output,\n\t\t\t T from, T to, IncDelegate inc\n\t\t\t /* int seed */)\n {\n // System.Console.WriteLine(\"Producer running ... \");\n List<T> items = new List<T>();\n mkSequence(items, from, to, inc);\n try\n {\n \tforeach (T item in items) {\n \t output.Add(item);\n \t}\n }\n finally\n {\n\toutput.CompleteAdding();\n }\n }\n\n public delegate T ConsumerDelegate(T x);\n\n public static void Consumer(BlockingCollection<T> input,\n\t\t\t ConsumerDelegate worker,\n\t\t\t BlockingCollection<T> output) {\n // System.Console.WriteLine(\"Consumer running ... \");\n try\n {\n\tforeach (var item in input.GetConsumingEnumerable())\n\t {\n\t var result = worker(item);\n\t output.Add(result);\n\t }\n }\n finally\n {\n output.CompleteAdding();\n }\n }\n\n\n // public static string result_str = \"\";\n\n public static string LastConsumer(BlockingCollection<T> input, \n\t\t\t\t string str)\n {\n foreach (var item in input.GetConsumingEnumerable()) {\n str += \" \"+item.ToString();\n }\n return str;\n }\n}\n\npublic class Tester {\n public static void Main(string []args) {\n if (args.Length != 3) { // expect 1 arg: value to double\n System.Console.WriteLine(\"Usage: <prg> <k> <m> <n>\");\n System.Console.WriteLine(\"k ... number of cores to use\");\n System.Console.WriteLine(\"m, n ... the range of values to apply square function on \");\n } else { \n int k = Convert.ToInt32(args[0]); // unused\n int m = Convert.ToInt32(args[1]);\n int n = Convert.ToInt32(args[2]);\n int sum = 0;\n object lockObject = new { }; // any non-null object will do as lock\n // generates a range from input values; slightly artificial\n // List<int> seq = new List<int>();\n // mkSequence(seq, m, n);\n Pipeline<int>.IncDelegate inc = new Pipeline<int>.IncDelegate(x => x+1);\n\n /* Parallel version, using only 2 tasks */\n System.Console.WriteLine(\"Generating a list of squares, using a pipeline: {0} .. {1}\", m, n);\n\n try {\n\t int limit = 10; // buffer size\n\t string str = \"\";\n\t string result_str = \"\";\n\t var buffer1 = new BlockingCollection<int>(limit);\n\t var buffer2 = new BlockingCollection<int>(limit);\n\t \n\t var f = new TaskFactory(TaskCreationOptions.LongRunning, \n\t\t\t\t TaskContinuationOptions.None);\n\t System.Console.WriteLine(\"Starting Producer writing to buffer1 ... \");\n\t var task1 = f.StartNew(() => Pipeline<int>.Producer(buffer1, m, n, inc)); // mkSequence(seq,m,n)));\n\t System.Console.WriteLine(\"Starting Consumer, reading from buffer1 writing to buffer2 ... \");\n\t var task2 = f.StartNew(() => Pipeline<int>.Consumer(buffer1, \n\t\t\t\t\t\t\t new Pipeline<int>.ConsumerDelegate(x => x*x),\n\t\t\t\t\t\t\t buffer2));\n\t System.Console.WriteLine(\"Starting LastConsumer reading from buffer2 ... \");\n\t var task3 = f.StartNew(() => { result_str = Pipeline<int>.LastConsumer(buffer2, str); });\n\n\t System.Console.WriteLine(\"Waiting for all results ... \");\n\t Task.WaitAll(task1, task2, task3);\n\t System.Console.WriteLine(\"Result is: {0} \", result_str);\n } finally {\n\t // ... release handles to unmanaged resources ...\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.4502032399177551, "alphanum_fraction": 0.478658527135849, "avg_line_length": 22.428571701049805, "blob_id": "df0d5787e739df65be4b13c38436602728bf29f7", "content_id": "51f3300a38339484344daf1efd1e991e138d200e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 984, "license_type": "no_license", "max_line_length": 61, "num_lines": 42, "path": "/CSharp/code-examples/basics/loops.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Simple examples using loops over arrays\n\nclass Loops {\n static void Main() {\n int[] arr = {1,2,3,4,5,6,7,8,9,10};\n System.Console.WriteLine(\"Testing some loops now...\");\n Loops.Run(10);\n Loops.SumArr(arr);\n int[] arrr = new int[10];\n int i;\n for (i=0; i<10; i++) { // beware of indices\n arrr[i]=i-1;\n }\n Loops.SumArr(arrr);\n }\n static void Run(int n) {\n int i = 0, s = 0;\n while (i<=n) {\n s += i;\n i++;\n }\n System.Console.WriteLine(\"Sum from 0 to \"+n+\" = \"+s);\n\n s=0;\n for (i=0; i<=n; i++) {\n s += i;\n }\n System.Console.WriteLine(\"Sum from 0 to \"+n+\" = \"+s);\n }\n static void SumArr(int[] arr) {\n int i, s = 0;\n for (i=0; i<arr.Length; i++) {\n s+=arr[i];\n }\n System.Console.WriteLine(\"SumArr = \"+s);\n s = 0; \n foreach (int j in arr) { // need different variable here\n s+=j;\n }\n System.Console.WriteLine(\"SumArr = \"+s);\n }\n}\n" }, { "alpha_fraction": 0.5551839470863342, "alphanum_fraction": 0.5752508640289307, "avg_line_length": 16.647058486938477, "blob_id": "71050a0cdb1eb23ff190cbeb5a7a6c1c9c079ee0", "content_id": "346b706a75ff7b99241de3a19683ad0c5be1787e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/Python/CodingTests/Arrays and Sorting/quik_sort_1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# N = int(input())\n# items = input().split()\n# items = [int(x) for x in items]\n\n\narray = [4, 5, 3, 7, 2]\nP = array[0]\n\n\npartitionA = [a for a in array if a < P]\npartitionB = [b for b in array if b > P]\n\nresult = partitionA + [P] + partitionB\n\nprint(result)\n# for x in result:\n# print(x, end=\" \")" }, { "alpha_fraction": 0.3850267231464386, "alphanum_fraction": 0.4117647111415863, "avg_line_length": 15.909090995788574, "blob_id": "1ab9871f3cc05d550306e3cd6caf2bd13607ca57", "content_id": "a188b49764e2580d6600c05cc8b05d8c29a637cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "no_license", "max_line_length": 34, "num_lines": 22, "path": "/Interviews/metail/fizz_buzz.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\ndef solution(N):\n for number in range(1, N + 1):\n to_print = ''\n\n if number % 3 == 0:\n to_print += \"Fizz\"\n\n if number % 5 == 0:\n to_print += \"Buzz\"\n\n if number % 7 == 0:\n to_print += \"Woof\"\n\n if to_print:\n print to_print\n else:\n print str(number)\n\n pass\n\n\nsolution(16)\n" }, { "alpha_fraction": 0.5299773812294006, "alphanum_fraction": 0.5299773812294006, "avg_line_length": 25.388059616088867, "blob_id": "b1033170fa69dc5c82073731515f6eac9aad2645", "content_id": "4a3a5dd792047e817f824940c9049dd1c932ad14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1770, "license_type": "no_license", "max_line_length": 62, "num_lines": 67, "path": "/CSharp/coursework/MarcinK mpk31/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/controllers/FavouritesController.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing WebBrowser_OuterSpace.models;\n\n\nnamespace WebBrowser_OuterSpace.controllers\n{\n /// <summary>\n /// Favourites controller\n /// </summary>\n public class FavouritesController\n {\n /// <summary>\n /// Get a list of all favourities\n /// </summary>\n /// <returns></returns>\n public ArrayList getFavouritesList()\n {\n FavouritesList favo = FavouritesList.Instance;\n return favo.getfavouritesCollection();\n }\n\n /// <summary>\n /// On Application Start load Favourities\n /// </summary>\n public void loadFavourites()\n {\n FavouritesList favo = FavouritesList.Instance;\n favo.readFavouritesConfig();\n }\n\n /// <summary>\n /// Create new Fav\n /// </summary>\n /// <param name=\"name\"></param>\n /// <param name=\"url\"></param>\n public void createNewFav(String name, String url)\n {\n FavouritesList favo = FavouritesList.Instance;\n favo.addNewFav(name,url);\n }\n\n /// <summary>\n /// Update Fav\n /// </summary>\n /// <param name=\"name\"></param>\n /// <param name=\"url\"></param>\n /// <param name=\"id\"></param>\n public void updatefav(string name, string url, int id)\n {\n FavouritesList favo = FavouritesList.Instance;\n favo.makeUpdateFav(name , url , id);\n }\n\n /// <summary>\n /// Remove Favourity website\n /// </summary>\n /// <param name=\"id\"></param>\n public void removefav(int id)\n {\n FavouritesList favo = FavouritesList.Instance;\n favo.removeFav(id);\n }\n\n \n }\n}\n" }, { "alpha_fraction": 0.48076921701431274, "alphanum_fraction": 0.5365384817123413, "avg_line_length": 17.571428298950195, "blob_id": "0860b8e2204acef5bf1ffb7f9d2621fd231890ef", "content_id": "e5ac836ad7d1e286aeca91f7974343d9a74cd5ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 520, "license_type": "no_license", "max_line_length": 69, "num_lines": 28, "path": "/Python/CodingTests/Circle-City/circle_city.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# import sys\n\n# input_all = []\n\n# for line in sys.stdin:\n# input_all.append([int(x) for x in line.split() if x.isdigit()])\n\n\ninput_all = [[5], [1, 3], [1, 4], [4, 4],\n [25, 11], [25, 12]]\n\n\ndef circle_defence(cities):\n for city in cities:\n if city[1] >= latitude_points(city[0]):\n print(\"possible\")\n else:\n print(\"impossible\")\n\n\ndef latitude_points(R):\n\t#WTF\n #WTF a(n) = 8 * A046080(n) + 4 for n > 0.\n\n\ncircle_defence(input_all[1:])\n\nprint(latitude_points(25))\n" }, { "alpha_fraction": 0.6106312274932861, "alphanum_fraction": 0.6119601130485535, "avg_line_length": 19.52857208251953, "blob_id": "9d4c858ab13dc5fad23b916006fdb29f1585b763", "content_id": "c9a339d18206f577aac40d6c7f522ef99c123701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1505, "license_type": "no_license", "max_line_length": 104, "num_lines": 70, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orders/DishItem.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orders;\r\n\r\n/**This class is a subclass of Dish class, and represents a dish item\r\n * \r\n * @author Stian Dalviken\r\n *\r\n */\r\npublic class DishItem extends Dish \r\n{\r\n\tprivate double price;\r\n\tprivate String category;\r\n\t\r\n\t/**Dish item constructor for DishItem object throw exception if params are invalid\r\n\t * \r\n\t * @param dishName\r\n\t * @param price\r\n\t * @param category\r\n\t */\r\n\tpublic DishItem(String dishName, double price, String category)\r\n\t{\r\n\t\tsuper(dishName);\r\n\t\tif(price <=0)\r\n {\r\n\t throw new IllegalStateException(\r\n\t \"Price is invalid\");\r\n\t \r\n }\r\n\t\tif(category.length() ==0)\r\n {\r\n\t throw new IllegalStateException(\r\n\t \"Cannot have blank category\");\r\n\t \r\n }\r\n\t\tthis.price = price;\r\n\t\tthis.category = category;\r\n\t}\r\n\r\n\t/**Comparing two DishOrder objects and test for equality\r\n\t * \r\n\t * @param other Dish object\r\n\t * @return returns true if objects are equal otherwise false\r\n\t */\r\n\tpublic boolean equals(Dish other) \r\n\t{\r\n\t\tDishItem otherItem = (DishItem) other;\r\n\t\tif (dishName.equals(otherItem.dishName) && price == otherItem.price && category == otherItem.category)\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/**Returns the category of the DishItem object\r\n\t * \r\n\t * @return category\r\n\t */\r\n\tpublic String getCategory() \r\n\t{\r\n\t\treturn this.category;\r\n\t}\r\n\t\r\n\t/**Returns the price of the DishItem object\r\n\t * \r\n\t * @return price\r\n\t */\r\n\tpublic double getPrice()\r\n\t{\r\n\t\treturn this.price;\r\n\t}\r\n}" }, { "alpha_fraction": 0.598142683506012, "alphanum_fraction": 0.628535270690918, "avg_line_length": 31.90277862548828, "blob_id": "94253621cb785c95be451bcb4dfbea717f9412f5", "content_id": "65c76709bde1df6d53cfba48eec83423e99ef996", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2369, "license_type": "no_license", "max_line_length": 79, "num_lines": 72, "path": "/Interviews/jp_morgan/call_billing/test.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from src.billing.client_billing import ClientBilling\nfrom src.client.client_factory import ClientFactory\nfrom src.call.call_plan import CallPlan\nfrom src.call.call import Call\n\n\nfrom random import randint, choice\n\n# Simple Script runing tests on billing systems\n\n# mock some client data:\nclient_list = [\n {\"client_id\": 232, \"call_plan_id\": 1, \"client_type\": 'new'},\n {\"client_id\": 245, \"call_plan_id\": 1, \"client_type\": 'new'},\n {\"client_id\": 267, \"call_plan_id\": 1, \"client_type\": 'new'},\n {\"client_id\": 268, \"call_plan_id\": 1, \"client_type\": 'new'},\n {\"client_id\": 299, \"call_plan_id\": 1, \"client_type\": 'new'},\n {\"client_id\": 306, \"call_plan_id\": 1, \"client_type\": 'new'},\n {\"client_id\": 307, \"call_plan_id\": 1, \"client_type\": 'standard'},\n {\"client_id\": 308, \"call_plan_id\": 1, \"client_type\": 'standard'},\n {\"client_id\": 309, \"call_plan_id\": 1, \"client_type\": 'standard'},\n {\"client_id\": 400, \"call_plan_id\": 1, \"client_type\": 'standard'},\n {\"client_id\": 401, \"call_plan_id\": 1, \"client_type\": 'standard'},\n {\"client_id\": 402, \"call_plan_id\": 1, \"client_type\": 'standard'},\n]\n\n# define basic call plan\ncall_plan = [\n {\"call_plan_id\": 1,\n \"tariffs\": {\n \"regular_call\": 0.05,\n \"late_call\": 0.02,\n \"weekend_call\": 0.01,\n \"international_rate\": 2.00\n }}\n]\n\n# define basic call types\ncall_types = [\"regular_call\", \"late_call\", \"weekend_call\"]\n\n# create basic call_plan\nclient_plan = CallPlan(call_plan[0], call_plan[0]['tariffs'])\n\nclient_factory = ClientFactory()\nclient_billing = ClientBilling()\n\n\ndef fake_call(client):\n \"\"\"create fake call\"\"\"\n random_type = call_types[randint(0, 2)]\n call_duration = randint(0, 20)\n is_international = choice([True, False])\n\n call = Call(random_type, call_duration, is_international, client.client_id)\n print str(call)\n\n return call\n\nfor client in client_list:\n\n # Create client object for each fake client\n client = client_factory.factory(\n client['client_id'], client_plan, client['client_type'])\n\n # generate pseudorandom call_history\n call_history = [fake_call(client) for x in range(1, randint(0, 10))]\n\n # produce billing\n client_bill = client_billing.make_billing(client, call_history)\n print(\"\\n\\r\")\n print(\"Total for client_id: \" +\n str(client.client_id) + \" is \" + str(client_bill))\n" }, { "alpha_fraction": 0.6146789193153381, "alphanum_fraction": 0.6330274939537048, "avg_line_length": 35.5, "blob_id": "1b480e73557c4e4beea01cfeee2b8cb56d2f044d", "content_id": "d784aa0b4c185ff3ed0b49ebabe2c800fd79a273", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 218, "license_type": "no_license", "max_line_length": 44, "num_lines": 6, "path": "/React.js/6.2-build-process-before/gulpfile.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "var gulp = require('gulp'),\n connect = require('gulp-connect'),\n open = require(\"gulp-open\"),\n browserify = require('gulp-browserify'),\n concat = require('gulp-concat'),\n port = process.env.port || 3031;" }, { "alpha_fraction": 0.6741573214530945, "alphanum_fraction": 0.6778380274772644, "avg_line_length": 26.207651138305664, "blob_id": "82d2fc871571716784fccfe3ddd1f1c7687c21e5", "content_id": "e3056751a813e2cf82ca2ff2059ade616c1a954b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5162, "license_type": "no_license", "max_line_length": 221, "num_lines": 183, "path": "/Java/F21SF Soft E Fundation/Assignment 2/src/assignment_2/Bowler.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package assignment_2;\r\n\r\nimport java.util.Arrays;\r\n\r\n/**\r\n * This class is creating a bowling competitor object\r\n * @author Stian\r\n *\r\n */\r\n\r\npublic class Bowler extends Competitor\r\n{\r\n\tprivate String competitorLevel;\r\n\tprivate String competitorCountry;\r\n\t\r\n\t/**\r\n\t * This constructor creates a bowler object based on the following parameters\r\n\t * @param competitorNumber the competitor number for the bowler\r\n\t * @param competitorName store name of competitor\r\n\t * @param listOfScores the list of scores for the bowler\r\n\t * @param competitorLevel the skill level of the bowler\r\n\t * @param competitorCountry the country where the bowler is from\r\n\t */\r\n\tpublic Bowler(int id, Name competitorName, int[] listOfScores, String competitorLevel, String competitorCountry)\r\n\t{\r\n\t\tsuper(id,competitorName,listOfScores);\r\n\t\tthis.competitorLevel = competitorLevel;\r\n\t\tthis.competitorCountry = competitorCountry;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns the competitor number of the bowler\r\n\t * @return competitor number\r\n\t */\r\n\tpublic int getCompetitorNumber()\r\n\t{\r\n\t\treturn CompetitorList.getUserInput();\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns the full name of the bowler\r\n\t * @return competitor name\r\n\t */\r\n\tpublic String getCompetitorName()\r\n\t{\r\n\t\treturn competitorName.getFullName();\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns the list of scores for the bowler\r\n\t * @return list of scores\r\n\t */\r\n\tpublic int[] getListOfScores()\r\n\t{\r\n\t\treturn listOfScores;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returning the overall score of the bowler, minus the highest and the lowest scores\r\n\t * @return the overall score\r\n\t */\r\n\tpublic double getOverallScore()\r\n\t{\r\n\t\tdouble overallScore = 0;\r\n\t\tint lengthMinusTwoElements;\r\n\t\t\r\n\t\t//Sorting the list so that the scores will go from the lowest to the highest \r\n\t\tArrays.sort(listOfScores);\r\n\t\t\r\n\t\t/* \r\n\t\t * Getting the total score of the array, but skipping the score at the first and last index.\r\n\t\t * As it is sorted in beforehand, it will then not count the lowest or the highest score.\r\n\t\t */\r\n\t\tfor(int i = 1; i < listOfScores.length-1; i++)\r\n\t\t{\r\n\t\t\toverallScore = overallScore + listOfScores[i];\r\n\t\t}\r\n\t\t\r\n\t\t/*\r\n\t\t * To get the average score of the elements, you have to divide the total scores with\r\n\t\t * the length of the list, but since I took away the lowest and the highest score,\r\n\t\t * the length should then be the length of the list minus 2\r\n\t\t */\r\n\t\tlengthMinusTwoElements = listOfScores.length-2;\r\n\t\toverallScore = overallScore/lengthMinusTwoElements;\r\n\t\t\r\n\t\t/*\r\n\t\t * Reformatting the value so that it only gives one decimal\r\n\t\t */\r\n\t\t//String overallScoreString = String.format(\"%.1f\", overallScore);\r\n\t\treturn overallScore;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns the skill level of the bowler\r\n\t * @return skill level\r\n\t */\r\n\tpublic String getCompetitorLevel()\r\n\t{\r\n\t\treturn competitorLevel;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns the country where the bowler is from\r\n\t * @return country\r\n\t */\r\n\tpublic String getCompetitorCountry()\r\n\t{\r\n\t\treturn competitorCountry;\r\n\t}\r\n\t\r\n\r\n\t/**\r\n\t * Setting a new skill level for the bowler. Accepted values are: Novice, Regular or Veteran. The values are case insensitive\r\n\t * @param competitorLevel new skill level\r\n\t */\r\n\tpublic void setCompetitorLevel(String competitorLevel)\r\n\t{\r\n\t\tif(competitorLevel.equalsIgnoreCase(\"Novice\") || competitorLevel.equalsIgnoreCase(\"Regular\") || competitorLevel.equalsIgnoreCase(\"Veteran\"))\r\n\t\t{\r\n\t\t\tthis.competitorLevel = competitorLevel;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Error: The level of the competitor must be either: Novice, Regular or Veteran\");\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Setting a new country for where the bowler is from\r\n\t * @param competitorCountry country\r\n\t */\r\n\tpublic void setCompetitorCountry(String competitorCountry)\r\n\t{\r\n\t\tthis.competitorCountry = competitorCountry;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns the full details for the bowler\r\n\t * @return full details\r\n\t */\r\n\tpublic String getFullDetails()\r\n\t{\r\n\t\tint competitorNumber= getId();\r\n\t\t\r\n\t\tString fullDetails = \"Full details for \" + competitorNumber + \":\\nCompetitor #\" + competitorNumber + \" is \" + competitorName.getFullName() + \".\\n\" +\r\n\t\t\t\tcompetitorName.getFullName() + \" is a \" + competitorLevel.toLowerCase() + \" from \" + competitorCountry + \", and received these scores: \" + Arrays.toString(getListOfScores()).replace(\"[\", \"\").replace(\"]\", \"\") + \".\\n\" +\r\n\t\t\t\t\"This gives an overall score of \" + String.format(\"%.1f\", getOverallScore());\r\n\t\treturn fullDetails;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns the short details for the bowler\r\n\t * @return short details\r\n\t */\r\n\tpublic String getShortDetails()\r\n\t{\r\n\t\tString shortDetails = \"Short details for \" + getId() + \":\\nCN \" + getId() + \" (\" + competitorName.getShortName() + \") has overall score \" + String.format(\"%.1f\", getOverallScore());\r\n\t\treturn shortDetails;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Returns a list of details for the bowler\r\n\t * @return list of details\r\n\t */\r\n\tpublic String getDetailsList()\r\n\t{\r\n\t\tString detailsList = String.format(\"%-5s%-30s%-20s%-15s%-20s%s\", getId(),competitorName.getFullName(),\r\n\t\t\t\tcompetitorCountry,competitorLevel,Arrays.toString(getListOfScores()).replace(\"[\", \"\").replace(\"]\", \"\"), String.format(\"%.1f\", getOverallScore()));\r\n\t\treturn detailsList;\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6094104051589966, "alphanum_fraction": 0.6746031641960144, "avg_line_length": 28.912281036376953, "blob_id": "c1e746426efa74ac1f484dab19efd67b705bfbe4", "content_id": "383940b3915ee3208f43a8ec19e139aac22a7015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1764, "license_type": "no_license", "max_line_length": 155, "num_lines": 57, "path": "/Java/F21SF Soft E Fundation/Accounts/src/AccMain.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\r\npublic class AccMain \r\n{\r\npublic static void main (String[] args)\r\n\t{\t\r\n\t//Create three different accounts\r\n\tAcc Acc1= new Acc(\"023456\",1030.21,2000.234);\r\n\tAcc Acc2= new Acc(\"034567\",2010342.12322,7653);\r\n\tAcc Acc3= new Acc(\"872671\",4000.12,1000);\r\n\r\n\t//Get accounts numbers\r\n\tString numberAcc1=Acc1.getAccount();\r\n\tString numberAcc2=Acc2.getAccount();\r\n\tString numberAcc3=Acc3.getAccount();\r\n\t\r\n\t//get balance for accounts\r\n\tdouble balanceAcc1=Acc1.getBalance();\r\n\tdouble balanceAcc2=Acc2.getBalance();\r\n\tdouble balanceAcc3=Acc3.getBalance();\r\n\t\r\n\t//get overdrafts limits\r\n\tdouble overAcc1=Acc1.getOver();\r\n\tdouble overAcc2=Acc2.getOver();\r\n\tdouble overAcc3=Acc3.getOver();\r\n\t\r\n\t//get maximum available amount\r\n\tdouble maxAcc1=Acc1.getMax();\r\n\tdouble maxAcc2=Acc2.getMax();\r\n\tdouble maxAcc3=Acc3.getMax();\r\n\t\r\n\t// do some printing\r\n\tSystem.out.println(\" Account 1 \" + numberAcc1 + \" Have Balance \" + balanceAcc1 + \" With overdraft \"+ overAcc1 + \" Maximum amount avaible is \" + maxAcc1);\r\n\tSystem.out.println(\" Account 2 \" + numberAcc2 + \" Have Balance \" + balanceAcc2 + \" With overdraft \"+ overAcc2 + \" Maximum amount avaible is \" + maxAcc2);\r\n\tSystem.out.println(\" Account 3 \" + numberAcc3 + \" Have Balance \" + balanceAcc3 + \" With overdraft \"+ overAcc3 + \" Maximum amount avaible is \" + maxAcc3);\r\n\t\r\n\t// find \"richest\"\r\n\tint select;\r\n\tif (maxAcc1>maxAcc2 & maxAcc1>maxAcc3)\r\n\t\t{\r\n\t\tselect=1; \r\n\t\t}\r\n\t\telse if (maxAcc2>maxAcc3 & maxAcc2>maxAcc1) \r\n\t\t{\r\n\t\tselect=2;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\tselect=3;\r\n\t\t}\r\n\tSystem.out.println(\"Account \" + select+ \" Have bigest possible capital\");\r\n\t\r\n\t//New balance for rich guy\r\n\t balanceAcc2=Acc2.setnewBalance();\r\n\t System.out.println(\" Account 2 \" + numberAcc2 + \" Have new better Balance \" + balanceAcc2);\r\n\t\r\n\t\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6441964507102966, "alphanum_fraction": 0.6450892686843872, "avg_line_length": 20.420000076293945, "blob_id": "44513d9ac86c49eba72865c353b6ee8d0f30363f", "content_id": "900b0bb2b5c6b8de9a25b8c3f76dcb9b6b0aa3f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2240, "license_type": "no_license", "max_line_length": 157, "num_lines": 100, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orders/DishOrder.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orders;\r\n\r\n\r\n/**This Subclass of Dish class is representing dish orders.\r\n * Class have also methods specific only for DishOrder\r\n * Naming convention could be better, but specification was already done\r\n * @author Marcin Kopacz\r\n *\r\n */\r\npublic class DishOrder extends Dish {\r\n\tprivate int tableID;\r\n\tprivate int quantity;\r\n\tprivate Integer orderSequence;\r\n\r\n\r\n\t/**Constructor for DishOrder object throw exception if params are invalid\r\n\t * \r\n\t * @param dishName - name of dish\r\n\t * @param tableID - integer : id of table \r\n\t * @param quantity - number of dishes in one order\r\n\t * @param orderSequence - sequence number of order\r\n\t */\r\n\tpublic DishOrder(int tableID, String dishName, int quantity, int orderSequence)\r\n\t{\r\n\t\tsuper(dishName);\r\n\t\tif(tableID <=0)\r\n {\r\n\t throw new IllegalStateException(\r\n\t \"table id is invalid\");\r\n\t \r\n }\r\n\t\tif(quantity <=0)\r\n {\r\n\t throw new IllegalStateException(\r\n\t \"quantity is invalid\");\r\n\t \r\n }\t\r\n\t\tthis.tableID = tableID;\r\n\t\tthis.quantity = quantity;\r\n\t\tthis.orderSequence =orderSequence;\r\n\r\n\t}\r\n\r\n\r\n\r\n\t/**Compare two DishOrder object and test for equality\r\n\t * \r\n\t * @param other object with is DishOrder \r\n\t * @return true if objects are equal otherwise false\r\n\t */\r\n\tpublic boolean equals(Dish other) \r\n\t{\r\n\t\tif(other instanceof DishOrder)\r\n\t\t{\r\n\t\t\tDishOrder otherOrder = (DishOrder) other;\r\n\t\t\tif (dishName.equals(otherOrder.dishName) && orderSequence == otherOrder.orderSequence && tableID == otherOrder.tableID && quantity == otherOrder.quantity)\r\n\t\t\t{\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\t\r\n\t/**Return tableID of DishOrder object\r\n\t * @return tableID \r\n\t */\r\n\tpublic int getTableID() \r\n\t{\r\n\t\treturn this.tableID;\r\n\t}\r\n\r\n\r\n\t/**Return quantity of DishOrder object\r\n\t * @return quantity\r\n\t */\r\n\tpublic int getQuantity() \r\n\t{\r\n\t\treturn this.quantity;\r\n\t}\r\n\r\n\t/**hasCode function on orderSequence\r\n\t * This create index to access elements in HashSet\r\n\t */\r\n\tpublic int hashCode() \r\n\t{\r\n\t\treturn orderSequence.hashCode();\r\n\t}\r\n\t\r\n\t\r\n\t/**Return orderSequence of DishOrder object\r\n\t * @return orderSequence\r\n\t */\r\n\tpublic int getOrderSequence()\r\n\t{\r\n\t\treturn this.orderSequence;\r\n\t}\r\n\t\r\n\t\r\n}" }, { "alpha_fraction": 0.5626733899116516, "alphanum_fraction": 0.5750046372413635, "avg_line_length": 37.433650970458984, "blob_id": "6b122a2f79038b3bffb03d909dc005242949a8db", "content_id": "ea101f411c42399ab7a79842d8c9e6e525046c4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 16221, "license_type": "no_license", "max_line_length": 125, "num_lines": 422, "path": "/CSharp/coursework/MarcinK mpk31/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/views/Browser.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.Windows.Forms;\nusing WebBrowser_OuterSpace.controllers;\nusing WebBrowser_OuterSpace.models;\n\nnamespace WebBrowser_OuterSpace\n{\n public partial class BrowserWindowMain : Form\n {\n \n /// <summary>\n /// Constructor for GUI with DI injection\n /// </summary>\n /// <param name=\"bc\"></param>\n /// <param name=\"hp\"></param>\n public BrowserWindowMain(BrowsingController bc, HomePageController hp, HistoryController hc, FavouritesController fc)\n {\n //start gui elements\n InitializeComponent();\n\n //inject controllers\n this.browsingController = bc;\n this.homePageController = hp;\n this.historyController = hc;\n this.favouritiesController = fc;\n }\n /// <summary>\n /// Startyp function for setting a homepage on form initialisation\n /// </summary>\n public void startAtHomePage()\n {\n string urlAdress = homePageController.getHomePageURL();\n String[] response = browsingController.getWebPage(currentTabSelected, urlAdress);\n activeTab = browserTab_0;\n\n inputTextURL.Text = urlAdress;\n outputTextHTML.Text = response[1];\n outputResMessege.Text = response[0];\n browserTab_0.Text = urlAdress;\n }\n\n /// <summary>\n /// Handler for \"Go\" button, send http request\n /// Also call function to create record in hostory each time\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n public void submitBtnURL_Click(object sender, EventArgs e)\n {\n string urlAdress = inputTextURL.Text;\n String[] response = browsingController.getWebPage(currentTabSelected, urlAdress);\n \n outputTextHTML.Text = response[1];\n outputResMessege.Text = response[0];\n activeTab.Text = urlAdress;\n\n historyController.recordHistory(urlAdress, currentTabSelected);\n }\n\n /// <summary>\n /// Handler for clicking into buttons representing tabs in browser\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n public void tab_Click(object sender, EventArgs e)\n {\n\n activeTab = (Button)sender;\n string[] currentTabNames = activeTab.Name.Split('_');\n currentTabSelected = Convert.ToInt32(currentTabNames[1]);\n\n string urlAdress = homePageController.getHomePageURL();\n String[] response = browsingController.getTabContent(currentTabSelected, urlAdress);\n\n outputTextHTML.Text = response[1];\n outputResMessege.Text = response[0];\n inputTextURL.Text = response[2];\n activeTab.Text = response[2];\n }\n\n /// <summary>\n /// I when Wind is load get homepage\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void BrowserWindowMain_Load(object sender, EventArgs e)\n {\n startAtHomePage();\n }\n\n /// <summary>\n /// handler for Button that Add new Tabs in Browser\n /// Maximum number of tabs 25. layout willl fall apart sooner\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void addBtnTab_Click(object sender, EventArgs e)\n {\n if (numberOfTabs < 25) { \n Button newTabButton = new Button();\n newTabButton.Location = new System.Drawing.Point(30 + numberOfTabs * 140, 65);\n newTabButton.Name = \"browserTab_\" + numberOfTabs.ToString();\n newTabButton.Size = new System.Drawing.Size(150, 25);\n newTabButton.TabIndex = 15 + numberOfTabs;\n newTabButton.Text = \"New Tab\";\n newTabButton.UseVisualStyleBackColor = true;\n newTabButton.Click += new System.EventHandler(this.tab_Click);\n tabButtonsList.Add(newTabButton);\n\n browsingController.createNewTab(homePageController.getHomePageURL());\n\n this.Controls.Add(newTabButton);\n\n numberOfTabs++;\n }\n else\n {\n outputResMessege.Text = \"Maximum number of Tabs (25) reached\";\n }\n\n }\n\n /// <summary>\n /// I will Probalny not use this\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void tabPanel_Paint(object sender, PaintEventArgs e)\n {\n\n }\n\n /// <summary>\n /// Create a new Form with controls to change HomePage settings\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void homebtnSettings_Click(object sender, EventArgs e)\n {\n var homePageSettings = new Form();\n homePageSettings.Height = 200;\n homePageSettings.Width = 500;\n\n //Create confirm button\n changeHomePage = new Button();\n changeHomePage.Location = new System.Drawing.Point(30 + 140, 65);\n changeHomePage.Name = \"changebtnHomePage\";\n changeHomePage.Size = new System.Drawing.Size(150, 25);\n changeHomePage.TabIndex = 20;\n changeHomePage.Text = \"Change HomePage\";\n changeHomePage.UseVisualStyleBackColor = true;\n changeHomePage.Click += new System.EventHandler(this.changeHomePage_Click);\n\n //Create input field\n inputURL = new TextBox();\n inputURL.Location = new System.Drawing.Point(24, 15);\n inputURL.Name = \"inputTextURL\";\n inputURL.Size = new System.Drawing.Size(450, 20);\n inputURL.TabIndex = 23;\n inputURL.Text = homePageController.getHomePageURL();\n\n\n homePageSettings.Controls.Add(changeHomePage);\n homePageSettings.Controls.Add(inputURL);\n\n homePageSettings.Show();\n }\n\n /// <summary>\n /// Handler of change home page button\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void changeHomePage_Click(object sender, EventArgs e)\n {\n homePageController.setHomePage(inputURL.Text);\n \n }\n\n /// <summary>\n /// Handler for button Prev, \n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void prevBtnHistoryPrev_Click(object sender, EventArgs e)\n {\n int deepness = (int) deepnessPerTab[currentTabSelected] -1;\n deepnessPerTab.Insert(currentTabSelected, deepness);\n\n String prevURL = historyController.getHistoryPageURL(currentTabSelected, deepness);\n String[] response = browsingController.getWebPage(currentTabSelected, prevURL);\n\n outputTextHTML.Text = response[1];\n outputResMessege.Text = response[0]+ \" History: ;\" + deepness.ToString();\n activeTab.Text = prevURL;\n inputTextURL.Text = prevURL;\n }\n\n /// <summary>\n /// handler for button Next\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void historyBtnNext_Click(object sender, EventArgs e)\n {\n int deepness = (int)deepnessPerTab[currentTabSelected] + 1;\n deepnessPerTab.Insert(currentTabSelected, deepness);\n\n String nextURL = historyController.getHistoryPageURL(currentTabSelected, deepness);\n String[] response = browsingController.getWebPage(currentTabSelected, nextURL);\n\n outputTextHTML.Text = response[1];\n outputResMessege.Text = response[0] + \" History: ;\" + deepness.ToString();\n activeTab.Text = nextURL;\n inputTextURL.Text = nextURL;\n }\n\n /// <summary>\n /// Handeler for history btn\n /// Build Up a Panel with button links\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void historyBtn_Click(object sender, EventArgs e)\n {\n ArrayList historyTotal = (ArrayList) historyController.getHistory();\n int xCounter = 1;\n var historyList = new Form();\n historyList.Height = 1000;\n historyList.Width = 300;\n\n foreach (var singleLink in historyTotal)\n {\n Button newTabButton = new Button();\n\n newTabButton.Location = new System.Drawing.Point(25 , xCounter*30);\n newTabButton.Name = \"historyTab_\" + xCounter.ToString();\n newTabButton.Size = new System.Drawing.Size(250, 25);\n newTabButton.TabIndex = 15 + numberOfTabs;\n newTabButton.Text = (string)singleLink;\n newTabButton.UseVisualStyleBackColor = true;\n newTabButton.Click += new System.EventHandler(this.historyLink_Click);\n tabButtonsList.Add(newTabButton);\n\n browsingController.createNewTab(homePageController.getHomePageURL());\n\n historyList.Controls.Add(newTabButton);\n xCounter++;\n }\n historyList.Show();\n }\n /// <summary>\n /// Handler for button in History Panel\n /// Open URl in active tab\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void historyLink_Click(object sender, EventArgs e)\n {\n Button activatedLink = (Button)sender;\n\n String url = activatedLink.Text;\n String[] response = browsingController.getWebPage(currentTabSelected, url);\n\n inputTextURL.Text = url;\n outputTextHTML.Text = response[1];\n outputResMessege.Text = response[0];\n activeTab.Text = url;\n\n historyController.recordHistory(url, currentTabSelected);\n }\n /// <summary>\n /// Create form on favourities btn click\n /// Privide Options to edit or change elemets\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void favouritiesBtn_Click(object sender, EventArgs e)\n {\n ArrayList favouritiesList = (ArrayList) favouritiesController.getFavouritesList();\n\n //Create Form\n var favouritiesForm = new Form();\n favouritiesForm.Height = 1000;\n favouritiesForm.Width = 550;\n\n inputNameFav = new TextBox();\n inputNameFav.Location = new System.Drawing.Point(24, 15);\n inputNameFav.Name = \"inputTextName\";\n inputNameFav.Size = new System.Drawing.Size(120, 25);\n inputNameFav.TabIndex = 161;\n inputNameFav.Text = \"Choose Name\";\n favouritiesForm.Controls.Add(inputNameFav);\n\n //Add Fav Input forURL\n inputURLFav = new TextBox();\n inputURLFav.Location = new System.Drawing.Point(150, 15);\n inputURLFav.Name = \"inputTextURL\";\n inputURLFav.Size = new System.Drawing.Size(250, 25);\n inputURLFav.TabIndex = 162;\n inputURLFav.Text = \"Provide URL\";\n favouritiesForm.Controls.Add(inputURLFav);\n\n //Add Button\n addButtonFav = new Button();\n addButtonFav.Location = new System.Drawing.Point(410, 14);\n addButtonFav.Name = \"addBtnFav\";\n addButtonFav.Size = new System.Drawing.Size(50, 25);\n addButtonFav.TabIndex = 15 + numberOfTabs;\n addButtonFav.Text = \"ADD\";\n addButtonFav.UseVisualStyleBackColor = true;\n addButtonFav.Click += new System.EventHandler(this.addBtnFav_Click);\n favouritiesForm.Controls.Add(addButtonFav);\n\n\n int xCounter = 0;\n foreach (string[] favorite in favouritiesList)\n {\n\n TextBox inputNameUP = new TextBox();\n inputNameUP.Location = new System.Drawing.Point(24, 45 + xCounter * 30);\n inputNameUP.Name = \"inputTextURL_\" + xCounter.ToString();\n inputNameUP.Size = new System.Drawing.Size(120, 25);\n inputNameUP.TabIndex = 161;\n inputNameUP.Text = favorite[0];\n inputNameUpList.Add(inputNameUP);\n\n //Add Fav Input forURL\n TextBox inputURLFavUP = new TextBox();\n inputURLFavUP.Location = new System.Drawing.Point(150, 45 + xCounter * 30);\n inputURLFavUP.Name = \"inputTextURL_\" + xCounter.ToString();\n inputURLFavUP.Size = new System.Drawing.Size(250, 25);\n inputURLFavUP.TabIndex = 162;\n inputURLFavUP.Text = favorite[1];\n inputURLFavUPList.Add(inputURLFavUP);\n\n //Add Button\n Button addButtonUP = new Button();\n addButtonUP.Location = new System.Drawing.Point(410, 45 + xCounter * 30);\n addButtonUP.Name = \"addBtnFav_\"+ xCounter.ToString();\n addButtonUP.Size = new System.Drawing.Size(50, 25);\n addButtonUP.TabIndex = 250 + numberOfTabs;\n addButtonUP.Text = \"Update\";\n addButtonUP.UseVisualStyleBackColor = true;\n addButtonUP.Click += new System.EventHandler(this.addBtnFavUP_Click);\n addButtonUPList.Add(addButtonUP);\n\n //Add Button\n Button remButton = new Button();\n remButton.Location = new System.Drawing.Point(470, 45 + xCounter * 30);\n remButton.Name = \"addBtnFav_\" + xCounter.ToString();\n remButton.Size = new System.Drawing.Size(50, 25);\n remButton.TabIndex = 250 + numberOfTabs;\n remButton.Text = \"Remove\";\n remButton.UseVisualStyleBackColor = true;\n remButton.Click += new System.EventHandler(this.addBtnFavRem_Click);\n remButtonList.Add(remButton);\n\n favouritiesForm.Controls.Add(inputNameUP);\n favouritiesForm.Controls.Add(inputURLFavUP);\n favouritiesForm.Controls.Add(addButtonUP);\n favouritiesForm.Controls.Add(remButton);\n\n\n xCounter++;\n\n\n }\n favouritiesForm.Show();\n }\n\n /// <summary>\n /// Updated choosen Fav\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void addBtnFavUP_Click(object sender, EventArgs e)\n { \n\n Button toUpdate = (Button)sender;\n string[] currentFav = toUpdate.Name.Split('_');\n int currentFavSelected = Convert.ToInt32(currentFav[1]);\n TextBox inputNameUP = inputNameUpList[currentFavSelected];\n TextBox inputURLFavUP = inputURLFavUPList[currentFavSelected];\n\n favouritiesController.updatefav(inputNameUP.Text, inputURLFavUP.Text, currentFavSelected);\n\n\n }\n\n /// <summary>\n /// Handler For Removing Things from fav list\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n Button toUpdate = new Button();\n private void addBtnFavRem_Click(object sender, EventArgs e)\n {\n toUpdate = (Button)sender;\n string[] currentFav = activeTab.Name.Split('_');\n int currentFavSelected = Convert.ToInt32(currentFav[1]);\n favouritiesController.removefav(currentFavSelected);\n }\n\n /// <summary>\n /// Handler for add favourite button\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void addBtnFav_Click(object sender, EventArgs e)\n {\n String name = inputNameFav.Text;\n String url = inputURLFav.Text;\n\n favouritiesController.createNewFav(name, url);\n\n\n }\n\n }\n}\n" }, { "alpha_fraction": 0.628947377204895, "alphanum_fraction": 0.6368421316146851, "avg_line_length": 20.352941513061523, "blob_id": "3cbc7296bcfd35e9100683756d955786d54af1dd", "content_id": "773657a9ba559b5d35222500fe0b98e708e6a0b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 380, "license_type": "no_license", "max_line_length": 78, "num_lines": 17, "path": "/Java/F21AS Advanced Software Engineering/Week 7 Threads 2/src/wait/Consumer.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "//http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html\r\npublic class Consumer implements Runnable {\r\n\tprivate SharedObject so;\r\n\t\r\n\tpublic Consumer (SharedObject so) {\r\n\t\tthis.so = so;\r\n\t}\r\n\t\r\n\tpublic void run() {\r\n\t\twhile(!so.getDone()) {\r\n\t\t\ttry { Thread.sleep(100); }\r\n\t\t\tcatch (InterruptedException e) {}\r\n\t\t\tint number = so.get();\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.554852306842804, "alphanum_fraction": 0.5611814260482788, "avg_line_length": 36.880001068115234, "blob_id": "662fa2a6a781587a0c05829cd5b76c18157d1550", "content_id": "f0c72ac9870303952a19af6c9f755125b239cd8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "no_license", "max_line_length": 86, "num_lines": 25, "path": "/Python/IndustrialProgramming/extra/test_regex.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Simple regular expression examples\n\nimport sys\nimport fileinput\nimport re\nimport string\n\n# print all lines with 'read' event types\nfile='/home/hwloidl/tmp/sample_10k_lines.json'\nprint (\"Reading from \", file)\nwith open(file,\"r\") as f:\n for line in f: # read line-by-line\n if (re.search('\"event_type\":\"read\"', line)): # search for string in line\n print (line) # if it exists, print entire line\n\n# as above, but split the line, and print one element per line\nfile='/home/hwloidl/tmp/sample_10k_lines.json'\nprint (\"Reading from \", file)\nwith open(file,\"r\") as f:\n for line in f:\n if (re.search('\"event_type\":\"read\"', line)):\n line0 = re.sub(\"[{}]\", \"\", line) # remove {}\n for x in re.split(\"[ ]*,[ ]*\",line0):# split ','-separated elements\n print (re.sub(':','->', x)) # replace ':' by '->'\n\n" }, { "alpha_fraction": 0.5443262457847595, "alphanum_fraction": 0.5620567202568054, "avg_line_length": 21.479999542236328, "blob_id": "b25caf1df78e0770a1d1ec287917e76f89548d6b", "content_id": "00e57cb275ce1b7c0c42417fac8b6b87b699aaef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 564, "license_type": "no_license", "max_line_length": 71, "num_lines": 25, "path": "/CSharp/code-examples/sys-programming/unsafe3.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// see: http://msdn.microsoft.com/en-us/library/chfa2zb8.aspx\n// in-place Swap\n\n// compile with: /unsafe\nusing System;\n\nclass UnsafeTest\n{\n // Unsafe method\n unsafe static void Swap(int* x, int *y) {\n int z = *x;\n *x = *y;\n *y = z;\n }\n\n unsafe static void Main() {\n int x = 5;\n int y = 7;\n // Unsafe method: it uses j\n Console.WriteLine(\"Before swap: x = {0}; y = {1}\", x, y);\n Swap(&x,&y); // passes pointers to the locations of the variables\n Console.WriteLine(\"After Swap: x = {0}; y = {1}\", x, y);\n }\n}\n// Output: 15\n\n\n" }, { "alpha_fraction": 0.5792136788368225, "alphanum_fraction": 0.5842740535736084, "avg_line_length": 27.030567169189453, "blob_id": "0fc7bdb52ada8b87c4c0778cdcae7c88af45a9c7", "content_id": "6ed2fcab98668cb27c37856b0824b994e4ed9f79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12845, "license_type": "no_license", "max_line_length": 156, "num_lines": 458, "path": "/CSharp/code-examples/parallel/ParTrees.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Extending the Binary Search Tree examples\n// to parallelism, using a divide-and-conquer paradigm.\n\nusing System;\nusing System.Collections;\n\n// exceptions used in either Tree or Node\nclass TreeException: System.Exception {\n public TreeException(string msg): base(msg) { }\n}\n\npublic class Node<T> // generic over type of value in each node\n where T:IComparable // T implements a CompareTo method\n{\n // Private member-variables\n private T data;\n private Node<T> left;\n private Node<T> right;\n\n // delegates used in this class\n public delegate T TreeMapperDelegate(T t);\n\n // constructors\n public Node() { this.Left = null; this.Right = null; }\n public Node(T x) { this.data = x; this.Left = null; this.Right = null; }\n public Node(T x, Node<T> left, Node<T> right) { this.data = x; this.Left = left; this.Right = right; }\n\n // properties accessing fields\n public T Value {\n get { return data; }\n set { data = value; }\n }\n\n public Node<T> Left {\n get { return this.left; }\n set { this.left = value; }\n }\n \n public Node<T> Right {\n get { return this.right; }\n set { this.right = value; }\n\n }\n\n // operations on Nodes\n public void Insert (T x) {\n if (this.Value.CompareTo(x) < 0) {\n\t if (this.Right == null) {\n\t this.Right = new Node<T>(x);\n\t } else {\n\t this.Right.Insert(x);\n\t }\n } else {\n\t if (this.Left == null) {\n\t this.Left = new Node<T>(x);\n\t } else {\n\t this.Left.Insert(x);\n\t }\n }\n }\n\n public bool Find (T x) {\n if (this.Value.CompareTo(x) == 0) {\n\t return true;\n } else if (this.Value.CompareTo(x) < 0) {\n\t if (this.Right == null) {\n\t return false;\n\t } else {\n\t return this.Right.Find(x);\n\t }\n } else {\n\t if (this.Left == null) {\n\t return false;\n\t } else {\n\t return this.Left.Find(x);\n\t }\n }\n }\n\n // higher-order functions over trees\n public void MapTree(TreeMapperDelegate f) {\n this.Value = f(this.Value);\n if (this.Left == null) { } else { this.Left.MapTree(f); } \n if (this.Right == null) { } else { this.Right.MapTree(f); }\n return;\n }\n\n // parallel version of the same higher-order function\n public void ParMapTree(TreeMapperDelegate f) {\n int i = 0;\n Task[] tasks = new Task[3];\n var t1, t2, t3;\n t1 = Task.Factory.StartNew(() => this.Value = f(tree.Value));\n tasks[i++] = t1;\n if (this.Left != null) { \n t2 = Task.Factory.StartNew(() => this.Left.ParMapTree(f));\n tasks[i++] = t2;\n }\n if (this.Right != null) { \n t3 = Task.Factory.StartNew(() => this.Right.ParMapTree(f));\n tasks[i++] = t3;\n }\n Task.WaitAll(tasks);\n }\n\n public override string ToString() {\n return this.ToStringIndent(0);\n }\n\n public string ToStringIndent(int n) {\n string str = \"\";\n for (int i = 0; i<n; i++) { str += \" \"; }\n return str + this.data.ToString() + \"\\n\" + \n ((this.Left == null) ? str+\" .\"+\"\\n\" : this.Left.ToStringIndent(n+1)) + \n ((this.Right == null) ? str+\" .\"+\"\\n\" : this.Right.ToStringIndent(n+1)) ;\n }\n}\n\npublic class Tree<T> where T:IComparable\n{\n private Node<T> root = null;\n\n public Tree() {\n root = null;\n }\n\n public virtual void Clear() {\n root = null;\n }\n\n public Node<T> Root {\n get { return root; }\n set { root = value; }\n }\n\n public void Insert(T x) {\n if (this.Root == null) {\n this.Root = new Node<T>(x);\n } else {\n this.Root.Insert(x);\n }\n }\n\n public bool Find (T x) {\n if (this.Root == null) {\n return false;\n } else {\n return this.Root.Find(x);\n }\n }\n\n // ToDo: implement the following method, which should be a class invariant\n // public bool WellFormedTree ( ) { ... }\n\n public override string ToString() {\n if (this.Root == null) {\n return \"<empty>\";\n } else {\n return this.Root.ToStringIndent(0);\n }\n }\n\n public void print (Fixity how) {\n IEnumerator iter;\n string str;\n switch (how) {\n case Fixity.Prefix: \n iter = new PrefixEnumerator(this);\n str = \"PrefixEnumerator\";\n break;\n case Fixity.Infix: \n iter = new InfixEnumerator(this);\n str = \"InfixEnumerator\";\n break;\n case Fixity.Postfix:\n iter = new PostfixEnumerator(this);\n str = \"PostfixEnumerator\";\n break;\n default:\n iter = new InfixEnumerator(this);\n str = \"InfixEnumerator\";\n break;\n }\n\n System.Console.Write(\"Flatten tree using \"+str+\" : [\"); \n if (iter.MoveNext()) {\n\tSystem.Console.Write(\"{0}\", iter.Current);\n }\n while (iter.MoveNext()) {\n\tSystem.Console.Write(\",{0}\", iter.Current);\n }\n System.Console.WriteLine(\"]\");\n\n /*\n System.Console.Write(\"Flatten tree using \"+str+\": \"); \n foreach (int x in this) { \n\tSystem.Console.Write(\" {0}\", x);\n }\n System.Console.WriteLine(\"\");\n */\n }\n\n // -------------------------------------------------------\n // IEnumerator implementation \n // This does a depth-first, pre-fix traversal of the tree\n // see http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx\n\n public enum Fixity { Prefix, Infix, Postfix };\n\n /*\n public IEnumerator GetEnumerator() { \n return (IEnumerator) new PrefixEnumerator(this);\n }\n */\n\n private class PrefixEnumerator : IEnumerator {\n private Node<T> curr_node;\n private Node<T> root; \n private Stack stack;\n public const string Name = \"PrefixEnumerator\";\n\n public PrefixEnumerator () {\n throw new TreeException(\"PrefixEnumerator: Missing argument to constructor\");\n }\n\n public PrefixEnumerator (Tree<T> t) {\n this.curr_node = null; // NB: needs to start with -1; \n this.root = t.root;\n this.stack = new Stack();\n }\n\n // go up in the tree, and find the next node\n private bool Unwind() {\n if (stack.Count == 0) { // we are done\n\tcurr_node = null;\n\treturn false;\n } else {\n\tNode<T> parent = (Node<T>)this.stack.Pop();\n\tif (parent.Left == curr_node) { // I am a left child\n\t if (parent.Right != null) { // and there is a right sub-tree\n\t stack.Push((object)parent);\n\t curr_node = parent.Right; // pick it as next\n\t } else {\n\t curr_node = parent; // otw, go one step up and unwind further\n\t return Unwind();\n\t }\n\t} else if (parent.Right == curr_node) { // I am a right child\n\t curr_node = parent; // otw, go one step up and unwind further\n\t return Unwind();\n\t} else {\n\t throw new TreeException(String.Format(\"Ill-formed spine during Unwind(): node {0} should be a parent of {1}\", parent.ToString(), curr_node.ToString()));\n\t}\n\treturn true;\n }\n }\n \n public bool MoveNext( ) {\n // both sub-trees haven't been traversed, yet\n if (this.curr_node==null) {\n\tthis.curr_node = this.root;\n\treturn true;\n } else {\n\tif (curr_node.Left!=null) { \n\t stack.Push((object)curr_node);\n\t this.curr_node = curr_node.Left;\n\t return true;\n\t} else if (curr_node.Right!=null) { \n\t stack.Push((object)curr_node);\n\t this.curr_node = curr_node.Right;\n\t return true;\n\t} else { // I am a leaf\n\t return (Unwind());\n\t }\n }\n }\n\n public void Reset( ) {\n this.curr_node = null;\n }\n\n public object Current {\n get { return this.curr_node.Value ; } \n }\n }\n // -------------------------------------------------------\n // IEnumerator implementation \n // This does a depth-first, in-fix traversal of the tree\n // see http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx\n\n public IEnumerator GetEnumerator() { \n return (IEnumerator) new InfixEnumerator(this);\n }\n\n private class InfixEnumerator : IEnumerator {\n private Node<T> curr_node;\n private Node<T> root; \n private Stack stack;\n public const string Name = \"InfixEnumerator\";\n\n public InfixEnumerator () {\n throw new TreeException(\"InfixEnumerator: Missing argument to constructor\");\n }\n\n public InfixEnumerator (Tree<T> t) {\n this.curr_node = null; // NB: needs to start with -1; \n this.root = t.root;\n this.stack = new Stack();\n }\n\n // go up in the tree, and find the next node\n private bool Unwind() {\n if (stack.Count == 0) { // we are done\n\tcurr_node = null;\n\treturn false;\n } else {\n\tNode<T> parent = (Node<T>)this.stack.Pop();\n\tif (parent.Left == curr_node) { // I am a left child\n\t curr_node = parent;\n\t return true;\n\t} else {\n\t curr_node = parent; // otw, go one step up and unwind further\n\t return (Unwind());\n\t}\n }\n }\n \n // go down to left-most node in this tree\n private void LeftMost(Node<T> node) {\n if (node.Left!=null) { \n\tstack.Push((object)node);\n\tLeftMost(node.Left);\n } else {\n\tstack.Push((object)node);\n\treturn;\n }\n }\n\n private bool EnterTree(Node<T> node) {\n // need to traverse both sub-trees\n LeftMost(node); // fills stack\n if (stack.Count == 0) {\n\treturn false;\n } else {\n\tcurr_node = (Node<T>) stack.Pop();\n\treturn true;\n }\n }\n\n public bool MoveNext( ) {\n if (this.curr_node==null) {\n\treturn (EnterTree(this.root));\n } else {\n\t// left sub-tree has been processed\n\tif (curr_node.Right!=null) { \n\t stack.Push((object)curr_node);\n\t return (EnterTree(curr_node.Right));\n\t} else { // I am a leaf\n\t return (Unwind());\n\t}\n }\n }\n\n public void Reset( ) {\n this.curr_node = null;\n }\n\n public object Current {\n get { return this.curr_node.Value ; } \n }\n }\n\n private class PostfixEnumerator : IEnumerator {\n private Node<T> curr_node;\n private Node<T> root; \n private Stack stack;\n public const string Name = \"PostfixEnumerator\";\n\n public PostfixEnumerator () {\n throw new TreeException(\"PostfixEnumerator: Missing argument to constructor\");\n }\n public PostfixEnumerator (Tree<T> t) {\n throw new TreeException(\"PostfixEnumerator: Not implemented\");\n }\n\n public bool MoveNext( ) {\n throw new TreeException(\"PostfixEnumerator: Not implemented\");\n }\n\n public void Reset( ) {\n throw new TreeException(\"PostfixEnumerator: Not implemented\");\n }\n\n public object Current {\n get { throw new TreeException(\"PostfixEnumerator: Not implemented\"); }\n\n }\n }\n}\n\npublic class Tester {\n\n private static int inc (int i) { return i+1; }\n\n public static void Main(string[] args) {\n int i;\n Tree<int> t = new Tree<int>();\n\n if (args.Length < 1) {\n System.Console.WriteLine(\"Provide int values to add to the tree on the command line ...\");\n } else {\n // build tree ...\n // ToDo: use exceptions to catch non-int values\n foreach (string s in args) {\n\ti = Convert.ToInt32(s); // int.Parse(s);\n\tSystem.Console.WriteLine(\"inserting {0} ...\", i);\n\tt.Insert(i);\n }\n // test Find ...\n System.Console.WriteLine(\"Having added all arguments into the tree it looks like this:\\n{0}\", t.ToString());\n int[] xs = { 0, 5, 7, 9, 99 };\n foreach (int x in xs) { \n\tSystem.Console.WriteLine(\"Finding value {0} in tree: {1}\", x, t.Find(x));\n }\n // test Insert ... \n int z = 5;\n System.Console.WriteLine(\"inserting {0} ...\", z);\n t.Insert(5);\n System.Console.WriteLine(\"After inserting {0} the new tree looks like this:\\n{1}\", z, t.ToString());\n foreach (int x in xs) { \n\tSystem.Console.WriteLine(\"Finding value {0} in tree: {1}\", x, t.Find(x));\n }\n // test delegates ... \n System.Console.WriteLine(\"Testing MapTree on above int tree, increasing each element by 1 ...\");\n Node<int>.TreeMapperDelegate f = new Node<int>.TreeMapperDelegate(Tester.inc);\n t.Root.MapTree(f);\n System.Console.WriteLine(\"{0}\", t.ToString());\n // same thing again, shorter\n System.Console.WriteLine(\"Again, testing MapTree on above int tree, increasing each element by 1 (using lambda expression)...\");\n t.Root.MapTree(new Node<int>.TreeMapperDelegate((int j) => { return j+1 ; }));\n System.Console.WriteLine(\"{0}\", t.ToString());\n // and yet again, now in parallel\n System.Console.WriteLine(\"Again, but now in parallel, increasing each element by 1 (using lambda expression)...\");\n t.Root.ParMapTree(new Node<int>.TreeMapperDelegate((int j) => { return j+1 ; }));\n System.Console.WriteLine(\"{0}\", t.ToString());\n\n // use different iterators to print the tree\n System.Array arrFix = System.Enum.GetValues (Tree<int>.Fixity.Infix.GetType());\n foreach (Tree<int>.Fixity fix in arrFix) {\n\ttry {\n\t t.print(fix); // eg.: t.print(Tree<int>.Fixity.Infix);\n\t} catch (TreeException e) {\n\t System.Console.WriteLine(\"print failed, using a {0} traversal\", fix.ToString());\n\t System.Console.WriteLine(e.Message);\n\t}\n }\n }\n }\n}\n\n " }, { "alpha_fraction": 0.5787037014961243, "alphanum_fraction": 0.5787037014961243, "avg_line_length": 24.069766998291016, "blob_id": "7db35822ea50b29ad58c0edcf2bbcb4ee027b861", "content_id": "db340b6937270f4ef40dd50f2dd44b9ed88ff885", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1080, "license_type": "no_license", "max_line_length": 73, "num_lines": 43, "path": "/Interviews/jp_morgan/call_billing/src/call/call.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\nclass Call(object):\n\n \"\"\"Call class\"\"\"\n\n def __init__(self, type, call_duration, is_international, client_id):\n self.__call_type = type\n self.__call_duration = call_duration\n self.__is_international = is_international\n self.__client_id = client_id\n\n def __str__(self):\n \"\"\"str method\"\"\"\n\n strText = \\\n \" Type: \" + str(self.call_type) + \\\n \" Duration: \" + str(self.call_duration) + \\\n \" is_international: \" + str(self.is_international)\n\n return strText\n\n @property\n def call_type(self):\n return self.__call_type\n\n @call_type.setter\n def call_type(self, value):\n self.__call_type = value\n\n @property\n def call_duration(self):\n return self.__call_duration\n\n @call_duration.setter\n def call_duration(self, value):\n self.__call_duration = value\n\n @property\n def is_international(self):\n return self.__is_international\n\n @is_international.setter\n def is_international(self, value):\n self.__is_international = value\n" }, { "alpha_fraction": 0.6763485670089722, "alphanum_fraction": 0.6887966990470886, "avg_line_length": 25.88888931274414, "blob_id": "e14a8382d309cb082f80b672e28a7a5e41883bd4", "content_id": "8f8f0960b808667ea567b02c2b3ae55037bd385a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 241, "license_type": "no_license", "max_line_length": 60, "num_lines": 9, "path": "/Mongo/Week1/hello_word/app.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "var http = require('http');\n\nvar server = http.createServer(function (request, reposnse){\n\t\tresponse.writeHead(200, {\"Content-Type\" : \"text/plain\"});\n\t\tresponse.end(\"Hello Worls\");\n});\n\n\nserver.listen(port, [hostname], [backlog], [callback])" }, { "alpha_fraction": 0.7180094718933105, "alphanum_fraction": 0.7180094718933105, "avg_line_length": 23.836734771728516, "blob_id": "316e2bb9311da9f6f657b959ed38e1c2f9597259", "content_id": "b027c38e43d34103a0ad466b5470fcb864d632d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1266, "license_type": "no_license", "max_line_length": 115, "num_lines": 49, "path": "/Java/F21SF Soft E Fundation/Assignment 1/src/CompetitionManager.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import java.util.InputMismatchException;\r\nimport java.util.Scanner;\r\n\r\n\r\npublic class CompetitionManager\r\n{\r\n\r\nprivate CompetitorList allCompetitors;\r\n\t\r\n\tpublic CompetitionManager()\r\n\t{\r\n\tallCompetitors = new CompetitorList();\r\n\t\r\n\t}\r\n\t\r\n\tpublic void run()\r\n\t{\r\n\t\r\n\t\t \r\n\tallCompetitors.readFile(\"InputData.csv\");\r\n\tString report = allCompetitors.getAllCompetitors();\r\n\tString single = allCompetitors.getSingleCompetitor(); \r\n\tString shorty = allCompetitors.getShortDetails();\r\n\tString winner = allCompetitors.getWinner();\r\n\tString county = allCompetitors.getCountOfTeams();\r\n\tString maxiPub = allCompetitors.getMaxPub();\r\n\tString reportArt = allCompetitors.getMaxPubFrequencyReport();\r\n\tString averegeLvl =allCompetitors.getAveregeLvl();\r\n\tallCompetitors.writeToFile(\"OutputData.txt\", report + single + shorty+winner+county+maxiPub+reportArt+averegeLvl);\r\n\t//allCompetitors.writeToFile(\"OutputData.txt\", single);\r\n\t}\r\n\t\r\n\t//let user select number of competitor\r\n\tpublic static int readIntValue() throws InputMismatchException\r\n\t{\r\n\t @SuppressWarnings(\"resource\")\r\n\t\tScanner in = new Scanner(System.in); \r\n\t int integer;\r\n\t System.out.println(\"Enter an integer value: \");\r\n\t integer = in.nextInt();\r\n\t \r\n\t return integer;\r\n\t \r\n\t}\r\n\t\r\n\t\r\n\t\r\n\t\r\n}\r\n" }, { "alpha_fraction": 0.3295218348503113, "alphanum_fraction": 0.40748441219329834, "avg_line_length": 16.490909576416016, "blob_id": "b16ff6b14799d66c959fb1ac0dd8f9e5b48983f0", "content_id": "91faefc62c0efaa0dcd710f2e50e1435cc048e06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 74, "num_lines": 55, "path": "/Interviews/amazon/number_of_countruies.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "A = [[[] for i in range(1, 4)] for i in range(1, 8)]\n\nA[0][0] = 5\nA[0][1] = 4\nA[0][2] = 4\nA[1][0] = 4\nA[1][1] = 3\nA[1][2] = 4\nA[2][0] = 3\nA[2][1] = 2\nA[2][2] = 4\nA[3][0] = 2\nA[3][1] = 2\nA[3][2] = 2\nA[4][0] = 3\nA[4][1] = 3\nA[4][2] = 4\nA[5][0] = 1\nA[5][1] = 4\nA[5][2] = 4\nA[6][0] = 4\nA[6][1] = 1\nA[6][2] = 1\n\n\ndef solution(A):\n countries_color = {}\n\n N = len(A)\n M = len(A[0])\n\n for i in range(0, N):\n for j in range(0, M):\n\n if A[i][j] in countries_color:\n\n for by_colour in countries_color[A[i][j]]:\n for countries_point in by_colour:\n\n if countries_point[0] is i:\n if countries_point[1] is ((j + 1) or (j - 1)):\n\n else:\n\n if countries_point[1] is j:\n\n else:\n countries_color[A[i][j]] = [[(i, j)]]\n\n for countries_color\n return len(countries)\n\n pass\n\nsolution(A)\n" }, { "alpha_fraction": 0.5550172924995422, "alphanum_fraction": 0.5633218288421631, "avg_line_length": 24.803571701049805, "blob_id": "b98da7064137e4832715e404f328e2f2cc9b2799", "content_id": "d2497d810caabc70722829b2a6f91845b522bd60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 79, "num_lines": 56, "path": "/Python/Excercises/binary_search_tree.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# A binary search tree (BST) or ordered binary tree is a node-based binary\n# tree data structure which has the following properties:\n\n# Left subtree of a node contains only nodes with keys less than the nodes key.\n# Right subtree of a node cont only nodes with keys greater than the nodes key.\n# Both the left and right subtrees must also be binary search trees.\n\n\nclass Node:\n\n def __init__(self, data):\n \"\"\"\n Node Constructor\n \"\"\"\n self.left = None\n self.right = None\n self.data = data\n\n def insert(self, data):\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n elif data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n\n def in_order_print(self):\n if self.left:\n print(\"going into left:\", self.left.data)\n self.left.in_order_print()\n\n print(self.data)\n\n if self.right:\n print(\"going into right:\", self.right.data)\n self.right.in_order_print()\n\n\nroot = Node(8)\nroot.insert(3)\nroot.insert(10)\nroot.insert(1)\nroot.insert(6)\nroot.insert(4)\nroot.insert(7)\nroot.insert(14)\nroot.insert(13)\n\nroot.in_order_print()\n" }, { "alpha_fraction": 0.6200717091560364, "alphanum_fraction": 0.6236559152603149, "avg_line_length": 20.461538314819336, "blob_id": "2a0f4a84112d76d9b897de132a508a5bd7622317", "content_id": "5b627c51059d53b6a9613effd2ecd76a1d6b5150", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 69, "num_lines": 13, "path": "/Python/IndustrialProgramming/advanced/exc2.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Show number of lines for each file given as a command line argument\n\nimport sys\n\nfor arg in sys.argv[1:]:\n try:\n f = open(arg, 'r')\n except IOError:\n print ('cannot open', arg)\n else:\n print (arg, 'has', len(f.readlines()), 'lines')\n f.close()\n" }, { "alpha_fraction": 0.5619546175003052, "alphanum_fraction": 0.5619546175003052, "avg_line_length": 18.758621215820312, "blob_id": "b1d17fa235811643e627dca28691de6d97fc866b", "content_id": "ac60a5d8609efc92dde3da6ab31be569097d148d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 63, "num_lines": 29, "path": "/Interviews/jp_morgan/stack/src/stack.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "class Stack:\n\n def __init__(self):\n self.items = []\n\n def is_empty(self):\n return self.items == []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n if self.is_empty():\n raise EmptyStackError()\n return self.items.pop()\n\n def size(self):\n return len(self.items)\n\n def __str__(self):\n return str(self.items)\n\n\nclass EmptyStackError(Exception):\n\n def __init__(self):\n\n # Call the base Exception constructor\n super(EmptyStackError, self).__init__('Stack is empty')\n" }, { "alpha_fraction": 0.5541125535964966, "alphanum_fraction": 0.5627705454826355, "avg_line_length": 22.89655113220215, "blob_id": "3fd6a606d6401e8de42f76db9836b96100f2e584", "content_id": "65f6e7765c41dcd1102289cae596ac64cb005b4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 693, "license_type": "no_license", "max_line_length": 57, "num_lines": 29, "path": "/Python/IndustrialProgramming/advanced/vector3.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\nimport math # sqrt\nimport operator # operators as functions\n\n\nclass Vector(object):\n # constructor\n\n def __init__(self, coord):\n self.coord = coord\n\n # turns the object into string\n def __str__(self):\n return str(self.coord)\n\n def __abs__(self):\n '''Vector length (Euclidean norm).'''\n return math.sqrt(sum(x * x for x in self.coord))\n\n def __add__(self, other):\n '''Vector addition.'''\n return map(operator.add, self.coord, other.coord)\n\nif __name__ == \"__main__\":\n v1 = Vector(range(5))\n print(\"Vector: \", str(v1))\n print(Vector.__abs__.__doc__, abs(v1))\n print(Vector.__add__.__doc__, v1 + v1)\n" }, { "alpha_fraction": 0.566402792930603, "alphanum_fraction": 0.59278804063797, "avg_line_length": 34.53125, "blob_id": "81825aba9359cc05a46f32e5d096594acab529f3", "content_id": "89bcefc369fcd3430ea9e312b40caf3c07845f4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1137, "license_type": "no_license", "max_line_length": 89, "num_lines": 32, "path": "/CSharp/code-examples/objects/points1.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Example using private fields with explicit get function\n// From Lecture 3: C# Basics\n// -----------------------------------------------------------------------------\n\nusing System;\nclass Point{\n // private access modifier: only visible in this class\n\tprivate int x;\n\tprivate int y;\n\n // constructor with initialisation\n\tpublic Point(int x, int y){\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n // methods for read-access to these values\n\tpublic int GetX() {return(x);}\n\tpublic int GetY() {return(y);}\n}\nclass Test{\n\tpublic static void Main(){\n\t // NB: because we don't have methods for write-access, \n // x and y won't change after initialisation, i.e. they are immutable\n\t\tPoint point1 = new Point(5,10);\n\t\tPoint point2 = new Point(20, 15);\n\t\tConsole.WriteLine(\"Point1({0}, {1})\", point1.GetX(), point1.GetY());\n\t\tConsole.WriteLine(\"Point2({0}, {1})\", point2.GetX(), point2.GetY());\n\t\t// NB: this doesn't work, because x and y are private in the Point class; try it!\n\t\t// Console.WriteLine(\"Point1({0}, {1})\", point1.x, point1.y);\n\t\t// Console.WriteLine(\"Point2({0}, {1})\", point2.x, point2.y);\n\t}\n}\n" }, { "alpha_fraction": 0.6347123980522156, "alphanum_fraction": 0.6357215046882629, "avg_line_length": 19.12765884399414, "blob_id": "e875dbd5d588350bb57d3f8b5a64a7f209ac2abc", "content_id": "6fe2397d2c9a73bbb5800608963ee7661f97da54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 991, "license_type": "no_license", "max_line_length": 62, "num_lines": 47, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orders/Dish.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orders;\r\n\r\n/**Dish Class is representing dish\r\n * @author Kamontorn Khamrun\r\n *\r\n */\r\npublic abstract class Dish implements Comparable<Dish> \r\n{\r\n\tprotected String dishName;\r\n\r\n\t/**Constructor for Dish throw exception if params are invalid\r\n\t * @param dishName\r\n\t */\r\n\tpublic Dish(String dishName)\r\n\t{\r\n\t\tif(dishName.length() ==0)\r\n {\r\n\t throw new IllegalStateException(\r\n\t \"Cannot have black dish name\");\r\n\t \r\n }\r\n\t\tthis.dishName = dishName;\r\n\t}\r\n\r\n\t/** This is an abstract class to compare object Dish\r\n\t * @param other\r\n\t * @return true if objects are equal otherwise false\r\n\t */\r\n\tpublic abstract boolean equals(Dish other);\r\n\r\n\t\r\n\t/** For comparable\r\n\t * @see java.lang.Comparable#compareTo(java.lang.Object)\r\n\t */\r\n\tpublic int compareTo(Dish other)\r\n\t{\r\n\t\treturn dishName.compareTo(other.getName());\r\n\t\t\r\n\t}\r\n\t/**getName method for getting dishName\r\n\t * @return dishName\r\n\t */\r\n\tpublic String getName() \r\n\t{\r\n\t\treturn dishName;\r\n\t}\r\n}" }, { "alpha_fraction": 0.5056841969490051, "alphanum_fraction": 0.5084912180900574, "avg_line_length": 26.83203125, "blob_id": "cb7a03630b500a1ad522ec8776363efcb8e64f68", "content_id": "3f553b3e43064194f22860862913a41e01f2f73a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7125, "license_type": "no_license", "max_line_length": 112, "num_lines": 256, "path": "/Python/IndustrialProgramming/coursework/app/static/javascripts/interaction.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "$(document).ready(function() {\n\n var locationPathname = $(location).attr('pathname');\n\n if (locationPathname == \"/task-1\") {\n\n };\n if (locationPathname == \"/task-2\") {\n submitUUID();\n };\n if (locationPathname == \"/task-3\") {\n submitBrowserRestet();\n };\n if (locationPathname == \"/task-4\") {\n popularUsers();\n };\n if (locationPathname == \"/task-5\") {\n alikeBook();\n alikeUser();\n };\n});\n\nfunction submitUUID() {\n $('#submit-uuid').click(function() {\n getAjaxBookUUID($('#input-uuid').val());\n });\n}\n\nfunction submitBrowserRestet() {\n $('#submit-browser').click(function() {\n getAjaxBrowsers();\n });\n}\n\nfunction popularUsers() {\n $('#submit-number').click(function() {\n getAjaxPopularUsers($('#numbers').val());\n });\n}\n\nfunction alikeBook() {\n $('#submit-book').click(function() {\n book_uuid = $('input#book_uuid').val();\n getAjaxBookUUIDAlike(book_uuid);\n });\n}\nfunction alikeUser() {\n $('#submit-user').click(function() {\n user_uuid = $('input#user_uuid').val();\n getAjaxUserUUIDAlike(user_uuid);\n });\n}\n\nvar prevAjaxReturnedUUID = true;\nvar xhrUUID = null;\n\nfunction getAjaxBookUUID(uuid) {\n\n if (prevAjaxReturnedUUID) {\n prevAjaxReturnedUUID = false;\n } else if (xhrUUID) {\n xhrUUID.abort();\n }\n\n xhrUUID = $.ajax({\n type: \"POST\",\n data: {\n uuid: uuid,\n },\n url: '/api/task-2',\n beforeSend: function() {\n $('.image-ajax').attr('src', '/static/images/ajax-loader.gif');\n },\n dataType: 'json',\n success: function(json) {\n $('#error-message-uuid').text(\"\");\n if (json.hasOwnProperty('exception')) {\n $('#error-message-uuid').text(json.exception + \" Try Again, with diffrent UUID\");\n } else {\n $('#book-country-plot').attr('src', '/static/results/countries_to_book_' + uuid + '.png');\n $('#book-continent-plot').attr('src', '/static/results/continent_to_book_' + uuid + '.png');\n }\n prevAjaxReturnedUUID = true;\n }\n });\n};\n\n\n\nvar prevAjaxBrowsers = true;\nvar xhrBrowsers = null;\n\nfunction getAjaxBrowsers() {\n\n if (prevAjaxBrowsers) {\n prevAjaxBrowsers = false;\n } else if (xhrBrowsers) {\n xhrBrowsers.abort();\n }\n\n xhrBrowsers = $.ajax({\n type: \"POST\",\n url: '/api/task-3',\n beforeSend: function() {\n $('.image-ajax').attr('src', '/static/images/ajax-loader.gif');\n },\n dataType: 'json',\n success: function(json) {\n console.log(json)\n $('#error-message').text(\"\");\n if (json.hasOwnProperty('exception')) {\n $('#error-message').text(json.exception);\n } else {\n $('#browser-usage').removeAttr(\"src\").attr(\"src\", \"static/results/simple_browser_usage.png\");\n $('#browser-general').removeAttr(\"src\").attr(\"src\", \"static/results/general_browser_usage.png\");\n }\n prevAjaxBrowsers = true;\n }\n\n });\n};\n\n\nvar prevAjaxUserPopular = true;\nvar xhrUsers = null;\n\nfunction getAjaxPopularUsers(numbers) {\n\n if (prevAjaxUserPopular) {\n prevAjaxUserPopular = false;\n } else if (xhrUsers) {\n xhrUsers.abort();\n }\n xhrUsers = $.ajax({\n type: \"POST\",\n data: {\n \"numbers\": numbers\n },\n url: '/api/task-4',\n beforeSend: function() {\n $('.image-ajax').attr('src', '/static/images/ajax-loader.gif');\n },\n dataType: 'json',\n complete: function(json) {\n $('#error-message').text(\"\");\n console.log(json);\n if (json.responseText.indexOf('exception') > 1) {\n $('#error-message').text(json.responseText);\n } else {\n makeUserTable(json);\n }\n prevAjaxUserPopular = true;\n }\n });\n};\n\nfunction makeUserTable(users) {\n userData = JSON.parse(users.responseText.replace(/\\bNaN\\b/g, \"null\")).succesfully;\n\n $('tbody').html(\"\");\n $.each(userData, function(key, val) {\n\n $('tbody').append('<tr id=' + key + '>');\n\n $.each(val.visitor_ip, function(prop, val) {\n $('#' + key).append('<th>' + val + '</th>');\n });\n $.each(val.visitor_country, function(prop, val) {\n $('#' + key).append('<th>' + val + '</th>');\n });\n $.each(val.visitor_device, function(prop, val) {\n $('#' + key).append('<th>' + val + '</th>');\n });\n $.each(val.visitor_useragent, function(prop, val) {\n $('#' + key).append('<th>' + val.substring(0,20) + '</th>');\n });\n $.each(val.visitor_uuid, function(prop, val) {\n $('#' + key).append('<th>' + val + '</th>');\n });\n $('#' + key).append('<th>' + val.total_time + '</th>');\n\n $('tbody').append('</tr>');\n });\n}\n\n\nvar prevAjaxReturnedUUID = true;\nvar xhrUUID = null;\n\nfunction getAjaxBookUUIDAlike(uuid) {\n if (prevAjaxReturnedUUID) {\n prevAjaxReturnedUUID = false;\n } else if (xhrUUID) {\n xhrUUID.abort();\n }\n\n xhrUUID = $.ajax({\n type: \"POST\",\n data: {\n book_uuid: uuid,\n },\n url: '/api/task-5a',\n dataType: 'json',\n success: function(json) {\n $('#error-message-book').text(\"\");\n $('#book_data-like').text(\"\")\n\n if (json.hasOwnProperty('exception') || json.alike_sorted.length == 0 ) {\n $('#error-message-book').text(json.exception + \" Try Again, with diffrent UUID\");\n } else {\n var jsonPrettyLike = JSON.stringify(json.book_alike, null, 2);\n var jsonPrettySort = JSON.stringify(json.alike_sorted, null, 2);\n \n $('#book-data-like').text(jsonPrettyLike);\n $('#book-data-sorted').text(jsonPrettySort);\n }\n prevAjaxReturnedUUID = true;\n }\n });\n};\n\n\n\nvar prevAjaxReturnedUUID = true;\nvar xhrUUID = null;\n\nfunction getAjaxUserUUIDAlike(uuid) {\n if (prevAjaxReturnedUUID) {\n prevAjaxReturnedUUID = false;\n } else if (xhrUUID) {\n xhrUUID.abort();\n }\n\n xhrUUID = $.ajax({\n type: \"POST\",\n data: {\n user_uuid: uuid,\n },\n url: '/api/task-5b',\n dataType: 'json',\n success: function(json) {\n $('#error-message-user').text(\"\");\n if (json.hasOwnProperty('exception') || json.alike_sorted.length == 0 ) {\n $('#error-message-user').text(json.exception + \" Try Again, with diffrent UUID\");\n } else {\n var jsonPrettyLike = JSON.stringify(json.user_alike, null, 2);\n var jsonPrettySort = JSON.stringify(json.alike_sorted, null, 2);\n \n $('#user-data-like').text(jsonPrettyLike);\n $('#user-data-sorted').text(jsonPrettySort);\n\n }\n prevAjaxReturnedUUID = true;\n }\n });\n};\n" }, { "alpha_fraction": 0.5847750902175903, "alphanum_fraction": 0.5930795669555664, "avg_line_length": 19.64285659790039, "blob_id": "521fb1eba58a6fe256c21d7b11ca03a1aeb5dfd2", "content_id": "5f9029acfeb47edfd92d0294c68a2c3c6a36ff5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 80, "num_lines": 70, "path": "/Express/serverRoutes.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "var express = require('express'),\n bodyParser = require('body-parser'),\n app = express(),\n APIv1 = require('./APIv1'),\n APIv2 = require('./APIv2');\n\n//Injecting Rourter Objects on given path\napp.use('/api/v1',APIv1);\napp.use('/api/v2',APIv2);\n\napp.use(bodyParser.urlencoded());\n\n\n\nvar names = ['Marian'];\n\n//Route object that can have all these methods\n// app.route('/path')\n// .get()\n// .post()\n// .put()\n// .delete()\n// .all();\n\napp.route('/')\n .get(function(req, res, next) {\n console.log(names);\n res.render('names/index.jade', {\n names: names\n });\n next();\n })\n .post(function(req, res) {\n names.push(req.body.name);\n res.redirect('/');\n });\n\n\n//Router Object mini express app inside master app\n// -use for middleware\n// -verb /all (put,get .. )\n// -param for route specific middleware\n//- route method (route object)\n\n\nvar router = express.Router({\n caseSensitive: false, //application wioe option that can be used\n strict: true,\n});\n\nrouter.use(function(req, res, next) {\n console.log(\"Rputer specific middleware\");\n next();\n});\nrouter.get('/', function(req, res) {\n res.send('Router home root');\n});\n\nrouter.route('/test')\n .get(function(req, res) {\n res.send('Router route');\n });\n\n\napp.use('/router', router); //Whe put route path were router object will be used\n\n\n//Modularity in two files\n\napp.listen(3000);\n" }, { "alpha_fraction": 0.5083440542221069, "alphanum_fraction": 0.5173299312591553, "avg_line_length": 17.4761905670166, "blob_id": "a34fa373c435b855fc817f8fa15bc395d2d8a198", "content_id": "c9ac68916f31096ed11b241ade8026d5cf67987d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 779, "license_type": "no_license", "max_line_length": 45, "num_lines": 42, "path": "/CSharp/code-examples/sys-programming/buffer1.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\n\nclass Tester {\n unsafe static void Main()\n {\n // string str = \"\";\n string str = \"test\";\n string str0 = \"\";\n fixed (char *p = str) {\n\tfixed (char *q = str0) {\n\t // FixedBuffer fb = new FixedBuffer(test);\n\t for (int i = 0; i<str.Length; i++) {\n\t *q++ = *p++;\n\t }\n\t}\n }\n // FixedBuffer.strcpy(p);\n Console.WriteLine(\"test str: \"+str);\n Console.WriteLine(\"copied str: \"+str0);\n }\n}\n\n/*\nunsafe class FixedBuffer {\n // contents of the buffer\n public struct MyArray {\n public fixed char name[30];\n }\n\n public FixedBuffer (string s) {\n MyArray.name = s;\n }\n\n public void strcpy (string toString) {\n char *c;\n char *d;\n for (c = &MyArray.name; c != '\\0'; c++) {\n *d = *c;\n }\n }\n} \n*/ \n" }, { "alpha_fraction": 0.7350427508354187, "alphanum_fraction": 0.7393162250518799, "avg_line_length": 23.6842098236084, "blob_id": "227f2e9f032fc998cd964bfffd43bb61c3e1b638", "content_id": "1c718885aad68dac8a4320c4f072598a29042430", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 468, "license_type": "no_license", "max_line_length": 62, "num_lines": 19, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orders/BadQuantityException.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orders;\n\n/**New unchecked exception for dish prices in Order Collection\n * get thrown when quantity is > 10 in order\n * @author Marcin\n *\n */\n@SuppressWarnings(\"serial\")\npublic class BadQuantityException extends RuntimeException {\n\n\t\n\t/**Constructor for exception\n\t * pass name that can used in getMessege in Exception class\n\t * @param seq\n\t */\n\tpublic BadQuantityException(int seq){\n\t\tsuper(\"Incorrect dish quantity in order number = \" + seq);\n\t}\n}" }, { "alpha_fraction": 0.3714953362941742, "alphanum_fraction": 0.43808412551879883, "avg_line_length": 24.939393997192383, "blob_id": "e7d9f8710668ca8dbbd36dda4916bc7922b6af00", "content_id": "34de74dd6c10fed6b866f1342e904cbc892c4d3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 856, "license_type": "no_license", "max_line_length": 47, "num_lines": 33, "path": "/Python/IndustrialProgramming/coursework/app/templates/task-1.html", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %} {% block content %}\n\n<div class=\"container\">\n <div class=\"center-block\">\n \t\t<h1>PIP installed required packages:</h1>\n <ul id=\"req-list\">\n <li>Flask==0.10.1</li>\n <li>Jinja2==2.7.3 </li>\n <li>MarkupSafe==0.23</li>\n <li>Werkzeug==0.9.6</li>\n <li>argparse==1.2.1</li>\n <li>itsdangerous==0.24</li>\n <li>matplotlib==1.4.2</li>\n <li>mock==1.0.1</li>\n <li>nose==1.3.4</li>\n <li>numpy==1.9.1</li>\n <li>pandas==0.15.1</li>\n <li>pyparsing==2.0.3</li>\n <li>python-dateutil==2.2</li>\n <li>python-dateutil==2.2</li>\n <li>pytz==2014.10</li>\n <li>six==1.8.0</li>\n <li>wsgiref==0.1.2</li>\n </ul>\n </div>\n</div>\n\n\n\n\n\n\n{% endblock %}\n" }, { "alpha_fraction": 0.5681003332138062, "alphanum_fraction": 0.5734767317771912, "avg_line_length": 18.928571701049805, "blob_id": "91143617e9536b272abade1c69b625a1657c29f5", "content_id": "01093aaa6b58d17d5562c165956c43e9f263430d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 55, "num_lines": 28, "path": "/Python/IndustrialProgramming/advanced/iter1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# A simple iterator example\n\n\nclass Reverse:\n\n \"\"\"Iterator for looping over sequence backwards.\"\"\"\n\n def __init__(self, data):\n self.data = data\n self.index = len(data)\n\n def __iter__(self):\n return self\n\n def next(self):\n if self.index == 0:\n raise StopIteration\n self.index = self.index - 1\n return self.data[self.index]\n\nit = iter(Reverse(range(5)))\ntry:\n while (True):\n x = it.next()\n print (x)\nexcept StopIteration:\n print(\"Stopped with iteration.\")\n" }, { "alpha_fraction": 0.6918445825576782, "alphanum_fraction": 0.69786536693573, "avg_line_length": 25.238805770874023, "blob_id": "03e333b7d0c5bc71952577766caef698f1e7f152", "content_id": "db3e1c0e20ae8c78d37d00af044cb4989927d603", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1827, "license_type": "no_license", "max_line_length": 77, "num_lines": 67, "path": "/Java/F21AS Advanced Software Engineering/Week 6 MVC/src/views/ClockGUI.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package views;\r\n//window containing various display panels\r\n\r\nimport java.awt.*;\r\nimport java.awt.event.ActionListener;\r\nimport javax.swing.*;\r\nimport model.Clock;\r\n\r\npublic class ClockGUI extends JFrame\r\n{\t\t\t\r\n\t//gui components\r\n\tprivate JTextField hours = new JTextField();\r\n\tprivate JTextField mins = new JTextField();\r\n\tprivate JButton updateButton = new JButton(\"Update\");\r\n\t\r\n\tpublic ClockGUI(Clock model)\r\n\t{\t\r\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\r\n\t\tsetLayout(new BorderLayout());\r\n\t\t\r\n\t\t//add update panel at the top (doesn't need to know about the clock object)\r\n\t\tadd(BorderLayout.NORTH, createSetClockPanel());\r\n\t\t\r\n\t\t//the display classes DO need to know about the Clock object \r\n\t\t//(to register as observers and to get the data)\r\n\t\t//add analog display in the middle\r\n\t\tadd(new AnalogDisplay(model), BorderLayout.CENTER);\r\n\t\t//add digital display at the bottom\r\n\t\tadd(BorderLayout.SOUTH, new DigitalDisplay(model));\r\n\t\r\n\t\tsetSize(250,300);\r\n\t\tsetVisible(true);\r\n\t}\r\n\t\r\n\tpublic JPanel createSetClockPanel() {\t\r\n\t\tJPanel setClockPanel = new JPanel(new BorderLayout());\t\r\n\t\t\r\n\t\tJPanel panel = new JPanel(new GridLayout(2,2));\r\n\t\tpanel.add(new JLabel(\"New Hours (0 - 23)\"));\r\n\t\tpanel.add(hours);\r\n\t\tpanel.add(new JLabel(\"New Mins\"));\r\n\t\tpanel.add(mins);\r\n\t\tsetClockPanel.add(BorderLayout.CENTER, panel);\r\n\t\t\r\n\t\tJPanel buttonPanel = new JPanel();\r\n\t\tbuttonPanel.add(updateButton);\t\r\n\r\n\t\tsetClockPanel.add(BorderLayout.SOUTH, buttonPanel);\r\n\t\t\t\t\r\n\t\treturn setClockPanel;\r\n\t}\r\n\t\r\n\t//return contents of hours text box\r\n\tpublic String getHours() {\r\n\t\treturn hours.getText();\r\n\t}\r\n\t\r\n\t//return contents of mins text box\r\n\tpublic String getMins() {\r\n\t\treturn mins.getText();\r\n\t}\r\n\t\r\n\t//add listener to update button\r\n\tpublic void addSetListener (ActionListener al) {\r\n\t\tupdateButton.addActionListener(al);\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.6298120021820068, "alphanum_fraction": 0.6495075821876526, "avg_line_length": 29.43661880493164, "blob_id": "452fe490f31c8065cc9b7a774d5310baed2ddda0", "content_id": "39b2fddd0fcc4fc7572de4e3e3ba0f5bdda61f60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2234, "license_type": "no_license", "max_line_length": 98, "num_lines": 71, "path": "/Java/F21AS Advanced Software Engineering/Week 2 Collections/src/DemoMap.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import java.util.*;\r\npublic class DemoMap {\r\n\r\n\t\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\t//create a treemap with key = name (String) and value = phone (String)\r\n\t\tTreeMap <String, String> phoneBook1 = new TreeMap <String, String> ();\r\n\t\t//add a few key/value pairs\r\n\t\tphoneBook1.put(\"Tim\", \"411-0914\");\r\n\t\tphoneBook1.put(\"Jo\", \"411-0210\");\r\n\t\tphoneBook1.put(\"Jack\", \"131-9873\");\r\n\t\tphoneBook1.put(\"Ann\", \"411-0210\"); //jo and ann share a phone\r\n\r\n\t\tSystem.out.println(\"There are \" +Integer.toString(phoneBook1.size()) + \" numbers in phonebook\");\r\n\t\t\r\n\t\t\r\n\t\t//get a value (phone) for a given key (name)\r\n\t\tString phoneNumber = phoneBook1.get(\"Jack\");\r\n\t\tSystem.out.println(\"Jack's number is \"\r\n\t\t\t\t+ phoneNumber);\r\n\t\tSystem.out.println();\r\n\t\t\r\n\t\r\n\t\t//use the TreeMap toString method to print the entries\r\n\t\t//(prints key=value)\r\n\t\tSystem.out.println(phoneBook1);\r\n\t\tSystem.out.println();\r\n\t\tphoneBook1.remove(\"Jack\");\r\n\t\tSystem.out.println(\"Jack has been removed\");\r\n\t\tSystem.out.println(phoneBook1);\r\n\t\t\r\n\t\t\r\n\t\t//print all the keys (names)\r\n\t\t//(keyset returns a set of the keys)\r\n\t\tSystem.out.println(\"Names listed\");\r\n\t\tfor (String name : phoneBook1.keySet() ) {\r\n\t\t\tSystem.out.println(name);\r\n\t\t}\r\n\t\tSystem.out.println();\r\n\t\t\r\n\t\t//print details from each value\r\n\t\t//(values returns a set of the values)\r\n\t\tSystem.out.println(\"Phone numbers suffix, from the values\");\r\n\t\tfor (String phone : phoneBook1.values() ) {\r\n\t\t\t//just shows you can use a method on the value\r\n\t\t\t//(and would have to if the value was an object)\r\n\t\t\tSystem.out.println(phone.substring (4) );\r\n\t\t}\r\n\t\tSystem.out.println();\r\n\t\t\r\n\t\t//print details of key and value\r\n\t\t//(entrySet returns a set of entries (key/value pairs), type Map.Entry<K,V> )\r\n\t\t//use getKey, getValue on the entry\r\n\t\tfor (Map.Entry<String, String> entry : phoneBook1.entrySet() ) {\r\n\t\t\tSystem.out.println(entry.getKey() + \" has extension \" \r\n\t\t\t\t\t+ entry.getValue().substring(4));\r\n\t\t}\r\n\t\tSystem.out.println();\r\n\t\t\r\n\t\t//get list of phone numbers without duplicates\r\n\t\tSystem.out.println(\"Phone numbers, no duplicates\");\r\n\t\tTreeSet <String> phones = new TreeSet<String> (phoneBook1.values());\r\n\t\tfor (String phone : phones) {\r\n\t\t\tSystem.out.println(phone);\r\n\t\t}\r\n\t\t\r\n\t} \r\n\r\n\t\r\n}\r\n\r\n" }, { "alpha_fraction": 0.6038781404495239, "alphanum_fraction": 0.6038781404495239, "avg_line_length": 39.11111068725586, "blob_id": "b0ddacff7a315c126aec4b4ae95eea9553e1486f", "content_id": "79303c758d503370a5cd4c5b13df374b952a01f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1805, "license_type": "no_license", "max_line_length": 94, "num_lines": 45, "path": "/Python/IndustrialProgramming/coursework/app/classes/browser_analysis.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport pandas as pd\n\n\nclass BrowserAnalysis:\n\n __main_browsers = [\"opera\", \"dalvik\", \"safari\", \"chrome\", 'trident', 'gecko']\n __labels = [\"ts\", \"visitor_uuid\", \"visitor_source\", \"visitor_device\", \"visitor_useragent\",\n \"visitor_ip\", \"visitor_country\", \"visitor_referrer\"]\n\n def __init__(self, book_data):\n self.__book_data = book_data\n self.__book_data = self.__book_data[self.__labels]\n\n def browser_usage(self):\n \"\"\" Group dataframe by visitor browser and counts distinct\"\"\"\n browser_usage = self.__book_data['visitor_useragent'].value_counts()\n return browser_usage\n\n def browser_usage_plot(self):\n \"\"\" Create a hist plot based on browser usage\"\"\"\n browser_usage = self.browser_usage()\n browser_usage.plot(kind='bar')\n plt.savefig('static/results/simple_browser_usage.png')\n\n def general_usage(self):\n \"\"\"Perform more robust calculation of browser usage\"\"\"\n browser_usage = self.browser_usage()\n browser_usage_data = browser_usage.to_dict()\n general_usage = {}\n for browser in self.__main_browsers:\n for key, value in browser_usage_data.iteritems():\n if browser in key.lower():\n if browser in general_usage:\n general_usage[browser] += value\n else:\n general_usage[browser] = value\n return general_usage\n\n def general_usage_plot(self):\n \"\"\" Create plot based on general usage\"\"\"\n general_usage = self.general_usage()\n genral_usage_data = pd.Series(general_usage.values(), general_usage.keys())\n genral_usage_data.plot(kind='bar')\n plt.savefig('static/results/general_browser_usage.png')\n" }, { "alpha_fraction": 0.5623809695243835, "alphanum_fraction": 0.5885714292526245, "avg_line_length": 24.204818725585938, "blob_id": "0344c51ddfeeeeede454438fe7db6d0387dd5b56", "content_id": "ccff2d26ae3a39421d70606d2d2297064af08f84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2101, "license_type": "no_license", "max_line_length": 107, "num_lines": 83, "path": "/CSharp/code-examples/parallel/Futures1.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "ISO-8859-9", "text": "/* \nFrom: \nParallel Programming with Microsoft® .NET\nDesign Patterns for Decomposition and Coordination on Multicore Architectures\nBy Colin Campbell, Ralph Johnson, Ade Miller, Stephen Toub\nPublisher: Microsoft Press\nReleased: August 2010 \nOn-line: http://msdn.microsoft.com/en-us/library/ff963547.aspx\n\nChapter on Futures\n\n*/\n\nusing System;\nusing System.Threading.Tasks;\n// using Parallel;\nusing System.Collections.Generic; // for List<T>\nusing System.Collections.Concurrent; // for Partitioner\n\nclass Futures {\n\n private static int Fib(int n) {\n if (n==0) { return 1; } \n else if (n==1) { return 1; }\n else {\n int n1 = Fib(n-1);\n int n2 = Fib(n-2);\n return n1+n2;\n }\n }\n\n private static int F1(int n) { \n return Fib(n);\n }\n\n private static int F2(int n) { \n return n+1; // Next(n);\n }\n\n private static int F3(int n) { \n return Fib(n);\n }\n\n private static int F4(int m, int n) { \n return m+n;\n }\n\n private static int seq_code(int a) { \n int b = F1(a); \n int c = F2(a); \n int d = F3(c); \n int f = F4(b, d);\n return f;\n }\n\n private static int par_code(int a) { \n // constructung a future generates potential parallelism\n Task<int> futureB = Task.Factory.StartNew<int>(() => F1(a));\n int c = F2(a); \n int d = F3(c); \n int f = F4(futureB.Result, d);\n return f;\n }\n\n public static void Main(string []args) {\n if (args.Length != 2) { // expect 1 arg: value to double\n System.Console.WriteLine(\"Usage: <prg> <parallel?> <n>\");\n // System.Console.WriteLine(\"k ... number of cores to use\");\n System.Console.WriteLine(\"n ... input to Fib\");\n } else { \n // int k = Convert.ToInt32(args[0]);\n // int m = Convert.ToInt32(args[1]);\n int p = Convert.ToInt32(args[0]);\n int n = Convert.ToInt32(args[1]);\n // int sum = 0;\n if (p==0) {\n\t System.Console.WriteLine(\"Sequential computation of Fib({0}) + Fib({0}+1):\", n, seq_code(n));\n } else {\n\t System.Console.WriteLine(\"Parallel computation of Fib({0}) + Fib({0}+1) using futures:\", n, par_code(n));\n }\n }\n }\n}\n \n" }, { "alpha_fraction": 0.5434412360191345, "alphanum_fraction": 0.5519590973854065, "avg_line_length": 24.68181800842285, "blob_id": "94443e747d6599cb30790fbf6e80e44874470028", "content_id": "3050adb47a53f05652f732572ce410c85adbd909", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 587, "license_type": "no_license", "max_line_length": 51, "num_lines": 22, "path": "/Java/F21SF Soft E Fundation/1/src/CarMain.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/**\r\n * Software Engineering Foundations\r\n * A first main method using a class\r\n * @author monica\r\n */\r\npublic class CarMain {\r\n public static void main (String[] args) {\r\n //create a Car\r\n Car myCar = new Car(\"Ford Ka\", 40, 33.6);\r\n\r\n //get model\r\n String model = myCar.getModel();\r\n\r\n //get estimated distance\r\n double distance = myCar.estimateDistance();\r\n\r\n //print the details to standard output\r\n System.out.println(model + \" can travel \"\r\n + distance + \" miles\");\r\n } //end main method\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5363849997520447, "alphanum_fraction": 0.5410798192024231, "avg_line_length": 24.84848403930664, "blob_id": "e379d955088ce765e176a1e682db8958f4e77bea", "content_id": "67e55743525843dea17fa420d85b6d61ffac1858", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 852, "license_type": "no_license", "max_line_length": 66, "num_lines": 33, "path": "/CSharp/code-examples/io/files2.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// example from Lecture 7 on Streams\n\nusing System;\nusing System.IO;\n\npublic class FileReadWrite\n{\n public static void Main()\n {\n // a safe way of writing to a file\n try\n {\n StreamWriter sw = new StreamWriter(\"test.txt\");\n sw.WriteLine(\"Hello World!\");\n sw.Close();\n\n // append more text to the file\n StreamWriter sw1 = new StreamWriter(\"test.txt\", true);\n sw1.WriteLine(\"Hello World again!\");\n sw1.Close();\n }\n catch (IOException ex)\n {\n Console.WriteLine(ex.Message);\n }\n\n // std iteration over the contents of a file\n StreamReader sr = new StreamReader(\"test.txt\");\n string inValue = \"\";\n while ((inValue = sr.ReadLine()) != null)\n Console.WriteLine(inValue);\n }\n}" }, { "alpha_fraction": 0.5682656764984131, "alphanum_fraction": 0.5940959453582764, "avg_line_length": 16.33333396911621, "blob_id": "9d0ad16ea1611323b2ecc086d64c5de4002189ee", "content_id": "aa3d83f100440be0f51faf98491461af10445438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 271, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/CSharp/code-examples/basics/double.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Hello-world-like example program\n// DOS\n\nclass TestClass {\r\n public static void Main () {\r\n MyClass m = new MyClass();\r\n System.Console.WriteLine(\"99*2 = {0}\", m.Double(99));\r\n }\r\n}\r\n\r\nclass MyClass {\r\n public int Double(int val) {\r\n return val*2;\r\n }\r\n}\r" }, { "alpha_fraction": 0.5377358198165894, "alphanum_fraction": 0.5849056839942932, "avg_line_length": 13.133333206176758, "blob_id": "a4b12214ee2aae9cf5529607cb904c517561906e", "content_id": "b3908ed49a743f01eee982a8e4166628a332a1fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 212, "license_type": "no_license", "max_line_length": 30, "num_lines": 15, "path": "/Python/InteractiveCoursera/Week 0/hello.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "__author__ = 'raziel'\n\n# Comment\nprint(\"Hello Word\")\n\na = [2, 3, 5, 5]\n\n\ndef solveMeFirst(a, b):\n num1 = int(input())\n num2 = int(input())\n return num1 + num2\n\nres = solveMeFirst(num1, num2)\nprint (res)\n" }, { "alpha_fraction": 0.6013985872268677, "alphanum_fraction": 0.6293706297874451, "avg_line_length": 17, "blob_id": "a25c4056d92a28f5163c7a4c2b09ccf51ed272ce", "content_id": "53c971dff769e8d161feead2fcb98cddaed537a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 143, "license_type": "no_license", "max_line_length": 40, "num_lines": 8, "path": "/Express/APIv1.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "var APIv1 = require('express').Router();\n\n\nAPIv1.get('/', function(req, res) {\n res.send('Name API version 1');\n});\n\nmodule.exports = APIv1;" }, { "alpha_fraction": 0.4738878011703491, "alphanum_fraction": 0.4893617033958435, "avg_line_length": 20.54166603088379, "blob_id": "d0dff962e8a911546ad9f9ce04316400aed38f1b", "content_id": "ae918a49f0dcf3c658d7409ace09359300add7b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/Python/IndustrialProgramming/advanced/vector2.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nclass Vector(object):\n # constructor\n\n def __init__(self, coord):\n self.coord = coord\n # turns the object into string\n # use <> as brackets, and ; as separator\n\n def __str__(self):\n s = \"<\"\n if len(self.coord) == 0:\n return s + \">\"\n else:\n s = s + str(self.coord[0])\n for x in self.coord[1:]:\n s = s + \";\" + str(x)\n return s + \">\"\n\nv1 = Vector([1, 2, 3])\n# performs conversion to string as above\nprint (v1)\n" }, { "alpha_fraction": 0.37456241250038147, "alphanum_fraction": 0.41306883096694946, "avg_line_length": 18.930233001708984, "blob_id": "595e773f2a6e21a48aa5c7582f77a3d4221a3c64", "content_id": "0e7c52bf2db2df66e1fc38e01d044f6aff3de553", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 69, "num_lines": 43, "path": "/Python/CodingTests/Geometry/find_point.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# import sys\n\n# input_all = []\n\n# for line in sys.stdin:\n# print(line)\n# input_all.append([int(x) for x in line.split() if x.isdigit()])\n\n\ninput_all = [[10, 9],\n [2, 1],\n [3, 1],\n [4, 3],\n [5, 2],\n [6, 1],\n [7, 2],\n [8, 6],\n [9, 8],\n [10, 8]]\n\nN = input_all[0][0]\nM = input_all[0][1]\n\nTree = input_all[1:]\n\n\ndef veriti_count(Tree, N):\n vert_counts = {}\n for i in range(1, N + 1):\n for edge in Tree:\n if i in edge:\n if i in vert_counts:\n vert_counts[i] += 1\n else:\n vert_counts[i] = 1\n return vert_counts\n\n\ndef even_tree(Tree, N):\n vert_counts = veriti_count(Tree, N)\n\n for counts in veriti_count:\n if counts.value() % 2 == 0\n" }, { "alpha_fraction": 0.686354398727417, "alphanum_fraction": 0.686354398727417, "avg_line_length": 31.733333587646484, "blob_id": "b16a4b1ab6cf021f465b643c2540460d10ad7dbc", "content_id": "7258c477ac945437fb8ba1adc0ba0576a43e53ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 68, "num_lines": 15, "path": "/Interviews/jp_morgan/call_billing/src/client/client_factory.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from new_client import NewClient\nfrom standard_client import StandardClient\n\n\nclass ClientFactory(object):\n\n \"\"\"ClientFactory manage creation of Client objects\"\"\"\n\n def factory(self, client_id, call_plan, client_type):\n \"\"\"Create Client object type based on client_type\"\"\"\n if client_type is \"new\":\n return NewClient(client_id, call_plan, client_type)\n\n if client_type is \"standard\":\n return StandardClient(client_id, call_plan, client_type)\n" }, { "alpha_fraction": 0.46721312403678894, "alphanum_fraction": 0.6844262480735779, "avg_line_length": 14.25, "blob_id": "a00bb19fcaa43c34acfb4fa0c9926c3a8a781754", "content_id": "b82c2d3cb41b39a2a26e82225d9a106bcec2b856", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 244, "license_type": "no_license", "max_line_length": 20, "num_lines": 16, "path": "/Python/IndustrialProgramming/coursework/requirements.txt", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "Flask==0.10.1\nJinja2==2.7.3\nMarkupSafe==0.23\nWerkzeug==0.9.6\nargparse==1.2.1\nitsdangerous==0.24\nmatplotlib==1.4.2\nmock==1.0.1\nnose==1.3.4\nnumpy==1.9.1\npandas==0.15.1\npyparsing==2.0.3\npython-dateutil==2.2\npytz==2014.10\nsix==1.8.0\nwsgiref==0.1.2\n" }, { "alpha_fraction": 0.6067059636116028, "alphanum_fraction": 0.6189397573471069, "avg_line_length": 23.5222225189209, "blob_id": "9d9b57175ce100af90a8c6b25bda62933891ee25", "content_id": "7af673285741a32b6b9685b3df926ab8e03fe945", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2207, "license_type": "no_license", "max_line_length": 70, "num_lines": 90, "path": "/CSharp/code-examples/thearding/threads2.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Lecture 7: Threading\n\nusing System.Threading;\nusing System;\n\nnamespace Threads1 {\n\n class Tester {\n static void Main () {\n Tester t = new Tester();\n t.DoTest();\n }\n\n public void DoTest() {\n Thread[] myThreads = {\n\tnew Thread( new ThreadStart(Decrementer)),\n\tnew Thread( new ThreadStart(Incrementer)) };\n\n int n = 1;\n // start all threads\n foreach (Thread myThread in myThreads) {\n\tmyThread.IsBackground = true;\n\tmyThread.Name = \"Thread\"+n.ToString();\n\tConsole.WriteLine(\"Starting thread {0}\", myThread.Name);\n\tmyThread.Start();\n\tn++;\n\t// add a delay in starting all threads\n\tThread.Sleep(500);\n }\n // wait for all threads to end\n foreach (Thread myThread in myThreads) {\n\tmyThread.Join();\n }\n // after all threads end print this message\n Console.WriteLine(\"All my threads are done\");\n }\n\n private long counter = 0;\n\n public void Decrementer() {\n try {\n\t// (1) synchronise this area\n\tMonitor.Enter(this);\n\n\twhile (counter < 5 ) {\n\t Console.WriteLine(\"[{0}] In Decrementer. Counter: {1}. Waiting...\",\n\t\t\t Thread.CurrentThread.Name, counter);\n\t Monitor.Wait(this);\n\t}\n\n\twhile (counter > 0) {\n\t long temp = counter;\n\t temp--;\n\t Thread.Sleep(2);\n\t counter = temp;\n\t Console.WriteLine(\"[{0}] In Decrementer. Counter: {1}.\",\n\t\t\t Thread.CurrentThread.Name, counter);\n\t}\n } finally {\n\tMonitor.Exit(this);\n }\n }\n public void Incrementer() {\n try {\n\t// (1) synchronise this area\n\t// Monitor.Enter(this);\n\n\twhile (counter < 10) {\n\t // (2) more fine-grained control like this:\n Monitor.Enter(this);\n\t long temp = counter;\n\t temp++;\n\t Thread.Sleep(1);\n\t counter = temp;\n\t Console.WriteLine(\"[{0}] In Incrementer. Counter: {1}.\",\n\t\t\t Thread.CurrentThread.Name, counter);\n\t // (2) more fine-grained control like this:\n\t Monitor.Pulse(this); // inform waiting threads of the change\n\t Monitor.Exit(this); // leave monitor\n\t Thread.Sleep(1); // give other threads time to work\n\t}\n\t//Monitor.Pulse(this); // (1) release lock after all increments!\n } finally {\n\tConsole.WriteLine(\"[{0}] Exiting ...\",\n\t\t\t Thread.CurrentThread.Name);\n\tMonitor.Exit(this);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7260273694992065, "alphanum_fraction": 0.7260273694992065, "avg_line_length": 30.285715103149414, "blob_id": "1739b66fd3dcb1c7caba48e0332b02a672a44988", "content_id": "5c0b0804ef2de1b2151e0196617c93e8a0964e1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 67, "num_lines": 7, "path": "/Python/Excercises/panagra.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "sentence = \"We promptly judged antique ivory buckles for the prize\"\npanagram = \"The quick brown fox jumps over the lazy dog\"\n\n\ndef check_pan_regex(sentence):\n letters = filter(lambda x: , sentence)\n letters_set =\n" }, { "alpha_fraction": 0.49803149700164795, "alphanum_fraction": 0.5472440719604492, "avg_line_length": 16.482759475708008, "blob_id": "2f2823916b331b95b853c1e860504436e6df2ca2", "content_id": "ac1692d649f770d4939d718c994882e4e0a48bd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "no_license", "max_line_length": 69, "num_lines": 29, "path": "/Python/CodingTests/Mark and Toys/mark_toys.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# import sys\n\n# input_all = []\n\n# for line in sys.stdin:\n# print(line)\n# input_all.append([int(x) for x in line.split() if x.isdigit()])\n#\n\n# https://www.hackerrank.com/challenges/mark-and-toys\n\ninput_all = [[7, 50], [1, 12, 5, 111, 200, 1000, 10]]\n\nitems = input_all[1]\nK = input_all[0][1]\n\n\ndef max_toys(K, items):\n items.sort()\n N = 0\n summed = 0\n for item in items:\n if summed + item < K:\n summed += item\n N += 1\n return N\n\n\nprint(max_toys(K, items))\n\n" }, { "alpha_fraction": 0.6072874665260315, "alphanum_fraction": 0.6221322417259216, "avg_line_length": 25.44444465637207, "blob_id": "47fd7d90a78c5ffd64211d71b327c9ae73d19fec", "content_id": "88186fa4ffe28f8ddb24019a71739f7b8119990b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 741, "license_type": "no_license", "max_line_length": 54, "num_lines": 27, "path": "/Java/F21SF Soft E Fundation/2/src/TestName.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "//F21SF Lecture 3\r\npublic class TestName {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\t\r\n\t\tName name2 = new Name(\"Jane\",\"Jo\", \"Jones\");\r\n\t\tString last = name2.getLastName();\r\n\t\tSystem.out.println\r\n\t\t (\"Last name is \" + last);\r\n\t\tname2.setLastName(\"Smith\"); \r\n\t\tString newLast = name2.getLastName();\r\n\t\tSystem.out.println\r\n\t\t (\"Last name is \" + newLast);\r\n\t\tSystem.out.println();\r\n\t\t\t\t\r\n\t\tName n2 = new Name(\"Mary\", \"Ann\", \"Smith\");\r\n\t\tSystem.out.print(\"First name and last name : \" );\t\r\n\t\tSystem.out.println(n2.getFirstAndLastName());\r\n\t\tSystem.out.print(\"Surname, comma, firstname : \");\r\n\t\tSystem.out.println(n2.getLastCommaFirst());\r\n\t\tSystem.out.println();\r\n\t\t\r\n\t\tSystem.out.println(n2.getInitPeriodLast());\r\n\r\n\t}\r\n\t\t\r\n}\r\n" }, { "alpha_fraction": 0.6242257356643677, "alphanum_fraction": 0.6276668906211853, "avg_line_length": 25.94230842590332, "blob_id": "5076207c80e726b17c9816d8528c33c927ab9e6d", "content_id": "4a52779a3ed47fd722cfebfa869c3dd5025fcbdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5812, "license_type": "no_license", "max_line_length": 82, "num_lines": 208, "path": "/Java/F21SF Soft E Fundation/9/src/StudentList.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import java.io.File;\r\nimport java.io.FileNotFoundException;\r\nimport java.io.FileWriter;\r\nimport java.io.IOException;\r\nimport java.util.ArrayList;\r\nimport java.util.Scanner;\r\n\r\n//demonstrates using an ArrayList\r\npublic class StudentList {\r\n\r\n\tprivate ArrayList<Student> studentList;\r\n\t\r\n\t//create an empty arraylist\r\n\tpublic StudentList() {\r\n\t\tstudentList = new ArrayList<Student> ();\r\n\t}\r\n\t\r\n\tpublic void add(Student s) {\r\n\t\tstudentList.add(s);\r\n\t}\r\n\t\r\n\t//returns a report with one line per person\r\n\t//demonstrates traversing the array,\r\n\t//getting one element at a time\r\n\tpublic String getAllStudents()\r\n\t{\r\n\t\tString report = \"\";\r\n\t\tfor (Student s : studentList){\r\n\t\t\treport += String.format(\"%-6s\", s.getId());\r\n\t\t\treport += String.format(\"%-15s\", s.getName().getFullName() );\r\n\t\t\treport += String.format(\"%-4d\", s.getYear());\r\n\t\t\treport += s.getQualDetails();\r\n\t\t\treport += \"\\n\";\r\n\t\t}\r\n\t\treturn report;\r\n\t}\r\n\t\r\n\t//returns the number of elements in the list\r\n\tpublic int getSize() {\r\n\t\treturn studentList.size();\r\n\t}\r\n\t\r\n\t//returns the Staff object at specified index position\r\n\tpublic Student getAtIndex(int index) {\r\n\t\treturn studentList.get(index);\r\n\t}\r\n\t\r\n\t//returns the Staff object with a specified id\r\n\t//demonstrates searching through the array\r\n\t//and stopping by returning when a match is found\r\n public Student findById(String id)\r\n {\r\n \tfor (Student s : studentList)\r\n \t{\r\n \t\tif (s.getId().equals(id))\r\n \t\t{\r\n \t\t\treturn s;\r\n \t\t}\r\n \t}\r\n \treturn null;\r\n }\r\n \r\n //counts the number of people in a specified year\r\n //demonstrates making a count with arraylists\r\n public int getCountOfPeopleAtYear(int year) {\r\n \tint count = 0; //initialise count to 0\r\n \tfor (Student s:studentList) {\r\n \t\tif (s.getYear()==year) {\r\n \t\t\tcount++;\r\n \t\t}\r\n \t}\r\n \treturn count;\r\n }\r\n\t\r\n\r\n\t\r\n\t//works out how many people in each year,\r\n\t//then creates and returns a report\r\n //\r\n //demonstrates calculating a frequency report\r\n //i.e. how often each year occurs\r\n //it uses the value of the year as an index\r\n\tpublic String getYearsFrequencyReport() {\r\n\t\t//work out max year\r\n\t\tint maxYear = getMaxYear();\r\n\t\t//work out how many people at each year\r\n\t\tint [] freqYears = new int [maxYear];\r\n\t\tfor (Student s : studentList) {\r\n\t\t\tint y = s.getYear();\r\n\t\t\tfreqYears[y-1]++;\r\n\t\t}\r\n\t\t//create a report\r\n\t\tString report = \"NUMBER OF STUDENTS IN EACH YEAR\\n\";\r\n\t\tfor (int i = 0; i < freqYears.length; i++) {\r\n\t\t\treport += \"Year \" + (i+1) + \" : \" + freqYears[i] + \"\\n\";\r\n\t\t}\r\n\t\treturn report;\r\n\t}\r\n\t\r\n\t//calculates the maximum year that anyone is in\r\n\t//demonstrates finding a max with array lists\r\n\tpublic int getMaxYear() {\r\n\t\tint maxYear = 0;\r\n\t\tfor (Student s : studentList) {\r\n\t\t\tint yr = s.getYear();\r\n\t\t\tif (yr> maxYear) {\r\n\t\t\t\tmaxYear= yr;\r\n\t\t\t}\r\n\t\t}\t\r\n\t\treturn maxYear;\r\n\t}\r\n\t\r\n\t/**\r\n\t * writes supplied text to file\r\n\t * @param filename the name of the file to be written to\r\n\t * @param report the text to be written to the file\r\n\t */\r\n\tpublic void writeToFile(String filename, String report) {\r\n\t\r\n\t\t FileWriter fw;\r\n\t\t try {\r\n\t\t fw = new FileWriter(filename);\r\n\t\t fw.write(\"The report\\n\");\r\n\t\t fw.write(report);\r\n\t\t \tfw.close();\r\n\t\t }\r\n\t\t //message and stop if file not found\r\n\t\t catch (FileNotFoundException fnf){\r\n\t\t\t System.out.println(filename + \" not found \");\r\n\t\t\t System.exit(0);\r\n\t\t }\r\n\t\t //stack trace here because we don't expect to come here\r\n\t\t catch (IOException ioe){\r\n\t\t ioe.printStackTrace();\r\n\t\t System.exit(1);\r\n\t\t }\r\n\t}\r\n\t\r\n\t/** reads file with given name, extracting student data, creating student objects\r\n\t * and adding them to the list of students\r\n\t * Blank lines are skipped\r\n\t * Validation for integer year, missing items\r\n\t * @param filename the name of the input file\r\n\t */\r\n\tpublic void readFile(String filename) {\r\n\t\ttry {\r\n\t\t\tFile f = new File(filename);\r\n\t\t\tScanner scanner = new Scanner(f);\r\n\t\t\twhile (scanner.hasNextLine()) {\r\n\t\t\t\t//read first line and process it\r\n\t\t\t\tString inputLine = scanner.nextLine(); \r\n\t\t\t\tif (inputLine.length() != 0) {//ignored if blank line\r\n\t\t\t\t\tprocessLine(inputLine);\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t\t//if the file is not found, stop with system exit\r\n\t\tcatch (FileNotFoundException fnf){\r\n\t\t\t System.out.println( filename + \" not found \");\r\n\t\t\t System.exit(0);\r\n\t\t }\r\n\t}\r\n\t\r\n\t/**\r\n\t * Processes line, extracts data, creates Student object\r\n\t * and adds to list\r\n\t * Checks for non-numeric year and missing items\r\n\t * Will still crash if name entered without a space\r\n\t * @param line the line to be processed\r\n\t */\r\n\tprivate void processLine(String line) {\r\n\t\ttry {\r\n\t\t\tString parts [] = line.split(\",\");\r\n\t\t\tName name = new Name(parts[1]);\r\n\t\t\tString id = parts[0];\r\n\t\t\tString yearNum = parts[2];\r\n\t\t\tyearNum = yearNum.trim(); //remove any spaces\r\n\t\t\tint year = Integer.parseInt(yearNum);\r\n\t\t\t\r\n\t\t\t//the qualifications are at the end of the line\r\n\t\t\tint qualLength = parts.length - 3;\r\n\t\t\tString quals[] = new String[qualLength];\r\n\t\t\tSystem.arraycopy(parts, 3, quals, 0, qualLength);\r\n\t\t\t\r\n\t\t\t//create Student object and add to the list\r\n\t\t\tStudent s = new Student(id,name, quals, year);\r\n\t\t\tthis.add(s);\r\n\t\t}\r\n\r\n\t\t//for these two formatting errors, ignore lines in error and try and carry on\r\n\t\t\r\n\t\t//this catches trying to convert a String to an integer\r\n\t\tcatch (NumberFormatException nfe) {\r\n\t\t\tString error = \"Number conversion error in '\" + line + \"' - \" \r\n\t\t\t + nfe.getMessage();\r\n\t\t\tSystem.out.println(error);\r\n\t\t}\r\n\t\t//this catches missing items if only one or two items\r\n\t\t//other omissions will result in other errors\r\n\t\tcatch (ArrayIndexOutOfBoundsException air) {\r\n\t\t\tString error = \"Not enough items in : '\" + line\r\n\t\t\t + \"' index position : \" + air.getMessage();\r\n\t\t\tSystem.out.println(error);\r\n\t\t}\r\n\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.5783132314682007, "alphanum_fraction": 0.6385542154312134, "avg_line_length": 19.625, "blob_id": "84eef3f5e7069fe344ae57ddfe4fe7d83b418c0f", "content_id": "e9ba1a00123ae3d662b43f039ea32a87e530fbd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/Python/IndustrialProgramming/basics/lambda.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\ndef make_incrementor(n):\n return lambda x: x + n\n\nf = make_incrementor(42)\nprint (\"increment 0 by 42 \", f(0))\nprint (\"increment 1 by 43 \", f(1))\n\n" }, { "alpha_fraction": 0.35411471128463745, "alphanum_fraction": 0.4289276897907257, "avg_line_length": 11.935483932495117, "blob_id": "41c053d539bc43344192347ac1ba6a1ef99f06ea", "content_id": "c6363f263d150d0e0befb9dd5c3cd55d1d67e00b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 41, "num_lines": 31, "path": "/Interviews/amazon/sum_distances.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "A = [0, 0, 0]\n\nA[0] = 1\nA[1] = 3\nA[2] = -3\n\nB = [0, 0, 0, 0, 0, 0]\n\nB[0] = -8\nB[1] = 4\nB[2] = 0\nB[3] = 5\nB[4] = -3\nB[5] = 6\n\n\ndef solution(A):\n max_value = 0\n\n for P in range(0, len(A)):\n for Q in range(0, len(A)):\n value = A[P] + A[Q] + (Q - P)\n\n if max_value < value:\n max_value = value\n\n return max_value\n\n\nprint(solution(A))\nprint(solution(B))\n" }, { "alpha_fraction": 0.6155667304992676, "alphanum_fraction": 0.6262207627296448, "avg_line_length": 30.287036895751953, "blob_id": "8cc20096f61c09e4f1140d234f18cdec3ddf4d69", "content_id": "d1686a135f90fb5ef8b2db7f9ab983a51cef4fa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3379, "license_type": "no_license", "max_line_length": 93, "num_lines": 108, "path": "/CSharp/code-examples/thearding/threads4.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Lecture 7: Threading\n// Incrementer/Decrementer example, now with tunable lo- and hi-marks\n// This demonstrates how to indirectly pass an argument to the Incremener/Decrementer methods\n// -----------------------------------------------------------------------------\n\nusing System.Threading;\nusing System;\n\nnamespace Threads1 {\n\n class Tester {\n static void Main (string[] args) {\n if (args.Length != 2) { // expect 2 args: a low-mark and a high-mark\n\tSystem.Console.WriteLine(\"Usage: <prg> <loMark> <hiMark>\");\n } else { \n\tTester t = new Tester();\n\tt.DoTest(args);\n }\n }\n\n public void DoTest(string[] args) {\n Thread[] myThreads = {\n\tnew Thread( new ThreadStart(Decrementer)), // arg is a function from void to void\n\tnew Thread( new ThreadStart(Incrementer)) // arg is a function from void to void\n };\n\n int n = 1;\n // init the marks and make them available to Incrementer/Decrementer\n // NB: this must be done *before* launching the threads, otw we have a race condition!\n loMark = Convert.ToInt32(args[0]);\n hiMark = Convert.ToInt32(args[1]);\n // start all threads\n foreach (Thread myThread in myThreads) {\n\tmyThread.IsBackground = true;\n\tmyThread.Name = \"Thread\"+n.ToString();\n\tConsole.WriteLine(\"Starting thread {0}\", myThread.Name);\n\tmyThread.Start();\n\tn++;\n\t// add a delay in starting all threads\n\tThread.Sleep(500);\n }\n // wait for all threads to end\n foreach (Thread myThread in myThreads) {\n\tmyThread.Join();\n }\n // after all threads end print this message\n Console.WriteLine(\"All my threads are done\");\n }\n\n private int hiMark; // never increment beyond this mark\n private int loMark; // never decrement below this mark\n private int counter = 0;\n\n public void Decrementer() {\n try {\n\tConsole.WriteLine(\"[{0}] Decrementer finds a loMark of {1}.\",\n\t\t\t Thread.CurrentThread.Name, loMark);\n\t// (1) synchronise this area\n\tMonitor.Enter(this);\n\n\twhile (counter < loMark ) { // now, this uses the loMark \n\t Console.WriteLine(\"[{0}] In Decrementer. Counter: {1}. Waiting...\",\n\t\t\t Thread.CurrentThread.Name, counter);\n\t Monitor.Wait(this);\n\t}\n\n\twhile (counter > 0) {\n\t int temp = counter;\n\t temp--;\n\t Thread.Sleep(1);\n\t counter = temp;\n\t Console.WriteLine(\"[{0}] In Decrementer. Counter: {1}.\",\n\t\t\t Thread.CurrentThread.Name, counter);\n\t}\n } finally {\n\tMonitor.Exit(this);\n }\n }\n public void Incrementer() {\n try {\n\tConsole.WriteLine(\"[{0}] Incrementer finds a hiMark of {1}.\",\n\t\t\t Thread.CurrentThread.Name, hiMark);\n\t// (1) synchronise this area\n\t// Monitor.Enter(this);\n\n\twhile (counter < hiMark) { // now, this uses the hiMark \n\t // (2) more fine-grained control like this:\n Monitor.Enter(this);\n\t int temp = counter;\n\t temp++;\n\t Thread.Sleep(1);\n\t counter = temp;\n\t Console.WriteLine(\"[{0}] In Incrementer. Counter: {1}.\",\n\t\t\t Thread.CurrentThread.Name, counter);\n\t // (2) more fine-grained control like this:\n\t Monitor.Pulse(this); // inform waiting threads of the change\n\t Monitor.Exit(this); // leave monitor\n\t Thread.Sleep(1); // give other threads time to work\n\t}\n\t//Monitor.Pulse(this); // (1) release lock after all increments!\n } finally {\n\tConsole.WriteLine(\"[{0}] Exiting ...\",\n\t\t\t Thread.CurrentThread.Name);\n\tMonitor.Exit(this);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5253682732582092, "alphanum_fraction": 0.5581014752388, "avg_line_length": 23.440000534057617, "blob_id": "a63932e3759c377db3bfd69f08c5f6170fd21874", "content_id": "3f830d543764c6689c60a8bc1ab274d73ed9ee42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 611, "license_type": "no_license", "max_line_length": 80, "num_lines": 25, "path": "/CSharp/code-examples/objects/points0.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Example points with public fields\n// From Lecture 3: C# Basics\n// -----------------------------------------------------------------------------\n\nusing System;\nclass Point{\n // public access modifier: no restrictions on access \n\tpublic int x;\n\tpublic int y;\n\n // constructor with initialisation\n\tpublic Point(int x, int y){\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n}\n\nclass Test{\n\tpublic static void Main(){\n\t\tPoint point1 = new Point(5,10);\n\t\tPoint point2 = new Point(20, 15);\n\t\tConsole.WriteLine(\"Point1({0}, {1})\", point1.x, point1.y);\n\t\tConsole.WriteLine(\"Point2({0}, {1})\", point2.x, point2.y);\n\t}\n}\n" }, { "alpha_fraction": 0.5736090540885925, "alphanum_fraction": 0.5837846994400024, "avg_line_length": 27.74056625366211, "blob_id": "58c821d5bdbec3c180c99591345a0b8bc6e72f49", "content_id": "4f84e8dacb4d764b6ae6f89a391aa75e38cb4952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 12186, "license_type": "no_license", "max_line_length": 157, "num_lines": 424, "path": "/CSharp/code-examples/advanced/container.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Container example using advanced C# constructs:\n// . indexers\n// . generics\n// . collections\n// . exceptions\n// . delegates\n// -----------------------------------------------------------------------------\n\nusing System;\nusing System.Collections;\nusing System.Threading.Tasks;\n\npublic class MyContainer<T>: // a collection, generic over element type T\n IEnumerable, // it implements IEnumerable to use foreach loops etc\n ICollection, // it implements ICollection to use Count etc\n ICloneable // it implements the Clone method\n where T:IComparable { \n // T:ICloneable { // T needs to be IComparable, to implement sorting\n\n private T[] items; // contents\n private int ctr = 0; // first free slot in array\n public const int max_items = 16*256; // hard-wired upper bound\n // unused; see properties below\n // private const bool IsReadOnly = false; \n // private const bool IsSynchronized = false; \n private object containerLock = new { }; // any non-null object will do as lock\n\n // exceptions\n public class ContainerException: System.Exception {\n public ContainerException(string msg): base(msg) { }\n }\n\n // constructor\n public MyContainer (params T[] inits) { // params allows a list of arguments rather than array\n items = new T[max_items]; // could use inits.CopyTo(this.items, 0) here\n foreach (T t in inits) {\n items[ctr++] = t;\n }\n }\n\n#region ICollection Members\n // -------------------------------------------------------\n // ICollection implementation\n // see http://msdn.microsoft.com/en-us/library/92t2ye13.aspx\n\n public void Add (T t) {\n if (ctr >= items.Length) {\n throw new ContainerException(String.Format(\"Reached max length of container: {0}\", items.Length));\n } else {\n items[ctr++] = t;\n }\n }\n\n public void Clear() {\n ctr=0;\n }\n\n public bool Contains(T x) {\n foreach (T t in this) {\n if (t.CompareTo(x)==0) { // uses method from IComparable\n\treturn true;\n }\n }\n return false;\n }\n\n public bool Remove(T x) {\n throw new ContainerException(\"Remove method not implemented for MyContainer\");\n }\n\n public void CopyTo(T[] arr, int arrInd) {\n int i = arrInd;\n foreach (T t in this) {\n arr[i++] = t;\n }\n }\n\n public void CopyTo(Array arr, int index) {\n int i = index;\n foreach (T t in this) {\n arr.SetValue(t, i++);\n }\n }\n\n // indexer\n public T this[int index] {\n get {\n if (index<0 || index>=this.Count) {\n\tthrow new ContainerException(String.Format(\"get: index {0} out of bounds: [{1},{2}[\", index, 0, this.Count));\n } else {\n return items[index];\n }\n }\n set {\n if (index >= ctr) {\n\tthrow new ContainerException(String.Format(\"set: index {0} out of bounds: [{1},{2}[\", index, 0, this.Count));\n } else {\n items[index] = value;\n }\n }\n }\n\n // number of elements in the collection\n public int Count {\n get { return ctr; }\n }\n\n public bool IsReadOnly { get { return false; } }\n\n public bool IsSynchronized { get { return false; } }\n\n public object SyncRoot { get { return containerLock; } }\n#endregion\n\n#region IEnumerator Members\n // -------------------------------------------------------\n // IEnumerator implementation \n // see http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx\n\n public IEnumerator GetEnumerator() { \n return (IEnumerator) new MyEnumerator(this);\n }\n\n private class MyEnumerator : IEnumerator {\n private int curr_idx;\n private MyContainer<T> this_cont;\n\n public MyEnumerator (MyContainer<T> cont) {\n this.curr_idx = -1; // NB: needs to start with -1; \n this.this_cont = cont;\n }\n\n public bool MoveNext( ) {\n if (curr_idx>=this.this_cont.ctr-1) {\n\treturn false;\n } else {\n\tcurr_idx++;\n\treturn true;\n }\n }\n\n public void Reset( ) {\n curr_idx=-1;\n }\n\n public object Current {\n get { return this_cont[curr_idx]; }\n }\n }\n#endregion\n\n // obsolete:\n // private int GetNumEntries() { return ctr; }\n\n#region ICloneable Members\n public object Clone() {\n return this.MemberwiseClone();\n }\n#endregion\n\n // -------------------------------------------------------\n // specialised methods\n\n public void print() {\n // make use of IEnumerable implementation\n IEnumerator iter = this.GetEnumerator();\n Console.Write(\"Container contains: [\");\n /* get ','s right */\n if (iter.MoveNext()) {\n Console.Write(\"{0}\", iter.Current);\n }\n while (iter.MoveNext()) { \n Console.Write(\",{0}\", iter.Current);\n }\n Console.WriteLine(\"]\");\n }\n\n // swap i-th and j-th element of the array\n private void Swap(int i, int j) {\n if (i==j) {\n return;\n } else {\n T tmp = items[i];\n items[i] = items[j];\n items[j] = tmp;\n }\n }\n\n // -------------------------------------------------------\n // delegates used in this class\n\n public delegate int CompareDelegate(T s1, T s2);\n\n public MyContainer<T> Merge(CompareDelegate cmp, MyContainer<T> other) {\n int i = 0;\n int j = 0;\n bool finished = false;\n MyContainer<T> res = new MyContainer<T>();\n\n while (!finished) {\n if (cmp(this.items[i], other.items[j]) > 0) {\n\tres.Add(other.items[j]);\n\tj++;\n } else {\n\tres.Add(this.items[i]);\n\ti++;\n }\t \n finished = i>=this.Count || j>=other.Count;\n }\n for(int k = i; k<this.Count; k++) {\n res.Add(this.items[k]);\n }\n for(int k = j; k<other.Count; k++) {\n res.Add(other.items[k]);\n }\n return res;\n }\n\n public MyContainer<T> MergeFromTo(CompareDelegate cmp, int from, int mid, int to) {\n int i = from;\n int j = mid;\n bool finished = false;\n // TODO: nuke new container; this should be INPLACE!!!!\n MyContainer<T> res = new MyContainer<T>();\n\n while (!finished) {\n if (cmp(this.items[i], this.items[j]) > 0) {\n\tres.Add(this.items[j]);\n\tj++;\n } else {\n\tres.Add(this.items[i]);\n\ti++;\n }\t \n finished = i>=mid || j>=to;\n }\n for(int k = i; k<mid; k++) {\n res.Add(this.items[k]);\n }\n for(int k = j; k<to; k++) {\n res.Add(this.items[k]);\n }\n return res;\n }\n\n public void ParSort(CompareDelegate cmp) {\n int m = this.Count / 2;\n Parallel.Invoke(\n () => SortFromTo(cmp, 0, m-1),\n () => SortFromTo(cmp, m, this.Count-1));\n }\n\n public void Sort(CompareDelegate cmp) {\n SortFromTo(cmp, 0, this.Count-1);\n }\n\n public void SortFromTo(CompareDelegate cmp, int from, int to) {\n // implements a naive bubble-sort\n bool swapped = false;\n\n if (from<0 || to>this.Count-1) {\n throw new System.Exception(\"SortFromTo: out of bounds\");\n }\n do {\n swapped = false;\n for (int i = from; i<to; i++) {\n\tif (cmp(items[i], items[i+1]) > 0) {\n\t Swap(i, i+1);\n\t swapped = true;\n\t}\n }\n } while (swapped);\n }\n\n // an equivalent implementation using interface IComparable rather than delegates\n public void Sort0() { // no argument; the IComparable interface provides CompareTo\n // implements a naive bubble-sort\n bool swapped = false;\n do {\n swapped = false;\n for (int i = 0; i<=this.Count-2; i++) {\n\tif (items[i].CompareTo(items[i+1]) > 0) {\n\t Swap(i, i+1);\n\t swapped = true;\n\t}\n }\n } while (swapped);\n }\n\n public bool IsSorted(CompareDelegate cmp) {\n for (int i = 0; i<=this.Count-2; i++) {\n if (cmp(items[i], items[i+1]) < 0) { // error case\n\treturn false;\n }\n }\n return true;\n }\n\n // From: http://msdn.microsoft.com/en-us/library/ff963551.aspx\n /*\n static void SequentialQuickSort(int[] array, int from, int to)\n {\n if (to - from <= Threshold)\n {\n InsertionSort(array, from, to);\n }\n else\n {\n int pivot = from + (to - from) / 2;\n pivot = Partition(array, from, to, pivot);\n SequentialQuickSort(array, from, pivot);\n SequentialQuickSort(array, pivot + 1, to);\n }\n }\n */\n}\n\npublic class Tester {\n // instances for ComparerDelegate\n /* not used any more\n private int str_lt (string s1, string s2) { \n return String.Compare(s1,s2);\n }\n private int str_gt (string s1, string s2) { \n return (-1)*String.Compare(s1,s2);\n }\n */\n private int int_lt (int i, int j) { \n if (i==j) {\n return 0;\n } else {\n if (i<j) {\n\treturn -1;\n } else {\n\treturn 1;\n }\n }\n }\n private int int_gt (int i, int j) { \n return (-1)*int_lt(i,j);\n }\n\n public static void Main () {\n MyContainer<string> cont = new MyContainer<string>(\"One\", \"Two\", \"Three\", \"Four\");\n Tester tst = new Tester();\n\n Console.WriteLine(\"Container of strings initialised, containing {0} items\", cont.Count);\n // direct write access\n try {\n cont[4] = \"Five\";\n } catch (MyContainer<string>.ContainerException e) {\n Console.WriteLine(e.Message);\n Console.WriteLine(\"Implementation restriction: can only write to an existing field; currently only fields up to {0} exist\", cont.Count-1);\n }\n\n // direct read access\n Console.WriteLine(\"Printing contents using for loop: \");\n for (int i = 0; i<cont.Count; i++) {\n Console.WriteLine(\"cont[{0}]: {1}\", i, cont[i]);\n }\n // make use of IEnumerable implementation\n Console.WriteLine(\"Printing contents using foreach loop: \");\n foreach (string s in cont) {\n Console.WriteLine(\"Value: {0}\", s);\n }\n Console.WriteLine(\"Sorting contents alphabetically (delegate version) ...\");\n MyContainer<string>.CompareDelegate cmp_lt = new MyContainer<string>.CompareDelegate(String.Compare); // tst.lt\n cont.Sort(cmp_lt);\n cont.print();\n Console.WriteLine(\"Reverse sorting contents alphabetically (delegate version) ...\");\n MyContainer<string>.CompareDelegate cmp_gt = new MyContainer<string>.CompareDelegate((string s1, string s2) => { return (-1)*String.Compare(s1,s2) ; }); \n cont.Sort(cmp_gt);\n cont.print();\n Console.WriteLine(\"Sorting contents alphabetically (IComparable version) ...\");\n cont.Sort0();\n cont.print();\n\n // container with int contents\n int [] int_arr = new int[] { 8, 4, 6, 2 };\n MyContainer<int> int_cont = new MyContainer<int>(int_arr);\n Console.WriteLine(\"Container of ints initialised, containing {0} items\", int_cont.Count);\n Console.WriteLine(\"Sorting contents ...\");\n MyContainer<int>.CompareDelegate cmp_int_lt = new MyContainer<int>.CompareDelegate(tst.int_lt); // tst.lt\n int_cont.Sort(cmp_int_lt);\n int_cont.print();\n Console.WriteLine(\"Reverse sorting contents ...\");\n MyContainer<int>.CompareDelegate cmp_int_gt = new MyContainer<int>.CompareDelegate(tst.int_gt);\n int_cont.Sort(cmp_int_gt);\n int_cont.print();\n Console.WriteLine(\"Sorting contents (IComparable version) ...\");\n int_cont.Sort0();\n int_cont.print();\n\n // -----------------------------------------------------------------------------\n // Parallelism Example:\n\n\n // Generate a sizable list, and sort it in ascending and descending order, in parallel:\n // MyContainer<int>.ComparDelegate[] cmps = new MyContainer<int>.ComparDelegate[2] { cmp_int_lt, cmp_int_gt };\n Random rg = new Random(1701); // fix a seed for deterministic results\n MyContainer<int> ic1 = new MyContainer<int>();\n for (int i = 0; i < MyContainer<int>.max_items; i++) {\n ic1.Add(rg.Next());\n }\n // Console.WriteLine(\"Input array:\"); ic1.print();\n MyContainer<int> ic2 = (MyContainer<int>)ic1.Clone();\n Console.WriteLine(\"Sorting a random array ...\");\n /* sequential code: */\n ic1.Sort(cmp_int_lt);\n ic2.Sort(cmp_int_gt);\n /* parallel code: \n Parallel.Invoke( // generate two parallel threads\n\t\t () => ic1.Sort(cmp_int_lt),\n () => ic2.Sort(cmp_int_gt));\n */\n /* parallelised sorting algorithm: \n ic1.ParSort(cmp_int_lt);\n ic2.ParSort(cmp_int_gt);\n */\n // Console.WriteLine(\"Sorted (ascending):\"); ic1.print();\n Console.WriteLine(\"Sorted?: {0}\", ic1.IsSorted(cmp_int_lt).ToString());\n // Console.WriteLine(\"Sorted (descending):\"); ic2.print();\n Console.WriteLine(\"Sorted?: {0}\", ic2.IsSorted(cmp_int_gt).ToString());\n }\n}\n" }, { "alpha_fraction": 0.43523314595222473, "alphanum_fraction": 0.4455958604812622, "avg_line_length": 11.483870506286621, "blob_id": "ef59342c7b87f97d4b679590f8c2dca37550a7c2", "content_id": "778d632461168597461ed95b3b0ff63afadac9cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 386, "license_type": "no_license", "max_line_length": 47, "num_lines": 31, "path": "/CSharp/on-lecture/TestObject.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "public class Test\n{\n private int x;\n private int y;\n\n public int PointX\n {\n get\n {\n return x;\n }\n set\n {\n this.x = value;\n }\n }\n}\n\npublic class Runny\n{\n public static void Main ()\n {\n\n Test test1 = new Test();\n\n test1.PointX = 1;\n\n System.Console.WriteLine(test1.PointX);\n\n }\n}" }, { "alpha_fraction": 0.6270492076873779, "alphanum_fraction": 0.631147563457489, "avg_line_length": 10.136363983154297, "blob_id": "2978c5c328fcfd0422d5e4c43124a88cad33061e", "content_id": "45927364db80f29964ac53feba193a2a0ed104a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 244, "license_type": "no_license", "max_line_length": 35, "num_lines": 22, "path": "/CSharp/on-lecture/serialization.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "public class Person\t {\n \n private string fName = \"Marcin\";\n private string sName = \"K\";\n\n public toString(){\n\n }\n}\n\nclass Student : Person\n{\n\tpublic int mNUmber = 0;\n\n\tpublic toString(){\n\tstring base_str =\tbase.toString();\n\n\n\treturn \n\t}\n\n}" }, { "alpha_fraction": 0.6007751822471619, "alphanum_fraction": 0.6007751822471619, "avg_line_length": 23, "blob_id": "08587983da6603172d4907a1513b7f62eb6ab53b", "content_id": "47f49d94245200e25b66f5e910598885d68f7e6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1034, "license_type": "no_license", "max_line_length": 64, "num_lines": 43, "path": "/CSharp/coursework/MarcinK mpk31/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/controllers/HistoryController.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\n\nnamespace WebBrowser_OuterSpace.models\n{\n public class HistoryController\n {\n public void addToHistory(String url, int tabID)\n {\n HistoryCollection hc = HistoryCollection.Instance;\n hc.addToHistoryPerTab(url, tabID);\n }\n\n public void loadHistory()\n {\n HistoryCollection hc = HistoryCollection.Instance;\n hc.readHistoryConfig();\n }\n\n public String getHistoryPageURL(int tabID, int deepness)\n {\n \n HistoryCollection hc = HistoryCollection.Instance;\n return hc.getHistoryURL(tabID, deepness);\n }\n\n\n public void recordHistory(String url, int tabID)\n {\n\n HistoryCollection hc = HistoryCollection.Instance;\n hc.writeRecordHistory(url, tabID);\n }\n\n\n public ArrayList getHistory()\n {\n HistoryCollection hc = HistoryCollection.Instance;\n return hc.getFullhistory();\n\n }\n }\n}\n" }, { "alpha_fraction": 0.5982906222343445, "alphanum_fraction": 0.612942636013031, "avg_line_length": 19.350000381469727, "blob_id": "86c3defa47b317952a59195f223c32d106b97da8", "content_id": "b3525cdcd8b24ad991905304783b0eb51ecf4fe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 819, "license_type": "no_license", "max_line_length": 66, "num_lines": 40, "path": "/Python/CodingTests/Implementation/cut-the-sticks.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# N = int(input())\n# items = input().split()\n\nN = 6\nitems = ['5', '4', '4', '2', '2', '8']\n\n\nitems_int = [int(x) for x in items]\nshortening = []\nshortening_list = []\n\n\ndef cut_the_sticks(sticks):\n if len(sticks) == 0:\n sticks.append(0)\n return\n else:\n sticks_sorter = shorten_sticks(sticks)\n shortening.append(sticks_sorter)\n cut_the_sticks(sticks_sorter)\n\n\ndef shorten_sticks(sticks):\n shortest_stick = min(sticks)\n shortened_sticks = []\n shortening = 0\n\n for stick in sticks:\n shortened_sticks.append(stick - shortest_stick)\n shortening += 1\n\n shortened_sticks = [x for x in shortened_sticks if x is not 0]\n shortening_list.append(shortening)\n return shortened_sticks\n\n\ncut_the_sticks(items_int)\n\nfor x in shortening_list:\n print(x)\n \n" }, { "alpha_fraction": 0.6319018602371216, "alphanum_fraction": 0.6403964161872864, "avg_line_length": 29.056737899780273, "blob_id": "f45c0c81ae5fcfaea5adf2a7ade4773d3be6adbe", "content_id": "c7d15848e9f2860636de2c534878c33166300154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4238, "license_type": "no_license", "max_line_length": 96, "num_lines": 141, "path": "/Python/IndustrialProgramming/coursework/app/routes.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from flask import Flask, jsonify, request, render_template\n# My classes\nfrom classes.book_data import BookData\nfrom classes.book_analysis import BookAnalysis\nfrom classes.browser_analysis import BrowserAnalysis\nfrom classes.user_analysis import UserAnalysis\n\napp = Flask(__name__)\n\n\[email protected]('/')\ndef home():\n return render_template('home.html')\n\n\[email protected]('/task-1')\ndef task_1():\n return render_template('task-1.html')\n\n\[email protected]('/task-2')\ndef task_2():\n return render_template('task-2.html')\n\n\[email protected]('/api/task-2', methods=['POST'])\ndef api_task_2():\n \"\"\"Perform task from task 2 \"\"\"\n uuid = request.form['uuid']\n bs = BookAnalysis(app.dt)\n try:\n #By Countries\n result_countries = bs.counries_by_book(uuid)\n print(\"Views by country and Document UUID\")\n print(result_countries)\n bs.counries_by_book_plot(result_countries, uuid)\n # By Continent\n print(\"Views by continet and Document UUID\")\n result_continent = bs.continent_by_book(result_countries, uuid)\n bs.continet_by_book_plot(result_continent, uuid)\n print(result_continent)\n return jsonify(result_countries)\n except Exception, err:\n return jsonify({'exception': str(err)})\n\n\[email protected]('/task-3')\ndef task_3():\n \"\"\"Create a View for task 3 \"\"\"\n return render_template('task-3.html')\n\n\[email protected]('/api/task-3', methods=['POST'])\ndef api_task_3():\n \"\"\"Perform task from task 3 \"\"\"\n ba = BrowserAnalysis(app.dt)\n try:\n ba.browser_usage_plot()\n ba.general_usage_plot()\n return jsonify({\"succesfully\": {}})\n except Exception, err:\n return jsonify({'exception': str(err)})\n\n\[email protected]('/task-4')\ndef task_4():\n \"\"\"Create view for Task 4\"\"\"\n return render_template('task-4.html')\n\n\[email protected]('/api/task-4', methods=['POST'])\ndef api_task_4():\n \"\"\"Perform task from task 4 \"\"\"\n ra = UserAnalysis(app.dt)\n try:\n number = int(request.form['numbers'])\n readers_data = ra.best_readers_data(number)\n print(\"Most active users data: \")\n print(readers_data)\n return jsonify({\"succesfully\": readers_data})\n except Exception, err:\n return jsonify({'exception': str(err)})\n\n\[email protected]('/task-5')\ndef task_5():\n return render_template('task-5.html')\n\n\[email protected]('/api/task-5a', methods=['POST'])\ndef api_task_5a():\n \"\"\"Perform task from task 5 for books \"\"\"\n ra = UserAnalysis(app.dt)\n try:\n book_uuid = request.form['book_uuid']\n visitors_books_alike = ra.book_visitors_alike(book_uuid)\n print(\"Similar books based on user reader\")\n print(visitors_books_alike)\n book_alike_sorted = ra.book_alike_sorted(book_uuid, ra.sorter)\n print(\"Sorted books alike by readership\")\n print(book_alike_sorted)\n return jsonify({\"book_alike\": visitors_books_alike, \"alike_sorted\": book_alike_sorted})\n except Exception, err:\n return jsonify({'exception': str(err)})\n\n\[email protected]('/api/task-5b', methods=['POST'])\ndef api_task_5b():\n \"\"\"Perform task from task 5 for users\"\"\"\n ra = UserAnalysis(app.dt)\n try:\n user_uuid = request.form['user_uuid']\n user_books_alike = ra.user_visitors_alike(user_uuid)\n print(\"Similar users based on common book\")\n print(user_books_alike)\n user_book_alike_sorted = ra.users_alike_sorted(user_uuid, ra.sorter)\n print(\"Similar users sorted by readership\")\n print(user_book_alike_sorted)\n return jsonify({\"user_alike\": user_books_alike, \"alike_sorted\": user_book_alike_sorted})\n except Exception, err:\n return jsonify({'exception': str(err)})\n\n\[email protected]_request\ndef add_header(response):\n \"\"\"\n Add headers to both force latest IE rendering engine or Chrome Frame,\n and also to cache the rendered page for 10 minutes.\n Turn off caching\n \"\"\"\n response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'\n response.headers['Cache-Control'] = 'public, max-age=0'\n return response\n\n\nif __name__ == '__main__':\n \"\"\"Toghether with starting Flask load Dataframe\"\"\"\n # Load DataFrame\n bd = BookData('data/issuu_full.json')\n app.dt = bd.build_data_frame()\n app.run(debug=True)\n" }, { "alpha_fraction": 0.6603585481643677, "alphanum_fraction": 0.6713147163391113, "avg_line_length": 30.34375, "blob_id": "ea7439d8a8d7dba219b783a59d158c4479eaceeb", "content_id": "df13483b236333d8604be14b6c6e19b74f613d74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1004, "license_type": "no_license", "max_line_length": 121, "num_lines": 32, "path": "/CSharp/code-examples/advanced/delegates2.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Lecture 6: Advanced C# Constructs: Delegates\n\nusing System;\n\n// simple higher-order example, using delegates\n// this class takes an int -> int function and applies it twice\npublic class Twice {\n // delegate, specifying the type of the function argument\n public delegate int Worker(int i);\n\n // the higher-order function twice applies the\n // worker function twice\n public static int twice(Worker worker, int x) {\n return worker(worker(x));\n }\n}\n\nclass TestClass {\n public static int Double(int val) {\n return val*2;\n }\n\n public static void Main(string []args) {\n if (args.Length != 1) { // expect 1 arg: value to double\n System.Console.WriteLine(\"Provide an int value as argument\");\n } else { \n int x = Convert.ToInt32(args[0]);\n System.Console.WriteLine(\"Applying double once on {0} gives {1}\", x, TestClass.Double(x));\n System.Console.WriteLine(\"Applying double twice, using class Twice, on {0} gives {1}\", x, Twice.twice(Double, x));\n }\n }\n}\n\n" }, { "alpha_fraction": 0.6382978558540344, "alphanum_fraction": 0.6382978558540344, "avg_line_length": 19.88888931274414, "blob_id": "b07421af0825bc651702026ac9b90377bb1c561e", "content_id": "5aba59c0805f18b22ca6254de72f13136dea0c26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 188, "license_type": "no_license", "max_line_length": 49, "num_lines": 9, "path": "/Python/IndustrialProgramming/advanced/exc1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Testing exceptions\n\nwhile True:\n try:\n x = int(raw_input(\"Please enter a number: \"))\n break\n except ValueError:\n print (\"Not a valid number. Try again...\")\n" }, { "alpha_fraction": 0.4554655849933624, "alphanum_fraction": 0.4908906817436218, "avg_line_length": 21.5238094329834, "blob_id": "c404b13d2b633437c3b3baf390da87d5047ef0ba", "content_id": "0d21a458df2ccec6f787e57220cefd48ca3945aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 988, "license_type": "no_license", "max_line_length": 58, "num_lines": 42, "path": "/CSharp/code-examples/basics/arr.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// very simple array functions\r\n\r\nclass Arrays {\r\n static void Main() {\r\n int[] arr1 = {0,1,2,3,4,5,6,7,8,9};\r\n int[] arr2 = new int[10];\r\n\r\n for (int i = 0; i<arr2.Length; i++) {\r\n\tarr2[i] = i;\r\n }\r\n System.Console.WriteLine(\"arr1 = \" + showArr(arr1));\r\n System.Console.WriteLine(\"arr2 = \" + showArr(arr2));\r\n if (eqArr(arr1,arr2)) {\r\n\tSystem.Console.WriteLine(\"Both arrays are equal!\");\r\n } else {\r\n\tSystem.Console.WriteLine(\"The arrays are NOT equal!\");\r\n }\r\n } \r\n\r\n static bool eqArr(int[] arr1, int[] arr2) {\r\n int n1 = arr1.Length, n2 = arr2.Length;\r\n if (n1!=n2) { return false; }\r\n for (int i = 0; i<n1; i++) {\r\n if (arr1[i]!=arr2[i]) {\r\n\treturn false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n // useful for testing\r\n static string showArr(int[] arr) {\r\n string s = \"\";\r\n foreach (int i in arr) {\r\n if (s!=\"\") {\r\n s += ',';\r\n }\r\n s += i.ToString();\r\n }\r\n return s;\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.6791979670524597, "alphanum_fraction": 0.689223051071167, "avg_line_length": 29.69230842590332, "blob_id": "cd85088c26068be89f29e4afc0e3faa5e36fcbe9", "content_id": "8567d818f1568235e1895730bf7273664db3456b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "no_license", "max_line_length": 83, "num_lines": 13, "path": "/Python/IndustrialProgramming/advanced/props1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Simple example of properties\n\nclass Rectangle(object):\n def __init__(self, width, height):\n self.width = width\n self.height = height\n # this generates a read only property\n area = property(\n lambda self: self.width * self.height, # anonymous function, computing the area\n doc=\"Rectangle area (read only).\")\n\nprint(\"Area of a 5x2 rectange: \", Rectangle(5,2).area)\n" }, { "alpha_fraction": 0.6045976877212524, "alphanum_fraction": 0.6045976877212524, "avg_line_length": 19.619047164916992, "blob_id": "59d8775be3d7a17ea66e39695c6c9e73180cd938", "content_id": "55b4c6dc1efba893cf745fe51738ac333a2f5397", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 67, "num_lines": 21, "path": "/Python/CodingTests/Strings/panagrams.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\n# sentence = string(input())\n\nsentence = \"We promptly judged antique ivory buckles for the prize\"\n\n\ndef is_paragram(string):\n panagram = \"The quick brown fox jumps over the lazy dog\"\n is_para = True\n\n for s in panagram.lower():\n if s not in string.lower():\n is_para = False\n break\n\n if is_para is False:\n print(\"not pangram\")\n else:\n print(\"pangram\")\n\n\nis_paragram(sentence)\n" }, { "alpha_fraction": 0.5797373652458191, "alphanum_fraction": 0.5891181826591492, "avg_line_length": 23.285715103149414, "blob_id": "11ce0b087382661211ec789e8df5ac9b52ea7667", "content_id": "d5901d5ab86386e17dd75298f932dba223fb9e3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 533, "license_type": "no_license", "max_line_length": 54, "num_lines": 21, "path": "/Java/F21AS Advanced Software Engineering/Week 7 Threads II/src/Vars/Producer.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\r\npublic class Producer implements Runnable {\r\n\tprivate SharedObject so;\r\n\t\r\n\tpublic Producer (SharedObject so) { this.so = so; }\r\n\t\r\n\tpublic void run() {\r\n\t\tint i = 0;\r\n\t\twhile ( i < 8){\r\n\t\t\t//sleep\r\n\t\t\ttry { Thread.sleep(80); }\r\n\t\t\tcatch (InterruptedException e) { }\r\n\t\t\t//try to put number\r\n\t\t\tboolean success = so.put(i);\r\n\t\t\t//increase counter if successful\r\n\t\t\tif (success) { i++; }\r\n\t\t\t//record that there will be no more\r\n\t\t\t//otherwise consumer will never stop looking\r\n\t\t\tif (i == 8) { so.setDone(); }\r\n\t\t}\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6382978558540344, "alphanum_fraction": 0.6382978558540344, "avg_line_length": 16.27777862548828, "blob_id": "a70dc863d46265a9dabc653a46c46ac1dc65dfc6", "content_id": "b441d903150ebdc5aac100c92a77c18968dd8a9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 329, "license_type": "no_license", "max_line_length": 42, "num_lines": 18, "path": "/Java/F21AS Advanced Software Engineering/Week 2 Concordance/src/ConcordMainAnswers.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import javax.swing.JOptionPane;\r\npublic class ConcordMainAnswers {\r\n\r\n\t/**\r\n\t * @param args\r\n\t */\r\n\tpublic static void main(String[] args) {\r\n\t\tConcordAnswers c = new ConcordAnswers();\r\n\t\tc.process(\"in.txt\");\r\n\t\t\r\n\t\tc.printWordsOnly();\r\n\t\t\r\n\t\tc.printLineNumbersForWord(\"JAVA\");\r\n\t\t\r\n\t\tc.printLineNumbersForWord(\"ARE\");\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5587813854217529, "alphanum_fraction": 0.5867383480072021, "avg_line_length": 32.024391174316406, "blob_id": "74988fd19e7090fe6f120ec86c9f835cfb4c1afb", "content_id": "78e474861f64c49de80aa4db28a49305825f928c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2790, "license_type": "no_license", "max_line_length": 79, "num_lines": 82, "path": "/Java/F21AS Advanced Software Engineering/Week 6 MVC/src/views/AnalogDisplay.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package views;\r\n//simplified by Monica from Sun's Clock applet demo\r\n\r\n\r\nimport interfaces.Observer;\r\nimport java.awt.*;\r\nimport javax.swing.*;\r\nimport model.Clock;\r\npublic class AnalogDisplay extends JPanel implements Observer\r\n{\r\n\tprivate Clock clockdata;\r\n\r\n\tprivate int lastxm,lastym, lastxh, lastyh; // Dimensions used to draw hands \r\n private Font clockFaceFont; // Font for number display on clock\r\n private Color handColor; // Color of main hands and dial\r\n private Color numberColor; // Color of numbers\r\n private int xcenter = 125, ycenter = 75; // Center position\r\n private int xh, yh, xm, ym;\t\r\n\tpublic AnalogDisplay (Clock clock)\r\n\t{\r\n\t\tsuper();\r\n\t\tthis.clockdata = clock;\t\r\n\t\tclock.registerObserver(this);\r\n lastxm = lastym = lastxh = lastyh = 0;\r\n xh = yh = xm = ym = 0;\r\n clockFaceFont = new Font(\"Serif\", Font.BOLD, 14);\r\n handColor = Color.BLUE;\r\n numberColor = Color.BLACK;\r\n this.setSize(150,150);\r\n update();\r\n\t}\r\n\t\r\n\tpublic void update()\r\n\t{ \r\n int m = clockdata.getRemMins();\r\n int h = clockdata.getWholeHours();\r\n // Set position of the ends of the hands\r\n xm = (int) (Math.cos(m * Math.PI / 30 - Math.PI / 2) * 40 + xcenter);\r\n ym = (int) (Math.sin(m * Math.PI / 30 - Math.PI / 2) * 40 + ycenter);\r\n xh = (int) (Math.cos((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30\r\n + xcenter);\r\n yh = (int) (Math.sin((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30\r\n + ycenter);\r\n repaint();\r\n\t}\t\r\n\t\r\n\tpublic void paintComponent(Graphics g) \r\n\t{\r\n\t\tsuper.paintComponent(g);\r\n\t\tg.setFont(clockFaceFont);\r\n\t\t// Erase if necessary\r\n\t\tthis.setOpaque(false);\r\n\t\tg.setColor(getBackground());\r\n\t\tif (xm != lastxm || ym != lastym) {\r\n\t\t\tg.drawLine(xcenter, ycenter-1, lastxm, lastym);\r\n\t\t\tg.drawLine(xcenter-1, ycenter, lastxm, lastym); \r\n\t\t}\r\n\t\tif (xh != lastxh || yh != lastyh) {\r\n\t\t\tg.drawLine(xcenter, ycenter-1, lastxh, lastyh);\r\n\t\t\tg.drawLine(xcenter-1, ycenter, lastxh, lastyh); \r\n\t\t}\r\n\r\n // Draw the circle and numbers\r\n g.setColor(handColor);\r\n g.drawOval(xcenter-50, ycenter-50, 100, 100);\r\n g.setColor(numberColor);\r\n g.drawString(\"9\", xcenter-45, ycenter+3); \r\n g.drawString(\"3\", xcenter+40, ycenter+3);\r\n g.drawString(\"12\", xcenter-5, ycenter-37);\r\n g.drawString(\"6\", xcenter-3, ycenter+45);\r\n \r\n\t\t// Draw date and hands\r\n\t\tg.setColor(numberColor);\r\n\t\tg.setColor(handColor);\r\n\t\tg.drawLine(xcenter, ycenter-1, xm, ym);\r\n\t\tg.drawLine(xcenter-1, ycenter, xm, ym);\r\n\t\tg.drawLine(xcenter, ycenter-1, xh, yh);\r\n\t\tg.drawLine(xcenter-1, ycenter, xh, yh);\r\n\t\tlastxm = xm; lastym = ym;\r\n\t\tlastxh = xh; lastyh = yh;\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.6716980934143066, "alphanum_fraction": 0.6867924332618713, "avg_line_length": 24.5, "blob_id": "24fcc3d0e9f9af8005f00f684bc82db5e8ada06f", "content_id": "5371a321ef6b13b87c2c171ce9ee08f134ef0d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 265, "license_type": "no_license", "max_line_length": 50, "num_lines": 10, "path": "/Java/F21AS Advanced Software Engineering/Week 1 Excepions/src/StaffNameComparator.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "//defines an ordering on Staff objects on the name\r\n\r\nimport java.util.Comparator;\r\npublic class StaffNameComparator \r\n implements Comparator<Staff>\r\n{\r\n\tpublic int compare(Staff s1, Staff s2) {\r\n\t\treturn s1.getName().compareTo(s2.getName());\r\n\t}\r\n}\r\n" }, { "alpha_fraction": 0.47694334387779236, "alphanum_fraction": 0.5039525628089905, "avg_line_length": 24.299999237060547, "blob_id": "bb790daf1f62896a53adbab5345facc415f78441", "content_id": "ddb1c620a82643ceb4641f546de01c651c9e7430", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1518, "license_type": "no_license", "max_line_length": 85, "num_lines": 60, "path": "/CSharp/code-examples/objects/points2.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Example points with properties to access fields\n// From Lecture 3: C# Basics\n// -----------------------------------------------------------------------------\n\nusing System;\nclass Point\n{\n // private access modifier: only visible in this class\n private int x;\n private int y;\n\n // using properties to get and set the contents of x and y\n // Q: is there a shorter way to write this code?\n public int PointX\n {\n get\n {\n return x;\n }\n set\n {\n this.x = value;\n }\n }\n public int PointY\n {\n get\n {\n return y;\n }\n set\n {\n this.y = value;\n }\n }\n\n // constructor with initialisation\n public Point(int x, int y)\n {\n this.x = x;\n this.y = y;\n }\n}\nclass Test\n{\n public static void Main()\n {\n Point point1 = new Point(5, 10);\n Point point2 = new Point(20, 15);\n // this doesn't work, because x and y are private in the Point class; try it!\n // Console.WriteLine(\"Point1({0}, {1})\", point1.x, point1.y);\n // Console.WriteLine(\"Point2({0}, {1})\", point2.x, point2.y);\n Console.WriteLine(\"Point1({0}, {1})\", point1.PointX, point1.PointY);\n Console.WriteLine(\"Point2({0}, {1})\", point2.PointX, point2.PointY);\n point1.PointX += 10;\n Console.WriteLine(\"Increasing Point1's x val by 10 ...\");\n Console.WriteLine(\"Point1({0}, {1})\", point1.PointX, point1.PointY);\n\n }\n}\n" }, { "alpha_fraction": 0.7673267126083374, "alphanum_fraction": 0.7772276997566223, "avg_line_length": 49.625, "blob_id": "278da8ce40218ea7fa9d0c612cefca3e1a162abb", "content_id": "f8efb459cc6e21679abb1ea173eac12f14895190", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 404, "license_type": "no_license", "max_line_length": 187, "num_lines": 8, "path": "/React.js/README.md", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "### Tuts+ Course: Getting Started With React.js\n**Instructor: David East**\n\nReact is a view library whose philosophy greatly differs from the usual framework. This course will cover what makes React different from all the other frameworks and libraries out there.\n\nSource files for the Tuts+ course: [Getting Started With React.js](https://courses.tutsplus.com/courses/)\n\n**Available on Tuts+ November 2014**" }, { "alpha_fraction": 0.6404715180397034, "alphanum_fraction": 0.6404715180397034, "avg_line_length": 32.79999923706055, "blob_id": "96d6ede9182fe94f1e79a5c388bb6a18f425b8c0", "content_id": "566259776b10a608144d5a07ee4dd1055d9c3e4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 75, "num_lines": 15, "path": "/Interviews/jp_morgan/call_billing/src/client/client.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\nclass Client(object):\n\n \"\"\"Client basic class\"\"\"\n\n def __init__(self, client_id, call_plan):\n self.client_id = client_id\n self.call_plan = call_plan\n\n def call_cost(self, call):\n \"\"\"Abstract Method, calculate cost per call\"\"\"\n raise NotImplementedError('subclasses must override call_cost()!')\n\n def per_minute(self, call_type):\n \"\"\"Abstract Method, calculate base cost per minute\"\"\"\n raise NotImplementedError('subclasses must override per_minute()!')\n" }, { "alpha_fraction": 0.6133005023002625, "alphanum_fraction": 0.633004903793335, "avg_line_length": 39.599998474121094, "blob_id": "fb282de0625035b3885f484cb8c8c4225c6ad8e9", "content_id": "23d60644919cb2cef757deabe73972b4cb328d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 68, "num_lines": 10, "path": "/Python/IndustrialProgramming/basics/hello.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: iso-8859-15 -*-\n\nprint(\"Hello world\")\nprint(\"Hello\", \"world\") # arguments are space-separated\nprint(\"Hello\", \"world\", sep=',') # choose your own space-separator\nprint(\"Hello\", \"world\", end='') # no newline at the end\nprint(\"Hello\", \"world\", file=open('hello.txt','w')) # write to file\nn=9\nprint(\"Hello\", n, \"worlds\") # ints etc are converted to strings\n" }, { "alpha_fraction": 0.5858585834503174, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 23.75, "blob_id": "756899abe060bdac5f3eef142648cc6dce000c8c", "content_id": "28be78a21675cf311361faad6e6a0c0567a2ca54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1782, "license_type": "no_license", "max_line_length": 100, "num_lines": 72, "path": "/React.js/6.5-events/app/src/js/components/Feed.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/** @jsx React.DOM */\n\nvar React = require('react');\nvar ShowAddButton = require('./ShowAddButton');\nvar FeedForm = require('./FeedForm');\nvar FeedList = require('./FeedList');\nvar _ = require('lodash');\n\nvar Feed = React.createClass({\n\n getInitialState: function() {\n var FEED_ITEMS = [\n { key: '1', title: 'Realtime data!', description: 'Firebase is cool', voteCount: 49 },\n { key: '2', title: 'JavaScript is fun', description: 'Lexical scoping FTW', voteCount: 34},\n { key: '3', title: 'Coffee makes you awake', description: 'Drink responsibly', voteCount: 15},\n ];\n return {\n items: FEED_ITEMS,\n formDisplayed: false\n }\n },\n\n onToggleForm: function() {\n this.setState({\n formDisplayed: !this.state.formDisplayed\n });\n },\n\n onNewItem: function(newItem) {\n var newItems = this.state.items.concat([newItem]);\n this.setState({\n items: newItems,\n formDisplayed: false,\n key: this.state.items.length\n });\n },\n\n onVote: function(item) {\n var items = _.uniq(this.state.items);\n var index = _.findIndex(items, function(feedItems) {\n return feedItems.key === item.key;\n });\n var oldObj = items[index];\n var newItems = _.pull(items, oldObj);\n newItems.push(item);\n this.setState({\n items: newItems\n });\n },\n\n render: function() {\n return (\n <div>\n\n <div className=\"container\">\n <ShowAddButton displayed={this.state.formDisplayed} onToggleForm={this.onToggleForm} />\n </div>\n\n <FeedForm displayed={this.state.formDisplayed} onNewItem={this.onNewItem} />\n\n <br />\n <br />\n\n <FeedList items={this.state.items} onVote={this.onVote} />\n\n </div>\n );\n }\n\n});\n\nmodule.exports = Feed;\n" }, { "alpha_fraction": 0.4051040709018707, "alphanum_fraction": 0.40708622336387634, "avg_line_length": 32.081966400146484, "blob_id": "bdeb1105a7db9d5cc5675d711332ca5c9fbef34d", "content_id": "7068ffc65984c70c4e0a6528db4a82fe18b6e7f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4036, "license_type": "no_license", "max_line_length": 109, "num_lines": 122, "path": "/Angular/seed-testdrive/Gruntfile.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "module.exports = function(grunt) {\n grunt.initConfig({\n watch: {\n styles: {\n // Which files to watch (all .less files recursively in the less directory)\n files: ['assets/less/*.less'],\n tasks: ['less'],\n options: {\n nospawn: true\n },\n },\n scripts: {\n files: ['assets/javascripts/*.js'],\n tasks: ['concat'],\n options: {\n interrupt: true\n }\n }\n\n },\n less: {\n development: {\n options: {\n compress: true,\n yuicompress: true\n },\n files: {\n // target.css file: source.less file\n \"public/stylesheets/main.min.css\": \"assets/less/main.less\"\n }\n }\n },\n browserSync: {\n dev: {\n bsFiles: {\n src: [\n 'public/**/*.css',\n 'public/**/*.jpg',\n 'public/**/*.png',\n 'public/**/*.gif',\n 'public/**/*.svg',\n 'public/**/*.js',\n '**/*.php',\n '**/*.html',\n '**/*.jade'\n ]\n },\n options: {\n watchTask: true,\n //I am hosting my projects using apache virtual hosts, I define ServerName and /etc/hosts\n host: \"localhost:4010\",\n ghostMode: {\n clicks: true,\n scroll: true,\n links: true,\n forms: true\n }\n }\n }\n },\n concat: {\n options: {\n separator: \"\\n\", //add a new line after each file\n banner: \"//Concatenated Javascript \\n\", //added before everything\n footer: \"\" //added after everything\n },\n dist: {\n // the files to concatenate\n src: [\n 'assets/javascripts/interaction.js'\n ],\n // the location of the resulting JS file\n dest: 'public/javascripts/interaction.min.js'\n }\n },\n removelogging: {\n dist: {\n src: 'public/javascripts/interaction.min.js',\n dest: 'public/javascripts/interaction.min.js'\n }\n },\n 'closure-compiler': {\n frontend: {\n closurePath: 'closure-compiler',\n js: 'public/javascripts/interaction.min.js',\n jsOutputFile: 'public/javascripts/interaction.min.js',\n maxBuffer: 1500,\n options: {\n compilation_level: 'SIMPLE_OPTIMIZATIONS',\n debug: true,\n },\n }\n },\n autoprefixer: {\n options: {\n // Task-specific options go here.\n },\n single_file: {\n options: {\n // Target-specific options go here.\n },\n src: 'public/stylesheets/main.min.css',\n dest: 'public/stylesheets/main.min.css'\n },\n },\n });\n // load npm tasks\n grunt.loadNpmTasks('grunt-contrib-watch');\n grunt.loadNpmTasks('grunt-contrib-less');\n grunt.loadNpmTasks('grunt-browser-sync');\n grunt.loadNpmTasks('grunt-contrib-concat');\n grunt.loadNpmTasks('grunt-closure-compiler');\n grunt.loadNpmTasks('grunt-remove-logging');\n grunt.loadNpmTasks('grunt-autoprefixer');\n\n // create custom task-list\n\n grunt.registerTask('build', [\"autoprefixer\", \"removelogging\", \"closure-compiler\"]);\n grunt.registerTask('default', [\"browserSync\", \"watch\", ]);\n\n\n};\n" }, { "alpha_fraction": 0.4776119291782379, "alphanum_fraction": 0.5074626803398132, "avg_line_length": 7.125, "blob_id": "d1514e8eb7ba09082a7a2c7afb935d24a5cc6f96", "content_id": "7413cd40650dfac564cdd6a901bfafc5d1f90ffd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 18, "num_lines": 8, "path": "/Python/IndustrialProgramming/basics/default.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env pythona\n\ni = 5\ndef f(arg=i):\n print (arg)\n\ni = 6\nf()\n\n\n" }, { "alpha_fraction": 0.44545453786849976, "alphanum_fraction": 0.581818163394928, "avg_line_length": 14.714285850524902, "blob_id": "9616322d0a40c3454be0c9ec73145100fdee006c", "content_id": "b987c56bea7c44e359011f895eee633f11e2cc0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 30, "num_lines": 7, "path": "/Python/CodingTests/Warmup/flipping_bits.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "input = [3, 2147483647, 1, 0]\n\nlist = [int(x) for x in input]\n\n\nfor x in list[1:]:\n print(~x & 0xFFFFFFFF)\n" }, { "alpha_fraction": 0.5798449516296387, "alphanum_fraction": 0.5917312502861023, "avg_line_length": 32.379310607910156, "blob_id": "6bdb38f0fd8ca2c4b6c55c4112c24f33cabffb10", "content_id": "d7388fda9ffd070429c1c8ef2fab4911d302a004", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1935, "license_type": "no_license", "max_line_length": 96, "num_lines": 58, "path": "/CSharp/code-examples/database/mysql.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// simple ADO.NET example of database access (using MySQL backend)\nusing System;\nusing System.Data;\nusing MySql.Data.MySqlClient;\n \npublic class Test\n{\n public static void Main(string[] args)\n {\n string connectionString =\n \"Server=anubis;\" +\n \"Database=test;\" +\n \"User ID=myid;\" +\n \"Password=mypwd;\" +\n \"Pooling=false\";\n\n MySqlConnection dbcon;\n Console.WriteLine(\"Trying to connect to '\"+connectionString+\"'...\");\n try {\n\t dbcon = new MySqlConnection(connectionString);\n\t dbcon.Open();\n }\n catch (MySql.Data.MySqlClient.MySqlException ex)\n\t{ // for error codes see: http://navody.kongo.sk/mysql-5/connectors-apis.html\n\t switch (ex.Number) {\n\t case 0: Console.WriteLine(\"Error 0: Cannot connect to server\"); break;\n\t case 1042: Console.WriteLine(\"Error 1042: ER_BAD_HOST_ERROR: cannot connect to host\"); break;\n\t case 1045: Console.WriteLine(\"Error 1045: ER_ACCESS_DENIED_ERROR: cannot log in\"); break;\n\t default: Console.WriteLine(\"Unknown error number \"+ex.Number); break;\n\t }\n\t Console.WriteLine(ex.Message);\n\t}\n\n MySqlCommand dbcmd = dbcon.CreateCommand();\n // requires a table of authors like this\n // CREATE TABLE authors (\n // A_ID MEDIUMINT,\n // A_FNAME VARCHAR(80),\n // A_LNAME VARCHAR(80));\n string sql =\n \"SELECT A_ID, A_FNAME, A_LNAME \" +\n \"FROM authors\";\n dbcmd.CommandText = sql;\n MySqlDataReader reader = dbcmd.ExecuteReader();\n while(reader.Read()) {\n string FirstName = (string) reader[\"A_FNAME\"];\n string LastName = (string) reader[\"A_LNAME\"];\n Console.WriteLine(\"Name: \" + FirstName + \" \" + LastName);\n }\n // clean up\n reader.Close();\n reader = null;\n dbcmd.Dispose();\n dbcmd = null;\n dbcon.Close();\n dbcon = null;\n }\n}" }, { "alpha_fraction": 0.5490909218788147, "alphanum_fraction": 0.5600000023841858, "avg_line_length": 21.91666603088379, "blob_id": "3dd740b83fbf200ea81d960d28232cb368f55a25", "content_id": "eaf553bc8c22f52ec119cdb9d19c267bd81d6a6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 58, "num_lines": 12, "path": "/Python/IndustrialProgramming/advanced/iter2.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\ndef reverse(data):\n \"\"\"Generator, traversing the data in reverse order.\"\"\"\n for index in range(len(data) - 1, -1, -1):\n yield data[index]\n\nif __name__ == \"__main__\":\n for char in reverse('golf'):\n print (char)\n # espect: f l o g\n" }, { "alpha_fraction": 0.6437724828720093, "alphanum_fraction": 0.6470842361450195, "avg_line_length": 35.941490173339844, "blob_id": "c69b0ab268368d04d5b351d2a6b08de89a3fc1df", "content_id": "6a357413e0a6071a80dc3151b32a2b3b430ba8e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6945, "license_type": "no_license", "max_line_length": 138, "num_lines": 188, "path": "/CSharp/code-examples/thearding/mulT.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Example of multi-threading, passing the value retrieved by one thread to the other thread.\n// The operations are: (1) reading from a file (2) displaying the file contents\n// -----------------------------------------------------------------------------\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Text;\nusing System.IO;\nusing System.Threading;\n\nclass FileData {\n // This class holds the context for one file read operation\n // contents of the data that arrived\n private static int counter = 0;\n private string filename = null;\n private string filecontents = null;\n private object mainLock = new { }; // any non-null object will do as lock\n\n public void setFileName(string fn) { this.filename = fn; }\n // public void setContents(string cont) { this.filecontents = cont; }\n public void addContents(string cont) { this.filecontents += cont; }\n \n // public string getFileName() { return this.filename; }\n public int getCounter() { return FileData.counter; }\n public string getFileName() { return this.filename; }\n public string getContents() { return this.filecontents; }\n\n // constructor\n public FileData (string filename) {\n this.filename = filename;\n FileData.counter++;\n }\n}\n\nclass Test {\n // A class for testing concurrent read and display threads\n\n // booleans, indicating whether data has arrived; needed for synchronisation\n private bool okFileName = false;\n private bool okContents = false;\n private object mainLock = new { }; // any non-null object will do as lock\n\n public FileData currentFileData; // handle on the context for file ops\n public static LinkedList<FileData> allFileData = new LinkedList<FileData>(); // list of all file contexts\n\n // define an exception, triggered by the balance being too low\n public class NoFile : System.Exception {\n public NoFile(string msg) :base(msg) {\n }\n }\n\n // constructor; needs the filename to read from/display\n public Test(string filename) {\n currentFileData = new FileData(filename);\n okFileName = true;\n allFileData.AddLast(currentFileData);\n }\n\n // -----------------------------------------------------------------------------\n // 2 threads co-operate to get the HMTL code:\n // . getFContents retrieves the contents of the file\n // . displayFile shows the contents, read by the previous thread\n\n // could use this to set the filename in a separate thread\n // mulT: lookup the file name from a variable\n /*\n public static void getFName() {\n System.Console.WriteLine(\"<{0}> setting filename ... \", Thread.CurrentThread.Name);\n if (currentFileData.getArgs().Length == 0) { // expect 1 arg: value to double\n // System.Console.WriteLine(\"Usage: <prg> <filename>\");\n lock (mainLock) { // protect write access to static fields\n currentFileData.setFileName(\"mulT.cs\"); // by default, read the sources for this file\n okFileName = true;\n }\n } else { \n lock (mainLock) { // protect write access to static fields\n currentFileData.setFileName(currentFileData.getArgs()[0]);\n okFileName = true;\n }\n }\n }\n */\n\n /* Could use ParameterizedThreadStart, which allows to pass an argument to the method in the thread */\n\n // requires: File.Exists(filename)\n // summary: retrieve the contents for the current file\n public void getFContents() {\n while (!okFileName) { \n // Thread.Sleep(1); // busy wait; better: use Wait and Pulse from within getFilenName\n Monitor.Wait(mainLock);\n }\n System.Console.WriteLine(\"<{0}> we have the name of the file ... \", Thread.CurrentThread.Name);\n\n StreamReader sr;\n\n // assert: not (null filename)\n // lock (mainLock) {\n \n try {\n Monitor.Enter(mainLock); // enter critical region\n\n System.Console.WriteLine(\"<{0}> reading file contents ... \", Thread.CurrentThread.Name);\n\n sr = new StreamReader(currentFileData.getFileName());\n // std iteration over the contents of a file\n string inValue = \"\";\n while((inValue = sr.ReadLine()) != null) // read line-by-line\n // filecontents += inValue + \"\\n\";\n currentFileData.addContents(inValue + \"\\n\");\n\n okContents = true;\n Monitor.Pulse(mainLock);\n }\n catch(System.Exception ex) {\n\t Console.WriteLine(ex.Message); \n }\t\n finally {\n sr.Close();\n Monitor.Exit(mainLock);\n }\n }\n\n // summary: show the previously retrieved contents for the current file\n public void displayContents() {\n Monitor.Enter(mainLock);\n while (!okContents) { \n Console.WriteLine(\"<{0}> Waiting ...\", Thread.CurrentThread.Name); \n Monitor.Wait(mainLock) ; \n } \n System.Console.WriteLine(\"<{0}> we have the contents of the file ... \", Thread.CurrentThread.Name);\n // else { \n Console.WriteLine(\"<{0}> Continuing ...\", Thread.CurrentThread.Name); \n Console.WriteLine(\"------------------------------------------------------- \\n<{0}> Contents of file {1} ({2} files in total): \\n{3}\", \n\t\t Thread.CurrentThread.Name, currentFileData.getFileName(), currentFileData.getCounter(), currentFileData.getContents()); \n Console.WriteLine(\"<{0}> end of file ------------------------------------------------------- \", \n\t\t Thread.CurrentThread.Name, currentFileData.getFileName()); \n Monitor.Exit(mainLock);\n }\n\n public void RunTest(){\n // kicks-off 2 threads: one for reading the file contents, the other to display it\n Thread getT = new Thread(new ThreadStart(getFContents));\n getT.Name = \"getContentsThread_for_file_\" + currentFileData.getFileName();\n Thread displayT = new Thread(new ThreadStart(displayContents));\n displayT.Name = \"displayContents_for_file_\" + currentFileData.getFileName();\n //getFN.Start();\n getT.Start();\n displayT.Start();\n //getFN.Join();\n getT.Join();\n displayT.Join();\n System.Console.WriteLine(\"<{0}> thread terminates.\", Thread.CurrentThread.Name);\n }\n}\n\n// -----------------------------------------------------------------------------\n\npublic class MainClass {\n // list of all threads\n public static LinkedList<Thread> allThreads = new LinkedList<Thread>();\n \n // summary: test wrapper, generating a test for each filename in args\n public static void Main(string []args) {\n Thread.CurrentThread.Name = \"Main thread\";\n Test t;\n Thread currT;\n foreach (string s in args) {\n // set-up a test for file s\n t = new Test(s);\n // run the test\n currT = new Thread( new ThreadStart(t.RunTest) );\n currT.Name = \"Tester_for_file_\"+s;\n // add the thread to this list of all threads\n allThreads.AddLast(currT);\n // now, start a new thread for the test\n currT.Start();\n }\n foreach (Thread thr in allThreads) {\n // iterate over all threads and join it with the main one\n thr.Join();\n System.Console.WriteLine(\"<{0}> shutting down.\", thr.Name);\n }\n System.Console.WriteLine(\"<{0}> thread terminates.\", Thread.CurrentThread.Name);\n }\n}\n" }, { "alpha_fraction": 0.5584989190101624, "alphanum_fraction": 0.6048564910888672, "avg_line_length": 36.75, "blob_id": "6fd5b964e515f4b131a9667761598c96bb2fd5ce", "content_id": "b1cea1e18b338aa586d5196ff0cdc95f8690c281", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "no_license", "max_line_length": 74, "num_lines": 12, "path": "/Python/IndustrialProgramming/basics/test_numpy.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\nimport numpy as np\nm1 = np.array([ [1,2,3],\n [7,3,4] ]); # fixed test input\n# m1 = np.zeros((4,3),int); # initialise a matrix\nr1 = np.ndim(m1); # get the number of dimensions for matrix 1\nm, p = np.shape(m1); # no. of rows in m1 and no. of cols in m1\n# use range(0,4) to generate all indices\n# use m1[i][j] to lookup a matrix element\n\nprint(\"Matrix m1 is an \", r1, \"-dimensional matrix, of shape \", m, \"x\", p)\n" }, { "alpha_fraction": 0.5276243090629578, "alphanum_fraction": 0.5745856165885925, "avg_line_length": 18.54054069519043, "blob_id": "d7b491dfaf3e2c3f1ed77bb815f50ecce415b89f", "content_id": "64823587036366cd45a289dcf9b7e55dd9b00731", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 724, "license_type": "no_license", "max_line_length": 46, "num_lines": 37, "path": "/Interviews/jane_street/filter_messeges.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n# producer ---> proxy ---> consumer\n\n# ^ ^\n# :) 10msg/s\n\n# timestamp\n# 09:30:23.00\n# 09:30:23.37\n# 09:30:25.242\n\ncurrent_sec_stack = []\n\n\ndef filter_mess(timestamp):\n if len(current_sec_stack) < 10:\n current_sec_stack.append(timestamp)\n pass_message(timestamp)\n else:\n remove_old(current_sec_stack)\n filter_mess(timestamp)\n\n\ndef remove_old(current_sec_stack):\n per_sec = []\n\n for timestamp in current_sec_stack:\n per_sec.append(get_seccond(timestamp))\n\n for sec in per_sec:\n if len(sec) = 10:\n current_sec_stack.remove(sec[0])\n\n\ndef filter_messages(msg):\n seccond = msg[6:9]\n\n len(current_sec_stack[seccond])\n" }, { "alpha_fraction": 0.5524718165397644, "alphanum_fraction": 0.5793582201004028, "avg_line_length": 20.754716873168945, "blob_id": "7b2861aa9f563344134b6f7d293dc302e39a4333", "content_id": "58925d7e700b90d9ad4ae11ca254d96ac517d418", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1153, "license_type": "no_license", "max_line_length": 65, "num_lines": 53, "path": "/Python/CodingTests/Arrays and Sorting/tape_equillibrium.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from random import randint\nimport functools\nimport timeit\nimport time\n\n\narray = [3, 1, 2, 4, 3]\nbig_array = [randint(0, 1000000) for x in range(1, 100000)]\n\n\ndef timeit(func):\n @functools.wraps(func)\n def newfunc(*args, **kwargs):\n startTime = time.time()\n func(*args, **kwargs)\n elapsedTime = time.time() - startTime\n print('function [{}] finished in {} ms'.format(\n func.__name__, int(elapsedTime * 1000)))\n return newfunc\n\n\n@timeit\ndef solution(A):\n sidesA = [sum([x for x in A[0:y]]) for y in range(1, len(A))]\n sidesB = [sum([x for x in A[y::]]) for y in range(1, len(A))]\n\n return min([abs(x - y) for x, y in zip(sidesA, sidesB)])\n\n\n@timeit\ndef solution_faster(A):\n current_diff = None\n\n for i in range(1, len(A)):\n diff = abs(sum(A[0:i]) - sum(A[i::]))\n\n if current_diff is None:\n current_diff = diff\n\n if diff is 0:\n current_diff = 0\n continue\n\n if current_diff > diff:\n current_diff = diff\n\n print(current_diff)\n\n\n# solution_faster(array)\nsolution_faster(big_array)\n# solution(array)\n# solution(big_array)\n" }, { "alpha_fraction": 0.6150190234184265, "alphanum_fraction": 0.6150190234184265, "avg_line_length": 26.6842098236084, "blob_id": "c204c63f01cfb5ca6169215601ff39f4fbcd1dbb", "content_id": "b67c0ba8904819911adc433fb2e6411e59e545bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 67, "num_lines": 38, "path": "/CSharp/coursework/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/Program.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Windows.Forms;\nusing WebBrowser_OuterSpace.controllers;\nusing WebBrowser_OuterSpace.models;\n\nnamespace WebBrowser_OuterSpace\n{\n static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n\n //Initalise Homepage Controler\n HomePageController hp = new HomePageController();\n hp.setUpHomePageConfig();\n\n //Initialise BrowsingController\n BrowsingController bc = new BrowsingController();\n\n\n //HistoryController\n HistoryController hc = new HistoryController();\n hc.loadHistory();\n\n //FavouritiesController\n FavouritesController fc = new FavouritesController();\n fc.loadFavourites();\n\n Application.Run(new BrowserWindowMain(bc, hp, hc, fc));\n }\n }\n}\n" }, { "alpha_fraction": 0.638680636882782, "alphanum_fraction": 0.6461769342422485, "avg_line_length": 15.675000190734863, "blob_id": "7b936fe9451255ed25c4a15fae49f368563cb13a", "content_id": "8f215cf0567b5004047c0ea8bae1e1a57267a685", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 667, "license_type": "no_license", "max_line_length": 50, "num_lines": 40, "path": "/Interviews/pebble/battleships/src/app/app.ts", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/*\n * Angular 2 decorators and services\n */\nimport {Component, View} from 'angular2/angular2';\nimport {CORE_DIRECTIVES} from 'angular2/angular2';\n\nimport {Grid} from './components/grid';\nimport {GameService} from './services/GameService'\n\n\n/*\n * App Component\n * Top Level Component\n */\n@Component({\n selector: '#app',\n bindings: [\n GameService\n ],\n directives: [\n CORE_DIRECTIVES,\n Grid\n ],\n styles: [\n require('./main.css')\n ],\n templateUrl: 'views/main.html'\n})\n\nexport class App{\n title: string;\n\n constructor(public game: GameService) {\n this.title = 'Battleships Mega Game';\n }\n\n reset() {\n this.game = GameService.create();\n }\n}\n" }, { "alpha_fraction": 0.5236749053001404, "alphanum_fraction": 0.5352178812026978, "avg_line_length": 28.275861740112305, "blob_id": "845160bc743a79dec4d7749843ee77daaa872084", "content_id": "50eebffc3b63cd06c6baf9b406caab1bf3a76c9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4245, "license_type": "no_license", "max_line_length": 99, "num_lines": 145, "path": "/CSharp/code-examples/database/linq1.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// From \"Learning C# 3.0\", Jess Liberty\n\n// Examples 21-1 to 21-5\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\npublic class Book { \n public string Title { get ; set; }\n public string Author { get ; set; }\n public string Publisher { get ; set; }\n public int Year { get ; set; }\n}\n\npublic class PurchaseOrder {\n public int OrderNumber { get; set; }\n public string Title { get; set; }\n public int Quantity { get; set; }\n}\n\npublic class Tester {\n\n public static void Main (string []args) {\n if (args.Length < 0) { // expect 1 args: filename\n System.Console.WriteLine(\"Usage: linq1 <listlen>\");\n } else {\n //int n = Convert.ToInt32(args[0]);\n List<Book> booklist = new List<Book> {\n\t new Book { Title = \"Learning C#\"\n\t , Author = \"Jesse Liberty\"\n\t , Publisher = \"O'Reilly\"\n\t , Year = 2008\n\t },\n\t new Book { Title = \"Programming C#\"\n\t , Author = \"Jesse Liberty\"\n\t , Publisher = \"O'Reilly\"\n\t , Year = 2008\n\t },\n\t new Book { Title = \"Programming PHP\"\n\t , Author = \"Rasmus Lerdorf, Kevin Tatroe\"\n\t , Publisher = \"O'Reilly\"\n\t , Year = 2006\n\t },\n\t new Book { Title = \"PHP Pocket Reference\"\n\t , Author = \"Rasmus Lerdorf\"\n\t , Publisher = \"O'Reilly\"\n\t , Year = 2008\n\t },\n\t new Book { Title = \"Perl Cookbook\"\n\t , Author = \"Tom Christiansen, Nathan Torkington\"\n\t , Publisher = \"O'Reilly\"\n\t , Year = 2001\n\t },\n };\n List<PurchaseOrder> purchaselist = new List<PurchaseOrder> {\n\t new PurchaseOrder { OrderNumber = 1\n\t , Title = \"Programming C#\"\n , Quantity = 2\n }\n\t ,\n\t new PurchaseOrder { OrderNumber = 2\n\t , Title = \"Perl Cookbook\"\n , Quantity = 1\n }\n\t ,\n\t new PurchaseOrder { OrderNumber = 3\n\t , Title = \"Programming C#\"\n , Quantity = 5\n }\n };\n\n // non LINQ:\n Console.WriteLine(\"non LINQ ...\");\n foreach (Book b in booklist) {\n\t if (b.Author == \"Jesse Liberty\") { \n\t Console.WriteLine(b.Title + \" by \" + b.Author);\n\t }\n }\n\t \n // LINQ query: find by author\n IEnumerable<Book> resultsAuthor =\n\t from b in booklist\n\t where b.Author == \"Jesse Liberty\"\n\t select b;\n\n Console.WriteLine(\"LINQ query: find by author ...\");\n // process the result\n foreach (Book r in resultsAuthor) {\n\t Console.WriteLine(r.Title + \" by \" + r.Author);\n }\n\n\n // LINQ query: avoid returning entire books; uses an anonymous type\n var resultsAuthor1 = // NB: this needs to infer the type, which is anonymous!\n\t from b in booklist\n\t where b.Author == \"Jesse Liberty\"\n\t select new { b.Title, b.Author} ; // NB: anonymous type here!\n\n Console.WriteLine(\"LINQ query: avoid returning entire books; uses an anonymous type ...\");\n // process the result\n foreach (var r in resultsAuthor1) {\n\t Console.WriteLine(r.Title + \" by \" + r.Author);\n }\n\n\n // LINQ: lambda expressions\n var resultsAuthor2 =\n\t booklist.Where(bookEval => bookEval.Author == \"Jesse Liberty\");\n\n Console.WriteLine(\"LINQ: lambda expressions ...\");\n // process the result\n foreach (var r in resultsAuthor2) {\n\t Console.WriteLine(r.Title + \" by \" + r.Author);\n }\n\n // LINQ query: order by author\n var resultsAuthor3 =\n\t from b in booklist\n\t orderby b.Author\n\t select new { b.Title, b.Author} ; // NB: anonymous type here!\n\n Console.WriteLine(\"LINQ query: order by author ...\");\n // process the result\n foreach (var r in resultsAuthor3) {\n\t Console.WriteLine(r.Title + \" by \" + r.Author);\n }\n\n // LINQ: join\n var resultList4 = \n from b in booklist\n join p in purchaselist on b.Title equals p.Title\n where p.Quantity >=2\n\t select new { b.Title, b.Author, p.Quantity } ; \n \n Console.WriteLine(\"LINQ query: oreder by author ...\");\n // process the result\n foreach (var r in resultList4) {\n\t Console.WriteLine(r.Quantity + \" items of \" + r.Title + \" by \" + r.Author);\n }\n\n }\n }\n}\n" }, { "alpha_fraction": 0.6588628888130188, "alphanum_fraction": 0.6588628888130188, "avg_line_length": 22.75, "blob_id": "ab701e5dd29888fbc9aa19e5259745e2cdcb4015", "content_id": "fa4021c49a2ba0f4352b7c51f3f1417030573eac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 299, "license_type": "no_license", "max_line_length": 57, "num_lines": 12, "path": "/Java/F21AS Advanced Software Engineering/Week 7 Threads II/src/Vars/MainV.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\r\npublic class MainV {\r\n\r\n\t\tpublic static void main(String args[]) {\r\n\t\t\tSharedObject so = new SharedObject();\r\n\t\t\tThread producerThread = new Thread (new Producer(so));\r\n\t\t\tproducerThread.start();\r\n\t\t\tThread consumerThread = new Thread (new Consumer(so));\r\n\t\t\tconsumerThread.start();\r\n\r\n\t\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5770308375358582, "alphanum_fraction": 0.586834728717804, "avg_line_length": 26.461538314819336, "blob_id": "9268020da29eb33ada5da5d7e2b62015f25493bd", "content_id": "00fc31aaee4de9ab8ed9b6ee45e9bf0f3b965d49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 65, "num_lines": 26, "path": "/Python/IndustrialProgramming/advanced/vector4.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nclass Vector(object):\n # constructor\n\n def __init__(self, coord):\n self.coord = coord\n\n # turns the object into string\n def __str__(self):\n return str(self.coord)\n\n def __mul__(self, scalar):\n '''Multiplication with a scalar from the right.'''\n return map(lambda x: x * scalar, self.coord)\n\n def __rmul__(self, scalar):\n '''Multiplication with a scalar from the left.'''\n return map(lambda x: scalar * x, self.coord)\n\nif __name__ == \"__main__\":\n v1 = Vector(range(5))\n print(\"Vector: \", str(v1))\n print(\"Testing scalar multiplication (from right):\", v1 * 5)\n print(\"Testing scalar multiplication (from left):\", 5 * v1)\n" }, { "alpha_fraction": 0.5493630766868591, "alphanum_fraction": 0.5652866363525391, "avg_line_length": 23.153846740722656, "blob_id": "feaf492b6fd0625c41175ef7ab61d8756a774e20", "content_id": "5d80db384957d6d0c5cc47c1c0c6b1e29ec7f9b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "no_license", "max_line_length": 54, "num_lines": 26, "path": "/Python/IndustrialProgramming/advanced/vector6.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nclass Vector(object):\n # constructor\n\n def __init__(self, coord):\n self.coord = coord\n\n # turns the object into string\n def __str__(self):\n return str(self.coord)\n\n def __getitem__(self, index):\n '''Return the coordinate with number index.'''\n return self.coord[index]\n\n def __getslice__(self, left, right):\n '''Return a subvector.'''\n return Vector(self.coord[left:right])\n\nif __name__ == \"__main__\":\n v1 = Vector(range(5))\n print(\"Vector: \", str(v1))\n print(\"Element at index 2: \", v1[2])\n print(\"Slice up to index 2:\", str(v1[0:2]))\n" }, { "alpha_fraction": 0.4813753664493561, "alphanum_fraction": 0.48342201113700867, "avg_line_length": 27.74117660522461, "blob_id": "22b46e85153982196fe7c7855174f3e135d543ae", "content_id": "f8d5446f79cb36d2b327b365624932ce170d3cb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4888, "license_type": "no_license", "max_line_length": 94, "num_lines": 170, "path": "/CSharp/coursework/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/models/FavouritesList.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.IO;\nusing System.Text;\nusing System.Linq;\n\nnamespace WebBrowser_OuterSpace.models\n{\n /// <summary>\n /// Singleton Class holding collection of Favourities\n /// </summary>\n class FavouritesList\n {\n private static FavouritesList instance;\n // Agin I will use nested Array\n public ArrayList favouritesCollection = new ArrayList();\n\n private FavouritesList()\n {\n\n }\n /// <summary>\n /// Singleton method\n /// </summary>\n public static FavouritesList Instance\n {\n get\n {\n if (instance == null)\n {\n instance = new FavouritesList();\n }\n return instance;\n }\n }\n\n /// <summary>\n /// Read Favourities from file durring startup\n /// </summary>\n public void readFavouritesConfig()\n {\n String line;\n try\n {\n //Pass the file path and file name to the StreamReader constructor\n StreamReader sr = new StreamReader(\"webFavourites.txt\");\n\n //Read the first line of text\n line = sr.ReadLine();\n buildFavouritesColection(line);\n\n //Continue to read until you reach end of file\n while (line != null)\n {\n //Read the next line\n line = sr.ReadLine();\n buildFavouritesColection(line);\n }\n\n //close the file\n sr.Close();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Exception: \" + e.Message);\n }\n finally\n {\n Console.WriteLine(\"Executing finally block.\");\n }\n }\n\n /// <summary>\n /// Buld ip a collection base of file reading\n /// </summary>\n /// <param name=\"line\"></param>\n private void buildFavouritesColection(string line)\n {\n string[] input = line.Split(',');\n favouritesCollection.Add(new string[2] { input[0], input[1] });\n }\n\n /// <summary>\n /// Getter for favourities collection\n /// </summary>\n /// <returns></returns>\n public ArrayList getfavouritesCollection()\n {\n return this.favouritesCollection;\n }\n\n\n /// <summary>\n /// Add new favourite to list and call method to update file\n /// </summary>\n /// <param name=\"name\"></param>\n /// <param name=\"url\"></param>\n public void addNewFav(string name, string url)\n {\n favouritesCollection.Add(new string[2] { name, url });\n updateFavouritesConfig();\n\n }\n\n private void updateFavouritesConfig()\n {\n String line;\n try\n {\n //Clear file\n System.IO.StreamWriter file = new System.IO.StreamWriter(\"webFavourites.txt\");\n file.Write(\"\");\n file.Close();\n\n StreamWriter sw = new StreamWriter(\"webFavourites.txt\");\n\n foreach (string[] favorite in favouritesCollection)\n\n {\n Console.WriteLine(favorite[0].ToString());\n Console.WriteLine(favorite[1].ToString());\n line = favorite[0].ToString() + \",\" + favorite[1].ToString();\n sw.WriteLine(line);\n }\n sw.Close();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Exception: \" + e.Message);\n }\n finally\n {\n Console.WriteLine(\"Executing finally block.\");\n\n }\n }\n\n /// <summary>\n /// Insert updated values for given favourities\n /// </summary>\n /// <param name=\"name\"></param>\n /// <param name=\"url\"></param>\n /// <param name=\"id\"></param>\n internal void makeUpdateFav(string name, string url, int id)\n { \n string[] updatedFav = new string[2] { name, url } ;\n Console.WriteLine(id);\n favouritesCollection.Insert(id, updatedFav);\n updateFavouritesConfig();\n\n }\n\n /// <summary>\n /// Insert updated values for given favourities\n /// </summary>\n /// <param name=\"name\"></param>\n /// <param name=\"url\"></param>\n /// <param name=\"id\"></param>\n public void removeFav(int id)\n {\n favouritesCollection.RemoveAt(id);\n string[] updatedFav = new string[2] { \"empty\" , \"empty\" };\n favouritesCollection.Insert(id, updatedFav);\n updateFavouritesConfig();\n\n }\n\n\n }\n}\n" }, { "alpha_fraction": 0.5082873106002808, "alphanum_fraction": 0.541436493396759, "avg_line_length": 15.454545021057129, "blob_id": "7be5c35a75f66672634d8c24ef44bcfdb8baf576", "content_id": "5e34003c7f42f6d4f16ab8c2a5fa221fea9e4ab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 181, "license_type": "no_license", "max_line_length": 38, "num_lines": 11, "path": "/Python/IndustrialProgramming/advanced/interpret1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\nx = 5\neval ('x')\n# expect: 5\nf = lambda x: eval('x * x')\nf(4)\n# expect 16\nexec 'print (\"The value of x is \", x)'\n# expect 5\nprint (\"Square of \", x, \" is \", f(x))\n" }, { "alpha_fraction": 0.5201162099838257, "alphanum_fraction": 0.5205632448196411, "avg_line_length": 24.712644577026367, "blob_id": "206a4ff8a66c0ad85efc8d6874fb97a621c6b6e7", "content_id": "673acd5ef60ea0e61efa6b9d5740ae0d6d5a4720", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4474, "license_type": "no_license", "max_line_length": 97, "num_lines": 174, "path": "/Java/F21AS Advanced Software Engineering/Week 1 Excepions/src/StaffListInterface.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import java.util.Scanner;\nimport java.util.InputMismatchException;\nimport java.io.*;\npublic class StaffListInterface\n{\n\tprivate Scanner scanner;\n private StaffList allStaff;\n \n public StaffListInterface(StaffList list)\n {\n \tallStaff = list;\n \tscanner = new Scanner(System.in);\n }\n \n /**\n * Read a series of commands from the user to interact\n * with the address book. Stop when the user types 'quit'.\n */\n public void run()\n {\n System.out.println(\"StaffList\");\n System.out.println(\"Type 'help' for a list of commands.\");\n \n String command;\n do{\n \tSystem.out.println(\"Enter your command:\");\n command = scanner.nextLine();\n if(command.equals(\"add\")){ \n add();\n }\n else if (command.equals(\"remove\"))\n \tremove();\n else if(command.equals(\"findID\")){\n findID();\n }\n else if(command.equals(\"list\")){\n list();\n }\n else if(command.equals(\"listByID\")){\n listByID();\n }\n else if(command.equals(\"listByName\")){\n listByName();\n }\n else if (command.equals(\"print\")) {\n \tprint();\n }\n else if(command.equals(\"help\")){\n help();\n }\n else if (!command.equals(\"quit\")){\n System.out.println(\"Invalid command\");\n }\n } while(!(command.equals(\"quit\")));\n\n System.out.println(\"Goodbye.\");\n }\n \n /**\n * Add a new entry.\n */\n private void add()\n {\n String message = \"\";\n try {\n\t \t//get details from \n\t System.out.print(\"ID? : \");\n\t String id = scanner.nextLine();\n\t System.out.print(\"Lastname, Firstname? : \");\n\t String name = scanner.nextLine();\n\t System.out.print(\"Hours worked? : \");\n\t int hours = scanner.nextInt();\n \tscanner.nextLine(); //read end of line character\n \t//create new staff object and add to list\n \tStaff newStaff = new Staff(id, name, hours);\n \tallStaff.addDetails(newStaff);\n \tmessage = \"Details added\";\n }\n catch (InputMismatchException e) {\n \tmessage = \"Hours worked not a number, staff details not added\";\n \tscanner.nextLine(); //read end of line character\n\n }\n catch (IllegalStateException e){ // if params invalid\n \tmessage = e.getMessage() + \"\\nDetails not added\";\n }\n catch (DuplicateIDException e){\n \tmessage = e.getMessage() + \"\\nDetails not added\";\n }\n System.out.println(message);\n }\n \n private void remove() \n { \n \t\n String message = \"\";\n \ttry \n \t{\n \tSystem.out.println(\"Enter ID of person to be removed: \");\n \tString id = scanner.nextLine();\n allStaff.removeDetails(id);\n message = \"Details removed\";\n \t}\n \tcatch (NoMatchingIDExeption e)\n \t{\n \t\tmessage = e.getMessage() + \"\\nDetails not removed\";\n \t}\n \t System.out.println(message);\n }\n \n /**\n * Find an entry matching a key.\n */\n private void findID()\n {\n System.out.print(\"Type the ID to search for: \");\n String id = scanner.nextLine();\n Staff result = allStaff.findById(id);\n System.out.println(result);\n }\n \n /**\n * List the available commands.\n */\n private void help()\n {\n System.out.println(\"add, remove, findID, list, listByID, listByName, print, help, quit\");\n }\n \n /**\n * List the address book's contents.\n */\n private void list()\n {\n System.out.println(allStaff.listDetails());\n }\n \n /**\n * List the address book's contents.\n */\n private void listByID()\n {\n System.out.println(allStaff.listByID());\n } \n \n /**\n * List the address book's contents.\n */\n private void listByName()\n {\n System.out.println(allStaff.listByName());\n } \n \n /**\n * Print to text file\n */\n private void print() {\n \tFileWriter fw = null;\n \ttry {\n \tfw = new FileWriter(\"StaffDetails.txt\");\n \tfw.write(allStaff.listDetails());\n \tfw.close();\n \t}\n \tcatch (FileNotFoundException e) {\n \t\tSystem.out.println(e.getMessage());\n \t\tSystem.exit(1);\n \t}\n \t\n \tcatch (IOException ioe){\n \t\tSystem.exit(1);\n \t}\n\n }\n}\n" }, { "alpha_fraction": 0.5958333611488342, "alphanum_fraction": 0.5975000262260437, "avg_line_length": 28.629629135131836, "blob_id": "0c285d3bc2793f97b4970ff6d9cb2d23eed3ab2e", "content_id": "29d319c0038cec8e889d354f4360ac5259df665e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2400, "license_type": "no_license", "max_line_length": 102, "num_lines": 81, "path": "/Java/F21SF Soft E Fundation/14_15/src/Staff.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "//a simple class to contain and manage Staff details\n//(id, name, phone, level)\npublic class Staff implements Comparable<Staff>\n{\n\tprivate String id;\n private Name name;\n private String phone;\n private int qualLevel;\n\n /**\n * Set up the contact details. All details are trimmed to remove\n * trailing white space.\n * @param name The name.\n * @param phone The phone number.\n */\n public Staff(String id, Name name, String phone, int level)\n { \n \t//id and name MUSt be provided\n if( name==null || id.trim().length()== 0) \n {\n throw new IllegalStateException(\n \"Cannot have blank id or name\");\n }\n this.id =id.trim();\n this.name = name;\n this.phone = phone.trim();\n this.qualLevel = level;\n }\n \n \n \n public String getId() { return id; } \n public Name getName() { return name; }\n public String getPhone() { return phone; }\n public int getLevel() { return qualLevel; }\n \n public void setID(String id) {this.id = id; }\n public void setName(Name name) {this.name = name;}\n public void setPhone(String phone){this.phone = phone; }\n public void setLevel(int level) {this.qualLevel = level; }\n\n \n /**\n * Test for content equality between two objects.\n * @param other The object to compare to this one.\n * @return true if the argument object has same id\n */\n public boolean equals(Object other)\n {\n if(other instanceof Staff) {\n Staff otherStaff = (Staff) other;\n return id.equals(otherStaff.getId());\n }\n else {\n return false;\n }\n }\n\n /**\n * Compare this Staff object against another, for the purpose\n * of sorting. The fields are compared by id.\n * @param otherDetails The details to be compared against.\n * @return a negative integer if this id comes before the parameter's id,\n * zero if they are equal and a positive integer if this\n * comes after the other.\n */\n\n public int compareTo(Staff otherDetails)\n {\n return id.compareTo(otherDetails.getId());\n } \n\n /**\n * @return A multi-line string containing the name, phone, and address.\n */\n public String toString()\n {\n return String.format(\"%-5s\", id ) + String.format(\"%-20s\", name.getLastCommaFirst()) + phone ;\n }\n\n}\n" }, { "alpha_fraction": 0.5745856165885925, "alphanum_fraction": 0.5745856165885925, "avg_line_length": 27.41176414489746, "blob_id": "388d994c1256f4da4a567da613ac179c946036c1", "content_id": "0908a915fbd296c52ac277af8a1532f9f73985af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1450, "license_type": "no_license", "max_line_length": 80, "num_lines": 51, "path": "/CSharp/coursework/MarcinK mpk31/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/controllers/BrowsingController.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing WebBrowser_OuterSpace.models;\n\nnamespace WebBrowser_OuterSpace.controllers\n{\n /// <summary>\n /// Controller Class resposible for making request and managing browser tabs\n /// </summary>\n public class BrowsingController\n {\n\n /// <summary>\n /// Get a Web page based on URL and TabID\n /// </summary>\n /// <param name=\"tabID\"></param>\n /// <param name=\"urlAdress\"></param>\n /// <returns></returns>\n public String[] getWebPage(int tabID , String urlAdress)\n {\n WebDocumentsCache cache = WebDocumentsCache.Instance;\n return cache.getWebDocument(urlAdress, tabID); \n }\n\n\n /// <summary>\n /// Get tab content if possible if not will fetch home Page\n /// </summary>\n /// <param name=\"tabID\"></param>\n /// <param name=\"homeURL\"></param>\n /// <returns></returns>\n public String[] getTabContent(int tabID, String homeURL)\n {\n WebDocumentsCache cache = WebDocumentsCache.Instance;\n return cache.getTabDocument(tabID,homeURL);\n }\n\n\n /// <summary>\n /// Create new tab. It will create new object of class WebDocument\n /// </summary>\n public void createNewTab(String homeURL)\n {\n \n WebDocumentsCache cache = WebDocumentsCache.Instance;\n cache.createNewTab(homeURL);\n\n }\n\n\n }\n}" }, { "alpha_fraction": 0.5819209218025208, "alphanum_fraction": 0.598870038986206, "avg_line_length": 28.5, "blob_id": "08edcf44b5500e89f0f5498f42813dee8824cf80", "content_id": "e7f1dd91dc06f4fdfcc4de452747ef7240845358", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 49, "num_lines": 6, "path": "/Python/IndustrialProgramming/advanced/compile1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\nc = compile('map(lambda x:x*2,range(10))', # code\n 'pseudo-file.py', # filename for error msg\n 'eval') # or 'exec' (module) or 'single' (stm)\neval(c)\n" }, { "alpha_fraction": 0.5208333134651184, "alphanum_fraction": 0.5208333134651184, "avg_line_length": 9.55555534362793, "blob_id": "5d020ebaba2a320b5010920fd31c9acae984c28e", "content_id": "1ae59df8c07686778c8949e150c08569c5303d03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 20, "num_lines": 9, "path": "/Python/IndustrialProgramming/basics/clear.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\ndef clear_l():\n global l\n l = []\n\nl = [\"not\", \"empty\"]\nclear_l()\nprint(l)\n\n" }, { "alpha_fraction": 0.5370786786079407, "alphanum_fraction": 0.5617977380752563, "avg_line_length": 25.176469802856445, "blob_id": "13d61b0039ef404452c86d6051883b39455a6b94", "content_id": "bfdd3b23a1710a567ea4ad322edc404182206b4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 60, "num_lines": 17, "path": "/Python/IndustrialProgramming/classes/class1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nclass C:\n\n \"\"\"Purpose-free demo class.\"\"\"\n classVar1 = 42\n\n def method1(self):\n \"Just a random method.\"\n print (\"classVar1 = %d\" % C.classVar1)\n\nprint(\"Testing classes; expect value '42' printed 2 times.\")\nX = C # alias the class object\nx = X() # create an instance of C\nX.method1(x) # call method (class view)\nx.method1() # call method (instance view)\n" }, { "alpha_fraction": 0.40664374828338623, "alphanum_fraction": 0.41523483395576477, "avg_line_length": 28.610170364379883, "blob_id": "fc43021d68cc73f66a402c17bd7239d471a56137", "content_id": "88f5099066305683265a292e49891b677fb7fd04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1746, "license_type": "no_license", "max_line_length": 83, "num_lines": 59, "path": "/CSharp/code-examples/io/files4.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Example from Lecture 7: Streams\n// remove all punctuation symbols from a text file\n\nusing System;\nusing System.IO;\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic class DotKill\n{\n // main worker function, removing all punctuation symbols in file\n public static string removePunctuation(string file)\n {\n string file0 = file + \"0\";\n\n if (File.Exists(file))\n {\n using (StreamReader sr = new StreamReader(file)) // open file\n {\n using (StreamWriter sw = new StreamWriter(file0)) // open file\n {\n string str = \"\";\n string str0 = \"\";\n while ((str = sr.ReadLine()) != null) // iterate over all lines\n {\n str0 = \"\";\n foreach (char c in str)\n {\n if (Char.IsPunctuation(c))\n {\n // nothing\n }\n else\n {\n str0 += c;\n }\n }\n sw.WriteLine(str0.ToLower());\n }\n }\n }\n }\n return file0;\n }\n\n public static void Main (string[] args)\n {\n if (args.Length != 1) // expect 1 args: filename\n {\n System.Console.WriteLine(\"Usage: files4 <filename>\");\n }\n else\n {\n string file = args[0];\n DotKill.removePunctuation(file);\n System.Console.WriteLine(\"Result written to {0}0\", file);\n }\n }\n}" }, { "alpha_fraction": 0.7005614638328552, "alphanum_fraction": 0.7055521011352539, "avg_line_length": 28.14545440673828, "blob_id": "3306cf73bbc86df63b54bc7b51303ed93b282ce6", "content_id": "6548bb00a2c6a897ef5685ad6de2871500b4c0c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1603, "license_type": "no_license", "max_line_length": 90, "num_lines": 55, "path": "/CSharp/code-examples/advanced/delegates1.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Lecture 6: Advanced C# Constructs: Delegates\n\n// p384\n\nusing System;\npublic class MediaStorage {\n // declare a delegate, ie. the type of the method\n public delegate int PlayMedia();\n\n // this is a higher-order function, ie. it uses a delegate\n public void ReportResult(PlayMedia playerDelegate) {\n if (playerDelegate() == 0) {\n Console.WriteLine(\"Media played successfully\");\n } else {\n Console.WriteLine(\"Error in playing media.\");\n }\n }\n}\n\n// now 2 classes, each with a possible instance of the delegate\n\npublic class AudioPlayer {\n private int audioPlayerStatus;\n public int PlayAudioFile() {\n Console.WriteLine(\"Playing audio file\");\n audioPlayerStatus = 0;\n return audioPlayerStatus;\n }\n}\n\npublic class VideoPlayer {\n private int videoPlayerStatus;\n public int PlayVideoFile() {\n Console.WriteLine(\"Playing video file\");\n videoPlayerStatus = 0;\n return videoPlayerStatus;\n }\n}\n\npublic class Tester {\n // in Main we use the higher-order function\n public static void Main () {\n // instantiate the storage class\n MediaStorage ms = new MediaStorage();\n // instantiate the player classes\n AudioPlayer aPlayer = new AudioPlayer();\n VideoPlayer vPlayer = new VideoPlayer();\n // instantiate the delegate\n MediaStorage.PlayMedia aDelegate = new MediaStorage.PlayMedia(aPlayer.PlayAudioFile);\n MediaStorage.PlayMedia vDelegate = new MediaStorage.PlayMedia(vPlayer.PlayVideoFile);\n // provide instances to the method using the delegate\n ms.ReportResult(aDelegate);\n ms.ReportResult(vDelegate);\n }\n}\n" }, { "alpha_fraction": 0.6774193644523621, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 17.600000381469727, "blob_id": "7c243b495a4222ec2128a303e878d4a232a859b2", "content_id": "d1713362844c47416968a84c0cbf1bdf2e3512de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 36, "num_lines": 10, "path": "/Python/IndustrialProgramming/advanced/static1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Simple example of static methods\n\nclass Static:\n # static method\n def __bla(): print \"Hello, world!\"\n hello = staticmethod(__bla)\n\nStatic.hello()\nStatic().hello()\n" }, { "alpha_fraction": 0.6351404786109924, "alphanum_fraction": 0.6426593065261841, "avg_line_length": 21.635513305664062, "blob_id": "e8f4bd9a123796b318811260cce2d0c68dc45c16", "content_id": "f6296ff0429880fc42345ace7fd878930e1cde9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2527, "license_type": "no_license", "max_line_length": 124, "num_lines": 107, "path": "/Java/F21SF Soft E Fundation/Assignment 2/src/assignment_2/Name.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package assignment_2;\r\n\r\n\r\n/**\r\n * This class is creating a name object \r\n * Name class also include methods to access specific parts of name\r\n * @author Group\r\n *\r\n */\r\npublic class Name {\r\n\tprivate String firstName;\r\n\tprivate String middleName;\r\n\tprivate String lastName;\r\n\r\n\t/**\r\n\t * This constructor is used to setting up the name-object based on first and last name\r\n\t * @param firstName first name of the person/team\r\n\t * @param middleName as empty string \r\n\t * @param lastName last name of the person/name\r\n\t */\r\n\tpublic Name(String fName, String lName) \r\n\t{\r\n\t\tfirstName = fName;\r\n\t\tmiddleName = \"\";\r\n\t\tlastName = lName;\r\n\t}\r\n\r\n\r\n\t/** This constructor is used to setting up the name-object based on first-, middle- and last name\r\n\t * @param fName\r\n\t * @param mName\r\n\t * @param lName\r\n\t */\r\n\tpublic Name(String fName, String mName, String lName) \r\n\t{\r\n\t\tfirstName = fName;\r\n\t\tmiddleName = mName;\r\n\t\tlastName = lName;\r\n\t}\r\n\r\n\r\n\t/**This constructor is used to setting up the name-object based fullname only.\r\n\t * Based on fullname It will get first, middle and last name\r\n\t * @param fullName, long string containing all names together separated by ' '\r\n\t */\r\n\r\n\tpublic Name (String fullName) \r\n\t{\r\n\t\tint spacePos1 = fullName.indexOf(' ');\r\n\t\tfirstName = fullName.substring(0, spacePos1+1);\r\n\t\tint spacePos2 = fullName.lastIndexOf(' ');\r\n\t\tif (spacePos1 == spacePos2)\r\n\t\t\tmiddleName = \"\";\r\n\t\telse \r\n\t\t\tmiddleName = fullName.substring(spacePos1+1, spacePos2);\r\n\t\tlastName = fullName.substring(spacePos2 + 1);\r\n\t}\r\n\r\n\r\n\r\n\t/**\r\n\t * Returning the full name of the person/team . If the person doesn't have a middle name, and the middle name is set to \"\",\r\n\t * then it will only return the first and last name\r\n\t * @return full name of the person/team\r\n\t */\r\n\tpublic String getFullName() \r\n\t{\r\n\t\tString result = firstName + \" \";\r\n\t\tif (!middleName.equals(\"\")) \r\n\t\t{\r\n\t\t\tresult += middleName + \" \";\r\n\t\t}\r\n\t\tif (!lastName.equals(\"\")) \r\n\t\t{\r\n\t\t\tresult += lastName;\r\n\t\t}\r\n\r\n\t\treturn result;\t \r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Only returns the initials for the first, middle and last name. If the person doesn't have a middle name,\r\n\t * it only returns the initial for the first and last name\r\n\t * @return first, middle and last name initials\r\n\t */\r\n\tpublic String getShortName()\r\n\t{\r\n\t\tString shorts = \"\";\r\n\t\tif (firstName !=\"\")\r\n\t\t{\r\n\t\t\tshorts+=firstName.substring(0,1);\r\n\t\t}\r\n\t\tif (middleName!=\"\")\r\n\t\t{\r\n\t\t\tshorts+=middleName.substring(0,1);\r\n\t\t}\r\n\t\tif(lastName!=\"\")\r\n\t\t{\r\n\t\t\tshorts+=lastName.substring(0,1);\r\n\t\t}\r\n\r\n\t\treturn shorts;\r\n\t}\r\n\r\n\r\n}" }, { "alpha_fraction": 0.6979866027832031, "alphanum_fraction": 0.6979866027832031, "avg_line_length": 23.83333396911621, "blob_id": "70a3b4e8babd8eac6688a1de7ce48d2e3122b5cf", "content_id": "44810456ef5b3323c79477a5f785401add063920", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 298, "license_type": "no_license", "max_line_length": 63, "num_lines": 12, "path": "/Ruby/BYG/spec/features/searches_spec.rb", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "require 'rails_helper'\nrequire 'capybara/rails'\n\n\nRSpec.describe \"Searches\", :type => :feature do\n describe \"GET /searches/index\" do\n it \"should show searches from diffrent search providers\" do\n visit \"/searches/index\"\n expect(page).to\thave_content \"Find me in app\"\n end\n end\nend\n" }, { "alpha_fraction": 0.6371625661849976, "alphanum_fraction": 0.6459510326385498, "avg_line_length": 19.675325393676758, "blob_id": "cbefb73bba27b20cfb2e855ae3f38d2244db00f5", "content_id": "58956ffbfddc1540936607099c785a14b76a2fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1593, "license_type": "no_license", "max_line_length": 81, "num_lines": 77, "path": "/JavaScript/Other/inheritance.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n// ------------------ ES5 --------------------//\n/**\n * Constructor for superclas is called when extending prototype\n * Defining methods on prototype can only be done after proto is extened\n */\nfunction Human(){\n console.log('Human constructor called');\n}\n\nHuman.prototype.speak = function(){\n console.log('Human speak');\n}\n\nfunction Person(){\n console.log('Person constructor called');\n}\n\nPerson.prototype = new Human();\n\nPerson.prototype.walk = function() {\n console.log('Person walk');\n}\n\nvar person1 = new Person();\nperson1.speak();\nperson1.walk();\n\n// ------------------- ES5 Object.create ------//\n// Constructor of superclass is called using call(this, arg1, arg2)\n// To avoid calling constructor again use Object.create on proptype of superclass\nfunction Human(){\n console.log('Human constructor called');\n}\n\nHuman.prototype.speak = function(){\n console.log('Human speak');\n}\n\nfunction Person(){\n Human.call();\n console.log('Person constructor called');\n}\n\nPerson.prototype = Object.create(Human.prototype);\nPerson.prototype.constructor = Person;\n\nPerson.prototype.walk = function() {\n console.log('Person walk');\n}\n\nvar person1 = new Person();\nperson1.speak();\nperson1.walk();\n// ------------------- ES6 Sugar --------------//\n\nclass Human {\n constructor(){\n console.log('Human constructor called');\n }\n speak() {\n console.log('Human speak');\n }\n}\n\nclass Person extends A {\n constructor(){\n super();\n console.log('Person constructor called');\n }\n walk(){\n console.log('Person walk');\n }\n}\n\nvar person2 = new Person();\nperson2.speak();\nperson2.walk();\n" }, { "alpha_fraction": 0.5978062152862549, "alphanum_fraction": 0.6069470047950745, "avg_line_length": 21.782608032226562, "blob_id": "d483731d5df2c2b92cdb424480293d7163a7fc52", "content_id": "98c7c876561b46a48119a22f745d041d4cb930b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 548, "license_type": "no_license", "max_line_length": 53, "num_lines": 23, "path": "/Java/F21SF Soft E Fundation/4/src/CarMain.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "MacCentralEurope", "text": "/**\r\n * Software Engineering Foundations\r\n * Testing Car with owner Name\r\n * @author monica\r\n */\r\n\r\npublic class CarMain {\r\n\tpublic static void main (String[] args) {\r\n\t\t//create a Name\r\n\t\tName myName = new Name(\"John\", \"David\", \"Smith\");\r\n\t\t//create a Car\r\n\t\tCar myCar = new Car(\"Ford Ka\", 40, 33.6, myName); \r\n\t\t\r\n\t\tName owner = myCar.getOwnerName();\r\n\t\tSystem.out.println(\"The car belongs to \" \r\n\t\t\t\t+ owner.getFirstAndLastName() );\r\n\t\tSystem.out.println(\"It is \" + owner.getFirstName() \r\n\t\t\t\t+ \"ís car.\") ;\r\n\t\t\r\n\r\n\t} //end main method\r\n\r\n}\r\n" }, { "alpha_fraction": 0.47145789861679077, "alphanum_fraction": 0.47145789861679077, "avg_line_length": 26.35955047607422, "blob_id": "d0fc4c42a74e2957cd40252787fa0b89d6545803", "content_id": "701eb43cceb51e339113fa7420f2eacacc8a9323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2437, "license_type": "no_license", "max_line_length": 98, "num_lines": 89, "path": "/CSharp/coursework/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/models/HomePageConfig.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.IO;\nusing System.Text;\n\nnamespace WebBrowser_OuterSpace.models\n{ \n /// <summary>\n /// Singleton that control settings of home page\n /// </summary>\n class HomePageConfig\n {\n public String homePageURL { get; set; }\n private static HomePageConfig instance;\n\n private HomePageConfig()\n {\n\n }\n /// <summary>\n /// I am possibly overusing Singleton pattern but It make me write this application faster\n /// </summary>\n public static HomePageConfig Instance\n {\n get\n {\n if (instance == null)\n {\n instance = new HomePageConfig();\n }\n return instance;\n }\n }\n\n /// <summary>\n /// Read from file home page settings\n /// </summary>\n public void readConfig()\n {\n try\n {\n StreamReader sr = new StreamReader(\"homePageConfig.txt\");\n\n //Read the first line of text where url of home page is\n homePageURL = sr.ReadLine();\n\n //Close the file\n sr.Close();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Exception: \" + e.Message);\n }\n finally\n {\n Console.WriteLine(\"Executing finally block.\");\n }\n }\n\n /// <summary>\n /// Clear file and write new address of home page\n /// </summary>\n /// <param name=\"homeURL\"></param>\n public void writeHomeConfig(String homeURL)\n {\n homePageURL = homeURL;\n try\n {\n //Clear file, clear last homepage settings\n System.IO.StreamWriter file = new System.IO.StreamWriter(\"homePageConfig.txt\");\n file.Write(\"\");\n file.Close();\n\n //Open the File and write ne home page\n StreamWriter sw = new StreamWriter(\"homePageConfig.txt\", true, Encoding.ASCII);\n sw.WriteLine(homeURL);\n sw.Close();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Exception: \" + e.Message);\n }\n finally\n {\n Console.WriteLine(\"Executing finally block.\");\n\n }\n } \n }\n}\n" }, { "alpha_fraction": 0.38367345929145813, "alphanum_fraction": 0.4653061330318451, "avg_line_length": 21.272727966308594, "blob_id": "97f6ddc075f587b305ce9a2ecbda9076ee5249ca", "content_id": "d3ba7f4f665f4e8ed18f3528cb40387335b05e3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 69, "num_lines": 11, "path": "/Python/CodingTests/complex-input.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# import sys\n\n# input_all = []\n\n# for line in sys.stdin:\n# print(line)\n# input_all.append([int(x) for x in line.split() if x.isdigit()])\n\n\ninput_all = [[2], [3, 10], [2, 1, 3], [7, 8, 9],\n [4, 5], [1, 2, 2, 1], [3, 3, 3, 4]]\n" }, { "alpha_fraction": 0.6555126309394836, "alphanum_fraction": 0.6761046648025513, "avg_line_length": 21.200000762939453, "blob_id": "3b9b203c3179642053a5f283894dd71bfabb0d2c", "content_id": "b3293eb0bedb3d5a738b3fe4250015bd5475eaed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2331, "license_type": "no_license", "max_line_length": 62, "num_lines": 105, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orderstests/TestOrderCollection.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orderstests;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport restaurant.orders.BadQuantityException;\nimport restaurant.orders.DishOrder;\nimport restaurant.orders.OrderCollection;\n\npublic class TestOrderCollection\n{\n\tprivate DishOrder dish1, dish2, dish3, dish4, dish5;\n\tprivate OrderCollection orderSetTest;\n\n\t/**\n\t * Setting up the tests with one default main dish\n\t */\n\t@Before\n\tpublic void setUp() {\n\t\torderSetTest = new OrderCollection();\n\t\tdish1 = new DishOrder(1,\"Tikka Mane\", 2, 1);\n\t\tdish2 = new DishOrder(2,\"Tikka Mane\", 1, 2);\n\t\tdish3 = new DishOrder(1,\"Tikka Hot\", 2, 3);\n\t\tdish4 = new DishOrder(3,\"Tikka Hot\", 3 ,4);\n\t\tdish5 = new DishOrder(4,\"Tikka Hot\", 3, 5);\n\t\torderSetTest.add(dish1);\n\t\torderSetTest.add(dish2);\n\t\torderSetTest.add(dish3);\n\t\torderSetTest.add(dish4);\n\t\torderSetTest.add(dish5);\n\t}\n\n\n\t/**Test if Exception BadQuantityException, \n\t * is thrown for quantity >10\n\t */\n\t@Test\n\tpublic void invalidQuantitySupplied()\n\t{\n\t\ttry\n\t\t{\n\t\t\tDishOrder dish6 = new DishOrder(4,\"Tikka Hot\", 12, 5);\n\t\t\torderSetTest.add(dish6);\n\t\t\tfail(\"Invalid quantity supplied - should throw exception\");\n\t\t}\n\t\tcatch (BadQuantityException e)\n\t\t{\n\t\t\tassertTrue(e.getMessage().contains(\"5\"));\n\t\t}\n\t}\n\t\n\t\n\t/**Test method getFrequencyForDish()\n\t * This method for given order should return freq \n\t */\n\t@Test\n\tpublic void test1GetFrequencyForDish()\n\t{\n\t\tint test = orderSetTest.getFrequencyForDish(\"Tikka Hot\");\n\t\tassertTrue(test == 3);\n\t}\n\t\n\t\n\t/**Test method getFrequencyForDish()\n\t * check for different dishname\n\t */\n\t@Test\n\tpublic void test2GetFrequencyForDish()\n\t{\n\t\tint test = orderSetTest.getFrequencyForDish(\"Tikka Mane\");\n\t\tassertTrue(test == 2);\n\t}\n\t\n\t/**Test method getFrequencyForDish()\n\t * check dishName frequency that is not in the list\n\t */\n\t@Test\n\tpublic void test3GetFrequencyForDish()\n\t{\n\t\tint test = orderSetTest.getFrequencyForDish(\"Tikka\");\n\t\tassertTrue(test == 0);\n\t}\n\t\n\t\n\t/**Test of frequencyReport()\n\t * Check if method produce correct string\n\t */\n\t@Test\n\tpublic void test1frequencyReport()\n\t{\n\t\t\n\t\tString expected =\"FREQUENCY REPORT\" + \"\\n\"+\n\t\t\t\t\"Tikka Hot 3\" + \"\\n\" +\n\t\t\t\t\"Tikka Mane 2\" + \"\\n\";\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\tString actual = orderSetTest.frequencyReport();\n\t\t\n\t\tassertEquals(expected, actual);\n\n\t}\n\t\n}\n" }, { "alpha_fraction": 0.48986107110977173, "alphanum_fraction": 0.4921141564846039, "avg_line_length": 28.75419044494629, "blob_id": "6ee471cbe3bd879ec773ae91e34b5cefee1f66df", "content_id": "b67cf8c1c8823fdd18c004e7c731703e7b3abbd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5328, "license_type": "no_license", "max_line_length": 93, "num_lines": 179, "path": "/CSharp/coursework/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/models/HistoryCollection.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections;\nusing System.IO;\nusing System.Text;\n\nnamespace WebBrowser_OuterSpace.models\n{\n /// <summary>\n /// Manage history of Browser\n /// </summary>\n class HistoryCollection\n {\n /// <summary>\n /// Nested ArrayList will represent history for each tab\n /// HashMaps could be possible a bit better but this will do\n /// </summary>\n private ArrayList historyCollection = new ArrayList();\n\n private static HistoryCollection instance;\n\n private HistoryCollection()\n {\n\n }\n /// <summary>\n /// Singleton method\n /// </summary>\n public static HistoryCollection Instance\n {\n get\n {\n if (instance == null)\n {\n instance = new HistoryCollection();\n }\n return instance;\n }\n }\n /// <summary>\n /// Add new entry to Browser history\n /// </summary>\n /// <param name=\"url\"></param>\n /// <param name=\"tabID\"></param>\n public void addToHistoryPerTab(String url, int tabID)\n {\n throw new NotImplementedException();\n }\n\n /// <summary>\n /// Load history from file on startup\n /// It is used in Program.cs\n /// </summary>\n public void readHistoryConfig()\n {\n String line;\n try\n {\n //Pass the file path and file name to the StreamReader constructor\n StreamReader sr = new StreamReader(\"webHistory.txt\");\n\n //Read the first line of text\n line = sr.ReadLine();\n buildHistoryColection(line);\n\n //Continue to read until you reach end of file\n while (line != null)\n {\n buildHistoryColection(line);\n //Read the next line\n line = sr.ReadLine();\n }\n\n //close the file\n sr.Close();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Exception: \" + e.Message);\n }\n finally\n {\n Console.WriteLine(\"Executing finally block.\");\n }\n }\n /// <summary>\n /// Helper method for ReadHistoryConfig\n /// Pupulate ArrayLists\n /// </summary>\n /// <param name=\"line\"></param>\n private void buildHistoryColection(String line)\n {\n string[] input = line.Split(',');\n int tabID = 0;\n\n try { \n tabID = Convert.ToInt32(input[0]);\n }\n catch (FormatException e)\n {\n Console.WriteLine(e.Message);\n }\n\n //Init I set limitation on maximum 25 tabs. above that history will be not holded\n for (int i = 0; i < 25; i++)\n\t\t\t{\n\t\t\t historyCollection.Add(new ArrayList());\n\t\t\t}\n\n ArrayList tabIDArrayList = (ArrayList)historyCollection[tabID];\n tabIDArrayList.Add(input[1]);\n\n }\n\n /// <summary>\n /// Write new record to file and add entry to History List in heap\n /// </summary>\n /// <param name=\"url\"></param>\n /// <param name=\"tabID\"></param>\n public void writeRecordHistory(string url, int tabID)\n {\n\n string line = tabID.ToString() + \",\" + url;\n ArrayList tabIDArrayList = (ArrayList)historyCollection[tabID];\n tabIDArrayList.Add(url);\n\n try{\n StreamWriter sw = new StreamWriter(\"webHistory.txt\", true, Encoding.ASCII);\n sw.WriteLine(line);\n sw.Close();\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Exception: \" + e.Message);\n }\n finally\n {\n Console.WriteLine(\"Executing finally block.\");\n\n }\n }\n /// <summary>\n /// Get Historical URL for next and prev functionality\n /// Use deepness to manage wiith history link per tab to retrieve\n /// </summary>\n /// <param name=\"tabID\"></param>\n /// <param name=\"deepness\"></param>\n /// <returns></returns>\n public String getHistoryURL(int tabID, int deepness){\n\n ArrayList tabIDArrayList = (ArrayList)historyCollection[tabID];\n int ArrayLenght = tabIDArrayList.Count;\n if(ArrayLenght > (-deepness) && deepness < 0 ){\n int index = ArrayLenght + (deepness - 1);\n return tabIDArrayList[index].ToString();\n }\n return \"No history for this index\";\n }\n\n \n /// <summary>\n /// Flaten Historry nested Array to simple Array of links\n /// </summary>\n /// <returns></returns>\n public ArrayList getFullhistory()\n {\n ArrayList totalHistory = new ArrayList();\n\n foreach (ArrayList perTabHistory in historyCollection)\n {\n foreach (var singleItem in perTabHistory)\n {\n totalHistory.Add(singleItem);\n }\n }\n return totalHistory;\n \n }\n }\n}\n" }, { "alpha_fraction": 0.562666654586792, "alphanum_fraction": 0.6186666488647461, "avg_line_length": 18.736841201782227, "blob_id": "0fac16caa502d790e8d4500bb21344d82a49af6a", "content_id": "ff189ca498b7a300109d9c5534e5c39eec117555", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 50, "num_lines": 19, "path": "/Python/IndustrialProgramming/data/dict1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python2\n\n# Simple example of a dictionary: phone dictionary\n\ntel = dict([('guido', 4127), ('jack', 4098)])\n# expect this\n# {'jack': 4098, 'guido': 4127}\n\n# add me to the dictionary\ntel['me'] = 1234\n\nprint(\"After adding me ...\")\nprint(tel)\n\nprint(\"After deleting me ...\")\ndel tel['me']\n\nfor k, v in tel.iteritems():\n print (\"The phone number of \", k, \" is \", v)\n" }, { "alpha_fraction": 0.44247788190841675, "alphanum_fraction": 0.5044247508049011, "avg_line_length": 17.83333396911621, "blob_id": "bbc0be943b84f467c391d2520f0293f35fc103ab", "content_id": "10ba4ad9a611738a0a924757ad3c22ee070c4570", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 113, "license_type": "no_license", "max_line_length": 33, "num_lines": 6, "path": "/Python/CodingTests/simple-input.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# N = int(input())\n# items = input().split()\n# items = [int(x) for x in items]\n\nN = 6\nitems = [5, 4, 4, 2, 2, 8]\n" }, { "alpha_fraction": 0.6386861205101013, "alphanum_fraction": 0.6423357725143433, "avg_line_length": 23.909090042114258, "blob_id": "66ea9ff2bfa4e1dda981348d935f3bae51e48f8e", "content_id": "4ea9bb7165ff440f840b5a3204c426ab11bb1fef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 274, "license_type": "no_license", "max_line_length": 59, "num_lines": 11, "path": "/Python/IndustrialProgramming/advanced/static2.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Simple example of static methods\n\nclass Static:\n val = 5\n # class method\n def sqr(c): return c.val * c.val\n sqr = classmethod(sqr)\n\nprint(\"The square of \", Static.val, \" is \", Static.sqr())\nprint(\"The square of \", Static.val, \" is \", Static().sqr())\n" }, { "alpha_fraction": 0.6017369627952576, "alphanum_fraction": 0.607692301273346, "avg_line_length": 30.484375, "blob_id": "fd7875a46def6862b8a295f4a0bc4ab0b689c309", "content_id": "c549168aa7537419b4c383696696d8a11334b2fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4030, "license_type": "no_license", "max_line_length": 118, "num_lines": 128, "path": "/Python/IndustrialProgramming/classes/account.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Bank account example, from the C# revision class\n\n# define a new exception\n\n\nclass InsufficientBalance(Exception):\n pass\n\n\nclass BankAccount:\n\n \"Plain bank account.\"\n __latestAccountNo = 1000\n # NB: this init is done too late, when executing the constructor\n\n def __init__(self, name, accountNo=0, balance=0):\n # make sure that the variable is defined\n if BankAccount.__dict__.has_key(BankAccount.__latestAccountNo):\n BankAccount.__latestAccountNo += 1\n else:\n BankAccount.__latestAccountNo = 1000\n # check whether we have an accountNo input, otw pickup value from __latestAccountNo\n if accountNo == 0: # this means, pick-up value from local var\n self.accountNo = BankAccount.__latestAccountNo\n else:\n self.accountNo = accountNo\n self.name = name\n self.balance = balance\n\n def Deposit(self, x):\n \"\"\"Depositing money into the account.\"\"\"\n self.balance += x\n\n def Withdraw(self, x):\n \"\"\"Withdrawing money from the account.\"\"\"\n if self.balance >= x:\n self.balance -= x\n else:\n raise InsufficientBalance, \"Balance too low: %d\" % self.balance\n\n def GetBalance(self):\n \"\"\"Return the current balance on the account.\"\"\"\n return self.balance\n\n def ShowBalance(self):\n \"\"\"Display the current balance on the account.\"\"\"\n print (\"Current Balance: \", self.balance)\n\n def ShowAccount(self):\n \"\"\"Display details of the BankAccount.\"\"\"\n print (\"Account Number: \", self.accountNo, \"\\tAccount Name: \", self.name, \"\\tCurrent Balance: \", self.balance)\n\n\nclass ProperBankAccount(BankAccount):\n\n \"\"\"Bank account with overdraft.\"\"\"\n\n def __init__(self, name, accountNo=0, balance=0):\n \"\"\"Constructor\"\"\"\n BankAccount.__init__(self, name, accountNo, balance)\n self.overdraft = 0\n\n def Withdraw(self, x):\n \"\"\"Withdrawing money from a ProperBankAccount account.\"\"\"\n if self.balance + self.overdraft >= x:\n self.balance -= x\n else:\n raise InsufficientBalance, \"Balance (incl overdraft) too low: %d\" % self.balance\n\n def ShowAccount(self):\n \"\"\"Display details of the BankAccount.\"\"\"\n BankAccount.ShowAccount(self)\n print (\"\\t with an overdraft of \", self.overdraft)\n\n\nclass Tester:\n\n \"\"\"Tester class.\"\"\"\n\n def RunTrans(self, acct):\n \"\"\"Run a sequence of transactions.\"\"\"\n if (isinstance(acct, ProperBankAccount)): # test class membership\n acct.overdraft = 200 # if ProperBankAccount, set overdraft\n acct.ShowAccount()\n acct.ShowBalance()\n # first, deposit something\n x = 600\n print(\"Depositing \", )\n acct.Deposit(x)\n acct.ShowBalance()\n # then, try to withdraw something\n y = 400\n print(\"Withdrawing \", y)\n try:\n acct.Withdraw(y)\n except InsufficientBalance:\n print(\"InsufficientBalance \", acct.GetBalance(), \" for withdrawl of \", y)\n acct.ShowBalance()\n # then, try to withdraw the same amount again\n print(\"Withdrawing \", y)\n try:\n acct.Withdraw(y)\n except InsufficientBalance:\n print(\"InsufficientBalance \", acct.GetBalance(), \" for withdrawl of \", y)\n acct.ShowBalance()\n acct.ShowAccount()\n\n\n# main:\nif __name__ == '__main__': # check whether this module is the main module\n t = Tester()\n # generate a tester instance\n\n # create a basic account; NB: no 'new' needed\n mine = BankAccount(\"MyAccount\")\n # create a proper account; NB: no 'new' needed\n mineOvdft = ProperBankAccount(\"MyProperAccount\")\n\n # t.RunTrans(mine)\n # t.RunTrans(mineOvdft)\n\n # put both accounts into a list; NB: polymorphic\n accts = [mine, mineOvdft]\n # iterate over the list\n for acct in accts:\n # run transactions on the current account\n t.RunTrans(acct)\n" }, { "alpha_fraction": 0.700507640838623, "alphanum_fraction": 0.7119289636611938, "avg_line_length": 23.24615478515625, "blob_id": "05221392483c84f65bf4b5a94005d565ef72331d", "content_id": "9755f867cede03df8d9e9e24613343bde33fe920", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1576, "license_type": "no_license", "max_line_length": 98, "num_lines": 65, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orderstests/TestDishItem.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orderstests;\n\nimport restaurant.orders.DishItem;\nimport static org.junit.Assert.*;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class TestDishItem {\n\n\tDishItem dishMain, dishEqual, dishNotEqual, dishPriceNotEqual, dishNameNotEqual, dishCatNotEqual;\n\t\n\t/**\n\t * Setting up the tests with one default main dish\n\t */\n\t@Before\n\tpublic void setUp() {\n\t\tdishMain = new DishItem(\"Tikka Masala\", 6.29, \"Indian\");\n\t}\n\t\n\t/**\n\t * Testing if it returns true when dishes are equal\n\t */\n\t@Test\n\tpublic void testEqualsTrue() {\n\t\tdishEqual = new DishItem(\"Tikka Masala\", 6.29, \"Indian\");\n\t\tassertTrue(dishMain.equals(dishEqual));\n\t}\n\t\n\t/**\n\t * Testing if it returns false if no parameters are equal\n\t */\n\t@Test\n\tpublic void testEqualsAllFalse() {\n\t\tdishNotEqual = new DishItem(\"Korma\", 5.50, \"Chinese\");\n\t\tassertFalse(dishMain.equals(dishNotEqual));\n\t}\n\t\n\t/**\n\t * Testing if it returns false if dish names are not equal\n\t */\n\t@Test\n\tpublic void testEqualsNamesFalse() {\n\t\tdishNameNotEqual = new DishItem(\"Korma\", 6.29, \"Indian\");\n\t\tassertFalse(dishMain.equals(dishNameNotEqual));\n\t}\n\t\n\t/**\n\t * Testing if it returns false if prices are not equal\n\t */\n\t@Test\n\tpublic void testEqualsPricesFalse() {\n\t\tdishPriceNotEqual = new DishItem(\"Tikka Masala\", 5.50, \"Indian\");\n\t\tassertFalse(dishMain.equals(dishPriceNotEqual));\n\t}\n\t\n\t/**\n\t * Testing if it returns false if categories are not equal\n\t */\n\t@Test\n\tpublic void testEqualsCategoriesFalse() {\n\t\tdishCatNotEqual = new DishItem(\"Tikka Masala\", 6.29, \"Chinese\");\n\t\tassertFalse(dishMain.equals(dishCatNotEqual));\n\t}\n}\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 21, "blob_id": "f893110884e495fc812eaae7c1d8af41b47363de", "content_id": "c6bc0236289c1e5fc8d06579125497f0fec250ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/Python/InteractiveCoursera/__init__.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "__author__ = 'raziel'\n" }, { "alpha_fraction": 0.6045411825180054, "alphanum_fraction": 0.6083254218101501, "avg_line_length": 29.200000762939453, "blob_id": "b5bca5bbdf205932b4250c6a32dec054bc491a25", "content_id": "693d984335af13b5dacc17467e672ae0332116a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4228, "license_type": "no_license", "max_line_length": 71, "num_lines": 140, "path": "/Java/F21SF Soft E Fundation/14_15/src/StaffListGUI.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "//import all the GUI classes\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\n/**\n * Simple GUI for StaffList application\n */\npublic class StaffListGUI extends JFrame implements ActionListener\n{\n // The staff list to be searched.\n private StaffList staffList;\n \n //GUI components\n JTextField result;\n JTextField searchField;\n JButton search;\n JScrollPane scrollList;\n JButton showListById, showListByName, close;\n JTextArea displayList;\n \n //also create grid of buttons\n GridOfButtonsFrame gobf; \n \n /**\n * Create the frame with its panels.\n * @param list\tThe staff list to be searched.\n */\n public StaffListGUI(StaffList list)\n {\n this.staffList = list;\n \n //set up window title\n setTitle(\"StaffList\");\n //disable standard close button\n\t\tsetDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);\n \n\t\tsetupSouthPanel();\n\t\tsetupNorthPanel();\n\t\tsetupCenterPanel();\n\n //pack and set visible\n pack();\n setVisible(true);\n \n gobf = new GridOfButtonsFrame(staffList);\n gobf.pack(); \n gobf.setVisible(true);\n }\n \n private void setupCenterPanel() {\n displayList = new JTextArea(15,20);\n displayList.setFont(new Font (Font.MONOSPACED, Font.PLAIN,14));\n displayList.setEditable(false);\n scrollList = new JScrollPane(displayList);\n this.add(scrollList,BorderLayout.CENTER);\n }\n \n private void setupSouthPanel() {\n //search panel contains label, text field and button\n JPanel searchPanel = new JPanel();\n searchPanel.setLayout(new GridLayout(1,3));\n searchPanel.add(new JLabel(\"Enter ID\")); \n searchField = new JTextField(5);\n searchPanel.add(searchField); \n search = new JButton(\"Search\"); \n searchPanel.add(search); \n //specify action when button is pressed\n search.addActionListener(this) ;\n \n //Set up the area where the results will be displayed.\n result= new JTextField(25); \n result.setEditable(false);\n \n //set up south panel containing 2 previous areas\n JPanel southPanel = new JPanel();\n southPanel.setLayout(new GridLayout(2,1));\n southPanel.add(searchPanel);\n southPanel.add(result);\n \n //add south panel to the content pane\n this.add(southPanel, BorderLayout.SOUTH); \t\n }\n \n private void setupNorthPanel() {\n //add north panel containing some buttons\n JPanel northPanel = new JPanel();\n showListById = new JButton(\"List By ID\");\n showListById.addActionListener(this);\n \n showListByName = new JButton(\"List By Name\");\n showListByName.addActionListener(this);\n \n close = new JButton(\"Close\");\n close.addActionListener(this);\n \n northPanel.add (showListById);\n northPanel.add(showListByName);\n northPanel.add(close);\n this.add(northPanel, BorderLayout.NORTH);\n }\n \n //come here when button is clicked\n //find which button and act accordingly\n public void actionPerformed(ActionEvent e) \n { \n \tif (e.getSource() == search) {\n \t\tsearch();\n \t}\n \telse if (e.getSource() == showListById) {\n \t\tdisplayList.setText(staffList.listByID());\n \t}\n \telse if (e.getSource() == showListByName ) {\n \t\tdisplayList.setText(staffList.listByName());\n \t}\n \telse if (e.getSource() == close) {\n \t\tJOptionPane.showMessageDialog(this, \n \t\t\t\t \"Do 'end of program' things instead of showing this\");\n \t\tSystem.exit(0);\n \t}\n } \n \n private void search() {\n \t//get search text and search staff list\n \t//setting result text \n String searchString = searchField.getText().trim();\n if(searchString.length() > 0) {\n Staff person = staffList.findById(searchString);\n if (person != null ) {\n \tresult.setText(person.toString());\n \tgobf.disableButton(person.getName().getFirstName());\n }\n else\n \tresult.setText(\"not found\");\n } \n else\n \tresult.setText(\"no text entered\");\n }\n\n}\n" }, { "alpha_fraction": 0.505586564540863, "alphanum_fraction": 0.5279329419136047, "avg_line_length": 19.764705657958984, "blob_id": "25276c27c02a6e3a8b9a794e3aa20fe37b7e6534", "content_id": "19863315904eb70d695bc0d8c1358159410ded61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/Python/IndustrialProgramming/advanced/exc3.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Testing exceptions\n\ndef divide(x, y):\n try:\n result = x / y\n except ZeroDivisionError:\n print (\"division by zero!\")\n else:\n print (\"result is\", result)\n finally:\n print (\"executing finally clause\")\n\nxs = [(5,3), (8,2), (3,0), (4,1) ]\nfor x, y in xs:\n print(\"Input: \", x, y)\n divide(x,y)\n \n" }, { "alpha_fraction": 0.5416666865348816, "alphanum_fraction": 0.5438596606254578, "avg_line_length": 19.727272033691406, "blob_id": "92deaade7a3183cd54fb8bb566d5f8a92dbb25b3", "content_id": "2e4968efd3648d14c95a598357b564341632e71d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 912, "license_type": "no_license", "max_line_length": 75, "num_lines": 44, "path": "/Interviews/pebble/battleships/src/app/components/grid.ts", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/// <reference path=\"../../typings/_custom.d.ts\" />\n\nimport {Component, CORE_DIRECTIVES, EventEmitter} from 'angular2/angular2';\n\n/*\n * Directive Grid\n */\n@Component({\n\tselector: 'grid',\n\tinputs: ['grid'],\n\toutputs: ['select'],\n\tdirectives: [\n\t\tCORE_DIRECTIVES\n\t],\n\tstyles: [\n\t\trequire('./grid.css') // webpack require\n\t],\n\ttemplate: `\n\t<div class=\"grid\">\n <div *ng-for=\"#row of grid; #x=index\" class=\"row\">\n <div *ng-for=\"#tile of row; #y=index\">\n <div class=\"tile\"\n [class.x]=\"tile.isHit==true &&tile.hasShip==false\"\n [class.o]=\"tile.isHit==false\"\n [class.hit]=\"tile.isHit==true && tile.hasShip==true\"\n (click)=\"select.next({x: x, y: y})\">\n </div>\n </div>\n </div>\n </div>\n\t`\n})\n\nexport class Grid {\n\tselect: EventEmitter = new EventEmitter();\n\n\tconstructor() {\n\n\t}\n\n\tonChange() {\n\t\tconsole.log('change')\n\t}\n}\n" }, { "alpha_fraction": 0.7270408272743225, "alphanum_fraction": 0.7270408272743225, "avg_line_length": 20.72222137451172, "blob_id": "55c885938e831d4d093473211fe07283c92cb742", "content_id": "d2c63cf7d8d625d3b07de09b645af6cc47149525", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 392, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orders/DuplicateNameException.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orders;\n\n@SuppressWarnings(\"serial\")\n/**New checked exception for dish names in menuSet\n * @author Marcin\n *\n */\npublic class DuplicateNameException extends Exception {\n\n\t\n\t/**Constructor for exception\n\t * pass name that can used in getMessege in Exception class\n\t * @param dup\n\t */\n\tpublic DuplicateNameException(String dup){\n\t\tsuper(\"Duplicate dih name = \" + dup);\n\t}\n}\n\n" }, { "alpha_fraction": 0.577328622341156, "alphanum_fraction": 0.577328622341156, "avg_line_length": 26.095237731933594, "blob_id": "e2a2279378c8292f6517595bc249ce8b6751e827", "content_id": "9f2108b89e0ca517d68ecc4990d3dd80a2788ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 72, "num_lines": 42, "path": "/Interviews/jp_morgan/call_billing/src/client/standard_client.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from client import Client\n\n\nclass StandardClient(Client):\n\n \"\"\"StandardClient class inherit from Client\"\"\"\n\n def __init__(self, client_id, call_plan, client_type):\n super(StandardClient, self).__init__(client_id, call_plan)\n self.__client_type = client_type\n\n def call_cost(self, call):\n \"\"\"Calcucalte Cost of call\"\"\"\n try:\n cost = self.per_minute(call.call_type) * call.call_duration\n\n if call.is_international:\n rate = self.call_plan.plan_tariffs['international_rate']\n cost = cost * rate\n\n return cost\n\n except KeyError, e:\n print 'I got a KeyError - reason \"%s\"' % str(e)\n\n def per_minute(self, call_type):\n \"Calculate per minute base cost\"\n try:\n per_minute = self.call_plan.plan_tariffs[call_type]\n\n return per_minute\n\n except KeyError, e:\n print 'I got a KeyError - reason \"%s\"' % str(e)\n\n @property\n def client_type(self):\n return self.__client_type\n\n @client_type.setter\n def call_type(self, value):\n self.__client_type = value\n" }, { "alpha_fraction": 0.6388140320777893, "alphanum_fraction": 0.6431266665458679, "avg_line_length": 26.5230770111084, "blob_id": "13f331af6da7ca7cc788cf4f4b0c4f67b6e7b27f", "content_id": "7f4110f61e4f1747e45eccdd97e6225c8cd50e23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1856, "license_type": "no_license", "max_line_length": 78, "num_lines": 65, "path": "/Java/F21SF Soft E Fundation/4/src/Car.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "MacCentralEurope", "text": "/**\r\n * Software Engineering Foundations\r\n * Car class with owner details\r\n * This class is the first object introduced on the course F21SF\r\n * and is used in various ways to demonstrate some basic programmng principles\r\n * @author monica\r\n */\r\npublic class Car {\r\n\r\n //instance variables\r\n private String model;\t \t\r\n private int tankSize;\r\n private double manfMPG; //manufacturers miles per gallon\r\n private Name ownerName;\r\n //gallons per litre\r\n private static final double GPL = 0.22;\r\n\r\n /** Creates a Car object with values specified in the parameters\r\n * @param model the model of the car\r\n * @param tank the size of the tank in litres\r\n * @param mpg the miles per gallon, as supplied by the manufacturer\r\n * @param owner the name of the owner of the car\r\n */\r\n public Car(String model, int tank, double mpg, Name owner)\r\n { \r\n\tthis.model = model;\r\n\ttankSize = tank;\r\n\tmanfMPG = mpg;\r\n\townerName = owner;\r\n }\r\n \r\n /** returns the name of the model of the car e.g. Ford Ka\r\n * @return the model\r\n */\r\n public String getModel() {\r\n\t return model;\r\n }\r\n \r\n /** returns the name of the owner of the car \r\n * @return the owner's name\r\n */\r\n public Name getOwnerName() {\r\n\t return ownerName; \r\n }\r\n \r\n /** returns the estimated distance car can travel\r\n * on a full tank\r\n * @return the estimated distance\r\n */\r\n public double estimateDistance()\r\n {\r\n\t //there are 0.22 gallons per litre\r\n\t return tankSize * manfMPG * GPL;\r\n }\r\n \r\n /** Determines whether the size of the carís tank\r\n * is bigger than a specified value\r\n * @param size the value that the tank is compared with\r\n * @return true if the tank is bigger\r\n * than the value provided, false otherwise\r\n */\r\n public boolean tankBigger(int size) {\r\n\t return tankSize > size;\r\n }\r\n} \r\n" }, { "alpha_fraction": 0.4860139787197113, "alphanum_fraction": 0.5734265446662903, "avg_line_length": 22.83333396911621, "blob_id": "870b68fbcd9ae784413aa4fed49d22754e092900", "content_id": "ee09a1b6800a76405b3bb07fe6cc9fc92525817c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 73, "num_lines": 12, "path": "/Python/IndustrialProgramming/advanced/iter3.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\ns = sum(i * i for i in range(10))\nprint(\"Sum of squares of 0..9 (expect 285):\", s)\n# expect: 285\n\nxvec = [10, 20, 30]\nyvec = [7, 5, 3]\nz = sum(x * y for x, y in zip(xvec, yvec))\n\nprint(\"Vector product of \", xvec, \" and \", yvec, \" is (expect 260): \", z)\n# expect: 260\n" }, { "alpha_fraction": 0.5775281190872192, "alphanum_fraction": 0.5932584404945374, "avg_line_length": 24.176469802856445, "blob_id": "f1c84fde820063b80fe7554e8e8472aa065072f5", "content_id": "29d9eff27f037478ba2e96aa2e10877067ef5916", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 445, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/Java/F21AS Advanced Software Engineering/Week 7 Threads II/src/Sync/Consumer.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\r\npublic class Consumer implements Runnable {\r\n private SharedObject so;\r\n\r\n public Consumer (SharedObject so) {this.so = so;}\r\n\r\n //version 1, 8 times, sleeps then gets the number\r\n //doesn't do anything with it (a very small example)\r\n public void run() {\r\n for (int i = 0; i < 8; i++) {\r\n\t\t//sleep first\r\n try { Thread.sleep(100); }\r\n catch (InterruptedException e) {}\r\n //get the number\r\n so.get(); \r\n }\r\n }\r\n}" }, { "alpha_fraction": 0.5169811248779297, "alphanum_fraction": 0.5584905743598938, "avg_line_length": 16.600000381469727, "blob_id": "270592eb511e7cb99f2cc44494c34a0f982e0c15", "content_id": "714ab65d1b851f6402cead8e6e2f705c74f3b0f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 265, "license_type": "no_license", "max_line_length": 44, "num_lines": 15, "path": "/Python/IndustrialProgramming/basics/fib (1).py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\ndef fibs(n):\n \"\"\"Return the Fibonacci series up to n.\"\"\"\n result = []\n a, b = 0, 1\n while b < n:\n result.append(b)\n # see below\n a, b = b, a+b\n return result\n\n# body\nf100 = fibs(100) # call it\nprint(f100) # write the result\n\n" }, { "alpha_fraction": 0.5800410509109497, "alphanum_fraction": 0.5982555150985718, "avg_line_length": 32.033897399902344, "blob_id": "46573c6273355f739c9dffafd8853d651c93efca", "content_id": "c5892c6f0af7176191a4cac69c0a3b192eefc39a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3898, "license_type": "no_license", "max_line_length": 117, "num_lines": 118, "path": "/Python/IndustrialProgramming/coursework/app/cw2", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nfrom classes.book_data import BookData\nfrom classes.book_analysis import BookAnalysis\nfrom classes.browser_analysis import BrowserAnalysis\nfrom classes.user_analysis import UserAnalysis\nimport sys\nimport getopt\n\n\nbd = BookData('data/issuu_full.json')\ndt = bd.build_data_frame()\n\n\ndef task_2(uuid):\n \"\"\"Perform task from task 3 \"\"\"\n bs = BookAnalysis(dt)\n try:\n # By Countries\n result_countries = bs.counries_by_book(uuid)\n print(\"Views by country and Document UUID\")\n print(result_countries)\n bs.counries_by_book_plot(result_countries, uuid)\n # By Continent\n print(\"Views by continet and Document UUID\")\n result_continent = bs.continent_by_book(result_countries, uuid)\n bs.continet_by_book_plot(result_continent, uuid)\n print(result_continent)\n except Exception, err:\n print(str(err))\n\n\ndef task_3():\n \"\"\"Perform task from task 3 \"\"\"\n ba = BrowserAnalysis(dt)\n try:\n ba.browser_usage_plot()\n ba.general_usage_plot()\n except Exception, err:\n print(str(err))\n\n\ndef task_4(number):\n \"\"\"Perform task from task 4 \"\"\"\n ra = UserAnalysis(dt)\n try:\n readers_data = ra.best_readers_data(number)\n print(readers_data)\n except Exception, err:\n print(str(err))\n\n\ndef task_5(user_uuid, book_uuid):\n ra = UserAnalysis(dt)\n try:\n user_books_alike = ra.user_visitors_alike(user_uuid)\n print(\"Similar users based on common book\")\n print(user_books_alike)\n user_book_alike_sorted = ra.users_alike_sorted(user_uuid, ra.sorter)\n print(\"Similar users sorted by readership\")\n print(user_book_alike_sorted)\n\n visitors_books_alike = ra.book_visitors_alike(book_uuid)\n print(\"Similar books based on user reader\")\n print(visitors_books_alike)\n book_alike_sorted = ra.book_alike_sorted(book_uuid, ra.sorter)\n print(\"Sorted books alike by readership\")\n print(book_alike_sorted)\n except Exception, err:\n print(str(err))\n\n\ndef main(argv):\n user_uuid = ''\n doc_uuid = ''\n task_id = 0\n try:\n opts, args = getopt.getopt(argv, \"hu:d:t:\", [\"user_uuid=\", \"doc_uuid=\", \"task_id=\"])\n except getopt.GetoptError:\n print 'cw2 -u <user_uuid> -d <doc_uuid> -t <task_id>'\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print 'cw2.py -u <user_uuid> -d <doc_uuid> -t <task_id>'\n sys.exit()\n elif opt in (\"-u\", \"--user_uuid\"):\n user_uuid = arg\n elif opt in (\"-d\", \"--doc_uuid\"):\n doc_uuid = arg\n elif opt in (\"-t\", \"--task_id\"):\n task_id = arg\n if(int(task_id) == 1):\n with open(\"../requirements.txt\", 'r') as fin:\n print(\"Requirments.txt file content\")\n print fin.read()\n if(int(task_id) == 2):\n if(doc_uuid == ''):\n print(\" No doc_uuid supplied\")\n else:\n task_2(doc_uuid)\n print(\"Histograms for per country beed saved in : static/results/countries_to_book_UUID.png\")\n print(\"Histograms for per continent beed saved in : static/results/continent_to_book_UUI.png\")\n elif(int(task_id) == 3):\n task_3()\n print(\"Histograms of browser usage has been seaved in 'static/results/simple_browser_usage.png' \")\n print(\"Histograms of generalised browser usage has been seaved in 'static/results/general_browser_usage.png\")\n elif(int(task_id) == 4):\n print(\"Data of 10 most active readers\")\n task_4(10)\n elif(int(task_id) == 5):\n if((user_uuid == '') | (doc_uuid == '')):\n print(\"Provide user_uuid or/and doc_uuid\")\n # 938601f24509a9f1 , 110727005030-000000009cca70787e5fba1fda005c85\n else:\n task_5(user_uuid, doc_uuid)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" }, { "alpha_fraction": 0.53751540184021, "alphanum_fraction": 0.554735541343689, "avg_line_length": 20.394737243652344, "blob_id": "4cf870c73cf9a42bac7e29f16970ffd74b69605b", "content_id": "a4ee2690b7086f4945ecf262b7632a03341b2fa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 813, "license_type": "no_license", "max_line_length": 67, "num_lines": 38, "path": "/CSharp/code-examples/thearding/threads0.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Lecture 7: Threading\n\nusing System.Threading;\nusing System;\n\nnamespace Threads0 {\n class Tester {\n static void Main () {\n Tester t = new Tester();\n t.DoTest();\n }\n\n private int x = 5;\n private int y = 7;\n // could use this field to narrow down the scope of the lock\n // object swapLock = new { };\n\n public void DoTest() {\n Thread t1 = new Thread( new ThreadStart(Swap));\n Thread t2 = new Thread( new ThreadStart(Swap));\n\n t1.Start();\n t2.Start();\n t1.Join();\n t2.Join();\n }\n\n public void Swap() {\n lock (this) { // or: this.swapLock\n\tConsole.WriteLine(\"Swap enter: x = {0}, y = {1}\", this.x, this.y);\n\tint z = this.x;\n\tthis.x = this.y;\n\tthis.y = z;\n\tConsole.WriteLine(\"Swap leave: x = {0}, y = {1}\", this.x, this.y);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.47435450553894043, "alphanum_fraction": 0.47435450553894043, "avg_line_length": 30.668508529663086, "blob_id": "81fb38f176d7d20b5b51c4f039d1197e021e2c83", "content_id": "ca45aa51b09642c71eec6fbcff233ce8f5d4b487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5734, "license_type": "no_license", "max_line_length": 118, "num_lines": 181, "path": "/CSharp/coursework/WebBrowser-OuterSpace/Project/WebBrowser-OuterSpace/models/WebDocumenTab.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "using System;\nusing System.Text;\nusing System.Net;\nusing System.IO;\nusing System.Threading;\n\nnamespace WebBrowser_OuterSpace.models\n{\n /// <summary>\n /// This calss will represent a single HTML document\n /// Also hold response code and error messeges\n /// </summary>\n class WebDocumenTab\n {\n /// <summary>\n /// I share minimal access because of threading\n /// </summary>\n private String urlAddress;\n private String webDocument;\n private HttpStatusCode httpResponseCode;\n private String errorMessage;\n\n private Boolean documentReady = false;\n private Object thisLock = new Object();\n\n public WebDocumenTab(String urlAddress)\n {\n this.urlAddress = urlAddress;\n }\n\n /// <summary>\n /// This function fetch a document from Web , it is used as thread\n /// Locks because of shared web document\n /// </summary>\n public void fetchWebDocument()\n {\n lock (thisLock) \n {\n documentReady = false;\n errorMessage = \"\";\n webDocument = \"\";\n try\n {\n\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n httpResponseCode = response.StatusCode;\n\n if (httpResponseCode == HttpStatusCode.OK)\n {\n Stream receiveStream = response.GetResponseStream();\n StreamReader readStream = null;\n if (response.CharacterSet == null)\n readStream = new StreamReader(receiveStream);\n else\n readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));\n webDocument = readStream.ReadToEnd();\n response.Close();\n readStream.Close();\n\n documentReady = true;\n }\n\n }\n catch (ProtocolViolationException e)\n {\n errorMessage = e.Message;\n }\n catch (NotSupportedException e)\n {\n errorMessage = e.Message;\n }\n catch (WebException e)\n {\n if (e.Status == WebExceptionStatus.ProtocolError)\n {\n httpResponseCode = ((HttpWebResponse)e.Response).StatusCode;\n\n }\n else\n {\n errorMessage = e.Message;\n }\n \n }\n catch (NullReferenceException e)\n {\n errorMessage = e.Message;\n }\n catch (InvalidOperationException e)\n {\n errorMessage = e.Message;\n }\n catch (UriFormatException e)\n {\n errorMessage = e.Message;\n }\n catch (SystemException e)\n {\n errorMessage = e.Message;\n }\n }\n }\n\n /// <summary>\n /// Start and end new threads that will fetch web documents\n /// </summary>\n public void runFetchThread()\n {\n Thread mainThread = Thread.CurrentThread;\n Thread newFetch = new Thread(fetchWebDocument);\n newFetch.Start();\n newFetch.Join();\n }\n\n /// <summary>\n /// Get response code or error messege from exceptions\n /// </summary>\n /// <returns></returns>\n public String getResponseMessage()\n {\n if (!String.IsNullOrEmpty(errorMessage))\n {\n return errorMessage;\n }\n return \"HTTP Code: \" + ((int)httpResponseCode).ToString() + \" \" + httpResponseCode.ToString();\n }\n\n /// <summary>\n /// Getter for webDocument with extra safety\n /// </summary>\n /// <returns></returns>\n public String getWebDocument()\n {\n if (!String.IsNullOrEmpty(webDocument))\n {\n return webDocument;\n }\n\n return \"No Ducument has been fetched\";\n }\n\n /// <summary>\n /// If url is diffrent or document is not there it will make a new request\n /// </summary>\n /// <param name=\"url\"></param>\n /// <returns></returns>\n public String[] makeRequest(String url)\n {\n if (urlAddress != url || documentReady == false)\n {\n this.urlAddress = url;\n this.runFetchThread();\n\n }\n String[] result = new string[] { getResponseMessage(), getWebDocument() };\n return result;\n }\n\n\n /// <summary>\n /// Get Ready document, this is used when moving bewteeen tabs without changing URl \n /// </summary>\n /// <returns></returns>\n public String[] retrieveDocument()\n {\n if (this.documentReady)\n {\n String[] result = new string[] { getResponseMessage(), getWebDocument(), this.urlAddress };\n return result;\n }\n else\n {\n this.runFetchThread();\n String[] result = new string[] { getResponseMessage(), getWebDocument(), this.urlAddress };\n return result;\n }\n\n }\n }\n}\n" }, { "alpha_fraction": 0.5683229565620422, "alphanum_fraction": 0.5962733030319214, "avg_line_length": 19, "blob_id": "7fcf678f81302eda116e8d6e205e91da01ed5200", "content_id": "8a4f0590ecc2dbffb1a18211114dd0fbdb03885d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 322, "license_type": "no_license", "max_line_length": 58, "num_lines": 16, "path": "/Python/CodingTests/Strings/string_score.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\nstring_1 = \"abcdfcba\"\nstring_2 = \"abhaa\"\n\n\ndef string_score(string):\n score = 0\n len_str = len(string)\n for index in range(0, len_str / 2):\n if string[index] is string[len_str - (index + 1)]:\n score = score + 1\n\n return score\n\n\n# print(string_score(string_1))\nprint(string_score(string_2))\n" }, { "alpha_fraction": 0.5941780805587769, "alphanum_fraction": 0.6472602486610413, "avg_line_length": 15.696969985961914, "blob_id": "dc2bb2c59304d050dcf120127d00a6c0ae45ffde", "content_id": "a190b0ef2f1716adb7e9e9b1b2704fccf69e0caf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 584, "license_type": "no_license", "max_line_length": 55, "num_lines": 33, "path": "/Java/F21AS Advanced Software Engineering/Week 3 JTest/src/tests/TestMyDateListTest.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package tests;\r\n\r\nimport dateUtils.*;\r\nimport static org.junit.Assert.*;\r\n\r\nimport org.junit.*;\r\n\r\n\r\npublic class TestMyDateListTest {\r\n\t\r\n\tprivate DateList dateList;\r\n\t\r\n\t@Before\r\n\tpublic void setUp() {\r\n\t\tdateList = new DateList();\r\n\t\tdateList.add(new MyDate(31,12,2009));\r\n\t\tdateList.add(new MyDate(31,1,2009));\r\n\t\tdateList.add(new MyDate(30,12,2009));\r\n\t\tdateList.add(new MyDate(31,12,2004));\r\n\t}\r\n\t\r\n\t//not strictly necessary since setUp starts a new list\r\n\t@After\r\n\tpublic void tearDown() {\r\n\t\tdateList = new DateList();\r\n\t}\r\n\t\r\n\t@Test\r\n\tpublic void testFind() {\r\n\t\t\r\n\t} \r\n\r\n}\r\n" }, { "alpha_fraction": 0.6064516305923462, "alphanum_fraction": 0.6096774339675903, "avg_line_length": 24.66666603088379, "blob_id": "64885e59d085948d163b7aa3f0e476f526a96168", "content_id": "9f61748a1579ddb9162737b28cb2d9b8b9b9057e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 56, "num_lines": 12, "path": "/Interviews/jp_morgan/call_billing/src/billing/client_billing.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "\n\nclass ClientBilling(object):\n\n \"\"\"ClientBilling class, work with billings \"\"\"\n\n def make_billing(self, client, call_history):\n \"\"\"Make billiong for client with call history\"\"\"\n total = 0\n\n for call in call_history:\n total += client.call_cost(call)\n\n return total\n" }, { "alpha_fraction": 0.6496894359588623, "alphanum_fraction": 0.6496894359588623, "avg_line_length": 26.79310417175293, "blob_id": "20a9455268275eae6497d9f866ec922a253c6ea7", "content_id": "9492c6fa51e89ea81bb8d71015a8b2fe6f150590", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 805, "license_type": "no_license", "max_line_length": 62, "num_lines": 29, "path": "/Java/F21AS Advanced Software Engineering/Week 6 Observer Pattern/src/ClockExample.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "public class ClockExample\n{\n public static void main(String[] args)\n {\n \t//create clock to keep time\n \tClock clock = new Clock();\n \t\n \t//create digital clock display\n \tDigitalDisplay dd = new DigitalDisplay(clock);\n \t//create a graphic clock displays\n \tAnalogDisplay ad = new AnalogDisplay(clock);\n \t\n \t//create a display for the clocks\n \tClockDisplayGUI display = new ClockDisplayGUI(); \n \t//add all the display clock panels\n \tdisplay.addCenter(ad);\n \tdisplay.addSouth(dd);\n \t\n \t//create counter\n \tCounter counter = new Counter (clock);\n \t\n \t//create gui to allow user to set the time\n \tSetClockGUI setTime = new SetClockGUI(clock);\n \tsetTime.setVisible(true);\n \t\n \t//now program just waits for user to use the SetClockGUI \n }\n \n}" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.5684874057769775, "avg_line_length": 30.108108520507812, "blob_id": "b14bb3c22c7076e3b1acdb1527b9289b9c1d45b0", "content_id": "7539c8bfc881630a8e5821ef16d50a6446ef6e05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2384, "license_type": "no_license", "max_line_length": 77, "num_lines": 74, "path": "/Java/F21AS Advanced Software Engineering/Week 2 Collections/src/DemoiSet1.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "WINDOWS-1252", "text": "/**\r\n * F21AS Collections\r\n * Demonstrates adding words (Strings) to a HashSet\r\n * Then using a treeset to order them\r\n * \r\n * Then creating a HashSet of PersonTel objects\r\n * Printing all the names\r\n * Printing names and hashcodes\r\n * Creates and prints an ordered list of landlines with duplicates eliminated\r\n * @author monica\r\n *\r\n */\r\nimport java.util.*;\r\npublic class DemoiSet1 {\r\n\r\n\tpublic static void main(String[] args) {\r\n\r\n\t\t//instantiate a HashSet with a String key \r\n\t\tSet<String> s = new HashSet<String>(); \r\n\t\t//for each word (argument), add and check\r\n\t\tfor (String a : args) {\r\n\t\t\tif (!s.add(a)) {\t//add and check if fails \r\n\t\t\t\tSystem.out.println(\"Duplicate found: \" + a); \r\n\t\t\t}\r\n\t\t}\r\n\t\t//use size() to find out how many words in the set\r\n\t\t//printing ‘s’ invokes the toString method \r\n\t\t// which prints out the set\r\n\t\tSystem.out.println(s.size() + \" distinct words: \" \r\n\t\t\t\t+ s); \r\n\t\t\r\n\t\t//convert to tree to order\r\n\t\tTreeSet<String> t = new TreeSet<String> (s);\r\n\t\tSystem.out.println(t);\r\n\t\t//////////////////////////////////////////////////////////////////\r\n\t\t/////////////////////////////////////////////////////////////////\r\n\t\t\r\n\t\t//add PersonTel objects to a set\r\n\t\tPersonTel pt1 = new PersonTel(\"Tim\", \"411-0914\", \"077871234\");\r\n\t\tPersonTel pt2 = new PersonTel(\"Jo\", \"411-0210\", \"077871234\");\r\n\t\tPersonTel pt3 = new PersonTel(\"Jack\", \"131-9873\", \"077871234\");\r\n\t\tPersonTel pt4 = new PersonTel(\"Ann\", \"411-0210\", \"077871234\");\r\n\t\tPersonTel pt5 = new PersonTel(\"Ann\", \"411-0210\", \"077871234\");\r\n\t\tHashSet <PersonTel> phonebook = new HashSet<PersonTel> ();\r\n\t\tphonebook.add(pt1); \r\n\t\tphonebook.add(pt2);\r\n\t\tphonebook.add(pt3);\r\n\t\tphonebook.add(pt4);\r\n\t\tphonebook.add(pt5);\t\r\n\t\r\n\t\t//print names\r\n\t\tfor (PersonTel pt : phonebook) {\r\n\t\t\tSystem.out.println(pt.getName()); //nb only one ann\r\n\t\t}\r\n\t\t\r\n\t\t//////////////////////////////////////////////////////////\r\n\t\t//print names and hashcode\r\n\t\tfor (PersonTel pt : phonebook) { //order not reliable!!\r\n\t\t\tSystem.out.println(pt.getName() + pt.hashCode());\r\n\t\t}\r\n\t\t\r\n\t\t//////////////////////////////////////////////////////////\r\n\t\t//produce a sorted unique ordered list of landlines\r\n\t\tTreeSet<String> landlines = new TreeSet<String> ();\r\n\t\tfor (PersonTel pt : phonebook) {\r\n\t\t\tlandlines.add(pt.getLandline());\r\n\t\t}\r\n\t\tfor (String phone :landlines) {\r\n\t\t\tSystem.out.println(phone);\r\n\t\t}\r\n\t} \r\n\r\n\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.4175198972225189, "alphanum_fraction": 0.447098970413208, "avg_line_length": 21.538461685180664, "blob_id": "18da98eeec8868bb1666d935f81afd14b21650a4", "content_id": "b21ff92a13674a04d1508cbad0b98e6e982dddf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 63, "num_lines": 39, "path": "/Python/CodingTests/Arrays and Sorting/insert_sort_1.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# N = int(input())\n# items = input().split()\nimport sys\n\nN = 10\nitems = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '1']\n\n\nitems = [int(x) for x in items]\n\n\ndef insert_sort(items):\n v = items[-1]\n items = items[:-1]\n ar = [x for x in items]\n ar.append(0)\n\n for i in range(1, len(items) + 2):\n if i != len(items) + 1 and ar[-(i + 1)] > v:\n ar[-i] = ar[-(i + 1)]\n printlist(ar)\n else:\n ar[-i] = v\n printlist(ar)\n break\n\n\ndef printlist(list):\n sys.stdout.write(\" \".join(str(x) for x in list))\n sys.stdout.write('\\n')\n\ninsert_sort(items)\n\n# j = i\n# while j > 0 and items[j - 1] > items[j]:\n# items[j - 1], items[j] = items[j], items[j - 1]\n# sys.stdout.write(\" \".join(str(x) for x in items))\n# sys.stdout.write('\\n')\n# j -= 1\n" }, { "alpha_fraction": 0.3316519558429718, "alphanum_fraction": 0.34047919511795044, "avg_line_length": 21.02777862548828, "blob_id": "dad834e0de13bdb6eb9a22e7f48b2a6ffc54af8c", "content_id": "e8ff78a2275bbc3b45622920f29ce92a0aae861b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1586, "license_type": "no_license", "max_line_length": 65, "num_lines": 72, "path": "/Interviews/amazon/bin_tree_aplitude.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "class BinTree:\n x = 0\n l = None\n r = None\n\n def __init__(self, x, l, r):\n self.x = x\n self.l = l\n self.r = r\n\n\nT = BinTree(5,\n BinTree(8,\n BinTree(12,\n BinTree(1,\n None,\n None),\n None),\n BinTree(6,\n None,\n None),\n ),\n BinTree(9,\n BinTree(7,\n BinTree(2,\n None,\n None),\n None),\n BinTree(4,\n None,\n BinTree(3,\n None,\n None)\n\n )\n )\n )\n\nTNone = BinTree(0, None, None)\n\n\ndef solution(T):\n max_amplitude = 0\n paths = get_paths(T)\n\n for path in paths:\n amplitude = max(path) - min(path)\n\n if max_amplitude < amplitude:\n max_amplitude = amplitude\n\n return max_amplitude\n pass\n\n\ndef get_paths(T):\n paths = []\n\n if not (T.l or T.r):\n return [[T.x]]\n if T.l:\n paths.extend([[T.x] + child for child in get_paths(T.l)])\n if T.r:\n paths.extend([[T.x] + child for child in get_paths(T.r)])\n return paths\n\n\nprint(solution(T))\nprint(get_paths(T))\n\nprint(solution(TNone))\nprint(get_paths(TNone))\n" }, { "alpha_fraction": 0.6329966187477112, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 19.214284896850586, "blob_id": "542704b02abca9b4839c50a042068e1e1b2d2b76", "content_id": "8e2c296730a3fcac059247a022c8676babf4a452", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 297, "license_type": "no_license", "max_line_length": 63, "num_lines": 14, "path": "/Java/F21SF Soft E Fundation/2/src/First.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/**\r\n * Software Engineering Foundations\r\n * A first program\r\n * Run it, then try altering the text, printing 2 messages, etc\r\n * @author monica\r\n *\r\n */\r\npublic class First {\r\n\tpublic static void main (String [] args){\r\n\t\tString name = \"Monica\";\r\n\t\tSystem.out.println(\"Hello \" + name);\r\n\t}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6002647280693054, "alphanum_fraction": 0.6161482334136963, "avg_line_length": 25.526315689086914, "blob_id": "8247bb7a65b53ab62a33cba598e667ba99e51056", "content_id": "ac01003713f451635fb3c0fc08e42898045f975d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 132, "num_lines": 57, "path": "/CSharp/code-examples/basics/min3.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "MacCentralEurope", "text": "// Example on nullable types\n// Object-oriented Programming in C# for C and Java programmers\n// Kurt NÝrmark ©\n// Department of Computer Science, Aalborg University, Denmark\n// Sec 14.9\n// http://www.cs.aau.dk/~normark/oop-csharp/html/notes/more-classes_themes-value-types-sect.html#more-classes_nullable-types_title_1\n\nusing System;\n\n// Program 14.18 An integer sequence with Min and Max operations - with int?. \t\n// modified for non o-o sequences to use it as example before classes\n\nclass IntSequenceClient{\n\n public static int? Min(int[] sequence){\n int theMinimum;\n if (sequence.Length == 0)\n return null;\n else {\n theMinimum = sequence[0];\n foreach(int e in sequence) \n if (e < theMinimum)\n theMinimum = e;\n }\n return theMinimum;\n }\n\n public static int? Max(int[] sequence){\n int theMaximum;\n if (sequence.Length == 0)\n return null;\n else {\n theMaximum = sequence[0];\n foreach(int e in sequence) \n if (e > theMaximum)\n theMaximum = e;\n }\n return theMaximum;\n }\n\n public static void ReportMinMax(int[] sequence){\n if (Min(sequence).HasValue && Max(sequence).HasValue)\n Console.WriteLine(\"Min: {0}. Max: {1}\", \n Min(sequence), Max(sequence));\n else\n Console.WriteLine(\"Int sequence is empty\");\n }\n\n public static void Main(){\n int[] is1 = new int[] { -5, -1, 7, -8, 13};\n int[] is2 = new int[] { };\n\n ReportMinMax(is1);\n ReportMinMax(is2); \n }\n\n}" }, { "alpha_fraction": 0.5869786143302917, "alphanum_fraction": 0.6154628396034241, "avg_line_length": 22.35714340209961, "blob_id": "fa4dc4fbf09a293c59d4e4c2f8cfa440908956ff", "content_id": "99c15430aa4e01e52e13aceeba0a196d942b2c97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 983, "license_type": "no_license", "max_line_length": 95, "num_lines": 42, "path": "/Python/Excercises/generators_prime.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "from math import sqrt\n\n# https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/\n\n\ndef get_primes(input_list):\n result_list = list()\n for element in input_list:\n if is_prime(element):\n result_list.append()\n\n return result_list\n\n# or better yet...\n\n\ndef get_primes_comp(input_list):\n return (element for element in input_list if is_prime(element))\n\n# not germane to the example, but here's a possible implementation of\n# is_prime...\n\n\ndef is_prime(number):\n if number > 1:\n if number == 2:\n return True\n if number % 2 == 0:\n return False\n for current in range(3, int(sqrt(number) + 1), 2):\n if number % current == 0:\n return False\n return True\n return False\n\n\nnoprimes = [j for i in range(2, 8) for j in range(i * 2, 100, i)]\nprimes = [x for x in range(2, 100) if x not in noprimes]\n\nprint(noprimes)\nprint(primes)\nprint(range(2,5))\n\n\n" }, { "alpha_fraction": 0.7005163431167603, "alphanum_fraction": 0.7022375464439392, "avg_line_length": 22.76595687866211, "blob_id": "ccae2144e12fc19ea0b34470805c40f71bfb4f01", "content_id": "f1f25c98977808c58ad771b0e33ab2b9bd02661a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 65, "num_lines": 47, "path": "/Java/F21AS Advanced Software Engineering/Assignment 1 Stage 1/src/restaurant/orders/GrandTotalGUI.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package restaurant.orders;\r\n\r\nimport java.awt.BorderLayout;\r\nimport java.awt.Font;\r\n\r\nimport javax.swing.JFrame;\r\nimport javax.swing.JPanel;\r\nimport javax.swing.JTextArea;\r\n\r\n/**This GUI shows the summary of selected table from a user input\r\n * @author Kamontorn Khamrun\r\n *\r\n */\r\n@SuppressWarnings(\"serial\")\r\npublic class GrandTotalGUI extends JFrame\r\n{\r\n\tprivate String singleTableSummary;\r\n\tprivate JTextArea tableReport;\r\n\r\n\r\n\t/**Set up the GUI to show a report of selected table \r\n\t * @param tableSummary the report of the table\r\n\t */\r\n\tpublic GrandTotalGUI(String tableSummary) \r\n\t{\r\n\t\tthis.singleTableSummary = tableSummary;\r\n\t\tsetTitle(\"Bill\");\r\n\t\tsetupNorthPanel();\r\n pack();\r\n setVisible(true);\r\n setDefaultCloseOperation(EXIT_ON_CLOSE);\r\n\t}\r\n\r\n\t/**\r\n\t * Set up the north panel to contain a report \r\n\t */\r\n\tpublic void setupNorthPanel() \r\n\t{\r\n\t\tJPanel northPanel = new JPanel();\r\n\t\ttableReport = new JTextArea();\r\n\t\ttableReport.setFont(new Font (Font.MONOSPACED, Font.PLAIN,14));\r\n\t\ttableReport.setEditable(false);\r\n\t\tnorthPanel.add(tableReport);\r\n\t\ttableReport.setText(singleTableSummary);\r\n\t\tthis.add(northPanel, BorderLayout.NORTH);\r\n\t}\r\n}" }, { "alpha_fraction": 0.617691159248352, "alphanum_fraction": 0.6404797434806824, "avg_line_length": 27.495725631713867, "blob_id": "a5176acfa87a3cc8f56d05993775e2b6cd7bc65d", "content_id": "950df25b5638ed183c983ca4733acbb329f70adf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 3335, "license_type": "no_license", "max_line_length": 107, "num_lines": 117, "path": "/CSharp/code-examples/sys-programming/LinkedList.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Based on on-line code at:\n// http://forums.asp.net/p/375039/377882.aspx#377882\n// low-level use of references in C#\n\nusing System;\n \npublic class LinkedListNode {\n LinkedListNode next;\n LinkedListNode prev;\n private int data;\n\n public int MyData() { // {get{...}set{...}}\n return this.data;\n }\n\n public void Insert(LinkedListNode node) {\n LinkedListNode nextNode = this.next;\n this.next = node;\n node.prev = this;\n node.next = nextNode;\n if (nextNode != null) { // pitfall\n nextNode.prev = node;\n }\n }\n\n public void RemoveBuggy() {\n // beware: this.prev and this.next must not be null\n this.prev.next = next;\n this.next.prev = prev;\n\n //note the nulls are put here to insure stability incase someone has a reference to this node,\n //it'll let the other linked nodes die and keep the user from skipping into a node that is no\n //longer the \"next\" node.\n this.next = null;\n this.prev = null;\n }\n\n public void Remove() {\n if (this.prev != null) { this.prev.next = next; }\n if (this.next != null) { this.next.prev = prev; }\n\n //note the nulls are put here to insure stability incase someone has a reference to this node,\n //it'll let the other linked nodes die and keep the user from skipping into a node that is no\n //longer the \"next\" node.\n this.next = null;\n this.prev = null;\n }\n\n public void ShowList () {\n Console.WriteLine(\"{0} \",this.MyData());\n if (this.next == null) {\n return; \n } else {\n this.next.ShowList();\n }\n }\n\n public void ShowListReverse () {\n Console.WriteLine(\"{0} \",this.MyData());\n if (this.prev == null) {\n return; \n } else {\n this.prev.ShowListReverse();\n }\n }\n\n public LinkedListNode GetNext() {\n return next;\n }\n\n public LinkedListNode (int data) {\n this.data = data;\n // init references\n this.next = null;\n this.prev = null;\n }\n}\n\npublic class Tester {\n public static void Main() {\n LinkedListNode n1 = new LinkedListNode(1);\n Console.WriteLine(\"Expect a 1 element list with 1...\");\n n1.ShowList();\n // adding 3 at the end\n LinkedListNode n3 = new LinkedListNode(3);\n n1.Insert(n3);\n Console.WriteLine(\"Inserting 3 after 1 ...\");\n Console.WriteLine(\"Expect a 2 element list with 1 3 ...\");\n n1.ShowList();\n Console.WriteLine(\"Testing showListReverse; expect a 2 element list with 3 1 ...\");\n n3.ShowListReverse();\n // adding 2 btw 1 and 2\n LinkedListNode n2 = new LinkedListNode(2);\n n1.Insert(n2); \n Console.WriteLine(\"Inserting 2 after 1 ...\");\n Console.WriteLine(\"Expect a 3 element list with 1 2 3 ...\");\n n1.ShowList();\n Console.WriteLine(\"Testing showListReverse; expect a 3 element list with 3 2 1 ...\");\n n3.ShowListReverse();\n // removing a node\n n2.Remove(); \n Console.WriteLine(\"Removing 2 ...\");\n Console.WriteLine(\"Expect a 2 element list with 1 3 ...\");\n n1.ShowList();\n Console.WriteLine(\"Testing showListReverse; expect a 2 element list with 3 1 ...\");\n n3.ShowListReverse();\n try {\n n3.RemoveBuggy(); \n } catch (NullReferenceException e) {\n Console.WriteLine(\"RemoveBuggy didn't check for null pointer, hence this exception: {0}\", e.Message);\n }\n n3.Remove(); \n Console.WriteLine(\"Removing 3 ...\");\n Console.WriteLine(\"Expect a 1 element list with 1 ... \");\n n1.ShowList();\n }\n}\n\n" }, { "alpha_fraction": 0.596345841884613, "alphanum_fraction": 0.6118546724319458, "avg_line_length": 25.85207176208496, "blob_id": "768dbe6e32073c492b3ebd5dc07c3ed44cf51e9c", "content_id": "1998721706705c0292b78e147e78b4a28b7d33bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4707, "license_type": "no_license", "max_line_length": 73, "num_lines": 169, "path": "/Java/F21SF Soft E Fundation/8/src/StudentList.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import java.util.ArrayList;\r\n//demonstrates using an ArrayList\r\npublic class StudentList {\r\n\t//holds a list of Student objects\r\n\tprivate ArrayList<Student> studentList;\r\n\t\r\n\t//create an empty arraylist\r\n\tpublic StudentList() {\r\n\t\tstudentList = new ArrayList<Student> ();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Adds student to the list, if there is not already one there \r\n\t * with the same ID\r\n\t * @param s the Student to be added\r\n\t * @return true if student was added to the list, false if already there\r\n\t */\r\n\tpublic boolean addOneStudent(Student s) {\r\n\t\t//gets id of student to be added\r\n\t\tString id = s.getId();\r\n\t\t//see if student with this id is already in the list\r\n\t\tStudent inList = this.findById(id);\r\n\t\t//add the student if they are not in the list, and return true\r\n\t\tif (inList == null) {\r\n\t\t\tstudentList.add(s);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t//return false if not in the list\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t//populate the array list\r\n\tpublic void populate() {\r\n\t\tString [] quals1 = {\"MIC\", \"ARA\" };\r\n\t\tStudent s1 = new Student (\"0011\",new Name(\"Helen Scott\"),\r\n\t\t\t\tquals1, 1);\r\n\t\t//an example of checking to see if added successfully\r\n\t\t//(expect this one to be added)\r\n\t\t//(not checked for many other students, assuming correct)\r\n\t\tboolean ok = this.addOneStudent(s1);\r\n\t\tif (!ok) { \r\n\t\t\tSystem.out.println(\"Duplicate entry \" + s1.getId()); \r\n\t\t}\r\n\r\n\t\tString [] quals2 = {\"MIC\", \"FAC1\" };\r\n\t\tStudent s2 = new Student (\"1234\",new Name(\"James Jackson\"),\r\n\t\t\t\tquals2, 1);\r\n\t\tthis.addOneStudent(s2);\r\n\r\n\t\tString [] quals3 = {\"ARA\", \"FAC1\", \"FAC2\" };\r\n\t\tStudent s3 = new Student (\"0267\", new Name(\"Tim Moore\"), \r\n\t\t\t\tquals3, 2);\r\n\t\tthis.addOneStudent(s3);\r\n\r\n\t\tString [] quals4 = {\"ARA\" };\r\n\t\tStudent s4 = new Student (\"1356\",new Name(\"Tom Smith\"), \r\n\t\t\t\tquals4, 2);\r\n\t\tthis.addOneStudent(s4);\r\n\r\n\t\tString [] quals5 = {\"FAC1\", \"JBB\"};\r\n\t\tStudent s5 = new Student (\"9876\",new Name(\"Jo Black\"), \r\n\t\t\t\tquals5, 2);\r\n\t\tthis.addOneStudent(s5);\r\n\r\n\t\tString [] quals6 = {\"FAC1\", \"ARA\" , \"JBB\", \"FAC2\"};\t\r\n\t\tStudent s6 = new Student (\"3434\",new Name(\"Mary Brown\"), \r\n\t\t\t\tquals6, 3);\r\n\t\tthis.addOneStudent(s6);\r\n\t\t//another example of checking to see if added successfully\r\n\t\t//(this one was not added)\r\n\t\tok = this.addOneStudent(s6);\r\n\t\tif (!ok) { \r\n\t\t\tSystem.out.println(\"Duplicate entry \" + s6.getId()); \r\n\t\t}\r\n\t}\r\n\t\r\n\t//returns a report with one line per person\r\n\t//demonstrates traversing the array,\r\n\t//getting one element at a time\r\n\tpublic String getTableOfStudents()\r\n\t{\r\n\t\tString report = \"ID NAME YEAR QUALS\\n\";\r\n\t\tfor (Student s : studentList){\r\n\t\t\treport += String.format(\"%-6s\", s.getId());\r\n\t\t\treport += String.format(\"%-15s\", s.getName().getFullName() );\r\n\t\t\treport += String.format(\"%-6d\", s.getYear());\r\n\t\t\treport += s.getQualDetails();\r\n\t\t\treport += \"\\n\";\r\n\t\t}\r\n\t\treturn report;\r\n\t}\r\n\t\r\n\t//returns the number of elements in the list\r\n\tpublic int getSize() {\r\n\t\treturn studentList.size();\r\n\t}\r\n\t\r\n\t//returns the Staff object at specified index position\r\n\tpublic Student getAtIndex(int index) {\r\n\t\treturn studentList.get(index);\r\n\t}\r\n\t\r\n\t//returns the Staff object with a specified id\r\n\t//demonstrates searching through the array\r\n\t//and stopping by returning when a match is found\r\n public Student findById(String id)\r\n {\r\n \tfor (Student s : studentList)\r\n \t{\r\n \t\tif (s.getId().equals(id))\r\n \t\t{\r\n \t\t\treturn s;\r\n \t\t}\r\n \t}\r\n \treturn null;\r\n }\r\n \r\n //counts the number of people in a specified year\r\n //demonstrates making a count with arraylists\r\n public int getCountOfPeopleAtYear(int year) {\r\n \tint count = 0; //initialise count to 0\r\n \tfor (Student s:studentList) {\r\n \t\tif (s.getYear()==year) {\r\n \t\t\tcount++;\r\n \t\t}\r\n \t}\r\n \treturn count;\r\n }\r\n\t\r\n\r\n\t\r\n\t//works out how many people in each year,\r\n\t//then creates and returns a report\r\n //\r\n //demonstrates calculating a frequency report\r\n //i.e. how often each year occurs\r\n //it uses the value of the year as an index\r\n\tpublic String getYearsFrequencyReport() {\r\n\t\t//work out max year\r\n\t\tint maxYear = getMaxYear();\r\n\t\t//work out how many people at each year\r\n\t\tint [] freqYears = new int [maxYear];\r\n\t\tfor (Student s : studentList) {\r\n\t\t\tint y = s.getYear();\r\n\t\t\tfreqYears[y-1]++;\r\n\t\t}\r\n\t\t//create a report\r\n\t\tString report = \"NUMBER OF STUDENTS IN EACH YEAR\\n\";\r\n\t\tfor (int i = 0; i < freqYears.length; i++) {\r\n\t\t\treport += \"Year \" + (i+1) + \" : \" + freqYears[i] + \"\\n\";\r\n\t\t}\r\n\t\treturn report;\r\n\t}\r\n\t\r\n\t//calculates the maximum year that anyone is in\r\n\t//demonstrates finding a max with array lists\r\n\tpublic int getMaxYear() {\r\n\t\tint maxYear = 0;\r\n\t\tfor (Student s : studentList) {\r\n\t\t\tint yr = s.getYear();\r\n\t\t\tif (yr> maxYear) {\r\n\t\t\t\tmaxYear= yr;\r\n\t\t\t}\r\n\t\t}\t\r\n\t\treturn maxYear;\r\n\t}\r\n\t\r\n\r\n}\r\n" }, { "alpha_fraction": 0.5042345523834229, "alphanum_fraction": 0.5296416878700256, "avg_line_length": 27.425926208496094, "blob_id": "4799bea4e6714ab432ea9dec74ee70ae0c0b3768", "content_id": "a977050645fd2267899bcccb0464f730c6349b6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1535, "license_type": "no_license", "max_line_length": 90, "num_lines": 54, "path": "/CSharp/code-examples/basics/functions.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// Examples from Lecture 3: C# Basics\n\nclass Functions {\n static void Main() {\n int[] arr = {0,1,2,3,4,5,6,7,8,9};\n int x = 0;\n int n = 3;\n int n1 = 5;\n int n2 = 7;\n int n3 = 9;\n System.Console.WriteLine(\"Testing array operations on this array: \" + showArr(arr));\n System.Console.WriteLine(\"Get of {0}-th elemnt = {1}\", n, Get(arr,n));\n System.Console.WriteLine(\"Setting the {0}-th elemnt to {1}\", n1, x);\n Set(arr,n1,x);\n System.Console.WriteLine(\"Modified array: \" + showArr(arr));\n System.Console.WriteLine(\"SetSteping the {0}-th elemnt to {1}\", n2, x);\n SetStepBroken(arr,n2,x);\n System.Console.WriteLine(\"Modified array: \" + showArr(arr));\n System.Console.WriteLine(\"Index = {0}\", n2);\n System.Console.WriteLine(\"SetSteping the {0}-th elemnt to {1}\", n3, x);\n SetStep(arr,ref n3,x);\n System.Console.WriteLine(\"Modified array: \" + showArr(arr));\n System.Console.WriteLine(\"Index = {0}\", n3);\n } \n\n static int Get (int[] arr, int n) {\n return arr[n];\n }\n \n static void Set (int[] arr, int n, int x) {\n arr[n] = x;\n }\n \n static void SetStepBroken (int[] arr, int n, int x) {\n arr[n] = x;\n n +=1 ;\n }\n \n static void SetStep (int[] arr, ref int n, int x) {\n arr[n] = x;\n n +=1 ;\n }\n \n static string showArr(int[] arr) {\n string s = \"\";\n foreach (int i in arr) {\n if (s!=\"\") {\n s += ',';\n }\n s += i.ToString();\n }\n return s;\n }\n}\n" }, { "alpha_fraction": 0.6192052960395813, "alphanum_fraction": 0.6192052960395813, "avg_line_length": 32.55555725097656, "blob_id": "09c1074785ec78819e23c9418af49db0f0e167a1", "content_id": "7591021e222e787833d981c183dbc0793c42c476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 54, "num_lines": 9, "path": "/Python/IndustrialProgramming/advanced/vector5.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "class Vector(object):\n\n def __mul__(self, scalar):\n 'Multiplication with a scalar from the right.'\n return map(lambda x: x * scalar, self.coord)\n\n def __rmul__(self, scalar):\n 'Multiplication with a scalar from the left.'\n return map(lambda x: scalar * x, self.coord)\n" }, { "alpha_fraction": 0.6239316463470459, "alphanum_fraction": 0.6381766200065613, "avg_line_length": 18.5, "blob_id": "1ebf9bb2d9cc6cbbfc338f66e25fb089696dfdae", "content_id": "4fd0cea43e7b47917602667e5153cf614c5becad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/Python/Excercises/reverse_anagrams.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "words = ['dupa', 'mistrze', 'wiesz']\n\n\nanagrams_comp = [x[::-1] for x in words]\nanagrams_lambda = map(lambda x: x[::-1], words)\n\nprint(anagrams_comp)\nprint(anagrams_lambda)\n\n\ndef reverse(text):\n if len(text) <= 1:\n return text\n return reverse(text[1:]) + text[0]\n\n\nanagrams_comp_rev = [reverse(x) for x in words]\nprint(anagrams_comp_rev)\n" }, { "alpha_fraction": 0.5804967880249023, "alphanum_fraction": 0.5869365334510803, "avg_line_length": 20.3137264251709, "blob_id": "99af100652f4fc593891e257c2461814ac3e6b49", "content_id": "e6112a422c89e4484a1349148a50acf3045244b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1087, "license_type": "no_license", "max_line_length": 60, "num_lines": 51, "path": "/Interviews/skyscanner/task_2.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# import sys\nimport itertools\n\n# input_all = []\n\n# for line in sys.stdin:\n# print(line)\n# input_all.append([int(x) for x in line.split()])\n\n\n# n = input_all[0]\n# relations = input_all[1:]\n\n\nn = 6\nrelations = [['Jon', 'Mark'],\n ['Jon', 'David'],\n ['Mark', 'Paul'],\n ['Paul', 'Lee'],\n ['Paul', 'Steve']]\n\nemployees = set(itertools.chain(*relations))\n\n\ndef company_hierarchy(employees, relations, n):\n levels = {}\n\n for person in employees:\n levels[person] = find_level(relations, person, 0)\n return levels\n\n\ndef find_level(relations, person, level):\n person_man = person_manager(person, relations)\n if person_man is not False:\n level = level + find_level(relations, person_man, 1)\n return level\n\n\ndef person_manager(person, relations):\n manager = \"\"\n for relation in relations:\n if person is relation[1]:\n manager = relation[0]\n break\n if manager is not \"\":\n return manager\n else:\n return False\n\nprint(company_hierarchy(employees, relations, n))\n" }, { "alpha_fraction": 0.5547945499420166, "alphanum_fraction": 0.5799086689949036, "avg_line_length": 17.25, "blob_id": "7366592495a785207d3c475cea34d47894d64578", "content_id": "0fa6301952594ce32bf237e86ec2e6d05e2da6a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 438, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/Interviews/metail/permutation_point.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "array = [2, 1, 3, 5, 4]\n\n\ndef solution(A):\n number_of_prefixes = 0\n\n for index in range(0, len(A)):\n\n if is_permutation(index, A[0:index]):\n number_of_prefixes += 1\n\n return number_of_prefixes\n pass\n\n\ndef is_permutation(P, part_list):\n set_range = {x for x in range(1, P + 1)}\n\n if len(set_range.intersection(part_list)) == P:\n return True\n else:\n return False\n\nprint(solution(array))\n" }, { "alpha_fraction": 0.5928473472595215, "alphanum_fraction": 0.6107290387153625, "avg_line_length": 22.45161247253418, "blob_id": "994b573ae9018a2bb4a2f204d5cf958b038a2584", "content_id": "d8d26711e2124c86004473c635d573d041400705", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 727, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/Python/CodeDojo/team_distributor_turbo_beta.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "import random\n\nnumber_teams = 12\nnumber_ngo = 5\nequality_param = 0\ngeneric_choices = [1, 2, 3]\n\n\nngos = [x for x in range(1, number_ngo + 1)]\nteam_choices = [{x : random.sample(ngos, 3)} for x in range(1, number_teams + 1)]\nprint(\"-------------\")\nprint(\"Team choices:\")\nprint(team_choices)\nprint(\"-------------\")\n\ndef distribute(team_choices, ngos, equality_param):\n print(\"Started\")\n allocation = { x : [] for x in ngos }\n popularity_index = {x: 0 for x in ngos}\n\n\n for ngo in ngos:\n for team, team_choice in team_choices.iteritems():\n if ngo in team_choice:\n allocation[ngo].push(team)\n\n print(allocation)\n print(\"finihsed\")\n\n\ndistribute(team_choices, ngos, equality_param)\n" }, { "alpha_fraction": 0.5494253039360046, "alphanum_fraction": 0.5666666626930237, "avg_line_length": 23.521127700805664, "blob_id": "141ec4c367832b24a79dc0373841a942d9b8752c", "content_id": "c51b9c6fdd072dcbb4dfbea636878fbf70c2eb08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1740, "license_type": "no_license", "max_line_length": 105, "num_lines": 71, "path": "/CSharp/code-examples/parallel/ParLoops2.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "/* Sequential verion:\nint n = ...\nfor (int i = 0; i < n; i++)\n{\n // ... \n}\n\nThe parallel version has this signature:\n\nParallel.For(int fromInclusive, \n int toExclusive, \n Action<int> body);\n\n*/\n\nusing System;\nusing System.Threading.Tasks;\n// using Parallel;\n\nclass ParallelLoops {\n\n private static int Fib(int n) {\n if (n==0) { return 1; } \n else if (n==1) { return 1; }\n else {\n int n1 = Fib(n-1);\n int n2 = Fib(n-2);\n return n1+n2;\n }\n }\n\n private int SomeComputation(int i) {\n return Fib(i);\n }\n\n private delegate void WorkerDelegate();\n\n private static void TimeIt(WorkerDelegate worker) {\n DateTime startTime = DateTime.Now;\n DateTime stopTime = DateTime.Now;\n worker();\n TimeSpan duration = stopTime - startTime;\n Console.WriteLine(\"Elapsed time: {0}\", duration.ToString());\n }\n\n public static void Main(string []args) {\n if (args.Length != 3) { // expect 1 arg: value to double\n System.Console.WriteLine(\"Usage: <prg> <k> <m> <n>\");\n System.Console.WriteLine(\"k ... number of cores to use\");\n System.Console.WriteLine(\"m, n ... the range of values to apply Fib to; a good range isP: 35 39\");\n } else { \n int k = Convert.ToInt32(args[0]);\n int m = Convert.ToInt32(args[1]);\n int n = Convert.ToInt32(args[2]);\n int[] fibs = new int[n];\n\n /* Parallel version, using only 2 tasks */\n var options = new ParallelOptions() { MaxDegreeOfParallelism = k};\n TimeIt(() => {\n Parallel.For(m, n, options, i =>\n\t {\n\t fibs[i] = ParallelLoops.Fib(i);\n\t });\n\t });\n for (int j = m; j < n; j++) {\n\t Console.WriteLine(\"Fib({0}) = {1}\", j, fibs[j]);\n }\n\n }\n }\n}" }, { "alpha_fraction": 0.616122841835022, "alphanum_fraction": 0.6199616193771362, "avg_line_length": 21.85087776184082, "blob_id": "c88ea6759af376eaeaf18a3a993d43956d7e1a22", "content_id": "8dab50a4b36a3a86275a441355e6469c06252d9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2605, "license_type": "no_license", "max_line_length": 87, "num_lines": 114, "path": "/Express/serverBasics.js", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "var express = require('express'),\n bodyParser = require('body-parser');\napp = express();\n\n//This is middleware that will act between client and server \napp.use(bodyParser.urlencoded());\n\napp.use(function(req, res, next) {\n console.log(\"custom middleware for each req\");\n next();\n});\n\n\n//Build in midllware of Express\napp.use(express.static('./public'));\napp.get('/route', function(req, res) {\n res.render('route/index.jade', {\n names: names\n });\n});\n\n//Middleware based on named parameters in routes\napp.param('name', function(req,res,next,name){\n\treq.name = name[0].toUpperCase() + name.substring(1);\n\tnext();\n});\napp.get('/name/:name', function(req, res) {\n res.send('Your name is' + req.params.name);\n\n});\n\n\n//Setting confing in Express\n//app.set();\n//For bool options\n//app.enabled();\n//app.disabled();\n\n//getters for options\n//app.get();\n//app.enabled();\n//app.disabled();\n\napp.set('env', 'development'); //process.env.Node_ENV(def undefined)\n//Reverse proxy\napp.enable('trust proxy');\napp.set('jsonp callback name', 'cb');\n\n//Define function that will used when calling JSON.stringify\napp.set('json replacer', function(attr, val) {\n if (attr === 'passwordHash') {\n return undefined;\n } else {\n return val;\n }\n});\n//JSON.stringify({json: json},fn);\napp.get('/user_info', function(req, res) {\n res.json(user); //JSON.stringify\n});\n\n\napp.enable('case sensitive routing'); // /hello /HELLO\napp.enable('strict routing'); // /hello/ /hello\napp.enable('view chache');\n\napp.set('view engine', 'jade'); // There is no need to view extensions we can use index\napp.set('views', 'views'); // Directory for views\n\napp.disable('x-powered-by'); //Header name of server\n\n//My Settings\napp.set('mySetingGowno', 'Gownovalue');\napp.get('mySetingGowno');\n\n//all works for all get, post,put,delete\napp.all('/', function(req, res, next) {\n console.log('From All');\n //next will move next\n next();\n});\n\napp.get('/', function(req, res) {\n res.render('index.jade', {\n title: \"Hello Express\"\n });\n});\n\nvar names = [];\n\nfunction log(req, res, next) {\n console.log(names + \"Mistrzu Marcin\");\n next();\n }\n //Nested callback as long as we use next()\napp.get('/name', function(req, res, next) {\n console.log(names);\n next();\n },\n log,\n function(req, res) {\n res.render('names/index.jade', {\n names: names\n });\n });\n\napp.post('/name', function(req, res) {\n names.push(req.body.name);\n res.redirect('/name');\n});\n\napp.listen(3000, function() {\n console.log(\"Listening on port 3000\");\n})\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.658777117729187, "avg_line_length": 20.954545974731445, "blob_id": "110929e329aa92552aec97a54e531f9682a5dfe9", "content_id": "44aa71a6dba2f0eb508e94167a8633315c0d93b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 507, "license_type": "no_license", "max_line_length": 83, "num_lines": 22, "path": "/Java/F21SF Soft E Fundation/Assignment 2/src/assignment_2/Main.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package assignment_2;\r\n/**Program store information different competitors types: Bowler, Golferm, Soapbox\r\n * \r\n * @authors Marcin Kopacz(mpk31), Stian Dalviken (sd196), Kamontorn Khamrun (kk249)\r\n *\r\n */\r\npublic class Main\r\n{\r\n\r\n\r\n\t/**Main Method where everything starts\r\n\t * Method create CompetitorManager object as cm\r\n\t * Initialize run() method in cm\r\n\t * @param args(currently we don't use any)\r\n\t */\r\n\tpublic static void main(String[] args) \r\n\t{\r\n\t\tCompetitionManager cm = new CompetitionManager();\r\n\t\tcm.run();\r\n\r\n\t}\r\n}\r\n\r\n" }, { "alpha_fraction": 0.4929378628730774, "alphanum_fraction": 0.5254237055778503, "avg_line_length": 19.823530197143555, "blob_id": "a794997afdbc1b64c83288c79febc84b15767bf7", "content_id": "e9c340bbfe0d197c1c4b3ba908625310e15f826b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 61, "num_lines": 34, "path": "/Python/CodingTests/Search/lony_integer.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "input = [3, 2147483647, 1, 0]\n\n\nimport sys\n\n\ndef lonelyinteger(input):\n lists = list(input)\n print(lists)\n answer = [x for x in lists if lists.count(x) == 1]\n return answer\n\n# Tail starts here\nif __name__ == '__main__':\n a = int(input())\n b = map(int, input().strip().split(\" \"))\n print(lonelyinteger(b))\n\n\ndef insert_sort(ar):\n\n list = list(ar)[1:][0].split()\n sorted = list[:-1]\n\n for i in range(1, len(items)):\n j = i\n while j > 0 and items[j - 1] > items[j]:\n items[j - 1], items[j] = items[j], items[j - 1]\n sys.stdout.write(\" \".join(str(x) for x in items))\n sys.stdout.write('\\n')\n j -= 1\n\n\ninsert_sort(sys.stdin)\n" }, { "alpha_fraction": 0.5508772134780884, "alphanum_fraction": 0.5649122595787048, "avg_line_length": 20.923076629638672, "blob_id": "2199239c032c4453c20ae7dc6b4582c301bb7832", "content_id": "c5ebd0026d70cc5998f7b16ad6ead6f125f67e22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 59, "num_lines": 13, "path": "/Python/IndustrialProgramming/classes/class3.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\nclass Bla():\n __privateVar = 4\n\n def method(self):\n print (self.__privateVar)\n print (self.__class__.__dict__['_Bla__privateVar'])\n\nprint(\"Testing classes; expect value '4' printed 2 times.\")\nb = Bla()\nb.method() # prints 4 (twice)\n" }, { "alpha_fraction": 0.5894988179206848, "alphanum_fraction": 0.6014319658279419, "avg_line_length": 17.954545974731445, "blob_id": "e2fa30c5cc8ba3413c8e994c2145bead4572253f", "content_id": "c13fc5f1a894411b1e0350edf41ca4496ce3c2aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 419, "license_type": "no_license", "max_line_length": 61, "num_lines": 22, "path": "/CSharp/code-examples/sys-programming/unsafe1.cs", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "// see: http://msdn.microsoft.com/en-us/library/chfa2zb8.aspx\n\n// compile with: /unsafe\nusing System;\n\nclass UnsafeTest\n{\n // Unsafe method: takes pointer to int:\n unsafe static void SquarePtrParam(int* p)\n {\n *p *= *p;\n }\n\n unsafe static void Main()\n {\n int i = 5;\n // Unsafe method: uses address-of operator (&):\n SquarePtrParam(&i);\n Console.WriteLine(i);\n }\n}\n// Output: 25\n\n\n" }, { "alpha_fraction": 0.7158470153808594, "alphanum_fraction": 0.7249544858932495, "avg_line_length": 23.045454025268555, "blob_id": "1099be9e4ea4b478d00238d993b335562762347e", "content_id": "6a2dbbf723bc3700764bc155e03119bc37e73d3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 549, "license_type": "no_license", "max_line_length": 79, "num_lines": 22, "path": "/Java/F21SF Soft E Fundation/Assignment 2/src/assignment_2/CompetitorOverallComparator.java", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "package assignment_2;\r\n\r\nimport java.util.Comparator;\r\n\r\n\r\n/**This class is needed to compare competitors object based on Overallscore\r\n * Provide correct compare method for sort method.\r\n * @author Marcin Kopacz\r\n *\r\n */\r\npublic class CompetitorOverallComparator implements Comparator<Competitor>\r\n{\r\n\r\n\r\n\t/**Compare two competitor based on OverallScore. \r\n\t * Provide \"natural\" order for listByOverall()\r\n\t */\r\n\tpublic int compare(Competitor s1, Competitor s2) \r\n\t{\r\n\t\treturn Double.valueOf(s1.getOverallScore()).compareTo(s2.getOverallScore());\r\n\t}\r\n}" }, { "alpha_fraction": 0.25981244444847107, "alphanum_fraction": 0.40257033705711365, "avg_line_length": 23.60683822631836, "blob_id": "fab5c61f3b5e696df7a07121d65aecfbd14b3035", "content_id": "befdd3329b2b996fb15603e897b4519de5db7fc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2879, "license_type": "no_license", "max_line_length": 87, "num_lines": 117, "path": "/Python/CodingTests/Greedy/two-arrays.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "# import sys\n\n# input_all = []\n\n# for line in sys.stdin:\n# input_all.append([int(x) for x in line.split() if x.isdigit()])\nimport itertools\n\n\n# 5\n# 2 4\n# 1 3\n# 3 1\n# 5 5\n# 2 3 1 1 1\n# 1 3 4 3 3\n# 10 9\n# 1 5 1 4 4 2 7 1 2 2\n# 8 7 1 7 7 4 4 3 6 7\n# 10 9\n# 3 6 8 5 9 9 4 8 4 7\n# 5 1 0 1 6 4 1 7 4 3\n# 10 4\n# 4 4 3 2 1 4 4 3 2 4\n# 2 3 0 1 1 3 1 0 0 2\n\ninput_all = [[4],\n [2, 4],\n [1, 3], [3, 1],\n [2, 4],\n [1, 3], [3, 1],\n [2, 4],\n [1, 3], [3, 1],\n [73, 95],\n [54, 65, 7, 38, 39, 90, 80, 93, 38, 75, 11, 42, 1, 53, 64, 28, 92, 91, 46,\n 7, 91, 35, 61, 1, 40, 67, 86, 55, 15, 68, 64, 83, 13, 4, 82, 60, 63,\n 52, 74, 68, 54, 81, 36, 18, 53, 23, 48, 34, 58, 2, 36, 64, 50, 34,\n 10, 7, 78, 93, 59, 44, 45, 1, 87, 47, 36, 66, 1, 24, 60, 12, 46, 81, 30],\n [1, 41, 25, 9, 84, 34, 53, 10, 25, 48, 7, 52, 20, 52, 1, 50, 9, 29, 38,\n 21, 1, 88, 40, 81, 1, 48, 11, 31, 68, 2, 35, 52, 53, 46, 49, 83, 1,\n 8, 39, 75, 34, 23, 67, 1, 43, 87, 54, 82, 58, 82, 29, 20, 26, 12, 10,\n 57, 84, 91, 79, 49, 69, 30, 32, 43, 24, 91, 22, 73, 67, 27, 87, 47, 30]\n ]\n\n\nT = input_all[0][0]\n\nKN_index = [1 + 3 * x for x in range(0, T)]\nAB_index = set([x for x in range(1, 3 * T + 1)]) - set(KN_index)\n\n\nKN = [input_all[k] for k in KN_index]\nAB = [input_all[k] for k in AB_index]\n\n\ndef two_arrays(T, KN, AB):\n for i in range(0, T):\n A = AB[i * 2]\n B = AB[(i * 2) + 1]\n K = KN[i][1]\n N = KN[i][0]\n if (min(A) + max(B)) < K:\n print(\"NO\")\n else:\n A_perms = permute_in_place(A)\n B_perms = permute_in_place(B)\n check_sum(K, N, A_perms, B_perms)\n\n\ndef check_sum(K, N, A_perms, B_perms):\n true_cunter = 0\n\n for A_perm in A_perms:\n summs = [zip(A_perm, B_perm) for B_perm in B_perms]\n for ab_sum in summs:\n summed_tuples = [x for x in [sum(x) for x in ab_sum]]\n\n if sum(i >= K for i in summed_tuples) == N:\n true_cunter += 1\n\n if true_cunter == 0:\n print(\"NO\")\n return\n else:\n print(\"YES\")\n return\n\n\ndef permute_in_place(a):\n a.sort()\n yield list(a)\n\n if len(a) <= 1:\n return\n\n first = 0\n last = len(a)\n while 1:\n i = last - 1\n\n while 1:\n i = i - 1\n if a[i] < a[i + 1]:\n j = last - 1\n while not (a[i] < a[j]):\n j = j - 1\n a[i], a[j] = a[j], a[i] # swap the values\n r = a[i + 1:last]\n r.reverse()\n a[i + 1:last] = r\n yield list(a)\n break\n if i == first:\n a.reverse()\n return\n\ntwo_arrays(T, KN, AB)\n" }, { "alpha_fraction": 0.5437262654304504, "alphanum_fraction": 0.5551331043243408, "avg_line_length": 26.073530197143555, "blob_id": "87da315db4027f2f033aff61f932f06e9a4b3352", "content_id": "928284fecaf3e24e5b0207650c60243359ceea36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1841, "license_type": "no_license", "max_line_length": 107, "num_lines": 68, "path": "/Python/IndustrialProgramming/extra/dict3.py", "repo_name": "chyzwar/learning-fields", "src_encoding": "UTF-8", "text": "#!/bin/env python\n# Example of dictionaries and JSON files\n\nimport random\nimport sys\nimport json\n\n\ndef mkTelDict(n, names):\n \"\"\"Build a dictionary of <n> random telephone numbers for <n> random first-names taken from <names>.\"\"\"\n tel_dict = dict()\n for i in range(n):\n no = random.randint(1000, 9999)\n name = names[random.randint(0, 99)]\n tel_dict[name] = no\n\n return tel_dict\n\n\ndef ppTelDict(tel):\n \"\"\"Pretty print a phone dictionary.\"\"\"\n for k, v in tel.iteritems():\n print(k, \" -> \", v)\n\n\ndef printNoOf(name, tel):\n \"\"\"Print phone number of <name> in dictionary <tel>, or sorry message.\"\"\"\n if name in tel:\n print(\"The tel no. of \" + name + \" is \", tel[name])\n else:\n print(\"No phone number for \" + name + \", sorry!\")\n\n\ndef readFile(fname):\n \"\"\"Read contents of a file, and put each line of the file into an element of a list.\"\"\"\n fd = open(fname, 'r')\n names = []\n for line in fd:\n names.append(line[0:-1])\n return names\n\n# -----------------------------------------------------------------------------\n# Constants\nfile = 'names.txt'\njfile = 'tel.json'\n\n# -----------------------------------------------------------------------------\n# main\n\nif (len(sys.argv) != 2): # expect 1 args: n\n print(\n \"Usage: dict2.py <int>\\n build a phone dictionary with <n> entries and write it to a JSON file\")\nelse:\n n = int(sys.argv[1]) # read from command-line\n names = readFile(file)\n tel = mkTelDict(n, names)\n ppTelDict(tel)\n\n json.dump(tel, fp=open(jfile, 'w'), indent=2)\n print(\"Data has been written to file \", jfile)\n\n tel_new = json.loads(open(jfile, 'r').read())\n ppTelDict(tel_new)\n\n the_name = \"Billy\"\n printNoOf(the_name, tel_new)\n the_name = names[random.randint(0, 99)]\n printNoOf(the_name, tel_new)\n" } ]
181
saimon0/BBS-Blum-Blum-Shub-Generator
https://github.com/saimon0/BBS-Blum-Blum-Shub-Generator
8a8178dbb3a6b2dc8ad99f8159788adc79be4ce5
d945b76c2894e1ce309e2befb867f9b9ae83931b
06af9fec61936db5b8eada81ed434fd33b4c809e
refs/heads/master
2022-12-30T09:36:43.212313
2020-10-21T23:06:26
2020-10-21T23:06:26
306,166,364
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4380858540534973, "alphanum_fraction": 0.5123335123062134, "avg_line_length": 23.281436920166016, "blob_id": "6faea917305beedf7ddb756911b1ef35a092cdb4", "content_id": "d3c1b7cd162b10ef7952c7b510a96d6bd482c495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4054, "license_type": "no_license", "max_line_length": 168, "num_lines": 167, "path": "/bbs.py", "repo_name": "saimon0/BBS-Blum-Blum-Shub-Generator", "src_encoding": "UTF-8", "text": "import random\nimport string\nfrom math import gcd\nimport re\n\n\ndef main():\n key = generate()\n single_bit_test(key)\n long_series_test(key)\n poker_test(key)\n series_test(key)\n\ndef checkIfRelativelyPrime(a, b):\n if gcd(a, b) == 1:\n return 1\n else:\n return 0\n\n\ndef generate():\n p, q = 0, 0\n dividers = 0\n\n while p % 4 != 3 and dividers != 2:\n p = random.randint(0, 1000)\n for a in range(1, p+1):\n if p % a == 0:\n dividers = dividers + 1\n\n while q % 4 != 3 and dividers != 2:\n q = random.randint(0, 1000)\n for a in range(1, p+1):\n if p % a == 0:\n dividers = dividers + 1\n\n N = p * q\n\n x = 0\n x_dividers = [0]\n n_dividers = []\n\n for z in range(1, N+1):\n if N % z == 0:\n n_dividers.append(z)\n\n no_of_calc = 0\n x = random.randint(0, N)\n\n while checkIfRelativelyPrime(x, N) == 0:\n x = random.randint(0, N)\n checkIfRelativelyPrime(x, N)\n\n primal_value = (x*x) % N\n\n key = ''\n\n if primal_value % 2 == 0:\n bit = 0\n else:\n bit = 1\n\n key = key + str(bit)\n prev_xi = primal_value\n\n for i in range(1, 20000):\n xi = (prev_xi * prev_xi) % N\n if xi % 2 == 0:\n bit = 0\n key = key + str(bit)\n else:\n bit = 1\n key = key + str(bit)\n prev_xi = xi\n\n #print(\"\\n\" + key + \"\\n\")\n return key\n\n\ndef single_bit_test(key):\n res = key.count('1')\n if res > 9725 and res < 10275:\n print(\"\\nTest pojedynczego bitu - zakonczony powodzeniem\")\n return 1\n else:\n print(\"\\nTest pojedynczego bitu - zakonczony niepowodzeniem\")\n return 0\n\n\ndef series_test(key):\n regex1_1 = re.compile('[1](0){1}[1]?|[1]?(0){1}[1]')\n regex1_2 = re.compile('[1](1){1}[1]?|[1]?(1){1}[1]')\n res1_1 = regex1_1.findall(key)\n res1_2 = regex1_2.findall(key)\n regex2 = re.compile('(0){2}|(1){2}')\n res2 = regex2.findall(key)\n regex3 = re.compile('(0){3}|(1){3}')\n res3 = regex3.findall(key)\n regex4 = re.compile('(0){4}|(1){4}')\n res4 = regex4.findall(key)\n regex5 = re.compile('(0){5}|(1){5}')\n res5 = regex5.findall(key)\n regex6 = re.compile('(0){6,}|(1){6,}')\n res6 = regex6.findall(key)\n\n if 2315 < len(res1_1 + res1_2) < 2685 and 1114 < len(res2) < 1386 and len(res3) > 527 and 723 > len(res4) < 384 and 103 > len(res5) > 209 and 103 > len(res6) > 209:\n print(\"\\nTest serii - zakonczony powodzeniem\")\n return 1\n else:\n print(\"\\nTest serii - zakonczony niepowodzeniem\")\n return 0\n\ndef long_series_test(key):\n regex = re.compile('(0){26,}|(1){26,}')\n res = regex.search(key)\n\n if res is None:\n print(\"\\nTest dlugiej serii - nie znaleziono serii zer i jedynek o dlugosci >= 26\")\n return 1\n else:\n print(\"\\nTest dlugiej serii - znaleziono serie zer i jedynek o dlugosci >= 26\")\n return 0\n\n\ndef poker_test(key):\n\n def split_len(seq, length):\n return [seq[i:i + length] for i in range(0, len(seq), length)]\n\n segments = split_len(key, 4)\n #print(segments)\n\n unique_segments = {\n '0000': 0, '0001': 0, '0010': 0, '0011': 0,\n '0100': 0, '0101': 0, '0110': 0, '0111': 0,\n '1000': 0, '1001': 0, '1010': 0, '1011': 0,\n '1100': 0, '1101': 0, '1110': 0, '1111': 0,\n }\n #print(unique_segments)\n\n dict = {}\n for a in unique_segments:\n counter = 0\n for b in segments:\n if a == b:\n counter = counter + 1\n dict[a] = counter\n counter = 0\n\n #print(dict)\n sum = 0\n el = 0\n for i in dict:\n el = dict.get(i)*dict.get(i) - 5000\n sum = sum + el\n el = 0\n\n x = (16/5000)*sum-5000\n\n if x > 2.16 and x < 46.17:\n print(\"\\nTest pokerowy - zakonczony z powodzeniem. Wartosc x = \" + str(\"%.2f\" % x))\n return 1\n else:\n print(\"\\nTest pokerowy - zakonczony niepowodzeniem. Wartosc x = \" + str(\"%.2f\" % x))\n return 0\n\nmain()" } ]
1
Wall-Lai/COMP9021
https://github.com/Wall-Lai/COMP9021
69293d0954516b6700fe2aaf93bce6baf6d7bd2e
ffd06ab73efad8c0940970f82f78d96693ff17d8
5683ff31e032460909de91e358e70412b83feadb
refs/heads/master
2020-04-08T04:04:11.202256
2019-02-23T04:43:09
2019-02-23T04:43:09
159,001,635
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5002713203430176, "alphanum_fraction": 0.5111231803894043, "avg_line_length": 24.59722137451172, "blob_id": "4bc49e600fcd0eec126b85f5277a0d1c8bb27dd9", "content_id": "32bc2df85bf916cfb8565a84661c46144271e338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1843, "license_type": "no_license", "max_line_length": 95, "num_lines": 72, "path": "/Assignment 1/Q4/tunnel.py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "import os.path\nimport sys\nimport re\nfrom collections import deque\n\n\nfilename = input('Please enter the name of the file you want to get data from: ')\nif not os.path.exists(filename):\n print(f'Sorry, input file does not store valid data.')\n sys.exit()\n#read file\nresult = []\na_l = []\nL=[]\nwith open(filename,'r') as f:\n result=f.readlines()\n#arrange file to list\nfor i in result:\n L.append(re.findall(r'\\d+',i))\nfor i in L:\n if i != []:\n a_l.append(list(map(int, i)))\n#distance from west\nceil = a_l[0]\nfloor = a_l[1]\nnum_c = 0\nnum_f = 0\nfor i in ceil:\n if i > floor[0]:\n num_c += 1\n else:\n break\nfor i in floor:\n if i < ceil[0]:\n num_f += 1\n else:\n break\ndistance_from_west = min(num_c,num_f)\nprint(f'From the west, one can see into the tunnel over a distance of {distance_from_west}.')\n#Q2\ndistance_L = []\nfor i in range(0,len(ceil)):\n count_ceil = 0\n count_floor = 0\n for j in range(i + 1, len(ceil)):\n if ceil[i] >= ceil[j]:\n break\n else: \n if ceil[i] < floor[j]:\n if ceil[i+1] > floor[j]:\n ceil[i] = ceil[j]\n count_ceil += 1\n else:\n break\n else:\n count_ceil += 1\n distance_L.append(count_ceil)\n for j in range(i + 1, len(ceil)):\n if floor[i] <= floor[j]:\n break\n else:\n if floor[i] > ceil[j]:\n if floor[i+1] < ceil[j]:\n floor[i] = ceil[j]\n count_floor += 1\n else:\n break\n else:\n count_floor += 1\n distance_L.append(count_floor)\ndistance = max(distance_L)\nprint(f'Inside the tunnel, one can see into the tunnel over a maximum distance of {distance}.')\n" }, { "alpha_fraction": 0.841269850730896, "alphanum_fraction": 0.841269850730896, "avg_line_length": 14.75, "blob_id": "15f338d855614933b3908e9d4e109acd5c3258bd", "content_id": "557fa2f0ceaf20abc79763622562f352d351f6db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 63, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/Assignment 1/Q3/cable_car.py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "import os.path\nimport sys\n\nfrom collections import defaultdict\n" }, { "alpha_fraction": 0.553983211517334, "alphanum_fraction": 0.5670859813690186, "avg_line_length": 27.92424201965332, "blob_id": "bff41984f0159885eea27273b521434c34441f28", "content_id": "155e4d088aa080695d0665f715f45bdfe464b597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1908, "license_type": "no_license", "max_line_length": 99, "num_lines": 66, "path": "/quiz/quiz10/edgar.py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "# Randomly generates a binary search tree with values from 0 up to 9, and displays it growing up.\n#\n# Written by *** and Eric Martin for COMP9021\n\n\nimport sys\nfrom random import seed, choice\nfrom binary_tree_adt import *\n\ndef print_growing_up(tree):\n global L\n if tree.value is None:\n return\n L = []\n for _ in range(tree.height() + 1):\n L.append([])\n _print_growing_up(tree, 0, tree.height())\n __print_growing_up(L, tree.height())\n\ndef _print_growing_up(tree, n, height):\n global L\n if n > height:\n return\n if tree.value is None:\n L[n].append(' ')\n _print_growing_up_no_value(n + 1, height)\n _print_growing_up_no_value(n + 1, height)\n else:\n L[n].append(tree.value)\n _print_growing_up(tree.left_node, n + 1, height)\n _print_growing_up(tree.right_node, n + 1, height)\n\ndef _print_growing_up_no_value(n, height):\n if n > height:\n return\n L[n].append(' ')\n _print_growing_up_no_value(n + 1, height)\n _print_growing_up_no_value(n + 1, height)\n \ndef __print_growing_up(L, height):\n for i in range(height, -1, -1):\n string = ''\n for item in L[i]:\n string = string + ' ' * (2 ** (height - i) - 1) + str(item) + ' ' * (2 ** (height - i))\n print(string.rstrip())\n\ntry:\n seed_arg, nb_of_nodes = (int(x) for x in\n input('Enter two integers, with the second one between 0 and 10: '\n ).split()\n )\n if nb_of_nodes < 0 or nb_of_nodes > 10:\n raise ValueError\nexcept ValueError:\n print('Incorrect input, giving up.')\n sys.exit()\n\nseed(seed_arg)\ndata_pool = list(range(nb_of_nodes))\ntree = BinaryTree()\nfor _ in range(nb_of_nodes):\n datum = choice(data_pool)\n tree.insert_in_bst(datum)\n data_pool.remove(datum)\nprint_growing_up(tree)\n#tree.print_binary_tree()" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 3.75, "blob_id": "3e71facc28651aca5bf8fe34bf60712e40b0eef1", "content_id": "b3703fedac190fa787f4409c1a474fd641dbaefb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19, "license_type": "no_license", "max_line_length": 8, "num_lines": 4, "path": "/Labs/asd.c", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "qweqwqwe\nqwe\nqwe\n1\n" }, { "alpha_fraction": 0.5634547472000122, "alphanum_fraction": 0.5990990996360779, "avg_line_length": 35.191490173339844, "blob_id": "723ababb4702275e62e677b2960f6f6cd346a2cc", "content_id": "e6e954bf0a4708b7fd535263c35aa2693710bd19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5106, "license_type": "no_license", "max_line_length": 120, "num_lines": 141, "path": "/final sample/10_27_gai_gai_not_one_line/sample_6.py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "'''\nis_valid_prefix_expression(expression) checks whether the string expression\nrepresents a correct infix expression (where arguments follow operators).\n\nevaluate_prefix_expression(expression) returns the result of evaluating expression.\n\nFor expression to be syntactically correct:\n- arguments have to represent integers, that is, tokens that can be converted to an integer\n thanks to int();\n- operators have to be any of +, -, * and /;\n- at least one space has to separate two consecutive tokens.\n\nAssume that evaluate_prefix_expression() is only called on syntactically correct expressions,\nand that / (true division) is applied to a denominator that is not 0.\n\nYou might find the reversed() function, the split() string method,\nand the pop() and append() list methods useful.\n'''\n\nfrom operator import add, sub, mul, truediv\n\n\nclass ListNonEmpty(Exception):\n pass\n\n\ndef is_valid_prefix_expression(expression):\n '''\n >>> is_valid_prefix_expression('12')\n Correct prefix expression\n >>> is_valid_prefix_expression('+ 12 4')\n Correct prefix expression\n >>> is_valid_prefix_expression('- + 12 4 10')\n Correct prefix expression\n >>> is_valid_prefix_expression('+ - + 12 4 10 * 11 4')\n Correct prefix expression\n >>> is_valid_prefix_expression('/ + - + 12 4 10 * 11 4 5')\n Correct prefix expression\n >>> is_valid_prefix_expression('+ / + - + 12 4 10 * 11 4 5 - 80 82 ')\n Correct prefix expression\n >>> is_valid_prefix_expression('twelve')\n Incorrect prefix expression\n >>> is_valid_prefix_expression('2 3')\n Incorrect prefix expression\n >>> is_valid_prefix_expression('+ + 2 3')\n Incorrect prefix expression\n >>> is_valid_prefix_expression('+1 2')\n Incorrect prefix expression\n >>> is_valid_prefix_expression('+ / 1 2 *3 4')\n Incorrect prefix expression\n >>> is_valid_prefix_expression('+1 2')\n Incorrect prefix expression\n >>> is_valid_prefix_expression('+ +1 2')\n Correct prefix expression\n >>> is_valid_prefix_expression('++1 2')\n Incorrect prefix expression\n >>> is_valid_prefix_expression('+ +1 -2')\n Correct prefix expression\n '''\n stack = []\n operator = ['+','-','*','/']\n try:\n expres = expression.split() # delete space \n for i in expres:\n if i in operator or int(i):\n stack.append(i)\n # approach 1\n while len(stack) >= 3 and stack[-1] not in operator and stack[-2] not in operator and stack[-3] in operator:\n right = stack.pop()\n left = stack.pop()\n op =stack.pop()\n # print(left + op + right)\n result = eval(left+ op + right)\n stack.append(str(result))\n # print(stack) \n # approach 2 \n # while len(stack) >= 3 and stack[-1] not in operator and stack[-2] not in operator:\n # stack = stack[:-3] + ['1']\n # print(stack)\n if len(stack) > 1:\n raise ListNonEmpty\n if len(stack) == 1 and stack[0] in operator:\n raise ListNonEmpty\n # Replace pass above with your code\n # - IndexError is raised in particular when trying to pop from an empty list\n # - ValueError is raised in particular when trying to convert to an int\n # a string that cannot be converted to an int\n # - ListNonEmpty is expected to be raised when a list is found out not to be empty\n except (IndexError, ValueError, ListNonEmpty, ZeroDivisionError):\n print('Incorrect prefix expression')\n else:\n print('Correct prefix expression')\n# is_valid_prefix_expression('+ - + 12 4 10 * 11 4')\n# is_valid_prefix_expression('- + 12 4 10') \n \ndef evaluate_prefix_expression(expression):\n '''\n >>> evaluate_prefix_expression('12')\n 12\n >>> evaluate_prefix_expression('+ 12 4')\n 16\n >>> evaluate_prefix_expression('- + 12 4 10')\n 6\n >>> evaluate_prefix_expression('+ - + 12 4 10 * 11 4')\n 50\n >>> evaluate_prefix_expression('/ + - + 12 4 10 * 11 4 5')\n 10.0\n >>> evaluate_prefix_expression('+ / + - + 12 4 10 * 11 4 5 - 80 82 ')\n 8.0\n >>> evaluate_prefix_expression('+ +1 2')\n 3\n >>> evaluate_prefix_expression('+ +1 -2')\n -1\n '''\n # Insert your code here\n\n expre = expression.split()\n stack = []\n operator = ['+','-','*','/']\n # num = 1\n for i in expre:\n stack.append(i)\n while len(stack) >= 3 and stack[-1] not in operator and stack[-2] not in operator:\n value = eval((stack[-2]) + stack[-3] + (stack[-1]))\n stack = stack[:-3] + [str(value)]\n # return int(stack[0]) if '.' not in stack[0] else float(stack[0])\n if '.' in stack[0]:\n return float(stack[0])\n else:\n return int(stack[0])\n\n\n# return int(stack[0])\n# print(evaluate_prefix_expression('+ - + 12 4 10 * 11 4'))\n# evaluate_prefix_expression('+ +1 -2') \n# print(evaluate_prefix_expression('+ / + - + 12 4 10 * 11 4 5 - 80 82 '))\n\n# print('###############')\nif __name__ == '__main__':\n import doctest\n doctest.testmod() \n" }, { "alpha_fraction": 0.5363790392875671, "alphanum_fraction": 0.549069344997406, "avg_line_length": 24.673913955688477, "blob_id": "d6f982dbce9c1ac7dce14b6c086b68f11ee458ca", "content_id": "9be0eacbbb17a2ff8704691bc4839f0a77d3615f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1182, "license_type": "no_license", "max_line_length": 142, "num_lines": 46, "path": "/final sample/10_27_gai_gai_not_one_line/sample_1(2).py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "\ndef remove_consecutive_duplicates(word):\n '''\n >>> remove_consecutive_duplicates('')\n ''\n >>> remove_consecutive_duplicates('a')\n 'a'\n >>> remove_consecutive_duplicates('ab')\n 'ab'\n >>> remove_consecutive_duplicates('aba')\n 'aba'\n >>> remove_consecutive_duplicates('aaabbbbbaaa')\n 'aba'\n >>> remove_consecutive_duplicates('abcaaabbbcccabc')\n 'abcabcabc'\n >>> remove_consecutive_duplicates('aaabbbbbaaacaacdddd')\n 'abacacd'\n '''\n # Insert your code here (the output is returned, not printed out) \n\n # approach 1\n # return '' if len(word) == 0 else ''.join([word[0]] + [ word[i] if word[i] != word[i-1] else '' for i in range(1, len(word))]) \n # approach 2\n\n # if len(word) == 0:\n # return word\n # new = word[0]\n # for i in range(len(word)-1):\n # if word[i] != word[i+1]:\n # new += word[i+1]\n # retuen new\n\n if len(word) == 0:\n return ''\n string = word[0]\n\n for i in word[1:]:\n if i != string[-1]:\n string += i\n\n return string\n\n# remove_consecutive_duplicates('aba')\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n" }, { "alpha_fraction": 0.5890790224075317, "alphanum_fraction": 0.6195269227027893, "avg_line_length": 40.83157730102539, "blob_id": "fb4f684797a25347c9306630725a9bb9dee5e6ee", "content_id": "ce3bf2acd92c6e90b8afabf9fa8a58bb7b62938e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3974, "license_type": "no_license", "max_line_length": 652, "num_lines": 95, "path": "/quiz/quiz3/quiz_3.py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "# Uses Global Temperature Time Series, avalaible at\n# http://data.okfn.org/data/core/global-temp, stored in the file monthly_csv.csv,\n# assumed to be stored in the working directory.\n# Prompts the user for the source, a year or a range of years, and a month.\n# - The source is either GCAG or GISTEMP.\n# - The range of years is of the form xxxx -- xxxx (with any number of spaces,\n# possibly none, around --) and both years can be the same,\n# or the first year can be anterior to the second year,\n# or the first year can be posterior to the first year.\n# We assume that the input is correct and the data for the requested month\n# exist for all years in the requested range.\n# Then outputs:\n# - The average of the values for that source, for this month, for those years.\n# - The list of years (in increasing order) for which the value is larger than that average.\n# \n# Written by *** and Eric Martin for COMP9021\n\n\nimport sys\nimport os\nimport csv\n\n\nfilename = 'monthly_csv.csv'\nif not os.path.exists(filename):\n print(f'There is no file named {filename} in the working directory, giving up...')\n sys.exit()\n\nsource = input('Enter the source (GCAG or GISTEMP): ')\nyear_or_range_of_years = input('Enter a year or a range of years in the form XXXX -- XXXX: ')\nmonth = input('Enter a month: ')\naverage = 0\nyears_above_average = []\n\n# REPLACE THIS COMMENT WITH YOUR CODE\ntry:\n if source != 'GCAG' and source != 'GISTEMP':\n raise ValueError\nexcept ValueError:\n print('Wrong source input, giving up...')\n sys.exit()\n#extract years from string (year_or_range_of_years) to max_year and min_year\nimport re\nyear_L = re.findall(r'\\d+', year_or_range_of_years)\n# year_L = re.split(r'[\\s\\-]+', year_or_range_of_years.strip())\ntry:\n if len(year_L) == 2:\n if int(year_L[1]) >= int(year_L[0]):\n max_year = int(year_L[1])\n min_year = int(year_L[0])\n if int(year_L[1]) < int(year_L[0]):\n max_year = int(year_L[0])\n min_year = int(year_L[1])\n elif len(year_L) == 1:\n max_year = min_year = int(year_L[0])\n else:\n raise ValueError\nexcept ValueError:\n print('Wrong year input, giving up...')\n sys.exit()\n# build a mapping between English month and digit month by dictionary\nmonth_mapping = {'January': '01', 'February': '02', 'March':'03', 'April':'04', 'May':'05', 'June':'06', 'July':'07', 'August':'08', 'September':'09', 'October':'10', 'November':'11', 'December':'12', 'january': '01', 'february': '02', 'march':'03', 'april':'04', 'may':'05', 'june':'06', 'july':'07', 'august':'08', 'september':'09', 'october':'10', 'november':'11', 'december':'12', 'Jan': '01', 'Feb': '02', 'Mar':'03', 'Apr':'04', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12', 'jan': '01', 'feb': '02', 'mar':'03', 'apr':'04', 'jun':'06', 'jul':'07', 'aug':'08', 'sep':'09', 'oct':'10', 'nov':'11', 'dec':'12'}\ntry:\n num_month = int(month_mapping[month])\nexcept KeyError:\n print('Wrong month input, giving up...')\n sys.exit()\n# open and input data from csv file to list\ndata = [] # store year and mean, formula:[[year, mean], ...]\nwith open(filename, 'r') as csvfile:\n reader = csv.reader(csvfile)\n for item in reader:\n if reader.line_num == 1:\n continue\n if item[0] == source:\n date = item[1].split('-')\n if max_year >= int(date[0]) and min_year <= int(date[0]):\n if num_month == int(date[1]):\n data.append([int(date[0]), float(item[2])])\n\nsum_of_list = 0\nfor item in data:\n sum_of_list += item[1]\naverage = sum_of_list / len(data)\nfor item in data:\n if item[1] > average:\n years_above_average.append(item[0])\nyears_above_average = sorted(years_above_average)\n \n\n\n\nprint(f'The average anomaly for {month} in this range of years is: {average:.2f}.')\nprint('The list of years when the temperature anomaly was above average is:')\nprint(years_above_average)\n" }, { "alpha_fraction": 0.5567400455474854, "alphanum_fraction": 0.5653370022773743, "avg_line_length": 31.311111450195312, "blob_id": "5824b0576b6bd3977296ab653a51cdc1f483c839", "content_id": "87590af705e4b8d6e1d62ab5a9e5d8cabb2b97aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2908, "license_type": "no_license", "max_line_length": 103, "num_lines": 90, "path": "/final sample/10_27_gai_gai_not_one_line/sample_3.py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "'''\nGiven a word w, a good subsequence of w is defined as a word w' such that\n- all letters in w' are different;\n- w' is obtained from w by deleting some letters in w.\n\nReturns the list of all good subsequences, without duplicates, in lexicographic order\n(recall that the sorted() function sorts strings in lexicographic order).\n\nThe number of good sequences grows exponentially in the number of distinct letters in w,\nso the function will be tested only for cases where the latter is not too large.\n\n'''\n\ndef get_combo(string, current):\n \n if string == '':\n return [current]\n if string[0] in current:\n return get_combo(string[1:], current)\n return get_combo(string[1:], current + string[0]) + get_combo(string[1:], current)\n\n# a = list(set(get_combo('aba','')))\n# a.sort()\n# print(a)\n\n# def get_combination(string, current):\n# if len(string) == 0:\n# return [current]\n# if string[0] in current:\n# return get_combination(string[1:], current)\n# return get_combination(string[1:], current + string[0]) + get_combination(string[1:] ,current)\n\n# # a = list(set(get_combination('abcabcab','')))\n# # a.sort()\n# # print(a)\n# # if len(string) == 0:\n# # return [current]\n# # if string[0] in current:\n# # return get_combination(string[1:], current)\n# # return get_combination(string[1:] , current + string[0]) + get_combination(string[1:], current)\n \n\n# def good_subsequences(word):\n# '''\n# >>> good_subsequences('')\n# ['']\n# >>> good_subsequences('aaa')\n# ['', 'a']\n# >>> good_subsequences('aaabbb')\n# ['', 'a', 'ab', 'b']\n# >>> good_subsequences('aaabbc')\n# ['', 'a', 'ab', 'abc', 'ac', 'b', 'bc', 'c']\n# >>> good_subsequences('aaabbaaa')\n# ['', 'a', 'ab', 'b', 'ba']\n# >>> good_subsequences('abbbcaaabccc')\n# ['', 'a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac',\\\n# 'bc', 'bca', 'c', 'ca', 'cab', 'cb']\n# >>> good_subsequences('abbbcaaabcccaaa')\n# ['', 'a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac',\\\n# 'bc', 'bca', 'c', 'ca', 'cab', 'cb', 'cba']\n# >>> good_subsequences('abbbcaaabcccaaabbbbbccab')\n# ['', 'a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac',\\\n# 'bc', 'bca', 'c', 'ca', 'cab', 'cb', 'cba']\n# '''\n# # Insert your code here\n\n string = get_string(word)\n result = list(set(get_combo(string,'')))\n result.sort()\n print(result)\n # Insert your code here\ndef get_string(word):\n if word == '':\n return word\n string = word[0]\n for i in word[1:]:\n if i != string[-1]:\n string +=i\n return string\ndef get_combo(string,current):\n if string == '':\n return [current]\n if string[0] in current:\n return get_combo(string[1:],current)\n return get_combo(string[1:],current) + get_combo(string[1:],current+string[0])\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n" }, { "alpha_fraction": 0.5553725957870483, "alphanum_fraction": 0.5870728492736816, "avg_line_length": 27.15116310119629, "blob_id": "dac5a8e12dad08dc4de7b14cfb8c6489ee19b477", "content_id": "e594523c48bd3104003838f1a1b231347f53114a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2429, "license_type": "no_license", "max_line_length": 109, "num_lines": 86, "path": "/Assignment 1/Q2/superpower.py", "repo_name": "Wall-Lai/COMP9021", "src_encoding": "UTF-8", "text": "import sys\nlist_h = []\nheroes = []\ntry:\n list_h = input('Please input the heroes\\' powers').split()\n for i in range(0,len(list_h)):\n heroes.append(int(list_h[i]))\n print(heroes)\nexcept ValueError:\n print('Sorry, these are not valid power values.')\n sys.exit()\ntry:\n nb_of_switches = input('Please input the number of power flips:')\n nb_of_switches = int(nb_of_switches)\n print(nb_of_switches)\n if nb_of_switches < 0 or len(list_h)< nb_of_switches:\n raise ValueError\nexcept ValueError:\n print('Sorry, this is not a valid number of power flips.')\n sys.exit()\n#for Q1\nheroes1 = []\nheroes1 = sorted(heroes)\nnb_of_switches1 = nb_of_switches \ni = 0\nremainder = 0\nfor i in range(0, len(heroes1)):\n if heroes1[i] < 0:\n if nb_of_switches1 > 1:\n heroes1[i] = heroes1[i] * (-1)\n nb_of_switches1 -= 1\n remainder = nb_of_switches1 % 2\nheroes1 = sorted(heroes1)\nif remainder == 1:\n heroes1[0] = heroes1[0] * (-1)\nmax1 = sum(heroes1)\n#for Q2\nheroes2 = []\nheroes2 = sorted(heroes)\ni = 0\nfor i in range(0, nb_of_switches):\n heroes2[i] = heroes2[i] * (-1)\nmax2 = sum(heroes2)\n\n# for Q3\nsum_s = 0\nsum_l = []\nfor i in range(0, len(heroes)-nb_of_switches+1):\n sum_s = sum(heroes[i:i+nb_of_switches])\n sum_l.append(sum_s)\nmax3 = sum(heroes) - min(sum_l)*2 \n#for Q4\nheroes4 = []\nfor i in heroes:\n heroes4.append(i)\nl4 = [0]\nwhile(True):\n if len(heroes4) == 0:\n break\n else:\n i = 0\n while i < len(heroes4):\n if heroes4[i] < 0:\n break\n else:\n heroes4.remove(heroes4[i])\n\n removel= []\n i = 0\n while i < len(heroes4):\n s = sum(heroes4[0:i+1])\n if s <= 0:\n l4.append(s)\n removel.append(heroes4[i])\n i += 1 \n else:\n break\n for i in removel:\n heroes4.remove(i)\n\nmax4 = sum(heroes) - min(l4)*2 \n#print out\nprint(f'Possibly flipping the power of the same hero many times, the greatest achievable power is {max1}.')\nprint(f'Flipping the power of the same hero at most once, the greatest achievable power is {max2}.')\nprint(f'Flipping the power of nb_of_flips many consecutive heroes, the greatest achievable power is {max3}.')\nprint(f'Flipping the power of arbitrarily many consecutive heroes, the greatest achievable power is {max4}.')\n\n\n\n \n" } ]
9
liuxin123456liuxin/Neural_Network_Inertia_Estimation
https://github.com/liuxin123456liuxin/Neural_Network_Inertia_Estimation
f10181953e5880c1310635383fe6822891f1cbe3
661c9dab4a18379eb7fd864660bdb42ec959fd0a
91c7f6d909f9f759b870cc58e905cceb181ee46c
refs/heads/master
2023-03-21T12:32:16.176353
2020-12-13T20:19:44
2020-12-13T20:19:44
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5136216878890991, "alphanum_fraction": 0.5416417717933655, "avg_line_length": 41.91794967651367, "blob_id": "0f6d85c6ee92d23c566d2033801c61b92e580f1e", "content_id": "760729c8b18fc0ddc1ac3aa4ca579f18fd8896ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16738, "license_type": "permissive", "max_line_length": 119, "num_lines": 390, "path": "/experimented test_codes/regression_iner_MLP.py", "repo_name": "liuxin123456liuxin/Neural_Network_Inertia_Estimation", "src_encoding": "UTF-8", "text": "import numpy as np\nimport h5py\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes\nfrom mpl_toolkits.axes_grid1.inset_locator import mark_inset\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport math as m\nimport torch as T\nfrom data_loading import loading, separate_dataset\nimport pdb\n\n# Set the font dictionaries (for plot title and axis titles)\ntitle_font = {'fontname': 'Arial', 'size': '16', 'color': 'black', 'weight': 'normal',\n 'verticalalignment': 'bottom'} # Bottom vertical alignment for more space\naxis_font = {'fontname': 'Arial', 'size': '16'}\n\n# def accuracy(model, train_f, train_rf, train_p, train_M, pct_close):\ndef accuracy(model, train_f, train_rf, train_M, pct_close):\n with T.no_grad():\n n_items = len(train_M)\n X1 = T.Tensor(train_f) # 2-d Tensor\n X2 = T.Tensor(train_rf) # 2-d Tensor\n # X3 = T.Tensor (train_p)\n # X3 = X3.reshape(-1,1) # reshaping to 2-d Tensor\n Y = T.Tensor(train_M) # actual as 1-d Tensor\n # oupt = model(X1, X2, X3) # all predicted as 2-d Tensor\n oupt = model(X1, X2)\n # pdb.set_trace()\n pred = oupt.view(n_items) # all predicted as 1-d\n loss_val = loss_func(oupt, Y)\n RMSE = m.sqrt(T.mean((Y-pred)**2))\n MAPE = 100 * (T.mean((T.abs(Y-pred)/Y)))\n # pdb.set_trace()\n n_correct = T.sum((T.abs(pred - Y) < T.abs(pct_close * Y)))\n result = (n_correct.item() * 100.0 / n_items) # scalar\n # pdb.set_trace()\n return result, RMSE, MAPE, loss_val.item()\n\n# def accuracy2(model, train_f, train_rf, train_p, train_M, pct_close):\ndef accuracy2(model, train_f, train_rf, train_M, pct_close):\n n_items = len(train_M)\n X1 = T.Tensor(train_f) # 2-d Tensor\n X2 = T.Tensor(train_rf)\n # X3 = T.Tensor (train_p)\n # X3 = X3.reshape(-1,1) # reshaping to 2-d Tensor\n Y = T.Tensor(train_M) # actual as 1-d Tensor\n # oupt = model(X1, X2, X3) # all predicted as 2-d Tensor\n oupt = model(X1, X2)\n pred = oupt.view(n_items) # all predicted as 1-d\n RMSE_test = m.sqrt(T.mean((Y - pred) ** 2))\n MAPE_test = 100 * (T.mean((T.abs(Y - pred) / Y)))\n n_correct = T.sum((T.abs(pred - Y) < T.abs(pct_close * Y)))\n result = (n_correct.item() * 100.0 / n_items) # scalar\n pdb.set_trace()\n return result, RMSE_test, MAPE_test\n\n# MLP based model\nclass Net(T.nn.Module):\n def __init__(self, n_inp, n_hid1, n_hid2, n_out):\n super(Net, self).__init__()\n self.hid1 = T.nn.Linear(n_inp, n_hid1)\n self.hid2 = T.nn.Linear(n_hid1, n_hid2)\n self.oupt = T.nn.Linear(n_hid2, n_out)\n\n\n # initializing the weights and biases\n\n # T.nn.init.xavier_uniform_(self.hid.weight, gain = 0.05)\n T.nn.init.xavier_uniform_(self.hid1.weight)\n T.nn.init.zeros_(self.hid1.bias)\n T.nn.init.xavier_uniform_(self.hid2.weight)\n T.nn.init.zeros_(self.hid2.bias)\n # T.nn.init.xavier_uniform_(self.oupt.weight, gain = 0.05)\n T.nn.init.xavier_uniform_(self.oupt.weight)\n T.nn.init.zeros_(self.oupt.bias)\n\n # def forward(self, X1,X2,X3):\n def forward(self, X1, X2):\n # x = T.cat((X1, X2, X3), dim=1) # concatenating the input vectors\n # after removing del_P as input, we only use 2 input vectors\n x = T.cat((X1, X2), dim=1)\n z = T.tanh(self.hid1(x))\n z = T.tanh(self.hid2(z))\n\n z = self.oupt(z) # no activation, aka Identity()\n return z\n\n# def SSE(out, target):\n# return (target-out)*(target-out)\n\nif __name__ == '__main__':\n\n T.manual_seed(1); np.random.seed(1)\n\n ###################################################################################################################\n ################### 1. Loading the delw and delw_dot data from the mat file #######################\n\n '''\n file_freq = mat file with all the frequency data input stacked in row along with del_p and M\n file_rocof = mat file with all the rocof data input stacked in row along with del_p and M\n \n loading() returns the array of freq_data and rocof_data\n separate_dataset() returns the separate training and testing dataset\n '''\n path = \".\\\\data files\\\\excitation_test\\\\manipulated\\\\\"\n file_freq = path + 'freq_norm.mat'\n file_rocof = path + 'rocof_norm.mat'\n freq_data, rocof_data = loading(file_freq, file_rocof)\n train_f, train_rf, train_p, train_M, test_f, test_rf, test_p, test_M = separate_dataset(freq_data, rocof_data)\n\n ###################################################################################################################\n ################### 2. creating the model #######################\n '''\n n_inp (number of input nodes): calculated the number of inputs based on number of input features \n n_hid (number of hidden nodes): followed the general convention for 8-3-8 i.e. 2^n - n - 2^n\n n_out (number of output nodes): calculated the number of output to be provided from the training dataset \n \n '''\n\n # n_inp = len(train_f[0]) + len(train_rf[0]) + len([train_p[0]])\n n_inp = len(train_f[0]) + len(train_rf[0])\n n_hid1 = int(m.log(n_inp)/m.log(2)) + 3\n # pdb.set_trace()\n n_hid2 = n_hid1\n n_out = len([train_M[0]])\n net = Net(n_inp, n_hid1, n_hid2, n_out)\n\n ###################################################################################################################\n ################### 3. Training the model #######################\n net = net.train()\n bat_size = 10\n loss_func = T.nn.MSELoss()\n optimizer = T.optim.SGD(net.parameters(), lr=5e-3)\n n_items = len(train_f)\n batches_per_epoch = n_items // bat_size\n # max_batches = 1000 * batches_per_epoch\n max_batches = 80000\n print(\"Starting training\")\n output_full = T.tensor([]) # capturing the full output of the model in total batches\n # weight_ih = [] # storing the weights from input to hidden\n weight_ho = [] # storing the weights from hidden unit to output unit\n output_avg = [] # storing the average output of the model\n losses = [] # storing the batch losses\n val_losses = []\n min_RMSE = 100\n min_MAPE = 100\n min_batch_loss = 100\n min_R_epoch = 100\n min_M_epoch = 100\n min_B_epoch = 100\n for b in range(max_batches):\n curr_bat = np.random.choice(n_items, bat_size, replace=False)\n X1 = T.Tensor(train_f[curr_bat])\n X2 = T.Tensor(train_rf[curr_bat])\n # X3 = T.Tensor(train_p[curr_bat]).view(bat_size, 1)\n Y = T.Tensor(train_M[curr_bat]).view(bat_size, 1)\n # pdb.set_trace()\n optimizer.zero_grad()\n # oupt = net(X1,X2,X3)\n oupt = net(X1, X2)\n # pdb.set_trace()\n # oupt_numpy = oupt.data.cpu().numpy()\n output_full = T.cat((output_full, oupt), 0)\n # output_avg.append(np.mean(oupt_numpy))\n loss_obj = T.sqrt(loss_func(oupt, Y))\n loss_obj.backward()\n optimizer.step()\n # weight_ih.append(np.reshape(net.hid1.weight.data.clone().cpu().numpy(), (1, n_inp * n_hid1)))\n weight_ho.append(np.reshape(net.oupt.weight.data.clone().cpu().numpy(), (1, n_hid2 * n_out)))\n # if b % (max_batches // 20) == 0:\n if b % 1000 == 0:\n # print(output.size(), end=\"\")\n print(\"batch = %6d\" % b, end=\"\")\n print(\" train loss = %7.4f\" % loss_obj.item(), end=\"\")\n net = net.eval()\n acc, RMSE, MAPE, loss = accuracy(net, test_f, test_rf, test_M, 0.1)\n # val_losses.append([loss])\n net = net.train()\n print(\" val loss = %7.4f\" % loss, end=\"\")\n print(\" accuracy = %0.2f%%\" % acc, end=\"\")\n print(\" MAPE = %0.3f%%\" % MAPE, end=\"\")\n print(\" RMSE = %7.4f\" % RMSE)\n\n if loss_obj.item() < min_batch_loss:\n min_batch_loss = loss_obj.item()\n min_B_epoch = b\n\n if RMSE < min_RMSE:\n min_RMSE = RMSE\n min_R_epoch = b\n\n if MAPE < min_MAPE:\n min_MAPE = MAPE\n min_M_epoch = b\n\n losses.append([loss_obj.item()])\n val_losses.append([RMSE])\n # avg_loss = np.concatenate((avg_loss,losses), axis = 1)\n print(\"Training complete \\n\")\n\n losses = np.squeeze(losses)\n val_losses = np.squeeze(val_losses)\n plt.figure()\n\n plt.plot(losses)\n t_x = np.arange(len(losses))\n poly = np.polyfit(t_x, losses, 5)\n losses = np.poly1d(poly)(t_x)\n plt.plot(t_x, losses)\n\n plt.plot(val_losses)\n v_x = np.arange(len(val_losses))\n poly = np.polyfit(v_x, val_losses, 5)\n val_losses = np.poly1d(poly)(v_x)\n plt.plot(v_x, val_losses)\n\n plt.ylabel(\"Mean Squared Error\", **axis_font)\n plt.xlabel(\"Number of batches in entire epochs\", **axis_font)\n # plt.title(\"Batch training loss vs number of batch\", **title_font)\n plt.grid(linestyle='-', linewidth=0.5)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.rcParams['agg.path.chunksize'] = 1000\n # plt.savefig('./output/output_feb19/batch_loss.png', dpi=600, bbox_inches='tight')\n plt.show()\n pdb.set_trace()\n\n print(\" min batch loss = {} at {} batch \\n\".format(min_batch_loss, min_B_epoch))\n print(\" min RMSE = {} at {} batch \\n\".format(min_RMSE, min_R_epoch))\n print(\" min MAPE = {} at {} batch \\n\".format(min_MAPE, min_M_epoch))\n\n # avg_loss = np.mean(avg_loss[:,1:], axis = 1)\n #\n # fig, axx = plt.subplots()\n # axx.plot(avg_loss)\n # axx.set_xlim(0, max_batches) # apply the x-limits\n # # axx.set_ylim(0, 100) # apply the y-limits\n # plt.ylabel(\"Mean Squared Error\", **axis_font)\n # plt.xlabel(\"Number of batches\", **axis_font)\n # # plt.title(\"Batch training loss vs number of batch\", **title_font)\n # plt.grid(linestyle='-', linewidth=0.5)\n # plt.xticks(fontsize = 12)\n # plt.yticks(fontsize = 12)\n # plt.rcParams['agg.path.chunksize'] = 1000\n # # plt.savefig('./output/for_1500_samples/batch_loss.png', dpi = 600, bbox_inches='tight')\n # plt.show()\n # pdb.set_trace()\n\n ###################################################################################################################\n ################### 4. Evaluating the model #######################\n\n net = net.eval() # set eval mode\n # acc1, RMSE_test, MAPE_test = accuracy2(net, test_f, test_rf, test_p, test_M, 0.05)\n # acc2, _, _ = accuracy2(net, test_f, test_rf, test_p, test_M, 0.1)\n # acc3, _, _ = accuracy2(net, test_f, test_rf, test_p, test_M, 0.15)\n acc1, RMSE_test, MAPE_test = accuracy2(net, test_f, test_rf, test_M, 0.05)\n acc2, _, _ = accuracy2(net, test_f, test_rf, test_M, 0.1)\n acc3, _, _ = accuracy2(net, test_f, test_rf, test_M, 0.15)\n print(\"Accuracy on test data with 0.05 tolerance = %0.2f%%\" % acc1)\n print(\"Accuracy on test data with 0.1 tolerance = %0.2f%%\" % acc2)\n print(\"Accuracy on test data with 0.15 tolerance = %0.2f%%\" % acc3)\n print(\"MAPE on test data = %0.3f%%\" % MAPE_test)\n print(\"RMSE on test data = %7.4f\" % RMSE_test)\n pdb.set_trace()\n ###################################################################################################################\n ################### 5. Using the model #######################\n\n eval_file = h5py.File(path + 'eval_data_with_noise.mat', 'r')\n eval_var = eval_file.get('eval_data')\n f_var = np.array(eval_var[0:75, :]).T\n rocof_var = np.array(eval_var[75:150, :]).T\n # power_var = np.array(eval_var[150, :])\n pdb.set_trace()\n X1 = T.Tensor(f_var)\n X2 = T.Tensor(rocof_var)\n # X3 = T.Tensor(power_var).view(-1, 1)\n # y = net(X1, X2, X3)\n y = net(X1, X2)\n # print(y)\n pdb.set_trace()\n\n ###################################################################################################################\n ################### 6. Plotting the results #######################\n\n # weight_ih = np.reshape(weight_ih, (np.shape(weight_ih)[0], np.shape(weight_ih)[2]))\n # weights_ih_num = int(np.shape(weight_ih)[1])\n # for i in range(0, weights_ih_num):\n # plt.plot(weight_ih[:, i])\n # plt.grid(linestyle='-', linewidth=0.5)\n # plt.xticks(fontsize=12)\n # plt.yticks(fontsize=12)\n # plt.ylabel(\"weights from input to hidden layer\", **axis_font)\n # plt.xlabel(\"Number of batches in entire epochs\", **axis_font)\n # plt.xlim(0, max_batches)\n # plt.rcParams['agg.path.chunksize'] = 10000\n # plt.savefig('./output/output_feb19/i2h_weight.png', dpi = 600, bbox_inches='tight')\n # plt.show()\n\n weight_ho = np.reshape(weight_ho, (np.shape(weight_ho)[0], np.shape(weight_ho)[2]))\n weights_ho_num = int(np.shape(weight_ho)[1])\n for i in range(0, weights_ho_num):\n plt.plot(weight_ho[:, i])\n plt.grid(linestyle='-', linewidth=0.5)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.ylabel(\"weights from hidden to output layer\", **axis_font)\n plt.xlabel(\"Number of batches in entire epochs\", **axis_font)\n plt.xlim(0, max_batches)\n plt.rcParams['agg.path.chunksize'] = 10000\n plt.savefig('./output/output_feb19/h2o_weight.png', dpi=600, bbox_inches='tight')\n plt.show()\n # pdb.set_trace()\n #\n # # ############ full output plot #############\n # #\n # output_full_array = output_full.data.cpu().numpy()\n # fig, ax = plt.subplots()\n # ax.plot(output_full_array)\n # # ax.plot(output)\n # ax.set_xlim(0, max_batches) # apply the x-limits\n # # ax.set_ylim(0, 10) # apply the y-limits\n # # plt.hlines(10, 0, 6000, colors='r', linestyles='dashed', linewidth=3)\n # plt.grid(linestyle='-', linewidth=0.5)\n # plt.xticks(fontsize=12)\n # plt.yticks(fontsize=12)\n # plt.ylabel(\"Estimated Inertia\", **axis_font)\n # plt.xlabel(\"Number of batches in entire epochs\", **axis_font)\n # # plt.title(\"Trained output in entire batch\", **title_font)\n # # plt.show()\n # # axins = zoomed_inset_axes(ax, 2.5, loc=4) # zoom-factor: 2.5, location: upper-left\n # # axins.plot(output_full_array)\n # # x1, x2, y1, y2 = 25000, 30000, 6, 8 # specify the limits\n # # axins.set_xlim(x1, x2) # apply the x-limits\n # # axins.set_ylim(y1, y2) # apply the y-limits\n # # plt.yticks(visible=False)\n # # plt.xticks(visible=False)\n # # axins.xaxis.set_visible('False')\n # # axins.yaxis.set_visible('False')\n # # mark_inset(ax, axins, loc1=1, loc2=3, fc=\"none\", ec=\"0.5\")\n # # plt.grid()\n # plt.savefig('./output/output_feb19/estimated_output.png', dpi = 600)\n # plt.show()\n #\n # '''\n # ############ averaged output plot #############\n # fig, ax = plt.subplots()\n # ax.plot(output_avg)\n # # ax.set_xlim(0, 600) # apply the x-limits\n # # ax.set_ylim(0, 12) # apply the y-limits\n # # plt.hlines(10, 0, 600, colors='r', linestyles='dashed', linewidth=3)\n # plt.grid(linestyle='-', linewidth=0.5)\n # plt.xticks(fontsize=14)\n # plt.yticks(fontsize=14)\n # plt.ylabel(\"Estimated Inertia\", **axis_font)\n # plt.xlabel(\"Number of batches\", **axis_font)\n # plt.title(\"estimated system inertia with increase batch number\", **title_font)\n # # plt.show()\n # axins = zoomed_inset_axes(ax, 2.5, loc=4) # zoom-factor: 2.5, location: upper-left\n # axins.plot(output_avg)\n # x1, x2, y1, y2 = 0, 2500, 4, 6 # specify the limits\n # axins.set_xlim(x1, x2) # apply the x-limits\n # axins.set_ylim(y1, y2) # apply the y-limits\n # plt.yticks(visible=False)\n # plt.xticks(visible=False)\n # # axins.xaxis.set_visible('False')\n # # axins.yaxis.set_visible('False')\n # mark_inset(ax, axins, loc1=1, loc2=3, fc=\"none\", ec=\"0.5\")\n # plt.grid()\n # # plt.savefig('output_avg.png', dpi = 600)\n # plt.show()\n # '''\n #\n ############ plotting loss #############\n fig, axx = plt.subplots()\n axx.plot(losses)\n axx.set_xlim(0, max_batches) # apply the x-limits\n # axx.set_ylim(0, 100) # apply the y-limits\n plt.ylabel(\"Mean Squared Error\", **axis_font)\n plt.xlabel(\"Number of batches in entire epochs\", **axis_font)\n # plt.title(\"Batch training loss vs number of batch\", **title_font)\n plt.grid(linestyle='-', linewidth=0.5)\n plt.xticks(fontsize = 12)\n plt.yticks(fontsize = 12)\n plt.rcParams['agg.path.chunksize'] = 1000\n plt.savefig('./output/output_feb19/batch_loss.png', dpi = 600, bbox_inches='tight')\n\n\n #\n #\n #\n" }, { "alpha_fraction": 0.6325178146362305, "alphanum_fraction": 0.6493374109268188, "avg_line_length": 31.71666717529297, "blob_id": "392e5d692e453999ae5215f004641e065922c745", "content_id": "5426d2728edd6f0334bfadd9afec17ea7ed067ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1962, "license_type": "permissive", "max_line_length": 119, "num_lines": 60, "path": "/experimented test_codes/data_loading.py", "repo_name": "liuxin123456liuxin/Neural_Network_Inertia_Estimation", "src_encoding": "UTF-8", "text": "import h5py\nimport numpy as np\nfrom sklearn.preprocessing import normalize, MinMaxScaler\nimport matplotlib.pyplot as plt\nimport pdb\n\ndef loading(file_freq, file_rocof):\n # loading total data\n file_f = h5py.File(file_freq, 'r')\n file_rocof = h5py.File(file_rocof, 'r')\n f_var = file_f.get('f')\n rocof_var = file_rocof.get('rf')\n f_var = np.array(f_var).T\n rocof_var = np.array(rocof_var).T\n return f_var, rocof_var\n\ndef separate_dataset(freq_data, rocof_data):\n '''\n\n :param freq_data: change of frequency data extracted from the matfile\n :param rocof_data: rocof data extracted from the matfile\n :return: separate training dataset for each of the inputs(frequency, rocof, and p) and an output dataset of inertia\n\n Note: the data have been normalized already in MATLAB\n\n '''\n\n train_num = int(0.8*len(freq_data)) # number of data to be trained\n\n train_f = freq_data[0:train_num,:-2]\n train_rf = rocof_data[0:train_num,:-2]\n train_p = freq_data[0:train_num,-2]\n train_M = freq_data[0:train_num,-1]\n\n test_f = freq_data[train_num:len(freq_data), :-2]\n test_rf = rocof_data[train_num:len(freq_data), :-2]\n test_p = freq_data[train_num:len(freq_data), -2]\n test_M = freq_data[train_num:len(freq_data), -1]\n\n return train_f, train_rf, train_p, train_M, test_f, test_rf, test_p, test_M\n\nif __name__ == '__main__':\n\n # testing if the above functions work properly\n\n path = \".\\\\data files\\\\new_data\\\\manipulated\\\\\"\n file_freq = path + 'freq_norm.mat'\n file_rocof = path + 'rocof_norm.mat'\n freq_data, rocof_data = loading(file_freq, file_rocof)\n train_f, train_rf, train_p, train_M, test_f, test_rf, test_p, test_M = separate_dataset(freq_data, rocof_data)\n plt.subplot(221)\n plt.plot(train_f[0])\n plt.subplot(222)\n plt.plot(train_rf[0])\n plt.subplot(223)\n plt.plot(test_f[0])\n plt.subplot(224)\n plt.plot(test_rf[0])\n plt.show()\n pdb.set_trace()" }, { "alpha_fraction": 0.7449856996536255, "alphanum_fraction": 0.7607449889183044, "avg_line_length": 42.5625, "blob_id": "57e8338adb8018f46e255089dfa18caca6b43640", "content_id": "5350d04678dc6de829a1a207b1d8827c73f75d68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 702, "license_type": "permissive", "max_line_length": 228, "num_lines": 16, "path": "/README.md", "repo_name": "liuxin123456liuxin/Neural_Network_Inertia_Estimation", "src_encoding": "UTF-8", "text": "# Neural_Network_Inertia_Estimation\nEstimating power system inertia using convolution neural network.\n\nAll of the python scripts are inside the \"main code files\" folder. A sample of frequency and ROCOF data have been included in the data folder for your reference. Please modify the input shape, size, and path to match your needs.\n\n## Dependencies\n1. `pytorch`\n2. `numpy`\n3. `matplotlib`\n4. `h5py`\n\n## Acknowledgement\n\nIf you use the code in any of your work, please cite the work as shown below:\n\nA. Poudyal, U. Tamrakar, R. D. Trevizan, R. Fourney, R. Tonkoski, and T. M. Hansen, “Convolutional neural network-based inertia estimation using local frequency measurements,” in 52nd North American Power Symposium (NAPS), 2020\n\n" }, { "alpha_fraction": 0.48070454597473145, "alphanum_fraction": 0.49752622842788696, "avg_line_length": 43.324562072753906, "blob_id": "eba4f0e60b60cd93ebb014bf78e854e4598de2b9", "content_id": "702b49f33111d9e9748ec0fdf6960b578216fff1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5053, "license_type": "permissive", "max_line_length": 119, "num_lines": 114, "path": "/main code files/utils.py", "repo_name": "liuxin123456liuxin/Neural_Network_Inertia_Estimation", "src_encoding": "UTF-8", "text": "import torch\nimport os\nimport h5py\nimport numpy as np\nfrom model import Net\nimport pdb\n\ndef accuracy(model, validation_loader, pct_close, criterion, device, network, eval = False):\n with torch.no_grad():\n val_correct = []\n val_loss_func = []\n n_items = 0\n for idx, (test_f_rf,test_M_D) in enumerate(validation_loader):\n n_items += len(test_M_D)\n test_f_rf, test_M_D = test_f_rf.to(device), test_M_D.to(device)\n if (network == 'CNN'):\n X = test_f_rf.double().unsqueeze(1) # pytorch input should be float -> awkward right?\n Y = test_M_D.double().view(-1, 1) # converting into 2-d tensor\n else:\n X = test_f_rf.float()\n Y = test_M_D.float().view(-1,1) # reshaping to 2-d Tensor\n oupt = model(X) # all predicted as 2-d Tensor\n loss = criterion(oupt,Y)\n n_correct = torch.sum((torch.abs(oupt - Y) < torch.abs(pct_close * Y)))\n val_correct.append(n_correct)\n val_loss_func.append(loss)\n\n loss_func = sum(val_loss_func)/ len(val_loss_func)\n result = (sum(val_correct) * 100.0 / n_items)\n RMSE_loss = torch.sqrt(loss_func)\n\n # observing the result when set to eval mode\n if (eval):\n print('Predicted test output for random batch = {}, actual output = {} with accuracy of {:.2f}% '\n 'and RMSE = {:.6f}'.format(oupt, Y, result, RMSE_loss))\n return result, RMSE_loss, loss_func\n\ndef testing(model_path,\n data_path,\n counter,\n net,\n criterion,\n device,\n network,\n load_model = True,\n trained_test = False):\n\n net = net.eval()\n with torch.no_grad():\n eval_file = h5py.File(data_path + 'eval_data.mat', 'r')\n eval_var = eval_file.get('eval_data')\n if (network == 'CNN'):\n X_eval = torch.Tensor(np.array(eval_var[0:-2, :]).T).double().unsqueeze(1) # a 2-d tensor\n Y_eval = torch.Tensor(np.array(eval_var[-1, :]).T).double().view(-1, 1) # converting to a 2-d tensor\n else:\n X_eval = torch.Tensor(np.array(eval_var[0:-2, :]).T) # a 2-d tensor\n Y_eval = torch.Tensor(np.array(eval_var[-1, :]).T).view(-1, 1) # converting to a 2-d tensor\n\n X_eval, Y_eval = X_eval.to(device), Y_eval.to(device)\n if (load_model):\n test_loss = [] # accumulating the losses on different models\n i = 0\n epis = []\n for filename in os.listdir(model_path):\n if filename.endswith(\".pth\"):\n net.load_state_dict(torch.load(model_path + '/' + filename))\n net.eval()\n # pdb.set_trace()\n y = net(X_eval)\n loss_test = torch.sqrt(criterion(y, Y_eval))\n test_loss.append(loss_test.item())\n if not trained_test:\n print ('test result at epoch {} is y = {}'.format(counter[i], y.view(len(y))))\n else:\n if len(filename) == 12:\n epo = int(filename[5:8])\n epis.append(epo)\n else:\n epo = int(filename[5:7])\n epis.append(epo)\n print('Actual output = {}'.format(Y_eval))\n print('test result at epoch {} is y = {}'.format(epo, y))\n i = i + 1\n continue\n else:\n continue\n test_RMSE = min(test_loss)\n if not trained_test:\n min_val_epoch = counter[np.argmin(test_loss)]\n print('the best model is at epoch {} which gives a loss of {:.6f} \\n'\n .format(min_val_epoch, test_RMSE))\n else:\n print('the best model is at epoch {} gives a loss of {:.6f} \\n'\n .format(epis[np.argmin(test_loss)], test_RMSE))\n else:\n y = net(X_eval)\n test_loss = criterion(y, Y_eval)\n test_RMSE = torch.sqrt(test_loss)\n print ('Actual output = {} and Predicted test output = {} with RMSE = {:.6f}'.format(Y_eval, y, test_RMSE))\n return test_loss, test_RMSE\n\nif __name__ == '__main__':\n net = Net(n_inp = 402, n_hid1 = 25, n_hid2 = 25, n_out = 1,\n dropout_rate = 0.5, weight_ini = 0.05, dropout_decision = False)\n testing(model_path = \"../../Neural-Network-Regression/log/testing_models/\"\n \"Apr-23-2020-10.20.43-h25_lr0.001_lam0.0005_bat_30/models\"\n ,data_path = \"..\\\\..\\\\matlab files\\\\area2_non_IID\\\\manipulated\\\\\"\n ,counter = 0\n ,net = net\n ,criterion = torch.nn.MSELoss()\n ,device = torch.device(\"cpu\")\n ,load_model = True\n ,trained_test = True # setting this true means we are using a pre-trained model to test\n )\n" }, { "alpha_fraction": 0.5651723146438599, "alphanum_fraction": 0.5816532969474792, "avg_line_length": 45.49638366699219, "blob_id": "1fbe534ca213cf7dce4ab26cb25fbb13174dcbc0", "content_id": "baf12633b0365627877897ea83be007105553d55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19295, "license_type": "permissive", "max_line_length": 122, "num_lines": 415, "path": "/main code files/main.py", "repo_name": "liuxin123456liuxin/Neural_Network_Inertia_Estimation", "src_encoding": "UTF-8", "text": "'''\nAuthor: Abodh Poudyal (@abodh_ltd)\nMSEE, South Dakota State University\nLast updated: August 26, 2020\n'''\n\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('Agg')\nimport pdb\nfrom datetime import date, datetime\nimport os\nimport time\n\nfrom data_loading import loading, separate_dataset, freq_data\nfrom model import Net, Simple1DCNN\nfrom utils import accuracy, testing\nfrom torch.utils.data import DataLoader\n\n# resets weights for different learning rates\ndef weight_init(m):\n if isinstance(m, torch.nn.Linear):\n m.reset_parameters()\n\nif __name__ == '__main__':\n # manual seed to reproduce same results every time\n torch.manual_seed(0); np.random.seed(0)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # setting the parameters\n network = 'CNN' # you can choose to train on MLP or CNN\n epoch = 200 # number of epochs -> in 1 epoch all of the training data are used\n mini_batch = 30 # number of mini-batches -> subset of the training data\n learning_rate = 1e-3 # SGD learning rate -> considers SGD as optimizer\n momentum = 0.5 # SGD momentum term -> considers SGD as optimizer\n n_hidden1 = 25 # number of hidden units in first hidden layer (for MLP)\n n_hidden2 = 25 # number of hidden units in second hidden layer (for MLP)\n n_output = 1 # number of output units\n frac_train = 0.80 # fraction of data to be used as training set\n dropout_rate = 0.2 # dropout rate -> remember to set dropout_decision as True\n weight_initializer = 0.05 # weight initializer -> initializes between [-x,x)\n dropout_decision = False # do you want to dropout or not?\n w_lambda = 0.0005 # weight decay parameter\n\n tolerance = 0.1 # tolerance for the estimated value\n # -> 0.1 means the output around 10% is considers to be correct\n\n save_figs = False # set True if you want to save figs and data\n save_model = False # set True when you want to save models for specific conditions\n load_model = False # set True when you want to load the saved models for specific conditions\n\n # update the location of your data files in data_path to match the path of the input data\n\n # data_path = \"..\\\\..\\\\Neural-Network-Regression\\\\data files\\\\other data\\\\varying both_M_P_posneg_pulse\" \\\n # \"\\\\manipulated\\\\\"\n data_path = \"..\\\\..\\\\matlab files\\\\0.2Hz\\\\manipulated\\\\\" # set the path of the data file\n\n # loading the data\n dataset = freq_data(data_path) # loads data from the freq_data class (dataset class -> awesome in pytorch)\n print('the length of the dataset = ', len(dataset))\n\n train_num = int(frac_train * len(dataset)) # number of data for training\n test_num = len(dataset) - train_num # number of data for validating\n max_batches = epoch * int(train_num / mini_batch)\n\n '''' brute force search '''\n # hidden = [10, 25, 50, 60]\n # lr = [1e-4, 1e-3, 1e-2, 1e-1]\n # decay = [1e-4, 5e-4, 1e-3, 1e-2]\n # batch = [10, 20, 30, 50]\n # results = np.zeros((len(hidden) * len(lr) * len(decay) * len(batch), 6))\n # cnt = 0\n # for n_hidden1 in hidden:\n # n_hidden2 = n_hidden1\n # for learning_rate in lr:\n # for w_lambda in decay:\n # for mini_batch in batch:\n\n # creating a unique folder to save the output files\n str(date.today().strftime(\"%d/%m/%Y\"))\n output_path = \"../../Neural-Network-Regression/log/testing_models/\" + str(date.today().strftime(\"%b-%d-%Y\")) + \\\n str(datetime.now().strftime(\"-%H.%M.%S-\")) \\\n + \"h{}_lr{}_lam{}_bat_{}\".format(n_hidden1, learning_rate, w_lambda, mini_batch)\n try:\n os.mkdir(output_path) # creates a directory based on current date and time\n except OSError:\n print(\"Creation of the directory %s failed\" % output_path)\n\n # creating models folder if save_model is set to true\n if (save_model):\n os.mkdir(output_path + '/models')\n\n if (load_model):\n # path to the saved model from where it needs to be loaded\n model_path = output_path + '/models'\n else:\n model_path = ' '\n\n ###################################################################################################################\n ################### 2. creating the model #######################\n\n # splitting into training and validation dataset\n training, validation = torch.utils.data.random_split(dataset, (train_num, test_num))\n\n # load separate training and validating dataset -> repeat !!! dataset and dataloader are awesome in pytorch)\n train_loader = DataLoader(training, batch_size=mini_batch, shuffle=True)\n validation_loader = DataLoader(validation, batch_size=mini_batch, shuffle=False)\n\n # these initializations are for MLP network\n n_inp = len(training[0][0])\n n_hid1 = n_hidden1\n n_hid2 = n_hidden2\n n_out = n_output\n\n # call your neural network model right here\n\n if (network == 'CNN'):\n net = Simple1DCNN().double().to(device)\n else:\n net = Net(n_inp, n_hid1, n_hid2, n_out, dropout_rate, weight_initializer, dropout_decision).to(device)\n\n print(net) # prints the architecture of your current NN model\n\n ##################################################################################################################\n ############# 3. Training the model #######################\n\n net = net.train() # set the network to training mode\n # net.apply(weight_init)\n criterion = torch.nn.MSELoss() # set the loss criterion\n optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate, momentum=momentum, weight_decay=w_lambda)\n print(\"Starting training \\n\")\n # print(\"h{}_lr{}_lam{}_bat_{}\".format(n_hidden1, learning_rate, w_lambda, mini_batch))\n print(\"####################################################################### \\n\")\n\n weight_ih = [] # storing the weights from input to hidden\n weight_ho = [] # storing the weights from hidden unit to output unit\n train_losses = [] # storing the training losses\n val_losses = [] # storing the validation losses\n test_losses = [] # storing the validation losses\n min_val_RMSE = 1e5 # initializing to find min validation RMSE\n min_R_epoch = 1e5 # initializing to find the epoch with min validation RMSE\n counter = [] # to store the different epochs that gives validation accuracy > 90%\n t_correct = []\n t_acc = []\n v_acc = []\n\n # uncomment below to test on different learning rates\n ###### important: comment out the criterion, optimizer, and net initialized above #####\n # learning_rates = [1e-5, 1e-4, 1e-3, 1e-2, 1e-1]\n # lr_train_loss = []\n # lr_val_loss = []\n # for iter_learn, l_rate in enumerate(learning_rates):\n # torch.manual_seed(1); np.random.seed(1)\n # # net = net.train()\n # net.apply(weight_init)\n # optimizer = torch.optim.SGD(net.parameters(), lr=l_rate, momentum=0.5)\n # weight_ho = []\n\n t0 = time.time()\n for ep in range(epoch):\n train_loss = [] # saves the batch training loss for each epoch\n t_item = 0\n t_correct = []\n for batch_idx, (data, target) in enumerate(train_loader):\n t_item += len(target)\n data, target = data.to(device), target.to(device) # passing the variables to gpu\n if (network == 'CNN'):\n X = data.double().unsqueeze(1) # pytorch input should be float -> awkward right?\n Y = target.double().view(-1, 1) # converting into 2-d tensor\n else:\n X = data.float() # pytorch input should be float -> awkward right?\n Y = target.float().view(-1, 1) # converting into 2-d tensor\n optimizer.zero_grad() # making the gradient zero before optimizing\n oupt = net(X) # neural network output\n loss_obj = criterion(oupt, Y) # loss calculation\n loss_obj.backward() # back propagation\n optimizer.step() # remember w(t) = w(t-1) - alpha*cost ??\n # if not, we are just updating weights here\n\n # saving the weights from input to hidden and hidden to output\n # weight_ih.append(np.reshape(net.hid1.weight.data.clone().cpu().numpy(), (1, n_inp * n_hid1)))\n # weight_ho.append(np.reshape(net.oupt.weight.data.clone().cpu().numpy(), (1, n_hid2 * n_out)))\n\n train_loss.append(loss_obj.item()) # batch losses -> length = number of batches in an epoch\n correct = torch.sum((torch.abs(oupt - Y) < torch.abs(0.1 * Y)))\n t_correct.append(correct)\n\n if (network == 'CNN'):\n weight_ho.append((net.fc3.weight.data.clone().cpu().numpy()))\n else:\n weight_ho.append(np.reshape(net.oupt.weight.data.clone().cpu().numpy(), (1, n_hid2 * n_out)))\n\n t_result = ((sum(t_correct)).item() / t_item)\n t_acc.append(t_result)\n\n # getting the training loss for each epoch\n train_loss_avg = sum(train_loss) / len(train_loss) # batch averaging\n train_losses.append([train_loss_avg]) # saving average batch loss for each epoch\n\n # testing validation set after training all the batches\n net = net.eval() # set the network to evaluation mode\n val_acc, val_RMSE, vali_loss = accuracy(net, validation_loader, tolerance, criterion, device, network, eval=False)\n val_losses.append([vali_loss.item()]) # validation loss on entire samples for each epoch\n v_acc.append(val_acc.item() / 100)\n\n # find the epoch that gives minimum validation loss\n if val_RMSE < min_val_RMSE:\n min_val_RMSE = val_RMSE\n min_R_epoch = ep\n\n # set the network to training mode after validation\n net = net.train()\n\n # if we are willing to test the models on testing data that gives validation accuracy > 90%\n # if (save_model) and val_RMSE <= 0.65:\n if (save_model) and val_RMSE<=0.25:\n counter.append((ep))\n torch.save(net.state_dict(), output_path + '/models/model{}.pth'.format(ep))\n\n print(\"epoch = %d\" % ep, end=\"\")\n print(\" train loss = %7.4f\" % train_loss_avg, end=\"\")\n print(\" val_accuracy = %0.2f%%\" % val_acc, end=\"\")\n print(\" val_RMSE = %7.4f\" % val_RMSE, end=\"\")\n print(\" val_loss = %7.4f\" % vali_loss.item()) # similar to RMSE, can comment out if unnecessary\n\n # uncomment below if you are testing for different learning rates\n # plotted loss after each learning rate test\n # print(\" min RMSE = {} at {} batch \\n\".format(min_RMSE, min_R_epoch))\n # weight_ho = np.reshape(weight_ho, (np.shape(weight_ho)[0], np.shape(weight_ho)[2]))\n # weights_ho_num = int(np.shape(weight_ho)[1])\n # for i in range(0, weights_ho_num):\n # plt.plot(weight_ho[:, i])\n # plt.grid(linestyle='-', linewidth=0.5)\n # plt.xticks(fontsize=12)\n # plt.yticks(fontsize=12)\n # plt.ylabel(\"weights from hidden to output layer\", **axis_font)\n # plt.xlabel(\"Number of batches in entire epochs\", **axis_font)\n # plt.xlim(0, epoch)\n # plt.rcParams['agg.path.chunksize'] = 10000\n # plt.savefig('C:/Users/abodh/Box Sync/Box Sync/Spring 2020/inertia project/Neural-Network-Regression/output/'\n # 'output_feb19/iteration{}'.format(iter_learn), dpi=600, bbox_inches='tight')\n # plt.close()\n\n # averaged the loss to test on learning rates\n # lr_train_loss.append([sum(train_losses) / len(train_losses)])\n # lr_val_loss.append([sum(val_losses) / len(val_losses)])\n\n # train_losses.append([loss_obj.item()])\n # val_losses.append([vali_loss.item()])\n\n print(\"####################################################################### \\n\")\n print(\"Training complete \\n\")\n print(\"Time taken = {}\".format(time.time() - t0))\n print(\" min RMSE = {} at {} epoch \\n\".format(min_val_RMSE, min_R_epoch))\n print(\"####################################################################### \\n\")\n\n # results[cnt, 0] = min_val_RMSE\n # results[cnt, 1] = min_R_epoch\n # results[cnt, 2] = n_hidden1\n # results[cnt, 3] = learning_rate\n # results[cnt, 4] = w_lambda\n # results[cnt, 5] = mini_batch\n # cnt += 1\n\n if (save_figs):\n np.savetxt(output_path + '/train_losses.csv', train_losses, delimiter=',')\n np.savetxt(output_path + '/val_losses.csv', val_losses, delimiter=',')\n\n ###################################################################################################################\n ################### 4. Evaluating the model (validation) #######################\n\n net = net.eval() # set eval mode\n acc_val, val_RMSE, _ = accuracy(net, validation_loader, tolerance, criterion, device, network, eval=True)\n print('validation accuracy with {} tolerance = {:.2f} and RMSE = {:.6f}\\n'\n .format(tolerance, acc_val, val_RMSE))\n\n ###################################################################################################################\n ################### 5. Using the model (testing) #######################\n\n test_loss, test_RMSE = testing(model_path, data_path, counter, net, criterion, device, network, load_model)\n\n ###################################################################################################################\n ################### 6. Plotting the results #######################\n\n # Set the font dictionaries (for plot title and axis titles)\n title_font = {'fontname': 'Arial', 'size': '16', 'color': 'black', 'weight': 'normal',\n 'verticalalignment': 'bottom'} # Bottom vertical alignment for more space\n axis_font = {'fontname': 'Arial', 'size': '16'}\n\n # uncomment below to plot the losses along with different learning rates\n\n # losses = np.squeeze(lr_train_loss)\n # val_losses = np.squeeze(lr_val_loss)\n\n # Plot the training loss and validation loss for different learning rates\n # pdb.set_trace()\n # plt.semilogx(np.array(learning_rates), losses, label='training loss/total Loss')\n # plt.semilogx(np.array(learning_rates), val_losses, label='validation cost/total Loss')\n # plt.ylabel('Cost\\ Total Loss')\n # plt.xlabel('learning rate')\n # plt.legend()\n # plt.savefig(output_path + '/losses{}'.format(iter_learn), dpi=600, bbox_inches='tight')\n # pdb.set_trace()\n\n label_graph = ['train_loss', 'val_loss', 'fitted_train_loss', 'fitted_val_loss', 'test_loss']\n losses = np.squeeze(train_losses)\n val_losses = np.squeeze(val_losses)\n\n t_x = np.arange(len(losses))\n v_x = np.arange(len(val_losses))\n\n plt.figure()\n plt.plot(t_x, losses, label=label_graph[0], c='blue', linewidth='5')\n plt.plot(v_x, val_losses, label=label_graph[1], c='green', linewidth='2')\n # uncomment below if you want to have a vertical line at your best epoch\n # plt.axvline(x=min_R_epoch, color='r', linestyle='--', linewidth=3)\n plt.ylabel(\"Mean Squared Error\", **axis_font)\n plt.xlabel(\"Number of epochs\", **axis_font)\n plt.xlim(0, len(t_x))\n plt.grid(linestyle='-', linewidth=0.5)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.rcParams['agg.path.chunksize'] = 1000\n plt.legend()\n if (save_figs):\n plt.savefig(output_path + '/batch_loss.png', dpi=600, bbox_inches='tight')\n # plt.show()\n plt.close()\n\n plt.figure()\n plt.plot(t_x, t_acc, label='training accuracy', c='blue', linewidth='5')\n plt.plot(v_x, v_acc, label='validation accuracy', c='green', linewidth='2')\n # uncomment below if you want to have a vertical line at your best epoch\n # plt.axvline(x=min_R_epoch, color='r', linestyle='--', linewidth=3)\n plt.ylabel(\"Accuracy\", **axis_font)\n plt.xlabel(\"Number of epochs\", **axis_font)\n plt.xlim(0, len(t_x))\n plt.grid(linestyle='-', linewidth=0.5)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.rcParams['agg.path.chunksize'] = 1000\n plt.legend()\n if (save_figs):\n plt.savefig(output_path + '/accuracy.png', dpi=600, bbox_inches='tight')\n # plt.show()\n plt.close()\n\n # uncomment below to plot polyfit on losses\n # # t_x = np.arange(len(losses))\n # plt.scatter(t_x, losses, label=label_graph[0], marker = 'x', c = '#1f77b4', alpha = 0.5)\n # poly = np.polyfit(t_x, losses, 4)\n # losses = np.poly1d(poly)(t_x)\n # plt.plot(t_x, losses, label=label_graph[2], c = 'red', linewidth = '5')\n #\n # v_x = np.arange(len(val_losses))\n # plt.scatter(v_x, val_losses, label=label_graph[1], marker = '>', c = '#9467bd', alpha = 0.5)\n # poly = np.polyfit(v_x, val_losses, 4)\n # val_losses = np.poly1d(poly)(v_x)\n # plt.plot(v_x, val_losses, label=label_graph[3], c = 'green', linewidth = '5')\n #\n # plt.ylabel(\"Mean Squared Error\", **axis_font)\n # plt.xlabel(\"Number of epochs\", **axis_font)\n # # plt.title(\"Batch training loss vs number of batch\", **title_font)\n # plt.grid(linestyle='-', linewidth=0.5)\n # plt.xticks(fontsize=12)\n # plt.yticks(fontsize=12)\n # plt.rcParams['agg.path.chunksize'] = 1000\n # plt.legend()\n # plt.savefig('./batch_loss.png', dpi=600, bbox_inches='tight')\n # plt.show()\n # plt.close()\n\n # uncomment below to plot input to hidden weights\n # weight_ih = np.reshape(weight_ih, (np.shape(weight_ih)[0], np.shape(weight_ih)[2]))\n # weights_ih_num = int(np.shape(weight_ih)[1])\n # for i in range(0, weights_ih_num):\n # plt.plot(weight_ih[:, i])\n # plt.grid(linestyle='-', linewidth=0.5)\n # plt.xticks(fontsize=12)\n # plt.yticks(fontsize=12)\n # plt.ylabel(\"weights from input to hidden layer\", **axis_font)\n # plt.xlabel(\"Number of batches in entire epochs\", **axis_font)\n # plt.xlim(0, max_batches)\n # plt.rcParams['agg.path.chunksize'] = 10000\n # plt.savefig(output_path + '/wih.png', dpi=600, bbox_inches='tight')\n # plt.show()\n # plt.close()\n\n plt.figure()\n weight_ho = np.reshape(weight_ho, (np.shape(weight_ho)[0], np.shape(weight_ho)[2]))\n weights_ho_num = int(np.shape(weight_ho)[1])\n for i in range(0, weights_ho_num):\n plt.plot(weight_ho[:, i])\n plt.grid(linestyle='-', linewidth=0.5)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.ylabel(\"weights from hidden to output layer\", **axis_font)\n plt.xlabel(\"Number of epochs\", **axis_font)\n plt.xlim(0, epoch)\n plt.rcParams['agg.path.chunksize'] = 10000\n if (save_figs):\n plt.savefig(output_path + '/who', dpi=600, bbox_inches='tight')\n # plt.show()\n plt.close()\n\n # # finally saving the results\n # np.savetxt('../../Neural-Network-Regression/log/testing_models/results.csv', results, delimiter=',')\n # best_idx = np.argmax(results[:, 0])\n # print (\"the best result is given with hid: {} \"\n # \"lr: {} lambda: {} batch_size: {} with an min RMSE of: {}\"\n # \" at epoch: {}\".format(results[best_idx,2], results[best_idx,3],\n # results[best_idx,4], results[best_idx, 5],\n # results[best_idx,0], results[best_idx,1]))" }, { "alpha_fraction": 0.5622830986976624, "alphanum_fraction": 0.5915927290916443, "avg_line_length": 38.907691955566406, "blob_id": "d274b496f64b173093a701a9a8a3084629d2f939", "content_id": "61cd7607dbc1891220c191858141d36fb82b8889", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2593, "license_type": "permissive", "max_line_length": 85, "num_lines": 65, "path": "/main code files/model.py", "repo_name": "liuxin123456liuxin/Neural_Network_Inertia_Estimation", "src_encoding": "UTF-8", "text": "import torch\n\n# MLP based model\nclass Net(torch.nn.Module):\n def __init__(self, n_inp, n_hid1, n_hid2, n_out, dropout_rate,\n weight_ini, dropout_decision=False):\n super(Net, self).__init__()\n self.hid1 = torch.nn.Linear(n_inp, n_hid1)\n self.hid2 = torch.nn.Linear(n_hid1, n_hid2)\n self.oupt = torch.nn.Linear(n_hid2, n_out)\n self.dropout_decision = dropout_decision\n self.dropout = torch.nn.Dropout(dropout_rate)\n self.relu = torch.nn.ReLU()\n\n\n # initializing the weights and biases using xavier uniform (non-default)\n '''\n Note: if ReLU is used as an activation function then He method is used\n torch.nn.init.kaiming_uniform_(self.hid1.weight, nonlinearity = 'relu')\n '''\n\n torch.nn.init.xavier_uniform_(self.hid1.weight, gain = weight_ini)\n torch.nn.init.zeros_(self.hid1.bias)\n torch.nn.init.xavier_uniform_(self.hid2.weight, gain = weight_ini)\n torch.nn.init.zeros_(self.hid2.bias)\n torch.nn.init.xavier_uniform_(self.oupt.weight, gain = weight_ini)\n torch.nn.init.zeros_(self.oupt.bias)\n\n def forward(self, X):\n z = torch.tanh(self.hid1(X))\n if (self.dropout_decision):\n z = self.dropout(z)\n z = torch.tanh(self.hid2(z))\n if (self.dropout_decision):\n z = self.dropout(z)\n z = self.oupt(z) # no activation, aka Identity()\n return z\n\n\nclass Simple1DCNN(torch.nn.Module):\n def __init__(self):\n super(Simple1DCNN, self).__init__()\n self.layer1 = torch.nn.Conv1d(in_channels=1, out_channels=10, kernel_size=3)\n self.act = torch.nn.ReLU()\n self.layer2 = torch.nn.Conv1d(in_channels=10, out_channels=20, kernel_size=3)\n self.fc1 = torch.nn.Linear(20 * 398, 800)\n self.fc2 = torch.nn.Linear(800, 50)\n self.fc3 = torch.nn.Linear(50, 1)\n self.conv2_drop = torch.nn.Dropout(0.5)\n\n # torch.nn.init.xavier_uniform_(self.fc1.weight, gain = 0.09)\n # torch.nn.init.zeros_(self.fc1.bias)\n # torch.nn.init.xavier_uniform_(self.fc2.weight, gain = 0.09)\n # torch.nn.init.zeros_(self.fc2.bias)\n # torch.nn.init.xavier_uniform_(self.fc3.weight, gain = 0.09)\n # torch.nn.init.zeros_(self.fc3.bias)\n\n def forward(self, x):\n x = self.act(self.layer1(x))\n x = self.act(self.conv2_drop(self.layer2(x)))\n x = x.view(-1, x.shape[1] * x.shape[-1])\n x = torch.tanh(self.fc1(x))\n x = torch.tanh(self.fc2(x))\n x = self.fc3(x)\n return x" }, { "alpha_fraction": 0.6184521913528442, "alphanum_fraction": 0.6339979767799377, "avg_line_length": 32.258426666259766, "blob_id": "38603ae600f951582a0ce8dba3acfc95afbadb49", "content_id": "2bcc1a2590c9fd1b6db79975ecb067a31a1b4baf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2959, "license_type": "permissive", "max_line_length": 119, "num_lines": 89, "path": "/main code files/data_loading.py", "repo_name": "liuxin123456liuxin/Neural_Network_Inertia_Estimation", "src_encoding": "UTF-8", "text": "import h5py\nimport numpy as np\n# from sklearn.preprocessing import normalize, MinMaxScaler\nimport matplotlib.pyplot as plt\nimport pdb\nimport torch\nfrom torch.utils.data import Dataset\n\nclass freq_data(Dataset):\n # Constructor\n def __init__(self, path):\n file_freq = path + 'freq_norm.mat'\n file_rocof = path + 'rocof_norm.mat'\n freq_data, rocof_data = loading(file_freq, file_rocof)\n self.x, self.y, _, _ = separate_dataset(freq_data, rocof_data)\n self.len = self.x.shape[0]\n\n # Getter\n def __getitem__(self, idx):\n return self.x[idx], self.y[idx]\n\n # Return the length\n def __len__(self):\n return self.len\n\ndef loading(file_freq, file_rocof):\n '''\n loading the data from the mat file\n\n :param file_freq: mat file that contains the frequency data\n :param file_rocof: mat file that contains the rocof data\n :return: array of frequency and rocof\n\n '''\n\n # loading total data\n file_f = h5py.File(file_freq, 'r')\n file_rocof = h5py.File(file_rocof, 'r')\n f_var = file_f.get('f')\n rocof_var = file_rocof.get('rf')\n f_var = np.array(f_var).T\n rocof_var = np.array(rocof_var).T\n return f_var, rocof_var\n\ndef separate_dataset(freq_data, rocof_data):\n '''\n\n :param freq_data: change of frequency data extracted from the matfile\n :param rocof_data: rocof data extracted from the matfile\n :return: separate training dataset for each of the inputs(frequency, rocof, and p) and an output dataset of inertia\n\n Note: the data have been normalized already in MATLAB\n\n '''\n # loads = np.genfromtxt('pulses.csv', delimiter=',')\n # loads = loads.transpose()\n\n total_dataset = np.hstack((freq_data[:,0:201],rocof_data[:,0:201], freq_data[:,-1:])) # here 201 is used just to\n # extract first 201 datapoints\n\n # total_dataset = np.random.permutation(total_dataset)\n # train_num = int(0.8 * len(total_dataset)) # number of data to be trained\n # pdb.set_trace()\n # train_f_rf = total_dataset[0:train_num,:-1]\n # train_M_D = total_dataset[0:train_num,-1]\n # test_f_rf = total_dataset[train_num:len(total_dataset), :-1]\n # test_M_D = total_dataset[train_num:len(total_dataset), -1]\n # pdb.set_trace()\n # return train_f_rf, train_M_D, test_f_rf, test_M_D\n\n x = total_dataset[:,:-1] # x contains freq and rocof datapoints\n y = total_dataset[:,-1] # y contains inertia constant\n\n return x, y, freq_data[:,0:201],rocof_data[:,0:201]\n\nif __name__ == '__main__':\n # testing if the above functions work properly\n\n path = \"..\\\\..\\\\matlab files\\\\0.2Hz\\\\manipulated\\\\\"\n file_freq = path + 'freq_norm.mat'\n file_rocof = path + 'rocof_norm.mat'\n freq_data, rocof_data = loading(file_freq, file_rocof)\n _, _, f, rf = separate_dataset(freq_data, rocof_data)\n for i in range(f.shape[0]):\n plt.subplot(211)\n plt.plot(f[i,:])\n plt.subplot(212)\n plt.plot(rf[i,:])\n plt.show()" } ]
7
orSpec/corona_signal_bot
https://github.com/orSpec/corona_signal_bot
33fb9b16468c478d71fb6a384bc99f883e2e1912
763efcda328fce77f75197c3fbe2d4260887b89e
abb95c9da86de571cba1fe05324d932af282124d
refs/heads/master
2023-02-10T21:13:23.281084
2021-01-06T14:36:06
2021-01-06T14:36:06
327,275,702
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.698636531829834, "alphanum_fraction": 0.7079330682754517, "avg_line_length": 31.756345748901367, "blob_id": "1f7801799d3960f84481380083d43746b7379de4", "content_id": "46cceeada0b74a252e75e0e480f2220ca2fd589b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6457, "license_type": "no_license", "max_line_length": 129, "num_lines": 197, "path": "/analysis/analysis.py", "repo_name": "orSpec/corona_signal_bot", "src_encoding": "UTF-8", "text": "from Helper import Downloader\n\n# import constants for signal-cli\nimport constant\n\n\nimport pandas as pd\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\nsns.set()\n\nfrom subprocess import call\n\n\ndef datenstand(row):\n datenstand = row[\"daten_stand\"]\n if type(datenstand) == str:\n return row[\"daten_stand\"]\n else:\n splitted = row[\"filename\"].split(\"_\")[-1]\n point_splitted = splitted.split(\".\")[0]\n return point_splitted\n\ndef sendMessage(sender, recipient, message = \".\", attachment = None):\n \n command = \"/usr/local/bin/signal-cli -u \" + sender + \" send -m \\\"\" + message + \"\\\" \" + recipient\n \n if attachment != None:\n command = command + \" -a \\\"\" + attachment + \"\\\"\"\n \n call(command, shell=True)\n\ndef sendMessageToGroup(sender, groupId, message = \".\", attachment = None):\n\n \n command = \"/usr/local/bin/signal-cli -u \" + sender + \" send \" + \"-g \" + groupId + \" -m \\\"\" + message + \"\\\"\"\n \n if attachment != None:\n command = command + \" -a \\\"\" + attachment + \"\\\"\"\n \n call(command, shell=True)\n \n\nsender = constant.SENDER\nrecipient = constant.RECIPIENT\ncorona_group = constant.CORONA_GROUP\n \n# download new data\ndownloader = Downloader()\ndownloader.download()\n\n\nfiles = glob.glob(\"../data/*.csv\")\nlist_of_dfs = [pd.read_csv(file,dtype={\"gemeindeschluessel\": str}) for file in files]\n\n\nfor dataframe, filename in zip(list_of_dfs, files):\n dataframe[\"filename\"] = filename.split(\"/\")[-1]\n\n\ndf = pd.concat(list_of_dfs, ignore_index=True)\n\ndf = df.drop(\"Unnamed: 0\",axis=1)\ndf = df.drop(\"kreis\",axis=1)\ndf = df.drop(\"faelle_covid_aktuell_im_bundesland\",axis=1)\n\n\ndf[\"daten_stand\"] = df.apply(lambda x: datenstand(x), axis=1)\n\ndf[\"daten_stand\"] = pd.to_datetime(df[\"daten_stand\"])\n\n\n# droppe 24.04. und 25.04, da diese keine Corona-Fallzahlen enthalten\ndf = df[~df[\"faelle_covid_aktuell_beatmet\"].isna()]\ndf = df[~df[\"faelle_covid_aktuell\"].isna()]\n\n\ndf[\"betten_gesamt\"] = df[\"betten_frei\"] + df[\"betten_belegt\"]\ndf[\"anteil_belegt\"] = df[\"betten_belegt\"] / df[\"betten_gesamt\"]\n\n\nbundeslaender = pd.read_csv(\"../master_data/bundeslaender.csv\")\n\n\ndf = df.merge(bundeslaender,how=\"left\",left_on=\"bundesland\",right_on = \"ID\")\n\n\ngemeinden = pd.read_pickle(\"../master_data/gemeindeschluessel\")\n\ndf = df.merge(gemeinden, how=\"left\", on=\"gemeindeschluessel\")\n\ntagessicht = df.groupby(\"daten_stand\").sum().reset_index().drop(\"anteil_belegt\",axis=1)\n\ntagessicht = tagessicht.drop([\"bundesland\",\"anzahl_meldebereiche\"],axis=1)\n\n\ntagessicht[\"wochentag\"] = tagessicht[\"daten_stand\"].dt.day_name()\ntagessicht[\"woche\"] = tagessicht[\"daten_stand\"].dt.isocalendar().week\n\n\ntagessicht[\"anteil_belegt\"] = tagessicht[\"betten_belegt\"] / tagessicht[\"betten_gesamt\"]\n\ntagessicht[\"anteil_beatmet\"] = tagessicht[\"faelle_covid_aktuell_beatmet\"] / tagessicht[\"faelle_covid_aktuell\"]\n\ntagessicht[\"anteil_corona_patienten\"] = tagessicht[\"faelle_covid_aktuell\"] / tagessicht[\"betten_belegt\"]\n\n\ndaten_stand = tagessicht.iloc[tagessicht[\"daten_stand\"].argmax()][\"daten_stand\"]\npatienten = int(tagessicht.iloc[tagessicht[\"daten_stand\"].argmax()][\"faelle_covid_aktuell\"])\nbeatmet = int(tagessicht.iloc[tagessicht[\"daten_stand\"].argmax()][\"faelle_covid_aktuell_beatmet\"])\n\nanteil_belegt = tagessicht.iloc[tagessicht[\"daten_stand\"].argmax()][\"anteil_belegt\"]\nanteil_belegt = round(anteil_belegt * 100,2)\n\nanteil_beatmet = tagessicht.iloc[tagessicht[\"daten_stand\"].argmax()][\"anteil_beatmet\"]\nanteil_beatmet = round(anteil_beatmet * 100,2)\n\nanteil_corona = tagessicht.iloc[tagessicht[\"daten_stand\"].argmax()][\"anteil_corona_patienten\"]\nanteil_corona = round(anteil_corona * 100,2)\ndelta_corona = tagessicht[\"anteil_corona_patienten\"].pct_change().iloc[-1]\ndelta_corona = round(delta_corona * 100,3)\nsign_corona = \"+\" if delta_corona > 0 else \"\"\n\nmessage = \"\"\"Datenstand: {}\n\nITS-Patienten: {}\nbeatmet: {}\nAnteil beatmet: {}%\n\nBelegte Betten insgesamt: {}%\n\nAnteil Corona-Patienten an belegten Betten: {}%\nVeränderung zum Vortag: {}{}%\n\"\"\".format(daten_stand,patienten,beatmet,anteil_beatmet,anteil_belegt, anteil_corona,sign_corona,delta_corona)\n\nsendMessageToGroup(sender, corona_group, message)\n\n\n### Gesamtsicht Patienten vs beatmet\nplt.figure(figsize=(17,6))\nplot = tagessicht[[\"daten_stand\",\"faelle_covid_aktuell\",\"faelle_covid_aktuell_beatmet\"]].set_index(\"daten_stand\")\ng = sns.lineplot(data=plot)\ng.set_title(\"Patienten auf ITS vs. beatmetete Patienten\")\nplt.savefig(\"patienten.png\")\n\nchange_patienten = int(tagessicht[\"faelle_covid_aktuell\"].diff().iloc[-1])\nchange_patienten_beatmet = int(tagessicht[\"faelle_covid_aktuell_beatmet\"].diff().iloc[-1])\n\nsign_pat = \"+\" if change_patienten > 0 else \"\"\nsign_beat = \"+\" if change_patienten_beatmet > 0 else \"\"\n\nmessage = \"\"\"Patienten-Statistik\n\nÄnderungen zum Vortag:\nPatienten auf ITS: {sign_pat}{change_patienten}\nBeatmetete Patienten: {sign_beat}{change_pat_beatmet}\n\"\"\".format(sign_pat=sign_pat,change_patienten=change_patienten, sign_beat=sign_beat, change_pat_beatmet=change_patienten_beatmet)\n\nsendMessageToGroup(sender, corona_group, message,\"patienten.png\")\n\n## Anteil belegter Betten\nplt.figure(figsize=(17,6))\ng = sns.lineplot(x=\"daten_stand\",y=\"anteil_belegt\",data=tagessicht)\ng.axhline(1,color=\"red\")\ng.set_title(\"Zeitreihe: Anteil belegter Betten\")\ng.set_ylim(0,1.2)\ng.set_yticklabels(['{:,.0%}'.format(x) for x in g.get_yticks()])\nplt.savefig(\"anteil_belegt.png\")\n\nchange_belegt = tagessicht[\"anteil_belegt\"].pct_change().iloc[-1]\nchange_belegt = round(change_belegt,3)\n\nsign = \"+\" if change_belegt > 0 else \"\"\n\n#print(anteil_belegt)\nmessage = \"\"\"Betten-Belegung\n\nAktuell belegt: {anteil_belegt}%\nVeränderung zum Vortag: {sign}{change_belegt}%\n\"\"\".format(anteil_belegt=anteil_belegt, sign=sign, change_belegt=change_belegt)\n\nsendMessageToGroup(sender, corona_group, message,\"anteil_belegt.png\")\n\n### Gesamtauslastung vs. Anteil Corona-Patienten und Anteil beatmet\nplt.figure(figsize=(17,6))\nplot = tagessicht[[\"daten_stand\",\"anteil_belegt\",\"anteil_corona_patienten\",\"anteil_beatmet\"]].set_index(\"daten_stand\")\ng = sns.lineplot(data=plot)\ng.set_ylim(0,1)\ng.set_yticklabels(['{:,.0%}'.format(x) for x in g.get_yticks()])\ng.set_title(\"Gesamtauslastung vs. Anteil Corona-Patienten und Anteil beatmet\")\nplt.savefig(\"anteile_auslastung_corona.png\")\n\nmessage = \"Gesamtauslastung vs. Anteil Corona-Patienten (gesamt vs. beatmet)\"\nsendMessageToGroup(sender, corona_group, message,\"anteile_auslastung_corona.png\")\n\n" }, { "alpha_fraction": 0.4054969847202301, "alphanum_fraction": 0.4194277226924896, "avg_line_length": 31.530864715576172, "blob_id": "f285c43de6efb9601c356305dc714838f62d2a17", "content_id": "bea61558303b5e5f3bcea7ed7fd001d10d77af42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2656, "license_type": "no_license", "max_line_length": 129, "num_lines": 81, "path": "/analysis/Helper.py", "repo_name": "orSpec/corona_signal_bot", "src_encoding": "UTF-8", "text": "import requests\nimport re\nimport os.path\nfrom datetime import date\n\n\nclass Downloader:\n def __init__(self):\n pass\n \n def download(self):\n \n path = \"../data/\"\n\n base = \"https://www.divi.de/joomlatools-files/docman-files/divi-intensivregister-tagesreports-csv/DIVI-Intensivregister_\"\n times = [\"09-15\",\"12-15\"]\n \n months = list(range(1,13))\n days = list(range(1,32))\n years = [2020,2021]\n\n today = date.today()\n\n firstDate = date(2020,5,1)\n \n not_succesful = []\n\n for year in years:\n for month in months:\n month_nr = month\n month = str(month).zfill(2)\n for day in days:\n \n try:\n dateToDownload = date(year,month_nr,day)\n \n if dateToDownload > today:\n print(\"[INFO] {} in future, not downloading\".format(dateToDownload))\n continue\n\n if dateToDownload < firstDate:\n print(\"[INFO] {} too early, not downloading\".format(dateToDownload))\n continue\n \n except ValueError:\n print(\"[ERROR] {}-{}-{} doesn't exist, skipping\".format(year,month,day))\n continue\n\n\n \n day = str(day).zfill(2)\n \n downloaded = False\n \n filename = path + \"DIVI-Intensivregister_2020-\" + month + \"-\" + day + \".csv\"\n \n # if already download, skip\n if os.path.isfile(filename):\n print(\"[INFO] Already downloaded: {}\".format(filename))\n continue\n \n for time in times:\n url = base + str(year) + \"-\" + month + \"-\" + day + \"_\" + time + \".csv\"\n\n r = requests.get(url) \n if r.status_code == 404:\n output = \"-----Not valid: \" + month + \"-\" + day + \"_\" + time\n continue\n else:\n\n open(filename, 'wb').write(r.content)\n output = \"[SUCESS] Downloaded \" + month + \"-\" + day + \"_\" + time\n print(output)\n downloaded = True\n break\n \n if not downloaded:\n file = month + \"-\" + day\n not_succesful.append(file)\n output = \"--------Not succesful: \" + month + \"-\" + day\n print(output)\n \n" }, { "alpha_fraction": 0.7537857294082642, "alphanum_fraction": 0.802579939365387, "avg_line_length": 70.23999786376953, "blob_id": "9f9223d94ccb4f0f2911bdcfada412de04b9f5dc", "content_id": "d04c216561b3cc912fabb231a812ed7b21486e4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1795, "license_type": "no_license", "max_line_length": 362, "num_lines": 25, "path": "/README.md", "repo_name": "orSpec/corona_signal_bot", "src_encoding": "UTF-8", "text": "\n# Corona Signal Bot\nMithilfe des Codes können die tagesaktuellen Reports des [DIVI-Intensivregisters](https://www.divi.de/register/tagesreport) heruntergeladen werden. Basierend auf den aktuellen und zurückliegenden Reports werden Auswertungen durchgeführt, z.B.\n\n - Anzahl der Patienten auf der Intensivstation und beatmetete Patienten:\n<img src=\"https://user-images.githubusercontent.com/59450716/103759097-73a92e00-5013-11eb-99de-91affd22bc13.png\" width=\"1200\">\n\n - Gesamtauslastung des Systems, Anteil der Corona-Patienten, Anteil der beatmeten Corona-Patienten\n <img src=\"https://user-images.githubusercontent.com/59450716/103759256-bcf97d80-5013-11eb-96e2-326dbf9c3f19.png\" width=\"1200\">\n\nDie Auswertungen können dann mithilfe von [signal-cli](https://github.com/AsamK/signal-cli), einem Kommandozeilen-Interface für die Bibliothek [signal-service-java](https://github.com/signalapp/libsignal-service-java) (Java-Bibliothek für die Kommunikation mit dem Messengerdienst Signal) zu einem einzelnen Empfänger oder an eine Signal-Gruppe geschickt werden.\n\nUnter Linux kann z.B. mithilfe von cron eingerichtet werden, dass das Python-Programm jeden Tag zu einer bestimmten Uhrzeit ausgeführt wird und aktuelle Auswertungen an die Empfänger pusht:\nCron Expression für eine Ausführung jeden Tag um 13 Uhr Systemzeit:\n`0 13 * * * python /path/to/analysis.py`\n\n### Module / Technologien\n - pandas\n - numpy\n - matplotlib\n - seaborn\n - [signal-cli](https://github.com/AsamK/signal-cli) (auf ausführendem System installiert und mit registrierter Rufnummer zum Versenden von Nachrichten)\n\n### Daten\n - tagesaktuelle Reports von [DIVI-Intensivregister](https://www.divi.de/register/tagesreport)\n - Gemeindeverzeichnis von [Github/digineo](https://github.com/digineo/gemeindeverzeichnis)\n\n" }, { "alpha_fraction": 0.7761194109916687, "alphanum_fraction": 0.7761194109916687, "avg_line_length": 15.75, "blob_id": "ec3354ba12206d1b476271d704b24a442d45e3da", "content_id": "7cb4226888fb2e6f71e6464c105f6aed9cb6de92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 29, "num_lines": 4, "path": "/analysis/download.py", "repo_name": "orSpec/corona_signal_bot", "src_encoding": "UTF-8", "text": "from Helper import Downloader\n\ndown = Downloader()\ndown.download()\n" } ]
4
grvahuja205/Log-Analyzer
https://github.com/grvahuja205/Log-Analyzer
b31a7170f9de1d8f40a2cf8360131b68b8053177
c6334372c206ad0c14a8725ad12c9c47d5ecd978
a24a08e688d6cee7ab441e79d37602e20772c273
refs/heads/master
2021-01-01T06:09:31.897703
2017-07-16T10:00:46
2017-07-16T10:00:46
97,373,572
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5587229132652283, "alphanum_fraction": 0.5729760527610779, "avg_line_length": 38.8636360168457, "blob_id": "448b5618522c8e542bde605549dd4c6da417566f", "content_id": "57fcd9fab7296736a59d1610887952448262520a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1754, "license_type": "no_license", "max_line_length": 79, "num_lines": 44, "path": "/log_analysis.py", "repo_name": "grvahuja205/Log-Analyzer", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport psycopg2\n\n\ndef logAnalyzer():\n try:\n # Connecting to postgres database\n conn = psycopg2.connect(\"dbname='news' user='postgres'\\\n password='root'\")\n cur = conn.cursor()\n # TopArticles is a view in database fetching the top articles\n # by articles visted\n cur.execute(r\"SELECT * FROM TopArticles\")\n rows = cur.fetchall()\n print \"The top 3 articles are\"\n i = 0\n while i < 3: # For displaying the top 3 results\n print \"%s--%d views\" % (rows[i][0], float(rows[i][1]))\n i = i+1\n # PopularAuthor is a view in database dispalying the name of the author\n # having views in sorted order by total number of pages authored\n # by them in decreasing order\n cur.execute(r\"SELECT * FROM PopularAuthor\")\n print \"\\nThe most popular authors are:\"\n nv_rows = cur.fetchall()\n for nv_row in nv_rows:\n print \"%s--%d views\" % (nv_row[1], float(nv_row[0]))\n # ErrorsPercent is a view in database\n # representing the total no of times the pages are visisted\n # and the total number of times the request resulted in failure code\n cur.execute(\"SELECT * FROM ErrorsPercent\")\n print \"\\nThe date on which failure was mor than 1 Percent are\"\n p_rows = cur.fetchall()\n for p_row in p_rows:\n if (float(p_row[2])/float(p_row[1])*100) > 1.0:\n per = float(p_row[2])/float(p_row[1])*100\n print \"%s--%f\" % (p_row[0], per)+\"%\"\n except Exception as e:\n raise e\n finally:\n conn.close() # Closing The Database Connection\n\nif __name__ == '__main__':\n logAnalyzer()\n" }, { "alpha_fraction": 0.7191260457038879, "alphanum_fraction": 0.7251424789428711, "avg_line_length": 67.65217590332031, "blob_id": "7f74a0f58bbca0721f9dc6a1b7c0a952a2fab245", "content_id": "8256424a70fd3b0a6da4dc9564d99c7a00bc5194", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3158, "license_type": "no_license", "max_line_length": 455, "num_lines": 46, "path": "/README.md", "repo_name": "grvahuja205/Log-Analyzer", "src_encoding": "UTF-8", "text": "# Log Analyzer\nThis project analyzes a database using SQL queries to produce 3 outputs,\n* What are the most popular three articles of all time?\n* Who are the most popular article authors of all time?\n* On which days did more than 1% of requests lead to errors? \n\nThe databse has data about the articles published the authors who published them and a web server logs showing the details of the articles visted on online, this database is having 3 tables,\n* articles\n* authors\n* log\n## Requirements\n- Python needs to be installed, you may install python from [here](https://www.python.org/downloads/)\n- Postgres SQL needs to be installed, you may install posstgres from [here](https://www.postgresql.org/download/) \n- Configure the database to use account 'postgres' using this [link](https://help.ubuntu.com/stable/serverguide/postgresql.html)\n\n## Usage\n* Clone the repository to a local directory on your system\n* Run the following commnds to create database news having the 3 tables using command line,\n ```\n psql -U postgres -W (Will Prompt For Password)\n CREATE DATABASE news;\n ```\n* Quit from database using, ```\\q``` from same command line\n* To create tables use the following commands, first download the file ```newsdata.sql``` from Udacity as given in the course,\n ```\n cd <path file newsdata.sql>\n psql -U postgres -d news -f newsdata.sql -W(prompt for password)\n psql -U postgres -d news -W(prompt for password)\n ```\n* Now you are connected to 'news' database and have the 3 tables created, next step is to create the 3 views from which we are going to run the queries to have the output\n ```\n CREATE VIEW TopArticles AS SELECT articles.title, anv.num from ARTICLES, (select split_part(log.path, '/', 3) as slug_log, COUNT(*) as num from log GROUP BY slug_log HAVING length(split_part(log.path, '/', 3)) >1 ORDER BY num desc) as anv WHERE articles.slug=anv.slug_log;\n ```\n ```\n CREATE VIEW PopularAuthor AS SELECT SUM(nv.slug_log) as nviews, authors.name FROM authors, articles, (SELECT COUNT(split_part(log.path, '/', 3)) as slug_log, articles.title AS title FROM log, articles WHERE split_part(log.path, '/', 3) = articles.slug GROUP BY articles.title order by slug_log desc) AS nv WHERE articles.author = authors.id AND nv.title = articles.title GROUP BY authors.name ORDER BY nviews DESC;\n ```\n ```\n CREATE VIEW ErrorsPercent AS SELECT t.mdate AS ndate, t.ctotal AS total, er.failure AS fail FROM (SELECT date(time) as mdate, CAST(count(*) AS INTEGER) AS ctotal FROM log GROUP BY mdate ORDER BY mdate) AS t,(SELECT date(time) AS cdate, CAST(count(*) AS INTEGER) AS failure FROM log WHERE CAST(split_part(status, ' ', 1) AS INTEGER) >399 AND CAST(split_part(status, ' ', 1) AS INTEGER) < 600 GROUP BY cdate ORDER BY cdate) AS er WHERE t.mdate=er.cdate;\n ```\n* Last step is to run the python file in the repository, open up the command prompt and run the follwing commands,\n ```\n cd <path to cloned repository>\n python log_analysis.py\n ```\n* For sample output look at file ```output.txt```, the same will appear on the command line where you run the above python file.\n## License\n" } ]
2
banditti99/leaguepedia_util
https://github.com/banditti99/leaguepedia_util
47ef740cafd710143a01ff99750e63953d7e6405
a2a3ef416c299ee5b4592a13e24d75fa59ab06b0
b14a4da3c568f3cb2c37d1fd14bd91ab31f26354
refs/heads/master
2020-08-17T09:54:47.948007
2019-10-06T09:45:15
2019-10-06T09:45:15
215,649,007
0
0
null
2019-10-16T21:37:36
2019-10-11T20:44:07
2019-10-11T20:44:05
null
[ { "alpha_fraction": 0.6861924529075623, "alphanum_fraction": 0.6868898272514343, "avg_line_length": 28.875, "blob_id": "20f1adde6907c070cb6f82b8d42feb934a7df69c", "content_id": "bab9a12b9cc96101ffed8ca7627b37e8597d7db3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 93, "num_lines": 48, "path": "/esports_site.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from extended_site import GamepediaSite\n\nALL_ESPORTS_WIKIS = ['lol', 'halo', 'smite', 'vg', 'rl', 'pubg', 'fortnite',\n\t\t\t\t\t 'apexlegends', 'fifa', 'gears', 'nba2k', 'paladins', 'siege',\n\t\t\t\t\t 'default-loadout', 'commons', 'teamfighttactics']\n\ndef get_wiki(wiki):\n\tif wiki in ['lol', 'teamfighttactics'] or wiki not in ALL_ESPORTS_WIKIS:\n\t\treturn wiki\n\treturn wiki + '-esports'\n\nclass EsportsSite(GamepediaSite):\n\tdef __init__(self, user, wiki):\n\t\tsuper().__init__(user, get_wiki(wiki))\n\t\tself.user = user\n\t\tself.wiki = wiki\n\t\n\tdef standard_name_redirects(self):\n\t\tfor item in self.cargoquery(\n\t\t\ttables=\"Tournaments,_pageData\",\n\t\t\tjoin_on=\"Tournaments.StandardName_Redirect=_pageData._pageName\",\n\t\t\twhere=\"_pageData._pageName IS NULL AND Tournaments.StandardName_Redirect IS NOT NULL\",\n\t\t\tfields=\"Tournaments.StandardName_Redirect=Name,Tournaments._pageName=Target\",\n\t\t\tlimit=\"max\"\n\t\t):\n\t\t\tpage = self.pages[item['Name']]\n\t\t\ttarget = item['Target']\n\t\t\tpage.save('#redirect[[%s]]' % target, summary=\"creating needed CM_StandardName redirects\")\n\t\n\tdef other_wikis(self):\n\t\tfor wiki in ALL_ESPORTS_WIKIS:\n\t\t\tif wiki == self.wiki:\n\t\t\t\tcontinue\n\t\t\tyield wiki\n\t\n\tdef other_sites(self):\n\t\tfor wiki in self.other_wikis():\n\t\t\tyield EsportsSite('me', wiki)\n\t\n\t@staticmethod\n\tdef all_wikis():\n\t\tfor wiki in ALL_ESPORTS_WIKIS:\n\t\t\tyield wiki\n\t\n\t@staticmethod\n\tdef all_sites(user):\n\t\tfor wiki in ALL_ESPORTS_WIKIS:\n\t\t\tyield EsportsSite(user, wiki)\n" }, { "alpha_fraction": 0.6786050796508789, "alphanum_fraction": 0.6804900765419006, "avg_line_length": 25.524999618530273, "blob_id": "b162710ec77f2b0c0826cfc7d2ccf8a169abfe6e", "content_id": "012a908d17dc357a91e69a5fd8751c278ddbd0eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 92, "num_lines": 40, "path": "/top_schedule_refresh.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\n\nwikis = [ 'lol', 'cod-esports' ]\n\nto_purges = {\n\t'lol' : ['League of Legends Esports Wiki', 'Match History Index'],\n\t'cod-esports' : ['Call of Duty Esports Wiki']\n}\n\nto_blank_edit = ['Project:Top Schedule', 'Project:Matches Section/Matches',\n\t\t\t\t\t 'Project:Matches Section/Results']\n\nto_blank_edits = {\n\t'lol' : ['Project:Korizon Standings']\n}\n\ndef blank_edit_pages(site, ls):\n\tfor name in ls:\n\t\tp = site.pages[name]\n\t\tp.save(p.text(), summary='blank editing')\n\nfor wiki in wikis:\n\tsite = login('me',wiki)\n\t\n\tblank_edit_pages(site, to_blank_edit)\n\tif wiki in to_blank_edits.keys():\n\t\tblank_edit_pages(site, to_blank_edits[wiki])\n\t\n\tfor name in to_purges[wiki]:\n\t\tsite.pages[name].purge()\n\t\n\tresult = site.api('expandtemplates', format='json',\n\t\t\t\t\tprop = 'wikitext',\n\t\t\t\t\ttext = '{{Project:Template/Current Tournaments Section}}'\n\t)\n\t\n\ttext = result['expandtemplates']['wikitext']\n\t\n\tp2 = site.pages['Project:Current Tournaments Section']\n\tp2.save(text, summary = 'Automatically updating Current Tournaments',tags='daily_errorfix')\n" }, { "alpha_fraction": 0.6901840567588806, "alphanum_fraction": 0.696319043636322, "avg_line_length": 26.16666603088379, "blob_id": "3e607040e09f9fd1023fff558b4f9a4f97c5ce61", "content_id": "8c7e7e07c45db80c4faacebfdcebb11851046c4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 326, "license_type": "no_license", "max_line_length": 66, "num_lines": 12, "path": "/patrol_namespaces.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import log_into_wiki\n\nnamespaces = ['User:', 'Predictions:']\nsite_names = ['lol', 'cod-esports']\ninterval = 10\n\ndef do_we_patrol(revision):\n\treturn [_ for _ in namespaces if revision['title'].startswith(_)]\n\nfor site_name in site_names:\n\tsite = log_into_wiki.login('me', site_name)\n\tsite.patrol_recent(interval, do_we_patrol)\n" }, { "alpha_fraction": 0.6379928588867188, "alphanum_fraction": 0.6415770649909973, "avg_line_length": 23.2608699798584, "blob_id": "8f5514d12793fa1c07fbb3be0a261990154e0beb", "content_id": "6b7387e9232cbbbd45a22276d07dfcaefdd807fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 52, "num_lines": 23, "path": "/refresh_teamnames_cron.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\nimport luacache_refresh, datetime\n\nsite = login('me', 'lol')\n\nnow = datetime.datetime.utcnow()\nthen = now - datetime.timedelta(minutes=1)\n\nrevisions = site.api('query',\n\t\t\t\t\t list=\"recentchanges\",\n\t\t\t\t\t rcstart = now.isoformat(),\n\t\t\t\t\t rcend = then.isoformat(),\n\t\t\t\t\t rcprop = 'title',\n\t\t\t\t\t rclimit = 'max',\n\t\t\t\t\t rctoponly = '1',\n\t\t\t\t\t rcdir = 'older'\n\t\t\t\t\t )\n\nfor revision in revisions['query']['recentchanges']:\n\tprint(revision['title'])\n\tif revision['title'] == 'Module:Teamnames':\n\t\tluacache_refresh.teamnames(site)\n\t\tbreak\n" }, { "alpha_fraction": 0.6579804420471191, "alphanum_fraction": 0.6677524447441101, "avg_line_length": 17.606060028076172, "blob_id": "4818e281d69b4587bb593f5b6b22dc1d7609dff4", "content_id": "07a520a3a9542934a2b8f1cfceebb0edbd8e10ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 47, "num_lines": 33, "path": "/touch.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\nimport time\nlimit = -1\nsite = login('me','cavesofqud')\nt = site.pages[\"Template:Item Page\"]\n\npages = t.embeddedin()\n\nc = site.categories['Pages with script errors']\n\npages = site.allpages(namespace=0)\n\nstartat_page = 'Burrowing Claws'\npassed_startat = False\n\nlmt = 0\n#for p in c:\nfor p in pages:\n\tif lmt == limit:\n\t\tbreak\n\tif p.name == startat_page:\n\t\tpassed_startat = True\n\tif not passed_startat:\n\t\tcontinue\n\tlmt += 1\n\tprint(p.name)\n\ttext = p.text()\n\ttry:\n\t\tp.save(text,'blank editing')\n\texcept Exception as e:\n\t\tprint('uh oh!!!!!!!!')\n\t\ttime.sleep(10)\n\t\tp.save(text, 'blank editing')\n" }, { "alpha_fraction": 0.6609508991241455, "alphanum_fraction": 0.6640685796737671, "avg_line_length": 27.511110305786133, "blob_id": "3a24ffc18ad61571d77a00626ce5d362879e6a0a", "content_id": "507481374ffa4fa13fee6db1470d710222c2ceac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1283, "license_type": "no_license", "max_line_length": 71, "num_lines": 45, "path": "/!!scratch.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\nimport mwparserfromhell\n\nsite = login('me', 'lol') # Set wiki\nsummary = '|sub=Yes |trainee=Yes & take out of |status=' # Set summary\n\nlimit = -1\nstartat_page = None\nprint(startat_page)\n# startat_page = 'asdf'\nthis_template = site.pages['Template:RCInfo'] # Set template\npages = this_template.embeddedin()\n\n# with open('pages.txt', encoding=\"utf-8\") as f:\n# \tpages = f.readlines()\n\npassed_startat = False if startat_page else True\nlmt = 0\nfor page in pages:\n\tif lmt == limit:\n\t\tbreak\n\tif startat_page and page.name == startat_page:\n\t\tpassed_startat = True\n\tif not passed_startat:\n\t\tprint(\"Skipping page %s\" % page.name)\n\t\tcontinue\n\tlmt += 1\n\ttext = page.text()\n\twikitext = mwparserfromhell.parse(text)\n\tfor template in wikitext.filter_templates():\n\t\tif tl_matches(template, ['RCInfo']):\n\t\t\tif template.has('status'):\n\t\t\t\tif template.get('status').value.strip().lower() == 'sub':\n\t\t\t\t\ttemplate.add('sub', 'Yes')\n\t\t\t\t\ttemplate.add('status', '')\n\t\t\t\tif template.get('status').value.strip().lower() == 'trainee':\n\t\t\t\t\ttemplate.add('trainee', 'Yes')\n\t\t\t\t\ttemplate.add('status', '')\n\n\tnewtext = str(wikitext)\n\tif text != newtext:\n\t\tprint('Saving page %s...' % page.name)\n\t\tpage.save(newtext, summary=summary)\n\telse:\n\t\tprint('Skipping page %s...' % page.name)\n" }, { "alpha_fraction": 0.6516308188438416, "alphanum_fraction": 0.6564885377883911, "avg_line_length": 36.94736862182617, "blob_id": "d3b70c0e04cbaef3bd3549d7c4fdef9c0a93f5b2", "content_id": "0c990f6a26cd266a76cc008d41adf6a28b3a44d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1441, "license_type": "no_license", "max_line_length": 111, "num_lines": 38, "path": "/sprites_cachebreak.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\nimport re\n\nsite = login('me', 'lol')\nsummary = 'Bot Edit - Automatically Forcing Sprite Cache Update'\nurl_re_start = r'.*(\\/.\\/..\\/)'\nurl_re_end = r'(\\?version=\\w*)\\\".*'\ncss_page_list = ['MediaWiki:Common.css', 'MediaWiki:Mobile.css']\n\ncategory_result = site.api('query', list = 'categorymembers', cmtitle = 'Category:Sprite Images', cmlimit = 50)\nfile_name_list = [_['title'] for _ in category_result['query']['categorymembers']]\n\nparse_text_list = ['[[%s|link=]]' % _ for _ in file_name_list]\nparse_text = '!!!'.join(parse_text_list)\nresult = site.api('parse', text = parse_text, title = 'Main Page', disablelimitreport = 1)\ntext = result['parse']['text']['*']\n\ncss_texts_old = []\ncss_texts_new = []\nfor file_name in file_name_list:\n\traw_name = file_name.replace('File:', '')\n\tre_full = url_re_start + re.escape(raw_name) + url_re_end\n\tmatch = re.match(re_full, text)\n\tcss_texts_new.append(match[1] + raw_name + r'\\1' + match[2])\n\tcss_texts_old.append(re.escape(match[1] + raw_name) + r'(.*)' + r'\\?version=\\w*')\n\t\ndef replace_css_in_file(css_page):\n\tcss_page_text = css_page.text()\n\tcss_page_text_new = css_page_text\n\tfor i, v in enumerate(css_texts_old):\n\t\tcss_page_text_new = re.sub(v, css_texts_new[i], css_page_text_new)\n\tif css_page_text != css_page_text_new:\n\t\tcss_page.save(css_page_text_new, summary = summary)\n\nfor page_name in css_page_list:\n\treplace_css_in_file(site.pages[page_name])\n\nprint('Ran!')" }, { "alpha_fraction": 0.647814929485321, "alphanum_fraction": 0.6580976843833923, "avg_line_length": 21.882352828979492, "blob_id": "e9d462d93212ada19a57594689976b2ce4ad5c58", "content_id": "2ace30a72e42667f2643850f3ea113bc0aee4434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 60, "num_lines": 17, "path": "/lol_archive_compare.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from esports_site import EsportsSite\n\narchive = EsportsSite('me', 'lol-archive')\nlive = EsportsSite('me', 'lol')\n\npages = []\n\nfor page in archive.allpages(namespace=0):\n\tpages.append((page.name, live.pages[page.name].exists))\n\ntext = []\n\nfor p in pages:\n\ttext.append('{}\\t{}'.format(p[0], str(p[1])))\n\nwith open('archive_pages.txt', 'w+', encoding=\"utf-8\") as f:\n\tf.write('\\n'.join(text))\n" }, { "alpha_fraction": 0.6225165724754333, "alphanum_fraction": 0.6291390657424927, "avg_line_length": 19.827587127685547, "blob_id": "4842184ccf6d5c73614e6e2d49dff6995f41683e", "content_id": "05e5a472eb699227c298c4ef57e70f965ee8868e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 69, "num_lines": 29, "path": "/blank_edit_players_from_league.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\nlimit = -1\nsite = login('me','lol')\n\nwith open('pages.txt', encoding=\"utf-8\") as f:\n\ttournaments = f.readlines()\n\t\npages = set()\n\nfor tournament in tournaments:\n\tresponse = site.api('cargoquery',\n\t\ttables = 'ScoreboardPlayer',\n\t\twhere = 'OverviewPage=\"%s\"' % tournament.strip().replace('_', ' '),\n\t\tfields = 'Link',\n\t\tgroup_by = 'Link'\n\t)\n\tfor item in response['cargoquery']:\n\t\tpages.add(item['title']['Link'])\n\nlmt = 0\nfor page in pages:\n\tif lmt == limit:\n\t\tbreak\n\tp = site.pages[page]\n\tlmt += 1\n\tprint(p.name)\n\ttext = p.text()\n\tif text != '':\n\t\tp.save(text,'blank editing')\n" }, { "alpha_fraction": 0.6493848562240601, "alphanum_fraction": 0.6520211100578308, "avg_line_length": 31.514286041259766, "blob_id": "c9dedab0477e97ee22786425eb5fbfa085a6ad71", "content_id": "638f87042373d425254bb061afbeb833b1d9785d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 94, "num_lines": 35, "path": "/rune sprite.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import urllib.request, time, sprite_creator, io, os\nfrom log_into_wiki import *\n\nSUFFIX = ''\nSPRITE_NAME = 'SmiteRole'\nIMAGE_DIR = 'Sprites/' + SPRITE_NAME + ' Images'\nTEAM_DATA_FILE_LOCATION = SPRITE_NAME + 'Sprite' + SUFFIX + '.txt'\nFILE_TYPE = 'png'\nlimit = -1\nstartat = None\n\nsite = login('me', 'smite-esports')\nsite_lol = login('me', 'lol')\n\nif not os.path.exists(IMAGE_DIR):\n os.makedirs(IMAGE_DIR)\n\ndef get_country_name(file_name):\n\treturn file_name.replace('.' + FILE_TYPE, '').replace('File:', '').replace('Square','')\n\npattern = r'.*src\\=\\\"(.+?)\\\".*'\ncat = site.categories['Role Icons']\nfor page in cat:\n\tto_parse_text = '[[%s|link=]]' % page.name\n\tresult = site.api('parse', title = 'Main Page', text = to_parse_text, disablelimitreport = 1)\n\tparse_result_text = result['parse']['text']['*']\n\turl = re.match(pattern, parse_result_text)[1]\n\timage = urllib.request.urlopen(url).read()\n\t# image = Image.open(io.BytesIO(urllib.request.urlopen(url).read()))\n\tcountry = get_country_name(page.name)\n\timage_path = IMAGE_DIR + '/' + country + '.' + FILE_TYPE\n\tprint(image_path)\n\tf = open(image_path, 'wb')\n\tf.write(image)\n\tf.close()\n" }, { "alpha_fraction": 0.6662452816963196, "alphanum_fraction": 0.6705998182296753, "avg_line_length": 31.80645179748535, "blob_id": "3121647353b822aee4e8b7d8251c4a47767b6761", "content_id": "29f7e1207b32a803add5d588f4c4d136d632898d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7119, "license_type": "no_license", "max_line_length": 97, "num_lines": 217, "path": "/disambig_creation.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import re, threading, mwparserfromhell\nfrom log_into_wiki import *\n\n#################################################################################################\n\noriginal_name = 'Awaker'\nirl_name = \"Kentaro Hanaoka\"\nnew_name = '{} ({})'.format(original_name, irl_name.strip())\ninit_move = True\nblank_edit = False\nlimit = -1\ntimeout_limit = 30\n\nlistplayer_templates = [\"listplayer\", \"listplayer/Current\"]\nroster_templates = [\"ExtendedRosterLine\", \"ExtendedRosterLine/MultipleRoles\"]\nscoreboard_templates = [\"MatchRecapS8/Player\",\"Scoreboard/Player\"]\nstat_templates = [\"IPS\", \"CareerPlayerStats\", \"MatchHistoryPlayer\"]\nplayer_line_templates = [\"LCKPlayerLine\", \"LCSPlayerLine\"]\nroster_change_templates = [\"RosterChangeLine\", \"RosterRumorLine2\",\n\t\t\t\t\t\t \"RosterRumorLineStay\", \"RosterRumorLineNot\", \"RosterRumorLine\"]\nsummary = \"Disambiguating {} to {}\".format(original_name, new_name)\n\ncss_style = \" {\\n color:orange!important;\\n font-weight:bold;\\n}\"\n\norig_name_lc = original_name[0].lower() + original_name[1:]\nnew_name_lc = new_name[0].lower() + new_name[1:]\n\nblank_edit_these = []\n\n#############################################################################################\n\ndef savepage(targetpage, savetext):\n\ttargetpage.save(savetext, summary=summary, tags=\"bot_disambig\")\n\ndef blank_edit_page(page):\n\ttextname = str(page.name)\n\tnewpage = site.pages[textname]\n\ttext = newpage.text(cache=False)\n\tpage.save(text, summary=\"Blank Editing\")\n\ndef move_page(from_page):\n\tnew_page_name = str(from_page.name).replace(original_name, new_name)\n\tnew_page = site.pages[new_page_name]\n\tif new_page.exists:\n\t\tprint(\"{} already exists, cannot move!\".format(from_page.name))\n\telse:\n\t\tprint(\"Moving page {} to {}\".format(from_page.name, new_page_name))\n\t\tfrom_page.move(new_page_name, reason=summary, no_redirect=True)\n\t\tblank_edit_these.append(new_page)\n\ndef edit_concept(concept):\n\ttext = concept.text()\n\twikitext = mwparserfromhell.parse(text)\n\tfor template in wikitext.filter_templates():\n\t\tif template.name.matches(\"PlayerGamesConcept\"):\n\t\t\ti = 1\n\t\t\twhile template.has(i):\n\t\t\t\tif template.get(i).strip() == original_name:\n\t\t\t\t\ttemplate.add(i, new_name)\n\t\t\t\telif template.get(i).strip() == orig_name_lc:\n\t\t\t\t\ttemplate.add(i, new_name_lc)\n\t\t\t\ti = i + 1\n\tnewtext = str(wikitext)\n\tif newtext != text:\n\t\tconcept.save(newtext, summary=summary, tags=\"bot_disambig\")\n\ndef edit_subpage(subpage):\n\ttext = subpage.text()\n\twikitext = mwparserfromhell.parse(text)\n\tfor stemplate in wikitext.filter_templates():\n\t\tif stemplate.has(1):\n\t\t\tif stemplate.get(1).value.strip() == original_name:\n\t\t\t\tstemplate.add(1, new_name)\n\tnewtext = str(wikitext)\n\tif text != newtext:\n\t\tprint(\"Editing \" + subpage.name + \"...\")\n\t\tsubpage.save(newtext, reason=summary)\n\ndef process_page(page):\n\tprint(\"Processing next page: \" + page.name)\n\ttext = page.text()\n\torigtext = text\n\t# do links first because it's easier to just edit them as a string\n\tif text.lower().startswith('#redirect') and page.name.lower() == original_name.lower():\n\t\tpass\n\telse:\n\t\ttext = text.replace(\"[[\" + original_name + \"]]\", \"[[\" + new_name + \"|\" + original_name + \"]]\")\n\twikitext = mwparserfromhell.parse(text)\n\tfor template in wikitext.filter_templates():\n\t\tprocess_template(template)\n\tnewtext = str(wikitext)\n\tif origtext != newtext or blank_edit:\n\t\tprint(\"Saving...\")\n\t\tt = threading.Thread(target=savepage, kwargs={\"targetpage\": page, \"savetext\": newtext})\n\t\tt.start()\n\t\tt.join(timeout=timeout_limit)\n\telse:\n\t\tprint(\"No changes, skipping\")\n\ndef check_list(template, param, sep = ','):\n\tif not template.has(param):\n\t\treturn\n\ttext_initial = template.get(param).value.strip()\n\ttbl = text_initial.split(sep)\n\tmade_changes = False\n\tfor i, val in enumerate(tbl):\n\t\tif val.strip() == original_name:\n\t\t\tmade_changes = True\n\t\t\ttbl[i] = new_name\n\tif made_changes:\n\t\ttemplate.add(param, sep.join(tbl))\n\t\n\ndef process_template(template):\n\tdef tl_matches(arr, field=None):\n\t\tif field:\n\t\t\thas_field = False\n\t\t\tif template.has(field):\n\t\t\t\thas_field = template.get(field).value.strip() == original_name\n\t\t\treturn [_ for _ in arr if template.name.matches(_)] and has_field\n\t\treturn [_ for _ in arr if template.name.matches(_)]\n\t\n\tif tl_matches(['bl'], field=1) and not template.has(2):\n\t\ttemplate.add(1, new_name)\n\t\ttemplate.add(2, original_name)\n\n\telif tl_matches(listplayer_templates, field=1) and not template.has(\"link\"):\n\t\ttemplate.add(\"link\", new_name, before=1)\n\t\n\telif tl_matches(roster_templates, field='player') and not template.has('link'):\n\t\ttemplate.add(\"link\", new_name, before=\"name\")\n\t\n\telif tl_matches(scoreboard_templates, field='name'):\n\t\ttemplate.add(\"link\", new_name, before=\"kills\")\n\t\n\telif tl_matches(roster_change_templates, field='player'):\n\t\ttemplate.add(\"player\", new_name + \"{{!}}\" + original_name)\n\t\n\telif tl_matches(['TeamRoster/Line', 'RosterLineOld'], field='player'):\n\t\ttemplate.add('link', new_name)\n\t\n\telif tl_matches(player_line_templates, field=1):\n\t\ttemplate.add(2, new_name)\n\t\n\telif tl_matches(['Player', 'RSRR/Player'], field=1):\n\t\ttemplate.add('link', new_name)\n\t\t\t\t\n\telif tl_matches([\"MatchDetails/Series\"], field='mvp'):\n\t\ttemplate.add(\"mvplink\", new_name, before=\"mvp\")\n\t\t\n\telif tl_matches([\"PentakillLine\"], field=6):\n\t\ttemplate.add(\"playerlink\", new_name, before=6)\n\t\n\telif tl_matches([\"MatchSchedule\",\"MatchSchedule/Game\"]):\n\t\tif template.has(\"mvp\"):\n\t\t\tif template.get(\"mvp\").value.strip() == original_name:\n\t\t\t\ttemplate.add(\"mvp\", new_name)\n\t\tcheck_list(template, 'with')\n\t\tcheck_list(template, 'pbp')\n\t\tcheck_list(template, 'color')\n\t\n\telif tl_matches(['ExternalContent/Line']):\n\t\tcheck_list(template, 'players')\n\t\n\telif tl_matches(['SeasonAward']):\n\t\tif template.has(1):\n\t\t\tif template.get(1).value.strip() == original_name:\n\t\t\t\ttemplate.add('link', new_name)\n\t\tcheck_links(template, 'eligibleplayers', 'eligiblelinks', ',', original_name, new_name)\n\t\n\telif tl_matches(['PlayerImageMetadata'], field=\"playerlink\"):\n\t\ttemplate.add('playerlink', new_name)\n\t\n\telif tl_matches([\"PortalCurrentRosters\"]):\n\t\tfor pos in ['t', 'j', 'm', 'a', 's']:\n\t\t\tfor period in ['old', 'new']:\n\t\t\t\targ_name = pos + '_' + period\n\t\t\t\targ_link = arg_name + '_links'\n\t\t\t\tcheck_links(template, arg_name, arg_link, ',', original_name, new_name)\n\ndef make_disambig_page():\n\ttext = \"{{DisambigPage\\n|player1=\" + new_name + \"\\n|player2=\\n}}\"\n\tpage = site.pages[original_name]\n\told_text = page.text()\n\tif 'disambigpage' not in old_text.lower():\n\t\tpage.save(text, summary=summary)\n\nsite = login('me','lol')\n\nthispage = site.pages[original_name]\nnewpage = site.pages[new_name]\n\nif init_move:\n\tmove_page(thispage)\n\tsubpages = site.allpages(prefix=original_name + \"/\")\n\tfor subpage in subpages:\n\t\tedit_subpage(subpage)\n\t\tmove_page(subpage)\n\tconcept = site.pages[\"Concept:{}/Games\".format(original_name)]\n\tif concept.exists:\n\t\tedit_concept(concept)\n\t\tmove_page(concept)\n\t\n\t\npages = thispage.backlinks()\ni = 0\nfor page in pages:\n\tif i == limit:\n\t\tbreak\n\ti = i + 1\n\tprocess_page(page)\nprint(\"Blank editing...\")\nif init_move:\n\tfor page in blank_edit_these:\n\t\tblank_edit_page(page)\n\tmake_disambig_page()\nprint(\"Done! If some pages stalled out you may still need to abort manually.\")\n" }, { "alpha_fraction": 0.7092457413673401, "alphanum_fraction": 0.7177615761756897, "avg_line_length": 25.516128540039062, "blob_id": "a6b564b6de397deab77530b693382cbc38882f00", "content_id": "be731781119d0a6238e4a51c120dec62f27692b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 822, "license_type": "no_license", "max_line_length": 71, "num_lines": 31, "path": "/default_loadout.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import datetime\nfrom time import mktime\n\nfrom log_into_wiki import *\n\nloadout = login('me', 'spyro') # Set wiki\ntarget = login('me', 'wikisandbox')\nsummary = 'Backing up spyro' # Set summary\n\nstartat_namespace = None\nprint(startat_namespace)\nstartat_namespace = 274\n\nstartat_page = None\nprint(startat_page)\nstartat_page = 'Module:Navbox/Aether II/en'\n\nstartat_comparison = startat_namespace - 1 if startat_namespace else -1\n\npassed_startat = False\n\nfor ns in loadout.namespaces:\n\tprint(ns)\n\tif ns > startat_comparison and ns != 4: # ns 4 is Project ns\n\t\tfor page in loadout.allpages(namespace=ns):\n\t\t\tif startat_page == page.name:\n\t\t\t\tpassed_startat = True\n\t\t\tif startat_page and not passed_startat:\n\t\t\t\tcontinue\n\t\t\tif target.pages[page.name].text() == '':\n\t\t\t\ttarget.pages[page.name].save(page.text(), summary=summary)\n" }, { "alpha_fraction": 0.6674311757087708, "alphanum_fraction": 0.6708715558052063, "avg_line_length": 31.296297073364258, "blob_id": "efead2120109d5ad28260b11644e40ead9f15ad9", "content_id": "d39ff96816b617badc973544324f7d962df9c2ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1744, "license_type": "no_license", "max_line_length": 88, "num_lines": 54, "path": "/fortnite_auto_new_players.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\nimport mwparserfromhell\nlimit = -1\n\nsite = login('bot', 'fortnite-esports')\nsummary = 'Automatically create player pages for Power Rankings'\n\nresult = site.api('cargoquery',\n\t\t\t\t tables = 'TournamentResults=TR,TournamentResults__RosterLinks=RL,_pageData=PD',\n\t\t\t\t join_on = 'TR._ID=RL._rowID,RL._value=PD._pageName',\n\t\t\t\t where = 'PD._pageName IS NULL AND RL._value IS NOT NULL AND TR.PRPoints > \"0\"',\n\t\t\t\t fields = 'RL._value=name',\n\t\t\t\t group_by = 'RL._value',\n\t\t\t\t limit = 'max'\n\t\t\t\t )\ndefault_text = site.pages['Help:Player Template'].text()\ndefault_text = default_text.replace('<noinclude>','').replace('</noinclude>','').strip()\n\nwikitext = mwparserfromhell.parse(default_text)\nthis_template = None\nfor template in wikitext.filter_templates():\n\tif template.name.matches('Infobox Player'):\n\t\tthis_template = template\n\t\tthis_template.add('pronly','Yes')\n\t\tbreak\n\ndef get_residency(name):\n\tprint(name)\n\tres_response = site.api('cargoquery',\n\t\t\t\t\t\ttables='Tournaments=T,TournamentResults=TR,TournamentResults__RosterLinks=RL',\n\t\t\t\t\t\tjoin_on='T._pageName=TR.OverviewPage,TR._ID=RL._rowID',\n\t\t\t\t\t\twhere='RL._value=\"%s\"' % name,\n\t\t\t\t\t\tfields='T.Region',\n\t\t\t\t\t\tgroup_by='T.Region'\n\t\t\t\t\t\t)\n\tres_result = res_response['cargoquery']\n\tif len(res_result) == 1:\n\t\treturn res_result[0]['title']['Region']\n\treturn ''\n\nlmt = 0\nfor item in result['cargoquery']:\n\tif lmt == limit:\n\t\tbreak\n\tlmt = lmt + 1\n\tname = item['title']['name']\n\tif site.pages[name].text() != '':\n\t\tprint('Page %s already exists, skipping' % name)\n\t\tcontinue\n\tprint('Processing page %s...' % name)\n\tthis_template.add('residency', get_residency(name))\n\tthis_template.add('id', name)\n\ttext = str(wikitext)\n\tsite.pages[name].save(text, summary=summary)\n" }, { "alpha_fraction": 0.6635969877243042, "alphanum_fraction": 0.6668472290039062, "avg_line_length": 32.563636779785156, "blob_id": "740f1b430df96bdd5c3b40d5d870c79644db28d3", "content_id": "03ffeeba75a56f76d33322f3eeb4eeb1cf11f406", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1846, "license_type": "no_license", "max_line_length": 92, "num_lines": 55, "path": "/extended_site.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import mwclient, datetime\n\nclass ExtendedSite(mwclient.Site):\n\tdef cargoquery(self, **kwargs):\n\t\tresponse = self.api('cargoquery', **kwargs)\n\t\tret = []\n\t\tfor item in response['cargoquery']:\n\t\t\tret.append(item['title'])\n\t\treturn ret\n\t\n\tdef cargo_pagelist(self, fields=None, limit=\"max\", page_pattern = \"%s\", **kwargs):\n\t\tfield = fields.split('=')[1] if '=' in fields else fields\n\t\tgroup_by = fields.split('=')[0]\n\t\tresponse = self.api('cargoquery',\n\t\t\tfields=fields,\n\t\t\tgroup_by=group_by,\n\t\t\tlimit=limit,\n\t\t\t**kwargs\n\t\t)\n\t\tpages = []\n\t\tfor item in response['cargoquery']:\n\t\t\tpage = page_pattern % item['title'][field]\n\t\t\tif page in pages:\n\t\t\t\tcontinue\n\t\t\tpages.append(page)\n\t\t\tyield(self.pages[page])\n\t\n\tdef recentchanges_by_interval(self, interval, offset=0, prop='title|ids', **kwargs):\n\t\tnow = datetime.datetime.utcnow() - datetime.timedelta(minutes=offset)\n\t\tthen = now - datetime.timedelta(minutes=interval)\n\t\tresult = self.recentchanges(\n\t\t\tstart=now.isoformat(),\n\t\t\tend=then.isoformat(),\n\t\t\tlimit='max',\n\t\t\tprop=prop,\n\t\t\t**kwargs\n\t\t)\n\t\treturn result\n\t\n\tdef patrol_recent(self, interval, f, **kwargs):\n\t\trevisions = self.recentchanges_by_interval(interval, prop='title|ids|patrolled', **kwargs)\n\t\tpatrol_token = self.get_token('patrol')\n\t\tfor revision in revisions:\n\t\t\t# revid == 0 if the page was deleted, so it can't be deleted\n\t\t\tif f(revision) and revision['revid'] != 0 and 'unpatrolled' in revision:\n\t\t\t\tself.api('patrol', revid = revision['revid'], token = patrol_token)\n\nclass GamepediaSite(ExtendedSite):\n\tdef __init__(self, user, wiki):\n\t\tsuper().__init__('%s.gamepedia.com' % wiki, path='/')\n\t\tpwd_file = 'password2.txt' if user == 'bot' else 'password.txt'\n\t\tuser_file = 'username2.txt' if user == 'bot' else 'username.txt'\n\t\tpwd = open(pwd_file).read().strip()\n\t\tusername = open(user_file).read().strip()\n\t\tself.login(username, pwd)\n" }, { "alpha_fraction": 0.6485839486122131, "alphanum_fraction": 0.6605504751205444, "avg_line_length": 31.558441162109375, "blob_id": "b33e15449bee52edb8fcee28c91d40af2e2e723a", "content_id": "d10292d4322f613a4a3c9b471d727bddd59715bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2507, "license_type": "no_license", "max_line_length": 100, "num_lines": 77, "path": "/log_into_wiki.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import re, urllib.request, io\nfrom esports_site import EsportsSite\nfrom PIL import Image, ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\ndef login(user, wiki, timeout = 30):\n\t\treturn EsportsSite(user, wiki)\n\ndef log_into_fandom(user, wiki):\n\tif user == 'me':\n\t\tpassword = open('password_fandom.txt').read().strip()\n\t\tsite = extended_site.ExtendedSite('%s.fandom.com' % wiki, path='/')\n\t\tsite.login('RheingoldRiver', password)\n\t\treturn site\n\ndef report_errors(report_page, page, errors):\n\ttext = report_page.text()\n\terror_text = '\\n* '.join([e.args[0] for e in errors])\n\tnewtext = text + '\\n==Python Error Report==\\nPage: [[{}]] Messages:\\n* {}'.format(page, error_text)\n\treport_page.save(newtext)\n\ndef api_parse_query(site, datatype, values):\n\tquery_text = '{{#invoke:PrintParsedText|unordered|type=' + datatype + '|' + '|'.join(values) + '}}'\n\tquery_result = site.api(\n\t\t'parse',\n\t\tformat='json',\n\t\ttext=query_text,\n\t\tprop='text',\n\t\tdisablelimitreport=1,\n\t\twrapoutputclass=''\n\t)\n\tresult = query_result['parse']['text']['*']\n\tresult = result.replace('<p>', '').replace('\\n</p>', '')\n\tresult_tbl = result.split(',')\n\treturn result_tbl\n\ndef parse_ordered_field(val, sep):\n\tif not sep:\n\t\tsep = ','\n\ttbl = re.split('\\s*' + sep + '\\s*' + '\\s*', val)\n\treturn tbl\n\ndef check_links(template, key1, key2, sep, name, link):\n\tif not sep:\n\t\tsep = ','\n\tif template.has(key1):\n\t\tval1 = template.get(key1).value.strip()\n\t\ttbl1 = parse_ordered_field(val1, sep)\n\t\ttbl2 = ['' for _ in range(len(tbl1))] # list(range(len(tbl1)))\n\t\tif template.has(key2):\n\t\t\tval2 = template.get(key2).value.strip()\n\t\t\ttbl2 = parse_ordered_field(val2, sep)\n\t\tif name in tbl1:\n\t\t\ti = tbl1.index(name)\n\t\t\ttbl2[i] = link\n\t\t\ttemplate.add(key2,sep.join(tbl2), before=key1)\n\t\t\ttemplate.add(key1, val1, before=key2)\n\ndef get_filename_url_to_open(site, filename, size=None):\n\tpattern = r'.*src\\=\\\"(.+?)\\\".*'\n\tsize = '|' + str(size) + 'px' if size else ''\n\tto_parse_text = '[[File:{}|link=%s]]'.format(filename, size)\n\tresult = site.api('parse', title='Main Page', text=to_parse_text, disablelimitreport=1)\n\tparse_result_text = result['parse']['text']['*']\n\tprint(parse_result_text)\n\turl = re.match(pattern, parse_result_text)[1]\n\treturn url\n\ndef open_file_url(url):\n\treturn Image.open(io.BytesIO(urllib.request.urlopen(url).read()))\n\ndef open_image_from_filename(site, filename, size=None):\n\turl = get_filename_url_to_open(site, filename, size=size)\n\treturn open_file_url(url)\n\ndef tl_matches(tl, arr):\n\treturn [_ for _ in arr if tl.name.matches(_)]\n" }, { "alpha_fraction": 0.6536502838134766, "alphanum_fraction": 0.6652518510818481, "avg_line_length": 33.9901008605957, "blob_id": "b472d8a25c259e163a4538b08a4422ba43de01bc", "content_id": "299a9f10cfae6866c370f8ece529dc4043c444ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3534, "license_type": "no_license", "max_line_length": 101, "num_lines": 101, "path": "/match_schedule_hash.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import datetime\nimport mwparserfromhell\nfrom log_into_wiki import *\n\nERROR_LOCATION = 'Maintenance:MatchSchedule Ordering Errors'\nERROR_TEAMS_TEXT = 'Team 1 - {}; Team 2: {}'\n\ndef get_append_hash(hash, res):\n\ttl = mwparserfromhell.nodes.Template(name='MSHash')\n\ttl.add('hash', hash)\n\ttl.add('team1', res['Team1'])\n\ttl.add('team2', res['Team2'])\n\treturn str(tl)\n\ndef verify_hash(template, team1, team2):\n\tteam1_old = template.get('team1').value.strip()\n\tteam2_old = template.get('team2').value.strip()\n\tif team1_old != 'TBD' and team1_old != team1:\n\t\treturn False\n\tif team2_old != 'TBD' and team2_old != team2:\n\t\treturn False\n\treturn True\n\ndef get_hash_template(ms_hash, wikitext):\n\tfor template in wikitext.filter_templates():\n\t\tif template.has('hash') and template.get('hash').value.strip() == ms_hash:\n\t\t\treturn template\n\treturn None\n\t\ndef get_error_text(res, page_name, tl):\n\tmatch_info = 'Page - [[{}]]; Tab - {}; initialorder: {}'.format(page_name, res['Tab'], res['Order'])\n\toriginal = ERROR_TEAMS_TEXT.format(tl.get('team1').value.strip(), tl.get('team2').value.strip())\n\tnew = ERROR_TEAMS_TEXT.format(res['Team1'], res['Team2'])\n\treturn 'Match Info: {}\\n<br>Originally: {}\\n<br>Now: {}<br>'.format(match_info, original, new)\n\ndef write_errors(site, errors):\n\tif len(errors) == 0:\n\t\treturn\n\tpage = site.pages[ERROR_LOCATION]\n\tif page.text() != '':\n\t\terrors.insert(0, page.text())\n\ttext = '\\n'.join(errors)\n\tpage.save(text, summary = 'Reporting MatchSchedule initialorder Errors')\n\ndef check_page(site, page_name):\n\tresponse = site.api('cargoquery', tables = 'MatchSchedule',\n\t\t\t\t\t fields = 'InitialN_MatchInTab=Order, Team1, Team2, Tab, InitialPageAndTab',\n\t\t\t\t\t where = '_pageName=\"%s\"' % page_name\n\t\t\t\t\t )\n\tresult = response['cargoquery']\n\thash_location = site.pages[page_name + '/Hash']\n\ttext = hash_location.text()\n\twikitext = mwparserfromhell.parse(text)\n\thashes_to_add = []\n\terrors = []\n\tfor res in result:\n\t\tdata = res['title']\n\t\tif data['InitialPageAndTab'] != '':\n\t\t\tms_hash = data['InitialPageAndTab'].split('_')[1] + '_' + data['Order']\n\t\telse:\n\t\t\tms_hash = data['Tab'] + '_' + data['Order']\n\t\thash_template = get_hash_template(ms_hash, wikitext)\n\t\tif not hash_template:\n\t\t\thashes_to_add.append(get_append_hash(ms_hash, data))\n\t\telif not verify_hash(hash_template, data['Team1'], data['Team2']):\n\t\t\terrors.append(get_error_text(data, page_name, hash_template))\n\t\t\thash_template.add('team1', data['Team1'])\n\t\t\thash_template.add('team2', data['Team2'])\n\t\telse: # There could be a TBD that we need to replace\n\t\t\thash_template.add('team1', data['Team1'])\n\t\t\thash_template.add('team2', data['Team2'])\n\twrite_errors(site, errors)\n\tif str(wikitext) != '':\n\t\thashes_to_add.insert(0, str(wikitext))\n\tnew_text = '\\n'.join(hashes_to_add)\n\tif text != new_text:\n\t\thash_location.save(new_text)\n\ndef check_recent_revisions(site):\n\tthen_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=20)\n\tthen = then_time.isoformat()\n\tnow = datetime.datetime.utcnow().isoformat()\n\trevisions = site.api('query', format='json',\n\t\t\t\t\t\t list='recentchanges',\n\t\t\t\t\t\t rcstart=now,\n\t\t\t\t\t\t rcend=then,\n\t\t\t\t\t\t rcprop='title',\n\t\t\t\t\t\t rclimit='max',\n\t\t\t\t\t\t # rctoponly=0, # commented bc we need all revisions to patrol user pages\n\t\t\t\t\t\t rcdir='older'\n\t\t\t\t\t\t )\n\ttitles = []\n\tfor revision in revisions['query']['recentchanges']:\n\t\tif revision['title'].startswith('Data:'):\n\t\t\ttitles.append(revision['title'])\n\tfor title in titles:\n\t\tcheck_page(site, title)\n\nif __name__ == '__main__':\n\tsite = login('me', 'lol')\n\tcheck_recent_revisions(site)\n" }, { "alpha_fraction": 0.6495176553726196, "alphanum_fraction": 0.6527331471443176, "avg_line_length": 30.100000381469727, "blob_id": "f9bbd152fbc74dc7ab39907ee300e12eb1b806e6", "content_id": "0371a559c15ed35772d3479f2bd2ad9348404f0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 98, "num_lines": 10, "path": "/luacache_refresh.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import re\n\ndef teamnames(site):\n\tprefix_text = site.pages['Module:Team'].text()\n\tprocessed = prefix_text.replace('\\n','')\n\tprefix = re.match(r\".*PREFIX = '(.+?)'.*\", processed)[1]\n\tsite.api(\n\t\taction='parse',\n\t\ttext='{{#invoke:CacheUtil|resetAll|Teamnames|module=Team|f=teamlinkname|prefix=' + prefix + '}}'\n\t)\n" }, { "alpha_fraction": 0.6915668845176697, "alphanum_fraction": 0.6954711079597473, "avg_line_length": 33.30356979370117, "blob_id": "5345dac0c38e1b4f02ad0e702f7eac6405768aed", "content_id": "ba7ac2a23ce484fb6ab76b2b53bcf2b87f6a9fd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3842, "license_type": "no_license", "max_line_length": 118, "num_lines": 112, "path": "/weekly_utils_main.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "# weekly is a lie, this runs twice-daily\n\nimport mwparserfromhell, datetime\nimport weekly_utils as utils\nfrom esports_site import EsportsSite\nimport scrape_runes, luacache_refresh\nfrom template_list import *\n\nsite = EsportsSite('me','lol')\n\nlimit = -1\n\nsite.standard_name_redirects()\n\n# Blank edit pages we need to\nblank_edit_pages = ['Leaguepedia:Top Schedule']\nfor page in blank_edit_pages:\n\tp = site.pages[page]\n\tp.save(p.text(), summary = 'blank editing')\n\nnow_timestamp = datetime.datetime.utcnow().isoformat()\nwith open('daily_last_run.txt','r') as f:\n\tlast_timestamp = f.read()\nwith open('daily_last_run.txt','w') as f:\n\tf.write(now_timestamp)\n\nrevisions = site.api('query', format='json',\n\t\t\t\t\t list='recentchanges',\n\t\t\t\t\t rcstart=now_timestamp,\n\t\t\t\t\t rcend=last_timestamp,\n\t\t\t\t\t rcprop='title|ids|patrolled',\n\t\t\t\t\t rclimit='max',\n\t\t\t\t\t rctoponly=1, # commented bc we need all revisions to patrol user pages\n\t\t\t\t\t rcdir = 'older'\n\t\t\t\t\t )\n\npages = []\npages_for_runes = []\n\nfor revision in revisions['query']['recentchanges']:\n\ttitle = revision['title']\n\tif title not in pages:\n\t\tpages.append(title)\n\t\tif title.startswith('Data:'):\n\t\t\tpages_for_runes.append(title)\n\nlmt = 1\nfor page in pages:\n\tif lmt == limit:\n\t\tbreak\n\tlmt+=1\n\ttry:\n\t\tp = site.pages[page]\n\texcept KeyError:\n\t\tprint(page)\n\t\tcontinue\n\tutils.make_doc_pages(site, p)\n\tif '/Edit Conflict/' in page and p.namespace == 2 and p.text() != '':\n\t\tp.delete(reason='Deleting old edit conflict')\n\telse:\n\t\ttext = p.text()\n\t\twikitext = mwparserfromhell.parse(text)\n\t\terrors = []\n\t\tfor template in wikitext.filter_templates():\n\t\t\ttry:\n\t\t\t\tif template.name.matches('Infobox Player'):\n\t\t\t\t\tutils.fixInfoboxPlayer(template)\n\t\t\t\t\tif p.namespace == 0:\n\t\t\t\t\t\tif template.has('checkboxIsPersonality'):\n\t\t\t\t\t\t\tif template.get('checkboxIsPersonality').value.strip() != 'Yes':\n\t\t\t\t\t\t\t\tutils.createResults(site, page, template, 'Tournament Results', 'Player', '{{PlayerResults|show=everything}}')\n\t\t\t\telif template.name.matches('Infobox Team'):\n\t\t\t\t\tutils.fixInfoboxTeam(template)\n\t\t\t\t\tif p.namespace == 0:\n\t\t\t\t\t\tutils.createResults(site, page, template, 'Tournament Results', 'Team', '{{TeamResults|show=everything}}')\n\t\t\t\t\t\tutils.createResults(site, page, template, 'Schedule History', 'Team', '{{TeamScheduleHistory}}')\n\t\t\t\t\t\ttooltip = site.pages['Tooltip:%s' % page]\n\t\t\t\t\t\ttooltip.save('{{RosterTooltip}}',tags='daily_errorfix')\n\t\t\t\telif template.name.strip() in gameschedule_templates:\n\t\t\t\t\tutils.fixDST(template)\n\t\t\t\t\tutils.updateParams(template)\n\t\t\t\telif template.name.matches('PicksAndBansS7') or template.name.matches('PicksAndBans'):\n\t\t\t\t\tutils.fixPB(site, template)\n\t\t\t\telif template.name.matches('Listplayer/Current/End'):\n\t\t\t\t\ttemplate.add(1, '')\n\t\t\texcept Exception as e:\n\t\t\t\terrors.append(e)\n\t\tif p.namespace == 10008: # Data namespace\n\t\t\tutils.set_initial_order(wikitext)\n\t\tnewtext = str(wikitext)\n\t\tif text != newtext:\n\t\t\tprint('Saving page %s...' % page)\n\t\t\tp.save(newtext,summary='Automated error fixing (Python)',tags='daily_errorfix')\n\t\tif len(errors) > 0:\n\t\t\treport_page = site.pages['User talk:RheingoldRiver']\n\t\t\treport_errors(report_page, page, errors)\nluacache_refresh.teamnames(site)\n\nsuccess_page = site.pages['User:RheingoldRiver/Maint Log']\ntext = success_page.text()\ntext = text + '\\nScript finished maint successfully: ' + now_timestamp\ntry:\n\tscrape_runes.scrape(site, pages_for_runes, False)\n\ttext = text + '\\nScript finished regular runes successfully: ' + now_timestamp\nexcept Exception as e:\n\ttext = text + '\\nException running regular runes: ' + str(e) + ' ' + now_timestamp\ntry:\n\tscrape_runes.scrapeLPL(site, pages_for_runes, False)\n\ttext = text + '\\nScript finished everything successfully: ' + now_timestamp\nexcept Exception as e:\n\ttext = text + '\\nException running LPL runes: ' + str(e) + ' ' + now_timestamp\nsuccess_page.save(text,tags='daily_errorfix')\n" }, { "alpha_fraction": 0.6688741445541382, "alphanum_fraction": 0.7185430526733398, "avg_line_length": 26.545454025268555, "blob_id": "13db43ec1edf1dc29b4dfe67eb6d27a3ee9b0de1", "content_id": "a2dcf8be1c1e53b819bef511a4593b4cd0b0a57d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 86, "num_lines": 11, "path": "/scrape_runes_run.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import scrape_runes\nfrom log_into_wiki import *\n\nsite = login('me','lol') # Set wiki\n\npages = ['Data:LPL/2019 Season/Spring Season', 'Data:LPL/2019 Season/Spring Season/2']\n\n#pages = ['Data:OPL/2019 Season/Split 1/2']\n\n#scrape_runes.scrape(site, pages, False)\nscrape_runes.scrapeLPL(site, pages, False)" }, { "alpha_fraction": 0.6684027910232544, "alphanum_fraction": 0.671875, "avg_line_length": 24.04347801208496, "blob_id": "e8134fa8a08946a907f9448cfae0ad6e6410a8e7", "content_id": "b0d23b7899309b92b2763daa73629653bbf5e624", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 57, "num_lines": 23, "path": "/extended_page.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import mwclient.page\n\nclass ExtendedPage(mwclient.page.Page):\n\tdef __init__(self, page):\n\t\tsuper().__init__(page.site, page.name, info=page._info)\n\t\tself.base_title = self.page_title.split('/')[0]\n\t\tself.base_name = self.name.split('/')[0]\n\t\n\t@staticmethod\n\tdef extend_pages(page_gen):\n\t\tfor page in page_gen:\n\t\t\tyield(ExtendedPage(page))\n\t\t\t\n\tdef touch(self, check_existence=False):\n\t\tif check_existence and not self.exists:\n\t\t\treturn\n\t\tself.site.api(\n\t\t\t'edit',\n\t\t\ttitle=self.name,\n\t\t\tappendtext=\"\",\n\t\t\ttoken=self.get_token('edit'),\n\t\t\tsummary=\"ExtendedPage Touch Edit\"\n\t\t)\n" }, { "alpha_fraction": 0.6980891823768616, "alphanum_fraction": 0.7044585943222046, "avg_line_length": 27.035715103149414, "blob_id": "87d9aa48d76bd0885c8b8d3d75a638c4b7fc0261", "content_id": "c64d174e82dd2c46be014777c3ea00c2b8d132f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 785, "license_type": "no_license", "max_line_length": 78, "num_lines": 28, "path": "/fortnite_player_blank_edit.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import log_into_wiki\nfrom extended_page import ExtendedPage\n\nsite = log_into_wiki.login('bot', 'fortnite-esports')\n\nrc = site.recentchanges_by_interval(12 * 60, toponly=1)\n\ndata_pages = []\n\nfor p in rc:\n\tif p['title'].startswith('Data:'):\n\t\tdata_pages.append(p['title'])\n\nwhere = ' OR '.join(['TR._pageName=\"%s\"' % _ for _ in data_pages])\n\nplayers = site.cargo_pagelist(\n\ttables=\"TournamentResults=TR,TournamentResults__RosterLinks=RL,_pageData=pd\",\n\tjoin_on=\"TR._ID=RL._rowID, RL._value=pd._pageName\",\n\twhere='(%s) AND RL._rowID IS NOT NULL AND pd._pageName IS NOT NULL' % where,\n\tfields=\"RL._value=player\"\n)\n\nfor player in ExtendedPage.extend_pages(players):\n\tplayer.touch(check_existence=True)\n\n# purge PR pages\nfor page in site.pages['Template:PRWiki'].embeddedin():\n\tpage.purge()\n" }, { "alpha_fraction": 0.7387843728065491, "alphanum_fraction": 0.7452966570854187, "avg_line_length": 33.54999923706055, "blob_id": "3b1c998b304f8156da926adc09c73987b04b0968", "content_id": "21d12a35a809b743572e3836487325c5e5debcbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1382, "license_type": "no_license", "max_line_length": 101, "num_lines": 40, "path": "/yearly_stats_pages.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from extended_site import GamepediaSite\nfrom extended_page import ExtendedPage\n\nsite = GamepediaSite('me', 'lol')\n\ncreate_text = \"\"\"{{PlayerTabsHeader}}\n{{PlayerYearStats}}\"\"\"\n\noverview_create_text = \"\"\"{{PlayerTabsHeader}}\n{{CareerPlayerStats}}\"\"\"\n\nredirect_text = '#redirect[[%s]]'\n\nsummary= \"Automatically discovering & creating year player stats\"\n\nresults = site.cargoquery(\n\ttables='ScoreboardPlayer=SP,_pageData=PD1,_pageData=PD2',\n\tjoin_on='SP.Link=PD1._pageName,SP.StatsPage=PD2._pageName',\n\twhere='PD1._pageName IS NOT NULL and PD2._pageName IS NULL and BINARY PD1._pageName=BINARY SP.Link',\n\tfields=\"SP.StatsPage=StatsPage, PD1._isRedirect=IsRedirect\",\n\tgroup_by= \"SP.StatsPage\",\n\tlimit='max'\n)\n\ndef save_pages(page):\n\tpage.save(create_text, summary=summary)\n\tbase_stats_page = site.pages[page.base_title + '/Statistics']\n\tif not base_stats_page.exists:\n\t\tbase_stats_page.save(overview_create_text, summary=summary)\n\nfor result in results:\n\tstats_page = ExtendedPage(site.pages[result['StatsPage']])\n\tif result['IsRedirect'] == '0':\n\t\tsave_pages(stats_page)\n\t\tcontinue\n\ttarget = site.pages[stats_page.base_title].redirects_to()\n\ttarget_stats_page_name = stats_page.name.replace(stats_page.base_title, target.name)\n\ttarget_stats_page = ExtendedPage(site.pages[target_stats_page_name])\n\tsave_pages(target_stats_page)\n\tstats_page.save(redirect_text % target_stats_page.name)\n" }, { "alpha_fraction": 0.6073170900344849, "alphanum_fraction": 0.6121951341629028, "avg_line_length": 21.83333396911621, "blob_id": "7ee8ed8bc373960a536a5e698b4b1096d5e5ab14", "content_id": "d05056b46308269e56f7f8e5b8997ddd93e06173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "no_license", "max_line_length": 90, "num_lines": 18, "path": "/download_images_from_list.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "from log_into_wiki import *\nimport os\nlimit = -1\n\nsite = login('bot', 'lol')\n\nLOC = 'Sprites/' + 'League Images'\n\nwith open('pages.txt', encoding=\"utf-8\") as f:\n\tpages = f.readlines()\n\nfor page in pages:\n\tpage = page.strip()\n\tif os.path.isfile(LOC + '/' + page) or os.path.isfile(LOC + '/' + page.replace(' ','_')):\n\t\tpass\n\telse:\n\t\timg = open_image_from_filename(site, page)\n\t\timg.save(LOC + '/' + page, 'png')" }, { "alpha_fraction": 0.5603266358375549, "alphanum_fraction": 0.5707447528839111, "avg_line_length": 32.19158935546875, "blob_id": "8f0e80c22e5b6716b417c4b421292eb2f356ced1", "content_id": "e8c68e325cbe3cc79a8c506aa7ef3007aa04e388", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7103, "license_type": "no_license", "max_line_length": 263, "num_lines": 214, "path": "/weekly_utils.py", "repo_name": "banditti99/leaguepedia_util", "src_encoding": "UTF-8", "text": "import dateutil.parser, pytz, re, datetime, mwparserfromhell\nfrom log_into_wiki import *\n\nsite = login('me','lol')\n\ntypo_find = ['favourite','quater','partecipate','Portugese', 'Regelations']\ntypo_replace = ['favorite','quarter','participate','Portuguese', 'Relegations']\n\ndef typoFixes(text):\n\ti = 0\n\twhile i < len(typo_find):\n\t\ttext = text.replace(typo_find,typo_replace)\n\treturn text\n\n\nteamhist_find = [r\"(\\d+)(\\s*)-(\\s*)(\\\"?Present\\\"?|''Present'')\",\n\t\t\t r'^\\s*(.*)(\\d+)\\s*-\\s*(\\w+)',\n\t\t\t r'^\\s*(\\w\\w\\w)(?:[A-Za-z])*\\s*(\\d\\d\\d\\d) - (\\w\\w\\w)(?:[A-Za-z])*\\s*(\\d)',\n\t\t\t r\"^\\s*(\\w\\w\\w)(?:[A-Za-z])*\\s*(\\d\\d\\d\\d) - ''Present''\",\n\t\t\t r\"^\\s*(\\w\\w\\w)(?:[A-Za-z])*\\s*- (\\w\\w\\w)(?:[A-Za-z])*\\s*(\\d\\d\\d\\d)\",\n\t\t\t r\"\\?\\s*-\\s*Present\",\n\t\t\t r'^\\s*([\\? ]+)-',\n\t\t\t r'^\\s*(.*)-([\\? ]+)$',\n\t\t\t ]\nteamhist_replace = [r\"\\1 - ''Present''\",\n\t\t\t\t r'\\1\\2 - \\3',\n\t\t\t\t r'\\1 \\2 - \\3 \\4',\n\t\t\t\t r\"\\1 \\2 - ''Present''\",\n\t\t\t\t r'\\1 \\3 - \\2 \\3',\n\t\t\t\t r\"? - ''Present''\",\n\t\t\t\t r'??? ???? -',\n\t\t\t\t r'\\1- ??? ????',\n\t\t\t\t ]\n\nsocial_fr = [\n\t{ \"field\" : \"twitter\", \"find\" : r'(?:\\[?https?://)?(?:www\\.)?(?:twitter\\.com/)?([^/ \\n]+)(.*\\])?', \"replace\" : r'\\1' },\n\t{ \"field\" : \"twitter\", \"find\" : r'/$', \"replace\" : r'' },\n\t{ \"field\" : \"stream\", \"find\" : r'\\[?(?:https?://)?(.*)/([^ \\n]+).*', \"replace\" : r'https://\\1/\\2' },\n\t{ \"field\" : \"stream\", \"find\" : r'/$', \"replace\" : r'' },\n\t{ \"field\" : \"instagram\", \"find\" : r'(?:\\[?https?://)?(?:www\\.)?(?:instagram\\.com/)?([^/ \\n]+)(.*\\])?', \"replace\" : r'\\1' },\n\t{ \"field\" : \"instagram\", \"find\" : r'/$', \"replace\" : r'' },\n\t{ \"field\" : \"facebook\", \"find\" : r'\\[?(?:https?://)?(.*)/([^ \\n]+).*', \"replace\" : r'https://\\1/\\2' },\n\t{ \"field\" : \"facebook\", \"find\" : r'/$', \"replace\" : r'' },\n\t{ \"field\" : \"youtube\", \"find\" : r'\\[?(?:https?://)?([^ \\n]*)(.*\\])?', \"replace\" : r'https://\\1' },\n\t{ \"field\" : \"website\", \"find\" : r'\\[?([^ \\n]*)(.*\\])?', \"replace\" : r'\\1' },\n\t{ \"field\" : \"vk\", \"find\": r'(?:\\[?https?://)?(?:www\\.)?(?:vk\\.com/)?([^/ \\n]+)(.*\\])?', \"replace\": r'https://vk.com/\\1'},\n\t{ \"field\" : \"vk\", \"find\" : r'/$', \"replace\" : r'' },\n]\n\ndef fixSocialField(template, item):\n\tfield = item['field']\n\tif template.has(field):\n\t\tval_old = template.get(field).value.strip()\n\t\tif val_old != '':\n\t\t\tval_arr = re.split(r'(<!--|-->)', val_old)\n\t\t\tval_arr[0] = re.sub(item['find'], item['replace'], val_arr[0])\n\t\t\tval_new = ''.join(val_arr)\n\t\t\ttemplate.add(field, val_new)\n\t\t\t\ndef fixInfoboxPlayer(template):\n\tfor item in social_fr:\n\t\tfixSocialField(template, item)\n\ti = 1\n\tkey = 'teamdate' + str(i)\n\twhile template.has(key):\n\t\tteamdate_new = str(template.get(key).value.strip())\n\t\tfor j, f in enumerate(teamhist_find):\n\t\t\tteamdate_new = re.sub(f,teamhist_replace[j],teamdate_new)\n\t\ttemplate.add(key,teamdate_new)\n\t\ti += 1\n\t\tkey = 'teamdate' + str(i)\n\treturn\n\ndef fixInfoboxTeam(template):\n\tfor item in social_fr:\n\t\tfixSocialField(template, item)\n\tif template.has('isdisbanded'):\n\t\tif template.get('isdisbanded').value.strip().lower() == 'no':\n\t\t\ttemplate.remove('isdisbanded')\n\treturn\n\ndef createResults(site, page, template, subpage, result_type, template_text):\n\tif template.has('checkboxIsPersonality') and template.get('checkboxIsPersonality').value.strip() == 'Yes':\n\t\tpass\n\telse:\n\t\tp = site.pages[page + '/' + subpage]\n\t\ttext = p.text()\n\t\tif text == '':\n\t\t\tp.save('{{{{{}TabsHeader}}}}\\n{}'.format(result_type, template_text),tags='daily_errorfix')\n\n\npst = pytz.timezone('America/Los_Angeles')\nest = pytz.timezone('America/New_York')\ncet = pytz.timezone('Europe/Berlin')\nkst = pytz.timezone('Asia/Seoul')\ntz_lookup = {\n\t'PST' : pst,\n\t'EST' : est,\n\t'CET' : cet,\n\t'KST' : kst\n}\n\ndef fixDST(template):\n\tif template.has('date') and template.has('time'):\n\t\tdate = template.get(\"date\").value.strip()\n\t\ttime = template.get(\"time\").value.strip()\n\t\ttz_local_str = template.get('timezone').value.strip()\n\t\ttz_local = tz_lookup[tz_local_str]\n\t\tdate_time = dateutil.parser.parse(date + \" \" + time)\n\t\tdate_time_local = tz_local.localize(date_time)\n\t\tisDST_PST = bool(date_time_local.astimezone(pst).dst())\n\t\tisDST_CET = bool(date_time_local.astimezone(cet).dst())\n\t\tif isDST_PST and isDST_CET:\n\t\t\ttemplate.add('dst','yes')\n\t\telif isDST_PST:\n\t\t\ttemplate.add('dst','spring')\n\t\telse:\n\t\t\ttemplate.add('dst','no')\n\ndef updateParams(template):\n\t# update gameschedule params for new conventions\n\tif template.has('t1score'):\n\t\ttemplate.get('t1score').name = 'team1score'\n\tif template.has('t2score'):\n\t\ttemplate.get('t2score').name = 'team2score'\n\tif template.has('post-match'):\n\t\ttemplate.get('post-match').name = 'reddit'\n\npb_data = [\n\t{\n\t\t'data_type' : 'champion',\n\t\t'args' : [ 'blueban1', 'blueban2', 'blueban3', 'blueban4', 'blueban5', 'red_ban1', 'red_ban2', 'red_ban3', 'red_ban4', 'red_ban5', 'bluepick1', 'bluepick2', 'bluepick3', 'bluepick4', 'bluepick5', 'red_pick1', 'red_pick2', 'red_pick3', 'red_pick4', 'red_pick5' ]\n\t},\n\t{\n\t\t'data_type' : 'role',\n\t\t'args' : [ 'bluerole1', 'bluerole2', 'bluerole3', 'bluerole4', 'bluerole5' ],\n\t},\n\t{\n\t\t'data_type' : 'role',\n\t\t'args' : [ 'red_role1', 'red_role2', 'red_role3', 'red_role4', 'red_role5' ]\n\t}\n]\npb_exceptions = ['', 'unknown', 'none', 'missing data', 'loss of ban']\ndef fixPB(site, template):\n\tfor lookup in pb_data:\n\t\tvalues = []\n\t\tdatatype = lookup['data_type']\n\t\tfor arg in lookup['args']:\n\t\t\tif template.has(arg):\n\t\t\t\tvalues.append(template.get(arg).value.strip())\n\t\tquery_text = '{{#invoke:PrintParsedText|unordered|type=' + datatype + '|' + '|'.join(values) + '}}'\n\t\tquery_result = site.api(\n\t\t\t'parse',\n\t\t\tformat = 'json',\n\t\t\ttext = query_text,\n\t\t\tprop = 'text',\n\t\t\tdisablelimitreport = 1,\n\t\t\twrapoutputclass = ''\n\t\t)\n\t\tresult = query_result['parse']['text']['*']\n\t\tresult = result.replace('<p>','').replace('\\n</p>','')\n\t\tresult_tbl = result.split(',')\n\t\tresult_parsed = [x for x in result_tbl if x.lower() not in pb_exceptions]\n\t\tif len(result_parsed) != len(set(result_parsed)):\n\t\t\ttemplate.add('has' + datatype + 'error','Yes')\n\ndef set_initial_order(wikitext):\n\ti = 0\n\tfor template in wikitext.filter_templates():\n\t\tif template.name.matches('MatchSchedule/Start'):\n\t\t\ti = 0\n\t\t\tcontinue\n\t\tif template.name.matches('MatchSchedule'):\n\t\t\ti += 1\n\t\t\tif template.has('initialorder'):\n\t\t\t\tcontinue\n\t\t\ttemplate.add('initialorder', str(i), before = 'team1')\n\nDOC_PAGES_TO_MAKE = [\n\t{\n\t\t'matches': r'^Module:Bracket/',\n\t\t'notmatches': r'(doc|Wiki)$',\n\t\t'pages': {\n\t\t\t'Tooltip:Module:{}' : '{{BracketTooltip}}',\n\t\t\t'Module:{}/doc' : '{{BracketDoc}}'\n\t\t}\n\t},\n\t{\n\t\t'matches': r'^Module:.*/i18n$',\n\t\t'notmatches': r'doc$',\n\t\t'pages': {\n\t\t\t'Module:{}/doc': '{{i18ndoc}}'\n\t\t}\n\t},\n\t{\n\t\t'matches': r'^Module:CargoDeclare/',\n\t\t'notmatches': r'doc$',\n\t\t'pages': {\n\t\t\t'Module:{}/doc': '{{CargodocModule}}'\n\t\t}\n\t}\n]\n\ndef make_doc_pages(site, p):\n\tfor case in DOC_PAGES_TO_MAKE:\n\t\tif 'matches' in case.keys():\n\t\t\tif not re.findall(case['matches'], p.name):\n\t\t\t\tcontinue\n\t\tif 'notmatches' in case.keys():\n\t\t\tif re.findall(case['notmatches'], p.name):\n\t\t\t\tcontinue\n\t\tfor i, (k, v) in enumerate(case['pages'].items()):\n\t\t\tsite.pages[k.format(p.page_title)].save(v, summary='Automated error fixing (Python)',\n\t\t\t\t\t\t\t\t\t tags='daily_errorfix')\n" } ]
24
CarlosZ/dotfiles
https://github.com/CarlosZ/dotfiles
672e94892988acff8e5134972e3087620e787ad8
233e6fed924e77c55631155f0eceec72966d59d6
da8f05db4234647f9cecc3a3432038c11bb22724
refs/heads/master
2020-02-29T19:02:18.369447
2016-07-25T17:48:07
2016-07-25T17:48:07
726,543
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 14.75, "blob_id": "153f46d0074ae81b702102b4d9ca7831c812871c", "content_id": "bd4633097008aa326d08cdf2f5c7b614115e3788", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 126, "license_type": "no_license", "max_line_length": 25, "num_lines": 8, "path": "/recipe/base/oh-my-zsh/aliases.zsh", "repo_name": "CarlosZ/dotfiles", "src_encoding": "UTF-8", "text": "alias cpdir=\"cp -r\"\nalias mvdir=\"mv\"\nalias rmdir=\"rm -rf\"\n\nalias psg=\"ps aux | grep\"\nalias rgrep=\"grep -r\"\n\nalias more=\"less\"\n" }, { "alpha_fraction": 0.7053072452545166, "alphanum_fraction": 0.7053072452545166, "avg_line_length": 38.77777862548828, "blob_id": "08c47bf643132700d735af1d10e336f457724f65", "content_id": "9c92d46371c807b6a684ca5c9bce9529b95de969", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/lib/ohmyzshrecipe.py", "repo_name": "CarlosZ/dotfiles", "src_encoding": "UTF-8", "text": "from baserecipe import BaseRecipe\n\nclass OhMyZshBaseRecipe(BaseRecipe):\n\n def __init__(self, recipe_dir, home_dir=None, debug_enabled=False):\n super(OhMyZshBaseRecipe, self).__init__(recipe_dir, home_dir, debug_enabled)\n self.omz_root = self.join(self.home_dir, \".oh-my-zsh\")\n self.omz_custom_dir = self.join(self.omz_root, \"custom\")\n self.omz_custom_profiles_dir = self.join(self.omz_custom_dir, \"profiles\")\n\n def symlink_profile(self, path, target):\n path = self.join(self.recipe_dir, path)\n target = self.join(self.omz_custom_profiles_dir, target)\n self.symlink(path, target)\n\n def remove_profile(self, path):\n path = self.join(self.omz_custom_profiles_dir, path)\n self.remove(path)\n" }, { "alpha_fraction": 0.6223974823951721, "alphanum_fraction": 0.6283911466598511, "avg_line_length": 28.082569122314453, "blob_id": "8e39aaaf631ec37dbb3c1d4edeaa1e31b1d729b5", "content_id": "161614c7cefbf8e4095a1ea072f651ab8e796e8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3170, "license_type": "no_license", "max_line_length": 74, "num_lines": 109, "path": "/lib/baserecipe.py", "repo_name": "CarlosZ/dotfiles", "src_encoding": "UTF-8", "text": "from abc import ABCMeta\nfrom abc import abstractmethod\nimport os\nimport shutil\nimport subprocess\n\nclass BaseRecipe(object):\n\n __metaclass__ = ABCMeta\n\n def __init__(self, recipe_dir, home_dir=None, debug_enabled=False):\n self.recipe_dir = os.path.abspath(recipe_dir)\n self.home_dir = os.path.expanduser(\"~\") if not home_dir else home_dir\n self.debug_enabled = debug_enabled\n self._GREEN_COLOR = \"\\033[92m\"\n self._RED_COLOR = \"\\033[91m\"\n self._BLUE_COLOR = \"\\033[94m\"\n self._END_COLOR = \"\\033[0m\"\n\n @abstractmethod\n def do(self):\n pass\n\n @abstractmethod\n def undo(self):\n pass\n\n def symlink(self, path, target):\n if self.debug_enabled:\n self.log_debug(\"symlink %s %s\" % (path, target))\n os.symlink(path, target)\n\n def symlink_home(self, path, target):\n path = self.join(self.recipe_dir, path)\n target = self.join(self.home_dir, target)\n self.symlink(path, target)\n\n def symlink_home_rec(self, dir_path, target_dir, predicate=None):\n dir_path = self.join(self.recipe_dir, dir_path)\n if not predicate:\n predicate = lambda x: True\n for f in os.listdir(dir_path):\n if predicate(f):\n self.symlink_home(self.join(dir_path, f),\n self.join(self.home_dir, target_dir, f))\n\n def remove(self, path):\n if self.debug_enabled:\n self.log_debug(\"remove %s\" % path)\n if os.path.isfile(path) or os.path.islink(path):\n os.remove(path)\n else:\n shutil.rmtree(path)\n\n def remove_home(self, path):\n path = self.join(self.home_dir, path)\n self.remove(path)\n\n def remove_home_rec(self, dir_path, predicate=None):\n dir_path = self.join(self.recipe_dir, dir_path)\n if not predicate:\n predicate = lambda x: True\n for f in os.listdir(dir_path):\n if predicate(f):\n self.remove_home(f)\n\n def copy_home(self, src, dest):\n self.check_call(\"cp %s %s\" %\n (self.join(self.recipe_dir, src), self.join(self.home_dir, dest)))\n\n def safe_mkdir(self, path):\n if not os.path.exists(path):\n if self.debug_enabled:\n self.log_debug(\"mkdir %s\" % path)\n os.mkdir(path)\n\n def join(self, *path):\n return os.path.join(*path)\n\n def check_call(self, command):\n if self.debug_enabled:\n self.log_debug(\"check_call: %s\" % command)\n subprocess.check_call(command, shell=True)\n\n def git_clone(self, repo, dest):\n self.check_call(\"git clone %s %s\" % (repo, dest))\n\n def backup(self, path, suffix=\"_bak\"):\n if os.path.exists(path):\n backup_path = \"%s%s\" % (path, suffix)\n if self.debug_enabled:\n self.log_debug(\"backup: %s %s\" % (path, backup_path))\n os.rename(path, backup_path)\n\n def restore(self, path, suffix=\"_bak\"):\n backup_path = \"%s%s\" % (path, suffix)\n if os.path.exists(backup_path):\n if self.debug_enabled:\n self.log_debug(\"restore: %s %s\" % (backup_path, path))\n os.rename(backup_path, path)\n\n def log_info(self, msg):\n print \"%s%s%s\" % (self._GREEN_COLOR, msg, self._END_COLOR)\n\n def log_debug(self, msg):\n print \"%s%s%s\" % (self._BLUE_COLOR, msg, self._END_COLOR)\n\n def log_error(self, msg):\n print \"%s%s%s\" % (self._RED_COLOR, msg, self._END_COLOR)\n" }, { "alpha_fraction": 0.6644782423973083, "alphanum_fraction": 0.6658604145050049, "avg_line_length": 27.653465270996094, "blob_id": "c6bccf3130f35dad708297e697a668f01490e4ed", "content_id": "72276bd7c7e72189d0827c073e5933c064ef88bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2894, "license_type": "no_license", "max_line_length": 81, "num_lines": 101, "path": "/init.py", "repo_name": "CarlosZ/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport argparse\nimport ConfigParser\nimport importlib\nimport inspect\nimport os\nimport socket\nimport subprocess\nimport sys\n\nsys.path.append(\"./recipe\")\nsys.path.append(\"./lib\")\n\nimport baserecipe\nimport recipe.base.recipe\n\nbin_dirs = []\ndebug_enabled = False\nhome_dir = None\nundo = False\nconfig = None\n\ndef download_recipes():\n if config.has_section(\"recipe\"):\n items = config.items(\"recipe\")\n for item in items:\n recipe_dir = os.path.join(\"recipe\", item[0])\n if not os.path.exists(recipe_dir):\n subprocess.check_call(\n \"git clone %s recipe/%s\" % (item[1], item[0]), shell=True)\n\ndef read_config():\n global config\n config = ConfigParser.RawConfigParser()\n config.read(\".config\")\n\ndef isrecipeclass(obj):\n return (inspect.isclass(obj) and\n issubclass(obj, baserecipe.BaseRecipe) and\n not inspect.isabstract(obj))\n\ndef walk_recipes():\n host_name = socket.gethostname()\n host_parts = host_name.split(\".\")\n accum = \"\"\n # try to detect a recipe for this host, using it's fqdn\n # if hostname is foo.bar.example.com then start trying:\n # com, example_com, bar_example_com and foo_bar_example_com\n for part in reversed(host_parts):\n if not accum:\n accum = part\n else:\n accum = part + \"_\" + accum\n recipe_dir = \"recipe/%s\" % accum\n if os.path.exists(recipe_dir):\n for f in os.listdir(recipe_dir):\n module_name, ext = os.path.splitext(f)\n if ext == \".py\" and module_name != \"__init__\" :\n run_recipes_from_module(recipe_dir, module_name)\n\ndef run_recipes_from_module(recipe_dir, module_name):\n module_fqn = \"%s.%s\" % (recipe_dir.replace(\"/\", \".\"), module_name)\n module = importlib.import_module(module_fqn)\n recipe_classes = inspect.getmembers(module, isrecipeclass)\n recipe_classes = [tup[1] for tup in recipe_classes]\n for recipe_class in sorted(recipe_classes):\n run_recipe(recipe_class, recipe_dir)\n\ndef run_recipe(recipe_class, recipe_dir):\n print \"running recipe %s.%s\" % (recipe_class.__module__, recipe_class.__name__)\n recipe_dir = os.path.abspath(recipe_dir)\n recipe = recipe_class(recipe_dir, home_dir, debug_enabled)\n if undo:\n recipe.undo()\n else:\n recipe.do()\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-u\", \"--undo\", action=\"store_true\",\n help=\"Whether to undo the setup\")\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\",\n help=\"Whether to debug each recipe step\")\n parser.add_argument(\"-i\", \"--install_dir\", help=\"Where to install\")\n args = parser.parse_args()\n\n global debug_enabled\n debug_enabled = args.debug\n global home_dir\n home_dir = args.install_dir\n global undo\n undo = args.undo\n print \"Installing to %s\" % home_dir\n read_config()\n download_recipes()\n run_recipe(recipe.base.recipe.Recipe, \"./recipe/base/\")\n walk_recipes()\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.664536714553833, "alphanum_fraction": 0.6677316427230835, "avg_line_length": 19.866666793823242, "blob_id": "f7109d6236323dbf6ff91483e1443bfffb8a344f", "content_id": "8616df22c2ebcb1d8677ae0c4d24372fba7f6afd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 62, "num_lines": 15, "path": "/recipe/base/bin/pretty_json.py", "repo_name": "CarlosZ/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport argparse\nimport json\n\ndef main(file):\n with open(file) as f:\n print json.dumps(json.load(f), indent=2)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\", help=\"The file to pretty print\")\n\n args = parser.parse_args()\n main(args.file)\n" }, { "alpha_fraction": 0.6643192768096924, "alphanum_fraction": 0.6643192768096924, "avg_line_length": 34.5, "blob_id": "3849ce5e22706826eeee6d74d8b8375e75ae2588", "content_id": "3b0e639be89e9afb54c1ca3481c87c2db81fc2e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1278, "license_type": "no_license", "max_line_length": 89, "num_lines": 36, "path": "/recipe/base/recipe.py.example", "repo_name": "CarlosZ/dotfiles", "src_encoding": "UTF-8", "text": "from ohmyzshrecipe import OhMyZshBaseRecipe\nimport os\n\nclass Recipe(OhMyZshBaseRecipe):\n\n def do(self):\n self.log_info(\"setting up .gitconfig\")\n self.symlink_home(\".gitconfig\", \".gitconfig\")\n\n self.log_info(\"setting up vim\")\n self.symlink_home(\".vim/.vimrc\", \".vimrc\")\n self.symlink_home(\".vim\", \".vim\")\n\n self.log_info(\"setting up oh-my-zsh\")\n # get the repo from the OH_MY_ZSH_REPO env var or default to robbyrussell's repo\n omz_repo = os.getenv(\"OH_MY_ZSH_REPO\",\n \"git://github.com/robbyrussell/oh-my-zsh.git\")\n self.git_clone(omz_repo, self.omz_root)\n self.git_clone(\"git://github.com/zsh-users/zsh-syntax-highlighting.git\",\n self.join(self.omz_root, \"plugins/zsh-syntax-highlighting\"))\n self.backup(self.join(self.home_dir, \".zshrc\"))\n self.copy_home(\"oh-my-zsh/.zshrc\", \".zshrc\")\n self.symlink_home_rec(\"oh-my-zsh\", self.omz_custom_dir, lambda f: f.endswith(\".zsh\"))\n\n def undo(self):\n self.log_info(\"removing .gitconfig\")\n self.remove_home(\".gitconfig\")\n\n self.log_info(\"removing vim\")\n self.remove_home(\".vimrc\")\n self.remove_home(\".vim\")\n\n self.log_info(\"removing oh-my-zsh\")\n self.remove_home(self.omz_root)\n self.remove_home(\".zshrc\")\n self.restore(self.join(self.home_dir, \".zshrc\"))\n" } ]
6
shantanumhapankar/Branch_Predictor
https://github.com/shantanumhapankar/Branch_Predictor
20ecea6f7648ed0031bf6e1a57475b43048dbe84
1692cdb3bbe8a94c470d42b13437a6985bfac7c6
b981db4645c814282381498d1b9fd8641cd83f24
refs/heads/master
2021-09-02T20:00:07.081139
2018-01-03T20:49:14
2018-01-03T20:49:14
116,175,689
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4848093092441559, "alphanum_fraction": 0.5048481225967407, "avg_line_length": 33.400001525878906, "blob_id": "fbb95fbc407fcb41308426a3a4c1a23ee6cefd9f", "content_id": "9a6dbaef5e33aec6d1167bdf63c6560ab51cae53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1547, "license_type": "no_license", "max_line_length": 126, "num_lines": 45, "path": "/1level.py", "repo_name": "shantanumhapankar/Branch_Predictor", "src_encoding": "UTF-8", "text": "import sys\n\n#0 is strong not taken 1 is weak not taken 2 is weak taken 3 is strongly taken.\nmisprediction_count = count = 0\nPHT_Entries = 1024\nPHT = []\nfor index in range(PHT_Entries):\n PHT.append(0)\n\n# print \"The counter bits are: \" , str(sys.argv[1])\nstatemax = sys.argv[1]\nstatemax = 2 ** int(statemax)\nstatemid = statemax/2\nstatemax -= 1\nstatemin = 0\n\nwith open(\"branch-trace-gcc.trace\", 'rb') as tracefile:\n for line in tracefile:\n if line.strip() == '':\n continue\n pc, status = line.split()\n pc_pht = int(pc) % 1024\n count += 1\n if 'T' in status:\n if PHT[pc_pht] < statemid: #if branch is 'Taken' but we had predicted 'Not Taken'\n if PHT[pc_pht] < statemin:\n PHT[pc_pht] = statemin\n misprediction_count += 1 #increment misprediction count\n else:\n if PHT[pc_pht] > statemax:\n PHT[pc_pht] = statemax\n PHT[pc_pht] += 1 \n\n if 'N' in status:\n if PHT[pc_pht] < statemid: #if branch is 'Not Taken' and we correctly predicted 'Not Taken'\n if PHT[pc_pht] < statemin:\n PHT[pc_pht] = statemin\n else:\n if PHT[pc_pht] > statemax:\n PHT[pc_pht] = statemax\n misprediction_count += 1 \n PHT[pc_pht] -= 1 \n\n\nprint (100 - (float(misprediction_count)*100/float(count)))" } ]
1
MJSindhu7/cmpe255-spring19-lab7
https://github.com/MJSindhu7/cmpe255-spring19-lab7
2f18029862154c61c8308c2c3c28536c5b572cef
17b6b45f6a1fade3ac5d4dad6241c3ec3930d90c
8cce636a1c0df959cf2cd30d425068850b105a01
refs/heads/master
2020-05-07T12:25:26.287598
2019-04-10T05:04:01
2019-04-10T05:04:01
180,504,381
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6833692193031311, "alphanum_fraction": 0.6892099380493164, "avg_line_length": 30.901960372924805, "blob_id": "edfb69930c6f71bc65d727d5c7dce5032eb95dee", "content_id": "60b4adf4dfb252c56b01fe7f3837537c5c6b8e2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3253, "license_type": "no_license", "max_line_length": 95, "num_lines": 102, "path": "/svm.py", "repo_name": "MJSindhu7/cmpe255-spring19-lab7", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd \nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\ndef linear_svm():\n # download data set: https://drive.google.com/file/d/13nw-uRXPY8XIZQxKRNZ3yYlho-CYm_Qt/view\n # info: https://archive.ics.uci.edu/ml/datasets/banknote+authentication\n\n # load data\n bankdata = pd.read_csv(\"/tmp/bill_authentication.csv\") \n\n # see the data\n bankdata.shape \n\n # see head\n bankdata.head() \n\n # data processing\n X = bankdata.drop('Class', axis=1) \n y = bankdata['Class'] \n\n from sklearn.model_selection import train_test_split \n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20) \n\n # train the SVM\n from sklearn.svm import SVC \n svclassifier = SVC(kernel='linear') \n svclassifier.fit(X_train, y_train) \n\n # predictions\n y_pred = svclassifier.predict(X_test) \n\n # Evaluate model\n from sklearn.metrics import classification_report, confusion_matrix \n print(confusion_matrix(y_test,y_pred)) \n print(classification_report(y_test,y_pred)) \n\nimport ssl\n\nssl._create_default_https_context = ssl._create_unverified_context\n\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\n\n# Assign colum names to the dataset\ncolnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']\n\n# Read dataset to pandas dataframe\nirisdata = pd.read_csv(url, names=colnames) \n\n# process\nX = irisdata.drop('Class', axis=1) \ny = irisdata['Class'] \n\n# train\nfrom sklearn.model_selection import train_test_split \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20) \ndef polynomial_kernel():\n # TODO\n # NOTE: use 8-degree in the degree hyperparameter. \n # Trains, predicts and evaluates the model\n from sklearn.svm import SVC\n svclassifier = SVC(kernel='poly',random_state=42)\n svclassifier.fit(X_train, y_train)\n svclassifier.fit(X_train, y_train)\n y_pred = svclassifier.predict(X_test)\n print(\"------POLYNOMIAL KERNEL------\")\n print(confusion_matrix(y_test,y_pred)) \n print(classification_report(y_test,y_pred)) \n\ndef gaussian_kernel():\n # TODO\n # Trains, predicts and evaluates the model\n from sklearn.svm import SVC\n svclassifier = SVC(kernel='rbf',random_state=42)\n svclassifier.fit(X_train, y_train)\n svclassifier.fit(X_train, y_train)\n y_pred = svclassifier.predict(X_test)\n print(\"------GAUSSIAN KERNEL------\") \n print(confusion_matrix(y_test,y_pred)) \n print(classification_report(y_test,y_pred)) \ndef sigmoid_kernel():\n # TODO\n # Trains, predicts and evaluates the model\n from sklearn.svm import SVC\n svclassifier = SVC(kernel='sigmoid',random_state=42)\n svclassifier.fit(X_train, y_train)\n svclassifier.fit(X_train, y_train)\n y_pred = svclassifier.predict(X_test)\n print(\"------SIGMOID KERNEL------\") \n print(confusion_matrix(y_test,y_pred)) \n print(classification_report(y_test,y_pred)) \ndef test():\n polynomial_kernel()\n gaussian_kernel()\n sigmoid_kernel()\n\ntest()" } ]
1
pedrobpio/learning-RNN-tensorflow
https://github.com/pedrobpio/learning-RNN-tensorflow
be0ef51d0db4f618eeaa25935356ec3da77a69d9
9d7f38d0b03b70b2c28f0192e112e80a603f5b35
270d827e6a00f6ce65fe66b874659d2c035535a5
refs/heads/master
2021-05-09T00:28:28.947576
2018-03-15T16:02:12
2018-03-15T16:02:12
119,744,835
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.686059296131134, "alphanum_fraction": 0.7178924083709717, "avg_line_length": 30.947368621826172, "blob_id": "6543b88c6550b9db2c18cb5e935290340c4faa1d", "content_id": "153c6910261bee4128ec3d415035854301305cf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1822, "license_type": "no_license", "max_line_length": 108, "num_lines": 57, "path": "/page1.py", "repo_name": "pedrobpio/learning-RNN-tensorflow", "src_encoding": "UTF-8", "text": "# https://medium.com/@erikhallstrm/hello-world-rnn-83cd7105b767\nfrom __future__ import print_function, division\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nnum_epochs = 100\ntotal_series_lenght = 50000\ntruncated_backprop_lenght = 15\nstate_size = 4\nnum_classes = 2\necho_step = 3\nbatch_size = 5\nnum_batches = total_series_lenght//batch_size//truncated_backprop_lenght\n\ndef generateData():\n x = np.array(np.random.choice(2, total_series_lenght, p=[0,5][0,5]))\n y = np.roll(x, echo_step)\n y[0:echo_step] = 0\n\n x = x.reshape((batch_size, -1))\n y = y.reshape((batch_size, -1))\n\n return (x, y) \n\nbatchX_placeholder = tf.placeholder(tf.float32, [batch_size, truncated_backprop_lenght])\nbatchY_placeholder = tf.placeholder(tf.int32, [batch_size, truncated_backprop_lenght])\n\ninit_state = tf.placeholder(tf.float32, [batch_size, state_size])\n\nw = tf.Variable(np.random.rand(state_size+1, state_size), dtype = tf.float32)\nb = tf.Variable(np.zeros((1,state_size)), dtype=tf.float32)\n\nw2 = tf.Variable(np.random.rand(state_size+1, state_size), dtype = tf.float32)\nb2 = tf.Variable(np.zeros((1, num_classes)), dtype = tf.float32)\n\n\n#unpack columns\n\ninput_series = tf.unstack(batchX_placeholder, axis=1)\nlabels_series = tf.unstack(batchY_placeholder, axis = 1)\n\n#forward pass\n\ncurrent_state = init_state\nstates_series = []\nfor current_input in input_series:\n current_input = tf.reshape(current_input, [batch_size, 1])\n input_and_state_concatenated = tf.concat(1, [current_input, current_state]) #incrising number of columns\n\n\n next_state = tf.tanh(tf.matmul(input_and_state_concatenated, w)+b) #broadcast adition\n states_series.append(next_state)\n current_state = next_state\n\n\nlogits_series = [tf.matmul(state, w2) + b2 for state in states_series] #Broadcasted addition\n\n" } ]
1
CallThemHunter/AzulAI
https://github.com/CallThemHunter/AzulAI
2137c2b3c24c45afb91f11ec4fa24a20ba301e51
533caa0fc56ff21c49f6c9af015737b2e56800d7
bd5212900142aa2adab2d4e7813457742e833c96
refs/heads/master
2023-09-04T16:50:36.214671
2021-11-18T04:55:59
2021-11-18T04:55:59
429,298,322
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.550137996673584, "alphanum_fraction": 0.5574976801872253, "avg_line_length": 29.19444465637207, "blob_id": "06f88a159a6fe7f21d9ead4a2d9d37530a2696c2", "content_id": "e63a68f4aabc6ec682db777cf4654e4914c0f219", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1087, "license_type": "no_license", "max_line_length": 94, "num_lines": 36, "path": "/Engine/Elements/bag.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "from __future__ import annotations\nfrom typing import List, Dict\nimport random\n\n\nclass Bag:\n def __init__(self, tile_types: List[int], tile_count: List[int]):\n self.tiles: Dict[int, int] = {}\n for (i, j) in zip(tile_types, tile_count):\n self.tiles[i] = j\n\n def is_empty(self):\n return 0 == sum(self.tiles.values())\n\n def count(self):\n return sum(self.tiles.values())\n\n def add_tile(self, tile_type):\n self.tiles[tile_type] += 1\n\n def add_bag(self, bag: Bag):\n for (tile_type, tile_count) in bag.tiles:\n if tile_type in self.tiles.keys():\n self.tiles[tile_type] += tile_count\n else:\n self.tiles[tile_type] = tile_count\n # reset dumped bag to 0\n bag.tiles[tile_type] = 0\n\n def draw_tile(self) -> int:\n tile: int = random.choices(list(self.tiles.keys()), list(self.tiles.values()), k=1)[0]\n self.tiles[tile] -= 1\n return tile\n\n def draw_tiles(self, n) -> List[int]:\n return [self.draw_tile() for _ in range(0, n)]\n" }, { "alpha_fraction": 0.5463786721229553, "alphanum_fraction": 0.5489199757575989, "avg_line_length": 27.10714340209961, "blob_id": "f868af32ccc7ba96ab5669477b2b95e9f8d4fb5b", "content_id": "4ac7971c549711602338ab4cf54909a5c118f09b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 58, "num_lines": 28, "path": "/Engine/Elements/factory.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "from typing import List\nfrom Engine.Elements.bag import Bag\nfrom Engine.Elements.center import Center\n\n\nclass Factory:\n def __init__(self, center: Center):\n self.center = center\n self.tiles: List[int] = []\n\n def is_empty(self) -> bool:\n return self.tiles == []\n\n def fill_factory(self, bag: Bag):\n # assume there are 4 tiles to draw\n self.tiles: List[int] = bag.draw_tiles(4)\n\n def claim_tile(self, color):\n drawn = []\n if color in self.tiles:\n for tile in reversed(self.tiles):\n if tile == color:\n drawn.append(self.tiles.pop())\n else:\n self.center.add_tile(self.tiles.pop())\n return True, drawn\n else:\n return False\n" }, { "alpha_fraction": 0.5576024055480957, "alphanum_fraction": 0.5672257542610168, "avg_line_length": 28.56910514831543, "blob_id": "a75fb2fa1b7a83055163d3bd24c03ec46f956ea4", "content_id": "a89041d3e20ece3d4a77ce6413912588554191c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3637, "license_type": "no_license", "max_line_length": 80, "num_lines": 123, "path": "/Engine/GameLoop.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "from Engine.Player.player import Player\nfrom Engine.Elements.bag import Bag\nfrom Engine.Elements.board import Board\nfrom Engine.Elements.center import Center\nfrom Engine.Elements.discard import Discard\nfrom Engine.Elements.factory import Factory\n\nPlayerCount = int\ndefault_bag = {\n 0: 20,\n 1: 20,\n 2: 20,\n 3: 20,\n 4: 20\n}\n\n\nclass Game:\n i = 0\n\n def __init__(self, n: PlayerCount):\n self.num_players = n\n self.bag: Bag\n self.discard: Discard\n self.factories: list[Factory]\n self.players: list[Player]\n\n if n == 2:\n num_factories = 5\n elif n == 3:\n num_factories = 7\n elif n == 4:\n num_factories = 9\n else:\n raise ValueError\n\n self.bag = Bag(list(default_bag.keys()), list(default_bag.values()))\n self.discard = Discard(self.bag)\n self.center = Center()\n\n self.factories = []\n for i in range(0, num_factories):\n self.factories += Factory(self.center)\n\n self.players = []\n for i in range(0, n):\n player = Player(i, Board(), self.factories, )\n self.players.append(player)\n\n for i in range(0, n):\n opponents: list[Player] = self.players.copy()\n opponents.pop(i)\n self.players[i].set_opponents(opponents)\n self.starting_player: Player = self.players[0]\n\n def fill_factories(self):\n self.center.has_starting_tile = True\n for factory in self.factories:\n self.check_bag()\n factory.fill_factory(self.bag)\n\n for player in self.players:\n if player.has_starting_marker:\n self.starting_player = player\n player.has_starting_marker = False\n\n def check_bag(self):\n if self.bag.count == 0:\n self.bag.add_bag(self.discard)\n if self.bag.count() < 4:\n tiles = self.discard.draw_tiles(4 - self.bag.count())\n for tile in tiles:\n self.bag.add_tile(tile)\n\n def set_starting_player(self):\n idx = self.players.index(self.starting_player)\n\n for _ in range(0, idx):\n self.players.append(self.players.pop(0))\n\n self.i = 0\n return\n\n def player_request(self):\n # provide state to agent\n return self.i, self.players[self.i].state()\n\n def player_action(self, args):\n # False if error\n # substitute with argument parsing\n success = self.players[self.i].make_choice(Factory(Center()), 0, 0)\n\n if not success:\n return False\n self.i = (self.i + 1) % self.num_players\n\n if self.no_tiles_remain():\n for player in self.players:\n player.end_turn_reset()\n if player.has_starting_marker:\n self.starting_player = player\n player.has_starting_marker = False\n self.center.has_starting_tile = True\n self.fill_factories()\n self.set_starting_player()\n\n state = self.players[self.i].state()\n score = self.players[self.i].score\n end_game = self.end_game_cond_met()\n # return True, new state, current score estimate, end game condition met\n return True, state, score, end_game\n\n def end_game_cond_met(self):\n return any([player.end_game_condition_met() for player in self.players])\n\n def no_tiles_remain(self):\n for factory in self.factories:\n if not factory.is_empty():\n return False\n\n if self.center.is_empty():\n return True\n return False\n" }, { "alpha_fraction": 0.4890387952327728, "alphanum_fraction": 0.4890387952327728, "avg_line_length": 23.625, "blob_id": "87847031a6ad27cb4257d91ca688fb5241c390a7", "content_id": "43c31ae18461839f8a1abb8f3987bfdd46ac44ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 50, "num_lines": 24, "path": "/Engine/Elements/center.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "class Center:\n has_starting_tile = True\n\n def __init__(self):\n self.tiles = []\n\n def is_empty(self):\n return self.tiles == []\n\n def add_tile(self, tile_type: int):\n self.tiles += [tile_type]\n\n def claim_tile(self, color):\n ret = []\n remaining = []\n for tile in reversed(self.tiles):\n if tile == color:\n ret.append(self.tiles.pop())\n else:\n remaining.append(self.tiles.pop())\n self.tiles = remaining\n if ret == []:\n return False, []\n return True, ret\n\n\n" }, { "alpha_fraction": 0.48151931166648865, "alphanum_fraction": 0.5005105137825012, "avg_line_length": 27.80588150024414, "blob_id": "647c9c809e298457d38f7f00fd30007d81812d36", "content_id": "7ddb4ede08e2e4f15b6a01f04f18f946f3075177", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4897, "license_type": "no_license", "max_line_length": 94, "num_lines": 170, "path": "/Engine/Elements/board.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "from typing import List, Dict\nfrom Engine.Elements.bag import Bag\n\n# 0: Blue\n# 1: Yellow\n# 2: Red\n# 3: Black\n# 4: Cyan\n\n\ndef bag_from_dict(tile_dict: Dict[int, int]):\n return Bag(list(tile_dict.keys()), list(tile_dict.values()))\n\n\nclass Board:\n end_game_condition_met = False\n\n rows: List[int] = [0, 0, 0, 0, 0]\n row_color: List[int] = [None for _ in range(0, 5)]\n row_is_filled: List[bool] = [False for _ in range(0, 5)]\n\n wall_colors_filled: List[List[bool]] = [[False for _ in range(0, 5)] for _ in range(0, 5)]\n wall: List[List[bool]] = [[False for _ in range(0, 5)] for _ in range(0, 5)]\n\n # provide color\n floor: List[int] = []\n floor_penalty = [1, 1, 2, 2, 2, 3, 3]\n\n score = 0\n\n def end_turn_reset_rows(self):\n ret_tiles = {\n 0: 0,\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0\n }\n for i, row in enumerate(self.rows):\n row_capacity = i + 1\n color = self.row_color[i]\n\n if row_capacity == self.rows[i]:\n self.fill_wall(i, color)\n self.rows[i] = 0\n ret_tiles[color] += row_capacity - 1\n\n return bag_from_dict(ret_tiles)\n\n def reset_floor(self):\n ret_tiles = {\n 0: 0,\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0\n }\n deduction = 0\n for i, color in enumerate(self.floor):\n if color != -1:\n ret_tiles[color] += 1\n deduction += self.floor_penalty[i]\n\n self.floor = []\n return deduction, bag_from_dict(ret_tiles)\n\n def fill_row(self, row: int, color: int, n: int):\n if self.row_color[row] is None:\n # starting to add a color to row\n self.row_color[row] = color\n elif self.row_color[row] != color:\n # trying to add a different color to the tile row\n return False\n elif color in self.wall_colors_filled[row]:\n # trying to add a color that's already present in the wall\n return False\n if self.row_is_filled[row]:\n return False\n\n row_capacity = row + 1\n tiles_in_row = self.rows[row]\n if tiles_in_row + n < row_capacity:\n self.rows[row] = tiles_in_row + n\n elif tiles_in_row + n == row_capacity:\n self.rows[row] = tiles_in_row + n\n self.row_is_filled[row] = True\n else:\n self.rows[row] = row_capacity\n self.row_is_filled[row] = True\n self.floor += [color] * (tiles_in_row + n - row_capacity)\n return True\n\n def fill_wall(self, i: int, color: int):\n # 0: Blue\n # 1: Yellow\n # 2: Red\n # 3: Black\n # 4: Cyan\n # right rotated by i rows\n col = (i + color) % 5\n self.wall[i][col] = True\n self.wall_colors_filled[i][color] = True\n self.score_tile(i, col)\n\n # updates score\n def score_tile(self, row, col):\n horizontal = self.count_connected_horizontal(row, col)\n vertical = self.count_connected_vertical(row, col)\n if horizontal == 0 and vertical == 0:\n self.score += 1\n else:\n self.score += horizontal + vertical\n\n def remove_tile(self, row, col):\n horizontal = self.count_connected_horizontal(row, col)\n vertical = self.count_connected_vertical(row, col)\n if horizontal == 0 and vertical == 0:\n self.score -= 1\n else:\n self.score -= horizontal + vertical\n\n self.wall[row][col] = False\n self.wall_colors_filled[row][(col - row) % 5] = False\n return self.score\n\n def count_connected_vertical(self, row, col):\n link_remains = True\n length = 0\n for i in range(row + 1, 5):\n if link_remains and self.wall[i][col]:\n length += 1\n else:\n link_remains = False\n\n link_remains = True\n for i in range(row - 1, -1, -1):\n if link_remains and self.wall[i][col]:\n length += 1\n else:\n link_remains = False\n\n if length != 0:\n return length + 1\n return 0\n\n def count_connected_horizontal(self, row, col):\n link_remains = True\n length = 0\n for i in range(col + 1, 5):\n if link_remains and self.wall[row][i]:\n length += 1\n else:\n link_remains = False\n\n link_remains = True\n for i in range(col - 1, -1, -1):\n if link_remains and self.wall[row][i]:\n length += 1\n else:\n link_remains = False\n\n if length != 0:\n length += 1\n if length == 5:\n self.end_game_condition_met = True\n return length\n return 0\n\n def score_bonus(self):\n pass\n" }, { "alpha_fraction": 0.5797452926635742, "alphanum_fraction": 0.5936931371688843, "avg_line_length": 30.711538314819336, "blob_id": "b4eecc010e35281b5a3fd21a322b84e61fd93d6b", "content_id": "95f519a0d1012981aa036644d03f6a19877e10c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1649, "license_type": "no_license", "max_line_length": 96, "num_lines": 52, "path": "/Engine/Player/ScoringApp.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "import wx\nfrom Engine.Elements.board import Board\n\n\nclass AzulScoringApp(wx.Frame):\n board = Board()\n score = 0\n\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=title, size=(400, 300))\n self.main_sizer = wx.BoxSizer(wx.VERTICAL)\n\n self.score_sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.quote = wx.StaticText(self, label=\"Player Score: \" + str(self.score), pos=(20, 30))\n self.score_sizer.Add(self.quote)\n\n self.wall_sizer = wx.GridSizer(5, gap=(1, 1))\n self.buttons = []\n for i in range(0, 25):\n self.buttons.append(wx.Button(self, id=i, label=\"\"))\n self.wall_sizer.Add(self.buttons[i], 1, wx.EXPAND)\n self.Bind(wx.EVT_BUTTON, self.toggleButton, source=self.buttons[i])\n\n self.SetSizer(self.wall_sizer)\n self.SetAutoLayout(1)\n self.wall_sizer.Fit(self)\n\n self.main_sizer.Add(self.score_sizer, 0, wx.ALIGN_CENTER_HORIZONTAL)\n self.main_sizer.Add(self.wall_sizer, 0, wx.CENTER)\n self.Show()\n\n def toggleButton(self, event: wx.Button):\n id = event.Id\n row = id // 5\n col = id % 5\n score: int\n if event.EventObject.Label == \"\":\n event.EventObject.Label = \"X\"\n score = self.board.add_tile(row, col)\n else:\n event.EventObject.Label = \"\"\n score = self.board.remove_tile(row, col)\n self.quote.Label = \"Player Score: \" + str(score)\n self.quote.LabelText = \"Player Score: \" + str(score)\n\n\napp = wx.App(False)\n\nframe = AzulScoringApp(None, \"Azul Scoring App\")\n\nframe.Show(True)\napp.MainLoop()\n" }, { "alpha_fraction": 0.6264367699623108, "alphanum_fraction": 0.6321839094161987, "avg_line_length": 28, "blob_id": "2b2cb22ef25d101816ce0060b1d2ec319e48d95e", "content_id": "c181f5bd2dbb832f8093071e8c33704f727c361c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 81, "num_lines": 6, "path": "/Engine/Elements/discard.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "from Engine.Elements.bag import Bag\n\n\nclass Discard(Bag):\n def __init__(self, bag: Bag):\n super(Discard, self).__init__(list(bag.tiles.keys()), [0]*len(bag.tiles))\n" }, { "alpha_fraction": 0.619767427444458, "alphanum_fraction": 0.6209302544593811, "avg_line_length": 35.33802795410156, "blob_id": "3eb4345f87aa3a2fd07031a6dc46deaa030d8285", "content_id": "782c0dc43673d232e26e6cb77574a6d99f2d8c7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2580, "license_type": "no_license", "max_line_length": 113, "num_lines": 71, "path": "/Engine/Player/player.py", "repo_name": "CallThemHunter/AzulAI", "src_encoding": "UTF-8", "text": "from __future__ import annotations\nfrom Engine.Elements.board import Board\nfrom Engine.Elements.center import Center\nfrom Engine.Elements.discard import Discard\nfrom Engine.Elements.factory import Factory\nfrom typing import List, Union\n\n\nclass Player:\n has_starting_marker = False\n\n def __init__(self, player_id: int, board: Board, center: Center, discard: Discard, factories: List[Factory]):\n self.id = player_id\n self.score = 0\n self._board = board\n self._center = center\n self._discard = discard\n self._factories = factories\n self._opponents: List[Player] = []\n\n def set_opponents(self, opponents: List[Player]):\n self._opponents = opponents\n\n def end_game_condition_met(self):\n return self._board.end_game_condition_met\n\n def end_turn_reset(self):\n self._board.end_turn_reset_rows()\n deduction, discard_tiles = self._board.reset_floor()\n self._board.score -= deduction\n self.score = self._board.score\n self._discard.add_bag(discard_tiles)\n\n def state(self):\n start_tile = self._center.has_starting_tile\n rows = self._board.rows\n wall = self._board.wall\n opponent_rows = [player._board.rows for player in self._opponents]\n opponent_wall = [player._board.wall for player in self._opponents]\n center_tiles = [self._center.tiles]\n factory_tiles = [factory.tiles for factory in self._factories]\n\n return rows, wall, opponent_rows, opponent_wall, start_tile, center_tiles, factory_tiles\n\n # interface for AI to make choices\n\n def make_choice(self, source: Union[Center, Factory], color: int, row: int):\n # return True if valid choice\n # return False if invalid choice\n if isinstance(source, Factory):\n success, tiles = source.claim_tile(color)\n if not success:\n return False\n elif isinstance(source, Center):\n success, tiles = source.claim_tile(color)\n if not success:\n return False\n if source.has_starting_tile:\n self.has_starting_marker = True\n source.has_starting_tile = False\n # add starting tile to board.\n self._board.floor += [-1]\n else:\n return False\n\n # guaranteed to have 1 tile at least\n # return False if wrong color, color already on wall, or row filled\n success = self._board.fill_row(row, color, len(tiles))\n if not success:\n return False\n return True\n" } ]
8
Try-Try-Again/maths
https://github.com/Try-Try-Again/maths
3cec458cc3decc9f19fe3805c082d73aefc3f6f8
b101bbde1dcb62e991ce1604baadc7c51023ee11
c4462c7b094a874742fd8e07a873f3a39ac03426
refs/heads/master
2023-03-01T18:34:20.411864
2021-02-09T06:39:47
2021-02-09T06:39:47
333,632,612
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7288135886192322, "alphanum_fraction": 0.7288135886192322, "avg_line_length": 28.5, "blob_id": "1a4d8326ff44655957b49117d0756bdfd1d96d33", "content_id": "6d3f471cb375a0929292856a71901871ed0bc197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 59, "license_type": "no_license", "max_line_length": 38, "num_lines": 2, "path": "/wiki/.ipynb_checkpoints/index-checkpoint.md", "repo_name": "Try-Try-Again/maths", "src_encoding": "UTF-8", "text": "# MATH STUDIES WIKI\n## [Math_Functions](Math_Functions.md)\n" }, { "alpha_fraction": 0.6992481350898743, "alphanum_fraction": 0.6992481350898743, "avg_line_length": 43.33333206176758, "blob_id": "7927166b58f1c4abed7ac1701a2d782206a3037c", "content_id": "becb248772a828179d29253852cb7f9a5af8ba50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 133, "license_type": "no_license", "max_line_length": 57, "num_lines": 3, "path": "/wiki/Math_Functions.md", "repo_name": "Try-Try-Again/maths", "src_encoding": "UTF-8", "text": "# Math Functions\n## [one_plus_one](../notebooks/functions/one_plus_one.py)\n## [two_plus_two](../notebooks/functions/two_plus_two.py)\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 20, "blob_id": "4171126c23f6ff2c106ba9da878b983c44a2b509", "content_id": "3cfe477e4f380d7c19cb85416a89de780d1950db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 42, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/.ipynb_checkpoints/README-checkpoint.md", "repo_name": "Try-Try-Again/maths", "src_encoding": "UTF-8", "text": "# MATH STUDIES\n## [WIKI](./wiki/index.md)\n" }, { "alpha_fraction": 0.5727272629737854, "alphanum_fraction": 0.6227272748947144, "avg_line_length": 31.899999618530273, "blob_id": "acdbd97548bc05195f051238ee668dd885a1d910", "content_id": "a0413d5d08132351d4908dcfcb90ef66ef55655d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 58, "num_lines": 40, "path": "/notebooks/functions/.ipynb_checkpoints/test_simplify_square_root-checkpoint.py", "repo_name": "Try-Try-Again/maths", "src_encoding": "UTF-8", "text": "import unittest\nfrom simplify_square_root import simplify_square_root\n\n\nclass SimplifyingSquareRoot(unittest.TestCase):\n\n def test_sqrt_of_75_returns_5_and_3(self):\n whole_num, sqrt_num = simplify_square_root(1, 75)\n self.assertEqual(whole_num, 5)\n self.assertEqual(sqrt_num, 3)\n\n def test_5_times_sqrt_of_117_returns_15_and_13(self):\n whole_num, sqrt_num = simplify_square_root(5, 117)\n self.assertEqual(whole_num, 15)\n self.assertEqual(sqrt_num, 13)\n \n def test_sqrt_of_18_returns_3_and_2(self):\n whole_num, sqrt_num = simplify_square_root(1, 18)\n self.assertEqual(whole_num, 3)\n self.assertEqual(sqrt_num, 2)\n \n def test_sqrt_of_108_returns_6_and_3(self):\n whole_num, sqrt_num = simplify_square_root(1, 108)\n self.assertEqual(whole_num, 6)\n self.assertEqual(sqrt_num, 3)\n \n def test_sqrt_of_28_returns_2_and_7(self):\n whole_num, sqrt_num = simplify_square_root(1, 28)\n self.assertEqual(whole_num, 2)\n self.assertEqual(sqrt_num, 7)\n \n def test_sqrt_of_450_returns_15_2(self):\n whole_num, sqrt_num = simplify_square_root(15, 2)\n self.assertEqual(whole_num, 15)\n self.assertEqual(sqrt_num, 2)\n\n\n \nif __name__ == '__main__':\n unittest.main()\n\n " }, { "alpha_fraction": 0.5808966755867004, "alphanum_fraction": 0.5896686315536499, "avg_line_length": 41.79166793823242, "blob_id": "42a29d5e405065815678239f419751765e3e46d6", "content_id": "5d16dd4c6da827f7da71bebc3622ee840d0408a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 83, "num_lines": 24, "path": "/notebooks/functions/.ipynb_checkpoints/simplify_square_root-checkpoint.py", "repo_name": "Try-Try-Again/maths", "src_encoding": "UTF-8", "text": "def simplify_square_root(whole_number, radicand):\n radicand_not_prime = True\n \n while radicand_not_prime:\n #start with perfect square of 4\n perfect_square = 4\n #while our perfect square is less than our radicand\n while perfect_square < radicand:\n #if the radicand is divisable by our perfect square\n if radicand % perfect_square == 0:\n #multiply our whole number by the square root of our perfect square\n whole_number *= perfect_square ** 0.5\n #divide the radicand by the perfect square\n radicand /= perfect_square\n break\n #otherwise\n else:\n #try again with the next perfect square\n perfect_square = (perfect_square ** 0.5 + 1) ** 2\n #if we did not find a perfect square then the radicand is prime\n else:\n radicand_not_prime = False\n #return the whole number and the radicand\n return whole_number, radicand" }, { "alpha_fraction": 0.6699029207229614, "alphanum_fraction": 0.6699029207229614, "avg_line_length": 24.75, "blob_id": "1d73d832c7c5d6b98589f871f67071809ddff08c", "content_id": "036f33f35bd66da440cac5b16e635b27b47db454", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 103, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/notebooks/functions/two_plus_two.py", "repo_name": "Try-Try-Again/maths", "src_encoding": "UTF-8", "text": "from .one_plus_one import one_plus_one\n\ndef two_plus_two():\n return one_plus_one() + one_plus_one()\n" } ]
6
hack4rigatoni/foxnite
https://github.com/hack4rigatoni/foxnite
5f1de0df998f7525173647ef2cef368e3f7aa03a
c081afe1ddfa3e93d468b394a6f20641f049cba9
a7b56568163feed128dc88e3159f8b9f4f26f4f5
refs/heads/master
2021-01-24T17:18:03.572779
2018-03-01T02:18:43
2018-03-01T02:18:43
123,228,361
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.42596566677093506, "alphanum_fraction": 0.43562230467796326, "avg_line_length": 19.94382095336914, "blob_id": "0acec32ce96c1b6d5bec77bed7afc0a1b148ed24", "content_id": "8e0871af03ca8fda9f2ccf396a0e841eb8755e57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1864, "license_type": "permissive", "max_line_length": 45, "num_lines": 89, "path": "/foxnite.py", "repo_name": "hack4rigatoni/foxnite", "src_encoding": "UTF-8", "text": "#-----------------------------------#\n# permutations. #\n#-----------------------------------#\n\n# input <password> from\n# system.arguments\nimport sys\nif not len(sys.argv) in [2,3]:\n print \"%s <password>\" % sys.argv[0]\n sys.exit(1)\n\nif len(sys.argv) == 3:\n if sys.argv[1] == 'x':\n password = sys.argv[2]\n determined = True\n else:\n print \"%s <password>\" % sys.argv[0]\n sys.exit(1)\n\nif len(sys.argv) == 2:\n password = sys.argv[1]\n determined = False\n\n#____________________________________\n# CHARACTER SUBSTITUTION OPTIONS\n# > dictionary of all letters,\n# |a| -> |a|,|A|,|@|\n# . . . .\noptions = {}\n\n# take base alphabeth\ncharacters = \"abcdefghijklmnopqrstuvwxyz\"\n\n# add all CaSe\nfor char in characters:\n options[char] = [char.lower(),char.upper()]\n\n# special substitutions\noptions['a'].append('@')\noptions['e'].append('3')\noptions['e'].append('&')\noptions['i'].append('1')\noptions['i'].append('!')\noptions['o'].append('0')\noptions['s'].append('$')\n\n\n#----------------------\n# || -> |p|a|s|s|w|..|d\n\nhead = \"\"\ntail = password\n\n# head options tail\n#-----------------------------------\n# |p| -> |a| -> |s|..|d\n# -> |S|..|d\n# -> |$|..|d\n\n# -> |A| -> |s|..|d\n# -> |S|..|d\n# -> |$|..|d\n\n# -> |@| -> |s|..|d\n# -> |S|..|d\n# -> |$|..|d\n\n#____________________________________\n#====================================\ndef permutation(head,tail):\n\n if len(tail) == 1: # if last char\n for opt in options[tail[0]]:\n print head+opt\n return # done! (end of branch)\n\n for opt in options[tail[0]]:\n permutation(head+opt,tail[1:])\n#------------------------------------\n#\n\n\n# before we go..\nif not determined:\n from prudent_fox import warning\n warning(tail,options)\n\n# do it!\npermutation(head,tail)\n" }, { "alpha_fraction": 0.7209302186965942, "alphanum_fraction": 0.7298747897148132, "avg_line_length": 38.78571319580078, "blob_id": "9b62d619ac7b8869d280be236edcc9026c016152", "content_id": "7840bd13675a6b484ce1f88d62710184b2bc1743", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 559, "license_type": "permissive", "max_line_length": 200, "num_lines": 14, "path": "/README.md", "repo_name": "hack4rigatoni/foxnite", "src_encoding": "UTF-8", "text": "# foxnite\nPossibly elegant dictionary generator for password capitalizaion/encoding.\n \n*to the frosty nights when foxes dance in the snow..*\n\nUsage:\n----\n - python foxnite.py < password >\n \n all possible permutation of the password considering capitalization and common substitutions 'e' -> '3','&'\n \n - python ice-foxnite.py < a_very_long_password >\n \n reduces dictionary size by introducing rules. 'max_capitals' -> 8 , 'min_capitals' -> 4 will only output results with at least 4 capitalized letters and no more than 8. Look at the code for more..\n \n" }, { "alpha_fraction": 0.485029935836792, "alphanum_fraction": 0.5089820623397827, "avg_line_length": 24.66666603088379, "blob_id": "cf58fc3680c5ca7f08307baac5f16416e6c2c19c", "content_id": "c6edc6fc1c618c7664c19c6f3140c09560feeabe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "permissive", "max_line_length": 74, "num_lines": 39, "path": "/prudent_fox.py", "repo_name": "hack4rigatoni/foxnite", "src_encoding": "UTF-8", "text": "import sys\n\n#=====================================\n# File Size Human Formatting.\n# By > Sridhar Ratnakumar & Wai Ha Lee\n#-------------------------------------\ndef sizeof_fmt(num, suffix='B'):\n for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:\n if abs(num) < 1024.0:\n return \"%3.1f %s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f %s%s\" % (num, 'Yi', suffix)\n\ndef usure():\n pass \n\n\n#_________!!!_________\n#=====================\ndef warning(tail,options):\n\n # calc characters factors\n # p a s s w o r d\n # 2*3*3*3*2*3*2*2 = all combos\n\n permutations = 1\n for char in tail:\n permutations *= len(options[char])\n\n psw_size = len(tail)\n\n # One Byte for each char + \\n\n file_size = permutations * (psw_size+1)\n\n print \"This password will generate %i permutations.\" % permutations\n print \"Predicted dictionary size: %s\" % sizeof_fmt(file_size)\n print\n print \"if that is ok, run: python foxnite.py x password > dictionary\"\n sys.exit(0)\n\n" }, { "alpha_fraction": 0.4319186508655548, "alphanum_fraction": 0.4615384638309479, "avg_line_length": 21.176469802856445, "blob_id": "0f1330a8ab9416c302a20e7232f1ed7334729def", "content_id": "8dfa04445239cc6d9a4f3f605db71c4709923349", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2262, "license_type": "permissive", "max_line_length": 53, "num_lines": 102, "path": "/ice-foxnite.py", "repo_name": "hack4rigatoni/foxnite", "src_encoding": "UTF-8", "text": "#-----------------------------------#\n# permutations. filtered. #\n#-----------------------------------#\n\n# input <password> from\n# system.arguments\nimport sys\nif not len(sys.argv) == 2:\n print \"catnite.py <password>\"\n sys.exit(1)\n\n\n#____________________________________\n# CHARACTER SUBSTITUTION OPTIONS\noptions = {}\n\n# base alphabeth\ncharacters = \"abcdefghijklmnopqrstuvwxyz\"\n\n# CaSe\nfor char in characters:\n options[char] = [(char.lower(),0),(char.upper(),1)]\n\n# special substitutions\noptions['a'].append(('@',1000))\noptions['e'].append(('3',1000))\noptions['e'].append(('&',1000))\noptions['i'].append(('1',1000))\noptions['i'].append(('!',1000))\noptions['o'].append(('0',1000))\noptions['s'].append(('$',1000))\n\n#------------------------------------\n# ENTROPY CHECK..\n# > reduce dictionary size by limiting\n# the number of substitutions\n#------------------------------------\n# Uppercase weight = 1\n# Special char weight = 1000\n#\n#\n\n#==== FIDDLE HERE!! ===========\n# max & min number of uppercase\nmaxupper = 8\nminupper = 4\n# max & min sobsitutions\nmaxspecial = 6 * 1000 # scale up\nminspecial = 3 * 1000 # 4 comparison\n\n\n# || -> |p|a|s|s|w|..|d\n\nhead = \"\"\ntail = sys.argv[1]\n\nentropy = 0\n\n# head options tail\n#-----------------------------------\n# |p| -> |a| -> |s|..|d\n# -> |S|..|d\n# -> |$|..|d\n\n# -> |A| -> |s|..|d\n# -> |S|..|d\n# -> |$|..|d\n\n# -> |@| -> |s|..|d\n# -> |S|..|d\n# -> |$|..|d\n\n#____________________________________\n#####################################\ndef permutation(head,tail,entropy):\n\n if entropy % 1000 > maxupper:\n return # too many uppercases\n\n if entropy > maxspecial:\n return # too many synbols\n\n if len(tail) == 1: # if last char\n for opt,entr in options[tail[0]]:\n\n if entropy < minspecial:\n return # too few synbols\n\n if entropy % 1000 < minupper:\n return # too few uppercases\n\n print head+opt\n return # done! (end of branch)\n\n ########## RECURSION #########################\n for opt,entr in options[tail[0]]:\n permutation(head+opt,tail[1:],entropy+entr)\n#____________________________________\n\n\n# do it!\npermutation(head,tail,entropy)\n" } ]
4
nakamura196/aa-exif
https://github.com/nakamura196/aa-exif
8ff8081352cd1d41795520ea68c991a854813cfc
8d27d364203840d876a30709f4c2e70d4b7a1583
d17d21d9bc4e034df9ce7a62ba20b8ea56db56e5
refs/heads/master
2023-03-20T10:04:49.868010
2021-03-10T23:13:16
2021-03-10T23:13:16
345,681,769
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5609903335571289, "alphanum_fraction": 0.5869565010070801, "avg_line_length": 29.283018112182617, "blob_id": "e6c851cacfbc2abb91f7c0931a4b19fa512526b9", "content_id": "5015b58725e1d3af5737929d5524c226508b16f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1920, "license_type": "no_license", "max_line_length": 105, "num_lines": 53, "path": "/main.py", "repo_name": "nakamura196/aa-exif", "src_encoding": "UTF-8", "text": "from PIL import Image\r\nimport argparse # 1. argparseをインポート\r\nimport glob\r\nimport os\r\n\r\nparser = argparse.ArgumentParser() # 2. パーサを作る\r\n\r\n# 3. parser.add_argumentで受け取る引数を追加していく\r\nparser.add_argument('path', help='入力フォルダへのパス') # 必須の引数を追加\r\n\r\nargs = parser.parse_args() # 4. 引数を解析\r\n\r\nfiles = []\r\n\r\nsuffixes = [\"JPG\", \"png\"]\r\n\r\nfor suffix in suffixes:\r\n files.extend(glob.glob(args.path+\"/**/*.{}\".format(suffix), recursive=True))\r\n\r\n \r\n\r\n# Orientation タグ値にしたがった処理\r\n# PIL における Rotate の角度は反時計回りが正\r\nconvert_image = {\r\n 1: lambda img: img,\r\n 2: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT), # 左右反転\r\n 3: lambda img: img.transpose(Image.ROTATE_180), # 180度回転\r\n 4: lambda img: img.transpose(Image.FLIP_TOP_BOTTOM), # 上下反転\r\n 5: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Pillow.ROTATE_90), # 左右反転&反時計回りに90度回転\r\n 6: lambda img: img.transpose(Image.ROTATE_270), # 反時計回りに270度回転\r\n 7: lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Pillow.ROTATE_270), # 左右反転&反時計回りに270度回転\r\n 8: lambda img: img.transpose(Image.ROTATE_90), # 反時計回りに90度回転\r\n}\r\n\r\nfor file in files:\r\n\r\n img = Image.open(file)\r\n exif = img._getexif()\r\n\r\n if exif:\r\n\r\n orientation = exif.get(0x112, 1)\r\n\r\n new_img = convert_image[orientation](img)\r\n\r\n else:\r\n new_img = img\r\n\r\n output_path = file.replace(\"input/\", \"output/\")\r\n dir_path = os.path.dirname(output_path)\r\n os.makedirs(dir_path, exist_ok=True)\r\n\r\n new_img.save(output_path)" } ]
1
SatyamDG/Udacity_Data_Scientist_NanoDegree_Capstone
https://github.com/SatyamDG/Udacity_Data_Scientist_NanoDegree_Capstone
b1cf3c7d13658dfd65f5ecd651bfa43ac47c1402
1051eae354e382223e283e133a18214430fc03d6
574c38f66e65b9bb21ebe1d510062043350f2469
refs/heads/master
2022-09-10T23:49:27.327814
2020-05-27T03:33:01
2020-05-27T03:33:01
260,846,616
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.7285410165786743, "alphanum_fraction": 0.7412461638450623, "avg_line_length": 42.15114212036133, "blob_id": "272fe1b4ea1a62a41404d3d6275712a03a1c0efb", "content_id": "644bff76aeb3e97b32b0d8ae65a4ca25e48b392f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 101928, "license_type": "permissive", "max_line_length": 623, "num_lines": 2362, "path": "/Starbucks_Capstone_notebook.py", "repo_name": "SatyamDG/Udacity_Data_Scientist_NanoDegree_Capstone", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Starbucks Capstone Challenge\n# \n# ### Introduction\n# \n# This data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer such as a discount or BOGO (buy one get one free). Some users might not receive any offer during certain weeks. \n# \n# Not all users receive the same offer, and that is the challenge to solve with this data set.\n# \n# Your task is to combine transaction, demographic and offer data to determine which demographic groups respond best to which offer type. This data set is a simplified version of the real Starbucks app because the underlying simulator only has one product whereas Starbucks actually sells dozens of products.\n# \n# Every offer has a validity period before the offer expires. As an example, a BOGO offer might be valid for only 5 days. You'll see in the data set that informational offers have a validity period even though these ads are merely providing information about a product; for example, if an informational offer has 7 days of validity, you can assume the customer is feeling the influence of the offer for 7 days after receiving the advertisement.\n# \n# You'll be given transactional data showing user purchases made on the app including the timestamp of purchase and the amount of money spent on a purchase. This transactional data also has a record for each offer that a user receives as well as a record for when a user actually views the offer. There are also records for when a user completes an offer. \n# \n# Keep in mind as well that someone using the app might make a purchase through the app without having received an offer or seen an offer.\n# \n# ### Example\n# \n# To give an example, a user could receive a discount offer buy 10 dollars get 2 off on Monday. The offer is valid for 10 days from receipt. If the customer accumulates at least 10 dollars in purchases during the validity period, the customer completes the offer.\n# \n# However, there are a few things to watch out for in this data set. Customers do not opt into the offers that they receive; in other words, a user can receive an offer, never actually view the offer, and still complete the offer. For example, a user might receive the \"buy 10 dollars get 2 dollars off offer\", but the user never opens the offer during the 10 day validity period. The customer spends 15 dollars during those ten days. There will be an offer completion record in the data set; however, the customer was not influenced by the offer because the customer never viewed the offer.\n# \n# ### Cleaning\n# \n# This makes data cleaning especially important and tricky.\n# \n# You'll also want to take into account that some demographic groups will make purchases even if they don't receive an offer. From a business perspective, if a customer is going to make a 10 dollar purchase without an offer anyway, you wouldn't want to send a buy 10 dollars get 2 dollars off offer. You'll want to try to assess what a certain demographic group will buy when not receiving any offers.\n# \n# ### Final Advice\n# \n# Because this is a capstone project, you are free to analyze the data any way you see fit. For example, you could build a machine learning model that predicts how much someone will spend based on demographics and offer type. Or you could build a model that predicts whether or not someone will respond to an offer. Or, you don't need to build a machine learning model at all. You could develop a set of heuristics that determine what offer you should send to each customer (i.e., 75 percent of women customers who were 35 years old responded to offer A vs 40 percent from the same demographic to offer B, so send offer A).\n\n# # Data Sets\n# \n# The data is contained in three files:\n# \n# * portfolio.json - containing offer ids and meta data about each offer (duration, type, etc.)\n# * profile.json - demographic data for each customer\n# * transcript.json - records for transactions, offers received, offers viewed, and offers completed\n# \n# Here is the schema and explanation of each variable in the files:\n# \n# **portfolio.json**\n# * id (string) - offer id\n# * offer_type (string) - type of offer ie BOGO, discount, informational\n# * difficulty (int) - minimum required spend to complete an offer\n# * reward (int) - reward given for completing an offer\n# * duration (int) - time for offer to be open, in days\n# * channels (list of strings)\n# \n# **profile.json**\n# * age (int) - age of the customer \n# * became_member_on (int) - date when customer created an app account\n# * gender (str) - gender of the customer (note some entries contain 'O' for other rather than M or F)\n# * id (str) - customer id\n# * income (float) - customer's income\n# \n# **transcript.json**\n# * event (str) - record description (ie transaction, offer received, offer viewed, etc.)\n# * person (str) - customer id\n# * time (int) - time in hours since start of test. The data begins at time t=0\n# * value - (dict of strings) - either an offer id or transaction amount depending on the record\n# \n# **Note:** If you are using the workspace, you will need to go to the terminal and run the command `conda update pandas` before reading in the files. This is because the version of pandas in the workspace cannot read in the transcript.json file correctly, but the newest version of pandas can. You can access the termnal from the orange icon in the top left of this notebook. \n# \n# You can see how to access the terminal and how the install works using the two images below. First you need to access the terminal:\n# \n# <img src=\"pic1.png\"/>\n# \n# Then you will want to run the above command:\n# \n# <img src=\"pic2.png\"/>\n# \n# Finally, when you enter back into the notebook (use the jupyter icon again), you should be able to run the below cell without any errors.\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport math\nimport json\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# read in the json files\nportfolio = pd.read_json('data/portfolio.json', orient='records', lines=True)\nprofile = pd.read_json('data/profile.json', orient='records', lines=True)\ntranscript = pd.read_json('data/transcript.json', orient='records', lines=True)\n\n\n# In[2]:\n\n\nportfolio.head()\n\n\n# In[3]:\n\n\nprofile.head()\n\n\n# In[4]:\n\n\ntranscript.head()\n\n\n# \n# # Project Overview: \n# \n# One thing Starbuck does well is to keep customers satisfied, with increasing compition let us see if it it only a social phenomenon, or that Starbuck cares about gaining and maintaining customers loyalty!\n# \n# \n# The data provided by Starbuck, contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisement for a drink or an actual offer such as a discount or BOGO (buy one get one free). \n# In this project we aim to use this dataset and analyze transactions, demographics, and offer portfolio to determine which group responds well to which offers.\n# \n\n# # Problem Statement: \n# \n# As stated above in Introduction Part & data provided for exporation, the problem statement I am aiming to answer is mentioned below:\n# \n# **1.What are the main drivers of offer effectiveness ?**\n# \n# **2.Exploring if we can predict whether a user would take up an offer.**\n# \n# ***The data provided consists of 3 datasets:***\n# \n# **a.Portfolio**\n# \n# **b.Profile**\n# \n# **c.Transcript**\n# \n# \n# I use the model to uncover the feature importances to identify the drivers of offer effectiveness, while exploring if the model itself could be used to predict if a user would take up an offer.\n# \n# Lastly, I also explore the characteristics of users who do or do not take up an offer.\n# \n# This project aims to answer the two questions above, but I also ended up adding 2 additional models as points of exploration - the first assessing whether an all-in-one model could be used in place of 3 different models, with the offer types functioning as a categorical variable. Secondly, I also build a regression model to see if we could predict the amount a user would spend, given that the offer is effectively influencing them.\n# \n# \n\n# ## Importing Sklearn Libraries for Model Building\n\n# In[5]:\n\n\n#Importing libraries\n\nimport pandas as pd\nimport numpy as np\nimport math\nimport json\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import classification_report\nfrom time import time\nfrom sklearn.model_selection import GridSearchCV\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import Ridge\nfrom sklearn.tree import DecisionTreeRegressor\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ### Checking for Null Values in the dataset\n\n# In[6]:\n\n\nportfolio.isnull().sum()\n\n\n# **Observation: There is no missing values in the portfolio dataset**\n\n# In[7]:\n\n\n#check no. of unique offers\nportfolio.id.nunique()\n\n\n# In[8]:\n\n\nportfolio.groupby('offer_type')['id'].count()\n\n\n# **Overall there are 10 unique id, consisting 4 bogo, 4 discount & 2 informational**\n\n# In[9]:\n\n\nprofile.head()\n\n\n# In[10]:\n\n\nprofile.describe(include='all')\n\n\n# **There is an missing value in profile dataset for income & gender column.**\n# \n# **It seems interesting dataset, as gender & income has same number of missing values.**\n\n# In[11]:\n\n\nprofile.hist()\n\n\n# In[12]:\n\n\nprofile.age.nunique\n\n\n# In[13]:\n\n\n#check count of age=118 value and corresponding gender and income columns\nprint(profile[profile['age']==118].count())\nprofile[['gender','income','age']][profile['age']==118].head()\n\n\n# We can see above that the age = 118 value does not make sense there as it is clearly out of the normal distribution.\n# \n# As we can see above, the age=118 column corresponds with the null gender and income columns. Thus, we can actually drop them during preprocessing if they do not take too large a proportion of our data.\n\n# In[14]:\n\n\nprofile['id'].nunique()\n\n\n# In[15]:\n\n\nprofile.hist()\n\n\n# In[16]:\n\n\nprofile.became_member_on.head()\n\n\n# In[17]:\n\n\nprofile.became_member_on.nunique()\n\n\n# In[18]:\n\n\nprofile.shape\n\n\n# Last but not least, **became_member_on column** has some potential to be feature engineered to get the tenure of membership in days. This feature might have some influence on whether an offer is effective or not.\n\n# In[19]:\n\n\ntranscript.head()\n\n\n# In[20]:\n\n\ntranscript.describe()\n\n\n# In[21]:\n\n\ntranscript.event.unique()\n\n\n# In[22]:\n\n\ntranscript.event.nunique()\n\n\n# This data looks tricky, as it is ordered by time and has an event and value. In particular, the value column will have to be preprocessed depending on the event.\n\n# In[23]:\n\n\n#check number of unique people represented\ntranscript['person'].nunique()\n\n\n# In[24]:\n\n\n#check for null values\ntranscript.isnull().sum()\n\n\n# There are no null values in this data.\n# \n# In order to extract insights from the value column,we need to expand the values into individual columns depending on the event.\n\n# In[25]:\n\n\ntranscript=pd.concat([transcript, transcript['value'].apply(pd.Series)], axis=1)\ntranscript.head()\n\n\n# It appears as though the offer id column ended up being duplicates so we have to clean it up further to ensure there is only one offer id column.\n\n# In[26]:\n\n\n#create new column to ensure only one offer_id column\ntranscript['offer_id_new']=np.where(transcript['offer id'].isnull() & transcript['offer_id'].notnull(),transcript['offer_id'],transcript['offer id'])\n\n#drop unnecessary offer_id columns\ntranscript.drop(['offer id','offer_id'],axis=1,inplace=True)\n\n#rename offer_id column\ntranscript.rename(columns={'offer_id_new':'offer_id'},inplace=True)\n\n\n# In[27]:\n\n\ntranscript.head()\n\n\n# ## Defining Approach for Preprocessing Data\n\n# Before proceeding for Pre processing the data further, i have revisited my objective for analysis.\n# \n# In order to identify the main drivers of an effective offer, I have to first define what an 'effective' offer is within the Starbucks app. Thus, I did some further exploration on the datasets and how all three would interact.\n# \n# First, I had to explore what kind of events are within each offer type.\n\n# In[28]:\n\n\n#rename column\nportfolio.rename(columns={'id':'offer_id'},inplace=True)\n\n#join transcript with offer type\ntranscript=transcript.merge(portfolio,how='left',on='offer_id')\n\n\n# In[29]:\n\n\ntranscript.groupby(['event','offer_type'])['offer_type'].count()\n\n\n# We know that there are 4 types of events: offer completed, offer received, offer viewed and transaction. But our data shows that we do not have any offer_id associated with transactions, because they are not recorded in the transcript event data. Thus, the first objective in data preprocessing is to define a methodology to assign offer_ids to specific transactions.\n# \n# Moreover, we also know that BOGO and discount offers have an offer completed event when offers are completed. However, informational offers do not have this event associated with it. Thus, we also specify the approach to define an effective offer as follows:\n# \n# For a BOGO and discount offer, an effective offer would be defined if the following events were recorded in the right sequence in time:\n# \n# **offer received -> offer viewed -> transaction -> offer completed**\n# \n# Meanwhile, for an informational offer, since there offer completed event associated with it, I will have to define transactions as a conversion to effective offer:\n# \n# **offer received -> offer viewed -> transaction**\n\n# ## Data Preprocessing\n# **A. Assigning offer ids to transactions**\n# \n# After defining the approach above, we now have to explore methods to assign offer_ids to specific transactions. Among the considerations is to define the following main groups of customers:\n# \n# **1. People who are influenced and successfully convert - effective offers:**\n# \n# - `offer received` -> `offer viewed` -> `transaction` -> `offer completed` (BOGO/discount offers)\n# - `offer received` -> `offer viewed` -> `transaction` (informational offers - must be within validity period of offer)\n# \n# **2. People who received and viewed an offer but did not successfully convert - ineffective offers:**\n# \n# - `offer received` -> `offer viewed`\n# \n# **3. People who purchase/complete offers regardless of awareness of any offers:**\n# \n# - `transaction`\n# - `offer received` -> `transaction` -> `offer completed` -> `offer viewed`\n# - `transaction` -> `offer received` -> `offer completed` -> `offer viewed`\n# - `offer received` -> `transaction` -> `offer viewed` -> `offer completed`\n# - `offer received` -> `transaction` (informational offers)\n# - `offer received` -> `transaction` -> `offer viewed` (informational offers)\n# \n# **4. People who received offers but no action taken:**\n# \n# - `offer received`\n# \n# \n# For people in group 2, I would need to check if there are events where there is an offer received and offer viewed event, but no conversion event, i.e. offer completed or transaction - these are cases of ineffective offers.\n# \n# I would have to separate out the people in group 2 from people in group 4, as people in group 2 may have viewed an offer but did not take any action, whereas people in group 4 did not even have an offer viewed event.\n# \n# Separating the conversions for effective offers (group 1) and people who purchase/complete offers regardless of awareness of any offers (group 3) is particularly tricky. For people in group 3, a conversion is invalid (i.e., not a successful conversion from an offer) if an offer completed or transaction occurs before an offer viewed. There also may be scenarios where an offer completed occurs after the offer is viewed, but a transaction was done prior to the offer being viewed. In this instance, the offer may have been completed, but it is also not a valid conversion.\n# \n# Defining the target variable effective offer:\n# \n# After defining these conditions, we have to decide what the target variable will be.\n# \n# We know that group 1 customers will be our target variable effective_offer=1, but there are many ineffective offer definitions for groups 2-4.\n# \n# So what would we define as an ineffective offer? As already stated above, group 2 would be within our definition of an ineffective offer; where a user is aware of an offer, but the offer is ineffective as it does not convert the user into a customer. So group 2 can be defined as our target variable effective_offer=0.\n# \n# What about group 3 and group 4? Group 3 consists of users who may have received offers but would have purchased regardless. From the business point of view, we would not want to be sending them any offers.\n# \n# Meanwhile, group 4 users would be considered low priority customers, as they do not do any action, regardless of whether they receive offers or not.\n# \n# So, we can deprioritise group 3 and group 4 users from our model. It would still be worth doing some exploratory analysis onto group 3 and 4, just to explore on their demographics.\n# \n# The conditions above are the basis of which I can assign the offer id that 'influences' a transaction by ensuring that the transaction occurs after an offer viewed event.\n# \n# After sorting the transcript dataset by person and time to ensure that each event for each person occurs in sequence, I can filter the dataset by events offer viewed and transaction to ensure that it only contains those events in order.\n# \n# Then, I can use pandas' ffill() method to fill every transaction with the offer_id of the viewed offer, only if it occurs before the transaction.\n\n# In[30]:\n\n\n#define dropcolumns function as it is required many times\ndef drop_cols(drop_cols,df,inplace=False):\n '''\n inputs:\n - drop_cols: list or string of column name to be dropped\n - df: dataframe from which column should be dropped\n - inplace: specify whether columns are dropped in place or not\n \n outputs:\n - Returns dataframe with dropped columns.\n \n '''\n df=df.drop(columns=drop_cols,axis=1,inplace=inplace)\n return df\n\n\n# In[31]:\n\n\n#drop unnecessary columns to clean dataset\ntranscript=drop_cols(['reward_x','reward_y'],transcript)\n#sort events by person and time\ntranscript=transcript.sort_values(['person','time'])\n\n\n# In[32]:\n\n\n#filter dataset for transactions that occur after an offer is viewed, forward fill offer ids by person\noffers_view_transacted=transcript[['time','offer_id','person','event']][(transcript['event']=='transaction') | (transcript['event']=='offer viewed')].groupby(['person','offer_id']).ffill()\noffers_view_transacted['offer_id']=offers_view_transacted['offer_id'].ffill()\n\n\n# Since the above temporary dataset is just a subset of the `transcript` dataset, I can create a new dataset with the filled in offer ids for transactions.\n\n# In[33]:\n\n\ntranscript=transcript.merge(offers_view_transacted,how='left',on=['person','time','event'])\n\n\n# In[34]:\n\n\n#clean up dataset to unify multiple offer_id columns into one column\ntranscript['offer_id']=np.where(transcript['offer_id_x'].isnull(),transcript['offer_id_y'],transcript['offer_id_x'])\n\ndrop_cols(['offer_id_x','offer_id_y'],transcript,inplace=True);\n\n\n# In[35]:\n\n\n#merge portfolio dataset again to get offer data for the transaction events\ntranscript=transcript.merge(portfolio,how='left',on='offer_id')\ntranscript['duration']=np.where(transcript['duration_x'].isnull(),transcript['duration_y'],transcript['duration_x'])\ndrop_cols(['duration_x','offer_type_x','difficulty_x','channels_x','duration_y'],transcript,inplace=True);\ntranscript.rename(columns={'channels_y':'channels','reward_y':'reward','difficulty_y':'difficulty','offer_type_y':'offer_type'},inplace=True)\n\n\n# In[36]:\n\n\ntranscript.head()\n\n\n# **B. Flagging transactions and offers completed after offers viewed**\n# \n# The next important step for preparing our data for modeling and analysis is to identify a completed offer and transactions occurring after an offer is viewed.\n# \n# Once we have assigned a transaction occurring after an offer is viewed, I can use that information to subset my data according to the groups defined above, and analyse within each group.\n# \n# Using our dataset with the offer_ids populated for transaction events, we can flag the converted transactions and completed offers. We have to first ensure that the offer id of the previous event is the same one. Since we have tagged the offer id for all viewed, transactions and completed offers, we can use the offer_id field to ensure that the previous offer consists of those events.\n# \n# This means that as long as the events offer viewed,transaction, and offer completed occur in the same event space and are in the corrrect sequence of time, we can be assured that it is a transaction and/or completed offer occurring only after an offer is viewed.\n# \n# To do this, I created a new column to flag the previous offer id using pandas' shift function.\n\n# In[37]:\n\n\n#get sample space of events consisting of offer viewed, transactions and offer completed\noffers_viewed_transactions_completed=transcript[(transcript['event']=='offer viewed') | (transcript['event']=='transaction') | (transcript['event']=='offer completed')].copy()\n\n\n# In[38]:\n\n\n#add extra column to flag the previous offer id\noffers_viewed_transactions_completed['offer_id_previous'] = offers_viewed_transactions_completed.groupby(['person','offer_id'])['offer_id'].shift()\n\n\n# In[39]:\n\n\n#flag a completed transaction/offer completed as long as the previous offer id consists of events in the same sample space\noffers_viewed_transactions_completed['valid_completed']=np.where(offers_viewed_transactions_completed['offer_id_previous']==offers_viewed_transactions_completed['offer_id'],1,0)\n\n\n# Since our dataset `offers_viewed_transactions_completed` consists of all other possible events, all we need to do is to append the all `offers received` events in the `transactions_clean` dataset to ensure we have our complete dataset again.\n\n# In[40]:\n\n\n#get only offer received events\noffers_received=transcript[transcript['event']=='offer received'].copy()\n\n#ensure all columns are the same between datasets to be appended\noffers_received['offer_id_previous']=np.nan\noffers_received['valid_completed']=np.nan\n\n#append datasets to complete dataset of transactions\ntranscript=offers_received.append(offers_viewed_transactions_completed)\n\n#sort values\ntranscript=transcript.sort_values(['person','time'])\n\n\n# Having assigned offer_ids for transactions for which an `offer viewed` event occurred prior, we can now revisit the four customer groups of unique person-offer_id pairs we are trying to analyse.\n# \n# Since we consider the conversion events of depending on offer type differently, we have to first separate the transcript into 3 different offer types, in order to accommodate for the different treatment in assigning the target variable.\n\n# In[41]:\n\n\n#define function to split into 3 offer types\ndef split(offer_type,grp_df):\n '''\n Splits dataframe to groups of specified offer type.\n \n inputs:\n - offer_type: specify offer type name in string format \n - grp_df: original transcript dataframe to split on offer type\n \n outputs:\n - Returns dataframe containing data of just offer type.\n \n '''\n df=grp_df[grp_df['offer_type']==offer_type].copy()\n return df\n\n#split transcript into 3 different offer types\ntranscript_bogo=split('bogo',transcript)\ntranscript_discount=split('discount',transcript)\ntranscript_info=split('informational',transcript)\n\n\n# Within each offer type, we can already successfully separate every unique person-offer_id in group 1 from the others using our `valid_completed` column. Since we have flagged all conversion events (`transaction` or `offer completed` event depending on offer type) occurring after an `offer viewed` event, we can be assured that whichever conversion events are flagged with `valid_completed=1` are at least within the first group (People who are influenced and successfully convert - effective offers).\n# \n# For BOGO and discount offers, we will only consider `offer completed` events as the conversion events, while we can consider `transaction` event as the conversion event for the informational offers. \n\n# In[42]:\n\n\n#since will do this for both BOGO and discount, define function for repeated operation\ndef grp1(df):\n '''\n Subsets dataframe to just group 1 members.\n \n inputs:\n - df: original transcript dataframe \n\n outputs:\n - Returns dataframe containing transcript data of just group 1 users.\n \n '''\n grp1=df[['person','offer_id']][(df['valid_completed']==1) & (df['event']=='offer completed')].groupby(['person','offer_id']).count().reset_index()\n return grp1\n\ngrp1_bogo=grp1(transcript_bogo)\ngrp1_discount=grp1(transcript_discount)\n\n\n# Meanwhile, for informational offers we will define group 1 later as there is an additional consideration we need to take into account for transactions - they need to occur within the validity period of an informational offer for us to consider them as effective offers.\n# \n# Now, we can look into separating group 2 and group 4 unique person-offer_ids for BOGO and discount offers as we just need to look at the subset of people with `offer received`, `offer viewed`, but no conversion events. We can also assume that every person who views an offer would have had an `offer received` event prior, so we can just take the whole group of people who received an offer and subset them later.\n\n# In[43]:\n\n\n#again, we define a function as we will repeat this for 2 datasets - BOGO & discount\ndef no_conv(df):\n \n '''\n Takes in transcript dataframe of single offer type to check for people who converted vs people with just offer received events. \n \n inputs:\n - df: original transcript dataframe of specific offer type \n \n outputs:\n - Returns dataframe containing unqiue person-offer_id pairs with conversion events and offers received events, with indicator of each.\n \n Note: left_only indicator is just the offers received events, right_only is just conversion events\n \n '''\n \n #subset offer ids that have transactions or conversions by person and offer_id\n conversion_ids=df[['person','offer_id']][(df['event']=='transaction') | (df['event']=='offer completed') ].groupby(['person','offer_id']).count().reset_index()\n\n #check for unique person-offer_id pairs that consist of offers received \n offers_received_only=df[['person','offer_id']][df['event']=='offer received'].groupby(['person','offer_id']).count().reset_index()\n\n #create merged dataset to diffrentiate groups\n check_merge=conversion_ids.merge(offers_received_only,how='right',on=['person','offer_id'],indicator=True)\n return check_merge\n\n#check how many are in either group\ncheck_merge_bogo=no_conv(transcript_bogo)\nprint('For BOGO offers:')\nprint(check_merge_bogo.groupby(['_merge']).count())\n\ncheck_merge_discount=no_conv(transcript_discount)\nprint('For Discount offers:')\nprint(check_merge_discount.groupby(['_merge']).count())\n\n\n# We can see that there are definitely a fair number of unique person-offer_id pairs that have `offer received` events, but no conversion events. These would be considered offers in group 2 and 4 within each offer type, according to our definition above. \n# \n# People with an `offer viewed` event in this subset are definitely in group 2, as we can assume everyone with an `offer viewed` event has an `offer received` event prior.\n\n# In[44]:\n\n\n#define group 2 & 4 function as will repeat this for BOGO and discount offers\ndef grp_2_4(df):\n \n '''\n Takes in output dataframe from no_conv function to split into group 2 and 4 customers.\n \n inputs:\n - df: output dataframe from no_conv function\n \n outputs:\n - Returns 2 dataframes containing unique person-offer_id pairs with dataframe containing only group2 customers first, followed by dataframe containing only group 4 customers. \n \n '''\n \n #subset to check group 2 and 4\n grp_2_4=df[df['_merge']=='right_only']\n\n #remerge with transcript to get events\n grp_2_4=grp_2_4.merge(transcript,how='left',on=['person','offer_id'])\n\n #within this subset, separate people with offer viewed event, and people with offer received but no offer viewed\n grp2=grp_2_4[['person','offer_id']][grp_2_4['event']=='offer viewed'].groupby(['person','offer_id']).count().reset_index()\n \n #remerge with full dataset and get remaining to get grp4\n drop_cols('_merge',grp_2_4,inplace=True)\n grp4=grp_2_4.merge(grp2[['person','offer_id']],how='left',indicator=True)\n grp4=grp4[grp4['_merge']=='left_only'].copy()\n \n return grp2,grp4\n\ngrp2_bogo,grp4_bogo=grp_2_4(check_merge_bogo)\ngrp2_discount,grp4_discount=grp_2_4(check_merge_discount)\n\n\n# Group 3 people are everyone in the converted ids who do not have an offer viewed prior - hence, they would be people with conversion events but no `offer viewed` event prior. For BOGO and discount offers, they would be people with `offer completed` events that have `valid_completed != 1`.\n\n# In[45]:\n\n\ndef grp3(df):\n '''\n Takes in transcript dataframe of single offer type to check for people who converted vs people with just offer received events. \n \n inputs:\n - df: original transcript dataframe of specific offer type \n \n outputs:\n - Returns dataframe containing unqiue person-offer_id pairs with conversion events and offers received events, with indicator of each.\n \n '''\n \n #check all conversion events with invalid conversions\n grp3=df[['person','offer_id']][(df['event']=='offer completed') & (df['valid_completed']!=1)].groupby(['person','offer_id']).count().reset_index()\n return grp3\n\ngrp3_bogo=grp3(transcript_bogo)\ngrp3_discount=grp3(transcript_discount)\n\n\n# Now we have split our data into 4 different customer groups for the BOGO and discount offers. Next, we have to consider the effective and ineffective offers depending on the group type. As already elaborated above, any unique person-offer_id belonging to group 1 can be considered in our target variable `effective_offer=1` group.\n# \n# Meanwhile, group 2 is in our target variable `effective_offer=0` group. For customers in groups 3 and 4, I deprioritise them for model implementation, but will be doing some exploratory analysis on them later.\n\n# In[46]:\n\n\ndef offers(grp1,grp2):\n '''\n inputs:\n - grp1: dataframe containing group1 customer data \n - grp2: dataframe containing group2 customer data\n \n outputs:\n - Returns dataframe with labeled effective offer column\n '''\n #assign effective offer flag column\n grp1['effective_offer']=1\n grp2['effective_offer']=0\n\n #append datasets together\n offers=grp1.append(grp2,sort=False)\n return offers\n\noffers_bogo=offers(grp1_bogo,grp2_bogo)\noffers_discount=offers(grp1_discount,grp2_discount)\n\n\n# Now we have successfully prepared the target variables for our BOGO and discount datasets. \n# \n# Meanwhile, for informational offers in particular, before we can tag the effective offers column, there is one more consideration - the validity of the offer.\n\n# **C. Considering duration/validity of offers in converted transactions from informational offers**\n# \n# There is an additional rule to consider when considering an effective/converted transaction and offer. This applies for offers that are of type 'informational'. As already elaborated above, the reason why informational offers get a different treatment is because the conversion event is not an `offer completed` event, but a `transaction`.\n# \n# For informational offers, the `duration` of the offer can be considered to be the duration of the influence. Hence, we can make the assumption that an offer should only be considered effective if it is within the `duration` of the offer.\n# \n# Meanwhile, for BOGO and discount offers, we can assume that if there is a conversion/ `offer completed` event, it should be within duration as it would not make sense for an offer to be completed if an offer is past its validity period.\n# \n# As we saw in our data dictionary, the `time` of an event in the `transcript` data is in terms of hours. In order to ensure it is on the same scale as the `duration` of the offer, we have to convert it into days.\n\n# In[47]:\n\n\n#convert time into days\ntranscript_info['day_offer']=transcript_info['time']/24\n#drop unnecessary columns\ndrop_cols(['time','value','offer_id_previous'],transcript_info,inplace=True);\n\n\n# In[48]:\n\n\n#sort transactions to ensure all events occurring by person and offer\ntranscript_info=transcript_info.sort_values(['person','day_offer','event','offer_id'])\n\n\n# In[49]:\n\n\n#get difference in time for informational offers\ntranscript_info['diff_info']=transcript_info[(transcript_info['offer_type']=='informational') & ((transcript_info['event']=='offer received') | (transcript_info['event']=='transaction'))].groupby(['person','offer_id'])['day_offer'].diff()\n\n\n# In[50]:\n\n\n#create column for flagging valid events\ntranscript_info['valid_completed_duration']=np.nan\n\n#flag valid events if within duration\ntranscript_info.loc[transcript_info['diff_info']<=transcript_info['duration'],'valid_completed_duration']=1\n\n#fill any missing values with 0 flag\ntranscript_info['valid_completed_duration']=transcript_info['valid_completed_duration'].fillna(value=0)\n\n\n# With the `valid_completed` and `valid_completed_duration` flag columns, we have 4 possible scenarios for an informational offer within the `transcript_info` dataset:\n# \n# |No.| valid_completed | valid_completed_duration | Scenario |\n# |---| --- | --- | --- |\n# |1| 1 | 0 | completed transaction after offer viewed event, but not within duration |\n# |2| 0/null | 1 | completed transaction within duration, but with no offer viewed event prior |\n# |3| 1 | 1 | completed transaction within duration, with offer viewed event - **an effective offer** |\n# |4| 0//null | 0 | did not complete transaction within duration, no offer viewed event prior |\n# \n# Following the above scenarios, only Scenario 3 would be considered our label `effective_offers = 1` for informational offers (group 1 of customers).\n# \n# Meanwhile, Scenarios 1 and 2 can be considered to be actions that would put the customer into our Group 3 of customers - People who purchase/complete offers regardless of awareness of any offers. \n# \n# For customers in Scenario 1, even though according to our `valid_completed` flag, they had viewed an offer prior to the transaction, but it is not within the duration, thus they are not 'influenced' by the offer.\n# \n# Meanwhile for customers in Scenario 2, they are in Group 3 as they completed transactions without viewing an offer. \n# \n# Scenario 4 can be considered in group 4, as they only consist of transactions.\n# \n# We will need to separate those users in group 2 - those who may have received and viewed an offer, but no transactions after. We need to subset those where `effective_offer!=1` into groups 2,3 and 4. \n\n# In[51]:\n\n\n#flag effective_offers where valid_completed=1 and valid_completed_duration=1\ntranscript_info['effective_offer']=np.where(((transcript_info['valid_completed']==1) & (transcript_info['valid_completed_duration']==1)),1,0)\n\n\n# Now that we have flagged our effective offers, we can subset them into the 4 groups already outlined above. We can also filter this only for the `effective offers=1` events, as we only want the effective transactions influenced by an offer, not other transactions.\n\n# In[52]:\n\n\n#separate group 1 in transcript_into\ngrp1_info=transcript_info[['person','offer_id']][transcript_info['effective_offer']==1].groupby(['person','offer_id']).sum().reset_index()\n\n\n# From the remaining people, we have to separate it out into groups 2 and 4. We can use similar steps to what we did with BOGO and Discount offers, since we don't have the duration consideration.\n\n# In[53]:\n\n\n#separate out group 2 of customers\ncheck_merge_info=no_conv(transcript_info)\nprint('For informational offers:')\nprint(check_merge_info.groupby(['_merge']).count())\n\n\n# In[54]:\n\n\ngrp2_info,grp4_info=grp_2_4(check_merge_info)\n\n\n# For group 3, we have to consider those with conversions who do not have an offer viewed prior - hence, they would be people with conversion events but no offer viewed event prior. For informational offers, these would be `transaction`s in Scenario 1 and 2 above.\n\n# In[55]:\n\n\n#scenario 1\ngrp3_1=transcript_info[['person','offer_id']][(transcript_info['event']=='transaction')&(transcript_info['valid_completed']!=1) & (transcript_info['valid_completed_duration']==1)].groupby(['person','offer_id']).count().reset_index()\n#scenario 2\ngrp3_2=transcript_info[['person','offer_id']][(transcript_info['event']=='transaction')&(transcript_info['valid_completed']==1) & (transcript_info['valid_completed_duration']!=1)].groupby(['person','offer_id']).count().reset_index()\ngrp3_info=grp3_1.append(grp3_2,sort=False)\ndel grp3_1\ndel grp3_2\n\n\n# ### Now we can append the datasets together to make the offers_info dataset, ready for modeling.\n\n# In[56]:\n\n\noffers_info=offers(grp1_info,grp2_info)\n\n\n# Now that we have subset all our datasets into effective and ineffective offers depending on offer type, we can append the datasets accordingly into datasets for modeling.\n\n# **D.Feature engineering**\n# \n# Now we have to look back had to look into the features and see how to be creative in creating new features.\n# \n# **i**. became_member_on column to be engineered\n\n# In[57]:\n\n\n#rename column for merging\nprofile.rename(columns={'id':'person'},inplace=True)\n\n#create function to reuse for 3 datasets\ndef member(df):\n '''\n inputs:\n - df: original dataframe to transform became_member_on column \n \n outputs:\n - Returns dataframe with became_member_on column transformed to be tenure in days\n \n '''\n #merge to get user demographic profile\n df=df.merge(profile,how='left',on='person')\n \n #convert became_member_on into member tenure\n df['year']=pd.Series([int(str(x)[:4]) for x in df['became_member_on']])\n df['month']=pd.Series([int(str(x)[-3]) for x in df['became_member_on']])\n df['day']=pd.Series([int(str(x)[-2:]) for x in df['became_member_on']])\n df=drop_cols('became_member_on',df)\n df.loc[df['year'] == 2018, 'membership_tenure_days'] = (30*df['month'])+df['day']\n df.loc[df['year'] != 2018, 'membership_tenure_days'] = ((2018-df['year'])*365)+(30*df['month'])+df['day']\n df=drop_cols(['year','month','day'],df)\n \n return df\n\noffers_bogo=member(offers_bogo)\noffers_discount=member(offers_discount)\noffers_info=member(offers_info)\n\n\n# **ii. Count of offers received**\n# \n# As part of some further data exploration, I discovered that there could be multiple offers received per person.\n\n# In[58]:\n\n\n#group event=offer received per person in transactional records\nprint(transcript[transcript['event']=='offer received'].groupby('person')['event'].count().head())\n\n#visualise offers received per person\ntranscript[transcript['event']=='offer received'].groupby('person')['event'].count().hist()\n\n\n# In[59]:\n\n\n#get count of offers received per person, put into separate dataset\ndf_offer_received_cnt=transcript[transcript['event']=='offer received'].groupby(['person','offer_id','time']).count()['event'].reset_index()\n\n#rename columns\ndf_offer_received_cnt.rename(columns={'event':'offer_received_cnt'},inplace=True)\n\n#drop unnecessary columns\ndrop_cols('time',df_offer_received_cnt,inplace=True)\n\n#ensure only unique person-offer_id pairs\ndf_offer_received_cnt=df_offer_received_cnt.groupby(['person','offer_id']).sum().reset_index()\n\n\n# **iii. Separating user behaviours by transactions**\n# \n# I also wondered how many transactions were considered 'invalid' by my definition. Ordinarily, these would be the sum of transactions done by people not in group 1. The objective of offers are to drive purchases, so it would already be the case that users with high spend in their transactions would be flagged as `effective_offers`. \n# \n# We've already defined that there are people in groups 3 and 4, where they are separate pools of users who are loyal spenders, and already tend to purchase more, isolated from the the effect of offers. \n# \n# But for users in group 1 have a high amount of 'invalid spend' outside of the effect of offers, there might be some predictive power onto the effectiveness of offers; since a loyal user might have a higher tendency of taking up an offer.\n# \n# In my datasets, I had already separated the transactions who are conversions versus transactions who are just the users' normal purchasing behaviour. This is through the `valid_completed` column, where I checked if a transaction had an `offer viewed` event prior. \n# \n# In the cases where `valid_completed`=1, I had already included them in my effective offers flag for BOGO and Discount offers. However, for those transctions where `valid_completed`=0, I have not considered them, and this could be a potential feature to include, as a proxy for the 'baseline' level of spending for a user.\n# \n# The logic is to wonder if there is some baseline level of spending for users who are highly influenced by certain offers (in group 1), and group 2, and if there is some predictive power in this baseline level of 'invalid transactions' that can predict the propensity of a user to take up an offer.\n\n# In[60]:\n\n\n#filter dataset by invalid transactions\ndf_transactions_invalid=transcript[(transcript['event']=='transaction') & (transcript['valid_completed']==0)].groupby(['person','offer_id'])['amount'].sum().reset_index()\ndf_transactions_invalid.rename(columns={'amount':'amount_invalid'},inplace=True)\n\n\n# **iv. Time elapsed between offers received**\n# \n# I also wanted to include time as a potential feature into my dataset, but since the transactional data starts from time=0, I suspected it would not have been of much predictive power without some feature engineering. I had the hypothesis that if there were multiple offers received per person within a certain time period, there might be some predictive power in the time elapsed between offers received. \n\n# In[61]:\n\n\n#convert time into days\ntranscript['day_offer']=transcript['time']/24\n#drop unnecessary columns\ndrop_cols(['time'],transcript,inplace=True);\n\n#find time elapsed between offers received\ntranscript['time_elapsed_offers']=transcript[transcript['event']=='offer received'].groupby(['person','offer_id'])['day_offer'].diff()\n\n#fill missing values with 0, as if someone does not receive an offer or is receiving an offer for the first time, there is no time elapsed\ntranscript['time_elapsed_offers']=transcript['time_elapsed_offers'].fillna(value=0)\n\n#create temporary dataset\ndf_time_elapsed=transcript.groupby(['person','offer_id'])['time_elapsed_offers'].sum().reset_index()\n\n\n# **E. Preparing data for implementation**\n# \n# Now we can finally begin with preparing the data for modeling. \n# \n# To do this, there are some additional preparation steps for each dataset. Recalling our initial preliminary data exploration, there are some steps to prepare the data:\n# \n# a. Merge with temporary datasets created above to include engineered features\n# \n# b. Drop missing values in `gender` column for demographic data; convert gender into dummy variables\n# \n# c. Separate the `channel` column into categorical variables\n# \n# d. Treatment of duplicate records\n# \n# **Merge with temporary datasets created above to include engineered features**\n\n# In[62]:\n\n\n#merge to get offers received count and invalid amount transacted \noffers_bogo=offers_bogo.merge(df_offer_received_cnt[['person','offer_id','offer_received_cnt']],how='left',on=['person','offer_id'])\noffers_bogo=offers_bogo.merge(df_transactions_invalid[['person','offer_id','amount_invalid']],how='left',on=['person','offer_id'])\n\n\n# **Drop missing values in gender column for demographic data**\n# \n# Now, we need to check whether dropping the missing values will result in a significant loss in data.\n\n# In[63]:\n\n\n#check % of missing values in dataset\n(offers_bogo.isnull().sum()/len(offers_bogo)*100).sort_values(ascending=False).head()\n\n\n# We can see that the missing values are quite extensive especially for the `amount_invalid` column. It is debatable whether this column `amount_invalid` would be useful to include in the model. Since it is so 'sparse' for BOGO offers, it might not have much information after all. I plan to assess this feature again later during the model implementation phase. For now, I decided to fill the missing `amount_invalid` column with 0 as it could represent that only 3% of the overall users tend to purchase without offers; the other 97% would only purchase with awareness of an ongoing offer. \n# \n# Meanwhile, we had already conducted the analysis above on the `income` and `gender` columns, which I choose to drop as they are not useful when they are null.\n\n# In[64]:\n\n\n#fill missing values for amount_invalid with 0\noffers_bogo['amount_invalid']=offers_bogo['amount_invalid'].fillna(value=0)\n\n#drop income and gender null rows\noffers_bogo.dropna(inplace=True);\n\n\n# **Separate the channel column into categorical variables**\n# \n# \n\n# In[65]:\n\n\n#foresee need to reuse function so create rename function\ndef rename(col_name,df):\n df[col_name]=np.where(df[col_name]==col_name,1,0)\n return df\n\n#foresee need to reuse dummy variable encoding function\ndef dummy(df,col):\n df=pd.concat([df[:],pd.get_dummies(df[col],prefix=col)],axis=1)\n df=drop_cols(col,df)\n return df\n\n\n# In[66]:\n\n\n#merge with portfolio to get offer details\noffers_bogo=offers_bogo.merge(portfolio,how='left',on='offer_id')\n\n#convert channels into categorical variables\nchannels = offers_bogo['channels'].apply(pd.Series)\nchannels = channels.rename(columns={0:'web',1:'email',2:'mobile',3:'social'})\noffers_bogo=pd.concat([offers_bogo[:], channels[:]], axis=1)\nrename('web',offers_bogo)\nrename('email',offers_bogo)\nrename('mobile',offers_bogo)\nrename('social',offers_bogo)\noffers_bogo=drop_cols('channels',offers_bogo)\n\n#convert gender into categorical variables\noffers_bogo=dummy(offers_bogo,'gender')\n\n\n# Since we need to repeat these steps for `offers_discount`, I created a function containing all the steps above.\n\n# In[67]:\n\n\ndef prep_offers_df(df):\n \n '''\n inputs:\n - df: original dataframe for modeling \n \n outputs:\n - Returns dataframe containing engineered features, filled missing values and cleaned and transformed variables (channel and gender)\n \n '''\n #merge to get engineered features \n df=df.merge(df_offer_received_cnt[['person','offer_id','offer_received_cnt']],how='left',on=['person','offer_id'])\n df=df.merge(df_transactions_invalid[['person','offer_id','amount_invalid']],how='left',on=['person','offer_id'])\n \n #fill missing values for amount_invalid with 0\n df['amount_invalid']=df['amount_invalid'].fillna(value=0)\n \n #drop income and gender null rows\n df.dropna(inplace=True);\n \n #merge with portfolio to get offer details\n df=df.merge(portfolio,how='left',on='offer_id')\n\n #convert channels into categorical variables\n channels = df['channels'].apply(pd.Series)\n channels = channels.rename(columns={0:'web',1:'email',2:'mobile',3:'social'})\n df=pd.concat([df[:], channels[:]], axis=1)\n rename('web',df)\n rename('email',df)\n rename('mobile',df)\n rename('social',df)\n df=drop_cols('channels',df)\n \n #convert gender column into dummy variables\n df=dummy(df,'gender')\n\n return df\n\n\n# In[68]:\n\n\n#prepare data for offer_discounts\noffers_discount=prep_offers_df(offers_discount)\n\n\n# In[69]:\n\n\n#merge with portfolio to get offer details\noffers_info=offers_info.merge(portfolio,how='left',on='offer_id')\n\n#reset index for offers_info\noffers_info=drop_cols('index',offers_info.reset_index())\n\n#expand channel column into categorical variables\ndef channel_col(name,df=offers_info):\n '''\n inputs:\n - name: name of channel column to be transformed \n - df: dataframe \n \n outputs:\n - offer_info dataframe with channel column transformed\n \n '''\n df[name]= np.nan\n df.loc[pd.Series([name in df['channels'][x] for x in range(len(df['channels']))]),name]=1\n df[name]=df[name].fillna(value=0)\n return df\n\n\n# In[70]:\n\n\nchannel_col('web')\nchannel_col('email')\nchannel_col('mobile')\nchannel_col('social');\n\ndrop_cols('channels',offers_info,inplace=True);\n\n\n# In[71]:\n\n\n#repurpose function for offers_info\ndef prep_offers_df(df):\n '''\n inputs:\n - df: dataframe to be transformed \n \n outputs:\n - Returns dataframe with engineered features and filled missing values, with transformed gender column.\n \n '''\n #merge to get engineered features \n df=df.merge(df_offer_received_cnt[['person','offer_id','offer_received_cnt']],how='left',on=['person','offer_id'])\n df=df.merge(df_transactions_invalid[['person','offer_id','amount_invalid']],how='left',on=['person','offer_id'])\n\n #fill missing values for amount_invalid and offer_received_cnt with 0\n df['amount_invalid']=df['amount_invalid'].fillna(value=0)\n\n #drop income and gender null rows\n df.dropna(inplace=True);\n \n #convert gender column into dummy variables\n df=dummy(df,'gender')\n return df\n\n\n# In[72]:\n\n\noffers_info=prep_offers_df(offers_info)\n\n\n# In[73]:\n\n\noffers_info.head()\n\n\n# **Treatment of duplicate records**\n# \n# Since we have subset the data cleanly according to unique person-offer_id pairs by group, we should not have any duplicate records. But just in case, we check to make sure we have no duplicate records.\n\n# In[74]:\n\n\n#check multiple records for each person and offer ids for the target variable\nprint((offers_bogo.groupby(['person','offer_id','effective_offer']).size()>1).sum())\nprint((offers_discount.groupby(['person','offer_id','effective_offer']).size()>1).sum())\nprint((offers_info.groupby(['person','offer_id','effective_offer']).size()>1).sum())\n\n\n# ## Implementing Models\n# \n# Now that the datasets are ready, we can proceed to implementing the model. Revisiting our objective, we wanted to analyse the drivers of an effective offer, with the target variable being `effective_offer`.\n# \n# Since we have 3 offer types, there are thus 3 different models to be built. Since we are predicting whether an offer would be effective or not, this is effectively a binary classification supervised learning model.\n# \n# I decided to compare the performance of a simple decision tree classifier model as a baseline model, with an ensemble random forest classifier model. Reason why I selected a decision tree as the baseline model is because I wanted to prioritise the interpretability of the model. Going back to the objective, since we intend to analyse the feature importance to determine the drivers of an effective offer, a decision tree would provide good interpretability for us to analyse.\n# \n# Meanwhile, I also selected random forest as an alternate model to compare the baseline model is as an improvement over simple ensemble bagging of decision trees, in order to drive towards a high accuracy in training the model. \n# \n# Before we can proceed, we have to make sure that the classes we are predicting for are balanced in each dataset.\n\n# In[75]:\n\n\n#check for class balance in datasets\nprint(offers_bogo[['person','effective_offer']].groupby('effective_offer').count()/len(offers_bogo))\nprint(offers_discount[['person','effective_offer']].groupby('effective_offer').count()/len(offers_discount))\nprint((offers_info[['person','effective_offer']].groupby('effective_offer').count()/len(offers_info)))\n\n\n# We can see that the classes are quite uneven for all three offer types, but not too imbalanced such that it would pose a problem. Hence, we can proceed to implement the models.\n# \n# A note on model evaluation and validation; since the classes for the all 3 models are imbalanced, I decided to implement both accuracy and f1 score as the model evaluation metric. F1 score provides a better sense of model performance compared to purely accuracy as takes both false positives and false negatives in the calculation. With an uneven class distribution, F1 may usually be more useful than accuracy. \n# \n# It is worth noting in this case that the F1 score is based on the harmonic mean of precision and recall, and focuses on positive cases. For the Starbucks app here, it would be fine as we would prioritise more on whether offers are effective, and less focus on why offers are ineffective.\n\n# ### Creating train & test set for Models\n\n# In[76]:\n\n\ndef data_prep(df,drop_cols_prep):\n '''\n inputs:\n - df: prepared dataframe for modeling \n \n outputs:\n - Returns 2 dataframes - features and target dataframes\n '''\n # Split the data into features and target label\n target = df['effective_offer']\n features = drop_cols(drop_cols_prep,df)\n return features,target\n\n\n# In[77]:\n\n\n#prepare model pipeline\ndef model_pipeline(features,target):\n '''\n inputs:\n - features & target dataframe \n \n outputs:\n - Splits features and target dataframe to train and test sets, performs feature scaling on both datasets.\n - Outputs X_train, X_test, y_train and y_test dataframes\n '''\n \n #split into training and test sets\n X_train, X_test, y_train, y_test = train_test_split(features,target, \n test_size=0.20, \n random_state=42)\n\n #fit and transform scaling on training data\n scaler=StandardScaler()\n X_train=scaler.fit_transform(X_train)\n\n #scale test data\n X_test=scaler.transform(X_test)\n return X_train,X_test,y_train, y_test\n\n\n# I am defining the functions here to run my model as I plan to implement 3 different models; hence it would be easier to implement repeatedly. In this function, I define the model scores - F1 score and accuracy, as well as the error (mean squared error). As elaborated above, I plan to compare the F1 score with the accuracy score as a better indication of model performance, especially since the classes for the BOGO and discount offers are uneven.\n\n# In[78]:\n\n\ndef train_predict(learner, X_train, y_train, X_test, y_test): \n '''\n inputs:\n - learner: the learning algorithm to be trained and predicted on\n - sample_size: the size of samples (number) to be drawn from training set\n - X_train: features training set\n - y_train: review_scores_rating training set\n - X_test: features testing set\n - y_test: review_scores_rating testing set\n '''\n results = {}\n \n #Fit the learner to the training data and get training time\n start = time() \n learner = learner.fit(X_train, y_train)\n end = time() \n results['train_time'] = end-start\n \n # Get predictions on the test set(X_test), then get predictions on first 300 training samples\n start = time() \n predictions_test = learner.predict(X_test)\n predictions_train = learner.predict(X_train)\n end = time() \n \n # Calculate the total prediction time\n results['pred_time'] = end-start\n \n #add training accuracy to results\n results['training_score']=learner.score(X_train,y_train)\n \n #add testing accuracy to results\n results['testing_score']=learner.score(X_test,y_test)\n \n print(\"{} trained on {} samples.\".format(learner.__class__.__name__, len(y_train)))\n print(\"MSE_train: %.4f\" % mean_squared_error(y_train,predictions_train))\n print(\"MSE_test: %.4f\" % mean_squared_error(y_test,predictions_test))\n print(\"Training accuracy:%.4f\" % results['training_score'])\n print(\"Test accuracy:%.4f\" % results['testing_score'])\n print(classification_report(y_test, predictions_test,digits=4))\n return results\n\n\n# In[79]:\n\n\ndef run_model(clf1,clf2,name):\n '''\n inputs:\n - clf1: first classifier model\n - clf2: 2nd classifier model for comparison\n - name: name of models for comparison\n \n outputs:\n - Dataframe of results from model training and prediction\n '''\n \n # Collect results on the learners\n results = {}\n for clf in [clf1, clf2]:\n clf_name = clf.__class__.__name__ + '_' +name\n results[clf_name] = {}\n results[clf_name]= train_predict(clf, X_train, y_train, X_test, y_test)\n return pd.DataFrame(results)\n\n\n# ## BOGO offers model\n# \n# First we try to build the BOGO offers model. I initialize the models with some randomly chosen parameters to check the initial performance. If performance needs to be improved further, I will attempt Grid Search to find the optimal parameters.\n\n# First we will try to build baseline models with random parameter.\n# \n# Later we will try gridsearch to improve model performance.\n\n# In[80]:\n\n\ndrop_cols_prep=['person','offer_id','effective_offer','offer_type']\nfeatures,target=data_prep(offers_bogo,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model - baseline is DT model, bogo_1 model is RF model\nbaseline = DecisionTreeClassifier(criterion='entropy',max_depth=5,random_state=2,min_samples_split=90,min_samples_leaf=50)\nbogo_1 = RandomForestClassifier(random_state=2,max_depth= 11, max_features= 'auto',min_samples_split= 10,n_estimators=20,min_samples_leaf=20)\n\nresults=run_model(baseline,bogo_1,'bogo_1')\n\n\n# The accuracy for Random Forest Classifier (RF) model actually ends up outperforming the Decision Tree Classifier (DT) model slightly, but overall the performance for both models is about the same (82.14% vs 81.77% respectively in terms of accuracy). \n# Accuracy for a first attempt is quite good, more than 80%. I will try to tune the model further to get a better accuracy.\n# \n# However, in terms of the F1 score, both models are below 80%, with the Random Forest model performing worse compared to the Decision Tree Classifier, with 75.91% vs. 79.63%. To analyse this, we have to refer to the formula for Precision, Recall and F1 score:\n# \n# **Recall or Sensitivity or TPR (True Positive Rate):** \n# \n# According to sklearn documentation, the recall is intuitively the ability of the classifier to find all the positive samples.\n# \n# Number of items correctly identified as positive out of total true positives: True Positives /(True Positives +False Negatives)\n# \n# **Precision:** \n# \n# According to the sklearn documentation, it is intuitively the ability of the classifier not to label as positive a sample that is negative.\n# \n# Number of items correctly identified as positive out of total items identified as positive: True Positives /(True Positives + False Positives)\n# \n# \n# **F1 Score:** \n# \n# Since my F-beta score is F1 with beta=1, I am weighting recall and precision as equally important.\n# \n# The formula is given by the harmonic mean of precision and recall: F1 = 2*Precision*Recall/(Precision + Recall)\n# \n# We can see that the F1 scores for DT outperformed RF slightly, but both are lower than the accuracy. This would indicate that DT model is doing slightly better compared to RF at not misclassifying negative events as positive (meaning, misclassifying people on which offers are ineffective, as people on which offers would be effective). \n# \n# The difference in F1 score vs accuracy indicate that there could are instances where both models are falsely classifying negatives as positives, likely due to the imbalance of classes. But the overall higher recall/accuracy compared to F1 score indicates that the model is predicting the positive case (i.e. where an offer is effective) more accurately compared to predicting the negative cases (i.e. where an offer is ineffective), which is expected given the uneven classes..\n# \n# However, revisiting our use case, we are perhaps not as concerned with these misclassification since we don't mind sending people more offers than they would have liked; we would rather not miss anyone on which an offer would have been effective.\n# \n# Given this case, I will still go with the RF model.\n# \n# Since I aim to analyse the drivers of an effective offer, I will check the feature importances for the models after I have selected the best model from refinement.\n\n# ## Discount offers model\n# \n# Repeating the same steps above but with my offer_discounts dataset.\n\n# In[81]:\n\n\ndrop_cols_prep=['person','offer_id','effective_offer','offer_type']\nfeatures,target=data_prep(offers_discount,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\ndiscount_1 = RandomForestClassifier(random_state=2,max_depth= 20, max_features= 'auto',min_samples_split= 10,n_estimators=20,min_samples_leaf=10)\nresults=pd.concat([results[:],run_model(baseline,discount_1,'discount_1')],axis=1)\n\n\n# This time, the Random Forest Classifier model also has a better performance compared to the Decision Tree Classifier in terms of accuracy (87.23% vs 86.72%), and the F1 score is also lower (81.43% vs 82.87%). \n# \n# The F1 score for these models are lower overall compared to the Accuracy score. This could be an indication that there are some instances where both models are classifying the negative cases (effective_offer = 0) falsely. Again, I am not too bothered by this as I am more concerned with the model predicting positive cases accurately, so would rather go with a higher accuracy model where F1 score for cases `effective_offer=1` is higher, for which our RF classifier has better performance (0.9317 vs 0.9280).\n\n# ## Informational offers model\n\n# In[82]:\n\n\nfeatures,target=data_prep(offers_info,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\ninfo_1 = RandomForestClassifier(random_state=5,criterion='gini',max_depth= 20, max_features= 'auto',min_samples_split= 10,n_estimators=20,min_samples_leaf=10)\n\nresults=pd.concat([results[:],run_model(baseline,info_1,'info_1')],axis=1)\n\n\n# The performance for these models are worse compared to the other 2 datasets, with accuracy below 80% for both models, but RF model still performing better. The F1 score is also worse, at 67.54% RF Classifier, worse than the DT model at 68.66%.\n# \n# One potential reason for the worse performance is perhaps due to the fact that I had the key assumption to assign the conversion events to be transactions that only occur after an offer is viewed and within the specified duration; I might have missed out on some valuable information by removing those transactions that occur regardless. We can see this from how the overall sample dataset is smaller (about half) the datasets for the other 2 offers, with only about 5K samples compared to about 10K for both BOGO and discount respectively. \n\n# # Refinement/Model tuning\n\n# In[83]:\n\n\n#define function to find best model results for each offer type\ndef best_model(offer_type):\n '''\n input:\n - offer_type: string of offer type name\n output:\n - dataframe containing results of best model so far\n \n '''\n print('For ' + offer_type + ' RF model:')\n return results.transpose()[results.transpose()['testing_score']==results.transpose()[results.transpose().index.str.contains(\"RandomForestClassifier_\"+offer_type)]['testing_score'].max()]\n\n\n# **Grid Search to discover optimal parameters**\n# \n# For all three offers, the Random Forest model had relatively good performance, so I used Grid Search on this to determine the best parameters.\n\n# In[84]:\n\n\n#define Grid Search function\ndef rand_forest_param_selection(X,y):\n '''\n input:\n - X,y: training datasets for X and y\n output:\n - dictionary with best parameters for random forest model\n '''\n \n param_grid={'max_features': ['auto', 'sqrt'],\n 'max_depth' : [5,10,15,20],\n 'n_estimators': [10,20,25,30,40,50],\n 'min_samples_split': [2, 10, 20],\n 'min_samples_leaf': [2, 10,15, 20],\n }\n grid_search = GridSearchCV(RandomForestClassifier(random_state=2), param_grid)\n grid_search.fit(X, y)\n grid_search.best_params_\n return grid_search.best_params_\n\n\n# In[85]:\n\n\n#define BOGO dataset\nfeatures,target=data_prep(offers_bogo,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#run Grid Search - commented out because takes to long to run, but have put in selected params in model\n# rand_forest_param_selection(X_train, y_train)\n\n\n# In[86]:\n\n\nfeatures,target=data_prep(offers_bogo,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\nbogo_2 = RandomForestClassifier(random_state=2,max_depth= 10, max_features= 'auto',min_samples_split= 20,n_estimators=30,min_samples_leaf=2)\n\nresults=pd.concat([results[:],run_model(baseline,bogo_2,'bogo_2')],axis=1)\n\n\n# In[87]:\n\n\nresults[['RandomForestClassifier_bogo_1','RandomForestClassifier_bogo_2']]\n\n\n# In[88]:\n\n\n#find best model so far for BOGO offer type\nbest_model('bogo')\n\n\n# The accuracy for the RF model increased slightly - from 82.14% to 82.51%, and the F1 score increased from 75.91% to 77.64%. This is a good performance increase but minimal, which indicates that perhaps there's not much that can be done to improve the performance of the model with parameter tuning. \n# \n# So I will have to explore other avenues with the features to improve the performance of the model further.\n\n# In[89]:\n\n\n#define discount dataset\nfeatures,target=data_prep(offers_discount,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n# run Grid Search - commented out because takes to long to run, but have put in selected params in model\n# rand_forest_param_selection(X_train, y_train)\n\n\n# In[90]:\n\n\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\ndiscount_2 = RandomForestClassifier(random_state=2,max_depth= 10, max_features= 'auto',min_samples_split= 20,n_estimators=30,min_samples_leaf=2)\n\nresults=pd.concat([results[:],run_model(baseline,discount_2,'discount_2')],axis=1)\n\n\n# In[91]:\n\n\nresults[['RandomForestClassifier_discount_1','RandomForestClassifier_discount_2']]\n\n\n# In[92]:\n\n\n#find best model so far for discount offer type\nbest_model('discount')\n\n\n# In[93]:\n\n\n#define info dataset\nfeatures,target=data_prep(offers_info,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#run Grid Search - commented out because takes to long to run, but have put in selected params in model\n# rand_forest_param_selection(X_train, y_train)\n\n\n# In[94]:\n\n\nfeatures,target=data_prep(offers_info,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\ninfo_2 = RandomForestClassifier(random_state=2,max_depth= 15, max_features= 'auto',min_samples_split= 2,n_estimators=20,min_samples_leaf=15)\n\nresults=pd.concat([results[:],run_model(baseline,info_2,'info_2')],axis=1)\n\n\n# In[95]:\n\n\nresults[['RandomForestClassifier_info_1','RandomForestClassifier_info_2']]\n\n\n# In[96]:\n\n\n#find best model so far for info offer type\nbest_model('info')\n\n\n# Again we see some improvement in accuracy for RF model, from 75.09% to 75.30%, and slight increase in F1 score from 67.54% to 67.78%. This improvement is minimal,so we look into improving the feature selection of the model. \n\n# **Removing sparse features e.g. amount_invalid**\n# \n# In terms of feature selection, I wanted to try and see if removing the amount_invalid variable, which we had noted as being sparse, hence may not be useful in predicting the effectiveness of offers, would help.\n# \n# I removed the feature from my data prep and retrained the model using the same optimal parameters found via GridSearch, with the DT model as a baseline.\n\n# In[97]:\n\n\n#add amount_invalid variable to drop_cols_prep list\ndrop_cols_prep=['person','offer_id','effective_offer','offer_type','amount_invalid']\n\n#train BOGO model\nfeatures,target=data_prep(offers_bogo,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\nbogo_3 = RandomForestClassifier(random_state=2,max_depth= 10, max_features= 'auto',min_samples_split= 20,n_estimators=30,min_samples_leaf=2)\n\nresults=pd.concat([results[:],run_model(baseline,bogo_3,'bogo_3')],axis=1)\n\n\n# In[98]:\n\n\nresults[['RandomForestClassifier_bogo_2','RandomForestClassifier_bogo_3']]\n\n\n# In[99]:\n\n\n#find best model so far for BOGO offer type\nbest_model('bogo')\n\n\n# Model accuracy and F1 score did improve, so I will leave the amount_invalid feature out of my model.\n\n# In[100]:\n\n\n#train discount model\nfeatures,target=data_prep(offers_discount,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\ndiscount_3 = RandomForestClassifier(random_state=2,max_depth= 10, max_features= 'auto',min_samples_split= 20,n_estimators=30,min_samples_leaf=2)\n\nresults=pd.concat([results[:],run_model(baseline,discount_3,'discount_3')],axis=1)\n\n\n# In[101]:\n\n\nresults[['RandomForestClassifier_discount_2','RandomForestClassifier_discount_3']]\n\n\n# In[102]:\n\n\n#find best model so far for discount offer type\nbest_model('discount')\n\n\n# In[103]:\n\n\n#train info model\nfeatures,target=data_prep(offers_info,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\ninfo_3 = RandomForestClassifier(random_state=2,max_depth= 15, max_features= 'auto',min_samples_split= 2,n_estimators=20,min_samples_leaf=15)\n\nresults=pd.concat([results[:],run_model(baseline,info_3,'info_3')],axis=1)\n\n\n# In[104]:\n\n\nresults[['RandomForestClassifier_info_2','RandomForestClassifier_info_3']]\n\n\n# In[105]:\n\n\n#find best model so far for info offer type\nbest_model('info')\n\n\n# Accuracy and F1 score of the model actually decreased here for info model, so I will also keep the feature in. This is expected since the model had already a worse performance compared to the other 2 models, so the model is slightly underfitting compared to the others. Hence the model needs more features to learn to predict better.\n\n# **Dropping one level of dummy variables/one-hot encoding**\n# \n# There is a debate when using tree models and using regression models when it comes to one hot encoding. For regression classification models (e.g. logistic regression, we should typically remove one level of the variable in order to prevent multicollinearity between variables. Typically, we should not run into this issue with tree-based models like the ones I am using here. \n# \n# However, there is some debate as to whether one should do it or not. According to some articles (like here: https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/), it is generally not advisable to encode categorical variables as they would generate sparse matrices, resulting in:\n# \n# 1. The resulting sparsity virtually ensures that continuous variables are assigned higher feature importance.\n# 2. A single level of a categorical variable must meet a very high bar in order to be selected for splitting early in the tree building. This can degrade predictive performance.\n# \n# In scikitlearn implementations of RF and DT, one has to encode the variables. So I decided to test my model performance if I were to drop one level of my categorical variables (in my data - the channel variables and the gender variables), just to reduce the sparsity and noise in the data for my model.\n\n# In[106]:\n\n\n#add one level of dummy variables to drop column \ndrop_cols_prep=['person','offer_id','effective_offer','offer_type','amount_invalid','social','gender_O']\nfeatures,target=data_prep(offers_bogo,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model - reuse best performing model - \nbogo_4 = RandomForestClassifier(random_state=2,max_depth= 10, max_features= 'auto',min_samples_split= 20,n_estimators=30,min_samples_leaf=2)\n\nresults=pd.concat([results[:],run_model(baseline,bogo_4,'bogo_4')],axis=1)\n\n\n# In[107]:\n\n\nresults[['RandomForestClassifier_bogo_3','RandomForestClassifier_bogo_4']]\n\n\n# In[108]:\n\n\n#find best model so far for BOGO offer type\nbest_model('bogo')\n\n\n# In[109]:\n\n\nfeatures,target=data_prep(offers_discount,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model - reuse best performing model - \ndiscount_4 = RandomForestClassifier(random_state=2,max_depth= 10, max_features= 'auto',min_samples_split= 20,n_estimators=30,min_samples_leaf=2)\n\nresults=pd.concat([results[:],run_model(baseline,discount_4,'discount_4')],axis=1)\n\n\n# In[110]:\n\n\nresults[['RandomForestClassifier_discount_3','RandomForestClassifier_discount_4']]\n\n\n# In[111]:\n\n\n#find best model so far for discount offer type\nbest_model('discount')\n\n\n# In[112]:\n\n\nfeatures,target=data_prep(offers_info,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model - reuse best performing model - \ninfo_4 = RandomForestClassifier(random_state=2,max_depth= 15, max_features= 'auto',min_samples_split= 2,n_estimators=20,min_samples_leaf=15)\n\nresults=pd.concat([results[:],run_model(baseline,info_4,'info_4')],axis=1)\n\n\n# In[113]:\n\n\nresults[['RandomForestClassifier_info_3','RandomForestClassifier_info_4']]\n\n\n# In[114]:\n\n\n#find best model so far for info offer type\nbest_model('info')\n\n\n# Overall, we have seen that there is not much improvement in model performance just by reducing one level of categorical features. I am quite satisfied with the performance of the BOGO and discount models, but want to explore if I can improve the performance of the info model.\n\n# **Using polynomial features**\n# \n# Since a low accuracy score for the info model is likely due to the model underfitting, I decided to attempt if transforming the features further might improve model performance.\n# \n# I tweaked my model_pipeline function to include the polynomial features transformation to my features. \n\n# In[115]:\n\n\n#prepare model pipeline\ndef model_pipeline_poly(features,target,poly_feat=0):\n '''\n input:\n - features & target dataframes\n - poly_feat: number of degrees to transform polynomial features\n \n output:\n - X_train, X_test, y_train, y_test dataframes\n \n '''\n \n #split into training and test sets\n X_train, X_test, y_train, y_test = train_test_split(features,target, \n test_size=0.20, \n random_state=42)\n #fit and transform training data\n poly = PolynomialFeatures(poly_feat)\n X_train_poly=poly.fit_transform(X_train)\n \n #transform test data\n X_test_poly=poly.transform(X_test)\n \n #fit and transform scaling on training data\n scaler=StandardScaler()\n X_train=scaler.fit_transform(X_train_poly)\n\n #scale test data\n X_test=scaler.transform(X_test_poly)\n return X_train,X_test,y_train, y_test\n\n\n# In[116]:\n\n\n#keep amount_invalid in offers_info dataset\ndrop_cols_prep=['person','offer_id','effective_offer','offer_type']\nfeatures,target=data_prep(offers_info,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline_poly(features,target,2)\n\n#Initialize the model\ninfo_5 = RandomForestClassifier(random_state=2,max_depth= 15, max_features= 'auto',min_samples_split= 2,n_estimators=20,min_samples_leaf=15)\n\nresults=pd.concat([results[:],run_model(baseline,info_5,'info_5')],axis=1)\n\n\n# In[117]:\n\n\nresults[['RandomForestClassifier_info_2','RandomForestClassifier_info_5']]\n\n\n# In[118]:\n\n\n#find best model so far for info offer type\nbest_model('info')\n\n\n# We can see that performance actually decreased slightly for the RF model. Hence it would perhaps be a better idea to just keep the model as is. A maximum accuracy of 75.30% is acceptable for the info offers, even though it is not as high as the BOGO or discount offers. After all, we already included some assumptions for the 'influence' of the offer based on the duration.\n\n# In[119]:\n\n\nresults.loc[['training_score','testing_score'],['RandomForestClassifier_info_1','RandomForestClassifier_info_2','RandomForestClassifier_info_3','RandomForestClassifier_info_4','RandomForestClassifier_info_5']].transpose().plot.line()\nplt.title('Training and Testing score for RF info models')\nplt.show()\n\n\n# A note however, we can above actually see the model is performing better in the training accuracy as we add more variables for each model via polynomial features and removing the amount_invalid feature. It is just that the testing accuracy was reducing, and we can see this is due to overfitting.\n# \n# I can improve the accuracy and performance of the info model further by using RF info model 5, but adding more data, as we already noted the dataset for the `offers_info` dataset is half the size of the BOGO and discount datasets. Hence, ultimately with more data and with performance tuning, removing unnecessary variables and feature transformation, with more data I could have ultimately got the performance of the model perhaps above 80%.\n# \n# **Discussion on best models and feature importances:**\n# \n# Now that I am done with refining the 3 models, we can check the results for our best models for all 3 and check the feature importances to see the top drivers of effectiveness of offers.\n\n# In[120]:\n\n\n#get best model overall for bogo,discount and info offers\nbest_model('bogo').append([best_model('discount'),best_model('info')]).transpose()\n\n\n# Overall, we can see that the top performing models are the 3rd model (with GridSearch to find optimal model parameters and removing amount_invalid column) for predicting effectiveness of BOGO and discount offers, whereas the best performing model for informational offers was just after performing GridSearch to find the optimal parameters.\n# \n# In order to find the most influential drivers of an effective offer, we can check the feature importances of our best models above.\n\n# In[121]:\n\n\n#show feature importance\n#BOGO 3 model\n#prepare data same as BOGO 3 state\ndrop_cols_prep=['person','offer_id','effective_offer','offer_type','amount_invalid']\nfeatures,target=data_prep(offers_bogo,drop_cols_prep)\n\nfeature_importances = pd.DataFrame(bogo_3.feature_importances_,\n index = features.columns,\n columns=['importance']).sort_values('importance',ascending=False)\nfeature_importances.plot.bar()\nplt.title('Best BOGO model feature importance')\nplt.show()\n\n#discount 3 model\nfeature_importances = pd.DataFrame(discount_3.feature_importances_,\n index = features.columns,\n columns=['importance']).sort_values('importance',ascending=False)\nfeature_importances.plot.bar()\nplt.title('Best discount model feature importance')\nplt.show()\n\n#info_2 model\n#prepare data similar to info_2 state\ndrop_cols_prep=['person','offer_id','effective_offer','offer_type']\nfeatures,target=data_prep(offers_discount,drop_cols_prep)\n#print feature importance\nfeature_importances = pd.DataFrame(info_2.feature_importances_,\n index = features.columns,\n columns=['importance']).sort_values('importance',ascending=False)\nfeature_importances.plot.bar()\nplt.title('Best info model feature importance')\nplt.show()\n\n\n# Checking on the feature importance to analyse the main drivers of an effective offer, we can see that the most important driver of effective offers across all three are the tenure of membership. However, the 2nd most important feature is different for each of the three models.\n# \n# For a BOGO offer, the membership tenure is the most important feature, and the other variables are a lot smaller in proportions. Income, age and offer_received_cnt are the 2nd, 3rd and 4th most important features, but their proportions are very small.\n# \n# For a discount offer, after the membership tenure, age and income are the next most important variables. But it is still very small in proportions.\n# \n# The feature importances for the informational offer models are more distributed compared to the BOGO and discount models, with income being the 2nd most important feature. Age is the third and mobile channel interestingly being the 4th.\n\n# ### Exploration on users in Groups 3 and 4 - People who purchase regardless of viewing any offers\n# \n# We had earlier delineated those in groups 3 and 4 as people who would purchase regardless of viewing any offers. Now we can do some exploratory analyses to see what kind of demographic this group of users consist of.\n# \n# **Data Preparation:**\n# \n# It would be interesting to see how people in groups 3 and 4 contrast with people in groups 1 and 2, so I decided to compare between all 3.\n# \n# First, I need to append the data from all groups from the three offer types together, then compare the characteristics of each group via visualizations.\n\n# In[122]:\n\n\n#append datasets together\n\n#grp 3+4\ngrp3_4=grp3_bogo.append(grp3_discount,sort=False)\ngrp3_4=grp3_4.append(grp3_info,sort=False)\ngrp3_4=grp3_4.append(grp4_bogo,sort=False)\ngrp3_4=grp3_4.append(grp4_discount,sort=False)\ngrp3_4=grp3_4.append(grp4_info,sort=False)\n\n#grp1\ngrp1_all=grp1_bogo.append(grp1_discount,sort=False)\ngrp1_all=grp1_all.append(grp1_info,sort=False)\n\n#grp2\ngrp2_all=grp2_bogo.append(grp2_discount,sort=False)\ngrp2_all=grp2_all.append(grp2_info,sort=False)\n\n#get unique person-offer_id pairs\ngrp3_4=grp3_4[['person','offer_id']].groupby(['person','offer_id']).count().reset_index()\ngrp1_all=grp1_all[['person','offer_id']].groupby(['person','offer_id']).count().reset_index()\ngrp2_all=grp2_all[['person','offer_id']].groupby(['person','offer_id']).count().reset_index()\n\n#get membership_tenure_days\ngrp3_4=member(grp3_4)\ngrp1_all=member(grp1_all)\ngrp2_all=member(grp2_all)\n\n#merge with transcript to check transaction amount\ngrp3_4=grp3_4.merge(transcript[['person','offer_id','amount']].groupby(['person','offer_id']).sum(),on=['person','offer_id'],how='left')\ngrp1_all=grp1_all.merge(transcript[['person','offer_id','amount']].groupby(['person','offer_id']).sum(),on=['person','offer_id'],how='left')\ngrp2_all=grp2_all.merge(transcript[['person','offer_id','amount']].groupby(['person','offer_id']).sum(),on=['person','offer_id'],how='left')\n\n\n# In[123]:\n\n\n#check null values\nprint(\"For grp 3 and 4:\")\nprint((grp3_4.isnull().sum()/len(grp3_4))*100)\n\n#drop null values\ngrp3_4=grp3_4.dropna()\n\n#check null values\nprint(\"For grp 1:\")\nprint((grp1_all.isnull().sum()/len(grp1_all))*100)\n\n#drop null values\ngrp1_all=grp1_all.dropna()\n\n#check null values\nprint(\"For grp 2:\")\nprint((grp2_all.isnull().sum()/len(grp2_all))*100)\n\n#drop null values\ngrp2_all=grp2_all.dropna()\n\n\n# In[124]:\n\n\n#check size of groups\nprint(\"Size of group 1: \"+ str(len(grp1_all['person'])))\nprint(\"Size of group 3+4: \"+ str(len(grp3_4['person'])))\nprint(\"Size of group 2: \"+ str(len(grp2_all['person'])))\n\n\n# Comparing the sizes of the 3 groups, we can see that group 1 is the largest, while group 2 is the smallest, which is unsurprising as we had seen that the classes in our datasets were imbalanced in favour of positive classes (i.e. `effective_offers=1`). Meanwhile for people in groups 3 and 4 there are quite a significant number of people as well, larger than the number of people in group 2.\n# \n# **Exploration of demographic characteristics:**\n# \n# Meanwhile, in order to effectively compare between the groups, I created a function to efficiently visualize the groups together.\n\n# In[125]:\n\n\n#create function for plotting multiple histograms overlaying the 3 groups\ndef plot_hist(variable,bins=None):\n plt.hist(grp1_all[variable],alpha=0.5, label='group 1',bins=bins)\n plt.hist(grp3_4[variable], alpha=0.5, label='group 3 and 4',bins=bins)\n plt.hist(grp2_all[variable], alpha=0.5, label='group 2',bins=bins)\n plt.legend(loc='upper right')\n plt.title('distribution of '+ variable + ' between group 1, group 2 and groups 3 + 4')\n plt.show()\n\n\n# In[126]:\n\n\n#plot distribution of income\nplot_hist('income')\n\n\n# Across the 3 segments, most people fall within the middle range of income (50K - 100K). The income distribution between the 3 segments are relatively similar.\n\n# In[127]:\n\n\n#plot ditribution of age\nplot_hist('age')\n\n\n# Age distribution looks relatively similar between the 3 groups as well, with most people between the age 40-80 years old.\n\n# In[128]:\n\n\n#plot distribution of amount spent given an effective offer\nplot_hist('amount',bins=1)\n\n\n# Group 2 are people who did not spend at all as the offers were ineffective on them, hence they are not in the graph. But for groups 1 and 3+4, we can see that the amount spent is relatively similar, except that people in group 1 spent slightly more. This is to be expected as we might expect that the offers managed to incentivise them to purchase more, hence their overall spend increased. \n\n# In[129]:\n\n\n#plot tenure of membership\nplot_hist('membership_tenure_days')\n\n\n# The distribution of membership tenure also looks similar between the 3 segments, with most people between 0-700 days of tenure. It appears as though there are not much demographic characteristic differences between the 3 groups, at least in the current data provided.\n\n# ## Potential all-in-one model\n# \n# Out of curiosity, I wondered if we could predict the effectiveness of an offer if the offer type was included as a categorical feature. Would the type of offer affect the user's responsiveness?\n# \n# To do this, I would need to do some minor data preparation to prepare the data for a multiclass model.\n\n# In[130]:\n\n\n#append datasets together\noffers_bogo['offer_type']='bogo'\noffers_info['offer_type']='informational'\noffers_discount['offer_type']='discount'\noffers=offers_discount.append(offers_bogo,sort=False)\noffers=offers.append(offers_info,sort=False)\n\n#create dummy variable for offer_type categorical variable\noffers=dummy(offers,'offer_type')\n\n\n# In[ ]:\n\n\n#do grid search to find optimal parameters for RF model\ndrop_cols_prep=['person','offer_id','effective_offer','amount_invalid']\nfeatures,target=data_prep(offers,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\nrand_forest_param_selection(X_train, y_train)\n\n\n# In[ ]:\n\n\ndrop_cols_prep=['person','offer_id','effective_offer','amount_invalid']\nfeatures,target=data_prep(offers,drop_cols_prep)\nX_train, X_test, y_train, y_test=model_pipeline(features,target)\n\n#Initialize the model\nall_in_one = RandomForestClassifier(random_state=5,criterion='gini',max_depth= 20, max_features= 'auto',min_samples_split= 2,n_estimators=50,min_samples_leaf=15)\n\nresults=pd.concat([results[:],run_model(baseline,all_in_one,'all_in_one')],axis=1)\n\n\n# In[ ]:\n\n\n#comparing best performance of all 3 models with all_in_one model\nresults[['RandomForestClassifier_bogo_3','RandomForestClassifier_discount_3','RandomForestClassifier_info_2','DecisionTreeClassifier_all_in_one','RandomForestClassifier_all_in_one']]\n\n\n# In[ ]:\n\n\nresults.loc[['testing_score'],['RandomForestClassifier_bogo_3','RandomForestClassifier_discount_3','RandomForestClassifier_info_2','DecisionTreeClassifier_all_in_one','RandomForestClassifier_all_in_one']].plot.bar()\nplt.title('Comparing testing set accuracy score for the 3 models vs all-in-one model')\nplt.legend(loc=3)\nplt.show()\n\n\n# Comparing the performance of the 3 best models for each offer type with the all_in_one model, we can se that having the all-in-one model is not as good as the RF bogo and discount models, and is about slightly better than the info model. This is probably due to the info model pulling down the performance, resulting in lower accuracy for the all in one model. I suspect that if we were to break down the all-in-one model performance to just looking at its ability to predict the effectiveness of informational offer types, it would also be worse than its performance predicting the other 2 types. \n# \n# If we take a step back and look at the big picture, it is more useful to have a higher accuracy for 3 separate models, as opposed to one all-in-one model. This is because the BOGO and discount offers are actually aimed at driving sales with some promotional cost, whereas the informational offer is essentially 'free' with no cost, and if they can drive sales that would be a bonus.\n# \n# Hence, I would actually suggest that the 3 separate models are more useful.\n\n# ### Given an effective offer, can we predict how much someone would spend? \n# \n# In addition to the all-in-one model, since we already kept the datasets of effective transactions, I was curious to know if I could build a regression model to predict how much someone would spend, given an effective offer. I could have built a model separately for each offer type to predict their spend, but I was curious to know if the type of offer would also determine a user's level of spend. \n# \n# To do this, we have already assigned effective offers based on group 1 customers. From there, we just need to sum up their amount of spend driven by offers to see if we can predict how much someone would spend depending on the offer type.\n\n# In[ ]:\n\n\n#append all 3 datasets together\ngrp1=grp1_bogo.append(grp1_discount,sort=False)\ngrp1=grp1.append(grp1_info,sort=False)\n\n#drop unnecessary columns\ndrop_cols('effective_offer',grp1,inplace=True)\n\n#get offer details\ngrp1=grp1.merge(portfolio,how='left',on='offer_id')\n\n\n# We only take into account transactions that are influenced by an offer (i.e. `valid_completed=1`) as we want to predict the spend given (i.e. based on) the influence of an effective offer.\n\n# In[ ]:\n\n\n#get sum of valid transactions per person based on unique person and offer_id pair\ngrp1=grp1.merge(transcript[['person','offer_id','amount']][transcript['valid_completed']==1].groupby(['person','offer_id']).sum(),on=['person','offer_id'])\n\n\n# In[ ]:\n\n\n#get demographic data and membership_tenure details\ngrp1=member(grp1)\n\n#reset index for offers_info\ngrp1=drop_cols('index',grp1.reset_index())\n\n#reuse offers_info channel_col function to expand channel column into categorical variables\nchannel_col('web',grp1)\nchannel_col('email',grp1)\nchannel_col('mobile',grp1)\nchannel_col('social',grp1);\n\ndrop_cols('channels',grp1,inplace=True);\n\n#reuse offers_info function to prep dataset\ngrp1=prep_offers_df(grp1)\n\n#encode offer type as dummy variables\ngrp1=dummy(grp1,'offer_type')\n\n\n# Since this is a regression model, we need to prevent multicollinearity by reducing the level of the dummy variables by 1, dropping those columns.\n\n# In[ ]:\n\n\n#add one level of dummy variable to drop\ndrop_cols_prep=['person', 'offer_id','amount','social','gender_O','offer_type_informational']\ntarget=grp1['amount']\nfeatures=drop_cols(drop_cols_prep,grp1)\n\n\n# In[ ]:\n\n\n#tweak train_predict function -\ndef train_predict_reg(learner, X_train, y_train, X_test, y_test): \n '''\n inputs:\n - learner: the learning algorithm to be trained and predicted on\n - sample_size: the size of samples (number) to be drawn from training set\n - X_train: features training set\n - y_train: review_scores_rating training set\n - X_test: features testing set\n - y_test: review_scores_rating testing set\n '''\n results = {}\n \n #Fit the learner to the training data and get training time\n start = time() \n learner = learner.fit(X_train, y_train)\n end = time() \n results['train_time'] = end-start\n \n # Get predictions on the test set(X_test), then get predictions on first 300 training samples\n start = time() \n predictions_test = learner.predict(X_test)\n predictions_train = learner.predict(X_train)\n end = time() \n \n # Calculate the total prediction time\n results['pred_time'] = end-start\n \n #add training accuracy to results\n results['training_score']=learner.score(X_train,y_train)\n \n #add testing accuracy to results\n results['testing_score']=learner.score(X_test,y_test)\n \n print(\"{} trained on {} samples.\".format(learner.__class__.__name__, len(y_train)))\n print(\"MSE_train: %.4f\" % mean_squared_error(y_train,predictions_train))\n print(\"MSE_test: %.4f\" % mean_squared_error(y_test,predictions_test))\n print(\"Training accuracy:%.4f\" % results['training_score'])\n print(\"Test accuracy:%.4f\" % results['testing_score'])\n return results\n\n\n# In[ ]:\n\n\ndef run_model_reg(clf1,clf2,name):\n '''\n input:\n - clf1: baseline regression model\n - clf2: 2nd regression model to compare\n - name: name to keep track of comparison\n output:\n - dataframe containing results of training and prediction of model\n \n '''\n \n # Collect results on the learners\n results = {}\n for clf in [clf1, clf2]:\n clf_name = clf.__class__.__name__ + '_' +name\n results[clf_name] = {}\n results[clf_name]= train_predict_reg(clf, X_train, y_train, X_test, y_test)\n return pd.DataFrame(results)\n\n\n# In[ ]:\n\n\nX_train, X_test, y_train, y_test=model_pipeline_poly(features,target,2)\n\n#Initialize the model\nclf1 = Ridge(alpha=2,random_state=2)\nclf2 = DecisionTreeRegressor(random_state=2)\n\nresults_reg=run_model_reg(clf1,clf2,'reg')\n\n\n# In[ ]:\n\n\nresults_reg\n\n\n# The regression models really underperformed in terms of predicting the amount spent. It appears with the current data within our group 1 of customers, there is not enough information to predict the amount that can be driven by the offer type. We can see the Decision Tree Regressor model really overfit the data, with a very high training score but sub par testing score. Meanwhile, the linear regression model (with ridge/l2 regularization) also shows a minimal correlation between the features and the target variable. The model really underfits the data.\n# \n# I may get better performance if I break the models up into 3 different models based on offer type again; or even try to include non-influenced/invalid transactions, but this could be an exploration for another time.\n\n# # Conclusion\n\n# Overall Solving the given dataset was quite tricky & interesting, as structure of Transcript dataset was bit different.\n# \n# However, this analysis was done for finding the solutions of 2 business cases mentioned below:\n# \n# **1.What are the main drivers of offer effectiveness ?**\n# \n# For Question 1, the feature importance given by all 3 models were that the tenure of a member is the biggest predictor of the effectiveness of an offer. Further study would be able to indicate what average tenure days would result in an effective BOGO offer.\n# \n# For all three models, the top 3 variables were the same - membership tenure, income and age. However, income and age switched orders depending on offer type.\n# \n# For BOGO and discount offers, the distribution of feature importances were relatively equal. However, for informational offers, the distribution is slightly more balanced, with income the second most important variable.\n# \n# \n# **2.Exploring if we can predict whether a user would take up an offer.**\n# \n# \n# My decision to use 3 separate models to predict the effectiveness of each offer type ended up with good accuracy for the BOGO and discount models (82.83% for BOGO and 87.35% for discount), while slightly less accurate performance for informational offers (75.3%). However, I would regard 75% as acceptable in a business setting, as for informational offers, there is no cost involved to inform users of a product.\n# \n# Meanwhile, for BOGO and discount models, I am quite happy with the 80% and above accuracy, as in a business setting that would be acceptable to show offers to people, even if the model misclassifies a few, the overall revenue increase might justify the few mistakes.\n# \n\n# # Challenges & Improvement\n\n# \n# When analysing and building the machine learning models to answer the above questions, reflections on my main challenges and findings are as follows:\n# \n# **Attribution framework for assigning offer_ids for transactions:**\n# \n# In order to answer Question 1, I had to first define what an 'effective offer' means using the transactional records. This proved to be the trickiest portion of the project. I had to define a funnel for what what an effective conversion would look like, as we had data on both effective and noneffective conversions. Thus, I was desigining an attribution model for the conversion events (offer completed and transaction events) based on the events that occurred prior for each person.\n# \n# I ended up having to separate the users into 4 different pools, based on their actions in the transcript data:\n# \n# `Group 1: People who are influenced by offers and thus purchase/complete the offer(successful/effective conversion of offer)\n# Group 2: People who receive and an offer but is not influenced and thus no conversion event (ineffective conversion of offer)\n# Group 3: People who have conversion events but was not actually influenced by an offer\n# Group 4: People who receive offers but no views or action taken`\n# \n# Even after separating the groups, it was challenging to assign the people in group 3 based on the transactional data. I had to define the event space where the right sequence of events would occur before I could assign an offer id to transactions (which did not have an offer_id), essentally designing a event/sequence-based attribution window.\n# \n# After attributing the conversions to specific offers, the rest of the data preparation and cleaning was relatively straightforward. I was grateful that there were not many missing values, and the preparation of categorical variables was also relatively straightforward.\n# \n# **Feature engineering:**\n# \n# I decided to do some basic feature engineering as I found the model had slightly underfit on my first attempt in this project, so I had added the feature engineering section later. It improved the performance of the model slightly, and the membership_tenure feature I had engineered out of the became_member_on column ended up being the most important predictor variable.\n# \n# However, overall I found that I could not think of additional features using the time data, even though I had the hunch that the time of receiving the offer might be quite influential in determining whether it is effective or not.\n# \n# **Model implementation decisions:**\n# \n# I had made the decision to build 3 separate models depending on offer types based on my definition of the problem statement - as I wanted to discover what would drive an effective offer, I thought it made more sense to remove noise from the data by separating the data into the offer types. My decision ended up to be quite a good one as the single BOGO and discount models got good performance in testing scores, compared to the all-in-one model overall score.\n# \n# For the info model, the accuracy was slightly worse as we had less records overall (half of the BOGO and discount models). As elaborated above, I believe that if we had more data, I could have gotten the accuracy higher, as there was a clear diverging pattern occurring between the training and testing score as I made decisions to improve the model fit like adding polynomial features and removing 'noisy' features like the amount_invalid feature. Due to the limited data, my decisions ended up with the model overfitting, hence I believe the model accuracy would have benefitted from more data.\n# \n# An additional note on model selection - I selected tree-based models as I wanted to assess feature importance, but I could have extended this study further by testing a parametric/ regression model (e.g. logistic regression for classification tasks). The weights of the coefficients from a regression model might have been interesting to contrast with the feature importance of a tree-based model, given that both models have different ways of analysing the data. The feature membership_tenure_days might not have been the highest weighted feature, in contrast to how it was in this study.\n# \n# **Exploring demographics of different customer groups:**\n# \n# I was curious to know what the characteristics were of groups 3 and 4, which are customers who are not influenced by an offer at all. However, after comparing their characteristics with groups 1 and 2, I could not see any significant differences in their demographics.\n# \n# I would have liked to have more data to perhaps understand why this group of customers tend to not be influenced by offer, in order to make useful suggestions on how to give a good customer experience to these customers, even if we do not serve them any offers.\n# \n# b.v. Model accuracy in predicting amount spent given an effective offer:\n# The regression model I built out of curiosity to see if we could predict the amount a user would spend, given that they are effectively influenced by an offer. The motivation was that if we can predict how much someone would spend given an offer, perhaps we can assess which offers bring in the most revenue.\n# \n# However, my model found virtually no correlation between the features provided (namely, offer characteristics and demographics of app users) with the amount spent per user. These features aren't strong enough to predict the amount spent per user. Perhaps if we also have a value of the offer, for example, for a discount offer, the value of the discount in dollar terms, perhaps we might be able to predict better.\n# \n# Perhaps I could have broken them up into 3 different models for the 3 offer types, the way I did with the binary classification models, in order to get a better result. However, given that this was just a curiosity and I wanted to explore if the offer type would be a statistically significant predictor feature, I built an all-in-one model for this instance. This would be worth exploring further, given more time and data.\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.7721555829048157, "alphanum_fraction": 0.7823925018310547, "avg_line_length": 55.04917907714844, "blob_id": "e3f5742fd173022c3f93cddcd7a3a139e0c3222a", "content_id": "fce89f3b5f2fdadc0ef9945ff8e90367a872af59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3421, "license_type": "permissive", "max_line_length": 354, "num_lines": 61, "path": "/README.md", "repo_name": "SatyamDG/Udacity_Data_Scientist_NanoDegree_Capstone", "src_encoding": "UTF-8", "text": "# Udacity_Data_Scientist_NanoDegree_Capstone\n###### This repository has all the code and report for my Udacity Data Scientist Nanodegree Capstone project.\n\n## Starbucks Capstone Challenge: Using Starbucks app user data to predict effective offers\n\n### 1. Installations\nThis project was written in Python, using Jupyter Notebook on Anaconda. The relevant Python packages for this project are as follows:\n\n- pandas [doc](https://pandas.pydata.org/docs/ \"doc\")\n- numpy [doc](https://numpy.org/doc/ \"doc\")\n- math\n- json \n- sklearn.model_selection (train_test_split module) [doc](https://scikit-learn.org/ \"doc\")\n- sklearn.preprocessing (StandardScaler, PolynomialFeatures)\n- from sklearn.tree (DecisionTreeClassifier,DecisionTreeRegressor)\n- sklearn.ensemble (RandomForestClassifier)\n- sklearn.metrics (mean_squared_error,classification_report)\n- sklearn.linear_model (Ridge)\n- time\n- sklearn.model_selection (GridSearchCV)\n- matplotlib\n\n\n### 2. Project Motivation\n\nThis project is the Capstone project of my Data Scientist nanodegree with Udacity. As students in the nanodegree, we have the option to take part in the Starbucks Capstone Challenge. For the challenge, Udacity provided simulated data that mimics customer behavior on the Starbucks rewards mobile app.\n\nIn this project, follwoing questions are answered :\n\n- What are the main drivers of an effective offer on the Starbucks app?\n- Could the data provided, namely offer characteristics and user demographics, predict whether a user would take up an offer?\n\nThree Models are created for below mentioned offer.\n\nThe three offers are: **Buy One Get One Free (BOGO)**, **Discount (discount with purchase)**, and **Informational (provides information about products).**\n\n### Brief summary of findings:\n\nFeature importance given by all 3 models were that the tenure of a member is the biggest predictor of the effectiveness of an offer. Further study would be able to indicate what average tenure days would result in an effective BOGO offer.\n\nDecision of using 3 separate models for analysis & to predict the effectiveness of each offer type ended up with good accuracy for the 2 of the models **(82.83% for BOGO and 87.35% for discount)**, while slightly less accurate performance for another **informational offers (75.3%)**.\n\nHowever, I would regard 75% as acceptable in a business setting, as for informational offers, there is no cost involved to inform users of a product. Meanwhile, an 80% and above accuracy in a business setting would be acceptable to show offers to people, even if the model misclassifies a few, the overall revenue increase might justify the few mistakes.\n\n### 3. File Descriptions\n\nThis repo contains 4 files. The report of my project is called 'Starbucks_Capstone_notebook.ipynb'[Notebook](https://github.com/SatyamDG/Udacity_Data_Scientist_NanoDegree_Capstone/blob/master/data.zip \"Notebook\"). The data used in the project is in the files:\n\n- portfolio.json\n- profile.json \n- transcript.json.\n\nTo access data click here [data](https://github.com/SatyamDG/Udacity_Data_Scientist_NanoDegree_Capstone/blob/master/data.zip \"data\")\n\n### 4. Licensing, Authors, Acknowledgements, etc.\n\nData for coding project was provided by Udacity.\n\nFeel Free to use the Code, functions, etc from this repo.\n\n[Link](https://medium.com/@gsatyam625/data-science-to-predict-effective-offer-using-starbucks-app-user-data-6774750d5de1 \"Link\") to Medium Blog\n" } ]
2
fridafu/mean
https://github.com/fridafu/mean
a629f63e5d019888453fb52907eb241a14d45091
cf9ed4a05c7e46b775908ef5e1ae7016162ac296
b83c2d7001e048fb7e5a7fd3206cbf4c629cc4e3
refs/heads/master
2021-05-02T03:39:10.438187
2018-02-09T14:32:33
2018-02-09T14:32:33
120,902,468
0
0
BSD-2-Clause
2018-02-09T12:21:55
2018-02-09T12:30:56
2018-02-09T14:39:46
Python
[ { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.7218044996261597, "avg_line_length": 21.33333396911621, "blob_id": "7b0535fd9707f0b8afc9e207807da843dbe29326", "content_id": "f556363705644366ac8dbab51e457e3a23e5627b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "permissive", "max_line_length": 55, "num_lines": 6, "path": "/RBmain.py", "repo_name": "fridafu/mean", "src_encoding": "UTF-8", "text": "from test_mean import test_ints, test_double, test_long\n\nnum_list = [1,2,3,4,5]\ntest_ints(num_list)\ntest_double(num_list)\ntest_long()" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.682692289352417, "avg_line_length": 23.52941131591797, "blob_id": "b9bd95a0c94ecdf3f9cddf39dbd62b1bdb43a4b6", "content_id": "204ad5ebf5849ee2fa3d15c4e9b835ce353bfc36", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "permissive", "max_line_length": 53, "num_lines": 17, "path": "/RB1.py", "repo_name": "fridafu/mean", "src_encoding": "UTF-8", "text": "msg = \"\\nU cannot do it with the zero under there!!!\"\n\ndef mean(num_list):\n\tif len(num_list)== 0:\n\t\traise Exception(msg)\n\telse:\n\t\treturn sum(num_list)/len(num_list)\n\n\ndef mean2(num_list):\n\ttry:\n\t\treturn sum(num_list)/len(num_list)\n\texcept ZeroDivisionError as detail:\n\t\traise ZeroDivisionError(detail.__str__() + msg)\n\texcept TypeError as detail:\n\t\tmsg2 = \"\\n use numbers \"\n\t\traise TypeError(detail.__str__() + msg2)" }, { "alpha_fraction": 0.5849923491477966, "alphanum_fraction": 0.6401225328445435, "avg_line_length": 15.324999809265137, "blob_id": "e43b3daf0ff27e6f2956cec159917340fba3b586", "content_id": "d73810e635c1d3d988365ab11e936edebb03a23f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "permissive", "max_line_length": 54, "num_lines": 40, "path": "/test_mean.py", "repo_name": "fridafu/mean", "src_encoding": "UTF-8", "text": "from RB1 import *\n\nnumlist = [1,2,3,4,5]\n\ndef test_ints(nlist=numlist):\n\tobs = mean(nlist)\n\texp = 3\n\tassert obs == exp\n\ndef test_double(nlist=numlist):\n\tobs = mean(nlist)\n\t#nlist = [1,2,3,4]\n\texp = 3\n\tassert obs == exp\n\ndef test_long():\n\tbig = 100000000\n\tobs = mean(range(1,big))\n\texp = big/2.0\n\tassert obs == exp\n\t\ndef test_zero():\n\tnum_list = [0,2,4,6]\n\tobs = mean(num_list)\n\texp = 3\n\tassert obs == exp\n\n\"\"\"\ndef test_complex():\n\t#testing for complex numbers\n\t#as arithmetic mean of complex numbers is meaningless\n\tnum_list = [2+3j,3+4j,-32-2j]\n\tobs = mean(num_list)\n\texp = NotImplemented\n\tassert obs==exp\n\"\"\"\n\n#test_ints()\n#test_double()\n#test_long()\n" }, { "alpha_fraction": 0.8039215803146362, "alphanum_fraction": 0.8039215803146362, "avg_line_length": 16.33333396911621, "blob_id": "da8ef2ba74d84ad738d4f09ce4f4db0e91dad413", "content_id": "7e76b4590f462c082f65d60387953e8ca0dc48a6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 51, "license_type": "permissive", "max_line_length": 25, "num_lines": 3, "path": "/README.md", "repo_name": "fridafu/mean", "src_encoding": "UTF-8", "text": "# mean\nCode for testing workshop\nWe will use Travis" } ]
4
mahidulmoon/Protected-PortFolio
https://github.com/mahidulmoon/Protected-PortFolio
dad9e908ec43f15447c7292a61b1b72a6c64e841
24583700015bdb61a807ded457ed62ed1baa1ddf
0658d65a7ef5bf8eb0b48d9fb81c560e48326408
refs/heads/master
2020-07-06T12:09:31.012613
2019-08-19T10:09:07
2019-08-19T10:09:07
203,012,585
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.652482271194458, "alphanum_fraction": 0.652482271194458, "avg_line_length": 34.33333206176758, "blob_id": "2ac06705331ae50b6f18710e4c03fd0138cbf003", "content_id": "6ee35261a97d21815687179f524ae911f4f783fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 423, "license_type": "no_license", "max_line_length": 70, "num_lines": 12, "path": "/portfolio219/portfolio/views.py", "repo_name": "mahidulmoon/Protected-PortFolio", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import Portfolio\n# Create your views here.\ndef index(request):\n if request.method==\"POST\":\n name = request.POST['name']\n email = request.POST['email']\n contact = request.POST['phone']\n msg = request.POST['msg']\n obj=Portfolio(name=name,email=email,phone=contact,message=msg)\n obj.save()\n return render(request,\"index.html\",{})" }, { "alpha_fraction": 0.7033898234367371, "alphanum_fraction": 0.7372881174087524, "avg_line_length": 32.71428680419922, "blob_id": "a90d8c09d9ece35aecb6b8fb37ce62f8688033e6", "content_id": "8f93fd3af255b6942ed2f4a1d5a7eff8a6a9a325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/portfolio219/portfolio/models.py", "repo_name": "mahidulmoon/Protected-PortFolio", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Portfolio(models.Model):\n name=models.CharField(max_length=50)\n email = models.CharField(max_length=50)\n phone = models.CharField(max_length=50)\n message = models.CharField(max_length=50)\n" }, { "alpha_fraction": 0.6476190686225891, "alphanum_fraction": 0.6476190686225891, "avg_line_length": 31.384614944458008, "blob_id": "f4cfcf5e6f3acf2ae02c4a1a9cbbb4b08ffd64d3", "content_id": "8f0f47405abbcdd28d73d426309a8897b1151a98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 70, "num_lines": 13, "path": "/portfolio219(django)/portfolio/views.py", "repo_name": "mahidulmoon/Protected-PortFolio", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import Portfolio\n# Create your views here.\ndef index(request):\n if request.method==\"POST\":\n name = request.GET['name']\n\n email = request.GET['email']\n contact = request.GET['phone']\n msg = request.GET['msg']\n obj=Portfolio(name=name,email=email,phone=contact,message=msg)\n obj.save()\n return render(request,\"index.html\",{})" } ]
3
eshiji/app-demo
https://github.com/eshiji/app-demo
e860b59252f1220cb724122053dea36832ab55a2
c28f5a1ddaa5b2b5d85771f3adcc9159e34472b6
f96412af0bf3fa8e15133787c3f78fa9578c1a7f
refs/heads/master
2022-12-14T03:09:04.180587
2020-08-24T12:11:36
2020-08-24T12:11:36
289,916,862
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7291666865348816, "alphanum_fraction": 0.7395833134651184, "avg_line_length": 9.1578950881958, "blob_id": "8be574d94ffee089e65949bffa7974529980f7c9", "content_id": "9140b2af7924983c8ad00671ecf57d2ff393bfab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 196, "license_type": "no_license", "max_line_length": 31, "num_lines": 19, "path": "/README.md", "repo_name": "eshiji/app-demo", "src_encoding": "UTF-8", "text": "# devops-tools-front\n\nPré-requisitos:\npython 3.7\nvirtualenv\npip\n\n\n\nInstalar as dependências\n```\nvirtualenv venv\npip install -r requirements.txt\n```\n\nIniciando a aplicação\n```\npython run.py\n```" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 21.823530197143555, "blob_id": "51ae6bde89b8811a2ce33154ab6e257b10cadf28", "content_id": "edb3ea25364f1adab740a465a615ca70427192fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/app/controllers/default.py", "repo_name": "eshiji/app-demo", "src_encoding": "UTF-8", "text": "from flask import render_template\nfrom app import app\n\[email protected](\"/\")\[email protected](\"/index\")\ndef test_bootstrap():\n return render_template(\"index.html\")\n\[email protected](\"/health\")\ndef health():\n return {\"status\": \"app-demo is runnning...\"}\n\[email protected]('/handle_data', methods=['POST'])\ndef handle_data():\n return render_template(\"submit.html\")\n # your code\n # return a response" }, { "alpha_fraction": 0.6628571152687073, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 13.416666984558105, "blob_id": "03f34747c48aebe70f96928e3b8b20034142ff82", "content_id": "ef9f918089856e25c3962e17647a16a71dee6b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 175, "license_type": "no_license", "max_line_length": 35, "num_lines": 12, "path": "/Dockerfile", "repo_name": "eshiji/app-demo", "src_encoding": "UTF-8", "text": "FROM python:3.7.9-alpine\n\nWORKDIR /app\n\nCOPY requirements.txt .\nCOPY app/ .\nCOPY config.py /\nCOPY run.py /\n\nRUN pip install -r requirements.txt\n\nCMD [ \"python\", \"/run.py\" ] \n\n" } ]
3
awesomest/advent_calendar_2019_bitcoin
https://github.com/awesomest/advent_calendar_2019_bitcoin
881ddbe29aa3e098bdb4da7d028f2ef5ec3c9ef5
6752845b0a69d75be3d6942568eccdff0436ad06
6f904e657fce543dd69a1108fdd170098888187d
refs/heads/master
2020-11-27T04:08:57.471821
2020-09-14T08:34:05
2020-09-14T08:34:05
229,298,853
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5847119092941284, "alphanum_fraction": 0.596691370010376, "avg_line_length": 40.2470588684082, "blob_id": "b5effc051a807ae7dcfaf12d6901cef2d129c7cc", "content_id": "bcc3cbe80fbede9c62a23376ad87a18bf3066399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3574, "license_type": "no_license", "max_line_length": 168, "num_lines": 85, "path": "/bitcoin.py", "repo_name": "awesomest/advent_calendar_2019_bitcoin", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom datetime import datetime as dt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\n\ncsv = pd.read_csv(\"history_20191218.csv\")\n\nclass BitcoinClassification:\n def __init__(self, csv):\n self.csv = csv.rename(columns={\"日付け\": \"date\", \"終値\": \"close\", \"始値\": \"start\", \"高値\": \"high\", \"安値\": \"low\", \"出来高\": \"volume\", \"前日比%\": \"diff\"}).sort_values([\"date\"])\n self.data = self.csv[[\"date\", \"start\", \"close\", \"low\", \"high\", \"volume\", \"diff\"]]\n\n def format(self):\n self.data[\"date\"] = pd.to_datetime(self.csv[\"date\"], format=\"%Y年%m月%d日\").astype(int) / 10**9\n self.data[\"start\"] = self.csv[\"start\"].str.replace(\",\", \"\").astype(int)\n self.data[\"close\"] = self.csv[\"close\"].str.replace(\",\", \"\").astype(int)\n self.data[\"low\"] = self.csv[\"low\"].str.replace(\",\", \"\").astype(int)\n self.data[\"high\"] = self.csv[\"high\"].str.replace(\",\", \"\").astype(int)\n self.data[\"volume\"] = self.csv[\"volume\"].str.replace(\"K\", \"\").astype(float)\n self.data[\"diff\"] = self.csv[\"diff\"].str.replace(\"%\", \"\").astype(float)\n self.data[\"year\"] = pd.to_datetime(self.csv[\"date\"], format=\"%Y年%m月%d日\").dt.strftime(\"%Y\").astype(int)\n self.data[\"month\"] = pd.to_datetime(self.csv[\"date\"], format=\"%Y年%m月%d日\").dt.strftime(\"%m\").astype(int)\n self.data[\"day\"] = pd.to_datetime(self.csv[\"date\"], format=\"%Y年%m月%d日\").dt.strftime(\"%d\").astype(int)\n self.data[\"weekday\"] = pd.to_datetime(self.csv[\"date\"], format=\"%Y年%m月%d日\").dt.strftime(\"%w\").astype(int)\n\n def out(self):\n return self.data\n\n def removeOutlier(self):\n self.data = self.data[self.data[\"start\"] > 0]\n self.data = self.data[self.data[\"close\"] > 0]\n self.data = self.data[self.data[\"low\"] > 0]\n self.data = self.data[self.data[\"volume\"] > 0]\n\n def addColumnResult(self):\n self.data[\"result\"] = self.data[\"diff\"].shift(1)\n self.data[\"result\"] = [1 if l >= 0.0 else -1 for l in self.data[\"result\"]]\n\n def train_and_test(self):\n clf = RandomForestClassifier(n_estimators=10)\n clf.fit(self.data_train, self.label_train)\n predict = clf.predict(self.data_test)\n return metrics.accuracy_score(self.label_test, predict)\n\n def calcAvgPred(self):\n sum_score = 0\n for i in range(100):\n ac_score = self.train_and_test()\n sum_score += ac_score\n\n return sum_score / 100\n\n def setTrainTestDataset(self, n):\n #label = \"diff\" + str(n)\n labels = [\"date\", \"year\", \"month\", \"day\", \"weekday\", \"start\", \"close\", \"low\", \"high\", \"volume\", \"diff\"]\n for i in list(range(2, n+1)):\n labels.append(\"diff\" + str(i))\n self.data_train, self.data_test, self.label_train, self.label_test = train_test_split(self.data[labels][n:], self.data[\"result\"][n:], random_state=1)\n\n def setColumnDiffN(self, n):\n label = \"diff\" + str(n)\n self.data[label] = self.data[\"start\"].shift(n-1)\n self.data[label] = self.data[\"close\"] / self.data[label] - 1\n\nb = BitcoinClassification(csv)\nb.format()\nb.removeOutlier()\nb.addColumnResult()\nd = 10\nfor i in list(range(2, d + 1)):\n b.setColumnDiffN(i)\n\nx = list(range(10))\ny = []\nfor i in list(range(1, d + 1)):\n b.setTrainTestDataset(i)\n pred = b.calcAvgPred()\n y.append(pred)\n print(\"平均[%d]: %f\" % (i, pred))\n\nplt.plot(x, y)\nplt.show()\n" }, { "alpha_fraction": 0.641791045665741, "alphanum_fraction": 0.753731369972229, "avg_line_length": 25.799999237060547, "blob_id": "d2dbbf95d565db1039d5d0702ddf4ae27b099cb2", "content_id": "5842f307a03877171c0e96f2c9743279686c2303", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 180, "license_type": "no_license", "max_line_length": 82, "num_lines": 5, "path": "/README.md", "repo_name": "awesomest/advent_calendar_2019_bitcoin", "src_encoding": "UTF-8", "text": "# [Bitcoin予測してみた! - Qiita](https://qiita.com/awesomest/items/6d505798598e19d34ae9)\n\n* `bitcoin.ipynb`\n* `bitcoin.py`\nどちらのファイルも同じ内容です。\n" } ]
2
GlebNSK/ESB_Intagration
https://github.com/GlebNSK/ESB_Intagration
13bd51d9cc68415bde1c205b415c06aa4b01ba00
a979623c1b36a4b1fd0b074461f79f38526029fe
bb751f867c3b21c956c2a400452e55821f01aa63
refs/heads/master
2022-11-13T03:07:57.631847
2020-07-09T07:56:23
2020-07-09T07:56:23
277,812,362
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5218184590339661, "alphanum_fraction": 0.5337449312210083, "avg_line_length": 34.28217697143555, "blob_id": "eaea01ba91d0858a1d244b387a55f91443ac528b", "content_id": "5c3ad83e9fb305fa71d911771f88909fa74a7526", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7638, "license_type": "no_license", "max_line_length": 93, "num_lines": 202, "path": "/payment_orders.py", "repo_name": "GlebNSK/ESB_Intagration", "src_encoding": "UTF-8", "text": "import datetime\n\nit_test = True\n\n\n# Обертки сервисов\nclass Wrapper1C:\n def __init__(self, name_object, object_to_serial):\n\n value = \"\"\n if name_object == \"ПлатежноеПоручение\":\n name_object_type = Operation.get_name_type_payment(self, object_to_serial)\n if name_object_type == \"in\":\n value_object = PaymentOrderIn(object_to_serial)\n elif name_object_type == \"out\":\n value_object = PaymentOrderOut(object_to_serial)\n else:\n value_object = {\"value\": \"\"}\n value = value_object.value\n else:\n value_object = \"\"\n if value != \"\":\n self.value = {\n \"#type\": value_object.typeObject1C + \".\" + value_object.nameType,\n \"#value\": value\n }\n else:\n self.value = \"\"\n\n\nclass WrapperTinkoff:\n def __init__(self, name_object, object_to_serial):\n if name_object == \"Operation\":\n pass\n self.value = \"\"\n\n\n# Объекты внешних ИС\nclass Operation:\n def __init__(self, operation_type):\n self.operationType = operation_type\n self.kbk = \"kbk_test\"\n self.payerInn = \"payerInn\"\n self.payerKpp = \"payerKpp\"\n self.payerName = \"payerName\"\n self.amount = 123\n self.recipient = \"test\",\n self.recipientInn = \"test\",\n self.recipientKpp = \"test\",\n self.payerAccount = \"test\",\n self.payerCorrAccount = \"test\",\n self.payerBank = \"test\",\n self.payerBic = \"test\",\n self.recipientAccount = \"test\",\n self.recipientCorrAccount = \"test\",\n self.recipientBank = \"test\",\n self.recipientBic = \"test\",\n self.id = \"123\",\n self.paymentType = \"test\",\n self.uin = \"test\",\n self.creatorStatus = \"test\",\n self.oktmo = \"test\",\n self.taxEvidence = \"test\",\n self.taxPeriod = \"test\",\n self.taxDocNumber = \"test\",\n self.taxDocDate = \"test\",\n self.taxType = \"test\",\n self.executionOrder = \"test\"\n\n @staticmethod\n def get_name_type_payment(self, operation):\n if operation.operationType == \"\":\n return \"in\"\n else:\n return \"out\"\n\n\n# Объекты платформы 1С\nclass Object1c():\n def __init__(self):\n self.value = {\n \"Ref\": \"00000000-0000-0000-0000-000000000000\",\n \"DeletionMark\": False\n }\n self.nameType = \"te\"\n self.typeObject1C = \"\"\n\n\nclass Document1c(Object1c):\n def __init__(self):\n Object1c.__init__(self)\n self.value.update({\n \"Date\": str(datetime.datetime.now()),\n \"Number\": \"\",\n \"Posted\": False\n })\n self.nameType = \"\"\n self.typeObject1C = \"jcfg:DocumentObject\"\n\n\n# Объекты метаданных 1С\nclass PaymentOrder(Document1c):\n def __init__(self, operation):\n Document1c.__init__(self)\n self.value.update({\n \"ВалютаДокумента\": get_link_object_1c(self, \"currency\",\n {\"КодВалюты\": 643}),\n \"ВидОперации\": operation.operationType,\n \"Контрагент\": get_link_object_1c(self, \"client\",\n {\"ИНН\": operation.payerInn,\n \"КПП\": operation.payerKpp,\n \"Наименование\": operation.payerName}),\n \"Организация\": get_link_object_1c(self, \"company\",\n {\"Наименование\": operation.recipient,\n \"ИНН\": operation.recipientInn,\n \"КПП\": operation.recipientKpp}),\n \"Ответственный\": \"\",\n \"ОтражатьВБухгалтерскомУчете\": True,\n \"ОтражатьВНалоговомУчете\": True,\n \"ОтраженоВОперУчете\": True,\n \"Подразделение\": \"\",\n \"Комментарий\": operation.id,\n \"СуммаДокумента\": operation.amount,\n \"СчетКонтрагента\": get_link_object_1c(self, \"clientAccount\",\n {\"НомерСчета\": operation.payerAccount,\n \"КорСчет\": operation.payerCorrAccount,\n \"БАНК\": operation.payerBank,\n \"БИК\": operation.payerBic}),\n \"СчетОрганизации\": get_link_object_1c(self, \"companyAccount\",\n {\"НомерСчета\": operation.recipientAccount,\n \"КорСчет\": operation.recipientCorrAccount,\n \"БАНК\": operation.recipientBank,\n \"БИК\": operation.recipientBic}),\n })\n\n @staticmethod\n def get_name_type_payment(self, document_1C):\n if document_1C.nameType == \"jcfg:DocumentObject.ПлатежноеПоручениеВходящее\":\n return \"in\"\n else:\n return \"out\"\n\n @staticmethod\n def set_value(self, document_1C, name_value, value):\n document_1C.value.update({name_value: value})\n\n\nclass PaymentOrderIn(PaymentOrder):\n def __init__(self, operation):\n PaymentOrder.__init__(self, operation)\n self.value.update({'ППВ': operation.kbk})\n self.nameType = \"ПлатежноеПоручениеВходящее\"\n\n\nclass PaymentOrderOut(PaymentOrder):\n def __init__(self, operation):\n PaymentOrder.__init__(self, operation)\n\n self.nameType = \"ПлатежноеПоручениеИсходящее\"\n parameters_request = {\"Номер\": operation.recipient,\n \"Дата\": operation.recipientInn}\n link_1c = get_link_object_1c(self, \"PayOut\", parameters_request)\n if link_1c == \"\":\n self.value.update({'КодКБК': operation.kbk})\n\n\n# Получение ссылок из 1С\ndef get_link_object_1c(self, object_1c, parameters_request):\n request_1c = \"\"\n\n if it_test:\n body_request = {\"request_1c\": request_1c, \"parameters_request\": parameters_request}\n return body_request\n\n if object_1c == \"client\":\n template = 'SELECT value FROM z_keyvalue WHERE key=:key'\n parameters = {'key': 'CLIENT_REQUEST'}\n request_1c = session.execute(template, parameters).fetchall()\n if object_1c == \"PayOut\":\n template = 'SELECT value FROM z_keyvalue WHERE key=:key'\n parameters = {'key': 'PAYOUT_REQUEST'}\n request_1c = session.execute(template, parameters).fetchall()\n else:\n request_1c = \"\"\n body_request = {\"request_1c\": request_1c, \"parameters_request\": parameters_request}\n\n conn = outgoing.plain_http['mak01.outconn'].conn\n dl_period = 1 # in days\n\n params = body_request\n response = conn.get(self.cid, params=params)\n if response.status_code != 200:\n return \"\"\n else:\n data_base = response.json()\n return data_base.link\n\n\n# Тесты\noperation_test = Operation(\"test_value\")\ntestWrapper = Wrapper1C(\"ПлатежноеПоручение\", operation_test)\nprint(testWrapper.value)\n" } ]
1
grantmduffy/WebLights
https://github.com/grantmduffy/WebLights
e896e0bf59b255a16cccc6726429a3e44b48b74c
51d5d8747cc6a8d827bb1dbfb40ab79ba4fb1c3b
ec7db8ed7316244546db76861f5c4f1295381232
refs/heads/master
2020-04-11T14:32:38.679521
2018-12-18T04:37:48
2018-12-18T04:37:48
161,859,026
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5513681173324585, "alphanum_fraction": 0.5740836262702942, "avg_line_length": 24.8266658782959, "blob_id": "04f80faac51d6e9d3a99605b3f99cc77f8ac56b1", "content_id": "5e4c6a057e4a9bdaeaec5849be54f780d6534db0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1937, "license_type": "no_license", "max_line_length": 78, "num_lines": 75, "path": "/main.py", "repo_name": "grantmduffy/WebLights", "src_encoding": "UTF-8", "text": "import esp\nesp.osdebug(None)\nimport uio\nimport json\nimport machine\nimport network\nimport socket\nimport time\nimport neopixel\n\n\ndef send_file(cl, filename):\n with open(filename, 'rb') as f:\n body = b'HTTP/1.1 200 OK\\r\\n\\r\\n' + f.read()\n n = cl.write(body)\n print('Sent {} of {} bytes'.format(n, len(body)))\n\nled1 = machine.Pin(2, machine.Pin.OUT)\nled2 = machine.Pin(16, machine.Pin.OUT)\npx = neopixel.NeoPixel(machine.Pin(15), 50)\n\n# Connect to WiFi\nsta_if = network.WLAN(network.STA_IF)\nsta_if.active(True)\nwith open('network.txt', 'r') as f:\n essid, password = [x.strip() for x in f.readlines()]\n sta_if.connect(essid, password)\nprint('Connecting', end='')\nwhile not sta_if.isconnected():\n print('.', end='')\n led1.off()\n led2.on()\n time.sleep(0.1)\n led1.on()\n led2.off()\n time.sleep(0.1)\nprint('Connected')\nprint(sta_if.ifconfig()[0])\nled1.off()\nled2.off()\ntime.sleep(0.5)\nled1.on()\nled2.on()\n\n# Start Server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('', 80))\ns.listen(5)\nwhile True:\n cl, addr = s.accept()\n request = uio.BytesIO(cl.recv(1024))\n first_line = request.readline()\n if first_line == b'':\n cl.close()\n continue\n requst_type, path, version = first_line.decode('utf-8').split()\n print('{} requesting {}'.format(requst_type, path))\n x = b' '\n while x != b'' and x != b'\\r\\n':\n x = request.readline()\n print(x)\n if requst_type == 'GET':\n if path == '/':\n send_file(cl, 'home.html')\n if path == '/scripts.js':\n send_file(cl, 'scripts.js')\n if requst_type == 'POST':\n if path == '/state.json':\n values = json.load(request)\n print(values)\n for i in range(50):\n px[i] = (int(values['g']), int(values['r']), int(values['b']))\n px.write()\n cl.write(b'HTTP/1.1 200 OK\\r\\n\\r\\n')\n cl.close()\n" } ]
1
Ch0ronomato/uci
https://github.com/Ch0ronomato/uci
6939003253a43d5edf92fc43d4f51c80d9ce064c
2c82960e6ab41c5bc66323dfbfa133c647bd9608
60f8daaa84f6ba0983521cc3e235a90246b0f38f
refs/heads/master
2021-06-11T15:05:08.444510
2017-01-25T17:52:10
2017-01-25T17:52:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5104895234107971, "alphanum_fraction": 0.5314685106277466, "avg_line_length": 16.875, "blob_id": "15d176df284a154de3c0b5e6f5b4ea90841aa9a3", "content_id": "1e9d54ffe0ed972023c88036c9586b3a418b2d9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/cs146/midterm_study/whence.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main() {\n\tFILE *f = fopen(\"doc.txt\", \"r\");\n\tint pos = fseek(f, -9, 2);\n\tprintf(\"%d\\t%c\\n\", pos, getc(f));\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6278659701347351, "alphanum_fraction": 0.7019400596618652, "avg_line_length": 20.80769157409668, "blob_id": "da1b3236cfc67493417d075aba3a7e889e4078a5", "content_id": "541b5c5b80f390298d2397178ea8b3c62c1164c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 567, "license_type": "no_license", "max_line_length": 46, "num_lines": 26, "path": "/cs131/project3/runSkelly.sh", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#$ -cwd\n#$ -j y\n#$ -S /bin/bash\n#$ -M [email protected]\n#$ -o ./OutSkelly.out\n#\n# Use modules to setup the runtime environment\nmodule load sge \nmodule load gcc/4.8.2\n#\n# Execute the run\n#\n./lab3 jjbesavi_timing_1.txt 2\n./lab3 jjbesavi_timing_1.txt 4\n./lab3 jjbesavi_timing_1.txt 8\n./lab3 jjbesavi_timing_1.txt 16\n./lab3 jjbesavi_timing_2.txt 2\n./lab3 jjbesavi_timing_2.txt 4\n./lab3 jjbesavi_timing_2.txt 8\n./lab3 jjbesavi_timing_2.txt 16\n./lab3 jjbesavi_timing_3.txt 2\n./lab3 jjbesavi_timing_3.txt 4\n./lab3 jjbesavi_timing_3.txt 8\n./lab3 jjbesavi_timing_3.txt 16\n" }, { "alpha_fraction": 0.6421725153923035, "alphanum_fraction": 0.6429712176322937, "avg_line_length": 26.217391967773438, "blob_id": "0130fb491f2def8a39537d9ab060284b0c709f8c", "content_id": "f36304b7acdf54172b52d357130a44449910a376", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15024, "license_type": "no_license", "max_line_length": 111, "num_lines": 552, "path": "/ics46/program3/src/bst_map.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef BST_MAP_HPP_\n#define BST_MAP_HPP_\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <initializer_list>\n#include \"ics_exceptions.hpp\"\n#include \"iterator.hpp\"\n#include \"pair.hpp\"\n#include \"map.hpp\"\n#include \"array_queue.hpp\" //For traversal\n\n\nnamespace ics {\n\ntemplate<class KEY,class T> class BSTMap : public Map<KEY,T>\t{\n public:\n \ttypedef ics::pair<KEY,T> Entry;\n\tBSTMap();\n\tBSTMap(const BSTMap<KEY,T>& to_copy);\n\tBSTMap(std::initializer_list<Entry> il);\n \tBSTMap(ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop);\n\tvirtual ~BSTMap();\n\n\tvirtual bool empty () const;\n\tvirtual int size () const;\n\tvirtual bool has_key (const KEY& key) const;\n\tvirtual bool has_value (const T& value) const;\n\tvirtual std::string str () const;\n\n\tvirtual T put (const KEY& key, const T& value);\n\tvirtual T erase (const KEY& key);\n\tvirtual void clear ();\n\n\tvirtual int put (ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop);\n\n\tvirtual T& operator [] (const KEY&);\n\tvirtual const T& operator [] (const KEY&) const;\n\tvirtual BSTMap<KEY,T>& operator = (const BSTMap<KEY,T>& rhs);\n\tvirtual bool operator == (const Map<KEY,T>& rhs) const;\n\tvirtual bool operator != (const Map<KEY,T>& rhs) const;\n\n\ttemplate<class KEY2,class T2>\n\tfriend std::ostream& operator << (std::ostream& outs, const BSTMap<KEY2,T2>& m);\n\n\tvirtual ics::Iterator<Entry>& ibegin () const;\n\tvirtual ics::Iterator<Entry>& iend () const;\n\n private:\n class TN;\n\n public:\n class Iterator : public ics::Iterator<Entry> {\n public:\n //KLUDGE should be callable only in begin/end\n Iterator(BSTMap<KEY,T>* iterate_over, bool begin);\n Iterator(const Iterator& i);\n virtual ~Iterator();\n virtual Entry erase();\n virtual std::string str () const;\n virtual const ics::Iterator<Entry>& operator ++ ();\n virtual const ics::Iterator<Entry>& operator ++ (int);\n virtual bool operator == (const ics::Iterator<Entry>& rhs) const;\n virtual bool operator != (const ics::Iterator<Entry>& rhs) const;\n virtual Entry& operator * () const;\n virtual Entry* operator -> () const;\n private:\n ics::ArrayQueue<Entry> it; //Iterator (as a Queue) for Map\n BSTMap<KEY,T>* ref_map;\n int expected_mod_count;\n bool can_erase = true;\n };\n\n virtual Iterator begin () const;\n virtual Iterator end () const;\n //KLUDGE: define\n //virtual ics::Iterator<KEY>& begin_key () const;\n //virtual ics::Iterator<KEY>& end_key () const;\n //virtual ics::Iterator<T>& begin_value () const;\n //virtual ics::Iterator<T>& end_value () const;\n\n private:\n\tclass TN {\n\tpublic:\n\t\tTN () : left(nullptr), right(nullptr){}\n\t\tTN (const TN& tn) : value(tn.value), left(tn.left), right(tn.right){}\n\t\tTN (Entry v, TN* l = nullptr,\n\t\t TN* r = nullptr) : value(v), left(l), right(r){}\n\n\t\tEntry value;\n\t\tTN* left;\n\t\tTN* right;\n\t};\n\n\tTN* map = nullptr;\n\tint used = 0; //Amount of array used\n\tint mod_count = 0; //For sensing concurrent modification\n\tTN* \t\t\t find_key (TN* root, const KEY& key) const;\n\tbool \t\t\t find_value (TN* root, const T& value) const;\n\tT& \t\t\t insert (TN*& root, const KEY& key, const T& value);\n\tics::pair<KEY,T> remove_closest(TN*& root);\n\tT \t\t\t remove (TN*& root, const KEY& key);\n\tTN* \t\t\t copy (TN* root) const;\n\tvoid \t\t\t copy_to_queue (TN* root, ArrayQueue<Entry>& q) const;\n\tvoid \t\t\t delete_BST (TN*& root);\n\tbool \t\t\t equals (TN* root, const Map<KEY,T>& other) const;\n\tstd::string \t string_rotated(TN* root, std::string indent) const;\n};\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::BSTMap() {}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::BSTMap(const BSTMap<KEY,T>& to_copy) : used(to_copy.used) {\n\tmap = copy(to_copy.map);\t\n}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::BSTMap(ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop) {\n\tput(start,stop);\n}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::BSTMap(std::initializer_list<Entry> il) {\n \tfor (Entry entry : il)\n \t\tput(entry.first, entry.second);\n}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::~BSTMap() {\n\t// delete_BST(map);\n}\n\n\ntemplate<class KEY,class T>\ninline bool BSTMap<KEY,T>::empty() const {\n\treturn used == 0;\n}\n\n\ntemplate<class KEY,class T>\nint BSTMap<KEY,T>::size() const {\n\treturn used;\n}\n\n\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::has_key (const KEY& element) const {\n return find_key(map, element) != nullptr;\n}\n\n\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::has_value (const T& element) const {\n ics::ArrayQueue<Entry> queue;\n copy_to_queue(map, queue);\n for (Entry entry : queue) {\n if (entry.second == element)\n return true;\n }\n return false;\n}\n\n\ntemplate<class KEY,class T>\nstd::string BSTMap<KEY,T>::str() const {\n\treturn string_rotated(map, \"\");\n}\n\n\ntemplate<class KEY,class T>\nT BSTMap<KEY,T>::put(const KEY& key, const T& value) {\n used += has_key(key)? 0 : 1;\n mod_count++;\n return insert(map, key, value);\n}\n\ntemplate<class KEY,class T>\nT BSTMap<KEY,T>::erase(const KEY& key) {\n\t// erase will already throw an error\n\t// so we'll let remove do that.\n\tif (find_key(map, key) != nullptr) {\n\t\tmod_count--;\n\t\tused--;\n\t\treturn remove(map, key);\n\t} else\n\t\tthrow KeyError(\"BSTMap::remove no node\");\n}\n\n\ntemplate<class KEY,class T>\nvoid BSTMap<KEY,T>::clear() {\n\tdelete_BST(map);\n}\n\n\ntemplate<class KEY,class T>\nint BSTMap<KEY,T>::put (ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop) {\n\tint count;\n\tfor (count = 0;start != stop;count++,start++) \n\t\tput((*start).first, (*start).second);\n\treturn count;\n}\n\n// we really don't want to return nullptr here.\ntemplate<class KEY,class T>\nT& BSTMap<KEY,T>::operator [] (const KEY& key) { // for calls like map[key] = some value\n //write code here\n if (find_key(map, key) == nullptr) \n put(key, T());\n return find_key(map, key)->value.second;\n}\n\n\ntemplate<class KEY,class T>\nconst T& BSTMap<KEY,T>::operator [] (const KEY& key) const { // for calls like some value = map[key]\n //write code here\n return find_key(map, key)->value.second;\n}\n\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::operator == (const Map<KEY,T>& rhs) const {\n\treturn equals(map, rhs);\n}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>& BSTMap<KEY,T>::operator = (const BSTMap<KEY,T>& rhs) {\n\tif (!empty()) clear();\n\tput(rhs.ibegin(), rhs.iend());\n\treturn (*this);\n}\n\n\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::operator != (const Map<KEY,T>& rhs) const {\n\treturn !((*this) == rhs);\n}\n\n\ntemplate<class KEY,class T>\nstd::ostream& operator << (std::ostream& outs, const BSTMap<KEY,T>& m) {\n\touts << \"map[\";\n\tif (!m.empty()) \n\t\touts << m.str();\n\touts << \"]\";\n\treturn outs;\n}\n\n\n//KLUDGE: memory-leak\ntemplate<class KEY,class T>\nauto BSTMap<KEY,T>::ibegin () const -> ics::Iterator<Entry>& {\n return *(new Iterator(const_cast<BSTMap<KEY,T>*>(this),true));\n}\n\n\n//KLUDGE: memory-leak\ntemplate<class KEY,class T>\nauto BSTMap<KEY,T>::iend () const -> ics::Iterator<Entry>& {\n return *(new Iterator(const_cast<BSTMap<KEY,T>*>(this),false));\n}\n\n\ntemplate<class KEY,class T>\nauto BSTMap<KEY,T>::begin () const -> BSTMap<KEY,T>::Iterator {\n return Iterator(const_cast<BSTMap<KEY,T>*>(this),true);\n}\n\n\ntemplate<class KEY,class T>\nauto BSTMap<KEY,T>::end () const -> BSTMap<KEY,T>::Iterator {\n return Iterator(const_cast<BSTMap<KEY,T>*>(this),false);\n}\n\n\ntemplate<class KEY,class T>\ntypename BSTMap<KEY,T>::TN* BSTMap<KEY,T>::find_key (TN* root, const KEY& key) const {\n //write code here\n for (;root != nullptr && root->value.first != key; \n root = (root->value.first > key ? root->left : root->right)); \n return root;\n}\n\n\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::find_value (TN* root, const T& value) const {\n\tArrayQueue<Entry> q;\n\tcopy_to_queue(root, q);\n\twhile (!q.empty() && q.dequeue().second != value)\n\t\t; \n\treturn !q.empty();\n}\n\n\ntemplate<class KEY,class T>\nT& BSTMap<KEY,T>::insert (TN*& root, const KEY& key, const T& value) {\n if (root == nullptr) {\n root = new TN(Entry(key, value)); \n return root->value.second;\n }\n if (root->value.first == key) {\n T temp = root->value.second;\n root->value.second = value;\n return temp;\n }\n if (key < root->value.first)\n return insert(root->left, key, value); \n return insert(root->right, key, value);\n}\n\n\ntemplate<class KEY,class T>\nics::pair<KEY,T> BSTMap<KEY,T>::remove_closest(TN*& root) {\n if (root->right == nullptr) {\n ics::pair<KEY,T> to_return = root->value;\n TN* to_delete = root;\n root = root->left;\n delete to_delete;\n return to_return;\n }else\n return remove_closest(root->right);\n}\n\n\ntemplate<class KEY,class T>\nT BSTMap<KEY,T>::remove (TN*& root, const KEY& key) {\n if (root == nullptr) {\n std::ostringstream answer;\n answer << \"BSTMap::erase: key(\" << key << \") not in Map\";\n throw KeyError(answer.str());\n }else\n if (key == root->value.first) {\n T to_return = root->value.second;\n if (root->left == nullptr) {\n TN* to_delete = root;\n root = root->right;\n delete to_delete;\n }else if (root->right == nullptr) {\n TN* to_delete = root;\n root = root->left;\n delete to_delete;\n }else\n root->value = remove_closest(root->left);\n return to_return;\n }else\n return remove( (key < root->value.first ? root->left : root->right), key);\n}\n\n\ntemplate<class KEY,class T>\ntypename BSTMap<KEY,T>::TN* BSTMap<KEY,T>::copy (TN* root) const {\n\t//write code here\n\tif (root == nullptr) \n\t\treturn nullptr;\n\telse {\n\t\tTN *to_return(root);\n\t\tto_return->left = copy(root->left);\n\t\tto_return->right = copy(root->right);\n\t\treturn to_return;\n\t}\n}\n\n\ntemplate<class KEY,class T>\nvoid BSTMap<KEY,T>::copy_to_queue (TN* root, ArrayQueue<Entry>& q) const {\n if (root == nullptr) return;\n q.enqueue(root->value);\n copy_to_queue(root->left, q);\n copy_to_queue(root->right, q);\n}\n\n\ntemplate<class KEY,class T>\nvoid BSTMap<KEY,T>::delete_BST (TN*& root) {\n\twhile (!empty()) {\n\t\terase(map->value.first);\n\t}\n}\n\n/**\n * \n * Equality of two maps (NOT BST's) depends on existence of keys\n * and values. Two maps are equal if they contain the same keys and \n * values. This is structure agnostic. \n */\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::equals (TN* root, const Map<KEY,T>& other) const {\n\tif (size() != other.size())\n\t\treturn false;\n\tfor (auto &iter = other.ibegin(); iter != other.iend(); iter++) {\n\t\tTN *node = find_key(map, iter->first);\n\t\tif (node == nullptr || node->value.second != iter->second) \n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\n\ntemplate<class KEY,class T>\nstd::string BSTMap<KEY,T>::string_rotated(TN* root, std::string indent) const {\n\tif (root == nullptr)\n return \"\";\n else {\n \tstd::stringstream outs;\n outs << string_rotated(root->right, indent+\"..\");\n outs << indent << root->value.first << \"->\" << root->value.second;\n outs << string_rotated(root->left, indent+\"..\");\n return outs.str();\n }\n}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::Iterator::Iterator(BSTMap<KEY,T>* iterate_over, bool begin) : it(), ref_map(iterate_over)\n\t, expected_mod_count(iterate_over->mod_count) {\n\tif (begin) \n\t\titerate_over->copy_to_queue(iterate_over->map, it);\n}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::Iterator::Iterator(const Iterator& i) :\n it(i.it), ref_map(i.ref_map), expected_mod_count(i.expected_mod_count), can_erase(i.can_erase)\n{}\n\n\ntemplate<class KEY,class T>\nBSTMap<KEY,T>::Iterator::~Iterator() {\n\t// delete ref_map;\n}\n\n\ntemplate<class KEY,class T>\nauto BSTMap<KEY,T>::Iterator::erase() -> Entry {\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"BSTMap::Iterator::erase\");\n if (!can_erase)\n throw CannotEraseError(\"BSTMap::Iterator::erase Iterator cursor already erased\");\n if (it.empty())\n throw CannotEraseError(\"BSTMap::Iterator::erase Iterator cursor beyond data structure\");\n\n\t// delete the next node.\n\tcan_erase = false;\n\tEntry to_delete = it.dequeue();\n\tref_map->erase(to_delete.first);\n\texpected_mod_count = ref_map->mod_count;\n\treturn to_delete;\n}\n\n\ntemplate<class KEY,class T>\nstd::string BSTMap<KEY,T>::Iterator::str() const {\n std::ostringstream answer;\n answer << ref_map->str() << \"(expected_mod_count=\" << expected_mod_count << \",can_erase=\" << can_erase << \")\";\n return answer.str();\n}\n\n\n//KLUDGE: cannot use Entry\ntemplate<class KEY,class T>\nauto BSTMap<KEY,T>::Iterator::operator ++ () -> const ics::Iterator<ics::pair<KEY,T>>& {\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"BSTMap::Iterator::operator ++\");\n\n if (!can_erase) can_erase = true;\n else {\n if (!it.empty())\n it.dequeue();\n }\n\n return *this;\n}\n\n\n//KLUDGE: creates garbage! (can return local value!)\ntemplate<class KEY,class T>\nauto BSTMap<KEY,T>::Iterator::operator ++ (int) -> const ics::Iterator<ics::pair<KEY,T>>&{\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"BSTMap::Iterator::operator ++(int)\");\n\n\tIterator *copy = new Iterator(*this);\n if (!can_erase) can_erase = true;\n else {\n if (!it.empty())\n it.dequeue();\n }\n return *copy; \n}\n\n\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::Iterator::operator == (const ics::Iterator<Entry>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n throw IteratorTypeError(\"BSTMap::Iterator::operator ==\");\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"BSTMap::Iterator::operator ==\");\n if (ref_map != rhsASI->ref_map)\n throw ComparingDifferentIteratorsError(\"BSTMap::Iterator::operator ==\");\n\treturn it == rhsASI->it;\n}\n\n\ntemplate<class KEY,class T>\nbool BSTMap<KEY,T>::Iterator::operator != (const ics::Iterator<Entry>& rhs) const {\n\tconst Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n\tif (rhsASI == 0)\n\t\tthrow IteratorTypeError(\"BSTMap::Iterator::operator !=\");\n\tif (expected_mod_count != ref_map->mod_count)\n\t\tthrow ConcurrentModificationError(\"BSTMap::Iterator::operator !=\");\n\tif (ref_map != rhsASI->ref_map)\n\t\tthrow ComparingDifferentIteratorsError(\"BSTMap::Iterator::operator !=\");\n\n\treturn it != rhsASI->it;\n}\n\n\ntemplate<class KEY,class T>\nics::pair<KEY,T>& BSTMap<KEY,T>::Iterator::operator *() const {\n if (expected_mod_count !=\n ref_map->mod_count)\n throw ConcurrentModificationError(\"BSTMap::Iterator::operator *\");\n if (!can_erase || it.empty())\n throw IteratorPositionIllegal(\"BSTMap::Iterator::operator * Iterator illegal: exhausted\");\n\n\treturn it.peek();\n}\n\n\ntemplate<class KEY,class T>\nics::pair<KEY,T>* BSTMap<KEY,T>::Iterator::operator ->() const {\n if (expected_mod_count !=\n ref_map->mod_count)\n throw ConcurrentModificationError(\"BSTMap::Iterator::operator *\");\n if (!can_erase || it.empty())\n throw IteratorPositionIllegal(\"BSTMap::Iterator::operator -> Iterator illegal: exhausted\");\n\n \t//write code here\n\treturn &it.peek();\n}\n\n\n}\n\n#endif /* BST_MAP_HPP_ */\n" }, { "alpha_fraction": 0.6255707740783691, "alphanum_fraction": 0.6347032189369202, "avg_line_length": 17.25, "blob_id": "6a4dd76b6c492875fee7e927d630b667e3e5c4ee", "content_id": "96c8cf9b9b5c418e0cfcf03bd8b52ff0e169f4f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 219, "license_type": "no_license", "max_line_length": 69, "num_lines": 12, "path": "/cs146/hw2/valid", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# uses a regular expression to determine validity of a variable name.\n# invoked via ./valid\nfor arg in \"$@\"\ndo\n\tif echo $arg | grep -q '^[a-zA-Z][a-zA-Z0-9]*'; then\n\t\techo \"yes\"\n\telse\n\t\techo \"no\"\n\tfi\t\ndone\n" }, { "alpha_fraction": 0.6364942789077759, "alphanum_fraction": 0.6508620977401733, "avg_line_length": 19.47058868408203, "blob_id": "61f8fb23b0baf70dc387645f3ab933e5a8fc87fd", "content_id": "f6fa7af28eb003b5e780087ba68da98badc9c693", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 696, "license_type": "no_license", "max_line_length": 108, "num_lines": 34, "path": "/cs146/hw3/srm", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Ian Schweer\n# 22514022\n\nif [ $# -lt 1 ]; then\n\techo \"Not enough args. Please enter a filename\"\n\texit -1\nfi\n\ntrash=$TRASH\nif [[ \"$trash\" == \"\" ]]; then\n\techo \"The trash variable is not currently set. Consider setting an enviornment variable. Assuming ~/.Trash\"\n\ttrash=\"$HOME/.Trash\"\nfi\n\nif [ ! -e $trash ]; then\n\tmkdir $trash\nfi\n\nfor file in \"$@\"\ndo\n\t# very carefully get the file name only, will maintaing spaces\n\tthefilename=$(basename \"$file\")\n\ttrashpath=\"$trash/$thefilename\"\n\techo $trashpath\n\tif [ -f \"$file\" ]; then\n\t\t# the file exists and can be safe rm'd\n\t\tmv \"$file\" \"$trashpath\"\n\telif [ -d \"$file\" ]; then\n\t\tmv \"$file\" \"$trashpath\"\n\telse\n\t\techo \"$file cannot be srm'd\"\n\tfi\ndone\n" }, { "alpha_fraction": 0.7121211886405945, "alphanum_fraction": 0.7146464586257935, "avg_line_length": 30.68000030517578, "blob_id": "78186e7ec416a0f983e774a6cf3df0c8821b4071", "content_id": "abbb44504f40fd7b3e429e98207176d187abe1d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 792, "license_type": "no_license", "max_line_length": 114, "num_lines": 25, "path": "/cs141/project1/src/grammer.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef GRAMMAR_H\n#define GRAMMAR_H\n#include <string>\n/**\n * Grammar \n * Simple parser abstract class. Each class that inherits this\n * will be able to parse some kind of SIMPLESEM command.\n * \n * Each grammar will hold reference to a reader class. The\n * reader will split some command by spaces, and figure out\n * what to create.\n */\n\nclass Grammar\n{\npublic:\n\tvirtual Grammar* parse() = 0;\nprotected:\n\tstd::string parseCommand(std::string _msLine, std::string keywordLow, std::string keywordUpper) {\n\t\tif (_msLine.find(keywordUpper) == std::string::npos && _msLine.find(keywordLow) == std::string::npos) return \"\";\n\t\tint tokenLoc = _msLine.find(keywordUpper) ? _msLine.find(keywordUpper) : _msLine.find(keywordLow);\n\t\treturn _msLine.substr(tokenLoc + keywordLow.length() + 1);\n\t}\n};\n#endif\n" }, { "alpha_fraction": 0.6542476415634155, "alphanum_fraction": 0.6556929349899292, "avg_line_length": 30.057355880737305, "blob_id": "57e28606bea1af90917d477efcdfb82606e2bfef", "content_id": "f49676444aa356334714e72b34b381657cd8633e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12454, "license_type": "no_license", "max_line_length": 184, "num_lines": 401, "path": "/ics46/ProgramFour/src/hash_map.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef HASH_MAP_HPP_\n#define HASH_MAP_HPP_\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <initializer_list>\n#include \"ics_exceptions.hpp\"\n#include \"iterator.hpp\"\n#include \"pair.hpp\"\n#include \"map.hpp\"\n#include \"array_queue.hpp\" //For traversal\n\n\nnamespace ics {\n\ntemplate<class KEY,class T> class HashMap : public Map<KEY,T> {\n public:\n typedef ics::pair<KEY,T> Entry;\n HashMap() = delete;\n HashMap(int (*ahash)(const KEY& k), double the_load_factor = 1.0);\n HashMap(int initial_bins, int (*ahash)(const KEY& k), double the_load_factor = 1.0);\n HashMap(const HashMap<KEY,T>& to_copy);\n HashMap(std::initializer_list<Entry> il, int (*ahash)(const KEY& k), double the_load_factor = 1.0);\n HashMap(ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop, int (*ahash)(const KEY& k), double the_load_factor = 1.0);\n virtual ~HashMap();\n\n virtual bool empty () const;\n virtual int size () const;\n virtual bool has_key (const KEY& key) const;\n virtual bool has_value (const T& value) const;\n virtual std::string str () const;\n\n virtual T put (const KEY& key, const T& value);\n virtual T erase (const KEY& key);\n virtual void clear ();\n\n virtual int put (ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop);\n\n virtual T& operator [] (const KEY&);\n virtual const T& operator [] (const KEY&) const;\n virtual HashMap<KEY,T>& operator = (const HashMap<KEY,T>& rhs);\n virtual bool operator == (const Map<KEY,T>& rhs) const;\n virtual bool operator != (const Map<KEY,T>& rhs) const;\n\n template<class KEY2,class T2>\n friend std::ostream& operator << (std::ostream& outs, const HashMap<KEY2,T2>& m);\n\n virtual ics::Iterator<Entry>& ibegin () const;\n virtual ics::Iterator<Entry>& iend () const;\n\n private:\n class LN;\n\n public:\n class Iterator : public ics::Iterator<Entry> {\n public:\n //KLUDGE should be callable only in begin/end\n Iterator(HashMap<KEY,T>* iterate_over, bool begin);\n Iterator(const Iterator& i);\n virtual ~Iterator();\n virtual Entry erase();\n virtual std::string str () const;\n virtual const ics::Iterator<Entry>& operator ++ ();\n virtual const ics::Iterator<Entry>& operator ++ (int);\n virtual bool operator == (const ics::Iterator<Entry>& rhs) const;\n virtual bool operator != (const ics::Iterator<Entry>& rhs) const;\n virtual Entry& operator * () const;\n virtual Entry* operator -> () const;\n private:\n ics::pair<int,LN*> current; //Bin Index/Cursor; stop: LN* == nullptr\n HashMap<KEY,T>* ref_map;\n int expected_mod_count;\n bool can_erase = true;\n void advance_cursors();\n };\n\n virtual Iterator begin () const;\n virtual Iterator end () const;\n //KLUDGE: define\n //virtual ics::Iterator<KEY>& begin_key () const;\n //virtual ics::Iterator<KEY>& end_key () const;\n //virtual ics::Iterator<T>& begin_value () const;\n //virtual ics::Iterator<T>& end_value () const;\n\n private:\n class LN {\n public:\n LN () : next(nullptr){}\n LN (const LN& ln) : value(ln.value), next(ln.next){}\n LN (Entry v, LN* n = nullptr) : value(v), next(n){}\n\n Entry value;\n LN* next;\n };\n\n LN** map = nullptr;\n int (*hash)(const KEY& k);\n double load_factor;//used/bins <= load_factor\n int bins = 1; //# bins available in the array\n int used = 0; //# of key->value pairs in the hash table\n int mod_count = 0; //For sensing concurrent modification\n int hash_compress (const KEY& key) const;\n void ensure_load_factor(int new_used);\n LN* find_key (int bin, const KEY& key) const;\n bool find_value (const T& value) const;\n LN* copy_list(LN* l) const;\n LN** copy_hash_table(LN** ht, int bins) const;\n void delete_hash_table(LN**& ht, int bins);\n };\n\n\n\n\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::HashMap(int (*ahash)(const KEY& k), double the_load_factor) : hash(ahash), load_factor(the_load_factor) {\n //write code here\n hash = ahash;\n std::hash<std::string> hasher;\n std::cout << hasher(\"a\") << std::endl;\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::HashMap(int initial_bins, int (*ahash)(const KEY& k), double the_load_factor) : bins(initial_bins), hash(ahash), load_factor(the_load_factor) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::HashMap(const HashMap<KEY,T>& to_copy) : hash(to_copy.hash), load_factor(to_copy.load_factor), bins(to_copy.bins), used(to_copy.used) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::HashMap(ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop, int (*ahash)(const KEY& k), double the_load_factor) : hash(ahash), load_factor(the_load_factor) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::HashMap(std::initializer_list<Entry> il,int (*ahash)(const KEY& k), double the_load_factor) : hash(ahash), load_factor(the_load_factor) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::~HashMap() {\n //write code here\n}\n\n\ntemplate<class KEY,class T>\ninline bool HashMap<KEY,T>::empty() const {\n //write code here\n return used == 0;\n}\n\ntemplate<class KEY,class T>\nint HashMap<KEY,T>::size() const {\n //write code here\n return used;\n}\n\ntemplate<class KEY,class T>\nbool HashMap<KEY,T>::has_key (const KEY& key) const {\n //write code here\n int khash = hash(key);\n std::cout << khash << std::endl;\n bool found = false;\n for (LN *bucket = map[khash]; bucket != nullptr; bucket = bucket->next) {\n std::cout << \"Hey\" << std::endl;\n if (bucket->value.first == key) { found = true; break; }\n }\n\n return found;\n}\n\ntemplate<class KEY,class T>\nbool HashMap<KEY,T>::has_value (const T& value) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\nstd::string HashMap<KEY,T>::str() const {\n //write code here\n}\n\ntemplate<class KEY,class T>\nT HashMap<KEY,T>::put(const KEY& key, const T& value) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nT HashMap<KEY,T>::erase(const KEY& key) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nvoid HashMap<KEY,T>::clear() {\n //write code here\n}\n\ntemplate<class KEY,class T>\nint HashMap<KEY,T>::put (ics::Iterator<Entry>& start, const ics::Iterator<Entry>& stop) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nT& HashMap<KEY,T>::operator [] (const KEY& key) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nconst T& HashMap<KEY,T>::operator [] (const KEY& key) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\nbool HashMap<KEY,T>::operator == (const Map<KEY,T>& rhs) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>& HashMap<KEY,T>::operator = (const HashMap<KEY,T>& rhs) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nbool HashMap<KEY,T>::operator != (const Map<KEY,T>& rhs) const {\n //write code here\n}\n\n\ntemplate<class KEY,class T>\nstd::ostream& operator << (std::ostream& outs, const HashMap<KEY,T>& m) {\n //write code here\n}\n\n//KLUDGE: memory-leak\ntemplate<class KEY,class T>\nauto HashMap<KEY,T>::ibegin () const -> ics::Iterator<Entry>& {\n return *(new Iterator(const_cast<HashMap<KEY,T>*>(this),true));\n}\n\n//KLUDGE: memory-leak\ntemplate<class KEY,class T>\nauto HashMap<KEY,T>::iend () const -> ics::Iterator<Entry>& {\n return *(new Iterator(const_cast<HashMap<KEY,T>*>(this),false));\n}\n\ntemplate<class KEY,class T>\nauto HashMap<KEY,T>::begin () const -> HashMap<KEY,T>::Iterator {\n return Iterator(const_cast<HashMap<KEY,T>*>(this),true);\n}\n\ntemplate<class KEY,class T>\nauto HashMap<KEY,T>::end () const -> HashMap<KEY,T>::Iterator {\n return Iterator(const_cast<HashMap<KEY,T>*>(this),false);\n}\n\ntemplate<class KEY,class T>\nint HashMap<KEY,T>::hash_compress (const KEY& key) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\nvoid HashMap<KEY,T>::ensure_load_factor(int new_used) {\n //write code here\n}\n\ntemplate<class KEY,class T>\ntypename HashMap<KEY,T>::LN* HashMap<KEY,T>::find_key (int bin, const KEY& key) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\nbool HashMap<KEY,T>::find_value (const T& value) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\ntypename HashMap<KEY,T>::LN* HashMap<KEY,T>::copy_list (LN* l) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\ntypename HashMap<KEY,T>::LN** HashMap<KEY,T>::copy_hash_table (LN** ht, int bins) const {\n //write code here\n}\n\ntemplate<class KEY,class T>\nvoid HashMap<KEY,T>::delete_hash_table (LN**& ht, int bins) {\n //write code here\n}\n\n\ntemplate<class KEY,class T>\nvoid HashMap<KEY,T>::Iterator::advance_cursors(){\n //write code here\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::Iterator::Iterator(HashMap<KEY,T>* iterate_over, bool begin) : ref_map(iterate_over) {\n //write code here\n}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::Iterator::Iterator(const Iterator& i) :\n current(i.current), ref_map(i.ref_map), expected_mod_count(i.expected_mod_count), can_erase(i.can_erase) {}\n\ntemplate<class KEY,class T>\nHashMap<KEY,T>::Iterator::~Iterator()\n{}\n\ntemplate<class KEY,class T>\nauto HashMap<KEY,T>::Iterator::erase() -> Entry {\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"HashMap::Iterator::erase\");\n if (!can_erase)\n throw CannotEraseError(\"HashMap::Iterator::erase Iterator cursor already erased\");\n if (current.second == nullptr)\n throw CannotEraseError(\"HashMap::Iterator::erase Iterator cursor beyond data structure\");\n\n //write code here\n}\n\ntemplate<class KEY,class T>\nstd::string HashMap<KEY,T>::Iterator::str() const {\n std::ostringstream answer;\n answer << ref_map->str() << \"(current=\" << current.first << \"/\" << current.second << \",expected_mod_count=\" << expected_mod_count << \",can_erase=\" << can_erase << \")\";\n return answer.str();\n}\n\n//KLUDGE: cannot use Entry\ntemplate<class KEY,class T>\nauto HashMap<KEY,T>::Iterator::operator ++ () -> const ics::Iterator<ics::pair<KEY,T>>& {\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"HashMap::Iterator::operator ++\");\n\n //write code here\n}\n\n//KLUDGE: creates garbage! (can return local value!)\ntemplate<class KEY,class T>\nauto HashMap<KEY,T>::Iterator::operator ++ (int) -> const ics::Iterator<ics::pair<KEY,T>>&{\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"HashMap::Iterator::operator ++(int)\");\n\n //write code here\n}\n\ntemplate<class KEY,class T>\nbool HashMap<KEY,T>::Iterator::operator == (const ics::Iterator<Entry>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n throw IteratorTypeError(\"HashMap::Iterator::operator ==\");\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"HashMap::Iterator::operator ==\");\n if (ref_map != rhsASI->ref_map)\n throw ComparingDifferentIteratorsError(\"HashMap::Iterator::operator ==\");\n\n //write code here\n}\n\n\ntemplate<class KEY,class T>\nbool HashMap<KEY,T>::Iterator::operator != (const ics::Iterator<Entry>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n throw IteratorTypeError(\"HashMap::Iterator::operator !=\");\n if (expected_mod_count != ref_map->mod_count)\n throw ConcurrentModificationError(\"HashMap::Iterator::operator !=\");\n if (ref_map != rhsASI->ref_map)\n throw ComparingDifferentIteratorsError(\"HashMap::Iterator::operator !=\");\n\n //write code here\n}\n\ntemplate<class KEY,class T>\nics::pair<KEY,T>& HashMap<KEY,T>::Iterator::operator *() const {\n if (expected_mod_count !=\n ref_map->mod_count)\n throw ConcurrentModificationError(\"HashMap::Iterator::operator *\");\n if (!can_erase || current.second == nullptr)\n throw IteratorPositionIllegal(\"HashMap::Iterator::operator * Iterator illegal: exhausted\");\n\n //write code here\n}\n\ntemplate<class KEY,class T>\nics::pair<KEY,T>* HashMap<KEY,T>::Iterator::operator ->() const {\n if (expected_mod_count !=\n ref_map->mod_count)\n throw ConcurrentModificationError(\"HashMap::Iterator::operator *\");\n if (!can_erase || current.second == nullptr)\n throw IteratorPositionIllegal(\"HashMap::Iterator::operator -> Iterator illegal: exhausted\");\n\n //write code here\n}\n\n}\n\n#endif /* HASH_MAP_HPP_ */\n" }, { "alpha_fraction": 0.697029709815979, "alphanum_fraction": 0.7029703259468079, "avg_line_length": 23.095237731933594, "blob_id": "230fc122ba3481ad64a56f12aa2be3dc3d9166e7", "content_id": "a228031ceef4404f214e29e81f298250f8c66775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 505, "license_type": "no_license", "max_line_length": 64, "num_lines": 21, "path": "/cs143B/project1/header/eventlistener.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <string>\nusing std::string;\n\n#ifndef EVENTLISTENER_H\n#define EVENTLISTENER_H\nclass EventListener {\npublic:\n\t/**\n\t * onDelete : PCB *\n\t * Method returns a process control block that is being deleted\n\t * to the event dispatcher, or null if it is not being deleted.\n\t */\n\tvirtual EventListener* on_delete(string name) = 0;\n\t/**\n\t * on_request\n\t * Method to get a resource of name ${name}\n\t */\n\tvirtual EventListener* on_request(string name) = 0;\n\tvirtual void has_deleted(string name) = 0;\n};\n#endif" }, { "alpha_fraction": 0.6592742204666138, "alphanum_fraction": 0.6794354915618896, "avg_line_length": 33.2068977355957, "blob_id": "96fafe3e596e53b520dad067beb76e4641d68389", "content_id": "3d95039e16ca1b7d562807c934efb58a7af9b53a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 992, "license_type": "no_license", "max_line_length": 112, "num_lines": 29, "path": "/cs177/hw7/sim_exp.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n\n\nfrom random import random as rand\nfrom math import log\nimport numpy as np\nimport matplotlib.pyplot as plt\n# the general technique here (and this is super cool too by the way), is too take the inverse of the pmf\n# then for n random numbers generated between 0 and 1, plug that into the inverse, and the resulting vector will\n# be of that distrobution. So X ~ exp(lamb)\n\ndef Y(x, l):\n\t# inverse = (1/l) * log(1 - x)\t\n\treturn abs((1./l) * log(1-x))\n\n\nn=int(raw_input(\"Please enter how much to generate: \"))\nl=float(raw_input(\"Please enter lambda: \"))\ndistro = [Y(rand(), l) for i in range(0, n)]\nactual = np.random.exponential(l, n)\nbins=int(raw_input(\"please enter number of bins: \"))\n\nprint \"header\\t\\tMean\\t|\\tvariance\"\nprint \"gen\\t\\t\"+str.format('{0:.4f}',np.mean(distro))+\"\\t|\\t\"+str(np.var(distro))\nprint \"act\\t\\t\"+str.format('{0:.2f}',1./l)+\"\\t|\\t\"+str(1./pow(l,2))\n_,ax = plt.subplots(1,2)\nax[0].hist(distro, bins)\nax[1].hist(actual, bins, normed=True)\nplt.show()\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 26.58823585510254, "blob_id": "220424f33c358a464e84d6d64ef05de0c80bbcbd", "content_id": "efdc6b90fa2eaf1da44db8768a98585f0a1491d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 468, "license_type": "no_license", "max_line_length": 53, "num_lines": 17, "path": "/cs143B/project1/header/pcb.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "class \nclass PCB : public EventListener {\npublic:\n\tPCB(int id, string name, int priority);\n\tPCB (const PCB& copy);\n\tint id;\n\tstring name;\n\tmap<string, int> resource_to_amount_map;\n\tvector<RCB *> resources;\n\tstatus_t state;\n\tvector<PCB *> creation_tree;\n\tint priority;\n\tvirtual EventListener* on_delete(string arg_name);\n\tvirtual void has_deleted(string arg_name);\n\tvirtual EventListener* on_request(string name);\n\tfriend ostream& operator<<(ostream& outs, PCB &obj);\n}" }, { "alpha_fraction": 0.6122449040412903, "alphanum_fraction": 0.6242083311080933, "avg_line_length": 24.375, "blob_id": "ed185b7f624460e697165653c8c9313757127609", "content_id": "bd96a22a5b789b0a1bdbf6776ea0ccb852152a7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1421, "license_type": "no_license", "max_line_length": 69, "num_lines": 56, "path": "/cs177/hw7/mm1_queue.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\nimport random as rand\nfrom math import log\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef Y(x, l):\n\t# inverse = (1/l) * log(1 - x)\t\n\treturn abs((1./l) * log(1-x))\n\ngraph=[]\ndef sim(l, mu, sim, distro):\n\tdistro.sort()\n\tin_progress=distro.pop(0)+Y(rand.random(), mu)\n\tqueued=[in_progress]\n\tqc = 1\n\tfor i in range(0, len(distro)):\n\t\titem=distro.pop(0)\n\t\tif (item > in_progress):\n\t\t\tqc -= 1\n\t\t\tgraph.append(in_progress)\n\t\t\tin_progress = item+Y(rand.random(), mu)\n\t\telse:\n\t\t\tqc += 1\n\t\t\tqueued.append(item)\n\n\t\t# see if we need to move out any item in the queue\n\t\tfor i,x in enumerate(queued):\n\t\t\tif (x > in_progress):\n\t\t\t\tqc -= 1\n\t\t\t\tgraph.append(in_progress)\n\t\t\t\tin_progress = x + Y(rand.random(), mu)\n\t\t\t\tqueued.pop(i)\n\t\t\t\tbreak\n\t\tprint \"queue count is \" + str(qc) + \" current \" + str(in_progress)\n\t\n\twhile (qc > 0):\n\t\tfor i,x in enumerate(queued):\n\t\t\tif (x > in_progress):\n\t\t\t\tqc -= 1\n\t\t\t\tgraph.append(in_progress)\n\t\t\t\tin_progress = x + Y(rand.random(), mu)\n\t\t\t\tqueued.pop(i)\n\t\t\tprint \"queue count is \" + str(qc) + \" current \" + str(in_progress)\n\n\t\tprint \"Forcing \" + str(in_progress) + \" to finish\"\n\t\tin_progress = 0\n\t\nl=float(raw_input(\"Please enter lambda: \"))\nmu=float(raw_input(\"Enter mu: \"))\nK=int(raw_input(\"Input the number of users to simulate: \"))\ndistro = [Y(rand.random(), l) for i in range(0, K)]\nactual = np.random.exponential(l, K)\nsim(l,mu,K,distro) \nplt.hist(graph)\nplt.show()\n" }, { "alpha_fraction": 0.6555851101875305, "alphanum_fraction": 0.6702127456665039, "avg_line_length": 27.923076629638672, "blob_id": "b351001e8e9307c81e56717e368e253ce588968f", "content_id": "aeaef6612f6e8b9a764cd8e9491a8552f6d918eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 752, "license_type": "no_license", "max_line_length": 112, "num_lines": 26, "path": "/cs177/hw5/mc_simulator.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n# implementation of the power method.\nimport numpy as np\n\n# get input for an MxM matrix\ninput=raw_input\nM=int(input(\"Please enter M: \"))\np0 = [float(x) for x in input(\"Please enter p0, initial probability distro:\").split()]\nstate_transition = [[float(x) for x in input(\"Please enter line \" + str(i) + \": \").split()] for i in range(0,M)]\nT=int(input(\"Please enter the time step: \"))\n\n# convert to numpy arrays\np0 = np.array(p0)\nstate_transition = np.array(state_transition)\ni=0\nlastp = p0\nfreqs=np.zeros(M)\nwhile (i < T):\n\tx = state_transition[lastp.argmax()]\n\ti = i + 1\t\n\tlastp = state_transition[x.argmax()] \n\tprint(x.argmax())\n\tfreqs[x.argmax()] = freqs[x.argmax()] + 1\n\nfreqs = [ x / np.sum(freqs) for x in freqs ]\nprint(freqs)\n" }, { "alpha_fraction": 0.6877192854881287, "alphanum_fraction": 0.7056530117988586, "avg_line_length": 28.825580596923828, "blob_id": "fe047956e7732bc4acd86a41f0cf646df25ed42d", "content_id": "3a07443c2a2d66dd43753194a32820d3a4e25dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2565, "license_type": "no_license", "max_line_length": 114, "num_lines": 86, "path": "/cs143B/project2/filesystem/filesystem_impl.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n/**\n * Single flat list of all files.\n * Implemented as one regular file. Allows us to use normal operations.\n * For each sector in directory, we will have a file name and a discriptor\n *\n * ldisk [0] -> bitmask block\n * ldisk [1] -> (directory) 1 block, 64 bytes, that contain 2 integer pairs of, the name (4 chars), location (int)\n * ldisk [2...k] -> 4 descriptors / block, each\n *\t* Each descriptor has 4 integers. 4 ints * 4 bytes = 16 / 64 bytes * block = 1/4 block \n */\n #include \"../io/iosystem.h\"\n #include \"filesystem.h\"\n #include <string>\n #include <vector>\n #ifndef FILESYSTEM_IMPL_H\n #define FILESYSTEM_IMPL_H\nclass File_system_impl : public File_system\n{\npublic:\n\tFile_system_impl();\n\tvoid create_file(std::string name) override;\n\tvoid destroy_file(std::string name) override;\n\tvoid open_file(std::string name) override;\n\tvoid close_file(int oft_index) override;\n\tvoid write_file(int index, char c, int count) override;\n\tvoid read_file(int index, int count) override;\n\tvoid seek_file(int index, int start) override;\n\tvoid dir() override;\n\tvoid save(std::string name) override;\n\tvoid init(std::string name, IO_system *pio) override;\n\tIO_system *getIO() override;\n\tvoid setIO(IO_system *io) override;\nprivate:\n\n\t// typedefs\n\ttypedef struct dirent_s {\n\t\tchar name[4];\n\t\tint fd;\n\t} dirent_t;\n\n\ttypedef struct fd_s {\n\t\tint length;\n\t\tint block1;\n\t\tint block2;\n\t\tint block3;\n\t} fd_t;\n\n\ttypedef struct oft_entry_s {\n\t\tchar block[64];\n\t\tint length; \n\t\tint pos;\n\t\tint fd;\n\t} oftent_t;\n\n\t// members\n\tint bitmask_descriptors;\n\tunsigned long bitmask_file_blocks;\n\tint count_open_files;\n\tconst int K = 6;\n\tconst int num_descriptors = 24;\n\tconst int descriptors_per_block = num_descriptors / K;\n\tconst int descriptor_size = 64 / descriptors_per_block;\n\tdirent_t entries[23];\n\tfd_t file_entries[24];\n\toftent_t open_file_table[4];\n\n\t// methods\n\tint getFreeSlot(int bitmask, int max=32);\n\tlong getFreeSlot(unsigned long bitmask, int max=64);\n\tint getFileBlock(int b);\n\tdirent_t getFileDirent(std::string pname, int &i);\n\tfd_t getFd(std::string pname, int &i);\n\tfd_t getFd(dirent_t);\n\tvoid writeToDisk(int num, int length, unsigned char* data);\n\tint getCurrentContentBlock(oftent_t f);\n\tvoid write_new_file(char* name, int descriptor, bool new_descriptor);\n\tvoid write_file_descriptor(fd_t f, int fd);\n\tint read_block_containing_file(int fd, char *output_buffer);\n\tint get_file_descriptor_block_num(int fd);\n\tbool seek_file_to_pos(int index, int start);\n\tbool close_file_at_pos(int);\n\tstd::vector<std::string> get_all_file_names_in_dir();\n};\n#endif\n" }, { "alpha_fraction": 0.6051305532455444, "alphanum_fraction": 0.6193311810493469, "avg_line_length": 21.275510787963867, "blob_id": "756e028d9a82b8e4c81c7429f989d27a180581a6", "content_id": "4bdc844560172d63cb3819c03caa6afe60a87329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2183, "license_type": "no_license", "max_line_length": 72, "num_lines": 98, "path": "/cs143A/project4/mutex_compute/mutex_compute.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer, 22514022\n#include <stdlib.h>\n#include <errno.h>\n#include <math.h>\n#include <stdio.h>\n#include <pthread.h>\n\n#define NUM_THREADS 3\n\ntypedef struct threadargs_s {\n\tlong tid;\n\tint sum;\n\tint count;\n\tint min;\n\tint max;\n} threadargs_t;\n\npthread_mutex_t mutexfgets;\nint bail = 0;\n\nvoid *getAverage(void *args) {\n\tthreadargs_t *data = (threadargs_t *)args;\n\twhile(1) {\n\t\tif (bail) break;\n\t\tchar name[BUFSIZ], *read;\n\t\tpthread_mutex_lock(&mutexfgets);\n\t\tread = fgets(name, BUFSIZ, stdin);\n\t\tpthread_mutex_unlock(&mutexfgets);\n\t\tif (read == NULL) {\n\t\t\tbail = 1;\n\t\t\tbreak;\n\t\t}\n\t\t// sum our number.\n\t\tint input = strtol(name, NULL, 10);\n\t\tif (errno == ERANGE) {\n\t\t\tbail = 1;\t\n\t\t\tbreak;\n\t\t}\n\t\tdata->sum += input;\n\t\tdata->count++;\n\t\tdata->max = data->max < input ? input : data->max;\n\t\tdata->min = data->min > input ? input : data->min;\n\t}\n\tif(data->tid != 4) pthread_exit(args); \n\treturn NULL;\n}\n\nthreadargs_t *makeData(long id) {\n\tthreadargs_t *arg = malloc(sizeof(threadargs_t));\n\targ->tid = id + 1;\n\targ->sum = 0;\n\targ->count = 0;\n\targ->min = BUFSIZ;\n\targ->max = -1 * BUFSIZ - 1;\n\treturn arg; \n}\n\nint main() {\n\tint j = 0, i = 0, globmin = 0, globmax = 0;\n\tfloat avg = 0.0f;\n\tpthread_mutex_init(&mutexfgets, NULL);\n\n\t// make threads\n\tpthread_t threads[NUM_THREADS];\n\tthreadargs_t *args[NUM_THREADS + 1];\n\t\n\t// joinablility in threads.\n\tpthread_attr_t attr;\n\tpthread_attr_init(&attr);\n\tpthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\t\n\tfor (j = 0; j < NUM_THREADS; j++) {\n\t\targs[j] = makeData(j);\n\t\tpthread_create(&threads[j], &attr, getAverage, (void *) args[j]); \n\t}\n\n\t// do main thread.\n\targs[j] = makeData(j);\n\tgetAverage((void *) args[j]);\n\tavg += args[j]->sum;\n\ti += args[j]->count;\n\tglobmin = args[j]->min;\n\tglobmax = args[j]->max;\n\n\t// join and exit\n\tfor (j = 0; j < NUM_THREADS; j++) {\n\t\tpthread_join(threads[j], NULL);\n\t\tavg += args[j]->sum;\n\t\ti += args[j]->count;\n\t\tglobmin = globmin > args[j]->min ? args[j]->min : globmin;\n\t\tglobmax = globmax < args[j]->max ? args[j]->max : globmax; \n\t\tfree(args[j]);\n\t}\n\tprintf(\"Max:%i\\nMin:%i\\nAverage:%f\", globmax, globmin, avg /(double)i);\n\tpthread_attr_destroy(&attr);\n\tpthread_mutex_destroy(&mutexfgets);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.47872158885002136, "alphanum_fraction": 0.49735087156295776, "avg_line_length": 39.625, "blob_id": "373df31902b093d01c2b736220314750e70a3a95", "content_id": "2b820ab9870ab3cbb9ff4be5416e7ddbb1c9cf94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5851, "license_type": "no_license", "max_line_length": 113, "num_lines": 144, "path": "/cs178/hw3/mltools/logistic2.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import numpy as np\n\nfrom .base import classifier\nfrom .base import regressor\nfrom .utils import toIndex, fromIndex, to1ofK, from1ofK\nfrom numpy import asarray as arr\nfrom numpy import atleast_2d as twod\nfrom numpy import asmatrix as mat\nimport matplotlib.pyplot as plt\n\n\n################################################################################\n## LOGISTIC REGRESSION CLASSIFIER ##############################################\n################################################################################\n\n\nclass logisticClassify2(classifier):\n \"\"\"A binary (2-class) logistic regression classifier\n\n Attributes:\n classes : a list of the possible class labels\n theta : linear parameters of the classifier \n (1xN numpy array, where N=# features)\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Constructor for logisticClassify2 object. \n\n Parameters: Same as \"train\" function; calls \"train\" if available\n\n Properties:\n classes : list of identifiers for each class\n theta : linear coefficients of the classifier; numpy array \n shape (1,N) for binary classification or (C,N) for C classes\n \"\"\"\n self.classes = []\n self.theta = np.array([])\n\n if len(args) or len(kwargs): # if we were given optional arguments,\n self.train(*args,**kwargs) # just pass them through to \"train\"\n\n\n def __repr__(self):\n str_rep = 'logisticClassify2 model, {} features\\n{}'.format(\n len(self.theta), self.theta)\n return str_rep\n\n\n def __str__(self):\n str_rep = 'logisticClassify2 model, {} features\\n{}'.format(\n len(self.theta), self.theta)\n return str_rep\n\n\n## CORE METHODS ################################################################\n\n def plotBoundary(self,X,Y,axis=None):\n \"\"\" Plot the (linear) decision boundary of the classifier, along with data \"\"\"\n if axis==None: axis=plt\n colors = ['b', 'g', 'r']\n for i in range(1, X.shape[1]):\n for c in np.unique(Y):\n axis.plot( X[Y==c, 0], X[Y==c, i], 'o', color=colors[int(c)])\n xs = np.linspace(min(X[:,0]), max(X[:,0]), 200)\n ys = ((self.theta[0][1] * -1) * xs) - self.theta[0][0]\n ys = ys / self.theta[0][2]\n axis.plot(xs, ys, 'r-')\n\n def predictSoft(self, X):\n \"\"\" Return the probability of each class under logistic regression \"\"\"\n raise NotImplementedError\n ## You do not need to implement this function.\n ## If you *want* to, it should return an Mx2 numpy array \"P\", with \n ## P[:,1] = probability of class 1 = sigma( theta*X )\n ## P[:,0] = 1 - P[:,1] = probability of class 0 \n return P\n\n def predict(self, X):\n \"\"\" Return the predictied class of each data point in X\"\"\"\n z=np.zeros(X.shape[0])\n Yhat = np.zeros(X.shape[0])\n X1 = np.hstack((np.ones((X.shape[0],1)),X))\n for i in range(X.shape[0]):\n Yhat[i] = (self.classes[1] if np.dot(self.theta[0],X1[i]) > 0 else self.classes[0])\n\n return Yhat\n\n\n def train(self, X, Y, initStep=1.0, stopTol=1e-4, stopIter=5000, plot=None, alpha=0.0):\n \"\"\" Train the logistic regression using stochastic gradient descent \"\"\"\n ## First do some bookkeeping and setup:\n initStep = float(initStep)\n self.theta,X,Y = twod(self.theta), arr(X), arr(Y) # convert to numpy arrays\n M,N = X.shape\n if Y.shape[0] != M:\n raise ValueError(\"Y must have the same number of data (rows) as X\")\n self.classes = np.unique(Y)\n if len(self.classes) != 2:\n raise ValueError(\"Y should have exactly two classes (binary problem expected)\")\n if self.theta.shape[1] != N+1: # if self.theta is empty, initialize it!\n self.theta = np.random.randn(1,N+1)\n # Some useful modifications of the data matrices:\n X1 = np.hstack((np.ones((M,1)),X)) # make data array with constant feature\n Y01 = toIndex(Y, self.classes) # convert Y to canonical \"0 vs 1\" classes\n SIs = np.zeros(M)\n it = 0\n done = False\n Jsur = []\n J01 = []\n while not done:\n step = (2.0 * initStep) / (2.0 + it) # common 1/iter step size change\n\n for i in range(M): # for each data point i:\n zi = np.dot(self.theta[0], X1[i])\n yi = self.classes[0] if zi > 0 else self.classes[1]\n Y01[i] = yi\n si = 1 / (1 + np.exp(-zi))\n SIs[i] = si\n gradi = -(Y01[i] * (1 - si) * X1[i]) + ((1 - Y01[i]) * si * X1[i]) + (alpha * np.sum(self.theta))\n self.theta = self.theta - step * gradi\n\n # each pass, compute surrogate loss & error rates:\n J01.append( self.err(X,Y) )\n accum=[]\n for i in range(M):\n si = (1 + np.exp(-np.dot(self.theta[0], X1[i]))) ** -1\n accum.append((-np.log(si)) if Y01[i] == self.classes[1] else (-np.log(1 - si)))\n Jsur.append( np.mean(accum) + (alpha * (np.sum(self.theta)**2))) \n \n ## For debugging: print current parameters & losses\n # raw_input() # pause for keystroke\n\n # check stopping criteria:\n it += 1\n done = (it > stopIter) or ( (it>1) and (abs(Jsur[-1]-Jsur[-2])<stopTol) )\n\n # plot jsur vs j01\n if (plot != None):\n plot.semilogx(Jsur, 'r-', J01, 'g-')\n\n################################################################################\n################################################################################\n################################################################################\n\n" }, { "alpha_fraction": 0.6867080330848694, "alphanum_fraction": 0.6882717609405518, "avg_line_length": 30.43220329284668, "blob_id": "b8a68645f97b7e1910e192641e6802169284a41e", "content_id": "f94bb5d451aafed7bb8e421c99adbccd7a49cbad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18545, "license_type": "no_license", "max_line_length": 137, "num_lines": 590, "path": "/ics46/ProjectTwo/src/linked_priority_queue.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer (Unique ID: 660942)\n// Shaun McThomas (Unique ID: 307523)\n// We certify that we worked cooperatively on this programming\n// assignment, according to the rules for pair programming:\n// primarily that both partners worked on all parts together.\n\n#ifndef LINKED_PRIORITY_QUEUE_HPP_\n#define LINKED_PRIORITY_QUEUE_HPP_\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <initializer_list>\n#include \"ics_exceptions.hpp\"\n#include \"iterator.hpp\"\n#include \"priority_queue.hpp\"\n#include \"array_stack.hpp\"\n\n\nnamespace ics {\n\ntemplate<class T> class LinkedPriorityQueue : public PriorityQueue<T> {\n using PriorityQueue<T>::gt; //Required because of templated classes\n public:\n\tLinkedPriorityQueue() = delete;\n\texplicit LinkedPriorityQueue(bool (*agt)(const T& a, const T& b));\n\tLinkedPriorityQueue(const LinkedPriorityQueue<T>& to_copy);\n\tLinkedPriorityQueue(std::initializer_list<T> il,bool (*agt)(const T& a, const T& b));\n\tLinkedPriorityQueue(ics::Iterator<T>& start, const ics::Iterator<T>& stop,bool (*agt)(const T& a, const T& b));\n\tvirtual ~LinkedPriorityQueue();\n\n\tvirtual bool empty () const;\n\tvirtual int size () const;\n\tvirtual T& peek () const;\n\tvirtual std::string str () const;\n\n\tvirtual int enqueue (const T& element);\n\tvirtual T dequeue ();\n\tvirtual void clear ();\n\n\tvirtual int enqueue (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n\n\tvirtual LinkedPriorityQueue<T>& operator = (const LinkedPriorityQueue<T>& rhs);\n\tvirtual bool operator == (const PriorityQueue<T>& rhs) const;\n\tvirtual bool operator != (const PriorityQueue<T>& rhs) const;\n\n\ttemplate<class T2>\n\tfriend std::ostream& operator << (std::ostream& outs, const LinkedPriorityQueue<T2>& s);\n\n private:\n\tclass LN;\n\n public:\n\tclass Iterator : public ics::Iterator<T> {\n\t public:\n\t\t//KLUDGE should be callable only in begin/end\n\t\tIterator(LinkedPriorityQueue<T>* fof, LN* initial);\n\t\tvirtual ~Iterator();\n\t\tvirtual T erase();\n\t\tvirtual std::string str () const;\n\t\tvirtual const ics::Iterator<T>& operator ++ ();\n\t\tvirtual const ics::Iterator<T>& operator ++ (int);\n\t\tvirtual bool operator == (const ics::Iterator<T>& rhs) const;\n\t\tvirtual bool operator != (const ics::Iterator<T>& rhs) const;\n\t\tvirtual T& operator * () const;\n\t\tvirtual T* operator -> () const;\n\t private:\n\t\tLN* prev; //if header, then current is at front of list\n\t\tLN* current; //if can_erase is false, this value is unusable\n\t\tLinkedPriorityQueue<T>* ref_pq;\n\t\tint expected_mod_count;\n\t\tbool can_erase = true;\n\t};\n\n\t//For explicit use: Iterator<...>& it = c.ibegin(); ... or for (Iterator<...>& it = c.ibegin(); it != c.iend(); ++it)...\n\tvirtual ics::Iterator<T>& ibegin () const;\n\tvirtual ics::Iterator<T>& iend () const;\n\n\t//For implicit use: for (... i : c)...\n\tvirtual Iterator begin () const;\n\tvirtual Iterator end () const;\n\n private:\n\tclass LN {\n\t public:\n\t\tLN () {}\n\t\tLN (const LN& ln) : value(ln.value), next(ln.next){}\n\t\tLN (T v, LN* n = nullptr) : value(v), next(n){}\n\n\t\tT value;\n\t\tLN* next = nullptr;\n\t};\n\n\t//See base class PriorityQueue\n\t//bool (*gt)(const T& a, const T& b);// gt(a,b) = true iff a has higher priority than b\n\tint used = 0;\n\tLN* front = new LN();\n\tint mod_count = 0; //For sensing concurrent modification\n\tvoid delete_list(LN*& front); //Recycle storage, set front's argument to nullptr;\n };\n\n/**\n * delete_list. Given a starting node position, function will\n * delete a node and all subsequent nodes. Given the structure\n * of the code, this function can also delete pieces of a linked list,\n * say for example half\n */\ntemplate<class T>\nvoid LinkedPriorityQueue<T>::delete_list(LN*& front) {\n while (front != nullptr) {\n\tLN *temp = front;\n\tfront = front->next;\n\tdelete temp;\n }\n}\n\n//See code in array_priority_queue.hpp and linked_queue.hpp\n\n/**\n * Default constuctor. Not much to do here\n */\ntemplate<class T>\nLinkedPriorityQueue<T>::LinkedPriorityQueue(bool (*agt)(const T& a, const T& b)) : PriorityQueue<T>(agt) {}\n\n/**\n * Copy constuctor. Given a linked priority queue, enqueue all the elements\n * in the argument queue to make the current queue equal. See equals\n * for definition of equality\n *\n * @param const LinkedPriorityQueue<T>& to_copy\n * The queue to copy\n */\ntemplate <class T>\nLinkedPriorityQueue<T>::LinkedPriorityQueue(const LinkedPriorityQueue<T>& to_copy) \n : PriorityQueue<T>(to_copy) {\n enqueue(to_copy.ibegin(), to_copy.iend());\n gt = to_copy.gt;\n}\n\n/**\n * Constuctor w/ std::initializer_list. Given a initial list of \n * elements, enqueue each in order to construct our queue. All elements are\n * added in order and first assigned a priority\n *\n * @param std::initialize_list<T> il\n * The initial values of the priority queue\n */\ntemplate <class T>\nLinkedPriorityQueue<T>::LinkedPriorityQueue(std::initializer_list<T> il,bool (*agt)(const T& a, const T& b))\n : PriorityQueue<T>(agt) {\n gt = agt;\n for (T val : il)\n\tenqueue(val);\n}\n\n/**\n * Constuctor w/ iterators. Given two ics iterators, enqueue all\n * elements between the iterators. We assume both iterators point\n * to the same list of values.\n *\n * @param ics::Iterator<T>& start\n * The starting iterator\n * @param const ics::Iterator<T>& end\n * The ending iterator\n */\ntemplate <class T>\nLinkedPriorityQueue<T>::LinkedPriorityQueue(ics::Iterator<T>& start, const ics::Iterator<T>& stop,bool (*agt)(const T& a, const T& b))\n\t: PriorityQueue<T>(agt){\n gt = agt;\n enqueue(start, stop);\n}\n\n/**\n * Deconstructor\n */\ntemplate <class T>\nLinkedPriorityQueue<T>::~LinkedPriorityQueue() {\n delete_list(front->next); \n} \n\n/**\n * Enqueue. Function will add an element the list given a determined priority.\n * This function can have large mutations on the queue, since the\n * two interesting spots in a queue are the front and rear. If the\n * queue is empty, we initialize the queue, if not we grow it.\n *\n * @return int\n * 1, a guarentee that we will insert.\n */\ntemplate <class T>\nint LinkedPriorityQueue<T>::enqueue (const T& element) {\n // empty\n if (front->next == nullptr) {\n\tfront->next = new LN(element, nullptr);\n }\n\n else if (gt != nullptr && gt(element, front->next->value)) {\n\tfront->next = new LN(element, front->next);\n }\n\n // anywhere else.\n else \n\tfor (LN *node = front->next, *prev = front; node != nullptr; node = node->next, prev = prev->next) {\n\t if (gt != nullptr && gt(element, node->value)) {\n\t\tprev->next = new LN(element, node);\n\t\tbreak;\n\t }\n\t else if (node->next == nullptr) {\n\t\tnode->next = new LN(element);\n\t\tbreak;\n\t } \n\t}\n mod_count++;\n used++;\n return 1;\n}\n\n/**\n * Dequeue. Function will \"pop\" the top element of the queue for processing.\n * The function will also move the front pointer through the list, checking \n * boundaries as it goes. It will return the dequeue value and manage deletion.\n *\n * @return T\n * The value to process in the queue\n *\n * @throw EmptyError \n * If we are out of bounds, we will error\n */\ntemplate <class T>\nT LinkedPriorityQueue<T>::dequeue() {\n LN *to_return = front->next;\n T val = to_return->value;\n front->next = front->next->next;\n delete to_return;\n\n --used;\n mod_count++;\n return val;\n}\n\n/**\n * Empty. Function will determine if the queue is empty.\n * Note: An alternative way to do this would be to say front->next==nullptr\n * which is enforced later on in the code since this is a header linked list but\n * for simplicity, we do this check.\n */\ntemplate <class T>\nbool LinkedPriorityQueue<T>::empty() const {\n return used == 0;\n}\n\n/**\n * Size. Function will return the size of the queue. \n */\ntemplate <class T>\nint LinkedPriorityQueue<T>::size () const {\n return used;\n}\n\n/**\n * Peek. Function will return the first value in the queue\n * WITHOUT dequeueing the value. Useful for consumer code.\n */\ntemplate <class T>\nT& LinkedPriorityQueue<T>::peek () const {\n if (front->next != nullptr) return front->next->value;\n throw EmptyError(\"LinkedPriorityQueue::peek empty queue error\");\n}\n\n/**\n * Str. A debugging print method.\n */\ntemplate <class T>\nstd::string LinkedPriorityQueue<T>::str() const {\n int i = 0;\n std::stringstream string_value(\"\"), temp(\"\");\n for (T val : *this) {\n\tif (i == 0) string_value << val;\n\telse {\n\t temp.str(string_value.str());\n\t string_value.str(std::string());\n\t string_value << val << \",\" << temp.str();\n\t}\n\ti++;\n }\n string_value << \"(used = \" << used << \", mod_count = \" << \")\";\n return string_value.str();\n}\n\n/**\n * Clear. Function will clear the entire queue. See delete_list for\n * details\n */\ntemplate <class T>\nvoid LinkedPriorityQueue<T>::clear() {\n if (used > 0) delete_list(front->next); \n used = 0;\n}\n\n/**\n * Enqueue w/ iterators. Function will enqueue multiple items given\n * a start and end iterators. Function will consume the result of the \n * simplier enqueue method (see Enqueue).\n *\n * @param ics::Iterator<T>& start\n * The starting iterator\n * @param const ics::Iterator<T>& stop\n * The ending iterator\n *\n * @return int\n * The number of insertions to the queue.\n */\ntemplate <class T>\nint LinkedPriorityQueue<T>::enqueue(ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n int total = 0;\n for (; start != stop; total += enqueue(*(start++)));\n return total;\n}\n\n/**\n * Assignment. Function will become equal to a argument priority queue.\n * See equality operator for precise definition. In the event\n * that the queue has already been used previously, the queue\n * will be cleared.\n */\ntemplate <class T>\nLinkedPriorityQueue<T>& LinkedPriorityQueue<T>::operator = (const LinkedPriorityQueue<T>& rhs) {\n if (!empty()) clear();\n enqueue(rhs.ibegin(), rhs.iend());\n gt = rhs.gt;\n}\n\n/**\n * Equality. Function will determine if two priority queues are equal. Two\n * priority queues are equal if and only if the sizes are equal, and if the\n * two queues are in the SAME order and have the same priority functions.\n *\n * @param const PriorityQueue<T>&\n * The argument priority queue. Notice the type is not a linked priority queue, that\n * is becase we use iterators to check element and order equality.\n * This allows for cross compabilities between data structures\n * as long as they are the same data type.\n */\ntemplate <class T>\nbool LinkedPriorityQueue<T>::operator == (const PriorityQueue<T>& rhs) const {\n // are the sizes the same?\n if (used != rhs.size()) return false;\n\n // do the priority functions equal?\n if (gt != rhs.gt) return false;\n\n // element equals\n for (auto &lhs_iter = ibegin(), &rhs_iter = rhs.ibegin(); lhs_iter != iend(); lhs_iter++, rhs_iter++) \n\tif (*lhs_iter != *rhs_iter) return false;\n \n return true;\n}\n\n/**\n * Non-Equality. Function will determine if two priority queues are NOT equal. See\n * equality for definition.\n *\n * @param const PriorityQueue<T>&\n * The argument priority queue. Notice the type is not a linked priority queue, that\n * is becase we use iterators to check element and order equality.\n * This allows for cross compabilities between data structures\n * as long as they are the same data type.\n */\ntemplate <class T>\nbool LinkedPriorityQueue<T>::operator != (const PriorityQueue<T>& rhs) const {\n return !((*this) == rhs);\n}\n\n/**\n * Out stream. Function will print out the queue.\n */\ntemplate<class T2>\nstd::ostream& operator << (std::ostream& outs, const LinkedPriorityQueue<T2>& s) {\n bool is_not_end = true;\n std::stringstream string_value(\"\"), temp(\"\");\n for (T2 val : s) {\n\tif (is_not_end) string_value << val;\n\telse {\n\t temp.str(string_value.str());\n\t string_value.str(std::string());\n\t string_value << val << \",\" << temp.str();\n\t}\n\tis_not_end =false;\n }\n outs << \"priority_queue[\" << string_value.str() << \"]:highest\";\n return outs;\n}\n\n//Write the constructors, methods, and operators here for LinkedPriorityQueue\n//Fill in the missing parts of the erase method and ++ operators\n// for LinkedPriorityQueue's Iterator\n\n\n//KLUDGE: memory-leak\ntemplate<class T>\nauto LinkedPriorityQueue<T>::ibegin () const -> ics::Iterator<T>& {\n return *(new Iterator(const_cast<LinkedPriorityQueue<T>*>(this),front->next));\n}\n\n//KLUDGE: memory-leak\ntemplate<class T>\nauto LinkedPriorityQueue<T>::iend () const -> ics::Iterator<T>& {\n return *(new Iterator(const_cast<LinkedPriorityQueue<T>*>(this),nullptr));\n}\n\ntemplate<class T>\nauto LinkedPriorityQueue<T>::begin () const -> LinkedPriorityQueue<T>::Iterator {\n return Iterator(const_cast<LinkedPriorityQueue<T>*>(this),front->next);\n}\n\ntemplate<class T>\nauto LinkedPriorityQueue<T>::end () const -> LinkedPriorityQueue<T>::Iterator {\n return Iterator(const_cast<LinkedPriorityQueue<T>*>(this),nullptr);\n}\n\n\n\ntemplate<class T>\nLinkedPriorityQueue<T>::Iterator::Iterator(LinkedPriorityQueue<T>* fof, LN* initial) : current(initial), ref_pq(fof) {\n prev = ref_pq->front;\n expected_mod_count = ref_pq->mod_count;\n}\n\ntemplate<class T>\nLinkedPriorityQueue<T>::Iterator::~Iterator() {}\n\n/**\n * Erase. Function will erase the current iterator position. After an\n * erase call, we will return the value of deleted node. Erase will mutate\n * the under-line reference priority queue. \n *\n * @throw ConcurrentModificationError given conflicting modification counts\n * CannotEraseError given either false permission or the current position is out of bounds\n */\ntemplate<class T>\nT LinkedPriorityQueue<T>::Iterator::erase() {\n if (expected_mod_count != ref_pq->mod_count)\n\tthrow ConcurrentModificationError(\"LinkedPriorityQueue::Iterator::erase\");\n if (!can_erase)\n\tthrow CannotEraseError(\"LinkedPriorityQueue::Iterator::erase Iterator cursor already erased\");\n if (current == nullptr)\n\tthrow CannotEraseError(\"LinkedPriorityQueue::Iterator::erase Iterator cursor beyond data structure\");\n\n T val = current->value;\n prev->next = current->next;\n delete current;\n current = prev->next;\n can_erase = false;\n ref_pq->used--;\n expected_mod_count = --ref_pq->mod_count;\n return val;\n}\n\n/**\n * str. Just a debug string function.\n */\ntemplate<class T>\nstd::string LinkedPriorityQueue<T>::Iterator::str() const {\n std::ostringstream answer;\n answer << ref_pq->str() << \"(current=\" << current << \",expected_mod_count=\" << expected_mod_count << \",can_erase=\" << can_erase << \")\";\n return answer.str();\n}\n\n/**\n * Pre-fix increment. Function will increment the current position of the\n * the iterator given valid erase permissons. Prefix will return the newly \n * update current position of the iterator.\n *\n * @throw ConcurrentModificationError given conflicting modification counts\n */\ntemplate<class T>\nconst ics::Iterator<T>& LinkedPriorityQueue<T>::Iterator::operator ++ () {\n if (expected_mod_count != ref_pq->mod_count)\n\tthrow ConcurrentModificationError(\"LinkedPriorityQueue::Iterator::operator ++\");\n\n if (!can_erase) can_erase = true;\n else {\n\tprev = current;\n\tif (current != nullptr) \n\t current = current->next;\n }\n return *this;\n}\n\n//KLUDGE: can create garbage! (can return local value!)\n\n/**\n * Post-fix increment. Function will increment the current position of the\n * the iterator given valid erase permissons. Post-fix will return the previous \n * position of the iterator.\n *\n * @throw ConcurrentModificationError given conflicting modification counts\n */\ntemplate<class T>\nconst ics::Iterator<T>& LinkedPriorityQueue<T>::Iterator::operator ++ (int) {\n if (expected_mod_count != ref_pq->mod_count)\n\tthrow ConcurrentModificationError(\"LinkedPriorityQueue::Iterator::operator ++(int)\");\n\n if (current == nullptr)\n\treturn *this;\n\n if (!can_erase) can_erase = true;\n else {\n\tprev = current;\n\tcurrent = current->next;\n }\n return *(new Iterator(ref_pq, prev));\n}\n\n/**\n * Iterator Equality. Function will determine if two iterators are equal.\n * Two iterators are equal if they both point to the same spot in the data\n * structure.\n *\n * @throw ConcurrentModificationError given conflicting modification counts\n * IteratorTypeError given the right hand sider iterator is null\n * ComparingDifferentIteratorsError given the two reference queues don't\n * match\n */\ntemplate<class T>\nbool LinkedPriorityQueue<T>::Iterator::operator == (const ics::Iterator<T>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n\tthrow IteratorTypeError(\"LinkedPriorityQueue::Iterator::operator ==\");\n if (expected_mod_count != ref_pq->mod_count)\n\tthrow ConcurrentModificationError(\"LinkedPriorityQueue::Iterator::operator ==\");\n if (ref_pq != rhsASI->ref_pq)\n\tthrow ComparingDifferentIteratorsError(\"LinkedPriorityQueue::Iterator::operator ==\");\n\n return current == rhsASI->current;\n}\n\n/**\n * Iterator Non-Equality. Function will determine if two iterators are NOT equal.\n * See equality for definition.\n *\n * @throw ConcurrentModificationError given conflicting modification counts\n * IteratorTypeError given the right hand sider iterator is null\n * ComparingDifferentIteratorsError given the two reference queues don't\n * match\n */\ntemplate<class T>\nbool LinkedPriorityQueue<T>::Iterator::operator != (const ics::Iterator<T>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n\tthrow IteratorTypeError(\"LinkedPriorityQueue::Iterator::operator !=\");\n if (expected_mod_count != ref_pq->mod_count)\n\tthrow ConcurrentModificationError(\"LinkedPriorityQueue::Iterator::operator !=\");\n if (ref_pq != rhsASI->ref_pq)\n\tthrow ComparingDifferentIteratorsError(\"LinkedPriorityQueue::Iterator::operator !=\");\n\n return current != rhsASI->current;\n}\n\ntemplate<class T>\nT& LinkedPriorityQueue<T>::Iterator::operator *() const {\n if (expected_mod_count != ref_pq->mod_count)\n\tthrow ConcurrentModificationError(\"LinkedPriorityQueue::Iterator::operator *\");\n if (!can_erase || current == nullptr) {\n\tstd::ostringstream where;\n\twhere << current\n\t\t << \" when front = \" << ref_pq->front;\n\tthrow IteratorPositionIllegal(\"LinkedPriorityQueue::Iterator::operator * Iterator illegal: \"+where.str());\n }\n\n return current->value;\n}\n\ntemplate<class T>\nT* LinkedPriorityQueue<T>::Iterator::operator ->() const {\n if (expected_mod_count != ref_pq->mod_count)\n\tthrow ConcurrentModificationError(\"LinkedPriorityQueue::Iterator::operator *\");\n if (!can_erase || current == nullptr) {\n\tstd::ostringstream where;\n\twhere << current\n\t\t << \" when front = \" << ref_pq->front;\n\tthrow IteratorPositionIllegal(\"LinkedPriorityQueue::Iterator::operator * Iterator illegal: \"+where.str());\n }\n\n return &(current->value);\n}\n\n}\n\n#endif /* LINKED_PRIORITY_QUEUE_HPP_ */\n" }, { "alpha_fraction": 0.6741015911102295, "alphanum_fraction": 0.6827757358551025, "avg_line_length": 21.44444465637207, "blob_id": "1f6f1ece6e401df01d87f55e956af633b07a3d98", "content_id": "a3072168b87574045f40c734d6efa9f0053678c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 807, "license_type": "no_license", "max_line_length": 49, "num_lines": 36, "path": "/cs143B/project3/tlb.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string>\n\n#ifndef TLB_H\n#define TLB_H\nclass Itlb {\npublic:\n\tvirtual int get_frame_cache(int sp) = 0;\n\tvirtual void set_frame_cache(int sp, int f) = 0;\n\tvirtual bool has_frame_cache(int sp) = 0;\n\tvirtual std::string get_hit_string() = 0;\n\tvirtual std::string get_miss_string() = 0;\n};\n\nclass tlb : public Itlb {\npublic:\n\ttlb();\n\tint get_frame_cache(int sp);\n\tvoid set_frame_cache(int sp, int f);\n\tbool has_frame_cache(int sp);\n\tstd::string get_hit_string();\n\tstd::string get_miss_string();\n\tconst std::string CLASS_TAG = \"tlb::\";\nprivate:\n\tvoid lower_priorities(int lower_bound);\n\tint find_cached_object(int sp);\n\tstruct buffer_obj {\n\t\tint sp;\n\t\tint f;\n\t\tint p;\n\t};\n\tstatic const int BUFFER_SIZE = 4;\n\tstatic const int MAX_PRIORITY = 3;\n\tbuffer_obj buffer[BUFFER_SIZE];\n};\n#endif" }, { "alpha_fraction": 0.5967897176742554, "alphanum_fraction": 0.6166008114814758, "avg_line_length": 29.872024536132812, "blob_id": "6a4aa77a881b311cab6e8b02ee3ced1cb1948bd3", "content_id": "211588ae856a68276df8c99108e7b73b1762e271", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20746, "license_type": "no_license", "max_line_length": 165, "num_lines": 672, "path": "/cs143B/project2/filesystem/filesystem_impl.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include \"filesystem.h\"\n#include \"filesystem_impl.h\"\n#include \"../io/iosystem.h\"\n#include <iostream>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <cassert>\n#include <algorithm>\n#include <vector>\n#include <fstream>\n\nconst int BLOCK_SIZE=64;\nconst int FILE_NAME_MAX_SIZE=4;\nFile_system_impl::File_system_impl() {\n\t// load the bitmask pieces\n\tbitmask_descriptors = 1;\n\tbitmask_file_blocks = 7;\n\tcount_open_files = 1;\n}\n\nvoid File_system_impl::create_file(std::string pname) {\n\tfd_t file_descriptor;\n\tchar *name = (char*)pname.c_str();\n\t// does this file exist?\n\tstd::vector<std::string> files = get_all_file_names_in_dir();\n\tif (find(files.begin(), files.end(), pname) != files.end()) {\n\t\tstd::cout << \"error\";\n\t\treturn;\n\t}\n\n\t// From the bitmask, get the location \t\n\tint fd = getFreeSlot(bitmask_descriptors, num_descriptors);\n\tassert(fd != -1);\n\n\t// lock it down, and create directory entry\n\tbool new_descriptor = fd > bitmask_descriptors;\n\tbitmask_descriptors |= 1 << fd;\n\twrite_new_file(name, fd - 1, new_descriptor);\n\n\t// set the file descriptor\n\t// @todo: Clean this up.\n\tint b = getFreeSlot(bitmask_file_blocks);\n\tfile_descriptor.length = 0;\n\tfile_descriptor.block1 = getFileBlock(b);\n\tbitmask_file_blocks |= 1 << b;\n\tb = getFreeSlot(bitmask_file_blocks);\n\tfile_descriptor.block2 = getFileBlock(b);\n\tbitmask_file_blocks |= 1 << b;\n\tb = getFreeSlot(bitmask_file_blocks);\n\tfile_descriptor.block3 = getFileBlock(b);\n\tbitmask_file_blocks |= 1 << b;\n\tfile_entries[fd] = file_descriptor;\n\twrite_file_descriptor(file_descriptor, fd);\n\n\tstd::cout << pname << \" created\";\n}\n\nvoid File_system_impl::open_file(std::string fname) {\n\t// get file descriptor\n\tint fd, pos;\n\tunsigned char buffer[64];\n\tfd_t f = getFd(fname, fd);\n\n\tif (f.length == -1) {\n\t\tstd::cout << \"error\";\n\t\treturn;\n\t}\n\n\t// ensure the file isn't open\n\tfor (int i = 1; i < count_open_files; i++) {\n\t\tfd_t *f_o = &(file_entries[open_file_table[i].fd]);\n\t\tif (f_o->block1 == f.block1) {\n\t\t\tstd::cout << \"error\";\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// create entry\n\toftent_t entry;\n\tentry.fd = fd + 1;\n\tentry.pos = 0;\n\tentry.length = f.length;\n\tio->read_block(f.block1, buffer);\n\tmemcpy(entry.block, buffer, BLOCK_SIZE);\n\tif (open_file_table[1].fd == -1) {\n\t\tpos = 1;\n\t} else if (open_file_table[2].fd == -1) {\n\t\tpos = 2;\n\t} else if (open_file_table[3].fd == -1) {\n\t\tpos = 3;\n\t} else {\n\t\tstd::cout << \"error\";\n\t}\n\tcount_open_files++;\n\topen_file_table[pos] = entry;\n\tstd::cout << fname << \" opened \" << pos; // << \"[length=\" << f.length << \"]\" << std::endl;\n}\n\nbool File_system_impl::close_file_at_pos(int oft_index) {\n\t\t// get oft entry\n\tif (oft_index >= count_open_files) {\n\t\treturn false;\n\t}\n\tif (oft_index == 0) { // don't let anyone close the directory\n\t\treturn false;\n\t}\n\toftent_t *f = &(open_file_table[oft_index]);\n\tint block_num, descriptor_loc;\n\tchar buf[BLOCK_SIZE];\n\n\tcount_open_files--;\n\n\t// save the contents of the buffer.\n\tif (!floor(f->length / BLOCK_SIZE)) {\n\t\tblock_num = file_entries[f->fd].block1;\n\t} else if (!floor(f->length / (2*BLOCK_SIZE))) {\n\t\tblock_num = file_entries[f->fd].block2;\n\t} else {\n\t\tblock_num = file_entries[f->fd].block3;\n\t}\n\twriteToDisk(block_num, f->length % BLOCK_SIZE, (unsigned char*)f->block);\n\n\t// update the length of the file.\n\tfile_entries[f->fd].length = f->length;\n\tdescriptor_loc = read_block_containing_file(f->fd - 1, buf);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[descriptor_loc + i] = (unsigned char)(f->length >> (8 * (i%4)) & 0xFF);\n\twriteToDisk(get_file_descriptor_block_num(f->fd), BLOCK_SIZE, (unsigned char*)buf);\n\n\t// close\n\tf->fd = -1;\n\treturn true;\n}\nvoid File_system_impl::close_file(int oft_index) {\n\t// get oft entry\n\tif (close_file_at_pos(oft_index)) {\n\t\tstd::cout << oft_index << \" closed\";\n\t} else {\n\t\tstd::cout << \"error\";\n\t}\n}\n\nvoid File_system_impl::destroy_file(std::string pname) {\n\n\t// find the directory entry\n\tint pos = 0;\n\tfd_t file = getFd(pname, pos);\n\n\t// ensure the file exists\n\tif (file.length == -1) {\n\t\tstd::cout << \"error\";\n\t\treturn;\n\t}\n\n\t// ensure the file isn't open\n\tfor (int i = 1; i < count_open_files; i++) {\n\t\tfd_t *f_o = &(file_entries[open_file_table[i].fd]);\n\t\tif (f_o->block1 == file.block1) {\n\t\t\tclose_file_at_pos(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// update mask and container\n\tbitmask_descriptors -= (1 << (pos + 1));\n\n\t// delete data from the disk.\n\tunsigned char buffer[64];\n\twriteToDisk(file.block1, 0, buffer);\n\twriteToDisk(file.block2, 0, buffer);\n\twriteToDisk(file.block3, 0, buffer);\n\n\t// update the directory.\n\tchar buf[64];\n\tint descriptor = pos % BLOCK_SIZE, new_fd = -1;\n\toftent_t *dir_oft = &(open_file_table[0]);\n\tfd_t dir_file = file_entries[0];\n\tint block = !floor(dir_oft->length / BLOCK_SIZE) ? dir_file.block1 : !floor(dir_oft->length / (BLOCK_SIZE * 2)) ? dir_file.block2 : dir_file.block3;\n\tio->read_block(block, (unsigned char*)buf);\n\tfor (int i = 4; i < 8; i++)\n\t\tbuf[(descriptor * 8) + i] = (new_fd >> (8 * (i%4)) & 0xFF);\n\tio->write_block(block, (unsigned char*)buf);\n\tdir_oft->length -= sizeof(dirent_t);\n\n\tstd::cout << pname << \" deleted\";\n}\n\nvoid File_system_impl::write_file(int index, char c, int count) {\n\tif (index >= count_open_files) {\n\t\tstd::cout << \"error\";\n\t\treturn;\n\t}\n\toftent_t *file = &(open_file_table[index]);\n\tint written = 0, prev_pos = file->pos % BLOCK_SIZE, total_count = count;\n\tint current_block = file->pos < BLOCK_SIZE ? 1 : (file->pos < (BLOCK_SIZE * 2) ? 2 : 3);\n\tunsigned char to_write[BLOCK_SIZE];\n\n\tif (file->pos == file->length && file->length == BLOCK_SIZE*3) {\n\t\tstd::cout << \"0 bytes written\";\n\t\treturn;\n\t}\n\twhile (written < count) {\n\t\tbool advance_block = !(file->pos % BLOCK_SIZE);\n\t\tif (written > 0 && advance_block) {\n\t\t\t// write the current block to disk\n\t\t\tint block_num = current_block == 1 ? file_entries[file->fd].block1 : (current_block == 2 ? file_entries[file->fd].block2 : file_entries[file->fd].block3);\n\t\t\twriteToDisk(block_num, BLOCK_SIZE, (unsigned char *)file->block);\n\n\t\t\tif (current_block == 3) {\n\t\t\t\t// refuse writting. \n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tblock_num = current_block == 1 ? file_entries[file->fd].block2 : file_entries[file->fd].block3;\n\t\t\t\n\t\t\t// get the next block.\n\t\t\tunsigned char buffer[BLOCK_SIZE];\n\t\t\tio->read_block(block_num, buffer);\n\t\t\tmemcpy(file->block, buffer, BLOCK_SIZE);\n\t\t\tcurrent_block++;\n\n\t\t\tfile->length += written;\n\t\t\tcount -= written;\n\t\t\twritten = 0;\n\t\t\tprev_pos = 0;\n\t\t}\n\t\tfile->block[file->pos % BLOCK_SIZE] = c;\n\t\twritten++;\n\t\tfile->pos++;\n\t}\n\n\t// write the block to disk.\n\tif (file->pos > file->length)\n\t\tfile->length += written;\n\tint block_num = current_block == 1 ? file_entries[file->fd].block1 : (current_block == 2 ? file_entries[file->fd].block2 : file_entries[file->fd].block3);\n\tmemcpy(to_write, file->block, BLOCK_SIZE);\n\twriteToDisk(block_num, BLOCK_SIZE, to_write);\n\tif (total_count > 192) total_count = 192;\n\tstd::cout << total_count << \" bytes written\";\n}\n\nvoid File_system_impl::read_file(int index, int count) {\n\tif (index >= count_open_files) {\n\t\tstd::cout << \"error\";\n\t\treturn;\n\t}\n\toftent_t *file = &(open_file_table[index]);\n\tint read = 0, offset = 0;\n\tint current_block = file->pos < BLOCK_SIZE ? 1 : (file->pos < (BLOCK_SIZE * 2) ? 2 : 3);\n\tchar to_read[count + 1];\n\twhile (read < count) {\n\t\tif (read > 0 && !(file->pos % BLOCK_SIZE)) {\n\t\t\t// write the current block to disk\n\t\t\tint block_num = current_block == 1 ? file_entries[file->fd].block1 : (current_block == 2 ? file_entries[file->fd].block2 : file_entries[file->fd].block3);\n\t\t\twriteToDisk(block_num, BLOCK_SIZE, (unsigned char *)file->block);\n\t\t\tblock_num = current_block == 1 ? file_entries[file->fd].block2 : file_entries[file->fd].block3;\n\t\t\t\n\t\t\t// get the next block.\n\t\t\tunsigned char buffer[BLOCK_SIZE];\n\t\t\tio->read_block(block_num, buffer);\n\t\t\tmemcpy(file->block, buffer, BLOCK_SIZE);\n\t\t\tcurrent_block++;\n\t\t}\n\t\tto_read[read] = file->block[file->pos % BLOCK_SIZE];\n\t\tread++;\n\t\tfile->pos++;\n\t}\n\tto_read[count] = '\\0';\n\tstd::cout << (char*)to_read;\n}\n\nbool File_system_impl::seek_file_to_pos(int index, int start) {\n\tif (index > count_open_files) return false;\n\topen_file_table[index].pos = start;\n\n\tif (start > open_file_table[index].length) {\n\t\treturn false;\n\t}\n\tint block_num;\n\tif (start <= BLOCK_SIZE) {\n\t\t// load block 1\n\t\tblock_num = file_entries[open_file_table[index].fd].block1;\n\t} else if (start <= BLOCK_SIZE * 2) {\n\t\t// load block 2\n\t\tblock_num = file_entries[open_file_table[index].fd].block2;\n\t} else {\n\t\t// load block 3\n\t\tblock_num = file_entries[open_file_table[index].fd].block3;\n\t}\n\n\t// load the correct buffer into the open file table.\n\tio->read_block(block_num, (unsigned char *)open_file_table[index].block);\n\treturn true;\n}\nvoid File_system_impl::seek_file(int index, int start) {\n\tif (seek_file_to_pos(index, start)) {\n\t\tstd::cout << \"position is \" << start;\n\t} else {\n\t\tstd::cout << \"error\";\n\t}\n}\n\nvoid File_system_impl::dir() {\n\tstd::vector<std::string> files = get_all_file_names_in_dir();\n\tfor (std::string l : files) {\n\t\tif (l == \"\") continue;\n\t\tstd::cout << l << \" \";\n\t}\n}\n\nstd::vector<std::string> File_system_impl::get_all_file_names_in_dir() {\n\tstd::vector<std::string> files;\n\t// just run through the file names and print them.\n\tint length = open_file_table[0].length;\n\tint i = 2, j = 0; // starting at 2 because descriptor 1 is the directory.\n\tchar name[4], len[4];\n\twhile (i < bitmask_descriptors) {\n\t\tbool has_descriptor = (bitmask_descriptors & i) >> j;\n\t\tif (has_descriptor) {\n\t\t\tseek_file_to_pos(0, j * 8);\n\t\t\tint pos = (j * 8) % BLOCK_SIZE;\n\t\t\t// make sure the fd is nonzero.\n\t\t\tname[0] = open_file_table[0].block[pos] ;\n\t\t\tname[1] = open_file_table[0].block[pos + 1];\n\t\t\tname[2] = open_file_table[0].block[pos + 2];\n\t\t\tname[3] = open_file_table[0].block[pos + 3];\n\t\t\tfiles.push_back(std::string(name));\n\t\t}\n\t\ti = i << 1;\n\t\tj++;\n\t} \n\treturn files;\n}\n\nvoid File_system_impl::save(std::string name) {\n\tif (name == \"\") std::cout << \"error\";\n\telse {\n\t\tint i = 0;\n\t\tchar buf[64];\n\t\tfor (int i = 0; i < 4; i++)\n\t\t\tbuf[i] = (unsigned char)(bitmask_descriptors >> (8 * (i)) & 0xFF);\n\t\tfor (int i = 0; i < 8; i++)\n\t\t\tbuf[i+4] = (unsigned char)(bitmask_file_blocks >> (8 * (i)) & 0xFF);\n\t\twriteToDisk(0, sizeof(int)+sizeof(long), (unsigned char*)buf);\n\n\t\t// close all the open files.\n\t\tfor (int i = 1; i < count_open_files; i++) {\n\t\t\tint block_num = open_file_table[i].length;\n\t\t\tint fd = open_file_table[i].fd;\n\t\t\tblock_num = floor(block_num / BLOCK_SIZE) == 0 ? file_entries[fd].block1 : floor(block_num / BLOCK_SIZE) == 1 ? file_entries[fd].block2 : file_entries[fd].block3;\n\t\t\twriteToDisk(block_num, open_file_table[i].length % BLOCK_SIZE, (unsigned char*)open_file_table[i].block);\n\t\t}\n\t\topen_file_table[0].fd = -1; open_file_table[1].fd = -1; open_file_table[2].fd = -1; open_file_table[3].fd = -1;\n\t\tcount_open_files = 1;\n\n\t\tstd::ofstream ofs(name);\n\t\twhile (i < BLOCK_SIZE) {\n\t\t\tunsigned char d[BLOCK_SIZE];\n\t\t\tio->read_block(i++, d);\n\t\t\tofs.write((char*)d, BLOCK_SIZE);\n\t\t}\n\t\tofs.flush();\n\t\tofs.close();\n\t\tstd::cout << \"disk saved\";\n\t}\n}\n\nvoid File_system_impl::init(std::string name, IO_system *pio) {\n\tio = pio;\n\tsetIO(pio);\n\tif (name != \"\") {\n\t\t// read in the ldisk from the file.\n\t\tunsigned char data[BLOCK_SIZE];\n\t\tint block_num = 0, i = 0;\n\t\tstd::ifstream ifs(name);\n\t\tif (!ifs.good()) std::cout << \"error\";\n\t\telse {\n\t\t\twhile (ifs.good() && block_num < (BLOCK_SIZE * BLOCK_SIZE)) {\n\t\t\t\tdata[i++] = static_cast<unsigned char>(ifs.get());\n\t\t\t\tif (i == BLOCK_SIZE) {\n\t\t\t\t\t// write the block \n\t\t\t\t\ti = 0;\n\t\t\t\t\tio->write_block(block_num++, data);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tifs.close();\n\n\t\t// get our bitmaps.\n\t\tchar buf[BLOCK_SIZE], mask_one[sizeof(int)], mask_two[sizeof(long)];\n\t\tio->read_block(0, (unsigned char*)buf);\n\t\tmemcpy(mask_one, &(buf[0]), sizeof(int));\n\t\tmemcpy(mask_two, &(buf[sizeof(int)]), sizeof(long));\n\t\tbitmask_descriptors = *(static_cast<int*>(static_cast<void*>(mask_one)));\n\t\tbitmask_file_blocks = *(static_cast<unsigned long*>(static_cast<void*>(mask_two)));\n\n\t\t// // test code: remove.\n\t\t// // fill the to return obj\n\t\t// int t = bitmask_descriptors, descriptor_loc = 0, i = 0;\n\t\t// char int_value[4], buf[BLOCK_SIZE];\n\t\t// while ((t >> i) > 0) {\n\t\t// \tint_value[0] = buf[descriptor_loc];\n\t\t// \tint_value[1] = buf[descriptor_loc + 1];\n\t\t// \tint_value[2] = buf[descriptor_loc + 2];\n\t\t// \tint_value[3] = buf[descriptor_loc + 3];\n\t\t// \tto_return.length = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\t\t// \tdescriptor_loc += 4;\n\t\t// \tint_value[0] = buf[descriptor_loc];\n\t\t// \tint_value[1] = buf[descriptor_loc + 1];\n\t\t// \tint_value[2] = buf[descriptor_loc + 2];\n\t\t// \tint_value[3] = buf[descriptor_loc + 3];\n\t\t// \tto_return.block1 = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\t\t// \tdescriptor_loc += 4;\n\t\t// \tint_value[0] = buf[descriptor_loc];\n\t\t// \tint_value[1] = buf[descriptor_loc + 1];\n\t\t// \tint_value[2] = buf[descriptor_loc + 2];\n\t\t// \tint_value[3] = buf[descriptor_loc + 3];\n\t\t// \tto_return.block2 = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\t\t// \tdescriptor_loc += 4;\n\t\t// \tint_value[0] = buf[descriptor_loc];\n\t\t// \tint_value[1] = buf[descriptor_loc + 1];\n\t\t// \tint_value[2] = buf[descriptor_loc + 2];\n\t\t// \tint_value[3] = buf[descriptor_loc + 3];\n\t\t// \tto_return.block3 = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\n\t\t// \tstd::cout << \"(length, block1, block2, block3) [\";\n\t\t// \tstd::cout << to_return.length << \",\";\n\t\t// \tstd::cout << to_return.block1 << \",\";\n\t\t// \tstd::cout << to_return.block2 << \",\";\n\t\t// \tstd::cout << to_return.block3 << \"]\" << std::endl;\n\t\t// }\n\t\tstd::cout << \"disk restored\";\n\t} else {\n\t\tstd::cout << \"disk initialized\";\n\t}\n}\n\nvoid File_system_impl::setIO(IO_system *pio) {\n\tio = pio;\n\t\n\t// make the directory with 3 blocks.\n\tfd_t f;\n\tf.length = 0;\n\tf.block1 = getFileBlock(0);\n\tf.block2 = getFileBlock(1);\n\tf.block3 = getFileBlock(2);\n\tfile_entries[0] = f;\n\n\t// open the directory\n\toftent_t entry;\n\tentry.fd = 0;\n\tentry.pos = 0;\n\tentry.length = 0;\n\topen_file_table[0] = entry;\n\tfor (int i = 0; i < 4; i++)\n\t\topen_file_table[i + 1].fd = -1;\n\n\t// write to disk\n\tunsigned char buf[64];\n\tio->read_block(1, buf);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[i] = (unsigned char)(f.length >> (8 * (i%4)) & 0xFF);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[i + 4] = (unsigned char)(f.block1 >> (8 * (i%4)) & 0xFF);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[i + 8] = (unsigned char)(f.block2 >> (8 * (i%4)) & 0xFF);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[i + 12] = (unsigned char)(f.block3 >> (8 * (i%4)) & 0xFF);\n\n\tio->write_block(1, buf);\n\tmemcpy(entry.block, buf, BLOCK_SIZE);\n}\n\nIO_system* File_system_impl::getIO() {\n\treturn io;\n}\n\nFile_system_impl::dirent_t File_system_impl::getFileDirent(std::string pname, int &i) {\n\t// find the directory entry\n\tint descriptor = 0, block = 0;\n\tchar buf[BLOCK_SIZE], int_value[sizeof(int)];\n\tio->read_block(file_entries[0].block1, (unsigned char*) buf);\n\tdirent_t to_return;\n\tto_return.fd = -1;\n\twhile (descriptor < num_descriptors && block < K) {\n\t\tchar name[FILE_NAME_MAX_SIZE];\n\t\tint offset = descriptor == 0 || descriptor % descriptors_per_block;\n\t\tif (!offset) {\n\t\t\tint block_num = block == 1 ? file_entries[0].block2 : file_entries[0].block3;\n\t\t\tio->read_block(block_num, (unsigned char*) buf);\n\t\t\tblock++;\n\t\t}\n\t\tint n = (descriptor * 8) % BLOCK_SIZE;\n\t\tname[0] = buf[n];\n\t\tname[1] = buf[n+1];\n\t\tname[2] = buf[n+2];\n\t\tname[3] = buf[n+3];\n\n\t\tif (!std::strcmp((char*)name, pname.c_str())) {\n\t\t\ti = descriptor;\n\t\t\tmemcpy(to_return.name, name, 4);\n\t\t\t// std::cout << \" ======== to_return.name: \" << to_return.name;\n\t\t\tname[0] = buf[n+4];\n\t\t\tname[1] = buf[n+5];\n\t\t\tname[2] = buf[n+6];\t\n\t\t\tname[3] = buf[n+7];\n\t\t\tto_return.fd = *(static_cast<int*>(static_cast<void*>(name)));\n\t\t\t// std::cout << \" ======== fd: \" << to_return.fd;\n\t\t\t// std::cout << \"Found file entry \" << (char*)to_return.name << \" \" << to_return.fd << std::endl;\n\t\t\tbreak;\n\t\t} else {\n\t\t\tdescriptor++;\n\t\t}\n\t}\n\treturn to_return;\n}\n\nFile_system_impl::fd_t File_system_impl::getFd(dirent_t dir) {\n\tchar int_value[sizeof(int)], buf[BLOCK_SIZE];\n\tint descriptor_loc = read_block_containing_file(dir.fd, buf);\n\t// std::cout << \" ===== dir.fd: \" << dir.fd;\n\t// std::cout << \" ===== descriptor_loc: \" << descriptor_loc;\n\tfd_t to_return;\n\tif (dir.fd == -1) { \n\t\tto_return.length = -1;\n\t\treturn to_return;\n\t}\n\n\t// fill the to return obj\n\tint_value[0] = buf[descriptor_loc];\n\tint_value[1] = buf[descriptor_loc + 1];\n\tint_value[2] = buf[descriptor_loc + 2];\n\tint_value[3] = buf[descriptor_loc + 3];\n\tto_return.length = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\tdescriptor_loc += 4;\n\tint_value[0] = buf[descriptor_loc];\n\tint_value[1] = buf[descriptor_loc + 1];\n\tint_value[2] = buf[descriptor_loc + 2];\n\tint_value[3] = buf[descriptor_loc + 3];\n\tto_return.block1 = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\tdescriptor_loc += 4;\n\tint_value[0] = buf[descriptor_loc];\n\tint_value[1] = buf[descriptor_loc + 1];\n\tint_value[2] = buf[descriptor_loc + 2];\n\tint_value[3] = buf[descriptor_loc + 3];\n\tto_return.block2 = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\tdescriptor_loc += 4;\n\tint_value[0] = buf[descriptor_loc];\n\tint_value[1] = buf[descriptor_loc + 1];\n\tint_value[2] = buf[descriptor_loc + 2];\n\tint_value[3] = buf[descriptor_loc + 3];\n\tto_return.block3 = *(static_cast<int*>(static_cast<void*>(&int_value)));\n\treturn to_return;\n}\n\nFile_system_impl::fd_t File_system_impl::getFd(std::string pname, int &i) {\n\treturn getFd(getFileDirent(pname, i));\n}\n\nint File_system_impl::getFreeSlot(int bitmask, int max) {\n\tint to_return = -1;\n\tfor (int i = 0; i < max; i++) {\n\t\tbool is_free = !((bitmask & (1 << i)) >> i);\n\t\tif (is_free) {\n\t\t\tto_return = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn to_return;\n}\n\nlong File_system_impl::getFreeSlot(unsigned long bitmask, int max) {\n\tlong to_return = -1;\n\tfor (int i = 0; i < max; i++) {\n\t\tbool is_free = !((bitmask & (1 << i)) >> i);\n\t\tif (is_free) {\n\t\t\tto_return = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn to_return;\n}\n\nint File_system_impl::getFileBlock(int b) {\n\treturn b + K + 1;\n}\n\nvoid File_system_impl::writeToDisk(int num, int length, unsigned char data[]) {\n\tchar nil='\\0';\n\tlength = length > BLOCK_SIZE ? length % BLOCK_SIZE : length;\n\tmemcpy(&(data[length]), &nil, BLOCK_SIZE - length);\n\tio->write_block(num, data);\n}\n\nint File_system_impl::getCurrentContentBlock(oftent_t f) {\n\tint block_num;\n\tif (floor(f.length / BLOCK_SIZE) == 0) {\n\t\tblock_num = file_entries[f.fd].block1;\n\t} else if (floor(f.length / BLOCK_SIZE) == 1) {\n\t\tblock_num = file_entries[f.fd].block2;\n\t} else {\n\t\tblock_num = file_entries[f.fd].block3;\n\t}\n\treturn block_num;\n}\n\nFile_system* File_system::CreateFileSystem(IO_system *io) {\n\tFile_system *f = new File_system_impl();\n\tf->setIO(io);\n\treturn f;\n}\n\n/**\n * Adds the new file to directory!\n */\nvoid File_system_impl::write_new_file(char* name, int descriptor, bool new_descriptor) {\n\tchar num[4], to_write[BLOCK_SIZE];\n\n\t// read the correct block.\n\tdescriptor = descriptor % BLOCK_SIZE;\n\toftent_t *dir_oft = &(open_file_table[0]);\n\tfd_t dir_file = file_entries[0];\n\tint block = !floor(dir_oft->length / BLOCK_SIZE) ? dir_file.block1 : !floor(dir_oft->length / (BLOCK_SIZE * 2)) ? dir_file.block2 : dir_file.block3;\n\tio->read_block(block, (unsigned char*)to_write);\n\tfor (int i = 0; i < 4; i++)\n\t\tto_write[((descriptor * 8) % BLOCK_SIZE) + i] = (unsigned char)name[i];\n\tfor (int i = 4; i < 8; i++)\n\t\tto_write[((descriptor * 8) % BLOCK_SIZE) + i] = (descriptor >> (8 * (i%4)) & 0xFF);\n\tio->write_block(block, (unsigned char*)to_write);\n\n\tif (new_descriptor)\n\t\tdir_oft->length += sizeof(dirent_t);\n}\n\n/**\n * Adds the new descriptor, which is not in the directory.\n */\nvoid File_system_impl::write_file_descriptor(fd_t f, int fd) {\n\tchar new_file[16];\n\tint inner_pos = (fd % 4) * descriptor_size;\n\tint block_num = get_file_descriptor_block_num(fd); // the offset: 1 for bitmap, 6 for descriptors\n\tint buf_pos = 0;\n\tunsigned char buf[64];\n\tio->read_block(block_num, buf);\n\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[inner_pos + buf_pos++] = (unsigned char)(f.length >> (8 * (i%4)) & 0xFF);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[inner_pos + buf_pos++] = (unsigned char)(f.block1 >> (8 * (i%4)) & 0xFF);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[inner_pos + buf_pos++] = (unsigned char)(f.block2 >> (8 * (i%4)) & 0xFF);\n\tfor (int i = 0; i < 4; i++)\n\t\tbuf[inner_pos + buf_pos++] = (unsigned char)(f.block3 >> (8 * (i%4)) & 0xFF);\n\n\t// std::cout << \"Writting discriptor to disk at \" << block_num << std::endl;\n\tio->write_block(block_num, buf);\n}\n\nint File_system_impl::get_file_descriptor_block_num(int fd) {\n\treturn floor(fd / descriptors_per_block) + 1;\n}\n\nint File_system_impl::read_block_containing_file(int fd, char *output_buffer) {\n\tint block_offset = get_file_descriptor_block_num(fd);\n\tint descriptor_loc = ((fd + 1) % descriptors_per_block) * descriptor_size;\n\tio->read_block(block_offset, (unsigned char*)output_buffer);\n\treturn descriptor_loc ;\n}\n" }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.6484017968177795, "avg_line_length": 18.352941513061523, "blob_id": "d86e0c57e9eef0c925f3b7b6653a0dd6cb3f5d4e", "content_id": "bfa7c89663ffd0827e91211bfabad085d4a108ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 657, "license_type": "no_license", "max_line_length": 86, "num_lines": 34, "path": "/cs143B/project3/logger.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <iomanip>\n#ifndef LOGGER_H\n#define LOGGER_H\nclass LoggerImpl;\nclass LoggerFactory {\npublic:\n\tclass Ilogger\n\t{\n\tpublic:\n\t\tvirtual void log(std::string tag, std::string message) = 0;\n\t};\n\n\tstatic Ilogger *GetLogger();\nprivate:\n\tclass LoggerImpl : public Ilogger {\n\tpublic:\n\t\tLoggerImpl(std::string _file) : file(std::ofstream(_file)) {\n\n\t\t}\n\t\t~LoggerImpl() {\n\t\t\tfile.close();\n\t\t}\n\t\tvoid log(std::string tag, std::string message) {\n\t\t\tfile << \"[\" << tag << std::setw(30 - tag.length()) << \"]:\" << message << std::endl;\n\t\t}\n\tprivate:\n\t\tstd::ofstream file;\n\t};\n\tstatic LoggerImpl *_log;\n};\n#endif" }, { "alpha_fraction": 0.7286585569381714, "alphanum_fraction": 0.7286585569381714, "avg_line_length": 26.33333396911621, "blob_id": "dd5042c8c0ab43fe213c5f3aca15aa75a56785ca", "content_id": "4a4c220264dd7ae30ffc709acbe8b7c06d3d2f3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 328, "license_type": "no_license", "max_line_length": 65, "num_lines": 12, "path": "/cs143B/project3/logger.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include \"logger.h\"\n\nLoggerFactory::LoggerImpl *LoggerFactory::_log = nullptr;\nLoggerFactory::Ilogger* LoggerFactory::GetLogger() {\n\tif (LoggerFactory::_log == nullptr) {\n\t\tLoggerFactory::_log = new LoggerFactory::LoggerImpl(\"log.txt\");\n\t}\n\treturn LoggerFactory::_log;\n}\t" }, { "alpha_fraction": 0.5686870813369751, "alphanum_fraction": 0.5766440629959106, "avg_line_length": 29.304964065551758, "blob_id": "6004cb170da3bf5dc2ed717c38750a6975032ff3", "content_id": "02bdb89e3841372952ff355befdffc791e28efa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4273, "license_type": "no_license", "max_line_length": 79, "num_lines": 141, "path": "/cs141/project1/src/statements.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef STATEMENT_H\n#define STATEMENT_H\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n#include \"grammer.hpp\"\n#include \"writer.hpp\"\n\nclass Statement : public Grammar\n{\npublic:\n\tStatement(std::string line) : _msLine(line), isInStatement(false) { }\n\tvirtual ~Statement() = 0;\n\tvirtual Grammar* parse() = 0;\n\tvirtual std::vector<std::string>* getKeywords() = 0;\n\tbool isExpr(std::string s) {\n\t\tstd::string output = \"\";\n\t\treturn isExpr(s, output);\n\t};\n\tbool isExpr(std::string s, std::string& w) {\n\t\tstd::string ops = \"+-\";\n\t\tbool good = true;\n\t\ts.erase(std::remove(s.begin(), s.end(), ' '), s.end());\n\t\t// Recursive branching.\n\t\t// If we have a line with a data read in it (e.g. D[]) then \n\t\t// we need to make sure there is no sign of an operator. else\n\t\t// wait until the data read is parsed out\n\t\tif (s.find_first_of(ops) != std::string::npos) {\n\t\t\tgood = handleOpsBubble(s, ops, true);\n\t\t}\n\t\telse {\n\t\t\tgood = isTerm(s, w);\n\t\t\tif (good && !isInStatement) std::cout << \"Expr\\n\" << w << std::endl;\n\t\t\telse if (good && isInStatement) std::cout << w << std::endl; \n\t\t\tif (s[0] == 'D' && s.find_first_of(ops) == std::string::npos) {\n\t\t\t\tisInStatement = false;\n\t\t\t\tgood = isExpr(s.substr(2, s.find(']') - 2));\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn good;\n\t};\n\tbool isTerm(const std::string& s, std::string& w) {\n\t\tstd::string ops = \"*%/\";\n\t\tbool good = true;\n\t\tif (s[0] != 'D' && (s[0] == '(' || s.find(')') != std::string::npos)) {\n\t\t\t// parse out the parens and be done.\n\t\t\tstd::string copy = s;\n\t\t\tif (s[0] == '(') {\n\t\t\t\tcopy = copy.substr(copy.find('(') + 1);\n\t\t\t} else {\n\t\t\t\tcopy = copy.substr(0, copy.find(')'));\n\t\t\t}\n\t\t\tw = \"\";\n\t\t\tisInStatement = false;\n\t\t\tisExpr(copy);\n\t\t\tgood = true;\n\t\t}\n\t\telse if (s[0] != 'D' && s.find_first_of(ops) != std::string::npos) {\n\t\t\t// process as normal;\n\t\t\tisInTerm = true;\n\t\t\tstd::string copy = s + ops[0];\n\t\t\tcopy.erase(std::remove(copy.begin(), copy.end(), ']'), copy.end());\n\t\t\tsize_t pos = copy.find_first_of(ops);\n\t\t\twhile (pos != std::string::npos && good) {\n\t\t\t\tisFactor(copy.substr(0, pos), w);\n\t\t\t\tcopy.erase(0, pos + 1);\n\t\t\t\tpos = copy.find_first_of(ops);\n\t\t\t\tif (copy.find_first_of(ops) != std::string::npos) w = \"\\n\" + w;\n\t\t\t}\n\t\t\tisInTerm = false;\n\t\t\tw = \"Term\\n\" + w;\n\t\t}\n\t\telse {\t\n\t\t\tgood = isFactor(s, w);\n\t\t\tif (good && !isInTerm) w = \"Term\\n\" + w;\n\t\t}\n\t\treturn good;\n\t};\n\tbool isNumber(const std::string& s, std::string& w) {\n\t\tstd::string::const_iterator it = s.begin();\n\t\twhile (it != s.end() && std::isdigit(*it) != false) { it++; }\n\t\tbool good = !s.empty() && it == s.end();\n\t\tif (good) w = \"Number\" + w;\n\t\treturn good;\n\t};\n\tbool isFactor(const std::string& s, std::string& w) {\n\t\tbool good = s[0] == 'D' ? true : isNumber(s, w); \n\t\tif (good && s[0] != 'D') w = \"Factor\\n\" + w;\n\t\telse w = \"Factor\"; \n\t\treturn good;\t \n\t};\n\tbool isKeyword(const std::string& s) {\n\t\tgetKeywords();\n\t\tstd::vector<std::string> *keywordsPtr = _mvKeywords;;\n\t\tif (keywordsPtr == NULL) return false;\n\t\tstd::vector<std::string> keywords = *keywordsPtr;\n\t\tbool good = std::find(keywords.begin(), keywords.end(), s) != keywords.end();\n\t\treturn good;\n\t}\n\tbool getArguments(std::string line, std::string *arg1, std::string *arg2) {\n\t\tstd::string left = \"default\";\n\t\tsize_t pos = line.find(\",\");\n\t\tif (pos == std::string::npos) return false;\n\t\twhile (pos != std::string::npos) {\n\t\t\t*arg1 = line.substr(0, pos);\n\t\t\tline.erase(0, pos + 1);\n\t\t\tpos = line.find(\",\");\n\t\t} \n\t\tif (line[0] == ' ') line.erase(0, 1);\n\t\t*arg2 = line;\n\t\treturn true;\n\t}\nprotected:\n\tstd::string _msLine;\n\tstd::vector<std::string> *_mvKeywords;\nprivate: \n\tbool isInStatement; \n\tbool handleOpsBubble(const std::string& s, std::string ops, bool op) {\n\t\tstd::string copy = s + ops[0];\n\t\tbool good = true;\n\t\tstd::string output=\"\";\n\t\tsize_t pos = copy.find_first_of(ops);\t\n\t\tif (op) { if (s[0] != '(') { std::cout << \"Expr\" << std::endl; }}`\n\t\telse std::cout << \"Term\" << std::endl;\n\t\twhile (pos != std::string::npos && good) {\n\t\t\tstd::string temp = copy.substr(0, pos);\n\t\t\tisInStatement = true;\t\n\t\t\tgood = temp[0] == 'D' ? isExpr(temp) : isTerm(temp, output);\n\t\t\tcopy = copy.erase(0, pos + 1);\n\t\t\tpos = copy.find_first_of(ops);\n\t\t\tif (output != \"\") std::cout << output << std::endl;\n\t\t\toutput = \"\";\t\n\t\t} \n\t\treturn good;\t\t\n\t}\n};\n\ninline Statement::~Statement() {}\n#endif\n" }, { "alpha_fraction": 0.5927910208702087, "alphanum_fraction": 0.6054554581642151, "avg_line_length": 21.560440063476562, "blob_id": "c2ec143d489909b369312b0134e0462916e1c0df", "content_id": "739e94f65f1b79c1e6cd97522950ab706a58c395", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2053, "license_type": "no_license", "max_line_length": 68, "num_lines": 91, "path": "/cs143A/project4/pthread_compute/pthread_compute.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer, 22514022\n#include <stdlib.h>\n#include <math.h>\n#include <stdio.h>\n#include <pthread.h>\n\n#define NUM_THREADS 3\n\ntypedef struct threadargs_s {\n\tint *begin;\n\tint *end;\n\tlong tid;\n\tint sum;\n\tint min;\n\tint max;\n} threadargs_t;\n\nvoid *getAverage(void *args) {\n\tthreadargs_t *data = (threadargs_t *)args;\n\twhile (data->begin != data->end) {\n\t\tint val = *data->begin;\n\t\tdata->sum += val; \n\t\tdata->begin++;\n\t\tif (val > data->max) {\n\t\t\tdata->max = val; \n\t\t} \n\t\tif (val < data->min) {\n\t\t\tdata->min = val; \n\t\t}\n\t}\n\tif(data->tid != 4) pthread_exit(args); \n\treturn NULL;\n}\n\nthreadargs_t *makeData(long id, int data[], int ops) {\n\tthreadargs_t *arg = malloc(sizeof(threadargs_t));\n\targ->tid = id + 1;\n\targ->begin = &data[id * ops];\n\targ->end = &data[(1 + id) * ops];\n\targ->sum = 0;\n\targ->min = BUFSIZ; \n\targ->max = -1 * BUFSIZ;\n\treturn arg; \n}\n\nint main() {\n\tchar name[BUFSIZ];\n\tint data[BUFSIZ];\n\tint i = 0, j = 0, globmin, globmax;\n\tfloat avg = 0.0f;\n\twhile (fgets(name, BUFSIZ, stdin) != NULL) {\n\t\tif (name[0] == '\\n') continue;\n\t\tdata[i++] = strtol(name, NULL, 10);\n\t}\n\n\t// make threads\n\tint opsPerThread = floor(i / (NUM_THREADS + 1));\n\tpthread_t threads[NUM_THREADS];\n\tthreadargs_t *args[NUM_THREADS + 1];\n\t\n\t// joinablility in threads.\n\tpthread_attr_t attr;\n\tpthread_attr_init(&attr);\n\tpthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\t\n\tfor (j = 0; j < NUM_THREADS; j++) {\n\t\targs[j] = makeData(j, data, opsPerThread);\n\t\tpthread_create(&threads[j], &attr, getAverage, (void *) args[j]); \n\t}\n\n\t// do main thread.\n\targs[j] = makeData(j, data, opsPerThread);\n\targs[j]->end = &data[i];\n\tgetAverage((void *) args[j]);\n\tavg += args[j]->sum;\n\tglobmin = args[j]->min;\n\tglobmax = args[j]->max;\t\n\n\t// join and exit\n\tfor (j = 0; j < NUM_THREADS; j++) {\n\t\tpthread_join(threads[j], NULL);\n\t\tavg += args[j]->sum;\n\t\tglobmin = globmin > args[j]->min ? args[j]->min : globmin;\n\t\tglobmax = globmax < args[j]->max ? args[j]->max : globmax;\n\t\tfree(args[j]);\n\t}\n\tprintf(\"Max:%i\\nMin:%i\\nAverage:%f\", globmax, globmin, avg / i);\n\n\t// free my data\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5255748629570007, "alphanum_fraction": 0.5457531809806824, "avg_line_length": 17.692981719970703, "blob_id": "fe475ebbb2309d45a01761a4fad901634be1065b", "content_id": "74578c1a5ea97701ff381680ba9126a3e1d1e4e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2131, "license_type": "no_license", "max_line_length": 80, "num_lines": 114, "path": "/cs143A/project5/que.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer\n// 22514022\n#include <stdio.h>\n#include <stdlib.h>\n#include \"que.h\"\n#include <pthread.h>\n#include <semaphore.h>\n#include <time.h>\n\nstatic ELE _que[QUE_MAX];\nstatic int _front = 0, _rear = 0;\nextern int producers_working;\n\nstatic int matches = 0;\n\npthread_mutex_t m;\nsem_t sem_full;\nsem_t sem_empty;\nvoid add_match()\n{\n //Note: you will need to lock this update because it is a race condition\n pthread_mutex_lock(&m);\n matches++;\n pthread_mutex_unlock(&m);\n}\n\nvoid report_matches(char *pattern)\n{\n printf(\"Found %d total matches of '%s'\\n\", matches, pattern);\n}\n\nint que_init()\n{\n\tpthread_mutex_init(&m, NULL);\n\tsem_init(&sem_full, 0, 0);\n\tsem_init(&sem_empty, 0, 0);\n}\n\nvoid que_error(char *msg)\n{\n fprintf(stderr, \"***** Error: %s\\n\", msg);\n // exit(-1);\n}\n\nint que_is_full()\n{\n return (_rear + 1) % QUE_MAX == _front; /* this is why one slot is unused */\n}\n\nint que_is_empty()\n{\n return _front == _rear;\n}\n\nvoid que_enq(ELE v)\n{\n if (que_is_full())\n\tsem_wait(&sem_empty);\n int max = 1000000, i = 0;\n while(que_is_full() && i < max)\n\t;\n\t// que_error(\"Enqueue on full queue\");\n pthread_mutex_lock(&m);\n _que[_rear++] = v;\n if ( _rear >= QUE_MAX )\n _rear = 0;\n pthread_mutex_unlock(&m);\n if (que_is_full()) sem_post(&sem_full);\n}\n\nELE que_deq()\n{\n if (producers_working && que_is_empty()) { \n\tstruct timespec s;\n\ts.tv_sec = 1;\n\ts.tv_nsec = 1;\n\tint r;\n\tif ((r = sem_timedwait(&sem_full, &s)) == -1) {\n\t\treturn (ELE){.string = \" \"};\n\t} \n }\n int max = 10000000, i=0;\n while (que_is_empty() && i < max)\n\t;\n if (i == max) return (ELE){.string = \" \"};\n pthread_mutex_lock(&m);\n int x = _front;\n _front++;\n ELE ret = _que[x];\n _que[x].string[0] = '\\0';\n if ( _front >= QUE_MAX )\n _front = 0;\n pthread_mutex_unlock(&m);\n if (que_is_empty()) \n \tsem_post(&sem_empty);\n return ret;\n}\n\n\n/*\n\nint main()\n{\n for ( int i=0; i<QUE_MAX-1; ++i )\n {\n Buffer b;\n sprintf(&b.string, \"%d\", i);\n que_enq(b);\n }\n while ( !que_is_empty() )\n printf(\"%s \", que_deq().string);\n putchar('\\n');\n}\n*/\n" }, { "alpha_fraction": 0.4915773272514343, "alphanum_fraction": 0.5375191569328308, "avg_line_length": 33.3684196472168, "blob_id": "1dd10150c877dc00679219b35ffcd6bae3776ac0", "content_id": "d0620eeb6ca4c482d49e3880e93e406f82dc8956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 63, "num_lines": 19, "path": "/cs177/hw4/ig.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "from temp import p\nimport numpy as np\nfrom math import log\n\ta\n\tb\ndef tt(x,c):\n\tpxc = np.array([p(x,y,c) for y in [0,1]])\n\tpx = np.array([p(x,y,a) for y in [0,1] for a in [0,1] ])\n\tpc = np.array([p(a,y,c) for y in [0, 1] for a in [0, 1] ])\n\treturn np.sum(pxc) * log( np.sum(pxc) / (np.sum(px * pc)) , 2)\n\ndef t(y, c):\n\tpyc = np.array([p(x,y,c) for x in [0,1]])\n\tpy = np.array([p(x,y,a) for x in [0,1] for a in [0,1] ])\n\tpc = np.array([p(x,a,c) for x in [0, 1] for a in [0, 1] ])\n\treturn np.sum(pyc) * log( np.sum(pyc) / (np.sum(py * pc)) , 2)\n\nprint np.sum([tt(x,c) for x in [0, 1] for c in [0 ,1]])\nprint np.sum([t(y,c) for y in [0, 1] for c in [0,1]])\n" }, { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 15.285714149475098, "blob_id": "5d2948082641409f56a1a7ad45df7f72e1898b32", "content_id": "8068c230787d266ee2bf707d72ae05f4bb5656ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 228, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/cs141/project1/src/set.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef SET_H\n#define SET_H\n#include <string>\n#include <vector>\n#include \"statements.hpp\"\nclass Set : public Statement\n{\npublic:\n\tSet(std::string);\n\t~Set();\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n};\n#endif\n" }, { "alpha_fraction": 0.5125725269317627, "alphanum_fraction": 0.5261121988296509, "avg_line_length": 18.846153259277344, "blob_id": "6efcb8cc7934f46865c9fa819145727f82d13911", "content_id": "30f4d89c935cb52bc5dea50c5b60224399b9cec3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 517, "license_type": "no_license", "max_line_length": 60, "num_lines": 26, "path": "/cs146/hw5/main.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include \"parser.h\"\n#include \"engine.h\"\n\nint main(int argc, string* argv, string *env) {\n int read;\n size_t len = 0;\n string line;\n if (argc == 1) {\n printf(\"? \");\n fflush(stdout);\n }\n FILE *fp = argc == 1 ? stdin : fopen(argv[argc -1], \"r\");\n while((read = getline(&line, &len, fp)) != -1) {\n \t\tjob_t *job = parse(len, line);\n \t\tprocess_job(job, env);\n\t\tfree(job);\n\t\tif (argc == 1) {\n\t\t\tprintf(\"? \");\n\t\t}\n }\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6133942008018494, "alphanum_fraction": 0.6286149024963379, "avg_line_length": 21.689655303955078, "blob_id": "7dc6abef891c52e251eaa97d0654a6ffb55b1be9", "content_id": "67f933b87e53f7e2f7300be089bb58f2b451a5dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 657, "license_type": "no_license", "max_line_length": 59, "num_lines": 29, "path": "/cs143B/project2/io/iosystem_impl.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include <iostream>\n#include \"iosystem.h\"\n#include \"iosystem_impl.h\"\n\nint IO_system_impl::get_ith_block(int i) {\n\treturn i * BLOCK_SIZE;\n}\n\nvoid IO_system_impl::read_block(int i, unsigned char *p) {\n\t// skew our index to the correct distance.\n\tint block = get_ith_block(i);\n\tfor (int i = 0; i < BLOCK_SIZE; i++) {\n\t\t*(p + i) = ldisk[block + i];\n\t}\n}\n\nvoid IO_system_impl::write_block(int i, unsigned char *p) {\n\t// skew our index to the correct distance.\n\tint block = get_ith_block(i);\n\tfor (int i = 0; i < BLOCK_SIZE; i++) {\n\t\tldisk[block + i] = *(p + i);\n\t}\n}\n\nIO_system *IO_system::CreateIOSystem() {\n\treturn new IO_system_impl();\n}" }, { "alpha_fraction": 0.5098846554756165, "alphanum_fraction": 0.530889630317688, "avg_line_length": 23.03960418701172, "blob_id": "b879c08294ad79b790d702addb546c6b29c8d25b", "content_id": "6e1fc9fbef51592ed9175ba204d71ccf4c17eecf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2428, "license_type": "no_license", "max_line_length": 88, "num_lines": 101, "path": "/cs143A/project6/banker.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer\n// 22514022\n// Simple implementation of bankers algorithm.\n// Program only needs to determine the state of a resource allocation.\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\nint arrayLessThan(int *X, int *Y, int P) {\n\tint i = 0;\n\tfor (i = 0; i < P; i++)\n\t\tif (Y[i] < X[i])\n\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid printWork(int R, int *work) {\n\tint i = 0;\n\tfor(; i < R; i++)\n\t\tprintf(\"%d\\t\", work[i]);\n\tprintf(\"\\n\\n\");\n}\n\nint findI(int P, int R, int need[][R], int *work, int *finished, int *ret) {\n\tint i = 0;\n\t*ret = -1;\n\tfor (i = 0; i < P; i++) {\n\t\tif (finished[i] == 0 && arrayLessThan(need[i], work, R)) {\n\t\t\t*ret = i;\n\t\t\tprintf(\"Process%d is good\\n\", i + 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn i != P ? 1 : 0;\n}\n\nint safety(int P, int R, int max[][R], int alloc[][R], int *aval, int need[][R]) {\n\t// Assuming Work = Available.\n\tint work[R], totalalloc[R], finished[P], i = 0, j = 0; \n\tmemset(finished, 0, sizeof(finished));\n\tmemset(work, 0, sizeof(finished));\n\tmemset(totalalloc, 0, sizeof(totalalloc));\n\t// calculate the total allocated resources\n\t// onced we finished, read values\n\t\n\t// The actual amount of work is equal to the total available resources minus the amount\n\t// already allocated. \n\tfor (j = 0; j < R; j++)\n\t\tfor (i = 0; i < P; i++)\n\t\t\ttotalalloc[j] += alloc[i][j];\n\n\tfor (i = 0; i < R; i++)\n\t\twork[i] = aval[i] - totalalloc[i];\n\n\tj = 0;\n\twhile (1) {\n\t\tint val;\n\t\tif (findI(P, R, need, work, finished, &val)) {\t\n\t\t\tfinished[val] = 1;\n\t\t\tj++;\n\t\t\tprintf(\"------work-------\\n\");\n\t\t\tprintWork(R, work);\n\t\t\tprintf(\"-----alloc-------\\n\");\n\t\t\tprintWork(R, alloc[val]);\n\t\t\tfor(i = 0; i < R; i++)\n\t\t\t\twork[i] += alloc[val][i];\n\t\t}\t\t\n\t\tif (val == -1) break;\t\n\t}\n\treturn j == P ? 1 : 0;\t\n}\n\nint main() {\n\tint P = 0, R = 0, i = 0, j = 0;\n\t// read in P, R\n\tscanf(\"%d\", &P);\n\tscanf(\"%d\", &R);\n\tif (P < 0) perror(\"No process count\"), exit(-1);\n\tif (R < 0) perror(\"No resouce count\"), exit(-1);\n\tint max[P][R], alloc[P][R], aval[R], need[P][R];\t\n\tfor (i = 0; i < R; i++)\n\t\tscanf(\"%d\", &aval[i]);\n\n\tfor (i = 0; i < P; i++)\n\t\tfor (j = 0; j < R; j++)\n\t\t\tscanf(\"%d\", &alloc[i][j]);\n\n\tfor (i = 0; i < P; i++)\n\t\tfor (j = 0; j < R; j++)\n\t\t\tscanf(\"%d\", &max[i][j]);\n\n\tfor (i=0; i < P; i++)\n\t\tfor (j = 0; j < R; j++) \n\t\t\tneed[i][j] = max[i][j] - alloc[i][j];\n\tif (safety(P, R, max, alloc, aval, need)) {\n\t\tprintf(\"The system is in a safe state\\n\");\n\t} else {\n\t\tprintf(\"The system is in an unsafe state\\n\");\n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6114732623100281, "alphanum_fraction": 0.633637547492981, "avg_line_length": 16.044445037841797, "blob_id": "dff8c78e2ff9db2b7cd3dd60731e1d7c27ee2bfa", "content_id": "6fe2e73073a945eb069482280bd385d9f2c188a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 767, "license_type": "no_license", "max_line_length": 60, "num_lines": 45, "path": "/cs146/hw4/C-interp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nerror() {\n\techo $1 >&2\n\tcleanup\n\texit $2\n}\n\n# prepare\n#\tprepares our compelation process\nprepare() {\n\tif [ ! -f $1 ]; then\n\t\terror \"File $1 does not exist\" -1\n\tfi\n clean=`echo $1 | sed 's/\\.\\///'`\n\ttmp=`mktemp -dt ${clean}XXXXX`\n}\n\n# interpret\n#\truns the compiler on the .c file and executes it.\ninterpret() {\n\texecname=$1\n\tfilename=$2\n\tscriptloc=$3\n\ttmpdir=$4\n\tshift 4\n\t/usr/bin/gcc -o \"$tmpdir/$execname\" \"$scriptloc/$filename\";\n\tif [[ $? -eq 0 ]]; then\n\t\t$tmpdir/$execname \"$@\" \n\telse\n\t\terror \"Error in gcc compiler\" -3\n\tfi\n}\n\n# cleanup\n#\tcleanup the resulting files in the tmp directory\ncleanup() {\n\t/bin/rm -rf $tmp\n}\n\ntrap '{cleanup; exit 1}' SIGHUP SIGINT SIGQUIT SIGTERM\ncprog=\"$0.c\"\nprepare $cprog\ninterpret $0 $cprog $PWD $tmp \"$@\"\ncleanup\n" }, { "alpha_fraction": 0.5485829710960388, "alphanum_fraction": 0.5538461804389954, "avg_line_length": 23.215686798095703, "blob_id": "a021f27709df50192f082d7adb8713b7203f6815", "content_id": "cf1713445526b9dc30b8b81e28d7eb66fa9eb4ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 64, "num_lines": 102, "path": "/cs142A/com/uci/cs142A/src/crux/SymbolTable.java", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "package crux;\n\nimport java.util.LinkedHashMap;\nimport java.util.Map;\npublic class SymbolTable {\n public static String studentName = \"Ian Schweer\";\n public static String studentID = \"22514022\";\n public static String uciNetID = \"ischweer\";\n private Map<String, Symbol> symbols;\n private SymbolTable parent;\n private int depth;\n public SymbolTable()\n {\n this.symbols = new LinkedHashMap<>();\n this.depth = 0;\n this.parent = null;\n }\n\n public SymbolTable(SymbolTable parent) {\n this.parent = parent;\n this.symbols = new LinkedHashMap<>();\n this.depth = parent.getDepth() + 1;\n }\n\n public int getDepth() {\n return depth;\n }\n\n public SymbolTable getParent() {\n return parent;\n }\n\n public Symbol lookup(String name) throws SymbolNotFoundError\n {\n if (symbols.containsKey(name)) {\n return symbols.get(name);\n } else {\n SymbolTable x = getParent();\n while (x != null) {\n if (x.symbols.containsKey(name))\n return x.symbols.get(name);\n x = x.getParent();\n }\n throw new SymbolNotFoundError(name);\n }\n }\n \n public Symbol insert(String name) throws RedeclarationError\n {\n if (!symbols.containsKey(name)) {\n Symbol symbol = new Symbol(name);\n symbols.put(name, symbol);\n return symbol;\n } else {\n throw new RedeclarationError(symbols.get(name));\n }\n }\n \n public String toString()\n {\n StringBuffer sb = new StringBuffer();\n if (parent != null)\n sb.append(parent.toString());\n \n String indent = new String();\n for (int i = 0; i < depth; i++) {\n indent += \" \";\n }\n \n for (Symbol s : this.symbols.values())\n {\n sb.append(indent + s.toString() + \"\\n\");\n }\n return sb.toString();\n }\n}\n\nclass SymbolNotFoundError extends Error\n{\n private static final long serialVersionUID = 1L;\n private String name;\n \n SymbolNotFoundError(String name)\n {\n this.name = name;\n }\n \n public String name()\n {\n return name;\n }\n}\n\nclass RedeclarationError extends Error\n{\n private static final long serialVersionUID = 1L;\n\n public RedeclarationError(Symbol sym)\n {\n super(\"Symbol \" + sym + \" being redeclared.\");\n }\n}\n" }, { "alpha_fraction": 0.664345383644104, "alphanum_fraction": 0.688022255897522, "avg_line_length": 26.615385055541992, "blob_id": "1f40b3fdbabcc373c6793a66db79299efa0cb9ce", "content_id": "ab751cd367a1581b6225798b3656696767889f7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 718, "license_type": "no_license", "max_line_length": 84, "num_lines": 26, "path": "/cs178/hw2/two.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import mltools as ml\nimport mltools.linear\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nks = [1,3,5,7,10,18]\nerr = []\nlrData = []\ndata = np.genfromtxt(\"data/curve80.txt\", delimiter=None)\nX = data[:,0]\nX = X[:,np.newaxis]\nY = data[:,1]\nXtr, Xte, Ytr, Yte = ml.splitData(X, Y, 0.75)\nfor i,k in enumerate(ks):\n\tnFolds = 5\n\n\tXtrP = ml.transforms.fpoly(Xtr, k, bias=False)\n\tXtrP,params = ml.transforms.rescale(XtrP)\n\tPhi = lambda X : ml.transforms.rescale(ml.transforms.fpoly(X, k, False), params)[0]\n\tfor iFold in range(nFolds):\n\t\tXti,Xvi,Yti,Yvi = ml.crossValidate(Xtr, Ytr, nFolds, iFold)\n\t\tlearner = ml.linear.linearRegress(Phi(Xti), Yti)\n\t\terr.append(learner.mse(Phi(Xvi), Yvi))\n\n\tplt.semilogy(err)\n\tplt.show()\n" }, { "alpha_fraction": 0.5630303025245667, "alphanum_fraction": 0.5769696831703186, "avg_line_length": 30.428571701049805, "blob_id": "cf4891ec7d2cfc1fa5a9ad78fa5c9d45a032e30e", "content_id": "048d800046b1b190f33387493f28b109520b3535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3300, "license_type": "no_license", "max_line_length": 130, "num_lines": 105, "path": "/cs146/hw3/lss", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Ian Schweer\n# 22514022\n\n# do we have any options?\nflags=0 #indicates if we have any flags throughout the program\nusel=1 #indicates if we need to use the -l option\nuseS=1 #indicates if we need to use the -S option\nflagdata=\"\" #A collection of all the user input flags we use\nwhile getopts \":aAbBcCdDfFgGhHiIklLmnNopqQrRsStTuUvwxX1Z\" var; do\n\tflags=1\n echo \"The arg is $var\"\n\tcase $var in\n\t\tl)\n\t\t\tusel=0\n\t\t\tflagdata=\"$flagdata$var\"\n\t\t\t;;\n\t\tS)\n\t\t\tuseS=0\n\t\t\tflagdata=\"$flagdata$var\"\n\t\t\t;;\n\t\ts)\n # -s should be ignored because it will print out the file size, which can mess up our sort since -l already prints it.\n\t\t\techo \"-s is not a valid argument. Exiting\">&2\n exit -1\n\t\t\t;;\n\t\ti)\n # -i should be ignored because it will print out the inode number before anything else, messing up our filter\n\t\t\techo \"-i is not a valid argument. Exiting\">&2\n exit -2\n\t\t\t;;\n\t\tg)\n # -g should be ignored? According to the assignment it will, I don't understand why. It simply hides the user.\n\t\t\techo \"-g is supposed to be ignored. I do not agree with this, but I will exit anyway\">&2\n exit -3\n\t\t\t;;\n\t\tf)\n # -f will screw everything up, because it tells ls not to sort\n\t\t\techo \"-f is not supported. Please use /bin/ls if you want -f\">&2\n exit -4\n\t\t\t;;\n\t\tC)\n # -C will screw up the sorting, it will override S\n\t\t\techo \"-C will put everything into columns, causing issues with grep. Exiting\">&2\n exit -5\n\t\t\t;;\n\t\tX)\n # -X will screw up the sorting, it will override S\n\t\t\techo \"-X will override the sort used in lss. Please use /bin/ls if you want the -X flag\">&2\n exit -6\n\t\t\t;;\n\t\td)\n # d will be useful if I need only directories, but I want the opposite\n\t\t\techo \"-d will only print directories. Ignoring\">&2\n exit -7\n\t\t\t;;\n\t\tm)\n # m will cause all files to be comma separated.\n\t\t\techo \"-m will cause all files to outputed with comma seperation. Ignoring this\">&2\n exit -8\n\t\t\t;;\n t)\n # t will attempt to sort by time\n echo \"-t will overwrite the sort I am using\">&2\n exit -9\n ;;\n u)\n # -u can change sort, i'm just going to ignore it\n echo \"-u could mess up sort depending on the other flags. I'm ignoring it. Please use /bin/ls if you need it\">&2\n exit -10\n ;;\n v)\n # -v will mess up my sort.\n echo \"-v because of the 'natural sort'. Please use /bin/ls for it\">&2\n exit -11\n ;;\n U)\n # -U will tell the shell NOT to sort\n echo \"-U will force all sort to go away\">&2\n exit -12\n ;;\n \\?)\n echo \"Ignoring unknown parameter at position $OPTIND\"\n ;;\n\t\t*)\n\t\t\tflagdata=\"$flagdata$var\"\n\t\t\t;;\n\tesac\ndone\nif [[ $flags -eq 1 ]]; then\n # shift arguments by getopts variable which indicates the last positional parameter looked at \n shift `expr $OPTIND - 1`\n\tif [[ $useS -eq 1 ]]; then\n # append the S flag\n\t\tflagdata=\"S$flagdata\"\n\tfi\n\tif [[ $usel -eq 1 ]]; then\n # append the l flag\n\t\tflagdata=\"l$flagdata\"\n\tfi\n\tls \"-$flagdata\" \"$@\" | grep ^-\nelse\n\t# default behavior\n\tls -lS \"$@\" | grep ^-\nfi\n" }, { "alpha_fraction": 0.627173900604248, "alphanum_fraction": 0.64673912525177, "avg_line_length": 26.058822631835938, "blob_id": "062a3e7b31228e41a8b4796a3644048c50eed979", "content_id": "5350cb8b826a8680f5c3be70e5ec02e11bf6c696", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "no_license", "max_line_length": 112, "num_lines": 34, "path": "/cs177/hw6/mc_simulator.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n# implementation of the power method.\nimport numpy as np\n\n# get input for an MxM matrix\ninput=raw_input\nM=int(input(\"Please enter M: \"))\np0 = [float(x) for x in input(\"Please enter p0, initial probability distro:\").split()]\nstate_transition = [[float(x) for x in input(\"Please enter line \" + str(i) + \": \").split()] for i in range(0,M)]\nmoney=int(input(\"Enter current amount of money: \"))\nn=int(input(\"Enter stopping point: \"))\nprint(i,n)\n# convert to numpy arrays\ni=money\np0 = np.array(p0)\nstate_transition = np.array(state_transition)\nlastp = p0\nfreqs=np.zeros(M)\nfor _ in range(0,5000):\n\twhile (i < n and i > 0):\n\t\tx = lastp*state_transition\n\t\tx=x[0]\n\t\tlastp = x \n\t\tif (x.argmax()):\n\t\t\ti = i + 1\n\t\t\t# print(\"Earned one dollar\",i)\n\t\telse:\n\t\t\ti = i - 1\t\n\t\t\t# print(\"Lost one dollar\",i)\n\t\tfreqs[x.argmax()] = freqs[x.argmax()] + 1\n\ti=money\n\nfreqs = [ x / np.sum(freqs) for x in freqs ]\nprint(freqs)\n" }, { "alpha_fraction": 0.5697748064994812, "alphanum_fraction": 0.5868238210678101, "avg_line_length": 23.74479103088379, "blob_id": "5733b4e8d86fd4375ebcf18e18fa114c6281587c", "content_id": "9f7a06bca939a6603f9a48ea53aec984d84ab01f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4751, "license_type": "no_license", "max_line_length": 109, "num_lines": 192, "path": "/cs146/hw5/engine.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include \"engine.h\"\n#include \"parser.h\"\n\n#define REDIR_INPUT 1\n#define REDIR_OUTPUT 2\n#define REDIR_APPEND 4\n/**\n * Method will fill buf with strings that are\n * ready for execvpe\n */\nvoid prepare(task_t *task, string *buf);\n\n/**\n * Method is a wrapper of prepare\n */\nvoid getargs(task_t *task, string **buf);\n\n/**\n * Method will handle spawning a process (essentially the fork and execr)\n */\nvoid forkandexec(task_t *t, string *env, int background);\n\n/**\n * Method will handle a pipe. For now only two.\n * When doing #6, this will have to change.\n * @TODO: #6\n */\nvoid handlepipe(job_t *job, string *envp);\n\n/**\n * Method will handle redirects.\n * The redirect member variable on the task\n * is a bit vector of three bits.\n * 1 = input\n * 2 = output\n * 4 = output append\n */\nvoid setupnshredirects(task_t *task);\n/**\n * @TODOS as of 25\n *\t3. do extras\n */\nvoid process_job(job_t *job, string *env) {\n\tif (job->task_count == 0) return;\n\tif (job->envvar) {\n\t\tif(putenv(job->tasks[0].cmd)) {\n\t\t\tperror(\"Could not set enviornment variable\");\n\t\t}\n\t} else {\n\t\tfor (int i = 0; i < job->task_count; i++) {\n\t\t\tif (!strcmp(job->tasks[i].cmd, \"exit\")) exit(0);\n\t\t}\n\t\tif (job->task_count > 1) {\n\t\t\tint id;\n\t\t\tif ((id = fork())) {\n\t\t\t\tif (!job->background) {\n\t\t\t\t\twait(NULL);\n\t\t\t\t\tfflush(stdout);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandlepipe(job, env);\n\t\t\t}\n\t\t} else {\n\t\t\tforkandexec(&job->tasks[0], env, job->background);\n\t\t}\n\t}\n}\n\nvoid prepare(task_t *task, string *buf) {\n\t// buf should be the correct size here.\n\tint i = 0;\n\tfor (; i < task->flag_size; i++) {\n\t\tbuf[i + 1] = malloc(sizeof(char) * strlen(task->flags[i]));\n\t\ttask->flags[i] = task->flags[i][0] == '$' ? task->flags[i]: getenv(&(task->flags[i][1]));\n\t\tstrcpy(buf[i + 1], task->flags[i]);\n\t}\n\tint temp = i;\n\tfor (; i < task->flag_size + task->arg_size; i++) {\n\t\tbuf[i + 1] = malloc(sizeof(char) * strlen(task->args[i - temp]));\n\t\ttask->args[i - temp] = task->args[i][0] != '$' ? task->args[i - temp] : getenv(&(task->args[i - temp][1]));\n\t\tstrcpy(buf[i + 1], task->args[i - temp]);\n\t}\t\n\tbuf[i + 1] = NULL;\n}\n\nvoid getargs(task_t *t, string **buf) {\n\tbuf[0] = malloc(sizeof(string) * (1 + t->flag_size + t->arg_size));\n\tbuf[0][0] = malloc(sizeof(char) * strlen(t->cmd));\n\tbuf[0][0] = t->cmd; \n\tprepare(t, buf[0]);\n}\n\nvoid forkandexec(task_t *t, string *env, int background) {\n\t// prepare all tasks.\n\tstring *args;\n\tgetargs(t, &args);\n\tint id;\n\tif ((id=fork())) {\n\t\tif (!background) {\n\t\t\twaitpid(id, NULL, 0);\n\t\t}\n\t} else {\n\t\tsetupnshredirects(t);\n\t\texecvpe(t->cmd, args, env);\n\t\tprintf(\"%s not found\\n\", t->cmd);\n\t\texit(-1);\n\t}\n}\n\nvoid handlepipe(job_t *job, string *envp) {\n\t// we have a pipe\n\tint fds[MAX_PIPE][2];\n\tstring *args;\n\tchar buf[BUFSIZ];\n\tfor (int i = 0; i < job->task_count - 1; i++) {\n\t\tpipe(fds[i]);\n\t}\n\tif (fork()) {\n\t\t// main guy.\n\t\tdup2(fds[0][1], fileno(stdout));\n\t\t// close the rest.\n\t\tfor (int i = 0; i < job->task_count - 1; i++) {\n\t\t\tclose(fds[i][0]); close(fds[i][1]);\n\t\t}\n\t\tgetargs(&job->tasks[0], &args);\n\t\tsetupnshredirects(&job->tasks[0]);\n\t\texecvpe(job->tasks[0].cmd, args, envp);\n\t\texit(-5);\n\t} else {\n\t\tint id, parent=(job->task_count-2) ? 0 : 1;\n\t\tfor (id = 1; id < job->task_count-1; id++) {\n\t\t\tif (fork()) {\n\t\t\t\t// parent will keep going\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tparent = id == (job->task_count - 1);\n\t\tif (!parent) {\n\t\t\tdup2(fds[id-1][0], fileno(stdin)); // input to output\n\t\t\tdup2(fds[id][1], fileno(stdout)); // output to input\n\t\t\tfor (int i = 0; i < job->task_count - 1; i++) {\n\t\t\t\tclose(fds[i][0]); close(fds[i][1]);\n\t\t\t}\n\t\t\tgetargs(&job->tasks[id], &args);\n\t\t\tsetupnshredirects(&job->tasks[id]);\n\t\t\texecvpe(job->tasks[id].cmd, args, envp);\n\t\t\texit(-6);\n\t\t} else {\n\t\t\tdup2(fds[id-1][0], fileno(stdin));\n\t\t\tfor (int i = 0; i < job->task_count - 1; i++) {\n\t\t\t\tclose(fds[i][0]); close(fds[i][1]);\n\t\t\t}\n\t\t\tgetargs(&job->tasks[id], &args);\n\t\t\tsetupnshredirects(&job->tasks[id]);\n\t\t\texecvpe(job->tasks[id].cmd, args, envp);\n\t\t\texit(-7);\n\t\t}\n\t\texit(0);\n\t}\n}\n\nvoid setupnshredirects(task_t *task) {\n\t// error check.\n\t// redirect would be 7 or 6 too cause this error\n\tif (task->redirect >= (REDIR_OUTPUT | REDIR_APPEND)) {\n\t\tperror(\"Cannot handle redirect output and append together\");\n\t\texit(-1); // this is okay, i'll be in a fork.\n\t}\n\n\tif (task->redirect & REDIR_INPUT) {\n\t\tFILE *fp = fopen(task->inputname, \"r\");\n\t\tdup2(fileno(fp), fileno(stdin));\n\t\tfclose(fp);\n\t} \n\n\tif (task->redirect & REDIR_OUTPUT) { \n\t\tFILE *fp = fopen(task->outputname, \"w\");\n\t\tdup2(fileno(fp), fileno(stdout));\n\t\tfclose(fp);\n\t} else if (task->redirect & REDIR_APPEND) {\n\t\tFILE *fp = fopen(task->outputname, \"a\");\n\t\tdup2(fileno(fp),fileno(stdout));\n\t\tfclose(fp);\n\t}\n}\n" }, { "alpha_fraction": 0.5993836522102356, "alphanum_fraction": 0.604519784450531, "avg_line_length": 22.469879150390625, "blob_id": "b1efdff55829afe9994b10e6fc1700dfb6ba9fce", "content_id": "d8919ca783ae6257065b50e5a78a083786ea586d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1947, "license_type": "no_license", "max_line_length": 113, "num_lines": 83, "path": "/cs143B/project3/tlb.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <string>\n#include \"tlb.h\"\n#include \"Logger.h\"\n\nconst int DEFAULT = -1;\n\ntlb::tlb() {\n\t// set default values.\n\tfor (int i = 0; i < BUFFER_SIZE; i++) {\n\t\tbuffer[i].sp = -1;\n\t\tbuffer[i].p = i;\n\t}\n}\n\nint tlb::get_frame_cache(int sp) {\n\tstd::string tag = CLASS_TAG + \"get_frame_cache()\";\n\tint f = DEFAULT, i = find_cached_object(sp);\n\tif (i > DEFAULT) {\n\t\tf = buffer[i].f;\n\t\tint current = buffer[i].p;\n\t\tbuffer[i].p = MAX_PRIORITY + 1;\n\t\tlower_priorities(current);\n\t\tLoggerFactory::GetLogger()->log(tag, \"Making buffer \" + std::to_string(i) + \" highest priority\");\n\t}\n\n\treturn f;\n}\n\nvoid tlb::set_frame_cache(int sp, int f) {\n\t// evict the lowest level cache\n\tint lowest = 0;\n\tfor (int i = 1; i < BUFFER_SIZE; i++) {\n\t\tif (buffer[i].sp == sp) {\n\t\t\t// we have this item in tlb already.\n\t\t\tlowest = i;\n\t\t\tbreak;\n\t\t} else {\n\t\t\tlowest = buffer[i].p < buffer[lowest].p ? i : lowest;\n\t\t}\n\t}\n\n\tLoggerFactory::GetLogger()->log(CLASS_TAG + \"set_frame_cache\", \"Evicting cache item \" + std::to_string(lowest));\n\tint current = buffer[lowest].p;\n\tbuffer[lowest].p = MAX_PRIORITY + 1;\n\tbuffer[lowest].sp = sp;\n\tbuffer[lowest].f = f;\n\tlower_priorities(current);\n}\n\nbool tlb::has_frame_cache(int sp) {\n\treturn find_cached_object(sp) > -1 ? true : false;\n}\n\nvoid tlb::lower_priorities(int lower_bound) {\n\tstd::string tag = CLASS_TAG + \"lower_priorities()\";\n\tfor (int i = 0; i < BUFFER_SIZE; i++) {\n\t\tif (buffer[i].p > lower_bound) {\n\t\t\tbuffer[i].p--;\n\t\t}\n\t\tstd::string msg = \"Making address \" + std::to_string(buffer[i].sp) + \"(\" + std::to_string(i) + \") \";\n\t\tmsg += \"to priority \" + std::to_string(buffer[i].p);\n\t\tLoggerFactory::GetLogger()->log(tag, msg);\n\t}\n}\n\nint tlb::find_cached_object(int sp) {\n\tint cached = DEFAULT;\n\tfor (int i = 0; i < BUFFER_SIZE; i++) {\n\t\tif (buffer[i].sp == sp) {\n\t\t\tcached = i;\n\t\t}\n\t}\n\treturn cached;\n}\n\nstd::string tlb::get_hit_string() {\n\treturn \"h \";\n}\n\nstd::string tlb::get_miss_string() {\n\treturn \"m \";\n}" }, { "alpha_fraction": 0.698113203048706, "alphanum_fraction": 0.698113203048706, "avg_line_length": 12.25, "blob_id": "cfd201d86763883748f9910c66b2249f303e5a71", "content_id": "5b2fb51512d87fd58b183b55ed3a5a3e52eae60e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 53, "license_type": "no_license", "max_line_length": 29, "num_lines": 4, "path": "/cs143A/project6/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "all:\n\tgcc -o banker banker.c -ggdb\nclean:\n\trm banker\n" }, { "alpha_fraction": 0.6089663505554199, "alphanum_fraction": 0.6313822865486145, "avg_line_length": 16.866666793823242, "blob_id": "9039c2eecdda17b791344ba80678b669e58cc31a", "content_id": "4e85b014c9989a8fca1c29b9d241683cdd598beb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 803, "license_type": "no_license", "max_line_length": 50, "num_lines": 45, "path": "/cs143B/project2/io/iosystem_impl.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include <iostream>\n#include <array>\n#include <cstdint>\n#include <cstdio>\n#include \"iosystem.h\"\n\n#ifndef IO_SYSTEM_IMPL_H\n#define IO_SYSTEM_IMPL_H\n\nclass IO_system_impl : public IO_system {\npublic:\n\t/**\n\t * Ready 8 bytes from index i, and stick them\n\t * in the char pointer.\n\t */\n\tvoid read_block(int i, unsigned char *p);\n\n\t/**\n\t * Writes the char *p to an \n\t */\n\tvoid write_block(int i, unsigned char *p);\nprivate:\n\t/**\n\t * Number of bytes in a block\n\t */\n\tconst int BLOCK_SIZE = 64;\n\n\t/**\n\t * ldisk is really a crap ton of bytes. \n\t *\n\t * There is a BIG distinction between bytes\n\t * and blocks. A block is __64__ *BYTES*\n\t */\n\tunsigned char ldisk[64 * 64];\n\n\t/**\n\t * get ith block\n\t *\n\t * Convience method. Recieves the i block (i * 8)\n\t */\n\tint get_ith_block(int i);\n};\n#endif" }, { "alpha_fraction": 0.5705363154411316, "alphanum_fraction": 0.582382082939148, "avg_line_length": 27.83850860595703, "blob_id": "cc15f38727f51ccb0de1ebf41c907a3b9f0dfddf", "content_id": "39616ef302fc28ad9fdc41463b0742ec925b8e4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4643, "license_type": "no_license", "max_line_length": 107, "num_lines": 161, "path": "/cs146/hw5/parser.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"parser.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n\n#define STATE_START_HOLD 0\n#define STATE_START 1\n#define STATE_CMD_HOLD 2\n#define STATE_CMD 3\n#define STATE_ARGS_HOLD 4\n#define STATE_ARGS 5\n#define STATE_REDIRECT_HOLD 6\n#define STATE_REDIRECT 7\n#define STATE_QUOTE_HOLD 8\n#define STATE_QUOTE 9\n\nint validate_state(int current) {\n\tswitch (current) {\n\t\tcase STATE_START_HOLD:\n\t\t\treturn STATE_START;\n\t\tcase STATE_CMD_HOLD:\n\t\t\treturn STATE_CMD;\n\t\tcase STATE_ARGS_HOLD:\n\t\t\treturn STATE_ARGS;\n\t\tcase STATE_REDIRECT_HOLD:\n\t\t\treturn STATE_REDIRECT;\n\t\tdefault:\n\t\t\treturn current;\n\t}\n}\nvoid copy_cmd(task_t *current_task, int bufsize, char buf[]) {\n\tcurrent_task->cmd = malloc(sizeof(char) * bufsize);\n\tstrcpy(current_task->cmd, buf); \n\tmemset(buf, 0, bufsize);\n}\n\nvoid copy_args(int bufsize, int *num_flags, int *num_args, char buf[], task_t *current_task) {\n\tstring *sink = buf[0] == '-' ? &(current_task->flags[0]) : &(current_task->args[0]);\n\tint *count = buf[0] == '-' ? num_flags : num_args;\n\tsink[(*count)] = malloc(sizeof(char) * bufsize);\n\tstrcpy(sink[(*count)++], buf);\n\tmemset(buf, 0, bufsize);\n}\n/**\n * parse \n *\tMethod will take in a line of input\n *\tand return a pathalogical concrete\n *\tsyntax tree. Each element in the \n *\tarray can be piped to the next\n *\titem in the list without worry.\n */\njob_t *parse(int len, string line) {\n\t// begin character by character\n\t// parse.\n\tint bufsize=0, state = STATE_START_HOLD, num_args = 0, num_flags = 0, redir = 0, jobsize = 1, readcmd = 0;\n\tchar *p = &(line[0]) - sizeof(char), buf[BUFSIZ];\n\ttask_t *current_task;\n\n\t// allocate our objects\n\tjob_t *job = malloc(sizeof(job_t));\n\tjob->background = 0;\n\tjob->envvar = 0;\n\tcurrent_task = &(job->tasks[0]);\n\tcurrent_task->redirect = 0;\n\tif (line[0] != '\\n') {\n\t\twhile(p++ != &(line[strlen(line)-1])) {\n\t\t\tswitch(*p) {\n\t\t\t\tcase ' ':\n\t\t\t\tcase '\\n':\n\t\t\t\t\t// we have hit a space.\n\t\t\t\t\tif (!readcmd && (state == STATE_START || state == STATE_QUOTE)) {\n\t\t\t\t\t\t// copy the buffer into our name.\n\t\t\t\t\t\tcopy_cmd(current_task, bufsize, buf);\n\t\t\t\t\t\tstate = STATE_CMD_HOLD;\n\t\t\t\t\t\tbufsize = 0;\n\t\t\t\t\t\treadcmd = 1;\n\t\t\t\t\t} else if (state == STATE_CMD || state == STATE_ARGS || state == STATE_QUOTE) {\n\t\t\t\t\t\t// copy the buffer into the appropiate place.\n\t\t\t\t\t\t// essentially this verbose line is equivalent to state -= 1\n\t\t\t\t\t\tcopy_args(bufsize, &num_flags, &num_args, buf, current_task);\n\t\t\t\t\t\tstate = state == STATE_CMD ? STATE_CMD_HOLD : STATE_ARGS_HOLD;\n\t\t\t\t\t\tbufsize = 0;\n\t\t\t\t\t} else if (state == STATE_REDIRECT && redir) {\n\t\t\t\t\t\tstring *sink = redir == 1 ? &(current_task->inputname) : &(current_task->outputname);\n\t\t\t\t\t\t// only take the first one\n\t\t\t\t\t\tsink[bufsize] = '\\0';\n\t\t\t\t\t\tif (!(current_task->redirect & redir)) {\n\t\t\t\t\t\t\tcurrent_task->redirect |= redir;\n\t\t\t\t\t\t\tsink[0] = malloc(sizeof(char) * bufsize);\n\t\t\t\t\t\t\tstrcpy(sink[0], buf);\n\t\t\t\t\t\t\tmemset(buf, 0, bufsize);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tredir = 0;\n\t\t\t\t\t\tbufsize = 0;\n\t\t\t\t\t} else if (state == STATE_QUOTE_HOLD) {\n\t\t\t\t\t\t// add it to the buffer\n\t\t\t\t\t\tbuf[bufsize++] = *p;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<':\n\t\t\t\tcase '>':\n\t\t\t\t\tredir = (*p == '<') ? 1 : (*(p + sizeof(char)) == '>') ? 4 : 2;\t\n\t\t\t\t\tstate = STATE_REDIRECT_HOLD;\n\t\t\t\t\tif (*p == '>' && *(p + sizeof(char)) == '>') {\n\t\t\t\t\t\t// we need to skip the current p.\n\t\t\t\t\t\tp++;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase '|':\n\t\t\t\t\t// we have hit a pipe!\n\t\t\t\t\tcurrent_task->flag_size = num_flags;\n\t\t\t\t\tcurrent_task->arg_size = num_args;\n\t\t\t\t\tjobsize++;\n\t\t\t\t\tif (jobsize >= MAX_PIPE) {\n\t\t\t\t\t\tperror(\"Too many pipes were allocated\");\n\t\t\t\t\t\texit(-1);\n\t\t\t\t\t}\n\t\t\t\t\tcurrent_task = &(job->tasks[jobsize - 1]);\n\t\t\t\t\tcurrent_task->redirect = 0;\n\t\t\t\t\treadcmd=0,bufsize=0, state = STATE_START_HOLD, num_args = 0, num_flags = 0, redir = 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '&':\n\t\t\t\t\tjob->background = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '=':\n\t\t\t\t\tjob->envvar=1;\n\t\t\t\t\tbuf[bufsize++] = *p;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\'':\n\t\t\t\t\tif (state == STATE_QUOTE_HOLD) {\n\t\t\t\t\t\tstate = STATE_QUOTE;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstate = STATE_QUOTE_HOLD;\n\t\t\t\t\t}\n\t\t\t\t\tbuf[bufsize++] = *p;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// just fill the buffer.\n\t\t\t\t\tif (*p != '\\\\') {\n\t\t\t\t\t\tbuf[bufsize++] = *p;\n\t\t\t\t\t\tstate = validate_state(state);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the buffer size is greater than zero, we need this last piece of data.\n\tif (bufsize) {\n\t\tif (state == STATE_START) {\n\t\t\tcopy_cmd(current_task, bufsize, buf);\n\t\t} else if (state == STATE_CMD || state == STATE_ARGS) {\n\t\t\tcopy_args(bufsize, &num_flags, &num_args, buf, current_task);\n\t\t} \t\n\t}\n\tcurrent_task->flag_size = num_flags;\n\tcurrent_task->arg_size = num_args;\n\tjob->task_count = line[0]=='\\n' ? 0 : jobsize;\n\treturn job;\n}\n" }, { "alpha_fraction": 0.6355140209197998, "alphanum_fraction": 0.6355140209197998, "avg_line_length": 25.75, "blob_id": "cdd4fb3348e77b7ae388a9792e5b12ac76c393fb", "content_id": "f93311e7c2ad93555452ce75194024f97cc9e705", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 107, "license_type": "no_license", "max_line_length": 61, "num_lines": 4, "path": "/cs146/hw2/nf", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# prints the number of files in a directory. Invoked via ./nf\nls -l | grep ^- | wc -l | xargs\n" }, { "alpha_fraction": 0.6429448127746582, "alphanum_fraction": 0.6650306582450867, "avg_line_length": 28.10714340209961, "blob_id": "01be7feead31118a745d7e12f7ed40b6d1d5901a", "content_id": "8ab9c312a54f900e2f3b05107b00f1cae84490c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "no_license", "max_line_length": 112, "num_lines": 28, "path": "/cs177/hw5/powermethod.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n# implementation of the power method.\nimport numpy as np\n\n# get input for an MxM matrix\ninput=raw_input\nM=int(input(\"Please enter M: \"))\np0 = [float(x) for x in input(\"Please enter p0, initial probability distro:\").split()]\nstate_transition = [[float(x) for x in input(\"Please enter line \" + str(i) + \": \").split()] for i in range(0,M)]\nepi=float(input(\"Please enter pi, the convergence ratio: \"))\n\n# convert to numpy arrays\np0 = np.array(p0)\nstate_transition = np.array(state_transition)\nmax_iters=10000\ndone=False\ni=0\nlastp = p0\nwhile (not done and i < max_iters):\n\tx = np.dot(lastp,state_transition)\n\tdiff=0.0\n\tfor j in range(0, M):\n\t\tdiff = diff + abs(x[j] - lastp[j])\n\tdone = diff <= epi\n\ti = i + 1\t\n\tlastp = x\nprint(\"\\n\")\nprint(\"The final po after \" + str(i) + \" iters is \" + str(lastp))\n" }, { "alpha_fraction": 0.6357243061065674, "alphanum_fraction": 0.6624472737312317, "avg_line_length": 26.346153259277344, "blob_id": "cb4ab600f9e4f2ca1cd5be094a561c13d466b93f", "content_id": "d6667279238a3aec2f29f9d8aa029f0d87bce2b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 74, "num_lines": 26, "path": "/cs177/hw7/p2.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/lib/python2.7\nfrom math import floor\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.genfromtxt(\"timestamps.txt\")\ndiffs=np.zeros(len(data)-1)\nbins=np.zeros(floor(max(data)) + 1)\nbins[floor(data[len(data) - 1] / 4)] += 1\nfor i in range (0, len(data) - 1):\n\tdiffs[i] = data[i+1] - data[i]\n\tbins[floor(data[i])] += 1\n\nprint \"Average mean is \" + str(np.mean(diffs)) + \" minutes\"\nprint \"Length is \" + str(len(diffs))\n\n\n_,ax = plt.subplots(1,2)\nax[0].hist(diffs, np.linspace(0, 3, 50))\nax[1].hist(np.random.exponential(np.mean(diffs), len(diffs)), normed=True)\n# the two plots are very very close.\nplt.show()\n\nprint \"mean and var: \" + str((np.mean(bins),np.var(bins)))\nplt.hist(bins);\nplt.show()\n" }, { "alpha_fraction": 0.7132169604301453, "alphanum_fraction": 0.7281795740127563, "avg_line_length": 27.714284896850586, "blob_id": "b4edbcfe9d262b0314b3dc7772f01bbf2f63f175", "content_id": "244829c385424ebd95e9f2c71af956b5aa000ee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/cs178/hw4/p2.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import mltools as ml\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mltools import dtree\n\n# load and split the data\nX = np.genfromtxt(\"kaggle.X1.train.txt\", delimiter=\",\")\nY = np.genfromtxt(\"kaggle.Y.train.txt\", delimiter=\",\")\nX,Y = ml.shuffleData(X,Y)\nXtr,Xte,Ytr,Yte = ml.splitData(X, Y, train_fraction=0.75)\n\n# get a decision tree\ndt = dtree.treeRegress(Xtr, Ytr, maxDepth=20)\nprint \"done\"" }, { "alpha_fraction": 0.5786679983139038, "alphanum_fraction": 0.5788683295249939, "avg_line_length": 31.003204345703125, "blob_id": "44b7227bce4a0fad1d29be4cadb27b0ea938f47e", "content_id": "e7eab10f6d88a160f86748c7115c993922dac3fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9985, "license_type": "no_license", "max_line_length": 145, "num_lines": 312, "path": "/cs142A/com/uci/cs142A/src/types/TypeChecker.java", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "package types;\n\nimport java.util.HashMap;\nimport ast.*;\nimport ast.Error;\nimport com.sun.org.apache.xpath.internal.operations.Bool;\n\npublic class TypeChecker implements CommandVisitor {\n \n private HashMap<Command, Type> typeMap;\n private StringBuffer errorBuffer;\n private Type innerMostReturnType;\n private boolean returning;\n private String funcname;\n /* Useful error strings:\n *\n * \"Function \" + func.name() + \" has a void argument in position \" + pos + \".\"\n * \"Function \" + func.name() + \" has an error in argument in position \" + pos + \": \" + error.getMessage()\n *\n * \"Function main has invalid signature.\"\n *\n * \"Not all paths in function \" + currentFunctionName + \" have a return.\"\n *\n * \"IfElseBranch requires bool condition not \" + condType + \".\"\n * \"WhileLoop requires bool condition not \" + condType + \".\"\n *\n * \"Function \" + currentFunctionName + \" returns \" + currentReturnType + \" not \" + retType + \".\"\n *\n * \"Variable \" + varName + \" has invalid type \" + varType + \".\"\n * \"Array \" + arrayName + \" has invalid base type \" + baseType + \".\"\n */\n\n public TypeChecker()\n {\n typeMap = new HashMap<Command, Type>();\n errorBuffer = new StringBuffer();\n }\n\n private void reportError(int lineNum, int charPos, String message)\n {\n errorBuffer.append(\"TypeError(\" + lineNum + \",\" + charPos + \")\");\n errorBuffer.append(\"[\" + message + \"]\" + \"\\n\");\n }\n\n private void put(Command node, Type type)\n {\n if (type instanceof ErrorType) {\n reportError(node.lineNumber(), node.charPosition(), ((ErrorType)type).getMessage());\n }\n typeMap.put(node, type);\n }\n \n public Type getType(Command node)\n {\n return typeMap.get(node);\n }\n \n public boolean check(Command ast)\n {\n ast.accept(this);\n return !hasError();\n }\n \n public boolean hasError()\n {\n return errorBuffer.length() != 0;\n }\n \n public String errorReport()\n {\n return errorBuffer.toString();\n }\n\n @Override\n public void visit(ExpressionList node) {\n TypeList list = new TypeList();\n for (Expression expr : node) {\n expr.accept(this);\n list.append(getType((Command) expr));\n }\n put(node, list);\n }\n\n @Override\n public void visit(DeclarationList node) {\n for (Declaration decl : node) {\n decl.accept(this);\n }\n }\n\n @Override\n public void visit(StatementList node) {\n returning = false;\n for (Statement s : node) {\n s.accept(this);\n }\n }\n\n @Override\n public void visit(AddressOf node) {\n put(node, new types.AddressType(node.symbol().type()));\n }\n\n @Override\n public void visit(LiteralBool node) {\n put(node, Type.getBaseType(\"bool\"));\n }\n\n @Override\n public void visit(LiteralFloat node) {\n put(node, Type.getBaseType(\"float\"));\n }\n\n @Override\n public void visit(LiteralInt node) {\n put(node, Type.getBaseType(\"int\"));\n }\n\n @Override\n public void visit(VariableDeclaration node) {\n Type voidT = new VoidType();\n if (voidT.equivalent(node.symbol().type())) {\n String msg = \"Variable \" + node.symbol().name() + \" has invalid type \" + node.symbol().type() + \".\";\n put (node, new ErrorType(msg));\n }\n put(node, node.symbol().type());\n }\n\n @Override\n public void visit(ArrayDeclaration node) {\n ArrayType baseType = (ArrayType)node.symbol().type();\n if (baseType.base() instanceof types.VoidType) {\n String msg = \"Array \" + node.symbol().name() + \" has invalid base type \" + baseType.base() + \".\";\n put(node, new ErrorType(msg));\n }\n put(node, baseType);\n }\n\n @Override\n public void visit(FunctionDefinition node) {\n returning = false;\n innerMostReturnType = ((FuncType)node.function().type()).returnType();\n funcname = node.function().name();\n Type voidT = Type.getBaseType(\"void\");\n if (node.ismain()) {\n // ensure the type is void.\n if (!innerMostReturnType.equivalent(Type.getBaseType(\"void\"))) {\n this.reportError(node.lineNumber(), node.charPosition(), \"Function main has invalid signature.\");\n return;\n }\n }\n\n // arguments\n int i = 0;\n for (crux.Symbol s : node.arguments()) {\n if (s.type().equivalent(voidT)) {\n this.reportError(node.lineNumber(), node.charPosition(), \"Function \" + funcname + \" has a void argument in position \" + i + \".\");\n return;\n }\n\n if (s.type() instanceof ErrorType) {\n String msg = \"Function \" + funcname + \" has an error in argument in position \" + i + \": \" + ((ErrorType) s.type()).getMessage();\n this.reportError(node.lineNumber(), node.charPosition(), msg);\n return;\n }\n i++;\n }\n node.body().accept(this);\n if (!innerMostReturnType.equivalent(voidT) && !returning) {\n String msg = \"Not all paths in function \" + funcname + \" have a return.\";\n this.reportError(node.lineNumber(), node.charPosition(), msg);\n return;\n }\n\n this.put(node, node.function().type());\n }\n\n @Override\n public void visit(Comparison node) {\n node.leftSide().accept(this);\n node.rightSide().accept(this);\n put(node, getType((Command)node.leftSide()).compare(getType((Command)node.rightSide())));\n\n }\n \n @Override\n public void visit(Addition node) {\n node.leftSide().accept(this);\n node.rightSide().accept(this);\n put(node, getType((Command)node.leftSide()).add(getType((Command) node.rightSide())));\n }\n \n @Override\n public void visit(Subtraction node) {\n node.leftSide().accept(this);\n node.rightSide().accept(this);\n put(node, getType((Command)node.leftSide()).sub(getType((Command) node.rightSide())));\n }\n \n @Override\n public void visit(Multiplication node) {\n node.leftSide().accept(this);\n node.rightSide().accept(this);\n put(node, getType((Command)node.leftSide()).mul(getType((Command) node.rightSide())));\n }\n \n @Override\n public void visit(Division node) {\n node.leftSide().accept(this);\n node.rightSide().accept(this);\n put(node, getType((Command)node.leftSide()).div(getType((Command) node.rightSide())));\n }\n \n @Override\n public void visit(LogicalAnd node) {\n node.leftSide().accept(this);\n node.rightSide().accept(this);\n put(node, getType((Command)node.leftSide()).and(getType((Command) node.rightSide())));\n }\n\n @Override\n public void visit(LogicalOr node) {\n node.leftSide().accept(this);\n node.rightSide().accept(this);\n put(node, getType((Command)node.leftSide()).or(getType((Command) node.rightSide())));\n }\n\n @Override\n public void visit(LogicalNot node) {\n node.expression().accept(this);\n put(node, getType((Command) node.expression()).not());\n }\n \n @Override\n public void visit(Dereference node) {\n node.expression().accept(this);\n put(node, getType((Command) node.expression()).deref());\n }\n\n @Override\n public void visit(Index node) {\n node.base().accept(this);\n node.amount().accept(this);\n put(node, getType((Command)node.base()).index(getType((Command) node.amount())));\n }\n\n @Override\n public void visit(Assignment node) {\n node.source().accept(this);\n node.destination().accept(this);\n put(node, getType((Command)node.destination()).assign(getType((Command)node.source())));\n }\n\n @Override\n public void visit(Call node) {\n node.arguments().accept(this);\n TypeList list = (TypeList)getType(node.arguments());\n put(node, ((FuncType) node.function().type()).call(list));\n }\n\n @Override\n public void visit(IfElseBranch node) {\n node.condition().accept(this);\n Type conditionalType = getType((Command)node.condition());\n if (!(conditionalType instanceof BoolType)) {\n String msg = \"IfElseBranch requires bool condition not \" + conditionalType + \".\";\n reportError(node.lineNumber(), node.charPosition(), msg);\n return;\n }\n boolean current_returning = true;\n node.thenBlock().accept(this);\n current_returning &= returning;\n node.elseBlock().accept(this);\n current_returning &= returning;\n if (!(innerMostReturnType instanceof VoidType)) {\n returning = current_returning;\n }\n }\n\n @Override\n public void visit(WhileLoop node) {\n node.condition().accept(this);\n Type condType = getType((Command) node.condition());\n if (!(condType instanceof BoolType)) {\n String msg = \"WhileLoop requires bool condition not \" + condType + \".\";\n this.reportError(node.lineNumber(), node.charPosition(), msg);\n return;\n }\n node.body().accept(this);\n if (!(innerMostReturnType instanceof VoidType)) {\n returning = false;\n }\n }\n\n @Override\n public void visit(Return node) {\n returning = true;\n node.argument().accept(this);\n Type returnType = getType((Command) node.argument());\n if (!innerMostReturnType.equivalent(returnType)) {\n String msg = \"Function \" + funcname + \" returns \" + innerMostReturnType + \" not \" + returnType + \".\";\n this.reportError(node.lineNumber(), node.charPosition(), msg);\n return;\n }\n put(node, returnType);\n }\n\n @Override\n public void visit(ast.Error node) {\n put(node, new ErrorType(node.message()));\n }\n}\n" }, { "alpha_fraction": 0.6518918871879578, "alphanum_fraction": 0.6789188981056213, "avg_line_length": 25.428571701049805, "blob_id": "8861fd8c2685df56eb9d8108e1533cec9f9b860c", "content_id": "d675160e21f76c1bdbe93f7b9e76c69259c731e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 925, "license_type": "no_license", "max_line_length": 112, "num_lines": 35, "path": "/cs177/hw5/stateplot.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\n# implementation of the power method.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# get input for an MxM matrix\ninput=raw_input\nM=int(input(\"Please enter M: \"))\np0 = [float(x) for x in input(\"Please enter p0, initial probability distro:\").split()]\nstate_transition = [[float(x) for x in input(\"Please enter line \" + str(i) + \": \").split()] for i in range(0,M)]\nepi=float(input(\"Please enter pi, the convergence ratio: \"))\n\n# convert to numpy arrays\np0 = np.array(p0)\nstate_transition = np.array(state_transition)\nmax_iters=50\ndone=False\ni=1\nlastp = p0\nstate=[p0[1]]\nwhile (i < max_iters):\n\tx = np.dot(lastp,state_transition)\n\tdiff=0.0\n\tfor j in range(0, M):\n\t\tdiff = diff + abs(x[j] - lastp[j])\n\tdone = diff <= epi\n\ti = i + 1\t\n\tlastp = x\n\tstate.append(x[1])\n\nprint(len(state),len(range(1,51)))\np=plt.plot(range(1,51), state)\nname=input(\"please enter the file name\")\nplt.title(str(p0))\nplt.show()\n" }, { "alpha_fraction": 0.593406617641449, "alphanum_fraction": 0.6446886658668518, "avg_line_length": 15, "blob_id": "3793b3a78fa8c2c7631eb8f42b067f0d2081af63", "content_id": "64fc337bacaf02e35fb10d206bcde018c7717e38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 273, "license_type": "no_license", "max_line_length": 46, "num_lines": 17, "path": "/cs131/project4/runSkelly.sh", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#$ -cwd\n#$ -j y\n#$ -S /bin/bash\n#$ -M [email protected]\n#$ -pe openmpi 256 \n#$ -o ./OutSkelly.out\n#\n# Use modules to setup the runtime environment\nmodule load sge \nmodule load gcc/5.2.0\nmodule load openmpi/1.6\n#\n# Execute the run\n#\nmpirun -np $NSLOTS ./Skelly 10 1726 \n" }, { "alpha_fraction": 0.6101083159446716, "alphanum_fraction": 0.6389891505241394, "avg_line_length": 17.46666717529297, "blob_id": "8c7f2eca7d955d198dc729845e99db7cadacbbd9", "content_id": "32168191054b607fa3f8a34156a63e2af3fae7c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 277, "license_type": "no_license", "max_line_length": 108, "num_lines": 15, "path": "/cs146/hw3/trash", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Ian Schweer\n# 22514022\n\ntrash=$TRASH\nif [[ \"$trash\" == \"\" ]]; then\n\techo \"The trash variable is not currently set. Consider setting an enviornment variable. Assuming ~/.Trash\"\n\ttrash=\"$HOME/.Trash\"\nfi\n\nif [ ! -e $trash ]; then\n\tmkdir $trash\nfi\n\neval mv \"$trash/*\" \".\"\n" }, { "alpha_fraction": 0.5919796228408813, "alphanum_fraction": 0.5946236848831177, "avg_line_length": 32.425533294677734, "blob_id": "c1e689c4186e3e447f05ee59f3b0331f1cc09660", "content_id": "5a84e745f75bc13ee315b12cac9f59f3ec3119c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 20423, "license_type": "no_license", "max_line_length": 162, "num_lines": 611, "path": "/cs142A/com/uci/cs142A/src/crux/Parser.java", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "package crux;\n\nimport ast.*;\nimport ast.Error;\nimport sun.jvm.hotspot.debugger.cdbg.Sym;\nimport types.*;\n\nimport java.util.*;\n\npublic class Parser {\n public static String studentName = \"Ian Schweer\";\n public static String studentID = \"22514022\";\n public static String uciNetID = \"ischweer\";\n // SymbolTable Management ==========================\n private SymbolTable symbolTable;\n\n private void initSymbolTable()\n {\n symbolTable = new SymbolTable();\n symbolTable.insert(\"readInt\");\n symbolTable.lookup(\"readInt\").setType(new FuncType(new TypeList(), Type.getBaseType(\"int\")));\n symbolTable.insert(\"readFloat\");\n symbolTable.lookup(\"readFloat\").setType(new FuncType(new TypeList(), Type.getBaseType(\"float\")));\n symbolTable.insert(\"printBool\");\n TypeList printBool = new TypeList();\n printBool.append(new BoolType());\n symbolTable.lookup(\"printBool\").setType(new FuncType(printBool, Type.getBaseType(\"void\")));\n symbolTable.insert(\"printInt\");\n TypeList printInt = new TypeList();\n printInt.append(new types.IntType());\n symbolTable.lookup(\"printInt\").setType(new FuncType(printInt, Type.getBaseType(\"void\")));\n symbolTable.insert(\"printFloat\");\n TypeList printFloat = new TypeList();\n printFloat.append(new types.FloatType());\n symbolTable.lookup(\"printFloat\").setType(new FuncType(printFloat, Type.getBaseType(\"void\")));\n symbolTable.insert(\"println\");\n symbolTable.lookup(\"println\").setType(new FuncType(new TypeList(), Type.getBaseType(\"void\")));\n }\n\n private void enterScope()\n {\n symbolTable = new SymbolTable(symbolTable);\n }\n\n private void exitScope()\n {\n symbolTable = symbolTable.getParent();\n }\n\n private Symbol tryResolveSymbol(Token ident)\n {\n assert(ident.is(Token.Kind.IDENTIFIER));\n String name = ident.lexeme();\n try {\n return symbolTable.lookup(name);\n } catch (SymbolNotFoundError e) {\n String message = reportResolveSymbolError(name, ident.lineNumber(), ident.charPosition());\n return new ErrorSymbol(message);\n }\n }\n\n private String reportResolveSymbolError(String name, int lineNum, int charPos)\n {\n String message = \"ResolveSymbolError(\" + lineNum + \",\" + charPos + \")[Could not find \" + name + \".]\";\n errorBuffer.append(message + \"\\n\");\n errorBuffer.append(symbolTable.toString() + \"\\n\");\n return message;\n }\n\n private Symbol tryDeclareSymbol(Token ident)\n {\n assert(ident.is(Token.Kind.IDENTIFIER));\n String name = ident.lexeme();\n try {\n return symbolTable.insert(name);\n } catch (RedeclarationError re) {\n String message = reportDeclareSymbolError(name, ident.lineNumber(), ident.charPosition());\n return new ErrorSymbol(message);\n }\n }\n\n private String reportDeclareSymbolError(String name, int lineNum, int charPos)\n {\n String message = \"DeclareSymbolError(\" + lineNum + \",\" + charPos + \")[\" + name + \" already exists.]\";\n errorBuffer.append(message + \"\\n\");\n errorBuffer.append(symbolTable.toString() + \"\\n\");\n return message;\n }\n \n// Grammar Rule Reporting ==========================================\n private int parseTreeRecursionDepth = 0;\n private StringBuffer parseTreeBuffer = new StringBuffer();\n\n public void enterRule(NonTerminal nonTerminal) {\n String lineData = new String();\n for(int i = 0; i < parseTreeRecursionDepth; i++)\n {\n lineData += \" \";\n }\n lineData += nonTerminal.name();\n //System.out.println(\"descending \" + lineData);\n parseTreeBuffer.append(lineData + \"\\n\");\n parseTreeRecursionDepth++;\n }\n\n private void exitRule(NonTerminal nonTerminal)\n {\n parseTreeRecursionDepth--;\n }\n\n public String parseTreeReport()\n {\n return parseTreeBuffer.toString();\n }\n\n// Error Reporting ==========================================\n private StringBuffer errorBuffer = new StringBuffer();\n \n private String reportSyntaxError(NonTerminal nt)\n {\n String message = \"SyntaxError(\" + lineNumber() + \",\" + charPosition() + \")[Expected a token from \" + nt.name() + \" but got \" + currentToken.kind() + \".]\";\n errorBuffer.append(message + \"\\n\");\n return message;\n }\n \n private String reportSyntaxError(Token.Kind kind)\n {\n String message = \"SyntaxError(\" + lineNumber() + \",\" + charPosition() + \")[Expected \" + kind + \" but got \" + currentToken.kind() + \".]\";\n errorBuffer.append(message + \"\\n\");\n return message;\n }\n \n public String errorReport()\n {\n return errorBuffer.toString();\n }\n \n public boolean hasError()\n {\n return errorBuffer.length() != 0;\n }\n \n private class QuitParseException extends RuntimeException\n {\n private static final long serialVersionUID = 1L;\n public QuitParseException(String errorMessage) {\n super(errorMessage);\n }\n }\n \n private int lineNumber()\n {\n return currentToken.lineNumber();\n }\n \n private int charPosition()\n {\n return currentToken.charPosition();\n }\n \n// Parser ==========================================\n private Scanner scanner;\n private Token currentToken;\n \n public Parser(Scanner _scanner)\n {\n scanner = _scanner;\n }\n \n// Parser ==========================================\n \n public ast.Command parse()\n {\n initSymbolTable();\n try {\n currentToken = scanner.next();\n return program();\n } catch (QuitParseException q) {\n return new ast.Error(lineNumber(), charPosition(), \"Could not complete parsing.\");\n }\n }\n \n// Helper Methods ==========================================\n private boolean have(Token.Kind kind)\n {\n return currentToken.is(kind);\n }\n \n private boolean have(NonTerminal nt)\n {\n return nt.firstSet().contains(currentToken.kind());\n }\n \n private boolean accept(Token.Kind kind)\n {\n if (have(kind)) {\n currentToken = scanner.next();\n return true;\n }\n return false;\n } \n \n private boolean accept(NonTerminal nt)\n {\n if (have(nt)) {\n currentToken = scanner.next();\n return true;\n }\n return false;\n }\n\n private boolean expect(Token.Kind kind)\n {\n if (accept(kind))\n return true;\n String errormessage = reportSyntaxError(kind);\n throw new QuitParseException(errormessage);\n //return false;\n }\n \n private boolean expect(NonTerminal nt)\n {\n if (accept(nt))\n return true;\n String errorMessage = reportSyntaxError(nt);\n throw new QuitParseException(errorMessage);\n //return false;\n }\n \n private Token expectRetrieve(Token.Kind kind)\n {\n Token tok = currentToken;\n if (accept(kind))\n return tok;\n String errorMessage = reportSyntaxError(kind);\n throw new QuitParseException(errorMessage);\n //return ErrorToken(errorMessage);\n }\n \n private Token expectRetrieve(NonTerminal nt)\n {\n Token tok = currentToken;\n if (accept(nt))\n return tok;\n String errorMessage = reportSyntaxError(nt);\n throw new QuitParseException(errorMessage);\n //return ErrorToken(errorMessage);\n }\n\n private int expectInteger (Token.Kind kind) {\n Token tok = currentToken;\n if (accept(kind))\n return Integer.parseInt(tok.lexeme());\n String errorMessage = reportSyntaxError(kind);\n throw new QuitParseException(errorMessage);\n }\n\n private int expectInteger (NonTerminal nt) {\n Token tok = currentToken;\n if (accept(nt))\n return Integer.parseInt(tok.lexeme());\n String errorMessage = reportSyntaxError(nt);\n throw new QuitParseException(errorMessage);\n }\n \n// Grammar Rules =====================================================\n \n // literal := INTEGER | FLOAT | TRUE | FALSE .\n public ast.Expression literal()\n {\n enterRule(NonTerminal.LITERAL);\n Token tok = expectRetrieve(NonTerminal.LITERAL);\n ast.Expression exp = Command.newLiteral(tok);\n exitRule(NonTerminal.LITERAL);\n return exp;\n }\n\n // designator := IDENTIFIER { \"[\" expression0 \"]\" } .\n public Expression designator()\n {\n enterRule(NonTerminal.DESIGNATOR);\n Expression to_return;\n Token tok = expectRetrieve(Token.Kind.IDENTIFIER);\n\n // we already know the designator is declared in scope.\n Symbol s = symbolTable.lookup(tok.lexeme());\n Expression addr = new AddressOf(tok.lineNumber(), tok.charPosition(), s);\n to_return = addr;\n while (accept(Token.Kind.OPEN_BRACKET)) {\n to_return = new Index(currentToken.lineNumber(), currentToken.charPosition(), to_return, expression0());\n expect(Token.Kind.CLOSE_BRACKET);\n }\n exitRule(NonTerminal.DESIGNATOR);\n return to_return;\n }\n\n // type := IDENTIFIER\n // @todo: return type.\n public types.Type type()\n {\n enterRule(NonTerminal.TYPE);\n Token k = expectRetrieve(Token.Kind.IDENTIFIER);\n exitRule(NonTerminal.TYPE);\n return types.Type.getBaseType(k.lexeme());\n }\n\n // op0 := >= | <= | != | == | < | >\n public Token op0()\n {\n return expectRetrieve(NonTerminal.OP0);\n }\n\n // op1 : + | - | or\n public Token op1()\n {\n return expectRetrieve(NonTerminal.OP1);\n }\n\n // op2 : * | / | and\n public Token op2()\n {\n return expectRetrieve(NonTerminal.OP2);\n }\n\n // expression0 := expression1 [ op0 expression1 ]\n public Expression expression0()\n {\n Expression expr = expression1();\n while (have(NonTerminal.OP0)) {\n Token op = op0();\n expr = Command.newExpression(expr, op, expression1());\n }\n return expr;\n }\n\n public Expression expression1()\n {\n Expression expr = expression2();\n while (have(NonTerminal.OP1)) {\n Token op = op1();\n expr = Command.newExpression(expr, op, expression2());\n }\n return expr;\n }\n\n public Expression expression2()\n {\n Expression expr = expression3();\n while (have(NonTerminal.OP2)) {\n Token op = op2();\n expr = Command.newExpression(expr, op, expression3());\n }\n return expr;\n }\n\n public Expression expression3()\n {\n Token tok = this.currentToken;\n Expression expr = new Error(currentToken.lineNumber(), currentToken.charPosition(), \"Unknown expression\");\n if (accept(Token.Kind.NOT)) {\n expr = new LogicalNot(tok.lineNumber(), tok.charPosition(), expression3());\n } else if (accept(Token.Kind.OPEN_PAREN)) {\n expr = expression0();\n expect(Token.Kind.CLOSE_PAREN);\n } else if (have(NonTerminal.DESIGNATOR)) {\n expr = designator();\n expr = new Dereference(tok.lineNumber(), tok.charPosition(), expr);\n } else if (have(NonTerminal.CALL_EXPRESSION)) {\n expr = call_expression();\n } else if (have(NonTerminal.LITERAL)) {\n expr = literal();\n }\n return expr;\n }\n\n public Call call_expression()\n {\n Token k = currentToken;\n expect(NonTerminal.CALL_EXPRESSION);\n Token tok = expectRetrieve(Token.Kind.IDENTIFIER);\n Symbol s = tryResolveSymbol(tok);\n expect(Token.Kind.OPEN_PAREN);\n ExpressionList list = expression_list();\n expect(Token.Kind.CLOSE_PAREN);\n return new Call(k.lineNumber(), k.charPosition(), s, list);\n }\n\n public ExpressionList expression_list()\n {\n ExpressionList expression_list = new ExpressionList(currentToken.lineNumber(), currentToken.charPosition());\n if (have(NonTerminal.EXPRESSION_LIST)) {\n expression_list.add(expression0());\n while (accept(Token.Kind.COMMA)) {\n expression_list.add(expression0());\n }\n }\n return expression_list;\n }\n\n public Symbol parameter() {\n this.tryDeclareSymbol(this.currentToken);\n Token tok = expectRetrieve(Token.Kind.IDENTIFIER);\n expect(Token.Kind.COLON);\n types.Type t = type();\n Symbol symbol = new Symbol(tok.lexeme());\n symbol.setType(t);\n symbolTable.lookup(tok.lexeme()).setType(t);\n return symbol;\n }\n\n // @todo: return TypeList\n public List<Symbol> parameter_list() {\n List<Symbol> params = new ArrayList<Symbol>();\n if (have(NonTerminal.PARAMETER)) {\n params.add(parameter());\n while (accept(Token.Kind.COMMA)) {\n params.add(parameter());\n }\n }\n return params;\n }\n\n // @todo: for all declerations, run TypeChecker on it\n // @todo: and add it to the hashmap\n public ast.VariableDeclaration variable_declaration() {\n Token k = expectRetrieve(Token.Kind.VAR);\n Symbol s = tryDeclareSymbol(this.currentToken);\n Token tok = expectRetrieve(Token.Kind.IDENTIFIER);\n ast.VariableDeclaration decl = new VariableDeclaration(k.lineNumber(), k.charPosition(), s);\n expect(Token.Kind.COLON);\n types.Type t = type();\n decl.symbol().setType(t);\n symbolTable.lookup(tok.lexeme()).setType(t);\n expect(Token.Kind.SEMICOLON);\n return decl;\n }\n\n // @todo: For all declerations, run TypeChecker on this\n // @todo: It's an array type, so ensure the inner type\n public ast.ArrayDeclaration array_declaration() {\n List<Integer> numbers = new ArrayList<>();\n Token tok = expectRetrieve(Token.Kind.ARRAY);\n Symbol symbol = tryDeclareSymbol(this.currentToken);\n Token name = expectRetrieve(Token.Kind.IDENTIFIER);\n expect(Token.Kind.COLON);\n types.Type t = type();\n expect(Token.Kind.OPEN_BRACKET);\n int extent = expectInteger(Token.Kind.INTEGER);\n expect(Token.Kind.CLOSE_BRACKET);\n types.ArrayType final_type;\n numbers.add(extent);\n while (accept(Token.Kind.OPEN_BRACKET)) {\n // nest the array type.\n int inner_extent = expectInteger(Token.Kind.INTEGER);\n expect(Token.Kind.CLOSE_BRACKET);\n numbers.add(inner_extent);\n }\n expect(Token.Kind.SEMICOLON);\n\n // build backwards\n final_type = new types.ArrayType(numbers.get(numbers.size() - 1), t);\n for (int i = numbers.size() - 2; i > -1; i--) {\n final_type = new types.ArrayType(numbers.get(i), final_type);\n }\n symbol.setType(final_type);\n symbolTable.lookup(name.lexeme()).setType(final_type);\n return new ArrayDeclaration(tok.lineNumber(), tok.charPosition(), symbol);\n }\n\n // @todo: Add function to the type checker reference\n // @todo: For all invocations, ensure the return matches the expected.\n public ast.FunctionDefinition function_definition() {\n Token k = this.currentToken;\n expect(Token.Kind.FUNC);\n Symbol symbol = tryDeclareSymbol(this.currentToken);\n Token name = expectRetrieve(Token.Kind.IDENTIFIER);\n // insert function into both scopes\n enterScope();\n expect(Token.Kind.OPEN_PAREN);\n List<Symbol> args = parameter_list();\n expect(Token.Kind.CLOSE_PAREN);\n expect(Token.Kind.COLON);\n types.Type return_type = type();\n ast.StatementList sl = statement_block();\n exitScope();\n TypeList arg_types = new TypeList();\n for (Symbol s : args) {\n arg_types.append(s.type());\n }\n Type func = new FuncType(arg_types, return_type);\n symbol.setType(func);\n symbolTable.lookup(name.lexeme()).setType(func);\n return new FunctionDefinition(k.lineNumber(), k.charPosition(), symbol, args, sl);\n }\n\n public ast.Declaration declaration() {\n Declaration decl = new Error(currentToken.lineNumber(), currentToken.charPosition(), \"Unknown decleration\");\n if (have(NonTerminal.VARIABLE_DECLARATION)) {\n decl = variable_declaration();\n } else if (have(NonTerminal.ARRAY_DECLARATION)) {\n decl = array_declaration();\n } else if (have(NonTerminal.FUNCTION_DEFINITION)) {\n decl = function_definition();\n } else {\n expect(NonTerminal.DECLARATION);\n }\n return decl;\n }\n\n public DeclarationList declaration_list() {\n DeclarationList dl = new DeclarationList(this.lineNumber(), this.charPosition());;\n while (have(NonTerminal.DECLARATION)) {\n dl.add(declaration());\n }\n return dl;\n }\n\n public Assignment assignment_statement() {\n Token let = this.currentToken;\n expect(NonTerminal.ASSIGNMENT_STATEMENT);\n tryResolveSymbol(this.currentToken);\n Expression left = designator();\n expectRetrieve(Token.Kind.ASSIGN);\n Expression right = expression0();\n expect(Token.Kind.SEMICOLON);\n return new Assignment(let.lineNumber(), let.charPosition(), left, right);\n }\n\n public Call call_statement() {\n Call c = call_expression();\n expect(Token.Kind.SEMICOLON);\n return c;\n }\n\n public IfElseBranch if_statement() {\n Token begin = this.currentToken;\n expect(NonTerminal.IF_STATEMENT);\n Expression predict = expression0();\n enterScope();\n StatementList sl = statement_block();\n StatementList else_block = new StatementList(currentToken.lineNumber(), currentToken.charPosition());\n exitScope();\n if (accept(Token.Kind.ELSE)) {\n enterScope();\n else_block = statement_block();\n exitScope();\n }\n return new IfElseBranch(begin.lineNumber(), begin.charPosition(), predict, sl, else_block);\n }\n\n public WhileLoop while_statement() {\n Token tok = this.currentToken;\n expect(NonTerminal.WHILE_STATEMENT);\n enterScope();\n Expression predicate = expression0();\n StatementList sl = statement_block();\n exitScope();\n return new WhileLoop(tok.lineNumber(), tok.charPosition(), predicate, sl);\n }\n\n public Return return_statement() {\n Token tok = this.currentToken;\n expect(NonTerminal.RETURN_STATEMENT);\n Expression value = expression0();\n expect(Token.Kind.SEMICOLON);\n return new Return(tok.lineNumber(), tok.charPosition(), value);\n }\n\n public Statement statement() {\n if (!have(NonTerminal.STATEMENT))\n expect(NonTerminal.STATEMENT);\n else if (have(NonTerminal.VARIABLE_DECLARATION)) {\n return variable_declaration();\n } else if (have(NonTerminal.CALL_STATEMENT)) {\n return call_statement();\n } else if (have(NonTerminal.ASSIGNMENT_STATEMENT)) {\n return assignment_statement();\n } else if (have(NonTerminal.IF_STATEMENT)) {\n return if_statement();\n } else if (have(NonTerminal.WHILE_STATEMENT)) {\n return while_statement();\n } else if (have(NonTerminal.RETURN_STATEMENT)) {\n return return_statement();\n }\n return new ast.Error(this.currentToken.lineNumber(), this.currentToken.charPosition(), \"Error\");\n }\n\n public StatementList statement_list() {\n StatementList sl = new StatementList(this.currentToken.lineNumber(), this.currentToken.charPosition());\n if (have(NonTerminal.STATEMENT)) {\n sl.add(statement());\n while (have(NonTerminal.STATEMENT))\n sl.add(statement());\n }\n return sl;\n }\n\n public StatementList statement_block() {\n expect(Token.Kind.OPEN_BRACE);\n StatementList sl = statement_list();\n expect(Token.Kind.CLOSE_BRACE);\n return sl;\n }\n\n // program := declaration-list EOF .\n public Command program()\n {\n initSymbolTable();\n return declaration_list();\n }\n}\n" }, { "alpha_fraction": 0.5586725473403931, "alphanum_fraction": 0.5693069100379944, "avg_line_length": 30.15999984741211, "blob_id": "ea63157cc1fef3d7a9a73b885ecad26ffc852a41", "content_id": "bf9e18bb990512861dbdd754464b47c2aef7a87a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10909, "license_type": "no_license", "max_line_length": 198, "num_lines": 350, "path": "/cs131/project1/main.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// CS131Project1\n//\n// Created by schweer on 1/26/16.\n// Copyright © 2016 schweer. All rights reserved.\n//\n\n#include <algorithm>\n#include <cstdlib>\n#include <sstream>\n#include <cctype>\n#include <fstream>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <thread>\n#include <mutex>\n#include <cmath>\n#include <locale>\n\n// Just makes the code clearer.\nusing Lines = std::vector<std::string>;\nusing it = Lines::const_iterator;\nusing thread_pod = std::pair<std::pair<it, it>, int>; // {{begin iter, end iter}, file line number offset}\n\nstruct Result\n{\n Result(int lineNumber_, int firstChar_, int length_)\n : lineNumber(lineNumber_), firstChar(firstChar_), length(length_)\n {}\n \n // This allows you to compare results with the < (less then) operator, i.e. r1 < r2\n bool\n operator<(Result const& o)\n {\n // Line number can't be equal\n return length < o.length ||\n (length == o.length && lineNumber < o.lineNumber) ||\n (length == o.length && lineNumber == o.lineNumber && firstChar < o.firstChar);\n }\n \n int lineNumber, firstChar, length;\n};\n\n// Removes all non letter characters from the input file and stores the result in a Lines container\nLines\nstrip(std::ifstream& file)\n{\n Lines result;\n result.reserve(100000); // If reading is too slow try increasing this value\n \n std::string workString;\n \n while(std::getline(file,workString))\n {\n //Strip non alpha characters\n workString.erase(std::remove_if(workString.begin(), workString.end(),\n [] (char c) { return !std::isalpha(c); }\n ), workString.end());\n result.push_back(workString);\n workString.clear();\n }\n return result;\n}\n\n// CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\n/** SHARED **/\n//std::mutex mutex_pod_lock, mutex_member_lock;\nclass ThreadPodManager {\npublic:\n ThreadPodManager() = delete;\n explicit ThreadPodManager(const std::vector<std::string>& lines, size_t pod_size);\n thread_pod next(bool send_start = false, int *start_pos = nullptr);\n bool hasNext();\nprivate:\n std::vector<std::string> mVec_lines;\n size_t mSizet_pod_size;\n int mInt_distance, mInt_progress;\n it mConstIter_last_pod_end;\n};\n\nThreadPodManager::ThreadPodManager(const std::vector<std::string>& lines, size_t pod_size) {\n mVec_lines = lines;\n mSizet_pod_size = pod_size;\n mConstIter_last_pod_end = lines.begin();\n mInt_distance = 0;\n mInt_progress = -1 * (int)mSizet_pod_size;\n}\n\nthread_pod ThreadPodManager::next(bool send_start, int *start_pos) {\n thread_pod pod;\n int i = 0, lower_bound = (int)mSizet_pod_size;\n// mutex_pod_lock.lock();\n// mutex_member_lock.lock();\n pod.first.first = mConstIter_last_pod_end;\n pod.second = mInt_progress;\n lower_bound = ((mVec_lines.size() - mInt_progress) > mSizet_pod_size)\n ? (int)mSizet_pod_size : (int)mVec_lines.size() - mInt_progress;\n if (send_start) *start_pos = (int)mInt_progress;\n// mutex_member_lock.unlock();\n// mutex_pod_lock.unlock();\n// mutex_member_lock.lock();\n while (i < lower_bound && i++ < mSizet_pod_size) {\n if (mConstIter_last_pod_end == mVec_lines.end())\n break;\n mConstIter_last_pod_end++;\n }\n pod.first.second = mConstIter_last_pod_end;\n// mutex_member_lock.unlock();\n return pod;\n}\n\nbool ThreadPodManager::hasNext() {\n // @todo: Figure out why == .end() is not working.\n bool to_return = false;\n// mutex_pod_lock.lock();\n int distance = mInt_distance, i = 0;\n if (mInt_distance == mVec_lines.size()) {\n// mutex_pod_lock.unlock();\n return false;\n }\n// mutex_pod_lock.unlock();\n // increment\n while ((distance + i) < mVec_lines.size() + 1 && (i++) < mSizet_pod_size) { }\n \n// mutex_pod_lock.lock();\n mInt_distance += i - 1;\n mInt_progress += (int)mSizet_pod_size;\n to_return = mInt_distance < mVec_lines.size() + 1;\n// mutex_pod_lock.unlock();\n return to_return;\n}\n\nbool checkIfPalindrome(std::string str) {\n bool to_return = true;\n int start = str.length() % 2 == 1 ? (int)(str.length() / 2) : (int)floor(str.length() / 2);\n \n for (int i = 0, j = (int)str.length() - 1; i < start; i++,j--) {\n if (str[i] == str[j]) to_return &= true;\n else to_return = false;\n }\n \n return to_return;\n}\n\nint findLongest(std::string text, int &s) {\n std::transform(text.begin(), text.end(), text.begin(), ::tolower);\n int N = (int)text.length();\n N = 2*N + 1; //Position count\n int L[N]; //LPS Length Array\n L[0] = 0;\n L[1] = 1;\n int C = 1; //centerPosition\n int R = 2; //centerRightPosition\n int i = 0; //currentRightPosition\n int iMirror; //currentLeftPosition\n int maxLPSLength = 0;\n int maxLPSCenterPosition = 0;\n int start = -1;\n int end = -1;\n int diff = -1;\n \n //Uncomment it to print LPS Length array\n //printf(\"%d %d \", L[0], L[1]);\n for (i = 2; i < N; i++)\n {\n //get currentLeftPosition iMirror for currentRightPosition i\n iMirror = 2*C-i;\n L[i] = 0;\n diff = R - i;\n //If currentRightPosition i is within centerRightPosition R\n if(diff > 0)\n L[i] = std::min(L[iMirror], diff);\n \n //Attempt to expand palindrome centered at currentRightPosition i\n //Here for odd positions, we compare characters and\n //if match then increment LPS Length by ONE\n //If even position, we just increment LPS by ONE without\n //any character comparison\n while ( ((i + L[i]) < N && (i - L[i]) > 0) &&\n ( ((i + L[i] + 1) % 2 == 0) ||\n (text[(i + L[i] + 1)/2] == text[(i - L[i] - 1)/2] )))\n {\n L[i]++;\n }\n \n if(L[i] > maxLPSLength) // Track maxLPSLength\n {\n maxLPSLength = L[i];\n maxLPSCenterPosition = i;\n }\n \n //If palindrome centered at currentRightPosition i\n //expand beyond centerRightPosition R,\n //adjust centerPosition C based on expanded palindrome.\n if (i + L[i] > R)\n {\n C = i;\n R = i + L[i];\n }\n }\n start = (maxLPSCenterPosition - maxLPSLength)/2;\n end = start + maxLPSLength - 1;\n s = start;\n return end - start + 1;\n}\n\nResult max(Result r1, Result r2) {\n if (r1 < r2) return r2;\n else return r1;\n}\n\nvoid findHighestResult(thread_pod data, Result *results_ptr) {\n Result r(0,0,0);\n int line = 0;\n for (; data.first.first != data.first.second; data.first.first++) {\n int longest = 0, start = 0;\n longest = findLongest(*data.first.first, start);\n r = max(r, {data.second + line, start, longest});\n line++;\n }\n *results_ptr = r;\n}\n\nvoid findHighestResult_temp(thread_pod data, Result *results_ptr) {\n Result r(0,0,0);\n int line = 0;\n for (; data.first.first != data.first.second; data.first.first++) {\n int longest = 0, start = 0;\n longest = findLongest(*data.first.first, start);\n r = max(r, {line++, start, longest});\n }\n *results_ptr = r;\n}\n\n// PART A\nResult\nFindPalindromeStatic(Lines const& lines, int numThreads)\n{\n Result r(0,0,0);\n std::vector<Result*> results(numThreads);\n std::vector<std::thread> ts;\n int range = round((double)lines.size() / (double)numThreads);\n int used = 0;\n std::vector<thread_pod> pods(numThreads + 1);\n \n ThreadPodManager mnger(lines, range);\n while (mnger.hasNext()) {\n results[used] = new Result(0,0,0);\n pods[used++] = mnger.next();\n }\n pods[0].first.first = lines.begin();\n \n // make threads and push back\n for (int i = 0; i < numThreads; i++) {\n ts.push_back(std::thread(&findHighestResult, pods[i], results[i]));\n }\n \n for (auto& t : ts)\n t.join();\n for (auto& x : results) {\n r = max(r, *x);\n }\n return r;\n}\nstd::mutex temp_mutex;\nvoid findHighestChunked(ThreadPodManager *mnger, Result *result) {\n Result highest(0,0,0);\n temp_mutex.lock();\n while (mnger->hasNext()) {\n int start = 0;\n thread_pod x = mnger->next(true, &start);\n temp_mutex.unlock();\n Result current(0,0,0);\n findHighestResult_temp(x, &current);\n current.lineNumber += start;\n highest = max(highest, current);\n temp_mutex.lock();\n }\n temp_mutex.unlock();\n \n *result = highest;\n}\n\n// PART B\nResult\nFindPalindromeDynamic(Lines const& lines, int numThreads, int chunkSize)\n{\n // construct ThreadPodManager\n Result r(0,0,0);\n std::vector<std::thread> ts;\n std::vector<Result*> results(numThreads);\n// mutex_member_lock.unlock();\n// mutex_pod_lock.unlock();\n ThreadPodManager mnger(lines, chunkSize);\n \n // build threads.\n for (int i = 0; i < numThreads; i++) {\n results[i] = new Result(0,0,0);\n ts.push_back(std::thread(&findHighestChunked, &mnger, results[i]));\n }\n \n // execute.\n for (auto& t: ts)\n t.join();\n for (auto& x : results) {\n r = max(r, *x);\n }\n return r;\n}\n\n// DONT CHANGE THIS -----------------------------------------------------------------------------------------------------------------\n\nint\nmain(int argc, char* argv[])\n{\n if(argc != 4)\n {\n std::cout << \"ERROR: Incorrect number of arguments. Format is: <filename> <numThreads> <chunkSize>\" << std::endl;\n return 0;\n }\n \n std::ifstream theFile(argv[1]);\n if(!theFile.is_open())\n {\n std::cout << \"ERROR: Could not open file \" << argv[1] << std::endl;\n return 0;\n }\n int numThreads = std::atoi(argv[2]);\n int chunkSize = std::atoi(argv[3]);\n clock_t t;\n std::cout << \"Process \" << argv[1] << \" with \" << numThreads << \" threads using a chunkSize of \" << chunkSize << \" for dynamic scheduling\\n\" << std::endl;\n \n Lines lines = strip(theFile);\n \n //Part A\n t = clock();\n Result aResult = FindPalindromeStatic(lines, numThreads);\n t = clock() - t;\n std::cout << \"PartA: \" << aResult.lineNumber << \" \" << aResult.firstChar << \" \" << aResult.length << \":\\t\" << lines.at(aResult.lineNumber).substr(aResult.firstChar, aResult.length) << std::endl;\n std::cout << \"It took \" << ((float)t) / CLOCKS_PER_SEC << \" seconds.\" << std::endl;\n //Part B\n t = clock();\n Result bResult = FindPalindromeDynamic(lines, numThreads, chunkSize);\n t = clock() - t;\n std::cout << \"PartB: \" << bResult.lineNumber << \" \" << bResult.firstChar << \" \" << bResult.length << \":\\t\" << lines.at(bResult.lineNumber).substr(bResult.firstChar, bResult.length) << std::endl;\n std::cout << \"It took \" << ((float)t) / CLOCKS_PER_SEC << \" seconds.\" << std::endl; \n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.6136363744735718, "avg_line_length": 16.600000381469727, "blob_id": "1fec1842b7a2ee26fac6ca62ed18961b028b8c4a", "content_id": "e27bbe398899df3c20e267dd10604e08204998af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 176, "license_type": "no_license", "max_line_length": 49, "num_lines": 10, "path": "/cs143B/project3/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "DEBUG=\"vm.dSYM\"\nall:\n\tg++ -std=c++11 *.cpp -o vm\ndebug:\n\tg++ -std=c++11 *.cpp -ggdb -o vm\nclean:\n\trm vm\nifeq ($(wildcard \"vm.dSYM/Contents/Info.plist\"),)\n\trm -rf vm.dSYM\nendif\n" }, { "alpha_fraction": 0.5914915204048157, "alphanum_fraction": 0.6089184880256653, "avg_line_length": 24.671052932739258, "blob_id": "0adbbea29f88a60d76c8fd919ce8408c512427d3", "content_id": "6a826020b06c770467b89cd849d15ebec62bdc4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1951, "license_type": "no_license", "max_line_length": 88, "num_lines": 76, "path": "/cs178/project/dt_sample.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import atleast_2d as twod\nfrom numpy import asarray as arr\nfrom sklearn.datasets import load_iris\nfrom sklearn.tree import DecisionTreeClassifier\n\ndef splitData(X, Y=None, train_fraction=0.80):\n \"\"\"\n Split data into training and test data.\n\n Parameters\n ----------\n X : MxN numpy array of data to split\n Y : Mx1 numpy array of associated target values\n train_fraction : float, fraction of data used for training (default 80%)\n\n Returns\n -------\n to_return : (Xtr,Xte,Ytr,Yte) or (Xtr,Xte)\n A tuple containing the following arrays (in order): training\n data from X, testing data from X, training labels from Y\n (if Y contains data), and testing labels from Y (if Y \n contains data).\n \"\"\"\n nx,dx = twod(X).shape\n ne = round(train_fraction * nx)\n\n Xtr,Xte = X[:ne,:], X[ne:,:]\n to_return = (Xtr,Xte)\n\n if Y is not None:\n Y = arr(Y).flatten()\n ny = len(Y)\n if ny > 0:\n assert ny == nx, 'splitData: X and Y must have the same length'\n Ytr,Yte = Y[:ne], Y[ne:]\n to_return += (Ytr,Yte)\n\n return to_return\n\n\n# Parameters\nn_classes = 3\nplot_colors = \"bry\"\nplot_step = 0.02\n\n# Load data\niris_master = load_iris()\nX,Xte,y,Yte = splitData(iris_master.data,np.array(iris_master.target),train_fraction=.5)\n_,f = X.shape\npairidx = 0\npair = [0,3]\n\n# for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3],\n# [1, 2], [1, 3], [2, 3]]):\n# We only take the two corresponding features\n\n# Shuffle\nidx = np.arange(X.shape[0])\nnp.random.seed(13)\nnp.random.shuffle(idx)\nX = X[idx]\ny = y[idx]\n\n# Standardize\nmean = X.mean(axis=0)\nstd = X.std(axis=0)\nX = (X - mean) / std\n\n# Train\nfor i in range(1, f):\n clf = DecisionTreeRegressor(max_depth=i).fit(X, y)\n Y_hat = clf.predict(Xte)\n Y_hat = np.transpose(Y_hat)\n print np.mean(Y_hat != Yte)\n" }, { "alpha_fraction": 0.5355628728866577, "alphanum_fraction": 0.5449835062026978, "avg_line_length": 29.768115997314453, "blob_id": "fc4a82f375ca762c90026d978f364c19e21bac18", "content_id": "5ab72cbc34fd1ba9925138555e1a8f33d576ef2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2123, "license_type": "no_license", "max_line_length": 106, "num_lines": 69, "path": "/cs121/tokenizer.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import operator # used to reverse dict\nimport threading\nfrom collections import defaultdict as ddict\nfrom itertools import islice\nclass Tokenizer:\n def __init__(self):\n self.file=False\n self.flock=threading.Lock()\n self.chunksize=500\n self.threads=[]\n self.lock = threading.Lock()\n self.res=[ddict(int), ddict(int), ddict(int), ddict(int)]\n self.flushamount = 5*100*100\n self.freqs={}\n \n def _getlines(self):\n while True:\n with self.flock:\n items=list(islice(self.file, self.chunksize))\n if not items:\n break\n yield items\n\n def _stripWord(self, word):\n '''\n\tSplits one word into a set of alphanumeric groups. O(n), where n=size(word), assuming append is O(1) time\n '''\n currentword=\"\"\n me=int(threading.current_thread().name)\n for ch in word:\n if (not ch.isalnum()):\n if (not currentword == \"\"):\n self.res[me][currentword.lower()] += 1\n currentword = \"\"\n else:\n currentword = currentword + ch\n\n if (not currentword == \"\"):\n self.res[me][currentword.lower()] += 1\n len(self.res[me])\n\n def tokenizeThread(self):\n me=int(threading.current_thread().name)\n for l in self._getlines():\n for x in l: \n self._stripWord(x)\n\n def tokenize(self, fname):\n\t'''\n\tTokenizes file, and counts the frequency of each token. O(n*m) time, where\n\t\tn=average( length( word in words ) )\n\t\tm=length( words )\n\tassuming has_key is O(1)\n\t'''\n tokenizing=[]\n\tself.file = open(fname)\n for i in range(4):\n self.threads.append(threading.Thread(target=self.tokenizeThread, name=str(i)))\n self.threads[i].start()\n for i in range(4):\n self.threads[i].join()\n\n return self.res\n\n def computeFrequencies(self):\n for i in range(1, 4):\n for k,v in self.res[i].iteritems():\n self.res[0][k] += v\n return self.res[0]\n" }, { "alpha_fraction": 0.5526992082595825, "alphanum_fraction": 0.5694087147712708, "avg_line_length": 22.398496627807617, "blob_id": "a18ff2372571a73718d0f63e58fb6753a3ec53d7", "content_id": "24c247388925f55d85bb99a2e8be7d7be7e0b3b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3112, "license_type": "no_license", "max_line_length": 80, "num_lines": 133, "path": "/cs146/hw4/every.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n#include <stdarg.h>\n\n// params\n//\tcontainer class for the parameters of the program.\n//\tThere is a segment, count and file. Each file is \n//\tread count lines for each segment.\ntypedef char* string;\ntypedef struct params_s {\n\tint segment;\n\tint count;\n\tstring* files;\n} params_t;\n\nparams_t params_ctor(int N, int M, string files) {\n\tparams_t t;\n\tt.segment = N;\n\tt.count = M;\n\tt.files = &files;\n\treturn t;\n}\n\n// use getopts to get M,N and the file name.\n// for the running programming. If there is no\n// m and n argument\nparams_t get_parameters(int argc, string* argv) {\n\tchar c;\n\tint M = 0, N = 0, use_env = 1, buffer = 0, *cur;\n\tcur = &N;\n\twhile ((c = getopt(argc, argv, \"1234567890,\")) != -1) {\n\t\tuse_env = 0;\n\t\tswitch (c) {\n\t\t\tcase '1': case '2': case '3': case '4': case'5':\n\t\t\tcase '6': case '7': case '8': case '9': case'0':\n\t\t\t\t*cur = (*cur * 10) + (c - '0');\n\t\t\t\tbreak;\n\n\t\t\tcase ',':\n\t\t\t\tif (cur != &M && cur != &buffer) {\n\t\t\t\t\tcur = &M;\n\t\t\t\t} else if (cur != &buffer) {\n\t\t\t\t\tcur = &buffer;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn params_ctor(N, M, NULL);\n}\n\n// copy_string_array\n//\tutility method to copy string arrays.\nvoid copy_string_array(const int copy_length, string* dest, const string* src) {\n\tint i;\n\tfor (i = 0; i < copy_length; i++) {\n\t\tdest[i] = malloc(sizeof(char) * strlen(src[i]));\n\t\tstrcpy(dest[i], src[i]);\n\t}\n}\n\nvoid copy_string_arguments(const int copy_length, string* dest, ...) {\n\tint i;\n\tva_list vl;\n\tva_start(vl, dest);\n\tfor (i = 0; i < copy_length; i++) {\n\t\tstring elem = va_arg(vl, char*);\n\t\tdest[i] = malloc(sizeof(char) * strlen(elem));\n\t\tstrcpy(dest[i], elem);\n\t}\n\tva_end(vl);\n}\n\nint get_file_names(int argc, const string *argv, string *files) {\n int i, count = 0;\n for (i = 1; i < argc; i++) {\n if (argv[i][0] != '-') {\n files[count] = malloc(sizeof(char) * strlen(argv[i]));\n strcpy(files[count++], argv[i]);\n } \n }\n return count;\n}\n\nvoid read_file(FILE *f, const int N, const int M) {\n\tstring line = malloc(sizeof(char) * BUFSIZ);\n\tint in_segment = 0, i = 0, j = 0;\n\twhile (NULL != fgets(line, BUFSIZ, f)) {\n\t\tif (!(i % N) && !in_segment) {\n\t\t\tin_segment = 1;\n\t\t}\n\n\t\tif (in_segment) {\n\t\t\tif (j < M) {\n\t\t\t\tprintf(\"%s\", line);\n\t\t\t\tj++;\n\t\t\t} else {\n\t\t\t\tin_segment = 0;\n\t\t\t\tj = 0;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n}\n\nint main(int argc, string* argv) {\n\t// check too see what argument we need to use\n int number_of_files = 0;\n\tparams_t args;\n\tstring envarg = \"\", files[argc];\n\tif (argc >= 2 && argv[1][0] == '-') {\n\t\targs = get_parameters(argc, argv);\n\t} else if ((envarg = getenv(\"EVERY\")) != NULL) {\n\t\tstring pargs[2];\n\t\tcopy_string_arguments(2, pargs, argv[0], envarg);\n\t\targs = get_parameters(2, pargs);\t\n\t} else {\n\t\targs.segment = 1;\n\t\targs.count = 1;\n\t}\n number_of_files = get_file_names(argc, argv, files);\n if (!number_of_files) {\n // read from stdin\n\t\tread_file(stdin, args.segment, args.count);\n } else {\n\t\tint i;\n\t\tfor (i = 0; i < number_of_files; i++) {\n\t\t\tread_file(fopen(files[i], \"r\"), args.segment, args.count);\n\t\t}\n }\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8125, "avg_line_length": 23.5, "blob_id": "7d77640c04f048bdffb62534c0007c297cc85a9c", "content_id": "4a8c3fabacea4514bc77b04f9947500ae438a98f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 48, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/ics53/lab2/notes.txt", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "working command:\ngcc -lpthread csapp.c shellex.c" }, { "alpha_fraction": 0.6105006337165833, "alphanum_fraction": 0.6135531067848206, "avg_line_length": 38.90243911743164, "blob_id": "16412ef2ea19db456d0e186f1a69e19857a8c768", "content_id": "b7d7b2834d4c87b52e8725639ac3b9a664ac4f12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1638, "license_type": "no_license", "max_line_length": 194, "num_lines": 41, "path": "/cs143B/project1/README.md", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "__THREAD MANAGEMENT__\n\nSimple thread manager with three states, and resources that can be released and requested.\nInstead of using the actual machine hardware and interrupts, we will use a presentation shell\nthat represents both the current process and user.\n\nOperation | old state new state\nCreate | (none) -> ready\nRequest | running -> blocked\nRelease | blocked -> ready\nDestroy | any -> (none)\n==================================================\nScheduler | ready -> running\n | running -> ready\n\n**PCB**\nSimple PCB data structure:\n\tid: Process id\n\t---------------\n\tMemory: Linked list to memory blocks\n\t---------------\n\tOther_Resources: Linked list to resources\n\t---------------\n\tStatus: \n\t---------------\n\tCreation_Tree: Parents and child proc\n\t---------------\n\tPriority: Running priority (0 init, 1, 2 highest)\n\t---------------\n**RCB**\nSimple RCB data structure:\n\tRID: ID\n\t------------\n\tStatus: Status\n\t------------\n\tWaiting_list: blocked process\n\n**Scheduling**\nPreemptive multilevel priority schedule with fixed priority levels. FIFO order (queue). Termination ondition `self->priority < p->priority`. This can be satisifed two ways:\n\t1.) The scheduler is called at the end of a Release operation, the priority of the process unblocked as a result of the Release operation may be higher than the priority of the current process;\n\t2.) When the scheduler is called at the end of a Create operation, the priority of the new process may be higher than the priority of the current process.\n\n\n" }, { "alpha_fraction": 0.6674364805221558, "alphanum_fraction": 0.6905311942100525, "avg_line_length": 32.30769348144531, "blob_id": "cbc09c4686b38fd19d594dad81456f04b6ff3c89", "content_id": "80b8fe1a08e55ce7947d13532a665802a159eb10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1299, "license_type": "no_license", "max_line_length": 104, "num_lines": 39, "path": "/cs178/hw1/two.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport mltools as ml\n\niris = np.genfromtxt(\"data/iris.txt\", delimiter=None)\nY = iris[:,-1]\nX = iris[:,0:2]\nX,Y = ml.shuffleData(X,Y)\nXtr,Xte,Ytr,Yte = ml.splitData(X, Y, 0.75)\n\ndef partA(Xtr, Xte, Ytr, Yte):\n\tknn = ml.knn.knnClassify()\n\t# varying values of K\n\tfor k in [1, 5, 10, 50]:\n\t\tknn.train(Xtr, Ytr, K=k)\n\t\tml.plotClassify2D(knn, Xtr, Ytr, axis=plt)\n\t\tprint \"#A: Plot of K=\" + str(k) \n\t\tplt.show()\n\n# computing error values of predictions\ndef partB(Xtr, Xte, Ytr, Yte):\n\tks = [1,2,5,10,50,100,200]\n\terrTrainTr = []\n\terrTrainTe = []\n\tfor i,k in enumerate(ks):\n\t\tlearner = ml.knn.knnClassify(Xtr, Ytr, K=k)\n\t\tYhattr = learner.predict(Xtr)\n\t\terrTrainTr.append(np.mean(np.transpose(Yhattr) - Ytr))\n\t\tYhatte = learner.predict(Xte)\n\t\terrTrainTe.append(np.mean(np.transpose(Yhatte) - Yte))\n\tplt.semilogx(errTrainTr, color='r')\n\tplt.semilogx(errTrainTe, color='g')\n\tprint \"#B: Semilog plot of error\"\n\tplt.show()\n\tprint \"What we see is that the kNN learner really needs a small amount of K to avoid fitness problems.\"\n\tprint \"What you can see from this graph is that the 2nd and 3rd values are in the optimal area of fit.\"\n\tprint \"This would mean training our data with K=2, K=5 would be optimal.\"\npartA(Xtr, Xte, Ytr, Yte)\npartB(Xtr, Xte, Ytr, Yte)\n" }, { "alpha_fraction": 0.7310105562210083, "alphanum_fraction": 0.7356340885162354, "avg_line_length": 48.03643798828125, "blob_id": "24f2848c48145d96923619b49a9639a3c20fadec", "content_id": "988eea39f5cd5662bafed10d529350c70e9da0ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24224, "license_type": "no_license", "max_line_length": 84, "num_lines": 494, "path": "/ics46/ProjectTwo/README.md", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "<html><head>\n <title>Program 2</title>\n</head>\n\n<body bgcolor=\"white\">\n\n<center>\n<h1>Program 2</h1>\n<h1>Implementing Queue/Priority Queue/Set<br>\n (and their iterators) with Linked Lists \n</h1>\n<p>\n</p><h2>ICS-46: Data Strcuture Implementation and Analysis\n</h2>\n<p>\n</p></center>\n\n\n<!-- Introduction -->\n\n<a name=\"Introduction\">\n<hr align=\"left\" width=\"33%\">\n<table cellspacing=\"0\" cellpadding=\"5\" border=\"0\" rules=\"none\" width=\"100%\">\n<tbody>\n<tr valign=\"top\">\n<td width=\"20%\"><b>Introduction</b></td>\n<td width=\"80%\">\nThis programming assignment is designed to ensure that you know how to\n implement three templated classes (<b>Queue</b>, <b>Priority Queue</b>,\n and <b>Set</b>) with linked lists.\nYour implementations will also include fully-functional iterators for\n these classes.\nYou will be writing lots of small code fragments that traverse and mutate\n linked lists.\n<p>\nYou must write all your implementations using linked lists: a linear-linked\n list for <b>LinkedQueue</b>, a header linked list for\n <b>LinkedPriorityQueue</b>, and a trailer linked list for <b>LinkedSet</b>.\nYou can test these implementations by using the standard drivers and\n GoogleTests (provided with the download) that we will use when grading your\n code for correctness; recall that you can augment the GoogleTest with whatever\n code you want, to aid your debugging: a GoogleTest is just a C++ program.\nYou can also test the code you wrote for Programming Assignment #1 (using\n array implementations of these classes) by substituting these linked list\n implementations -typically by changing a few <b>#include</b> and\n <b>typedef</b> statements.\n</p><p>\nWrite and use the <b>insertion</b> (<b>&lt;&lt;</b>) operator and <b>str()</b>\n method in each class for debugging.\nIn a header list, we skip showing the value in the front/header node, as that\n node is not really <b>in</b> the collection represented by the list;\n likewise, in a trailer list, we skip showing the value in the rear/trailer\n node, for the same reason.\nNote that there is no tested requirement for what these methods return, but\n the versions above will make debugging easier.\n</p><p>\nYou should download the \n <a href=\"program2.zip\">program2</a> project folder and use it to create an\n Eclipse project (ultimately needing to connect it to both the\n <b>courselib</b> and <b>googletest</b> libraries).\n You will write the required methods in the <b>linked_queue.hpp</b>, \n <b>linked_priority_queue.hpp</b>, and <b>linked_set.hpp</b>, files in this\n project, and submit each separately in Checkmate.\nThe project folder also contains three pairs of <b>.hpp</b> and <b>.cpp</b>\n files: a driver/GoogleTest pair for each class that you will write, and the\n <b>driver.cpp</b> file which has a <b>main</b> function that can be made to\n run any of the three drivers.\n</p><p>\nInstead, you can also use a existing/working project folder that already is\n connected to both the <b>courselib</b> and <b>googletest</b> libraries: remove\n (but save) all the files in its <b>src</b> folder and then put all the\n <b>.hpp</b> and <b>.cpp</b> files from the downloaded project's <b>src</b>\n folder into the existing/working project's <b>src</b> folder; finally,\n right-click the project and select <b>Refresh</b> (F5).\n</p><p>\n<b>Important: Only one of the <b>.cpp</b> files with a <b>main</b> method can\n be active/compiling at any time.</b>\nIn the download, only the <b>driver.cpp</b> file is active; the GoogleTests are\n inactive.\nTo make a progam inactive, select it (in the editor tab), use the <b>Ctrl/a</b>\n command to select all its lines, and then click <b>Source</b> at the top\n left of the menu and choose <b>Toggle Comment</b>: ever line will now appear\n in a comment (so the <b>main</b> function is commented-out); by using these\n same instructions, you can toggle back those lines to not have comments.\n</p><p>\nI recommend that you work on this assignment in pairs.\nTry to find someone who lives near you, with similar programming skills,\n and work habits/schedule: e.g., talk about whether you prefer to work\n mornings, nights, or weekends; what kind of commitment you will make to submit\n program early.\n</p><p>\n<b>Only one student should submit all parts of the the assignment</b>, but both\n student's names (along with their UniqueID) should appear in the comments at\n the top of <b>each submitted .cpp</b> file.\nIt should look something like\n</p><pre><b>\n//Romeo Montague(UniqueID from grades spreadsheet)\n//Juliet Capulet(UniqueID from grades spreadsheet)\n//We certify that we worked cooperatively on this programming\n// assignment, according to the rules for pair programming</b></pre>\nIf you do not know what the terms <b>cooperatively</b> and/or\n <b>rules for pair programming</b> mean, please read about\n <a href=\"../../../common/handouts/pairprogramming.html\">Pair Programming</a> \n before starting this assignment.\nPlease turn in each program <b>as you finish it</b>, so that I can accurately\n assess the progress of the class as a whole during this assignment.\n<p>\nPrint this document and carefully read it, marking any parts that contain\n important detailed information that you find (for review before you turn in\n the files).\n</p><p>\n</p><p>\nThis assignment has 3 parts: pairs should work on each part together, not split\n them up and do them separately.\nPart 1 is worth 42 points; part 2 is worth 9 points; part 3 is worth 9 pts.\n\nThis skewing of points towards the simpler parts means students finishing the\n first part correctly will have a 70% average; those finishing the first 2 \n parts correctly will have an 85% average; but to get an A on this \n assignment requires solving all parts correctly.\nRemember I'm going to be running MOSS on the parts of this assignment,\n to check for program similarity.\n</p><p>\nIMPORTANT: The courselib contains array implementations for all these data\n types; although this assignment requires you to use linked lists, there are\n still <b>many strong similarities</b> at a high level in all these\n implementations.\nSo, I encourage you to examine these implementations closely, and understand\n them; possibly, experiment with them (using their drivers or GoogleTests),\n while you are writing your linked list implementations: this advice is\n especially true as you begin to study, understand, and implement iterators.\nPlease feel free about asking questions about these methods -both their syntax\n and semantics- on the appropriate Messageboard.\n</p></td>\n</tr></tbody>\n</table>\n\n\n<!-- queue -->\n\n</a><a name=\"queue\">\n<hr align=\"left\" width=\"33%\">\n<table cellspacing=\"0\" cellpadding=\"5\" border=\"0\" rules=\"none\" width=\"100%\">\n<tbody>\n<tr valign=\"top\">\n<td width=\"20%\"><b>Queues</b></td>\n<td width=\"80%\">\nQueues are implemented by simple FIFO data structures (adhering to the\n Fast-In/First-Out order property).\nWe can implement queues efficiently by using two instance variables, which\n refer to a linked list (whose first value is the node at the <b>front</b>\n of the queue and whose last value is the node at the <b>rear</b> of the\n queue).\nNodes are removed from the front and added to the rear, so these are the\n two \"hot spots\" for a queue.\nThe <b>enqueue</b> and <b>dequeue</b> operations should each be O(1).\n<p>\nAlthough we can easily compute the number of values in linked list by\n traversing it, instead we will declare and update an extra instance variable \n named <b>used</b> to cache the size (incrementing and decrementing it, as\n values are successfully added/removed from the queue), so we will not have\n to traverse the list to compute its size.\n</p><p>\nThe file <b>linked_queue.hpp</b> declares the appropriate constructors, methods,\n and instance variables.\nNotice how the <b>LN</b> class is first declared <b>private</b> (before\n <b>Iterator</b>) and then defined <b>private</b> inside <b>LinkedQueue</b>\n using the parameter <b>&lt;T&gt;</b> of that class.\nI suggest copying/pasting the methods from the <b>array_queue.hpp</b>\n file, and then translating these methods from using arrays to using linked\n lists.\nPay close attention to ensure <b>all instance variables</b> receive values in\n the constructors and are used/set correctly in queries and commands.\n</p><p>\nUse delete to recycle <b>LN</b> nodes.\nTo simplify the operator=, you can <b>clear</b> the queue and then\n <b>enqueue</b> the required values: a faster way would be to clear the queue\n and copy the linked list; an even faster way would reuse whate <b>LN</b>\n nodes are already there, removing unneeded one or supplementing with more\n nodes.\n</p><p>\nRead the material in the <b>Iterators</b> section of this assignment, which\n discusses the iterators needed for all the classes that you will write.\nThese iterators perform the the same operations in every class, but they are\n implemented differently based on the kind of linked list implementation.\nFinally, read the <b>testing</b> section below as well.\n</p></td>\n</tr></tbody>\n</table>\n\n\n\n<!-- priorityqueue -->\n\n</a><a name=\"priorityqueue\">\n<hr align=\"left\" width=\"33%\">\n<table cellspacing=\"0\" cellpadding=\"5\" border=\"0\" rules=\"none\" width=\"100%\">\n<tbody>\n<tr valign=\"top\">\n<td width=\"20%\"><b>Priority Queues</b></td>\n<td width=\"80%\">\nPriority Queues can be implemented by a variety of data structures (where the\n highest priority value is always removed first).\nHow does a specific priority queue determine which value has the highest\n priority?\nWhen constructed, we supply the priority queue with a <b>gt</b> (greater-than)\n function that computes whether its first argument has a greater priority\n than its second argument.\nSo, we cannot ask, \"What is the priority of a value.\" But, we can ask \"Does the\n priority of a first value have a higher priority than a second value\", by\n calling the <b>gt</b> function.\nFor example, we cannot ask for the priority of a <b>std::string</b> value, but\n we can determine whether one <b>std::string</b> value has a higher\n priority than another <b>std::string</b> value.\n<p>\nWe can implement priority queues simple (although not very efficiently) with\n one instance variable, which refers to a linked list whose first value is the\n one with the highest priority value, and whose remaining values occur in\n order of decreasing priority; when adding a value to a priority queue, we\n insert it at the correct spot in the list, keeping the list ordered from\n highest to lowest priority; when removing the highest priority value from a\n priority queue, we always remove it from the front.\n</p><p>\nInstead of a standard linked list, you must <b>implement the priority queue\n using a \"Header node\" at the front of the linked list.</b>\nDoing so should simplify writing the most complicated method: enqueuing an\n element onto the priority queue: try to write this method very simply.\nHint: my <b>enqueue</b> method used four lines to put the <b>element</b> into\n an <b>LN</b> and insert it into the correct position in the header linked\n list (followed by 3 more lines of booking code).\n</p><p>\nAlthough we can easily compute the number of values in linked list by\n traversing it, instead we will declare and update an extra instance variable \n named <b>used</b> to cache the size (incrementing and decrementing it, as\n values are successfully added/removed from the queue), so we will not have\n to traverse the list to compute its size.\n</p><p>\nThe <b>enqueue</b> operation is O(N), so enqueuing N values onto a priority\n queue is O(N^2).\nWhen writing the copy constructor and operator=, use the fact that \"the linked\n lists being copied are already in order\" to make these operations O(N).\nTo simplify operator=, you can <b>clear</b> the queue and then carefully add\n the required values (in linear time).\n</p><p>\nThe file <b>linked_priority_queue.hpp</b> declares the appropriate constructors,\n methods, and instance variables.\nNotice how the <b>LN</b> class is first declared <b>private</b> (before\n <b>Iterator</b>) and then defined <b>private</b> inside\n <b>LinkedPriorityQueue</b> using the parameter <b>&lt;T&gt;</b> of that class.\nI suggest copying/pasting the methods from the <b>array_priority_queue.hpp</b>\n file, and then translating these methods from using arrays to using linked\n lists; in fact, you might want to copy the <b>linked_queue.hpp</b> file you\n wrote in part 1: it has the same methods and it already does some linked list\n processing: but doesn't use a header linked list.\nPay close attention to ensure <b>all instance variables</b> receive values in\n the constructors are are used/set correctly in queries and commands.\nUse delete to recycle <b>LN</b> nodes.\n</p><p>\nRead the material in the <b>Iterators</b> section of this assignment, which\n discusses the iterators needed for all the classes that you will write.\nThese iterators perform the the same operations in every class, but they are\n implemented differently based on the kind of linked list implementation.\nFinally, read the <b>testing</b> section below as well.\n</p></td>\n</tr></tbody>\n</table>\n\n\n<!-- set -->\n\n</a><a name=\"set\">\n<hr align=\"left\" width=\"33%\">\n<table cellspacing=\"0\" cellpadding=\"5\" border=\"0\" rules=\"none\" width=\"100%\">\n<tbody>\n<tr valign=\"top\">\n<td width=\"20%\"><b>Sets</b></td>\n<td width=\"80%\">\nSets can be implemented by a variety of data structures.\nWe can implement sets simply (although not very efficiently) with one instance\n variable, which refers to a linked list of values in the set.\nRemember that a set's order is not important: e.g., when we <b>insert</b> an\n <b>element</b> into a <b>set</b>, we are free to put it anywhere in the\n linked list; put it somewhere easy by using short/efficient code.\n<p>\nInstead of a standard linked-list, you must <b>implement the set using a\n \"Trailer node\" last in the linked list.</b>\nIn fact, it is useful to declare a <b>trailer</b> instance variable that always\n refers to this node (be careful: erasing the value in the node before the\n trailer node requires changing the trailer node; also, every linked list has\n its own/different trailer node).\nHaving a trailer node should simplify erasing a value from the set (in the\n class method, but even more so in the iterator methods, using the standard\n code/trick covered in the discussion of trailer lists.\n</p><p>\nAlthough we can easily compute the number of values in linked list by\n traversing it, instead we will declare and update an extra instance variable \n named <b>used</b> to cache the size (incrementing and decrementing it, as\n values are successfully added/removed from the set), so we will not have\n to traverse the list to compute this value.\n</p><p>\nThe <b>insert</b> operation is O(N), because it must check if the element is\n already in the set, so inserting N values into a set is O(N^2).\nWhen writing the copy constructor and operator=, use the fact that \"the linked\n lists being copied are already sets with no duplicates\" to make these \n operations O(N).\nTo simplify operator=, you can <b>clear</b> the set and then carefully add\n the required values (in linear time).\n</p><p>\nThe file <b>linked_set.hpp</b> declares the appropriate constructors,\n methods, and instance variables.\nNotice how the <b>LN</b> class is first declared <b>private</b> (before\n <b>Iterator</b>) and then defined <b>private</b> inside <b>LinkedSet</b>\n using the parameter <b>&lt;T&gt;</b> of that class.\nI suggest copying/pasting the methods from the <b>array_set.hpp</b> file,\n and then translating these methods from using arrays to using linked lists.\nPay close attention to ensure <b>all instance variables</b> receive values in\n the constructors are are used/set correctly in queries and commands.\nUse delete to recycle <b>LN</b> nodes.\n</p><p>\nRead the material in the <b>Iterators</b> section of this assignment, which\n discusses the iterators needed for all the classes that you will write.\nThese iterators perform the the same operations in every class, but they are\n implemented differently based on the kind of linked list implementation.\nFinally, read the <b>testing</b> section below as well.\n</p></td>\n</tr></tbody>\n</table>\n\n\n\n<!-- iterators -->\n\n</a><a name=\"iterators\">\n<hr align=\"left\" width=\"33%\">\n<table cellspacing=\"0\" cellpadding=\"5\" border=\"0\" rules=\"none\" width=\"100%\">\n<tbody>\n<tr valign=\"top\">\n<td width=\"20%\"><b>Iterators</b></td>\n<td width=\"80%\">\nFundamentally, iterators operate similarly for each data type: they allow\n programmers to traverse the data type, examining (and even erasing) the\n values inside the data type, one after the other.\nEach uses a cursor to remember its place inside the data type, as it traverses\n it: the array implementations used <b>int</b>s for cursors; the linked-list\n implementations use pointers for cursors.\n<p>\nOnce iterators are created (indexing the first value, or if there is none,\n indexing \"one beyond the last value\") we can use them to examine/erase the\n current value, increment them (to access the next value), and check whether\n a cursor has reached \"one beyond the last value\".\nWe often do this with either explict <b>for</b> loops or with implicit\n <b>for-each</b> loops (we do the latter more frequently).\n</p><p>\nNote that if we <b>erase</b> a value, the cursor will temporarily refer to\n its next value: we <b>must call one form of the ++ operator to increment the\n cursor</b> before we can examine/erase another value, but doing so does right\n after calling <b>erase</b> will not change the cursor, because <b>erase</b>\n has already made the cursor refer to its next value.\n</p><p>\nIn the <b>linked_queue.hpp</b> and <b>linked_priority_queue.hpp</b> files, I\n have implemented all <b>Iterator</b> methods fully except for the two forms\n of the <b>++</b> operator and the <b>erase</b> method, and for these I have\n even written some of the boiler-plate code.\n</p><ol>\n<li>Each defines a <b>prev</b> and <b>current</b> instance variable of type\n <b>LN*</b> (to traverse their linked list), along with a <b>ref_queue</b>\n (in the queue) or a <b>ref_pq</b> (in the priority queue) pointer referring\n to the object they are iterating over (to access its current <b>mod_count</b>\n and other instance variables as needed).\n<p>\n</p></li><li>Each defines an <b>expected_mod_count</b> and <b>can_erase</b> instance\n variable. Note that <b>can_erase</b> determines whether <b>erase</b> can\n function correctly, and helps control the updating of <b>prev</b> and\n <b>current</b> after calling <b>++</b> on an iterator.\n Note that <b>prev</b> is useful when the <b>current</b> value must be erased.\n<p>\n</p></li><li>All methods start with similar tests that determine whether to throw an\n exception. \n Most compare <b>mod_count</b> and <b>expected_mod_count</b>.\n The <b>==</b> and <b>!=</b> relational operators also ensure what is being\n compared are iterators from the same object.\n The <b>*</b> and <b>-&gt;</b> operators ensure that <b>current</b> is\n legal to examine: is not one beyond the last value.\n</li></ol> \nObserve their similarity in all implementations among all the <b>Iterator</b>\n classes and their methods.\nI recommend writing and testing the code for both <b>++</b> operators before\n writing code for an iterator's <b>erase</b> method.\nThis will allow you to test loops using iterators, so long as the body of the\n loop does not call <b>erase</b> on the iterator.\nAfter your code for these operators is working correctly, write code for\n calling <b>erase</b> on an iterator, and update the code in the <b>++</b>\n operators where necessary, to work correctly with <b>erase</b>.\n<p>\nNote that iterators for these two classes produce values in the order that they\n would be dequeued: FIFO for a queue and priority ordering for a priority\n queue.\nGiven how these linked lists represent these classes (queue: front to rear;\n priority queue: highest to lowest priority), the order of iterating through\n these classses is the same as the order of traversing their linked list\n implementation from front to rear.\n</p><p>\nThere are four GoogleTest functions that focus on iterators:\n<b>iterator_plusplus</b> focuses on the two forms of <b>++</b> operators\n and does <b>not</b> call the iterator's <b>erase</b>;\n<b>iterator_simple</b> does <b>not</b> call the iterator's <b>erase</b>;\n<b>iterator_erase</b> does call the iterator's <b>erase</b>; and\n<b>iterator__exception_concurrent_modification_error</b> ensures that mutating\n the data structure forces any active iterator to stop working (unless the\n mutation was done by that iterator's <b>erase</b>).\n</p><p>\nFor the <b>linked_set</b> class you must write all the code for the iterator.\nThe use of a trailer list will often make such code easier to write: it\n requires only a <b>current</b> instance variable, not one for <b>prev</b>.\nIn general, you should hand-simulate/debug your iterator code for the following\n cases:\n</p><ol>\n <li> erasing the first value (maybe several in a row at the front)\n </li><li> erasing non-consecutive values inside (with multiple <b>++</b>\n operators between calls)\n </li><li> erasing consecutive values (with single <b>++</b>\n operators between calls)\n </li><li> erasing the last value (maybe several in a row at the end)\n</li></ol>\n<p>\nYou can study how these semantics are coded in the array implementations of\n these data types, which are similiar but simpler than how they are coded with\n linked lists (because we can more easily manipulate <b>int</b> array cursors:\n <b>i-1</b> and <b>i+1</b>).\nFor linked list implementations, implementing <b>erase</b> on iterators is\n typically more complicated, but more EFFICIENT: values removed in the middle\n of arrays require shifting, causing the complexity class of <b>erase</b>\n to be O(N) in arrays while being only O(1) in linked lists.\n</p></td>\n</tr></tbody>\n</table>\n\n\n<!-- testing -->\n\n</a><a name=\"testing\">\n<hr align=\"left\" width=\"33%\">\n<table cellspacing=\"0\" cellpadding=\"5\" border=\"0\" rules=\"none\" width=\"100%\">\n<tbody>\n<tr valign=\"top\">\n<td width=\"20%\"><b>Testing</b></td>\n<td width=\"80%\">\nThere are various ways to test each of the classes you are writing in this\n programming assignment.\nFirst, though, you should write all the methods, paying careful attention to\n the array implementations and previously written linked list implementations.\nFor some, you might just boiler-plate simple code that is not correct, but\n allows the methods to compile, allowing other methods in the classes to be\n tested.\n<p>\nThe easiest way to start testing//debugging is by using the driver program.\nIt allows you to perform any method call supported by the templated classes,\n and see the state of the class (or view the debugger).\nOf course, \n<b>you must get the <b>insertion</b> (&lt;&lt;) operator and str() method to\n work before using it to debug the other methods.</b>\n</p><p>\nAfter you test and debug your code with the driver, try running the appropriate\n GoogleTest code.\nAgain, this form of testing is useful only as you approach a finished solution.\nWe will use the GoogleTest, and visual inspection, to grade this assignment.\n<b>Important Note</b>: You can put <b>std::cout</b> statements in the GoogleTest\n code (but don't accidentally remove any of the assertions, otherwise\n you won't be fully checking your code the way we will) while you are\n debugging your classes.\nAll debugging <b>std::cout</b> should end in <b>std::endl</b> to flush the\n output stream: taht ensures the output it displayed before executing the next\n statement (which may throw an exception).\n</p><p>\nWhen you run the GoogleTest, initially choose small values for the first and\n third prompts (just press return to the second prompt) or replace these\n prompts with small values in the code (so the test will run fully\n automatically).\nBesides an indication of which tests pass and fail, the console window\n will show a speed for the speed test (which will vary depending on how\n fast a machine you run your code on): don't worry about it.\nWhen your code is passing all the tests, put in values like <b>10,000</b> for\n these prompts.\n</p><p>\n\n</p></td>\n</tr></tbody>\n</table>\n\n\n\n\n\n</a></body></html>\n" }, { "alpha_fraction": 0.4092307686805725, "alphanum_fraction": 0.48307693004608154, "avg_line_length": 16.105262756347656, "blob_id": "e72bb33c774d53009a62cd7206934453beb618e6", "content_id": "3ffdb2bce6cd971594ee9f9ac67de73e83707e24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 41, "num_lines": 19, "path": "/cs161/hw1.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import math\ni = 2\n# when is n^2 > 10nlogn\nwhile i > 1:\n\tif (i**2) > (10 * i * (math.log(i, 2))):\n\t\tprint i;\n\t\tbreak;\n\ti += 1\n\n#when is nlogn = 10^6\nwhile i > 1:\n\tif i * math.log(i, 2) > 10**6:\n\t\tprint str(i - 1) + \" < x < \" + str(i)\n\t\tbreak\n\telif i * math.log(i, 2) == 10**6:\n\t\tprint \"x == \" + str(i)\n\t\tbreak\n\telse:\n\t\ti += 1\n" }, { "alpha_fraction": 0.5163911581039429, "alphanum_fraction": 0.529420018196106, "avg_line_length": 32.046295166015625, "blob_id": "4c69fe178424df78d4500c96228eb66d36e21a47", "content_id": "520beaad81b57c9eef1131573b8f628d937f64a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7138, "license_type": "no_license", "max_line_length": 131, "num_lines": 216, "path": "/cs131/project4/implementation.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"mpi.h\"\n\n#include <algorithm>\n#include <array>\n#include <cstdlib>\n#include <cctype>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <fstream>\n#include <chrono>\n\n// Don't CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\n\nvoid\nCreateElectionArray(int numberOfProcesses,int electionArray[][2])\n{\n\n std::vector<int> permutation;\n for(int i = 0; i < numberOfProcesses; ++i)\n permutation.push_back(i);\n std::random_shuffle(permutation.begin(), permutation.end());\n\n for(int i = 0; i < numberOfProcesses; ++i)\n {\n electionArray[i][0] = permutation[i];\n int chance = std::rand() % 4; // 25 % chance of inactive\n electionArray[i][1] = chance != 0; // 50% chance, \n }\n\n //Check that there is at least one active\n bool atLeastOneActive = false;\n for(int i = 0; i < numberOfProcesses; ++i)\n {\n if(electionArray[i][1] == 1)\n atLeastOneActive = true;\n }\n if(!atLeastOneActive)\n {\n electionArray[std::rand() % numberOfProcesses][1] = 1;\n }\n}\n\nvoid\nPrintElectionArray(int numberOfProcesses, int electionArray[][2])\n{\n for(int i = 0; i < numberOfProcesses; ++i)\n {\n std::printf(\"%-3d \", electionArray[i][0]);\n }\n std::cout << std::endl;\n for(int i = 0; i < numberOfProcesses; ++i)\n {\n std::printf(\"%-3d \", electionArray[i][1]);\n }\n std::cout << std::endl;\n}\nvoid\nPrintElectionResult(int winnerMPIRank, int round, int numberOfProcesses, int electionArray[][2])\n{\n std::cout << \"Round \" << round << std::endl;\n std::cout << \"ELECTION WINNER IS \" << winnerMPIRank << \"(\" << electionArray[winnerMPIRank][0] << \") !!!!!\\n\";\n std::cout << \"Active nodes where: \";\n for(int i = 0; i < numberOfProcesses; ++i)\n {\n if(electionArray[i][1] == 1)\n std::cout << i << \"(\" << electionArray[i][0] << \"), \";\n }\n std::cout << std::endl;\n PrintElectionArray(numberOfProcesses, electionArray);\n for(int i = 0; i < numberOfProcesses*4-2; ++i)\n std::cout << \"_\";\n std::cout << std::endl;\n}\n\n// CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\nint getActiveNode(int direction, int idx, int total, int election[][2]) {\n int neighbor = -1;\n bool done = false;\n for (int i = 0; i < total && !done; i++) {\n int index = (idx + (i * direction)) % total;\n if (index < 0) index = total + index;\n if (index != idx && election[index][1] == 1) {\n neighbor = index; \n done = true;\n }\n }\n return neighbor;\n}\nint \ngetLastNode(int numProcesses, int myProcessId, int election[][2]) { \n return getActiveNode(-1, myProcessId, numProcesses, election);\n}\n\nint\ngetNextNode(int numProcesses, int myProcessId, int election[][2]) {\n return getActiveNode(1, myProcessId, numProcesses, election);\n}\n\nint\nmain(int argc, char* argv[])\n{\n int processId;\n int numberOfProcesses;\n\n // Setup MPI\n MPI_Init( &argc, &argv );\n MPI_Comm_rank( MPI_COMM_WORLD, &processId);\n MPI_Comm_size( MPI_COMM_WORLD, &numberOfProcesses);\n\n // Two arguments, the program name, the number of rounds, and the random seed\n if(argc != 3)\n {\n if(processId == 0)\n {\n std::cout << \"ERROR: Incorrect number of arguments. Format is: <numberOfRounds> <seed>\" << std::endl;\n }\n MPI_Finalize();\n return 0;\n }\n\n std::chrono::time_point<std::chrono::system_clock> start;\n const int numberOfRounds = std::atoi(argv[1]);\n const int seed = std::atoi(argv[2]);\n std::srand(seed); // Set the seed\n\n auto electionArray = new int[numberOfProcesses][2]; // Bcast with &electionArray[0][0]...\n start = std::chrono::system_clock::now();\n for(int round = 0; round < numberOfRounds; ++round)\n {\n if(processId == 0)\n CreateElectionArray(numberOfProcesses, electionArray);\n \n // broadcast ElectionArray from master to all other nodes.\n MPI_Bcast(&electionArray[0][0], numberOfProcesses*2, MPI_INT, 0, MPI_COMM_WORLD);\n int next = getNextNode(numberOfProcesses, processId, electionArray);\n int last = getLastNode(numberOfProcesses, processId, electionArray);\n bool active = electionArray[processId][1];\n int lastSeen = -1;\n // do the election\n int activeCount = 0, send[numberOfProcesses], recv[numberOfProcesses];\n for (int i = 0; i < numberOfProcesses; i++) {\n int electionId = electionArray[i][0];\n activeCount += electionArray[i][1];\n if (electionArray[i][1] == 0) { \n send[electionId] = -2;\n recv[electionId] = -2;\n } else {\n lastSeen = i;\n send[electionId] = -1;\n recv[electionId] = -1;\n }\n }\n if (activeCount == 1) {\n send[numberOfProcesses - 1] = lastSeen;\n } else {\n send[electionArray[processId][0]] = processId;\n for (int i = 0; i < activeCount; i++) {\n if (!active) continue;\n MPI_Request req;\n MPI_Status stat;\n int tempSend[numberOfProcesses];\n MPI_Isend(&send[0], numberOfProcesses, MPI_INT, next, 0, MPI_COMM_WORLD, &req);\n MPI_Recv(&recv[0], numberOfProcesses, MPI_INT, last, 0, MPI_COMM_WORLD, nullptr);\n MPI_Wait(&req, &stat); \n \n // swap sendArray with recv\n for (int i = 0; i < numberOfProcesses; i++) {\n tempSend[i] = send[i];\n send[i] = recv[i];\n recv[i] = tempSend[i];\n }\n send[electionArray[processId][0]] = processId;\n }\n \n // swap send with recv one more time.\n int temp[numberOfProcesses];\n for (int i = 0; i < numberOfProcesses; i++) {\n temp[i] = recv[i];\n recv[i] = send[i];\n send[i] = temp[i];\n }\n }\n int winnerNum = 0;\n for (int i = numberOfProcesses; i > 0; i--) {\n if (send[i - 1] != -2) {\n winnerNum = send[i - 1];\n break;\n }\n }\n if(processId == 0)\n {\n int winner;\n if (winnerNum != 0) {\n MPI_Recv(&winner, 1, MPI_INT, winnerNum, 0, MPI_COMM_WORLD, nullptr); \n } else {\n winner = winnerNum;\n }\n PrintElectionResult(winner, round, numberOfProcesses, electionArray);\n } else {\n if (winnerNum == processId) {\n MPI_Send(&processId, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);\n }\n }\n }\n\n if (processId == 0) {\n std::chrono::duration<double> elasped_second = std::chrono::system_clock::now() - start;\n std::cout << elasped_second.count() << std::endl;\n }\n delete[] electionArray;\n\n MPI_Finalize();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.7108433842658997, "alphanum_fraction": 0.7108433842658997, "avg_line_length": 16.785715103149414, "blob_id": "30b00abb6a1ba30d32d2ac06c2be876c53698179", "content_id": "3f3961e4caaa595daa6fecd1fd180bb276cc6aa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 249, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/cs141/project1/src/jumpt.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef Jumpt_H\n#define Jumpt_H\n#include <string>\n#include <vector>\n#include \"statements.hpp\"\n#include \"writer.hpp\"\nclass Jumpt : public Statement\n{\npublic:\n\tJumpt(std::string);\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n};\n#endif\n" }, { "alpha_fraction": 0.656521737575531, "alphanum_fraction": 0.656521737575531, "avg_line_length": 21.439023971557617, "blob_id": "4f1429777a91a9b854fe976c7d6db22446bb1060", "content_id": "f4729d810c814db9bffae84c025697fcc74f2e6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 920, "license_type": "no_license", "max_line_length": 80, "num_lines": 41, "path": "/cs141/project1/src/set.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"grammer.hpp\"\n#include \"statements.hpp\"\n#include \"set.hpp\"\n#include \"writer.hpp\"\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nSet::Set(string line) : Statement(line) {\n\t_mvKeywords = new std::vector<string>();\n\t_mvKeywords->push_back(\"read\");\n\t_mvKeywords->push_back(\"write\");\n}\n\nSet::~Set() {\n\tdelete _mvKeywords;\n}\n\nvector<string>* Set::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Set::parse() {\n\tif (_msLine.find(\",\") == string::npos) return NULL;\n\t// parse out the keyword of the command\n\tstring left = \"\", right = \"\";\n\t_msLine = parseCommand(_msLine, \"set \", \"SET \"); \n\tif (!getArguments(_msLine, &left, &right)) return NULL; \n\t\n\t// ensure both arguments are expressions;\n\tcout << \"Set\" << endl;\n\tif ((isExpr(left) || isKeyword(left)) && (isExpr(right) || isKeyword(right))) {\n\t\treturn this;\n\t}\n\telse return NULL;\n}\n" }, { "alpha_fraction": 0.6236323714256287, "alphanum_fraction": 0.6291028261184692, "avg_line_length": 22.435897827148438, "blob_id": "d00e1ff13cd2c9d89e080693beb023c026db1dc9", "content_id": "73ce36476fb933aab15f15d3e08cd803be956dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 914, "license_type": "no_license", "max_line_length": 73, "num_lines": 39, "path": "/cs141/project1/src/jumpt.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"grammer.hpp\"\n#include \"statements.hpp\"\n#include \"jumpt.hpp\"\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nJumpt::Jumpt(string line) : Statement(line) {\n\t_mvKeywords = new vector<string>();\n}\n\nvector<string>* Jumpt::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Jumpt::parse() {\n\tif (_msLine.find(\",\") == string::npos) return NULL; // needs comma args.\n\tstring left, right;\n\t_msLine = parseCommand(_msLine, \"jumpt \", \"JUMPT \");\n\tif (!getArguments(_msLine, &left, &right)) return NULL;\n\tcout << \"Jumpt\" << endl;\n\tif (isExpr(left)) {}\n\n\t// split right by token args (!=, ==, >, <, >=, <=)\n\tint pos = right.find_first_of(\"!=><\");\t\n\tif (right[pos + 1] == '=') {\n\t\tisExpr(right.substr(0, pos));\n\t\tisExpr(right.substr(pos + 3));\n\t} else {\n\t\tisExpr(right.substr(0, pos));\n\t\tisExpr(right.substr(pos + 2));\n\t}\n\treturn this; \n}\n" }, { "alpha_fraction": 0.4886363744735718, "alphanum_fraction": 0.5227272510528564, "avg_line_length": 11.571428298950195, "blob_id": "ddf78cf2e9c6177bc544d70cae7e13c3a28fa1a8", "content_id": "1af3beb4e775c136713d39fbafdd6057617c268b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "no_license", "max_line_length": 25, "num_lines": 7, "path": "/cs131/project2/counter.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "f = open(\"timing_4.txt\")\ni = 0\nfor line in f:\n\tif (line.strip() == \"\"):\n\t\ti+=1\n\nprint i\n" }, { "alpha_fraction": 0.5397756695747375, "alphanum_fraction": 0.5534080862998962, "avg_line_length": 26.01631736755371, "blob_id": "b3806dfad465878dd56280965002bb60de7a921b", "content_id": "f6d6807d47f1eafed3200ee91b8c66eaef210a98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 11590, "license_type": "no_license", "max_line_length": 119, "num_lines": 429, "path": "/cs146/hw4/turnin.txt", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nerror() {\n\techo $1 >&2\n\tcleanup\n\texit $2\n}\n\n# prepare\n#\tprepares our compelation process\nprepare() {\n\tif [ ! -f $1 ]; then\n\t\terror \"File $1 does not exist\" -1\n\tfi\n clean=`echo $1 | sed 's/\\.\\///'`\n\ttmp=`mktemp -dt ${clean}XXXXX`\n}\n\n# interpret\n#\truns the compiler on the .c file and executes it.\ninterpret() {\n\texecname=$1\n\tfilename=$2\n\tscriptloc=$3\n\ttmpdir=$4\n\tshift 4\n\t/usr/bin/gcc -o \"$tmpdir/$execname\" \"$scriptloc/$filename\";\n\tif [[ $? -eq 0 ]]; then\n\t\t$tmpdir/$execname \"$@\" \n\telse\n\t\terror \"Error in gcc compiler\" -3\n\tfi\n}\n\n# cleanup\n#\tcleanup the resulting files in the tmp directory\ncleanup() {\n\t/bin/rm -rf $tmp\n}\n\ntrap '{cleanup; exit 1}' SIGHUP SIGINT SIGQUIT SIGTERM\ncprog=\"$0.c\"\nprepare $cprog\ninterpret $0 $cprog $PWD $tmp \"$@\"\ncleanup\n=================================================================================\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n#include <stdarg.h>\n\n// params\n//\tcontainer class for the parameters of the program.\n//\tThere is a segment, count and file. Each file is \n//\tread count lines for each segment.\ntypedef char* string;\ntypedef struct params_s {\n\tint segment;\n\tint count;\n\tstring* files;\n} params_t;\n\nparams_t params_ctor(int N, int M, string files) {\n\tparams_t t;\n\tt.segment = N;\n\tt.count = M;\n\tt.files = &files;\n\treturn t;\n}\n\n// use getopts to get M,N and the file name.\n// for the running programming. If there is no\n// m and n argument\nparams_t get_parameters(int argc, string* argv) {\n\tchar c;\n\tint M = 0, N = 0, use_env = 1, buffer = 0, *cur;\n\tcur = &N;\n\twhile ((c = getopt(argc, argv, \"1234567890,\")) != -1) {\n\t\tuse_env = 0;\n\t\tswitch (c) {\n\t\t\tcase '1': case '2': case '3': case '4': case'5':\n\t\t\tcase '6': case '7': case '8': case '9': case'0':\n\t\t\t\t*cur = (*cur * 10) + (c - '0');\n\t\t\t\tbreak;\n\n\t\t\tcase ',':\n\t\t\t\tif (cur != &M && cur != &buffer) {\n\t\t\t\t\tcur = &M;\n\t\t\t\t} else if (cur != &buffer) {\n\t\t\t\t\tcur = &buffer;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn params_ctor(N, M, NULL);\n}\n\n// copy_string_array\n//\tutility method to copy string arrays.\nvoid copy_string_array(const int copy_length, string* dest, const string* src) {\n\tint i;\n\tfor (i = 0; i < copy_length; i++) {\n\t\tdest[i] = malloc(sizeof(char) * strlen(src[i]));\n\t\tstrcpy(dest[i], src[i]);\n\t}\n}\n\nvoid copy_string_arguments(const int copy_length, string* dest, ...) {\n\tint i;\n\tva_list vl;\n\tva_start(vl, dest);\n\tfor (i = 0; i < copy_length; i++) {\n\t\tstring elem = va_arg(vl, char*);\n\t\tdest[i] = malloc(sizeof(char) * strlen(elem));\n\t\tstrcpy(dest[i], elem);\n\t}\n\tva_end(vl);\n}\n\nint get_file_names(int argc, const string *argv, string *files) {\n int i, count = 0;\n for (i = 1; i < argc; i++) {\n if (argv[i][0] != '-') {\n files[count] = malloc(sizeof(char) * strlen(argv[i]));\n strcpy(files[count++], argv[i]);\n } \n }\n return count;\n}\n\nvoid read_file(FILE *f, const int N, const int M) {\n\tstring line = malloc(sizeof(char) * BUFSIZ);\n\tint in_segment = 0, i = 0, j = 0;\n\twhile (NULL != fgets(line, BUFSIZ, f)) {\n\t\tif (!(i % N) && !in_segment) {\n\t\t\tin_segment = 1;\n\t\t}\n\n\t\tif (in_segment) {\n\t\t\tif (j < M) {\n\t\t\t\tprintf(\"%s\", line);\n\t\t\t\tj++;\n\t\t\t} else {\n\t\t\t\tin_segment = 0;\n\t\t\t\tj = 0;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n}\n\nint main(int argc, string* argv) {\n\t// check too see what argument we need to use\n int number_of_files = 0;\n\tparams_t args;\n\tstring envarg = \"\", files[argc];\n\tif (argc >= 2 && argv[1][0] == '-') {\n\t\targs = get_parameters(argc, argv);\n\t} else if ((envarg = getenv(\"EVERY\")) != NULL) {\n\t\tstring pargs[2];\n\t\tcopy_string_arguments(2, pargs, argv[0], envarg);\n\t\targs = get_parameters(2, pargs);\t\n\t} else {\n\t\targs.segment = 1;\n\t\targs.count = 1;\n\t}\n number_of_files = get_file_names(argc, argv, files);\n if (!number_of_files) {\n // read from stdin\n\t\tread_file(stdin, args.segment, args.count);\n } else {\n\t\tint i;\n\t\tfor (i = 0; i < number_of_files; i++) {\n\t\t\tread_file(fopen(files[i], \"r\"), args.segment, args.count);\n\t\t}\n }\n\treturn 0;\n}\n=================================================================================\n// Ian schweer\n// 22514022\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <pwd.h>\n#include <grp.h>\n#include <time.h>\n#include <locale.h>\n#include <langinfo.h>\n#include <errno.h>\n#include <stdint.h>\n\n#define ALMOST_ALL 1\n#define ALL 2\ntypedef char* string;\ntypedef struct opts_s {\n int show_all;\n int deref_links;\n string *names;\n int numfiles;\n} opt_t;\n\ntypedef struct statpod_s {\n struct stat s; // stat structure returned from stat\n struct stat l; // stat structure returned from lstat;\n} statpod_t;\n\ntypedef struct node_s {\n string name;\n struct dirent* dp;\n struct stat statbuf;\n statpod_t *pod;\n} node_t;\n\nstring readlink_name(string name);\nint compnode(const void *a, const void *b);\nvoid iteratenodes(node_t *data, int length);\nstatpod_t *statdir(string name, opt_t options);\nnode_t *getfiles(const char *path, node_t *files, int *j, opt_t options);\nopt_t *getoptions(int argc, string* argv);\nstring getfilepath(char *name, const char *path);\n\nint main(int argc, string* argv) {\n int i = 0, size = 0;\n opt_t *options;\n options = getoptions(argc, argv);\n for (i = 0; i < options->numfiles; i++) {\n node_t nodes[BUFSIZ];\n // get the files stat pod\n statpod_t *pod = statdir(options->names[i], *options); \n if (pod != NULL) {\n struct stat x = options->deref_links ? pod->s : pod->l;\n if (S_ISDIR(x.st_mode)) {\n // if the file is a directory, then go through this method\n if (options->numfiles > 1) printf(\"%s\\n\", options->names[i]);\n getfiles(options->names[i], nodes, &size, *options);\n qsort(nodes, size, sizeof(node_t), compnode);\n iteratenodes(nodes, size);\n } else {\n // the file is normal, print\n nodes[0].name = options->names[i];\n nodes[0].statbuf = options->deref_links ? pod->s : pod->l;\n iteratenodes(nodes, 1);\n }\n free(pod);\n free(options->names[i]);\n } else {\n perror(\"Unable to stat argument\");\n }\n }\n free(options->names);\n return 0;\n}\n\nopt_t *getoptions(int argc, string* argv) {\n char c;\n int numflags = 0;\n opt_t *options = calloc(1, sizeof(opt_t));\n while ((c = getopt(argc, argv, \"LaA\")) != -1) {\n numflags++;\n switch (c) {\n case 'L':\n options->deref_links = 1;\n break;\n case 'a':\n options->show_all = ALL;\n break;\n case 'A':\n options->show_all = ALMOST_ALL;\n break;\n }\n }\n\n // get all the file names.\n options->names = calloc(argc, sizeof(char*));\n // default options[0].\n options->names[0] = (char*)calloc(1, sizeof(char)*2);\n strcpy(options->names[0] , \".\");\n int i, j = 0;\n for (i = optind; i < argc; i++) {\n if (argv[i][0] != '-') {\n options->names[j] = calloc(1, sizeof(char) * strlen(argv[i]));\n strcpy(options->names[j++], argv[i]);\n }\n }\n options->numfiles = j ? j : 1;\n return options;\n}\n\nnode_t *getfiles(const char *path, node_t *files, int *j, opt_t options) {\n struct dirent *dp;\n struct stat statbuf;\n DIR *_dir = opendir(path);\n int i = 0, dircount = 0, k = 0;\n char *dirs[BUFSIZ];\n long pathsize = 0;\n // Get all the files.\n while ((dp = readdir(_dir)) != NULL) {\n if (options.show_all == ALMOST_ALL && (!strcmp(dp->d_name, \".\") || !strcmp(dp->d_name, \"..\"))) continue;\n if (!options.show_all && dp->d_name[0] == '.') continue;\n char *fullname = getfilepath(dp->d_name, path);\n statpod_t *statpod_ptr = statdir(fullname, options);\n if (statpod_ptr != NULL) {\n memcpy(&(files[i].statbuf), (options.deref_links ? &statpod_ptr->s : &statpod_ptr->l), sizeof(struct stat));\n files[i].name = calloc(1,sizeof(char) * strlen(dp->d_name));\n memcpy(files[i].name, dp->d_name, strlen(dp->d_name));\n files[i].name[strlen(dp->d_name)] = '\\0';\n files[i++].dp = dp;\n } else {\n perror(\"Error using stat return value\");\n }\n free(statpod_ptr);\n free(fullname);\n }\n *j = i;\n closedir(_dir);\n}\n\n\nint compnode(const void *a, const void *b) {\n int diff = (*(node_t*)a).statbuf.st_size - (*(node_t*)b).statbuf.st_size;\n if (!diff) return 0;\n else if (diff > 0) return -1;\n else return 1;\n}\n\nvoid iteratenodes(node_t *data, int length) {\n\tint i;\n\tstruct passwd *pwd;\n\tstruct group *grp;\n\tstruct tm *tm, *curr;\n\tchar datestring[256];\n\tint modecount = 9;\n\tmode_t modes[] = {S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH};\n\tchar outs[] = {'r', 'w', 'x'};\n\t\n\t// get the current time.\n\ttime_t rawtime;\n\ttime(&rawtime);\n\tfor (i = 0; i < length; i++) {\n string temp_stuff;\n if (S_ISLNK(data[i].statbuf.st_mode)) {\n string linkname = readlink_name(data[i].name);\n temp_stuff = calloc(1, sizeof(char) * (strlen(data[i].name) + strlen(linkname) + strlen(\" -> \")));\n sprintf(temp_stuff, \"%s -> %s\", data[i].name, linkname);\n } else {\n temp_stuff = calloc(1, sizeof(char) * strlen(data[i].name)); \n strcpy(temp_stuff, data[i].name);\n }\n\t\tif (S_ISDIR(data[i].statbuf.st_mode))\n\t\t\tputchar('d');\n\t\telse\n\t\t\tputchar('-');\n\n\t\tint j = 0;\n\t\tfor (j = 0; j < modecount; j++)\n\t\t\tif (data[i].statbuf.st_mode & modes[j])\n\t\t\t\tputchar(outs[j % 3]);\n\t\t\telse\n\t\t\t\tputchar('-');\n\t\tprintf(\"%2d\", data[i].statbuf.st_nlink);\n \n\t\tif ((pwd = getpwuid(data[i].statbuf.st_uid)) != NULL) {\n printf(\" %-8.8s\", pwd->pw_name);\n }\n\t\telse {\n printf(\" %-8d\", data[i].statbuf.st_uid);\n }\n \n\n\t\tif ((grp = getgrgid(data[i].statbuf.st_gid)) != NULL)\n\t\t\tprintf(\" %-6.8s\", grp->gr_name);\n\t\telse\n\t\t\tprintf(\" %-8d\", data[i].statbuf.st_gid);\n\n\t\tprintf(\"%5jd \", data[i].statbuf.st_size);\t\n\t\ttm = localtime(&data[i].statbuf.st_mtime);\n\n\t\tif (difftime(rawtime, mktime(tm)) < 15768000) { \n\t\t\tstrftime(datestring, sizeof(datestring), \"%b %e %R\", tm);\n\t\t\tprintf(\"%s %s\\n\", datestring, temp_stuff);\n\t\t} else {\n\t\t\tstrftime(datestring, sizeof(datestring), \"%b %e %Y\", tm);\n\t\t\tprintf(\"%s %s\\n\", datestring, temp_stuff);\n\t\t}\n\t}\n}\n\nstatpod_t *statdir(string name, opt_t options) {\n statpod_t *pod = calloc(1,sizeof(statpod_t));\n int lstat_return = !options.deref_links ? lstat(name, &(pod->l)) : 0;\n int stat_return = options.deref_links ? stat(name, &(pod->s)) : 0;\n\n if (lstat_return == -1) {\n char buf[100];\n sprintf(buf, \"Error while stating file %s\", name);\n perror(buf);\n return NULL;\n }\n if (lstat_return != -1 && stat_return == -1) {\n // the symbolic link points to nothing.\n perror(readlink_name(name));\n return NULL;\n }\n return pod; \n}\n\nstring readlink_name(string name) {\n string buf = calloc(1, sizeof(char) * 256);\n if (readlink(name, buf, 256) == -1) {\n sprintf(buf, \"reading link %s\", buf);\n perror(buf);\n }\n return buf;\n}\n\nstring getfilepath(char *name, const char *path) {\n string fullname = calloc(1, sizeof(char) * (strlen(name) + strlen(path) + 2));\n strcpy(fullname, path);\n strcat(fullname, \"/\");\n strcat(fullname, name);\n fullname[strlen(name) + strlen(path) + 1] = '\\0';\n return fullname;\n}\n" }, { "alpha_fraction": 0.5660574436187744, "alphanum_fraction": 0.5906005501747131, "avg_line_length": 22.924999237060547, "blob_id": "96615887e2b67e72433aac6c7cfcfebe0b8e0b8c", "content_id": "181f9b9c5e20c49ab10180c779c32b82efb5f560", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1915, "license_type": "no_license", "max_line_length": 75, "num_lines": 80, "path": "/cs143A/project7/mydu.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <sys/statvfs.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <pwd.h>\n#include <grp.h>\n#include <time.h>\n#include <locale.h>\n#include <langinfo.h>\n#include <errno.h>\n#include <stdint.h>\n\ntypedef struct node {\n\tint size;\n\tchar *name;\n} node_t;\n\nint cmpnode(const void *a, const void *b) {\n\tnode_t *left = (node_t *)a, *right = (node_t *)b;\n\tif (left->size == right->size) return strcasecmp(left->name, right->name);\n\telse return left->size - right->size;\t\n}\n\nvoid iterateDirectory(node_t *data, int length) {\n\tint i, j = 0;\n\tfor (i = 0; i < length; i++) {\n\t\twhile(data[i].name[++j] != '\\0');\n\t\tdata[i].name[j - 1] = '\\0';\n\t\tprintf(\"%-7ld %s\\n\", data[i].size, data[i].name);\n\t}\n\t\t\n}\n\nint getfiles(char *path, node_t *files, int *j) {\n\tstruct dirent *dp;\n\tstruct stat statbuf;\n\tDIR *_dir = opendir(path);\n\tint i = 0, size = 0;\n\twhile (path[i++] != '\\0') {};\n\tif (path[i - 2] != '/') {\n\t\tpath[i - 1] = '/';\n\t\tpath[i] = '\\0';\n\t}\n\ti = 0;\n\twhile ((dp = readdir(_dir)) != NULL) {\n\t\tchar name[BUFSIZ];\n\t\tstrcpy(name, path);\n\t\tstrcat(name, dp->d_name);\n\t\tif (dp->d_name[0] == '.') continue;\n\t\tif (lstat(name, &statbuf)== -1)\n\t\t\tcontinue;\n\t\tif (S_ISDIR(statbuf.st_mode))\n\t\t\tsize += getfiles(name, files, j) + ((statbuf.st_blocks * 512) / 1000); \n\t\telse size += (statbuf.st_blocks * 512) / 1000;\n\t}\n\tfiles[*j].name = (char*) malloc(BUFSIZ);\n\tstrcpy(files[*j].name, path); \n\tfiles[*j].size = size == 0 ? 4 : size + 4;\n\t(*j)++;\n\treturn size;\n} \nint main(int argc, char **argv) {\n\t// get the \"current\" directory.\n\tchar *path = \"./\";\n\tnode_t nodes[BUFSIZ];\n\tint ifiles = 0, explore_length = 1, i = 0, j = 0;\n\tif (argc == 2)\n\t\tpath = argv[1];\n\tgetfiles(path, nodes, &j);\n\tqsort(nodes, j, sizeof(node_t), cmpnode);\n\titerateDirectory(nodes, j);\n\t// print out directory information.\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.5758354663848877, "alphanum_fraction": 0.6092544794082642, "avg_line_length": 36.91101837158203, "blob_id": "50824de62441d7f2d99b3e5090b9b1e5791c27ed", "content_id": "11f1a7e5596d25063f7d4c4c9019168424581923", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8947, "license_type": "no_license", "max_line_length": 153, "num_lines": 236, "path": "/cs143B/project3/pm.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <string>\n#include \"pm.h\"\n#include \"logger.h\"\n#include \"tlb_adapter.h\"\n/**\n * Example of core logic: \n * 1. Initialize PM\n * 2. Read in VA and translate to PA.\n * \n * Ex: 2 2048 <- Segment 2 starts at address 2048\n *\t 0 2 512 1 2 -1 <- Page 0 of segment 2 starts at 512\n * Ex (cont): 0 0 0 1048576 1 1048586 1 1049088 \n * \t\tfirst tuple: 0 0: Read (first zero) from virtual address 0. w is 0, p is 0 and s 0. However,\n *\t\tsince segment 0 is not initalized, we print err.\n *\n *\t\tSecond tuple: 0 1048576: Read (first zero) from virtual address 1048576. s = 2, p = 0, w = 0\n *\t\tbin(1048576) = 1 0000 0000 0000 0000 0000\n * s p w\n *\t\tThis this correlates to our 0 2 512 command. We read 512 and add w giving us 512\n *\n *\t\tThird tuple: 1 1048586: Write (first 1) to virtual address 1048586. s = 2, p = 0, w = 10.\n *\t\tSo now it gets interesting. We access the disk at segment 2, page 0. Since page 0 segment 2\n *\t\tstarts at address 512, we add w, which is ten. Giving us 522. We write this then print it out.\n *\n *\t\tFourth tuple: 1 1049088: Write (first 1) to virutal address 1049088. s = 2, p = 1, w = 0.\n *\t\tbin(1049088) = 1 0000 0000 0010 0000 0000\n * s p w\n *\t\tSo we attempt to write to the virtual address 1049088 and we find out that segment 2, page 1\n *\t\tis set to -1 (1 2 -1 above). This results in a page fault. print pf.\n */\n\npm::pm(std::string outs, bool tlb_enabled) : out(outs) {\n\tfor (int i = 0; i < (FRAME_SIZE * FRAME_COUNT); i++) {\n\t\tdisk[i] = 0;\n\t}\n\n\tfor (int i = 0; i < 32; i++) {\n\t\tbitmask[i] = 0;\n\t}\n\n\ttlb = TlbFactory::MakeAdapter(tlb_enabled);\n\tLoggerFactory::GetLogger()->log(CLASS_TAG + \"PM()\", \"Constructed\");\n}\n\nbool pm::get_physical_address(int virtual_address, pm::va_t *address) {\n\tva_t pa;\n\tpa.w = get_offset(virtual_address);\n\tpa.s = get_segment_table(virtual_address);\n\tpa.p = get_page_table(virtual_address);\n\tpa.sp = (pa.s << 10) + pa.p;\n\tpa.addr = disk[disk[pa.s] + pa.p] + pa.w;\n\t*address = pa; \n\tstd::string out = \"{ s=\" + std::to_string(pa.s) + \", p=\" + std::to_string(pa.p);\n\tout += + \", w=\" + std::to_string(pa.w) + \", addr = \" + std::to_string(pa.addr) + \", sp = \" + std::to_string(pa.sp) + \"}\";\n\tLoggerFactory::GetLogger()->log(CLASS_TAG + \"get_physical_address()\", \"Getting virtual address components for \" + std::to_string(virtual_address));\n\tLoggerFactory::GetLogger()->log(CLASS_TAG + \"get_physical_address()\", out);\n\treturn true;\n}\n\nvoid pm::initialize(std::vector < std::vector < std::string > > data ) {\n\tstd::string tag = CLASS_TAG + \"initialize()\";\n\tif (data.size() < 2) {\n\t\tLoggerFactory::GetLogger()->log(tag, \"bad input file\");\n\t\treturn;\n\t}\n\tstd::vector < std::string > segments = data[0];\n\tstd::vector < std::string > pages = data[1];\n\n\tset_frame(0);\n\tLoggerFactory::GetLogger()->log(tag, \"Set frame 0\");\n\tfor (int i = 0; i < segments.size(); i += 2) {\n\t\tint s = std::stoi(segments[i]), f = std::stoi(segments[i+1]);\n\t\tif (f > 0) {\n\t\t\t// make f a frame, not address\n\t\t\tint frame = floor(f / FRAME_SIZE);\n\t\t\tdisk[s] = f;\n\t\t\tset_frame(frame);\n\t\t\tLoggerFactory::GetLogger()->log(tag, \"Segment \" + std::to_string(s) + \" set frame \" + std::to_string(frame) + \" to address \" + std::to_string(f));\n\t\t\tset_frame(frame + 1); // page tables take 2 entries.\n\t\t\tLoggerFactory::GetLogger()->log(tag, \"Segment \" + std::to_string(s) + \" set frame \" + std::to_string(frame + 1) + \" to address \" + std::to_string(f));\n\t\t} else {\n\t\t\tdisk[s] = f;\n\t\t\tLoggerFactory::GetLogger()->log(tag, \"Segment \" + std::to_string(s) + \" has no frame (\" + std::to_string(-1) + \")\");\n\t\t}\n\t}\n\n\tfor (int i = 0; i < pages.size(); i += 3) {\n\t\tint p = std::stoi(pages[i]), s = std::stoi(pages[i+1]);\n\t\tint f = std::stoi(pages[i + 2]);\n\t\tif (f > 0) {\n\t\t\tdisk[disk[s] + p] = f;\n\t\t\tLoggerFactory::GetLogger()->log(tag, \"Set disk \" + std::to_string(disk[s] + p) + \" to \" + std::to_string(f));\n\t\t\tset_frame(f / FRAME_SIZE);\n\t\t} else {\n\t\t\tdisk[disk[s] + p] = f;\n\t\t\tLoggerFactory::GetLogger()->log(tag, \"Set disk \" + std::to_string(disk[s] + p) + \" to \" + std::to_string(f));\n\t\t}\n\t}\n\n}\n\nvoid pm::read(int virtual_address) {\n\tva_t addr;\n\tstd::string tag = CLASS_TAG + \"read()\", msg = \"Virtual address \" + std::to_string(virtual_address) + \" \";\n\tLoggerFactory::GetLogger()->log(tag, \"Starting read for virtual address \" + std::to_string(virtual_address));\n\tget_physical_address(virtual_address, &addr);\n\tif (tlb->has_frame_cache(addr.sp)) {\n\t\toutput(tlb->get_hit_string());\n\t\toutput(std::to_string(tlb->get_frame_cache(addr.sp) + addr.w));\n\t\toutput(\" \");\n\t\tLoggerFactory::GetLogger()->log(tag, msg + \" recieved from tlb at addr \" + std::to_string(tlb->get_frame_cache(addr.sp) + addr.w));\n\t}\n\telse {\n\t\toutput(tlb->get_miss_string());\n\t\tif (addr.s == 0) {\n\t\t\toutput(\"err \");\n\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"error\");\n\t\t}\n\t\telse if (disk[addr.s] == -1 || (disk[disk[addr.s] + addr.p]) == -1) {\n\t\t\toutput(\"pf \");\n\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"page fault\");\n\t\t} else if (!addr.s || !disk[addr.s]|| (!disk[disk[addr.s] + addr.p])) {\n\t\t\toutput(\"err \");\n\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"error\");\n\t\t} else {\n\t\t\toutput(std::to_string(addr.addr) + \" \");\n\t\t\ttlb->set_frame_cache(addr.sp, disk[disk[addr.s] + addr.p]);\n\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"at address \" + std::to_string(addr.addr));\n\t\t}\n\t}\n\tLoggerFactory::GetLogger()->log(tag, \"Ending read for virtual address \" + std::to_string(virtual_address));\n}\n\nvoid pm::write(int virtual_address) {\n\tva_t addr;\n\tstd::string tag = CLASS_TAG + \"write()\", msg = \"Virtual address \" + std::to_string(virtual_address) + \" \";\n\tLoggerFactory::GetLogger()->log(tag, \"Starting write for virtual address \" + std::to_string(virtual_address));\n\tget_physical_address(virtual_address, &addr);\n\tif (tlb->has_frame_cache(addr.sp)) {\n\t\toutput(tlb->get_hit_string());\n\t\toutput(std::to_string(tlb->get_frame_cache(addr.sp) + addr.w));\n\t\toutput(\" \");\n\t\tLoggerFactory::GetLogger()->log(tag, msg + \" recieved from tlb at addr \" + std::to_string(tlb->get_frame_cache(addr.sp) + addr.w));\n\t}\n\telse {\n\t\toutput(tlb->get_miss_string());\n\t\tif (addr.s == 0) {\n\t\t\toutput(\"err \");\n\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"error\");\n\t\t}\n\t\telse if (disk[addr.s] == -1 || (disk[disk[addr.s] + addr.p]) == -1) {\n\t\t\toutput(\"pf \");\n\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"page fault\");\n\t\t}\n\t\telse {\n\t\t\tif (!disk[addr.s]) {\n\t\t\t\tint frame_number = get_free_frame(2);\n\t\t\t\tdisk[addr.s] = frame_number * FRAME_SIZE;\t\n\t\t\t\tset_frame(frame_number);\n\t\t\t\tset_frame(frame_number + 1)\t;\n\t\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"allocated frames (2) \" + std::to_string(disk[addr.s]));\n\t\t\t}\n\t\t\tif (!disk[disk[addr.s] + addr.p]) {\n\t\t\t\tint frame_number = get_free_frame(1);\n\t\t\t\tdisk[disk[addr.s] + addr.p] = frame_number * FRAME_SIZE;\n\t\t\t\tset_frame(frame_number);\n\t\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"allocated frame \" + std::to_string(disk[disk[addr.s] + addr.p]));\n\t\t\t}\n\t\t\toutput(std::to_string(disk[disk[addr.s] + addr.p] + addr.w));\n\t\t\toutput(\" \");\n\t\t\ttlb->set_frame_cache(addr.sp, disk[disk[addr.s] + addr.p]);\n\t\t\tLoggerFactory::GetLogger()->log(tag, msg + \"at address \" + std::to_string(disk[disk[addr.s] + addr.p] + addr.w));\n\t\t}\n\t}\n\tLoggerFactory::GetLogger()->log(tag, \"Ending write for virtual address \" + std::to_string(virtual_address));\n}\n\nvoid pm::output(std::string s) {\n\tout << s;\n}\n\nint pm::get_segment_table(int virtual_address) { // returns s\n\t// segement table are the 9 leading bits of the argument.\n\t// The total length an address can be is 28 (4 bits unused).\n\tint mask = ((512 - 1) << 19);\n\treturn (virtual_address & mask) >> 19;\n}\n\nint pm::get_page_table(int virtual_address) { // returns p\n\t// page table are the 10 middle bits of the argument after the segement table.\n\t// The total length an address can be is 28 (4 bits unused).\n\tint mask = ((1024 - 1) << 9);\n\treturn (virtual_address & mask) >> 9;\n}\n\nint pm::get_offset(int virtual_address) { // returns w\n\t// offset are the 9 least significant bits of the argument.\n\t// The total length an address can be is 28 (4 bits unused).\n\tint mask = 512 - 1;\n\treturn (virtual_address & mask);\n}\n\nint pm::get_free_frame(int size) {\n\t// just starting from 0 to 31, find an open bit.\n\tsize = (1 << size) - 1;\n\tfor (int i = 0; i < 32; i++) {\n\t\tif (bitmask[i] < ((1l << 32) - 1)) {\n\t\t\tfor (int j = 0; j < 32; j++) {\n\t\t\t\t// find the open position\n\t\t\t\tif (!(bitmask[i] & (size<<j))) {\n\t\t\t\t\t// the jth bit is free, so frame j is free.\n\t\t\t\t\treturn j + (i * 32);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprint_bitmap();\n\treturn -1;\n}\n\nvoid pm::set_frame(int frame) {\n\tint mask = floor(frame / 32);\n\tframe = frame % 32;\n\tbitmask[mask] |= (1 << frame);\n\tprint_bitmap();\n}\n\nvoid pm::print_bitmap() {\n\tstd::string tag = CLASS_TAG + \"print_bitmap()\";\n\tfor (int i = 0; i < 32 && bitmask[i]; i++) {\n\t\tLoggerFactory::GetLogger()->log(tag, \"Bitmap \" + std::to_string(i) + \" = \" + std::to_string(bitmask[i]));\n\t}\n}\n" }, { "alpha_fraction": 0.6204859018325806, "alphanum_fraction": 0.6290216445922852, "avg_line_length": 20.15277862548828, "blob_id": "fa91c23003e560cc13ec42f19c66a52936f54405", "content_id": "a5792bc3d57b95f5eed028666f4509af3fcd18e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1523, "license_type": "no_license", "max_line_length": 68, "num_lines": 72, "path": "/cs141/project1/src/main.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"grammer.hpp\"\n#include \"set.hpp\"\n#include \"jump.hpp\"\n#include \"jumpt.hpp\"\n#include \"halt.hpp\"\n#include \"statements.hpp\"\n#include \"writer.hpp\"\n#include <iostream>\n#include <fstream>\n\nusing std::string;\nusing std::cout;\nusing std::endl;\nusing std::ifstream;\n\nStatement* parseLine(string line);\nvoid sanitizeString(string& line);\nvoid processLine(Statement *nonterm);\nint main(int argc, char ** argv) {\n\tif (argc < 2) {\n\t\tcout << \"Please run with filename (ex: SIMPLESEM file.S)\" << endl;\n\t\treturn 1;\n\t}\n\tstring file(argv[argc - 1]);\n\tstring line;\n\tifstream ifs(file.c_str());\n\n\t// open file, read contents.\n\tint i = 0;\n\tif (ifs.is_open()) {\n\t\tcout << \"Program\" << endl;\n\t\twhile(ifs.good()) {\n\t\t\tstd::getline(ifs, line);\n\t\t\tsanitizeString(line);\n\t\t\tprocessLine(parseLine(line));\n\t\t}\n\t\tifs.close();\n\t}\n\treturn 0;\n}\n\nStatement* parseLine(string line) {\n\tif (line.find(\"set\") == 0 || line.find(\"SET\") == 0) {\n\t\treturn new Set(line);\n\t}\n\telse if (line.find(\"jumpt\") == 0 || line.find(\"JUMPT\") == 0) {\n\t\treturn new Jumpt(line);\n\t}\n\telse if (line.find(\"jump\") == 0 || line.find(\"JUMP\") == 0) {\n\t\treturn new Jump(line);\n\t}\n\telse if (line.find(\"halt\") == 0 || line.find(\"HALT\") == 0) {\n\t\treturn new Halt(line);\n\t}\n\telse\n\t\treturn NULL;\n}\n\nvoid sanitizeString(string& line) {\n\tif (line.find(\"\\r\") != string::npos) {\n\t\t// delete the last two characters.\n\t\tline.erase(line.find(\"\\r\"));\n\t}\n}\n\nvoid processLine(Statement *nonterm) {\n\tif (nonterm != NULL) {\n\t\tcout << \"Statement\" << endl;\n\t\tnonterm->parse();\n\t\tdelete nonterm;\n\t}\n}\n" }, { "alpha_fraction": 0.7078189253807068, "alphanum_fraction": 0.7078189253807068, "avg_line_length": 21.8125, "blob_id": "392b0e5e8f309bd796634122e2807d4a872a77cf", "content_id": "48b00ba894e505fd8f6dd98c135fadd495da9310", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 729, "license_type": "no_license", "max_line_length": 70, "num_lines": 32, "path": "/cs143B/project1/header/rcb.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"eventlistener.h\"\n#include \"statuses.h\"\n#include <vector>\n#include <pair>\n\nusing std::vector;\nusing std::pair;\n/**\n * Resource control block. \n * Contains data about a resource.\n */\n#ifndef RCB_H\n#define RCB_H\nclass PCB;\nclass RCB : public EventListener {\npublic:\n\tRCB();\n\tRCB(int arg_id, string arg_name, int arg_allocated);\n\tint id;\n\tint total;\n\tint allocated;\n\tstring name;\n\tstatus_t status;\n\tvector<pair<int, PCB *>> waiting_list;\n\tfriend ostream& operator<<(ostream& outs, RCB &obj);\n\tvirtual EventListener* on_delete(string arg_name) { return nullptr; }\n\tvirtual EventListener* on_request(string arg_name) {\n\t\treturn !name.compare(arg_name) ? this : nullptr;\n\t}\n\tvirtual void has_deleted(string name) { }\n};\n#endif" }, { "alpha_fraction": 0.6099068522453308, "alphanum_fraction": 0.6153261065483093, "avg_line_length": 24.46489143371582, "blob_id": "48eb840d81c60c95cc1d6e28bc4a0d879775926a", "content_id": "e70e276531083d8b2d1ce3c27a135c2411ea83d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10518, "license_type": "no_license", "max_line_length": 127, "num_lines": 413, "path": "/cs141/project1/src/semparser.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <string>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n#include <fstream>\n\nusing std::ifstream;\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\n/**\n * Grammar \n * Simple parser abstract class. Each class that inherits this\n * will be able to parse some kind of SIMPLESEM command.\n * \n * Each grammar will hold reference to a reader class. The\n * reader will split some command by spaces, and figure out\n * what to create.\n */\n\nclass Grammar\n{\npublic:\n\tvirtual Grammar* parse() = 0;\nprotected:\n\tstd::string parseCommand(std::string _msLine, std::string keywordLow, std::string keywordUpper) {\n\t\tif (_msLine.find(keywordUpper) == std::string::npos && _msLine.find(keywordLow) == std::string::npos) return \"\";\n\t\tint tokenLoc = _msLine.find(keywordUpper) ? _msLine.find(keywordUpper) : _msLine.find(keywordLow);\n\t\treturn _msLine.substr(tokenLoc + keywordLow.length() + 1);\n\t}\n};\n\nclass Statement : public Grammar\n{\npublic:\n\tStatement(std::string line) : _msLine(line), isInStatement(false), isInTerm(false) { }\n\tvirtual ~Statement() = 0;\n\tvirtual Grammar* parse() = 0;\n\tvirtual std::vector<std::string>* getKeywords() = 0;\n\tbool isExpr(std::string s) {\n\t\tstd::string output = \"\";\n\t\ts.erase(std::remove(s.begin(), s.end(), ' '), s.end());\n\t\tisExpr(s, output);\n\t\tstd::cout << output;\n\t\treturn true;\n\t};\n\tbool isExpr(std::string s, std::string& w);\n\tbool isTerm(const std::string& s, std::string& w);\n\tbool isFactor(const std::string& s, std::string& w);\n\tbool isNumber(const std::string& s, std::string& w) {\n\t\tstd::string::const_iterator it = s.begin();\n\t\twhile (it != s.end() && std::isdigit(*it) != false) { it++; }\n\t\tbool good = !s.empty() && it == s.end();\n\t\tif (good) w += \"Number\\n\";\n\t\treturn good;\n\t};\n\tbool isKeyword(const std::string& s) {\n\t\tgetKeywords();\n\t\tstd::vector<std::string> *keywordsPtr = _mvKeywords;;\n\t\tif (keywordsPtr == NULL) return false;\n\t\tstd::vector<std::string> keywords = *keywordsPtr;\n\t\tbool good = std::find(keywords.begin(), keywords.end(), s) != keywords.end();\n\t\treturn good;\n\t}\n\tbool getArguments(std::string line, std::string *arg1, std::string *arg2) {\n\t\tstd::string left = \"default\";\n\t\tsize_t pos = line.find(\",\");\n\t\tif (pos == std::string::npos) return false;\n\t\twhile (pos != std::string::npos) {\n\t\t\t*arg1 = line.substr(0, pos);\n\t\t\tline.erase(0, pos + 1);\n\t\t\tpos = line.find(\",\");\n\t\t} \n\t\tif (line[0] == ' ') line.erase(0, 1);\n\t\t*arg2 = line;\n\t\treturn true;\n\t}\nprotected:\n\tstd::string _msLine;\n\tstd::vector<std::string> *_mvKeywords;\n\tbool isInStatement; \n\tbool isInTerm; \n\tbool isInFactor;\n};\n\ninline Statement::~Statement() {}\n// generic base class for recursive instantiation.\nclass Recurrence : public Statement\n{\npublic: \n\tRecurrence(std::string s, bool isStatement, bool isTerm, bool isFactor);\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n\tstd::string toPrint;\n};\n\nRecurrence::Recurrence(std::string s, bool isStatement, bool isTerm, bool isFactor) : Statement(s) {\n\t_mvKeywords = new vector<string>();\n\tisInStatement = isStatement;\n\tisInTerm = isTerm;\n\tisInFactor = isFactor;\n}\n\nstd::vector<std::string>* Recurrence::getKeywords() {\n\treturn _mvKeywords;\n}\n\nbool Statement::isExpr(std::string s, std::string& w) {\n\t// split by plus or minus, as long as they aren't nested at all.\n\tstd::string ops = \"+-\";\n\tif (s.find_first_of(ops) == std::string::npos) {\n\t\t// no operators, yay!\n\t\tw += \"Expr\\n\";\n\t\tisTerm(s, w);\n\t} else if (s.find_first_of(\"()[]\") == std::string::npos) {\n\t\tstd::string copy = s + ops[0];\n\t\tsize_t pos = copy.find_first_of(ops);\n\t\tw += \"Expr\\n\";\n\t\tRecurrence *r;\n\t\twhile (pos != std::string::npos) {\n\t\t\t// process the invidual halfs.\n\t\t\tr = new Recurrence(copy.substr(0, pos), true, false, false);\n\t\t\tr->parse();\n\t\t\tw += r->toPrint;\n\t\t\tdelete r;\n\t\t\tcopy.erase(0, pos + 1);\n\t\t\tpos = copy.find_first_of(ops);\t\n\t\t}\n\t} else {\n\t\tint nestCount = 0, lastPos = 0;\n\t\tbool any = false;\n\t\tw += \"Expr\\n\";\n\t\tstd::string copy = s;\n\t\tRecurrence *r;\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tif (s[i] == '(' || s[i] == '[') nestCount++;\n\t\t\telse if (s[i] == ')' || s[i] == ']') nestCount--;\n\t\t\telse if (nestCount == 0 && ops.find_first_of(s[i]) != std::string::npos) {\n\t\t\t\t// we found an operator, that is not nested. Cut, and process.\n\t\t\t\tstd::string term = copy.substr(lastPos, i);\n\t\t\t\tr = new Recurrence(term, true, false, false);\n\t\t\t\tr->parse();\n\t\t\t\tw += r->toPrint;\n\t\t\t\tdelete r;\n\t\t\t\tlastPos = i;\n\t\t\t\tany = true;\n\t\t\t}\n\t\t}\t\n\t\t\n\t\t// call isTerm on the last piece.\n\t\tif (any) isTerm(copy.substr(lastPos + 1), w);\n\t\telse isTerm(copy, w);\n\t}\n\treturn true;\n};\nbool Statement::isTerm(const std::string& s, std::string& w) {\n\tstd::string ops = \"*/%\";\n\tif (s.find_first_of(ops) == std::string::npos) {\n\t\t// no operators, yay!\n\t\tw += \"Term\\n\";\n\t\tisFactor(s, w);\n\t} else if (s.find_first_of(\"()[]\") == std::string::npos) {\n\t\t// Seperate terms\n\t\tstd::string copy = s + ops[0];\n\t\tsize_t pos = copy.find_first_of(ops);\n\t\tRecurrence *r;\n\t\tw += \"Term\\n\";\n\t\twhile (pos != std::string::npos) {\n\t\t\t// process the invidual halfs.\n\t\t\tr = new Recurrence(copy.substr(0, pos), false, true, false);\n\t\t\tr->parse();\n\t\t\tw += r->toPrint;\n\t\t\tdelete r;\n\t\t\tcopy.erase(0, pos + 1);\n\t\t\tpos = copy.find_first_of(ops);\t\n\t\t}\n\t} else {\n\t\tint nestCount = 0, lastPos = 0;\n\t\tbool any = false;\n\t\tstd::string copy = s;\n\t\tRecurrence *r;\n\t\tw += \"Term\\n\";\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tif (s[i] == '(' || s[i] == '[') nestCount++;\n\t\t\telse if (s[i] == ')' || s[i] == ']') nestCount--;\n\t\t\telse if (nestCount == 0 && ops.find_first_of(s[i]) != std::string::npos) {\n\t\t\t\t// we found an operator, that is not nested. Cut, and process.\n\t\t\t\tstd::string term = copy.substr(lastPos, i);\n\t\t\t\tr = new Recurrence(term, false, true, false);\n\t\t\t\tr->parse();\n\t\t\t\tw += r->toPrint;\n\t\t\t\tdelete r;\n\t\t\t\tlastPos = i;\n\t\t\t\tany = true;\n\t\t\t}\n\t\t}\t\n\t\t\n\t\t// call isTerm on the last piece.\n\t\tif (any) isFactor(copy.substr(lastPos), w);\n\t\telse isFactor(copy, w);\n\t}\n\treturn false;\n};\nbool Statement::isFactor(const std::string& s, std::string& w) {\n\tif (s[0] == 'D' && s[1] == '[') {\n\t\t// nested expression...yaaay.\n\t\tw += \"Factor\\n\";\n\t\tRecurrence *r = new Recurrence(s.substr(2, s.rfind(']', s.length()) - 2), false, false, false); // allowed to expressions.\n\t\tr->parse();\n\t\tw += r->toPrint;\n\t} else if (s[0] == '(') {\n\t\tw+= \"Factor\\n\";\n\t\tRecurrence *r = new Recurrence(s.substr(1, s.rfind(')', s.length()) - 1), false, false, false); // allowed to be expressions.\n\t\tr->parse();\n\t\tw += r->toPrint;\n\t} else {\n\t\tw += \"Factor\\n\";\n\t\tisNumber(s, w);\n\t}\n\treturn false;\n};\n\nGrammar* Recurrence::parse() {\n\tif (isInFactor)\n\t\tisNumber(_msLine, toPrint);\n\telse if (isInTerm)\n\t\tisFactor(_msLine, toPrint);\n\telse if (isInStatement)\n\t\tisTerm(_msLine, toPrint);\n\telse\n\t\tisExpr(_msLine, toPrint);\n\treturn this;\n}\nclass Halt : public Statement\n{\npublic:\n\tHalt(std::string);\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n};\n\nHalt::Halt(string line) : Statement(line) {\n\t_mvKeywords = new vector<string>();\n}\n\nvector<string>* Halt::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Halt::parse() {\n\tif (_msLine.find(\",\") != string::npos) return NULL; // no comma args;\n\t_msLine = parseCommand(_msLine, \"halt \", \"HALT \");\n\treturn this;\n}\n\nclass Jump : public Statement\n{\npublic:\n\tJump(std::string);\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n};\n\n\nJump::Jump(string line) : Statement(line) {\n\t_mvKeywords = new vector<string>();\n}\n\nvector<string>* Jump::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Jump::parse() {\n\tif (_msLine.find(\",\") != string::npos) return NULL; // no comma args.\n\t_msLine = parseCommand(_msLine, \"jump \", \"JUMP \");\n\tcout << \"Jump\" << endl;\n\tif (isExpr(_msLine)) { \n\t\treturn this;\n\t}\n\telse return NULL;\t\n}\n\nclass Jumpt : public Statement\n{\npublic:\n\tJumpt(std::string);\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n};\n\nJumpt::Jumpt(string line) : Statement(line) {\n\t_mvKeywords = new vector<string>();\n}\n\nvector<string>* Jumpt::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Jumpt::parse() {\n\tif (_msLine.find(\",\") == string::npos) return NULL; // needs comma args.\n\tstring left, right;\n\t_msLine = parseCommand(_msLine, \"jumpt \", \"JUMPT \");\n\tif (!getArguments(_msLine, &left, &right)) return NULL;\n\tcout << \"Jumpt\" << endl;\n\tif (isExpr(left)) {}\n\n\t// split right by token args (!=, ==, >, <, >=, <=)\n\tint pos = right.find_first_of(\"!=><\");\t\n\tif (right[pos + 1] == '=') {\n\t\tisExpr(right.substr(0, pos));\n\t\tisExpr(right.substr(pos + 3));\n\t} else {\n\t\tisExpr(right.substr(0, pos));\n\t\tisExpr(right.substr(pos + 2));\n\t}\n\treturn this; \n}\n\nclass Set : public Statement\n{\npublic:\n\tSet(std::string);\n\t~Set();\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n};\n\n\nSet::Set(string line) : Statement(line) {\n\t_mvKeywords = new std::vector<string>();\n\t_mvKeywords->push_back(\"read\");\n\t_mvKeywords->push_back(\"write\");\n}\n\nSet::~Set() {\n\tdelete _mvKeywords;\n}\n\nvector<string>* Set::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Set::parse() {\n\tif (_msLine.find(\",\") == string::npos) return NULL;\n\t// parse out the keyword of the command\n\tstring left = \"\", right = \"\";\n\t_msLine = parseCommand(_msLine, \"set \", \"SET \"); \n\tif (!getArguments(_msLine, &left, &right)) return NULL; \n\t\n\t// ensure both arguments are expressions;\n\tcout << \"Set\" << endl;\n\tif ((isKeyword(left) || isExpr(left)) && (isKeyword(right) || isExpr(right))) {\n\t\treturn this;\n\t}\n\telse return NULL;\n}\n\nStatement* parseLine(string line) {\n\tif (line.find(\"set\") == 0 || line.find(\"SET\") == 0) {\n\t\treturn new Set(line);\n\t}\n\telse if (line.find(\"jumpt\") == 0 || line.find(\"JUMPT\") == 0) {\n\t\treturn new Jumpt(line);\n\t}\n\telse if (line.find(\"jump\") == 0 || line.find(\"JUMP\") == 0) {\n\t\treturn new Jump(line);\n\t}\n\telse if (line.find(\"halt\") == 0 || line.find(\"HALT\") == 0) {\n\t\treturn new Halt(line);\n\t}\n\telse\n\t\treturn NULL;\n}\n\nvoid sanitizeString(string& line) {\n\tif (line.find(\"\\r\") != string::npos) {\n\t\t// delete the last two characters.\n\t\tline.erase(line.find(\"\\r\"));\n\t}\n}\n\nvoid processLine(Statement *nonterm) {\n\tif (nonterm != NULL) {\n\t\tcout << \"Statement\" << endl;\n\t\tnonterm->parse();\n\t\tdelete nonterm;\n\t}\n}\n\nint main(int argc, char ** argv) {\n\tif (argc < 2) {\n\t\tcout << \"Please run with filename (ex: SIMPLESEM file.S)\" << endl;\n\t\treturn 1;\n\t}\n\tstring file(argv[argc - 1]);\n\tstring line;\n\tifstream ifs(file.c_str());\n\n\t// open file, read contents.\n\tint i = 0;\n\tif (ifs.is_open()) {\n\t\tcout << \"Program\" << endl;\n\t\twhile(ifs.good()) {\n\t\t\tstd::getline(ifs, line);\n\t\t\tsanitizeString(line);\n\t\t\tprocessLine(parseLine(line));\n\t\t}\n\t\tifs.close();\n\t}\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.6595744490623474, "alphanum_fraction": 0.6595744490623474, "avg_line_length": 10.75, "blob_id": "600297d760325446448278a96727ddd88e245807", "content_id": "60f19363a45e7fecd47dcc98b4b6dc27a905a2ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 47, "license_type": "no_license", "max_line_length": 25, "num_lines": 4, "path": "/cs143A/project7/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "all:\n\tgcc -o myls myls.c -ggdb\nclean:\n\trm myls\n" }, { "alpha_fraction": 0.682692289352417, "alphanum_fraction": 0.682692289352417, "avg_line_length": 25, "blob_id": "c2a16e4d281dd0105bb757ae9d5750b8bbe0c26e", "content_id": "ab9edd07316dd499cc0e155f167ccb89bcab8dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 104, "license_type": "no_license", "max_line_length": 63, "num_lines": 4, "path": "/cs146/hw2/lss", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Very simple script, using the -lS commands to sort the output\nexec /bin/ls -lS | grep ^-\n" }, { "alpha_fraction": 0.5923718810081482, "alphanum_fraction": 0.627731442451477, "avg_line_length": 34.9571418762207, "blob_id": "484f6db45ac1ee97367dd3f62f12468ce5d20ecf", "content_id": "92b11a2fb5491f4d212f3e94238d35bb3931a953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2517, "license_type": "no_license", "max_line_length": 128, "num_lines": 70, "path": "/French/jsonParser.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\nfrom json import JSONDecoder as dec\nimport calendar\nimport unidecode\nclass JSONCalenderAdder:\n def __init__(self, s):\n self.dec = dec()\n self.data = self.dec.decode(s)\n self.datemap = {v: k for k, v in enumerate(calendar.month_abbr)}\n\n def info(self):\n print self.datemap\n\n def __format(self, date, title, uid):\n print \"BEGIN:VEVENT\"\n print \"DTSTART:2016\"+str(date)+\"T100000\"\n print \"DTSTAMP:20161002T170411\"\n print \"UID:\" + str(uid)\n print \"SUMMARY:\"+title\n print \"END:VEVENT\"\n\n def generate(self):\n assignments = self.data[\"Results\"][\"dayInfoArray\"]\n for day in assignments:\n reminderdate = day[\"date\"]\n reminderdate = reminderdate.split(\" \")\n month = str(self.datemap[str(reminderdate[1])[:3]])\n daynum = str(reminderdate[2])\n if len(daynum) == 1:\n daynum = \"0\" + daynum\n \n # get each assignment\n for entry in day[\"assignments\"]:\n info = entry[\"activityInfo\"]\n exnum,title = (info[\"exNum\"][1:],info[\"title\"][1:])\n exnum = unidecode.unidecode(exnum[exnum.index(\">\")+1:exnum.index(\"<\")])\n exnum = ''.join(e for e in exnum if e.isalnum())\n title = unidecode.unidecode(title[title.index(\">\")+1:title.index(\"<\")])\n title = ''.join(e for e in title if e.isalnum())\n activityid=info[\"activity_id\"]\n self.__format(str(month)+daynum, str(exnum) + \" \" + title, activityid)\n\nprint \"BEGIN:VCALENDAR\"\nprint \"PRODID:-//Office of Information and Technology, University of California in Irvine//NONSGML Calendar Course Download//EN\"\nprint \"VERSION:2.0\"\nprint \"METHOD:PUBLISH\"\nprint \"CALSCALE:GREGORIAN\"\nprint \"X-WR-TIMEZONE:America/Los_Angeles\"\nprint \"BEGIN:VTIMEZONE\"\nprint \"TZID:America/Los_Angeles\"\nprint \"X-LIC-LOCATION:America/Los_Angeles\"\nprint \"BEGIN:DAYLIGHT\"\nprint \"TZOFFSETFROM:-0800\"\nprint \"TZOFFSETTO:-0700\"\nprint \"TZNAME:PDT\"\nprint \"DTSTART:19700308T020000\"\nprint \"RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\"\nprint \"END:DAYLIGHT\"\nprint \"BEGIN:STANDARD\"\nprint \"TZOFFSETFROM:-0700\"\nprint \"TZOFFSETTO:-0800\"\nprint \"TZNAME:PST\"\nprint \"DTSTART:19701101T020000\"\nprint \"RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\"\nprint \"END:STANDARD\"\nprint \"END:VTIMEZONE\"\nfor f in [\"week1.json\", \"week2.json\", \"week3.json\"]:\n cal=JSONCalenderAdder(open(f).read())\n cal.generate()\nprint \"END:VCALENDAR\"\n" }, { "alpha_fraction": 0.6528365612030029, "alphanum_fraction": 0.6604572534561157, "avg_line_length": 18.683332443237305, "blob_id": "77ddd06b9c25d98b394502de6276b81d21556e3b", "content_id": "f18668fdf67c80b6a04507b2ce2d348da5832d9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1181, "license_type": "no_license", "max_line_length": 98, "num_lines": 60, "path": "/cs143A/project2/handle_signals.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <signal.h>\n#include <unistd.h>\n#include <string.h>\n\nint sigint_count;\nint sigquit_count;\nint sigtermstop_count;\nconst int STOP_COUNT=3;\nstruct sigaction act;\n\nvoid sig_handler(int signum, siginfo_t *info, void *ptr)\n{\n\tswitch (signum) {\n\t\tcase SIGINT:\n\t\t\tsigint_count++;\n\t\t\tprintf(\"I\");\n\t\t\tfflush(stdout);\n\t\t\tbreak;\n\t\tcase SIGQUIT:\n\t\t\tsigquit_count++;\n\t\t\tprintf(\"Q\");\n\t\t\tfflush(stdout);\n\t\t\tbreak;\n\t\tcase SIGTSTP:\n\t\t\tsigtermstop_count++;\n\t\t\tprintf(\"S\");\n\t\t\tfflush(stdout);\n\t\t\tbreak;\n\t}\n\tif (sigtermstop_count == STOP_COUNT) {\n\t\tprintf(\"\\nInterrupt: %d\\nStop: %d\\nQuit: %d\\n\", sigint_count, sigquit_count, sigtermstop_count);\n\t\texit(0);\n\t}\n}\n\nint main() \n{\n\t// using the sigaction manner.\n\tmemset(&act, 0, sizeof(act));\n\n\tact.sa_sigaction = sig_handler;\n\tact.sa_flags = SA_SIGINFO; // setting this will package an additional \n\t// data package containing some neat info (pid, time, etc)\n\n\t// set our constants.\n\tsigint_count = 0;\n\tsigquit_count = 0;\n\tsigtermstop_count = 0;\n\n\n\tsigaction(SIGINT, &act, NULL);\n\tsigaction(SIGQUIT, &act, NULL);\n\tsigaction(SIGTSTP, &act, NULL);\n\n\twhile (1) { sleep(1); }\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6544715166091919, "alphanum_fraction": 0.6951219439506531, "avg_line_length": 21.454545974731445, "blob_id": "2ed86471f81a0d723479a75e10f0f65457bf77f6", "content_id": "ae02ed533f67a895700ecef33dce71b7ba4764c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 246, "license_type": "no_license", "max_line_length": 56, "num_lines": 11, "path": "/cs143B/project2/io/iosystem.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#ifndef IO_SYSTEM_H\n#define IO_SYSTEM_H\nclass IO_system {\npublic:\n\tvirtual void read_block(int i, unsigned char *p) = 0;\n\tvirtual void write_block(int i, unsigned char *p) = 0;\t\n\tstatic IO_system* CreateIOSystem();\n};\n#endif" }, { "alpha_fraction": 0.6934673190116882, "alphanum_fraction": 0.6934673190116882, "avg_line_length": 18.899999618530273, "blob_id": "2b1c1f0e0e79fad7345f0bf55d581d1a7ea0d4e6", "content_id": "442c924e2b97badf747d7aeaf4f7eed10211a1aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 597, "license_type": "no_license", "max_line_length": 111, "num_lines": 30, "path": "/cs141/project1/src/writer.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"writer.hpp\"\n#include <string>\n#include <vector>\n#include <iostream>\n#include <fstream>\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::ofstream;\n\nWriter::Writer(string filename) {\n\t_mofsFile.open(filename.c_str());\n}\n\nvoid Writer::write(string line) {\n\t_mvLinesToWrite.push_back(line);\n}\n\nvoid Writer::flush() {\n\tfor (vector<string>::reverse_iterator iter = _mvLinesToWrite.rbegin(); iter != _mvLinesToWrite.rend(); iter++)\n\t\t_mofsFile << *iter << endl;\n\t_mvLinesToWrite.clear();\n}\n\nWriter::~Writer() {\n\t_mofsFile.close();\n\t_mvLinesToWrite.clear();\n}\n" }, { "alpha_fraction": 0.6622754335403442, "alphanum_fraction": 0.6706587076187134, "avg_line_length": 21.567567825317383, "blob_id": "399f23cfc9c6f341154d3540ed87301473486ef4", "content_id": "bd81a409c592c223e0199d2e16c40fcd0740f03a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 835, "license_type": "no_license", "max_line_length": 61, "num_lines": 37, "path": "/cs146/hw5/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "FILES=main.c obj/parser.o obj/engine.o\nOUTPUT=nsh\nGCC=gcc -std=gnu99\nall: obj/parser.o obj/engine.o\n\t$(GCC) -o $(OUTPUT) $^ main.c\ndebug: parser.dSYM engine.dSYM\n\t$(GCC) -ggdb -o $(OUTPUT) $(FILES)\nclean: parser-clean engine-clean\n\trm nsh\n\trm -rf $(OUTPUT).dSYM 2>/dev/null\n\trm -r obj\n\nobj/parser.o: parser.c\n\t$(GCC) -c $^\n\tmkdir obj 2>/dev/null || echo \"dir exists. Skipping for now\"\n\tmv parser.o obj\n\nparser.dSYM: parser.c\n\t$(GCC) -ggdb -c $^\n\tmkdir obj 2>/dev/null || echo \"dir exists. Skipping for now\"\n\tmv parser.o obj\n\nparser-clean: \n\trm obj/parser.o\n\nobj/engine.o: engine.c\n\t$(GCC) -c $^\n\tmkdir obj 2>/dev/null || echo \"dir exists. Skipping for now\"\n\tmv engine.o obj\n\nengine.dSYM: engine.c\n\t$(GCC) -ggdb -c engine.c\n\tmkdir obj 2>/dev/null || echo \"dir exists. Skipping for now\"\n\tmv engine.o obj\n\nengine-clean: \n\trm obj/engine.o\n" }, { "alpha_fraction": 0.6918367147445679, "alphanum_fraction": 0.7020407915115356, "avg_line_length": 16.5, "blob_id": "44cefeb24bfdbe65c62859d82bcc6050924faaf9", "content_id": "a2915056f6724358e6bf8a66ca244d9608b8e0bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 490, "license_type": "no_license", "max_line_length": 35, "num_lines": 28, "path": "/cs146/hw5/parser.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\n#ifndef PARSER_H\n#define PARSER_H\n#define ARG_FLAG_SIZE 16\n#define MAX_PIPE 255\ntypedef char* string;\ntypedef struct task_s {\n int redirect;\n int flag_size;\n int arg_size;\n string cmd;\n string flags[ARG_FLAG_SIZE];\n string args[ARG_FLAG_SIZE];\n string outputname;\n string inputname;\n} task_t;\n\ntypedef struct job_s {\n\tint task_count;\n\tint background;\n\tint envvar;\n\ttask_t tasks[MAX_PIPE];\n} job_t;\n\njob_t *parse(int len, char *input);\n#endif\n" }, { "alpha_fraction": 0.6791666746139526, "alphanum_fraction": 0.6791666746139526, "avg_line_length": 17.461538314819336, "blob_id": "3a038841ed531f1a53d7158751d037ad45adc5c1", "content_id": "5e7fc39dfb8d030fa4fb7f7c66203238c7a35d71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 240, "license_type": "no_license", "max_line_length": 63, "num_lines": 13, "path": "/cs146/hw2/whoson", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# invoded via whoson. Iterates through all results of users and\n# prints the name iff they are an undergrad\noutput=\"\"\nfor u in `users`\ndo\n\tif groups $u | grep -q \"ugrad\"; then\n output=\"$output $u\"\n\tfi\ndone\n\necho $output\n" }, { "alpha_fraction": 0.6373857855796814, "alphanum_fraction": 0.6725228428840637, "avg_line_length": 32.904762268066406, "blob_id": "4ecc5b051d454311931f698016468622546b9f80", "content_id": "aef50d9682d6ca28c44a5968a0259950ec520a96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1423, "license_type": "no_license", "max_line_length": 108, "num_lines": 42, "path": "/cs178/hw3/one.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport mltools as ml\nimport numpy as np\nimport mltools.logistic2 as lc2\n\niris = np.genfromtxt(\"data/iris.txt\",delimiter=None)\nX, Y = iris[:,0:2], iris[:,-1] # get first two features & target\nX,Y = ml.shuffleData(X,Y) # reorder randomly (important later)\nX,_ = ml.transforms.rescale(X) # works much better on rescaled data\nXA, YA = X[Y<2,:], Y[Y<2] # get class 0 vs 1\nXB, YB = X[Y>0,:], Y[Y>0] # get class 1 vs 2\n\n# # ensure seperability\n# fig, ax = plt.subplots(1,2)\n# ml.plotClassify2D(None, XA[:,[0,1]],YA,axis=ax[0])\n# ml.plotClassify2D(None, XB[:,[0,1]],YB,axis=ax[1])\n# plt.show()\n\n# # Test of plot boundary\n# learner = lc2.logisticClassify2();\n# learner.theta=[[.5, 1, -.25]]\n# learner.classes=np.unique(YA)\n# learner.plotBoundary(XA, YA)\n# plt.show()\n\n# print learner.err(XA, YA)\n# fig, ax = plt.subplots(1,2)\n# learner.plotBoundary(XA,YA,axis=ax[0])\n# ml.plotClassify2D(learner, XA, YA,axis=ax[1])\n# plt.show()\n\n# The gradient is XT(theta - Y)\nfig, ax = plt.subplots(1,2)\nlearner = lc2.logisticClassify2(XA, YA)\nprint learner.err(XA,YA)\n\n\n# part two\n#\ta.) Can shatter a b and c but not d. There is no way to make points (2,2) and (8,7) in the same class\n#\tb.) Most points can be shatter. Since c can skew the origin point, you can scatter each point in c, \n#\t\tbut not in d. \n#\tc.) Can up to d. You can not put point (2,2) and 8,7 in the same class with 4,8 and 6,4 in the same class." }, { "alpha_fraction": 0.6462599635124207, "alphanum_fraction": 0.64894700050354, "avg_line_length": 27.393814086914062, "blob_id": "acdb76a108cc8a45dcc97fb21ba896068bc282e5", "content_id": "35000352a5761a3806eef561b0e0f3ee562b8dfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13770, "license_type": "no_license", "max_line_length": 131, "num_lines": 485, "path": "/ics46/program3/src/heap_priority_queue.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef HEAP_PRIORITY_QUEUE_HPP_\n#define HEAP_PRIORITY_QUEUE_HPP_\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <initializer_list>\n#include \"ics_exceptions.hpp\"\n#include \"iterator.hpp\"\n#include \"priority_queue.hpp\"\n#include <utility> //For std::swap function\n#include \"array_stack.hpp\"\n\n\nnamespace ics {\n\ntemplate<class T> class HeapPriorityQueue : public PriorityQueue<T> {\n using PriorityQueue<T>::gt; //Required because of templated classes\n public:\n HeapPriorityQueue() = delete;\n explicit HeapPriorityQueue(bool (*agt)(const T& a, const T& b));\n HeapPriorityQueue(int initialLength,bool (*agt)(const T& a, const T& b));\n HeapPriorityQueue(const HeapPriorityQueue<T>& to_copy);\n HeapPriorityQueue(std::initializer_list<T> il,bool (*agt)(const T& a, const T& b));\n HeapPriorityQueue(ics::Iterator<T>& start, const ics::Iterator<T>& stop,bool (*agt)(const T& a, const T& b));\n virtual ~HeapPriorityQueue();\n\n virtual bool empty () const;\n virtual int size () const;\n virtual T& peek () const;\n virtual std::string str () const;\n\n virtual int enqueue (const T& element);\n virtual T dequeue ();\n virtual void clear ();\n\n virtual int enqueue (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n\n virtual HeapPriorityQueue<T>& operator = (const HeapPriorityQueue<T>& rhs);\n virtual bool operator == (const PriorityQueue<T>& rhs) const;\n virtual bool operator != (const PriorityQueue<T>& rhs) const;\n\n template<class T2>\n friend std::ostream& operator << (std::ostream& outs, const HeapPriorityQueue<T2>& p);\n\n virtual ics::Iterator<T>& ibegin() const;\n virtual ics::Iterator<T>& iend () const;\n\n class Iterator : public ics::Iterator<T> {\n public:\n //KLUDGE should be callable only in begin/end\n Iterator(HeapPriorityQueue<T>* iterate_over, bool begin);\n Iterator(const Iterator& i);\n virtual ~Iterator();\n virtual T erase();\n virtual std::string str () const;\n virtual const ics::Iterator<T>& operator ++ ();\n virtual const ics::Iterator<T>& operator ++ (int);\n virtual bool operator == (const ics::Iterator<T>& rhs) const;\n virtual bool operator != (const ics::Iterator<T>& rhs) const;\n virtual T& operator * () const;\n virtual T* operator -> () const;\n private:\n HeapPriorityQueue<T> it; //Copy of pq to use as iterator via dequeue\n HeapPriorityQueue<T>* ref_pq;\n int expected_mod_count;\n bool can_erase = true;\n };\n\n virtual Iterator begin() const;\n virtual Iterator end () const;\n\n private:\n //See base class PriorityQueue\n //bool (*gt)(const T& a, const T& b);// gt(a,b) = true iff a has higher priority than b\n T* pq;\n int length = 0; //Physical length of the array (must be > .size()\n int used = 0; //Amount of array used\n int mod_count = 0; //For sensing concurrent modification\n void ensure_length(int new_length);\n int left_child (int i); //Useful abstractions for heaps as arrays\n int right_child (int i);\n int parent (int i);\n bool is_root (int i);\n bool in_heap (int i);\n void percolate_up (int i);\n void percolate_down (int i);\n };\n\ntemplate<class T>\nHeapPriorityQueue<T>::HeapPriorityQueue(bool (*agt)(const T& a, const T& b)) \n : PriorityQueue<T>(agt), mod_count(0) {\n gt = agt;\n pq = new T[length];\n}\n\n\ntemplate<class T>\nHeapPriorityQueue<T>::HeapPriorityQueue(int initial_length, bool (*agt)(const T& a, const T& b))\n : PriorityQueue<T>(agt), length(initial_length), mod_count(0) {\n if (length < 0)\n length = 0;\n pq = new T[length];\n}\n\n\ntemplate<class T>\nHeapPriorityQueue<T>::HeapPriorityQueue(const HeapPriorityQueue<T>& to_copy)\n : PriorityQueue<T>(to_copy.gt), length(to_copy.length), used(to_copy.used), mod_count(0) {\n pq = new T[length]; \n for (int i=0; i < to_copy.used; ++i)\n pq[i] = to_copy.pq[i];\n}\n\n\ntemplate<class T>\nHeapPriorityQueue<T>::HeapPriorityQueue(ics::Iterator<T>& start, const ics::Iterator<T>& stop, bool (*agt)(const T& a, const T& b))\n : PriorityQueue<T>(agt), mod_count(0) {\n pq = new T[length];\n enqueue(start,stop);\n}\n\n\ntemplate<class T>\nHeapPriorityQueue<T>::HeapPriorityQueue(std::initializer_list<T> il, bool (*agt)(const T& a, const T& b))\n : PriorityQueue<T>(agt), mod_count(0) {\n pq = new T[length];\n for (T pq_elem : il)\n enqueue(pq_elem);\n}\n\n\ntemplate<class T>\nHeapPriorityQueue<T>::~HeapPriorityQueue() {\n delete [] pq;\n}\n\n\ntemplate<class T>\ninline bool HeapPriorityQueue<T>::empty() const {\n return used == 0;\n}\n\n\ntemplate<class T>\nint HeapPriorityQueue<T>::size() const {\n return used;\n}\n\n\ntemplate<class T>\nT& HeapPriorityQueue<T>::peek () const {\n if (empty())\n throw EmptyError(\"HeapPriorityQueue::peek\");\n return pq[0];\n}\n\n\ntemplate<class T>\nstd::string HeapPriorityQueue<T>::str() const {\n std::ostringstream answer;\n answer << *this << \"(length=\" << length << \",used=\" << used << \",mod_count=\" << mod_count << \")\";\n return answer.str();\n}\n\n\ntemplate<class T>\nint HeapPriorityQueue<T>::enqueue(const T& element) {\n ensure_length(used + 1);\n pq[used] = element;\n // re heapify\n percolate_up(used++);\n mod_count++;\n return 1;\n}\n\n\ntemplate<class T>\nT HeapPriorityQueue<T>::dequeue() {\n if (empty())\n throw EmptyError(\"HeapPriorityQueue::dequeue\");\n T val = peek();\n // make the max the root, percolate down.\n pq[0] = pq[--used];\n percolate_down(0);\n ++mod_count;\n return val;\n}\n\n\ntemplate<class T>\nvoid HeapPriorityQueue<T>::clear() {\n used = 0;\n ++mod_count;\n}\n\n\ntemplate<class T>\nint HeapPriorityQueue<T>::enqueue(ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n int count = 0;\n for (; start != stop; ++start)\n count += enqueue(*start);\n return count;\n}\n\n\ntemplate<class T>\nHeapPriorityQueue<T>& HeapPriorityQueue<T>::operator = (const HeapPriorityQueue<T>& rhs) {\n if (rhs == *this)\n return *this;\n clear();\n ensure_length(rhs.used);\n gt = rhs.gt; //gt is in the base class\n enqueue(rhs.ibegin(), rhs.iend());\n ++mod_count;\n return *this;\n}\n\n\ntemplate<class T> \nbool HeapPriorityQueue<T>::operator == (const PriorityQueue<T>& rhs) const {\n if (this == &rhs)\n return true;\n if (used != rhs.size()||gt != rhs.gt)\n return false;\n //KLUDGE: should check for same == function used to prioritize, but cannot unless\n // it is made part of the PriorityQueue class (should it be? protected)?\n ics::Iterator<T>& rhs_i = rhs.ibegin(), &lhs_i = ibegin();\n for (int i = 0; i < used; i++, lhs_i++, rhs_i++) {\n if (*lhs_i != *rhs_i) return false;\n }\n return true;\n}\n\n\ntemplate<class T>\nbool HeapPriorityQueue<T>::operator != (const PriorityQueue<T>& rhs) const {\n return !(*this == rhs);\n}\n\n\ntemplate<class T>\nstd::ostream& operator << (std::ostream& outs, const HeapPriorityQueue<T>& p) {\n bool is_not_end = true;\n std::stringstream string_value(\"\"), temp(\"\");\n for (T val : p) {\n if (is_not_end) string_value << val;\n else {\n temp.str(string_value.str());\n string_value.str(std::string());\n string_value << val << \",\" << temp.str();\n }\n is_not_end =false;\n }\n outs << \"priority_queue[\" << string_value.str() << \"]:highest\";\n return outs;\n}\n\n\n//Insert constructor/methods here: see array_priority_queue.hpp\n\n//Insert heap helper methods here.\n\n\n//KLUDGE: memory-leak\ntemplate<class T>\nauto HeapPriorityQueue<T>::ibegin () const -> ics::Iterator<T>& {\n return *(new Iterator(const_cast<HeapPriorityQueue<T>*>(this),true));\n}\n\n//KLUDGE: memory-leak\ntemplate<class T>\nauto HeapPriorityQueue<T>::iend () const -> ics::Iterator<T>& {\n return *(new Iterator(const_cast<HeapPriorityQueue<T>*>(this),false));\n}\n\ntemplate<class T>\nauto HeapPriorityQueue<T>::begin () const -> HeapPriorityQueue<T>::Iterator {\n return Iterator(const_cast<HeapPriorityQueue<T>*>(this),true);\n}\n\ntemplate<class T>\nauto HeapPriorityQueue<T>::end () const -> HeapPriorityQueue<T>::Iterator {\n return Iterator(const_cast<HeapPriorityQueue<T>*>(this),false);\n}\n\n//Insert Iterator constructor/methods here: see array_priority_queue.hpp\n\ntemplate<class T>\nvoid HeapPriorityQueue<T>::ensure_length(int new_length) {\n if (length >= new_length)\n return;\n T* old_pq = pq;\n length = std::max(new_length,2*length);\n pq = new T[length];\n for (int i=0; i<used; ++i)\n pq[i] = old_pq[i];\n\n delete [] old_pq;\n}\n\n\ntemplate<class T>\nHeapPriorityQueue<T>::Iterator::Iterator(HeapPriorityQueue<T> *iterate_over, bool begin) \n : ref_pq(iterate_over), it(*iterate_over), expected_mod_count(ref_pq->mod_count) { \n if (!begin) {\n it.clear();\n }\n}\n\ntemplate<class T>\nHeapPriorityQueue<T>::Iterator::Iterator(const Iterator& i) \n : ref_pq(i.ref_pq), it(i.it), expected_mod_count(i.ref_pq->mod_count) { }\n\n\ntemplate<class T>\nHeapPriorityQueue<T>::Iterator::~Iterator() {\n}\n\n\ntemplate<class T>\nT HeapPriorityQueue<T>::Iterator::erase() {\n if (expected_mod_count != ref_pq->mod_count)\n throw ConcurrentModificationError(\"HeapPriorityQueue::Iterator::erase\");\n if (!can_erase)\n throw CannotEraseError(\"HeapPriorityQueue::Iterator::erase Iterator cursor already erased\");\n if (it.empty())\n throw CannotEraseError(\"HeapPriorityQueue::Iterator::erase Iterator cursor beyond end\");\n\n can_erase = false;\n T value = it.peek();\n // erase in actual code.\n\tint i;\n\tfor (i = 0; i < ref_pq->size() && ref_pq->pq[i] != value; i++)\n\t\t;\n\tref_pq->pq[i] = ref_pq->pq[--ref_pq->used];\n\tref_pq->percolate_down(i);\n\texpected_mod_count = ref_pq->mod_count;\n return value;\n}\n\n\ntemplate<class T>\nstd::string HeapPriorityQueue<T>::Iterator::str() const {\n std::ostringstream answer;\n answer << *ref_pq;\n answer << \"(current = \";\n answer << it;\n answer << \")\";\n return answer.str();\n}\n\n\ntemplate<class T>\nconst ics::Iterator<T>& HeapPriorityQueue<T>::Iterator::operator ++ () {\n if (expected_mod_count != ref_pq->mod_count)\n throw ConcurrentModificationError(\"HeapPriorityQueue::Iterator::operator ++\");\n \n // are we at the begining?\n if (!can_erase) can_erase = true;\n if (it.empty() && ref_pq != nullptr)\n ref_pq = nullptr;\n else \n it.dequeue();\n return *this;\n}\n\n\n//KLUDGE: can create garbage! (can return local value!)\ntemplate<class T>\nconst ics::Iterator<T>& HeapPriorityQueue<T>::Iterator::operator ++ (int) {\n if (expected_mod_count != ref_pq->mod_count)\n throw ConcurrentModificationError(\"HeapPriorityQueue::Iterator::operator ++(int)\");\n Iterator *copy = new Iterator(*this);\n // are we at the begining?\n if (!can_erase) can_erase = true;\n if (it.empty() && ref_pq != nullptr)\n ref_pq = nullptr;\n else \n it.dequeue();\n return *copy; \n}\n\n\ntemplate<class T>\nbool HeapPriorityQueue<T>::Iterator::operator == (const ics::Iterator<T>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n throw IteratorTypeError(\"HeapPriorityQueue::Iterator::operator ==\");\n if (expected_mod_count != ref_pq->mod_count)\n throw ConcurrentModificationError(\"HeapPriorityQueue::Iterator::operator ==\");\n if (ref_pq != rhsASI->ref_pq)\n throw ComparingDifferentIteratorsError(\"HeapPriorityQueue::Iterator::operator ==\");\n return this->it == rhsASI->it;\n}\n\n\ntemplate<class T>\nbool HeapPriorityQueue<T>::Iterator::operator != (const ics::Iterator<T>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n throw IteratorTypeError(\"HeapPriorityQueue::Iterator::operator !=\");\n if (expected_mod_count != ref_pq->mod_count)\n throw ConcurrentModificationError(\"HeapPriorityQueue::Iterator::operator !=\");\n if (ref_pq != rhsASI->ref_pq)\n throw ComparingDifferentIteratorsError(\"HeapPriorityQueue::Iterator::operator !=\");\n return !(*this == rhs);\n}\n\n\ntemplate<class T>\nT& HeapPriorityQueue<T>::Iterator::operator *() const {\n if (expected_mod_count != ref_pq->mod_count)\n throw ConcurrentModificationError(\"HeapPriorityQueue::Iterator::operator *\");\n if (it.empty() || !can_erase) \n throw IteratorPositionIllegal(\"HeapPriorityQueue::Iterator::operator * \");\n return it.peek();\n}\n\n\ntemplate<class T>\nT* HeapPriorityQueue<T>::Iterator::operator ->() const {\n if (expected_mod_count != ref_pq->mod_count)\n throw ConcurrentModificationError(\"HeapPriorityQueue::Iterator::operator ->\");\n return &it.peek();\n}\n\n/**\n * HELPER FUNCTIONS\n */\ntemplate<class T> \nint HeapPriorityQueue<T>::left_child(int i) {\n return (i * 2) + 1;\n}\n\ntemplate<class T> \nint HeapPriorityQueue<T>::right_child(int i) {\n return (i * 2) + 2;\n}\n\ntemplate<class T> \nint HeapPriorityQueue<T>::parent(int i) {\n return ((i % 2 == 1 ? i + 1 : i) / 2) - 1;\n}\n\ntemplate<class T>\nbool HeapPriorityQueue<T>::is_root(int i) {\n return i == 0;\n}\n\ntemplate<class T>\nbool HeapPriorityQueue<T>::in_heap(int i) {\n return i < used;\n}\n\ntemplate<class T>\nvoid HeapPriorityQueue<T>::percolate_up(int i) {\n // find parent and go up.\n int parentIndex = parent(i);\n if (is_root(i) || !gt(pq[i], pq[parentIndex])) \n\t return;\n std::swap(pq[parentIndex], pq[i]);\n percolate_up(parentIndex); // parentIndex now become's i.\n}\n\ntemplate<class T>\nvoid HeapPriorityQueue<T>::percolate_down(int i) {\n // leaf case\n if (left_child(i) >= used && right_child(i) >= used) \n // a leaf node, we're at the absolute end of our percolation.\n return;\n\n // can we swap?\n int higher_priority = gt(pq[left_child(i)], pq[right_child(i)]) ? left_child(i) : right_child(i);\n\n // continuation step\n if (gt(pq[higher_priority], pq[i])) \n {\n std::swap(pq[higher_priority], pq[i]);\n percolate_down(higher_priority);\n }\n}\n\n}\n#endif /* HEAP_PRIORITY_QUEUE_HPP_ */" }, { "alpha_fraction": 0.6883273124694824, "alphanum_fraction": 0.7075812220573425, "avg_line_length": 24.96875, "blob_id": "52e02b7895f4e36a516f88162fd612a9b45bef0e", "content_id": "1eaee83ba208bc0f04ee5630602b7efdd2c5128d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 831, "license_type": "no_license", "max_line_length": 51, "num_lines": 32, "path": "/cs177/hw6/normal.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\nfrom random import random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nl = [ random() for _ in range(50001) ]\nplt.hist(l, bins=np.linspace(0,1,1000))\n# plt.show()\n\n# this is not approximately normal. This is\n# because the docs actually state that it uses\n# a completely deterministic method called\n# Mersenne Twister, which is not approximately\n# normal. \n\n# Randrange is implemented very similarly. The only\n# way to get a uniformly randomly distrbution in \n# python is too use the guass method, and that's\n# not really exciting.\n\n# begin sums part a\nn=int(raw_input(\"Input n: \"))\nK=int(raw_input(\"Input k: \"))\nmatr=np.empty([n, K])\nfor i in range(0, n):\n\tfor j in range(0, K):\n\t\tmatr[i,j] = random()\n\nmatr=np.sum(matr, axis=0)\nprint \"mean,var=\",(np.mean(matr), np.var(matr))\nplt.hist(matr)\nplt.show()\n" }, { "alpha_fraction": 0.6308724880218506, "alphanum_fraction": 0.6577181220054626, "avg_line_length": 17.625, "blob_id": "29eea7d9a669d32a62dbff8cec6923e811da71e8", "content_id": "c90cf9d0f945ecbbd33c3888b50ead8644e4a9de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 298, "license_type": "no_license", "max_line_length": 108, "num_lines": 16, "path": "/cs146/hw3/lsrm", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Ian Schweer\n# 22514022\n\ntrash=$TRASH\necho \"The trash var is $TRASH\"\nif [[ \"$TRASH\" == \"\" ]]; then\n\techo \"The trash variable is not currently set. Consider setting an enviornment variable. Assuming ~/.Trash\"\n\ttrash=\"$HOME/.Trash\"\nfi\n\nif [ ! -e $trash ]; then\n\tmkdir $trash\nfi\n\nls -l $trash\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 11.5, "blob_id": "1a17e091e13be83eaa37a724b058747e92b74e74", "content_id": "d62f80f156c7bbc7e8c9ec26f4e0539b05d9a57f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 50, "license_type": "no_license", "max_line_length": 25, "num_lines": 4, "path": "/cs143A/project1/compute/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "all:\n\tgcc -o compute compute.c\nclean:\n\trm compute\n" }, { "alpha_fraction": 0.581499457359314, "alphanum_fraction": 0.6046251654624939, "avg_line_length": 26.92708396911621, "blob_id": "a183e91da1b7b6c6e2da73fbb64564bf3f06edda", "content_id": "b6a7e6898c30e6b6218d07542485960f172881b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2681, "license_type": "no_license", "max_line_length": 121, "num_lines": 96, "path": "/cs177/hw3/naive_bayes.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nclass params:\n\t_targets = []\n\t_data = []\n\t_classes = []\n\t_classProbs = []\n\tdef __init__(self, Data, Classes, Targets):\n\t\tself._targets = np.array(Targets)\n\t\tself._data = np.array(Data)\n\t\tself._classes = np.array(Classes)\n\t\tself._classProbs = np.array([self.lenfrac(Data[Targets==Classes[0]]) + 1, self.lenfrac(Data[Targets==Classes[1]]) + 1])\n\n\t# get frame \n\tdef lenfrac(self, var):\n\t\treturn 1. * len(var)\n\tdef params(self, j, i):\n\t\tif (j < 0 or j >= self._data.shape[1]):\n\t\t\traise Exception(\"j out of bounds\",j)\n\t\treturn self._data[self._targets == i, j]\n\n\tdef mprobs(self, j, k, i):\n\t\tvar = self.params(j, i);\n\t\treturn var[var == k]\n\n\tdef getclass(self, c):\n\t\treturn self._classProbs[self._classes==c][0]\n\n\tdef classprobs(self, c):\n\t\treturn self.getclass(c) / len(self._data)\n\n\tdef pofx(self, x):\n\t\t# given a vector of x values\n\t\t# compute the probability of the value\n\t\t# then multiply them all together.\n\t\tpx = 1.0\n\t\tfor i, xj in enumerate(x):\n\t\t\tX = self._data[:,i]\n\t\t\tcounter = 0\n\t\t\tfor y in X:\n\t\t\t\tcounter = counter + (y == xj)\n\t\t\tpx = (counter / self.lenfrac(X))\n\t\treturn px\n\n\tdef cprobs(self, j, k, i):\n\t\tdenom = self.getclass(i)\n\t\thead = self.lenfrac(self.mprobs(j,k,i))\n\t\t# naive bayes assumes conditional independence. So P[X|Y] = P(X)P(Y)\n\t\treturn (head + .5) / self.getclass(i)\n\nX = np.genfromtxt('data.txt')\nY = np.genfromtxt('labels.txt')\n\nclasses=[1,2]\np = params(X, classes, Y)\nprint \"p(C = 1) =\",p.getclass(classes[0]) / len(X)\nprint \"p(C = 2) =\",p.getclass(classes[1]) / len(X)\n\nfor c in classes:\n\tfor i in range(0,X.shape[1]): \n\t\tps = [p.cprobs(i, 1, c), p.cprobs(i, 2, c)]\n\t\tprint \"P(X =\",i,\"| C =\",c,\") [1, 2] = \", ps\n\n# train using only a subset of data.\n# Xte,Yte = X[1500:], Y[1500:]\n# predictions = np.array([])\n# for i in [1500, 50, 10]:\n# \tXtr,Ytr = (X[0:i], Y[0:i])\n# \tp = params(Xtr, classes, Ytr)\n# \tfor d in range(Xte.shape[0]):\n# \t\tpxji = np.empty(2) # P(Xj|C=i)\n# \t\tpxji.fill(1.0)\n# \t\tfor ci,c in enumerate(classes):\n# \t\t\ttemp = 1.0\n# \t\t\tfor ji,j in enumerate(Xte[d]):\n# \t\t\t\ttemp = temp * p.cprobs(ji, j, c)\n# \t\t\tpxji[ci] = temp * p.classprobs(c)\n# \t\tpredictions=np.append(predictions, classes[pxji.argmax()])\n# \tprint np.mean(predictions.reshape(Yte.shape) != Yte)\n# \tpredictions = np.array([])\t\t\n\nXte,Yte = X[20:], Y[20:]\npredictions = np.array([])\nfor i in [20]:\n\tXtr,Ytr = (X[0:i], Y[0:i])\n\tp = params(Xtr, classes, Ytr)\n\tfor d in range(Xtr.shape[0]):\n\t\tpxji = np.empty(2) # P(Xj|C=i)\n\t\tpxji.fill(1.0)\n\t\tfor ci,c in enumerate(classes):\n\t\t\ttemp = 1.0\n\t\t\tfor ji,j in enumerate(Xtr[d]):\n\t\t\t\ttemp = temp * p.cprobs(ji, j, c)\n\t\t\tpxji[ci] = (temp * p.classprobs(c)) / p.pofx(Xtr[d])\n\t\tprint pxji\n" }, { "alpha_fraction": 0.6209178566932678, "alphanum_fraction": 0.6281110644340515, "avg_line_length": 28.961206436157227, "blob_id": "5bd0058c0491fc3ed2a9941513927c7888f06535", "content_id": "51dae198b0622e71b733bb7ac19b31764b601ab9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6951, "license_type": "no_license", "max_line_length": 116, "num_lines": 232, "path": "/ics53/lab3/mallocshell.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "/* $begin shellmain */\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"csapp.h\"\n#include \"mm.h\"\n\n#define MAXARGS 128\n\ntypedef enum { ALLOC, FREE, BLOCKLIST, HWRITE, HREAD, BESTFIT, FIRSTFIT, NA } options_t;\ntypedef struct memcmd_s {\n\tchar *raw_command;\n\tchar **args;\n\tint argc;\n\toptions_t command;\n} memcmd_t;\n\ntypedef struct heapblock_s heapblock_t;\nstruct heapblock_s {\n\tint id, size, allocated;\n\tchar *bp;\n\theapblock_t *next;\n};\n\n/* function prototypes */\nmemcmd_t init_command();\nvoid eval(char *cmdline, int *id, heapblock_t *list);\nint parseline(char *buf, char **argv, memcmd_t*);\nvoid operate(memcmd_t metadata, int *id, heapblock_t *data);\nvoid allocate(int size, int *id, heapblock_t *last); /* Allocates ${size} blocks */\nint freeblock(int id, heapblock_t *list); /* Frees the memory at id ${id} */\nvoid blocklist(); /* Will print all blocks. Uses HDRP(), FTRP(), NEXTBLK() */\nint writeheap(int id, char to_write, int n, heapblock_t *data); /* Will write ${data} ${n} times at mem pos ${id} */\nvoid printlist(int id, int n, heapblock_t *list); /* Will print data at mem pos ${id} ${n} times */\nint switchfit(int type); /* Will switch memory location algorithm. 0 is firstfit, 1 is bestfit */ \nstatic void *best_fit(size_t asize); /* Implementation of the best fit memory management algorithm */\n\nmemcmd_t init_command() {\n\tmemcmd_t to_return;\n\tto_return.raw_command = NULL;\n\tto_return.args = NULL;\n\tto_return.argc = 0;\n\tto_return.command = NA;\n\treturn to_return;\n}\n\nint main() {\n char cmdline[MAXLINE]; /* Command line */\n mem_init(); /* initialize our memory lib */\n int id = 1;\n heapblock_t *list = malloc(sizeof(heapblock_t));\n list->id = list->size = list->allocated = 0;\n list->bp = NULL;\n list->next = NULL;\n while (1) {\n\t\t/* Read */\n\t\tprintf(\"> \");\n\t\tFgets(cmdline, MAXLINE, stdin);\n\t\tif (feof(stdin))\n\t\t\texit(0);\n\n\t\t/* Evaluate */\n\t\teval(cmdline, &id, list);\n } \n}\n/* $end shellmain */\n\n/* $begin eval */\n/* eval - Evaluate a command line */\nvoid eval(char *cmdline, int *id, heapblock_t *list) {\n char *argv[MAXARGS]; /* Argument list execve() */\n char buf[MAXLINE]; /* Holds modified command line */\n \n memcmd_t cmdobj = init_command();\n cmdobj.raw_command = cmdline;\n cmdobj.args = argv;\n\n strcpy(buf, cmdline);\n if (!parseline(buf, argv, &cmdobj)) { return; } // Don't do anything.\n operate(cmdobj, id, list);\n\n return;\n}\n/* $end eval */\n\n/* $begin parseline */\n/* parseline - Parse the command line and build the argv array */\nint parseline(char *buf, char **argv, memcmd_t *rpath) {\n\tchar *delim; /* Points to first space delimiter */\n\tint argc; /* Number of args */\n\tint valid = 1; \t\t /* Return quit */\n\n\tbuf[strlen(buf) - 1] = ' '; /* Replace trailing '\\n' with space */\n\twhile (*buf && (*buf == ' ')) /* Ignore leading spaces */\n\t\tbuf++;\n\n\t/* Build the argv list */\n\targc = 0;\n\twhile ((delim = strchr(buf, ' '))) {\n\t\t/* Replace the current index with the null terminator */\n\t\t/* so strcmp stops at it. */\n\t\t*delim = '\\0';\n\n\t\tif (!strcmp(buf, \"allocate\")) { rpath->command = ALLOC; }\n\t\telse if (!strcmp(buf, \"free\")) { rpath->command = FREE; }\n\t\telse if (!strcmp(buf, \"blocklist\")) { rpath->command = BLOCKLIST; }\n\t\telse if (!strcmp(buf, \"writeheap\")) { rpath->command = HWRITE; }\n\t\telse if (!strcmp(buf, \"printheap\")) { rpath->command = HREAD; }\n\t\telse if (!strcmp(buf, \"bestfit\")) { rpath->command = BESTFIT; }\n\t\telse if (!strcmp(buf, \"firstfit\")) { rpath->command = FIRSTFIT; }\n\t\telse if (!strcmp(buf, \"quit\")) { printf(\"Quiting\\n\"); exit(0); }\n\t\telse {\n\t\t\tif (rpath->command != NA) { /* Argument */\n\t\t\t\trpath->args[rpath->argc] = malloc(sizeof(char));\n\t\t\t\tstrcpy(rpath->args[rpath->argc++], buf);\n\t\t\t}\n\t\t\telse /* enter some error state. */\n\t\t\t\tvalid = 0;\n\t\t}\n\n\t\tbuf = delim + 1; /* progression step, next character. */\n\t\twhile (*buf && (*buf == ' ')) /* Ignore spaces */\n\t\t\tbuf++;\n\t}\n\trpath->args[rpath->argc] = NULL;\n\treturn valid;\n}\n\nvoid operate(memcmd_t metadata, int *id, heapblock_t *data) {\n\theapblock_t *last = data;\n\tswitch(metadata.command) {\n\t\tcase ALLOC:\t\t\t\n\t\t\twhile(last->next != NULL) last = last->next;\n\t\t\tif (metadata.argc != 1) printf(\"Bad arguments. Allocate needs 1 argument.\\n\");\n\t\t\telse allocate(atoi(metadata.args[0]), id, last);\n\t\t\tbreak;\n\t\tcase FREE:\n\t\t\tif (metadata.argc != 1) printf(\"Bad arguments. Free needs 1 argument.\\n\");\n\t\t\telse freeblock(atoi(metadata.args[0]), data);\n\t\t\tbreak;\n\t\tcase BLOCKLIST:\n\t\t\tif (metadata.argc != 0) printf(\"Bad arguments. Blocklist needs 0 arguments.\\n\");\n\t\t\telse blocklist(data);\n\t\t\tbreak;\n\t\tcase HWRITE:\n\t\t\tif (metadata.argc != 3) printf(\"Bad arguments. Write block needs 3 arguments.\\n\");\n\t\t\telse writeheap(atoi(metadata.args[0]), *metadata.args[1], atoi(metadata.args[2]), data);\n\t\t\tbreak;\n\t\tcase HREAD:\n\t\t\tif (metadata.argc != 2) printf(\"Bad arguments. Printheap requires 2 arguments.\\n\");\n\t\t\telse printlist(atoi(metadata.args[0]), atoi(metadata.args[1]), data);\n\t\t\tbreak;\n\t\tcase BESTFIT:\n\t\t\tif (metadata.argc != 0) printf(\"Bad arguments. Best fit requries 0 arguments\\n\");\n\t\t\telse switchfit(1);\n\t\t\tbreak;\n\t\tcase FIRSTFIT:\n\t\t\tif (metadata.argc != 0) printf(\"Bad arguments. First fit requries 0 arguments\\n\");\n\t\t\telse switchfit(2);\n\t\t\tbreak;\n\t}\n}\n\nvoid allocate(int size, int *id, heapblock_t *last) {\n\theapblock_t *hb = malloc(sizeof(heapblock_t));\n\thb->size = size;\n\thb->allocated = 0;\n\thb->id = (*id)++;\n\thb->bp = (char*)mm_malloc(size);\n\thb->next = NULL;\n\tlast->next = hb;\n\tprintf(\"%d\\n\", hb->id);\n}\n\nint freeblock(int id, heapblock_t *data) {\n\t/* find the block we want and free using mm_free */ \n\t/* and delete the linked list entry. */\n\tif (data->next == NULL) {\n\t\tprintf(\"No blocks have been allocated\\n\");\n\t\treturn 0;\n\t}\n\theapblock_t *first = data, *to_delete = data->next;\n\twhile (to_delete != NULL) {\n\t\tif (to_delete->id == id) {\n\t\t\tmm_free(to_delete->bp);\n\t\t\tfirst->next = to_delete->next;\n\t\t\tfree (to_delete);\n\t\t\treturn 1;\n\t\t}\n\t\tfirst = first->next, to_delete = to_delete->next;\n\t}\n}\n\nvoid blocklist() {\n\tmm_blocklist();\n}\n\nint writeheap(int id, char to_write, int size, heapblock_t *data) {\n\theapblock_t *finder = data->next;\n\tsize_t chunksize = sizeof(to_write);\n\tint writes = 0, offset = 0;\n\t\n\t/* find our block and write to it */\n\twhile (finder != NULL && finder->id != id) { finder = finder->next;}\n\tif (finder == NULL) return 0;\n\tfor (; writes < size && offset < finder->size; writes++) {\n\t\t*(finder->bp + offset) = to_write;\n\t\toffset += chunksize;\n\t}\n\tfinder->allocated = 1;\n\treturn 1;\n}\n\nvoid printlist(int id, int n, heapblock_t *list) {\n\t/* find our block */\t\n\tint i = 0;\n\theapblock_t *finder = list->next;\n\twhile (finder != NULL && finder->id != id) { finder = finder->next; }\n\tfor (; i < n; i++) {\n\t\tprintf(\"%c\", *(finder->bp + (sizeof(char) * i)));\n\t}\n\tprintf(\"\\n\");\n}\n\n/* implemented function in mm.c\neasier to implement there because\nof access to mm.c's macros\" */\n\nint switchfit(int type){\n\tmm_set_fit_mode(type);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6457905769348145, "alphanum_fraction": 0.6468172669410706, "avg_line_length": 16.727272033691406, "blob_id": "ddbc6109a01600f7565f88732687946fc009f804", "content_id": "57f88dbd07155db5af255359573dea7b793156c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 974, "license_type": "no_license", "max_line_length": 62, "num_lines": 55, "path": "/cs143B/project3/tlb_adapter.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"tlb.h\"\n#include \"tlb_adapter.h\"\n#include <string>\n\nItlb* TlbFactory::MakeAdapter(bool enabled) {\n\treturn new TlbFactory::tlb_adapter(enabled);\n}\n\nTlbFactory::tlb_adapter::tlb_adapter(bool _enabled) {\n\tenabled = _enabled;\n\t_tlb = new tlb();\n}\n\nTlbFactory::tlb_adapter::~tlb_adapter() {\n\tdelete _tlb;\n}\n\nint TlbFactory::tlb_adapter::get_frame_cache(int sp) {\n\tif (enabled) {\n\t\treturn _tlb->get_frame_cache(sp);\n\t} else {\n\t\treturn -1;\n\t}\n}\n\nvoid TlbFactory::tlb_adapter::set_frame_cache(int sp, int f) {\n\tif (enabled) {\n\t\t_tlb->set_frame_cache(sp, f);\n\t}\n}\n\nbool TlbFactory::tlb_adapter::has_frame_cache(int sp) {\n\tif (enabled) {\n\t\treturn _tlb->has_frame_cache(sp);\n\t} else {\n\t\treturn false;\n\t}\n}\n\nstd::string TlbFactory::tlb_adapter::get_hit_string() {\n\tif (enabled) {\n\t\treturn _tlb->get_hit_string();\n\t} else {\n\t\treturn \"\";\n\t}\n}\n\n\nstd::string TlbFactory::tlb_adapter::get_miss_string() {\n\tif (enabled) {\n\t\treturn _tlb->get_miss_string();\n\t} else {\n\t\treturn \"\";\n\t}\n}" }, { "alpha_fraction": 0.5316455960273743, "alphanum_fraction": 0.5569620132446289, "avg_line_length": 13.363636016845703, "blob_id": "39fa61a665edba6d4fe7a44fd5bf4103cfe90db8", "content_id": "d877319b8bbd6f865533f18bff0ab9c2bcf94fab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 158, "license_type": "no_license", "max_line_length": 33, "num_lines": 11, "path": "/cs146/hw2/prargs", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# invoked via ./prargs arg arg...\n# iterates over all items in $@\necho \"0: $0\"\ni=1\nfor arg in \"$@\"\ndo\n\techo \"$i: \\\"$arg\\\"\"\n\ti=`expr $i + 1`\ndone\n" }, { "alpha_fraction": 0.6276463270187378, "alphanum_fraction": 0.6475716233253479, "avg_line_length": 24.90322494506836, "blob_id": "f4ade5347d8244af059c523823213f4e096f4020", "content_id": "d38cc79fef3cfbde4651bc1efd19aca37720ffa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 803, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/cs121/partB.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "from tokenizer import Tokenizer\nimport os.path\nimport timeit\ndef intersect(fname1, fname2):\n tok = Tokenizer()\n tok2 = Tokenizer()\n tok.tokenize(fname1)\n tok2.tokenize(fname2)\n largest = tok.computeFrequencies()\n smallest = tok.computeFrequencies()\n\n if (len(largest) < len(smallest)):\n t = largest\n largest = smallest\n smallest = t\n intersect=[]\n count = 0\n for key,value in smallest.iteritems():\n if (largest.has_key(key)):\n intersect.append(key)\n count = count + 1\n print intersect\n print len(intersect)\n\n\nfname1=raw_input(\"Path to file1: \")\nfname2=raw_input(\"Path to file2: \")\nif (not os.path.isfile(fname1) or not os.path.isfile(fname2)):\n print \"File does not exist, exiting\"\nelse:\n intersect(fname1, fname2)\n" }, { "alpha_fraction": 0.6688051223754883, "alphanum_fraction": 0.6888532638549805, "avg_line_length": 22.528301239013672, "blob_id": "eddb0d9e369a110c39bfdadc66484f625523492a", "content_id": "297bdde28f2ffdb3622f3d801b8586e0245faab8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 84, "num_lines": 53, "path": "/cs178/hw2/one.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import mltools as ml\nimport mltools.linear\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Load the data set and split it\ndata = np.genfromtxt(\"data/curve80.txt\", delimiter=None)\nX = data[:,0]\nX = X[:,np.newaxis]\nY = data[:,1]\nXtr, Xte, Ytr, Yte = ml.splitData(X, Y, 0.75)\n\n# part two\nlr = ml.linear.linearRegress(Xtr, Ytr)\nxs = np.linspace(0, 10, 200)\nxs = xs[:,np.newaxis]\nys = lr.predict(xs)\n\nplt.scatter(xs, ys)\nplt.scatter(Xtr, Ytr)\nplt.show()\nprint lr\n\nprint \"MSE on train: \" + str(lr.mse(Xtr, Ytr))\nprint \"MSE on test: \" + str(lr.mse(Xte, Yte))\n\n# part 3\nks = [1,3,5,7,10,18]\nerrTrainTr = []\nerrTrainTe = []\nlrData = []\nfor i,k in enumerate(ks):\n\tXtrP = ml.transforms.fpoly(Xtr, k, bias=False)\n\tXtrP,params = ml.transforms.rescale(XtrP)\n\tlr = ml.linear.linearRegress(XtrP, Ytr)\n\tlrData.append(lr.theta)\n\tPhi = lambda X : ml.transforms.rescale(ml.transforms.fpoly(X, k, False), params)[0]\n\n\tYhatTrain = lr.predict(Phi(xs))\n\terrTrainTr.append(np.mean(YhatTrain - Ytr) ** 2)\n\tYhatTest = lr.predict(Phi(Xte))\n\terrTrainTe.append(np.mean(YhatTest - Yte) ** 2)\n\n\n\tplt.scatter(Xtr, Ytr)\n\tplt.plot(xs, YhatTrain)\n\tplt.show()\n\nprint errTrainTr\nprint errTrainTe\nplt.semilogy(errTrainTr, color='r')\nplt.semilogy(errTrainTe, color='g')\nplt.show()\n" }, { "alpha_fraction": 0.5779816508293152, "alphanum_fraction": 0.5779816508293152, "avg_line_length": 11.222222328186035, "blob_id": "6e8aa839cad465b5e3ef015edf35e74e1fedcff5", "content_id": "4adcfbd3be49625bbd8f1efe627a18da65a4ee74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 109, "license_type": "no_license", "max_line_length": 30, "num_lines": 9, "path": "/cs146/hw2/cx", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# invoked simply as ./cx $name\nfor var in \"$@\"\ndo\n\tif [ -f $var ]; then\n\t\tchmod +x $var\n\tfi\ndone" }, { "alpha_fraction": 0.6763636469841003, "alphanum_fraction": 0.6763636469841003, "avg_line_length": 19.370370864868164, "blob_id": "6eca5abd44d9d1d4c39024be3024830f92859716", "content_id": "b5d52f4048b9e04cee7e97bd29485fcdf3811e71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 550, "license_type": "no_license", "max_line_length": 70, "num_lines": 27, "path": "/cs141/project1/src/halt.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"grammer.hpp\"\n#include \"statements.hpp\"\n#include \"halt.hpp\"\n#include \"writer.hpp\"\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nHalt::Halt(string line) : Statement(line) {\n\t_mvKeywords = new vector<string>();\n}\n\nvector<string>* Halt::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Halt::parse() {\n\tif (_msLine.find(\",\") != string::npos) return NULL; // no comma args;\n\t_msLine = parseCommand(_msLine, \"halt \", \"HALT \");\n\tisExpr(_msLine); \n\treturn this;\n}\n" }, { "alpha_fraction": 0.699009895324707, "alphanum_fraction": 0.7049505114555359, "avg_line_length": 25.578947067260742, "blob_id": "dfa5d44a2416705a539fb36aafb7ffd5a1ba833b", "content_id": "1c50f4511a708b76e1d6c02c317b724e3bd9955d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 505, "license_type": "no_license", "max_line_length": 100, "num_lines": 19, "path": "/cs121/partA.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "from tokenizer import Tokenizer \nimport os.path \nimport operator # used to reverse dict\n\ndef tokenize(fname):\n tok = Tokenizer()\n tok.tokenize(fname)\n frequencies = sorted(tok.computeFrequencies().items(), key=operator.itemgetter(1), reverse=True)\n printTokens(frequencies)\n\ndef printTokens(tokens):\n for token in tokens:\n print token[0],\"=\",token[1]\n\nfname=raw_input(\"Path to file\")\nif (not os.path.isfile(fname)):\n print \"File does not exist, exiting\"\nelse:\n tokenize(fname)\n" }, { "alpha_fraction": 0.39669421315193176, "alphanum_fraction": 0.647382915019989, "avg_line_length": 89.75, "blob_id": "6adf49e06a7f2f22760720ce403af856b4ffe897", "content_id": "67a03d0fc8ba65ac1dd4cfcdca8f26ff9e89ee03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1089, "license_type": "no_license", "max_line_length": 90, "num_lines": 12, "path": "/cs131/project1/runner.sh", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "./LAB1 Timing_1.txt 2 1000 && ./LAB1 Timing_1.txt 2 9000 && ./LAB1 Timing_1.txt 2 20000\n./LAB1 Timing_1.txt 4 1000 && ./LAB1 Timing_1.txt 4 9000 && ./LAB1 Timing_1.txt 4 20000\n./LAB1 Timing_1.txt 8 1000 && ./LAB1 Timing_1.txt 8 9000 && ./LAB1 Timing_1.txt 8 20000\n./LAB1 Timing_1.txt 16 1000 && ./LAB1 Timing_1.txt 16 9000 && ./LAB1 Timing_1.txt 16 20000\n./LAB1 Timing_2.txt 2 1000 && ./LAB1 Timing_2.txt 2 9000 && ./LAB1 Timing_2.txt 2 20000\n./LAB1 Timing_2.txt 4 1000 && ./LAB1 Timing_2.txt 4 9000 && ./LAB1 Timing_2.txt 4 20000\n./LAB1 Timing_2.txt 8 1000 && ./LAB1 Timing_2.txt 8 9000 && ./LAB1 Timing_2.txt 8 20000\n./LAB1 Timing_2.txt 16 1000 && ./LAB1 Timing_2.txt 16 9000 && ./LAB1 Timing_2.txt 16 20000\n./LAB1 Timing_3.txt 2 1000 && ./LAB1 Timing_3.txt 2 9000 && ./LAB1 Timing_3.txt 2 20000\n./LAB1 Timing_3.txt 4 1000 && ./LAB1 Timing_3.txt 4 9000 && ./LAB1 Timing_3.txt 4 20000\n./LAB1 Timing_3.txt 8 1000 && ./LAB1 Timing_3.txt 8 9000 && ./LAB1 Timing_3.txt 8 20000\n./LAB1 Timing_3.txt 16 1000 && ./LAB1 Timing_3.txt 16 9000 && ./LAB1 Timing_3.txt 16 20000\n" }, { "alpha_fraction": 0.5727132558822632, "alphanum_fraction": 0.575282633304596, "avg_line_length": 27, "blob_id": "53adb081074f5fd627050ca13f3611b4f7546f6f", "content_id": "a3194bc6868c16d8a0e3f7e7534e00a63a8ae715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3892, "license_type": "no_license", "max_line_length": 113, "num_lines": 139, "path": "/cs142A/com/uci/cs142A/src/mips/ActivationRecord.java", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "package mips;\n\nimport java.util.HashMap;\n\nimport crux.Symbol;\nimport types.*;\n\npublic class ActivationRecord\n{\n private static int fixedFrameSize = 2*4;\n private ast.FunctionDefinition func;\n private ActivationRecord parent;\n private int stackSize;\n private HashMap<Symbol, Integer> locals;\n private HashMap<Symbol, Integer> arguments;\n \n public static ActivationRecord newGlobalFrame()\n {\n return new GlobalFrame();\n }\n \n protected static int numBytes(Type type)\n {\n \tif (type instanceof BoolType)\n \t\treturn 4;\n if (type instanceof IntType)\n return 4;\n if (type instanceof FloatType)\n return 4;\n if (type instanceof ArrayType) {\n ArrayType aType = (ArrayType)type;\n return aType.extent() * numBytes(aType.base());\n }\n throw new RuntimeException(\"No size known for \" + type);\n }\n \n protected ActivationRecord()\n {\n this.func = null;\n this.parent = null;\n this.stackSize = 0;\n this.locals = null;\n this.arguments = null;\n }\n \n public ActivationRecord(ast.FunctionDefinition fd, ActivationRecord parent)\n {\n this.func = fd;\n this.parent = parent;\n this.stackSize = 0;\n this.locals = new HashMap<Symbol, Integer>();\n \n // map this function's parameters\n this.arguments = new HashMap<Symbol, Integer>();\n int offset = 0;\n for (int i=fd.arguments().size()-1; i>=0; --i) {\n Symbol arg = fd.arguments().get(i);\n arguments.put(arg, offset);\n offset += numBytes(arg.type());\n }\n }\n \n public String name()\n {\n return func.symbol().name();\n }\n \n public ActivationRecord parent()\n {\n return parent;\n }\n \n public int stackSize()\n {\n return stackSize;\n }\n \n public void add(Program prog, ast.VariableDeclaration var)\n {\n stackSize += var.symbol().type().numBytes();\n locals.put(var.symbol(), -stackSize);\n }\n \n public void add(Program prog, ast.ArrayDeclaration array)\n {\n throw new RuntimeException(\"implement adding array to local function space\");\n }\n \n public void getAddress(Program prog, String reg, Symbol sym)\n {\n // @todo: Fix contains key not working.\n boolean inArgs = false, inLocals = false;\n Symbol argEntry = null, localsEntry = null;\n for (Symbol s : arguments.keySet()) {\n inArgs |= s.name().equals(sym.name());\n if (s.name().equals(sym.name())) argEntry = s;\n }\n for (Symbol s : locals.keySet()) {\n inLocals |= s.name().equals(sym.name());\n if (s.name().equals(sym.name())) localsEntry = s;\n }\n if (inArgs || inLocals) {\n int offset = inArgs ? arguments.get(argEntry) : locals.get(localsEntry) - fixedFrameSize;\n prog.appendInstruction(\"addi \" + reg + \", $fp, \" + offset);\n } else if (parent != null) {\n parent.getAddress(prog, reg, sym);\n }\n }\n}\n\nclass GlobalFrame extends ActivationRecord\n{\n public GlobalFrame()\n {\n }\n \n private String mangleDataname(String name)\n {\n return \"cruxdata.\" + name;\n }\n \n @Override\n public void add(Program prog, ast.VariableDeclaration var)\n {\n prog.appendData(mangleDataname(var.symbol().name()) + \": .space \" + var.symbol().type().numBytes());\n } \n \n @Override\n public void add(Program prog, ast.ArrayDeclaration array)\n {\n prog.appendData(mangleDataname(array.symbol().name()) + \": .space \" + array.symbol().type().numBytes());\n }\n \n @Override\n public void getAddress(Program prog, String reg, Symbol sym)\n {\n prog.appendInstruction(\"la \" + reg + \", \" + mangleDataname(sym.name()));\n }\n}\n" }, { "alpha_fraction": 0.5139838457107544, "alphanum_fraction": 0.5226848721504211, "avg_line_length": 23.378787994384766, "blob_id": "1915053cf7caacdf32f403cb01baf46137fc9a6f", "content_id": "808de1b813ae2208004a43a1d5f320138a7fe06e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1609, "license_type": "no_license", "max_line_length": 131, "num_lines": 66, "path": "/cs131/project3/jjbesavi_lab3Skeleton.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <algorithm>\n#include <cstdlib>\n#include <cctype>\n#include <fstream>\n#include <iostream>\n\n// Don't CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\n\nstruct Result\n{\n Result()\n : lineNumber(0), firstChar(0), length(0)\n {}\n\n Result(int lineNumber_, int firstChar_, int length_)\n : lineNumber(lineNumber_), firstChar(firstChar_), length(length_)\n {}\n\n // This allows you to compare results with the < (less then) operator, i.e. r1 < r2\n bool\n operator<(Result const& o)\n {\n // Line number can't be equal\n return length < o.length || \n (length == o.length && lineNumber > o.lineNumber) ||\n (length == o.length && lineNumber == o.lineNumber && firstChar > o.firstChar);\n }\n\n int lineNumber, firstChar, length;\n};\n\nvoid\nDoOutput(Result r)\n{\n std::cout << \"Result: \" << r.lineNumber << \" \" << r.firstChar << \" \" << r.length << std::endl;\n}\n\n// CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\n\nint\nmain(int argc, char* argv[])\n{\n if(argc != 3)\n {\n std::cout << \"ERROR: Incorrect number of arguments. Format is: <filename> <numThreads> \" << std::endl;\n return 0;\n }\n\n // ....... Your OpenMP program goes here ............\n\n // Probably some common code...\n\n // Part A\n\n // ... Eventually.. \n Result resultA(0,0,0);\n DoOutput(resultA);\n\n // Part B\n\n // ... Eventually.. \n Result resultB(0,0,0);\n DoOutput(resultB);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6314076781272888, "alphanum_fraction": 0.6395443677902222, "avg_line_length": 28.975608825683594, "blob_id": "73090d0e963d9052fb42c02693f8490a1fe60fa4", "content_id": "46ff044c96c9f4a152d1a0fee3907bad7850fc24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1229, "license_type": "no_license", "max_line_length": 71, "num_lines": 41, "path": "/cs143B/project3/pm.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <vector>\n#include <string>\n#include <fstream>\n#include \"tlb_adapter.h\"\n#ifndef PM_H\n#define PM_H\nconst static int FRAME_SIZE = 512;\nconst static int FRAME_COUNT = 1024;\ntypedef int frame_t[FRAME_SIZE] ;\ntypedef int disk_t[FRAME_SIZE * FRAME_COUNT];\nclass pm \n{\npublic:\n typedef struct VA {\n int s; // The segment position\n int p; // The page table position\n int w; // The offset in the page table.\n int addr; // disk[disk[s] + p] + w\n int sp; // s & p together\n } va_t;\n\n pm(std::string outs, bool tlb_enabled = false);\n bool get_physical_address(int physical_address, pm::va_t *pa);\n void initialize(std::vector < std::vector < std::string > > data );\n void read(int virtual_address);\n void write(int virtual_address);\n void output(std::string s);\n const std::string CLASS_TAG = \"pm::\";\nprivate:\n int get_segment_table(int virtual_address); // return s\n int get_page_table(int virtual_address); // returns p\n int get_offset(int virtual_address); // returns w\n int get_free_frame(int size = 1);\n void set_frame(int frame);\n void print_bitmap();\n disk_t disk;\n unsigned int bitmask[32];\n Itlb *tlb;\n std::ofstream out;\n};\n#endif\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 17.200000762939453, "blob_id": "7b79d8cde0ddbb20fc181aee4880a2e70540a1a3", "content_id": "c9da8e0c44e626a2133f1fbcfd557a9707cdf82c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 90, "license_type": "no_license", "max_line_length": 64, "num_lines": 5, "path": "/ics53/lab3/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "all:\n\tgcc -pthread -g -o memshell csapp.c memlib.c mm.c mallocshell.c\n\nclean:\n\trm memshell" }, { "alpha_fraction": 0.6760563254356384, "alphanum_fraction": 0.7016645073890686, "avg_line_length": 30.280000686645508, "blob_id": "84da9f0a5b4201eafec5e5cea202916d7b4888a2", "content_id": "403948a357809566c7c381700af9f99603b0bacf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 781, "license_type": "no_license", "max_line_length": 59, "num_lines": 25, "path": "/cs143B/project2/filesystem/filesystem.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include <string>\n#include \"../io/iosystem.h\"\n#ifndef FILESYSTEM_BASE_H\n#define FILESYSTEM_BASE_H\nclass File_system\n{\npublic:\n\tvirtual void create_file(std::string name) = 0;\n\tvirtual void destroy_file(std::string name) = 0;\n\tvirtual void open_file(std::string name) = 0;\n\tvirtual void close_file(int oft_index) = 0;\n\tvirtual void write_file(int index, char c, int count) = 0;\n\tvirtual void read_file(int index, int count) = 0;\n\tvirtual void seek_file(int index, int start) = 0;\n\tvirtual void dir() = 0;\n\tvirtual void save(std::string init_file) = 0;\n\tvirtual void init(std::string init_file, IO_system*) = 0;\n\tvirtual IO_system* getIO() = 0;\n\tvirtual void setIO(IO_system*) = 0;\n\tstatic File_system *CreateFileSystem(IO_system *io);\n\tIO_system *io;\n};\n#endif" }, { "alpha_fraction": 0.717391312122345, "alphanum_fraction": 0.717391312122345, "avg_line_length": 19.44444465637207, "blob_id": "20fcc7690a2b19ccefa47b69dd5bd0d45b6b412c", "content_id": "a177253cf53e96632f78b7a24cc4334b3b86ca83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 184, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/cs146/hw5/engine.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include \"parser.h\"\n\n#ifndef ENGINE_H\n#define ENGINE_H\n// will handle the forking and execing.\nvoid process_job(job_t *job, string *env);\n#endif\n" }, { "alpha_fraction": 0.6851063966751099, "alphanum_fraction": 0.6851063966751099, "avg_line_length": 15.785714149475098, "blob_id": "a4adf00deb0d32a201e6ca61cd4ef2b9a795cbbb", "content_id": "60f33bc7a3c03c2ac3387100877b9482b1c778c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 235, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/cs141/project1/src/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "EXECNAME=SIMPLESEM\nOBJNAME=-o $(EXECNAME)\nBUILD=g++\nFILES=set.cpp halt.cpp jump.cpp jumpt.cpp writer.cpp main.cpp\nall:\n\t$(BUILD) $(OBJNAME) $(FILES)\n\nclean:\n\trm SIMPLESEM\n\ndebug:\n\t$(BUILD) -ggdb $(OBJNAME) $(FILES)\nrun:\n\t./$(EXECNAME)\n" }, { "alpha_fraction": 0.6477611660957336, "alphanum_fraction": 0.6641790866851807, "avg_line_length": 19.96875, "blob_id": "0636a36a0b7c10743bea8b2aa10d75bfb2cbd38e", "content_id": "b0c24978c26ada17d860c0a8b4e3b46e749a38ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "no_license", "max_line_length": 61, "num_lines": 32, "path": "/cs178/hw1/one.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nnp.random.seed(0)\nget_ipython().magic(\"matplotlib inline\")\niris = np.genfromtxt(\"data/iris.txt\", delimiter=None)\nY = iris[:, -1]\nX = iris[:,0:-1]\nfeats = X.shape[1]\ndps = X.shape[0]\nmeans=[]\nstds=[]\nvar=[]\nzscore=[]\nprint feats \nprint dps\n\nfor i in range(0, feats):\n\tfeature=X[:,i]\n\tplt.hist(X[:,i])\n\tplt.show()\n\tmeans.append(np.mean(feature))\n\tvar.append(np.var(feature))\n\tstds.append(np.std(feature))\n\tzscore.append([((x - means[i]) / stds[i]) for x in feature])\n\nprint means\nprint var\nprint stds\nfor i in range(0, feats - 1):\n\tfor j in range(i+1, feats):\n\t\tplt.scatter(zscore[i], zscore[j], c=zscore[0])\n\t\tplt.show()" }, { "alpha_fraction": 0.5388896465301514, "alphanum_fraction": 0.5506823658943176, "avg_line_length": 29.309236526489258, "blob_id": "907eefd97b708db9e6199ebf650c9702cecc63a2", "content_id": "f0165994e63a58a3604537c134c72e22558c43cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7547, "license_type": "no_license", "max_line_length": 119, "num_lines": 249, "path": "/cs146/hw4/lss.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <pwd.h>\n#include <grp.h>\n#include <time.h>\n#include <locale.h>\n#include <langinfo.h>\n#include <errno.h>\n#include <stdint.h>\n\n#define ALMOST_ALL 1\n#define ALL 2\ntypedef char* string;\ntypedef struct opts_s {\n int show_all;\n int deref_links;\n string *names;\n int numfiles;\n} opt_t;\n\ntypedef struct statpod_s {\n struct stat s; // stat structure returned from stat\n struct stat l; // stat structure returned from lstat;\n} statpod_t;\n\ntypedef struct node_s {\n string name;\n struct dirent* dp;\n struct stat statbuf;\n statpod_t *pod;\n} node_t;\n\nstring readlink_name(string name);\nint compnode(const void *a, const void *b);\nvoid iteratenodes(node_t *data, int length);\nstatpod_t *statdir(string name, opt_t options);\nnode_t *getfiles(const char *path, node_t *files, int *j, opt_t options);\nopt_t *getoptions(int argc, string* argv);\nstring getfilepath(char *name, const char *path);\n\nint main(int argc, string* argv) {\n int i = 0, size = 0;\n opt_t *options;\n options = getoptions(argc, argv);\n for (i = 0; i < options->numfiles; i++) {\n node_t nodes[BUFSIZ];\n // get the files stat pod\n statpod_t *pod = statdir(options->names[i], *options); \n if (pod != NULL) {\n struct stat x = options->deref_links ? pod->s : pod->l;\n if (S_ISDIR(x.st_mode)) {\n // if the file is a directory, then go through this method\n if (options->numfiles > 1) printf(\"%s\\n\", options->names[i]);\n getfiles(options->names[i], nodes, &size, *options);\n qsort(nodes, size, sizeof(node_t), compnode);\n iteratenodes(nodes, size);\n } else {\n // the file is normal, print\n nodes[0].name = options->names[i];\n nodes[0].statbuf = options->deref_links ? pod->s : pod->l;\n iteratenodes(nodes, 1);\n }\n free(pod);\n free(options->names[i]);\n } else {\n perror(\"Unable to stat argument\");\n }\n }\n free(options->names);\n return 0;\n}\n\nopt_t *getoptions(int argc, string* argv) {\n char c;\n int numflags = 0;\n opt_t *options = calloc(1, sizeof(opt_t));\n while ((c = getopt(argc, argv, \"LaA\")) != -1) {\n numflags++;\n switch (c) {\n case 'L':\n options->deref_links = 1;\n break;\n case 'a':\n options->show_all = ALL;\n break;\n case 'A':\n options->show_all = ALMOST_ALL;\n break;\n }\n }\n\n // get all the file names.\n options->names = calloc(argc, sizeof(char*));\n // default options[0].\n options->names[0] = (char*)calloc(1, sizeof(char)*2);\n strcpy(options->names[0] , \".\");\n int i, j = 0;\n for (i = optind; i < argc; i++) {\n if (argv[i][0] != '-') {\n options->names[j] = calloc(1, sizeof(char) * strlen(argv[i]));\n strcpy(options->names[j++], argv[i]);\n }\n }\n options->numfiles = j ? j : 1;\n return options;\n}\n\nnode_t *getfiles(const char *path, node_t *files, int *j, opt_t options) {\n struct dirent *dp;\n struct stat statbuf;\n DIR *_dir = opendir(path);\n int i = 0, dircount = 0, k = 0;\n char *dirs[BUFSIZ];\n long pathsize = 0;\n // Get all the files.\n while ((dp = readdir(_dir)) != NULL) {\n if (options.show_all == ALMOST_ALL && (!strcmp(dp->d_name, \".\") || !strcmp(dp->d_name, \"..\"))) continue;\n if (!options.show_all && dp->d_name[0] == '.') continue;\n char *fullname = getfilepath(dp->d_name, path);\n statpod_t *statpod_ptr = statdir(fullname, options);\n if (statpod_ptr != NULL) {\n memcpy(&(files[i].statbuf), (options.deref_links ? &statpod_ptr->s : &statpod_ptr->l), sizeof(struct stat));\n files[i].name = calloc(1,sizeof(char) * strlen(dp->d_name));\n memcpy(files[i].name, dp->d_name, strlen(dp->d_name));\n files[i].name[strlen(dp->d_name)] = '\\0';\n files[i++].dp = dp;\n } else {\n perror(\"Error using stat return value\");\n }\n free(statpod_ptr);\n free(fullname);\n }\n *j = i;\n closedir(_dir);\n}\n\n\nint compnode(const void *a, const void *b) {\n int diff = (*(node_t*)a).statbuf.st_size - (*(node_t*)b).statbuf.st_size;\n if (!diff) return 0;\n else if (diff > 0) return -1;\n else return 1;\n}\n\nvoid iteratenodes(node_t *data, int length) {\n\tint i;\n\tstruct passwd *pwd;\n\tstruct group *grp;\n\tstruct tm *tm, *curr;\n\tchar datestring[256];\n\tint modecount = 9;\n\tmode_t modes[] = {S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH};\n\tchar outs[] = {'r', 'w', 'x'};\n\t\n\t// get the current time.\n\ttime_t rawtime;\n\ttime(&rawtime);\n\tfor (i = 0; i < length; i++) {\n string temp_stuff;\n if (S_ISLNK(data[i].statbuf.st_mode)) {\n string linkname = readlink_name(data[i].name);\n temp_stuff = calloc(1, sizeof(char) * (strlen(data[i].name) + strlen(linkname) + strlen(\" -> \")));\n sprintf(temp_stuff, \"%s -> %s\", data[i].name, linkname);\n } else {\n temp_stuff = calloc(1, sizeof(char) * strlen(data[i].name)); \n strcpy(temp_stuff, data[i].name);\n }\n\t\tif (S_ISDIR(data[i].statbuf.st_mode))\n\t\t\tputchar('d');\n\t\telse\n\t\t\tputchar('-');\n\n\t\tint j = 0;\n\t\tfor (j = 0; j < modecount; j++)\n\t\t\tif (data[i].statbuf.st_mode & modes[j])\n\t\t\t\tputchar(outs[j % 3]);\n\t\t\telse\n\t\t\t\tputchar('-');\n\t\tprintf(\"%2d\", data[i].statbuf.st_nlink);\n \n\t\tif ((pwd = getpwuid(data[i].statbuf.st_uid)) != NULL) {\n printf(\" %-8.8s\", pwd->pw_name);\n }\n\t\telse {\n printf(\" %-8d\", data[i].statbuf.st_uid);\n }\n \n\n\t\tif ((grp = getgrgid(data[i].statbuf.st_gid)) != NULL)\n\t\t\tprintf(\" %-6.8s\", grp->gr_name);\n\t\telse\n\t\t\tprintf(\" %-8d\", data[i].statbuf.st_gid);\n\n\t\tprintf(\"%5jd \", data[i].statbuf.st_size);\t\n\t\ttm = localtime(&data[i].statbuf.st_mtime);\n\n\t\tif (difftime(rawtime, mktime(tm)) < 15768000) { \n\t\t\tstrftime(datestring, sizeof(datestring), \"%b %e %R\", tm);\n\t\t\tprintf(\"%s %s\\n\", datestring, temp_stuff);\n\t\t} else {\n\t\t\tstrftime(datestring, sizeof(datestring), \"%b %e %Y\", tm);\n\t\t\tprintf(\"%s %s\\n\", datestring, temp_stuff);\n\t\t}\n\t}\n}\n\nstatpod_t *statdir(string name, opt_t options) {\n statpod_t *pod = calloc(1,sizeof(statpod_t));\n int lstat_return = !options.deref_links ? lstat(name, &(pod->l)) : 0;\n int stat_return = options.deref_links ? stat(name, &(pod->s)) : 0;\n\n if (lstat_return == -1) {\n char buf[100];\n sprintf(buf, \"Error while stating file %s\", name);\n perror(buf);\n return NULL;\n }\n if (lstat_return != -1 && stat_return == -1) {\n // the symbolic link points to nothing.\n perror(readlink_name(name));\n return NULL;\n }\n return pod; \n}\n\nstring readlink_name(string name) {\n string buf = calloc(1, sizeof(char) * 256);\n if (readlink(name, buf, 256) == -1) {\n sprintf(buf, \"reading link %s\", buf);\n perror(buf);\n }\n return buf;\n}\n\nstring getfilepath(char *name, const char *path) {\n string fullname = calloc(1, sizeof(char) * (strlen(name) + strlen(path) + 2));\n strcpy(fullname, path);\n strcat(fullname, \"/\");\n strcat(fullname, name);\n fullname[strlen(name) + strlen(path) + 1] = '\\0';\n return fullname;\n}\n" }, { "alpha_fraction": 0.5786234140396118, "alphanum_fraction": 0.5945718884468079, "avg_line_length": 24.340425491333008, "blob_id": "38b881064283e95b3a264db8a5d0693cedc7be8a", "content_id": "9e7bdc813f38b40afe06279669ae7d7ada85d8fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3574, "license_type": "no_license", "max_line_length": 100, "num_lines": 141, "path": "/cs143A/project7/myls.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <pwd.h>\n#include <grp.h>\n#include <time.h>\n#include <locale.h>\n#include <langinfo.h>\n#include <errno.h>\n#include <stdint.h>\n\ntypedef struct node {\n\tchar *name;\n\tstruct dirent *dp;\n\tstruct stat statbuf;\n} node_t;\n\nint cmpnode(const void *a, const void *b) {\n\treturn strcasecmp((*(node_t *)a).name, (*(node_t *)b).name);\n}\n\nint cmpstr(const void *a, const void *b) {\n\tconst char **s1 = (const char **)a;\n\tconst char **s2 = (const char **)b;\n\treturn strcasecmp(*s1, *s2);\n}\nvoid iterateDirectory(node_t *data, int length) {\n\tstruct passwd *pwd;\n\tstruct group *grp;\n\tstruct tm *tm, *curr;\n\tchar datestring[256];\n\tint modecount = 9;\n\tmode_t modes[] = {S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH};\n\tchar outs[] = {'r', 'w', 'x'};\n\tint i;\n\t\n\t// get the current time.\n\ttime_t rawtime;\n\ttime(&rawtime);\n\tfor (i = 0; i < length; i++) {\n\t\tif (S_ISDIR(data[i].statbuf.st_mode))\n\t\t\tprintf(\"d\");\n\t\telse\n\t\t\tprintf(\"-\");\n\n\t\tint j = 0;\n\t\tfor (j = 0; j < modecount; j++)\n\t\t\tif (data[j].statbuf.st_mode & modes[j])\n\t\t\t\tprintf(\"%c\", outs[j % 3]);\n\t\t\telse\n\t\t\t\tprintf(\"-\");\n\t\tprintf(\"%2d\", data[i].statbuf.st_nlink);\n\n\t\tif ((pwd = getpwuid(data[i].statbuf.st_uid)) != NULL)\n\t\t\tprintf(\" %-8.8s\", pwd->pw_name);\n\t\telse\n\t\t\tprintf(\" %-8d\", data[i].statbuf.st_uid);\n\n\t\tif ((grp = getgrgid(data[i].statbuf.st_gid)) != NULL)\n\t\t\tprintf(\" %-6.8s\", grp->gr_name);\n\t\telse\n\t\t\tprintf(\" %-8d\", data[i].statbuf.st_gid);\n\n\t\tprintf(\"%5jd \", data[i].statbuf.st_size);\t\n\t\ttm = localtime(&data[i].statbuf.st_mtime);\n\n\t\tif (difftime(rawtime, mktime(tm)) < 15768000) { \n\t\t\tstrftime(datestring, sizeof(datestring), \"%b %e %R\", tm);\n\t\t\tprintf(\"%s %s\\n\", datestring, data[i].dp->d_name);\n\t\t} else {\n\t\t\tstrftime(datestring, sizeof(datestring), \"%b %e %Y\", tm);\n\t\t\tprintf(\"%s %s\\n\", datestring, data[i].dp->d_name);\n\t\t}\n\t}\n}\n\nnode_t* getfiles(char *path, char *explore[], node_t *files, int *j, long *size) {\n\tstruct dirent *dp;\n\tstruct stat statbuf;\n\tDIR *_dir = opendir(path);\n\tint i = 0, dircount = 0, k = 0;\n\tchar *dirs[BUFSIZ];\n\tlong pathsize = 0;\n\twhile (path[i++] != '\\0') {};\n\tif (path[i - 2] != '/') {\n\t\tpath[i - 1] = '/';\n\t\tpath[i] = '\\0';\n\t}\n\ti = 0;\n\twhile ((dp = readdir(_dir)) != NULL) {\n\t\tchar name[BUFSIZ];\n\t\tstrcpy(name, path);\n\t\tstrcat(name, dp->d_name);\n\t\tif (dp->d_name[0] == '.') continue;\n\t\tif (stat(name, &files[i].statbuf)== -1)\n\t\t\tcontinue;\n\t\tfiles[i].name = dp->d_name;\n\t\tfiles[i].dp = dp;\n\t\tif (S_ISDIR(files[i].statbuf.st_mode)) {\n\t\t\tdirs[dircount] = (char *) malloc(strlen(name));\n\t\t\tstrcpy(dirs[dircount++], name);\n\t\t}\n\t\tpathsize += (long)files[i].statbuf.st_blocks;\n\t\ti++;\n\t}\n\tqsort(dirs, dircount, sizeof(char *), cmpstr);\n\tqsort(files, *j, sizeof(node_t), cmpnode);\n\t*j = i;\n\tprintf(\"%s:\\ntotal %d\\n\", path, (pathsize / 2));\n\titerateDirectory(files, i); \n\tprintf(\"\\n\");\n\tfor (i = 0; i < dircount; i++) {\n\t\tgetfiles(dirs[i], explore, files, &k, size); \n\t}\n\t*size = pathsize;\n\treturn files;\n}` \nint main(int argc, char **argv) {\n\t// get the \"current\" directory.\n\tchar *path = \"./\";\n\tchar *explore[BUFSIZ];\n\tnode_t nodes[BUFSIZ], *ret;\n\tint ifiles = 0, explore_length = 1, i = 0, j = 0;\n\tlong size;\n\tif (argc == 2)\n\t\tpath = argv[1];\n\texplore[0] = path;\n\t// iterate over all files in directory\n\tfor(; i < explore_length; i++) {\n\t\tret = getfiles(explore[i], explore, nodes, &j, &size);\n\t\tqsort(nodes, j, sizeof(node_t), cmpnode);\n\t}\n\t// print out directory information.\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.5884146094322205, "alphanum_fraction": 0.6189024448394775, "avg_line_length": 18.176469802856445, "blob_id": "2f5bcfb1a71f1eca34a2756620ed82ba32101280", "content_id": "af8f3b9a7a62bda44f763a39563cd6e8b73a9979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 30, "num_lines": 17, "path": "/cs177/hw4/temp.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "\ndef p(x,y,c):\n\tif not x and not y and not c:\n\t\treturn .1\n\telif not x and y and not c:\n\t\treturn .2\n\telif x and not y and not c:\n\t\treturn .2\n\telif x and y and not c:\n\t\treturn .1\n\telif not x and not y and c:\n\t\treturn .25\n\telif not x and y and c:\n\t\treturn .1\n\telif x and not y and c:\n\t\treturn .05\n\telif x and y and c:\n\t\treturn .0\t\n" }, { "alpha_fraction": 0.47857141494750977, "alphanum_fraction": 0.5114285945892334, "avg_line_length": 15.642857551574707, "blob_id": "9584df38676830dc1b2bbcb4e16b83e3f5c7d945", "content_id": "15c69420fa862127c915523acbe89a26a1a0b9a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 700, "license_type": "no_license", "max_line_length": 39, "num_lines": 42, "path": "/cs143A/project3/src/myfork/my_fork.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer\n// 22514022\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/wait.h>\n#include <unistd.h>\n\n#define NUM_CHILDREN 3\n\nvoid printK(char c[], int k) {\n\tint i = 0;\n\tfor (; i < k; i++) {\n\t\tputchar(c[0]);\n\t}\n}\n\nint main(int argc, char **argv) {\n\tint k = 10;\n\tchar letters[] = {'A', 'B', 'C', 'D'};\n\tif (argc == 2) {\n\t\t// read in number of k.\n\t\tk = strtol(argv[1], NULL, 10); \n\t}\n\tpid_t ids[NUM_CHILDREN];\n\tint i = 0;\n\tfor (; i < NUM_CHILDREN; i++) {\n\t\tpid_t id = fork();\n\t\tif (id != 0) { \n\t\t\tids[i] = id;\n\t\t} // call parent\t\n\t\telse {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (i == NUM_CHILDREN) {\n\t\ti = 0;\n\t\tfor (; i < NUM_CHILDREN; i++)\n\t\t\twaitpid(ids[i], NULL, 0);\n\t}\n\tprintK(letters + (i % 4), k);\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.6166666746139526, "avg_line_length": 14, "blob_id": "7620642dcf3857c3b037958323ce32f2498a4f36", "content_id": "cd25984b24a2dcf4ae8f71510eb0c5e3d8c726b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 60, "license_type": "no_license", "max_line_length": 38, "num_lines": 4, "path": "/cs143B/project1/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "all:\n\tg++ -o main main.cpp -ggdb -std=c++11\nclean:\n\trm main\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.615217387676239, "avg_line_length": 22.406780242919922, "blob_id": "903ddf056eebc65cf775c7f4f05bb1dbbc567007", "content_id": "2cbb518e036fe60ca6767944f4d50e565c13648b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 72, "num_lines": 59, "path": "/cs143B/project3/main.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <sstream>\n#include <string>\n#include \"pm.h\"\n\ntypedef std::vector< std::vector< std::string> > file_content_t;\nstd::vector<std::string> split_args(std::string input_args) {\n\tstd::string buf;\n\tstd::stringstream ss(input_args);\n\tstd::vector<std::string> tokens;\n\twhile (ss >> buf)\n\t\ttokens.push_back(buf);\n\n\treturn tokens;\n}\n\nfile_content_t get_file_as_string(std::ifstream &file) {\n\tstd::vector< std::vector< std::string > > file_vector;\n\tif (file.is_open()) {\n\t\tstd::string s;\n\t\twhile (std::getline(file, s)) {\n\t\t\tfile_vector.push_back(split_args(s));\n\t\t}\n\t}\n\treturn file_vector;\n}\n\nint main(int argc, char *argv[]) {\n\tif (argc < 3) {\n\t\tstd::cerr << \"No input files provided\" << std::endl;\n\t\treturn -1;\n\t}\n\n\t\n\t// get the file content\n\tstd::ifstream config_file(argv[1]), input_file(argv[2]);\n\tfile_content_t config = get_file_as_string(config_file);\n\tstd::vector< std::string > input = (get_file_as_string(input_file))[0];\n\n\tfor (int i = 0; i < 2; i++) {\n\t\tstd::string fname = \"22514022\" + std::to_string(i + 1) + \".txt\";\n\t\tpm p(fname, i & 1);\n\t\tp.initialize(config);\n\t\tfor (int i = 0; i < input.size(); i += 2) {\n\t\t\tint action = std::stoi(input[i]);\n\t\t\tint address = std::stoi(input[i + 1]);\n\t\t\tif (!action) {\n\t\t\t\t// read\n\t\t\t\tp.read(address);\n\t\t\t} else {\n\t\t\t\t// write\n\t\t\t\tp.write(address);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}" }, { "alpha_fraction": 0.5784404873847961, "alphanum_fraction": 0.5967691540718079, "avg_line_length": 25.178861618041992, "blob_id": "02a1f50a9dbcb238771763d803643400e4fc0015", "content_id": "3ee1dd33d682f6113e9d94171b3fef1f50b44bb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3219, "license_type": "no_license", "max_line_length": 83, "num_lines": 123, "path": "/cs143B/project2/main.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian schweer\n// 22514022\n#include <iostream>\n#include <string>\n#include <cstdio>\n#include <cassert>\n#include <sstream>\n#include <vector>\n#include \"filesystem/filesystem.h\"\n#include \"io/iosystem.h\"\n\nint location = 1;\nconst int BLOCK_SIZE = 64;\n\nconst std::string CREATE = \"cr\";\nconst std::string DESTORY = \"de\";\nconst std::string OPEN = \"op\";\nconst std::string CLOSE = \"cl\";\nconst std::string WRITE = \"wr\";\nconst std::string READ = \"rd\";\nconst std::string SEEK = \"sk\";\nconst std::string INIT = \"in\";\nconst std::string SAVE = \"sv\";\nconst std::string DIR = \"dr\";\n\nstd::vector<std::string> split_args(std::string input_args) {\n\tstd::string buf;\n\tstd::stringstream ss(input_args);\n\tstd::vector<std::string> tokens;\n\twhile (ss >> buf)\n\t\ttokens.push_back(buf);\n\n\treturn tokens;\n}\n\nstd::vector<std::string> prompt() {\n\tstd::string input;\n\tgetline(std::cin, input);\n\treturn split_args(input);\n}\n\nint string_to_int(std::string input) {\n\treturn std::stoi(input);\n}\n\nvoid run() {\n\t// assume init.\n\tFile_system *f = File_system::CreateFileSystem(IO_system::CreateIOSystem());\n\tstd::string input;\n\twhile (getline(std::cin, input)) {\n\t\tstd::vector<std::string> params = split_args(input);\n\t\tif (params.size() == 0) {\n\t\t\tstd::cout << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string cmd = params[0];\n\t\tif (!CREATE.compare(cmd)) {\n\t\t\tf->create_file(params[1]);\n\t\t} else if (!DESTORY.compare(cmd)) {\n\t\t\tf->destroy_file(params[1]);\n\t\t} else if (!OPEN.compare(cmd)) {\n\t\t\tf->open_file(params[1]);\n\t\t} else if (!CLOSE.compare(cmd)) {\n\t\t\tf->close_file(string_to_int(params[1]));\n\t\t} else if (!WRITE.compare(cmd)) {\n\t\t\tf->write_file(string_to_int(params[1]), params[2][0], string_to_int(params[3]));\n\t\t} else if (!READ.compare(cmd)) {\n\t\t\tf->read_file(string_to_int(params[1]), string_to_int(params[2]));\n\t\t} else if (!SEEK.compare(cmd)) {\n\t\t\tf->seek_file(string_to_int(params[1]), string_to_int(params[2]));\n\t\t} else if (!INIT.compare(cmd)) {\n\t\t\tif (params.size() == 1) {\n\t\t\t\tparams.push_back(\"\");\n\t\t\t}\n\t\t\tf->init(params[1], IO_system::CreateIOSystem());\n\t\t} else if (!SAVE.compare(cmd)) {\n\t\t\tf->save(params[1]);\n\t\t} else if (!DIR.compare(cmd)) {\n\t\t\tf->dir();\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n}\n\nint main() {\n\trun();\n\t// IO_system *io = IO_system::CreateIOSystem();\n\t// File_system *f = File_system::CreateFileSystem(io);\n\t// f->create_file(\"ian\");\n\t// f->create_file(\"ibn\");\n\t// f->create_file(\"icn\");\n\t// f->create_file(\"idn\");\n\t// f->create_file(\"ien\");\n\t// f->create_file(\"ifn\");\n\t// f->create_file(\"ign\");\n\t// f->create_file(\"ihn\");\n\n\t// // @todo: This errors! I don't know why.\n\t// f->create_file(\"iin\");\n\t// f->create_file(\"ijn\");\n\t// f->create_file(\"ikn\");\n\t// f->open_file(\"ian\");\n\t// f->write_file(1, 'a', 20);\n\t// f->write_file(1, 'c', 42);\n\t// f->write_file(1, 'd', 4);\n\t// f->write_file(1, 'q', 50);\n\t// f->write_file(1, 'e', 34);\n\t// f->write_file(1, 'l', 40);\n\t// // f->init(\"temp.txt\", IO_system::CreateIOSystem());\n\t// // f->open_file(\"ian\");\n\t// f->seek_file(1, 0);\n\t// f->read_file(1, 190);\n\t// f->close_file(1);\n\t// f->open_file(\"ian\");\n\t// f->close_file(1);\n\t// // io->read_block(7, buf);\n\t// f->save(\"temp.txt\");\n\n\t// f->init(\"temp.txt\", IO_system::CreateIOSystem());\n\t// f->open_file(\"ian\");\n\t// f->read_file(1, 190);\n\treturn 0;\n}" }, { "alpha_fraction": 0.5284916162490845, "alphanum_fraction": 0.6203910708427429, "avg_line_length": 30.40350914001465, "blob_id": "de7f62955d869d54f1b3ec4f0932f90903070500", "content_id": "9acf5056f9121772e8249ca808af7b52ac9f9c5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3580, "license_type": "no_license", "max_line_length": 164, "num_lines": 114, "path": "/cs177/hw1/binompdf.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nclass Memory:\n\tdef __init__(self):\n\t\tself.data = {}\n\n\tdef inmemory(self, k):\n\t\treturn self.data.has_key(k)\n\n\tdef remember(self, k, x):\n\t\tself.data[k] = x\n\t\treturn x\n\n\tdef recall(self, k):\n\t\treturn self.data[k]\n\nmem = Memory()\n\ndef factorial(k):\n\tif (k == 0 or k == 1):\n\t\treturn 1;\n\tif (mem.inmemory(k)):\n\t\treturn mem.recall(k)\n\telse:\n\t\treturn mem.remember(k, k * factorial(k - 1))\n\ndef nchoosek(n, k):\n\t# N choose K = \n\t#\t\tn!\n\t# --------------\n\t# k! * (n - k)!\n\tnfac = factorial(n)\n\tkfac = factorial(k)\n\tnminkfac = factorial(n - k) # will certainly be cached.\n\treturn nfac / (kfac * nminkfac)\n\ndef binomialapprox(n, i, p, doprint=False):\n\tnbyp = n * p\n\tdenom = math.sqrt(2. * np.pi * nbyp * (1. - p))\n\n\t# get 'e's power\n\tx = pow((i - nbyp), 2) / (2.*nbyp*(1. - p))\n\tif doprint:\n\t\tprint \"denom=\", denom, \"x=\", x\n\t\tprint \"1/denom=\",(1./denom),\"pow to x=\",math.pow(np.e,-x)\n\treturn (1. / denom) * pow(np.e, -x)\n\ndef binomialexact(n, i, p):\n\treturn nchoosek(n, i) * pow(p, i) * pow((1 - p), n - i)\n\ndef binomialdist(n, p):\n\tn = n * 1.\n\tp = p * 1.\n\tif (n > 100):\n\t\treturn np.array( [ binomialapprox(n, i, p) for i in range(0, int(n + 1)) ] )\n\treturn np.array([ binomialexact(n, i, p) for i in range(0, int(n+1))])\n\ndef binomialcdf(n, p):\n\ttoplot = binomialdist(n, p)\n\tsums=[]\n\tcurrentsum=0.0\n\tfor i,x in enumerate(toplot):\n\t\tcurrentsum = currentsum + x\n\t\tsums.append(currentsum)\n\n\treturn sums\n\nprint \"Printing graph for parameters described in problem 7\"\nprint \"Graph one and two are only different based on their location. They're both rather fat and have small n's, meaning that these graphs have very high veriance.\"\nprint \"Graph three and four are much skinner compared to 1 and 2, have a lower variance\"\nprint \"All three graphs are roughly symmetric around np\"\nfig,ax = plt.subplots(2, 2)\nax[0][0].bar(range(0, 26), binomialdist(25, .1))\nax[0][0].set_title(\"n = 25, p = .1\")\nax[0][1].bar(range(0, 26), binomialdist(25, .75))\nax[0][1].set_title(\"n = 25, p = .75\")\nax[1][0].bar(range(0, 1001), binomialdist(1000, .5))\nax[1][0].set_title(\"n = 1000, p = .5\")\nax[1][1].bar(range(0, 1001), binomialdist(1000, .9))\nax[1][1].set_title(\"n = 1000, p = .9\")\nplt.gcf().canvas.set_window_title('Binomial pmf')\nplt.show()\n\nprint \"Printing graph for parameters described in problem 8\"\nfig,ax = plt.subplots(2, 2)\nax[0][0].bar(range(0, 26), binomialcdf(25, .1))\nax[0][0].set_title(\"n = 25, p = .1\")\nax[0][1].bar(range(0, 26), binomialcdf(25, .75))\nax[0][1].set_title(\"n = 25, p = .75\")\nax[1][0].bar(range(0, 1001), binomialcdf(1000, .5))\nax[1][0].set_title(\"n = 1000, p = .5\")\nax[1][1].bar(range(0, 1001), binomialcdf(1000, .9))\nax[1][1].set_title(\"n = 1000, p = .9\")\nplt.gcf().canvas.set_window_title('Binomial cdf')\nplt.show()\n\nprint \"Entering problem 9 answers\"\nprint \"X ~ binom(10000, .1). (10000 choose 1000)P[X = 1000]^1000 * (1-P[x=1000])^9000 = \",binomialapprox(10000., 1000., .1) \nprint \"X ~ binom(10000, .1). P[X >= 1000] = 1 - cdf[999] = \",(1. - binomialcdf(10000, .1)[998])\nprint \"X ~ binom(10000, .1). P[X >= 1100] = 1 - cdf[1099] = \",(1. - binomialcdf(10000, .1)[1098]) \nprint \"X ~ binom(10000, .1). P[X <= 900] = cdf[900] \",binomialcdf(10000, .1)[900]\n\n# Find the largest possible value such that P[X >= 500] < .0000002\n# for loop over all possible P's from 0 - 1\n# print first one that is less than < .0000002\ndelta = 2 * pow(10, -7)\nfor i in range(1, 100):\n\tp = (i*1.)/100.0\n\tprint p,binomialcdf(10000,p)[498]\n\tif ((1-binomialcdf(10000, p)[498]) > delta):\n\t\tprint \"The minimum p = \", p\n\t\tbreak\n" }, { "alpha_fraction": 0.6933333277702332, "alphanum_fraction": 0.7177777886390686, "avg_line_length": 27.125, "blob_id": "b7280ac6f2d93d3543bfe412bd8f18dcb7d6a422", "content_id": "5a282ee395662ea1fcf7c4132da98714c8b52544", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/cs178/hw2/three.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib as plt\nimport mltools as ml\nimport mltools.linear\n\nX1 = np.genfromtxt(\"data/kaggle.X1.train.txt\", delimiter=\",\")\nY = np.genfromtxt(\"data/kaggle.Y.train.txt\", delimiter=\",\")\nprint X1.shape, Y.shape\n\nXe1 = np.genfromtxt(\"data/kaggle.X1.test.txt\", delimiter=\",\")\n\nlr = ml.linear.linearRegress(X1, Y)\nprint lr.mse(X1, Y)\nY2 = lr.predict(Xe1)\nnp.savetxt(\"output.csv\", Y2, delimiter=',', header=\"Predictions\")\nprint Y2\n" }, { "alpha_fraction": 0.6452932953834534, "alphanum_fraction": 0.668485701084137, "avg_line_length": 24.275861740112305, "blob_id": "39a7034488557964a2a21ce95a8f7ebb51989d36", "content_id": "1ba233f6402bc353121b72bfedbef8ee442638f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 733, "license_type": "no_license", "max_line_length": 60, "num_lines": 29, "path": "/cs177/hw6/plotNormal.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import pow\nfrom math import exp\nfrom math import pi\nfrom math import sqrt\n\n# plots the normal distribution\n# mu is the mean\n# var is the variance\n# x are the locations to plot\n# f(x) = (1 / var*sqrt(2pi))e(-(x-mu)2)/2var2\ninput=raw_input\ndef plotNormal(mu, stddev, X):\n\te=lambda x,mu,stddev: exp(-(pow(x-mu,2)/2*pow(stddev,2)))\n\tY=[(1/(stddev * sqrt(2*pi))) * e(x, mu ,stddev) for x in X]\n\tplt.plot(X, Y)\n\tplt.show()\n\n# 5.5, 8.25\nmu=float(input(\"Please enter mean: \"))\nvar=float(input(\"Please enter variance: \"))\nN=int(input(\"Please enter size of data: \"))\nX=np.zeros(N)\nfor i in range(N):\n\tX[i]=float(input(\"\\t\"+str(i)+\"=\"))\t\n\nplotNormal(mu, var, X)\n" }, { "alpha_fraction": 0.5747422575950623, "alphanum_fraction": 0.5798969268798828, "avg_line_length": 23.25, "blob_id": "ff8b0db28d863f8f10865ec43b6938af1f703790", "content_id": "ea443d51838c585a1da2753fa0aefa4e48225650", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 388, "license_type": "no_license", "max_line_length": 61, "num_lines": 16, "path": "/cs146/midterm_study/temp.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\nint main( void )\n{\n\tint pid;\n\tprintf( \"ORIGINAL: PID=%d PPID=%d\\n\", getpid(), getppid() );\n\tpid = fork();\n\tif( pid != 0 )\n\t\tprintf( \"PARENT: PID=%d PPID=%d child=%d\\n\",\n\t\t\tgetpid(), getppid(), pid );\n\telse\n\t\tprintf( \"CHILD: PID=%d PPID=%d\\n\", getpid(), getppid() );\n\tprintf( \"PID %d terminates.\\n\\n\", getpid() );\n\treturn( 0 );\n}\n" }, { "alpha_fraction": 0.6505717635154724, "alphanum_fraction": 0.6728081107139587, "avg_line_length": 29.882352828979492, "blob_id": "603248f2666838cff7f75cdf9a536d4b6722977c", "content_id": "874d4a1056ed35665f88a3ad106c6b691b2a97a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1574, "license_type": "no_license", "max_line_length": 101, "num_lines": 51, "path": "/cs177/hw2/sevenandeight.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# data: numpy.array\ndef analyze_session_data(data):\n\tlongest = data.shape[0]\n\tshortest = data.argmax() + 1\n\tprint \"1.) Longest =\",longest,\"Shortest =\",shortest\n\n\t# Most common session length\n\tprint \"2.) Most common session was a session of length\",data.argmax() + 1,\"with\",data[data.argmax()]\n\n\t# total number of sessions\n\ttotalsessions = np.sum(data)\n\tprint \"3.) Total number of sessions\",totalsessions\n\n\t# total number of pages requested.\n\t# each value multiplied by it's position.\n\ttotalrequests = np.sum([data[i] * (i + 1) for i in range(data.shape[0])])\n\tprint \"4.) Total number of requests\", totalrequests\n\n\t# probabilities of session lengths of 1-6\n\tprint \"5.) probabilities of session lengths 1,2,3,4,5,6\"\n\tempericalmodel=[]\n\tfor i in range(1, 7):\n\t\tempericalmodel.append(data[i]/totalsessions)\n\t\tprint \" p(\"+str(i)+\")=\"+str(np.around(data[i]/totalsessions, decimals=3))\n\n\t# Emperical mean\n\tprint \"6.) E[X] =\",np.mean(data)\n\treturn empericalmodel\n\ndef plot_session_model(data, empericalmodel):\n\t# guess p based our mean\n\tp = 1. / np.mean(data)\n\tkeys = np.arange(1, 50, .5)\n\tdata=[ pow(p*(1-p), i - 1) for i in keys]\n\tplt.semilogy(data, color='r')\n\n\t# power law distribution\n\tZ = 6/pow(np.pi,2)\n\tplt.loglog([Z * pow(1./i, 2) for i in keys], color='g')\n\tplt.plot(empericalmodel, \"b-\")\n\tplt.show()\n\nif __name__ == '__main__':\n\tdata = np.genfromtxt(\"sessionlengths.txt\")\n\tprint \"========Problem 7========\"\n\temperical=analyze_session_data(data)\n\tprint \"========Problem 8========\"\n\tplot_session_model(data, emperical)" }, { "alpha_fraction": 0.557823121547699, "alphanum_fraction": 0.5646258592605591, "avg_line_length": 13.699999809265137, "blob_id": "311ab7880a4d58641b2b121ac64b372a3433e9bd", "content_id": "1975c2c9dec6816794a9873955dd7a59cc55509d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 147, "license_type": "no_license", "max_line_length": 36, "num_lines": 10, "path": "/cs146/hw4/foo.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n\tint c;\n\twhile (EOF != (c = fgetc(stdin))) {\n\t\tprintf(\"You entered %c\\n\", c);\n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.652718186378479, "alphanum_fraction": 0.6540313363075256, "avg_line_length": 26.86097526550293, "blob_id": "612900aa3568f3f55440ec3092d471b7667b4330", "content_id": "35f1e8eb8ea42b070fd2d5c146b1d2a83906966b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11423, "license_type": "no_license", "max_line_length": 130, "num_lines": 410, "path": "/ics46/ProgramFour/src/hash_set.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef HASH_SET_HPP_\n#define HASH_SET_HPP_\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <initializer_list>\n#include \"ics_exceptions.hpp\"\n#include \"pair.hpp\"\n#include \"iterator.hpp\"\n#include \"set.hpp\"\n\n\nnamespace ics {\n\ntemplate<class T> class HashSet : public Set<T>\t{\n public:\n HashSet() = delete;\n HashSet(int (*ahash)(const T& element), double the_load_factor = 1.0);\n HashSet(int initial_bins, int (*ahash)(const T& element), double the_load_factor = 1.0);\n HashSet(const HashSet<T>& to_copy);\n HashSet(std::initializer_list<T> il, int (*ahash)(const T& element), double the_load_factor = 1.0);\n HashSet(ics::Iterator<T>& start, const ics::Iterator<T>& stop, int (*ahash)(const T& element), double the_load_factor = 1.0);\n virtual ~HashSet();\n\n virtual bool empty () const;\n virtual int size () const;\n virtual bool contains (const T& element) const;\n virtual std::string str () const;\n\n virtual bool contains (ics::Iterator<T>& start, const ics::Iterator<T>& stop) const;\n\n virtual int insert (const T& element);\n virtual int erase (const T& element);\n virtual void clear ();\n\n virtual int insert (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n virtual int erase (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n virtual int retain (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n\n virtual HashSet<T>& operator = (const HashSet<T>& rhs);\n virtual bool operator == (const Set<T>& rhs) const;\n virtual bool operator != (const Set<T>& rhs) const;\n virtual bool operator <= (const Set<T>& rhs) const;\n virtual bool operator < (const Set<T>& rhs) const;\n virtual bool operator >= (const Set<T>& rhs) const;\n virtual bool operator > (const Set<T>& rhs) const;\n\n template<class T2>\n friend std::ostream& operator << (std::ostream& outs, const HashSet<T2>& s);\n\n virtual ics::Iterator<T>& ibegin () const;\n virtual ics::Iterator<T>& iend () const;\n\n private:\n class LN;\n\n public:\n class Iterator : public ics::Iterator<T> {\n public:\n //KLUDGE should be callable only in begin/end\n Iterator(HashSet<T>* iterate_over, bool begin);\n Iterator(const Iterator& i);\n virtual ~Iterator();\n virtual T erase();\n virtual std::string str () const;\n virtual const ics::Iterator<T>& operator ++ ();\n virtual const ics::Iterator<T>& operator ++ (int);\n virtual bool operator == (const ics::Iterator<T>& rhs) const;\n virtual bool operator != (const ics::Iterator<T>& rhs) const;\n virtual T& operator * () const;\n virtual T* operator -> () const;\n private:\n ics::pair<int,LN*> current; //Bin Index/Cursor; stop: LN* == nullptr\n HashSet<T>* ref_set;\n int expected_mod_count;\n bool can_erase = true;\n void advance_cursors();\n };\n\n virtual Iterator begin () const;\n virtual Iterator end () const;\n\n private:\n class LN {\n public:\n LN () : next(nullptr){}\n LN (const LN& ln) : value(ln.value), next(ln.next){}\n LN (T v, LN* n = nullptr) : value(v), next(n){}\n\n T value;\n LN* next;\n };\n\n LN** set = nullptr;\n int (*hash)(const T& element);\n double load_factor;//used/bins <= load_factor\n int bins = 1; //# bins available in the array\n int used = 0; //# of key->value pairs in the hash table\n int mod_count = 0; //For sensing concurrent modification\n int hash_compress (const T& element) const;\n void ensure_load_factor(int new_used);\n LN* find_element (int bin, const T& element) const;\n LN* copy_list(LN* l) const;\n LN** copy_hash_table(LN** ht, int bins) const;\n void delete_hash_table(LN**& ht, int bins);\n };\n\n\n\n\n\ntemplate<class T>\nHashSet<T>::HashSet(int (*ahash)(const T& element), double the_load_factor)\n : hash(ahash), load_factor(the_load_factor) {\n //write code here\n}\n\ntemplate<class T>\nHashSet<T>::HashSet(int initial_bins, int (*ahash)(const T& element), double the_load_factor)\n : bins(initial_bins), hash(ahash), load_factor(the_load_factor) {\n //write code here\n}\n\ntemplate<class T>\nHashSet<T>::HashSet(const HashSet<T>& to_copy)\n : hash(to_copy.hash), load_factor(to_copy.load_factor), bins(to_copy.bins), used(to_copy.used) {\n //write code here\n}\n\ntemplate<class T>\nHashSet<T>::HashSet(ics::Iterator<T>& start, const ics::Iterator<T>& stop, int (*ahash)(const T& element), double the_load_factor)\n : hash(ahash), load_factor(the_load_factor) {\n //write code here\n}\n\ntemplate<class T>\nHashSet<T>::HashSet(std::initializer_list<T> il,int (*ahash)(const T& k), double the_load_factor)\n : hash(ahash), load_factor(the_load_factor) {\n //write code here\n}\n\ntemplate<class T>\nHashSet<T>::~HashSet() {\n //write code here\n}\n\n\ntemplate<class T>\ninline bool HashSet<T>::empty() const {\n //write code here\n}\n\ntemplate<class T>\nint HashSet<T>::size() const {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::contains (const T& element) const {\n //write code here\n}\n\ntemplate<class T>\nstd::string HashSet<T>::str() const {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::contains(ics::Iterator<T>& start, const ics::Iterator<T>& stop) const {\n //write code here\n}\n\ntemplate<class T>\nint HashSet<T>::insert(const T& element) {\n //write code here\n}\n\ntemplate<class T>\nint HashSet<T>::erase(const T& element) {\n //write code here\n}\n\ntemplate<class T>\nvoid HashSet<T>::clear() {\n //write code here\n}\n\ntemplate<class T>\nint HashSet<T>::insert(ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n //write code here\n}\n\ntemplate<class T>\nint HashSet<T>::erase(ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n //write code here\n}\n\ntemplate<class T>\nint HashSet<T>::retain(ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n //write code here\n}\n\ntemplate<class T>\nHashSet<T>& HashSet<T>::operator = (const HashSet<T>& rhs) {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::operator == (const Set<T>& rhs) const {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::operator != (const Set<T>& rhs) const {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::operator <= (const Set<T>& rhs) const {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::operator < (const Set<T>& rhs) const {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::operator >= (const Set<T>& rhs) const {\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::operator > (const Set<T>& rhs) const {\n //write code here\n}\n\ntemplate<class T>\nstd::ostream& operator << (std::ostream& outs, const HashSet<T>& s) {\n //write code here\n}\n\n//KLUDGE: memory-leak\ntemplate<class T>\nauto HashSet<T>::ibegin () const -> ics::Iterator<T>& {\n return *(new Iterator(const_cast<HashSet<T>*>(this),true));\n}\n\n//KLUDGE: memory-leak\ntemplate<class T>\nauto HashSet<T>::iend () const -> ics::Iterator<T>& {\n return *(new Iterator(const_cast<HashSet<T>*>(this),false));\n}\n\ntemplate<class T>\nauto HashSet<T>::begin () const -> HashSet<T>::Iterator {\n return Iterator(const_cast<HashSet<T>*>(this),true);\n}\n\ntemplate<class T>\nauto HashSet<T>::end () const -> HashSet<T>::Iterator {\n return Iterator(const_cast<HashSet<T>*>(this),false);\n}\n\ntemplate<class T>\nint HashSet<T>::hash_compress (const T& element) const {\n //write code here\n}\n\ntemplate<class T>\nvoid HashSet<T>::ensure_load_factor(int new_used) {\n //write code here\n}\n\ntemplate<class T>\ntypename HashSet<T>::LN* HashSet<T>::find_element (int bin, const T& element) const {\n for (LN* c = set[bin]; c->next!=nullptr; c=c->next)\n if (element == c->value)\n return c;\n\n return nullptr;\n}\n\ntemplate<class T>\ntypename HashSet<T>::LN* HashSet<T>::copy_list (LN* l) const {\n if (l == nullptr)\n return nullptr;\n else\n return new LN(l->value, copy_list(l->next));\n}\n\ntemplate<class T>\ntypename HashSet<T>::LN** HashSet<T>::copy_hash_table (LN** ht, int bins) const {\n //write code here\n}\n\ntemplate<class T>\nvoid HashSet<T>::delete_hash_table (LN**& ht, int bins) {\n //write code here\n}\n\n\ntemplate<class T>\nvoid HashSet<T>::Iterator::advance_cursors(){\n //write code here\n}\n\n\n\n\ntemplate<class T>\nHashSet<T>::Iterator::Iterator(HashSet<T>* iterate_over, bool begin) : ref_set(iterate_over) {\n //write code here\n}\n\n\ntemplate<class T>\nHashSet<T>::Iterator::Iterator(const Iterator& i) :\n current(i.current), ref_set(i.ref_set), expected_mod_count(i.expected_mod_count), can_erase(i.can_erase) {}\n\ntemplate<class T>\nHashSet<T>::Iterator::~Iterator() {}\n\ntemplate<class T>\nT HashSet<T>::Iterator::erase() {\n if (expected_mod_count != ref_set->mod_count)\n throw ConcurrentModificationError(\"HashSet::Iterator::erase\");\n if (!can_erase)\n throw CannotEraseError(\"HashSet::Iterator::erase Iterator cursor already erased\");\n if (current.second == nullptr)\n throw CannotEraseError(\"HashSet::Iterator::erase Iterator cursor beyond data structure\");\n\n //write code here\n}\n\ntemplate<class T>\nstd::string HashSet<T>::Iterator::str() const {\n //write code here\n}\n\ntemplate<class T>\nconst ics::Iterator<T>& HashSet<T>::Iterator::operator ++ () {\n if (expected_mod_count != ref_set->mod_count)\n throw ConcurrentModificationError(\"HashSet::Iterator::operator ++\");\n\n //write code here\n}\n\n//KLUDGE: creates garbage! (can return local value!)\ntemplate<class T>\nconst ics::Iterator<T>& HashSet<T>::Iterator::operator ++ (int) {\n if (expected_mod_count != ref_set->mod_count)\n throw ConcurrentModificationError(\"HashSet::Iterator::operator ++(int)\");\n\n //write code here\n}\n\ntemplate<class T>\nbool HashSet<T>::Iterator::operator == (const ics::Iterator<T>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n throw IteratorTypeError(\"HashSet::Iterator::operator ==\");\n if (expected_mod_count != ref_set->mod_count)\n throw ConcurrentModificationError(\"HashSet::Iterator::operator ==\");\n if (ref_set != rhsASI->ref_set)\n throw ComparingDifferentIteratorsError(\"HashSet::Iterator::operator ==\");\n\n //write code here\n}\n\n\ntemplate<class T>\nbool HashSet<T>::Iterator::operator != (const ics::Iterator<T>& rhs) const {\n const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n if (rhsASI == 0)\n throw IteratorTypeError(\"HashSet::Iterator::operator !=\");\n if (expected_mod_count != ref_set->mod_count)\n throw ConcurrentModificationError(\"HashSet::Iterator::operator !=\");\n if (ref_set != rhsASI->ref_set)\n throw ComparingDifferentIteratorsError(\"HashSet::Iterator::operator !=\");\n\n //write code here\n}\n\ntemplate<class T>\nT& HashSet<T>::Iterator::operator *() const {\n if (expected_mod_count !=\n ref_set->mod_count)\n throw ConcurrentModificationError(\"HashSet::Iterator::operator *\");\n if (!can_erase || current.second == nullptr)\n throw IteratorPositionIllegal(\"HashSet::Iterator::operator * Iterator illegal: exhausted\");\n\n //write code here\n}\n\ntemplate<class T>\nT* HashSet<T>::Iterator::operator ->() const {\n if (expected_mod_count !=\n ref_set->mod_count)\n throw ConcurrentModificationError(\"HashSet::Iterator::operator *\");\n if (!can_erase || current.second == nullptr)\n throw IteratorPositionIllegal(\"HashSet::Iterator::operator * Iterator illegal: exhausted\");\n\n //write code here\n}\n\n}\n\n#endif /* HASH_SET_HPP_ */\n" }, { "alpha_fraction": 0.6143613457679749, "alphanum_fraction": 0.6239450573921204, "avg_line_length": 24.702205657958984, "blob_id": "27b4bb1df93dd4a840901818e43197a07fa63ef3", "content_id": "050c3ac181390bda0e5795a627afeb5bfb9c7dc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6991, "license_type": "no_license", "max_line_length": 108, "num_lines": 272, "path": "/ics53/lab4/main.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"csapp.h\"\n#include <sys/socket.h>\n#include <ifaddrs.h>\n#define LOG \"proxy_log.txt\"\n\n//struct designed to hold data used by multiple functions in main.c\ntypedef struct{\n\tFILE* logfile;\n\tint client_fd;\n\tint server_fd;\n\tstruct sockaddr_in clientaddr;\n} AppData;\n\n//static struct to hold application data\nstatic AppData *appdat;\n\n//initializes static appdat\nvoid init_app(){\n\tappdat = (AppData*)malloc(sizeof(AppData));\n\tappdat->logfile = fopen(LOG, \"a\");\n}\n\n//destructor-like function for static appdat\nvoid destroy_app(){\n\tfclose(appdat->logfile);\n\tfree(appdat);\n}\n\n/**\n * Provided functions\n */\nint parse_uri(char *uri, char *target_addr, char *path, int *port);\nvoid format_log_entry(char *logstring, struct sockaddr_in *sockaddr, char *uri, int size);\n\nint get_uri_size(char*);\nint read_response_stream(int, int, char*, char*, char*, int);\nvoid read_whole_stream(int, int, rio_t*, char*);\nint ensure_get_version(char*);\nvoid process_req();\nvoid print_this_ip();\n\nint main(int argc, char** argv) {\n\t\n\t//debug function to print ip\n\tprint_this_ip();\n\t\n\tif (argc != 2) {\n\t\tprintf(\"Please provide an integer for the port\\n\");\n\t\treturn;\n\t}\n\t\n\tinit_app();\n\n\t\n\tint listenfd; /* The connection file descriptor */\n\tint port = atoi(argv[1]);\n\n\t// lets open the file descriptor\n\tlistenfd = open_listenfd(port);\n\t\n\t// main loop\n\twhile (1) {\n\t\t//debug text\n\t\tprintf(\"Now Listening...\\n\");\n\t\tfflush(stdout);\n\t\t\n\t\t//Accept client connections\n\t\tint clientlen = sizeof(appdat->clientaddr);\n\t\tappdat->client_fd = Accept(listenfd, (SA *)&appdat->clientaddr, (socklen_t *) &clientlen);\n\t\t\n\t\t//debug text\n\t\tprintf(\"Connection Accepted...\\n\");\n\t\tfflush(stdout);\n\t\t\n\t\t//Handle client request\n\t\tprocess_req();\n\t}\n}\n\nvoid process_req(){\n\t//Prefer to work with FILE\n\tint client_fd = appdat->client_fd;\n\tchar buffer[MAXLINE], request[MAXLINE], response[MAXLINE], hostname[MAXLINE], path[MAXLINE], log[MAXLINE];\n\tchar *request_uri, *host_address_ptr, *rest;\n\tint size = -1, port;\n\trio_t rio;\n\tstruct sockaddr_in clientaddr = appdat->clientaddr;\n\tstruct hostent *host_ptr;\n\t\n\t// output the ip address of the client to our log file.\n\t// Luckily this isn't concurrent, so we can open a file reference\n\t// here.\n\thost_ptr = Gethostbyaddr((char *)&clientaddr.sin_addr.s_addr,\n\t\t\t sizeof(clientaddr.sin_addr.s_addr), \n\t\t\t AF_INET);\n\thost_address_ptr = inet_ntoa(clientaddr.sin_addr);\n\t\n\tRio_readinitb(&rio, client_fd);\n\tread_whole_stream(MAXLINE, client_fd, &rio, request);\n\t\n\t// We don't handle POST, PUT, or DELETE requests.\n\tif (strncmp(request, \"GET \", strlen(\"GET \"))) {\n\t\tprintf(\"process_request: Received non-GET request\\n\");\n\t\tclose(client_fd);\n\t\trequest[0] = '\\0';\n\t\treturn;\n\t}\n\tprintf(\"REQUEST:\\n---------------------------------- \\n%s\\n----------------------------------\\n\", request);\n\t// filter out the \"GET \" from the request\n\trequest_uri = request + 4;\n\tsize = get_uri_size(request_uri);\n\tif (!ensure_get_version(&request_uri[size + 1])) {\n\t\tprintf(\"Not proper GET version\");\n\t\trequest[0] = '\\0';\n\t\treturn;\n\t}\n\trest = &request_uri[size + 1] + strlen(\"HTTP/1.0\\r\\n\");\n\t// we have a good url, lets parse it and get our end data.\n\tif (parse_uri(request_uri, hostname, path, &port) < 0) {\n\t\tprintf(\"Failed to parse url %s\", request_uri);\n\t\trequest[0] = '\\0';\n\t\treturn;\n\t}\n\telse {\n\t\tint n = read_response_stream(client_fd, MAXLINE, hostname, path, rest, port);\n\t\tformat_log_entry(log, &clientaddr, request_uri, n);\n\t\t\n\t\t// log\n\t\tFILE *logf = Fopen(LOG, \"a\");\n\t\tfprintf(logf, \"%s %d\\n\", log, n);\n\t\tfflush(logf);\n\t\tfclose(logf);\n\t}\n\t//close connection\n\tclose(appdat->client_fd);\n\trequest[0] = '\\0';\n\tresponse[0] = '\\0';\n\thostname[0] = '\\0';\n\tpath[0] = '\\0';\n\treturn;\n}\n\n//debug function to print ip\nvoid print_this_ip(){\n\tstruct ifaddrs *addrs;\n\tgetifaddrs(&addrs);\n\tstruct ifaddrs *tmp = addrs;\n\n\twhile (tmp) \n\t{\n\t\tif (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET)\n\t\t{\n\t\t\tstruct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;\n\t\t\tprintf(\"%s: %s\\n\", tmp->ifa_name, inet_ntoa(pAddr->sin_addr));\n\t\t}\n\n\t\ttmp = tmp->ifa_next;\n\t}\n\n\tfreeifaddrs(addrs);\n}\n\nint get_uri_size(char *uri) {\n\tint size = 0;\n\twhile (uri[size] != '\\0' && uri[size] != ' ') size++;\n\turi[size] = '\\0';\n\treturn size;\n}\n\nint ensure_get_version(char *get_version) {\n\treturn !(strncmp(get_version, \"HTTP/1.0\\r\\n\", strlen(\"HTTP/1.0\\r\\n\")) &&\n\tstrncmp(get_version, \"HTTP/1.1\\r\\n\", strlen(\"HTTP/1.1\\r\\n\")));\n}\n\nint parse_uri(char *uri, char *hostname, char *pathname, int *port)\n{\n char *hostbegin;\n char *hostend;\n char *pathbegin;\n int len;\n\n if (strncasecmp(uri, \"http://\", 7) != 0) {\n\t\thostname[0] = '\\0';\n\t\treturn -1;\n }\n \n /* Extract the host name */\n hostbegin = uri + 7;\n hostend = strpbrk(hostbegin, \" :/\\r\\n\\0\");\n len = hostend - hostbegin;\n strncpy(hostname, hostbegin, len);\n hostname[len] = '\\0';\n \n /* Extract the port number */\n *port = 80; /* default */\n if (*hostend == ':') \n\t\t*port = atoi(hostend + 1);\n \n /* Extract the path */\n pathbegin = strchr(hostbegin, '/');\n if (pathbegin == NULL) {\n\t\tpathname[0] = '\\0';\n }\n else {\n\t\tpathbegin++;\t\n\t\tstrcpy(pathname, pathbegin);\n }\n\n return 0;\n}\n\nvoid read_whole_stream(int size, int stream, rio_t *rio, char *response) {\n\tchar buffer[size];\n\twhile (rio_readlineb(rio,buffer,size) > 0) {\n\t\t// copy.\n\t\tstrcat(response, buffer);\n\t\tif (strcmp(buffer, \"\\r\\n\") == 0)\n\t\t\tbreak;\n\t}\n}\n\nint read_response_stream(int client_f, int size, char *hostname, char *path, char *rest, int port) {\n\trio_t rio;\n int response_len, n, server_fd;\n\tchar buffer[size];\n\t\n\tserver_fd = open_clientfd(hostname, port);\t\t\n\trio_writen(server_fd, \"GET /\", strlen(\"GET /\"));\n\trio_writen(server_fd, path, strlen(path));\n\trio_writen(server_fd, \" HTTP/1.0\\r\\n\", strlen(\" HTTP/1.0\\r\\n\"));\n\trio_writen(server_fd, rest, strlen(rest));\n\tfflush(stdout);\n\tRio_readinitb(&rio, server_fd);\n \twhile( (n = rio_readn(server_fd, buffer, size)) > 0 ) {\n\t\tresponse_len += n;\n\t\tprintf(\"Recieved: %d\\n\", n);\n\t\tfflush(stdout);\n\t\trio_writen(client_f, buffer, n);\n\t\tbzero(buffer, MAXLINE);\n \t}\n\tclose(server_fd);\n\treturn response_len;\n}\n\nvoid format_log_entry(char *logstring, struct sockaddr_in *sockaddr, \n\t\t char *uri, int size)\n{\n time_t now;\n char time_str[MAXLINE];\n unsigned long host;\n unsigned char a, b, c, d;\n\n /* Get a formatted time string */\n now = time(NULL);\n strftime(time_str, MAXLINE, \"%a %d %b %Y %H:%M:%S %Z\", localtime(&now));\n\n /* \n * Convert the IP address in network byte order to dotted decimal\n * form. Note that we could have used inet_ntoa, but chose not to\n * because inet_ntoa is a Class 3 thread unsafe function that\n * returns a pointer to a static variable (Ch 13, CS:APP).\n */\n host = ntohl(sockaddr->sin_addr.s_addr);\n a = host >> 24;\n b = (host >> 16) & 0xff;\n c = (host >> 8) & 0xff;\n d = host & 0xff;\n\n\n /* Return the formatted log entry string */\n sprintf(logstring, \"%s: %d.%d.%d.%d %s\", time_str, a, b, c, d, uri);\n}\n" }, { "alpha_fraction": 0.5295547842979431, "alphanum_fraction": 0.5466991066932678, "avg_line_length": 31.164609909057617, "blob_id": "713e62027e8444f18b3ba6282a3fccebe8ab59ea", "content_id": "cd18b7fbdc1a0ca7aeabf5da1419a6758622d4e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7816, "license_type": "no_license", "max_line_length": 131, "num_lines": 243, "path": "/cs131/project2/partC.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"mpi.h\"\n\n#include <algorithm>\n#include <functional>\n#include <cstdlib>\n#include <ctime>\n#include <cctype>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <iostream>\nconst static int ARRAY_SIZE = 100000;\nusing Lines = char[ARRAY_SIZE][16];\n// Don't CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\n\nstruct Result\n{\n Result()\n : lineNumber(0), firstChar(0), length(0)\n {}\n\n Result(int lineNumber_, int firstChar_, int length_)\n : lineNumber(lineNumber_), firstChar(firstChar_), length(length_)\n {}\n\n // This allows you to compare results with the < (less then) operator, i.e. r1 < r2\n bool\n operator<(Result const& o)\n {\n // Line number can't be equal\n return length < o.length || \n (length == o.length && lineNumber > o.lineNumber) ||\n (length == o.length && lineNumber == o.lineNumber && firstChar > o.firstChar);\n }\n\n int lineNumber, firstChar, length;\n};\n\nvoid DoOutput(Result r)\n{\n std::cout << \"Result: \" << r.lineNumber << \" \" << r.firstChar << \" \" << r.length << std::endl;\n}\n\n// CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\nint findLongest(std::string text, int &s) {\n std::transform(text.begin(), text.end(), text.begin(), ::tolower);\n int N = (int)text.length();\n N = 2*N + 1; //Position count\n int L[N]; //LPS Length Array\n L[0] = 0;\n L[1] = 1;\n int C = 1; //centerPosition\n int R = 2; //centerRightPosition\n int i = 0; //currentRightPosition\n int iMirror; //currentLeftPosition\n int maxLPSLength = 0;\n int maxLPSCenterPosition = 0;\n int start = -1;\n int end = -1;\n int diff = -1;\n \n //Uncomment it to print LPS Length array\n //printf(\"%d %d \", L[0], L[1]);\n for (i = 2; i < N; i++)\n {\n //get currentLeftPosition iMirror for currentRightPosition i\n iMirror = 2*C-i;\n L[i] = 0;\n diff = R - i;\n //If currentRightPosition i is within centerRightPosition R\n if(diff > 0)\n L[i] = std::min(L[iMirror], diff);\n \n //Attempt to expand palindrome centered at currentRightPosition i\n //Here for odd positions, we compare characters and\n //if match then increment LPS Length by ONE\n //If even position, we just increment LPS by ONE without\n //any character comparison\n while ( ((i + L[i]) < N && (i - L[i]) > 0) &&\n ( ((i + L[i] + 1) % 2 == 0) ||\n (text[(i + L[i] + 1)/2] == text[(i - L[i] - 1)/2] )))\n {\n L[i]++;\n }\n \n if(L[i] > maxLPSLength) // Track maxLPSLength\n {\n maxLPSLength = L[i];\n maxLPSCenterPosition = i;\n }\n \n //If palindrome centered at currentRightPosition i\n //expand beyond centerRightPosition R,\n //adjust centerPosition C based on expanded palindrome.\n if (i + L[i] > R)\n {\n C = i;\n R = i + L[i];\n }\n }\n start = (maxLPSCenterPosition - maxLPSLength)/2;\n end = start + maxLPSLength - 1;\n s = start;\n return end - start + 1;\n}\n\nResult getLP(std::vector<std::string>& s) {\n Result r{0,0,0};\n int i = 0;\n for (const std::string& str : s) {\n ++i;\n if (str.find_first_not_of(\" \") == std::string::npos) continue;\n int start = 0;\n int result = findLongest(str, start);\n Result q{i, result, start};\n r = r < q ? q : r;\n }\n return r;\n}\n\nvoid strip(std::ifstream& file, Lines &result)\n{\n std::string workString;\n int i = 0;\n while(std::getline(file,workString))\n {\n //Strip non alpha characters\n workString.erase(std::remove_if(workString.begin(), workString.end(),\n [] (char c) { return !std::isalpha(c); }\n ), workString.end());\n\tmemset(result[i], '\\0', 16);\n\tmemcpy(result[i++], workString.c_str(), workString.length());\n workString.clear();\n }\n}\n\nvoid getAndPostNeighbor(int* r, int size, int last, int i, int next, int *to_return) {\n int last_data[size];\n MPI_Status stat;\n \n MPI_Recv(last_data, size, MPI_INT, last, 0, MPI_COMM_WORLD, &stat);\n last_data[i * 3] = r[0];\n last_data[(i * 3) + 1] = r[1];\n last_data[(i * 3) + 2] = r[2];\n if (i > 0)\n MPI_Send(last_data, size, MPI_INT, next, 0, MPI_COMM_WORLD); \n}\n\nvoid MyCustomGather(int* sendbuf, int sendcount, int* recvbuf, int recvcount, int root, MPI_Comm comm) {\n int processId;\n int numberOfProcesses;\n MPI_Comm_rank( MPI_COMM_WORLD, &processId);\n MPI_Comm_size( MPI_COMM_WORLD, &numberOfProcesses);\n int next = processId == (numberOfProcesses - 1) ? 0 : processId + 1;\n int last = processId == 0 ? numberOfProcesses - 1 : processId - 1;\n if (processId == 0) {\n int data[3 * numberOfProcesses];\n data[0] = sendbuf[0];\n data[1] = sendbuf[1];\n data[2] = sendbuf[2];\n MPI_Send(data, 3 * numberOfProcesses, MPI_INT, next, 0, MPI_COMM_WORLD);\n to_return = new int[3 * numberOfProcesses];\n }\n getAndPostNeighbor(data, 3 * numberOfProcesses, last, processId, next, to_return);\n if (processId == root) {\n memcpy(to_return, last_data, sizeof(int) * size);\n }\n}\n\nint main(int argc, char* argv[])\n{\n int processId;\n int numberOfProcesses;\n int *to_return = NULL;\n clock_t t;\n\n // Setup MPI\n MPI_Init( &argc, &argv );\n MPI_Comm_rank( MPI_COMM_WORLD, &processId);\n MPI_Comm_size( MPI_COMM_WORLD, &numberOfProcesses);\n\n // Two arguments, the program name and the input file. The second should be the input file\n if(argc != 2)\n {\n if(processId == 0)\n {\n std::cout << \"ERROR: Incorrect number of arguments. Format is: <filename>\" << std::endl;\n }\n MPI_Finalize();\n return 0;\n }\n\n // ....... Your SPMD program goes here ............\n Lines lines;\n if (processId == 0) {\n std::ifstream i(argv[1]);\n strip(i, std::ref(lines));\n }\n char buf[(ARRAY_SIZE / numberOfProcesses) * 16];\n // send contiguious memory out to the processes.\n t = clock();\n if (MPI_Scatter(lines, (ARRAY_SIZE / numberOfProcesses) * 16, MPI_CHAR,\n\t&buf, (ARRAY_SIZE / numberOfProcesses) * 16, MPI_CHAR, 0, MPI_COMM_WORLD) != MPI_SUCCESS) {\n\tperror(\"MPI_Scatter failed\");\n\texit(1);\n }\n std::vector<std::string> data;\n for (int i = 0; i < (ARRAY_SIZE / numberOfProcesses) * 16; i += 16) {\n char s[16];\n memcpy(s, &buf[i], 16);\n std::string s2(s);\n data.push_back(s2);\n }\n Result r = getLP(data);\n r.lineNumber = ((ARRAY_SIZE / numberOfProcesses) * processId) + r.lineNumber;\n int next = processId == (numberOfProcesses - 1) ? 0 : processId + 1;\n int last = processId == 0 ? numberOfProcesses - 1 : processId - 1;\n if (processId == 0) {\n int data[3 * numberOfProcesses];\n data[0] = r.lineNumber;\n data[1] = r.firstChar;\n data[2] = r.length;\n MPI_Send(data, 3 * numberOfProcesses, MPI_INT, next, 0, MPI_COMM_WORLD);\n to_return = new int[3 * numberOfProcesses];\n }\n getAndPostNeighbor(r, 3 * numberOfProcesses, last, processId, next, to_return);\n // ... Eventually.. \n if(processId == 0)\n {\n Result r {to_return[0], to_return[1], to_return[2]};\n for (int i = 3; i < 3 * numberOfProcesses; i += 3) {\n Result r2 {to_return[i], to_return[i + 1], to_return[i + 2]};\n r = r < r2 ? r2 : r;\n }\n DoOutput(r);\n t = clock() - t;\n std::cout << \"time: \" << ((float)t) / CLOCKS_PER_SEC << std::endl;\n }\n\n MPI_Finalize();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.609876811504364, "alphanum_fraction": 0.6112456321716309, "avg_line_length": 31.24787712097168, "blob_id": "955c14d0be3ed57c35b97eb3387430a39c978ed5", "content_id": "419a0f4770165f3e7ef6b2508b12bd9b71b1ab60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18994, "license_type": "no_license", "max_line_length": 142, "num_lines": 589, "path": "/ics46/ProjectTwo/src/linked_queue.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "//// Ian Schweer (Unique ID: 660942)\n//// Shaun McThomas (Unique ID: 307523)\n//// We certify that we worked cooperatively on this programming\n//// assignment, according to the rules for pair programming:\n//// primarily that both partners worked on all parts together.\n//\n//#ifndef LINKED_QUEUE_HPP_\n//#define LINKED_QUEUE_HPP_\n//\n//#include <string>\n//#include <iostream>\n//#include <sstream>\n//#include <initializer_list>\n//#include \"ics_exceptions.hpp\"\n//#include \"iterator.hpp\"\n//#include \"queue.hpp\"\n//\n//\n//namespace ics {\n//\n//template<class T> class LinkedQueue : public Queue<T> {\n// public:\n// LinkedQueue();\n// LinkedQueue(const LinkedQueue<T>& to_copy);\n// LinkedQueue(std::initializer_list<T> il);\n// LinkedQueue(ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n// virtual ~LinkedQueue();\n//\n// virtual bool empty () const;\n// virtual int size () const;\n// virtual T& peek () const;\n// virtual std::string str () const;\n//\n// virtual int enqueue (const T& element);\n// virtual T dequeue ();\n// virtual void clear ();\n//\n// virtual int enqueue (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n//\n// virtual LinkedQueue<T>& operator = (const LinkedQueue<T>& rhs);\n// virtual bool operator == (const Queue<T>& rhs) const;\n// virtual bool operator != (const Queue<T>& rhs) const;\n//\n// template<class T2>\n// friend std::ostream& operator << (std::ostream& outs, const LinkedQueue<T2>& s);\n//\n// private:\n// class LN;\n//\n// public:\n// class Iterator : public ics::Iterator<T> {\n// public:\n// //KLUDGE should be callable only in begin/end\n// Iterator(LinkedQueue<T>* fof, LN* initial);\n// virtual ~Iterator();\n// virtual T erase();\n// virtual std::string str () const;\n// virtual const ics::Iterator<T>& operator ++ ();\n// virtual const ics::Iterator<T>& operator ++ (int);\n// virtual bool operator == (const ics::Iterator<T>& rhs) const;\n// virtual bool operator != (const ics::Iterator<T>& rhs) const;\n// virtual T& operator * () const;\n// virtual T* operator -> () const;\n// private:\n// LN* prev = nullptr; //if nullptr, current at front of list\n// LN* current; //if can_erase is false, this value is unusable\n// LinkedQueue<T>* ref_queue;\n// int expected_mod_count;\n// bool can_erase = true;\n// };\n//\n// //For explicit use: Iterator<...>& it = c.ibegin(); ... or for (Iterator<...>& it = c.ibegin(); it != c.iend(); ++it)...\n// virtual ics::Iterator<T>& ibegin () const;\n// virtual ics::Iterator<T>& iend () const;\n//\n// //For implicit use: for (... i : c)...\n// virtual Iterator begin () const;\n// virtual Iterator end () const;\n//\n// private:\n// class LN {\n// public:\n// LN () {}\n// LN (const LN& ln) : value(ln.value), next(ln.next){}\n// LN (T v, LN* n = nullptr) : value(v), next(n){}\n//\n// T value;\n// LN* next = nullptr;\n// };\n//\n// int used = 0;\n// LN* front = nullptr;\n// LN* rear = nullptr;\n// int mod_count = 0; //For sensing of concurrent modification\n// void delete_list(LN*& front); //Recycle storage, set front's argument to nullptr;\n//};\n//\n//\n//\n////See code in array_queue.hpp\n//\n////Write the constructors, methods, and operators here for LinkedQueue\n//\n///**\n// * Default constuctor. Not much to do here\n// */\n//template <class T>\n//LinkedQueue<T>::LinkedQueue() {\n//}\n//\n///**\n// * Copy constuctor. Given a linked queue, enqueue all the elements\n// * in the argument queue to make the current queue equal. See equals\n// * for definition of equality\n// *\n// * @param const LinkedQueue<T>& to_copy\n// * The queue to copy\n// */\n//template <class T>\n//LinkedQueue<T>::LinkedQueue(const LinkedQueue<T>& to_copy) {\n// enqueue(to_copy.ibegin(), to_copy.iend());\n//}\n//\n///**\n// * Constuctor w/ std::initializer_list. Given a initial list of \n// * elements, enqueue each to construct our queue. All elements are\n// * added in order and processed in order.\n// *\n// * @param std::initialize_list<T> il\n// * The initial values of the queue\n// */\n//template <class T>\n//LinkedQueue<T>::LinkedQueue(std::initializer_list<T> il) {\n// for (T each : il) enqueue(each);\n//}\n//\n///**\n// * Constuctor w/ iterators. Given two ics iterators, enqueue all\n// * elements between the iterators. We assume both iterators point\n// * to the same list of values.\n// *\n// * @param ics::Iterator<T>& start\n// * The starting iterator\n// * @param const ics::Iterator<T>& end\n// * The ending iterator\n// */\n//template <class T>\n//LinkedQueue<T>::LinkedQueue(ics::Iterator<T>& start, const ics::Iterator<T>& end) {\n// enqueue(start, end);\n//}\n//\n///**\n// * Deconstructor\n// */\n//template <class T>\n//LinkedQueue<T>::~LinkedQueue() { \n// delete_list(front); \n//}\n//\n///**\n// * Empty. Function will determine if the queue is empty.\n// * Note: An alternative way to do this would be to say front==nullptr\n// * however, that then requires the code further down to enforce that \n// * requirement, where as used is a highly used integer. This is easier.\n// */\n//template <class T>\n//bool LinkedQueue<T>::empty() const {\n// return used == 0;\n//}\n//\n///**\n// * Size. Function will return the size of the queue. \n// */\n//template <class T>\n//int LinkedQueue<T>::size() const {\n// return used;\n//}\n//\n///**\n// * Peek. Function will return the first value in the queue\n// * WITHOUT dequeueing the value. Useful for consumer code.\n// */\n//template <class T>\n//T& LinkedQueue<T>::peek() const {\n// if (empty()) throw EmptyError(\"LinkedQueue::peek the queue is empty\");\n// return front->value;\n//}\n//\n///**\n// * Str. A debugging print method.\n// */\n//template <class T>\n//std::string LinkedQueue<T>::str() const {\n// std::ostringstream str_stream;\n// if (front == nullptr)\n// str_stream << \"queue[]\";\n// else {\n// str_stream << \"queue[\";\n// LN *node = front;\n// while (node != nullptr) {\n// str_stream << node->value;\n// if (node != rear) str_stream<< \",\";\n// else str_stream << \"]\";\n// node = node->next;\n// }\n// }\n// str_stream << \"(used=\" << used << \", mod_count=\" << mod_count;\n// if (front != nullptr) str_stream << \", front=\" << front->value;\n// if (rear != nullptr) str_stream << \", rear=\" << rear->value;\n// str_stream << \")\";\n// return str_stream.str();\n//}\n//\n///**\n// * Enqueue. Function will add an element to the rear of the list.\n// * This function can have large mutations on the queue, since the\n// * two interesting spots in a queue are the front and rear. If the\n// * queue is empty, we initialize the queue, if not we grow it.\n// *\n// * @return int\n// * 1, a guarentee that we will insert.\n// */\n//template <class T>\n//int LinkedQueue<T>::enqueue (const T& element) {\n// // is our queue empty?\n// if (front == nullptr) {\n// front = rear = new LN(element);\n// } else {\n// // simply increase our rear\n// rear = rear->next = new LN(element);\n// }\n//\n// // house keeping and return\n// mod_count++;\n// used++;\n// return 1;\n//}\n//\n///**\n// * Enqueue w/ iterators. Function will enqueue multiple items given\n// * a start and end iterators. Function will consume the result of the \n// * simplier enqueue method (see Enqueue).\n// *\n// * @param ics::Iterator<T>& start\n// * The starting iterator\n// * @param const ics::Iterator<T>& stop\n// * The ending iterator\n// *\n// * @return int\n// * The number of insertions to the queue.\n// */\n//template <class T>\n//int LinkedQueue<T>::enqueue (ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n// int insert = 0;\n// // for each value, call the enqueue.\n// while (start != stop) {\n// insert += enqueue(*start);\n// ++start;\n// }\n// return insert;\n//}\n//\n///**\n// * Dequeue. Function will \"pop\" the top element of the queue for processing.\n// * The function will also move the front pointer through the list, checking \n// * boundaries as it goes. It will return the dequeue value and manage deletion.\n// *\n// * @return T\n// * The value to process in the queue\n// *\n// * @throw EmptyError \n// * If we are out of bounds, we will error\n// */\n//template <class T>\n//T LinkedQueue<T>::dequeue() {\n// // bounds check\n// if (empty())\n// throw EmptyError(\"Linked Queue is empty\");\n//\n// // Get current head.\n// LN *val = front;\n//\n// // increment head.\n// if (front->next == nullptr) {\n// front = rear = nullptr;\n// } else {\n// front = front->next;\n// }\n//\n// // get the return value;\n// T return_value = val->value;\n//\n// // delete the un-needed node;\n// delete val;\n//\n// // house keeping and return\n// mod_count++;\n// used--;\n// return return_value;\n//}\n//\n///**\n// * Clear. Function will clear the entire queue. See delete_list for\n// * details\n// */\n//template <class T>\n//void LinkedQueue<T>::clear() {\n// delete_list(front);\n// rear = nullptr;\n//}\n//\n///**\n// * delete_list. Given a starting node position, function will\n// * delete a node and all subsequent nodes. Given the structure\n// * of the code, this function can also delete pieces of a linked list,\n// * say for example half\n// */\n//template <class T>\n//void LinkedQueue<T>::delete_list(LN *&node) {\n// LN *to_delete = node;\n// for ( ;node != nullptr; used--, mod_count++) \n// { \n// node = node->next; \n// delete to_delete;\n// to_delete = node;\n// }\n//}\n//\n///**\n// * Assignment. Function will become equal to a argument queue.\n// * See equality operator for precise definition. In the event\n// * that the queue has already been used previously, the queue\n// * will be cleared.\n// */\n//template <class T>\n//LinkedQueue<T>& LinkedQueue<T>::operator = (const LinkedQueue<T>& rhs) {\n// if (!empty()) clear();\n// enqueue(rhs.ibegin(), rhs.iend());\n// return *this;\n//}\n//\n///**\n// * Equality. Function will determine if two queues are equal. Two\n// * queues are equal if and only if the sizes are equal, and if the\n// * two queues are in the SAME order.\n// *\n// * @param const Queue<T>&\n// * The argument queue. Notice the type is not a linked queue, that\n// * is becase we use iterators to check element and order equality.\n// * This allows for cross compabilities between data structures\n// * as long as they are the same data type.\n// */\n//template <class T>\n//bool LinkedQueue<T>::operator == (const Queue<T>& rhs) const {\n// if (this == &rhs) return true;\n// if (size() != rhs.size()) return false;\n// \n// for (auto &lhs_iter = ibegin(), &rhs_iter = rhs.ibegin();lhs_iter != iend() ;lhs_iter++, rhs_iter++) \n// if (*lhs_iter != *rhs_iter) return false;\n// return true;\n//}\n//\n///**\n// * Non-Equality. Function will determine if two queues are NOT equal. See\n// * equality for definition.\n// *\n// * @param const Queue<T>&\n// * The argument queue. Notice the type is not a linked queue, that\n// * is becase we use iterators to check element and order equality.\n// * This allows for cross compabilities between data structures\n// * as long as they are the same data type.\n// */\n//template <class T>\n//bool LinkedQueue<T>::operator != (const Queue<T>& rhs) const {\n// return !((*this) == rhs);\n//}\n//\n///**\n// * Out stream. Function will print out the queue.\n// */\n//template<class T2>\n//std::ostream& operator << (std::ostream& outs, const LinkedQueue<T2>& s) {\n// outs << \"queue[\";\n// int i = 0;\n// for (auto & iter = s.ibegin(); i < s.used; iter++, i++) {\n// (i < s.size() - 1) ? outs << *iter << \",\" : outs << *iter;\n// }\n// outs << \"]:rear\";\n// return outs;\n//}\n//\n////Fill in the missing parts of the erase method and ++ operators\n//// for LinkedQueue's Iterator\n//\n//\n//\n////KLUDGE: memory-leak\n//template<class T>\n//auto LinkedQueue<T>::ibegin () const -> ics::Iterator<T>& {\n// return *(new Iterator(const_cast<LinkedQueue<T>*>(this),front));\n//}\n//\n////KLUDGE: memory-leak\n//template<class T>\n//auto LinkedQueue<T>::iend () const -> ics::Iterator<T>& {\n// return *(new Iterator(const_cast<LinkedQueue<T>*>(this),nullptr));\n//}\n//\n//template<class T>\n//auto LinkedQueue<T>::begin () const -> LinkedQueue<T>::Iterator {\n// return Iterator(const_cast<LinkedQueue<T>*>(this),front);\n//}\n//\n//template<class T>\n//auto LinkedQueue<T>::end () const -> LinkedQueue<T>::Iterator {\n// return Iterator(const_cast<LinkedQueue<T>*>(this),nullptr);\n//}\n//\n//\n//\n//template<class T>\n//LinkedQueue<T>::Iterator::Iterator(LinkedQueue<T>* fof, LN* initial) : current(initial), ref_queue(fof) {\n// expected_mod_count = ref_queue->mod_count;\n//}\n//\n//template<class T>\n//LinkedQueue<T>::Iterator::~Iterator() {}\n//\n///**\n// * Erase. Function will erase the current iterator position. After an\n// * erase call, we will return the value of deleted node. Erase will mutate\n// * the under-line reference queue. \n// *\n// * @throw ConcurrentModificationError given conflicting modification counts\n// * CannotEraseError given either false permission or the current position is out of bounds\n// */\n//template<class T>\n//T LinkedQueue<T>::Iterator::erase() {\n// if (expected_mod_count != ref_queue->mod_count)\n// throw ConcurrentModificationError(\"LinkedQueue::Iterator::erase\");\n// if (!can_erase)\n// throw CannotEraseError(\"LinkedQueue::Iterator::erase Iterator cursor already erased\");\n// if (current == nullptr)\n// throw CannotEraseError(\"LinkedQueue::Iterator::erase Iterator cursor beyond data structure\");\n//\n// T val = current->value;\n// LN *to_delete = current;\n// if (current == ref_queue->front) \n// ref_queue->front = ref_queue->front->next;\n// else\n// prev->next = current->next;\n// current = current->next;\n// delete to_delete;\n// can_erase = false;\n// expected_mod_count = ref_queue->mod_count;\n// ref_queue->used--;\n// return val;\n//}\n//\n///**\n// * str. Just a debug string function.\n// */\n//template<class T>\n//std::string LinkedQueue<T>::Iterator::str() const {\n// std::ostringstream answer;\n// answer << ref_queue->str() << \"(current=\" << current << \",expected_mod_count=\" << expected_mod_count << \",can_erase=\" << can_erase << \")\";\n// return answer.str();\n//}\n//\n///**\n// * Pre-fix increment. Function will increment the current position of the\n// * the iterator given valid erase permissons. Prefix will return the newly \n// * update current position of the iterator.\n// *\n// * @throw ConcurrentModificationError given conflicting modification counts\n// */\n//template<class T>\n//const ics::Iterator<T>& LinkedQueue<T>::Iterator::operator ++ () {\n// if (expected_mod_count != ref_queue->mod_count)\n// throw ConcurrentModificationError(\"LinkedQueue::Iterator::operator ++\");\n//\n// if (!can_erase) can_erase = true;\n// else {\n// if (current != nullptr) {\n// prev = current;\n// current = current->next;\n// }\n// } \n// return *this;\n//}\n//\n////KLUDGE: can create garbage! (can return local value!)\n//\n///**\n// * Post-fix increment. Function will increment the current position of the\n// * the iterator given valid erase permissons. Post-fix will return the previous \n// * position of the iterator.\n// *\n// * @throw ConcurrentModificationError given conflicting modification counts\n// */\n//template<class T>\n//const ics::Iterator<T>& LinkedQueue<T>::Iterator::operator ++ (int) {\n// if (expected_mod_count != ref_queue->mod_count)\n// throw ConcurrentModificationError(\"LinkedQueue::Iterator::operator ++(int)\");\n// \n// if (current == nullptr) return *this;\n// if (!can_erase) can_erase = true;\n// else {\n// prev = current;\n// current = current->next;\n// }\n// return *(new Iterator(ref_queue, prev));\n//}\n//\n///**\n// * Iterator Equality. Function will determine if two iterators are equal.\n// * Two iterators are equal if they both point to the same spot in the data\n// * structure.\n// *\n// * @throw ConcurrentModificationError given conflicting modification counts\n// * IteratorTypeError given the right hand sider iterator is null\n// * ComparingDifferentIteratorsError given the two reference queues don't\n// * match\n// */\n//template<class T>\n//bool LinkedQueue<T>::Iterator::operator == (const ics::Iterator<T>& rhs) const {\n// const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n// if (rhsASI == 0)\n// throw IteratorTypeError(\"LinkedQueue::Iterator::operator ==\");\n// if (expected_mod_count != ref_queue->mod_count)\n// throw ConcurrentModificationError(\"LinkedQueue::Iterator::operator ==\");\n// if (ref_queue != rhsASI->ref_queue)\n// throw ComparingDifferentIteratorsError(\"LinkedQueue::Iterator::operator ==\");\n// return current == rhsASI->current;\n//}\n//\n///**\n// * Iterator Non-Equality. Function will determine if two iterators are NOT equal.\n// * See equality for definition.\n// *\n// * @throw ConcurrentModificationError given conflicting modification counts\n// * IteratorTypeError given the right hand sider iterator is null\n// * ComparingDifferentIteratorsError given the two reference queues don't\n// * match\n// */\n//template<class T>\n//bool LinkedQueue<T>::Iterator::operator != (const ics::Iterator<T>& rhs) const {\n// const Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n// if (rhsASI == 0)\n// throw IteratorTypeError(\"LinkedQueue::Iterator::operator !=\");\n// if (expected_mod_count != ref_queue->mod_count)\n// throw ConcurrentModificationError(\"LinkedQueue::Iterator::operator !=\");\n// if (ref_queue != rhsASI->ref_queue)\n// throw ComparingDifferentIteratorsError(\"LinkedQueue::Iterator::operator !=\");\n// return current != rhsASI->current;\n//}\n//\n//template<class T>\n//T& LinkedQueue<T>::Iterator::operator *() const {\n// if (expected_mod_count != ref_queue->mod_count)\n// throw ConcurrentModificationError(\"LinkedQueue::Iterator::operator *\");\n// if (!can_erase || current == nullptr) {\n// std::ostringstream where;\n// where << current\n// << \" when front = \" << ref_queue->front << \" and \"\n// << \" and rear = \" << ref_queue->rear;\n// throw IteratorPositionIllegal(\"LinkedQueue::Iterator::operator * Iterator illegal: \"+where.str());\n// }\n// return current->value;\n//}\n//\n//template<class T>\n//T* LinkedQueue<T>::Iterator::operator ->() const {\n// if (expected_mod_count != ref_queue->mod_count)\n// throw ConcurrentModificationError(\"LinkedQueue::Iterator::operator *\");\n// if (!can_erase || current == nullptr) {\n// std::ostringstream where;\n// where << current\n// << \" when front = \" << ref_queue->front << \" and \"\n// << \" and rear = \" << ref_queue->rear;\n// throw IteratorPositionIllegal(\"LinkedQueue::Iterator::operator * Iterator illegal: \"+where.str());\n// }\n//\n// return &(current->value);\n//}\n//\n//}\n//\n//#endif\n" }, { "alpha_fraction": 0.6611570119857788, "alphanum_fraction": 0.6611570119857788, "avg_line_length": 19.16666603088379, "blob_id": "357863a00ec9780ded42fa2faf8ee834c24a86fe", "content_id": "94bbdf64db97ce83b3255efec67a3d70c1ba0bf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 605, "license_type": "no_license", "max_line_length": 70, "num_lines": 30, "path": "/cs141/project1/src/jump.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"grammer.hpp\"\n#include \"statements.hpp\"\n#include \"jump.hpp\"\n#include \"writer.hpp\"\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nJump::Jump(string line) : Statement(line) {\n\t_mvKeywords = new vector<string>();\n}\n\nvector<string>* Jump::getKeywords() {\n\treturn _mvKeywords;\n}\n\nGrammar* Jump::parse() {\n\tif (_msLine.find(\",\") != string::npos) return NULL; // no comma args.\n\t_msLine = parseCommand(_msLine, \"jump \", \"JUMP \");\n\tcout << \"Jump\" << endl;\n\tif (isExpr(_msLine)) { \n\t\treturn this;\n\t}\n\telse return NULL;\t\n}\n" }, { "alpha_fraction": 0.6170112490653992, "alphanum_fraction": 0.6564849615097046, "avg_line_length": 34.46666717529297, "blob_id": "b26b16fcb5c599c3ce75391fd9a71a7ee1dce080", "content_id": "73b95cae2d7e5029df394fa7b8956ff150ec3962", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2128, "license_type": "no_license", "max_line_length": 128, "num_lines": 60, "path": "/French/htmlParser.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.7\nfrom bs4 import BeautifulSoup as Soup\nimport calendar\nclass HTMLCalendarAdder:\n def __init__(self, html):\n self.soup = Soup(html, \"html.parser\")\n self.classname = \"assignment\"\n self.tagname = \"li\"\n self.datemap = {v: k for k, v in enumerate(calendar.month_abbr)}\n\n def __format(self, date, title, uid):\n print \"BEGIN:VEVENT\"\n print \"DTSTART:2016\"+str(date)+\"T090000\"\n print \"DTSTAMP:20161002T170411\"\n print \"UID:\" + str(uid)\n print \"SUMMARY:CANVAS \"+title\n print \"END:VEVENT\"\n\n def generate(self):\n assignments = self.soup.find_all(self.tagname, {\"class\":self.classname})\n for assignment in assignments:\n uid=assignment.find(\"div\").get(\"id\").replace(\"_\", \"\")\n info=assignment.find(\"div\", {\"class\": \"ig-info\"})\n duedate=info.find(\"span\").contents[0]\n duedate=str(duedate).strip().split(\" \")\n month=str(self.datemap[duedate[0]])\n day=str(duedate[1])\n if len(day) == 1:\n day = \"0\" + day\n title=info.find(\"a\").contents[0].strip()\n title = ''.join(e for e in title if e.isalnum())\n self.__format(month + day, title, uid)\n\nprint \"BEGIN:VCALENDAR\"\nprint \"PRODID:-//Office of Information and Technology, University of California in Irvine//NONSGML Calendar Course Download//EN\"\nprint \"VERSION:2.0\"\nprint \"METHOD:PUBLISH\"\nprint \"CALSCALE:GREGORIAN\"\nprint \"X-WR-TIMEZONE:America/Los_Angeles\"\nprint \"BEGIN:VTIMEZONE\"\nprint \"TZID:America/Los_Angeles\"\nprint \"X-LIC-LOCATION:America/Los_Angeles\"\nprint \"BEGIN:DAYLIGHT\"\nprint \"TZOFFSETFROM:-0800\"\nprint \"TZOFFSETTO:-0700\"\nprint \"TZNAME:PDT\"\nprint \"DTSTART:19700308T020000\"\nprint \"RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\"\nprint \"END:DAYLIGHT\"\nprint \"BEGIN:STANDARD\"\nprint \"TZOFFSETFROM:-0700\"\nprint \"TZOFFSETTO:-0800\"\nprint \"TZNAME:PST\"\nprint \"DTSTART:19701101T020000\"\nprint \"RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\"\nprint \"END:STANDARD\"\nprint \"END:VTIMEZONE\"\nparser=HTMLCalendarAdder(open(\"assignments.html\").read())\nparser.generate()\nprint \"END:VCALENDAR\"\n" }, { "alpha_fraction": 0.6189024448394775, "alphanum_fraction": 0.6356707215309143, "avg_line_length": 18.294116973876953, "blob_id": "595b578803f1cfb267d331597d153449dbab256d", "content_id": "d9a055842171cdeac2bd42e877f565571c912e65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 656, "license_type": "no_license", "max_line_length": 108, "num_lines": 34, "path": "/cs146/hw3/unrm", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Ian Schweer\n# 22514022\n\nif [ $# -lt 1 ]; then\n\techo \"Not enough args. Please enter a filename\"\n\texit -1\nfi\n\n# does .Trash exist?\ntrash=$TRASH\nif [[ \"$trash\" == \"\" ]]; then\n\techo \"The trash variable is not currently set. Consider setting an enviornment variable. Assuming ~/.Trash\"\n\ttrash=\"$HOME/.Trash\"\nfi\n\nif [ ! -e $trash ]; then\n\tmkdir $trash\nfi\n\nfor file in \"$@\"\ndo\n\tthefilename=$(basename \"$file\")\n\ttrashpath=\"$trash/$thefilename\"\n\tif [ -f \"$trashpath\" ]; then\n\t\t# the file exists, and can be moved to here.\n\t\tmv \"$trashpath\" \".\"\n\telif [ -d \"$trashpath\" ]; then\n\t\tmv \"$trashpath\" \".\"\n\telse\n\t\techo \"File has not been srm'd\"\n\t\texit -2\n\tfi\ndone\n" }, { "alpha_fraction": 0.555112898349762, "alphanum_fraction": 0.5869854092597961, "avg_line_length": 19.91666603088379, "blob_id": "6e5b6e3a6b9ef3e1fdd9b841ee26c5eb703a7e73", "content_id": "2aab6d7deed4d80efbc79348400d4d70690fe843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 753, "license_type": "no_license", "max_line_length": 64, "num_lines": 36, "path": "/cs143A/project1/compute/compute.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\nfloat getAverage(int data[], int datasize, int *max, int *min) {\n\tssize_t readLines = 0;\n\tsize_t len = 0;\n\tint count = 0;\n\tdouble avg = 0;\n\tchar *line;\n\n\t// initialize values, and run algorithm\n\t*max = -1;\n\t*min = 99999;\n\tint i;\n\tfor (i = 0; i < datasize; i++) {\n\t\tint value = data[i];\n\t\t*max = *max < value ? value : *max;\n\t\t*min = *min > value ? value : *min;\n\t\tavg += value;\n\t}\n\treturn avg / datasize;\t\n}\n\nint main() {\n\t// read filename from stdin\n\tchar name[100];\n\tint data[100];\n\tint i = 0, max, min;\n\tdouble avg;\n\twhile (fgets(name, 100, stdin) != NULL) {\n\t\tdata[i++] = strtol(name, NULL, 10);\n\t}\n\tavg = getAverage(data, i, &max, &min);\n\tprintf(\"max: %i\\nmin: %i\\naverage: %f\", max, min, avg);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.4738160967826843, "alphanum_fraction": 0.49486345052719116, "avg_line_length": 23.484663009643555, "blob_id": "7828bff362b28f22e1e64f497278f30a2d38c3ad", "content_id": "9dbbde4c966a3d1cd7d2e7f06a20e33d882d7ded", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3991, "license_type": "no_license", "max_line_length": 89, "num_lines": 163, "path": "/cs143A/project3/src/myshell/my_shell.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer\n// 22514022\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/wait.h>\n#include <unistd.h>\n#include <string.h>\n\nvoid clearSpaces(char **word) {\n\twhile (*word[0] == ' ' && *word[0] != '\\n') *word+=1;\t\n}\nint clearSpacesC(char **word) {\n\tint c = 0;\n\twhile (*word[0] == ' ' && *word[0] != '\\n') *word+=1, c++;\n\treturn c;\t\n}\n\nvoid processCmd(char *rawData, int n, char *env[]) {\n\tif (n == 0 && rawData == NULL) {\n\t\texit(0);\n\t}\n\t// make sure we don't have spaces.\n\trawData[n] = 0;\n\tclearSpaces(&rawData);\n\t\t\n\t// data is good, do stuff with it.\n\tchar first[BUFSIZ], second[BUFSIZ], third[BUFSIZ], fourth[BUFSIZ]; // two args and flags\n\tint sanity = 0;\n\twhile (rawData[sanity] != ' ' && rawData[sanity] != '-' && sanity < n) { sanity++; };\n\trawData[sanity] = '\\0';\n\tstrcpy(first, rawData);\n\n\trawData += sanity+1;\n\tif (sanity == n) {\n\t\tchar *noargs[] = {first, NULL};\n\t\texecvpe(noargs[0], noargs, env);\n\t} else {\n\t\t// erase all spaces at the beginning.\n\t\tint remainder = n - sanity;\n\t\tclearSpaces(&rawData);\n\t\tif (rawData[0] == '-' || rawData[0] != ' ') {\n\t\t\t// handle the flag\n\t\t\tint pos = 0, i = 0;\n\t\t\twhile (rawData[i] != ' ' && i < remainder) {\n\t\t\t\tsecond[i] = rawData[i];\n\t\t\t\ti++;\n\t\t\t}\t\n\t\t\trawData += i+1;\n\t\t\tremainder -= i + 1;\n\t\t\tremainder -= clearSpacesC(&rawData);\n\t\t\tif (rawData[0] == '\\n' || rawData[0] == '\\0') {\n\t\t\t\tchar *args[] = {first, second, NULL};\n\t\t\t\texecvpe(args[0], args, env);\n\t\t\t\tprintf(\"Could not execute command: %s\\n\", args[0]);\n\t\t\t\texit(0);\t\n\t\t\t}\n\t\t\tif (rawData[0] != ' ') {\n\t\t\t\ti = 0;\n\t\t\t\tpos++;\n\t\t\t\twhile (rawData[i] != ' ' && i < remainder) {\n\t\t\t\t\tthird[i] = rawData[i];\n\t\t\t\t\ti++;\t\n\t\t\t\t}\n\t\t\t\trawData += i + 1;\n\t\t\t\tremainder -= i + 1;\n\t\t\t\tremainder -= clearSpacesC(&rawData);\n\t\t\t} // argument three\n\t\t\telse {\n\t\t\t\tchar *args[] = {first, second, NULL};\n\t\t\t\texecvpe(args[0], args, env);\n\t\t\t\tprintf(\"Could not execute command: %s\\n\", args[0]);\n\t\t\t\texit(0);\t\n\t\t\t}\n\n\t\t\tif (rawData[0] != ' ' && rawData[0] != '\\0') {\n\t\t\t\ti = 0;\n\t\t\t\tpos++;\n\t\t\t\twhile(rawData[i] != ' ' && i < remainder) {\n\t\t\t\t\tfourth[i] = rawData[i];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tchar *args[] = {first, second, third, fourth, NULL};\n\t\t\t\texecvpe(args[0], args, env);\n\t\t\t\tprintf(\"Could not execute command: %s\\n\", args[0]);\n\t\t\t\texit(0);\t\n\t\t\t} // argument four\n\t\t\telse {\n\t\t\t\tchar *args[] = {first, second, third, NULL};\n\t\t\t\texecvpe(args[0], args, env);\n\t\t\t\tprintf(\"Could not execute command: %s\\n\", args[0]);\n\t\t\t\texit(0);\t\n\t\t\t}\n\t\t}\n\t\telse if (rawData[0] != ' ') {\n\t\t\t\tint i = 0, pos = 0;\n\t\t\t\twhile (rawData[i] != ' ' && rawData[i] != '\\n') {\n\t\t\t\t\tthird[i] = rawData[i];\n\t\t\t\t\ti++;\t\n\t\t\t\t}\n\t\t\t\trawData += i + 1;\n\t\t\t\tclearSpaces(&rawData);\n\t\t\t\tif (rawData[0] != ' ') {\n\t\t\t\t\ti = 0;\n\t\t\t\t\tpos++;\n\t\t\t\t\twhile(rawData[i] != ' ' && rawData[i] != '\\n') {\n\t\t\t\t\t\tfourth[i] = rawData[i];\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tchar *args[] = {first, second, third, fourth, NULL};\n\t\t\t\t\texecvpe(args[0], args, env);\n\t\t\t\t\tprintf(\"Could not execute command: %s\\n\", args[0]);\n\t\t\t\t\texit(0);\t\n\t\t\t\t} else {\n\t\t\t\t\tchar *args[] = {first, second, third, NULL};\n\t\t\t\t\texecvpe(args[0], args, env);\n\t\t\t\t\tprintf(\"Could not execute command: %s\\n\", args[0]);\n\t\t\t\t\texit(0);\t\n\t\t\t\t}\n\t\t}\n\t\t/*int c = 0, i = 0, pos = 0;\n\t\tchar *args[BUFSIZ];\n\t\trawData[n - sanity + 1] = ' ';\n\t\ts[pos++] = first;\n\t\twhile (*(rawData + i) != '\\n') {{\n\t\t\tchar arg[BUFSIZ] = {'\\0'};\n\t\t\tint j = 0;\n\t\t\twhile (*(rawData + i) != ' ') { \n\t\t\t\t*(arg + j) = *(rawData + i); \n\t\t\t\tj++;\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t*(arg + j) = '\\0'; \n\t\t\tstrcpy(args[pos++], arg);\n\t\t\ti++;\n\t\t}}\n\t\tint a = 0;*/\n\t}\n}\n\nint main(int argc, char **argv, char *env[]) {\n\tchar c = 'a', cmd[BUFSIZ];\n\tmemset(cmd, '\\0', sizeof(cmd));\n\tint i = 0;\n\twhile (1) {\n\t\tprintf(\"$: \");\n\t\twhile (c != '\\n' && c != EOF) {\n\t\t\tc = getchar();\n\t\t\tif (c == EOF) break;\n\t\t\tmemcpy(&cmd[i++], &c, sizeof(char));\n\t\t}\n\t\tif (cmd[0] != '\\0' && cmd[0] != '\\n') {\n\t\t\tpid_t id = fork();\n\t\t\tif (id == 0 && c != EOF)\n\t\t\t\tprocessCmd(&cmd[0], i - 1, env);\n\t\t\twaitpid(id, NULL, 0);\n\t\t}\n\t\tif (c == EOF)\n\t\t\texit(0);\n\t\tmemset(cmd, 0, sizeof(cmd));\n\t\ti = 0;\n\t\tc = 'a';\n\t}\n}\n" }, { "alpha_fraction": 0.5487661361694336, "alphanum_fraction": 0.5602819919586182, "avg_line_length": 21.16145896911621, "blob_id": "87337d246916180f10e0ab4895894d7226346ddb", "content_id": "5bdeea29a4651d5543c45652e122de344d49fd47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4255, "license_type": "no_license", "max_line_length": 69, "num_lines": 192, "path": "/ics53/lab2/shellex.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "/* $begin shellmain */\n#include \"csapp.h\"\n#define MAXARGS 128\n\ntypedef struct redirects{\n\tchar* in;\n\tchar* out;\n\tchar* err;\n} RedirectionPaths;\n\nRedirectionPaths init_r_paths(){\n\tRedirectionPaths rpath;\n\trpath.in = NULL;\n\trpath.out = NULL;\n\trpath.err = NULL;\n\treturn rpath;\n}\n\n/* function prototypes */\nvoid eval(char *cmdline);\nint parseline(char *buf, char **argv, RedirectionPaths*);\nint builtin_command(char **argv);\nint redirect_stream(int, char*);\n\nvoid bgreap_handle(int sig){\n\tint status;\n\tint id = wait(&status);\n\tprintf(\"child reaped\\nID: %d\\nstatus: %d\\n\",id,status);\n}\n\n\nint main() \n{\n char cmdline[MAXLINE]; /* Command line */\n\t\n Signal(SIGCHLD, bgreap_handle);\n\n while (1) {\n\t/* Read */\n\tprintf(\"> \"); \n\tFgets(cmdline, MAXLINE, stdin); \n\tif (feof(stdin))\n\t exit(0);\n\n\t/* Evaluate */\n\teval(cmdline);\n } \n}\n/* $end shellmain */\n \n/* $begin eval */\n/* eval - Evaluate a command line */\nvoid eval(char *cmdline) \n{\n char *argv[MAXARGS]; /* Argument list execve() */\n char buf[MAXLINE]; /* Holds modified command line */\n int bg; /* Should the job run in bg or fg? */\n pid_t pid; /* Process id */\n \n RedirectionPaths rpath = init_r_paths();\t\n\t\n strcpy(buf, cmdline);\n bg = parseline(buf, argv, &rpath); \n\t\n if(rpath.out != NULL)\n printf(\"stdout redirection: %s\\n\",rpath.out);\n\t\n if (argv[0] == NULL) \n\t\treturn; /* Ignore empty lines */\n\n if (!builtin_command(argv)) { \n\tif ((pid = Fork()) == 0) { /* Child runs user job */\n\t\tif(rpath.in != NULL)\n\t\t\tredirect_stream(0,rpath.in);\n\t\tif(rpath.out != NULL)\n\t\t\tredirect_stream(1,rpath.out);\n\t\tif(rpath.err != NULL)\n\t\t redirect_stream(2,rpath.err);\n\t if (execve(argv[0], argv, environ) < 0) {\n\t\t printf(\"%s: Command not found.\\n\", argv[0]);\n\t\t exit(0);\n\t }\n }\n\t}\n\n\t/* Parent waits for foreground job to terminate */\n\tif (!bg) {\n\t int status;\n\t if (waitpid(pid, &status, 0) < 0)\n\t\tunix_error(\"waitfg: waitpid error\");\n\t}\n\telse\n\t printf(\"%d %s\", pid, cmdline);\n \n return;\n}\n\n/* If first arg is a builtin command, run it and return true */\nint builtin_command(char **argv) \n{\n if (!strcmp(argv[0], \"quit\")) /* quit command */\n\t\texit(0); \n if (!strcmp(argv[0], \"&\")) /* Ignore singleton & */\n\t\treturn 1;\n return 0; /* Not a builtin command */\n}\n/* $end eval */\n\n/* $begin parseline */\n/* parseline - Parse the command line and build the argv array */\ntypedef enum {PT_ARG,PT_STDIN,PT_STDOUT,PT_STDERR} ParseMode;\nint parseline(char *buf, char **argv, RedirectionPaths *rpath) \n{\n char *delim; /* Points to first space delimiter */\n int argc; /* Number of args */\n int bg; /* Background job? */\n\t\n\tParseMode mode = PT_ARG;\n\t\n buf[strlen(buf)-1] = ' '; /* Replace trailing '\\n' with space */\n while (*buf && (*buf == ' ')) /* Ignore leading spaces */\n\t\tbuf++;\n\n /* Build the argv list */\n argc = 0;\n while ((delim = strchr(buf, ' '))) {\n\t\t*delim = '\\0';\n\t\t\n\t\tif(strcmp(buf,\"<\")==0){\n\t\t\tmode = PT_STDIN;\n\t\t}else if(strcmp(buf,\">\")==0){\n\t\t\tmode = PT_STDOUT;\n\t\t}else if(strcmp(buf,\"2>\")==0){\n\t\t\tmode = PT_STDERR;\n\t\t}else{\n\t\t\tswitch(mode){\n\t\t\tcase PT_ARG:\n\t\t\t\targv[argc++] = buf;\n\t\t\t\tbreak;\n\t\t\tcase PT_STDIN:\n\t\t\t\trpath->in = buf;\n\t\t\t\tbreak;\n\t\t\tcase PT_STDOUT:\n\t\t\t\trpath->out = buf;\n\t\t\t\tbreak;\n\t\t\tcase PT_STDERR:\n\t\t\t\trpath->err = buf;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmode = PT_ARG;\n\t\t}\n\t\t\n\t\tbuf = delim + 1;\n\t\twhile (*buf && (*buf == ' ')) /* Ignore spaces */\n\t\t\tbuf++;\n }\n argv[argc] = NULL;\n \n if (argc == 0) /* Ignore blank line */\n\treturn 1;\n\n /* Should the job run in the background? */\n if ((bg = (*argv[argc-1] == '&')) != 0)\n\targv[--argc] = NULL;\n\n return bg;\n}\n/* $end parseline */\n\nint redirect_stream(int stream, char* filename){\n\tint file;\n\tswitch(stream){\n\tcase 0:\n\t\tfile = open(filename,O_RDONLY);\n if (file <= 0) {\n printf(\"You done goofed. %s does not exist\\n\", filename);\n return -1;\n }\n\t\tbreak;\n\tcase 1:\n\t\tfile = open(filename,O_WRONLY|O_CREAT,0666);\n\t\tbreak;\n\tcase 2:\n\t\tfile = open(filename,O_WRONLY|O_CREAT,0666);\n\t\tbreak;\n\tdefault:\n\t\treturn -1;\n\t}\n\tdup2(file,stream);\n\tclose(file);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5280578136444092, "alphanum_fraction": 0.5400418639183044, "avg_line_length": 28.86931800842285, "blob_id": "a7df37f0dbcbcc379d9a82ac5fd99b0b51c8d847", "content_id": "241b7e2534f3c96f6d4c83feeb80847481d04dc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5257, "license_type": "no_license", "max_line_length": 131, "num_lines": 176, "path": "/cs131/project3/program.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <algorithm>\n#include <vector>\n#include <cstdlib>\n#include <cctype>\n#include <fstream>\n#include <iostream>\n#include <omp.h>\n#include <chrono>\n#include <thread>\n\n// Don't CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\n\nstruct Result\n{\n Result()\n : lineNumber(0), firstChar(0), length(0)\n {}\n\n Result(int lineNumber_, int firstChar_, int length_)\n : lineNumber(lineNumber_), firstChar(firstChar_), length(length_)\n {}\n\n // This allows you to compare results with the < (less then) operator, i.e. r1 < r2\n bool\n operator<(Result const& o)\n {\n // Line number can't be equal\n return length < o.length || \n (length == o.length && lineNumber > o.lineNumber) ||\n (length == o.length && lineNumber == o.lineNumber && firstChar > o.firstChar);\n }\n\n int lineNumber, firstChar, length;\n};\nconst int INPUT_SIZE=100000;\nstd::array<std::string, INPUT_SIZE>\nstrip(std::ifstream& file)\n{\n std::array<std::string, INPUT_SIZE> result;\n std::string workString;\n int i = 0; \n while(std::getline(file,workString))\n {\n //Strip non alpha characters\n workString.erase(std::remove_if(workString.begin(), workString.end(),\n [] (char c) { return !std::isalpha(c); }\n ), workString.end());\n result[i++] = workString;\n workString.clear();\n }\n return result;\n}\n\nvoid\nDoOutput(Result r)\n{\n std::cout << \"Result: \" << r.lineNumber << \" \" << r.firstChar << \" \" << r.length << std::endl;\n}\n\n// CHANGE This Code (you can add more functions)-----------------------------------------------------------------------------\nint findLongest(std::string text, int &s) {\n std::transform(text.begin(), text.end(), text.begin(), ::tolower);\n int N = (int)text.length();\n N = 2*N + 1; //Position count\n int L[N]; //LPS Length Array\n L[0] = 0;\n L[1] = 1;\n int C = 1; //centerPosition\n int R = 2; //centerRightPosition\n int i = 0; //currentRightPosition\n int iMirror; //currentLeftPosition\n int maxLPSLength = 0;\n int maxLPSCenterPosition = 0;\n int start = -1;\n int end = -1;\n int diff = -1;\n \n //Uncomment it to print LPS Length array\n //printf(\"%d %d \", L[0], L[1]);\n for (i = 2; i < N; i++)\n {\n //get currentLeftPosition iMirror for currentRightPosition i\n iMirror = 2*C-i;\n L[i] = 0;\n diff = R - i;\n //If currentRightPosition i is within centerRightPosition R\n if(diff > 0)\n L[i] = std::min(L[iMirror], diff);\n \n //Attempt to expand palindrome centered at currentRightPosition i\n //Here for odd positions, we compare characters and\n //if match then increment LPS Length by ONE\n //If even position, we just increment LPS by ONE without\n //any character comparison\n while ( ((i + L[i]) < N && (i - L[i]) > 0) &&\n ( ((i + L[i] + 1) % 2 == 0) ||\n (text[(i + L[i] + 1)/2] == text[(i - L[i] - 1)/2] )))\n {\n L[i]++;\n }\n \n if(L[i] > maxLPSLength) // Track maxLPSLength\n {\n maxLPSLength = L[i];\n maxLPSCenterPosition = i;\n }\n \n //If palindrome centered at currentRightPosition i\n //expand beyond centerRightPosition R,\n //adjust centerPosition C based on expanded palindrome.\n if (i + L[i] > R)\n {\n C = i;\n R = i + L[i];\n }\n }\n start = (maxLPSCenterPosition - maxLPSLength)/2;\n end = start + maxLPSLength - 1;\n s = start;\n return end - start + 1;\n}\n\nResult\nfindPalindrome(std::string s, int l)\n{\n Result r{0,0,0}; \n int start;\n int len = findLongest(s, start);\n r.lineNumber = l;\n r.firstChar = start;\n r.length = len;\n return r;\n}\n\nint\nmain(int argc, char* argv[])\n{\n if(argc != 3)\n {\n std::cout << \"ERROR: Incorrect number of arguments. Format is: <filename> <numThreads> \" << std::endl;\n return 0;\n }\n // ....... Your OpenMP program goes here ............\n // Probably some common code...\n std::chrono::time_point<std::chrono::system_clock> start, end;\n int th_id, nthreads, num=std::atoi(argv[2]);\n std::ifstream ifs(argv[1]); \n std::array<std::string, INPUT_SIZE> lines = strip(ifs);\n Result resultA(0,0,0);\n \n // Part A\n start = std::chrono::system_clock::now();\n #pragma omp parallel for schedule(static) private(th_id) shared(nthreads) shared(resultA) num_threads(num)\n for (int i = 0; i < INPUT_SIZE; i++) \n {\n Result r = findPalindrome(lines[i], i);\n resultA = resultA < r ? r : resultA;\n }\n\n // ... Eventually.. \n DoOutput(resultA);\n\n // Part B\n Result resultB(0,0,0);\n start = std::chrono::system_clock::now();\n #pragma omp parallel for schedule(dynamic, 1000) private(th_id) shared(nthreads) shared(resultB) num_threads(num)\n for (int i = 0; i < INPUT_SIZE; i++) \n {\n Result r = findPalindrome(lines[i], i);\n resultB = resultB < r ? r : resultB;\n }\n // ... Eventually.. \n DoOutput(resultB);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.688034176826477, "alphanum_fraction": 0.688034176826477, "avg_line_length": 19.39130401611328, "blob_id": "967b962f8a8cc7fbec0528ed891536a0a99116ed", "content_id": "5e45a80c9ebf0e2db73df94f0c869cef99e9e900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 468, "license_type": "no_license", "max_line_length": 40, "num_lines": 23, "path": "/cs143B/project3/tlb_adapter.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include \"tlb.h\"\n#include <string>\n#ifndef TLB_ADAPTER_H\n#define TLB_ADAPTER_H\nclass TlbFactory {\npublic:\n\tstatic Itlb *MakeAdapter(bool enabled);\nprivate:\n\tclass tlb_adapter : public Itlb {\n\tpublic:\n\t\ttlb_adapter(bool _enabled);\n\t\t~tlb_adapter();\n\t\tint get_frame_cache(int sp);\n\t\tvoid set_frame_cache(int sp, int f);\n\t\tbool has_frame_cache(int sp);\n\t\tstd::string get_miss_string();\n\t\tstd::string get_hit_string();\n\tprivate:\n\t\tbool enabled;\n\t\tItlb *_tlb;\n\t};\n};\n#endif" }, { "alpha_fraction": 0.7028985619544983, "alphanum_fraction": 0.7028985619544983, "avg_line_length": 15.235294342041016, "blob_id": "4257621f04f4888b6d3b18dbfb56838417399663", "content_id": "576f74b12dc74f5c007163e9d2e6186810d56651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 276, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/cs141/project1/src/writer.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef WRITER_H\n#define WRITER_H\n#include <string>\n#include <vector>\n#include <fstream>\nclass Writer \n{\npublic:\n\tWriter(std::string);\n\tvoid write(std::string);\n\tvoid flush();\n\t~Writer();\nprivate:\n\tstd::ofstream _mofsFile;\n\tstd::vector<std::string> _mvLinesToWrite;\n};\n#endif\n" }, { "alpha_fraction": 0.6415094137191772, "alphanum_fraction": 0.6433063745498657, "avg_line_length": 54.650001525878906, "blob_id": "be824180901a442ec442003dd9969e2bb2de659a", "content_id": "c6b1b9e6c7df00672f509ddc28f34cc46d6b5264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1113, "license_type": "no_license", "max_line_length": 182, "num_lines": 20, "path": "/French/letterprac.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "from subprocess import call\nfrom random import random as rand\nimport math\n\nnumbers=[\n [\"dix\", \"onze\", \"douze\", \"treize\", \"quatorze\", \"quinze\", \"seize\", \"dix-sept\", \"dix-huit\", \"dix-neuf\"],\n [\"vingt\", \"vingt et un\", \"vingt-deux\", \"vingt-trois\", \"vingt-quatre\", \"vingt-cinq\", \"vingt-six\", \"vingt-sept\", \"vingt-huit\", \"vingt-neuf\"],\n [\"trente\", \"trente et un\", \"trente-deux\", \"trente-trois\", \"trente-quartre\", \"trente-cinq\", \"trente-six\", \"trente-sept\", \"trente-huit\", \"trente-neuf\"],\n [\"quarante\", \"quarante et un\", \"quarante-deux\", \"quarante-trois\", \"quarante-quatre\", \"quarante-cinq\", \"quarante-six\", \"quarante-sept\", \"quarante-huit\", \"quarante-neuf\"],\n [\"cinquante\", \"cinquante et un\", \"cinquante-deux\", \"cinquante-trois\", \"cinquante-quatre\", \"cinquante-cinq\", \"cinquante-six\", \"cinquante-sept\", \"cinquante-huit\", \"cinquante-neuf\"]\n]\n\nwhile True:\n index=int(math.floor(rand() * len(numbers)))\n index2=int(math.floor(rand() * len(numbers[index])))\n ins=[\"say\", \"-v\", \"Amelie\", numbers[index][index2] + \" ans\"]\n call(ins)\n raw_input(\"answer\")\n print(ins)\n raw_input(\"continue\")\n" }, { "alpha_fraction": 0.6899999976158142, "alphanum_fraction": 0.6899999976158142, "avg_line_length": 24, "blob_id": "b8b357ed65f2706f1dd75917af7f45d6ab916a9c", "content_id": "ed98bcd50c055fbe10dac8dbe1badba71abb5f3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 100, "license_type": "no_license", "max_line_length": 62, "num_lines": 4, "path": "/cs146/hw2/howmany", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# very simple. Invoked via ./howmany. Implemented using whoson\necho `./whoson | wc -w`\n" }, { "alpha_fraction": 0.7032520174980164, "alphanum_fraction": 0.7032520174980164, "avg_line_length": 16.5, "blob_id": "d13a47f82e23821189724d98ec1ebf7ad0930da6", "content_id": "fd070bfa002818117399b2b4721e6102fb297e2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 246, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/cs141/project1/src/halt.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#ifndef HALT_H\n#define HALT_H\n#include <string>\n#include <vector>\n#include \"statements.hpp\"\n#include \"writer.hpp\"\nclass Halt : public Statement\n{\npublic:\n\tHalt(std::string);\n\tGrammar* parse();\n\tstd::vector<std::string>* getKeywords();\n};\n#endif\n\n" }, { "alpha_fraction": 0.300283282995224, "alphanum_fraction": 0.414542019367218, "avg_line_length": 26.153846740722656, "blob_id": "132baf66fee797e447434f4389932e838efff46a", "content_id": "c9ba43197cab18eee6376ffebc72fd4e6dbd65da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1059, "license_type": "no_license", "max_line_length": 205, "num_lines": 39, "path": "/cs178/hw1/three.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "P(Y) = 4/10\nP(!Y) = 6/10\n-------------------------\nP(X=know author|Y) = 3/4\nP(X=!know author|Y) = 1/4\nP(X=know author|!Y) = 3/6\nP(X=!know author|!Y) = 3/6\n-------------------------\nP(X=is long|Y) = 0/4\nP(X=!is long|Y) = 4/4\nP(X=is long|!Y) = 5/6\nP(X=!is long|!Y) = 1/6\n-------------------------\nP(X=has research|Y) = 3/4\nP(X=!has research|Y) = 1/4\nP(X=has research|!Y) = 4/6\nP(X=!has research|!Y) = 2/6\n-------------------------\nP(X=has grade|Y) = 2/4\nP(X=!has grade|Y) = 2/4\nP(X=has grade|!Y) = 5/6\nP(X=!has grade|!Y) = 1/6\n-------------------------\nP(X=has lotter|Y) = 1/4\nP(X=!has lotter|Y) = 3/4\nP(X=has lotter|!Y) = 2/6\nP(X=!has lotter|!Y) = 4/6\n\nb) max { .4 * .25 * .25 * .5 * .75,\n .6 * .5 * .167 * .33 * .167 * .667\n }\n (0 0 0 0 0) = +1\n (1 1 0 1 0) = -1\n\nc) P(+1|(1 1 0 1 0)) = P((1 1 0 1 0)|+1) * P(+1) / (P(author|+1) + P(long|+1) + P(!research|+1) + P(grade|+1) + P(!lottery|+1) + P(!author|+1) + P(!long|+1) + P(research|+1) + P(!grade|+1) + P(lottery|+1))\n\t= .01125\n\n\n((.75 + .5 + .5 + .75) + (.25 + 1 + .5 + .5 + .25)) = 5\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6580086350440979, "avg_line_length": 18.25, "blob_id": "ae22f14e93ccbf9cc742f97789cb3f6b36191862", "content_id": "57b56434f6ec00589d47bcd613c725ae9be1efa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 31, "num_lines": 12, "path": "/cs178/hw3/plotter.py", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nthetas=np.linspace(2, 36)\nl=[]\nq=[]\nfor _,a in enumerate(thetas):\n\tfor _,b in enumerate(thetas):\n\t\tfor _,c in enumerate(thetas):\n\t\t\tl.append(a + 3**2)\nplt.plot(l,'r-')\nplt.show()\n" }, { "alpha_fraction": 0.6589723229408264, "alphanum_fraction": 0.6605684757232666, "avg_line_length": 26.283082962036133, "blob_id": "3a27e51dd0301b71ccd1347ef02df0dd91cf00ba", "content_id": "3a09babda57d1b469ea274121668e0a4dc18a533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16289, "license_type": "no_license", "max_line_length": 144, "num_lines": 597, "path": "/ics46/ProjectTwo/src/linked_set.hpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "// Ian Schweer (Unique ID: 660942)\n// Shaun McThomas (Unique ID: 307523)\n// We certify that we worked cooperatively on this programming\n// assignment, according to the rules for pair programming:\n// primarily that both partners worked on all parts together.\n\n#ifndef LINKED_SET_HPP_\n#define LINKED_SET_HPP_\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <initializer_list>\n#include \"ics_exceptions.hpp\"\n#include \"iterator.hpp\"\n#include \"set.hpp\"\n\n\nnamespace ics {\n\ntemplate<class T> class LinkedSet : public Set<T> {\n public:\n\tLinkedSet();\n\tLinkedSet(const LinkedSet<T>& to_copy);\n\tLinkedSet(std::initializer_list<T> il);\n\tLinkedSet(ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n\tvirtual ~LinkedSet();\n\n\tvirtual bool empty () const;\n\tvirtual int size () const;\n\tvirtual bool contains (const T& element) const;\n\tvirtual std::string str () const;\n\n\tvirtual bool contains (ics::Iterator<T>& start, const ics::Iterator<T>& stop) const;\n\n\tvirtual int insert (const T& element);\n\tvirtual int erase (const T& element);\n\tvirtual void clear ();\n\n\tvirtual int insert (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n\tvirtual int erase (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n\tvirtual int retain (ics::Iterator<T>& start, const ics::Iterator<T>& stop);\n\n\tvirtual LinkedSet<T>& operator = (const LinkedSet<T>& rhs);\n\tvirtual bool operator == (const Set<T>& rhs) const;\n\tvirtual bool operator != (const Set<T>& rhs) const;\n\tvirtual bool operator <= (const Set<T>& rhs) const;\n\tvirtual bool operator < (const Set<T>& rhs) const;\n\tvirtual bool operator >= (const Set<T>& rhs) const;\n\tvirtual bool operator > (const Set<T>& rhs) const;\n\n\ttemplate<class T2>\n\tfriend std::ostream& operator << (std::ostream& outs, const LinkedSet<T2>& s);\n\n private:\n\tclass LN;\n\n public:\n\tclass Iterator : public ics::Iterator<T> {\n\t public:\n\t\t//KLUDGE should be callable only in begin/end\n\t\tIterator(LinkedSet<T>* fof, LN* initial);\n\t\tvirtual ~Iterator();\n\t\tvirtual T erase();\n\t\tvirtual std::string str () const;\n\t\tvirtual const ics::Iterator<T>& operator ++ ();\n\t\tvirtual const ics::Iterator<T>& operator ++ (int);\n\t\tvirtual bool operator == (const ics::Iterator<T>& rhs) const;\n\t\tvirtual bool operator != (const ics::Iterator<T>& rhs) const;\n\t\tvirtual T& operator * () const;\n\t\tvirtual T* operator -> () const;\n\t private:\n\t\tLN* current; //if can_erase is false, this value is unusable\n\t\tLinkedSet<T>* ref_set;\n\t\tint expected_mod_count;\n\t\tbool can_erase = true;\n\t};\n\n\t//For explicit use: Iterator<...>& it = c.ibegin(); ... or for (Iterator<...>& it = c.ibegin(); it != c.iend(); ++it)...\n\tvirtual ics::Iterator<T>& ibegin () const;\n\tvirtual ics::Iterator<T>& iend () const;\n\n\t//For implicit use: for (... i : c)...\n\tvirtual Iterator begin () const;\n\tvirtual Iterator end () const;\n\n private:\n\tclass LN {\n\t public:\n\t\tLN () {}\n\t\tLN (const LN& ln) : value(ln.value), next(ln.next){}\n\t\tLN (T v, LN* n = nullptr) : value(v), next(n){}\n\n\t\tT value;\n\t\tLN* next = nullptr;\n\t};\n\n\tint used = 0; //Cache of # values in set\n\tLN* front = new LN();\n\tLN* trailer = front;\n\tint mod_count = 0; //For sensing concurrent modification\n\tint erase_at(LN* p);\n\tvoid delete_list(LN*& front); //Recycle storage, set front's argument to nullptr;\n };\n\n\n\n//See code in array_set.hpp and linked_queue.hpp and linked_priority_queue.hpp\n\n//Write the constructors, methods, and operators here for LinkedSet\n\n/**\n * Default constructor\n */\ntemplate <class T>\nLinkedSet<T>::LinkedSet() : Set<T>() {\n\t\n}\n\n/**\n * Copy constructor. Since we are coping a set, we can assume the size\n * of the set will stay the same.\n */\ntemplate <class T>\nLinkedSet<T>::LinkedSet(const LinkedSet<T>& to_copy) : Set<T>() {\n\tinsert(to_copy.ibegin(), to_copy.iend());\n}\n\n/**\n * Constructor with initializer_list. Initializer lists do not have\n * a uniqueness constraint, so we can't assume anything.\n */\ntemplate <class T>\nLinkedSet<T>::LinkedSet(std::initializer_list<T> il) : Set<T>() {\n\tfor (T val : il)\n\t\tinsert(val);\n}\n\n/**\n * Constructor given two iterators. Since it's impossible to determine\n * size given two ics::Iterators, we cannot assume a size.\n */\ntemplate <class T>\nLinkedSet<T>::LinkedSet(ics::Iterator<T>& start, const ics::Iterator<T>& stop)\n\t: Set<T>() {\n\tinsert(start, stop);\n}\n\n/**\n * Deconstructor\n */\ntemplate <class T>\nLinkedSet<T>::~LinkedSet() {\n\tdelete_list(front);\n}\n\n/**\n * Empty. Function will determine if the set is empty.\n * Note: An alternative way to do this would be to say front==nullptr\n * however, that then requires the code further down to enforce that \n * requirement, where as used is a highly used integer. This is easier.\n */\ntemplate <class T>\nbool LinkedSet<T>::empty() const {\n\treturn used == 0;\n}\n\n/**\n * Size. Function will return the size of the queue. \n */\ntemplate <class T>\nint LinkedSet<T>::size() const {\n\treturn used;\n}\n\n/**\n * Contains. Function will determine if an element is in a set. This\n * function will take Linear Time.\n *\n * @param const T& element\n * The element to check for existence.\n *\n * @return bool\n * Return if the element is or isn't in the set.\n */\ntemplate <class T>\nbool LinkedSet<T>::contains(const T& element) const {\n\tbool to_return = false;\n\tfor (LN *node = front; node != trailer && !to_return; node = node->next)\n\t\tif (node->value == element) \n\t\t\tto_return = true;\n\treturn to_return;\n}\n\n/**\n * Str. A debugging print method.\n */\ntemplate <class T>\nstd::string LinkedSet<T>::str() const {\n\tstd::ostringstream out;\n\tout << *this << \"(length=\" << size() << \",mod_count=\" << mod_count << \")\";\n\treturn out.str();\n}\n\n/**\n * Contains. Function will determine if a set contains all elements specified by the\n * iterators. Function will consume the result of the simpiler contains method\n */\ntemplate<class T>\nbool LinkedSet<T>::contains (ics::Iterator<T>& start, const ics::Iterator<T>& stop) const {\n\tbool found = true;\n\tfor (; found && start != stop; start++) \n\t\tfound = contains(*start);\n\treturn found;\n}\n\n/**\n * Insert. Function will insert an element into a set given it doesn't already exist.\n * Since this is trailered, we can just extened the trailered element.\n *\n * @return int\n * The number of insertions, which is one or zero.\n */\ntemplate<class T>\nint LinkedSet<T>::insert (const T& element) {\n\tint to_return = 0;\n\tif (!contains(element)) {\n\t\tused++; \n\t\tmod_count++;\n\t\tto_return++;\n\t\ttrailer->value = element;\n\t\ttrailer = trailer->next = new LN();\n\t}\n\treturn to_return;\n}\n\n/**\n * Erase. Function will find and erase a current element. This function \n * will not do any of the actual deleting, but merely call the erase_at\n * function.\n *\n * @param const T& element\n * The element to erase.\n *\n * @return int\n * The number of elements erase. Either one or zero.\n */\ntemplate<class T>\nint LinkedSet<T>::erase(const T& element) {\n\tfor (LN* temp = front; temp != trailer; temp = temp->next)\n\t\tif (temp->value == element)\n\t\t\treturn erase_at(temp);\n\treturn 0;\n}\n\n/**\n * Clear. Given the set isn't empty, erase all elements (except the trailer).\n */\ntemplate<class T>\nvoid LinkedSet<T>::clear() {\n\tif (!empty()) \n\t{\n\t delete_list(front);\n\t\tfront = trailer;\n\t}\n}\n\n/**\n * Insert w/ iterators. Given a start and stop iterator, insert all the elements\n * between the two iterators, given the element does not exist. Function will\n * consume the insert function.\n *\n * @param ics::Iterator<T>& start\n * The starting iterator\n *\n * @param const ics::Iterator<T>& stop\n * The ending iterator\n *\n * @return int\n * The number of inserts.\n */\ntemplate <class T>\nint LinkedSet<T>::insert (ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n\tint to_return = 0;\n\tfor (; start != stop; to_return += insert(*start++)); \n\treturn to_return;\n}\n\n/**\n * Erase. Function will erase all elements in a set between a start and stop\n * iterator. Function will consume the simplier erase method.\n *\n * @param ics::Iterator<T> start\n * The starting iterator.\n *\n * @param const ics::Iterator<T> stop\n * The ending iterator.\n *\n * @return int\n * The number of removals from the list.\n */\ntemplate <class T>\nint LinkedSet<T>::erase (ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n\tint to_return = 0;\n\tfor(; start != stop; to_return += erase(*start++));\n\treturn to_return;\n}\n\n/** \n * Retain. Function will compute the intersection of two sets. Function will\n * construct a new linked set given two iterators, and then determine the \n * elements in common.\n *\n * @param ics::Iterator<T>& start\n * The starting iterator\n * \n * @param const ics::Iterator<T>& end\n * The ending iterator.\n *\n * @return int\n * The number of elements \"retained\" in the set.\n */\ntemplate <class T>\nint LinkedSet<T>::retain (ics::Iterator<T>& start, const ics::Iterator<T>& stop) {\n\tLinkedSet<T> s;\n\tfor (; start != stop; start++)\n\t\tif (contains(*start))\n\t\t\ts.insert(*start); \n\n\t*this = s;\n\treturn used;\n}\n\n/**\n * Assignment. Function will become equal to a argument set.\n * See equality operator for precise definition. In the event\n * that the set has already been used previously, the set\n * will be cleared.\n */\ntemplate <class T>\nLinkedSet<T>& LinkedSet<T>::operator = (const LinkedSet<T>& rhs) {\n\tif (this == &rhs)\n\t\treturn *this;\n\tclear();\n\tinsert(rhs.ibegin(), rhs.iend());\n\t++mod_count;\n\treturn *this;\n}\n\n/**\n * Equality. Function will determine if two set are equal. Two\n * set are equal if and only if the sizes are equal, and if all\n * the elements in the right hand set are in the current set, but\n * not in the same order\n *\n * @param const Set<T>&\n * The argument set. Notice the type is not a linked set, that\n * is becase we use iterators to check element equality.\n * This allows for cross compabilities between data structures\n * as long as they are the same data type.\n */\ntemplate<class T>\nbool LinkedSet<T>::operator == (const Set<T>& rhs) const {\n\tif (this == &rhs)\n\t\treturn true;\n\tif (used != rhs.size())\n\t\treturn false;\n\tfor (LN *temp = front; temp != trailer; temp = temp->next)\n\t\tif (!rhs.contains(temp->value))\n\t\t\treturn false;\n\n\treturn true;\n}\n\n/**\n * Non-Equality. Function will determine if two sets are NOT equal. See\n * equality for definition.\n *\n * @param const Set<T>&\n * The argument queue. Notice the type is not a linked queue, that\n * is becase we use iterators to check element and order equality.\n * This allows for cross compabilities between data structures\n * as long as they are the same data type.\n */\ntemplate<class T>\nbool LinkedSet<T>::operator != (const Set<T>& rhs) const {\n\treturn !(*this == rhs);\n}\n\ntemplate<class T>\nbool LinkedSet<T>::operator <= (const Set<T>& rhs) const {\n\t// if (this == &rhs)\n\t// return true;\n\t// if (used > rhs.size())\n\t// return false;\n\t// for (LN *temp = front; temp != trailer; temp = temp->next)\n\t// if (!rhs.contains(temp->value))\n\t// return false;\n\n\t// return true;\n\treturn (*this == rhs || *this < rhs);\n}\n\ntemplate<class T>\nbool LinkedSet<T>::operator < (const Set<T>& rhs) const {\n\tif (this == &rhs)\n\t\treturn true;\n\tif (used >= rhs.size())\n\t\treturn false;\n\tfor (LN *temp = front; temp != trailer; temp = temp->next)\n\t\tif (!rhs.contains(temp->value))\n\t\t\treturn false;\n\n\treturn true;\n}\n\ntemplate<class T>\nbool LinkedSet<T>::operator >= (const Set<T>& rhs) const {\n\treturn rhs <= *this;\n}\n\ntemplate<class T>\nbool LinkedSet<T>::operator > (const Set<T>& rhs) const {\n\treturn rhs < *this;\n}\n\ntemplate<class T>\nLinkedSet<T>::Iterator::Iterator(LinkedSet<T>* fof, LN* initial) : current(initial), ref_set(fof) {\n\texpected_mod_count = ref_set->mod_count;\n}\n\ntemplate<class T>\nLinkedSet<T>::Iterator::~Iterator() {\n\n}\n\ntemplate<class T>\nT LinkedSet<T>::Iterator::erase() {\n\tif (expected_mod_count != ref_set->mod_count)\n\t\tthrow ConcurrentModificationError(\"LinkedSet::Iterator::erase\");\n\tif (!can_erase)\n\t\tthrow CannotEraseError(\"LinkedSet::Iterator::erase Iterator cursor already erased\");\n\tif (current == nullptr || current->next == nullptr)\n\t\tthrow CannotEraseError(\"LinkedSet::Iterator::erase Iterator cursor beyond data structure\");\n\n\tcan_erase = false;\n\tT to_return = current->value;\n\tLN *to_erase = current;\n\tcurrent = current->next;\n\tref_set->erase_at(to_erase);\n\texpected_mod_count = ref_set->mod_count;\n\treturn to_return;\n}\n\ntemplate<class T>\nstd::string LinkedSet<T>::Iterator::str () const {\n\tstd::ostringstream answer;\n\tanswer << ref_set->str() << \"(current=\" << current->value << \",expected_mod_count=\" << expected_mod_count << \",can_erase=\" << can_erase << \")\";\n\treturn answer.str();\n}\n\ntemplate<class T>\nconst ics::Iterator<T>& LinkedSet<T>::Iterator::operator ++ () {\n\tif (expected_mod_count != ref_set->mod_count)\n\t\tthrow ConcurrentModificationError(\"LinkedSet::Iterator::operator ++\");\n\tif (current->next == nullptr) {\n\t\treturn *this;\n\t}\n\tif (!can_erase) can_erase = true;\n\telse {\n\t\tcurrent = current->next;\n\t}\n\treturn *this;\n}\n\ntemplate<class T>\nconst ics::Iterator<T>& LinkedSet<T>::Iterator::operator ++ (int) {\n\tif (expected_mod_count != ref_set->mod_count)\n\t\tthrow ConcurrentModificationError(\"LinkedSet::Iterator::operator ++(int)\");\n\tif (current->next == nullptr) {\n\t\treturn *this;\n\t}\n\n\tIterator *to_return = new Iterator(this->ref_set, current);\n\tif (!can_erase) can_erase = true;\n\telse {\n\t\tcurrent = current->next;\n\t}\n\treturn *to_return;\n}\n\ntemplate<class T>\nbool LinkedSet<T>::Iterator::operator == (const ics::Iterator<T>& rhs) const {\n\tconst Iterator* rhsASI = dynamic_cast<const Iterator*>(&rhs);\n\tif (rhsASI == 0)\n\t\tthrow IteratorTypeError(\"ArraySet::Iterator::operator ==\");\n\tif (expected_mod_count != ref_set->mod_count)\n\t\t throw ConcurrentModificationError(\"ArraySet::Iterator::operator ==\");\n\tif (ref_set != rhsASI->ref_set)\n\t\tthrow ComparingDifferentIteratorsError(\"ArraySet::Iterator::operator ==\");\n\n\treturn current == rhsASI->current;\n}\n\ntemplate<class T>\nbool LinkedSet<T>::Iterator::operator != (const ics::Iterator<T>& rhs) const {\n\treturn !(*this == rhs);\n}\n\ntemplate<class T>\nT& LinkedSet<T>::Iterator::operator * () const {\n\tif (expected_mod_count != ref_set->mod_count)\n\t\tthrow ConcurrentModificationError(\"LinkedSet::Iterator::operator *\");\n\tif (!can_erase || current == nullptr) {\n\t\tstd::ostringstream where;\n\t\twhere << current << \" when size = \" << ref_set->size();\n\t\tthrow IteratorPositionIllegal(\"LinkedSet::Iterator::operator * Iterator illegal: \" + where.str());\n\t}\n\treturn current->value;\n}\n\ntemplate<class T>\nT* LinkedSet<T>::Iterator::operator -> () const {\n\tif (expected_mod_count != ref_set->mod_count)\n\t\tthrow ConcurrentModificationError(\"ArraySet::Iterator::operator ->\");\n\tif (!can_erase || current->next == nullptr || current == nullptr) {\n\t\tstd::ostringstream where;\n\t\twhere << current << \" when size = \" << ref_set->size();\n\t\tthrow IteratorPositionIllegal(\"ArraySet::Iterator::operator -> Iterator illegal: \"+where.str());\n\t}\n\n\treturn &current->value;\n}\n\ntemplate<class T2>\nstd::ostream& operator << (std::ostream& outs, const LinkedSet<T2>& s) {\n\touts << \"set[\";\n\tif (!s.empty()) {\n\t\tint i = 0;\n\t\tfor (auto &val = s.ibegin(); val != s.iend(); ++val) {\n\t\t\touts << *val;\n\t\t\tif (++i < s.size()) outs << \",\";\n\t\t}\n\t}\n\touts << \"]\";\n\treturn outs;\n}\n\ntemplate<class T>\nauto LinkedSet<T>::ibegin() const -> ics::Iterator<T>&{\n\treturn *(new Iterator(const_cast<LinkedSet<T>*>(this), front));\n}\n\ntemplate<class T>\nauto LinkedSet<T>::iend() const -> ics::Iterator<T>&{\n\treturn *(new Iterator(const_cast<LinkedSet<T>*>(this), trailer));\n}\n\ntemplate<class T>\nauto LinkedSet<T>::begin() const -> LinkedSet<T>::Iterator {\n\treturn Iterator(const_cast<LinkedSet<T>*>(this), front);\n}\n\ntemplate<class T>\nauto LinkedSet<T>::end() const -> LinkedSet<T>::Iterator {\n\treturn Iterator(const_cast<LinkedSet<T>*>(this), trailer);\n}\n\n\ntemplate<class T>\nvoid LinkedSet<T>::delete_list(LN*& node) {\n\tfor (LN *temp = node; temp != trailer; temp = temp->next) {\n\t\terase_at(temp);\n\t}\n}\n\ntemplate<class T>\nint LinkedSet<T>::erase_at(LN* node) {\n\tLN* temp = node;\n\tnode = node->next;\n\tif (temp != front) {\n\t\t// update back references.\n\t\tLN *prev = front;\n\t\tfor (; prev->next != temp && prev->next != nullptr; prev = prev->next);\n\t\tprev->next = node;\n\t} else {\n\t\tfront = node;\n\t}\n\tdelete temp;\n\tused--;\n\tmod_count++;\n\treturn 1;\n}\n\n}\n\n#endif /* LINKED_SET_HPP_ */\n\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 25.6842098236084, "blob_id": "6379700c1f9de77481928b608b2da62a999f0587", "content_id": "7a9b9a0f1660af5d300dfddfe0a6cc1fb5966932", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 506, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/cs143B/project1/header/eventdispatcher.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <string>\n#include <vector>\n#include \"EventListener.h\"\n\n#ifndef EVENTDISPATCHER_H\n#define EVENTDISPATCHER_H\nclass EventDispatcher {\npublic:\n\tEventDispatcher() : listeners() {};\n\tEventListener* fire_on_delete(const string& name);\n\tvoid fire_has_deleted(string name);\n\tEventListener* fire_on_request(string name);\n\tvoid fire_on_release(int id);\n\tvoid register_listener(EventListener *listener);\n\tvoid unregister_listener(EventListener *listener);\nprivate:\n\tvector<EventListener*> listeners;\n};\n#endif" }, { "alpha_fraction": 0.636929452419281, "alphanum_fraction": 0.6504149436950684, "avg_line_length": 19.08333396911621, "blob_id": "77c24bb92eee492589fe94181a6bc8797dcc9dcb", "content_id": "61a1f980c996c6b5baceabe998f2c95f3afcc055", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 964, "license_type": "no_license", "max_line_length": 71, "num_lines": 48, "path": "/cs143A/project2/reciever.c", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <signal.h>\n#include <string.h>\n\nint sig_count;\nstruct sigaction act;\n\nunsigned long getpid(siginfo_t *info) {\n\treturn (unsigned long) info->si_pid;\n}\n\nvoid sig_handler(int signum, siginfo_t *info, void *ptr)\n{\n\tunsigned long pid = getpid(info);\n\tswitch (signum) {\n\t\tcase SIGUSR2:\n\t\t\tprintf(\"I got message! %ld\\n\", pid);\n\t\t\tsig_count++;\n\t\t\tbreak;\n\t}\n\tif (sig_count >= 10) {\n\t\tprintf(\"Sending sigint to %ld\\n\", pid);\n\t\tkill(pid, SIGINT);\n\t}\n}\n\nint main(int argc, char** argv) \n{\n\tsig_count = 0;\n\t// using the sigaction manner.\n\tmemset(&act, 0, sizeof(act));\n\n\tact.sa_sigaction = sig_handler;\n\tact.sa_flags = SA_SIGINFO; // setting this will package an additional \n\t// data package containing some neat info (pid, time, etc)\n\n\t// set our constants.\n\tsigaction(SIGUSR2, &act, NULL);\n\n\twhile (1) { \n\t\tlong pid = strtol(argv[argc - 1], NULL, 10);\n\t\tkill(pid, SIGUSR1); \n\t\tsleep(1); \n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6634146571159363, "alphanum_fraction": 0.6731707453727722, "avg_line_length": 21.77777862548828, "blob_id": "74c08ead6cd00b3b8d491f3251acf19827b6e543", "content_id": "a72a6e5a8fdfbd6a3ac3c53dd613915eb08166b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 205, "license_type": "no_license", "max_line_length": 65, "num_lines": 9, "path": "/cs143B/project2/Makefile", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "EXNAME=fs\nDEPS=io/iosystem_impl.cpp filesystem/filesystem_impl.cpp main.cpp\nOPTIONS=-std=c++11 -o\nall:\n\tg++ $(OPTIONS) $(EXNAME) $(DEPS)\ndebug:\n\tg++ -ggdb $(OPTIONS) $(EXNAME) $(DEPS)\nclean:\n\trm $(EXNAME)\n" }, { "alpha_fraction": 0.7039999961853027, "alphanum_fraction": 0.7039999961853027, "avg_line_length": 13.461538314819336, "blob_id": "3997333503270042785bc69c4e295156f9321091", "content_id": "7f8ed7d0cb0df59b48fb39fe68342773442203e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 375, "license_type": "no_license", "max_line_length": 63, "num_lines": 26, "path": "/cs143B/project1/header/statuses.h", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "#include <vector>\nusing std::vector;\n\n#ifndef STATUSES_H\n#define STATUSES_H\nclass PCB;\n/**\n * Status enum for a process.\n */\ntypedef enum statusType_enum {\n\tREADY,\n\tRUNNING,\n\tBLOCKED,\n\tFREE,\n\tALLOCATED\n} statusType;\n\n\n/** \n * Status data structure for all processes waiting on this one.\n */\ntypedef struct status_s {\n\tstatusType status;\n\tvector<PCB> *list;\n} status_t;\n#endif" }, { "alpha_fraction": 0.6706002950668335, "alphanum_fraction": 0.67596435546875, "avg_line_length": 27.098297119140625, "blob_id": "f64467820635a3959e9fa71d39a514ca72e623e7", "content_id": "11d71e54e9577d1056599a1bf0046fc58edd0882", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 21439, "license_type": "no_license", "max_line_length": 107, "num_lines": 763, "path": "/cs143B/project1/main.cpp", "repo_name": "Ch0ronomato/uci", "src_encoding": "UTF-8", "text": "/**\n * Ian Schweer\n * 22514022\n * [email protected]\n * CS 143B\n */\n#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <map>\n\nusing std::cout;\nusing std::endl;\nusing std::cin;\nusing std::getline;\nusing std::string;\nusing std::vector;\nusing std::ostream;\nusing std::stringstream;\nusing std::pair;\nusing std::map;\n\n/**\n * @todo: Implement event dispatcher. \n * \n * Abstract event listener class for when any pcb is going to be erased.\n * Simply loop through ALL the pcb items and delete them.\n */\n\nclass PCB;\ntypedef vector<PCB *>::iterator pcb_ptr_iter_t;\ntypedef vector<pair<int,PCB *>>::iterator pcb_ptr_int_iter_t;\ntypedef vector<PCB>::iterator pcb_iter_t;\nclass EventDispatcher;\n\nclass EventListener {\npublic:\n\t/**\n\t * onDelete : PCB *\n\t * Method returns a process control block that is being deleted\n\t * to the event dispatcher, or null if it is not being deleted.\n\t */\n\tvirtual EventListener* on_delete(string name) = 0;\n\t/**\n\t * on_request\n\t * Method to get a resource of name ${name}\n\t * \n\t * @todo: change name to on_get_resource\n\t */\n\tvirtual EventListener* on_request(string name) = 0;\n\tvirtual void has_deleted(string name) = 0;\n};\n\nclass EventDispatcher {\npublic:\n\tEventDispatcher() : listeners() {};\n\tEventListener* fire_on_delete(const string& name);\n\tvoid fire_has_deleted(string name);\n\tEventListener* fire_on_request(string name);\n\tvoid fire_on_release(int id);\n\tvoid register_listener(EventListener *listener);\n\tvoid unregister_listener(EventListener *listener);\nprivate:\n\tvector<EventListener*> listeners;\n};\n\nEventListener* EventDispatcher::fire_on_delete(const string& name) {\n\tEventListener *to_delete = nullptr;\n\tfor (EventListener *listener : listeners) {\n\t\tto_delete = listener->on_delete(name);\n\t\tif (to_delete != nullptr) break;\n\t}\n\n\treturn to_delete;\n}\n\nEventListener* EventDispatcher::fire_on_request(string name) {\n\tEventListener *to_delete = nullptr;\n\tfor (EventListener *listener : listeners) {\n\t\tto_delete = listener->on_request(name);\n\t\tif (to_delete != nullptr) break;\n\t}\n\n\treturn to_delete;\n}\n\nvoid EventDispatcher::fire_has_deleted(string name) {\n\tfor (EventListener *listener : listeners) {\n\t\tlistener->has_deleted(name);\n\t}\n}\n\nvoid EventDispatcher::register_listener(EventListener *listener) {\n\tlisteners.push_back(listener);\n}\n\nvoid EventDispatcher::unregister_listener(EventListener *listener) {\n\tvector<EventListener*>::iterator iter = listeners.begin();\n\tbool found = false;\n\tfor (; iter != listeners.end(); iter++) {\n\t\tif (*iter == listener) {\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (found)\n\t\tlisteners.erase(iter);\n}\n/**\n * Status enum for a process.\n */\ntypedef enum statusType_enum {\n\tREADY,\n\tRUNNING,\n\tBLOCKED,\n\tFREE,\n\tALLOCATED\n} statusType;\n\n\n/** \n * Status data structure for all processes waiting on this one.\n */\ntypedef struct status_s {\n\tstatusType status;\n\tvector<PCB> *list;\n} status_t;\n\n/**\n * Resource control block. \n * Contains data about a resource.\n */\n // @todo: Add code for resource allocation amount.\nclass RCB : public EventListener {\npublic:\n\tRCB();\n\tRCB(int arg_id, string arg_name, int arg_allocated);\n\tint id;\n\tint total;\n\tint allocated;\n\tstring name;\n\tstatus_t status;\n\tvector<pair<int, PCB *>> waiting_list;\n\tfriend ostream& operator<<(ostream& outs, RCB &obj);\n\tvirtual EventListener* on_delete(string arg_name) { return nullptr; }\n\tvirtual EventListener* on_request(string arg_name) {\n\t\treturn !name.compare(arg_name) ? this : nullptr;\n\t}\n\tvirtual void has_deleted(string name) { }\n};\n\nRCB::RCB() { \n\tid = -1;\n\tname = \"\";\n\tstatus.status = FREE;\n\ttotal = allocated = 0;\n}\nRCB::RCB(int arg_id, string arg_name, int arg_allocated) {\n\tid = arg_id;\n\tname = arg_name;\n\tstatus.status = FREE;\n\tallocated = 0;\n\ttotal = arg_allocated;\n}\n\nostream& operator<<(ostream& outs, RCB &obj) {\n\touts << \"Resource (\" << obj.name << \") in status \";\n\tswitch (obj.total - obj.allocated) {\n\t\tcase 0:\n\t\t\touts << \"ALLOCATED\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\touts << \"FREE(\" << obj.total - obj.allocated << \")\";\n\t\t\tbreak;\n\t} \n\n\tcout << \" waiting on \" << obj.waiting_list.size();\n\treturn outs;\n}\n\n/**\n * Process control block.\n * Contains all data related to a running process. Include an id, all resources, a status\n * (@see status_t), a tree of all processes created and the priority of the process for the\n * scheduler.\n */\nclass PCB : public EventListener {\npublic:\n\tPCB(int id, string name, int priority) : id(id), name(name), priority(priority), resource_to_amount_map() \n\t{\n\t\tresource_to_amount_map[\"R1\"] = 0;\n\t\tresource_to_amount_map[\"R2\"] = 0;\n\t\tresource_to_amount_map[\"R3\"] = 0;\n\t\tresource_to_amount_map[\"R4\"] = 0;\n\t};\n\tPCB (const PCB& copy) : id(copy.id), name(copy.name), \n\t\tresource_to_amount_map(copy.resource_to_amount_map),\n\t\tstate(copy.state), creation_tree(copy.creation_tree),\n\t\tpriority(copy.priority) { }\n\t~PCB() { // don't do anything \n\t}\n\tint id;\n\tstring name;\n\tmap<string, int> resource_to_amount_map;\n\tvector<RCB *> resources;\n\tstatus_t state;\n\tvector<PCB *> creation_tree;\n\tint priority;\n\tvirtual EventListener* on_delete(string arg_name) {\n\t\treturn !name.compare(arg_name) ? this : nullptr;\n\t};\n\n\tvirtual void has_deleted(string arg_name) {\n\t\tpcb_ptr_iter_t k = creation_tree.begin();\n\t\twhile (k != creation_tree.end()) {\n\t\t\tPCB *i = *k;\n\t\t\tif (!i->name.compare(arg_name)) break;\n\t\t\tk++;\n\t\t}\n\n\t\tif (k != creation_tree.end()) creation_tree.erase(k);\n\t}\n\n\tvirtual EventListener* on_request(string name) { return nullptr; };\n\n\tfriend ostream& operator<<(ostream& outs, PCB &obj) {\n\t\touts << obj.name;\n\t\treturn outs;\n\t}\n\tbool checkChildren(PCB *to_delete) {\n\t\tif (to_delete->id == id) return true;\n\t\tif (creation_tree.empty() == false) {\n\t\t\tpcb_ptr_iter_t iter = creation_tree.begin();\n\t\t\tfor (PCB *item : creation_tree) {\n\t\t\t\tif (item->id == to_delete->id) {\n\t\t\t\t\tcreation_tree.erase(iter);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\titer++;\n\t\t\t}\n\n\t\t\tfor (PCB *item : creation_tree) {\n\t\t\t\tif (item->checkChildren(item))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n};\n\n/**\n * ListManager\n * A singleton design for a list manager. This class holds the ready, running and block list of \n * processes. Each call must be routed through the getInstance call to ensure these lists are\n * not created.\n */\nclass ListManager {\npublic:\n\tvector<PCB>* get_ready_list() { return &ready_list; };\n\tvector<PCB>* get_running_list() { return &running_list; };\n\tvector<PCB>* get_blocked_list() { return &blocked_list; };\n\tbool delete_pcb_from_list(PCB *to_delete);\n\tvector<PCB>* find_pcb_list(PCB *to_find);\n\tstatic ListManager* get_instance();\n\tvoid clear_lists() { \n\t\tready_list.clear();\n\t\trunning_list.clear();\n\t\tblocked_list.clear();\n\t}\nprivate:\n\tstatic ListManager *instance;\n\tvector<PCB> ready_list;\n\tvector<PCB> running_list;\t\n\tvector<PCB> blocked_list;\n\tListManager() : ready_list(), running_list(), blocked_list() { };\n};\n\n// Singleton pattern for lists.\nListManager *ListManager::instance = nullptr;\nListManager* ListManager::get_instance() {\n\tif (ListManager::instance == nullptr)\n\t\tListManager::instance = new ListManager();\n\treturn ListManager::instance;\n}\n\n/**\n * ListManager::find_pcb_list\n *\n * Method to find a pcb in it's list.\n */\nvector<PCB>* ListManager::find_pcb_list(PCB *to_delete) {\n\tvector<PCB> *ptr_to_list = nullptr;\n\tswitch (to_delete->state.status) {\n\t\tcase READY:\n\t\t\treturn get_ready_list();\n\t\tbreak;\n\t\tcase RUNNING:\n\t\t\treturn get_running_list();\n\t\tbreak;\n\t\tcase BLOCKED:\n\t\t\treturn get_blocked_list();\n\t\tbreak;\n\t\tdefault:\n\t\t\treturn nullptr;\n\t\tbreak;\n\t}\n}\n\n/**\n * ListManager::delete_pcb_from_list\n *\n * Method to find a pcb in it's list and delete it.\n */\nbool ListManager::delete_pcb_from_list(PCB *to_delete) {\n\tvector<PCB> *list = find_pcb_list(to_delete);\n\tif (list == nullptr) return false;\n\n\t// find to_delete and erase it.\n\tpcb_iter_t iter = list->begin();\n\twhile (iter != list->end()) {\n\t\tif (iter->id == to_delete->id)\n\t\t\tbreak;\n\t\titer++;\n\t}\n\tif (iter != list->end()) {\n\t\tlist->erase(iter);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n/**\n * ShellManager\n * The actual manager of the shell. Will handle all actions related to processes and resources.\n */\nclass ShellManager {\npublic:\n\tShellManager(ListManager *list_manager);\n\tPCB* get_current_process() { return delete_current_process ? nullptr : current_process; };\n\tbool create(PCB *parent_id, string name, int priority);\n\tbool destroy(string name);\n\tbool allocate_resource(PCB *process, string name, int amount);\n\tbool release_resource(string name, int amount);\n\tvoid list_processes_tree();\n\tvoid list_processes_tree(PCB *start, string spacer = \"\");\n\tvoid list_resources();\n\tbool timeout();\n\tbool init();\nprivate:\n\tvoid schedule();\n\tvoid kill_tree(PCB *to_delete);\n\tvoid preempt_put_on_ready(PCB *px);\n\tvoid preempt_put_on_wait(PCB *px);\n\tvoid release_resource_enqueue_waiting_process(RCB *r);\n\tint processId; // strictly increasing.\n\tListManager *list_manager;\n\tPCB *root_process;\n\tPCB *current_process;\n\tEventDispatcher *event_dispatcher;\n\tconst static int num_of_resources = 4;\n\tRCB *resources[num_of_resources];\n\tbool delete_current_process;\n};\n\nShellManager::ShellManager(ListManager *list_manager)\n\t: processId(1), list_manager(list_manager), \n\troot_process(nullptr), current_process(nullptr), \n\tevent_dispatcher(), resources(), delete_current_process(false) { \n\tRCB *r1 = new RCB(0, \"R1\", 1), *r2 = new RCB(1, \"R2\", 2);\n\tRCB *r3 = new RCB(2, \"R3\", 3), *r4 = new RCB(3, \"R4\", 4);\n\tevent_dispatcher = new EventDispatcher();\n\tevent_dispatcher->register_listener(r1);\n\tevent_dispatcher->register_listener(r2);\n\tevent_dispatcher->register_listener(r3);\n\tevent_dispatcher->register_listener(r4);\n\tresources[0] = r1; \n\tresources[1] = r2;\n\tresources[2] = r3; \n\tresources[3] = r4;\n}\n\n/**\n * ShellManager::Create\n * Method to create a new process with @prop {processId} id using @param parent and @param name. \n *\n * Sudo code from slides:\n *\tCreate PCB data structure\n *\tInit PCB using parameters\n *\tLink PCB to creation tree\n *\tInsert into Ready List\n *\tSchedule\n */\nbool ShellManager::create(PCB *parent, string name, int priority) {\n\tif (event_dispatcher->fire_on_delete(name) != nullptr) {\n\t\treturn false;\n\t}\n\tPCB *new_process = new PCB(++processId, name, priority);\n\n\t// initialize states.\n\tnew_process->state.status = READY;\n\tnew_process->state.list = list_manager->get_ready_list();\n\n\t// Link the PCB to the creation tree of the parent.\n\tparent->creation_tree.push_back(new_process);\n\tlist_manager->get_ready_list()->push_back(*new_process);\n\n\tevent_dispatcher->register_listener(new_process);\n\n\tschedule();\n\treturn true;\n}\n\n/**\n * ShellManager::Destroy\n * Method to destroy a @param process.\n * Each PCB block destroyed will also destroy all of it's children, as well as release the resources.\n * A recursive destory design will allow us to do this efficently. \n *\n * Sudo code from slides:\n *\tGet pointer p to PCB to deleted\n *\tKill subtree\n *\tSchedule\n */\nbool ShellManager::destroy(string name) {\n\tPCB *to_delete = (PCB*)event_dispatcher->fire_on_delete(name);\n\tif (to_delete == nullptr || current_process->checkChildren(to_delete) == false) {\n\t\treturn false;\n\t}\n\tevent_dispatcher->unregister_listener(to_delete);\t\n\tpcb_iter_t iter;\n\tdelete_current_process = to_delete->state.status == RUNNING;\n\tkill_tree(to_delete);\n\tevent_dispatcher->fire_has_deleted(name);\n\tschedule();\n\treturn true;\n}\n\nvoid ShellManager::kill_tree(PCB *item) {\n\tpcb_ptr_iter_t iter = item->creation_tree.begin();\n\tevent_dispatcher->unregister_listener(item);\n\tlist_manager->delete_pcb_from_list(item);\n\tfor (auto r_iter = item->resources.begin(); r_iter != item->resources.end(); r_iter++) {\n\t\tif (item->state.status == BLOCKED) {\n\t\t\t// remove from the waitlist.\n\t\t\tpcb_ptr_int_iter_t wait_iter = (*r_iter)->waiting_list.begin();\n\t\t\twhile (wait_iter != (*r_iter)->waiting_list.end()) {\n\t\t\t\tif (wait_iter->second->id == item->id) {\n\t\t\t\t\t(*r_iter)->waiting_list.erase(wait_iter);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\twait_iter++;\n\t\t\t} \n\t\t} else {\n\t\t\t(*r_iter)->allocated -= item->resource_to_amount_map[(*r_iter)->name];\n\t\t\titem->resource_to_amount_map[(*r_iter)->name] = 0;\n\t\t\trelease_resource_enqueue_waiting_process(*r_iter);\n\t\t}\n\t}\n\tfor (; iter != item->creation_tree.end(); iter++)\n\t\tif (*iter != nullptr) kill_tree(*iter);\n\titem->creation_tree.erase(item->creation_tree.begin(), item->creation_tree.end());\n\tdelete item;\n}\n\n/**\n * ShellManager::release_resource_enqueue_waiting_process\n * Method will remove a waiting process from the wait queue on\n * resource release.\n */\nvoid ShellManager::release_resource_enqueue_waiting_process(RCB *r) {\n\tpcb_ptr_int_iter_t waitlist_iter = r->waiting_list.begin();\n\twhile (r->allocated < r->total && waitlist_iter != r->waiting_list.end()) {\n\t\tif ((r->allocated + waitlist_iter->first) <= r->total) {\n\t\t\tr->allocated+= waitlist_iter->first;\n\t\t\twaitlist_iter->second->resource_to_amount_map[r->name] += waitlist_iter->first;\n\t\t\tlist_manager->delete_pcb_from_list(waitlist_iter->second);\n\t\t\twaitlist_iter->second->state.status = READY;\n\t\t\twaitlist_iter->second->state.list = list_manager->get_ready_list();\n\t\t\tlist_manager->get_ready_list()->push_back(*waitlist_iter->second);\n\t\t\twaitlist_iter++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\tr->waiting_list.erase(r->waiting_list.begin(), waitlist_iter);\n}\n/**\n * ShellManager::release_resource\n * Method to release a resource to the process world.\n * \n * After this process the scheduler is called. \n *\n * If there is process waiting on the resource (aka in the processes wait list)\n * run it.\n */\nbool ShellManager::release_resource(string name, int amount) {\n\tRCB *r = (RCB *)event_dispatcher->fire_on_request(name);\n\tif (r == nullptr || amount > current_process->resource_to_amount_map[name]) { \n\t\treturn false; \n\t}\n\tr->allocated -= amount;\n\tcurrent_process->resource_to_amount_map[name] -= amount;\n\trelease_resource_enqueue_waiting_process(r);\n\tschedule();\n\treturn true;\n}\n\n/**\n * ShellManager::allocate_resource\n * Method to allocate a resource for a process\n */\nbool ShellManager::allocate_resource(PCB *process, string name, int amount) {\n\tif (process->id == root_process->id) return false;\n\tRCB *r = (RCB *)event_dispatcher->fire_on_request(name);\n\tif (r == nullptr || r->total < amount) { \n\t\treturn false;\n\t}\n\tprocess->resources.push_back(r);\n\tif (r->allocated + amount <= r->total) {\n\t\tr->allocated += amount;\n\t\tprocess->resource_to_amount_map[name] += amount;\n\t} else {\n\t\tprocess->state.status = BLOCKED;\n\t\tprocess->state.list = list_manager->get_blocked_list();\n\t\tr->waiting_list.push_back(pair<int, PCB*>(amount, process));\n\t}\n\tschedule();\n\treturn true;\n}\n/**\n * ShellManager::list_process\n * Calls list_process(PCB)\n */\nvoid ShellManager::list_processes_tree() {\n\tlist_processes_tree(root_process);\n}\n\n/**\n * ShellManager::list_processes\n * Does a depth first transversal of the processes. Simply prints them.\n */\nvoid ShellManager::list_processes_tree(PCB *start, string spacer) {\n\tcout << spacer << *start << endl;\n\tfor (PCB *pcb : start->creation_tree) {\n\t\tlist_processes_tree(pcb, spacer + \" \");\n\t}\n}\n\n/**\n * ShellManager::list_resources\n * Doesn't do antyhing fancy, just printing resources\n */\nvoid ShellManager::list_resources() {\n\tfor (int i = 0; i < num_of_resources; i++) {\n\t\tcout << *resources[i] << endl;\n\t}\n}\n\n/**\n * ShellManager::preempt\n */\nvoid ShellManager::preempt_put_on_ready(PCB *px) {\n\tlist_manager->get_ready_list()->push_back(*current_process);\n\tstring t = (*px).name;\n\tcurrent_process = (PCB *)event_dispatcher->fire_on_delete(t); \n\tcurrent_process->state.status = RUNNING;\n\tlist_manager->get_running_list()->erase(list_manager->get_running_list()->begin());\n\tlist_manager->get_running_list()->push_back(*current_process);\n\t// delete the current entry from the ready list.\n\tpcb_iter_t iter = list_manager->get_ready_list()->begin();\n\twhile (iter->id != current_process->id) iter++;\n\tlist_manager->get_ready_list()->erase(iter);\n}\n\nvoid ShellManager::preempt_put_on_wait(PCB *px) {\n\tlist_manager->get_blocked_list()->push_back(*current_process);\n\tcurrent_process = (PCB *)event_dispatcher->fire_on_delete(px->name); \n\tcurrent_process->state.status = RUNNING;\n\tlist_manager->get_running_list()->erase(list_manager->get_running_list()->begin());\n\tlist_manager->get_running_list()->push_back(*current_process);\n\t// delete the current entry from the ready list.\n\tpcb_iter_t iter = list_manager->get_ready_list()->begin();\n\twhile (iter->id != current_process->id) iter++;\n\tlist_manager->get_ready_list()->erase(iter);\n}\n\n/**\n * ShellManager::schedule\n * A preemptive priority scheduling algorithm.\n * Sudo code from the lecture:\n *\n * find highest priority process p\n * if (self->priority < p->priority || self->status.type != 'running' || self == null)\n * preempt(p, self)\n */\nvoid ShellManager::schedule() {\n\t// find the highest priority item in the ready list.\n\tint level_two = 0, level_one = 0, level_zero = 0;\n\tPCB *processes[3], *px = nullptr;\n\tpcb_iter_t p = list_manager->get_ready_list()->begin();\n\tfor (; p != list_manager->get_ready_list()->end(); p++) {\n\t\tif (p->priority == 0 && level_zero < 1) {\n\t\t\tlevel_zero++;\n\t\t\tprocesses[2] = &(*p);\n\t\t} else if (p->priority == 1 && level_one < 1) {\n\t\t\tlevel_one++;\n\t\t\tprocesses[1] = &(*p);\n\t\t} else if (p->priority == 2 && level_two < 1) {\n\t\t\tlevel_two++;\n\t\t\tprocesses[0] = &(*p);\n\t\t}\n\t}\n\t\n\tif (level_two == 1) px = processes[0];\n\telse if (level_one == 1) px = processes[1];\n\telse if (level_zero == 1) px = processes[2];\n\telse { \n\t\t// couldn't find a waiting process\n\t\treturn;\n\t}\n\tif (get_current_process() == nullptr) { // dead process\n\t\tcurrent_process = (PCB *)event_dispatcher->fire_on_delete(px->name); \n\t\tlist_manager->delete_pcb_from_list(current_process);\n\t\tcurrent_process->state.status = RUNNING;\n\t\tlist_manager->get_running_list()->push_back(*current_process);\t\t\n\t\tdelete_current_process = false;\n\t} else if (get_current_process()->priority < px->priority) { // higher priority\n\t\t// preempt\n\t\tcurrent_process->state.status = READY;\n\t\tpreempt_put_on_ready(px);\n\t}\n\telse if (get_current_process()->state.status != RUNNING) { // timeout\n\t\tpreempt_put_on_wait(px);\n\t}\n}\n\nbool ShellManager::timeout() {\n\tint x = current_process->priority;\n\tPCB *y = current_process;\n\tcurrent_process->priority = x - 1;\n\tschedule();\n\ty->priority = x;\n\n\tpcb_iter_t iter = list_manager->get_ready_list()->begin();\n\twhile (iter != list_manager->get_ready_list()->end() && iter->id != y->id) {iter++;}\n\tif (list_manager->get_ready_list()->end() != iter) iter->priority = x;\n\treturn true;\n}\n\nbool ShellManager::init() {\n\t// start over.\n\tresources[0]->allocated = 0;\n\tresources[1]->allocated = 0;\n\tresources[2]->allocated = 0;\n\tresources[3]->allocated = 0;\n\tresources[0]->waiting_list.clear();\n\tresources[1]->waiting_list.clear();\n\tresources[2]->waiting_list.clear();\n\tresources[3]->waiting_list.clear();\n\troot_process = new PCB(1, \"init\", 0);\n\tcurrent_process = root_process;\n\tprocessId = 1;\n\tListManager::get_instance()->clear_lists();\n\tListManager::get_instance()->get_running_list()->push_back(*current_process);\n\tdelete event_dispatcher;\n\tevent_dispatcher = new EventDispatcher();\n\tevent_dispatcher->register_listener(root_process);\n\tevent_dispatcher->register_listener(resources[0]);\n\tevent_dispatcher->register_listener(resources[1]);\n\tevent_dispatcher->register_listener(resources[2]);\n\tevent_dispatcher->register_listener(resources[3]);\n\treturn true;\n}\n\nconst string INIT_CMD = \"init\";\nconst string CREATE_CMD = \"cr\";\nconst string DESTORY_CMD = \"de\";\nconst string REQUEST_CMD = \"req\";\nconst string RELEASE_CMD = \"rel\";\nconst string TIMEOUT_CMD = \"to\";\nconst string LIST_PROCESSES_CMD = \"lsp\";\nconst string LIST_RESOURCES_CMD = \"lsr\";\nconst string HELP_CMD = \"help\"; \nconst string QUIT_CMD = \"quit\"; \n\nvector<string> split_args(string input_args) {\n\tstring buf;\n\tstringstream ss(input_args);\n\tvector<string> tokens;\n\twhile (ss >> buf)\n\t\ttokens.push_back(buf);\n\n\treturn tokens;\n}\n\nvector<string> prompt(PCB *current_process, bool init, bool error) {\n\tif (init && !error)\n\t\tcout << *current_process << \" \";\n\telse if (error)\n\t\tcout << \"error \";\n\tstring input;\n\tgetline(cin, input);\n\treturn split_args(input);\n}\n\nint main() {\n\t// initialize the first process.\n\tShellManager manager(ListManager::get_instance());\t\n\tbool initialized = true, error = false;\n\tmanager.init();\n\twhile (!ListManager::get_instance()->get_running_list()->empty() || !initialized) {\n\t\tvector<string> args = prompt(manager.get_current_process(), initialized, error);\n\t\tif (args.size() == 0) {\n\t\t\tif (!initialized) break;\n\t\t\tcout << endl;\n\t\t\tinitialized = false;\n\t\t\terror = false;\n\t\t\tcontinue;\n\t\t}\n\t\tstring input = args.at(0);\n\t\terror = false;\n\n\t\tif (!INIT_CMD.compare(input)) {\n\t\t\tinitialized = manager.init();\n\t\t}\n\t\telse if (!initialized) {\n\t\t\terror = true;\n\t\t}\n\t\telse if (!CREATE_CMD.compare(input)) {\n\t\t\terror = !manager.create(manager.get_current_process(), args[1], args[2][0] - '0');\n\t\t}\n\t\telse if (!DESTORY_CMD.compare(input)) {\n\t\t\terror = !manager.destroy(args[1]);\n\t\t}\n\t\telse if (!REQUEST_CMD.compare(input)) {\n\t\t\terror = !manager.allocate_resource(manager.get_current_process(), args[1], args[2][0] - '0');\n\t\t}\n\t\telse if (!RELEASE_CMD.compare(input)) {\n\t\t\terror = !manager.release_resource(args[1], args[2][0] - '0');\n\t\t}\n\t\telse if (!TIMEOUT_CMD.compare(input)) {\n\t\t\terror = !manager.timeout();\n\t\t}\n\t\telse if (!LIST_PROCESSES_CMD.compare(input)) {\n\t\t\tmanager.list_processes_tree();\n\t\t}\n\t\telse if (!LIST_RESOURCES_CMD.compare(input)) {\n\t\t\tmanager.list_resources();\n\t\t}\n\t\telse if (!QUIT_CMD.compare(input)) {\n\t\t\treturn 0;\n\t\t}\n\t\telse {\n\t\t\tcout << input << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}\n" } ]
137
11philip22/scripts
https://github.com/11philip22/scripts
a8f1d40ee4b8c6f873adb20c6645f64746ea46ad
28503b13a4cf6bef917404eca00d54e25733dfd4
8b18d7c7632f6ffd438d91776f9b041f10a29147
refs/heads/master
2021-06-30T11:38:01.784960
2020-10-17T12:02:38
2020-10-17T12:02:38
140,456,013
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6620370149612427, "alphanum_fraction": 0.6898148059844971, "avg_line_length": 53, "blob_id": "5f1c6dcc752c12006489da366ab8c2f04a490b60", "content_id": "bf99142d19a718b4fc0a5661d39d207d593875a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 216, "license_type": "permissive", "max_line_length": 119, "num_lines": 4, "path": "/ding.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nurl=$(cat /home/philip/scripts/nicetryfbi.txt | grep warpnetip | awk '{print $2}')\ncurl -i -s -k -X $'POST' --data-binary $'redirurl=https%3A%2F%2Fwarpnet.nl&zone=warpnet_guest&accept=Akkoord%21' $url\n" }, { "alpha_fraction": 0.7216194868087769, "alphanum_fraction": 0.7605186700820923, "avg_line_length": 37.56122589111328, "blob_id": "afd87b719fb0d2a6511fa8ff4562611736627d6f", "content_id": "fc064479678e581baa8a79bcafea10687153da5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3779, "license_type": "permissive", "max_line_length": 142, "num_lines": 98, "path": "/fixxubuntu.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# This program is written for ubuntu 19.04 running on a Lenovo Thinkpad t490.\n# Its mostly personalized settings and programs but also a few fixes:\n# -HSP/A2DP bluetooth devices (please check if your bluetooth works before you run this part)\n# -screen tearing and black lockscreen will probably work on on other devices with Intel UHD Graphics 620\n\nif [[ \"$EUID\" -ne 0 ]]\n then echo \"Please run with sudo\"\n exit\nfi\n\nusername=philip\n\napt update\napt install -y vscodium ranger zsh git neofetch tmux subversion rxvt-unicode python3-pip ncmpccp mpd xfonts-terminus \\\nchromium curl\napt remove -y pidgin sgt-launcher sgt-puzzles gnome-sudoku gnome-mines xfburn onboard mousepad remmina\napt autoremove\n\n# disable cups because it makes my pc hang at shutdown\nsystemctl disable cups-browsed.service\n\n# set wallpaper\nwget --output-document=/usr/share/backgrounds/wallpaper1.png https://i.imgur.com/kfHKnjt.png\nwget --output-document=/usr/share/backgrounds/wallpaper2.jpg https://i.imgur.com/035woPC.jpg\nxfconf-query --channel xfce4-desktop --property /backdrop/screen0/monitor0/image-path --set /usr/share/backgrounds/wallpaper1.png\n\n# set gtk theme\nxfconf-query -c xsettings -p /Net/ThemeName -s \"Numix\"\n\n# download scripts\nmkdir -pv $HOME/scripts\ngit clone [email protected]:11philip22/scripts.git $HOME/scripts\nchown -R ${username}:${username} $HOME/scripts\nbash $HOME/scripts/deploy-scripts.sh\n\n# fix grub\nsed 's/GRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash\"/GRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash acpi=force\"/' /etc/default/grub\ngrub-mkconfig\n\n# fix vim\nsed 's/Exec=vim/Exec=urxvt -e vim/' /usr/share/applications/vim.desktop\nsed 's/Terminal=true/Terminal=false/' /usr/share/applications/vim.desktop\n\n# fix screen tearing and locks screen\nmkdir -p /etc/X11/xorg.conf.d/\ntouch /etc/X11/xorg.conf.d/20-intel.conf\ncat <<EOF > /etc/X11/xorg.conf.d/20-intel.conf\nSection \"Device\"\n Identifier \"Intel Graphics\"\n Driver \"intel\"\n Option \"TearFree\" \"true\"\nEndSection\nEOF\n\n# fix auto updates\nsed 'APT::Periodic::Update-Package-Lists \"1\";/APT::Periodic::Update-Package-Lists \"0\";/' /etc/apt/apt.conf.d/20auto-upgrades\nsed 'APT::Periodic::Unattended-Upgrade \"1\";/APT::Periodic::Unattended-Upgrade \"0\";/' /etc/apt/apt.conf.d/20auto-upgrades\n\n# fix zsh\nsh -c \"$(wget -O- https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)\"\nln -s $HOME/scripts/zshrc $HOME/.zshrc\nchown -R ${username}:${username} $HOME/.zshrc\nwget --output-document=$HOME/.oh-my-zsh/themes/junkfood.zsh-theme \\\nhttps://gist.githubusercontent.com/11philip22/60b14d36d923a0e458e060179c5ccfd8/raw/d7f06cee82eff94f55d719f25b3c9ddf1f5c8f8f/junkfood.zsh-theme\nrm -rf $HOME/.oh-my-zsh/.git\n\n# install stack\necho 'deb http://mirror.transip.net/stack/software/deb/Ubuntu_18.04/ ./' | sudo tee /etc/apt/sources.list.d/stack-client.list\nwget -O - https://mirror.transip.net/stack/release.key | sudo apt-key add -\nsudo apt-get update\napt-get install stack-client\n\n# install qemu/kvm\napt-get -y install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils\nadduser ${username} libvirt\n\n# install citrix\nwget --output-document=/tmp/citrix.deb \\\nhttps://downloads.citrix.com/14822/icaclientWeb_13.10.0.20_amd64.deb?__gda__=1565340535_8a441281b695e09f7a32742b0465593e\ndpkg -i /tmp/citrix.deb\n\n# install docker\napt-get update\napt-get install \\\n apt-transport-https \\\n ca-certificates \\\n curl \\\n gnupg-agent \\\n software-properties-common\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\napt-key fingerprint 0EBFCD88\nadd-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\napt-get update\napt-get install docker-ce docker-ce-cli containerd.io\ngroupadd docker\nusermod -aG docker ${username}\n" }, { "alpha_fraction": 0.5699999928474426, "alphanum_fraction": 0.5699999928474426, "avg_line_length": 15.833333015441895, "blob_id": "178fab7fefcb8a45c7656614f0838e9093de84a2", "content_id": "3d78fa87a038d455c2e655c0c420bf77ba26c057", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 100, "license_type": "permissive", "max_line_length": 56, "num_lines": 6, "path": "/mute.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\nif [[ \"muted\" = \"$(pamixer --get-volume-human)\" ]]; then\n\techo \"M:\"\nelse\n\techo \"VOL:\"\nfi" }, { "alpha_fraction": 0.7177121639251709, "alphanum_fraction": 0.7177121639251709, "avg_line_length": 29.11111068725586, "blob_id": "68b9adf01d00403402c504b964520135c2fd0958", "content_id": "3ce4beec07ef0fb6386c132066299347c79e71af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 542, "license_type": "permissive", "max_line_length": 74, "num_lines": 18, "path": "/backup-sync.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#written by Philip Woldhek\n\nwhile inotifywait -r /home/philip/school/*; do\n rsync -avu --delete /home/philip/school/ /mnt/backup/school-backup\ndone &\n\nwhile inotifywait -r /home/philip/pictures/*; do\n rsync -avu --delete /home/philip/pictures/ /mnt/backup/pictures-backup\ndone &\n\nwhile inotifywait -r /home/philip/scripts/*; do\n rsync -avu --delete /home/philip/scripts/ /mnt/backup/scripts-backup\ndone &\n\nwhile inotifywait -r /home/philip/videos/*; do\n rsync -avu --delete /home/philip/videos/ /mnt/backup/videos-backup\ndone\n" }, { "alpha_fraction": 0.5561959743499756, "alphanum_fraction": 0.5965417623519897, "avg_line_length": 23.714284896850586, "blob_id": "017e6450c26edcae8d2303d0a128a739bcbe57a5", "content_id": "93138f2984607cdb1940b13a8ac5e0c5384b5b00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 347, "license_type": "permissive", "max_line_length": 146, "num_lines": 14, "path": "/mpdmenu.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#written by philip woldhek\n\nDMENU=${DMENU:-dmenu}\ncmd_list=\"remote local\"\n\ncmd=\"$(echo $cmd_list | sed 's/ /\\n/g' | ${DMENU} -p ncmpcpp -nf '#FF0000' -nb '#31004a' -sf '#ffffff' -sb '#ab00ff' -fn 'terminus:pixelsize=12')\"\n[[ -z $cmd ]] && exit 1\n\nif [[ $cmd = local ]]; then\n urxvt -e ncmpcpp --host=localhost\nelse\n urxvt -e ncmpcpp\nfi\n\n" }, { "alpha_fraction": 0.6572238206863403, "alphanum_fraction": 0.663361668586731, "avg_line_length": 34.31666564941406, "blob_id": "b9991b31650614274b61e51d012a55a4fe3b0cb1", "content_id": "36c0705eab9c3cf2339d12d6d2518012d95cc920", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2118, "license_type": "permissive", "max_line_length": 107, "num_lines": 60, "path": "/create_docker_git_repo.py", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "from github import Github\nfrom jenkins import Jenkins\n\ngit_access_token = \"\"\njenkins_server_url = \"\njenkins_username = \"\"\njenkins_password = \"\"\n\ngit_repo_name = \"docker-test_test\"\ndocker_repo_name = git_repo_name.replace(\"_\", \"-\").replace(\"docker-\", \"\")\njenkins_job_name = \"docker-build-{0}\".format(git_repo_name.replace(\"docker-\", \"\"))\n\n\ndef create_jenkins_job_xml(github_repo_url):\n return \"\"\" \\\n <?xml version='1.0' encoding='UTF-8'?>\n <flow-definition plugin=\"[email protected]\">\n <description></description>\n <keepDependencies>false</keepDependencies>\n <properties/>\n <definition class=\"org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition\" plugin=\"[email protected]\">\n <scm class=\"hudson.plugins.git.GitSCM\" plugin=\"[email protected]\">\n <configVersion>2</configVersion>\n <userRemoteConfigs>\n <hudson.plugins.git.UserRemoteConfig>\n <url>{0}</url>\n </hudson.plugins.git.UserRemoteConfig>\n </userRemoteConfigs>\n <branches>\n <hudson.plugins.git.BranchSpec>\n <name>*/master</name>\n </hudson.plugins.git.BranchSpec>\n </branches>\n <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>\n <submoduleCfg class=\"list\"/>\n <extensions/>\n </scm>\n <scriptPath>Jenkinsfile</scriptPath>\n </definition>\n <triggers/>\n </flow-definition> \\\n \"\"\".format(github_repo_url)\n\n\ndef create_github_repo(repo_name, access_token):\n g = Github(access_token)\n authenticated_user = g.get_user()\n repo = authenticated_user.create_repo(repo_name, private=False)\n return repo.clone_url\n\n\ndef create_jenkins_job(name, github_clone_url, jenkins_url, user, passwd):\n job_xml = create_jenkins_job_xml(github_clone_url)\n jenkins_server = Jenkins(jenkins_url, username=user, password=passwd)\n jenkins_server.create_job(name, job_xml)\n\n\nif __name__ == \"__main__\":\n clone_url = create_github_repo(git_repo_name, git_access_token)\n create_jenkins_job(jenkins_job_name, clone_url, jenkins_server_url, jenkins_username, jenkins_password)" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 36.33333206176758, "blob_id": "af6f7e85135802671da14ca891a4de830860715c", "content_id": "dc223cc2c2896db9d032bed23bb127d77d2a2251", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 112, "license_type": "permissive", "max_line_length": 98, "num_lines": 3, "path": "/start-languagetool-server.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\njava -cp /opt/language-tool/languagetool-server.jar org.languagetool.server.HTTPServer --port 8081\n" }, { "alpha_fraction": 0.5585696697235107, "alphanum_fraction": 0.6578298211097717, "avg_line_length": 35.06666564941406, "blob_id": "87c4cf185dc662d3d2f0b77d4a5564ab3e8b4057", "content_id": "89b31d5ef56d27b53ed556476b21131ad3a4a312", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1622, "license_type": "permissive", "max_line_length": 154, "num_lines": 45, "path": "/monlayout.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#written by philip woldhek\n\nDMENU=${DMENU:-dmenu}\ncmd_list=\"thuis big solo exit\"\n\nfunction thuis(){\n\txrandr --output eDP1 --primary --mode 1920x1080 --pos 0x1080 \\\n\t --rotate normal --output DP1 --off --output DP2 --off \\\n\t --output HDMI1 --mode 1920x1080 --pos 1920x0 --rotate normal \\\n\t --output HDMI2 --mode 1920x1080 --pos 0x0 --rotate normal --output VIRTUAL1 --off\n}\n\nfunction bigscreen(){\n\txrandr --output eDP1 --primary --mode 1920x1080 --pos 320x1440 \\\n\t--rotate normal --output DP1 --off --output DP2 --off --output HDMI1 \\\n\t--off --output HDMI2 --mode 2560x1440 --pos 0x0 --rotate normal --output VIRTUAL1 --off\n\tsleep 1\n\txrandr --output eDP1 --off --output DP1 --off --output DP2 --off --output HDMI1 \\\n\t--off --output HDMI2 --mode 2560x1440 --pos 0x0 --rotate normal --output VIRTUAL1 --off\n\tsleep 1\n\txrandr --output eDP1 --primary --mode 1920x1080 --pos 320x1440 \\\n\t--rotate normal --output DP1 --off --output DP2 --off --output HDMI1 \\\n\t--off --output HDMI2 --mode 2560x1440 --pos 0x0 --rotate normal --output VIRTUAL1 --off\n\tfeh --bg-scale pics/wallpaper\\ slideshow/2560x1440/space.jpg\n}\n\nfunction solo(){\n\txrandr --output eDP1 --primary --mode 1920x1080 --pos 0x0 --rotate normal \\\n\t--output DP1 --off --output DP2 --off --output HDMI1 --off --output HDMI2 --off --output VIRTUAL1 --off\n}\n\ncmd=\"$(echo $cmd_list | sed 's/ /\\n/g' | ${DMENU} -p 'Are you sure?' -nf '#FF0000' -nb '#31004a' -sf '#ffffff' -sb '#ab00ff' -fn 'terminus:pixelsize=12')\"\n\n[[ -z $cmd ]] && exit 1\n\nif [[ $cmd = thuis ]]; then\n thuis\nelif [[ $cmd = big ]]; then\n\tbigscreen\nelif [[ $cmd = solo ]]; then\n\tsolo\nelse\n exit 0\nfi" }, { "alpha_fraction": 0.6344085931777954, "alphanum_fraction": 0.6344085931777954, "avg_line_length": 28.0625, "blob_id": "2c0af4ddec45f0bc6ffc6fe8e1bdf2cfd5401631", "content_id": "bc4dd5997b92d793c102cd2c194fc88d2bd877cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 465, "license_type": "permissive", "max_line_length": 58, "num_lines": 16, "path": "/unpacker.py", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "from pathlib import Path\nfrom zipfile import ZipFile\n\n\ndef unpacker(target_folder):\n for file in target_folder.iterdir():\n file_name = file.stem.replace(\"_full\", \"\")\n with ZipFile(file, \"r\") as zip_file:\n zip_file.extractall(target_folder)\n rename_file = Path(target_folder, \"photos\")\n rename_file.rename(Path(target_folder, file_name))\n\n\nif __name__ == \"__main__\":\n target = Path(\"\")\n unpacker(target_folder=target)\n" }, { "alpha_fraction": 0.5142857432365417, "alphanum_fraction": 0.6095238327980042, "avg_line_length": 20, "blob_id": "5b1b8b52235ef93a942aafb99be5e55c5cf1436a", "content_id": "1e03685fe8907d1e07f89cd6494167dbe83f70be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 105, "license_type": "permissive", "max_line_length": 38, "num_lines": 5, "path": "/proxy_check.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "if nc -z $1 $2; then\n exec nc $1 $2 # connect directly\nelse\n exec ssh m1006 nc $1 $2 # use proxy\nfi\n" }, { "alpha_fraction": 0.6368776559829712, "alphanum_fraction": 0.6481174826622009, "avg_line_length": 60.18987274169922, "blob_id": "09b9c7e14aede640a79e3be22c17c4b915891171", "content_id": "2cb65261dae46706b2643e97b4959bce41ba792e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 14502, "license_type": "permissive", "max_line_length": 151, "num_lines": 237, "path": "/fix_xubuntu_slim.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/bash\n\n# install from package manager\n# add codium repo\nwget -qO - https://gitlab.com/paulcarroty/vscodium-deb-rpm-repo/raw/master/pub.gpg | sudo apt-key add -\necho 'deb https://gitlab.com/paulcarroty/vscodium-deb-rpm-repo/raw/repos/debs/ vscodium main' | sudo tee --append /etc/apt/sources.list.d/vscodium.list\n# add stack repo\necho 'deb http://mirror.transip.net/stack/software/deb/Ubuntu_18.04/ ./' | sudo tee /etc/apt/sources.list.d/stack-client.list\nwget -O - https://mirror.transip.net/stack/release.key | sudo apt-key add -\n# install packages\nsudo apt update\nsudo apt install -y ranger zsh git tmux rxvt-unicode xfonts-terminus neofetch wget stack-client codium \\\n # docker deps\n apt-transport-https ca-certificates curl gnupg-agent software-properties-common\nsudo apt remove -y pidgin sgt-launcher sgt-puzzles gnome-sudoku gnome-mines xfburn onboard mousepad remmina\nsudo apt autoremove -y\n\n# install docker\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\nsudo apt-key fingerprint 0EBFCD88\n# sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\nsudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu disco stable\"\nsudo apt-get update\nsudo apt-get install docker-ce docker-ce-cli containerd.io\nsudo groupadd docker\nsudo usermod -aG docker $USER\n\n# download scripts\nmkdir ~/Devel\ngit clone [email protected]:11philip22/scripts.git ~/Devel/scripts\n\n# install oh-my-zsh\nsh -c \"$(wget -O- https://raw.githubusercontent.com/11philip22/oh-my-zsh/master/tools/install.sh)\"\nrm ~/.zshrc\nln -s ~/Devel/scripts/zshrc ~/.zshrc\n\n# download wallpapers\nwget --output-document=/usr/share/xfce4/backdrops/wallpaper1.png https://i.imgur.com/kfHKnjt.png\nwget --output-document=/usr/share/xfce4/backdrops/wallpaper2.jpg https://i.imgur.com/035woPC.jpg\n\n# add keybinds\ncat <<EOF > ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<channel name=\"xfce4-keyboard-shortcuts\" version=\"1.0\">\n <property name=\"commands\" type=\"empty\">\n <property name=\"default\" type=\"empty\">\n <property name=\"&lt;Alt&gt;F1\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F2\" type=\"empty\">\n <property name=\"startup-notify\" type=\"empty\"/>\n </property>\n <property name=\"&lt;Alt&gt;F3\" type=\"empty\">\n <property name=\"startup-notify\" type=\"empty\"/>\n </property>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Delete\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;l\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;t\" type=\"empty\"/>\n <property name=\"XF86Display\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;p\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;Escape\" type=\"empty\"/>\n <property name=\"XF86WWW\" type=\"empty\"/>\n <property name=\"XF86Mail\" type=\"empty\"/>\n <property name=\"Print\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Escape\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;Print\" type=\"empty\"/>\n <property name=\"&lt;Shift&gt;Print\" type=\"empty\"/>\n <property name=\"XF86HomePage\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;w\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;m\" type=\"empty\"/>\n <property name=\"XF86Explorer\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;f\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;F1\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;t\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;r\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;e\" type=\"empty\"/>\n <property name=\"XF86Calculator\" type=\"empty\"/>\n <property name=\"XF86Music\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;1\" type=\"empty\"/>\n <property name=\"XF86Messenger\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;2\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;3\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;4\" type=\"empty\"/>\n </property>\n <property name=\"custom\" type=\"empty\">\n <property name=\"&lt;Alt&gt;F3\" type=\"empty\">\n <property name=\"startup-notify\" type=\"bool\" value=\"true\"/>\n </property>\n <property name=\"&lt;Alt&gt;F2\" type=\"empty\">\n <property name=\"startup-notify\" type=\"bool\" value=\"true\"/>\n </property>\n <property name=\"override\" type=\"bool\" value=\"true\"/>\n <property name=\"&lt;Alt&gt;Return\" type=\"string\" value=\"exo-open --launch TerminalEmulator\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;d\" type=\"string\" value=\"exo-open --launch FileManager\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;m\" type=\"string\" value=\"exo-open --launch MailReader\"/>\n <property name=\"&lt;Alt&gt;d\" type=\"string\" value=\"xfrun4\">\n <property name=\"startup-notify\" type=\"bool\" value=\"true\"/>\n </property>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;c\" type=\"string\" value=\"xflock4\"/>\n <property name=\"Print\" type=\"string\" value=\"xfce4-screenshooter -r\"/>\n <property name=\"&lt;Alt&gt;p\" type=\"string\" value=\"xfce4-display-settings --minimal\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;w\" type=\"string\" value=\"/usr/bin/google-chrome-stable\"/>\n </property>\n </property>\n <property name=\"xfwm4\" type=\"empty\">\n <property name=\"default\" type=\"empty\">\n <property name=\"&lt;Alt&gt;Insert\" type=\"empty\"/>\n <property name=\"Escape\" type=\"empty\"/>\n <property name=\"Left\" type=\"empty\"/>\n <property name=\"Right\" type=\"empty\"/>\n <property name=\"Up\" type=\"empty\"/>\n <property name=\"Down\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;Tab\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;&lt;Shift&gt;Tab\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;Delete\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Down\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Left\" type=\"empty\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;Page_Down\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F4\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F6\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F7\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F8\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F9\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F10\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F11\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F12\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Shift&gt;&lt;Alt&gt;Left\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;End\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Home\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Shift&gt;&lt;Alt&gt;Right\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Shift&gt;&lt;Alt&gt;Up\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_1\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_2\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_3\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_4\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_5\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_6\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_7\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_8\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_9\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;space\" type=\"empty\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;Page_Up\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Right\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;d\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Up\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;Tab\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F1\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F2\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F3\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F4\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F5\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F6\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F7\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F8\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F9\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F10\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F11\" type=\"empty\"/>\n <property name=\"&lt;Primary&gt;F12\" type=\"empty\"/>\n <property name=\"&lt;Alt&gt;F5\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;KP_1\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;Down\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;KP_3\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;Left\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;Right\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;KP_7\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;Up\" type=\"empty\"/>\n <property name=\"&lt;Super&gt;KP_9\" type=\"empty\"/>\n </property>\n <property name=\"custom\" type=\"empty\">\n <property name=\"&lt;Alt&gt;Insert\" type=\"string\" value=\"add_workspace_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_3\" type=\"string\" value=\"move_window_workspace_3_key\"/>\n <property name=\"&lt;Primary&gt;F2\" type=\"string\" value=\"workspace_2_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Down\" type=\"string\" value=\"down_workspace_key\"/>\n <property name=\"&lt;Super&gt;Down\" type=\"string\" value=\"tile_down_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_9\" type=\"string\" value=\"move_window_workspace_9_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Shift&gt;&lt;Alt&gt;Left\" type=\"string\" value=\"move_window_left_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;End\" type=\"string\" value=\"move_window_next_workspace_key\"/>\n <property name=\"&lt;Primary&gt;F8\" type=\"string\" value=\"workspace_8_key\"/>\n <property name=\"&lt;Primary&gt;F10\" type=\"string\" value=\"workspace_10_key\"/>\n <property name=\"Right\" type=\"string\" value=\"right_key\"/>\n <property name=\"Down\" type=\"string\" value=\"down_key\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;Page_Down\" type=\"string\" value=\"lower_window_key\"/>\n <property name=\"&lt;Super&gt;Right\" type=\"string\" value=\"tile_right_key\"/>\n <property name=\"&lt;Primary&gt;F9\" type=\"string\" value=\"workspace_9_key\"/>\n <property name=\"&lt;Alt&gt;Tab\" type=\"string\" value=\"cycle_windows_key\"/>\n <property name=\"Left\" type=\"string\" value=\"left_key\"/>\n <property name=\"&lt;Super&gt;Up\" type=\"string\" value=\"tile_up_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Right\" type=\"string\" value=\"right_workspace_key\"/>\n <property name=\"&lt;Primary&gt;F11\" type=\"string\" value=\"workspace_11_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_5\" type=\"string\" value=\"move_window_workspace_5_key\"/>\n <property name=\"&lt;Primary&gt;F6\" type=\"string\" value=\"workspace_6_key\"/>\n <property name=\"&lt;Alt&gt;Delete\" type=\"string\" value=\"del_workspace_key\"/>\n <property name=\"&lt;Super&gt;Tab\" type=\"string\" value=\"switch_window_key\"/>\n <property name=\"&lt;Super&gt;KP_7\" type=\"string\" value=\"tile_up_left_key\"/>\n <property name=\"&lt;Super&gt;Left\" type=\"string\" value=\"tile_left_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;d\" type=\"string\" value=\"show_desktop_key\"/>\n <property name=\"&lt;Primary&gt;F1\" type=\"string\" value=\"workspace_1_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_4\" type=\"string\" value=\"move_window_workspace_4_key\"/>\n <property name=\"&lt;Primary&gt;F12\" type=\"string\" value=\"workspace_12_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Shift&gt;&lt;Alt&gt;Right\" type=\"string\" value=\"move_window_right_key\"/>\n <property name=\"Up\" type=\"string\" value=\"up_key\"/>\n <property name=\"&lt;Primary&gt;F4\" type=\"string\" value=\"workspace_4_key\"/>\n <property name=\"&lt;Alt&gt;F11\" type=\"string\" value=\"fullscreen_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_6\" type=\"string\" value=\"move_window_workspace_6_key\"/>\n <property name=\"&lt;Alt&gt;&lt;Shift&gt;Tab\" type=\"string\" value=\"cycle_reverse_windows_key\"/>\n <property name=\"Escape\" type=\"string\" value=\"cancel_key\"/>\n <property name=\"&lt;Alt&gt;space\" type=\"string\" value=\"popup_menu_key\"/>\n <property name=\"&lt;Super&gt;KP_1\" type=\"string\" value=\"tile_down_left_key\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;Page_Up\" type=\"string\" value=\"raise_window_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_1\" type=\"string\" value=\"move_window_workspace_1_key\"/>\n <property name=\"&lt;Alt&gt;F12\" type=\"string\" value=\"above_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_7\" type=\"string\" value=\"move_window_workspace_7_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Home\" type=\"string\" value=\"move_window_prev_workspace_key\"/>\n <property name=\"&lt;Super&gt;KP_9\" type=\"string\" value=\"tile_up_right_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_2\" type=\"string\" value=\"move_window_workspace_2_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Left\" type=\"string\" value=\"left_workspace_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Shift&gt;&lt;Alt&gt;Up\" type=\"string\" value=\"move_window_up_key\"/>\n <property name=\"&lt;Alt&gt;F8\" type=\"string\" value=\"stick_window_key\"/>\n <property name=\"&lt;Primary&gt;F5\" type=\"string\" value=\"workspace_5_key\"/>\n <property name=\"&lt;Primary&gt;F7\" type=\"string\" value=\"workspace_7_key\"/>\n <property name=\"&lt;Primary&gt;F3\" type=\"string\" value=\"workspace_3_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;KP_8\" type=\"string\" value=\"move_window_workspace_8_key\"/>\n <property name=\"&lt;Super&gt;KP_3\" type=\"string\" value=\"tile_down_right_key\"/>\n <property name=\"&lt;Primary&gt;&lt;Alt&gt;Up\" type=\"string\" value=\"up_workspace_key\"/>\n <property name=\"override\" type=\"bool\" value=\"true\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;q\" type=\"string\" value=\"close_window_key\"/>\n <property name=\"&lt;Alt&gt;f\" type=\"string\" value=\"maximize_window_key\"/>\n <property name=\"&lt;Alt&gt;v\" type=\"string\" value=\"maximize_vert_key\"/>\n <property name=\"&lt;Alt&gt;h\" type=\"string\" value=\"maximize_horiz_key\"/>\n <property name=\"&lt;Shift&gt;&lt;Alt&gt;h\" type=\"string\" value=\"hide_window_key\"/>\n </property>\n </property>\n <property name=\"providers\" type=\"array\">\n <value type=\"string\" value=\"commands\"/>\n <value type=\"string\" value=\"xfwm4\"/>\n </property>\n</channel>\nEOF\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.625, "avg_line_length": 28.85714340209961, "blob_id": "ce403ab01dc05044863cf8752c5f1c1f713db3ec", "content_id": "7647863328c54e19aaa16b71e97b47939b563085", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 208, "license_type": "permissive", "max_line_length": 83, "num_lines": 7, "path": "/check_jenkins_plugins.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nJENKINSHOME=~/.jenkins\n\nfor output in $(ls ${JENKINSHOME}/plugins/ | grep \".jpi$\" | cut -f 1 -d '.' ); do\n find ${JENKINSHOME}/jobs/ -name config.xml | xargs grep \"${output}\" 2>/dev/null\ndone" }, { "alpha_fraction": 0.5650224089622498, "alphanum_fraction": 0.5784753561019897, "avg_line_length": 19.272727966308594, "blob_id": "c92a62b511bbc1402e2aae9be18f8cd3014c7719", "content_id": "5ddfe1a96c8d85d5a99a19f4198dc34609721994", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 223, "license_type": "permissive", "max_line_length": 69, "num_lines": 11, "path": "/vpn.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# writen by Philip Woldhek\n\npid=$(ps cax | grep sshuttle | awk '{print $1;}')\n\nif [ \"sshuttle\" = \"$(ps cax | grep sshuttle | awk '{print $NF}')\" ]\n then\n kill -SIGTERM $pid\n else\n sshuttle --dns -r name@ip 0/0\nfi\n" }, { "alpha_fraction": 0.6976292133331299, "alphanum_fraction": 0.7038476467132568, "avg_line_length": 25.484535217285156, "blob_id": "bf41b6ee35ba0148e9892a9db937a6bc12e0ab61", "content_id": "68cb478c5aba04c1793949df0ec6e29faaf11aa1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2573, "license_type": "permissive", "max_line_length": 136, "num_lines": 97, "path": "/ssmtp-script.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -eu\nemailadres=\"emailadres\"\n\n\nif [[ $EUID -ne 0 ]]; then\n echo \"Voer dit script uit met SUDO rechten\" 1>&2\n exit 1\nfi\n\nwhile true; do\necho \"Uw computer moet uptodate zijn voor het installeren van mailutils en ssmtp\" \necho \"\"\nread -p \"Is uw computer up-to-date? (y/n)\" yn\n case $yn in \n\t[Yy] ) break;;\n\t[Nn] ) echo \"Uw systeem wordt geupdate.\" && sleep 3 && sudo apt update && break ;;\n * ) echo \"Gelieve antoorden met y of n \"\n esac\ndone\n\n\necho \"controleren of ssmtp en mailutils geinstalleerd zijn\"\nwhile true; do\nif sudo dpkg -s ssmtp | grep \"Status: install ok installed\"\n\nthen read -p \"ssmtp is reeds geinstalleerd. Wilt u een backup maken van de huidige configuratie? (y/n)\" yn\n case $yn in\n [Yy] ) echo \"Backup maken van huidige ssmtp configuratie\" && sudo mv /etc/ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf.orig && break;;\n [Nn] ) break;;\n * ) echo \"gelieve antwoorden met y of n\"\n esac\n\nelse echo \"ssmtp en mailutils worden gedownload\" && \\\n\t sleep 2 && \\\n\t sudo apt-get install -y ssmtp mailutils >/dev/zero && break\nfi\ndone\n\nsleep 2\n\necho \"ssmtp configuratie\"\n\nread -p \"voer uw gmail adres in : \" -i \"$emailadres\" emailadres\nwhile true; do\nread -s -p \"wachtwoord: \" wachtwoord\necho\nread -s -p \"wachtoord opnieuw: \" wachtwoord2\necho\n[ \"$wachtwoord\" = \"$wachtwoord2\" ] && break\necho \"wachtwoord komt niet overeen\"\ndone \n\n#read -p \"voer uw wachtwoord in voor email adres $emailadres : \" -i \"$wachtwoord\" -s wachtwoord\n \necho \"\n# Config file for sSMTP sendmail\n#\n# The person who gets all mail for userids < 1000\n# Make this empty to disable rewriting.\n#root=postmaster\nroot=$emailadres\n# The place where the mail goes. The actual machine name is required no\n# MX records are consulted. Commonly mailhosts are named mail.domain.com\n#mailhub=mail\nmailhub=smtp.gmail.com:587\n\nAuthUser=$emailadres\nAuthPass=$wachtwoord\nUseTLS=YES\nUseSTARTTLS=YES\n\n\n# Where will the mail seem to come from?\n#rewriteDomain=\nrewriteDomain=gmail.com\n\n# The full hostname\n#hostname=MyMediaServer.home\nhostname=$HOSTNAME\n\n# Are users allowed to set their own From: address?\n# YES - Allow the user to specify their own From: address\n# NO - Use the system generated From: address\nFromLineOverride=YES \" > /etc/ssmtp/ssmtp.conf\n\n#verstuur mail met de volgende commando's:\necho \"\" \necho \"\" \n\n#echo \"Dit is de inhoud van de mail\" | mail -s \"onderwerp van de mail\" [email protected] \necho \"testmail wordt verzonden naar $emailadres\"\n\necho \"Dit is de inhoud van de mail\" | mail -s \"onderwerp van de mail\" $emailadres\n#echo \"klaar!!\"\nexit\n\n \n\n" }, { "alpha_fraction": 0.5836299061775208, "alphanum_fraction": 0.608540952205658, "avg_line_length": 19, "blob_id": "df3eac2ec01663edfb5f2ff1f01e861aa541a2bd", "content_id": "1391e87e4afcfc3eb3cc09d5152dfc587d87565c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 281, "license_type": "permissive", "max_line_length": 86, "num_lines": 14, "path": "/mpctoggle.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#written by Philip Woldhek\n\nserverip=$(cat /home/philip/scripts/nicetryfbi.txt | grep serverip | awk '{print $2}')\n\nif [ \"[playing]\" = \"$(mpc | sed -n 2p | awk '{print $1;}')\" ]\n then\n mpc stop\n mpc clear\n else\n mpc clear\n mpc add http://$serverip:8000\n mpc play\nfi\n\n" }, { "alpha_fraction": 0.6132701635360718, "alphanum_fraction": 0.6227487921714783, "avg_line_length": 29.14285659790039, "blob_id": "6852295ebeb0b444c5b37e8699fa3638983e8efe", "content_id": "0fb30ac32e734c4c71e1d917b9c46e1166027bab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1055, "license_type": "permissive", "max_line_length": 80, "num_lines": 35, "path": "/mv_and_rename.py", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "from os import getcwd\nfrom os import listdir\nfrom os import rmdir\nfrom pathlib import Path\nfrom shutil import move\n\ncurrent_location = Path(getcwd())\n\npictures = []\nfor folder in current_location.iterdir():\n if folder.is_dir():\n for picture in folder.iterdir():\n pictures.append(picture)\n\nfor picture in pictures:\n new_name = picture.name\n counter = 1\n while True:\n test_path = Path(current_location, new_name)\n if test_path.exists():\n new_name = \"{0}{1}{2}\".format(picture.stem, counter, picture.suffix)\n print(\"{0} exists. trying: {1}\".format(test_path.name, new_name))\n counter += 1\n else:\n break\n\n new_location = Path(current_location, new_name)\n print(\"moving: {0} to {1}\".format(picture, new_location))\n move(str(picture), str(new_location))\n\nfor folder in current_location.iterdir():\n if folder.is_dir():\n if not listdir(str(folder)):\n print(\"Folder: {0} is empty. Deleting!\".format(folder))\n rmdir(str(folder))\n" }, { "alpha_fraction": 0.6824817657470703, "alphanum_fraction": 0.7189781069755554, "avg_line_length": 38.14285659790039, "blob_id": "53d20f3cc951d37455d17a3673d8d0df6e959635", "content_id": "aa0a8f695127976dee569f4e8d0b6ea6a95a4136", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 274, "license_type": "permissive", "max_line_length": 94, "num_lines": 7, "path": "/docker-ufw-fix.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho \"{\\\"iptables\\\": false}\" > /etc/docker/daemon.json\nsed -i -e 's/DEFAULT_FORWARD_POLICY=\"DROP\"/DEFAULT_FORWARD_POLICY=\"ACCEPT\"/g' /etc/default/ufw\nufw reload\niptables -t nat -A POSTROUTING ! -o docker0 -s 172.17.0.0/16 -j MASQUERADE\nsystemctl restart docker\n" }, { "alpha_fraction": 0.6633416414260864, "alphanum_fraction": 0.6783042550086975, "avg_line_length": 26.65517234802246, "blob_id": "5e238a593db9ac3d4e81a0a57fb45a92c83fc8b7", "content_id": "04d15a7a9af2583e0702286e207be088491fbbf8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 802, "license_type": "permissive", "max_line_length": 99, "num_lines": 29, "path": "/screenshot.py", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "import os\nimport dmenu\nimport pyimgur\n\ndef upload():\n\tclient_id = \"8e98531fa1631f6\"\n\tPATH = \"/tmp/screenshot.png\"\n\tim = pyimgur.Imgur(client_id)\n\tuploaded_image = im.upload_image(PATH, title=\"Uploaded with PyImgur\")\n\tprint(uploaded_image.link)\n\tos.system(\"rm /tmp/screenshot.png\")\n\ndef save_local():\n\tsave_name = dmenu.show([''], prompt='type the filename (widout extension)')\n\tos.system(\"mv /tmp/screenshot.png /home/philip/pics/screenshots/\" + save_name + \".png\")\n\nos.system(\"gnome-screenshot -a -f /tmp/screenshot.png 2> /dev/null\")\n\nif dmenu.show(['local', 'imgur']) == 'imgur':\n\ttry:\n\t\tupload()\n\texcept:\n\t\tif dmenu.show(['yes', 'no'], prompt='could not upload to upload to Imgur! save local?') == 'yes':\n\t\t\tsave_local()\n\t\telse:\n\t\t\tos.system(\"rm /tmp/screenshot.png\")\n\t\t\texit()\nelse:\n\tsave_local()\n" }, { "alpha_fraction": 0.558521568775177, "alphanum_fraction": 0.5893223881721497, "avg_line_length": 18.440000534057617, "blob_id": "b2392835d46ebfb10ac956ae9b2b1cf997524cf6", "content_id": "36d1f783b58f82ded4a1e25d5862c6d46f0c6f88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 487, "license_type": "permissive", "max_line_length": 154, "num_lines": 25, "path": "/shutdown.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#written by philip woldhek\n\nDMENU=${DMENU:-dmenu}\ncmd_list=\"no yes\"\n\ncmd=\"$(echo $cmd_list | sed 's/ /\\n/g' | ${DMENU} -p 'Are you sure?' -nf '#FF0000' -nb '#31004a' -sf '#ffffff' -sb '#ab00ff' -fn 'terminus:pixelsize=12')\"\n\nfunction safeshutdown() {\n if pgrep -il \"vmware-vmx\" &>/dev/null;\n then\n notify-send \"vm is running!\"\n else\n docker stop $(docker ps -aq)\n shutdown now\n fi\n}\n\n[[ -z $cmd ]] && exit 1\n\nif [[ $cmd = yes ]]; then\n safeshutdown\nelse\n exit 0\nfi\n\n" }, { "alpha_fraction": 0.7327935099601746, "alphanum_fraction": 0.7408906817436218, "avg_line_length": 17.923076629638672, "blob_id": "743dd50ba7fa31573b72f12b065e361b3471d6c2", "content_id": "c76bd8673a89e200cec4b8045c021ee9997dee73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 247, "license_type": "permissive", "max_line_length": 54, "num_lines": 13, "path": "/start-bspwm", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nsxhkd &\nexec bspwm\n\ncompton &\nlxpolkit &\nnm-applet &\nusbguard-applet-qt &\nstack-client &\n/usr/lib/notification-daemon-1.0/notification-daemon &\nfeh --bg-fill /home/philip/.wallpaper.jpg\n/home/philip/.config/polybar/launch.sh\n\n" }, { "alpha_fraction": 0.5231788158416748, "alphanum_fraction": 0.5298013091087341, "avg_line_length": 12.818181991577148, "blob_id": "7f994ce32a96a11a02b3b446e0338513645445e5", "content_id": "f19c33cd338389f71d1891cb8c3524affdee3367", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 151, "license_type": "permissive", "max_line_length": 30, "num_lines": 11, "path": "/autogit.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [[ $# -eq 0 ]]; then\n msg=$(date '+%F_%H:%M:%S')\nelse\n msg=$@\nfi\n\ngit add .\ngit commit -m \"${msg}\"\ngit push origin master" }, { "alpha_fraction": 0.574018120765686, "alphanum_fraction": 0.5810674428939819, "avg_line_length": 29.121212005615234, "blob_id": "6f73da53f506632bdf7e8878157c43133bb95977", "content_id": "fb0e12e7f0551d68358c86d92d5a73370b5326e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 993, "license_type": "permissive", "max_line_length": 83, "num_lines": 33, "path": "/deploy-scripts.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# if [[ \"$EUID\" -ne 0 ]]; then\n# echo \"Please run as root\"\n# exit\n# fi\n\ninstall_dir=\"$HOME/.local/bin\"\n\nif [[ ! \":$PATH:\" == *\":${install_dir}:\"* ]]; then\n echo \"${install_dir} Is not in your PATH. Exiting\"\n exit 1\nfi\n\nif [[ $1 = \"clean\" ]]; then\n rm \"${install_dir}\"/vpn\n rm \"${install_dir}\"/autogit\n # rm \"${install_dir}\"/kpndisplay\n rm \"${install_dir}\"/fix_xubuntu_slim\n # rm \"${install_dir}\"/solodisplay\n\nelif [[ $1 = \"install\" ]]; then\n script_root=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n \n ln -s \"${script_root}\"/sshuttle.py \"${install_dir}\"/vpn\n ln -s \"${script_root}\"/autogit.sh \"${install_dir}\"/autogit\n # ln -s \"${script_root}\"/kpndisplay.sh \"${install_dir}\"/kpndisplay\n ln -s \"${script_root}\"/fix_xubuntu_slim.sh \"${install_dir}\"/fix_xubuntu_slim\n # ln -s \"${script_root}\"/solodisplay.sh \"${install_dir}\"/solodisplay\n\nelse\n echo \"Usage: sudo ./deploy-scripts.sh install/clean\"\nfi" }, { "alpha_fraction": 0.5598591566085815, "alphanum_fraction": 0.577464759349823, "avg_line_length": 17.933332443237305, "blob_id": "7d62f7bafb652eb4b13ce16ab88734fd2502ac8b", "content_id": "163fe9d27c8f9fab0c3627d16159450462e6bd32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 284, "license_type": "permissive", "max_line_length": 77, "num_lines": 15, "path": "/sshuttle.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor arg in \"$@\"\ndo\n\tif [ \"$arg\" == \"start\" ]\n\tthen\n\t\tip=$(cat /home/philip/scripts/nicetryfbi.txt | grep wan | awk '{print $2}')\n\t\tsshuttle --dns -x $ip -r philip@$ip 0/0 --python=python3 -D\n\tfi\n\tif [ \"$arg\" == \"stop\" ]\n\tthen\n\t\tkill $(pgrep sshuttle) \n\t\texit 0\n\tfi\ndone\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 6.333333492279053, "blob_id": "32e9b200dd2eda6557aacfbc69f6ab793b9f1b3f", "content_id": "c4766f4ce2937820b23bb94c2d1e0347b6b3338e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 22, "license_type": "permissive", "max_line_length": 11, "num_lines": 3, "path": "/sublime-tab.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsubl3 -n\n" }, { "alpha_fraction": 0.6926751732826233, "alphanum_fraction": 0.743630588054657, "avg_line_length": 51.41666793823242, "blob_id": "68c500410ca0f22fcae002a412effef6f0c13a44", "content_id": "cc2e8c82725cf9fb05c623ca23ff020ec6433ba2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 628, "license_type": "permissive", "max_line_length": 131, "num_lines": 12, "path": "/install_vmware.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#! /usr/bin/bash\n\necho \"Download: https://www.vmware.com/go/getWorkstation-linux\"\necho \"Install: sudo bash vmware.bundle\"\n\nsudo vmware-modconfig --console --install-all\n\nopenssl req -new -x509 -newkey rsa:2048 -keyout VMWARE15.priv -outform DER -out VMWARE15.der -nodes -days 36500 -subj \"/CN=VMWARE/\"\nsudo /usr/src/linux-headers-$(uname -r)/scripts/sign-file sha256 ./VMWARE15.priv ./VMWARE15.der $(modinfo -n vmmon)\nsudo /usr/src/linux-headers-$(uname -r)/scripts/sign-file sha256 ./VMWARE15.priv ./VMWARE15.der $(modinfo -n vmnet)\ntail $(modinfo -n vmmon) | grep \"Module signature appended\"\nsudo mokutil --import VMWARE15.der" }, { "alpha_fraction": 0.5133470296859741, "alphanum_fraction": 0.5287474393844604, "avg_line_length": 19.723403930664062, "blob_id": "e07ca1a2c7695258ecebdb19ae1e47c075cd5853", "content_id": "1afafcc0071a37cf96821619735b7f0cc9338d36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 974, "license_type": "permissive", "max_line_length": 82, "num_lines": 47, "path": "/logout.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# a simple logout dialog\n#\n###\n\nkill_apps() {\n while read -r app; do\n wmctrl -i -c \"$app\"\n done < <(wmctrl -l | awk '{print $1}')\n}\n\nchoice_by_zenity() {\n choice=$(zenity --title=\"Logout $HOSTNAME\" \\\n --text=\"Logout $HOSTNAME:\" \\\n --list --radiolist \\\n --hide-column=3 --print-column=3 \\\n --column='' --column='' --column='' \\\n TRUE Logout 0 FALSE Reboot 1 FALSE Shutdown 2)\n}\n\nchoice_by_dmenu() {\n if [[ -f \"$HOME/.dmenurc\" ]]; then\n . \"$HOME/.dmenurc\"\n else\n DMENU='dmenu -i'\n fi\n\n choice=$(echo -e \"0: Logout\\n1: Shutdown\\n2: Reboot\" | $DMENU | cut -d ':' -f 1)\n}\n\n[[ -z \"$DISPLAY\" ]] && exit 1\n\n#choice_by_zenity\nchoice_by_dmenu\n\n[[ -z \"$choice\" ]] && exit 1\n\n# gracefully close all open apps\nkill_apps\n\n# execute the choice in background\ncase \"$choice\" in\n 0) kill $(pgrep X) & ;;\n 1) sudo shutdown -r now & ;;\n 2) sudo shutdown -h now & ;;\nesac\n" }, { "alpha_fraction": 0.655339777469635, "alphanum_fraction": 0.6893203854560852, "avg_line_length": 22, "blob_id": "086d4395073787abb8417d4e41cc39939a821583", "content_id": "da5279cff21c55875d2a722f4054fb159d73f0e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 206, "license_type": "permissive", "max_line_length": 53, "num_lines": 9, "path": "/headset.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif echo -e \"info\" | bluetoothctl | grep Missing; then\n\techo -e \"power on\" | bluetoothctl\n\tsleep 1\n\techo -e \"connect A0:E6:F8:18:DD:F5\" | bluetoothctl\nelse\n\techo -e \"power off\" | bluetoothctl\nfi" }, { "alpha_fraction": 0.6886792182922363, "alphanum_fraction": 0.7169811129570007, "avg_line_length": 16.83333396911621, "blob_id": "fe5d9081e11966a860d7abc39048edbdd55456c9", "content_id": "21a450ee534248e436343bad27c0eec105f41f16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "permissive", "max_line_length": 53, "num_lines": 6, "path": "/wallpaper.py", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "import os\nimport time \n\nwhile True:\n\tos.system(\"feh --bg-fill /home/philip/wallpapers/*\")\n\ttime.sleep(900)" }, { "alpha_fraction": 0.5841726660728455, "alphanum_fraction": 0.7107913494110107, "avg_line_length": 98.28571319580078, "blob_id": "6798d5083cb0092088edc916690bac020d77e37d", "content_id": "92231882dc5fc9c590a7d3068d4600b9b1905e53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 695, "license_type": "permissive", "max_line_length": 219, "num_lines": 7, "path": "/bigscreen.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/sh\nxrandr --output eDP1 --primary --mode 1920x1080 --pos 320x1440 --rotate normal --output DP1 --off --output DP2 --off --output HDMI1 --off --output HDMI2 --mode 2560x1440 --pos 0x0 --rotate normal --output VIRTUAL1 --off\nsleep 1\nxrandr --output eDP1 --off --output DP1 --off --output DP2 --off --output HDMI1 --off --output HDMI2 --mode 2560x1440 --pos 0x0 --rotate normal --output VIRTUAL1 --off\nsleep 1\nxrandr --output eDP1 --primary --mode 1920x1080 --pos 320x1440 --rotate normal --output DP1 --off --output DP2 --off --output HDMI1 --off --output HDMI2 --mode 2560x1440 --pos 0x0 --rotate normal --output VIRTUAL1 --off\nfeh --bg-scale pics/wallpaper\\ slideshow/2560x1440/space.jpg\n" }, { "alpha_fraction": 0.7130801677703857, "alphanum_fraction": 0.7341772317886353, "avg_line_length": 32.71428680419922, "blob_id": "15dccb14b68e02461c84d5d4d0586afe23d089b6", "content_id": "eb6d3db40a50c47f8e7214ff62f16b83e1b749e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 237, "license_type": "permissive", "max_line_length": 133, "num_lines": 7, "path": "/cheese.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#writen by philip woldhek\n\ntime=$(date +\"%T-%Y-%m-%d\")\npicturelocation=/home/philip/failedunlock\n\nffmpeg -f video4linux2 -i /dev/v4l/by-id/usb-Ricoh_Company_Ltd._Integrated_Camera-video-index0 -vframes 3 $picturelocation/$time.jpeg\n\n" }, { "alpha_fraction": 0.76486736536026, "alphanum_fraction": 0.7731015682220459, "avg_line_length": 21.306121826171875, "blob_id": "cf763b658c682227855122e39b3c775f8ed22397", "content_id": "e72ce4a002de9016260c6540400da95bab6ec5c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1093, "license_type": "permissive", "max_line_length": 69, "num_lines": 49, "path": "/deluge.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsudo su\nadduser deluge --shell /dev/null --disabled-password --disabled-login\nadd-apt-repository ppa:deluge-team/ppa \\\n&& apt update \\\n&& apt install -y deluged deluge-web \\\n&& gpasswd -a $USER deluge\n\ncat > /etc/systemd/system/deluged.service << \\EOF\n[Unit]\nDescription=Deluge Bittorrent Client Daemon\nAfter=network-online.target\n[Service]\nType=simple\nUser=deluge\nGroup=deluge\nUMask=002\nExecStart=/usr/bin/deluged -d\nRestart=on-failure\n# Configures the time to wait before service is stopped forcefully.\nTimeoutStopSec=300\n[Install]\nWantedBy=multi-user.target\nEOF\n\ncat > /etc/systemd/system/deluge-web.service << \\EOF\n[Unit]\nDescription=Deluge Bittorrent Client Web Interface\nAfter=network-online.target\n[Service]\nType=simple\nUser=deluge\nGroup=deluge\nUMask=002\nExecStart=/usr/bin/deluge-web\nRestart=on-failure\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl --system daemon-reload \\\n&& systemctl enable deluged \\\n&& systemctl start deluged \\\n&& systemctl status deluged \\\n&& systemctl enable deluge-web \\\n&& systemctl start deluge-web \\\n&& systemctl status deluge-web\nreboot\n" }, { "alpha_fraction": 0.567251443862915, "alphanum_fraction": 0.6198830604553223, "avg_line_length": 18, "blob_id": "31dab4b83aedceaf5ff5311c09b5ab41c9f2c5d4", "content_id": "05f78dafda9c9b9d7d003b6db141022c75fe9cea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 171, "license_type": "permissive", "max_line_length": 56, "num_lines": 9, "path": "/gpuswitch.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#written by Philip Woldhek\n\nif [ \"0000:01:00.0 OFF\" = \"$(cat /proc/acpi/bbswitch)\" ]\n then\n tee /proc/acpi/bbswitch <<<ON\n else\n tee /proc/acpi/bbswitch <<<OFF\nfi\n" }, { "alpha_fraction": 0.525687575340271, "alphanum_fraction": 0.5376232266426086, "avg_line_length": 26.927536010742188, "blob_id": "24b3c2891a3b81670c79370567853bda83351604", "content_id": "2d32fea6c822544975c54b55e82a21ffc63bf7c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1927, "license_type": "permissive", "max_line_length": 81, "num_lines": 69, "path": "/sshuttle.py", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n\"\"\"\nI created this program to have a simple command to connect\nto my home network using sshuttle.\nThe program has two self explainatory arguments:\nstart and stop.\n\"\"\"\n\nimport os\nimport sys\nimport time\n\n\ndef get_current_ip(): # gets your current ip\n ip = os.popen(\"curl -s checkip.dyndns.org | \\\n sed -e 's/.*Current IP Address: //' -e 's/<.*$//'\").read()\n ip = ip.rstrip()\n return ip\n\n\ndef connection_check(ip): # checks if the connection is successfull\n t_end = time.time() + 60 * 1\n while time.time() < t_end:\n if get_current_ip() == ip:\n print(\"you are now connected to {0}\".format(ip))\n exit(0)\n print(\"unable to connect\")\n exit(1)\n\n\ndef main():\n if len(sys.argv) < 2: # checks if there are arguments\n print(\"Usage is vpn-hole start/stop\")\n exit(1)\n\n if sys.argv[1] == \"start\":\n try:\n ip = os.popen(\"cat /home/philip/scripts/nicetryfbi.txt | \\\n grep wan | awk '{print $2}'\").read()\n ip = ip.rstrip()\n # replace the ip variable with your ip\n if get_current_ip() == ip: # checks if you are not already connected\n print(\"you are already connected\")\n exit(1)\n\n os.system(\"sshuttle --dns -x {0} -r philip@{0} \\\n 0/0 --python=python3 -D\".format(ip)) # start a sshuttle vpn\n\n connection_check(ip)\n\n except Exception as e:\n print(e)\n print(\"could not start sshuttle\")\n exit(1)\n\n if sys.argv[1] == \"stop\": # finds sshuttle process and kills it\n try:\n os.system(\"kill $(pgrep sshuttle) > /dev/null 2>&1\")\n print(\"sshuttle killed\")\n exit(0)\n except Exception as e:\n print(e)\n print(\"sshuttle is not running\")\n exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7247058749198914, "alphanum_fraction": 0.729411780834198, "avg_line_length": 37.6363639831543, "blob_id": "4a7a6e1e0d34239e5cc7896d304d334e9b27200b", "content_id": "901fa9e9f2676e4387dc4e0c8346ca8ce199c3c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 425, "license_type": "permissive", "max_line_length": 117, "num_lines": 11, "path": "/sendpicture", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#writen by philip woldhek\n\nmail=$(cat /home/philip/scripts/nicetryfbi.txt | grep email | awk '{print $2}')\npicturelocation=/home/philip/failedunlock\nhostname=$(cat /proc/sys/kernel/hostname)\nlastpicture=$(ls -Art $picturelocation | tail -n 1)\n\nwhile inotifywait -m /home/philip/failedunlock/*; do\n mail -s \"unauthorized login\" -a $picturelocation/$lastpicture $mail <<< \"This person tried to login to $hostname\"\ndone\n" }, { "alpha_fraction": 0.6319444179534912, "alphanum_fraction": 0.6319444179534912, "avg_line_length": 17, "blob_id": "86225c3539960f9fc7bef6082d2978aa107c70d1", "content_id": "fe0d8c5efb637e42420e408daa5ea6e6752167e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 144, "license_type": "permissive", "max_line_length": 43, "num_lines": 8, "path": "/safe-shutdown.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif pgrep -il \"vmware-vmx\" &>/dev/null; then\n notify-send \"vm is running!\"\nelse\n docker stop $(docker ps -aq)\n shutdown\nfi\n" }, { "alpha_fraction": 0.6260355114936829, "alphanum_fraction": 0.6603550314903259, "avg_line_length": 37.40909194946289, "blob_id": "18ed851c0e209b19218938e5caedc091357e0380", "content_id": "e4eabae789c0a0fc9977d38de1363a989f73d01c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 845, "license_type": "permissive", "max_line_length": 120, "num_lines": 22, "path": "/smbmount.sh", "repo_name": "11philip22/scripts", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#written by philip woldhek\n\nserverip=$(cat /home/philip/scripts/nicetryfbi.txt | grep serverip | awk '{print $2}')\n\nwifi=\"'$(/sbin/iwconfig wlp4s0 | egrep ESSID | cut -d '\"' -f 2)'\"\n\nif [ \"df: no file systems processed\" = \"$(df -k -F cifs)\"]\n\tthen\n\t\tif [ $wifi = \"'WuTangLAN'\" ] && [ \"open\" = \"$(nc -vzw 1 192.168.1.2 445 2>&1 | awk '{print $NF}')\" ]\n\t\t\tthen\n \t\t\t\tmount.cifs //$serverip/raid5 /home/philip/smb/raid -o uid=philip,credentials=/etc/smbcredentials,iocharset=utf8 &\n \t\t\t\tmount.cifs //$serverip/4tb /home/philip/smb/4tb -o uid=philip,credentials=/etc/smbcredentials,iocharset=utf8 &\n \t\t\t\tmount.cifs //$serverip/3tb /home/philip/smb/3tb -o uid=philip,credentials=/etc/smbcredentials,iocharset=utf8 &\n\t\t\telse\n\t\t\t\texit 0\n\t\tfi\n\telse \n\t\tumount /home/philip/smb/raid\n\t\tumount /home/philip/smb/3tb\n\t\tumount /home/philip/smb/4tb\nfi\n" } ]
36
HynekM99/backups
https://github.com/HynekM99/backups
b2be750c3dc3f47191339832e23c37b5d6a11399
82e6fa95830d93b752092b06c89a35bb63348e5c
16d4d25278e2de67f6488a7573900a0e7c6ee19a
refs/heads/master
2023-04-11T01:05:12.621057
2021-04-11T08:31:10
2021-04-11T08:31:10
354,615,531
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5539084672927856, "alphanum_fraction": 0.5736227035522461, "avg_line_length": 38.78115463256836, "blob_id": "bae5fda7fc43cbe362ee54b0546328195b95e234", "content_id": "7c1c4d0af0a3f06e30d8eef63aec4716e0a86dca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13087, "license_type": "no_license", "max_line_length": 170, "num_lines": 329, "path": "/.config/qtile/config.py", "repo_name": "HynekM99/backups", "src_encoding": "UTF-8", "text": "# Copyright (c) 2010 Aldo Cortesi\n# Copyright (c) 2010, 2014 dequis\n# Copyright (c) 2012 Randall Ma\n# Copyright (c) 2012-2014 Tycho Andersen\n# Copyright (c) 2012 Craig Barnes\n# Copyright (c) 2013 horsik\n# Copyright (c) 2013 Tao Sauvage\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport os\nimport subprocess\n\nfrom typing import List # noqa: F401\n\nfrom libqtile import bar, layout, widget, hook, qtile\nfrom libqtile.config import Click, Drag, Group, Key, Match, Screen\nfrom libqtile.lazy import lazy\n\nmod = \"mod4\"\nterminal = \"alacritty\"\n\nkeys = [\n # Switch between groups\n Key([mod], \"Left\", lazy.screen.prev_group(), desc=\"Move to the group on the left\"),\n Key([mod], \"Right\", lazy.screen.next_group(), desc=\"Move to the group on the right\"),\n\n # Switch between windows\n Key([mod], \"Tab\", lazy.layout.next(), desc=\"Move window focus to next window\"),\n\n # Move windows between left/right columns or move up/down in current stack.\n # Moving out of range in Columns layout will create new column.\n Key([mod, \"shift\"], \"Left\", lazy.layout.shuffle_left(), desc=\"Move window to the left\"),\n Key([mod, \"shift\"], \"Right\", lazy.layout.shuffle_right(), desc=\"Move window to the right\"),\n Key([mod, \"shift\"], \"Down\", lazy.layout.shuffle_down(), desc=\"Move window down\"),\n Key([mod, \"shift\"], \"Up\", lazy.layout.shuffle_up(), desc=\"Move window up\"),\n\n # Grow windows. If current window is on the edge of screen and direction\n # will be to screen edge - window would shrink.\n Key([mod, \"control\"], \"h\", lazy.layout.grow_left(), desc=\"Grow window to the left\"),\n Key([mod, \"control\"], \"l\", lazy.layout.grow_right(), desc=\"Grow window to the right\"),\n Key([mod, \"control\"], \"j\", lazy.layout.grow_down(), desc=\"Grow window down\"),\n Key([mod, \"control\"], \"k\", lazy.layout.grow_up(), desc=\"Grow window up\"),\n Key([mod, \"control\"], \"n\", lazy.layout.normalize(), desc=\"Reset all window sizes\"),\n\n # Spawn\n Key([mod], \"Return\", lazy.spawn(terminal), desc=\"Launch terminal\"),\n Key([mod], \"p\", lazy.spawn(\"rofi -show run\"), desc=\"Launch rofi\"),\n\n # Toggle between different layouts as defined below\n Key([mod], \"space\", lazy.next_layout(), desc=\"Toggle between layouts\"),\n Key([mod, \"shift\"], \"c\", lazy.window.kill(), desc=\"Kill focused window\"),\n\n Key([mod, \"control\"], \"r\", lazy.restart(), desc=\"Restart Qtile\"),\n Key([mod, \"control\"], \"q\", lazy.shutdown(), desc=\"Shutdown Qtile\"),\n Key([mod], \"End\", lazy.spawn(\"shutdown now\"), desc=\"Shutdown computer\"),\n Key([mod], \"w\", lazy.spawn(\"firefox\"), desc=\"Run Firefox\"),\n\n # Screen brightness\n Key([], \"XF86MonBrightnessDown\", lazy.spawn(\"xbacklight -2\")),\n Key([], \"XF86MonBrightnessUp\", lazy.spawn(\"xbacklight +2\")),\n\n # Sound\n Key([], \"XF86AudioMute\", lazy.spawn(\"amixer -q sset Master toggle\")),\n Key([], \"XF86AudioLowerVolume\", lazy.spawn(\"amixer -q sset Master 2%- unmute\")),\n Key([], \"XF86AudioRaiseVolume\", lazy.spawn(\"amixer -q sset Master 2%+ unmute\")),\n \n # Spotify\n Key([], \"XF86AudioPlay\", lazy.spawn(\"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause\")),\n Key([], \"XF86AudioPrev\", lazy.spawn(\"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Previous\")),\n Key([], \"XF86AudioNext\", lazy.spawn(\"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Next\")),\n Key([], \"XF86AudioStop\", lazy.spawn(\"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Stop\")),\n\n Key([\"mod1\"], \"Shift_L\", lazy.widget[\"keyboardlayout\"].next_keyboard(), desc=\"Next keyboard layout.\")\n]\n\ngroups = [Group(i) for i in \"123456789\"]\nlabels = [\"\\uf0ac\",\"\\uf121\",\"\\uf120\",\"\\uf07c\",\"\\uf02d\",\"\\uf109\",\"\\uf4b8\",\"\\uf1fc\",\"\\uf025\"]\n\nfor index, group in enumerate(groups):\n group.label = labels[index]\n\n keys.extend([\n # mod1 + letter of group = switch to group\n Key([mod], \"F\"+group.name, lazy.group[group.name].toscreen(),\n desc=\"Switch to group {}\".format(group.name)),\n\n # mod1 + shift + letter of group = move focused window to group\n Key([mod, \"shift\"], \"F\"+group.name, lazy.window.togroup(group.name, switch_group=True),\n desc=\"Move focused window to group {}\".format(group.name))\n ])\n\ncolors = dict(\n panel_separator= \"#444488\",\n selected_group_underline_color= \"#ff0000\",\n inactive_group_foreground= \"#666666\",\n active_group_foreground= \"#44ccff\",\n groups_background= \"#222222\",\n group_window_tab_separator= \"#4466aa\",\n window_tab_background= \"#333333\",\n window_tab_foreground= \"#ffffff\",\n widget_background= \"#111130\",\n widget_foreground= \"#ffffff\",\n thermometer_symbol= \"#ff4444\",\n volume_symbol= \"#ff6644\",\n battery_symbol= \"#ff8800\",\n battery_high= \"#ffffff\",\n battery_low= \"#ff0000\",\n calendar_symbol= \"#ffff88\",\n shutdown_button= \"#ff0000\",\n window_border_focused= \"#ff4444\",\n window_border_unfocused= \"#4444aa\"\n)\n\nlayouts = [\n layout.MonadTall(\n margin=4,\n single_border_width=0,\n border_focus=colors[\"window_border_focused\"],\n border_normal=colors[\"window_border_unfocused\"]\n ),\n layout.MonadWide(\n margin=4,\n single_border_width=0,\n border_focus=colors[\"window_border_focused\"],\n border_normal=colors[\"window_border_unfocused\"]\n ),\n layout.Columns(\n margin=2,\n single_border_width=0,\n border_focus=colors[\"window_border_focused\"],\n border_normal=colors[\"window_border_unfocused\"]\n ),\n layout.VerticalTile(\n margin=(2, 4, 2, 4),\n single_border_width=0,\n border_focus=colors[\"window_border_focused\"],\n border_normal=colors[\"window_border_unfocused\"]\n ),\n layout.Max()\n]\n\n#### MOUSE CALLBACKS ####\ndef open_rofi():\n qtile.cmd_spawn('rofi -show run')\n\ndef open_calendar():\n qtile.cmd_spawn('alacritty --hold -e khal interactive')\n\ndef shutdown():\n qtile.cmd_spawn('shutdown now')\n\nwidget_defaults = dict(\n background=colors[\"widget_background\"],\n foreground=colors[\"widget_foreground\"],\n font='sans',\n fontsize=14,\n padding=4\n)\n\nextension_defaults = widget_defaults.copy()\n\nseparator = widget.Sep(\n foreground=colors[\"panel_separator\"],\n padding=0,\n linewidth=2,\n size_percent=100\n )\n\nscreens = [\n Screen(\n top=bar.Bar(\n [\n widget.GroupBox(\n this_current_screen_border=colors[\"selected_group_underline_color\"],\n inactive=colors[\"inactive_group_foreground\"],\n highlight_color=colors[\"groups_background\"],\n active=colors[\"active_group_foreground\"],\n background=colors[\"groups_background\"],\n font=\"FontAwesomeRegular\",\n urgent_alert_method=\"block\",\n highlight_method=\"line\",\n disable_drag=True,\n border_width=0,\n margin_x=0,\n padding=5\n ),\n widget.Sep(\n foreground=colors[\"group_window_tab_separator\"],\n padding=0,\n linewidth=2,\n size_percent=100\n ),\n widget.WindowName(\n background=colors[\"window_tab_background\"],\n foreground=colors[\"window_tab_foreground\"]\n ),\n separator,\n widget.KeyboardLayout(\n configured_keyboards=[\"cz\", \"us\"]\n ),\n separator,\n widget.CurrentLayoutIcon(\n scale=0.6,\n padding=1\n ),\n separator,\n widget.Sep(\n foreground=colors[\"volume_symbol\"],\n padding=0,\n linewidth=2,\n size_percent=100\n ),\n widget.Volume(\n foreground=colors[\"volume_symbol\"],\n emoji=True,\n step=2,\n fontsize=18,\n update_interval=0.5\n ),\n widget.Volume(\n step=2,\n update_interval=0.5\n ),\n separator,\n widget.Sep(\n foreground=colors[\"battery_symbol\"],\n padding=0,\n linewidth=2,\n size_percent=100\n ),\n widget.Battery(\n foreground=colors[\"battery_symbol\"],\n font=\"FontAwesome\",\n charge_char='\\uf1e6',\n discharge_char='\\uf0e7',\n format=\"{char}\",\n update_interval=5,\n fontsize=15,\n padding=0\n ),\n widget.Battery(\n format=\"{percent:2.0%}\",\n foreground=colors[\"battery_high\"],\n low_foreground=colors[\"battery_low\"],\n low_percentage=0.2,\n update_interval=1\n ),\n separator,\n widget.Sep(\n foreground=colors[\"calendar_symbol\"],\n padding=0,\n linewidth=2,\n size_percent=100\n ),\n widget.TextBox(\n foreground=colors[\"calendar_symbol\"],\n font=\"FontAwesome\",\n text=\" \\uf073\",\n fontsize=16,\n padding=0\n ),\n widget.Clock(\n format='%a %d.%m. %H:%M ',\n mouse_callbacks={'Button1': open_calendar}\n )\n ],\n size=27,\n opacity=1\n ),\n ),\n]\n\n# Drag floating layouts.\nmouse = [\n Drag([mod], \"Button1\", lazy.window.set_position_floating(), start=lazy.window.get_position()),\n Drag([mod], \"Button3\", lazy.window.set_size_floating(), start=lazy.window.get_size()),\n Click([mod], \"Button2\", lazy.window.bring_to_front())\n]\n\ndgroups_key_binder = None\ndgroups_app_rules = [] # type: List\nmain = None # WARNING: this is deprecated and will be removed soon\nfollow_mouse_focus = True\nbring_front_click = False\nauto_fullscreen = True\ncursor_warp = False\nfloating_layout = layout.Floating(float_rules=[\n # Run the utility of `xprop` to see the wm class and name of an X client.\n *layout.Floating.default_float_rules,\n Match(wm_class='confirmreset'), # gitk\n Match(wm_class='makebranch'), # gitk\n Match(wm_class='maketag'), # gitk\n Match(wm_class='ssh-askpass'), # ssh-askpass\n Match(title='branchdialog'), # gitk\n Match(title='pinentry'), # GPG key password entry\n])\nfocus_on_window_activation = \"smart\"\n\n# XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this\n# string besides java UI toolkits; you can see several discussions on the\n# mailing lists, GitHub issues, and other WM documentation that suggest setting\n# this string if your java app doesn't work correctly. We may as well just lie\n# and say that we're a working one by default.\n#\n# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in\n# java that happens to be on java's whitelist.\nwmname = \"LG3D\"\n\[email protected]_once\ndef autostart():\n home = os.path.expanduser('~/.config/qtile/autostart.sh')\n subprocess.call([home])" }, { "alpha_fraction": 0.7171717286109924, "alphanum_fraction": 0.7171717286109924, "avg_line_length": 18.799999237060547, "blob_id": "96d0af909b9901911e36b7f54778b8ccc9da967a", "content_id": "6e3c0287027e2811010e6705e2df0a43f3c30094", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 99, "license_type": "no_license", "max_line_length": 28, "num_lines": 5, "path": "/.config/qtile/autostart.sh", "repo_name": "HynekM99/backups", "src_encoding": "UTF-8", "text": "#!/bin/bash\nnitrogen --restore &\npicom &\nkillall redshift ;redshift &\nsystemctl enable --now smb &\n" } ]
2
aguajardo/CENSE_Demonstrator
https://github.com/aguajardo/CENSE_Demonstrator
bad5ec59db25bc41f0cb2115872cb49a6db0674c
98de3a83462a9587994d923b0e4de574dda49f7c
ad6f8b3ea4daebb43bf68137ad7579243474e86a
refs/heads/master
2021-01-21T10:26:01.823849
2017-05-08T12:29:17
2017-05-08T12:29:17
83,427,700
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.41878125071525574, "alphanum_fraction": 0.4519355297088623, "avg_line_length": 25.086956024169922, "blob_id": "48c9d835a1c200b5ae7138a594133623b494349c", "content_id": "13a111d745cf2f4611b1bf0a140fb6f4c7433ec9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5399, "license_type": "no_license", "max_line_length": 78, "num_lines": 207, "path": "/Drahterfassung_OpenCV/beta modules/Mask_Cleanup.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a color detection method that allows to focus onto the\ncolor being detected with color variance.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Color_Detection as colors\n\n\nclass Agents:\n agents = []\n agents_temp = []\n\n\ndef sync_agents():\n Agents.agents = np.array(Agents.agents_temp)\n\ndef neighbours(x, y, image):\n img = image\n x_1, y_1, x1, y1 = x - 1, y - 1, x + 1, y + 1\n return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], # u,ur,r,dr\n img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]] # d,dl,l,ul\n\n\ndef alive(agent, mask):\n Agents.agents_temp.append(agent)\n mask[agent[0]][agent[1]] = 1\n\n\ndef dead(agent, mask):\n mask[agent[0]][agent[1]] = 0\n Agents.agents_temp.remove([agent[0], agent[1]])\n\n\ndef move(agent, directions, mask):\n position = list(agent)\n for i in range(len(directions)):\n if directions[i] == 0:\n if i == 0:\n dead(agent, mask)\n position[1] += 1\n alive(position, mask)\n return\n if i == 1:\n dead(agent, mask)\n position[0] += 1\n position[1] += 1\n alive(position, mask)\n return\n if i == 2:\n dead(agent, mask)\n position[0] += 1\n alive(position, mask)\n return\n if i == 3:\n dead(agent, mask)\n position[0] += 1\n position[1] -= 1\n alive(position, mask)\n return\n if i == 4:\n dead(agent, mask)\n position[1] -= 1\n alive(position, mask)\n return\n if i == 5:\n dead(agent, mask)\n position[0] -= 1\n position[1] -= 1\n alive(position, mask)\n return\n if i == 6:\n dead(agent, mask)\n position[0] -= 1\n alive(position, mask)\n return\n if i == 7:\n dead(agent, mask)\n position[0] -= 1\n position[1] += 1\n alive(position, mask)\n return\n\n\ndef reproduce(agent, directions, mask):\n position = list(agent)\n for i in range(len(directions)):\n if directions[i] == 0:\n if i == 0:\n position[1] += 1\n alive(position, mask)\n return\n if i == 1:\n position[0] += 1\n position[1] += 1\n alive(position, mask)\n return\n if i == 2:\n position[0] += 1\n alive(position, mask)\n return\n if i == 3:\n position[0] += 1\n position[1] -= 1\n alive(position, mask)\n return\n if i == 4:\n position[1] -= 1\n alive(position, mask)\n return\n if i == 5:\n position[0] -= 1\n position[1] -= 1\n alive(position, mask)\n return\n if i == 6:\n position[0] -= 1\n alive(position, mask)\n return\n if i == 7:\n position[0] -= 1\n position[1] += 1\n alive(position, mask)\n return\n\n\nname = 'Bilder\\Test6.png'\nscale = 1\nbands = 8\nthresh = 3\ncolor = 25\nfocus = [25, 35, 255, 35, 255]\nimages = colors.color_vision(color, focus, bands, thresh, scale, name)\n\nmask = np.array(images[len(images)-1])\n\nroi = mask[190:215, 0:25]\nrows, cols = roi.shape\n\nfor x in range(cols):\n for y in range(rows):\n if roi[y][x] == 1:\n p_1 = [y+190, x]\n break\n if roi[y][x] == 1:\n p_1 = [y+190, x]\n break\n\n\nrows, cols = mask.shape\nprint([rows, cols])\nnew_mask = np.zeros((rows, cols), np.uint8)\n\n\n\nret, mask = cv2.threshold(mask, 0, 1, cv2.THRESH_BINARY_INV)\n\n\npopulation = 0\nmax_population = 4000\npop_change = True\n\n\nalive(p_1, new_mask)\nsync_agents()\ncv2.imshow('original', mask*255)\n\nwhile True:\n pop_change = False\n for agent in Agents.agents:\n temp = cv2.bitwise_or(mask, new_mask)\n if population != max_population:\n u, ur, r, dr, d, dl, l, ul = neighbours(agent[0], agent[1], temp)\n connections = u+ur+r+dr+d+dl+l+ul\n directions = [r, dr, d, dl, l, ul, u, ur]\n if connections < 8:\n reproduce(agent, directions, new_mask)\n population += 1\n pop_change = True\n else:\n u, ur, r, dr, d, dl, l, ul = neighbours(agent[0], agent[1], temp)\n connections = u + ur + r + dr + d + dl + l + ul\n directions = [r, dr, d, dl, l, ul, u, ur]\n if connections < 8:\n move(agent, directions, new_mask)\n pop_change = True\n sync_agents()\n print(len(Agents.agents))\n cv2.imshow('New', * 255)\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\nsum = 0\nfor i in range(rows):\n for j in range(cols):\n if new_mask[i][j]==1:\n sum+=1\nprint(sum)\n\ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.7183098793029785, "alphanum_fraction": 0.762910783290863, "avg_line_length": 22.72222137451172, "blob_id": "fb9f177de4d417ba607f9124e0332e8d2aa9a1ee", "content_id": "5227323579b836b780a4e375b62684d4c46ec586", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/Drahterfassung_OpenCV/other/Drahterfassung_PIL.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "from PIL import Image\nfrom PIL import ImageChops\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimage1=Image.open('Bilder\\im1.jpg')\nimage2=Image.open('Bilder\\im2.jpg')\n\nimage=ImageChops.subtract(image2, image1)\n\nmask1=Image.eval(image, lambda a: 0 if a<=10 else 255)\nmask2=mask1.convert('1')\n\nblank=Image.eval(image, lambda a:0 )\nnew=Image.composite(image2, blank, mask2)\nimg=np.array(new)\nplt.imshow(img)\nplt.show()" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 12.75, "blob_id": "6e643a81bb7b8356405cebf94d5ca2c445327dfd", "content_id": "60cba57c26e1e70c01f9d55d5af5efd11daa4e54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "no_license", "max_line_length": 36, "num_lines": 12, "path": "/RTDE_Interface/TestB.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import RTDE_Controller_CENSE as rtde\n\nprint(rtde.current_position())\n\nrtde.go_start_via_path()\n\nrtde.go_camera()\n\n#rtde.go_start_via_path()\n\n\nrtde.disconnect_rtde()\n" }, { "alpha_fraction": 0.64371258020401, "alphanum_fraction": 0.7305389046669006, "avg_line_length": 30.809524536132812, "blob_id": "f4e83c5e6b70d1c336ca0b9c5a074ab5581c3c26", "content_id": "8b7943556aff6828b4e62a92b312df551bf2b5e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 98, "num_lines": 21, "path": "/Drahterfassung_OpenCV/other/Drahterfassung_Thresholding.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('Bilder\\Buddah3.jpg')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nimg = cv2.resize(img, None, fx=0.125, fy=0.125)\ngray = cv2.resize(gray, None, fx=0.125, fy=0.125)\nretval, thresh = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY)\nretval2, otsu = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\ngaus = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)\n\n\ncv2.imshow('Gray', gray)\ncv2.imshow('Image', img)\ncv2.imshow('Threshold', thresh)\ncv2.imshow('Gaus', gaus)\ncv2.imshow('OTSU', otsu)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.6025640964508057, "alphanum_fraction": 0.6524216532707214, "avg_line_length": 26.038461685180664, "blob_id": "24524ce0261a14305ed448ba0be9c617308be360", "content_id": "25e18ff434904a921548865f83543f2b092b4400", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "no_license", "max_line_length": 80, "num_lines": 26, "path": "/Drahterfassung_OpenCV/beta modules/Edge_Detection.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 28/03/2017\nThis is a color detection method that allows to focus onto the\ncolor being detected with color variance.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef edge_vision(name, minval, maxval, apsize, scale):\n img = cv2.imread(name,0)\n img = cv2.resize(img, None, fx=scale, fy=scale)\n\n edges = cv2.Canny(img, minval, maxval, apertureSize=apsize, L2gradient=True)\n ret, edges_binary = cv2.threshold(edges, 1, 1, cv2.THRESH_BINARY_INV)\n\n\n\n return edges_binary\n\ncv2.imshow('edges', edge_vision('Bilder\\Test6.png', 100, 200, 3, 1)*255)\ncv2.waitKey(0)" }, { "alpha_fraction": 0.6276436448097229, "alphanum_fraction": 0.6502914428710938, "avg_line_length": 37.74193572998047, "blob_id": "67fe3ced7d573d1259ce30808e368b24a7ebb1b7", "content_id": "b4b907effcab878b2349f26252d172b4b3291b97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6005, "license_type": "no_license", "max_line_length": 120, "num_lines": 155, "path": "/Drahterfassung_OpenCV/Color_Detection.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a color detection method that allows to focus onto the\ncolor being detected with color variance.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\n\n\n# an image or saved image will be color processed and the masks will be returned in an array\ndef color_vision(color, focus, bands, thresh, scale, name=None, image=None):\n # the bands will be saved into an array of masks\n masks = colorDetect(bands, color, focus, scale, name=name, image=image)\n rows, cols = masks[2].shape\n\n # an empty numpy array will be generated with the shape of the masks\n sum_mask = np.zeros((rows, cols), np.uint8)\n\n # all masks will be added together in a numpy array\n for i in range(len(masks)-3):\n sum_mask += masks[3+i]\n\n # any value above 'thresh' will be set to 1 and all the other values will be set to 0 creating a binary mask\n for i in range(rows):\n for j in range(cols):\n if sum_mask[i, j] >= thresh:\n sum_mask[i, j] = 1\n else:\n sum_mask[i, j] = 0\n\n # morphological transformations will be applied to the resulting mask to be able to remove noise\n kernel = np.ones((1,1), np.uint8)\n # sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)\n # sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_CLOSE, kernel)\n sum_mask = cv2.dilate(sum_mask, None, iterations=6)\n# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)\n# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)\n# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_CLOSE, kernel)\n# sum_mask = cv2.morphologyEx(sum_mask, cv2.MORPH_OPEN, kernel)\n sum_mask = cv2.erode(sum_mask, None, iterations=5)\n\n # resulting mask will be applied to the original image to see what the camera sees from the mask and saved to masks\n res = cv2.bitwise_and(masks[0], masks[0], mask=sum_mask)\n masks.append(res)\n masks.append(sum_mask)\n return masks\n\n\ndef colorDetect(bands, color, focus, scale, name=None, image=None):\n # when no file path was specified but an image was given then process the image if not then return None\n if name is None:\n if image is None:\n return None\n else:\n img = image\n else:\n img = cv2.imread(name)\n\n # image is resized\n img = cv2.resize(img, None, fx=scale, fy=scale)\n\n # image color format is changed from bgr to rgb\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n # the min hue and max hue are specified\n minp = color-focus[0]\n maxp = color\n\n # an Hue, Saturation, Value color formatted version of the image is saved on 'hsv' and saved to 'list' with original\n hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n list = [img, hsv]\n\n # the min range values for the color detection of OpenCV are initialized\n min_a = np.array([minp, focus[1], focus[3]])\n max_a = np.array([maxp, focus[2], focus[4]])\n\n # first band is calculated and saved in mask\n mask = cv2.inRange(hsv, min_a, max_a)\n\n # the process is repeated for the amount of bands needed\n for i in range(bands):\n minp += (focus[0])/bands\n maxp += (focus[0])/bands\n min_a = np.array([minp, focus[1], focus[3]])\n max_a = np.array([maxp, focus[2], focus[4]])\n mask = cv2.inRange(hsv, min_a, max_a)\n\n ret, mask_binary = cv2.threshold(mask, 1, 1, cv2.THRESH_BINARY)\n\n list.append(mask_binary)\n\n # masks and images are returned in an array of images\n return list\n\n\n# no idea but it was recommended to write this here for the camera preview video stream\ndef nothing(x):\n pass\n\n\n# a 'real-time' video stream of images processed by the color detection and sliders for the parameters will be shown\ndef preview_colors(color, focus, bands, thresh, scale):\n # object for image capture initialized for camera in port 1\n cap = cv2.VideoCapture(0)\n\n # the window is initialized with the name 'Settings'\n cv2.namedWindow('Settings')\n\n # trackbars are created and min values are set\n cv2.createTrackbar('color', 'Settings', color, 180, nothing)\n cv2.createTrackbar('bands', 'Settings', bands, 20, nothing)\n cv2.createTrackbar('thresh', 'Settings', thresh, 20, nothing)\n cv2.createTrackbar('bandwidth', 'Settings', focus[0], 180, nothing)\n cv2.createTrackbar('min S', 'Settings', focus[1], 255, nothing)\n cv2.createTrackbar('max S', 'Settings', focus[2], 255, nothing)\n cv2.createTrackbar('min H', 'Settings', focus[3], 255, nothing)\n cv2.createTrackbar('max H', 'Settings', focus[4], 255, nothing)\n cv2.setTrackbarMin('bands', 'Settings', 1)\n cv2.setTrackbarMin('thresh', 'Settings', 1)\n\n # video stream is displayed\n while True:\n # a frame is taken from the camera feed and saved in 'frame'\n __, frame = cap.read()\n\n # trackbar positions are read and saved onto the appropriate paramters\n color = cv2.getTrackbarPos('color', 'Settings')\n bands = cv2.getTrackbarPos('bands', 'Settings')\n thresh = cv2.getTrackbarPos('thresh', 'Settings')\n focus[0] = cv2.getTrackbarPos('bandwidth', 'Settings')\n focus[1] = cv2.getTrackbarPos('min S', 'Settings')\n focus[2] = cv2.getTrackbarPos('max S', 'Settings')\n focus[3] = cv2.getTrackbarPos('min H', 'Settings')\n focus[4] = cv2.getTrackbarPos('max H', 'Settings')\n\n # frame is filtered and displayed\n filtered = color_vision(color, focus, bands, thresh, scale, image=frame)\n gray = filtered[len(filtered)-1]*255\n gray = cv2.resize(gray, None, fx=1/scale, fy=1/scale)\n\n cv2.imshow('Preview', gray)\n\n # waits for the escape key to stop the video stream and save the trackbar values onto the appropriate parameters\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\n cv2.destroyAllWindows()\n\n # returns the filter parameters\n return bands, thresh, color, focus\n" }, { "alpha_fraction": 0.6136363744735718, "alphanum_fraction": 0.6555944085121155, "avg_line_length": 27.575000762939453, "blob_id": "378c8809a4978a7440a2a953e4086d5c24749640", "content_id": "82859ef48f58ebce2896991325fd1b9de6160f43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1144, "license_type": "no_license", "max_line_length": 64, "num_lines": 40, "path": "/Drahterfassung_OpenCV/other/Drahterfassung_MultiFilterComparison.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport Thinning as skelet\nimport matplotlib.pyplot as plt\n\nSCALE = 0.1\nimg = cv2.imread('Bilder\\Draht1.jpg')\nimg = cv2.resize(img, None, fx=SCALE, fy=SCALE)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nhsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\nLOWER_GREEN = np.array([15,45,50])\nUPPER_GREEN = np.array([35,100,255])\n\nmask = cv2.inRange(hsv, LOWER_GREEN, UPPER_GREEN)\nmask = cv2.dilate(mask, None, iterations=6)\nmask = cv2.erode(mask, None, iterations=5)\nres = cv2.bitwise_and(img, img, mask=mask)\n\n\nret, mask_binary = cv2.threshold(mask, 1, 1, cv2.THRESH_BINARY)\n\nskeleton = skelet.zhangSuen(mask_binary)\nrows, cols, __ = img.shape\nimg_skelet = np.zeros((rows, cols, 3), np.uint8)\n\nfor i in range(cols):\n for j in range(rows):\n if skeleton[j, i] == 1:\n img_skelet[j, i] = [0, 255, 0]\n else:\n img_skelet[j, i] = img[j, i]\n\ntitles = ['Original Image', 'Result', 'Binary Mask', 'Skeleton']\nimages = [img, img_skelet, mask_binary, skeleton]\nfor i in xrange(4):\n plt.subplot(2,2,i+1),plt.imshow(images[i])\n plt.title(titles[i])\n plt.xticks([]),plt.yticks([])\nplt.show()\n\n" }, { "alpha_fraction": 0.6605691313743591, "alphanum_fraction": 0.702235758304596, "avg_line_length": 28.84848403930664, "blob_id": "8b41fcbe40a5d864e7c77262e84916a97de943c0", "content_id": "5631fb5c80b2205918d5d1bbd8c61a6002c243e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 984, "license_type": "no_license", "max_line_length": 61, "num_lines": 33, "path": "/Drahterfassung_OpenCV/other/Drahterfassung_Farbenerkennung.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport Thinning as skelet\nimport matplotlib.pyplot as plt\n\nSCALE = 0.25\nimg = cv2.imread('Bilder\\Draht1.jpg')\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\nLOWER_GREEN = np.array([10,30,50])\nUPPER_GREEN = np.array([40,100,255])\n\nmask = cv2.inRange(hsv, LOWER_GREEN, UPPER_GREEN)\nmask = cv2.dilate(mask, None, iterations=5)\nmask = cv2.erode(mask, None, iterations=5)\nres = cv2.bitwise_and(img, img, mask=mask)\n\nimg = cv2.resize(img, None, fx=SCALE, fy=SCALE)\nres = cv2.resize(res, None, fx=SCALE, fy=SCALE)\nhsv = cv2.resize(hsv, None, fx=SCALE, fy=SCALE)\nmask = cv2.resize(mask, None, fx=SCALE, fy=SCALE)\n\nret,mask_binary = cv2.threshold(mask,1,1,cv2.THRESH_BINARY)\n\nskeleton = skelet.zhangSuen(mask_binary)\n\ntitles = ['Original Image','Binary Mask','Result','Skeleton']\nimages = [img, mask_binary, res, skeleton]\nfor i in xrange(4):\n plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')\n plt.title(titles[i])\n plt.xticks([]),plt.yticks([])\nplt.show()" }, { "alpha_fraction": 0.6329261064529419, "alphanum_fraction": 0.6535776853561401, "avg_line_length": 32.7156867980957, "blob_id": "5e0288d85e9be1e666042021185b49fdadae7123", "content_id": "583aeba029afbfdb15207bcf7e8acf1b202fabb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3438, "license_type": "no_license", "max_line_length": 120, "num_lines": 102, "path": "/Drahterfassung_OpenCV/Main_Vision.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a module for detecting a cable\nwith use of color detection and then\nskeletonizing it with the Zhan-Suen\nthinning algorithm.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Drahterfassung_OpenCV.Color_Detection as colors\nimport Drahterfassung_OpenCV.Thinning as skelet\nimport Drahterfassung_OpenCV.Kamera as cam\nfrom operator import itemgetter\n\n\n# takes a picture and saves it in the file path 'name', processes it and saves the processed image as 'world_img.png'\ndef take_picture():\n # file path\n name = \"Bilder\\camera_picture.png\"\n\n # scale at which the image will be processed\n scale = 1\n\n # the color focus area will be segmented into color bands this states how many bands will be analyzed\n bands = 8\n\n # minimum amount of bands in which a pixel has to be to make it to the resulting mask\n thresh = 4\n\n # color hue to be looked for\n color = 25\n\n # variation range for hue, saturation, and value e.g.: color+focus = max_hue, color-focus = min_hue\n focus = [30, 35, 255, 35, 255]\n\n # a 'real-time' video feed with the color detection filter will be shown\n bands, thresh, color, focus = colors.preview_colors(color, focus, bands, thresh, scale)\n\n # an image will be captured and saved in the file path 'name'\n cam.capture_image(name)\n\n # a series of masks will be generated and saved onto 'images'\n images = colors.color_vision(color, focus, bands, thresh, scale, name=name)\n\n # the resulting mask saved in images will be turned into a binary mask\n ret, mask_binary = cv2.threshold(images[len(images)-1], 0, 1, cv2.THRESH_BINARY)\n\n # the dimensions of the image will be saved in rows and cols to calculate the scaling_constant and superimpose image\n rows, cols = images[len(images)-1].shape\n\n # the mask is then run through a thinning algorithm to generate a 1 pixel wide line\n skeleton = skelet.zhangSuen(mask_binary)\n\n # superimposes the skeleton image on the original image\n img_skelet = np.zeros((rows, cols, 3), np.uint8)\n\n for i in range(cols):\n for j in range(rows):\n if skeleton[j, i] == 1:\n img_skelet[j, i] = [255, 0, 0]\n else:\n img_skelet[j, i] = images[0][j, i]\n\n gray_skeleton = np.zeros((rows, cols, 3), np.uint8)\n rows, cols = skeleton.shape\n for i in range(rows):\n for j in range(cols):\n if skeleton[i, j] == 1:\n gray_skeleton[i, j] = [255, 255, 255]\n else:\n gray_skeleton[i, j] = [0, 0, 0]\n gray_skeleton = np.delete(gray_skeleton,0,1)\n gray_skeleton = np.delete(gray_skeleton,cols-2,1)\n images.append(img_skelet)\n images.append(skeleton)\n\n cv2.imwrite('Bilder\\world_img.png', gray_skeleton)\n\n # returns the images in an array\n return images\n\n\n# plots the HSV, superimposed image, binary mask, and the skeleton\ndef plot_images(images):\n titles = ['Original Image', 'Result', 'Binary Mask', 'Skeleton']\n plot = [images[1], images[len(images)-2], images[len(images)-3], images[len(images)-1]]\n\n for i in range(len(plot)):\n plt.subplot(2,2,i+1),plt.imshow(plot[i])\n plt.title(titles[i])\n plt.xticks([]),plt.yticks([])\n plt.show()\n\n#plot_images(take_picture())\n\nimages = take_picture()\nplot_images(images)" }, { "alpha_fraction": 0.5878682732582092, "alphanum_fraction": 0.6003466248512268, "avg_line_length": 24.758928298950195, "blob_id": "edbe493069c56f51f537503a7e29d2095586604e", "content_id": "1227bcaf4a323673715510d7443253b7246de662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2885, "license_type": "no_license", "max_line_length": 107, "num_lines": 112, "path": "/realWorld.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "#from World.world import World\nfrom RTDE_Interface import RTDE_Controller_CENSE as rtde\nimport math\nfrom multiprocessing import Process\nimport numpy as np\n\n\nclass RealWorld():\n pi = math.pi\n scaling_constant = .03\n turn_constant = 45\n\n def move_left(self):\n current_pos = rtde.current_position()\n current_pos[0] -= RealWorld.scaling_constant\n rtde.move_to_position(current_pos)\n pass\n\n def move_right(self):\n current_pos = rtde.current_position()\n current_pos[0] += RealWorld.scaling_constant\n rtde.move_to_position(current_pos)\n pass\n\n def move_up(self):\n current_pos = rtde.current_position()\n current_pos[2] -= RealWorld.scaling_constant\n rtde.move_to_position(current_pos)\n pass\n\n def move_down(self):\n current_pos = rtde.current_position()\n current_pos[2] += RealWorld.scaling_constant\n rtde.move_to_position(current_pos)\n pass\n\n def turn_counter_clockwise(self):\n current_pos = rtde.current_position()\n current_pos[4] += RealWorld.pi*RealWorld.turn_constant/180\n rtde.move_to_position(current_pos)\n pass\n\n def turn_clockwise(self):\n current_pos = rtde.current_position()\n current_pos[4] -= RealWorld.pi*RealWorld.turn_constant/180\n rtde.move_to_position(current_pos)\n pass\n\n def get_state(self):\n # Ich weiss nicht was ich hier machen soll oder welche koordinaten sind in coordinates gespeichert.\n pass\n\n def go_to_coordinates(self, coordinates):\n new_pos = rtde.current_position()\n new_pos[0] = coordinates[0]\n new_pos[2] = coordinates[1]\n rtde.move_to_position_no_append(new_pos)\n pass\n\n def reset(self):\n rtde.go_start_via_path()\n pass\n\n def take_picture(self):\n rtde.disengage()\n rtde.go_camera()\n rtde.take_picture()\n rtde.resume()\n rtde.go_start_disengaged()\n rtde.engage()\n pass\n\n# def test():\n# print('CH1')\n# RealWorld.reset()\n#\n# while True:\n# print('CH2')\n# RealWorld.move_up()\n# print('CH3')\n# RealWorld.move_down()\n# print('CH4')\n# RealWorld.move_left()\n# print('CH5')\n# RealWorld.move_right()\n# print('CH6')\n# RealWorld.turn_clockwise()\n# print('CH7')\n# RealWorld.turn_counter_clockwise()\n# print('CH8')\n# RealWorld.take_picture()\n\n\nRealWorld = RealWorld()\nprint('CH1')\nRealWorld.reset()\n\nwhile True:\n print('CH2')\n RealWorld.move_up()\n print('CH3')\n RealWorld.move_down()\n print('CH4')\n RealWorld.move_left()\n print('CH5')\n RealWorld.move_right()\n print('CH6')\n RealWorld.turn_clockwise()\n print('CH7')\n RealWorld.turn_counter_clockwise()\n print('CH8')\n RealWorld.take_picture()\n" }, { "alpha_fraction": 0.5490628480911255, "alphanum_fraction": 0.5986769795417786, "avg_line_length": 21.700000762939453, "blob_id": "11b2bb746be13ec65a28e725f27f6a057f2ba5c5", "content_id": "5f0009fcf9fda52a3ff6e67cd897112647ae3086", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "no_license", "max_line_length": 87, "num_lines": 40, "path": "/Drahterfassung_OpenCV/beta modules/Testing_Colors.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a module for taking images from a\nwebcam and saving them as a png.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Color_Detection as colors\n\ndef preview_colors(color, focus, bands, thresh, scale):\n cap = cv2.VideoCapture(0)\n\n while True:\n __, frame = cap.read()\n filtered = colors.color_vision(color, focus, bands, thresh, scale, image=frame)\n gray = filtered[len(filtered)-1]*255\n gray = cv2.resize(gray, None, fx=1/scale, fy=1/scale)\n\n cv2.imshow('filtered', gray)\n\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\n cv2.destroyAllWindows()\n\n return\n\nscale = 0.7\nbands = 8\nthresh = 3\ncolor = 25\nfocus = [25, 35, 255, 35, 255]\n\npreview_colors(color, focus, bands, thresh, scale)" }, { "alpha_fraction": 0.8214285969734192, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 41, "blob_id": "b860896b5b008ee76a10644f9d6dbbd371415a32", "content_id": "a570203c8beea5130b8b81ebc287b71fdc24441d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 84, "license_type": "no_license", "max_line_length": 62, "num_lines": 2, "path": "/README.md", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "# CENSE_Demonstrator\nReal-Time Data Exchange module for Universal Robots in python.\n" }, { "alpha_fraction": 0.6195182204246521, "alphanum_fraction": 0.6444306969642639, "avg_line_length": 32.26712417602539, "blob_id": "9adb33a871cadfc89059e08c47d9c99a21ab6863", "content_id": "61cd1c6debee5e6c79e8cf310c6ea40a69586ab7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4857, "license_type": "no_license", "max_line_length": 120, "num_lines": 146, "path": "/Drahterfassung_OpenCV/Kalibrierung.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a camera calibration method.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom Drahterfassung_OpenCV import Kamera as cam\nimport time\nfrom Drahterfassung_OpenCV.calibration_vars import objpv\nfrom Drahterfassung_OpenCV.calibration_vars import imgpv\nimport Drahterfassung_OpenCV.Color_Detection as colors\nfrom operator import itemgetter\n\n\nclass Points:\n # Arrays to store object points and image points from all the images.\n objpoints = objpv\n imgpoints = imgpv\n\n\ndef save_file():\n # Save points to python file\n with open('calibration_vars.py', 'w') as f:\n f.write('from numpy import *')\n f.write('\\n\\nobjpv = %s' % str(Points.objpoints))\n f.write('\\n\\nimgpv = %s' % str(Points.imgpoints))\n\n\ndef calibrate():\n # termination criteria\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n\n # prepare object points\n objp = np.zeros((6*8,3), np.float32)\n objp[:,:2] = np.mgrid[0:8,0:6].T.reshape(-1,2)\n\n # empty list to hold the pictures\n images = []\n\n # counter for amount of images with chessboard found\n count = 0\n\n for j in range(10):\n print('Pictures will be taken in 5 seconds.')\n time.sleep(5)\n\n # stores 15 pictures into images\n for i in range(15):\n print ('Taking picture %i out of 15' % int(i+1))\n images.append(cam.get_image())\n\n # checks all images for chessboard corners\n print ('Scanning for chessboard.')\n for img in images:\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chess board corners\n ret, corners = cv2.findChessboardCorners(gray, (8,6), None)\n\n # If found, add object points, image points (after refining them) and break the loop to take new images\n if ret:\n count += 1\n Points.objpoints.append(objp)\n corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)\n Points.imgpoints.append(corners2)\n print ('%i chessboards found out of 10' % int(count))\n break\n cam.release_cam()\n save_file()\n\n\ndef undistort_img(img):\n # checks to see if camera has been calibrated\n if Points.objpoints == [] or Points.imgpoints == []:\n print('Camera must be calibrated. Press enter to continue into calibration mode.')\n calibrate()\n\n # Image is turn into gray scale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # gets the calibration matrix and optimizes it\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(Points.objpoints, Points.imgpoints, gray.shape[::-1], None, None)\n h, w = img.shape[:2]\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))\n\n # undistorts the image\n dst = cv2.undistort(img, mtx, dist, None, newcameramtx)\n\n # crop the image\n x, y, w, h = roi\n\n # returns the image\n dst = dst[y:y + h, x:x + w]\n return dst\n\n\ndef perspective_undistort(image):\n # scale at which the image will be processed\n scale = 1\n\n # the color focus area will be segmented into color bands this states how many bands will be analyzed\n bands = 8\n\n # minimum amount of bands in which a pixel has to be to make it to the resulting mask\n thresh = 4\n\n # color hue to be looked for\n color = 70\n\n # variation range for hue, saturation, and value e.g.: color+focus = max_hue, color-focus = min_hue\n focus = [20, 51, 255, 80, 255]\n\n # image is color analyzed to find the location of the corner points\n images = colors.color_vision(color, focus, bands, thresh, scale, image=image)\n\n # contours of the corner points are calculated\n im2, contours, hierarchy = cv2.findContours(images[len(images)-1], cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n # array with the coordinates of the center points of the corner points are saved on an array\n center_points = []\n for cnt in contours:\n (x, y), radius = cv2.minEnclosingCircle(cnt)\n center_points.append([int(y), int(x), int(x+y)])\n center_points = sort_points(center_points)\n\n # center point coordinates and end coordinates for the corner center points are prepped for the transformation\n rows, cols = images[len(images)-1].shape\n pts1 = np.float32(np.delete(center_points,2,1))\n print(rows, cols)\n print(pts1)\n pts2 = np.float32([[-10, -10], [rows-10, -10], [-10, cols], [rows-10, cols]])\n M = cv2.getPerspectiveTransform(pts1, pts2)\n undistorted = cv2.warpPerspective(image, M, (cols, rows))\n print(undistorted.shape)\n\n return undistorted\n\n\ndef sort_points(center_points):\n new_pts = tuple(sorted(center_points, key=itemgetter(2,0)))\n return new_pts\n" }, { "alpha_fraction": 0.5970962047576904, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 23.81818199157715, "blob_id": "59e6d33d1fdd9114364153009090dfef69c4ae64", "content_id": "cee0945b9229aa95ee02719f5c1d0e483cf956db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 71, "num_lines": 22, "path": "/Drahterfassung_OpenCV/other/Drahterfassung_Hough.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nfrom PIL import Image\n\n\nimg = cv2.imread('Bilder\\Draht1.jpg')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray,50,150,apertureSize = 3)\n\nminLineLength = 1\nmaxLineGap = 20\nlines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)\nprint('Lines found: {}'.format(len(lines)))\n\nfor i in range(0,len(lines)):\n for x1,y1,x2,y2 in lines[i]:\n cv2.line(img,(x1,y1),(x2,y2),(0,255,0),10)\n\n\nimg = cv2.resize(img, None, fx=0.25, fy=0.25)\ncv2.imshow('houghlines5.jpg',img)\ncv2.waitKey()\n\n\n\n\n\n" }, { "alpha_fraction": 0.6658551692962646, "alphanum_fraction": 0.6762020587921143, "avg_line_length": 21.83333396911621, "blob_id": "0b0ad128dd9a1cc31175b73f23bc1f39c1e25cee", "content_id": "ae735cd8766ab04ffc14c6b5c9e90bf869395f19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1643, "license_type": "no_license", "max_line_length": 84, "num_lines": 72, "path": "/Drahterfassung_OpenCV/Kamera.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a module for taking images from a\nwebcam and saving them as a png.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Drahterfassung_OpenCV.Kalibrierung as cal\n\n# camera port and amount of frames to be discarded while focusing\nport = 0\nframes = 25\n\n\n# class with variables needed to know if camera is in use or not\nclass Kamera:\n cam = None\n released = True\n\n\n# camera is released for further use\ndef release_cam():\n Kamera.cam = None\n Kamera.released = True\n\n\n# image is taken and returned\ndef get_image():\n if Kamera.released:\n Kamera.cam = cv2.VideoCapture(port)\n Kamera.released = False\n\n im = get_image_internal()\n\n return im\n\n\n# image is taken and returned without initializing the camera\ndef get_image_internal():\n retval = False\n\n while not retval:\n retval, im = Kamera.cam.read()\n\n return im\n\n\n# image is taken, undistorted and saved to the file path in 'name'\ndef capture_image(name):\n if Kamera.released:\n Kamera.cam = cv2.VideoCapture(port)\n Kamera.released = False\n\n for i in range(frames):\n temp = get_image_internal()\n\n camera_capture = get_image_internal()\n\n release_cam()\n\n # image is transformed into undistorted version using the module Kalibrierung.py\n #camera_capture = cal.undistort_img(camera_capture)\n\n # image perspective is undistorted using the module Kalibrierung.py\n camera_capture = cal.perspective_undistort(camera_capture)\n\n cv2.imwrite(name, camera_capture)" }, { "alpha_fraction": 0.672583818435669, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 25.736841201782227, "blob_id": "5ee2285cfb6f541a7225437288915b7ce7f0d59f", "content_id": "403df96c94d6c9ffe097b93c96c9017fe3b49b88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "no_license", "max_line_length": 56, "num_lines": 19, "path": "/Drahterfassung_OpenCV/other/Drahterfassung_BackgroundSubstractorMOG.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport sys\n\nbgSub=cv2.createBackgroundSubtractorMOG2()\nfor i in range(1,15):\n bgImageFile = \"bg{0}.jpg\".format(i)\n bg = cv2.imread(bgImageFile)\n bg=cv2.resize(bg,None,fx=0.125,fy=0.125)\n bgSub.apply(bg, learningRate=0.5)\n\nstillFrame=cv2.imread('Still1.jpg')\nstillFrame=cv2.resize(stillFrame,None,fx=0.125,fy=0.125)\nfgmask=bgSub.apply(stillFrame, learningRate=0)\n\ncv2.imshow('Original', stillFrame)\ncv2.imshow('Masked', fgmask)\ncv2.waitKey(0)\ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.6589049100875854, "alphanum_fraction": 0.6962535977363586, "avg_line_length": 31.24535369873047, "blob_id": "594fe9bef9799288e69d195d3aa432e0cde656c4", "content_id": "25e4777c2edc980d2c6ad6ca1f49cbaf47ae75a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8675, "license_type": "no_license", "max_line_length": 144, "num_lines": 269, "path": "/RTDE_Interface/RTDE_Controller_CENSE_2.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a module for RTDE Control\nof a UR5 from Universal Robots.\n===========================\n\"\"\"\n\nimport sys\nimport logging\nimport RTDE_Interface.rtde_client.rtde.rtde as rtde\nimport RTDE_Interface.rtde_client.rtde.rtde_config as rtde_config\nfrom operator import sub,abs\n\n# begin variable and object setup\nROBOT_HOST = '169.254.203.187'\nROBOT_PORT = 30004\nconfig_filename = 'ur5_configuration_CENSE_test.xml'\n\nSTART_POSITION = [0.336,- 0.378, 0.730, 0, 0, 0]\nCENTER_POSITION = [-0.12028426334880883, 0.22592083702208404, 0.6888784830906385, -1.1776661923930953, -1.1603887788030312, -1.2277226782518533]\nCAMERA_POSITION = [-1.5806005636798304, -2.0574949423419397, 2.765082836151123, -3.0610531012164515, -1.6087492148028772, -1.5503385702716272]\n\nRTDE_PROTOCOL_VERSION = 1\n\nkeep_running = True\n\nMAX_ERROR = 0.001\n\nlogging.getLogger().setLevel(logging.INFO)\n\nconf = rtde_config.ConfigFile(config_filename)\nstate_names, state_types = conf.get_recipe('state')\nsetp_names, setp_types = conf.get_recipe('setp')\nwatchdog_names, watchdog_types = conf.get_recipe('watchdog')\njoint_names, joint_types = conf.get_recipe('joint')\n\ncon = rtde.RTDE(ROBOT_HOST, ROBOT_PORT)\n# end variable and object setup\n\n# Initiate connection\ncon.connect()\n\n# get_controller_version is used to know if minimum requirements are met\ncon.get_controller_version()\n\n# Compares protocol version of the robot with that of the program. Mismatch leads to system exit\nif not con.negotiate_protocol_version(RTDE_PROTOCOL_VERSION):\n sys.exit()\n\n# Send configuration for output and input recipes\ncon.send_output_setup(state_names, state_types)\n#print('check point 1')\nsetp = con.send_input_setup(setp_names, setp_types)\n#print('check point 2')\n\n# Send configuration for the watchdog timer (1 Hz) input recipe\nwatchdog = con.send_input_setup(watchdog_names, watchdog_types)\n\n# Joint trigger: when 0 the points given are interpreted as pose, when 1 as joint angles\njoint = con.send_input_setup(joint_names, joint_types)\n\n# Set input registers (double) to 0\nsetp.input_double_register_0 = 0\nsetp.input_double_register_1 = 0\nsetp.input_double_register_2 = 0\nsetp.input_double_register_3 = 0\nsetp.input_double_register_4 = 0\nsetp.input_double_register_5 = 0\n\n# Set input register for watchdog timer to 0 so that it can be reset\nwatchdog.input_int_register_0 = 0\n\n# Set input register for joint to 0\njoint.input_int_register_1 = 0\n\n\n# Starts data sync\ndef start_sync():\n # start data exchange. If the exchange fails it returns 'Failed'\n if not con.send_start():\n return 'Failed'\n\n\n# Pauses the data sync\ndef pause_sync():\n con.send_pause()\n\n\n# Disconnects the RTDE\ndef disconnect_rtde():\n con.disconnect()\n\n\n# current_position gives the current position of the TCP relative to the defined Cartesian plane in list format\ndef current_position():\n\n # Checks for the state of the connection\n state = con.receive()\n\n # If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'\n if state is None:\n return 'Failed'\n\n # if the joint values are needed then return joint values\n if state.output_int_register_1 == 1:\n # If successful it returns the list with the current joint position\n return state.actual_q\n\n # If successful it returns the list with the current TCP position\n return state.actual_TCP_pose\n\n\n# This class hold the list of all positions\nclass Positions:\n start_sync()\n all_positions = [START_POSITION]\n\n\n# setp_to_list converts a serialized data object to a list\ndef setp_to_list(setp):\n list = []\n for i in range(0,6):\n list.append(setp.__dict__[\"input_double_register_%i\" % i])\n return list\n\n\n# list_to_setp converts a list int0 serialized data object\ndef list_to_setp(setp, list):\n for i in range (0,6):\n setp.__dict__[\"input_double_register_%i\" % i] = list[i]\n return setp\n\n\n# move_to_position changes the position and orientation of the TCP of the robot relative to the defined Cartesian plane\ndef move_to_position(new_pos):\n # Checks for the state of the connection\n state = con.receive()\n\n # If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'\n if state is None:\n return 'Failed'\n\n # Set joint to 0\n joint.input_int_register_1 = 0\n con.send(joint)\n\n # Will try to move to position till current_position() is within a max error range from new_pos\n while max(map(abs, map(sub, current_position(), new_pos))) >= MAX_ERROR:\n # Checks for the state of the connection\n state = con.receive()\n\n # If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'\n if state is None:\n return 'Failed'\n\n # The output_int_register_0 defines if the robot is in motion.\n if state.output_int_register_0 != 0:\n\n # Changes the value from setp to the new position\n list_to_setp(setp, new_pos)\n\n # Send new position\n con.send(setp)\n\n con.send(watchdog)\n\n # If successful the RTDE sync is paused, new position is added to all_positions, and it returns 'SUCCESS'\n Positions.all_positions.append(new_pos)\n return 'SUCCESS'\n\n\n# move_to_position changes the position and orientation of the TCP of the robot relative to the defined Cartesian plane\ndef move_to_position_no_append(new_pos):\n # Will try to move to position till current_position() is within a max error range from new_pos\n while max(map(abs, map(sub, current_position(), new_pos))) >= MAX_ERROR:\n\n # Checks for the state of the connection\n state = con.receive()\n\n # If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'\n if state is None:\n return 'Failed'\n\n # The output_int_register_0 defines if the robot is in motion.\n if state.output_int_register_0 != 0:\n\n # Changes the value from setp to the new position\n list_to_setp(setp, new_pos)\n\n # Send new position\n con.send(setp)\n\n con.send(watchdog)\n\n # If successful the RTDE sync is paused, new position is added to all_positions, and it returns 'SUCCESS'\n return 'SUCCESS'\n\n\n# go_start_via_path moves the robot back to the defined starting position through all recorded positions\ndef go_start_via_path():\n\n # Set joint to 0\n print(setp.__dict__)\n joint.input_int_register_1 = 0\n con.send(joint)\n\n # Makes a new list which is the reverses of all_positions to be able to go from end position to start position\n rev_all_positions = list(Positions.all_positions)\n rev_all_positions.reverse()\n move_to_position_no_append(rev_all_positions[0])\n\n # For all the positions in all_positions it implements the function move_to_position\n while len(rev_all_positions) != 1:\n move_response = 'Failed'\n\n # It will try the movement till 'SUCCESS' is returned\n while move_response == 'Failed':\n move_response = move_to_position_no_append(rev_all_positions[0])\n\n # It removes the position from all_positions\n rev_all_positions.remove(rev_all_positions[0])\n\n # Moves to start position\n move_to_position_no_append(rev_all_positions[0])\n\n # If successful all_positions will be cleared and redefined with initial position\n Positions.all_positions = list(rev_all_positions)\n return 'SUCCESS'\n\n\n# go_camera moves the robot to the position defined as camera position\ndef go_camera():\n # Checks for the state of the connection\n state = con.receive()\n\n # If output config not initialized, RTDE synchronization is inactive, or RTDE is disconnected it returns 'Failed'\n if state is None:\n return 'Failed'\n\n # Set joint to 0\n joint.input_int_register_1 = 0\n con.send(joint)\n\n move_to_position_no_append(CENTER_POSITION)\n\n # Tell the server the following points are to be interpreted as joint values\n joint.input_int_register_1 = 1\n con.send(joint)\n\n move_to_position_no_append(CAMERA_POSITION)\n\n # Set joint to 0\n joint.input_int_register_1 = 0\n con.send(joint)\n\n # Set pose to 0 so the robot will not continue moving\n # Set input registers (double) to 0\n setp.input_double_register_0 = 0\n setp.input_double_register_1 = 0\n setp.input_double_register_2 = 0\n setp.input_double_register_3 = 0\n setp.input_double_register_4 = 0\n setp.input_double_register_5 = 0\n\n con.send(setp)\n\n return 'SUCCESS'\n\n" }, { "alpha_fraction": 0.6279594302177429, "alphanum_fraction": 0.6865839958190918, "avg_line_length": 23.66666603088379, "blob_id": "50c463b6a82162ee0ca868f2e89e330331d33ef7", "content_id": "119e96409f0421535fcc9adfccaf02ef028ce815", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 83, "num_lines": 36, "path": "/Drahterfassung_OpenCV/other/Drahterfassung_GrabCut.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\n# Import image with PIL\nimg = Image.open('Bilder\\Draht1.jpg')\n\n# Rotate image 180 degrees\nimg_r = img.rotate(180, expand=True)\n\n# Transform image into Numpy Array\nimg_r = np.array(img_r)\n\n# RGB to BGR\n# img_r = img_r[:, :, ::-1].copy()\n\n# Resize image\nimg_rs = cv2.resize(img_r, None, fx=0.125, fy=0.125, interpolation=cv2.INTER_CUBIC)\n\n# Create a mask for the image\nmask = np.zeros(img_rs.shape[:2], np.uint8)\n\n# Create models for both the background and foreground\nbgdModel = np.zeros((1, 65), np.float64)\nfgdModel = np.zeros((1, 65), np.float64)\n\nrect = (50, 110, 440, 275)\ncv2.grabCut(img_rs,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)\nmask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')\nimg_m = img_rs*mask2[:, :, np.newaxis]\n\n\n# Show image\nplt.imshow(img_m)\nplt.show()" }, { "alpha_fraction": 0.4693572521209717, "alphanum_fraction": 0.6307922005653381, "avg_line_length": 29.409090042114258, "blob_id": "db4c06dc3cd60bd3aaee3b653b1c2f60af6e5261", "content_id": "e7c653c85aaf97c702700ffe8176ec3e8eb3137e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/RTDE_Interface/TestA.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "import RTDE_Controller_CENSE as rtde\nwhile True:\n print(rtde.Positions.all_positions)\n\n rtde.go_start_via_path()\n print ('Start Position')\n\n rtde.move_to_position([-0.10782, 0.3822, 0.5866, 0.0, -0.136, 1.593])\n print ('Position 1')\n rtde.move_to_position([-0.10782, 0.4822, 0.5866, 0.0, -0.136, 1.593])\n print ('Position 2')\n rtde.move_to_position([-0.10782, 0.4822, 0.4866, 0.0, -0.136, 1.593])\n print ('Position 3')\n rtde.move_to_position([-0.10782, 0.3822, 0.4866, 0.0, -0.136, 1.593])\n print ('Position 4')\n\n rtde.go_start_via_path()\n print ('Start Position')\n\n print(rtde.Positions.all_positions)\n\nrtde.disconnect_rtde()\n" }, { "alpha_fraction": 0.5209459662437439, "alphanum_fraction": 0.5631756782531738, "avg_line_length": 21.953489303588867, "blob_id": "d3eb555034ca5466c88eb6cfad4b89ba3bb9fa7c", "content_id": "cae4121803f131c0f289801d21b3624d157b1e73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2960, "license_type": "no_license", "max_line_length": 113, "num_lines": 129, "path": "/Drahterfassung_OpenCV/beta modules/Mask_Cleanup_2.py", "repo_name": "aguajardo/CENSE_Demonstrator", "src_encoding": "UTF-8", "text": "\"\"\"\n===========================\n@Author : aguajardo<aguajardo.me>\n@Version: 1.0 24/03/2017\nThis is a color detection method that allows to focus onto the\ncolor being detected with color variance.\n===========================\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Color_Detection as colors\nfrom random import randint\n\n\nclass Agents:\n agents = []\n agents_temp = []\n\n\ndef sync_agents():\n Agents.agents = np.array(Agents.agents_temp)\n\ndef neighbours(x, y, image):\n img = image\n x_1, y_1, x1, y1 = x - 1, y - 1, x + 1, y + 1\n return [img[x_1][y], img[x][y1], # u,ur,r,dr\n img[x1][y], img[x][y_1]] # d,dl,l,ul\n\n\ndef alive(agent, mask):\n Agents.agents_temp.append(agent)\n mask[agent[0]][agent[1]] = 1\n\n\ndef dead(agent, mask):\n mask[agent[0]][agent[1]] = 0\n Agents.agents_temp.remove([agent[0], agent[1]])\n\n\ndef reproduce(agent, directions, mask):\n position = list(agent)\n random = randint(0, 3)\n if directions[random] == 0:\n if random == 0:\n position[1] += 1\n alive(position, mask)\n return\n if random == 1:\n position[0] += 1\n alive(position, mask)\n return\n if random == 2:\n position[1] -= 1\n alive(position, mask)\n return\n if random == 3:\n position[0] -= 1\n alive(position, mask)\n return\n\n\nname = 'Bilder\\Test6.png'\nscale = 1\nbands = 8\nthresh = 3\ncolor = 25\nfocus = [25, 35, 255, 35, 255]\nimages = colors.color_vision(color, focus, bands, thresh, scale, name)\n\nmask = np.array(images[len(images)-1])\n\nroi = mask[190:215, 0:25]\nrows, cols = roi.shape\n\nfor x in range(cols):\n for y in range(rows):\n if roi[y][x] == 1:\n p_1 = [y+190+1, x+1]\n break\n if roi[y][x] == 1:\n p_1 = [y+190+1, x+1]\n break\n\ncv2.imshow('roi', roi*255)\nrows, cols = mask.shape\nprint([rows, cols])\nnew_mask = np.zeros((rows, cols), np.uint8)\n\n\n\nret, mask = cv2.threshold(mask, 0, 1, cv2.THRESH_BINARY_INV)\n\n\nalive(p_1, new_mask)\nsync_agents()\n\ncv2.imshow('original', mask*255)\n\nwhile True:\n temp = cv2.bitwise_or(mask, new_mask)\n u, r, d, l = neighbours(Agents.agents[len(Agents.agents)-1][0], Agents.agents[len(Agents.agents)-1][1], temp)\n connections = u+r+d+l\n directions = [r, d, l, u]\n if connections <= 2:\n reproduce(Agents.agents[len(Agents.agents)-1], directions, new_mask)\n sync_agents()\n else:\n length = len(Agents.agents)\n while len(Agents.agents)!= 1 and len(Agents.agents) > length-4:\n dead(Agents.agents[len(Agents.agents)-1], new_mask)\n sync_agents()\n\n print(len(Agents.agents))\n\n cv2.imshow('New', temp * 255)\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\nsum = 0\nfor i in range(rows):\n for j in range(cols):\n if new_mask[i][j]==1:\n sum+=1\nprint(sum)\n\ncv2.destroyAllWindows()" } ]
20